3 * Contains the EditPage class
7 * The edit page/HTML interface (split from Article)
8 * The actual database and text munging is still in Article,
9 * but it should get easier to call those from alternate
16 var $isConflict = false;
17 var $isCssJsSubpage = false;
18 var $deletedSinceEdit = false;
22 var $mTokenOk = false;
23 var $mTokenOkExceptSuffix = false;
24 var $mTriedSave = false;
26 var $kblength = false;
27 var $missingComment = false;
28 var $missingSummary = false;
29 var $allowBlankSummary = false;
32 var $mPreviewTemplates;
35 var $save = false, $preview = false, $diff = false;
36 var $minoredit = false, $watchthis = false, $recreate = false;
37 var $textbox1 = '', $textbox2 = '', $summary = '';
38 var $edittime = '', $section = '', $starttime = '';
39 var $oldid = 0, $editintro = '', $scrolltop = null;
41 # Placeholders for text injection by hooks (must be HTML)
42 # extensions should take care to _append_ to the present value
43 public $editFormPageTop; // Before even the preview
44 public $editFormTextTop;
45 public $editFormTextAfterWarn;
46 public $editFormTextAfterTools;
47 public $editFormTextBottom;
53 function EditPage( $article ) {
54 $this->mArticle
=& $article;
56 $this->mTitle
=& $wgTitle;
58 # Placeholders for text injection by hooks (empty per default)
59 $this->editFormPageTop
=
60 $this->editFormTextTop
=
61 $this->editFormTextAfterWarn
=
62 $this->editFormTextAfterTools
=
63 $this->editFormTextBottom
= "";
67 * Fetch initial editing page content.
69 private function getContent( $def_text = '' ) {
70 global $wgOut, $wgRequest, $wgParser;
72 # Get variables from query string :P
73 $section = $wgRequest->getVal( 'section' );
74 $preload = $wgRequest->getVal( 'preload' );
75 $undoafter = $wgRequest->getVal( 'undoafter' );
76 $undo = $wgRequest->getVal( 'undo' );
78 wfProfileIn( __METHOD__
);
81 if( !$this->mTitle
->exists() ) {
82 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
83 # If this is a system message, get the default text.
84 $text = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
86 # If requested, preload some text.
87 $text = $this->getPreloadedText( $preload );
89 # We used to put MediaWiki:Newarticletext here if
90 # $text was empty at this point.
91 # This is now shown above the edit box instead.
93 // FIXME: may be better to use Revision class directly
94 // But don't mess with it just yet. Article knows how to
95 // fetch the page record from the high-priority server,
96 // which is needed to guarantee we don't pick up lagged
99 $text = $this->mArticle
->getContent();
101 if ($undo > 0 && $undoafter > 0 && $undo < $undoafter) {
102 # If they got undoafter and undo round the wrong way, switch them
103 list( $undo, $undoafter ) = array( $undoafter, $undo );
106 if ( $undo > 0 && $undo > $undoafter ) {
107 # Undoing a specific edit overrides section editing; section-editing
108 # doesn't work with undoing.
110 $undorev = Revision
::newFromId($undo);
111 $oldrev = Revision
::newFromId($undoafter);
113 $undorev = Revision
::newFromId($undo);
114 $oldrev = $undorev ?
$undorev->getPrevious() : null;
117 #Sanity check, make sure it's the right page.
118 # Otherwise, $text will be left as-is.
119 if ( !is_null($undorev) && !is_null($oldrev) && $undorev->getPage()==$oldrev->getPage() && $undorev->getPage()==$this->mArticle
->getID() ) {
120 $undorev_text = $undorev->getText();
121 $oldrev_text = $oldrev->getText();
122 $currev_text = $text;
124 #No use doing a merge if it's just a straight revert.
125 if ( $currev_text != $undorev_text ) {
126 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
128 $text = $oldrev_text;
132 // Failed basic sanity checks.
133 // Older revisions may have been removed since the link
134 // was created, or we may simply have got bogus input.
139 # Inform the user of our success and set an automatic edit summary
140 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
141 $firstrev = $oldrev->getNext();
142 # If we just undid one rev, use an autosummary
143 if ( $firstrev->mId
== $undo ) {
144 $this->summary
= wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
146 $this->formtype
= 'diff';
148 # Warn the user that something went wrong
149 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
151 } else if( $section != '' ) {
152 if( $section == 'new' ) {
153 $text = $this->getPreloadedText( $preload );
155 $text = $wgParser->getSection( $text, $section, $def_text );
160 wfProfileOut( __METHOD__
);
165 * Get the contents of a page from its title and remove includeonly tags
167 * @param $preload String: the title of the page.
168 * @return string The contents of the page.
170 private function getPreloadedText($preload) {
171 if ( $preload === '' )
174 $preloadTitle = Title
::newFromText( $preload );
175 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
176 $rev=Revision
::newFromTitle($preloadTitle);
177 if ( is_object( $rev ) ) {
178 $text = $rev->getText();
179 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
180 // its own mini-parser! -ævar
181 $text = preg_replace( '~</?includeonly>~', '', $text );
190 * This is the function that extracts metadata from the article body on the first view.
191 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
192 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
194 function extractMetaDataFromArticle () {
195 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
196 $this->mMetaData
= '' ;
197 if ( !$wgUseMetadataEdit ) return ;
198 if ( $wgMetadataWhitelist == '' ) return ;
200 $t = $this->getContent();
202 # MISSING : <nowiki> filtering
204 # Categories and language links
205 $t = explode ( "\n" , $t ) ;
206 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
207 $cat = $ll = array() ;
208 foreach ( $t AS $key => $x )
210 $y = trim ( strtolower ( $x ) ) ;
211 while ( substr ( $y , 0 , 2 ) == '[[' )
213 $y = explode ( ']]' , trim ( $x ) ) ;
214 $first = array_shift ( $y ) ;
215 $first = explode ( ':' , $first ) ;
216 $ns = array_shift ( $first ) ;
217 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
218 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
220 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
221 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
223 $x = implode ( ']]' , $y ) ;
225 $y = trim ( strtolower ( $x ) ) ;
229 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
230 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
231 $t = implode ( "\n" , $t ) ;
234 $sat = array () ; # stand-alone-templates; must be lowercase
235 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
236 $wl_article = new Article ( $wl_title ) ;
237 $wl = explode ( "\n" , $wl_article->getContent() ) ;
238 foreach ( $wl AS $x )
242 while ( substr ( $x , 0 , 1 ) == '*' )
245 $x = trim ( substr ( $x , 1 ) ) ;
249 $sat[] = strtolower ( $x ) ;
254 # Templates, but only some
255 $t = explode ( '{{' , $t ) ;
257 foreach ( $t AS $key => $x )
259 $y = explode ( '}}' , $x , 2 ) ;
260 if ( count ( $y ) == 2 )
263 $z = explode ( '|' , $z ) ;
264 $tn = array_shift ( $z ) ;
265 if ( in_array ( strtolower ( $tn ) , $sat ) )
267 $tl[] = '{{' . $y[0] . '}}' ;
269 $y = explode ( '}}' , $y[1] , 2 ) ;
271 else $t[$key] = '{{' . $x ;
273 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
276 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
277 $t = implode ( '' , $t ) ;
279 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
280 $this->mArticle
->mContent
= $t ;
281 $this->mMetaData
= $s ;
289 * This is the function that gets called for "action=edit". It
290 * sets up various member variables, then passes execution to
291 * another function, usually showEditForm()
293 * The edit form is self-submitting, so that when things like
294 * preview and edit conflicts occur, we get the same form back
295 * with the extra stuff added. Only when the final submission
296 * is made and all is well do we actually save and redirect to
297 * the newly-edited page.
300 global $wgOut, $wgUser, $wgRequest, $wgTitle;
302 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
305 $fname = 'EditPage::edit';
306 wfProfileIn( $fname );
307 wfDebug( "$fname: enter\n" );
309 // this is not an article
310 $wgOut->setArticleFlag(false);
312 $this->importFormData( $wgRequest );
313 $this->firsttime
= false;
316 $this->livePreview();
317 wfProfileOut( $fname );
321 $permErrors = $this->mTitle
->getUserPermissionsErrors('edit', $wgUser);
322 if( !$this->mTitle
->exists() )
323 $permErrors +
= array_diff( $this->mTitle
->getUserPermissionsErrors('create', $wgUser), $permErrors );
325 # Ignore some permissions errors.
327 foreach( $permErrors as $error ) {
328 if ($this->preview ||
$this->diff
&&
329 ($error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext'))
331 // Don't worry about blocks when previewing/diffing
335 if ($error[0] == 'readonlytext')
338 $this->formtype
= 'preview';
339 } elseif ($this->save ||
$this->preview ||
$this->diff
) {
344 # array_diff returns elements in $permErrors that are not in $remove.
345 $permErrors = array_diff( $permErrors, $remove );
347 if ( !empty($permErrors) )
349 wfDebug( "$fname: User can't edit\n" );
350 $wgOut->readOnlyPage( $this->getContent(), true, $permErrors );
351 wfProfileOut( $fname );
355 $this->formtype
= 'save';
356 } else if ( $this->preview
) {
357 $this->formtype
= 'preview';
358 } else if ( $this->diff
) {
359 $this->formtype
= 'diff';
360 } else { # First time through
361 $this->firsttime
= true;
362 if( $this->previewOnOpen() ) {
363 $this->formtype
= 'preview';
365 $this->extractMetaDataFromArticle () ;
366 $this->formtype
= 'initial';
371 wfProfileIn( "$fname-business-end" );
373 $this->isConflict
= false;
374 // css / js subpages of user pages get a special treatment
375 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
376 $this->isValidCssJsSubpage
= $wgTitle->isValidCssJsSubpage();
378 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
379 * no matter it's current state
381 $this->deletedSinceEdit
= false;
382 if ( $this->edittime
!= '' ) {
383 /* Note that we rely on logging table, which hasn't been always there,
384 * but that doesn't matter, because this only applies to brand new
385 * deletes. This is done on every preview and save request. Move it further down
386 * to only perform it on saves
388 if ( $this->mTitle
->isDeleted() ) {
389 $this->lastDelete
= $this->getLastDelete();
390 if ( !is_null($this->lastDelete
) ) {
391 $deletetime = $this->lastDelete
->log_timestamp
;
392 if ( ($deletetime - $this->starttime
) > 0 ) {
393 $this->deletedSinceEdit
= true;
399 # Show applicable editing introductions
400 if( $this->formtype
== 'initial' ||
$this->firsttime
)
403 if( $this->mTitle
->isTalkPage() ) {
404 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
407 # Attempt submission here. This will check for edit conflicts,
408 # and redundantly check for locked database, blocked IPs, etc.
409 # that edit() already checked just in case someone tries to sneak
410 # in the back door with a hand-edited submission URL.
412 if ( 'save' == $this->formtype
) {
413 if ( !$this->attemptSave() ) {
414 wfProfileOut( "$fname-business-end" );
415 wfProfileOut( $fname );
420 # First time through: get contents, set time for conflict
422 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
423 if ($this->initialiseForm() === false) {
424 $this->noSuchSectionPage();
425 wfProfileOut( "$fname-business-end" );
426 wfProfileOut( $fname );
429 if( !$this->mTitle
->getArticleId() )
430 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
433 $this->showEditForm();
434 wfProfileOut( "$fname-business-end" );
435 wfProfileOut( $fname );
439 * Should we show a preview when the edit form is first shown?
443 private function previewOnOpen() {
444 global $wgRequest, $wgUser;
445 if( $wgRequest->getVal( 'preview' ) == 'yes' ) {
446 // Explicit override from request
448 } elseif( $wgRequest->getVal( 'preview' ) == 'no' ) {
449 // Explicit override from request
451 } elseif( $this->section
== 'new' ) {
452 // Nothing *to* preview for new sections
454 } elseif( ( $wgRequest->getVal( 'preload' ) !== '' ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
455 // Standard preference behaviour
457 } elseif( !$this->mTitle
->exists() && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
458 // Categories are special
469 function importFormData( &$request ) {
470 global $wgLang, $wgUser;
471 $fname = 'EditPage::importFormData';
472 wfProfileIn( $fname );
474 if( $request->wasPosted() ) {
475 # These fields need to be checked for encoding.
476 # Also remove trailing whitespace, but don't remove _initial_
477 # whitespace from the text boxes. This may be significant formatting.
478 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
479 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
480 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
481 # Truncate for whole multibyte characters. +5 bytes for ellipsis
482 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
484 $this->edittime
= $request->getVal( 'wpEdittime' );
485 $this->starttime
= $request->getVal( 'wpStarttime' );
487 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
489 if( is_null( $this->edittime
) ) {
490 # If the form is incomplete, force to preview.
491 wfDebug( "$fname: Form data appears to be incomplete\n" );
492 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
493 $this->preview
= true;
495 /* Fallback for live preview */
496 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
497 $this->diff
= $request->getCheck( 'wpDiff' );
499 // Remember whether a save was requested, so we can indicate
500 // if we forced preview due to session failure.
501 $this->mTriedSave
= !$this->preview
;
503 if ( $this->tokenOk( $request ) ) {
504 # Some browsers will not report any submit button
505 # if the user hits enter in the comment box.
506 # The unmarked state will be assumed to be a save,
507 # if the form seems otherwise complete.
508 wfDebug( "$fname: Passed token check.\n" );
509 } else if ( $this->diff
) {
510 # Failed token check, but only requested "Show Changes".
511 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
513 # Page might be a hack attempt posted from
514 # an external site. Preview instead of saving.
515 wfDebug( "$fname: Failed token check; forcing preview\n" );
516 $this->preview
= true;
519 $this->save
= ! ( $this->preview
OR $this->diff
);
520 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
521 $this->edittime
= null;
524 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
525 $this->starttime
= null;
528 $this->recreate
= $request->getCheck( 'wpRecreate' );
530 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
531 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
533 # Don't force edit summaries when a user is editing their own user or talk page
534 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
535 $this->allowBlankSummary
= true;
537 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
540 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
542 # Not a posted form? Start with nothing.
543 wfDebug( "$fname: Not a posted form.\n" );
544 $this->textbox1
= '';
545 $this->textbox2
= '';
546 $this->mMetaData
= '';
548 $this->edittime
= '';
549 $this->starttime
= wfTimestampNow();
551 $this->preview
= false;
554 $this->minoredit
= false;
555 $this->watchthis
= false;
556 $this->recreate
= false;
559 $this->oldid
= $request->getInt( 'oldid' );
561 # Section edit can come from either the form or a link
562 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
564 $this->live
= $request->getCheck( 'live' );
565 $this->editintro
= $request->getText( 'editintro' );
567 wfProfileOut( $fname );
571 * Make sure the form isn't faking a user's credentials.
573 * @param $request WebRequest
577 function tokenOk( &$request ) {
579 $token = $request->getVal( 'wpEditToken' );
580 $this->mTokenOk
= $wgUser->matchEditToken( $token );
581 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
582 return $this->mTokenOk
;
586 * Show all applicable editing introductions
588 private function showIntro() {
589 global $wgOut, $wgUser;
590 if( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
591 if( $wgUser->isLoggedIn() ) {
592 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
594 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
596 $this->showDeletionLog( $wgOut );
601 * Attempt to show a custom editing introduction, if supplied
605 private function showCustomIntro() {
606 if( $this->editintro
) {
607 $title = Title
::newFromText( $this->editintro
);
608 if( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
610 $revision = Revision
::newFromTitle( $title );
611 $wgOut->addSecondaryWikiText( $revision->getText() );
623 * @return bool false if output is done, true if the rest of the form should be displayed
625 function attemptSave() {
626 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut, $wgParser;
627 global $wgMaxArticleSize;
629 $fname = 'EditPage::attemptSave';
630 wfProfileIn( $fname );
631 wfProfileIn( "$fname-checks" );
633 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
635 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
639 # Reintegrate metadata
640 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
641 $this->mMetaData
= '' ;
645 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
646 $this->spamPage ( $matches[0] );
647 wfProfileOut( "$fname-checks" );
648 wfProfileOut( $fname );
651 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
652 # Error messages or other handling should be performed by the filter function
653 wfProfileOut( $fname );
654 wfProfileOut( "$fname-checks" );
657 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
) ) ) {
658 # Error messages etc. could be handled within the hook...
659 wfProfileOut( $fname );
660 wfProfileOut( "$fname-checks" );
662 } elseif( $this->hookError
!= '' ) {
663 # ...or the hook could be expecting us to produce an error
664 wfProfileOut( "$fname-checks " );
665 wfProfileOut( $fname );
668 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
669 # Check block state against master, thus 'false'.
670 $this->blockedPage();
671 wfProfileOut( "$fname-checks" );
672 wfProfileOut( $fname );
675 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
676 if ( $this->kblength
> $wgMaxArticleSize ) {
677 // Error will be displayed by showEditForm()
678 $this->tooBig
= true;
679 wfProfileOut( "$fname-checks" );
680 wfProfileOut( $fname );
684 if ( !$wgUser->isAllowed('edit') ) {
685 if ( $wgUser->isAnon() ) {
686 $this->userNotLoggedInPage();
687 wfProfileOut( "$fname-checks" );
688 wfProfileOut( $fname );
692 $wgOut->readOnlyPage();
693 wfProfileOut( "$fname-checks" );
694 wfProfileOut( $fname );
699 if ( wfReadOnly() ) {
700 $wgOut->readOnlyPage();
701 wfProfileOut( "$fname-checks" );
702 wfProfileOut( $fname );
705 if ( $wgUser->pingLimiter() ) {
706 $wgOut->rateLimited();
707 wfProfileOut( "$fname-checks" );
708 wfProfileOut( $fname );
712 # If the article has been deleted while editing, don't save it without
714 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
715 wfProfileOut( "$fname-checks" );
716 wfProfileOut( $fname );
720 wfProfileOut( "$fname-checks" );
722 # If article is new, insert it.
723 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
726 // Late check for create permission, just in case *PARANOIA*
727 if ( !$this->mTitle
->userCan( 'create' ) ) {
728 wfDebug( "$fname: no create permission\n" );
729 $this->noCreatePermission();
730 wfProfileOut( $fname );
734 # Don't save a new article if it's blank.
735 if ( ( '' == $this->textbox1
) ) {
736 $wgOut->redirect( $this->mTitle
->getFullURL() );
737 wfProfileOut( $fname );
741 $isComment=($this->section
=='new');
742 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
743 $this->minoredit
, $this->watchthis
, false, $isComment);
745 wfProfileOut( $fname );
749 # Article exists. Check for edit conflict.
751 $this->mArticle
->clear(); # Force reload of dates, etc.
752 $this->mArticle
->forUpdate( true ); # Lock the article
754 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
756 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
757 $this->isConflict
= true;
758 if( $this->section
== 'new' ) {
759 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
760 $this->mArticle
->getComment() == $this->summary
) {
761 // Probably a duplicate submission of a new comment.
762 // This can happen when squid resends a request after
763 // a timeout but the first one actually went through.
764 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
766 // New comment; suppress conflict.
767 $this->isConflict
= false;
768 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
772 $userid = $wgUser->getID();
774 if ( $this->isConflict
) {
775 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
776 $this->mArticle
->getTimestamp() . "')\n" );
777 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
780 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
781 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
783 if( is_null( $text ) ) {
784 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
785 $this->isConflict
= true;
786 $text = $this->textbox1
;
789 # Suppress edit conflict with self, except for section edits where merging is required.
790 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
791 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
792 $this->isConflict
= false;
794 # switch from section editing to normal editing in edit conflict
795 if($this->isConflict
) {
797 if( $this->mergeChangesInto( $text ) ){
798 // Successful merge! Maybe we should tell the user the good news?
799 $this->isConflict
= false;
800 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
803 $this->textbox1
= $text;
804 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
809 if ( $this->isConflict
) {
810 wfProfileOut( $fname );
814 $oldtext = $this->mArticle
->getContent();
816 # Handle the user preference to force summaries here, but not for null edits
817 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary')
818 && 0 != strcmp($oldtext, $text) && !Article
::getRedirectAutosummary( $text )) {
819 if( md5( $this->summary
) == $this->autoSumm
) {
820 $this->missingSummary
= true;
821 wfProfileOut( $fname );
826 #And a similar thing for new sections
827 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
828 if (trim($this->summary
) == '') {
829 $this->missingSummary
= true;
830 wfProfileOut( $fname );
836 wfProfileIn( "$fname-sectionanchor" );
838 if( $this->section
== 'new' ) {
839 if ( $this->textbox1
== '' ) {
840 $this->missingComment
= true;
843 if( $this->summary
!= '' ) {
844 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary
);
845 # This is a new section, so create a link to the new section
846 # in the revision summary.
847 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
848 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
850 } elseif( $this->section
!= '' ) {
851 # Try to get a section anchor from the section source, redirect to edited section if header found
852 # XXX: might be better to integrate this into Article::replaceSection
853 # for duplicate heading checking and maybe parsing
854 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
855 # we can't deal with anchors, includes, html etc in the header for now,
856 # headline would need to be parsed to improve this
857 if($hasmatch and strlen($matches[2]) > 0) {
858 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
861 wfProfileOut( "$fname-sectionanchor" );
863 // Save errors may fall down to the edit form, but we've now
864 // merged the section into full text. Clear the section field
865 // so that later submission of conflict forms won't try to
866 // replace that into a duplicated mess.
867 $this->textbox1
= $text;
870 // Check for length errors again now that the section is merged in
871 $this->kblength
= (int)(strlen( $text ) / 1024);
872 if ( $this->kblength
> $wgMaxArticleSize ) {
873 $this->tooBig
= true;
874 wfProfileOut( $fname );
878 # update the article here
879 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
880 $this->watchthis
, '', $sectionanchor ) ) {
881 wfProfileOut( $fname );
884 $this->isConflict
= true;
886 wfProfileOut( $fname );
891 * Initialise form fields in the object
892 * Called on the first invocation, e.g. when a user clicks an edit link
894 function initialiseForm() {
895 $this->edittime
= $this->mArticle
->getTimestamp();
897 $this->textbox1
= $this->getContent(false);
898 if ($this->textbox1
=== false) return false;
900 if ( !$this->mArticle
->exists() && $this->mArticle
->mTitle
->getNamespace() == NS_MEDIAWIKI
)
901 $this->textbox1
= wfMsgWeirdKey( $this->mArticle
->mTitle
->getText() );
907 * Send the edit form and related headers to $wgOut
908 * @param $formCallback Optional callable that takes an OutputPage
909 * parameter; will be called during form output
910 * near the top, for captchas and the like.
912 function showEditForm( $formCallback=null ) {
913 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
915 $fname = 'EditPage::showEditForm';
916 wfProfileIn( $fname );
918 $sk = $wgUser->getSkin();
920 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
922 $wgOut->setRobotpolicy( 'noindex,nofollow' );
924 # Enabled article-related sidebar, toplinks, etc.
925 $wgOut->setArticleRelated( true );
927 if ( $this->formtype
== 'preview' ) {
928 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
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] ) ) {
953 $this->summary
= "/* " .
954 $wgParser->stripSectionName(trim($matches[2])) .
960 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
962 $wgOut->setPageTitle( $s );
964 if ( $this->missingComment
) {
965 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
968 if( $this->missingSummary
&& $this->section
!= 'new' ) {
969 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
972 if( $this->missingSummary
&& $this->section
== 'new' ) {
973 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
976 if( !$this->hookError
== '' ) {
977 $wgOut->addWikiText( $this->hookError
);
980 if ( !$this->checkUnicodeCompliantBrowser() ) {
981 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
983 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
984 // Let sysop know that this will make private content public if saved
985 if( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
986 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
988 if( !$this->mArticle
->mRevision
->isCurrent() ) {
989 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
990 $wgOut->addWikiText( wfMsg( 'editingold' ) );
996 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
997 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
998 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
1000 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
1001 # Check the skin exists
1002 if( $this->isValidCssJsSubpage
) {
1003 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
1005 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
1010 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1011 # Show a warning if editing an interface message
1012 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
1013 } elseif( $this->mTitle
->isProtected( 'edit' ) ) {
1014 # Is the title semi-protected?
1015 if( $this->mTitle
->isSemiProtected() ) {
1016 $notice = wfMsg( 'semiprotectedpagewarning' );
1017 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' )
1020 # Then it must be protected based on static groups (regular)
1021 $notice = wfMsg( 'protectedpagewarning' );
1023 $wgOut->addWikiText( $notice );
1025 if ( $this->mTitle
->isCascadeProtected() ) {
1026 # Is this page under cascading protection from some source pages?
1027 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1028 if ( count($cascadeSources) > 0 ) {
1029 # Explain, and list the titles responsible
1030 $notice = wfMsgExt( 'cascadeprotectedwarning', array('parsemag'), count($cascadeSources) ) . "\n";
1031 foreach( $cascadeSources as $page ) {
1032 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1035 $wgOut->addWikiText( $notice );
1038 if ( $this->kblength
=== false ) {
1039 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1041 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1042 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgMaxArticleSize ) );
1043 } elseif( $this->kblength
> 29 ) {
1044 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) ) );
1047 #need to parse the preview early so that we know which templates are used,
1048 #otherwise users with "show preview after edit box" will get a blank list
1049 if ( $this->formtype
== 'preview' ) {
1050 $previewOutput = $this->getPreviewText();
1053 $rows = $wgUser->getIntOption( 'rows' );
1054 $cols = $wgUser->getIntOption( 'cols' );
1056 $ew = $wgUser->getOption( 'editwidth' );
1057 if ( $ew ) $ew = " style=\"width:100%\"";
1060 $q = 'action=submit';
1061 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1062 $action = $this->mTitle
->escapeLocalURL( $q );
1064 $summary = wfMsg('summary');
1065 $subject = wfMsg('subject');
1067 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
1068 wfMsgExt('cancel', array('parseinline')) );
1069 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1070 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1071 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1072 htmlspecialchars( wfMsg( 'newwindow' ) );
1074 global $wgRightsText;
1075 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1076 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
1077 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1078 $wgRightsText ) . "\n</div>";
1080 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1081 # prepare toolbar for edit buttons
1082 $toolbar = $this->getEditToolbar();
1087 // activate checkboxes if user wants them to be always active
1088 if( !$this->preview
&& !$this->diff
) {
1089 # Sort out the "watch" checkbox
1090 if( $wgUser->getOption( 'watchdefault' ) ) {
1092 $this->watchthis
= true;
1093 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1095 $this->watchthis
= true;
1096 } elseif( $this->mTitle
->userIsWatching() ) {
1098 $this->watchthis
= true;
1101 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1104 $wgOut->addHTML( $this->editFormPageTop
);
1106 if ( $wgUser->getOption( 'previewontop' ) ) {
1108 if ( 'preview' == $this->formtype
) {
1109 $this->showPreview( $previewOutput );
1111 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1114 if ( 'diff' == $this->formtype
) {
1120 $wgOut->addHTML( $this->editFormTextTop
);
1122 # if this is a comment, show a subject line at the top, which is also the edit summary.
1123 # Otherwise, show a summary field at the bottom
1124 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1125 if( $this->section
== 'new' ) {
1126 $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 />";
1128 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1129 $summarypreview = '';
1131 $commentsubject = '';
1132 $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 />";
1133 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1134 $subjectpreview = '';
1137 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1138 if( !$this->preview
&& !$this->diff
) {
1139 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1141 $templates = ($this->preview ||
$this->section
!= '') ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1142 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1144 global $wgUseMetadataEdit ;
1145 if ( $wgUseMetadataEdit ) {
1146 $metadata = $this->mMetaData
;
1147 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1148 $top = wfMsgWikiHtml( 'metadata_help' );
1149 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1151 else $metadata = "" ;
1155 if ($this->deletedSinceEdit
) {
1156 if ( 'save' != $this->formtype
) {
1157 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1159 // Hide the toolbar and edit area, use can click preview to get it back
1160 // Add an confirmation checkbox and explanation.
1162 $hidden = 'type="hidden" style="display:none;"';
1163 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1165 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1166 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1172 $checkboxes = self
::getCheckboxes( $tabindex, $sk,
1173 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1175 $checkboxhtml = implode( $checkboxes, "\n" );
1177 $buttons = $this->getEditButtons( $tabindex );
1178 $buttonshtml = implode( $buttons, "\n" );
1180 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1181 ?
'' : Xml
::hidden( 'safemode', '1' );
1183 $wgOut->addHTML( <<<END
1185 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1189 if( is_callable( $formCallback ) ) {
1190 call_user_func_array( $formCallback, array( &$wgOut ) );
1193 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1195 // Put these up at the top to ensure they aren't lost on early form submission
1197 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1198 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1199 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1200 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1202 $wgOut->addHTML( <<<END
1206 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1207 cols='{$cols}'{$ew} $hidden>
1209 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
1214 $wgOut->addWikiText( $copywarn );
1215 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1225 "<div class='editButtons'>
1227 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1228 </div><!-- editButtons -->
1229 </div><!-- editOptions -->");
1231 $wgOut->addHtml( '<div class="mw-editTools">' );
1232 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1233 $wgOut->addHtml( '</div>' );
1235 $wgOut->addHTML( $this->editFormTextAfterTools
);
1238 <div class='templatesUsed'>
1239 {$formattedtemplates}
1244 * To make it harder for someone to slip a user a page
1245 * which submits an edit form to the wiki without their
1246 * knowledge, a random token is associated with the login
1247 * session. If it's not passed back with the submission,
1248 * we won't save the page, or render user JavaScript and
1251 * For anon editors, who may not have a session, we just
1252 * include the constant suffix to prevent editing from
1253 * broken text-mangling proxies.
1255 $token = htmlspecialchars( $wgUser->editToken() );
1256 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1259 # If a blank edit summary was previously provided, and the appropriate
1260 # user preference is active, pass a hidden tag here. This will stop the
1261 # user being bounced back more than once in the event that a summary
1263 if( $this->missingSummary
) {
1264 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1267 # For a bit more sophisticated detection of blank summaries, hash the
1268 # automatic one and pass that in a hidden field.
1269 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1270 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1272 if ( $this->isConflict
) {
1273 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1275 $de = new DifferenceEngine( $this->mTitle
);
1276 $de->setText( $this->textbox2
, $this->textbox1
);
1277 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1279 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1280 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1281 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1283 $wgOut->addHTML( $this->editFormTextBottom
);
1284 $wgOut->addHTML( "</form>\n" );
1285 if ( !$wgUser->getOption( 'previewontop' ) ) {
1287 if ( $this->formtype
== 'preview') {
1288 $this->showPreview( $previewOutput );
1290 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1293 if ( $this->formtype
== 'diff') {
1299 wfProfileOut( $fname );
1303 * Append preview output to $wgOut.
1304 * Includes category rendering if this is a category page.
1306 * @param string $text The HTML to be output for the preview.
1308 private function showPreview( $text ) {
1311 $wgOut->addHTML( '<div id="wikiPreview">' );
1312 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1313 $this->mArticle
->openShowCategory();
1315 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1316 $wgOut->addHTML( $text );
1317 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1318 $this->mArticle
->closeShowCategory();
1320 $wgOut->addHTML( '</div>' );
1324 * Live Preview lets us fetch rendered preview page content and
1325 * add it to the page without refreshing the whole page.
1326 * If not supported by the browser it will fall through to the normal form
1327 * submission method.
1329 * This function outputs a script tag to support live preview, and
1330 * returns an onclick handler which should be added to the attributes
1331 * of the preview button
1333 function doLivePreviewScript() {
1334 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1335 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1336 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1337 '"></script>' . "\n" );
1338 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1339 return "return !lpDoPreview(" .
1340 "editform.wpTextbox1.value," .
1341 '"' . $liveAction . '"' . ")";
1344 function getLastDelete() {
1345 $dbr = wfGetDB( DB_SLAVE
);
1346 $fname = 'EditPage::getLastDelete';
1347 $res = $dbr->select(
1348 array( 'logging', 'user' ),
1358 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1359 'log_title' => $this->mTitle
->getDBkey(),
1360 'log_type' => 'delete',
1361 'log_action' => 'delete',
1362 'user_id=log_user' ),
1364 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1366 if($dbr->numRows($res) == 1) {
1367 while ( $x = $dbr->fetchObject ( $res ) )
1369 $dbr->freeResult ( $res ) ;
1379 function getPreviewText() {
1380 global $wgOut, $wgUser, $wgTitle, $wgParser;
1382 $fname = 'EditPage::getPreviewText';
1383 wfProfileIn( $fname );
1385 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1386 if ( $this->mTokenOkExceptSuffix
) {
1387 $msg = 'token_suffix_mismatch';
1389 $msg = 'session_fail_preview';
1392 $msg = 'previewnote';
1394 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1395 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1396 if ( $this->isConflict
) {
1397 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1400 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1401 $parserOptions->setEditSection( false );
1404 if( $wgRawHtml && !$this->mTokenOk
) {
1405 // Could be an offsite preview attempt. This is very unsafe if
1406 // HTML is enabled, as it could be an attack.
1407 return $wgOut->parse( "<div class='previewnote'>" .
1408 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1411 # don't parse user css/js, show message about preview
1412 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1414 if ( $this->isCssJsSubpage
) {
1415 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1416 $previewtext = wfMsg('usercsspreview');
1417 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1418 $previewtext = wfMsg('userjspreview');
1420 $parserOptions->setTidy(true);
1421 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1422 $wgOut->addHTML( $parserOutput->mText
);
1423 wfProfileOut( $fname );
1424 return $previewhead;
1426 $toparse = $this->textbox1
;
1428 # If we're adding a comment, we need to show the
1429 # summary as the headline
1430 if($this->section
=="new" && $this->summary
!="") {
1431 $toparse="== {$this->summary} ==\n\n".$toparse;
1434 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1435 $parserOptions->setTidy(true);
1436 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1437 $wgTitle, $parserOptions );
1439 $previewHTML = $parserOutput->getText();
1440 $wgOut->addParserOutputNoText( $parserOutput );
1442 # ParserOutput might have altered the page title, so reset it
1443 $wgOut->setPageTitle( wfMsg( 'editing', $this->mTitle
->getPrefixedText() ) );
1445 foreach ( $parserOutput->getTemplates() as $ns => $template)
1446 foreach ( array_keys( $template ) as $dbk)
1447 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1449 wfProfileOut( $fname );
1450 return $previewhead . $previewHTML;
1455 * Call the stock "user is blocked" page
1457 function blockedPage() {
1458 global $wgOut, $wgUser;
1459 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1461 # If the user made changes, preserve them when showing the markup
1462 # (This happens when a user is blocked during edit, for instance)
1463 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1465 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1467 $source = $this->textbox1
;
1470 # Spit out the source or the user's modified version
1471 if( $source !== false ) {
1472 $rows = $wgUser->getOption( 'rows' );
1473 $cols = $wgUser->getOption( 'cols' );
1474 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1475 $wgOut->addHtml( '<hr />' );
1476 $wgOut->addWikiText( wfMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() ) );
1477 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1482 * Produce the stock "please login to edit pages" page
1484 function userNotLoggedInPage() {
1485 global $wgUser, $wgOut;
1486 $skin = $wgUser->getSkin();
1488 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1489 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle
->getPrefixedUrl() );
1491 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1492 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1493 $wgOut->setArticleRelated( false );
1495 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1496 $wgOut->returnToMain( false, $this->mTitle
);
1500 * Creates a basic error page which informs the user that
1501 * they have attempted to edit a nonexistant section.
1503 function noSuchSectionPage() {
1506 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1507 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1508 $wgOut->setArticleRelated( false );
1510 $wgOut->addWikiText( wfMsg( 'nosuchsectiontext', $this->section
) );
1511 $wgOut->returnToMain( false, $this->mTitle
);
1515 * Produce the stock "your edit contains spam" page
1517 * @param $match Text which triggered one or more filters
1519 function spamPage( $match = false ) {
1522 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1523 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1524 $wgOut->setArticleRelated( false );
1526 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1528 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1530 $wgOut->returnToMain( false, $this->mTitle
);
1537 function mergeChangesInto( &$editText ){
1538 $fname = 'EditPage::mergeChangesInto';
1539 wfProfileIn( $fname );
1541 $db = wfGetDB( DB_MASTER
);
1543 // This is the revision the editor started from
1544 $baseRevision = Revision
::loadFromTimestamp(
1545 $db, $this->mArticle
->mTitle
, $this->edittime
);
1546 if( is_null( $baseRevision ) ) {
1547 wfProfileOut( $fname );
1550 $baseText = $baseRevision->getText();
1552 // The current state, we want to merge updates into it
1553 $currentRevision = Revision
::loadFromTitle(
1554 $db, $this->mArticle
->mTitle
);
1555 if( is_null( $currentRevision ) ) {
1556 wfProfileOut( $fname );
1559 $currentText = $currentRevision->getText();
1562 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1563 $editText = $result;
1564 wfProfileOut( $fname );
1567 wfProfileOut( $fname );
1573 * Check if the browser is on a blacklist of user-agents known to
1574 * mangle UTF-8 data on form submission. Returns true if Unicode
1575 * should make it through, false if it's known to be a problem.
1579 function checkUnicodeCompliantBrowser() {
1580 global $wgBrowserBlackList;
1581 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1582 // No User-Agent header sent? Trust it by default...
1585 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1586 foreach ( $wgBrowserBlackList as $browser ) {
1587 if ( preg_match($browser, $currentbrowser) ) {
1595 * @deprecated use $wgParser->stripSectionName()
1597 function pseudoParseSectionAnchor( $text ) {
1599 return $wgParser->stripSectionName( $text );
1603 * Format an anchor fragment as it would appear for a given section name
1604 * @param string $text
1608 function sectionAnchor( $text ) {
1610 return $wgParser->guessSectionNameFromWikiText( $text );
1614 * Shows a bulletin board style toolbar for common editing functions.
1615 * It can be disabled in the user preferences.
1616 * The necessary JavaScript code can be found in style/wikibits.js.
1618 function getEditToolbar() {
1619 global $wgStylePath, $wgContLang, $wgJsMimeType;
1622 * toolarray an array of arrays which each include the filename of
1623 * the button image (without path), the opening tag, the closing tag,
1624 * and optionally a sample text that is inserted between the two when no
1625 * selection is highlighted.
1626 * The tip text is shown when the user moves the mouse over the button.
1628 * Already here are accesskeys (key), which are not used yet until someone
1629 * can figure out a way to make them work in IE. However, we should make
1630 * sure these keys are not defined on the edit page.
1633 array( 'image' => 'button_bold.png',
1634 'id' => 'mw-editbutton-bold',
1635 'open' => '\\\'\\\'\\\'',
1636 'close' => '\\\'\\\'\\\'',
1637 'sample'=> wfMsg('bold_sample'),
1638 'tip' => wfMsg('bold_tip'),
1641 array( 'image' => 'button_italic.png',
1642 'id' => 'mw-editbutton-italic',
1643 'open' => '\\\'\\\'',
1644 'close' => '\\\'\\\'',
1645 'sample'=> wfMsg('italic_sample'),
1646 'tip' => wfMsg('italic_tip'),
1649 array( 'image' => 'button_link.png',
1650 'id' => 'mw-editbutton-link',
1653 'sample'=> wfMsg('link_sample'),
1654 'tip' => wfMsg('link_tip'),
1657 array( 'image' => 'button_extlink.png',
1658 'id' => 'mw-editbutton-extlink',
1661 'sample'=> wfMsg('extlink_sample'),
1662 'tip' => wfMsg('extlink_tip'),
1665 array( 'image' => 'button_headline.png',
1666 'id' => 'mw-editbutton-headline',
1668 'close' => " ==\\n",
1669 'sample'=> wfMsg('headline_sample'),
1670 'tip' => wfMsg('headline_tip'),
1673 array( 'image' => 'button_image.png',
1674 'id' => 'mw-editbutton-image',
1675 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1677 'sample'=> wfMsg('image_sample'),
1678 'tip' => wfMsg('image_tip'),
1681 array( 'image' => 'button_media.png',
1682 'id' => 'mw-editbutton-media',
1683 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1685 'sample'=> wfMsg('media_sample'),
1686 'tip' => wfMsg('media_tip'),
1689 array( 'image' => 'button_math.png',
1690 'id' => 'mw-editbutton-math',
1692 'close' => "<\\/math>",
1693 'sample'=> wfMsg('math_sample'),
1694 'tip' => wfMsg('math_tip'),
1697 array( 'image' => 'button_nowiki.png',
1698 'id' => 'mw-editbutton-nowiki',
1699 'open' => "<nowiki>",
1700 'close' => "<\\/nowiki>",
1701 'sample'=> wfMsg('nowiki_sample'),
1702 'tip' => wfMsg('nowiki_tip'),
1705 array( 'image' => 'button_sig.png',
1706 'id' => 'mw-editbutton-signature',
1710 'tip' => wfMsg('sig_tip'),
1713 array( 'image' => 'button_hr.png',
1714 'id' => 'mw-editbutton-hr',
1715 'open' => "\\n----\\n",
1718 'tip' => wfMsg('hr_tip'),
1722 $toolbar = "<div id='toolbar'>\n";
1723 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1725 foreach($toolarray as $tool) {
1727 $cssId = $tool['id'];
1728 $image=$wgStylePath.'/common/images/'.$tool['image'];
1729 $open=$tool['open'];
1730 $close=$tool['close'];
1731 $sample = wfEscapeJsString( $tool['sample'] );
1733 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1734 // Older browsers show a "speedtip" type message only for ALT.
1735 // Ideally these should be different, realistically they
1736 // probably don't need to be.
1737 $tip = wfEscapeJsString( $tool['tip'] );
1739 #$key = $tool["key"];
1741 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1744 $toolbar.="/*]]>*/\n</script>";
1745 $toolbar.="\n</div>";
1750 * Returns an array of html code of the following checkboxes:
1753 * @param $tabindex Current tabindex
1754 * @param $skin Skin object
1755 * @param $checked Array of checkbox => bool, where bool indicates the checked
1756 * status of the checkbox
1760 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1763 $checkboxes = array();
1765 $checkboxes['minor'] = '';
1766 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1767 if ( $wgUser->isAllowed('minoredit') ) {
1769 'tabindex' => ++
$tabindex,
1770 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1771 'id' => 'wpMinoredit',
1773 $checkboxes['minor'] =
1774 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1775 " <label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1778 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1779 $checkboxes['watch'] = '';
1780 if ( $wgUser->isLoggedIn() ) {
1782 'tabindex' => ++
$tabindex,
1783 'accesskey' => wfMsg( 'accesskey-watch' ),
1784 'id' => 'wpWatchthis',
1786 $checkboxes['watch'] =
1787 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1788 " <label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1794 * Returns an array of html code of the following buttons:
1795 * save, diff, preview and live
1797 * @param $tabindex Current tabindex
1801 public function getEditButtons(&$tabindex) {
1802 global $wgLivePreview, $wgUser;
1810 'tabindex' => ++
$tabindex,
1811 'value' => wfMsg('savearticle'),
1812 'accesskey' => wfMsg('accesskey-save'),
1813 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1815 $buttons['save'] = wfElement('input', $temp, '');
1817 ++
$tabindex; // use the same for preview and live preview
1818 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1820 'id' => 'wpPreview',
1821 'name' => 'wpPreview',
1823 'tabindex' => $tabindex,
1824 'value' => wfMsg('showpreview'),
1826 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1827 'style' => 'display: none;',
1829 $buttons['preview'] = wfElement('input', $temp, '');
1832 'id' => 'wpLivePreview',
1833 'name' => 'wpLivePreview',
1835 'tabindex' => $tabindex,
1836 'value' => wfMsg('showlivepreview'),
1837 'accesskey' => wfMsg('accesskey-preview'),
1839 'onclick' => $this->doLivePreviewScript(),
1841 $buttons['live'] = wfElement('input', $temp, '');
1844 'id' => 'wpPreview',
1845 'name' => 'wpPreview',
1847 'tabindex' => $tabindex,
1848 'value' => wfMsg('showpreview'),
1849 'accesskey' => wfMsg('accesskey-preview'),
1850 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1852 $buttons['preview'] = wfElement('input', $temp, '');
1853 $buttons['live'] = '';
1860 'tabindex' => ++
$tabindex,
1861 'value' => wfMsg('showdiff'),
1862 'accesskey' => wfMsg('accesskey-diff'),
1863 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1865 $buttons['diff'] = wfElement('input', $temp, '');
1871 * Output preview text only. This can be sucked into the edit page
1872 * via JavaScript, and saves the server time rendering the skin as
1873 * well as theoretically being more robust on the client (doesn't
1874 * disturb the edit box's undo history, won't eat your text on
1877 * @todo This doesn't include category or interlanguage links.
1878 * Would need to enhance it a bit, <s>maybe wrap them in XML
1879 * or something...</s> that might also require more skin
1880 * initialization, so check whether that's a problem.
1882 function livePreview() {
1885 header( 'Content-type: text/xml; charset=utf-8' );
1886 header( 'Cache-control: no-cache' );
1888 $previewText = $this->getPreviewText();
1889 #$categories = $skin->getCategoryLinks();
1892 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1893 Xml
::tags( 'livepreview', null,
1894 Xml
::element( 'preview', null, $previewText )
1895 #. Xml::element( 'category', null, $categories )
1902 * Get a diff between the current contents of the edit box and the
1903 * version of the page we're editing from.
1905 * If this is a section edit, we'll replace the section as for final
1906 * save and then make a comparison.
1908 function showDiff() {
1909 $oldtext = $this->mArticle
->fetchContent();
1910 $newtext = $this->mArticle
->replaceSection(
1911 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1912 $newtext = $this->mArticle
->preSaveTransform( $newtext );
1913 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1914 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1915 if ( $oldtext !== false ||
$newtext != '' ) {
1916 $de = new DifferenceEngine( $this->mTitle
);
1917 $de->setText( $oldtext, $newtext );
1918 $difftext = $de->getDiff( $oldtitle, $newtitle );
1919 $de->showDiffStyle();
1925 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
1929 * Filter an input field through a Unicode de-armoring process if it
1930 * came from an old browser with known broken Unicode editing issues.
1932 * @param WebRequest $request
1933 * @param string $field
1937 function safeUnicodeInput( $request, $field ) {
1938 $text = rtrim( $request->getText( $field ) );
1939 return $request->getBool( 'safemode' )
1940 ?
$this->unmakesafe( $text )
1945 * Filter an output field through a Unicode armoring process if it is
1946 * going to an old browser with known broken Unicode editing issues.
1948 * @param string $text
1952 function safeUnicodeOutput( $text ) {
1954 $codedText = $wgContLang->recodeForEdit( $text );
1955 return $this->checkUnicodeCompliantBrowser()
1957 : $this->makesafe( $codedText );
1961 * A number of web browsers are known to corrupt non-ASCII characters
1962 * in a UTF-8 text editing environment. To protect against this,
1963 * detected browsers will be served an armored version of the text,
1964 * with non-ASCII chars converted to numeric HTML character references.
1966 * Preexisting such character references will have a 0 added to them
1967 * to ensure that round-trips do not alter the original data.
1969 * @param string $invalue
1973 function makesafe( $invalue ) {
1974 // Armor existing references for reversability.
1975 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1980 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1981 $bytevalue = ord( $invalue{$i} );
1982 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1983 $result .= chr( $bytevalue );
1985 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1986 $working = $working << 6;
1987 $working +
= ($bytevalue & 0x3F);
1989 if( $bytesleft <= 0 ) {
1990 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1992 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1993 $working = $bytevalue & 0x1F;
1995 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1996 $working = $bytevalue & 0x0F;
1998 } else { //1111 0xxx
1999 $working = $bytevalue & 0x07;
2007 * Reverse the previously applied transliteration of non-ASCII characters
2008 * back to UTF-8. Used to protect data from corruption by broken web browsers
2009 * as listed in $wgBrowserBlackList.
2011 * @param string $invalue
2015 function unmakesafe( $invalue ) {
2017 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2018 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2022 $hexstring .= $invalue{$i};
2024 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2026 // Do some sanity checks. These aren't needed for reversability,
2027 // but should help keep the breakage down if the editor
2028 // breaks one of the entities whilst editing.
2029 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2030 $codepoint = hexdec($hexstring);
2031 $result .= codepointToUtf8( $codepoint );
2033 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2036 $result .= substr( $invalue, $i, 1 );
2039 // reverse the transform that we made for reversability reasons.
2040 return strtr( $result, array( "�" => "&#x" ) );
2043 function noCreatePermission() {
2045 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2046 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
2050 * If there are rows in the deletion log for this page, show them,
2051 * along with a nice little note for the user
2053 * @param OutputPage $out
2055 private function showDeletionLog( $out ) {
2056 $title = $this->mArticle
->getTitle();
2057 $reader = new LogReader(
2060 'page' => $title->getPrefixedText(),
2065 if( $reader->hasRows() ) {
2066 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2067 $out->addWikiText( wfMsg( 'recreate-deleted-warn' ) );
2068 $viewer = new LogViewer( $reader );
2069 $viewer->showList( $out );
2070 $out->addHtml( '</div>' );