Don't force edit summaries when a user is editing their own user/talk page
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Contain the EditPage class
4 * @package MediaWiki
5 */
6
7 /**
8 * Splitting edit page/HTML interface from Article...
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
11 * interfaces.
12 *
13 * @package MediaWiki
14 */
15
16 class EditPage {
17 var $mArticle;
18 var $mTitle;
19 var $mMetaData = '';
20 var $isConflict = false;
21 var $isCssJsSubpage = false;
22 var $deletedSinceEdit = false;
23 var $formtype;
24 var $firsttime;
25 var $lastDelete;
26 var $mTokenOk = true;
27 var $tooBig = false;
28 var $kblength = false;
29 var $missingComment = false;
30 var $missingSummary = false;
31 var $allowBlankSummary = false;
32 var $autoSumm = '';
33
34 # Form values
35 var $save = false, $preview = false, $diff = false;
36 var $minoredit = false, $watchthis = false, $recreate = false;
37 var $textbox1 = '', $textbox2 = '', $summary = '';
38 var $edittime = '', $section = '', $starttime = '';
39 var $oldid = 0, $editintro = '', $scrolltop = null;
40
41 /**
42 * @todo document
43 * @param $article
44 */
45 function EditPage( $article ) {
46 $this->mArticle =& $article;
47 global $wgTitle;
48 $this->mTitle =& $wgTitle;
49 }
50
51 /**
52 * This is the function that extracts metadata from the article body on the first view.
53 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
54 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
55 */
56 function extractMetaDataFromArticle () {
57 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
58 $this->mMetaData = '' ;
59 if ( !$wgUseMetadataEdit ) return ;
60 if ( $wgMetadataWhitelist == '' ) return ;
61 $s = '' ;
62 $t = $this->mArticle->getContent();
63
64 # MISSING : <nowiki> filtering
65
66 # Categories and language links
67 $t = explode ( "\n" , $t ) ;
68 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
69 $cat = $ll = array() ;
70 foreach ( $t AS $key => $x )
71 {
72 $y = trim ( strtolower ( $x ) ) ;
73 while ( substr ( $y , 0 , 2 ) == '[[' )
74 {
75 $y = explode ( ']]' , trim ( $x ) ) ;
76 $first = array_shift ( $y ) ;
77 $first = explode ( ':' , $first ) ;
78 $ns = array_shift ( $first ) ;
79 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
80 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
81 {
82 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
83 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
84 else $ll[] = $add ;
85 $x = implode ( ']]' , $y ) ;
86 $t[$key] = $x ;
87 $y = trim ( strtolower ( $x ) ) ;
88 }
89 }
90 }
91 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
92 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
93 $t = implode ( "\n" , $t ) ;
94
95 # Load whitelist
96 $sat = array () ; # stand-alone-templates; must be lowercase
97 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
98 $wl_article = new Article ( $wl_title ) ;
99 $wl = explode ( "\n" , $wl_article->getContent() ) ;
100 foreach ( $wl AS $x )
101 {
102 $isentry = false ;
103 $x = trim ( $x ) ;
104 while ( substr ( $x , 0 , 1 ) == '*' )
105 {
106 $isentry = true ;
107 $x = trim ( substr ( $x , 1 ) ) ;
108 }
109 if ( $isentry )
110 {
111 $sat[] = strtolower ( $x ) ;
112 }
113
114 }
115
116 # Templates, but only some
117 $t = explode ( '{{' , $t ) ;
118 $tl = array () ;
119 foreach ( $t AS $key => $x )
120 {
121 $y = explode ( '}}' , $x , 2 ) ;
122 if ( count ( $y ) == 2 )
123 {
124 $z = $y[0] ;
125 $z = explode ( '|' , $z ) ;
126 $tn = array_shift ( $z ) ;
127 if ( in_array ( strtolower ( $tn ) , $sat ) )
128 {
129 $tl[] = '{{' . $y[0] . '}}' ;
130 $t[$key] = $y[1] ;
131 $y = explode ( '}}' , $y[1] , 2 ) ;
132 }
133 else $t[$key] = '{{' . $x ;
134 }
135 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
136 else $t[$key] = $x ;
137 }
138 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
139 $t = implode ( '' , $t ) ;
140
141 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
142 $this->mArticle->mContent = $t ;
143 $this->mMetaData = $s ;
144 }
145
146 function submit() {
147 $this->edit();
148 }
149
150 /**
151 * This is the function that gets called for "action=edit". It
152 * sets up various member variables, then passes execution to
153 * another function, usually showEditForm()
154 *
155 * The edit form is self-submitting, so that when things like
156 * preview and edit conflicts occur, we get the same form back
157 * with the extra stuff added. Only when the final submission
158 * is made and all is well do we actually save and redirect to
159 * the newly-edited page.
160 */
161 function edit() {
162 global $wgOut, $wgUser, $wgRequest, $wgTitle;
163 global $wgEmailConfirmToEdit;
164
165 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
166 return;
167
168 $fname = 'EditPage::edit';
169 wfProfileIn( $fname );
170 wfDebug( "$fname: enter\n" );
171
172 // this is not an article
173 $wgOut->setArticleFlag(false);
174
175 $this->importFormData( $wgRequest );
176 $this->firsttime = false;
177
178 if( $this->live ) {
179 $this->livePreview();
180 wfProfileOut( $fname );
181 return;
182 }
183
184 if ( ! $this->mTitle->userCanEdit() ) {
185 wfDebug( "$fname: user can't edit\n" );
186 $wgOut->readOnlyPage( $this->mArticle->getContent(), true );
187 wfProfileOut( $fname );
188 return;
189 }
190 wfDebug( "$fname: Checking blocks\n" );
191 if ( !$this->preview && !$this->diff && $wgUser->isBlockedFrom( $this->mTitle, !$this->save ) ) {
192 # When previewing, don't check blocked state - will get caught at save time.
193 # Also, check when starting edition is done against slave to improve performance.
194 wfDebug( "$fname: user is blocked\n" );
195 $wgOut->blockedPage();
196 wfProfileOut( $fname );
197 return;
198 }
199 if ( !$wgUser->isAllowed('edit') ) {
200 if ( $wgUser->isAnon() ) {
201 wfDebug( "$fname: user must log in\n" );
202 $this->userNotLoggedInPage();
203 wfProfileOut( $fname );
204 return;
205 } else {
206 wfDebug( "$fname: read-only page\n" );
207 $wgOut->readOnlyPage( $this->mArticle->getContent(), true );
208 wfProfileOut( $fname );
209 return;
210 }
211 }
212 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
213 wfDebug("$fname: user must confirm e-mail address\n");
214 $this->userNotConfirmedPage();
215 wfProfileOut($fname);
216 return;
217 }
218 if ( !$this->mTitle->userCan( 'create' ) && !$this->mTitle->exists() ) {
219 wfDebug( "$fname: no create permission\n" );
220 $this->noCreatePermission();
221 wfProfileOut( $fname );
222 return;
223 }
224 if ( wfReadOnly() ) {
225 wfDebug( "$fname: read-only mode is engaged\n" );
226 if( $this->save || $this->preview ) {
227 $this->formtype = 'preview';
228 } else if ( $this->diff ) {
229 $this->formtype = 'diff';
230 } else {
231 $wgOut->readOnlyPage( $this->mArticle->getContent() );
232 wfProfileOut( $fname );
233 return;
234 }
235 } else {
236 if ( $this->save ) {
237 $this->formtype = 'save';
238 } else if ( $this->preview ) {
239 $this->formtype = 'preview';
240 } else if ( $this->diff ) {
241 $this->formtype = 'diff';
242 } else { # First time through
243 $this->firsttime = true;
244 if( $this->previewOnOpen() ) {
245 $this->formtype = 'preview';
246 } else {
247 $this->extractMetaDataFromArticle () ;
248 $this->formtype = 'initial';
249 }
250 }
251 }
252
253 wfProfileIn( "$fname-business-end" );
254
255 $this->isConflict = false;
256 // css / js subpages of user pages get a special treatment
257 $this->isCssJsSubpage = $wgTitle->isCssJsSubpage();
258 $this->isValidCssJsSubpage = $wgTitle->isValidCssJsSubpage();
259
260 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
261 * no matter it's current state
262 */
263 $this->deletedSinceEdit = false;
264 if ( $this->edittime != '' ) {
265 /* Note that we rely on logging table, which hasn't been always there,
266 * but that doesn't matter, because this only applies to brand new
267 * deletes. This is done on every preview and save request. Move it further down
268 * to only perform it on saves
269 */
270 if ( $this->mTitle->isDeleted() ) {
271 $this->lastDelete = $this->getLastDelete();
272 if ( !is_null($this->lastDelete) ) {
273 $deletetime = $this->lastDelete->log_timestamp;
274 if ( ($deletetime - $this->starttime) > 0 ) {
275 $this->deletedSinceEdit = true;
276 }
277 }
278 }
279 }
280
281 if(!$this->mTitle->getArticleID() && ('initial' == $this->formtype || $this->firsttime )) { # new article
282 $this->showIntro();
283 }
284 if( $this->mTitle->isTalkPage() ) {
285 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
286 }
287
288 # Attempt submission here. This will check for edit conflicts,
289 # and redundantly check for locked database, blocked IPs, etc.
290 # that edit() already checked just in case someone tries to sneak
291 # in the back door with a hand-edited submission URL.
292
293 if ( 'save' == $this->formtype ) {
294 if ( !$this->attemptSave() ) {
295 wfProfileOut( "$fname-business-end" );
296 wfProfileOut( $fname );
297 return;
298 }
299 }
300
301 # First time through: get contents, set time for conflict
302 # checking, etc.
303 if ( 'initial' == $this->formtype || $this->firsttime ) {
304 $this->initialiseForm();
305 }
306
307 $this->showEditForm();
308 wfProfileOut( "$fname-business-end" );
309 wfProfileOut( $fname );
310 }
311
312 /**
313 * Return true if this page should be previewed when the edit form
314 * is initially opened.
315 * @return bool
316 * @access private
317 */
318 function previewOnOpen() {
319 global $wgUser;
320 return $this->section != 'new' &&
321 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle->exists() ) ||
322 ( $this->mTitle->getNamespace() == NS_CATEGORY &&
323 !$this->mTitle->exists() ) );
324 }
325
326 /**
327 * @todo document
328 */
329 function importFormData( &$request ) {
330 global $wgLang, $wgUser;
331 $fname = 'EditPage::importFormData';
332 wfProfileIn( $fname );
333
334 if( $request->wasPosted() ) {
335 # These fields need to be checked for encoding.
336 # Also remove trailing whitespace, but don't remove _initial_
337 # whitespace from the text boxes. This may be significant formatting.
338 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
339 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
340 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
341 # Truncate for whole multibyte characters. +5 bytes for ellipsis
342 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
343
344 $this->edittime = $request->getVal( 'wpEdittime' );
345 $this->starttime = $request->getVal( 'wpStarttime' );
346
347 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
348
349 if( is_null( $this->edittime ) ) {
350 # If the form is incomplete, force to preview.
351 wfDebug( "$fname: Form data appears to be incomplete\n" );
352 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
353 $this->preview = true;
354 } else {
355 /* Fallback for live preview */
356 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
357 $this->diff = $request->getCheck( 'wpDiff' );
358
359 if( !$this->preview ) {
360 if ( $this->tokenOk( $request ) ) {
361 # Some browsers will not report any submit button
362 # if the user hits enter in the comment box.
363 # The unmarked state will be assumed to be a save,
364 # if the form seems otherwise complete.
365 wfDebug( "$fname: Passed token check.\n" );
366 } else {
367 # Page might be a hack attempt posted from
368 # an external site. Preview instead of saving.
369 wfDebug( "$fname: Failed token check; forcing preview\n" );
370 $this->preview = true;
371 }
372 }
373 }
374 $this->save = ! ( $this->preview OR $this->diff );
375 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
376 $this->edittime = null;
377 }
378
379 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
380 $this->starttime = null;
381 }
382
383 $this->recreate = $request->getCheck( 'wpRecreate' );
384
385 $this->minoredit = $request->getCheck( 'wpMinoredit' );
386 $this->watchthis = $request->getCheck( 'wpWatchthis' );
387
388 # Don't force edit summaries when a user is editing their own user or talk page
389 if( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) && $this->mTitle->getText() == $wgUser->getName() ) {
390 $this->allowBlankSummary = true;
391 } else {
392 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
393 }
394
395 $this->autoSumm = $request->getText( 'wpAutoSummary' );
396 } else {
397 # Not a posted form? Start with nothing.
398 wfDebug( "$fname: Not a posted form.\n" );
399 $this->textbox1 = '';
400 $this->textbox2 = '';
401 $this->mMetaData = '';
402 $this->summary = '';
403 $this->edittime = '';
404 $this->starttime = wfTimestampNow();
405 $this->preview = false;
406 $this->save = false;
407 $this->diff = false;
408 $this->minoredit = false;
409 $this->watchthis = false;
410 $this->recreate = false;
411 }
412
413 $this->oldid = $request->getInt( 'oldid' );
414
415 # Section edit can come from either the form or a link
416 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
417
418 $this->live = $request->getCheck( 'live' );
419 $this->editintro = $request->getText( 'editintro' );
420
421 wfProfileOut( $fname );
422 }
423
424 /**
425 * Make sure the form isn't faking a user's credentials.
426 *
427 * @param WebRequest $request
428 * @return bool
429 * @access private
430 */
431 function tokenOk( &$request ) {
432 global $wgUser;
433 if( $wgUser->isAnon() ) {
434 # Anonymous users may not have a session
435 # open. Don't tokenize.
436 $this->mTokenOk = true;
437 } else {
438 $this->mTokenOk = $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
439 }
440 return $this->mTokenOk;
441 }
442
443 function showIntro() {
444 global $wgOut, $wgUser;
445 $addstandardintro=true;
446 if($this->editintro) {
447 $introtitle=Title::newFromText($this->editintro);
448 if(isset($introtitle) && $introtitle->userCanRead()) {
449 $rev=Revision::newFromTitle($introtitle);
450 if($rev) {
451 $wgOut->addSecondaryWikiText($rev->getText());
452 $addstandardintro=false;
453 }
454 }
455 }
456 if($addstandardintro) {
457 if ( $wgUser->isLoggedIn() )
458 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
459 else
460 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
461 }
462 }
463
464 /**
465 * Attempt submission
466 * @return bool false if output is done, true if the rest of the form should be displayed
467 */
468 function attemptSave() {
469 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
470 global $wgMaxArticleSize;
471
472 $fname = 'EditPage::attemptSave';
473 wfProfileIn( $fname );
474 wfProfileIn( "$fname-checks" );
475
476 # Reintegrate metadata
477 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
478 $this->mMetaData = '' ;
479
480 # Check for spam
481 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
482 $this->spamPage ( $matches[0] );
483 wfProfileOut( "$fname-checks" );
484 wfProfileOut( $fname );
485 return false;
486 }
487 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
488 # Error messages or other handling should be performed by the filter function
489 wfProfileOut( $fname );
490 wfProfileOut( "$fname-checks" );
491 return false;
492 }
493 if ( !wfRunHooks( 'EditFilter', array( &$this, $this->textbox1, $this->section ) ) ) {
494 # Error messages or other handling should be performed by the filter function
495 wfProfileOut( $fname );
496 wfProfileOut( "$fname-checks" );
497 return false;
498 }
499 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
500 # Check block state against master, thus 'false'.
501 $this->blockedIPpage();
502 wfProfileOut( "$fname-checks" );
503 wfProfileOut( $fname );
504 return false;
505 }
506 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
507 if ( $this->kblength > $wgMaxArticleSize ) {
508 // Error will be displayed by showEditForm()
509 $this->tooBig = true;
510 wfProfileOut( "$fname-checks" );
511 wfProfileOut( $fname );
512 return true;
513 }
514
515 if ( !$wgUser->isAllowed('edit') ) {
516 if ( $wgUser->isAnon() ) {
517 $this->userNotLoggedInPage();
518 wfProfileOut( "$fname-checks" );
519 wfProfileOut( $fname );
520 return false;
521 }
522 else {
523 $wgOut->readOnlyPage();
524 wfProfileOut( "$fname-checks" );
525 wfProfileOut( $fname );
526 return false;
527 }
528 }
529
530 if ( wfReadOnly() ) {
531 $wgOut->readOnlyPage();
532 wfProfileOut( "$fname-checks" );
533 wfProfileOut( $fname );
534 return false;
535 }
536 if ( $wgUser->pingLimiter() ) {
537 $wgOut->rateLimited();
538 wfProfileOut( "$fname-checks" );
539 wfProfileOut( $fname );
540 return false;
541 }
542
543 # If the article has been deleted while editing, don't save it without
544 # confirmation
545 if ( $this->deletedSinceEdit && !$this->recreate ) {
546 wfProfileOut( "$fname-checks" );
547 wfProfileOut( $fname );
548 return true;
549 }
550
551 wfProfileOut( "$fname-checks" );
552
553 # If article is new, insert it.
554 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
555 if ( 0 == $aid ) {
556 // Late check for create permission, just in case *PARANOIA*
557 if ( !$this->mTitle->userCan( 'create' ) ) {
558 wfDebug( "$fname: no create permission\n" );
559 $this->noCreatePermission();
560 wfProfileOut( $fname );
561 return;
562 }
563
564 # Don't save a new article if it's blank.
565 if ( ( '' == $this->textbox1 ) ) {
566 $wgOut->redirect( $this->mTitle->getFullURL() );
567 wfProfileOut( $fname );
568 return false;
569 }
570
571 $isComment=($this->section=='new');
572 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
573 $this->minoredit, $this->watchthis, false, $isComment);
574
575 wfProfileOut( $fname );
576 return false;
577 }
578
579 # Article exists. Check for edit conflict.
580
581 $this->mArticle->clear(); # Force reload of dates, etc.
582 $this->mArticle->forUpdate( true ); # Lock the article
583
584 if( $this->mArticle->getTimestamp() != $this->edittime ) {
585 $this->isConflict = true;
586 if( $this->section == 'new' ) {
587 if( $this->mArticle->getUserText() == $wgUser->getName() &&
588 $this->mArticle->getComment() == $this->summary ) {
589 // Probably a duplicate submission of a new comment.
590 // This can happen when squid resends a request after
591 // a timeout but the first one actually went through.
592 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
593 } else {
594 // New comment; suppress conflict.
595 $this->isConflict = false;
596 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
597 }
598 }
599 }
600 $userid = $wgUser->getID();
601
602 if ( $this->isConflict) {
603 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
604 $this->mArticle->getTimestamp() . "'\n" );
605 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
606 }
607 else {
608 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
609 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
610 }
611 if( is_null( $text ) ) {
612 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
613 $this->isConflict = true;
614 $text = $this->textbox1;
615 }
616
617 # Suppress edit conflict with self, except for section edits where merging is required.
618 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
619 wfDebug( "Suppressing edit conflict, same user.\n" );
620 $this->isConflict = false;
621 } else {
622 # switch from section editing to normal editing in edit conflict
623 if($this->isConflict) {
624 # Attempt merge
625 if( $this->mergeChangesInto( $text ) ){
626 // Successful merge! Maybe we should tell the user the good news?
627 $this->isConflict = false;
628 wfDebug( "Suppressing edit conflict, successful merge.\n" );
629 } else {
630 $this->section = '';
631 $this->textbox1 = $text;
632 wfDebug( "Keeping edit conflict, failed merge.\n" );
633 }
634 }
635 }
636
637 if ( $this->isConflict ) {
638 wfProfileOut( $fname );
639 return true;
640 }
641
642 # Handle the user preference to force summaries here
643 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
644 if( md5( $this->summary ) == $this->autoSumm ) {
645 $this->missingSummary = true;
646 wfProfileOut( $fname );
647 return( true );
648 }
649 }
650
651 # All's well
652 wfProfileIn( "$fname-sectionanchor" );
653 $sectionanchor = '';
654 if( $this->section == 'new' ) {
655 if ( $this->textbox1 == '' ) {
656 $this->missingComment = true;
657 return true;
658 }
659 if( $this->summary != '' ) {
660 $sectionanchor = $this->sectionAnchor( $this->summary );
661 }
662 } elseif( $this->section != '' ) {
663 # Try to get a section anchor from the section source, redirect to edited section if header found
664 # XXX: might be better to integrate this into Article::replaceSection
665 # for duplicate heading checking and maybe parsing
666 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
667 # we can't deal with anchors, includes, html etc in the header for now,
668 # headline would need to be parsed to improve this
669 if($hasmatch and strlen($matches[2]) > 0) {
670 $sectionanchor = $this->sectionAnchor( $matches[2] );
671 }
672 }
673 wfProfileOut( "$fname-sectionanchor" );
674
675 // Save errors may fall down to the edit form, but we've now
676 // merged the section into full text. Clear the section field
677 // so that later submission of conflict forms won't try to
678 // replace that into a duplicated mess.
679 $this->textbox1 = $text;
680 $this->section = '';
681
682 // Check for length errors again now that the section is merged in
683 $this->kblength = (int)(strlen( $text ) / 1024);
684 if ( $this->kblength > $wgMaxArticleSize ) {
685 $this->tooBig = true;
686 wfProfileOut( $fname );
687 return true;
688 }
689
690 # update the article here
691 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
692 $this->watchthis, '', $sectionanchor ) ) {
693 wfProfileOut( $fname );
694 return false;
695 } else {
696 $this->isConflict = true;
697 }
698 wfProfileOut( $fname );
699 return true;
700 }
701
702 /**
703 * Initialise form fields in the object
704 * Called on the first invocation, e.g. when a user clicks an edit link
705 */
706 function initialiseForm() {
707 $this->edittime = $this->mArticle->getTimestamp();
708 $this->textbox1 = $this->mArticle->getContent();
709 $this->summary = '';
710 if ( !$this->mArticle->exists() && $this->mArticle->mTitle->getNamespace() == NS_MEDIAWIKI )
711 $this->textbox1 = wfMsgWeirdKey ( $this->mArticle->mTitle->getText() ) ;
712 wfProxyCheck();
713 }
714
715 /**
716 * Send the edit form and related headers to $wgOut
717 * @param $formCallback Optional callable that takes an OutputPage
718 * parameter; will be called during form output
719 * near the top, for captchas and the like.
720 */
721 function showEditForm( $formCallback=null ) {
722 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
723
724 $fname = 'EditPage::showEditForm';
725 wfProfileIn( $fname );
726
727 $sk =& $wgUser->getSkin();
728
729 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
730
731 $wgOut->setRobotpolicy( 'noindex,nofollow' );
732
733 # Enabled article-related sidebar, toplinks, etc.
734 $wgOut->setArticleRelated( true );
735
736 if ( $this->isConflict ) {
737 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
738 $wgOut->setPageTitle( $s );
739 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
740
741 $this->textbox2 = $this->textbox1;
742 $this->textbox1 = $this->mArticle->getContent();
743 $this->edittime = $this->mArticle->getTimestamp();
744 } else {
745
746 if( $this->section != '' ) {
747 if( $this->section == 'new' ) {
748 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
749 } else {
750 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
751 if( !$this->preview && !$this->diff ) {
752 preg_match( "/^(=+)(.+)\\1/mi",
753 $this->textbox1,
754 $matches );
755 if( !empty( $matches[2] ) ) {
756 $this->summary = "/* ". trim($matches[2])." */ ";
757 }
758 }
759 }
760 } else {
761 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
762 }
763 $wgOut->setPageTitle( $s );
764
765 if ( $this->missingComment ) {
766 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
767 }
768
769 if( $this->missingSummary ) {
770 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
771 }
772
773 if ( !$this->checkUnicodeCompliantBrowser() ) {
774 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
775 }
776 if ( isset( $this->mArticle )
777 && isset( $this->mArticle->mRevision )
778 && !$this->mArticle->mRevision->isCurrent() ) {
779 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
780 $wgOut->addWikiText( wfMsg( 'editingold' ) );
781 }
782 }
783
784 if( wfReadOnly() ) {
785 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
786 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
787 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
788 } else {
789 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
790 # Check the skin exists
791 if( $this->isValidCssJsSubpage ) {
792 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
793 } else {
794 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
795 }
796 }
797 }
798
799 if( $this->mTitle->isProtected( 'edit' ) ) {
800 if( $this->mTitle->isSemiProtected() ) {
801 $notice = wfMsg( 'semiprotectedpagewarning' );
802 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' ) {
803 $notice = '';
804 }
805 } else {
806 $notice = wfMsg( 'protectedpagewarning' );
807 }
808 $wgOut->addWikiText( $notice );
809 }
810
811 if ( $this->kblength === false ) {
812 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
813 }
814 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
815 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
816 } elseif( $this->kblength > 29 ) {
817 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
818 }
819
820 $rows = $wgUser->getOption( 'rows' );
821 $cols = $wgUser->getOption( 'cols' );
822
823 $ew = $wgUser->getOption( 'editwidth' );
824 if ( $ew ) $ew = " style=\"width:100%\"";
825 else $ew = '';
826
827 $q = 'action=submit';
828 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
829 $action = $this->mTitle->escapeLocalURL( $q );
830
831 $summary = wfMsg('summary');
832 $subject = wfMsg('subject');
833 $minor = wfMsg('minoredit');
834 $watchthis = wfMsg ('watchthis');
835
836 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
837 wfMsg('cancel') );
838 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
839 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
840 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
841 htmlspecialchars( wfMsg( 'newwindow' ) );
842
843 global $wgRightsText;
844 $copywarn = "<div id=\"editpage-copywarn\">\n" .
845 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
846 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
847 $wgRightsText ) . "\n</div>";
848
849 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
850 # prepare toolbar for edit buttons
851 $toolbar = $this->getEditToolbar();
852 } else {
853 $toolbar = '';
854 }
855
856 // activate checkboxes if user wants them to be always active
857 if( !$this->preview && !$this->diff ) {
858 # Sort out the "watch" checkbox
859 if( $wgUser->getOption( 'watchdefault' ) ) {
860 # Watch all edits
861 $this->watchthis = true;
862 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
863 # Watch creations
864 $this->watchthis = true;
865 } elseif( $this->mTitle->userIsWatching() ) {
866 # Already watched
867 $this->watchthis = true;
868 }
869
870 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
871 }
872
873 $minoredithtml = '';
874
875 if ( $wgUser->isAllowed('minoredit') ) {
876 $minoredithtml =
877 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
878 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
879 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
880 }
881
882 $watchhtml = '';
883
884 if ( $wgUser->isLoggedIn() ) {
885 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
886 ($this->watchthis?" checked='checked'":"").
887 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
888 "<label for='wpWatchthis' title=\"" .
889 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
890 }
891
892 $checkboxhtml = $minoredithtml . $watchhtml;
893
894 if ( $wgUser->getOption( 'previewontop' ) ) {
895
896 if ( 'preview' == $this->formtype ) {
897 $this->showPreview();
898 } else {
899 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
900 }
901
902 if ( 'diff' == $this->formtype ) {
903 $wgOut->addHTML( $this->getDiff() );
904 }
905 }
906
907
908 # if this is a comment, show a subject line at the top, which is also the edit summary.
909 # Otherwise, show a summary field at the bottom
910 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
911 if( $this->section == 'new' ) {
912 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span> <div class='editOptions'><input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
913 $editsummary = '';
914 } else {
915 $commentsubject = '';
916 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span> <div class='editOptions'><input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
917 }
918
919 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
920 if( !$this->preview && !$this->diff ) {
921 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
922 }
923 $templates = $this->formatTemplates();
924
925 global $wgUseMetadataEdit ;
926 if ( $wgUseMetadataEdit ) {
927 $metadata = $this->mMetaData ;
928 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
929 $helppage = Title::newFromText( wfMsg( "metadata_page" ) ) ;
930 $top = wfMsg( 'metadata', $helppage->getLocalURL() );
931 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
932 }
933 else $metadata = "" ;
934
935 $hidden = '';
936 $recreate = '';
937 if ($this->deletedSinceEdit) {
938 if ( 'save' != $this->formtype ) {
939 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
940 } else {
941 // Hide the toolbar and edit area, use can click preview to get it back
942 // Add an confirmation checkbox and explanation.
943 $toolbar = '';
944 $hidden = 'type="hidden" style="display:none;"';
945 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
946 $recreate .=
947 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
948 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
949 }
950 }
951
952 $temp = array(
953 'id' => 'wpSave',
954 'name' => 'wpSave',
955 'type' => 'submit',
956 'tabindex' => '5',
957 'value' => wfMsg('savearticle'),
958 'accesskey' => wfMsg('accesskey-save'),
959 'title' => wfMsg('tooltip-save'),
960 );
961 $buttons['save'] = wfElement('input', $temp, '');
962 $temp = array(
963 'id' => 'wpDiff',
964 'name' => 'wpDiff',
965 'type' => 'submit',
966 'tabindex' => '7',
967 'value' => wfMsg('showdiff'),
968 'accesskey' => wfMsg('accesskey-diff'),
969 'title' => wfMsg('tooltip-diff'),
970 );
971 $buttons['diff'] = wfElement('input', $temp, '');
972
973 global $wgLivePreview;
974 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
975 $temp = array(
976 'id' => 'wpPreview',
977 'name' => 'wpPreview',
978 'type' => 'submit',
979 'tabindex' => '6',
980 'value' => wfMsg('showpreview'),
981 'accesskey' => '',
982 'title' => wfMsg('tooltip-preview'),
983 'style' => 'display: none;',
984 );
985 $buttons['preview'] = wfElement('input', $temp, '');
986 $temp = array(
987 'id' => 'wpLivePreview',
988 'name' => 'wpLivePreview',
989 'type' => 'submit',
990 'tabindex' => '6',
991 'value' => wfMsg('showlivepreview'),
992 'accesskey' => wfMsg('accesskey-preview'),
993 'title' => '',
994 'onclick' => $this->doLivePreviewScript(),
995 );
996 $buttons['live'] = wfElement('input', $temp, '');
997 } else {
998 $temp = array(
999 'id' => 'wpPreview',
1000 'name' => 'wpPreview',
1001 'type' => 'submit',
1002 'tabindex' => '6',
1003 'value' => wfMsg('showpreview'),
1004 'accesskey' => wfMsg('accesskey-preview'),
1005 'title' => wfMsg('tooltip-preview'),
1006 );
1007 $buttons['preview'] = wfElement('input', $temp, '');
1008 $buttons['live'] = '';
1009 }
1010
1011 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1012 ? ""
1013 : "<input type='hidden' name=\"safemode\" value='1' />\n";
1014
1015 $wgOut->addHTML( <<<END
1016 {$toolbar}
1017 <form id="editform" name="editform" method="post" action="$action"
1018 enctype="multipart/form-data">
1019 END
1020 );
1021
1022 if( is_callable( $formCallback ) ) {
1023 call_user_func_array( $formCallback, array( &$wgOut ) );
1024 }
1025
1026 // Put these up at the top to ensure they aren't lost on early form submission
1027 $wgOut->addHTML( "
1028 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1029 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1030 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1031 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1032
1033 $wgOut->addHTML( <<<END
1034 $recreate
1035 {$commentsubject}
1036 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1037 cols='{$cols}'{$ew} $hidden>
1038 END
1039 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1040 "
1041 </textarea>
1042 " );
1043
1044 $wgOut->addWikiText( $copywarn );
1045 $wgOut->addHTML( "
1046 {$metadata}
1047 {$editsummary}
1048 {$checkboxhtml}
1049 {$safemodehtml}
1050 ");
1051
1052 $wgOut->addHTML("
1053 <div class='editButtons'>
1054 {$buttons['save']}
1055 {$buttons['preview']}
1056 {$buttons['live']}
1057 {$buttons['diff']}
1058 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1059 </div><!-- editButtons -->
1060 </div><!-- editOptions -->");
1061
1062 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1063
1064 $wgOut->addHTML( "
1065 <div class='templatesUsed'>
1066 {$templates}
1067 </div>
1068 " );
1069
1070 if ( $wgUser->isLoggedIn() ) {
1071 /**
1072 * To make it harder for someone to slip a user a page
1073 * which submits an edit form to the wiki without their
1074 * knowledge, a random token is associated with the login
1075 * session. If it's not passed back with the submission,
1076 * we won't save the page, or render user JavaScript and
1077 * CSS previews.
1078 */
1079 $token = htmlspecialchars( $wgUser->editToken() );
1080 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1081 }
1082
1083 # If a blank edit summary was previously provided, and the appropriate
1084 # user preference is active, pass a hidden tag here. This will stop the
1085 # user being bounced back more than once in the event that a summary
1086 # is not required.
1087 if( $this->missingSummary ) {
1088 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1089 }
1090
1091 # For a bit more sophisticated detection of blank summaries, hash the
1092 # automatic one and pass that in a hidden field.
1093 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1094 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpAutoSummary\" value=\"$autosumm\" />\n" );
1095
1096 if ( $this->isConflict ) {
1097 require_once( "DifferenceEngine.php" );
1098 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1099
1100 $de = new DifferenceEngine( $this->mTitle );
1101 $de->setText( $this->textbox2, $this->textbox1 );
1102 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1103
1104 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1105 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1106 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1107 }
1108 $wgOut->addHTML( "</form>\n" );
1109 if ( !$wgUser->getOption( 'previewontop' ) ) {
1110
1111 if ( $this->formtype == 'preview') {
1112 $this->showPreview();
1113 } else {
1114 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1115 }
1116
1117 if ( $this->formtype == 'diff') {
1118 $wgOut->addHTML( $this->getDiff() );
1119 }
1120
1121 }
1122
1123 wfProfileOut( $fname );
1124 }
1125
1126 /**
1127 * Append preview output to $wgOut.
1128 * Includes category rendering if this is a category page.
1129 * @access private
1130 */
1131 function showPreview() {
1132 global $wgOut;
1133 $wgOut->addHTML( '<div id="wikiPreview">' );
1134 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1135 $this->mArticle->openShowCategory();
1136 }
1137 $previewOutput = $this->getPreviewText();
1138 $wgOut->addHTML( $previewOutput );
1139 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1140 $this->mArticle->closeShowCategory();
1141 }
1142 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
1143 $wgOut->addHTML( '</div>' );
1144 }
1145
1146 /**
1147 * Prepare a list of templates used by this page. Returns HTML.
1148 */
1149 function formatTemplates() {
1150 global $wgUser;
1151
1152 $fname = 'EditPage::formatTemplates';
1153 wfProfileIn( $fname );
1154
1155 $sk =& $wgUser->getSkin();
1156
1157 $outText = '';
1158 $templates = $this->mArticle->getUsedTemplates();
1159 if ( count( $templates ) > 0 ) {
1160 # Do a batch existence check
1161 $batch = new LinkBatch;
1162 foreach( $templates as $title ) {
1163 $batch->addObj( $title );
1164 }
1165 $batch->execute();
1166
1167 # Construct the HTML
1168 $outText = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
1169 foreach ( $templates as $titleObj ) {
1170 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
1171 }
1172 $outText .= '</ul>';
1173 }
1174 wfProfileOut( $fname );
1175 return $outText;
1176 }
1177
1178 /**
1179 * Live Preview lets us fetch rendered preview page content and
1180 * add it to the page without refreshing the whole page.
1181 * If not supported by the browser it will fall through to the normal form
1182 * submission method.
1183 *
1184 * This function outputs a script tag to support live preview, and
1185 * returns an onclick handler which should be added to the attributes
1186 * of the preview button
1187 */
1188 function doLivePreviewScript() {
1189 global $wgStylePath, $wgJsMimeType, $wgOut, $wgTitle;
1190 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1191 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
1192 '"></script>' . "\n" );
1193 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1194 return "return !livePreview(" .
1195 "getElementById('wikiPreview')," .
1196 "editform.wpTextbox1.value," .
1197 '"' . $liveAction . '"' . ")";
1198 }
1199
1200 function getLastDelete() {
1201 $dbr =& wfGetDB( DB_SLAVE );
1202 $fname = 'EditPage::getLastDelete';
1203 $res = $dbr->select(
1204 array( 'logging', 'user' ),
1205 array( 'log_type',
1206 'log_action',
1207 'log_timestamp',
1208 'log_user',
1209 'log_namespace',
1210 'log_title',
1211 'log_comment',
1212 'log_params',
1213 'user_name', ),
1214 array( 'log_namespace' => $this->mTitle->getNamespace(),
1215 'log_title' => $this->mTitle->getDBkey(),
1216 'log_type' => 'delete',
1217 'log_action' => 'delete',
1218 'user_id=log_user' ),
1219 $fname,
1220 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1221
1222 if($dbr->numRows($res) == 1) {
1223 while ( $x = $dbr->fetchObject ( $res ) )
1224 $data = $x;
1225 $dbr->freeResult ( $res ) ;
1226 } else {
1227 $data = null;
1228 }
1229 return $data;
1230 }
1231
1232 /**
1233 * @todo document
1234 */
1235 function getPreviewText() {
1236 global $wgOut, $wgUser, $wgTitle, $wgParser;
1237
1238 $fname = 'EditPage::getPreviewText';
1239 wfProfileIn( $fname );
1240
1241 if ( $this->mTokenOk ) {
1242 $msg = 'previewnote';
1243 } else {
1244 $msg = 'session_fail_preview';
1245 }
1246 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1247 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1248 if ( $this->isConflict ) {
1249 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1250 }
1251
1252 $parserOptions = ParserOptions::newFromUser( $wgUser );
1253 $parserOptions->setEditSection( false );
1254
1255 # don't parse user css/js, show message about preview
1256 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1257
1258 if ( $this->isCssJsSubpage ) {
1259 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1260 $previewtext = wfMsg('usercsspreview');
1261 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1262 $previewtext = wfMsg('userjspreview');
1263 }
1264 $parserOptions->setTidy(true);
1265 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1266 $wgOut->addHTML( $parserOutput->mText );
1267 wfProfileOut( $fname );
1268 return $previewhead;
1269 } else {
1270 # if user want to see preview when he edit an article
1271 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
1272 $this->textbox1 = $this->mArticle->getContent();
1273 }
1274
1275 $toparse = $this->textbox1;
1276
1277 # If we're adding a comment, we need to show the
1278 # summary as the headline
1279 if($this->section=="new" && $this->summary!="") {
1280 $toparse="== {$this->summary} ==\n\n".$toparse;
1281 }
1282
1283 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1284 $parserOptions->setTidy(true);
1285 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1286 $wgTitle, $parserOptions );
1287
1288 $previewHTML = $parserOutput->getText();
1289 $wgOut->addParserOutputNoText( $parserOutput );
1290
1291 wfProfileOut( $fname );
1292 return $previewhead . $previewHTML;
1293 }
1294 }
1295
1296 /**
1297 * @todo document
1298 */
1299 function blockedIPpage() {
1300 global $wgOut;
1301 $wgOut->blockedPage();
1302 }
1303
1304 /**
1305 * @todo document
1306 */
1307 function userNotLoggedInPage() {
1308 global $wgOut;
1309
1310 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1311 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1312 $wgOut->setArticleRelated( false );
1313
1314 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
1315 $wgOut->returnToMain( false );
1316 }
1317
1318 /**
1319 * Creates a basic error page which informs the user that
1320 * they have to validate their email address before being
1321 * allowed to edit.
1322 */
1323 function userNotConfirmedPage() {
1324
1325 global $wgOut;
1326
1327 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1328 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1329 $wgOut->setArticleRelated( false );
1330 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1331 $wgOut->returnToMain( false );
1332 }
1333
1334 /**
1335 * @todo document
1336 */
1337 function spamPage ( $match = false )
1338 {
1339 global $wgOut;
1340 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1341 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1342 $wgOut->setArticleRelated( false );
1343
1344 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1345 if ( $match ) {
1346 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1347 }
1348 $wgOut->returnToMain( false );
1349 }
1350
1351 /**
1352 * @access private
1353 * @todo document
1354 */
1355 function mergeChangesInto( &$editText ){
1356 $fname = 'EditPage::mergeChangesInto';
1357 wfProfileIn( $fname );
1358
1359 $db =& wfGetDB( DB_MASTER );
1360
1361 // This is the revision the editor started from
1362 $baseRevision = Revision::loadFromTimestamp(
1363 $db, $this->mArticle->mTitle, $this->edittime );
1364 if( is_null( $baseRevision ) ) {
1365 wfProfileOut( $fname );
1366 return false;
1367 }
1368 $baseText = $baseRevision->getText();
1369
1370 // The current state, we want to merge updates into it
1371 $currentRevision = Revision::loadFromTitle(
1372 $db, $this->mArticle->mTitle );
1373 if( is_null( $currentRevision ) ) {
1374 wfProfileOut( $fname );
1375 return false;
1376 }
1377 $currentText = $currentRevision->getText();
1378
1379 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1380 $editText = $result;
1381 wfProfileOut( $fname );
1382 return true;
1383 } else {
1384 wfProfileOut( $fname );
1385 return false;
1386 }
1387 }
1388
1389 /**
1390 * Check if the browser is on a blacklist of user-agents known to
1391 * mangle UTF-8 data on form submission. Returns true if Unicode
1392 * should make it through, false if it's known to be a problem.
1393 * @return bool
1394 * @access private
1395 */
1396 function checkUnicodeCompliantBrowser() {
1397 global $wgBrowserBlackList;
1398 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1399 // No User-Agent header sent? Trust it by default...
1400 return true;
1401 }
1402 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1403 foreach ( $wgBrowserBlackList as $browser ) {
1404 if ( preg_match($browser, $currentbrowser) ) {
1405 return false;
1406 }
1407 }
1408 return true;
1409 }
1410
1411 /**
1412 * Format an anchor fragment as it would appear for a given section name
1413 * @param string $text
1414 * @return string
1415 * @access private
1416 */
1417 function sectionAnchor( $text ) {
1418 $headline = Sanitizer::decodeCharReferences( $text );
1419 # strip out HTML
1420 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1421 $headline = trim( $headline );
1422 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1423 $replacearray = array(
1424 '%3A' => ':',
1425 '%' => '.'
1426 );
1427 return str_replace(
1428 array_keys( $replacearray ),
1429 array_values( $replacearray ),
1430 $sectionanchor );
1431 }
1432
1433 /**
1434 * Shows a bulletin board style toolbar for common editing functions.
1435 * It can be disabled in the user preferences.
1436 * The necessary JavaScript code can be found in style/wikibits.js.
1437 */
1438 function getEditToolbar() {
1439 global $wgStylePath, $wgContLang, $wgJsMimeType;
1440
1441 /**
1442 * toolarray an array of arrays which each include the filename of
1443 * the button image (without path), the opening tag, the closing tag,
1444 * and optionally a sample text that is inserted between the two when no
1445 * selection is highlighted.
1446 * The tip text is shown when the user moves the mouse over the button.
1447 *
1448 * Already here are accesskeys (key), which are not used yet until someone
1449 * can figure out a way to make them work in IE. However, we should make
1450 * sure these keys are not defined on the edit page.
1451 */
1452 $toolarray=array(
1453 array( 'image'=>'button_bold.png',
1454 'open' => "\'\'\'",
1455 'close' => "\'\'\'",
1456 'sample'=> wfMsg('bold_sample'),
1457 'tip' => wfMsg('bold_tip'),
1458 'key' => 'B'
1459 ),
1460 array( 'image'=>'button_italic.png',
1461 'open' => "\'\'",
1462 'close' => "\'\'",
1463 'sample'=> wfMsg('italic_sample'),
1464 'tip' => wfMsg('italic_tip'),
1465 'key' => 'I'
1466 ),
1467 array( 'image'=>'button_link.png',
1468 'open' => '[[',
1469 'close' => ']]',
1470 'sample'=> wfMsg('link_sample'),
1471 'tip' => wfMsg('link_tip'),
1472 'key' => 'L'
1473 ),
1474 array( 'image'=>'button_extlink.png',
1475 'open' => '[',
1476 'close' => ']',
1477 'sample'=> wfMsg('extlink_sample'),
1478 'tip' => wfMsg('extlink_tip'),
1479 'key' => 'X'
1480 ),
1481 array( 'image'=>'button_headline.png',
1482 'open' => "\\n== ",
1483 'close' => " ==\\n",
1484 'sample'=> wfMsg('headline_sample'),
1485 'tip' => wfMsg('headline_tip'),
1486 'key' => 'H'
1487 ),
1488 array( 'image'=>'button_image.png',
1489 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1490 'close' => ']]',
1491 'sample'=> wfMsg('image_sample'),
1492 'tip' => wfMsg('image_tip'),
1493 'key' => 'D'
1494 ),
1495 array( 'image' =>'button_media.png',
1496 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1497 'close' => ']]',
1498 'sample'=> wfMsg('media_sample'),
1499 'tip' => wfMsg('media_tip'),
1500 'key' => 'M'
1501 ),
1502 array( 'image' =>'button_math.png',
1503 'open' => "\\<math\\>",
1504 'close' => "\\</math\\>",
1505 'sample'=> wfMsg('math_sample'),
1506 'tip' => wfMsg('math_tip'),
1507 'key' => 'C'
1508 ),
1509 array( 'image' =>'button_nowiki.png',
1510 'open' => "\\<nowiki\\>",
1511 'close' => "\\</nowiki\\>",
1512 'sample'=> wfMsg('nowiki_sample'),
1513 'tip' => wfMsg('nowiki_tip'),
1514 'key' => 'N'
1515 ),
1516 array( 'image' =>'button_sig.png',
1517 'open' => '--~~~~',
1518 'close' => '',
1519 'sample'=> '',
1520 'tip' => wfMsg('sig_tip'),
1521 'key' => 'Y'
1522 ),
1523 array( 'image' =>'button_hr.png',
1524 'open' => "\\n----\\n",
1525 'close' => '',
1526 'sample'=> '',
1527 'tip' => wfMsg('hr_tip'),
1528 'key' => 'R'
1529 )
1530 );
1531 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1532
1533 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1534 foreach($toolarray as $tool) {
1535
1536 $image=$wgStylePath.'/common/images/'.$tool['image'];
1537 $open=$tool['open'];
1538 $close=$tool['close'];
1539 $sample = wfEscapeJsString( $tool['sample'] );
1540
1541 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1542 // Older browsers show a "speedtip" type message only for ALT.
1543 // Ideally these should be different, realistically they
1544 // probably don't need to be.
1545 $tip = wfEscapeJsString( $tool['tip'] );
1546
1547 #$key = $tool["key"];
1548
1549 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1550 }
1551
1552 $toolbar.="document.writeln(\"</div>\");\n";
1553 $toolbar.="/*]]>*/\n</script>";
1554 return $toolbar;
1555 }
1556
1557 /**
1558 * Output preview text only. This can be sucked into the edit page
1559 * via JavaScript, and saves the server time rendering the skin as
1560 * well as theoretically being more robust on the client (doesn't
1561 * disturb the edit box's undo history, won't eat your text on
1562 * failure, etc).
1563 *
1564 * @todo This doesn't include category or interlanguage links.
1565 * Would need to enhance it a bit, maybe wrap them in XML
1566 * or something... that might also require more skin
1567 * initialization, so check whether that's a problem.
1568 */
1569 function livePreview() {
1570 global $wgOut;
1571 $wgOut->disable();
1572 header( 'Content-type: text/xml' );
1573 header( 'Cache-control: no-cache' );
1574 # FIXME
1575 echo $this->getPreviewText( );
1576 /* To not shake screen up and down between preview and live-preview */
1577 echo "<br style=\"clear:both;\" />\n";
1578 }
1579
1580
1581 /**
1582 * Get a diff between the current contents of the edit box and the
1583 * version of the page we're editing from.
1584 *
1585 * If this is a section edit, we'll replace the section as for final
1586 * save and then make a comparison.
1587 *
1588 * @return string HTML
1589 */
1590 function getDiff() {
1591 require_once( 'DifferenceEngine.php' );
1592 $oldtext = $this->mArticle->fetchContent();
1593 $newtext = $this->mArticle->replaceSection(
1594 $this->section, $this->textbox1, $this->summary, $this->edittime );
1595 $oldtitle = wfMsg( 'currentrev' );
1596 $newtitle = wfMsg( 'yourtext' );
1597 if ( $oldtext !== false || $newtext != '' ) {
1598 $de = new DifferenceEngine( $this->mTitle );
1599 $de->setText( $oldtext, $newtext );
1600 $difftext = $de->getDiff( $oldtitle, $newtitle );
1601 } else {
1602 $difftext = '';
1603 }
1604
1605 return '<div id="wikiDiff">' . $difftext . '</div>';
1606 }
1607
1608 /**
1609 * Filter an input field through a Unicode de-armoring process if it
1610 * came from an old browser with known broken Unicode editing issues.
1611 *
1612 * @param WebRequest $request
1613 * @param string $field
1614 * @return string
1615 * @access private
1616 */
1617 function safeUnicodeInput( $request, $field ) {
1618 $text = rtrim( $request->getText( $field ) );
1619 return $request->getBool( 'safemode' )
1620 ? $this->unmakesafe( $text )
1621 : $text;
1622 }
1623
1624 /**
1625 * Filter an output field through a Unicode armoring process if it is
1626 * going to an old browser with known broken Unicode editing issues.
1627 *
1628 * @param string $text
1629 * @return string
1630 * @access private
1631 */
1632 function safeUnicodeOutput( $text ) {
1633 global $wgContLang;
1634 $codedText = $wgContLang->recodeForEdit( $text );
1635 return $this->checkUnicodeCompliantBrowser()
1636 ? $codedText
1637 : $this->makesafe( $codedText );
1638 }
1639
1640 /**
1641 * A number of web browsers are known to corrupt non-ASCII characters
1642 * in a UTF-8 text editing environment. To protect against this,
1643 * detected browsers will be served an armored version of the text,
1644 * with non-ASCII chars converted to numeric HTML character references.
1645 *
1646 * Preexisting such character references will have a 0 added to them
1647 * to ensure that round-trips do not alter the original data.
1648 *
1649 * @param string $invalue
1650 * @return string
1651 * @access private
1652 */
1653 function makesafe( $invalue ) {
1654 // Armor existing references for reversability.
1655 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1656
1657 $bytesleft = 0;
1658 $result = "";
1659 $working = 0;
1660 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1661 $bytevalue = ord( $invalue{$i} );
1662 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1663 $result .= chr( $bytevalue );
1664 $bytesleft = 0;
1665 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1666 $working = $working << 6;
1667 $working += ($bytevalue & 0x3F);
1668 $bytesleft--;
1669 if( $bytesleft <= 0 ) {
1670 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1671 }
1672 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1673 $working = $bytevalue & 0x1F;
1674 $bytesleft = 1;
1675 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1676 $working = $bytevalue & 0x0F;
1677 $bytesleft = 2;
1678 } else { //1111 0xxx
1679 $working = $bytevalue & 0x07;
1680 $bytesleft = 3;
1681 }
1682 }
1683 return $result;
1684 }
1685
1686 /**
1687 * Reverse the previously applied transliteration of non-ASCII characters
1688 * back to UTF-8. Used to protect data from corruption by broken web browsers
1689 * as listed in $wgBrowserBlackList.
1690 *
1691 * @param string $invalue
1692 * @return string
1693 * @access private
1694 */
1695 function unmakesafe( $invalue ) {
1696 $result = "";
1697 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1698 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1699 $i += 3;
1700 $hexstring = "";
1701 do {
1702 $hexstring .= $invalue{$i};
1703 $i++;
1704 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1705
1706 // Do some sanity checks. These aren't needed for reversability,
1707 // but should help keep the breakage down if the editor
1708 // breaks one of the entities whilst editing.
1709 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1710 $codepoint = hexdec($hexstring);
1711 $result .= codepointToUtf8( $codepoint );
1712 } else {
1713 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1714 }
1715 } else {
1716 $result .= substr( $invalue, $i, 1 );
1717 }
1718 }
1719 // reverse the transform that we made for reversability reasons.
1720 return strtr( $result, array( "&#x0" => "&#x" ) );
1721 }
1722
1723 function noCreatePermission() {
1724 global $wgOut;
1725 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1726 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
1727 }
1728
1729 }
1730
1731 ?>