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 $editFormTextBeforeContent;
46 public $editFormTextAfterWarn;
47 public $editFormTextAfterTools;
48 public $editFormTextBottom;
50 public $didSave = false;
51 public $suppressIntro = false;
57 function EditPage( $article ) {
58 $this->mArticle
=& $article;
60 $this->mTitle
=& $wgTitle;
62 # Placeholders for text injection by hooks (empty per default)
63 $this->editFormPageTop
=
64 $this->editFormTextTop
=
65 $this->editFormTextBeforeContent
=
66 $this->editFormTextAfterWarn
=
67 $this->editFormTextAfterTools
=
68 $this->editFormTextBottom
= "";
72 * Fetch initial editing page content.
74 private function getContent( $def_text = '' ) {
75 global $wgOut, $wgRequest, $wgParser;
77 # Get variables from query string :P
78 $section = $wgRequest->getVal( 'section' );
79 $preload = $wgRequest->getVal( 'preload' );
80 $undoafter = $wgRequest->getVal( 'undoafter' );
81 $undo = $wgRequest->getVal( 'undo' );
83 wfProfileIn( __METHOD__
);
86 if( !$this->mArticle
->getTitle()->exists() ) {
87 if ( $this->mArticle
->getTitle()->getNamespace() == NS_MEDIAWIKI
) {
88 # If this is a system message, get the default text.
89 $text = wfMsgWeirdKey ( $this->mArticle
->getTitle()->getText() ) ;
91 # If requested, preload some text.
92 $text = $this->getPreloadedText( $preload );
94 # We used to put MediaWiki:Newarticletext here if
95 # $text was empty at this point.
96 # This is now shown above the edit box instead.
98 // FIXME: may be better to use Revision class directly
99 // But don't mess with it just yet. Article knows how to
100 // fetch the page record from the high-priority server,
101 // which is needed to guarantee we don't pick up lagged
104 $text = $this->mArticle
->getContent();
106 if ($undo > 0 && $undoafter > 0 && $undo < $undoafter) {
107 # If they got undoafter and undo round the wrong way, switch them
108 list( $undo, $undoafter ) = array( $undoafter, $undo );
111 if ( $undo > 0 && $undo > $undoafter ) {
112 # Undoing a specific edit overrides section editing; section-editing
113 # doesn't work with undoing.
115 $undorev = Revision
::newFromId($undo);
116 $oldrev = Revision
::newFromId($undoafter);
118 $undorev = Revision
::newFromId($undo);
119 $oldrev = $undorev ?
$undorev->getPrevious() : null;
122 #Sanity check, make sure it's the right page.
123 # Otherwise, $text will be left as-is.
124 if ( !is_null($undorev) && !is_null($oldrev) && $undorev->getPage()==$oldrev->getPage() && $undorev->getPage()==$this->mArticle
->getID() ) {
125 $undorev_text = $undorev->getText();
126 $oldrev_text = $oldrev->getText();
127 $currev_text = $text;
129 #No use doing a merge if it's just a straight revert.
130 if ( $currev_text != $undorev_text ) {
131 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
133 $text = $oldrev_text;
137 // Failed basic sanity checks.
138 // Older revisions may have been removed since the link
139 // was created, or we may simply have got bogus input.
144 # Inform the user of our success and set an automatic edit summary
145 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
146 $firstrev = $oldrev->getNext();
147 # If we just undid one rev, use an autosummary
148 if ( $firstrev->mId
== $undo ) {
149 $this->summary
= wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
151 $this->formtype
= 'diff';
153 # Warn the user that something went wrong
154 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
156 } else if( $section != '' ) {
157 if( $section == 'new' ) {
158 $text = $this->getPreloadedText( $preload );
160 $text = $wgParser->getSection( $text, $section, $def_text );
165 wfProfileOut( __METHOD__
);
170 * Get the contents of a page from its title and remove includeonly tags
172 * @param $preload String: the title of the page.
173 * @return string The contents of the page.
175 private function getPreloadedText($preload) {
176 if ( $preload === '' )
179 $preloadTitle = Title
::newFromText( $preload );
180 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
181 $rev=Revision
::newFromTitle($preloadTitle);
182 if ( is_object( $rev ) ) {
183 $text = $rev->getText();
184 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
185 // its own mini-parser! -ævar
186 $text = preg_replace( '~</?includeonly>~', '', $text );
195 * This is the function that extracts metadata from the article body on the first view.
196 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
197 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
199 function extractMetaDataFromArticle () {
200 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
201 $this->mMetaData
= '' ;
202 if ( !$wgUseMetadataEdit ) return ;
203 if ( $wgMetadataWhitelist == '' ) return ;
205 $t = $this->getContent();
207 # MISSING : <nowiki> filtering
209 # Categories and language links
210 $t = explode ( "\n" , $t ) ;
211 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
212 $cat = $ll = array() ;
213 foreach ( $t AS $key => $x )
215 $y = trim ( strtolower ( $x ) ) ;
216 while ( substr ( $y , 0 , 2 ) == '[[' )
218 $y = explode ( ']]' , trim ( $x ) ) ;
219 $first = array_shift ( $y ) ;
220 $first = explode ( ':' , $first ) ;
221 $ns = array_shift ( $first ) ;
222 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
223 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
225 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
226 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
228 $x = implode ( ']]' , $y ) ;
230 $y = trim ( strtolower ( $x ) ) ;
234 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
235 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
236 $t = implode ( "\n" , $t ) ;
239 $sat = array () ; # stand-alone-templates; must be lowercase
240 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
241 $wl_article = new Article ( $wl_title ) ;
242 $wl = explode ( "\n" , $wl_article->getContent() ) ;
243 foreach ( $wl AS $x )
247 while ( substr ( $x , 0 , 1 ) == '*' )
250 $x = trim ( substr ( $x , 1 ) ) ;
254 $sat[] = strtolower ( $x ) ;
259 # Templates, but only some
260 $t = explode ( '{{' , $t ) ;
262 foreach ( $t AS $key => $x )
264 $y = explode ( '}}' , $x , 2 ) ;
265 if ( count ( $y ) == 2 )
268 $z = explode ( '|' , $z ) ;
269 $tn = array_shift ( $z ) ;
270 if ( in_array ( strtolower ( $tn ) , $sat ) )
272 $tl[] = '{{' . $y[0] . '}}' ;
274 $y = explode ( '}}' , $y[1] , 2 ) ;
276 else $t[$key] = '{{' . $x ;
278 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
281 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
282 $t = implode ( '' , $t ) ;
284 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
285 $this->mArticle
->mContent
= $t ;
286 $this->mMetaData
= $s ;
294 * This is the function that gets called for "action=edit". It
295 * sets up various member variables, then passes execution to
296 * another function, usually showEditForm()
298 * The edit form is self-submitting, so that when things like
299 * preview and edit conflicts occur, we get the same form back
300 * with the extra stuff added. Only when the final submission
301 * is made and all is well do we actually save and redirect to
302 * the newly-edited page.
305 global $wgOut, $wgUser, $wgRequest, $wgTitle;
307 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
310 $fname = 'EditPage::edit';
311 wfProfileIn( $fname );
312 wfDebug( "$fname: enter\n" );
314 // this is not an article
315 $wgOut->setArticleFlag(false);
317 $this->importFormData( $wgRequest );
318 $this->firsttime
= false;
321 $this->livePreview();
322 wfProfileOut( $fname );
326 $permErrors = $this->mArticle
->getTitle()->getUserPermissionsErrors('edit', $wgUser);
327 if( !$this->mArticle
->getTitle()->exists() )
328 $permErrors +
= array_diff( $this->mArticle
->getTitle()->getUserPermissionsErrors('create', $wgUser), $permErrors );
330 # Ignore some permissions errors.
332 foreach( $permErrors as $error ) {
333 if ($this->preview ||
$this->diff
&&
334 ($error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext'))
336 // Don't worry about blocks when previewing/diffing
340 if ($error[0] == 'readonlytext')
343 $this->formtype
= 'preview';
344 } elseif ($this->save ||
$this->preview ||
$this->diff
) {
349 # array_diff returns elements in $permErrors that are not in $remove.
350 $permErrors = array_diff( $permErrors, $remove );
352 if ( !empty($permErrors) )
354 wfDebug( "$fname: User can't edit\n" );
355 $wgOut->readOnlyPage( $this->getContent(), true, $permErrors );
356 wfProfileOut( $fname );
360 $this->formtype
= 'save';
361 } else if ( $this->preview
) {
362 $this->formtype
= 'preview';
363 } else if ( $this->diff
) {
364 $this->formtype
= 'diff';
365 } else { # First time through
366 $this->firsttime
= true;
367 if( $this->previewOnOpen() ) {
368 $this->formtype
= 'preview';
370 $this->extractMetaDataFromArticle () ;
371 $this->formtype
= 'initial';
376 wfProfileIn( "$fname-business-end" );
378 $this->isConflict
= false;
379 // css / js subpages of user pages get a special treatment
380 $this->isCssJsSubpage
= $this->mArticle
->getTitle()->isCssJsSubpage();
381 $this->isValidCssJsSubpage
= $this->mArticle
->getTitle()->isValidCssJsSubpage();
383 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
384 * no matter it's current state
386 $this->deletedSinceEdit
= false;
387 if ( $this->edittime
!= '' ) {
388 /* Note that we rely on logging table, which hasn't been always there,
389 * but that doesn't matter, because this only applies to brand new
390 * deletes. This is done on every preview and save request. Move it further down
391 * to only perform it on saves
393 if ( $this->mArticle
->getTitle()->isDeleted() ) {
394 $this->lastDelete
= $this->getLastDelete();
395 if ( !is_null($this->lastDelete
) ) {
396 $deletetime = $this->lastDelete
->log_timestamp
;
397 if ( ($deletetime - $this->starttime
) > 0 ) {
398 $this->deletedSinceEdit
= true;
404 # Show applicable editing introductions
405 if( $this->formtype
== 'initial' ||
$this->firsttime
)
408 if( $this->mArticle
->getTitle()->isTalkPage() ) {
409 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
412 # Attempt submission here. This will check for edit conflicts,
413 # and redundantly check for locked database, blocked IPs, etc.
414 # that edit() already checked just in case someone tries to sneak
415 # in the back door with a hand-edited submission URL.
417 if ( 'save' == $this->formtype
) {
418 if ( !$this->attemptSave() ) {
419 wfProfileOut( "$fname-business-end" );
420 wfProfileOut( $fname );
425 # First time through: get contents, set time for conflict
427 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
428 if ($this->initialiseForm() === false) {
429 $this->noSuchSectionPage();
430 wfProfileOut( "$fname-business-end" );
431 wfProfileOut( $fname );
434 if( !$this->mArticle
->getID() )
435 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mArticle
->mTitle
) );
438 $this->showEditForm();
439 wfProfileOut( "$fname-business-end" );
440 wfProfileOut( $fname );
444 * Should we show a preview when the edit form is first shown?
448 private function previewOnOpen() {
449 global $wgRequest, $wgUser;
450 $title = $this->mArticle
->getTitle();
451 if( $wgRequest->getVal( 'preview' ) == 'yes' ) {
452 // Explicit override from request
454 } elseif( $wgRequest->getVal( 'preview' ) == 'no' ) {
455 // Explicit override from request
457 } elseif( $this->section
== 'new' ) {
458 // Nothing *to* preview for new sections
460 } elseif( ( $wgRequest->getVal( 'preload' ) !== '' ||
$title->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
461 // Standard preference behaviour
463 } elseif( !$title->exists() && $title->getNamespace() == NS_CATEGORY
) {
464 // Categories are special
475 function importFormData( &$request ) {
476 global $wgLang, $wgUser;
477 $fname = 'EditPage::importFormData';
478 wfProfileIn( $fname );
480 if( $request->wasPosted() ) {
481 # These fields need to be checked for encoding.
482 # Also remove trailing whitespace, but don't remove _initial_
483 # whitespace from the text boxes. This may be significant formatting.
484 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
485 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
486 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
487 # Truncate for whole multibyte characters. +5 bytes for ellipsis
488 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
490 $this->edittime
= $request->getVal( 'wpEdittime' );
491 $this->starttime
= $request->getVal( 'wpStarttime' );
493 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
495 if( is_null( $this->edittime
) ) {
496 # If the form is incomplete, force to preview.
497 wfDebug( "$fname: Form data appears to be incomplete\n" );
498 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
499 $this->preview
= true;
501 /* Fallback for live preview */
502 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
503 $this->diff
= $request->getCheck( 'wpDiff' );
505 // Remember whether a save was requested, so we can indicate
506 // if we forced preview due to session failure.
507 $this->mTriedSave
= !$this->preview
;
509 if ( $this->tokenOk( $request ) ) {
510 # Some browsers will not report any submit button
511 # if the user hits enter in the comment box.
512 # The unmarked state will be assumed to be a save,
513 # if the form seems otherwise complete.
514 wfDebug( "$fname: Passed token check.\n" );
515 } else if ( $this->diff
) {
516 # Failed token check, but only requested "Show Changes".
517 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
519 # Page might be a hack attempt posted from
520 # an external site. Preview instead of saving.
521 wfDebug( "$fname: Failed token check; forcing preview\n" );
522 $this->preview
= true;
525 $this->save
= ! ( $this->preview
OR $this->diff
);
526 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
527 $this->edittime
= null;
530 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
531 $this->starttime
= null;
534 $this->recreate
= $request->getCheck( 'wpRecreate' );
536 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
537 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
539 # Don't force edit summaries when a user is editing their own user or talk page
540 if( ( $this->mArticle
->getTitle()->mNamespace
== NS_USER ||
$this->mArticle
->getTitle()->mNamespace
== NS_USER_TALK
) && $this->mArticle
->getTitle()->getText() == $wgUser->getName() ) {
541 $this->allowBlankSummary
= true;
543 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
546 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
548 # Not a posted form? Start with nothing.
549 wfDebug( "$fname: Not a posted form.\n" );
550 $this->textbox1
= '';
551 $this->textbox2
= '';
552 $this->mMetaData
= '';
554 $this->edittime
= '';
555 $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->suppressIntro
) return;
597 if( !$this->showCustomIntro() && !$this->mArticle
->getTitle()->exists() ) {
598 if( $wgUser->isLoggedIn() ) {
599 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
601 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
603 $this->showDeletionLog( $wgOut );
608 * Attempt to show a custom editing introduction, if supplied
612 private function showCustomIntro() {
613 if( $this->editintro
) {
614 $title = Title
::newFromText( $this->editintro
);
615 if( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
617 $revision = Revision
::newFromTitle( $title );
618 $wgOut->addSecondaryWikiText( $revision->getText() );
630 * @return bool false if output is done, true if the rest of the form should be displayed
632 function attemptSave() {
633 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut, $wgParser;
634 global $wgMaxArticleSize;
636 $fname = 'EditPage::attemptSave';
637 wfProfileIn( $fname );
638 wfProfileIn( "$fname-checks" );
640 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
642 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
646 # Reintegrate metadata
647 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
648 $this->mMetaData
= '' ;
652 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
653 $this->spamPage ( $matches[0] );
654 wfProfileOut( "$fname-checks" );
655 wfProfileOut( $fname );
658 if ( $wgFilterCallback && $wgFilterCallback( $this->mArticle
->getTitle(), $this->textbox1
, $this->section
) ) {
659 # Error messages or other handling should be performed by the filter function
660 wfProfileOut( $fname );
661 wfProfileOut( "$fname-checks" );
664 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
) ) ) {
665 # Error messages etc. could be handled within the hook...
666 wfProfileOut( $fname );
667 wfProfileOut( "$fname-checks" );
669 } elseif( $this->hookError
!= '' ) {
670 # ...or the hook could be expecting us to produce an error
671 wfProfileOut( "$fname-checks " );
672 wfProfileOut( $fname );
675 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
676 # Check block state against master, thus 'false'.
677 $this->blockedPage();
678 wfProfileOut( "$fname-checks" );
679 wfProfileOut( $fname );
682 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
683 if ( $this->kblength
> $wgMaxArticleSize ) {
684 // Error will be displayed by showEditForm()
685 $this->tooBig
= true;
686 wfProfileOut( "$fname-checks" );
687 wfProfileOut( $fname );
691 if ( !$wgUser->isAllowed('edit') ) {
692 if ( $wgUser->isAnon() ) {
693 $this->userNotLoggedInPage();
694 wfProfileOut( "$fname-checks" );
695 wfProfileOut( $fname );
699 $wgOut->readOnlyPage();
700 wfProfileOut( "$fname-checks" );
701 wfProfileOut( $fname );
706 if ( wfReadOnly() ) {
707 $wgOut->readOnlyPage();
708 wfProfileOut( "$fname-checks" );
709 wfProfileOut( $fname );
712 if ( $wgUser->pingLimiter() ) {
713 $wgOut->rateLimited();
714 wfProfileOut( "$fname-checks" );
715 wfProfileOut( $fname );
719 # If the article has been deleted while editing, don't save it without
721 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
722 wfProfileOut( "$fname-checks" );
723 wfProfileOut( $fname );
727 wfProfileOut( "$fname-checks" );
729 # If article is new, insert it.
730 $aid = $this->mArticle
->getTitle()->getArticleID( GAID_FOR_UPDATE
);
733 // Late check for create permission, just in case *PARANOIA*
734 if ( !$this->mArticle
->getTitle()->userCan( 'create' ) ) {
735 wfDebug( "$fname: no create permission\n" );
736 $this->noCreatePermission();
737 wfProfileOut( $fname );
741 # Don't save a new article if it's blank.
742 if ( ( '' == $this->textbox1
) ) {
743 $wgOut->redirect( $this->mTitle
->getFullURL() );
744 wfProfileOut( $fname );
748 $isComment=($this->section
=='new');
749 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
750 $this->minoredit
, $this->watchthis
, false, $isComment);
751 $this->didSave
= true;
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( "EditPage::editForm 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( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
811 $this->textbox1
= $text;
812 wfDebug( "EditPage::editForm 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 = $wgParser->guessSectionNameFromWikiText( $this->summary
);
853 # This is a new section, so create a link to the new section
854 # in the revision summary.
855 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
856 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
858 } elseif( $this->section
!= '' ) {
859 # Try to get a section anchor from the section source, redirect to edited section if header found
860 # XXX: might be better to integrate this into Article::replaceSection
861 # for duplicate heading checking and maybe parsing
862 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
863 # we can't deal with anchors, includes, html etc in the header for now,
864 # headline would need to be parsed to improve this
865 if($hasmatch and strlen($matches[2]) > 0) {
866 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
869 wfProfileOut( "$fname-sectionanchor" );
871 // Save errors may fall down to the edit form, but we've now
872 // merged the section into full text. Clear the section field
873 // so that later submission of conflict forms won't try to
874 // replace that into a duplicated mess.
875 $this->textbox1
= $text;
878 // Check for length errors again now that the section is merged in
879 $this->kblength
= (int)(strlen( $text ) / 1024);
880 if ( $this->kblength
> $wgMaxArticleSize ) {
881 $this->tooBig
= true;
882 wfProfileOut( $fname );
886 # update the article here
887 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
888 $this->watchthis
, '', $sectionanchor ) ) {
889 $this->didSave
= true;
890 wfProfileOut( $fname );
893 $this->isConflict
= true;
895 wfProfileOut( $fname );
900 * Initialise form fields in the object
901 * Called on the first invocation, e.g. when a user clicks an edit link
903 function initialiseForm() {
904 $this->edittime
= $this->mArticle
->getTimestamp();
906 $this->textbox1
= $this->getContent(false);
907 if ($this->textbox1
=== false) return false;
909 if ( !$this->mArticle
->exists() && $this->mArticle
->getTitle()->getNamespace() == NS_MEDIAWIKI
)
910 $this->textbox1
= wfMsgWeirdKey( $this->mArticle
->getTitle()->getText() );
916 * Send the edit form and related headers to $wgOut
917 * @param $formCallback Optional callable that takes an OutputPage
918 * parameter; will be called during form output
919 * near the top, for captchas and the like.
921 function showEditForm( $formCallback=null ) {
922 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
924 $fname = 'EditPage::showEditForm';
925 wfProfileIn( $fname );
927 $sk = $wgUser->getSkin();
929 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
931 $wgOut->setRobotpolicy( 'noindex,nofollow' );
933 # Enabled article-related sidebar, toplinks, etc.
934 $wgOut->setArticleRelated( true );
936 if ( $this->formtype
== 'preview' ) {
937 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
940 if ( $this->isConflict
) {
941 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
942 $wgOut->setPageTitle( $s );
943 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
945 $this->textbox2
= $this->textbox1
;
946 $this->textbox1
= $this->getContent();
947 $this->edittime
= $this->mArticle
->getTimestamp();
950 if( $this->section
!= '' ) {
951 if( $this->section
== 'new' ) {
952 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
954 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
956 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
957 preg_match( "/^(=+)(.+)\\1/mi",
960 if( !empty( $matches[2] ) ) {
962 $this->summary
= "/* " .
963 $wgParser->stripSectionName(trim($matches[2])) .
969 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
971 $wgOut->setPageTitle( $s );
973 if ( $this->missingComment
) {
974 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
977 if( $this->missingSummary
&& $this->section
!= 'new' ) {
978 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
981 if( $this->missingSummary
&& $this->section
== 'new' ) {
982 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
985 if( !$this->hookError
== '' ) {
986 $wgOut->addWikiText( $this->hookError
);
989 if ( !$this->checkUnicodeCompliantBrowser() ) {
990 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
992 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
993 // Let sysop know that this will make private content public if saved
994 if( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
995 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
997 if( !$this->mArticle
->mRevision
->isCurrent() ) {
998 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
999 $wgOut->addWikiText( wfMsg( 'editingold' ) );
1004 if( wfReadOnly() ) {
1005 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
1006 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
1007 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
1009 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
1010 # Check the skin exists
1011 if( $this->isValidCssJsSubpage
) {
1012 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
1014 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
1019 if( $this->mArticle
->getTitle()->getNamespace() == NS_MEDIAWIKI
) {
1020 # Show a warning if editing an interface message
1021 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
1022 } elseif( $this->mArticle
->getTitle()->isProtected( 'edit' ) ) {
1023 # Is the title semi-protected?
1024 if( $this->mArticle
->getTitle()->isSemiProtected() ) {
1025 $notice = wfMsg( 'semiprotectedpagewarning' );
1026 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' )
1029 # Then it must be protected based on static groups (regular)
1030 $notice = wfMsg( 'protectedpagewarning' );
1032 $wgOut->addWikiText( $notice );
1034 if ( $this->mArticle
->getTitle()->isCascadeProtected() ) {
1035 # Is this page under cascading protection from some source pages?
1036 list($cascadeSources, /* $restrictions */) = $this->mArticle
->getTitle()->getCascadeProtectionSources();
1037 if ( count($cascadeSources) > 0 ) {
1038 # Explain, and list the titles responsible
1039 $notice = wfMsgExt( 'cascadeprotectedwarning', array('parsemag'), count($cascadeSources) ) . "\n";
1040 foreach( $cascadeSources as $page ) {
1041 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1044 $wgOut->addWikiText( $notice );
1047 if ( $this->kblength
=== false ) {
1048 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1050 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1051 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgMaxArticleSize ) );
1052 } elseif( $this->kblength
> 29 ) {
1053 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) ) );
1056 #need to parse the preview early so that we know which templates are used,
1057 #otherwise users with "show preview after edit box" will get a blank list
1058 if ( $this->formtype
== 'preview' ) {
1059 $previewOutput = $this->getPreviewText();
1062 $rows = $wgUser->getIntOption( 'rows' );
1063 $cols = $wgUser->getIntOption( 'cols' );
1065 $ew = $wgUser->getOption( 'editwidth' );
1066 if ( $ew ) $ew = " style=\"width:100%\"";
1069 $q = 'action=submit';
1070 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1071 $action = $this->mTitle
->escapeLocalURL( $q );
1073 $summary = wfMsg('summary');
1074 $subject = wfMsg('subject');
1076 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
1077 wfMsgExt('cancel', array('parseinline')) );
1078 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1079 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1080 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1081 htmlspecialchars( wfMsg( 'newwindow' ) );
1083 global $wgRightsText;
1084 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1085 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
1086 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1087 $wgRightsText ) . "\n</div>";
1089 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1090 # prepare toolbar for edit buttons
1091 $toolbar = $this->getEditToolbar();
1096 // activate checkboxes if user wants them to be always active
1097 if( !$this->preview
&& !$this->diff
) {
1098 # Sort out the "watch" checkbox
1099 if( $wgUser->getOption( 'watchdefault' ) ) {
1101 $this->watchthis
= true;
1102 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mArticle
->getTitle()->exists() ) {
1104 $this->watchthis
= true;
1105 } elseif( $this->mArticle
->getTitle()->userIsWatching() ) {
1107 $this->watchthis
= true;
1110 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1113 $wgOut->addHTML( $this->editFormPageTop
);
1115 if ( $wgUser->getOption( 'previewontop' ) ) {
1117 if ( 'preview' == $this->formtype
) {
1118 $this->showPreview( $previewOutput );
1120 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1123 if ( 'diff' == $this->formtype
) {
1129 $wgOut->addHTML( $this->editFormTextTop
);
1131 # if this is a comment, show a subject line at the top, which is also the edit summary.
1132 # Otherwise, show a summary field at the bottom
1133 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1134 if( $this->section
== 'new' ) {
1135 $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 />";
1137 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary
, $this->mArticle
->getTitle() )."</div>\n" : '';
1138 $summarypreview = '';
1140 $commentsubject = '';
1141 $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 />";
1142 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary
, $this->mArticle
->getTitle() )."</div>\n" : '';
1143 $subjectpreview = '';
1146 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1147 if( !$this->preview
&& !$this->diff
) {
1148 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1150 $templates = ($this->preview ||
$this->section
!= '') ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1151 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1153 global $wgUseMetadataEdit ;
1154 if ( $wgUseMetadataEdit ) {
1155 $metadata = $this->mMetaData
;
1156 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1157 $top = wfMsgWikiHtml( 'metadata_help' );
1158 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1160 else $metadata = "" ;
1164 if ($this->deletedSinceEdit
) {
1165 if ( 'save' != $this->formtype
) {
1166 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1168 // Hide the toolbar and edit area, use can click preview to get it back
1169 // Add an confirmation checkbox and explanation.
1171 $hidden = 'type="hidden" style="display:none;"';
1172 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1174 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1175 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1181 $checkboxes = self
::getCheckboxes( $tabindex, $sk,
1182 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1184 $checkboxhtml = implode( $checkboxes, "\n" );
1186 $buttons = $this->getEditButtons( $tabindex );
1187 $buttonshtml = implode( $buttons, "\n" );
1189 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1190 ?
'' : Xml
::hidden( 'safemode', '1' );
1192 $wgOut->addHTML( <<<END
1194 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1198 if( is_callable( $formCallback ) ) {
1199 call_user_func_array( $formCallback, array( &$wgOut ) );
1202 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1204 // Put these up at the top to ensure they aren't lost on early form submission
1206 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1207 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1208 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1209 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1211 $wgOut->addHTML( <<<END
1215 {$this->editFormTextBeforeContent}
1216 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1217 cols='{$cols}'{$ew} $hidden>
1219 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
1224 $wgOut->addWikiText( $copywarn );
1225 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1235 "<div class='editButtons'>
1237 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1238 </div><!-- editButtons -->
1239 </div><!-- editOptions -->");
1241 $wgOut->addHtml( '<div class="mw-editTools">' );
1242 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1243 $wgOut->addHtml( '</div>' );
1245 $wgOut->addHTML( $this->editFormTextAfterTools
);
1248 <div class='templatesUsed'>
1249 {$formattedtemplates}
1254 * To make it harder for someone to slip a user a page
1255 * which submits an edit form to the wiki without their
1256 * knowledge, a random token is associated with the login
1257 * session. If it's not passed back with the submission,
1258 * we won't save the page, or render user JavaScript and
1261 * For anon editors, who may not have a session, we just
1262 * include the constant suffix to prevent editing from
1263 * broken text-mangling proxies.
1265 $token = htmlspecialchars( $wgUser->editToken() );
1266 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1269 # If a blank edit summary was previously provided, and the appropriate
1270 # user preference is active, pass a hidden tag here. This will stop the
1271 # user being bounced back more than once in the event that a summary
1273 if( $this->missingSummary
) {
1274 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1277 # For a bit more sophisticated detection of blank summaries, hash the
1278 # automatic one and pass that in a hidden field.
1279 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1280 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1282 if ( $this->isConflict
) {
1283 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1285 $de = new DifferenceEngine( $this->mArticle
->getTitle() );
1286 $de->setText( $this->textbox2
, $this->textbox1
);
1287 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1289 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1290 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1291 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1293 $wgOut->addHTML( $this->editFormTextBottom
);
1294 $wgOut->addHTML( "</form>\n" );
1295 if ( !$wgUser->getOption( 'previewontop' ) ) {
1297 if ( $this->formtype
== 'preview') {
1298 $this->showPreview( $previewOutput );
1300 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1303 if ( $this->formtype
== 'diff') {
1309 wfProfileOut( $fname );
1313 * Append preview output to $wgOut.
1314 * Includes category rendering if this is a category page.
1316 * @param string $text The HTML to be output for the preview.
1318 private function showPreview( $text ) {
1321 $wgOut->addHTML( '<div id="wikiPreview">' );
1322 if($this->mArticle
->getTitle()->getNamespace() == NS_CATEGORY
) {
1323 $this->mArticle
->openShowCategory();
1325 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1326 $wgOut->addHTML( $text );
1327 if($this->mArticle
->getTitle()->getNamespace() == NS_CATEGORY
) {
1328 $this->mArticle
->closeShowCategory();
1330 $wgOut->addHTML( '</div>' );
1334 * Live Preview lets us fetch rendered preview page content and
1335 * add it to the page without refreshing the whole page.
1336 * If not supported by the browser it will fall through to the normal form
1337 * submission method.
1339 * This function outputs a script tag to support live preview, and
1340 * returns an onclick handler which should be added to the attributes
1341 * of the preview button
1343 function doLivePreviewScript() {
1344 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1345 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1346 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1347 '"></script>' . "\n" );
1348 $liveAction = $this->mTitle
->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1349 return "return !lpDoPreview(" .
1350 "editform.wpTextbox1.value," .
1351 '"' . $liveAction . '"' . ")";
1354 function getLastDelete() {
1355 $dbr = wfGetDB( DB_SLAVE
);
1356 $fname = 'EditPage::getLastDelete';
1357 $res = $dbr->select(
1358 array( 'logging', 'user' ),
1368 array( 'log_namespace' => $this->mArticle
->getTitle()->getNamespace(),
1369 'log_title' => $this->mArticle
->getTitle()->getDBkey(),
1370 'log_type' => 'delete',
1371 'log_action' => 'delete',
1372 'user_id=log_user' ),
1374 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1376 if($dbr->numRows($res) == 1) {
1377 while ( $x = $dbr->fetchObject ( $res ) )
1379 $dbr->freeResult ( $res ) ;
1389 function getPreviewText() {
1390 global $wgOut, $wgUser, $wgTitle, $wgParser;
1392 $fname = 'EditPage::getPreviewText';
1393 wfProfileIn( $fname );
1395 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1396 if ( $this->mTokenOkExceptSuffix
) {
1397 $msg = 'token_suffix_mismatch';
1399 $msg = 'session_fail_preview';
1402 $msg = 'previewnote';
1404 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1405 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1406 if ( $this->isConflict
) {
1407 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1410 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1411 $parserOptions->setEditSection( false );
1414 if( $wgRawHtml && !$this->mTokenOk
) {
1415 // Could be an offsite preview attempt. This is very unsafe if
1416 // HTML is enabled, as it could be an attack.
1417 return $wgOut->parse( "<div class='previewnote'>" .
1418 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1421 # don't parse user css/js, show message about preview
1422 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1424 if ( $this->isCssJsSubpage
) {
1425 if(preg_match("/\\.css$/", $this->mArticle
->getTitle()->getText() ) ) {
1426 $previewtext = wfMsg('usercsspreview');
1427 } else if(preg_match("/\\.js$/", $this->mArticle
->getTitle()->getText() ) ) {
1428 $previewtext = wfMsg('userjspreview');
1430 $parserOptions->setTidy(true);
1431 $parserOutput = $wgParser->parse( $previewtext , $this->mArticle
->getTitle(), $parserOptions );
1432 $wgOut->addHTML( $parserOutput->mText
);
1433 wfProfileOut( $fname );
1434 return $previewhead;
1436 $toparse = $this->textbox1
;
1438 # If we're adding a comment, we need to show the
1439 # summary as the headline
1440 if($this->section
=="new" && $this->summary
!="") {
1441 $toparse="== {$this->summary} ==\n\n".$toparse;
1444 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1445 $parserOptions->setTidy(true);
1446 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1447 $this->mArticle
->getTitle(), $parserOptions );
1449 $previewHTML = $parserOutput->getText();
1450 $wgOut->addParserOutputNoText( $parserOutput );
1452 # ParserOutput might have altered the page title, so reset it
1453 $wgOut->setPageTitle( wfMsg( 'editing', $this->mTitle
->getPrefixedText() ) );
1455 foreach ( $parserOutput->getTemplates() as $ns => $template)
1456 foreach ( array_keys( $template ) as $dbk)
1457 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1459 wfProfileOut( $fname );
1460 return $previewhead . $previewHTML;
1465 * Call the stock "user is blocked" page
1467 function blockedPage() {
1468 global $wgOut, $wgUser;
1469 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1471 # If the user made changes, preserve them when showing the markup
1472 # (This happens when a user is blocked during edit, for instance)
1473 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1475 $source = $this->mArticle
->getTitle()->exists() ?
$this->getContent() : false;
1477 $source = $this->textbox1
;
1480 # Spit out the source or the user's modified version
1481 if( $source !== false ) {
1482 $rows = $wgUser->getOption( 'rows' );
1483 $cols = $wgUser->getOption( 'cols' );
1484 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1485 $wgOut->addHtml( '<hr />' );
1486 $wgOut->addWikiText( wfMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mArticle
->getTitle()->getPrefixedText() ) );
1487 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1492 * Produce the stock "please login to edit pages" page
1494 function userNotLoggedInPage() {
1495 global $wgUser, $wgOut;
1496 $skin = $wgUser->getSkin();
1498 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1499 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle
->getPrefixedUrl() );
1501 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1502 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1503 $wgOut->setArticleRelated( false );
1505 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1506 $wgOut->returnToMain( false, $this->mTitle
);
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
);
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, $this->mTitle
);
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
->getTitle(), $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
->getTitle() );
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 * @deprecated use $wgParser->stripSectionName()
1607 function pseudoParseSectionAnchor( $text ) {
1609 return $wgParser->stripSectionName( $text );
1613 * Format an anchor fragment as it would appear for a given section name
1614 * @param string $text
1618 function sectionAnchor( $text ) {
1620 return $wgParser->guessSectionNameFromWikiText( $text );
1624 * Shows a bulletin board style toolbar for common editing functions.
1625 * It can be disabled in the user preferences.
1626 * The necessary JavaScript code can be found in style/wikibits.js.
1628 function getEditToolbar() {
1629 global $wgStylePath, $wgContLang, $wgJsMimeType;
1632 * toolarray an array of arrays which each include the filename of
1633 * the button image (without path), the opening tag, the closing tag,
1634 * and optionally a sample text that is inserted between the two when no
1635 * selection is highlighted.
1636 * The tip text is shown when the user moves the mouse over the button.
1638 * Already here are accesskeys (key), which are not used yet until someone
1639 * can figure out a way to make them work in IE. However, we should make
1640 * sure these keys are not defined on the edit page.
1643 array( 'image' => 'button_bold.png',
1644 'id' => 'mw-editbutton-bold',
1645 'open' => '\\\'\\\'\\\'',
1646 'close' => '\\\'\\\'\\\'',
1647 'sample'=> wfMsg('bold_sample'),
1648 'tip' => wfMsg('bold_tip'),
1651 array( 'image' => 'button_italic.png',
1652 'id' => 'mw-editbutton-italic',
1653 'open' => '\\\'\\\'',
1654 'close' => '\\\'\\\'',
1655 'sample'=> wfMsg('italic_sample'),
1656 'tip' => wfMsg('italic_tip'),
1659 array( 'image' => 'button_link.png',
1660 'id' => 'mw-editbutton-link',
1663 'sample'=> wfMsg('link_sample'),
1664 'tip' => wfMsg('link_tip'),
1667 array( 'image' => 'button_extlink.png',
1668 'id' => 'mw-editbutton-extlink',
1671 'sample'=> wfMsg('extlink_sample'),
1672 'tip' => wfMsg('extlink_tip'),
1675 array( 'image' => 'button_headline.png',
1676 'id' => 'mw-editbutton-headline',
1678 'close' => " ==\\n",
1679 'sample'=> wfMsg('headline_sample'),
1680 'tip' => wfMsg('headline_tip'),
1683 array( 'image' => 'button_image.png',
1684 'id' => 'mw-editbutton-image',
1685 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1687 'sample'=> wfMsg('image_sample'),
1688 'tip' => wfMsg('image_tip'),
1691 array( 'image' => 'button_media.png',
1692 'id' => 'mw-editbutton-media',
1693 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1695 'sample'=> wfMsg('media_sample'),
1696 'tip' => wfMsg('media_tip'),
1699 array( 'image' => 'button_math.png',
1700 'id' => 'mw-editbutton-math',
1702 'close' => "<\\/math>",
1703 'sample'=> wfMsg('math_sample'),
1704 'tip' => wfMsg('math_tip'),
1707 array( 'image' => 'button_nowiki.png',
1708 'id' => 'mw-editbutton-nowiki',
1709 'open' => "<nowiki>",
1710 'close' => "<\\/nowiki>",
1711 'sample'=> wfMsg('nowiki_sample'),
1712 'tip' => wfMsg('nowiki_tip'),
1715 array( 'image' => 'button_sig.png',
1716 'id' => 'mw-editbutton-signature',
1720 'tip' => wfMsg('sig_tip'),
1723 array( 'image' => 'button_hr.png',
1724 'id' => 'mw-editbutton-hr',
1725 'open' => "\\n----\\n",
1728 'tip' => wfMsg('hr_tip'),
1732 $toolbar = "<div id='toolbar'>\n";
1733 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1735 foreach($toolarray as $tool) {
1737 $cssId = $tool['id'];
1738 $image=$wgStylePath.'/common/images/'.$tool['image'];
1739 $open=$tool['open'];
1740 $close=$tool['close'];
1741 $sample = wfEscapeJsString( $tool['sample'] );
1743 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1744 // Older browsers show a "speedtip" type message only for ALT.
1745 // Ideally these should be different, realistically they
1746 // probably don't need to be.
1747 $tip = wfEscapeJsString( $tool['tip'] );
1749 #$key = $tool["key"];
1751 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1754 $toolbar.="/*]]>*/\n</script>";
1755 $toolbar.="\n</div>";
1760 * Returns an array of html code of the following checkboxes:
1763 * @param $tabindex Current tabindex
1764 * @param $skin Skin object
1765 * @param $checked Array of checkbox => bool, where bool indicates the checked
1766 * status of the checkbox
1770 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1773 $checkboxes = array();
1775 $checkboxes['minor'] = '';
1776 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1777 if ( $wgUser->isAllowed('minoredit') ) {
1779 'tabindex' => ++
$tabindex,
1780 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1781 'id' => 'wpMinoredit',
1783 $checkboxes['minor'] =
1784 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1785 " <label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1788 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1789 $checkboxes['watch'] = '';
1790 if ( $wgUser->isLoggedIn() ) {
1792 'tabindex' => ++
$tabindex,
1793 'accesskey' => wfMsg( 'accesskey-watch' ),
1794 'id' => 'wpWatchthis',
1796 $checkboxes['watch'] =
1797 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1798 " <label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1804 * Returns an array of html code of the following buttons:
1805 * save, diff, preview and live
1807 * @param $tabindex Current tabindex
1811 public function getEditButtons(&$tabindex) {
1812 global $wgLivePreview, $wgUser;
1820 'tabindex' => ++
$tabindex,
1821 'value' => wfMsg('savearticle'),
1822 'accesskey' => wfMsg('accesskey-save'),
1823 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1825 $buttons['save'] = wfElement('input', $temp, '');
1827 ++
$tabindex; // use the same for preview and live preview
1828 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1830 'id' => 'wpPreview',
1831 'name' => 'wpPreview',
1833 'tabindex' => $tabindex,
1834 'value' => wfMsg('showpreview'),
1836 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1837 'style' => 'display: none;',
1839 $buttons['preview'] = wfElement('input', $temp, '');
1842 'id' => 'wpLivePreview',
1843 'name' => 'wpLivePreview',
1845 'tabindex' => $tabindex,
1846 'value' => wfMsg('showlivepreview'),
1847 'accesskey' => wfMsg('accesskey-preview'),
1849 'onclick' => $this->doLivePreviewScript(),
1851 $buttons['live'] = wfElement('input', $temp, '');
1854 'id' => 'wpPreview',
1855 'name' => 'wpPreview',
1857 'tabindex' => $tabindex,
1858 'value' => wfMsg('showpreview'),
1859 'accesskey' => wfMsg('accesskey-preview'),
1860 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1862 $buttons['preview'] = wfElement('input', $temp, '');
1863 $buttons['live'] = '';
1870 'tabindex' => ++
$tabindex,
1871 'value' => wfMsg('showdiff'),
1872 'accesskey' => wfMsg('accesskey-diff'),
1873 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1875 $buttons['diff'] = wfElement('input', $temp, '');
1881 * Output preview text only. This can be sucked into the edit page
1882 * via JavaScript, and saves the server time rendering the skin as
1883 * well as theoretically being more robust on the client (doesn't
1884 * disturb the edit box's undo history, won't eat your text on
1887 * @todo This doesn't include category or interlanguage links.
1888 * Would need to enhance it a bit, <s>maybe wrap them in XML
1889 * or something...</s> that might also require more skin
1890 * initialization, so check whether that's a problem.
1892 function livePreview() {
1895 header( 'Content-type: text/xml; charset=utf-8' );
1896 header( 'Cache-control: no-cache' );
1898 $previewText = $this->getPreviewText();
1899 #$categories = $skin->getCategoryLinks();
1902 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1903 Xml
::tags( 'livepreview', null,
1904 Xml
::element( 'preview', null, $previewText )
1905 #. Xml::element( 'category', null, $categories )
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->mArticle
->getTitle() );
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>' );