3 * Contains the EditPage class
7 * The edit page/HTML interface (split from Article)
8 * The actual database and text munging is still in Article,
9 * but it should get easier to call those from alternate
16 var $isConflict = false;
17 var $isCssJsSubpage = false;
18 var $deletedSinceEdit = false;
22 var $mTokenOk = false;
23 var $mTokenOkExceptSuffix = false;
24 var $mTriedSave = false;
26 var $kblength = false;
27 var $missingComment = false;
28 var $missingSummary = false;
29 var $allowBlankSummary = false;
32 var $mPreviewTemplates;
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;
41 # Placeholders for text injection by hooks (must be HTML)
42 # extensions should take care to _append_ to the present value
43 public $editFormPageTop; // Before even the preview
44 public $editFormTextTop;
45 public $editFormTextAfterWarn;
46 public $editFormTextAfterTools;
47 public $editFormTextBottom;
53 function EditPage( $article ) {
54 $this->mArticle
=& $article;
56 $this->mTitle
=& $wgTitle;
58 # Placeholders for text injection by hooks (empty per default)
59 $this->editFormPageTop
=
60 $this->editFormTextTop
=
61 $this->editFormTextAfterWarn
=
62 $this->editFormTextAfterTools
=
63 $this->editFormTextBottom
= "";
67 * Fetch initial editing page content.
69 private function getContent( $def_text = '' ) {
70 global $wgOut, $wgRequest, $wgParser;
72 # Get variables from query string :P
73 $section = $wgRequest->getVal( 'section' );
74 $preload = $wgRequest->getVal( 'preload' );
75 $undoafter = $wgRequest->getVal( 'undoafter' );
76 $undo = $wgRequest->getVal( 'undo' );
78 wfProfileIn( __METHOD__
);
81 if( !$this->mTitle
->exists() ) {
82 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
83 # If this is a system message, get the default text.
84 $text = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
86 # If requested, preload some text.
87 $text = $this->getPreloadedText( $preload );
89 # We used to put MediaWiki:Newarticletext here if
90 # $text was empty at this point.
91 # This is now shown above the edit box instead.
93 // FIXME: may be better to use Revision class directly
94 // But don't mess with it just yet. Article knows how to
95 // fetch the page record from the high-priority server,
96 // which is needed to guarantee we don't pick up lagged
99 $text = $this->mArticle
->getContent();
101 if ($undo > 0 && $undoafter > 0 && $undo < $undoafter) {
102 # If they got undoafter and undo round the wrong way, switch them
103 list( $undo, $undoafter ) = array( $undoafter, $undo );
106 if ( $undo > 0 && $undo > $undoafter ) {
107 # Undoing a specific edit overrides section editing; section-editing
108 # doesn't work with undoing.
110 $undorev = Revision
::newFromId($undo);
111 $oldrev = Revision
::newFromId($undoafter);
113 $undorev = Revision
::newFromId($undo);
114 $oldrev = $undorev ?
$undorev->getPrevious() : null;
117 #Sanity check, make sure it's the right page.
118 # Otherwise, $text will be left as-is.
119 if ( !is_null($undorev) && !is_null($oldrev) && $undorev->getPage()==$oldrev->getPage() && $undorev->getPage()==$this->mArticle
->getID() ) {
120 $undorev_text = $undorev->getText();
121 $oldrev_text = $oldrev->getText();
122 $currev_text = $text;
124 #No use doing a merge if it's just a straight revert.
125 if ( $currev_text != $undorev_text ) {
126 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
128 $text = $oldrev_text;
132 // Failed basic sanity checks.
133 // Older revisions may have been removed since the link
134 // was created, or we may simply have got bogus input.
139 # Inform the user of our success and set an automatic edit summary
140 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
141 $firstrev = $oldrev->getNext();
142 # If we just undid one rev, use an autosummary
143 if ( $firstrev->mId
== $undo ) {
144 $this->summary
= wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
146 $this->formtype
= 'diff';
148 # Warn the user that something went wrong
149 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
151 } else if( $section != '' ) {
152 if( $section == 'new' ) {
153 $text = $this->getPreloadedText( $preload );
155 $text = $wgParser->getSection( $text, $section, $def_text );
160 wfProfileOut( __METHOD__
);
165 * Get the contents of a page from its title and remove includeonly tags
167 * @param $preload String: the title of the page.
168 * @return string The contents of the page.
170 private function getPreloadedText($preload) {
171 if ( $preload === '' )
174 $preloadTitle = Title
::newFromText( $preload );
175 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
176 $rev=Revision
::newFromTitle($preloadTitle);
177 if ( is_object( $rev ) ) {
178 $text = $rev->getText();
179 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
180 // its own mini-parser! -ævar
181 $text = preg_replace( '~</?includeonly>~', '', $text );
190 * This is the function that extracts metadata from the article body on the first view.
191 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
192 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
194 function extractMetaDataFromArticle () {
195 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
196 $this->mMetaData
= '' ;
197 if ( !$wgUseMetadataEdit ) return ;
198 if ( $wgMetadataWhitelist == '' ) return ;
200 $t = $this->getContent();
202 # MISSING : <nowiki> filtering
204 # Categories and language links
205 $t = explode ( "\n" , $t ) ;
206 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
207 $cat = $ll = array() ;
208 foreach ( $t AS $key => $x )
210 $y = trim ( strtolower ( $x ) ) ;
211 while ( substr ( $y , 0 , 2 ) == '[[' )
213 $y = explode ( ']]' , trim ( $x ) ) ;
214 $first = array_shift ( $y ) ;
215 $first = explode ( ':' , $first ) ;
216 $ns = array_shift ( $first ) ;
217 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
218 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
220 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
221 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
223 $x = implode ( ']]' , $y ) ;
225 $y = trim ( strtolower ( $x ) ) ;
229 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
230 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
231 $t = implode ( "\n" , $t ) ;
234 $sat = array () ; # stand-alone-templates; must be lowercase
235 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
236 $wl_article = new Article ( $wl_title ) ;
237 $wl = explode ( "\n" , $wl_article->getContent() ) ;
238 foreach ( $wl AS $x )
242 while ( substr ( $x , 0 , 1 ) == '*' )
245 $x = trim ( substr ( $x , 1 ) ) ;
249 $sat[] = strtolower ( $x ) ;
254 # Templates, but only some
255 $t = explode ( '{{' , $t ) ;
257 foreach ( $t AS $key => $x )
259 $y = explode ( '}}' , $x , 2 ) ;
260 if ( count ( $y ) == 2 )
263 $z = explode ( '|' , $z ) ;
264 $tn = array_shift ( $z ) ;
265 if ( in_array ( strtolower ( $tn ) , $sat ) )
267 $tl[] = '{{' . $y[0] . '}}' ;
269 $y = explode ( '}}' , $y[1] , 2 ) ;
271 else $t[$key] = '{{' . $x ;
273 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
276 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
277 $t = implode ( '' , $t ) ;
279 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
280 $this->mArticle
->mContent
= $t ;
281 $this->mMetaData
= $s ;
289 * This is the function that gets called for "action=edit". It
290 * sets up various member variables, then passes execution to
291 * another function, usually showEditForm()
293 * The edit form is self-submitting, so that when things like
294 * preview and edit conflicts occur, we get the same form back
295 * with the extra stuff added. Only when the final submission
296 * is made and all is well do we actually save and redirect to
297 * the newly-edited page.
300 global $wgOut, $wgUser, $wgRequest, $wgTitle;
301 global $wgEmailConfirmToEdit;
303 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
306 $fname = 'EditPage::edit';
307 wfProfileIn( $fname );
308 wfDebug( "$fname: enter\n" );
310 // this is not an article
311 $wgOut->setArticleFlag(false);
313 $this->importFormData( $wgRequest );
314 $this->firsttime
= false;
317 $this->livePreview();
318 wfProfileOut( $fname );
322 if ( ! $this->mTitle
->userCan( 'edit' ) ) {
323 wfDebug( "$fname: user can't edit\n" );
324 $wgOut->readOnlyPage( $this->getContent(), true );
325 wfProfileOut( $fname );
328 wfDebug( "$fname: Checking blocks\n" );
329 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
330 # When previewing, don't check blocked state - will get caught at save time.
331 # Also, check when starting edition is done against slave to improve performance.
332 wfDebug( "$fname: user is blocked\n" );
333 $this->blockedPage();
334 wfProfileOut( $fname );
337 if ( !$wgUser->isAllowed('edit') ) {
338 if ( $wgUser->isAnon() ) {
339 wfDebug( "$fname: user must log in\n" );
340 $this->userNotLoggedInPage();
341 wfProfileOut( $fname );
344 wfDebug( "$fname: read-only page\n" );
345 $wgOut->readOnlyPage( $this->getContent(), true );
346 wfProfileOut( $fname );
350 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
351 wfDebug("$fname: user must confirm e-mail address\n");
352 $this->userNotConfirmedPage();
353 wfProfileOut($fname);
356 if ( !$this->mTitle
->userCan( 'create' ) && !$this->mTitle
->exists() ) {
357 wfDebug( "$fname: no create permission\n" );
358 $this->noCreatePermission();
359 wfProfileOut( $fname );
362 if ( wfReadOnly() ) {
363 wfDebug( "$fname: read-only mode is engaged\n" );
364 if( $this->save ||
$this->preview
) {
365 $this->formtype
= 'preview';
366 } else if ( $this->diff
) {
367 $this->formtype
= 'diff';
369 $wgOut->readOnlyPage( $this->getContent() );
370 wfProfileOut( $fname );
375 $this->formtype
= 'save';
376 } else if ( $this->preview
) {
377 $this->formtype
= 'preview';
378 } else if ( $this->diff
) {
379 $this->formtype
= 'diff';
380 } else { # First time through
381 $this->firsttime
= true;
382 if( $this->previewOnOpen() ) {
383 $this->formtype
= 'preview';
385 $this->extractMetaDataFromArticle () ;
386 $this->formtype
= 'initial';
391 wfProfileIn( "$fname-business-end" );
393 $this->isConflict
= false;
394 // css / js subpages of user pages get a special treatment
395 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
396 $this->isValidCssJsSubpage
= $wgTitle->isValidCssJsSubpage();
398 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
399 * no matter it's current state
401 $this->deletedSinceEdit
= false;
402 if ( $this->edittime
!= '' ) {
403 /* Note that we rely on logging table, which hasn't been always there,
404 * but that doesn't matter, because this only applies to brand new
405 * deletes. This is done on every preview and save request. Move it further down
406 * to only perform it on saves
408 if ( $this->mTitle
->isDeleted() ) {
409 $this->lastDelete
= $this->getLastDelete();
410 if ( !is_null($this->lastDelete
) ) {
411 $deletetime = $this->lastDelete
->log_timestamp
;
412 if ( ($deletetime - $this->starttime
) > 0 ) {
413 $this->deletedSinceEdit
= true;
419 # Show applicable editing introductions
420 if( $this->formtype
== 'initial' ||
$this->firsttime
)
423 if( $this->mTitle
->isTalkPage() ) {
424 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
427 # Attempt submission here. This will check for edit conflicts,
428 # and redundantly check for locked database, blocked IPs, etc.
429 # that edit() already checked just in case someone tries to sneak
430 # in the back door with a hand-edited submission URL.
432 if ( 'save' == $this->formtype
) {
433 if ( !$this->attemptSave() ) {
434 wfProfileOut( "$fname-business-end" );
435 wfProfileOut( $fname );
440 # First time through: get contents, set time for conflict
442 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
443 if ($this->initialiseForm() === false) {
444 $this->noSuchSectionPage();
445 wfProfileOut( "$fname-business-end" );
446 wfProfileOut( $fname );
449 if( !$this->mTitle
->getArticleId() )
450 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
453 $this->showEditForm();
454 wfProfileOut( "$fname-business-end" );
455 wfProfileOut( $fname );
459 * Return true if this page should be previewed when the edit form
460 * is initially opened.
464 function previewOnOpen() {
466 return $this->section
!= 'new' &&
467 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle
->exists() ) ||
468 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
469 !$this->mTitle
->exists() ) );
476 function importFormData( &$request ) {
477 global $wgLang, $wgUser;
478 $fname = 'EditPage::importFormData';
479 wfProfileIn( $fname );
481 if( $request->wasPosted() ) {
482 # These fields need to be checked for encoding.
483 # Also remove trailing whitespace, but don't remove _initial_
484 # whitespace from the text boxes. This may be significant formatting.
485 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
486 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
487 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
488 # Truncate for whole multibyte characters. +5 bytes for ellipsis
489 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
491 $this->edittime
= $request->getVal( 'wpEdittime' );
492 $this->starttime
= $request->getVal( 'wpStarttime' );
494 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
496 if( is_null( $this->edittime
) ) {
497 # If the form is incomplete, force to preview.
498 wfDebug( "$fname: Form data appears to be incomplete\n" );
499 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
500 $this->preview
= true;
502 /* Fallback for live preview */
503 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
504 $this->diff
= $request->getCheck( 'wpDiff' );
506 // Remember whether a save was requested, so we can indicate
507 // if we forced preview due to session failure.
508 $this->mTriedSave
= !$this->preview
;
510 if ( $this->tokenOk( $request ) ) {
511 # Some browsers will not report any submit button
512 # if the user hits enter in the comment box.
513 # The unmarked state will be assumed to be a save,
514 # if the form seems otherwise complete.
515 wfDebug( "$fname: Passed token check.\n" );
516 } else if ( $this->diff
) {
517 # Failed token check, but only requested "Show Changes".
518 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
520 # Page might be a hack attempt posted from
521 # an external site. Preview instead of saving.
522 wfDebug( "$fname: Failed token check; forcing preview\n" );
523 $this->preview
= true;
526 $this->save
= ! ( $this->preview
OR $this->diff
);
527 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
528 $this->edittime
= null;
531 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
532 $this->starttime
= null;
535 $this->recreate
= $request->getCheck( 'wpRecreate' );
537 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
538 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
540 # Don't force edit summaries when a user is editing their own user or talk page
541 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
542 $this->allowBlankSummary
= true;
544 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
547 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
549 # Not a posted form? Start with nothing.
550 wfDebug( "$fname: Not a posted form.\n" );
551 $this->textbox1
= '';
552 $this->textbox2
= '';
553 $this->mMetaData
= '';
555 $this->edittime
= '';
556 $this->starttime
= wfTimestampNow();
557 $this->preview
= false;
560 $this->minoredit
= false;
561 $this->watchthis
= false;
562 $this->recreate
= false;
565 $this->oldid
= $request->getInt( 'oldid' );
567 # Section edit can come from either the form or a link
568 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
570 $this->live
= $request->getCheck( 'live' );
571 $this->editintro
= $request->getText( 'editintro' );
573 wfProfileOut( $fname );
577 * Make sure the form isn't faking a user's credentials.
579 * @param $request WebRequest
583 function tokenOk( &$request ) {
585 $token = $request->getVal( 'wpEditToken' );
586 $this->mTokenOk
= $wgUser->matchEditToken( $token );
587 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
588 return $this->mTokenOk
;
592 * Show all applicable editing introductions
594 private function showIntro() {
595 global $wgOut, $wgUser;
596 if( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
597 if( $wgUser->isLoggedIn() ) {
598 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
600 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
602 $this->showDeletionLog( $wgOut );
607 * Attempt to show a custom editing introduction, if supplied
611 private function showCustomIntro() {
612 if( $this->editintro
) {
613 $title = Title
::newFromText( $this->editintro
);
614 if( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
616 $revision = Revision
::newFromTitle( $title );
617 $wgOut->addSecondaryWikiText( $revision->getText() );
629 * @return bool false if output is done, true if the rest of the form should be displayed
631 function attemptSave() {
632 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
633 global $wgMaxArticleSize;
635 $fname = 'EditPage::attemptSave';
636 wfProfileIn( $fname );
637 wfProfileIn( "$fname-checks" );
639 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
641 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
645 # Reintegrate metadata
646 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
647 $this->mMetaData
= '' ;
651 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
652 $this->spamPage ( $matches[0] );
653 wfProfileOut( "$fname-checks" );
654 wfProfileOut( $fname );
657 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
658 # Error messages or other handling should be performed by the filter function
659 wfProfileOut( $fname );
660 wfProfileOut( "$fname-checks" );
663 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
) ) ) {
664 # Error messages etc. could be handled within the hook...
665 wfProfileOut( $fname );
666 wfProfileOut( "$fname-checks" );
668 } elseif( $this->hookError
!= '' ) {
669 # ...or the hook could be expecting us to produce an error
670 wfProfileOut( "$fname-checks " );
671 wfProfileOut( $fname );
674 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
675 # Check block state against master, thus 'false'.
676 $this->blockedPage();
677 wfProfileOut( "$fname-checks" );
678 wfProfileOut( $fname );
681 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
682 if ( $this->kblength
> $wgMaxArticleSize ) {
683 // Error will be displayed by showEditForm()
684 $this->tooBig
= true;
685 wfProfileOut( "$fname-checks" );
686 wfProfileOut( $fname );
690 if ( !$wgUser->isAllowed('edit') ) {
691 if ( $wgUser->isAnon() ) {
692 $this->userNotLoggedInPage();
693 wfProfileOut( "$fname-checks" );
694 wfProfileOut( $fname );
698 $wgOut->readOnlyPage();
699 wfProfileOut( "$fname-checks" );
700 wfProfileOut( $fname );
705 if ( wfReadOnly() ) {
706 $wgOut->readOnlyPage();
707 wfProfileOut( "$fname-checks" );
708 wfProfileOut( $fname );
711 if ( $wgUser->pingLimiter() ) {
712 $wgOut->rateLimited();
713 wfProfileOut( "$fname-checks" );
714 wfProfileOut( $fname );
718 # If the article has been deleted while editing, don't save it without
720 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
721 wfProfileOut( "$fname-checks" );
722 wfProfileOut( $fname );
726 wfProfileOut( "$fname-checks" );
728 # If article is new, insert it.
729 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
732 // Late check for create permission, just in case *PARANOIA*
733 if ( !$this->mTitle
->userCan( 'create' ) ) {
734 wfDebug( "$fname: no create permission\n" );
735 $this->noCreatePermission();
736 wfProfileOut( $fname );
740 # Don't save a new article if it's blank.
741 if ( ( '' == $this->textbox1
) ) {
742 $wgOut->redirect( $this->mTitle
->getFullURL() );
743 wfProfileOut( $fname );
747 $isComment=($this->section
=='new');
748 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
749 $this->minoredit
, $this->watchthis
, false, $isComment);
751 wfProfileOut( $fname );
755 # Article exists. Check for edit conflict.
757 $this->mArticle
->clear(); # Force reload of dates, etc.
758 $this->mArticle
->forUpdate( true ); # Lock the article
760 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
762 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
763 $this->isConflict
= true;
764 if( $this->section
== 'new' ) {
765 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
766 $this->mArticle
->getComment() == $this->summary
) {
767 // Probably a duplicate submission of a new comment.
768 // This can happen when squid resends a request after
769 // a timeout but the first one actually went through.
770 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
772 // New comment; suppress conflict.
773 $this->isConflict
= false;
774 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
778 $userid = $wgUser->getID();
780 if ( $this->isConflict
) {
781 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
782 $this->mArticle
->getTimestamp() . "'\n" );
783 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
786 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
787 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
789 if( is_null( $text ) ) {
790 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
791 $this->isConflict
= true;
792 $text = $this->textbox1
;
795 # Suppress edit conflict with self, except for section edits where merging is required.
796 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
797 wfDebug( "Suppressing edit conflict, same user.\n" );
798 $this->isConflict
= false;
800 # switch from section editing to normal editing in edit conflict
801 if($this->isConflict
) {
803 if( $this->mergeChangesInto( $text ) ){
804 // Successful merge! Maybe we should tell the user the good news?
805 $this->isConflict
= false;
806 wfDebug( "Suppressing edit conflict, successful merge.\n" );
809 $this->textbox1
= $text;
810 wfDebug( "Keeping edit conflict, failed merge.\n" );
815 if ( $this->isConflict
) {
816 wfProfileOut( $fname );
820 $oldtext = $this->mArticle
->getContent();
822 # Handle the user preference to force summaries here, but not for null edits
823 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary')
824 && 0 != strcmp($oldtext, $text) && !Article
::getRedirectAutosummary( $text )) {
825 if( md5( $this->summary
) == $this->autoSumm
) {
826 $this->missingSummary
= true;
827 wfProfileOut( $fname );
832 #And a similar thing for new sections
833 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
834 if (trim($this->summary
) == '') {
835 $this->missingSummary
= true;
836 wfProfileOut( $fname );
842 wfProfileIn( "$fname-sectionanchor" );
844 if( $this->section
== 'new' ) {
845 if ( $this->textbox1
== '' ) {
846 $this->missingComment
= true;
849 if( $this->summary
!= '' ) {
850 $sectionanchor = $this->sectionAnchor( $this->summary
);
852 } elseif( $this->section
!= '' ) {
853 # Try to get a section anchor from the section source, redirect to edited section if header found
854 # XXX: might be better to integrate this into Article::replaceSection
855 # for duplicate heading checking and maybe parsing
856 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
857 # we can't deal with anchors, includes, html etc in the header for now,
858 # headline would need to be parsed to improve this
859 if($hasmatch and strlen($matches[2]) > 0) {
860 $sectionanchor = $this->sectionAnchor( $matches[2] );
863 wfProfileOut( "$fname-sectionanchor" );
865 // Save errors may fall down to the edit form, but we've now
866 // merged the section into full text. Clear the section field
867 // so that later submission of conflict forms won't try to
868 // replace that into a duplicated mess.
869 $this->textbox1
= $text;
872 // Check for length errors again now that the section is merged in
873 $this->kblength
= (int)(strlen( $text ) / 1024);
874 if ( $this->kblength
> $wgMaxArticleSize ) {
875 $this->tooBig
= true;
876 wfProfileOut( $fname );
880 # update the article here
881 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
882 $this->watchthis
, '', $sectionanchor ) ) {
883 wfProfileOut( $fname );
886 $this->isConflict
= true;
888 wfProfileOut( $fname );
893 * Initialise form fields in the object
894 * Called on the first invocation, e.g. when a user clicks an edit link
896 function initialiseForm() {
897 $this->edittime
= $this->mArticle
->getTimestamp();
899 $this->textbox1
= $this->getContent(false);
900 if ($this->textbox1
=== false) return false;
902 if ( !$this->mArticle
->exists() && $this->mArticle
->mTitle
->getNamespace() == NS_MEDIAWIKI
)
903 $this->textbox1
= wfMsgWeirdKey( $this->mArticle
->mTitle
->getText() );
909 * Send the edit form and related headers to $wgOut
910 * @param $formCallback Optional callable that takes an OutputPage
911 * parameter; will be called during form output
912 * near the top, for captchas and the like.
914 function showEditForm( $formCallback=null ) {
915 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
917 $fname = 'EditPage::showEditForm';
918 wfProfileIn( $fname );
920 $sk = $wgUser->getSkin();
922 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
924 $wgOut->setRobotpolicy( 'noindex,nofollow' );
926 # Enabled article-related sidebar, toplinks, etc.
927 $wgOut->setArticleRelated( true );
929 if ( $this->isConflict
) {
930 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
931 $wgOut->setPageTitle( $s );
932 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
934 $this->textbox2
= $this->textbox1
;
935 $this->textbox1
= $this->getContent();
936 $this->edittime
= $this->mArticle
->getTimestamp();
939 if( $this->section
!= '' ) {
940 if( $this->section
== 'new' ) {
941 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
943 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
945 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
946 preg_match( "/^(=+)(.+)\\1/mi",
949 if( !empty( $matches[2] ) ) {
950 $this->summary
= "/* ". trim($matches[2])." */ ";
955 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
957 $wgOut->setPageTitle( $s );
959 if ( $this->missingComment
) {
960 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
963 if( $this->missingSummary
&& $this->section
!= 'new' ) {
964 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
967 if( $this->missingSummary
&& $this->section
== 'new' ) {
968 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
971 if( !$this->hookError
== '' ) {
972 $wgOut->addWikiText( $this->hookError
);
975 if ( !$this->checkUnicodeCompliantBrowser() ) {
976 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
978 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
979 // Let sysop know that this will make private content public if saved
980 if( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
981 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
983 if( !$this->mArticle
->mRevision
->isCurrent() ) {
984 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
985 $wgOut->addWikiText( wfMsg( 'editingold' ) );
991 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
992 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
993 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
995 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
996 # Check the skin exists
997 if( $this->isValidCssJsSubpage
) {
998 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
1000 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
1005 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1006 # Show a warning if editing an interface message
1007 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
1008 } elseif( $this->mTitle
->isProtected( 'edit' ) ) {
1009 # Is the title semi-protected?
1010 if( $this->mTitle
->isSemiProtected() ) {
1011 $notice = wfMsg( 'semiprotectedpagewarning' );
1012 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' )
1015 # Then it must be protected based on static groups (regular)
1016 $notice = wfMsg( 'protectedpagewarning' );
1018 $wgOut->addWikiText( $notice );
1020 if ( $this->mTitle
->isCascadeProtected() ) {
1021 # Is this page under cascading protection from some source pages?
1022 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1023 if ( count($cascadeSources) > 0 ) {
1024 # Explain, and list the titles responsible
1025 $notice = wfMsgExt( 'cascadeprotectedwarning', array('parsemag'), count($cascadeSources) ) . "\n";
1026 foreach( $cascadeSources as $id => $page )
1027 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1029 $wgOut->addWikiText( $notice );
1032 if ( $this->kblength
=== false ) {
1033 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1035 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1036 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgMaxArticleSize ) );
1037 } elseif( $this->kblength
> 29 ) {
1038 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) ) );
1041 #need to parse the preview early so that we know which templates are used,
1042 #otherwise users with "show preview after edit box" will get a blank list
1043 if ( $this->formtype
== 'preview' ) {
1044 $previewOutput = $this->getPreviewText();
1047 $rows = $wgUser->getIntOption( 'rows' );
1048 $cols = $wgUser->getIntOption( 'cols' );
1050 $ew = $wgUser->getOption( 'editwidth' );
1051 if ( $ew ) $ew = " style=\"width:100%\"";
1054 $q = 'action=submit';
1055 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1056 $action = $this->mTitle
->escapeLocalURL( $q );
1058 $summary = wfMsg('summary');
1059 $subject = wfMsg('subject');
1061 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
1062 wfMsgExt('cancel', array('parseinline')) );
1063 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1064 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1065 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1066 htmlspecialchars( wfMsg( 'newwindow' ) );
1068 global $wgRightsText;
1069 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1070 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
1071 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1072 $wgRightsText ) . "\n</div>";
1074 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1075 # prepare toolbar for edit buttons
1076 $toolbar = $this->getEditToolbar();
1081 // activate checkboxes if user wants them to be always active
1082 if( !$this->preview
&& !$this->diff
) {
1083 # Sort out the "watch" checkbox
1084 if( $wgUser->getOption( 'watchdefault' ) ) {
1086 $this->watchthis
= true;
1087 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1089 $this->watchthis
= true;
1090 } elseif( $this->mTitle
->userIsWatching() ) {
1092 $this->watchthis
= true;
1095 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1098 $wgOut->addHTML( $this->editFormPageTop
);
1100 if ( $wgUser->getOption( 'previewontop' ) ) {
1102 if ( 'preview' == $this->formtype
) {
1103 $this->showPreview( $previewOutput );
1105 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1108 if ( 'diff' == $this->formtype
) {
1114 $wgOut->addHTML( $this->editFormTextTop
);
1116 # if this is a comment, show a subject line at the top, which is also the edit summary.
1117 # Otherwise, show a summary field at the bottom
1118 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1119 if( $this->section
== 'new' ) {
1120 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span>\n<div class='editOptions'>\n<input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
1122 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1123 $summarypreview = '';
1125 $commentsubject = '';
1126 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span>\n<div class='editOptions'>\n<input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
1127 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1128 $subjectpreview = '';
1131 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1132 if( !$this->preview
&& !$this->diff
) {
1133 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1135 $templates = ($this->preview ||
$this->section
!= '') ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1136 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1138 global $wgUseMetadataEdit ;
1139 if ( $wgUseMetadataEdit ) {
1140 $metadata = $this->mMetaData
;
1141 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1142 $top = wfMsgWikiHtml( 'metadata_help' );
1143 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1145 else $metadata = "" ;
1149 if ($this->deletedSinceEdit
) {
1150 if ( 'save' != $this->formtype
) {
1151 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1153 // Hide the toolbar and edit area, use can click preview to get it back
1154 // Add an confirmation checkbox and explanation.
1156 $hidden = 'type="hidden" style="display:none;"';
1157 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1159 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1160 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1166 $checkboxes = self
::getCheckboxes( $tabindex, $sk,
1167 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1169 $checkboxhtml = implode( $checkboxes, "\n" );
1171 $buttons = $this->getEditButtons( $tabindex );
1172 $buttonshtml = implode( $buttons, "\n" );
1174 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1175 ?
'' : Xml
::hidden( 'safemode', '1' );
1177 $wgOut->addHTML( <<<END
1179 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1183 if( is_callable( $formCallback ) ) {
1184 call_user_func_array( $formCallback, array( &$wgOut ) );
1187 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1189 // Put these up at the top to ensure they aren't lost on early form submission
1191 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1192 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1193 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1194 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1196 $wgOut->addHTML( <<<END
1200 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1201 cols='{$cols}'{$ew} $hidden>
1203 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
1208 $wgOut->addWikiText( $copywarn );
1209 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1219 "<div class='editButtons'>
1221 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1222 </div><!-- editButtons -->
1223 </div><!-- editOptions -->");
1225 $wgOut->addHtml( '<div class="mw-editTools">' );
1226 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1227 $wgOut->addHtml( '</div>' );
1229 $wgOut->addHTML( $this->editFormTextAfterTools
);
1232 <div class='templatesUsed'>
1233 {$formattedtemplates}
1238 * To make it harder for someone to slip a user a page
1239 * which submits an edit form to the wiki without their
1240 * knowledge, a random token is associated with the login
1241 * session. If it's not passed back with the submission,
1242 * we won't save the page, or render user JavaScript and
1245 * For anon editors, who may not have a session, we just
1246 * include the constant suffix to prevent editing from
1247 * broken text-mangling proxies.
1249 $token = htmlspecialchars( $wgUser->editToken() );
1250 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1253 # If a blank edit summary was previously provided, and the appropriate
1254 # user preference is active, pass a hidden tag here. This will stop the
1255 # user being bounced back more than once in the event that a summary
1257 if( $this->missingSummary
) {
1258 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1261 # For a bit more sophisticated detection of blank summaries, hash the
1262 # automatic one and pass that in a hidden field.
1263 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1264 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1266 if ( $this->isConflict
) {
1267 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1269 $de = new DifferenceEngine( $this->mTitle
);
1270 $de->setText( $this->textbox2
, $this->textbox1
);
1271 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1273 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1274 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1275 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1277 $wgOut->addHTML( $this->editFormTextBottom
);
1278 $wgOut->addHTML( "</form>\n" );
1279 if ( !$wgUser->getOption( 'previewontop' ) ) {
1281 if ( $this->formtype
== 'preview') {
1282 $this->showPreview( $previewOutput );
1284 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1287 if ( $this->formtype
== 'diff') {
1293 wfProfileOut( $fname );
1297 * Append preview output to $wgOut.
1298 * Includes category rendering if this is a category page.
1300 * @param string $text The HTML to be output for the preview.
1302 private function showPreview( $text ) {
1305 $wgOut->addHTML( '<div id="wikiPreview">' );
1306 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1307 $this->mArticle
->openShowCategory();
1309 $wgOut->addHTML( $text );
1310 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1311 $this->mArticle
->closeShowCategory();
1313 $wgOut->addHTML( '</div>' );
1317 * Live Preview lets us fetch rendered preview page content and
1318 * add it to the page without refreshing the whole page.
1319 * If not supported by the browser it will fall through to the normal form
1320 * submission method.
1322 * This function outputs a script tag to support live preview, and
1323 * returns an onclick handler which should be added to the attributes
1324 * of the preview button
1326 function doLivePreviewScript() {
1327 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1328 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1329 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1330 '"></script>' . "\n" );
1331 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1332 return "return !livePreview(" .
1333 "getElementById('wikiPreview')," .
1334 "editform.wpTextbox1.value," .
1335 '"' . $liveAction . '"' . ")";
1338 function getLastDelete() {
1339 $dbr = wfGetDB( DB_SLAVE
);
1340 $fname = 'EditPage::getLastDelete';
1341 $res = $dbr->select(
1342 array( 'logging', 'user' ),
1352 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1353 'log_title' => $this->mTitle
->getDBkey(),
1354 'log_type' => 'delete',
1355 'log_action' => 'delete',
1356 'user_id=log_user' ),
1358 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1360 if($dbr->numRows($res) == 1) {
1361 while ( $x = $dbr->fetchObject ( $res ) )
1363 $dbr->freeResult ( $res ) ;
1373 function getPreviewText() {
1374 global $wgOut, $wgUser, $wgTitle, $wgParser;
1376 $fname = 'EditPage::getPreviewText';
1377 wfProfileIn( $fname );
1379 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1380 if ( $this->mTokenOkExceptSuffix
) {
1381 $msg = 'token_suffix_mismatch';
1383 $msg = 'session_fail_preview';
1386 $msg = 'previewnote';
1388 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1389 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1390 if ( $this->isConflict
) {
1391 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1394 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1395 $parserOptions->setEditSection( false );
1398 if( $wgRawHtml && !$this->mTokenOk
) {
1399 // Could be an offsite preview attempt. This is very unsafe if
1400 // HTML is enabled, as it could be an attack.
1401 return $wgOut->parse( "<div class='previewnote'>" .
1402 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1405 # don't parse user css/js, show message about preview
1406 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1408 if ( $this->isCssJsSubpage
) {
1409 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1410 $previewtext = wfMsg('usercsspreview');
1411 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1412 $previewtext = wfMsg('userjspreview');
1414 $parserOptions->setTidy(true);
1415 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1416 $wgOut->addHTML( $parserOutput->mText
);
1417 wfProfileOut( $fname );
1418 return $previewhead;
1420 $toparse = $this->textbox1
;
1422 # If we're adding a comment, we need to show the
1423 # summary as the headline
1424 if($this->section
=="new" && $this->summary
!="") {
1425 $toparse="== {$this->summary} ==\n\n".$toparse;
1428 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1429 $parserOptions->setTidy(true);
1430 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1431 $wgTitle, $parserOptions );
1433 $previewHTML = $parserOutput->getText();
1434 $wgOut->addParserOutputNoText( $parserOutput );
1436 # ParserOutput might have altered the page title, so reset it
1437 $wgOut->setPageTitle( wfMsg( 'editing', $this->mTitle
->getPrefixedText() ) );
1439 foreach ( $parserOutput->getTemplates() as $ns => $template)
1440 foreach ( array_keys( $template ) as $dbk)
1441 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1443 wfProfileOut( $fname );
1444 return $previewhead . $previewHTML;
1449 * Call the stock "user is blocked" page
1451 function blockedPage() {
1452 global $wgOut, $wgUser;
1453 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1455 # If the user made changes, preserve them when showing the markup
1456 # (This happens when a user is blocked during edit, for instance)
1457 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1459 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1461 $source = $this->textbox1
;
1464 # Spit out the source or the user's modified version
1465 if( $source !== false ) {
1466 $rows = $wgUser->getOption( 'rows' );
1467 $cols = $wgUser->getOption( 'cols' );
1468 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1469 $wgOut->addHtml( '<hr />' );
1470 $wgOut->addWikiText( wfMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() ) );
1471 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1476 * Produce the stock "please login to edit pages" page
1478 function userNotLoggedInPage() {
1479 global $wgUser, $wgOut;
1480 $skin = $wgUser->getSkin();
1482 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1483 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle
->getPrefixedUrl() );
1485 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1486 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1487 $wgOut->setArticleRelated( false );
1489 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1490 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1494 * Creates a basic error page which informs the user that
1495 * they have to validate their email address before being
1498 function userNotConfirmedPage() {
1501 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1502 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1503 $wgOut->setArticleRelated( false );
1505 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1506 $wgOut->returnToMain( false );
1510 * Creates a basic error page which informs the user that
1511 * they have attempted to edit a nonexistant section.
1513 function noSuchSectionPage() {
1516 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1517 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1518 $wgOut->setArticleRelated( false );
1520 $wgOut->addWikiText( wfMsg( 'nosuchsectiontext', $this->section
) );
1521 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1525 * Produce the stock "your edit contains spam" page
1527 * @param $match Text which triggered one or more filters
1529 function spamPage( $match = false ) {
1532 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1533 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1534 $wgOut->setArticleRelated( false );
1536 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1538 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1540 $wgOut->returnToMain( false );
1547 function mergeChangesInto( &$editText ){
1548 $fname = 'EditPage::mergeChangesInto';
1549 wfProfileIn( $fname );
1551 $db = wfGetDB( DB_MASTER
);
1553 // This is the revision the editor started from
1554 $baseRevision = Revision
::loadFromTimestamp(
1555 $db, $this->mArticle
->mTitle
, $this->edittime
);
1556 if( is_null( $baseRevision ) ) {
1557 wfProfileOut( $fname );
1560 $baseText = $baseRevision->getText();
1562 // The current state, we want to merge updates into it
1563 $currentRevision = Revision
::loadFromTitle(
1564 $db, $this->mArticle
->mTitle
);
1565 if( is_null( $currentRevision ) ) {
1566 wfProfileOut( $fname );
1569 $currentText = $currentRevision->getText();
1572 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1573 $editText = $result;
1574 wfProfileOut( $fname );
1577 wfProfileOut( $fname );
1583 * Check if the browser is on a blacklist of user-agents known to
1584 * mangle UTF-8 data on form submission. Returns true if Unicode
1585 * should make it through, false if it's known to be a problem.
1589 function checkUnicodeCompliantBrowser() {
1590 global $wgBrowserBlackList;
1591 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1592 // No User-Agent header sent? Trust it by default...
1595 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1596 foreach ( $wgBrowserBlackList as $browser ) {
1597 if ( preg_match($browser, $currentbrowser) ) {
1605 * Format an anchor fragment as it would appear for a given section name
1606 * @param string $text
1610 function sectionAnchor( $text ) {
1611 $headline = Sanitizer
::decodeCharReferences( $text );
1613 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1614 $headline = trim( $headline );
1615 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1616 $replacearray = array(
1621 array_keys( $replacearray ),
1622 array_values( $replacearray ),
1627 * Shows a bulletin board style toolbar for common editing functions.
1628 * It can be disabled in the user preferences.
1629 * The necessary JavaScript code can be found in style/wikibits.js.
1631 function getEditToolbar() {
1632 global $wgStylePath, $wgContLang, $wgJsMimeType;
1635 * toolarray an array of arrays which each include the filename of
1636 * the button image (without path), the opening tag, the closing tag,
1637 * and optionally a sample text that is inserted between the two when no
1638 * selection is highlighted.
1639 * The tip text is shown when the user moves the mouse over the button.
1641 * Already here are accesskeys (key), which are not used yet until someone
1642 * can figure out a way to make them work in IE. However, we should make
1643 * sure these keys are not defined on the edit page.
1646 array( 'image' => 'button_bold.png',
1647 'id' => 'mw-editbutton-bold',
1648 'open' => '\\\'\\\'\\\'',
1649 'close' => '\\\'\\\'\\\'',
1650 'sample'=> wfMsg('bold_sample'),
1651 'tip' => wfMsg('bold_tip'),
1654 array( 'image' => 'button_italic.png',
1655 'id' => 'mw-editbutton-italic',
1656 'open' => '\\\'\\\'',
1657 'close' => '\\\'\\\'',
1658 'sample'=> wfMsg('italic_sample'),
1659 'tip' => wfMsg('italic_tip'),
1662 array( 'image' => 'button_link.png',
1663 'id' => 'mw-editbutton-link',
1666 'sample'=> wfMsg('link_sample'),
1667 'tip' => wfMsg('link_tip'),
1670 array( 'image' => 'button_extlink.png',
1671 'id' => 'mw-editbutton-extlink',
1674 'sample'=> wfMsg('extlink_sample'),
1675 'tip' => wfMsg('extlink_tip'),
1678 array( 'image' => 'button_headline.png',
1679 'id' => 'mw-editbutton-headline',
1681 'close' => " ==\\n",
1682 'sample'=> wfMsg('headline_sample'),
1683 'tip' => wfMsg('headline_tip'),
1686 array( 'image' => 'button_image.png',
1687 'id' => 'mw-editbutton-image',
1688 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1690 'sample'=> wfMsg('image_sample'),
1691 'tip' => wfMsg('image_tip'),
1694 array( 'image' => 'button_media.png',
1695 'id' => 'mw-editbutton-media',
1696 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1698 'sample'=> wfMsg('media_sample'),
1699 'tip' => wfMsg('media_tip'),
1702 array( 'image' => 'button_math.png',
1703 'id' => 'mw-editbutton-math',
1705 'close' => "<\\/math>",
1706 'sample'=> wfMsg('math_sample'),
1707 'tip' => wfMsg('math_tip'),
1710 array( 'image' => 'button_nowiki.png',
1711 'id' => 'mw-editbutton-nowiki',
1712 'open' => "<nowiki>",
1713 'close' => "<\\/nowiki>",
1714 'sample'=> wfMsg('nowiki_sample'),
1715 'tip' => wfMsg('nowiki_tip'),
1718 array( 'image' => 'button_sig.png',
1719 'id' => 'mw-editbutton-signature',
1723 'tip' => wfMsg('sig_tip'),
1726 array( 'image' => 'button_hr.png',
1727 'id' => 'mw-editbutton-hr',
1728 'open' => "\\n----\\n",
1731 'tip' => wfMsg('hr_tip'),
1735 $toolbar = "<div id='toolbar'>\n";
1736 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1738 foreach($toolarray as $tool) {
1740 $cssId = $tool['id'];
1741 $image=$wgStylePath.'/common/images/'.$tool['image'];
1742 $open=$tool['open'];
1743 $close=$tool['close'];
1744 $sample = wfEscapeJsString( $tool['sample'] );
1746 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1747 // Older browsers show a "speedtip" type message only for ALT.
1748 // Ideally these should be different, realistically they
1749 // probably don't need to be.
1750 $tip = wfEscapeJsString( $tool['tip'] );
1752 #$key = $tool["key"];
1754 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1757 $toolbar.="/*]]>*/\n</script>";
1758 $toolbar.="\n</div>";
1763 * Returns an array of html code of the following checkboxes:
1766 * @param $tabindex Current tabindex
1767 * @param $skin Skin object
1768 * @param $checked Array of checkbox => bool, where bool indicates the checked
1769 * status of the checkbox
1773 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1776 $checkboxes = array();
1778 $checkboxes['minor'] = '';
1779 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1780 if ( $wgUser->isAllowed('minoredit') ) {
1782 'tabindex' => ++
$tabindex,
1783 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1784 'id' => 'wpMinoredit',
1786 $checkboxes['minor'] =
1787 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1788 " <label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1791 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1792 $checkboxes['watch'] = '';
1793 if ( $wgUser->isLoggedIn() ) {
1795 'tabindex' => ++
$tabindex,
1796 'accesskey' => wfMsg( 'accesskey-watch' ),
1797 'id' => 'wpWatchthis',
1799 $checkboxes['watch'] =
1800 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1801 " <label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1807 * Returns an array of html code of the following buttons:
1808 * save, diff, preview and live
1810 * @param $tabindex Current tabindex
1814 public function getEditButtons(&$tabindex) {
1815 global $wgLivePreview, $wgUser;
1823 'tabindex' => ++
$tabindex,
1824 'value' => wfMsg('savearticle'),
1825 'accesskey' => wfMsg('accesskey-save'),
1826 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1828 $buttons['save'] = wfElement('input', $temp, '');
1830 ++
$tabindex; // use the same for preview and live preview
1831 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1833 'id' => 'wpPreview',
1834 'name' => 'wpPreview',
1836 'tabindex' => $tabindex,
1837 'value' => wfMsg('showpreview'),
1839 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1840 'style' => 'display: none;',
1842 $buttons['preview'] = wfElement('input', $temp, '');
1845 'id' => 'wpLivePreview',
1846 'name' => 'wpLivePreview',
1848 'tabindex' => $tabindex,
1849 'value' => wfMsg('showlivepreview'),
1850 'accesskey' => wfMsg('accesskey-preview'),
1852 'onclick' => $this->doLivePreviewScript(),
1854 $buttons['live'] = wfElement('input', $temp, '');
1857 'id' => 'wpPreview',
1858 'name' => 'wpPreview',
1860 'tabindex' => $tabindex,
1861 'value' => wfMsg('showpreview'),
1862 'accesskey' => wfMsg('accesskey-preview'),
1863 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1865 $buttons['preview'] = wfElement('input', $temp, '');
1866 $buttons['live'] = '';
1873 'tabindex' => ++
$tabindex,
1874 'value' => wfMsg('showdiff'),
1875 'accesskey' => wfMsg('accesskey-diff'),
1876 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1878 $buttons['diff'] = wfElement('input', $temp, '');
1884 * Output preview text only. This can be sucked into the edit page
1885 * via JavaScript, and saves the server time rendering the skin as
1886 * well as theoretically being more robust on the client (doesn't
1887 * disturb the edit box's undo history, won't eat your text on
1890 * @todo This doesn't include category or interlanguage links.
1891 * Would need to enhance it a bit, <s>maybe wrap them in XML
1892 * or something...</s> that might also require more skin
1893 * initialization, so check whether that's a problem.
1895 function livePreview() {
1898 header( 'Content-type: text/xml; charset=utf-8' );
1899 header( 'Cache-control: no-cache' );
1902 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1903 Xml
::openElement( 'livepreview' ) .
1904 Xml
::element( 'preview', null, $this->getPreviewText() ) .
1905 Xml
::element( 'br', array( 'style' => 'clear: both;' ) ) .
1906 Xml
::closeElement( 'livepreview' );
1912 * Get a diff between the current contents of the edit box and the
1913 * version of the page we're editing from.
1915 * If this is a section edit, we'll replace the section as for final
1916 * save and then make a comparison.
1918 function showDiff() {
1919 $oldtext = $this->mArticle
->fetchContent();
1920 $newtext = $this->mArticle
->replaceSection(
1921 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1922 $newtext = $this->mArticle
->preSaveTransform( $newtext );
1923 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1924 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1925 if ( $oldtext !== false ||
$newtext != '' ) {
1926 $de = new DifferenceEngine( $this->mTitle
);
1927 $de->setText( $oldtext, $newtext );
1928 $difftext = $de->getDiff( $oldtitle, $newtitle );
1929 $de->showDiffStyle();
1935 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
1939 * Filter an input field through a Unicode de-armoring process if it
1940 * came from an old browser with known broken Unicode editing issues.
1942 * @param WebRequest $request
1943 * @param string $field
1947 function safeUnicodeInput( $request, $field ) {
1948 $text = rtrim( $request->getText( $field ) );
1949 return $request->getBool( 'safemode' )
1950 ?
$this->unmakesafe( $text )
1955 * Filter an output field through a Unicode armoring process if it is
1956 * going to an old browser with known broken Unicode editing issues.
1958 * @param string $text
1962 function safeUnicodeOutput( $text ) {
1964 $codedText = $wgContLang->recodeForEdit( $text );
1965 return $this->checkUnicodeCompliantBrowser()
1967 : $this->makesafe( $codedText );
1971 * A number of web browsers are known to corrupt non-ASCII characters
1972 * in a UTF-8 text editing environment. To protect against this,
1973 * detected browsers will be served an armored version of the text,
1974 * with non-ASCII chars converted to numeric HTML character references.
1976 * Preexisting such character references will have a 0 added to them
1977 * to ensure that round-trips do not alter the original data.
1979 * @param string $invalue
1983 function makesafe( $invalue ) {
1984 // Armor existing references for reversability.
1985 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1990 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1991 $bytevalue = ord( $invalue{$i} );
1992 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1993 $result .= chr( $bytevalue );
1995 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1996 $working = $working << 6;
1997 $working +
= ($bytevalue & 0x3F);
1999 if( $bytesleft <= 0 ) {
2000 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2002 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
2003 $working = $bytevalue & 0x1F;
2005 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
2006 $working = $bytevalue & 0x0F;
2008 } else { //1111 0xxx
2009 $working = $bytevalue & 0x07;
2017 * Reverse the previously applied transliteration of non-ASCII characters
2018 * back to UTF-8. Used to protect data from corruption by broken web browsers
2019 * as listed in $wgBrowserBlackList.
2021 * @param string $invalue
2025 function unmakesafe( $invalue ) {
2027 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2028 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2032 $hexstring .= $invalue{$i};
2034 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2036 // Do some sanity checks. These aren't needed for reversability,
2037 // but should help keep the breakage down if the editor
2038 // breaks one of the entities whilst editing.
2039 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2040 $codepoint = hexdec($hexstring);
2041 $result .= codepointToUtf8( $codepoint );
2043 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2046 $result .= substr( $invalue, $i, 1 );
2049 // reverse the transform that we made for reversability reasons.
2050 return strtr( $result, array( "�" => "&#x" ) );
2053 function noCreatePermission() {
2055 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2056 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
2060 * If there are rows in the deletion log for this page, show them,
2061 * along with a nice little note for the user
2063 * @param OutputPage $out
2065 private function showDeletionLog( $out ) {
2066 $title = $this->mArticle
->getTitle();
2067 $reader = new LogReader(
2070 'page' => $title->getPrefixedText(),
2075 if( $reader->hasRows() ) {
2076 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2077 $out->addWikiText( wfMsg( 'recreate-deleted-warn' ) );
2078 $viewer = new LogViewer( $reader );
2079 $viewer->showList( $out );
2080 $out->addHtml( '</div>' );