3 * Contain the EditPage class
7 * Splitting edit page/HTML interface from Article...
8 * The actual database and text munging is still in Article,
9 * but it should get easier to call those from alternate
18 var $isConflict = false;
19 var $isCssJsSubpage = false;
20 var $deletedSinceEdit = false;
24 var $mTokenOk = false;
25 var $mTriedSave = false;
27 var $kblength = false;
28 var $missingComment = false;
29 var $missingSummary = false;
30 var $allowBlankSummary = false;
33 var $mPreviewTemplates;
36 var $save = false, $preview = false, $diff = false;
37 var $minoredit = false, $watchthis = false, $recreate = false;
38 var $textbox1 = '', $textbox2 = '', $summary = '';
39 var $edittime = '', $section = '', $starttime = '';
40 var $oldid = 0, $editintro = '', $scrolltop = null;
42 # Placeholders for text injection by hooks (must be HTML)
43 # extensions should take care to _append_ to the present value
44 public $editFormPageTop; // Before even the preview
45 public $editFormTextTop;
46 public $editFormTextAfterWarn;
47 public $editFormTextAfterTools;
48 public $editFormTextBottom;
54 function EditPage( $article ) {
55 $this->mArticle
=& $article;
57 $this->mTitle
=& $wgTitle;
59 # Placeholders for text injection by hooks (empty per default)
60 $this->editFormPageTop
=
61 $this->editFormTextTop
=
62 $this->editFormTextAfterWarn
=
63 $this->editFormTextAfterTools
=
64 $this->editFormTextBottom
= "";
68 * Fetch initial editing page content.
70 private function getContent( $def_text = '' ) {
71 global $wgOut, $wgRequest, $wgParser;
73 # Get variables from query string :P
74 $section = $wgRequest->getVal( 'section' );
75 $preload = $wgRequest->getVal( 'preload' );
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();
102 #Undoing a specific edit overrides section editing; section-editing
103 # doesn't work with undoing.
104 $undorev = Revision
::newFromId($undo);
105 $oldrev = $undorev ?
$undorev->getPrevious() : null;
107 #Sanity check, make sure it's the right page.
108 # Otherwise, $text will be left as-is.
109 if( !is_null($undorev)
110 && !is_null( $oldrev )
111 && $undorev->getPage() == $this->mArticle
->getID() ) {
113 $undorev_text = $undorev->getText();
114 $oldrev_text = $oldrev->getText();
115 $currev_text = $text;
117 #No use doing a merge if it's just a straight revert.
118 if ($currev_text != $undorev_text) {
119 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
121 $text = $oldrev_text;
125 // Failed basic sanity checks.
126 // Older revisions may have been removed since the link
127 // was created, or we may simply have got bogus input.
132 # Inform the user of our success and set an automatic edit summary
133 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
134 $firstrev = $oldrev->getNext();
135 # If we just undid one rev, use an autosummary
136 if ( $firstrev->mId
== $undo ) {
137 $this->summary
= wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
139 $this->formtype
= 'diff';
141 # Warn the user that something went wrong
142 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
144 } else if( $section != '' ) {
145 if( $section == 'new' ) {
146 $text = $this->getPreloadedText( $preload );
148 $text = $wgParser->getSection( $text, $section, $def_text );
153 wfProfileOut( __METHOD__
);
158 * Get the contents of a page from its title and remove includeonly tags
160 * @param $preload String: the title of the page.
161 * @return string The contents of the page.
163 private function getPreloadedText($preload) {
164 if ( $preload === '' )
167 $preloadTitle = Title
::newFromText( $preload );
168 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
169 $rev=Revision
::newFromTitle($preloadTitle);
170 if ( is_object( $rev ) ) {
171 $text = $rev->getText();
172 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
173 // its own mini-parser! -ævar
174 $text = preg_replace( '~</?includeonly>~', '', $text );
183 * This is the function that extracts metadata from the article body on the first view.
184 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
185 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
187 function extractMetaDataFromArticle () {
188 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
189 $this->mMetaData
= '' ;
190 if ( !$wgUseMetadataEdit ) return ;
191 if ( $wgMetadataWhitelist == '' ) return ;
193 $t = $this->getContent();
195 # MISSING : <nowiki> filtering
197 # Categories and language links
198 $t = explode ( "\n" , $t ) ;
199 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
200 $cat = $ll = array() ;
201 foreach ( $t AS $key => $x )
203 $y = trim ( strtolower ( $x ) ) ;
204 while ( substr ( $y , 0 , 2 ) == '[[' )
206 $y = explode ( ']]' , trim ( $x ) ) ;
207 $first = array_shift ( $y ) ;
208 $first = explode ( ':' , $first ) ;
209 $ns = array_shift ( $first ) ;
210 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
211 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
213 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
214 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
216 $x = implode ( ']]' , $y ) ;
218 $y = trim ( strtolower ( $x ) ) ;
222 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
223 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
224 $t = implode ( "\n" , $t ) ;
227 $sat = array () ; # stand-alone-templates; must be lowercase
228 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
229 $wl_article = new Article ( $wl_title ) ;
230 $wl = explode ( "\n" , $wl_article->getContent() ) ;
231 foreach ( $wl AS $x )
235 while ( substr ( $x , 0 , 1 ) == '*' )
238 $x = trim ( substr ( $x , 1 ) ) ;
242 $sat[] = strtolower ( $x ) ;
247 # Templates, but only some
248 $t = explode ( '{{' , $t ) ;
250 foreach ( $t AS $key => $x )
252 $y = explode ( '}}' , $x , 2 ) ;
253 if ( count ( $y ) == 2 )
256 $z = explode ( '|' , $z ) ;
257 $tn = array_shift ( $z ) ;
258 if ( in_array ( strtolower ( $tn ) , $sat ) )
260 $tl[] = '{{' . $y[0] . '}}' ;
262 $y = explode ( '}}' , $y[1] , 2 ) ;
264 else $t[$key] = '{{' . $x ;
266 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
269 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
270 $t = implode ( '' , $t ) ;
272 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
273 $this->mArticle
->mContent
= $t ;
274 $this->mMetaData
= $s ;
282 * This is the function that gets called for "action=edit". It
283 * sets up various member variables, then passes execution to
284 * another function, usually showEditForm()
286 * The edit form is self-submitting, so that when things like
287 * preview and edit conflicts occur, we get the same form back
288 * with the extra stuff added. Only when the final submission
289 * is made and all is well do we actually save and redirect to
290 * the newly-edited page.
293 global $wgOut, $wgUser, $wgRequest, $wgTitle;
294 global $wgEmailConfirmToEdit;
296 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
299 $fname = 'EditPage::edit';
300 wfProfileIn( $fname );
301 wfDebug( "$fname: enter\n" );
303 // this is not an article
304 $wgOut->setArticleFlag(false);
306 $this->importFormData( $wgRequest );
307 $this->firsttime
= false;
310 $this->livePreview();
311 wfProfileOut( $fname );
315 if ( ! $this->mTitle
->userCan( 'edit' ) ) {
316 wfDebug( "$fname: user can't edit\n" );
317 $wgOut->readOnlyPage( $this->getContent(), true );
318 wfProfileOut( $fname );
321 wfDebug( "$fname: Checking blocks\n" );
322 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
323 # When previewing, don't check blocked state - will get caught at save time.
324 # Also, check when starting edition is done against slave to improve performance.
325 wfDebug( "$fname: user is blocked\n" );
326 $this->blockedPage();
327 wfProfileOut( $fname );
330 if ( !$wgUser->isAllowed('edit') ) {
331 if ( $wgUser->isAnon() ) {
332 wfDebug( "$fname: user must log in\n" );
333 $this->userNotLoggedInPage();
334 wfProfileOut( $fname );
337 wfDebug( "$fname: read-only page\n" );
338 $wgOut->readOnlyPage( $this->getContent(), true );
339 wfProfileOut( $fname );
343 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
344 wfDebug("$fname: user must confirm e-mail address\n");
345 $this->userNotConfirmedPage();
346 wfProfileOut($fname);
349 if ( !$this->mTitle
->userCan( 'create' ) && !$this->mTitle
->exists() ) {
350 wfDebug( "$fname: no create permission\n" );
351 $this->noCreatePermission();
352 wfProfileOut( $fname );
355 if ( wfReadOnly() ) {
356 wfDebug( "$fname: read-only mode is engaged\n" );
357 if( $this->save ||
$this->preview
) {
358 $this->formtype
= 'preview';
359 } else if ( $this->diff
) {
360 $this->formtype
= 'diff';
362 $wgOut->readOnlyPage( $this->getContent() );
363 wfProfileOut( $fname );
368 $this->formtype
= 'save';
369 } else if ( $this->preview
) {
370 $this->formtype
= 'preview';
371 } else if ( $this->diff
) {
372 $this->formtype
= 'diff';
373 } else { # First time through
374 $this->firsttime
= true;
375 if( $this->previewOnOpen() ) {
376 $this->formtype
= 'preview';
378 $this->extractMetaDataFromArticle () ;
379 $this->formtype
= 'initial';
384 wfProfileIn( "$fname-business-end" );
386 $this->isConflict
= false;
387 // css / js subpages of user pages get a special treatment
388 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
389 $this->isValidCssJsSubpage
= $wgTitle->isValidCssJsSubpage();
391 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
392 * no matter it's current state
394 $this->deletedSinceEdit
= false;
395 if ( $this->edittime
!= '' ) {
396 /* Note that we rely on logging table, which hasn't been always there,
397 * but that doesn't matter, because this only applies to brand new
398 * deletes. This is done on every preview and save request. Move it further down
399 * to only perform it on saves
401 if ( $this->mTitle
->isDeleted() ) {
402 $this->lastDelete
= $this->getLastDelete();
403 if ( !is_null($this->lastDelete
) ) {
404 $deletetime = $this->lastDelete
->log_timestamp
;
405 if ( ($deletetime - $this->starttime
) > 0 ) {
406 $this->deletedSinceEdit
= true;
412 if(!$this->mTitle
->getArticleID() && ('initial' == $this->formtype ||
$this->firsttime
)) { # new article
415 if( $this->mTitle
->isTalkPage() ) {
416 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
419 # Attempt submission here. This will check for edit conflicts,
420 # and redundantly check for locked database, blocked IPs, etc.
421 # that edit() already checked just in case someone tries to sneak
422 # in the back door with a hand-edited submission URL.
424 if ( 'save' == $this->formtype
) {
425 if ( !$this->attemptSave() ) {
426 wfProfileOut( "$fname-business-end" );
427 wfProfileOut( $fname );
432 # First time through: get contents, set time for conflict
434 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
435 if ($this->initialiseForm() === false) {
436 $this->noSuchSectionPage();
437 wfProfileOut( "$fname-business-end" );
438 wfProfileOut( $fname );
441 if( !$this->mTitle
->getArticleId() )
442 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
445 $this->showEditForm();
446 wfProfileOut( "$fname-business-end" );
447 wfProfileOut( $fname );
451 * Return true if this page should be previewed when the edit form
452 * is initially opened.
456 function previewOnOpen() {
458 return $this->section
!= 'new' &&
459 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle
->exists() ) ||
460 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
461 !$this->mTitle
->exists() ) );
468 function importFormData( &$request ) {
469 global $wgLang, $wgUser;
470 $fname = 'EditPage::importFormData';
471 wfProfileIn( $fname );
473 if( $request->wasPosted() ) {
474 # These fields need to be checked for encoding.
475 # Also remove trailing whitespace, but don't remove _initial_
476 # whitespace from the text boxes. This may be significant formatting.
477 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
478 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
479 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
480 # Truncate for whole multibyte characters. +5 bytes for ellipsis
481 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
483 $this->edittime
= $request->getVal( 'wpEdittime' );
484 $this->starttime
= $request->getVal( 'wpStarttime' );
486 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
488 if( is_null( $this->edittime
) ) {
489 # If the form is incomplete, force to preview.
490 wfDebug( "$fname: Form data appears to be incomplete\n" );
491 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
492 $this->preview
= true;
494 /* Fallback for live preview */
495 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
496 $this->diff
= $request->getCheck( 'wpDiff' );
498 // Remember whether a save was requested, so we can indicate
499 // if we forced preview due to session failure.
500 $this->mTriedSave
= !$this->preview
;
502 if ( $this->tokenOk( $request ) ) {
503 # Some browsers will not report any submit button
504 # if the user hits enter in the comment box.
505 # The unmarked state will be assumed to be a save,
506 # if the form seems otherwise complete.
507 wfDebug( "$fname: Passed token check.\n" );
508 } else if ( $this->diff
) {
509 # Failed token check, but only requested "Show Changes".
510 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
512 # Page might be a hack attempt posted from
513 # an external site. Preview instead of saving.
514 wfDebug( "$fname: Failed token check; forcing preview\n" );
515 $this->preview
= true;
518 $this->save
= ! ( $this->preview
OR $this->diff
);
519 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
520 $this->edittime
= null;
523 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
524 $this->starttime
= null;
527 $this->recreate
= $request->getCheck( 'wpRecreate' );
529 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
530 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
532 # Don't force edit summaries when a user is editing their own user or talk page
533 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
534 $this->allowBlankSummary
= true;
536 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
539 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
541 # Not a posted form? Start with nothing.
542 wfDebug( "$fname: Not a posted form.\n" );
543 $this->textbox1
= '';
544 $this->textbox2
= '';
545 $this->mMetaData
= '';
547 $this->edittime
= '';
548 $this->starttime
= wfTimestampNow();
549 $this->preview
= false;
552 $this->minoredit
= false;
553 $this->watchthis
= false;
554 $this->recreate
= false;
557 $this->oldid
= $request->getInt( 'oldid' );
559 # Section edit can come from either the form or a link
560 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
562 $this->live
= $request->getCheck( 'live' );
563 $this->editintro
= $request->getText( 'editintro' );
565 wfProfileOut( $fname );
569 * Make sure the form isn't faking a user's credentials.
571 * @param $request WebRequest
575 function tokenOk( &$request ) {
577 if( $wgUser->isAnon() ) {
578 # Anonymous users may not have a session
579 # open. Check for suffix anyway.
580 $this->mTokenOk
= ( EDIT_TOKEN_SUFFIX
== $request->getVal( 'wpEditToken' ) );
582 $this->mTokenOk
= $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
584 return $this->mTokenOk
;
588 function showIntro() {
589 global $wgOut, $wgUser;
590 $addstandardintro=true;
591 if($this->editintro
) {
592 $introtitle=Title
::newFromText($this->editintro
);
593 if(isset($introtitle) && $introtitle->userCanRead()) {
594 $rev=Revision
::newFromTitle($introtitle);
596 $wgOut->addSecondaryWikiText($rev->getText());
597 $addstandardintro=false;
601 if($addstandardintro) {
602 if ( $wgUser->isLoggedIn() )
603 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
605 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
611 * @return bool false if output is done, true if the rest of the form should be displayed
613 function attemptSave() {
614 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
615 global $wgMaxArticleSize;
617 $fname = 'EditPage::attemptSave';
618 wfProfileIn( $fname );
619 wfProfileIn( "$fname-checks" );
621 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
623 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
627 # Reintegrate metadata
628 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
629 $this->mMetaData
= '' ;
633 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
634 $this->spamPage ( $matches[0] );
635 wfProfileOut( "$fname-checks" );
636 wfProfileOut( $fname );
639 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
640 # Error messages or other handling should be performed by the filter function
641 wfProfileOut( $fname );
642 wfProfileOut( "$fname-checks" );
645 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
) ) ) {
646 # Error messages etc. could be handled within the hook...
647 wfProfileOut( $fname );
648 wfProfileOut( "$fname-checks" );
650 } elseif( $this->hookError
!= '' ) {
651 # ...or the hook could be expecting us to produce an error
652 wfProfileOut( "$fname-checks " );
653 wfProfileOut( $fname );
656 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
657 # Check block state against master, thus 'false'.
658 $this->blockedPage();
659 wfProfileOut( "$fname-checks" );
660 wfProfileOut( $fname );
663 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
664 if ( $this->kblength
> $wgMaxArticleSize ) {
665 // Error will be displayed by showEditForm()
666 $this->tooBig
= true;
667 wfProfileOut( "$fname-checks" );
668 wfProfileOut( $fname );
672 if ( !$wgUser->isAllowed('edit') ) {
673 if ( $wgUser->isAnon() ) {
674 $this->userNotLoggedInPage();
675 wfProfileOut( "$fname-checks" );
676 wfProfileOut( $fname );
680 $wgOut->readOnlyPage();
681 wfProfileOut( "$fname-checks" );
682 wfProfileOut( $fname );
687 if ( wfReadOnly() ) {
688 $wgOut->readOnlyPage();
689 wfProfileOut( "$fname-checks" );
690 wfProfileOut( $fname );
693 if ( $wgUser->pingLimiter() ) {
694 $wgOut->rateLimited();
695 wfProfileOut( "$fname-checks" );
696 wfProfileOut( $fname );
700 # If the article has been deleted while editing, don't save it without
702 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
703 wfProfileOut( "$fname-checks" );
704 wfProfileOut( $fname );
708 wfProfileOut( "$fname-checks" );
710 # If article is new, insert it.
711 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
714 // Late check for create permission, just in case *PARANOIA*
715 if ( !$this->mTitle
->userCan( 'create' ) ) {
716 wfDebug( "$fname: no create permission\n" );
717 $this->noCreatePermission();
718 wfProfileOut( $fname );
722 # Don't save a new article if it's blank.
723 if ( ( '' == $this->textbox1
) ) {
724 $wgOut->redirect( $this->mTitle
->getFullURL() );
725 wfProfileOut( $fname );
729 $isComment=($this->section
=='new');
730 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
731 $this->minoredit
, $this->watchthis
, false, $isComment);
733 wfProfileOut( $fname );
737 # Article exists. Check for edit conflict.
739 $this->mArticle
->clear(); # Force reload of dates, etc.
740 $this->mArticle
->forUpdate( true ); # Lock the article
742 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
744 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
745 $this->isConflict
= true;
746 if( $this->section
== 'new' ) {
747 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
748 $this->mArticle
->getComment() == $this->summary
) {
749 // Probably a duplicate submission of a new comment.
750 // This can happen when squid resends a request after
751 // a timeout but the first one actually went through.
752 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
754 // New comment; suppress conflict.
755 $this->isConflict
= false;
756 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
760 $userid = $wgUser->getID();
762 if ( $this->isConflict
) {
763 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
764 $this->mArticle
->getTimestamp() . "'\n" );
765 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
768 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
769 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
771 if( is_null( $text ) ) {
772 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
773 $this->isConflict
= true;
774 $text = $this->textbox1
;
777 # Suppress edit conflict with self, except for section edits where merging is required.
778 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
779 wfDebug( "Suppressing edit conflict, same user.\n" );
780 $this->isConflict
= false;
782 # switch from section editing to normal editing in edit conflict
783 if($this->isConflict
) {
785 if( $this->mergeChangesInto( $text ) ){
786 // Successful merge! Maybe we should tell the user the good news?
787 $this->isConflict
= false;
788 wfDebug( "Suppressing edit conflict, successful merge.\n" );
791 $this->textbox1
= $text;
792 wfDebug( "Keeping edit conflict, failed merge.\n" );
797 if ( $this->isConflict
) {
798 wfProfileOut( $fname );
802 $oldtext = $this->mArticle
->getContent();
804 # Handle the user preference to force summaries here, but not for null edits
805 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary')
806 && 0 != strcmp($oldtext, $text) && !Article
::getRedirectAutosummary( $text )) {
807 if( md5( $this->summary
) == $this->autoSumm
) {
808 $this->missingSummary
= true;
809 wfProfileOut( $fname );
814 #And a similar thing for new sections
815 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
816 if (trim($this->summary
) == '') {
817 $this->missingSummary
= true;
818 wfProfileOut( $fname );
824 wfProfileIn( "$fname-sectionanchor" );
826 if( $this->section
== 'new' ) {
827 if ( $this->textbox1
== '' ) {
828 $this->missingComment
= true;
831 if( $this->summary
!= '' ) {
832 $sectionanchor = $this->sectionAnchor( $this->summary
);
834 } elseif( $this->section
!= '' ) {
835 # Try to get a section anchor from the section source, redirect to edited section if header found
836 # XXX: might be better to integrate this into Article::replaceSection
837 # for duplicate heading checking and maybe parsing
838 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
839 # we can't deal with anchors, includes, html etc in the header for now,
840 # headline would need to be parsed to improve this
841 if($hasmatch and strlen($matches[2]) > 0) {
842 $sectionanchor = $this->sectionAnchor( $matches[2] );
845 wfProfileOut( "$fname-sectionanchor" );
847 // Save errors may fall down to the edit form, but we've now
848 // merged the section into full text. Clear the section field
849 // so that later submission of conflict forms won't try to
850 // replace that into a duplicated mess.
851 $this->textbox1
= $text;
854 // Check for length errors again now that the section is merged in
855 $this->kblength
= (int)(strlen( $text ) / 1024);
856 if ( $this->kblength
> $wgMaxArticleSize ) {
857 $this->tooBig
= true;
858 wfProfileOut( $fname );
862 # update the article here
863 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
864 $this->watchthis
, '', $sectionanchor ) ) {
865 wfProfileOut( $fname );
868 $this->isConflict
= true;
870 wfProfileOut( $fname );
875 * Initialise form fields in the object
876 * Called on the first invocation, e.g. when a user clicks an edit link
878 function initialiseForm() {
879 $this->edittime
= $this->mArticle
->getTimestamp();
881 $this->textbox1
= $this->getContent(false);
882 if ($this->textbox1
=== false) return false;
884 if ( !$this->mArticle
->exists() && $this->mArticle
->mTitle
->getNamespace() == NS_MEDIAWIKI
)
885 $this->textbox1
= wfMsgWeirdKey( $this->mArticle
->mTitle
->getText() );
891 * Send the edit form and related headers to $wgOut
892 * @param $formCallback Optional callable that takes an OutputPage
893 * parameter; will be called during form output
894 * near the top, for captchas and the like.
896 function showEditForm( $formCallback=null ) {
897 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
899 $fname = 'EditPage::showEditForm';
900 wfProfileIn( $fname );
902 $sk = $wgUser->getSkin();
904 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
906 $wgOut->setRobotpolicy( 'noindex,nofollow' );
908 # Enabled article-related sidebar, toplinks, etc.
909 $wgOut->setArticleRelated( true );
911 if ( $this->isConflict
) {
912 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
913 $wgOut->setPageTitle( $s );
914 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
916 $this->textbox2
= $this->textbox1
;
917 $this->textbox1
= $this->getContent();
918 $this->edittime
= $this->mArticle
->getTimestamp();
921 if( $this->section
!= '' ) {
922 if( $this->section
== 'new' ) {
923 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
925 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
927 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
928 preg_match( "/^(=+)(.+)\\1/mi",
931 if( !empty( $matches[2] ) ) {
932 $this->summary
= "/* ". trim($matches[2])." */ ";
937 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
939 $wgOut->setPageTitle( $s );
941 if ( $this->missingComment
) {
942 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
945 if( $this->missingSummary
&& $this->section
!= 'new' ) {
946 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
949 if( $this->missingSummary
&& $this->section
== 'new' ) {
950 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
953 if( !$this->hookError
== '' ) {
954 $wgOut->addWikiText( $this->hookError
);
957 if ( !$this->checkUnicodeCompliantBrowser() ) {
958 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
960 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
961 // Let sysop know that this will make private content public if saved
962 if( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
963 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
965 if( !$this->mArticle
->mRevision
->isCurrent() ) {
966 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
967 $wgOut->addWikiText( wfMsg( 'editingold' ) );
973 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
974 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
975 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
977 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
978 # Check the skin exists
979 if( $this->isValidCssJsSubpage
) {
980 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
982 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
987 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
988 # Show a warning if editing an interface message
989 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
990 } elseif( $this->mTitle
->isProtected( 'edit' ) ) {
991 # Is the title semi-protected?
992 if( $this->mTitle
->isSemiProtected() ) {
993 $notice = wfMsg( 'semiprotectedpagewarning' );
994 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' )
997 # It's either cascading protection or regular protection; work out which
998 list($cascadeSources, $restrictions) = $this->mTitle
->getCascadeProtectionSources();
999 if ( !$cascadeSources ||
count( $cascadeSources ) == 0 ) {
1000 # Regular protection
1001 $notice = wfMsg( 'protectedpagewarning' );
1003 # Cascading protection; explain, and list the titles responsible
1004 $notice = wfMsg( 'cascadeprotectedwarning' ) . "\n";
1005 foreach( $cascadeSources as $source )
1006 $notice .= '* [[:' . $source->getPrefixedText() . "]]\n";
1009 $wgOut->addWikiText( $notice );
1012 if ( $this->kblength
=== false ) {
1013 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1015 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1016 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgMaxArticleSize ) );
1017 } elseif( $this->kblength
> 29 ) {
1018 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) ) );
1021 #need to parse the preview early so that we know which templates are used,
1022 #otherwise users with "show preview after edit box" will get a blank list
1023 if ( $this->formtype
== 'preview' ) {
1024 $previewOutput = $this->getPreviewText();
1027 $rows = $wgUser->getIntOption( 'rows' );
1028 $cols = $wgUser->getIntOption( 'cols' );
1030 $ew = $wgUser->getOption( 'editwidth' );
1031 if ( $ew ) $ew = " style=\"width:100%\"";
1034 $q = 'action=submit';
1035 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1036 $action = $this->mTitle
->escapeLocalURL( $q );
1038 $summary = wfMsg('summary');
1039 $subject = wfMsg('subject');
1041 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
1042 wfMsgExt('cancel', array('parseinline')) );
1043 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1044 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1045 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1046 htmlspecialchars( wfMsg( 'newwindow' ) );
1048 global $wgRightsText;
1049 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1050 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
1051 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1052 $wgRightsText ) . "\n</div>";
1054 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1055 # prepare toolbar for edit buttons
1056 $toolbar = $this->getEditToolbar();
1061 // activate checkboxes if user wants them to be always active
1062 if( !$this->preview
&& !$this->diff
) {
1063 # Sort out the "watch" checkbox
1064 if( $wgUser->getOption( 'watchdefault' ) ) {
1066 $this->watchthis
= true;
1067 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1069 $this->watchthis
= true;
1070 } elseif( $this->mTitle
->userIsWatching() ) {
1072 $this->watchthis
= true;
1075 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1078 $wgOut->addHTML( $this->editFormPageTop
);
1080 if ( $wgUser->getOption( 'previewontop' ) ) {
1082 if ( 'preview' == $this->formtype
) {
1083 $this->showPreview( $previewOutput );
1085 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1088 if ( 'diff' == $this->formtype
) {
1089 $wgOut->addHTML( $this->getDiff() );
1094 $wgOut->addHTML( $this->editFormTextTop
);
1096 # if this is a comment, show a subject line at the top, which is also the edit summary.
1097 # Otherwise, show a summary field at the bottom
1098 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1099 if( $this->section
== 'new' ) {
1100 $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 />";
1102 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1103 $summarypreview = '';
1105 $commentsubject = '';
1106 $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 />";
1107 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1108 $subjectpreview = '';
1111 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1112 if( !$this->preview
&& !$this->diff
) {
1113 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1115 $templates = ($this->preview ||
$this->section
) ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1116 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1118 global $wgUseMetadataEdit ;
1119 if ( $wgUseMetadataEdit ) {
1120 $metadata = $this->mMetaData
;
1121 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1122 $top = wfMsgWikiHtml( 'metadata_help' );
1123 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1125 else $metadata = "" ;
1129 if ($this->deletedSinceEdit
) {
1130 if ( 'save' != $this->formtype
) {
1131 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1133 // Hide the toolbar and edit area, use can click preview to get it back
1134 // Add an confirmation checkbox and explanation.
1136 $hidden = 'type="hidden" style="display:none;"';
1137 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1139 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1140 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1146 $checkboxes = self
::getCheckboxes( $tabindex, $sk,
1147 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1149 $checkboxhtml = implode( $checkboxes, "\n" );
1151 $buttons = $this->getEditButtons( $tabindex );
1152 $buttonshtml = implode( $buttons, "\n" );
1154 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1155 ?
'' : Xml
::hidden( 'safemode', '1' );
1157 $wgOut->addHTML( <<<END
1159 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1163 if( is_callable( $formCallback ) ) {
1164 call_user_func_array( $formCallback, array( &$wgOut ) );
1167 // Put these up at the top to ensure they aren't lost on early form submission
1169 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1170 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1171 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1172 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1174 $wgOut->addHTML( <<<END
1178 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1179 cols='{$cols}'{$ew} $hidden>
1181 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
1186 $wgOut->addWikiText( $copywarn );
1187 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1197 "<div class='editButtons'>
1199 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1200 </div><!-- editButtons -->
1201 </div><!-- editOptions -->");
1203 $wgOut->addHtml( '<div class="mw-editTools">' );
1204 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1205 $wgOut->addHtml( '</div>' );
1207 $wgOut->addHTML( $this->editFormTextAfterTools
);
1210 <div class='templatesUsed'>
1211 {$formattedtemplates}
1216 * To make it harder for someone to slip a user a page
1217 * which submits an edit form to the wiki without their
1218 * knowledge, a random token is associated with the login
1219 * session. If it's not passed back with the submission,
1220 * we won't save the page, or render user JavaScript and
1223 * For anon editors, who may not have a session, we just
1224 * include the constant suffix to prevent editing from
1225 * broken text-mangling proxies.
1227 if ( $wgUser->isLoggedIn() )
1228 $token = htmlspecialchars( $wgUser->editToken() );
1230 $token = EDIT_TOKEN_SUFFIX
;
1231 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1234 # If a blank edit summary was previously provided, and the appropriate
1235 # user preference is active, pass a hidden tag here. This will stop the
1236 # user being bounced back more than once in the event that a summary
1238 if( $this->missingSummary
) {
1239 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1242 # For a bit more sophisticated detection of blank summaries, hash the
1243 # automatic one and pass that in a hidden field.
1244 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1245 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1247 if ( $this->isConflict
) {
1248 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1250 $de = new DifferenceEngine( $this->mTitle
);
1251 $de->setText( $this->textbox2
, $this->textbox1
);
1252 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1254 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1255 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1256 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1258 $wgOut->addHTML( $this->editFormTextBottom
);
1259 $wgOut->addHTML( "</form>\n" );
1260 if ( !$wgUser->getOption( 'previewontop' ) ) {
1262 if ( $this->formtype
== 'preview') {
1263 $this->showPreview( $previewOutput );
1265 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1268 if ( $this->formtype
== 'diff') {
1269 $wgOut->addHTML( $this->getDiff() );
1274 wfProfileOut( $fname );
1278 * Append preview output to $wgOut.
1279 * Includes category rendering if this is a category page.
1281 * @param string $text The HTML to be output for the preview.
1283 private function showPreview( $text ) {
1286 $wgOut->addHTML( '<div id="wikiPreview">' );
1287 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1288 $this->mArticle
->openShowCategory();
1290 $wgOut->addHTML( $text );
1291 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1292 $this->mArticle
->closeShowCategory();
1294 $wgOut->addHTML( '</div>' );
1298 * Live Preview lets us fetch rendered preview page content and
1299 * add it to the page without refreshing the whole page.
1300 * If not supported by the browser it will fall through to the normal form
1301 * submission method.
1303 * This function outputs a script tag to support live preview, and
1304 * returns an onclick handler which should be added to the attributes
1305 * of the preview button
1307 function doLivePreviewScript() {
1308 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1309 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1310 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1311 '"></script>' . "\n" );
1312 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1313 return "return !livePreview(" .
1314 "getElementById('wikiPreview')," .
1315 "editform.wpTextbox1.value," .
1316 '"' . $liveAction . '"' . ")";
1319 function getLastDelete() {
1320 $dbr = wfGetDB( DB_SLAVE
);
1321 $fname = 'EditPage::getLastDelete';
1322 $res = $dbr->select(
1323 array( 'logging', 'user' ),
1333 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1334 'log_title' => $this->mTitle
->getDBkey(),
1335 'log_type' => 'delete',
1336 'log_action' => 'delete',
1337 'user_id=log_user' ),
1339 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1341 if($dbr->numRows($res) == 1) {
1342 while ( $x = $dbr->fetchObject ( $res ) )
1344 $dbr->freeResult ( $res ) ;
1354 function getPreviewText() {
1355 global $wgOut, $wgUser, $wgTitle, $wgParser;
1357 $fname = 'EditPage::getPreviewText';
1358 wfProfileIn( $fname );
1360 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1361 $msg = 'session_fail_preview';
1363 $msg = 'previewnote';
1365 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1366 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1367 if ( $this->isConflict
) {
1368 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1371 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1372 $parserOptions->setEditSection( false );
1375 if( $wgRawHtml && !$this->mTokenOk
) {
1376 // Could be an offsite preview attempt. This is very unsafe if
1377 // HTML is enabled, as it could be an attack.
1378 return $wgOut->parse( "<div class='previewnote'>" .
1379 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1382 # don't parse user css/js, show message about preview
1383 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1385 if ( $this->isCssJsSubpage
) {
1386 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1387 $previewtext = wfMsg('usercsspreview');
1388 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1389 $previewtext = wfMsg('userjspreview');
1391 $parserOptions->setTidy(true);
1392 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1393 $wgOut->addHTML( $parserOutput->mText
);
1394 wfProfileOut( $fname );
1395 return $previewhead;
1397 $toparse = $this->textbox1
;
1399 # If we're adding a comment, we need to show the
1400 # summary as the headline
1401 if($this->section
=="new" && $this->summary
!="") {
1402 $toparse="== {$this->summary} ==\n\n".$toparse;
1405 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1406 $parserOptions->setTidy(true);
1407 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1408 $wgTitle, $parserOptions );
1410 $previewHTML = $parserOutput->getText();
1411 $wgOut->addParserOutputNoText( $parserOutput );
1413 foreach ( $parserOutput->getTemplates() as $ns => $template)
1414 foreach ( array_keys( $template ) as $dbk)
1415 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1417 wfProfileOut( $fname );
1418 return $previewhead . $previewHTML;
1423 * Call the stock "user is blocked" page
1425 function blockedPage() {
1426 global $wgOut, $wgUser;
1427 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1429 # If the user made changes, preserve them when showing the markup
1430 # (This happens when a user is blocked during edit, for instance)
1431 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1433 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1435 $source = $this->textbox1
;
1438 # Spit out the source or the user's modified version
1439 if( $source !== false ) {
1440 $rows = $wgUser->getOption( 'rows' );
1441 $cols = $wgUser->getOption( 'cols' );
1442 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1443 $wgOut->addHtml( '<hr />' );
1444 $wgOut->addWikiText( wfMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() ) );
1445 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1450 * Produce the stock "please login to edit pages" page
1452 function userNotLoggedInPage() {
1453 global $wgUser, $wgOut;
1454 $skin = $wgUser->getSkin();
1456 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1457 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle
->getPrefixedUrl() );
1459 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1460 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1461 $wgOut->setArticleRelated( false );
1463 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1464 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1468 * Creates a basic error page which informs the user that
1469 * they have to validate their email address before being
1472 function userNotConfirmedPage() {
1475 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1476 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1477 $wgOut->setArticleRelated( false );
1479 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1480 $wgOut->returnToMain( false );
1484 * Creates a basic error page which informs the user that
1485 * they have attempted to edit a nonexistant section.
1487 function noSuchSectionPage() {
1490 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1491 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1492 $wgOut->setArticleRelated( false );
1494 $wgOut->addWikiText( wfMsg( 'nosuchsectiontext', $this->section
) );
1495 $wgOut->returnToMain( false );
1499 * Produce the stock "your edit contains spam" page
1501 * @param $match Text which triggered one or more filters
1503 function spamPage( $match = false ) {
1506 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1507 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1508 $wgOut->setArticleRelated( false );
1510 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1512 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1514 $wgOut->returnToMain( false );
1521 function mergeChangesInto( &$editText ){
1522 $fname = 'EditPage::mergeChangesInto';
1523 wfProfileIn( $fname );
1525 $db = wfGetDB( DB_MASTER
);
1527 // This is the revision the editor started from
1528 $baseRevision = Revision
::loadFromTimestamp(
1529 $db, $this->mArticle
->mTitle
, $this->edittime
);
1530 if( is_null( $baseRevision ) ) {
1531 wfProfileOut( $fname );
1534 $baseText = $baseRevision->getText();
1536 // The current state, we want to merge updates into it
1537 $currentRevision = Revision
::loadFromTitle(
1538 $db, $this->mArticle
->mTitle
);
1539 if( is_null( $currentRevision ) ) {
1540 wfProfileOut( $fname );
1543 $currentText = $currentRevision->getText();
1546 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1547 $editText = $result;
1548 wfProfileOut( $fname );
1551 wfProfileOut( $fname );
1557 * Check if the browser is on a blacklist of user-agents known to
1558 * mangle UTF-8 data on form submission. Returns true if Unicode
1559 * should make it through, false if it's known to be a problem.
1563 function checkUnicodeCompliantBrowser() {
1564 global $wgBrowserBlackList;
1565 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1566 // No User-Agent header sent? Trust it by default...
1569 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1570 foreach ( $wgBrowserBlackList as $browser ) {
1571 if ( preg_match($browser, $currentbrowser) ) {
1579 * Format an anchor fragment as it would appear for a given section name
1580 * @param string $text
1584 function sectionAnchor( $text ) {
1585 $headline = Sanitizer
::decodeCharReferences( $text );
1587 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1588 $headline = trim( $headline );
1589 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1590 $replacearray = array(
1595 array_keys( $replacearray ),
1596 array_values( $replacearray ),
1601 * Shows a bulletin board style toolbar for common editing functions.
1602 * It can be disabled in the user preferences.
1603 * The necessary JavaScript code can be found in style/wikibits.js.
1605 function getEditToolbar() {
1606 global $wgStylePath, $wgContLang, $wgJsMimeType;
1609 * toolarray an array of arrays which each include the filename of
1610 * the button image (without path), the opening tag, the closing tag,
1611 * and optionally a sample text that is inserted between the two when no
1612 * selection is highlighted.
1613 * The tip text is shown when the user moves the mouse over the button.
1615 * Already here are accesskeys (key), which are not used yet until someone
1616 * can figure out a way to make them work in IE. However, we should make
1617 * sure these keys are not defined on the edit page.
1620 array( 'image' => 'button_bold.png',
1621 'id' => 'mw-editbutton-bold',
1622 'open' => '\\\'\\\'\\\'',
1623 'close' => '\\\'\\\'\\\'',
1624 'sample'=> wfMsg('bold_sample'),
1625 'tip' => wfMsg('bold_tip'),
1628 array( 'image' => 'button_italic.png',
1629 'id' => 'mw-editbutton-italic',
1630 'open' => '\\\'\\\'',
1631 'close' => '\\\'\\\'',
1632 'sample'=> wfMsg('italic_sample'),
1633 'tip' => wfMsg('italic_tip'),
1636 array( 'image' => 'button_link.png',
1637 'id' => 'mw-editbutton-link',
1640 'sample'=> wfMsg('link_sample'),
1641 'tip' => wfMsg('link_tip'),
1644 array( 'image' => 'button_extlink.png',
1645 'id' => 'mw-editbutton-extlink',
1648 'sample'=> wfMsg('extlink_sample'),
1649 'tip' => wfMsg('extlink_tip'),
1652 array( 'image' => 'button_headline.png',
1653 'id' => 'mw-editbutton-headline',
1655 'close' => " ==\\n",
1656 'sample'=> wfMsg('headline_sample'),
1657 'tip' => wfMsg('headline_tip'),
1660 array( 'image' => 'button_image.png',
1661 'id' => 'mw-editbutton-image',
1662 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1664 'sample'=> wfMsg('image_sample'),
1665 'tip' => wfMsg('image_tip'),
1668 array( 'image' => 'button_media.png',
1669 'id' => 'mw-editbutton-media',
1670 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1672 'sample'=> wfMsg('media_sample'),
1673 'tip' => wfMsg('media_tip'),
1676 array( 'image' => 'button_math.png',
1677 'id' => 'mw-editbutton-math',
1679 'close' => "<\\/math>",
1680 'sample'=> wfMsg('math_sample'),
1681 'tip' => wfMsg('math_tip'),
1684 array( 'image' => 'button_nowiki.png',
1685 'id' => 'mw-editbutton-nowiki',
1686 'open' => "<nowiki>",
1687 'close' => "<\\/nowiki>",
1688 'sample'=> wfMsg('nowiki_sample'),
1689 'tip' => wfMsg('nowiki_tip'),
1692 array( 'image' => 'button_sig.png',
1693 'id' => 'mw-editbutton-signature',
1697 'tip' => wfMsg('sig_tip'),
1700 array( 'image' => 'button_hr.png',
1701 'id' => 'mw-editbutton-hr',
1702 'open' => "\\n----\\n",
1705 'tip' => wfMsg('hr_tip'),
1709 $toolbar = "<div id='toolbar'>\n";
1710 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1712 foreach($toolarray as $tool) {
1714 $cssId = $tool['id'];
1715 $image=$wgStylePath.'/common/images/'.$tool['image'];
1716 $open=$tool['open'];
1717 $close=$tool['close'];
1718 $sample = wfEscapeJsString( $tool['sample'] );
1720 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1721 // Older browsers show a "speedtip" type message only for ALT.
1722 // Ideally these should be different, realistically they
1723 // probably don't need to be.
1724 $tip = wfEscapeJsString( $tool['tip'] );
1726 #$key = $tool["key"];
1728 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1731 $toolbar.="/*]]>*/\n</script>";
1732 $toolbar.="\n</div>";
1737 * Returns an array of html code of the following checkboxes:
1740 * @param $tabindex Current tabindex
1741 * @param $skin Skin object
1742 * @param $checked Array of checkbox => bool, where bool indicates the checked
1743 * status of the checkbox
1747 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1750 $checkboxes = array();
1752 $checkboxes['minor'] = '';
1753 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1754 if ( $wgUser->isAllowed('minoredit') ) {
1756 'tabindex' => ++
$tabindex,
1757 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1758 'id' => 'wpMinoredit',
1760 $checkboxes['minor'] =
1761 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1762 " <label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1765 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1766 $checkboxes['watch'] = '';
1767 if ( $wgUser->isLoggedIn() ) {
1769 'tabindex' => ++
$tabindex,
1770 'accesskey' => wfMsg( 'accesskey-watch' ),
1771 'id' => 'wpWatchthis',
1773 $checkboxes['watch'] =
1774 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1775 " <label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1781 * Returns an array of html code of the following buttons:
1782 * save, diff, preview and live
1784 * @param $tabindex Current tabindex
1788 public function getEditButtons(&$tabindex) {
1789 global $wgLivePreview, $wgUser;
1797 'tabindex' => ++
$tabindex,
1798 'value' => wfMsg('savearticle'),
1799 'accesskey' => wfMsg('accesskey-save'),
1800 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1802 $buttons['save'] = wfElement('input', $temp, '');
1804 ++
$tabindex; // use the same for preview and live preview
1805 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1807 'id' => 'wpPreview',
1808 'name' => 'wpPreview',
1810 'tabindex' => $tabindex,
1811 'value' => wfMsg('showpreview'),
1813 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1814 'style' => 'display: none;',
1816 $buttons['preview'] = wfElement('input', $temp, '');
1819 'id' => 'wpLivePreview',
1820 'name' => 'wpLivePreview',
1822 'tabindex' => $tabindex,
1823 'value' => wfMsg('showlivepreview'),
1824 'accesskey' => wfMsg('accesskey-preview'),
1826 'onclick' => $this->doLivePreviewScript(),
1828 $buttons['live'] = wfElement('input', $temp, '');
1831 'id' => 'wpPreview',
1832 'name' => 'wpPreview',
1834 'tabindex' => $tabindex,
1835 'value' => wfMsg('showpreview'),
1836 'accesskey' => wfMsg('accesskey-preview'),
1837 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1839 $buttons['preview'] = wfElement('input', $temp, '');
1840 $buttons['live'] = '';
1847 'tabindex' => ++
$tabindex,
1848 'value' => wfMsg('showdiff'),
1849 'accesskey' => wfMsg('accesskey-diff'),
1850 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1852 $buttons['diff'] = wfElement('input', $temp, '');
1858 * Output preview text only. This can be sucked into the edit page
1859 * via JavaScript, and saves the server time rendering the skin as
1860 * well as theoretically being more robust on the client (doesn't
1861 * disturb the edit box's undo history, won't eat your text on
1864 * @todo This doesn't include category or interlanguage links.
1865 * Would need to enhance it a bit, <s>maybe wrap them in XML
1866 * or something...</s> that might also require more skin
1867 * initialization, so check whether that's a problem.
1869 function livePreview() {
1872 header( 'Content-type: text/xml; charset=utf-8' );
1873 header( 'Cache-control: no-cache' );
1876 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1877 Xml
::openElement( 'livepreview' ) .
1878 Xml
::element( 'preview', null, $this->getPreviewText() ) .
1879 Xml
::element( 'br', array( 'style' => 'clear: both;' ) ) .
1880 Xml
::closeElement( 'livepreview' );
1886 * Get a diff between the current contents of the edit box and the
1887 * version of the page we're editing from.
1889 * If this is a section edit, we'll replace the section as for final
1890 * save and then make a comparison.
1892 * @return string HTML
1894 function getDiff() {
1895 $oldtext = $this->mArticle
->fetchContent();
1896 $newtext = $this->mArticle
->replaceSection(
1897 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1898 $newtext = $this->mArticle
->preSaveTransform( $newtext );
1899 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1900 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1901 if ( $oldtext !== false ||
$newtext != '' ) {
1902 $de = new DifferenceEngine( $this->mTitle
);
1903 $de->setText( $oldtext, $newtext );
1904 $difftext = $de->getDiff( $oldtitle, $newtitle );
1909 return '<div id="wikiDiff">' . $difftext . '</div>';
1913 * Filter an input field through a Unicode de-armoring process if it
1914 * came from an old browser with known broken Unicode editing issues.
1916 * @param WebRequest $request
1917 * @param string $field
1921 function safeUnicodeInput( $request, $field ) {
1922 $text = rtrim( $request->getText( $field ) );
1923 return $request->getBool( 'safemode' )
1924 ?
$this->unmakesafe( $text )
1929 * Filter an output field through a Unicode armoring process if it is
1930 * going to an old browser with known broken Unicode editing issues.
1932 * @param string $text
1936 function safeUnicodeOutput( $text ) {
1938 $codedText = $wgContLang->recodeForEdit( $text );
1939 return $this->checkUnicodeCompliantBrowser()
1941 : $this->makesafe( $codedText );
1945 * A number of web browsers are known to corrupt non-ASCII characters
1946 * in a UTF-8 text editing environment. To protect against this,
1947 * detected browsers will be served an armored version of the text,
1948 * with non-ASCII chars converted to numeric HTML character references.
1950 * Preexisting such character references will have a 0 added to them
1951 * to ensure that round-trips do not alter the original data.
1953 * @param string $invalue
1957 function makesafe( $invalue ) {
1958 // Armor existing references for reversability.
1959 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1964 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1965 $bytevalue = ord( $invalue{$i} );
1966 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1967 $result .= chr( $bytevalue );
1969 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1970 $working = $working << 6;
1971 $working +
= ($bytevalue & 0x3F);
1973 if( $bytesleft <= 0 ) {
1974 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1976 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1977 $working = $bytevalue & 0x1F;
1979 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1980 $working = $bytevalue & 0x0F;
1982 } else { //1111 0xxx
1983 $working = $bytevalue & 0x07;
1991 * Reverse the previously applied transliteration of non-ASCII characters
1992 * back to UTF-8. Used to protect data from corruption by broken web browsers
1993 * as listed in $wgBrowserBlackList.
1995 * @param string $invalue
1999 function unmakesafe( $invalue ) {
2001 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2002 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2006 $hexstring .= $invalue{$i};
2008 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2010 // Do some sanity checks. These aren't needed for reversability,
2011 // but should help keep the breakage down if the editor
2012 // breaks one of the entities whilst editing.
2013 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2014 $codepoint = hexdec($hexstring);
2015 $result .= codepointToUtf8( $codepoint );
2017 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2020 $result .= substr( $invalue, $i, 1 );
2023 // reverse the transform that we made for reversability reasons.
2024 return strtr( $result, array( "�" => "&#x" ) );
2027 function noCreatePermission() {
2029 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2030 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );