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
108 if ( $undo > 0 && $undo > $undoafter ) {
109 # Undoing a specific edit overrides section editing; section-editing
110 # doesn't work with undoing.
112 $undorev = Revision
::newFromId($undo);
113 $oldrev = Revision
::newFromId($undoafter);
115 $undorev = Revision
::newFromId($undo);
116 $oldrev = $undorev ?
$undorev->getPrevious() : null;
119 #Sanity check, make sure it's the right page.
120 # Otherwise, $text will be left as-is.
121 if ( !is_null($undorev) && !is_null($oldrev) && $undorev->getPage()==$oldrev->getPage() && $undorev->getPage()==$this->mArticle
->getID() ) {
122 $undorev_text = $undorev->getText();
123 $oldrev_text = $oldrev->getText();
124 $currev_text = $text;
126 #No use doing a merge if it's just a straight revert.
127 if ( $currev_text != $undorev_text ) {
128 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
130 $text = $oldrev_text;
134 // Failed basic sanity checks.
135 // Older revisions may have been removed since the link
136 // was created, or we may simply have got bogus input.
141 # Inform the user of our success and set an automatic edit summary
142 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
143 $firstrev = $oldrev->getNext();
144 # If we just undid one rev, use an autosummary
145 if ( $firstrev->mId
== $undo ) {
146 $this->summary
= wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
148 $this->formtype
= 'diff';
150 # Warn the user that something went wrong
151 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
153 } else if( $section != '' ) {
154 if( $section == 'new' ) {
155 $text = $this->getPreloadedText( $preload );
157 $text = $wgParser->getSection( $text, $section, $def_text );
162 wfProfileOut( __METHOD__
);
167 * Get the contents of a page from its title and remove includeonly tags
169 * @param $preload String: the title of the page.
170 * @return string The contents of the page.
172 private function getPreloadedText($preload) {
173 if ( $preload === '' )
176 $preloadTitle = Title
::newFromText( $preload );
177 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
178 $rev=Revision
::newFromTitle($preloadTitle);
179 if ( is_object( $rev ) ) {
180 $text = $rev->getText();
181 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
182 // its own mini-parser! -ævar
183 $text = preg_replace( '~</?includeonly>~', '', $text );
192 * This is the function that extracts metadata from the article body on the first view.
193 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
194 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
196 function extractMetaDataFromArticle () {
197 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
198 $this->mMetaData
= '' ;
199 if ( !$wgUseMetadataEdit ) return ;
200 if ( $wgMetadataWhitelist == '' ) return ;
202 $t = $this->getContent();
204 # MISSING : <nowiki> filtering
206 # Categories and language links
207 $t = explode ( "\n" , $t ) ;
208 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
209 $cat = $ll = array() ;
210 foreach ( $t AS $key => $x )
212 $y = trim ( strtolower ( $x ) ) ;
213 while ( substr ( $y , 0 , 2 ) == '[[' )
215 $y = explode ( ']]' , trim ( $x ) ) ;
216 $first = array_shift ( $y ) ;
217 $first = explode ( ':' , $first ) ;
218 $ns = array_shift ( $first ) ;
219 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
220 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
222 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
223 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
225 $x = implode ( ']]' , $y ) ;
227 $y = trim ( strtolower ( $x ) ) ;
231 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
232 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
233 $t = implode ( "\n" , $t ) ;
236 $sat = array () ; # stand-alone-templates; must be lowercase
237 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
238 $wl_article = new Article ( $wl_title ) ;
239 $wl = explode ( "\n" , $wl_article->getContent() ) ;
240 foreach ( $wl AS $x )
244 while ( substr ( $x , 0 , 1 ) == '*' )
247 $x = trim ( substr ( $x , 1 ) ) ;
251 $sat[] = strtolower ( $x ) ;
256 # Templates, but only some
257 $t = explode ( '{{' , $t ) ;
259 foreach ( $t AS $key => $x )
261 $y = explode ( '}}' , $x , 2 ) ;
262 if ( count ( $y ) == 2 )
265 $z = explode ( '|' , $z ) ;
266 $tn = array_shift ( $z ) ;
267 if ( in_array ( strtolower ( $tn ) , $sat ) )
269 $tl[] = '{{' . $y[0] . '}}' ;
271 $y = explode ( '}}' , $y[1] , 2 ) ;
273 else $t[$key] = '{{' . $x ;
275 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
278 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
279 $t = implode ( '' , $t ) ;
281 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
282 $this->mArticle
->mContent
= $t ;
283 $this->mMetaData
= $s ;
291 * This is the function that gets called for "action=edit". It
292 * sets up various member variables, then passes execution to
293 * another function, usually showEditForm()
295 * The edit form is self-submitting, so that when things like
296 * preview and edit conflicts occur, we get the same form back
297 * with the extra stuff added. Only when the final submission
298 * is made and all is well do we actually save and redirect to
299 * the newly-edited page.
302 global $wgOut, $wgUser, $wgRequest, $wgTitle;
303 global $wgEmailConfirmToEdit;
305 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
308 $fname = 'EditPage::edit';
309 wfProfileIn( $fname );
310 wfDebug( "$fname: enter\n" );
312 // this is not an article
313 $wgOut->setArticleFlag(false);
315 $this->importFormData( $wgRequest );
316 $this->firsttime
= false;
319 $this->livePreview();
320 wfProfileOut( $fname );
324 if ( ! $this->mTitle
->userCan( 'edit' ) ) {
325 wfDebug( "$fname: user can't edit\n" );
326 $wgOut->readOnlyPage( $this->getContent(), true );
327 wfProfileOut( $fname );
330 wfDebug( "$fname: Checking blocks\n" );
331 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
332 # When previewing, don't check blocked state - will get caught at save time.
333 # Also, check when starting edition is done against slave to improve performance.
334 wfDebug( "$fname: user is blocked\n" );
335 $this->blockedPage();
336 wfProfileOut( $fname );
339 if ( !$wgUser->isAllowed('edit') ) {
340 if ( $wgUser->isAnon() ) {
341 wfDebug( "$fname: user must log in\n" );
342 $this->userNotLoggedInPage();
343 wfProfileOut( $fname );
346 wfDebug( "$fname: read-only page\n" );
347 $wgOut->readOnlyPage( $this->getContent(), true );
348 wfProfileOut( $fname );
352 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
353 wfDebug("$fname: user must confirm e-mail address\n");
354 $this->userNotConfirmedPage();
355 wfProfileOut($fname);
358 if ( !$this->mTitle
->userCan( 'create' ) && !$this->mTitle
->exists() ) {
359 wfDebug( "$fname: no create permission\n" );
360 $this->noCreatePermission();
361 wfProfileOut( $fname );
364 if ( wfReadOnly() ) {
365 wfDebug( "$fname: read-only mode is engaged\n" );
366 if( $this->save ||
$this->preview
) {
367 $this->formtype
= 'preview';
368 } else if ( $this->diff
) {
369 $this->formtype
= 'diff';
371 $wgOut->readOnlyPage( $this->getContent() );
372 wfProfileOut( $fname );
377 $this->formtype
= 'save';
378 } else if ( $this->preview
) {
379 $this->formtype
= 'preview';
380 } else if ( $this->diff
) {
381 $this->formtype
= 'diff';
382 } else { # First time through
383 $this->firsttime
= true;
384 if( $this->previewOnOpen() ) {
385 $this->formtype
= 'preview';
387 $this->extractMetaDataFromArticle () ;
388 $this->formtype
= 'initial';
393 wfProfileIn( "$fname-business-end" );
395 $this->isConflict
= false;
396 // css / js subpages of user pages get a special treatment
397 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
398 $this->isValidCssJsSubpage
= $wgTitle->isValidCssJsSubpage();
400 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
401 * no matter it's current state
403 $this->deletedSinceEdit
= false;
404 if ( $this->edittime
!= '' ) {
405 /* Note that we rely on logging table, which hasn't been always there,
406 * but that doesn't matter, because this only applies to brand new
407 * deletes. This is done on every preview and save request. Move it further down
408 * to only perform it on saves
410 if ( $this->mTitle
->isDeleted() ) {
411 $this->lastDelete
= $this->getLastDelete();
412 if ( !is_null($this->lastDelete
) ) {
413 $deletetime = $this->lastDelete
->log_timestamp
;
414 if ( ($deletetime - $this->starttime
) > 0 ) {
415 $this->deletedSinceEdit
= true;
421 # Show applicable editing introductions
422 if( $this->formtype
== 'initial' ||
$this->firsttime
)
425 if( $this->mTitle
->isTalkPage() ) {
426 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
429 # Attempt submission here. This will check for edit conflicts,
430 # and redundantly check for locked database, blocked IPs, etc.
431 # that edit() already checked just in case someone tries to sneak
432 # in the back door with a hand-edited submission URL.
434 if ( 'save' == $this->formtype
) {
435 if ( !$this->attemptSave() ) {
436 wfProfileOut( "$fname-business-end" );
437 wfProfileOut( $fname );
442 # First time through: get contents, set time for conflict
444 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
445 if ($this->initialiseForm() === false) {
446 $this->noSuchSectionPage();
447 wfProfileOut( "$fname-business-end" );
448 wfProfileOut( $fname );
451 if( !$this->mTitle
->getArticleId() )
452 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
455 $this->showEditForm();
456 wfProfileOut( "$fname-business-end" );
457 wfProfileOut( $fname );
461 * Return true if this page should be previewed when the edit form
462 * is initially opened.
466 function previewOnOpen() {
468 return $this->section
!= 'new' &&
469 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle
->exists() ) ||
470 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
471 !$this->mTitle
->exists() ) );
478 function importFormData( &$request ) {
479 global $wgLang, $wgUser;
480 $fname = 'EditPage::importFormData';
481 wfProfileIn( $fname );
483 if( $request->wasPosted() ) {
484 # These fields need to be checked for encoding.
485 # Also remove trailing whitespace, but don't remove _initial_
486 # whitespace from the text boxes. This may be significant formatting.
487 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
488 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
489 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
490 # Truncate for whole multibyte characters. +5 bytes for ellipsis
491 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
493 $this->edittime
= $request->getVal( 'wpEdittime' );
494 $this->starttime
= $request->getVal( 'wpStarttime' );
496 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
498 if( is_null( $this->edittime
) ) {
499 # If the form is incomplete, force to preview.
500 wfDebug( "$fname: Form data appears to be incomplete\n" );
501 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
502 $this->preview
= true;
504 /* Fallback for live preview */
505 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
506 $this->diff
= $request->getCheck( 'wpDiff' );
508 // Remember whether a save was requested, so we can indicate
509 // if we forced preview due to session failure.
510 $this->mTriedSave
= !$this->preview
;
512 if ( $this->tokenOk( $request ) ) {
513 # Some browsers will not report any submit button
514 # if the user hits enter in the comment box.
515 # The unmarked state will be assumed to be a save,
516 # if the form seems otherwise complete.
517 wfDebug( "$fname: Passed token check.\n" );
518 } else if ( $this->diff
) {
519 # Failed token check, but only requested "Show Changes".
520 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
522 # Page might be a hack attempt posted from
523 # an external site. Preview instead of saving.
524 wfDebug( "$fname: Failed token check; forcing preview\n" );
525 $this->preview
= true;
528 $this->save
= ! ( $this->preview
OR $this->diff
);
529 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
530 $this->edittime
= null;
533 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
534 $this->starttime
= null;
537 $this->recreate
= $request->getCheck( 'wpRecreate' );
539 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
540 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
542 # Don't force edit summaries when a user is editing their own user or talk page
543 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
544 $this->allowBlankSummary
= true;
546 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
549 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
551 # Not a posted form? Start with nothing.
552 wfDebug( "$fname: Not a posted form.\n" );
553 $this->textbox1
= '';
554 $this->textbox2
= '';
555 $this->mMetaData
= '';
557 $this->edittime
= '';
558 $this->starttime
= wfTimestampNow();
559 $this->preview
= false;
562 $this->minoredit
= false;
563 $this->watchthis
= false;
564 $this->recreate
= false;
567 $this->oldid
= $request->getInt( 'oldid' );
569 # Section edit can come from either the form or a link
570 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
572 $this->live
= $request->getCheck( 'live' );
573 $this->editintro
= $request->getText( 'editintro' );
575 wfProfileOut( $fname );
579 * Make sure the form isn't faking a user's credentials.
581 * @param $request WebRequest
585 function tokenOk( &$request ) {
587 $token = $request->getVal( 'wpEditToken' );
588 $this->mTokenOk
= $wgUser->matchEditToken( $token );
589 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
590 return $this->mTokenOk
;
594 * Show all applicable editing introductions
596 private function showIntro() {
597 global $wgOut, $wgUser;
598 if( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
599 if( $wgUser->isLoggedIn() ) {
600 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
602 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
604 $this->showDeletionLog( $wgOut );
609 * Attempt to show a custom editing introduction, if supplied
613 private function showCustomIntro() {
614 if( $this->editintro
) {
615 $title = Title
::newFromText( $this->editintro
);
616 if( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
618 $revision = Revision
::newFromTitle( $title );
619 $wgOut->addSecondaryWikiText( $revision->getText() );
631 * @return bool false if output is done, true if the rest of the form should be displayed
633 function attemptSave() {
634 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
635 global $wgMaxArticleSize;
637 $fname = 'EditPage::attemptSave';
638 wfProfileIn( $fname );
639 wfProfileIn( "$fname-checks" );
641 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
643 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
647 # Reintegrate metadata
648 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
649 $this->mMetaData
= '' ;
653 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
654 $this->spamPage ( $matches[0] );
655 wfProfileOut( "$fname-checks" );
656 wfProfileOut( $fname );
659 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
660 # Error messages or other handling should be performed by the filter function
661 wfProfileOut( $fname );
662 wfProfileOut( "$fname-checks" );
665 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
) ) ) {
666 # Error messages etc. could be handled within the hook...
667 wfProfileOut( $fname );
668 wfProfileOut( "$fname-checks" );
670 } elseif( $this->hookError
!= '' ) {
671 # ...or the hook could be expecting us to produce an error
672 wfProfileOut( "$fname-checks " );
673 wfProfileOut( $fname );
676 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
677 # Check block state against master, thus 'false'.
678 $this->blockedPage();
679 wfProfileOut( "$fname-checks" );
680 wfProfileOut( $fname );
683 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
684 if ( $this->kblength
> $wgMaxArticleSize ) {
685 // Error will be displayed by showEditForm()
686 $this->tooBig
= true;
687 wfProfileOut( "$fname-checks" );
688 wfProfileOut( $fname );
692 if ( !$wgUser->isAllowed('edit') ) {
693 if ( $wgUser->isAnon() ) {
694 $this->userNotLoggedInPage();
695 wfProfileOut( "$fname-checks" );
696 wfProfileOut( $fname );
700 $wgOut->readOnlyPage();
701 wfProfileOut( "$fname-checks" );
702 wfProfileOut( $fname );
707 if ( wfReadOnly() ) {
708 $wgOut->readOnlyPage();
709 wfProfileOut( "$fname-checks" );
710 wfProfileOut( $fname );
713 if ( $wgUser->pingLimiter() ) {
714 $wgOut->rateLimited();
715 wfProfileOut( "$fname-checks" );
716 wfProfileOut( $fname );
720 # If the article has been deleted while editing, don't save it without
722 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
723 wfProfileOut( "$fname-checks" );
724 wfProfileOut( $fname );
728 wfProfileOut( "$fname-checks" );
730 # If article is new, insert it.
731 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
734 // Late check for create permission, just in case *PARANOIA*
735 if ( !$this->mTitle
->userCan( 'create' ) ) {
736 wfDebug( "$fname: no create permission\n" );
737 $this->noCreatePermission();
738 wfProfileOut( $fname );
742 # Don't save a new article if it's blank.
743 if ( ( '' == $this->textbox1
) ) {
744 $wgOut->redirect( $this->mTitle
->getFullURL() );
745 wfProfileOut( $fname );
749 $isComment=($this->section
=='new');
750 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
751 $this->minoredit
, $this->watchthis
, false, $isComment);
753 wfProfileOut( $fname );
757 # Article exists. Check for edit conflict.
759 $this->mArticle
->clear(); # Force reload of dates, etc.
760 $this->mArticle
->forUpdate( true ); # Lock the article
762 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
764 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
765 $this->isConflict
= true;
766 if( $this->section
== 'new' ) {
767 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
768 $this->mArticle
->getComment() == $this->summary
) {
769 // Probably a duplicate submission of a new comment.
770 // This can happen when squid resends a request after
771 // a timeout but the first one actually went through.
772 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
774 // New comment; suppress conflict.
775 $this->isConflict
= false;
776 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
780 $userid = $wgUser->getID();
782 if ( $this->isConflict
) {
783 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
784 $this->mArticle
->getTimestamp() . "'\n" );
785 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
788 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
789 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
791 if( is_null( $text ) ) {
792 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
793 $this->isConflict
= true;
794 $text = $this->textbox1
;
797 # Suppress edit conflict with self, except for section edits where merging is required.
798 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
799 wfDebug( "Suppressing edit conflict, same user.\n" );
800 $this->isConflict
= false;
802 # switch from section editing to normal editing in edit conflict
803 if($this->isConflict
) {
805 if( $this->mergeChangesInto( $text ) ){
806 // Successful merge! Maybe we should tell the user the good news?
807 $this->isConflict
= false;
808 wfDebug( "Suppressing edit conflict, successful merge.\n" );
811 $this->textbox1
= $text;
812 wfDebug( "Keeping edit conflict, failed merge.\n" );
817 if ( $this->isConflict
) {
818 wfProfileOut( $fname );
822 $oldtext = $this->mArticle
->getContent();
824 # Handle the user preference to force summaries here, but not for null edits
825 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary')
826 && 0 != strcmp($oldtext, $text) && !Article
::getRedirectAutosummary( $text )) {
827 if( md5( $this->summary
) == $this->autoSumm
) {
828 $this->missingSummary
= true;
829 wfProfileOut( $fname );
834 #And a similar thing for new sections
835 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
836 if (trim($this->summary
) == '') {
837 $this->missingSummary
= true;
838 wfProfileOut( $fname );
844 wfProfileIn( "$fname-sectionanchor" );
846 if( $this->section
== 'new' ) {
847 if ( $this->textbox1
== '' ) {
848 $this->missingComment
= true;
851 if( $this->summary
!= '' ) {
852 $sectionanchor = $this->sectionAnchor( $this->summary
);
854 } elseif( $this->section
!= '' ) {
855 # Try to get a section anchor from the section source, redirect to edited section if header found
856 # XXX: might be better to integrate this into Article::replaceSection
857 # for duplicate heading checking and maybe parsing
858 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
859 # we can't deal with anchors, includes, html etc in the header for now,
860 # headline would need to be parsed to improve this
861 if($hasmatch and strlen($matches[2]) > 0) {
862 $sectionanchor = $this->sectionAnchor( $matches[2] );
865 wfProfileOut( "$fname-sectionanchor" );
867 // Save errors may fall down to the edit form, but we've now
868 // merged the section into full text. Clear the section field
869 // so that later submission of conflict forms won't try to
870 // replace that into a duplicated mess.
871 $this->textbox1
= $text;
874 // Check for length errors again now that the section is merged in
875 $this->kblength
= (int)(strlen( $text ) / 1024);
876 if ( $this->kblength
> $wgMaxArticleSize ) {
877 $this->tooBig
= true;
878 wfProfileOut( $fname );
882 # update the article here
883 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
884 $this->watchthis
, '', $sectionanchor ) ) {
885 wfProfileOut( $fname );
888 $this->isConflict
= true;
890 wfProfileOut( $fname );
895 * Initialise form fields in the object
896 * Called on the first invocation, e.g. when a user clicks an edit link
898 function initialiseForm() {
899 $this->edittime
= $this->mArticle
->getTimestamp();
901 $this->textbox1
= $this->getContent(false);
902 if ($this->textbox1
=== false) return false;
904 if ( !$this->mArticle
->exists() && $this->mArticle
->mTitle
->getNamespace() == NS_MEDIAWIKI
)
905 $this->textbox1
= wfMsgWeirdKey( $this->mArticle
->mTitle
->getText() );
911 * Send the edit form and related headers to $wgOut
912 * @param $formCallback Optional callable that takes an OutputPage
913 * parameter; will be called during form output
914 * near the top, for captchas and the like.
916 function showEditForm( $formCallback=null ) {
917 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
919 $fname = 'EditPage::showEditForm';
920 wfProfileIn( $fname );
922 $sk = $wgUser->getSkin();
924 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
926 $wgOut->setRobotpolicy( 'noindex,nofollow' );
928 # Enabled article-related sidebar, toplinks, etc.
929 $wgOut->setArticleRelated( true );
931 if ( $this->isConflict
) {
932 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
933 $wgOut->setPageTitle( $s );
934 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
936 $this->textbox2
= $this->textbox1
;
937 $this->textbox1
= $this->getContent();
938 $this->edittime
= $this->mArticle
->getTimestamp();
941 if( $this->section
!= '' ) {
942 if( $this->section
== 'new' ) {
943 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
945 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
947 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
948 preg_match( "/^(=+)(.+)\\1/mi",
951 if( !empty( $matches[2] ) ) {
952 $this->summary
= "/* ". trim($matches[2])." */ ";
957 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
959 $wgOut->setPageTitle( $s );
961 if ( $this->missingComment
) {
962 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
965 if( $this->missingSummary
&& $this->section
!= 'new' ) {
966 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
969 if( $this->missingSummary
&& $this->section
== 'new' ) {
970 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
973 if( !$this->hookError
== '' ) {
974 $wgOut->addWikiText( $this->hookError
);
977 if ( !$this->checkUnicodeCompliantBrowser() ) {
978 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
980 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
981 // Let sysop know that this will make private content public if saved
982 if( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
983 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
985 if( !$this->mArticle
->mRevision
->isCurrent() ) {
986 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
987 $wgOut->addWikiText( wfMsg( 'editingold' ) );
993 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
994 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
995 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
997 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
998 # Check the skin exists
999 if( $this->isValidCssJsSubpage
) {
1000 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
1002 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
1007 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1008 # Show a warning if editing an interface message
1009 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
1010 } elseif( $this->mTitle
->isProtected( 'edit' ) ) {
1011 # Is the title semi-protected?
1012 if( $this->mTitle
->isSemiProtected() ) {
1013 $notice = wfMsg( 'semiprotectedpagewarning' );
1014 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' )
1017 # Then it must be protected based on static groups (regular)
1018 $notice = wfMsg( 'protectedpagewarning' );
1020 $wgOut->addWikiText( $notice );
1022 if ( $this->mTitle
->isCascadeProtected() ) {
1023 # Is this page under cascading protection from some source pages?
1024 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1025 if ( count($cascadeSources) > 0 ) {
1026 # Explain, and list the titles responsible
1027 $notice = wfMsgExt( 'cascadeprotectedwarning', array('parsemag'), count($cascadeSources) ) . "\n";
1028 foreach( $cascadeSources as $id => $page )
1029 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1031 $wgOut->addWikiText( $notice );
1034 if ( $this->kblength
=== false ) {
1035 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1037 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1038 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgMaxArticleSize ) );
1039 } elseif( $this->kblength
> 29 ) {
1040 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) ) );
1043 #need to parse the preview early so that we know which templates are used,
1044 #otherwise users with "show preview after edit box" will get a blank list
1045 if ( $this->formtype
== 'preview' ) {
1046 $previewOutput = $this->getPreviewText();
1049 $rows = $wgUser->getIntOption( 'rows' );
1050 $cols = $wgUser->getIntOption( 'cols' );
1052 $ew = $wgUser->getOption( 'editwidth' );
1053 if ( $ew ) $ew = " style=\"width:100%\"";
1056 $q = 'action=submit';
1057 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1058 $action = $this->mTitle
->escapeLocalURL( $q );
1060 $summary = wfMsg('summary');
1061 $subject = wfMsg('subject');
1063 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
1064 wfMsgExt('cancel', array('parseinline')) );
1065 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1066 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1067 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1068 htmlspecialchars( wfMsg( 'newwindow' ) );
1070 global $wgRightsText;
1071 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1072 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
1073 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1074 $wgRightsText ) . "\n</div>";
1076 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1077 # prepare toolbar for edit buttons
1078 $toolbar = $this->getEditToolbar();
1083 // activate checkboxes if user wants them to be always active
1084 if( !$this->preview
&& !$this->diff
) {
1085 # Sort out the "watch" checkbox
1086 if( $wgUser->getOption( 'watchdefault' ) ) {
1088 $this->watchthis
= true;
1089 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1091 $this->watchthis
= true;
1092 } elseif( $this->mTitle
->userIsWatching() ) {
1094 $this->watchthis
= true;
1097 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1100 $wgOut->addHTML( $this->editFormPageTop
);
1102 if ( $wgUser->getOption( 'previewontop' ) ) {
1104 if ( 'preview' == $this->formtype
) {
1105 $this->showPreview( $previewOutput );
1107 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1110 if ( 'diff' == $this->formtype
) {
1116 $wgOut->addHTML( $this->editFormTextTop
);
1118 # if this is a comment, show a subject line at the top, which is also the edit summary.
1119 # Otherwise, show a summary field at the bottom
1120 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1121 if( $this->section
== 'new' ) {
1122 $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 />";
1124 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1125 $summarypreview = '';
1127 $commentsubject = '';
1128 $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 />";
1129 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1130 $subjectpreview = '';
1133 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1134 if( !$this->preview
&& !$this->diff
) {
1135 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1137 $templates = ($this->preview ||
$this->section
!= '') ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1138 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1140 global $wgUseMetadataEdit ;
1141 if ( $wgUseMetadataEdit ) {
1142 $metadata = $this->mMetaData
;
1143 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1144 $top = wfMsgWikiHtml( 'metadata_help' );
1145 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1147 else $metadata = "" ;
1151 if ($this->deletedSinceEdit
) {
1152 if ( 'save' != $this->formtype
) {
1153 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1155 // Hide the toolbar and edit area, use can click preview to get it back
1156 // Add an confirmation checkbox and explanation.
1158 $hidden = 'type="hidden" style="display:none;"';
1159 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1161 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1162 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1168 $checkboxes = self
::getCheckboxes( $tabindex, $sk,
1169 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1171 $checkboxhtml = implode( $checkboxes, "\n" );
1173 $buttons = $this->getEditButtons( $tabindex );
1174 $buttonshtml = implode( $buttons, "\n" );
1176 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1177 ?
'' : Xml
::hidden( 'safemode', '1' );
1179 $wgOut->addHTML( <<<END
1181 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1185 if( is_callable( $formCallback ) ) {
1186 call_user_func_array( $formCallback, array( &$wgOut ) );
1189 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1191 // Put these up at the top to ensure they aren't lost on early form submission
1193 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1194 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1195 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1196 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1198 $wgOut->addHTML( <<<END
1202 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1203 cols='{$cols}'{$ew} $hidden>
1205 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
1210 $wgOut->addWikiText( $copywarn );
1211 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1221 "<div class='editButtons'>
1223 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1224 </div><!-- editButtons -->
1225 </div><!-- editOptions -->");
1227 $wgOut->addHtml( '<div class="mw-editTools">' );
1228 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1229 $wgOut->addHtml( '</div>' );
1231 $wgOut->addHTML( $this->editFormTextAfterTools
);
1234 <div class='templatesUsed'>
1235 {$formattedtemplates}
1240 * To make it harder for someone to slip a user a page
1241 * which submits an edit form to the wiki without their
1242 * knowledge, a random token is associated with the login
1243 * session. If it's not passed back with the submission,
1244 * we won't save the page, or render user JavaScript and
1247 * For anon editors, who may not have a session, we just
1248 * include the constant suffix to prevent editing from
1249 * broken text-mangling proxies.
1251 $token = htmlspecialchars( $wgUser->editToken() );
1252 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1255 # If a blank edit summary was previously provided, and the appropriate
1256 # user preference is active, pass a hidden tag here. This will stop the
1257 # user being bounced back more than once in the event that a summary
1259 if( $this->missingSummary
) {
1260 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1263 # For a bit more sophisticated detection of blank summaries, hash the
1264 # automatic one and pass that in a hidden field.
1265 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1266 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1268 if ( $this->isConflict
) {
1269 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1271 $de = new DifferenceEngine( $this->mTitle
);
1272 $de->setText( $this->textbox2
, $this->textbox1
);
1273 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1275 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1276 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1277 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1279 $wgOut->addHTML( $this->editFormTextBottom
);
1280 $wgOut->addHTML( "</form>\n" );
1281 if ( !$wgUser->getOption( 'previewontop' ) ) {
1283 if ( $this->formtype
== 'preview') {
1284 $this->showPreview( $previewOutput );
1286 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1289 if ( $this->formtype
== 'diff') {
1295 wfProfileOut( $fname );
1299 * Append preview output to $wgOut.
1300 * Includes category rendering if this is a category page.
1302 * @param string $text The HTML to be output for the preview.
1304 private function showPreview( $text ) {
1307 $wgOut->addHTML( '<div id="wikiPreview">' );
1308 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1309 $this->mArticle
->openShowCategory();
1311 $wgOut->addHTML( $text );
1312 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1313 $this->mArticle
->closeShowCategory();
1315 $wgOut->addHTML( '</div>' );
1319 * Live Preview lets us fetch rendered preview page content and
1320 * add it to the page without refreshing the whole page.
1321 * If not supported by the browser it will fall through to the normal form
1322 * submission method.
1324 * This function outputs a script tag to support live preview, and
1325 * returns an onclick handler which should be added to the attributes
1326 * of the preview button
1328 function doLivePreviewScript() {
1329 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1330 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1331 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1332 '"></script>' . "\n" );
1333 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1334 return "return !livePreview(" .
1335 "getElementById('wikiPreview')," .
1336 "editform.wpTextbox1.value," .
1337 '"' . $liveAction . '"' . ")";
1340 function getLastDelete() {
1341 $dbr = wfGetDB( DB_SLAVE
);
1342 $fname = 'EditPage::getLastDelete';
1343 $res = $dbr->select(
1344 array( 'logging', 'user' ),
1354 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1355 'log_title' => $this->mTitle
->getDBkey(),
1356 'log_type' => 'delete',
1357 'log_action' => 'delete',
1358 'user_id=log_user' ),
1360 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1362 if($dbr->numRows($res) == 1) {
1363 while ( $x = $dbr->fetchObject ( $res ) )
1365 $dbr->freeResult ( $res ) ;
1375 function getPreviewText() {
1376 global $wgOut, $wgUser, $wgTitle, $wgParser;
1378 $fname = 'EditPage::getPreviewText';
1379 wfProfileIn( $fname );
1381 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1382 if ( $this->mTokenOkExceptSuffix
) {
1383 $msg = 'token_suffix_mismatch';
1385 $msg = 'session_fail_preview';
1388 $msg = 'previewnote';
1390 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1391 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1392 if ( $this->isConflict
) {
1393 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1396 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1397 $parserOptions->setEditSection( false );
1400 if( $wgRawHtml && !$this->mTokenOk
) {
1401 // Could be an offsite preview attempt. This is very unsafe if
1402 // HTML is enabled, as it could be an attack.
1403 return $wgOut->parse( "<div class='previewnote'>" .
1404 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1407 # don't parse user css/js, show message about preview
1408 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1410 if ( $this->isCssJsSubpage
) {
1411 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1412 $previewtext = wfMsg('usercsspreview');
1413 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1414 $previewtext = wfMsg('userjspreview');
1416 $parserOptions->setTidy(true);
1417 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1418 $wgOut->addHTML( $parserOutput->mText
);
1419 wfProfileOut( $fname );
1420 return $previewhead;
1422 $toparse = $this->textbox1
;
1424 # If we're adding a comment, we need to show the
1425 # summary as the headline
1426 if($this->section
=="new" && $this->summary
!="") {
1427 $toparse="== {$this->summary} ==\n\n".$toparse;
1430 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1431 $parserOptions->setTidy(true);
1432 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1433 $wgTitle, $parserOptions );
1435 $previewHTML = $parserOutput->getText();
1436 $wgOut->addParserOutputNoText( $parserOutput );
1438 # ParserOutput might have altered the page title, so reset it
1439 $wgOut->setPageTitle( wfMsg( 'editing', $this->mTitle
->getPrefixedText() ) );
1441 foreach ( $parserOutput->getTemplates() as $ns => $template)
1442 foreach ( array_keys( $template ) as $dbk)
1443 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1445 wfProfileOut( $fname );
1446 return $previewhead . $previewHTML;
1451 * Call the stock "user is blocked" page
1453 function blockedPage() {
1454 global $wgOut, $wgUser;
1455 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1457 # If the user made changes, preserve them when showing the markup
1458 # (This happens when a user is blocked during edit, for instance)
1459 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1461 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1463 $source = $this->textbox1
;
1466 # Spit out the source or the user's modified version
1467 if( $source !== false ) {
1468 $rows = $wgUser->getOption( 'rows' );
1469 $cols = $wgUser->getOption( 'cols' );
1470 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1471 $wgOut->addHtml( '<hr />' );
1472 $wgOut->addWikiText( wfMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() ) );
1473 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1478 * Produce the stock "please login to edit pages" page
1480 function userNotLoggedInPage() {
1481 global $wgUser, $wgOut;
1482 $skin = $wgUser->getSkin();
1484 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1485 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle
->getPrefixedUrl() );
1487 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1488 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1489 $wgOut->setArticleRelated( false );
1491 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1492 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1496 * Creates a basic error page which informs the user that
1497 * they have to validate their email address before being
1500 function userNotConfirmedPage() {
1503 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1504 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1505 $wgOut->setArticleRelated( false );
1507 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1508 $wgOut->returnToMain( false );
1512 * Creates a basic error page which informs the user that
1513 * they have attempted to edit a nonexistant section.
1515 function noSuchSectionPage() {
1518 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1519 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1520 $wgOut->setArticleRelated( false );
1522 $wgOut->addWikiText( wfMsg( 'nosuchsectiontext', $this->section
) );
1523 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1527 * Produce the stock "your edit contains spam" page
1529 * @param $match Text which triggered one or more filters
1531 function spamPage( $match = false ) {
1534 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1535 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1536 $wgOut->setArticleRelated( false );
1538 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1540 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1542 $wgOut->returnToMain( false );
1549 function mergeChangesInto( &$editText ){
1550 $fname = 'EditPage::mergeChangesInto';
1551 wfProfileIn( $fname );
1553 $db = wfGetDB( DB_MASTER
);
1555 // This is the revision the editor started from
1556 $baseRevision = Revision
::loadFromTimestamp(
1557 $db, $this->mArticle
->mTitle
, $this->edittime
);
1558 if( is_null( $baseRevision ) ) {
1559 wfProfileOut( $fname );
1562 $baseText = $baseRevision->getText();
1564 // The current state, we want to merge updates into it
1565 $currentRevision = Revision
::loadFromTitle(
1566 $db, $this->mArticle
->mTitle
);
1567 if( is_null( $currentRevision ) ) {
1568 wfProfileOut( $fname );
1571 $currentText = $currentRevision->getText();
1574 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1575 $editText = $result;
1576 wfProfileOut( $fname );
1579 wfProfileOut( $fname );
1585 * Check if the browser is on a blacklist of user-agents known to
1586 * mangle UTF-8 data on form submission. Returns true if Unicode
1587 * should make it through, false if it's known to be a problem.
1591 function checkUnicodeCompliantBrowser() {
1592 global $wgBrowserBlackList;
1593 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1594 // No User-Agent header sent? Trust it by default...
1597 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1598 foreach ( $wgBrowserBlackList as $browser ) {
1599 if ( preg_match($browser, $currentbrowser) ) {
1607 * Format an anchor fragment as it would appear for a given section name
1608 * @param string $text
1612 function sectionAnchor( $text ) {
1613 $headline = Sanitizer
::decodeCharReferences( $text );
1615 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1616 $headline = trim( $headline );
1617 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1618 $replacearray = array(
1623 array_keys( $replacearray ),
1624 array_values( $replacearray ),
1629 * Shows a bulletin board style toolbar for common editing functions.
1630 * It can be disabled in the user preferences.
1631 * The necessary JavaScript code can be found in style/wikibits.js.
1633 function getEditToolbar() {
1634 global $wgStylePath, $wgContLang, $wgJsMimeType;
1637 * toolarray an array of arrays which each include the filename of
1638 * the button image (without path), the opening tag, the closing tag,
1639 * and optionally a sample text that is inserted between the two when no
1640 * selection is highlighted.
1641 * The tip text is shown when the user moves the mouse over the button.
1643 * Already here are accesskeys (key), which are not used yet until someone
1644 * can figure out a way to make them work in IE. However, we should make
1645 * sure these keys are not defined on the edit page.
1648 array( 'image' => 'button_bold.png',
1649 'id' => 'mw-editbutton-bold',
1650 'open' => '\\\'\\\'\\\'',
1651 'close' => '\\\'\\\'\\\'',
1652 'sample'=> wfMsg('bold_sample'),
1653 'tip' => wfMsg('bold_tip'),
1656 array( 'image' => 'button_italic.png',
1657 'id' => 'mw-editbutton-italic',
1658 'open' => '\\\'\\\'',
1659 'close' => '\\\'\\\'',
1660 'sample'=> wfMsg('italic_sample'),
1661 'tip' => wfMsg('italic_tip'),
1664 array( 'image' => 'button_link.png',
1665 'id' => 'mw-editbutton-link',
1668 'sample'=> wfMsg('link_sample'),
1669 'tip' => wfMsg('link_tip'),
1672 array( 'image' => 'button_extlink.png',
1673 'id' => 'mw-editbutton-extlink',
1676 'sample'=> wfMsg('extlink_sample'),
1677 'tip' => wfMsg('extlink_tip'),
1680 array( 'image' => 'button_headline.png',
1681 'id' => 'mw-editbutton-headline',
1683 'close' => " ==\\n",
1684 'sample'=> wfMsg('headline_sample'),
1685 'tip' => wfMsg('headline_tip'),
1688 array( 'image' => 'button_image.png',
1689 'id' => 'mw-editbutton-image',
1690 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1692 'sample'=> wfMsg('image_sample'),
1693 'tip' => wfMsg('image_tip'),
1696 array( 'image' => 'button_media.png',
1697 'id' => 'mw-editbutton-media',
1698 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1700 'sample'=> wfMsg('media_sample'),
1701 'tip' => wfMsg('media_tip'),
1704 array( 'image' => 'button_math.png',
1705 'id' => 'mw-editbutton-math',
1707 'close' => "<\\/math>",
1708 'sample'=> wfMsg('math_sample'),
1709 'tip' => wfMsg('math_tip'),
1712 array( 'image' => 'button_nowiki.png',
1713 'id' => 'mw-editbutton-nowiki',
1714 'open' => "<nowiki>",
1715 'close' => "<\\/nowiki>",
1716 'sample'=> wfMsg('nowiki_sample'),
1717 'tip' => wfMsg('nowiki_tip'),
1720 array( 'image' => 'button_sig.png',
1721 'id' => 'mw-editbutton-signature',
1725 'tip' => wfMsg('sig_tip'),
1728 array( 'image' => 'button_hr.png',
1729 'id' => 'mw-editbutton-hr',
1730 'open' => "\\n----\\n",
1733 'tip' => wfMsg('hr_tip'),
1737 $toolbar = "<div id='toolbar'>\n";
1738 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1740 foreach($toolarray as $tool) {
1742 $cssId = $tool['id'];
1743 $image=$wgStylePath.'/common/images/'.$tool['image'];
1744 $open=$tool['open'];
1745 $close=$tool['close'];
1746 $sample = wfEscapeJsString( $tool['sample'] );
1748 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1749 // Older browsers show a "speedtip" type message only for ALT.
1750 // Ideally these should be different, realistically they
1751 // probably don't need to be.
1752 $tip = wfEscapeJsString( $tool['tip'] );
1754 #$key = $tool["key"];
1756 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1759 $toolbar.="/*]]>*/\n</script>";
1760 $toolbar.="\n</div>";
1765 * Returns an array of html code of the following checkboxes:
1768 * @param $tabindex Current tabindex
1769 * @param $skin Skin object
1770 * @param $checked Array of checkbox => bool, where bool indicates the checked
1771 * status of the checkbox
1775 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1778 $checkboxes = array();
1780 $checkboxes['minor'] = '';
1781 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1782 if ( $wgUser->isAllowed('minoredit') ) {
1784 'tabindex' => ++
$tabindex,
1785 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1786 'id' => 'wpMinoredit',
1788 $checkboxes['minor'] =
1789 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1790 " <label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1793 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1794 $checkboxes['watch'] = '';
1795 if ( $wgUser->isLoggedIn() ) {
1797 'tabindex' => ++
$tabindex,
1798 'accesskey' => wfMsg( 'accesskey-watch' ),
1799 'id' => 'wpWatchthis',
1801 $checkboxes['watch'] =
1802 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1803 " <label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1809 * Returns an array of html code of the following buttons:
1810 * save, diff, preview and live
1812 * @param $tabindex Current tabindex
1816 public function getEditButtons(&$tabindex) {
1817 global $wgLivePreview, $wgUser;
1825 'tabindex' => ++
$tabindex,
1826 'value' => wfMsg('savearticle'),
1827 'accesskey' => wfMsg('accesskey-save'),
1828 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1830 $buttons['save'] = wfElement('input', $temp, '');
1832 ++
$tabindex; // use the same for preview and live preview
1833 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1835 'id' => 'wpPreview',
1836 'name' => 'wpPreview',
1838 'tabindex' => $tabindex,
1839 'value' => wfMsg('showpreview'),
1841 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1842 'style' => 'display: none;',
1844 $buttons['preview'] = wfElement('input', $temp, '');
1847 'id' => 'wpLivePreview',
1848 'name' => 'wpLivePreview',
1850 'tabindex' => $tabindex,
1851 'value' => wfMsg('showlivepreview'),
1852 'accesskey' => wfMsg('accesskey-preview'),
1854 'onclick' => $this->doLivePreviewScript(),
1856 $buttons['live'] = wfElement('input', $temp, '');
1859 'id' => 'wpPreview',
1860 'name' => 'wpPreview',
1862 'tabindex' => $tabindex,
1863 'value' => wfMsg('showpreview'),
1864 'accesskey' => wfMsg('accesskey-preview'),
1865 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1867 $buttons['preview'] = wfElement('input', $temp, '');
1868 $buttons['live'] = '';
1875 'tabindex' => ++
$tabindex,
1876 'value' => wfMsg('showdiff'),
1877 'accesskey' => wfMsg('accesskey-diff'),
1878 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1880 $buttons['diff'] = wfElement('input', $temp, '');
1886 * Output preview text only. This can be sucked into the edit page
1887 * via JavaScript, and saves the server time rendering the skin as
1888 * well as theoretically being more robust on the client (doesn't
1889 * disturb the edit box's undo history, won't eat your text on
1892 * @todo This doesn't include category or interlanguage links.
1893 * Would need to enhance it a bit, <s>maybe wrap them in XML
1894 * or something...</s> that might also require more skin
1895 * initialization, so check whether that's a problem.
1897 function livePreview() {
1900 header( 'Content-type: text/xml; charset=utf-8' );
1901 header( 'Cache-control: no-cache' );
1904 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1905 Xml
::openElement( 'livepreview' ) .
1906 Xml
::element( 'preview', null, $this->getPreviewText() ) .
1907 Xml
::element( 'br', array( 'style' => 'clear: both;' ) ) .
1908 Xml
::closeElement( 'livepreview' );
1914 * Get a diff between the current contents of the edit box and the
1915 * version of the page we're editing from.
1917 * If this is a section edit, we'll replace the section as for final
1918 * save and then make a comparison.
1920 function showDiff() {
1921 $oldtext = $this->mArticle
->fetchContent();
1922 $newtext = $this->mArticle
->replaceSection(
1923 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1924 $newtext = $this->mArticle
->preSaveTransform( $newtext );
1925 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1926 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1927 if ( $oldtext !== false ||
$newtext != '' ) {
1928 $de = new DifferenceEngine( $this->mTitle
);
1929 $de->setText( $oldtext, $newtext );
1930 $difftext = $de->getDiff( $oldtitle, $newtitle );
1931 $de->showDiffStyle();
1937 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
1941 * Filter an input field through a Unicode de-armoring process if it
1942 * came from an old browser with known broken Unicode editing issues.
1944 * @param WebRequest $request
1945 * @param string $field
1949 function safeUnicodeInput( $request, $field ) {
1950 $text = rtrim( $request->getText( $field ) );
1951 return $request->getBool( 'safemode' )
1952 ?
$this->unmakesafe( $text )
1957 * Filter an output field through a Unicode armoring process if it is
1958 * going to an old browser with known broken Unicode editing issues.
1960 * @param string $text
1964 function safeUnicodeOutput( $text ) {
1966 $codedText = $wgContLang->recodeForEdit( $text );
1967 return $this->checkUnicodeCompliantBrowser()
1969 : $this->makesafe( $codedText );
1973 * A number of web browsers are known to corrupt non-ASCII characters
1974 * in a UTF-8 text editing environment. To protect against this,
1975 * detected browsers will be served an armored version of the text,
1976 * with non-ASCII chars converted to numeric HTML character references.
1978 * Preexisting such character references will have a 0 added to them
1979 * to ensure that round-trips do not alter the original data.
1981 * @param string $invalue
1985 function makesafe( $invalue ) {
1986 // Armor existing references for reversability.
1987 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1992 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1993 $bytevalue = ord( $invalue{$i} );
1994 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1995 $result .= chr( $bytevalue );
1997 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1998 $working = $working << 6;
1999 $working +
= ($bytevalue & 0x3F);
2001 if( $bytesleft <= 0 ) {
2002 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2004 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
2005 $working = $bytevalue & 0x1F;
2007 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
2008 $working = $bytevalue & 0x0F;
2010 } else { //1111 0xxx
2011 $working = $bytevalue & 0x07;
2019 * Reverse the previously applied transliteration of non-ASCII characters
2020 * back to UTF-8. Used to protect data from corruption by broken web browsers
2021 * as listed in $wgBrowserBlackList.
2023 * @param string $invalue
2027 function unmakesafe( $invalue ) {
2029 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2030 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2034 $hexstring .= $invalue{$i};
2036 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2038 // Do some sanity checks. These aren't needed for reversability,
2039 // but should help keep the breakage down if the editor
2040 // breaks one of the entities whilst editing.
2041 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2042 $codepoint = hexdec($hexstring);
2043 $result .= codepointToUtf8( $codepoint );
2045 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2048 $result .= substr( $invalue, $i, 1 );
2051 // reverse the transform that we made for reversability reasons.
2052 return strtr( $result, array( "�" => "&#x" ) );
2055 function noCreatePermission() {
2057 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2058 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
2062 * If there are rows in the deletion log for this page, show them,
2063 * along with a nice little note for the user
2065 * @param OutputPage $out
2067 private function showDeletionLog( $out ) {
2068 $title = $this->mArticle
->getTitle();
2069 $reader = new LogReader(
2072 'page' => $title->getPrefixedText(),
2077 if( $reader->hasRows() ) {
2078 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2079 $out->addWikiText( wfMsg( 'recreate-deleted-warn' ) );
2080 $viewer = new LogViewer( $reader );
2081 $viewer->showList( $out );
2082 $out->addHtml( '</div>' );