1afe416d84b5f79a8238abacfa55d63db5a94266
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() {
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 $this->summary
= wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
135 $this->formtype
= 'diff';
137 # Warn the user that something went wrong
138 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
141 else if( $section != '' ) {
142 if( $section == 'new' ) {
143 $text = $this->getPreloadedText( $preload );
145 $text = $wgParser->getSection( $text, $section );
150 wfProfileOut( __METHOD__
);
155 * Get the contents of a page from its title and remove includeonly tags
157 * @param $preload String: the title of the page.
158 * @return string The contents of the page.
160 private function getPreloadedText($preload) {
161 if ( $preload === '' )
164 $preloadTitle = Title
::newFromText( $preload );
165 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
166 $rev=Revision
::newFromTitle($preloadTitle);
167 if ( is_object( $rev ) ) {
168 $text = $rev->getText();
169 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
170 // its own mini-parser! -ævar
171 $text = preg_replace( '~</?includeonly>~', '', $text );
180 * This is the function that extracts metadata from the article body on the first view.
181 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
182 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
184 function extractMetaDataFromArticle () {
185 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
186 $this->mMetaData
= '' ;
187 if ( !$wgUseMetadataEdit ) return ;
188 if ( $wgMetadataWhitelist == '' ) return ;
190 $t = $this->getContent();
192 # MISSING : <nowiki> filtering
194 # Categories and language links
195 $t = explode ( "\n" , $t ) ;
196 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
197 $cat = $ll = array() ;
198 foreach ( $t AS $key => $x )
200 $y = trim ( strtolower ( $x ) ) ;
201 while ( substr ( $y , 0 , 2 ) == '[[' )
203 $y = explode ( ']]' , trim ( $x ) ) ;
204 $first = array_shift ( $y ) ;
205 $first = explode ( ':' , $first ) ;
206 $ns = array_shift ( $first ) ;
207 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
208 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
210 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
211 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
213 $x = implode ( ']]' , $y ) ;
215 $y = trim ( strtolower ( $x ) ) ;
219 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
220 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
221 $t = implode ( "\n" , $t ) ;
224 $sat = array () ; # stand-alone-templates; must be lowercase
225 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
226 $wl_article = new Article ( $wl_title ) ;
227 $wl = explode ( "\n" , $wl_article->getContent() ) ;
228 foreach ( $wl AS $x )
232 while ( substr ( $x , 0 , 1 ) == '*' )
235 $x = trim ( substr ( $x , 1 ) ) ;
239 $sat[] = strtolower ( $x ) ;
244 # Templates, but only some
245 $t = explode ( '{{' , $t ) ;
247 foreach ( $t AS $key => $x )
249 $y = explode ( '}}' , $x , 2 ) ;
250 if ( count ( $y ) == 2 )
253 $z = explode ( '|' , $z ) ;
254 $tn = array_shift ( $z ) ;
255 if ( in_array ( strtolower ( $tn ) , $sat ) )
257 $tl[] = '{{' . $y[0] . '}}' ;
259 $y = explode ( '}}' , $y[1] , 2 ) ;
261 else $t[$key] = '{{' . $x ;
263 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
266 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
267 $t = implode ( '' , $t ) ;
269 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
270 $this->mArticle
->mContent
= $t ;
271 $this->mMetaData
= $s ;
279 * This is the function that gets called for "action=edit". It
280 * sets up various member variables, then passes execution to
281 * another function, usually showEditForm()
283 * The edit form is self-submitting, so that when things like
284 * preview and edit conflicts occur, we get the same form back
285 * with the extra stuff added. Only when the final submission
286 * is made and all is well do we actually save and redirect to
287 * the newly-edited page.
290 global $wgOut, $wgUser, $wgRequest, $wgTitle;
291 global $wgEmailConfirmToEdit;
293 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
296 $fname = 'EditPage::edit';
297 wfProfileIn( $fname );
298 wfDebug( "$fname: enter\n" );
300 // this is not an article
301 $wgOut->setArticleFlag(false);
303 $this->importFormData( $wgRequest );
304 $this->firsttime
= false;
307 $this->livePreview();
308 wfProfileOut( $fname );
312 if ( ! $this->mTitle
->userCan( 'edit' ) ) {
313 wfDebug( "$fname: user can't edit\n" );
314 $wgOut->readOnlyPage( $this->getContent(), true );
315 wfProfileOut( $fname );
318 wfDebug( "$fname: Checking blocks\n" );
319 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
320 # When previewing, don't check blocked state - will get caught at save time.
321 # Also, check when starting edition is done against slave to improve performance.
322 wfDebug( "$fname: user is blocked\n" );
323 $this->blockedPage();
324 wfProfileOut( $fname );
327 if ( (!$this->mTitle
->isTalkPage() && !$wgUser->isAllowed('edit')) ||
($this->mTitle
->isTalkPage() && !$wgUser->isAllowed('edittalk')) ) {
328 if ( $wgUser->isAnon() ) {
329 wfDebug( "$fname: user must log in\n" );
330 $this->userNotLoggedInPage();
331 wfProfileOut( $fname );
334 wfDebug( "$fname: read-only page\n" );
335 $wgOut->readOnlyPage( $this->getContent(), true );
336 wfProfileOut( $fname );
340 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
341 wfDebug("$fname: user must confirm e-mail address\n");
342 $this->userNotConfirmedPage();
343 wfProfileOut($fname);
346 if ( !$this->mTitle
->userCan( 'create' ) && !$this->mTitle
->exists() ) {
347 wfDebug( "$fname: no create permission\n" );
348 $this->noCreatePermission();
349 wfProfileOut( $fname );
352 if ( wfReadOnly() ) {
353 wfDebug( "$fname: read-only mode is engaged\n" );
354 if( $this->save ||
$this->preview
) {
355 $this->formtype
= 'preview';
356 } else if ( $this->diff
) {
357 $this->formtype
= 'diff';
359 $wgOut->readOnlyPage( $this->getContent() );
360 wfProfileOut( $fname );
365 $this->formtype
= 'save';
366 } else if ( $this->preview
) {
367 $this->formtype
= 'preview';
368 } else if ( $this->diff
) {
369 $this->formtype
= 'diff';
370 } else { # First time through
371 $this->firsttime
= true;
372 if( $this->previewOnOpen() ) {
373 $this->formtype
= 'preview';
375 $this->extractMetaDataFromArticle () ;
376 $this->formtype
= 'initial';
381 wfProfileIn( "$fname-business-end" );
383 $this->isConflict
= false;
384 // css / js subpages of user pages get a special treatment
385 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
386 $this->isValidCssJsSubpage
= $wgTitle->isValidCssJsSubpage();
388 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
389 * no matter it's current state
391 $this->deletedSinceEdit
= false;
392 if ( $this->edittime
!= '' ) {
393 /* Note that we rely on logging table, which hasn't been always there,
394 * but that doesn't matter, because this only applies to brand new
395 * deletes. This is done on every preview and save request. Move it further down
396 * to only perform it on saves
398 if ( $this->mTitle
->isDeleted() ) {
399 $this->lastDelete
= $this->getLastDelete();
400 if ( !is_null($this->lastDelete
) ) {
401 $deletetime = $this->lastDelete
->log_timestamp
;
402 if ( ($deletetime - $this->starttime
) > 0 ) {
403 $this->deletedSinceEdit
= true;
409 if(!$this->mTitle
->getArticleID() && ('initial' == $this->formtype ||
$this->firsttime
)) { # new article
412 if( $this->mTitle
->isTalkPage() ) {
413 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
416 # Attempt submission here. This will check for edit conflicts,
417 # and redundantly check for locked database, blocked IPs, etc.
418 # that edit() already checked just in case someone tries to sneak
419 # in the back door with a hand-edited submission URL.
421 if ( 'save' == $this->formtype
) {
422 if ( !$this->attemptSave() ) {
423 wfProfileOut( "$fname-business-end" );
424 wfProfileOut( $fname );
429 # First time through: get contents, set time for conflict
431 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
432 $this->initialiseForm();
433 if( !$this->mTitle
->getArticleId() )
434 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
437 $this->showEditForm();
438 wfProfileOut( "$fname-business-end" );
439 wfProfileOut( $fname );
443 * Return true if this page should be previewed when the edit form
444 * is initially opened.
448 function previewOnOpen() {
450 return $this->section
!= 'new' &&
451 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle
->exists() ) ||
452 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
453 !$this->mTitle
->exists() ) );
460 function importFormData( &$request ) {
461 global $wgLang, $wgUser;
462 $fname = 'EditPage::importFormData';
463 wfProfileIn( $fname );
465 if( $request->wasPosted() ) {
466 # These fields need to be checked for encoding.
467 # Also remove trailing whitespace, but don't remove _initial_
468 # whitespace from the text boxes. This may be significant formatting.
469 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
470 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
471 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
472 # Truncate for whole multibyte characters. +5 bytes for ellipsis
473 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
475 $this->edittime
= $request->getVal( 'wpEdittime' );
476 $this->starttime
= $request->getVal( 'wpStarttime' );
478 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
480 if( is_null( $this->edittime
) ) {
481 # If the form is incomplete, force to preview.
482 wfDebug( "$fname: Form data appears to be incomplete\n" );
483 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
484 $this->preview
= true;
486 /* Fallback for live preview */
487 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
488 $this->diff
= $request->getCheck( 'wpDiff' );
490 // Remember whether a save was requested, so we can indicate
491 // if we forced preview due to session failure.
492 $this->mTriedSave
= !$this->preview
;
494 if ( $this->tokenOk( $request ) ) {
495 # Some browsers will not report any submit button
496 # if the user hits enter in the comment box.
497 # The unmarked state will be assumed to be a save,
498 # if the form seems otherwise complete.
499 wfDebug( "$fname: Passed token check.\n" );
500 } else if ( $this->diff
) {
501 # Failed token check, but only requested "Show Changes".
502 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
504 # Page might be a hack attempt posted from
505 # an external site. Preview instead of saving.
506 wfDebug( "$fname: Failed token check; forcing preview\n" );
507 $this->preview
= true;
510 $this->save
= ! ( $this->preview
OR $this->diff
);
511 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
512 $this->edittime
= null;
515 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
516 $this->starttime
= null;
519 $this->recreate
= $request->getCheck( 'wpRecreate' );
521 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
522 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
524 # Don't force edit summaries when a user is editing their own user or talk page
525 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
526 $this->allowBlankSummary
= true;
528 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
531 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
533 # Not a posted form? Start with nothing.
534 wfDebug( "$fname: Not a posted form.\n" );
535 $this->textbox1
= '';
536 $this->textbox2
= '';
537 $this->mMetaData
= '';
539 $this->edittime
= '';
540 $this->starttime
= wfTimestampNow();
541 $this->preview
= false;
544 $this->minoredit
= false;
545 $this->watchthis
= false;
546 $this->recreate
= false;
549 $this->oldid
= $request->getInt( 'oldid' );
551 # Section edit can come from either the form or a link
552 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
554 $this->live
= $request->getCheck( 'live' );
555 $this->editintro
= $request->getText( 'editintro' );
557 wfProfileOut( $fname );
561 * Make sure the form isn't faking a user's credentials.
563 * @param $request WebRequest
567 function tokenOk( &$request ) {
569 if( $wgUser->isAnon() ) {
570 # Anonymous users may not have a session
571 # open. Check for suffix anyway.
572 $this->mTokenOk
= ( EDIT_TOKEN_SUFFIX
== $request->getVal( 'wpEditToken' ) );
574 $this->mTokenOk
= $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
576 return $this->mTokenOk
;
580 function showIntro() {
581 global $wgOut, $wgUser;
582 $addstandardintro=true;
583 if($this->editintro
) {
584 $introtitle=Title
::newFromText($this->editintro
);
585 if(isset($introtitle) && $introtitle->userCanRead()) {
586 $rev=Revision
::newFromTitle($introtitle);
588 $wgOut->addSecondaryWikiText($rev->getText());
589 $addstandardintro=false;
593 if($addstandardintro) {
594 if ( $wgUser->isLoggedIn() )
595 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
597 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
603 * @return bool false if output is done, true if the rest of the form should be displayed
605 function attemptSave() {
606 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
607 global $wgMaxArticleSize;
609 $fname = 'EditPage::attemptSave';
610 wfProfileIn( $fname );
611 wfProfileIn( "$fname-checks" );
613 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
615 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
619 # Reintegrate metadata
620 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
621 $this->mMetaData
= '' ;
625 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
626 $this->spamPage ( $matches[0] );
627 wfProfileOut( "$fname-checks" );
628 wfProfileOut( $fname );
631 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
632 # Error messages or other handling should be performed by the filter function
633 wfProfileOut( $fname );
634 wfProfileOut( "$fname-checks" );
637 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
) ) ) {
638 # Error messages etc. could be handled within the hook...
639 wfProfileOut( $fname );
640 wfProfileOut( "$fname-checks" );
642 } elseif( $this->hookError
!= '' ) {
643 # ...or the hook could be expecting us to produce an error
644 wfProfileOut( "$fname-checks " );
645 wfProfileOut( $fname );
648 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
649 # Check block state against master, thus 'false'.
650 $this->blockedPage();
651 wfProfileOut( "$fname-checks" );
652 wfProfileOut( $fname );
655 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
656 if ( $this->kblength
> $wgMaxArticleSize ) {
657 // Error will be displayed by showEditForm()
658 $this->tooBig
= true;
659 wfProfileOut( "$fname-checks" );
660 wfProfileOut( $fname );
664 if ( !$wgUser->isAllowed('edit') ) {
665 if ( $wgUser->isAnon() ) {
666 $this->userNotLoggedInPage();
667 wfProfileOut( "$fname-checks" );
668 wfProfileOut( $fname );
672 $wgOut->readOnlyPage();
673 wfProfileOut( "$fname-checks" );
674 wfProfileOut( $fname );
679 if ( wfReadOnly() ) {
680 $wgOut->readOnlyPage();
681 wfProfileOut( "$fname-checks" );
682 wfProfileOut( $fname );
685 if ( $wgUser->pingLimiter() ) {
686 $wgOut->rateLimited();
687 wfProfileOut( "$fname-checks" );
688 wfProfileOut( $fname );
692 # If the article has been deleted while editing, don't save it without
694 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
695 wfProfileOut( "$fname-checks" );
696 wfProfileOut( $fname );
700 wfProfileOut( "$fname-checks" );
702 # If article is new, insert it.
703 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
706 // Late check for create permission, just in case *PARANOIA*
707 if ( !$this->mTitle
->userCan( 'create' ) ) {
708 wfDebug( "$fname: no create permission\n" );
709 $this->noCreatePermission();
710 wfProfileOut( $fname );
714 # Don't save a new article if it's blank.
715 if ( ( '' == $this->textbox1
) ) {
716 $wgOut->redirect( $this->mTitle
->getFullURL() );
717 wfProfileOut( $fname );
721 $isComment=($this->section
=='new');
722 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
723 $this->minoredit
, $this->watchthis
, false, $isComment);
725 wfProfileOut( $fname );
729 # Article exists. Check for edit conflict.
731 $this->mArticle
->clear(); # Force reload of dates, etc.
732 $this->mArticle
->forUpdate( true ); # Lock the article
734 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
735 $this->isConflict
= true;
736 if( $this->section
== 'new' ) {
737 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
738 $this->mArticle
->getComment() == $this->summary
) {
739 // Probably a duplicate submission of a new comment.
740 // This can happen when squid resends a request after
741 // a timeout but the first one actually went through.
742 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
744 // New comment; suppress conflict.
745 $this->isConflict
= false;
746 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
750 $userid = $wgUser->getID();
752 if ( $this->isConflict
) {
753 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
754 $this->mArticle
->getTimestamp() . "'\n" );
755 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
758 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
759 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
761 if( is_null( $text ) ) {
762 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
763 $this->isConflict
= true;
764 $text = $this->textbox1
;
767 # Suppress edit conflict with self, except for section edits where merging is required.
768 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
769 wfDebug( "Suppressing edit conflict, same user.\n" );
770 $this->isConflict
= false;
772 # switch from section editing to normal editing in edit conflict
773 if($this->isConflict
) {
775 if( $this->mergeChangesInto( $text ) ){
776 // Successful merge! Maybe we should tell the user the good news?
777 $this->isConflict
= false;
778 wfDebug( "Suppressing edit conflict, successful merge.\n" );
781 $this->textbox1
= $text;
782 wfDebug( "Keeping edit conflict, failed merge.\n" );
787 if ( $this->isConflict
) {
788 wfProfileOut( $fname );
792 $oldtext = $this->mArticle
->getContent();
794 # Handle the user preference to force summaries here, but not for null edits
795 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary')
796 && 0 != strcmp($oldtext, $text) && !Article
::getRedirectAutosummary( $text )) {
797 if( md5( $this->summary
) == $this->autoSumm
) {
798 $this->missingSummary
= true;
799 wfProfileOut( $fname );
804 #And a similar thing for new sections
805 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
806 if (trim($this->summary
) == '') {
807 $this->missingSummary
= true;
808 wfProfileOut( $fname );
814 wfProfileIn( "$fname-sectionanchor" );
816 if( $this->section
== 'new' ) {
817 if ( $this->textbox1
== '' ) {
818 $this->missingComment
= true;
821 if( $this->summary
!= '' ) {
822 $sectionanchor = $this->sectionAnchor( $this->summary
);
824 } elseif( $this->section
!= '' ) {
825 # Try to get a section anchor from the section source, redirect to edited section if header found
826 # XXX: might be better to integrate this into Article::replaceSection
827 # for duplicate heading checking and maybe parsing
828 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
829 # we can't deal with anchors, includes, html etc in the header for now,
830 # headline would need to be parsed to improve this
831 if($hasmatch and strlen($matches[2]) > 0) {
832 $sectionanchor = $this->sectionAnchor( $matches[2] );
835 wfProfileOut( "$fname-sectionanchor" );
837 // Save errors may fall down to the edit form, but we've now
838 // merged the section into full text. Clear the section field
839 // so that later submission of conflict forms won't try to
840 // replace that into a duplicated mess.
841 $this->textbox1
= $text;
844 // Check for length errors again now that the section is merged in
845 $this->kblength
= (int)(strlen( $text ) / 1024);
846 if ( $this->kblength
> $wgMaxArticleSize ) {
847 $this->tooBig
= true;
848 wfProfileOut( $fname );
852 # update the article here
853 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
854 $this->watchthis
, '', $sectionanchor ) ) {
855 wfProfileOut( $fname );
858 $this->isConflict
= true;
860 wfProfileOut( $fname );
865 * Initialise form fields in the object
866 * Called on the first invocation, e.g. when a user clicks an edit link
868 function initialiseForm() {
869 $this->edittime
= $this->mArticle
->getTimestamp();
871 $this->textbox1
= $this->getContent();
872 if ( !$this->mArticle
->exists() && $this->mArticle
->mTitle
->getNamespace() == NS_MEDIAWIKI
)
873 $this->textbox1
= wfMsgWeirdKey( $this->mArticle
->mTitle
->getText() );
878 * Send the edit form and related headers to $wgOut
879 * @param $formCallback Optional callable that takes an OutputPage
880 * parameter; will be called during form output
881 * near the top, for captchas and the like.
883 function showEditForm( $formCallback=null ) {
884 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
886 $fname = 'EditPage::showEditForm';
887 wfProfileIn( $fname );
889 $sk = $wgUser->getSkin();
891 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
893 $wgOut->setRobotpolicy( 'noindex,nofollow' );
895 # Enabled article-related sidebar, toplinks, etc.
896 $wgOut->setArticleRelated( true );
898 if ( $this->isConflict
) {
899 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
900 $wgOut->setPageTitle( $s );
901 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
903 $this->textbox2
= $this->textbox1
;
904 $this->textbox1
= $this->getContent();
905 $this->edittime
= $this->mArticle
->getTimestamp();
908 if( $this->section
!= '' ) {
909 if( $this->section
== 'new' ) {
910 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
912 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
914 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
915 preg_match( "/^(=+)(.+)\\1/mi",
918 if( !empty( $matches[2] ) ) {
919 $this->summary
= "/* ". trim($matches[2])." */ ";
924 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
926 $wgOut->setPageTitle( $s );
928 if ( $this->missingComment
) {
929 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
932 if( $this->missingSummary
&& $this->section
!= 'new' ) {
933 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
936 if( $this->missingSummary
&& $this->section
== 'new' ) {
937 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
940 if( !$this->hookError
== '' ) {
941 $wgOut->addWikiText( $this->hookError
);
944 if ( !$this->checkUnicodeCompliantBrowser() ) {
945 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
947 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
948 // Let sysop know that this will make private content public if saved
949 if( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
950 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
952 if( !$this->mArticle
->mRevision
->isCurrent() ) {
953 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
954 $wgOut->addWikiText( wfMsg( 'editingold' ) );
960 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
961 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
962 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
964 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
965 # Check the skin exists
966 if( $this->isValidCssJsSubpage
) {
967 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
969 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
974 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
975 # Show a warning if editing an interface message
976 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
977 } elseif( $this->mTitle
->isProtected( 'edit' ) ) {
978 # Is the title semi-protected?
979 if( $this->mTitle
->isSemiProtected() ) {
980 $notice = wfMsg( 'semiprotectedpagewarning' );
981 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' )
984 # It's either cascading protection or regular protection; work out which
985 $cascadeSources = $this->mTitle
->getCascadeProtectionSources();
986 if( $cascadeSources && count( $cascadeSources ) > 0 ) {
987 # Cascading protection; explain, and list the titles responsible
988 $notice = wfMsg( 'cascadeprotectedwarning' ) . "\n";
989 foreach( $cascadeSources as $source )
990 $notice .= '* [[:' . $source->getPrefixedText() . "]]\n";
993 $notice = wfMsg( 'protectedpagewarning' );
996 $wgOut->addWikiText( $notice );
999 if ( $this->kblength
=== false ) {
1000 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1002 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1003 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgMaxArticleSize ) );
1004 } elseif( $this->kblength
> 29 ) {
1005 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) ) );
1008 #need to parse the preview early so that we know which templates are used,
1009 #otherwise users with "show preview after edit box" will get a blank list
1010 if ( $this->formtype
== 'preview' ) {
1011 $previewOutput = $this->getPreviewText();
1014 $rows = $wgUser->getIntOption( 'rows' );
1015 $cols = $wgUser->getIntOption( 'cols' );
1017 $ew = $wgUser->getOption( 'editwidth' );
1018 if ( $ew ) $ew = " style=\"width:100%\"";
1021 $q = 'action=submit';
1022 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1023 $action = $this->mTitle
->escapeLocalURL( $q );
1025 $summary = wfMsg('summary');
1026 $subject = wfMsg('subject');
1028 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
1029 wfMsgExt('cancel', array('parseinline')) );
1030 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1031 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1032 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1033 htmlspecialchars( wfMsg( 'newwindow' ) );
1035 global $wgRightsText;
1036 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1037 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
1038 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1039 $wgRightsText ) . "\n</div>";
1041 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1042 # prepare toolbar for edit buttons
1043 $toolbar = $this->getEditToolbar();
1048 // activate checkboxes if user wants them to be always active
1049 if( !$this->preview
&& !$this->diff
) {
1050 # Sort out the "watch" checkbox
1051 if( $wgUser->getOption( 'watchdefault' ) ) {
1053 $this->watchthis
= true;
1054 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1056 $this->watchthis
= true;
1057 } elseif( $this->mTitle
->userIsWatching() ) {
1059 $this->watchthis
= true;
1062 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1065 $wgOut->addHTML( $this->editFormPageTop
);
1067 if ( $wgUser->getOption( 'previewontop' ) ) {
1069 if ( 'preview' == $this->formtype
) {
1070 $this->showPreview( $previewOutput );
1072 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1075 if ( 'diff' == $this->formtype
) {
1076 $wgOut->addHTML( $this->getDiff() );
1081 $wgOut->addHTML( $this->editFormTextTop
);
1083 # if this is a comment, show a subject line at the top, which is also the edit summary.
1084 # Otherwise, show a summary field at the bottom
1085 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1086 if( $this->section
== 'new' ) {
1087 $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 />";
1089 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1090 $summarypreview = '';
1092 $commentsubject = '';
1093 $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 />";
1094 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1095 $subjectpreview = '';
1098 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1099 if( !$this->preview
&& !$this->diff
) {
1100 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1102 $templates = ($this->preview ||
$this->section
) ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1103 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1105 global $wgUseMetadataEdit ;
1106 if ( $wgUseMetadataEdit ) {
1107 $metadata = $this->mMetaData
;
1108 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1109 $top = wfMsgWikiHtml( 'metadata_help' );
1110 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1112 else $metadata = "" ;
1116 if ($this->deletedSinceEdit
) {
1117 if ( 'save' != $this->formtype
) {
1118 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1120 // Hide the toolbar and edit area, use can click preview to get it back
1121 // Add an confirmation checkbox and explanation.
1123 $hidden = 'type="hidden" style="display:none;"';
1124 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1126 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1127 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1133 $checkboxes = self
::getCheckboxes( $tabindex, $sk,
1134 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1136 $checkboxhtml = implode( $checkboxes, "\n" );
1138 $buttons = $this->getEditButtons( $tabindex );
1139 $buttonshtml = implode( $buttons, "\n" );
1141 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1142 ?
'' : Xml
::hidden( 'safemode', '1' );
1144 $wgOut->addHTML( <<<END
1146 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1150 if( is_callable( $formCallback ) ) {
1151 call_user_func_array( $formCallback, array( &$wgOut ) );
1154 // Put these up at the top to ensure they aren't lost on early form submission
1156 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1157 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1158 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1159 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1161 $wgOut->addHTML( <<<END
1165 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1166 cols='{$cols}'{$ew} $hidden>
1168 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
1173 $wgOut->addWikiText( $copywarn );
1174 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1184 "<div class='editButtons'>
1186 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1187 </div><!-- editButtons -->
1188 </div><!-- editOptions -->");
1190 $wgOut->addHtml( '<div class="mw-editTools">' );
1191 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1192 $wgOut->addHtml( '</div>' );
1194 $wgOut->addHTML( $this->editFormTextAfterTools
);
1197 <div class='templatesUsed'>
1198 {$formattedtemplates}
1203 * To make it harder for someone to slip a user a page
1204 * which submits an edit form to the wiki without their
1205 * knowledge, a random token is associated with the login
1206 * session. If it's not passed back with the submission,
1207 * we won't save the page, or render user JavaScript and
1210 * For anon editors, who may not have a session, we just
1211 * include the constant suffix to prevent editing from
1212 * broken text-mangling proxies.
1214 if ( $wgUser->isLoggedIn() )
1215 $token = htmlspecialchars( $wgUser->editToken() );
1217 $token = EDIT_TOKEN_SUFFIX
;
1218 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1221 # If a blank edit summary was previously provided, and the appropriate
1222 # user preference is active, pass a hidden tag here. This will stop the
1223 # user being bounced back more than once in the event that a summary
1225 if( $this->missingSummary
) {
1226 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1229 # For a bit more sophisticated detection of blank summaries, hash the
1230 # automatic one and pass that in a hidden field.
1231 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1232 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1234 if ( $this->isConflict
) {
1235 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1237 $de = new DifferenceEngine( $this->mTitle
);
1238 $de->setText( $this->textbox2
, $this->textbox1
);
1239 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1241 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1242 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1243 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1245 $wgOut->addHTML( $this->editFormTextBottom
);
1246 $wgOut->addHTML( "</form>\n" );
1247 if ( !$wgUser->getOption( 'previewontop' ) ) {
1249 if ( $this->formtype
== 'preview') {
1250 $this->showPreview( $previewOutput );
1252 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1255 if ( $this->formtype
== 'diff') {
1256 $wgOut->addHTML( $this->getDiff() );
1261 wfProfileOut( $fname );
1265 * Append preview output to $wgOut.
1266 * Includes category rendering if this is a category page.
1268 * @param string $text The HTML to be output for the preview.
1270 private function showPreview( $text ) {
1273 $wgOut->addHTML( '<div id="wikiPreview">' );
1274 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1275 $this->mArticle
->openShowCategory();
1277 $wgOut->addHTML( $text );
1278 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1279 $this->mArticle
->closeShowCategory();
1281 $wgOut->addHTML( '</div>' );
1285 * Live Preview lets us fetch rendered preview page content and
1286 * add it to the page without refreshing the whole page.
1287 * If not supported by the browser it will fall through to the normal form
1288 * submission method.
1290 * This function outputs a script tag to support live preview, and
1291 * returns an onclick handler which should be added to the attributes
1292 * of the preview button
1294 function doLivePreviewScript() {
1295 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1296 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1297 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1298 '"></script>' . "\n" );
1299 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1300 return "return !livePreview(" .
1301 "getElementById('wikiPreview')," .
1302 "editform.wpTextbox1.value," .
1303 '"' . $liveAction . '"' . ")";
1306 function getLastDelete() {
1307 $dbr = wfGetDB( DB_SLAVE
);
1308 $fname = 'EditPage::getLastDelete';
1309 $res = $dbr->select(
1310 array( 'logging', 'user' ),
1320 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1321 'log_title' => $this->mTitle
->getDBkey(),
1322 'log_type' => 'delete',
1323 'log_action' => 'delete',
1324 'user_id=log_user' ),
1326 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1328 if($dbr->numRows($res) == 1) {
1329 while ( $x = $dbr->fetchObject ( $res ) )
1331 $dbr->freeResult ( $res ) ;
1341 function getPreviewText() {
1342 global $wgOut, $wgUser, $wgTitle, $wgParser;
1344 $fname = 'EditPage::getPreviewText';
1345 wfProfileIn( $fname );
1347 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1348 $msg = 'session_fail_preview';
1350 $msg = 'previewnote';
1352 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1353 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1354 if ( $this->isConflict
) {
1355 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1358 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1359 $parserOptions->setEditSection( false );
1362 if( $wgRawHtml && !$this->mTokenOk
) {
1363 // Could be an offsite preview attempt. This is very unsafe if
1364 // HTML is enabled, as it could be an attack.
1365 return $wgOut->parse( "<div class='previewnote'>" .
1366 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1369 # don't parse user css/js, show message about preview
1370 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1372 if ( $this->isCssJsSubpage
) {
1373 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1374 $previewtext = wfMsg('usercsspreview');
1375 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1376 $previewtext = wfMsg('userjspreview');
1378 $parserOptions->setTidy(true);
1379 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1380 $wgOut->addHTML( $parserOutput->mText
);
1381 wfProfileOut( $fname );
1382 return $previewhead;
1384 $toparse = $this->textbox1
;
1386 # If we're adding a comment, we need to show the
1387 # summary as the headline
1388 if($this->section
=="new" && $this->summary
!="") {
1389 $toparse="== {$this->summary} ==\n\n".$toparse;
1392 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1393 $parserOptions->setTidy(true);
1394 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1395 $wgTitle, $parserOptions );
1397 $previewHTML = $parserOutput->getText();
1398 $wgOut->addParserOutputNoText( $parserOutput );
1400 foreach ( $parserOutput->getTemplates() as $ns => $template)
1401 foreach ( array_keys( $template ) as $dbk)
1402 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1404 wfProfileOut( $fname );
1405 return $previewhead . $previewHTML;
1410 * Call the stock "user is blocked" page
1412 function blockedPage() {
1413 global $wgOut, $wgUser;
1414 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1416 # If the user made changes, preserve them when showing the markup
1417 # (This happens when a user is blocked during edit, for instance)
1418 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1420 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1422 $source = $this->textbox1
;
1425 # Spit out the source or the user's modified version
1426 if( $source !== false ) {
1427 $rows = $wgUser->getOption( 'rows' );
1428 $cols = $wgUser->getOption( 'cols' );
1429 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1430 $wgOut->addHtml( '<hr />' );
1431 $wgOut->addWikiText( wfMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() ) );
1432 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1437 * Produce the stock "please login to edit pages" page
1439 function userNotLoggedInPage() {
1440 global $wgUser, $wgOut;
1441 $skin = $wgUser->getSkin();
1443 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1444 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle
->getPrefixedUrl() );
1446 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1447 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1448 $wgOut->setArticleRelated( false );
1450 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1451 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1455 * Creates a basic error page which informs the user that
1456 * they have to validate their email address before being
1459 function userNotConfirmedPage() {
1462 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1463 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1464 $wgOut->setArticleRelated( false );
1466 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1467 $wgOut->returnToMain( false );
1471 * Produce the stock "your edit contains spam" page
1473 * @param $match Text which triggered one or more filters
1475 function spamPage( $match = false ) {
1478 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1479 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1480 $wgOut->setArticleRelated( false );
1482 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1484 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1486 $wgOut->returnToMain( false );
1493 function mergeChangesInto( &$editText ){
1494 $fname = 'EditPage::mergeChangesInto';
1495 wfProfileIn( $fname );
1497 $db = wfGetDB( DB_MASTER
);
1499 // This is the revision the editor started from
1500 $baseRevision = Revision
::loadFromTimestamp(
1501 $db, $this->mArticle
->mTitle
, $this->edittime
);
1502 if( is_null( $baseRevision ) ) {
1503 wfProfileOut( $fname );
1506 $baseText = $baseRevision->getText();
1508 // The current state, we want to merge updates into it
1509 $currentRevision = Revision
::loadFromTitle(
1510 $db, $this->mArticle
->mTitle
);
1511 if( is_null( $currentRevision ) ) {
1512 wfProfileOut( $fname );
1515 $currentText = $currentRevision->getText();
1518 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1519 $editText = $result;
1520 wfProfileOut( $fname );
1523 wfProfileOut( $fname );
1529 * Check if the browser is on a blacklist of user-agents known to
1530 * mangle UTF-8 data on form submission. Returns true if Unicode
1531 * should make it through, false if it's known to be a problem.
1535 function checkUnicodeCompliantBrowser() {
1536 global $wgBrowserBlackList;
1537 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1538 // No User-Agent header sent? Trust it by default...
1541 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1542 foreach ( $wgBrowserBlackList as $browser ) {
1543 if ( preg_match($browser, $currentbrowser) ) {
1551 * Format an anchor fragment as it would appear for a given section name
1552 * @param string $text
1556 function sectionAnchor( $text ) {
1557 $headline = Sanitizer
::decodeCharReferences( $text );
1559 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1560 $headline = trim( $headline );
1561 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1562 $replacearray = array(
1567 array_keys( $replacearray ),
1568 array_values( $replacearray ),
1573 * Shows a bulletin board style toolbar for common editing functions.
1574 * It can be disabled in the user preferences.
1575 * The necessary JavaScript code can be found in style/wikibits.js.
1577 function getEditToolbar() {
1578 global $wgStylePath, $wgContLang, $wgJsMimeType;
1581 * toolarray an array of arrays which each include the filename of
1582 * the button image (without path), the opening tag, the closing tag,
1583 * and optionally a sample text that is inserted between the two when no
1584 * selection is highlighted.
1585 * The tip text is shown when the user moves the mouse over the button.
1587 * Already here are accesskeys (key), which are not used yet until someone
1588 * can figure out a way to make them work in IE. However, we should make
1589 * sure these keys are not defined on the edit page.
1592 array( 'image' => 'button_bold.png',
1593 'id' => 'mw-editbutton-bold',
1594 'open' => '\\\'\\\'\\\'',
1595 'close' => '\\\'\\\'\\\'',
1596 'sample'=> wfMsg('bold_sample'),
1597 'tip' => wfMsg('bold_tip'),
1600 array( 'image' => 'button_italic.png',
1601 'id' => 'mw-editbutton-italic',
1602 'open' => '\\\'\\\'',
1603 'close' => '\\\'\\\'',
1604 'sample'=> wfMsg('italic_sample'),
1605 'tip' => wfMsg('italic_tip'),
1608 array( 'image' => 'button_link.png',
1609 'id' => 'mw-editbutton-link',
1612 'sample'=> wfMsg('link_sample'),
1613 'tip' => wfMsg('link_tip'),
1616 array( 'image' => 'button_extlink.png',
1617 'id' => 'mw-editbutton-extlink',
1620 'sample'=> wfMsg('extlink_sample'),
1621 'tip' => wfMsg('extlink_tip'),
1624 array( 'image' => 'button_headline.png',
1625 'id' => 'mw-editbutton-headline',
1627 'close' => " ==\\n",
1628 'sample'=> wfMsg('headline_sample'),
1629 'tip' => wfMsg('headline_tip'),
1632 array( 'image' => 'button_image.png',
1633 'id' => 'mw-editbutton-image',
1634 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1636 'sample'=> wfMsg('image_sample'),
1637 'tip' => wfMsg('image_tip'),
1640 array( 'image' => 'button_media.png',
1641 'id' => 'mw-editbutton-media',
1642 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1644 'sample'=> wfMsg('media_sample'),
1645 'tip' => wfMsg('media_tip'),
1648 array( 'image' => 'button_math.png',
1649 'id' => 'mw-editbutton-math',
1651 'close' => "<\\/math>",
1652 'sample'=> wfMsg('math_sample'),
1653 'tip' => wfMsg('math_tip'),
1656 array( 'image' => 'button_nowiki.png',
1657 'id' => 'mw-editbutton-nowiki',
1658 'open' => "<nowiki>",
1659 'close' => "<\\/nowiki>",
1660 'sample'=> wfMsg('nowiki_sample'),
1661 'tip' => wfMsg('nowiki_tip'),
1664 array( 'image' => 'button_sig.png',
1665 'id' => 'mw-editbutton-signature',
1669 'tip' => wfMsg('sig_tip'),
1672 array( 'image' => 'button_hr.png',
1673 'id' => 'mw-editbutton-hr',
1674 'open' => "\\n----\\n",
1677 'tip' => wfMsg('hr_tip'),
1681 $toolbar = "<div id='toolbar'>\n";
1682 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1684 foreach($toolarray as $tool) {
1686 $cssId = $tool['id'];
1687 $image=$wgStylePath.'/common/images/'.$tool['image'];
1688 $open=$tool['open'];
1689 $close=$tool['close'];
1690 $sample = wfEscapeJsString( $tool['sample'] );
1692 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1693 // Older browsers show a "speedtip" type message only for ALT.
1694 // Ideally these should be different, realistically they
1695 // probably don't need to be.
1696 $tip = wfEscapeJsString( $tool['tip'] );
1698 #$key = $tool["key"];
1700 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1703 $toolbar.="/*]]>*/\n</script>";
1704 $toolbar.="\n</div>";
1709 * Returns an array of html code of the following checkboxes:
1712 * @param $tabindex Current tabindex
1713 * @param $skin Skin object
1714 * @param $checked Array of checkbox => bool, where bool indicates the checked
1715 * status of the checkbox
1719 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1722 $checkboxes = array();
1724 $checkboxes['minor'] = '';
1725 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1726 if ( $wgUser->isAllowed('minoredit') ) {
1728 'tabindex' => ++
$tabindex,
1729 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1730 'id' => 'wpMinoredit',
1732 $checkboxes['minor'] =
1733 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1734 " <label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1737 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1738 $checkboxes['watch'] = '';
1739 if ( $wgUser->isLoggedIn() ) {
1741 'tabindex' => ++
$tabindex,
1742 'accesskey' => wfMsg( 'accesskey-watch' ),
1743 'id' => 'wpWatchthis',
1745 $checkboxes['watch'] =
1746 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1747 " <label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1753 * Returns an array of html code of the following buttons:
1754 * save, diff, preview and live
1756 * @param $tabindex Current tabindex
1760 public function getEditButtons(&$tabindex) {
1761 global $wgLivePreview, $wgUser;
1769 'tabindex' => ++
$tabindex,
1770 'value' => wfMsg('savearticle'),
1771 'accesskey' => wfMsg('accesskey-save'),
1772 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1774 $buttons['save'] = wfElement('input', $temp, '');
1776 ++
$tabindex; // use the same for preview and live preview
1777 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1779 'id' => 'wpPreview',
1780 'name' => 'wpPreview',
1782 'tabindex' => $tabindex,
1783 'value' => wfMsg('showpreview'),
1785 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1786 'style' => 'display: none;',
1788 $buttons['preview'] = wfElement('input', $temp, '');
1791 'id' => 'wpLivePreview',
1792 'name' => 'wpLivePreview',
1794 'tabindex' => $tabindex,
1795 'value' => wfMsg('showlivepreview'),
1796 'accesskey' => wfMsg('accesskey-preview'),
1798 'onclick' => $this->doLivePreviewScript(),
1800 $buttons['live'] = wfElement('input', $temp, '');
1803 'id' => 'wpPreview',
1804 'name' => 'wpPreview',
1806 'tabindex' => $tabindex,
1807 'value' => wfMsg('showpreview'),
1808 'accesskey' => wfMsg('accesskey-preview'),
1809 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1811 $buttons['preview'] = wfElement('input', $temp, '');
1812 $buttons['live'] = '';
1819 'tabindex' => ++
$tabindex,
1820 'value' => wfMsg('showdiff'),
1821 'accesskey' => wfMsg('accesskey-diff'),
1822 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1824 $buttons['diff'] = wfElement('input', $temp, '');
1830 * Output preview text only. This can be sucked into the edit page
1831 * via JavaScript, and saves the server time rendering the skin as
1832 * well as theoretically being more robust on the client (doesn't
1833 * disturb the edit box's undo history, won't eat your text on
1836 * @todo This doesn't include category or interlanguage links.
1837 * Would need to enhance it a bit, <s>maybe wrap them in XML
1838 * or something...</s> that might also require more skin
1839 * initialization, so check whether that's a problem.
1841 function livePreview() {
1844 header( 'Content-type: text/xml; charset=utf-8' );
1845 header( 'Cache-control: no-cache' );
1848 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1849 Xml
::openElement( 'livepreview' ) .
1850 Xml
::element( 'preview', null, $this->getPreviewText() ) .
1851 Xml
::element( 'br', array( 'style' => 'clear: both;' ) ) .
1852 Xml
::closeElement( 'livepreview' );
1858 * Get a diff between the current contents of the edit box and the
1859 * version of the page we're editing from.
1861 * If this is a section edit, we'll replace the section as for final
1862 * save and then make a comparison.
1864 * @return string HTML
1866 function getDiff() {
1867 $oldtext = $this->mArticle
->fetchContent();
1868 $newtext = $this->mArticle
->replaceSection(
1869 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1870 $newtext = $this->mArticle
->preSaveTransform( $newtext );
1871 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1872 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1873 if ( $oldtext !== false ||
$newtext != '' ) {
1874 $de = new DifferenceEngine( $this->mTitle
);
1875 $de->setText( $oldtext, $newtext );
1876 $difftext = $de->getDiff( $oldtitle, $newtitle );
1881 return '<div id="wikiDiff">' . $difftext . '</div>';
1885 * Filter an input field through a Unicode de-armoring process if it
1886 * came from an old browser with known broken Unicode editing issues.
1888 * @param WebRequest $request
1889 * @param string $field
1893 function safeUnicodeInput( $request, $field ) {
1894 $text = rtrim( $request->getText( $field ) );
1895 return $request->getBool( 'safemode' )
1896 ?
$this->unmakesafe( $text )
1901 * Filter an output field through a Unicode armoring process if it is
1902 * going to an old browser with known broken Unicode editing issues.
1904 * @param string $text
1908 function safeUnicodeOutput( $text ) {
1910 $codedText = $wgContLang->recodeForEdit( $text );
1911 return $this->checkUnicodeCompliantBrowser()
1913 : $this->makesafe( $codedText );
1917 * A number of web browsers are known to corrupt non-ASCII characters
1918 * in a UTF-8 text editing environment. To protect against this,
1919 * detected browsers will be served an armored version of the text,
1920 * with non-ASCII chars converted to numeric HTML character references.
1922 * Preexisting such character references will have a 0 added to them
1923 * to ensure that round-trips do not alter the original data.
1925 * @param string $invalue
1929 function makesafe( $invalue ) {
1930 // Armor existing references for reversability.
1931 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1936 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1937 $bytevalue = ord( $invalue{$i} );
1938 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1939 $result .= chr( $bytevalue );
1941 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1942 $working = $working << 6;
1943 $working +
= ($bytevalue & 0x3F);
1945 if( $bytesleft <= 0 ) {
1946 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1948 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1949 $working = $bytevalue & 0x1F;
1951 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1952 $working = $bytevalue & 0x0F;
1954 } else { //1111 0xxx
1955 $working = $bytevalue & 0x07;
1963 * Reverse the previously applied transliteration of non-ASCII characters
1964 * back to UTF-8. Used to protect data from corruption by broken web browsers
1965 * as listed in $wgBrowserBlackList.
1967 * @param string $invalue
1971 function unmakesafe( $invalue ) {
1973 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1974 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
1978 $hexstring .= $invalue{$i};
1980 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1982 // Do some sanity checks. These aren't needed for reversability,
1983 // but should help keep the breakage down if the editor
1984 // breaks one of the entities whilst editing.
1985 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1986 $codepoint = hexdec($hexstring);
1987 $result .= codepointToUtf8( $codepoint );
1989 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1992 $result .= substr( $invalue, $i, 1 );
1995 // reverse the transform that we made for reversability reasons.
1996 return strtr( $result, array( "�" => "&#x" ) );
1999 function noCreatePermission() {
2001 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2002 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );