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);
106 #Sanity check, make sure it's the right page.
107 # Otherwise, $text will be left as-is.
108 if (!is_null($undorev) && $undorev->getPage() == $this->mArticle
->getID()) {
109 $oldrev = $undorev->getPrevious();
110 $undorev_text = $undorev->getText();
111 $oldrev_text = $oldrev->getText();
112 $currev_text = $text;
114 #No use doing a merge if it's just a straight revert.
115 if ($currev_text != $undorev_text) {
116 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
118 $text = $oldrev_text;
123 # Inform the user of our success and set an automatic edit summary
124 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
125 $this->summary
= wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
126 $this->formtype
= 'diff';
128 # Warn the user that something went wrong
129 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
134 else if( $section != '' ) {
135 if( $section == 'new' ) {
136 $text = $this->getPreloadedText( $preload );
138 $text = $wgParser->getSection( $text, $section );
143 wfProfileOut( __METHOD__
);
148 * Get the contents of a page from its title and remove includeonly tags
150 * @param $preload String: the title of the page.
151 * @return string The contents of the page.
153 private function getPreloadedText($preload) {
154 if ( $preload === '' )
157 $preloadTitle = Title
::newFromText( $preload );
158 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
159 $rev=Revision
::newFromTitle($preloadTitle);
160 if ( is_object( $rev ) ) {
161 $text = $rev->getText();
162 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
163 // its own mini-parser! -ævar
164 $text = preg_replace( '~</?includeonly>~', '', $text );
173 * This is the function that extracts metadata from the article body on the first view.
174 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
175 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
177 function extractMetaDataFromArticle () {
178 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
179 $this->mMetaData
= '' ;
180 if ( !$wgUseMetadataEdit ) return ;
181 if ( $wgMetadataWhitelist == '' ) return ;
183 $t = $this->getContent();
185 # MISSING : <nowiki> filtering
187 # Categories and language links
188 $t = explode ( "\n" , $t ) ;
189 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
190 $cat = $ll = array() ;
191 foreach ( $t AS $key => $x )
193 $y = trim ( strtolower ( $x ) ) ;
194 while ( substr ( $y , 0 , 2 ) == '[[' )
196 $y = explode ( ']]' , trim ( $x ) ) ;
197 $first = array_shift ( $y ) ;
198 $first = explode ( ':' , $first ) ;
199 $ns = array_shift ( $first ) ;
200 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
201 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
203 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
204 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
206 $x = implode ( ']]' , $y ) ;
208 $y = trim ( strtolower ( $x ) ) ;
212 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
213 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
214 $t = implode ( "\n" , $t ) ;
217 $sat = array () ; # stand-alone-templates; must be lowercase
218 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
219 $wl_article = new Article ( $wl_title ) ;
220 $wl = explode ( "\n" , $wl_article->getContent() ) ;
221 foreach ( $wl AS $x )
225 while ( substr ( $x , 0 , 1 ) == '*' )
228 $x = trim ( substr ( $x , 1 ) ) ;
232 $sat[] = strtolower ( $x ) ;
237 # Templates, but only some
238 $t = explode ( '{{' , $t ) ;
240 foreach ( $t AS $key => $x )
242 $y = explode ( '}}' , $x , 2 ) ;
243 if ( count ( $y ) == 2 )
246 $z = explode ( '|' , $z ) ;
247 $tn = array_shift ( $z ) ;
248 if ( in_array ( strtolower ( $tn ) , $sat ) )
250 $tl[] = '{{' . $y[0] . '}}' ;
252 $y = explode ( '}}' , $y[1] , 2 ) ;
254 else $t[$key] = '{{' . $x ;
256 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
259 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
260 $t = implode ( '' , $t ) ;
262 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
263 $this->mArticle
->mContent
= $t ;
264 $this->mMetaData
= $s ;
272 * This is the function that gets called for "action=edit". It
273 * sets up various member variables, then passes execution to
274 * another function, usually showEditForm()
276 * The edit form is self-submitting, so that when things like
277 * preview and edit conflicts occur, we get the same form back
278 * with the extra stuff added. Only when the final submission
279 * is made and all is well do we actually save and redirect to
280 * the newly-edited page.
283 global $wgOut, $wgUser, $wgRequest, $wgTitle;
284 global $wgEmailConfirmToEdit;
286 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
289 $fname = 'EditPage::edit';
290 wfProfileIn( $fname );
291 wfDebug( "$fname: enter\n" );
293 // this is not an article
294 $wgOut->setArticleFlag(false);
296 $this->importFormData( $wgRequest );
297 $this->firsttime
= false;
300 $this->livePreview();
301 wfProfileOut( $fname );
305 if ( ! $this->mTitle
->userCan( 'edit' ) ) {
306 wfDebug( "$fname: user can't edit\n" );
307 $wgOut->readOnlyPage( $this->getContent(), true );
308 wfProfileOut( $fname );
311 wfDebug( "$fname: Checking blocks\n" );
312 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
313 # When previewing, don't check blocked state - will get caught at save time.
314 # Also, check when starting edition is done against slave to improve performance.
315 wfDebug( "$fname: user is blocked\n" );
316 $this->blockedPage();
317 wfProfileOut( $fname );
320 if ( !$wgUser->isAllowed('edit') ) {
321 if ( $wgUser->isAnon() ) {
322 wfDebug( "$fname: user must log in\n" );
323 $this->userNotLoggedInPage();
324 wfProfileOut( $fname );
327 wfDebug( "$fname: read-only page\n" );
328 $wgOut->readOnlyPage( $this->getContent(), true );
329 wfProfileOut( $fname );
333 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
334 wfDebug("$fname: user must confirm e-mail address\n");
335 $this->userNotConfirmedPage();
336 wfProfileOut($fname);
339 if ( !$this->mTitle
->userCan( 'create' ) && !$this->mTitle
->exists() ) {
340 wfDebug( "$fname: no create permission\n" );
341 $this->noCreatePermission();
342 wfProfileOut( $fname );
345 if ( wfReadOnly() ) {
346 wfDebug( "$fname: read-only mode is engaged\n" );
347 if( $this->save ||
$this->preview
) {
348 $this->formtype
= 'preview';
349 } else if ( $this->diff
) {
350 $this->formtype
= 'diff';
352 $wgOut->readOnlyPage( $this->getContent() );
353 wfProfileOut( $fname );
358 $this->formtype
= 'save';
359 } else if ( $this->preview
) {
360 $this->formtype
= 'preview';
361 } else if ( $this->diff
) {
362 $this->formtype
= 'diff';
363 } else { # First time through
364 $this->firsttime
= true;
365 if( $this->previewOnOpen() ) {
366 $this->formtype
= 'preview';
368 $this->extractMetaDataFromArticle () ;
369 $this->formtype
= 'initial';
374 wfProfileIn( "$fname-business-end" );
376 $this->isConflict
= false;
377 // css / js subpages of user pages get a special treatment
378 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
379 $this->isValidCssJsSubpage
= $wgTitle->isValidCssJsSubpage();
381 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
382 * no matter it's current state
384 $this->deletedSinceEdit
= false;
385 if ( $this->edittime
!= '' ) {
386 /* Note that we rely on logging table, which hasn't been always there,
387 * but that doesn't matter, because this only applies to brand new
388 * deletes. This is done on every preview and save request. Move it further down
389 * to only perform it on saves
391 if ( $this->mTitle
->isDeleted() ) {
392 $this->lastDelete
= $this->getLastDelete();
393 if ( !is_null($this->lastDelete
) ) {
394 $deletetime = $this->lastDelete
->log_timestamp
;
395 if ( ($deletetime - $this->starttime
) > 0 ) {
396 $this->deletedSinceEdit
= true;
402 if(!$this->mTitle
->getArticleID() && ('initial' == $this->formtype ||
$this->firsttime
)) { # new article
405 if( $this->mTitle
->isTalkPage() ) {
406 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
409 # Attempt submission here. This will check for edit conflicts,
410 # and redundantly check for locked database, blocked IPs, etc.
411 # that edit() already checked just in case someone tries to sneak
412 # in the back door with a hand-edited submission URL.
414 if ( 'save' == $this->formtype
) {
415 if ( !$this->attemptSave() ) {
416 wfProfileOut( "$fname-business-end" );
417 wfProfileOut( $fname );
422 # First time through: get contents, set time for conflict
424 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
425 $this->initialiseForm();
426 if( !$this->mTitle
->getArticleId() )
427 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
430 $this->showEditForm();
431 wfProfileOut( "$fname-business-end" );
432 wfProfileOut( $fname );
436 * Return true if this page should be previewed when the edit form
437 * is initially opened.
441 function previewOnOpen() {
443 return $this->section
!= 'new' &&
444 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle
->exists() ) ||
445 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
446 !$this->mTitle
->exists() ) );
453 function importFormData( &$request ) {
454 global $wgLang, $wgUser;
455 $fname = 'EditPage::importFormData';
456 wfProfileIn( $fname );
458 if( $request->wasPosted() ) {
459 # These fields need to be checked for encoding.
460 # Also remove trailing whitespace, but don't remove _initial_
461 # whitespace from the text boxes. This may be significant formatting.
462 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
463 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
464 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
465 # Truncate for whole multibyte characters. +5 bytes for ellipsis
466 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
468 $this->edittime
= $request->getVal( 'wpEdittime' );
469 $this->starttime
= $request->getVal( 'wpStarttime' );
471 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
473 if( is_null( $this->edittime
) ) {
474 # If the form is incomplete, force to preview.
475 wfDebug( "$fname: Form data appears to be incomplete\n" );
476 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
477 $this->preview
= true;
479 /* Fallback for live preview */
480 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
481 $this->diff
= $request->getCheck( 'wpDiff' );
483 // Remember whether a save was requested, so we can indicate
484 // if we forced preview due to session failure.
485 $this->mTriedSave
= !$this->preview
;
487 if ( $this->tokenOk( $request ) ) {
488 # Some browsers will not report any submit button
489 # if the user hits enter in the comment box.
490 # The unmarked state will be assumed to be a save,
491 # if the form seems otherwise complete.
492 wfDebug( "$fname: Passed token check.\n" );
493 } else if ( $this->diff
) {
494 # Failed token check, but only requested "Show Changes".
495 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
497 # Page might be a hack attempt posted from
498 # an external site. Preview instead of saving.
499 wfDebug( "$fname: Failed token check; forcing preview\n" );
500 $this->preview
= true;
503 $this->save
= ! ( $this->preview
OR $this->diff
);
504 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
505 $this->edittime
= null;
508 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
509 $this->starttime
= null;
512 $this->recreate
= $request->getCheck( 'wpRecreate' );
514 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
515 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
517 # Don't force edit summaries when a user is editing their own user or talk page
518 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
519 $this->allowBlankSummary
= true;
521 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
524 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
526 # Not a posted form? Start with nothing.
527 wfDebug( "$fname: Not a posted form.\n" );
528 $this->textbox1
= '';
529 $this->textbox2
= '';
530 $this->mMetaData
= '';
532 $this->edittime
= '';
533 $this->starttime
= wfTimestampNow();
534 $this->preview
= false;
537 $this->minoredit
= false;
538 $this->watchthis
= false;
539 $this->recreate
= false;
542 $this->oldid
= $request->getInt( 'oldid' );
544 # Section edit can come from either the form or a link
545 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
547 $this->live
= $request->getCheck( 'live' );
548 $this->editintro
= $request->getText( 'editintro' );
550 wfProfileOut( $fname );
554 * Make sure the form isn't faking a user's credentials.
556 * @param $request WebRequest
560 function tokenOk( &$request ) {
562 if( $wgUser->isAnon() ) {
563 # Anonymous users may not have a session
564 # open. Check for suffix anyway.
565 $this->mTokenOk
= ( EDIT_TOKEN_SUFFIX
== $request->getVal( 'wpEditToken' ) );
567 $this->mTokenOk
= $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
569 return $this->mTokenOk
;
573 function showIntro() {
574 global $wgOut, $wgUser;
575 $addstandardintro=true;
576 if($this->editintro
) {
577 $introtitle=Title
::newFromText($this->editintro
);
578 if(isset($introtitle) && $introtitle->userCanRead()) {
579 $rev=Revision
::newFromTitle($introtitle);
581 $wgOut->addSecondaryWikiText($rev->getText());
582 $addstandardintro=false;
586 if($addstandardintro) {
587 if ( $wgUser->isLoggedIn() )
588 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
590 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
596 * @return bool false if output is done, true if the rest of the form should be displayed
598 function attemptSave() {
599 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
600 global $wgMaxArticleSize;
602 $fname = 'EditPage::attemptSave';
603 wfProfileIn( $fname );
604 wfProfileIn( "$fname-checks" );
606 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
608 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
612 # Reintegrate metadata
613 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
614 $this->mMetaData
= '' ;
618 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
619 $this->spamPage ( $matches[0] );
620 wfProfileOut( "$fname-checks" );
621 wfProfileOut( $fname );
624 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
625 # Error messages or other handling should be performed by the filter function
626 wfProfileOut( $fname );
627 wfProfileOut( "$fname-checks" );
630 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
) ) ) {
631 # Error messages etc. could be handled within the hook...
632 wfProfileOut( $fname );
633 wfProfileOut( "$fname-checks" );
635 } elseif( $this->hookError
!= '' ) {
636 # ...or the hook could be expecting us to produce an error
637 wfProfileOut( "$fname-checks " );
638 wfProfileOut( $fname );
641 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
642 # Check block state against master, thus 'false'.
643 $this->blockedPage();
644 wfProfileOut( "$fname-checks" );
645 wfProfileOut( $fname );
648 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
649 if ( $this->kblength
> $wgMaxArticleSize ) {
650 // Error will be displayed by showEditForm()
651 $this->tooBig
= true;
652 wfProfileOut( "$fname-checks" );
653 wfProfileOut( $fname );
657 if ( !$wgUser->isAllowed('edit') ) {
658 if ( $wgUser->isAnon() ) {
659 $this->userNotLoggedInPage();
660 wfProfileOut( "$fname-checks" );
661 wfProfileOut( $fname );
665 $wgOut->readOnlyPage();
666 wfProfileOut( "$fname-checks" );
667 wfProfileOut( $fname );
672 if ( wfReadOnly() ) {
673 $wgOut->readOnlyPage();
674 wfProfileOut( "$fname-checks" );
675 wfProfileOut( $fname );
678 if ( $wgUser->pingLimiter() ) {
679 $wgOut->rateLimited();
680 wfProfileOut( "$fname-checks" );
681 wfProfileOut( $fname );
685 # If the article has been deleted while editing, don't save it without
687 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
688 wfProfileOut( "$fname-checks" );
689 wfProfileOut( $fname );
693 wfProfileOut( "$fname-checks" );
695 # If article is new, insert it.
696 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
699 // Late check for create permission, just in case *PARANOIA*
700 if ( !$this->mTitle
->userCan( 'create' ) ) {
701 wfDebug( "$fname: no create permission\n" );
702 $this->noCreatePermission();
703 wfProfileOut( $fname );
707 # Don't save a new article if it's blank.
708 if ( ( '' == $this->textbox1
) ) {
709 $wgOut->redirect( $this->mTitle
->getFullURL() );
710 wfProfileOut( $fname );
714 $isComment=($this->section
=='new');
715 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
716 $this->minoredit
, $this->watchthis
, false, $isComment);
718 wfProfileOut( $fname );
722 # Article exists. Check for edit conflict.
724 $this->mArticle
->clear(); # Force reload of dates, etc.
725 $this->mArticle
->forUpdate( true ); # Lock the article
727 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
728 $this->isConflict
= true;
729 if( $this->section
== 'new' ) {
730 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
731 $this->mArticle
->getComment() == $this->summary
) {
732 // Probably a duplicate submission of a new comment.
733 // This can happen when squid resends a request after
734 // a timeout but the first one actually went through.
735 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
737 // New comment; suppress conflict.
738 $this->isConflict
= false;
739 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
743 $userid = $wgUser->getID();
745 if ( $this->isConflict
) {
746 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
747 $this->mArticle
->getTimestamp() . "'\n" );
748 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
751 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
752 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
754 if( is_null( $text ) ) {
755 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
756 $this->isConflict
= true;
757 $text = $this->textbox1
;
760 # Suppress edit conflict with self, except for section edits where merging is required.
761 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
762 wfDebug( "Suppressing edit conflict, same user.\n" );
763 $this->isConflict
= false;
765 # switch from section editing to normal editing in edit conflict
766 if($this->isConflict
) {
768 if( $this->mergeChangesInto( $text ) ){
769 // Successful merge! Maybe we should tell the user the good news?
770 $this->isConflict
= false;
771 wfDebug( "Suppressing edit conflict, successful merge.\n" );
774 $this->textbox1
= $text;
775 wfDebug( "Keeping edit conflict, failed merge.\n" );
780 if ( $this->isConflict
) {
781 wfProfileOut( $fname );
785 $oldtext = $this->mArticle
->getContent();
787 # Handle the user preference to force summaries here, but not for null edits
788 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary')
789 && 0 != strcmp($oldtext, $text) && !Article
::getRedirectAutosummary( $text )) {
790 if( md5( $this->summary
) == $this->autoSumm
) {
791 $this->missingSummary
= true;
792 wfProfileOut( $fname );
797 #And a similar thing for new sections
798 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
799 if (trim($this->summary
) == '') {
800 $this->missingSummary
= true;
801 wfProfileOut( $fname );
807 wfProfileIn( "$fname-sectionanchor" );
809 if( $this->section
== 'new' ) {
810 if ( $this->textbox1
== '' ) {
811 $this->missingComment
= true;
814 if( $this->summary
!= '' ) {
815 $sectionanchor = $this->sectionAnchor( $this->summary
);
817 } elseif( $this->section
!= '' ) {
818 # Try to get a section anchor from the section source, redirect to edited section if header found
819 # XXX: might be better to integrate this into Article::replaceSection
820 # for duplicate heading checking and maybe parsing
821 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
822 # we can't deal with anchors, includes, html etc in the header for now,
823 # headline would need to be parsed to improve this
824 if($hasmatch and strlen($matches[2]) > 0) {
825 $sectionanchor = $this->sectionAnchor( $matches[2] );
828 wfProfileOut( "$fname-sectionanchor" );
830 // Save errors may fall down to the edit form, but we've now
831 // merged the section into full text. Clear the section field
832 // so that later submission of conflict forms won't try to
833 // replace that into a duplicated mess.
834 $this->textbox1
= $text;
837 // Check for length errors again now that the section is merged in
838 $this->kblength
= (int)(strlen( $text ) / 1024);
839 if ( $this->kblength
> $wgMaxArticleSize ) {
840 $this->tooBig
= true;
841 wfProfileOut( $fname );
845 # update the article here
846 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
847 $this->watchthis
, '', $sectionanchor ) ) {
848 wfProfileOut( $fname );
851 $this->isConflict
= true;
853 wfProfileOut( $fname );
858 * Initialise form fields in the object
859 * Called on the first invocation, e.g. when a user clicks an edit link
861 function initialiseForm() {
862 $this->edittime
= $this->mArticle
->getTimestamp();
864 $this->textbox1
= $this->getContent();
865 if ( !$this->mArticle
->exists() && $this->mArticle
->mTitle
->getNamespace() == NS_MEDIAWIKI
)
866 $this->textbox1
= wfMsgWeirdKey( $this->mArticle
->mTitle
->getText() );
871 * Send the edit form and related headers to $wgOut
872 * @param $formCallback Optional callable that takes an OutputPage
873 * parameter; will be called during form output
874 * near the top, for captchas and the like.
876 function showEditForm( $formCallback=null ) {
877 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
879 $fname = 'EditPage::showEditForm';
880 wfProfileIn( $fname );
882 $sk =& $wgUser->getSkin();
884 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
886 $wgOut->setRobotpolicy( 'noindex,nofollow' );
888 # Enabled article-related sidebar, toplinks, etc.
889 $wgOut->setArticleRelated( true );
891 if ( $this->isConflict
) {
892 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
893 $wgOut->setPageTitle( $s );
894 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
896 $this->textbox2
= $this->textbox1
;
897 $this->textbox1
= $this->getContent();
898 $this->edittime
= $this->mArticle
->getTimestamp();
901 if( $this->section
!= '' ) {
902 if( $this->section
== 'new' ) {
903 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
905 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
907 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
908 preg_match( "/^(=+)(.+)\\1/mi",
911 if( !empty( $matches[2] ) ) {
912 $this->summary
= "/* ". trim($matches[2])." */ ";
917 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
919 $wgOut->setPageTitle( $s );
921 if ( $this->missingComment
) {
922 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
925 if( $this->missingSummary
&& $this->section
!= 'new' ) {
926 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
929 if( $this->missingSummary
&& $this->section
== 'new' ) {
930 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
933 if( !$this->hookError
== '' ) {
934 $wgOut->addWikiText( $this->hookError
);
937 if ( !$this->checkUnicodeCompliantBrowser() ) {
938 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
940 if ( isset( $this->mArticle
)
941 && isset( $this->mArticle
->mRevision
)
942 && !$this->mArticle
->mRevision
->isCurrent() ) {
943 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
944 $wgOut->addWikiText( wfMsg( 'editingold' ) );
949 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
950 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
951 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
953 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
954 # Check the skin exists
955 if( $this->isValidCssJsSubpage
) {
956 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
958 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
963 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
964 # Show a warning if editing an interface message
965 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
966 } elseif( $this->mTitle
->isProtected( 'edit' ) ) {
967 # Is the title semi-protected?
968 if( $this->mTitle
->isSemiProtected() ) {
969 $notice = wfMsg( 'semiprotectedpagewarning' );
970 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' )
973 # It's either cascading protection or regular protection; work out which
974 $cascadeSources = $this->mTitle
->getCascadeProtectionSources();
975 if( $cascadeSources && count( $cascadeSources ) > 0 ) {
976 # Cascading protection; explain, and list the titles responsible
977 $notice = wfMsg( 'cascadeprotectedwarning' ) . "\n";
978 foreach( $cascadeSources as $source )
979 $notice .= '* [[:' . $source->getPrefixedText() . "]]\n";
982 $notice = wfMsg( 'protectedpagewarning' );
985 $wgOut->addWikiText( $notice );
988 if ( $this->kblength
=== false ) {
989 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
991 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
992 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgMaxArticleSize ) );
993 } elseif( $this->kblength
> 29 ) {
994 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) ) );
997 #need to parse the preview early so that we know which templates are used,
998 #otherwise users with "show preview after edit box" will get a blank list
999 if ( $this->formtype
== 'preview' ) {
1000 $previewOutput = $this->getPreviewText();
1003 $rows = $wgUser->getIntOption( 'rows' );
1004 $cols = $wgUser->getIntOption( 'cols' );
1006 $ew = $wgUser->getOption( 'editwidth' );
1007 if ( $ew ) $ew = " style=\"width:100%\"";
1010 $q = 'action=submit';
1011 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1012 $action = $this->mTitle
->escapeLocalURL( $q );
1014 $summary = wfMsg('summary');
1015 $subject = wfMsg('subject');
1016 $minor = wfMsgExt('minoredit', array('parseinline'));
1017 $watchthis = wfMsgExt('watchthis', array('parseinline'));
1019 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
1020 wfMsgExt('cancel', array('parseinline')) );
1021 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1022 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1023 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1024 htmlspecialchars( wfMsg( 'newwindow' ) );
1026 global $wgRightsText;
1027 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1028 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
1029 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1030 $wgRightsText ) . "\n</div>";
1032 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1033 # prepare toolbar for edit buttons
1034 $toolbar = $this->getEditToolbar();
1039 // activate checkboxes if user wants them to be always active
1040 if( !$this->preview
&& !$this->diff
) {
1041 # Sort out the "watch" checkbox
1042 if( $wgUser->getOption( 'watchdefault' ) ) {
1044 $this->watchthis
= true;
1045 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1047 $this->watchthis
= true;
1048 } elseif( $this->mTitle
->userIsWatching() ) {
1050 $this->watchthis
= true;
1053 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1056 $minoredithtml = '';
1058 if ( $wgUser->isAllowed('minoredit') ) {
1060 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?
" checked='checked'":"").
1061 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />\n".
1062 "<label for='wpMinoredit'".$sk->tooltipAndAccesskey('minoredit').">{$minor}</label>\n";
1067 if ( $wgUser->isLoggedIn() ) {
1068 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
1069 ($this->watchthis?
" checked='checked'":"").
1070 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />\n".
1071 "<label for='wpWatchthis'".$sk->tooltipAndAccesskey('watch').">{$watchthis}</label>\n";
1074 $checkboxhtml = $minoredithtml . $watchhtml;
1076 $wgOut->addHTML( $this->editFormPageTop
);
1078 if ( $wgUser->getOption( 'previewontop' ) ) {
1080 if ( 'preview' == $this->formtype
) {
1081 $this->showPreview( $previewOutput );
1083 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1086 if ( 'diff' == $this->formtype
) {
1087 $wgOut->addHTML( $this->getDiff() );
1092 $wgOut->addHTML( $this->editFormTextTop
);
1094 # if this is a comment, show a subject line at the top, which is also the edit summary.
1095 # Otherwise, show a summary field at the bottom
1096 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1097 if( $this->section
== 'new' ) {
1098 $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 />";
1100 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1101 $summarypreview = '';
1103 $commentsubject = '';
1104 $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 />";
1105 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1106 $subjectpreview = '';
1109 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1110 if( !$this->preview
&& !$this->diff
) {
1111 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1113 $templates = ($this->preview ||
$this->section
) ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1114 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1116 global $wgUseMetadataEdit ;
1117 if ( $wgUseMetadataEdit ) {
1118 $metadata = $this->mMetaData
;
1119 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1120 $top = wfMsgWikiHtml( 'metadata_help' );
1121 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1123 else $metadata = "" ;
1127 if ($this->deletedSinceEdit
) {
1128 if ( 'save' != $this->formtype
) {
1129 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1131 // Hide the toolbar and edit area, use can click preview to get it back
1132 // Add an confirmation checkbox and explanation.
1134 $hidden = 'type="hidden" style="display:none;"';
1135 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1137 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1138 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1147 'value' => wfMsg('savearticle'),
1148 'accesskey' => wfMsg('accesskey-save'),
1149 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1151 $buttons['save'] = wfElement('input', $temp, '');
1157 'value' => wfMsg('showdiff'),
1158 'accesskey' => wfMsg('accesskey-diff'),
1159 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1161 $buttons['diff'] = wfElement('input', $temp, '');
1163 global $wgLivePreview;
1164 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1166 'id' => 'wpPreview',
1167 'name' => 'wpPreview',
1170 'value' => wfMsg('showpreview'),
1172 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1173 'style' => 'display: none;',
1175 $buttons['preview'] = wfElement('input', $temp, '');
1177 'id' => 'wpLivePreview',
1178 'name' => 'wpLivePreview',
1181 'value' => wfMsg('showlivepreview'),
1182 'accesskey' => wfMsg('accesskey-preview'),
1184 'onclick' => $this->doLivePreviewScript(),
1186 $buttons['live'] = wfElement('input', $temp, '');
1189 'id' => 'wpPreview',
1190 'name' => 'wpPreview',
1193 'value' => wfMsg('showpreview'),
1194 'accesskey' => wfMsg('accesskey-preview'),
1195 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1197 $buttons['preview'] = wfElement('input', $temp, '');
1198 $buttons['live'] = '';
1201 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1203 : "<input type='hidden' name=\"safemode\" value='1' />\n";
1205 $wgOut->addHTML( <<<END
1207 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1211 if( is_callable( $formCallback ) ) {
1212 call_user_func_array( $formCallback, array( &$wgOut ) );
1215 // Put these up at the top to ensure they aren't lost on early form submission
1217 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1218 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1219 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1220 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1222 $wgOut->addHTML( <<<END
1226 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1227 cols='{$cols}'{$ew} $hidden>
1229 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
1234 $wgOut->addWikiText( $copywarn );
1235 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1245 "<div class='editButtons'>
1247 {$buttons['preview']}
1250 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1251 </div><!-- editButtons -->
1252 </div><!-- editOptions -->");
1254 $wgOut->addHtml( '<div class="mw-editTools">' );
1255 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1256 $wgOut->addHtml( '</div>' );
1258 $wgOut->addHTML( $this->editFormTextAfterTools
);
1261 <div class='templatesUsed'>
1262 {$formattedtemplates}
1267 * To make it harder for someone to slip a user a page
1268 * which submits an edit form to the wiki without their
1269 * knowledge, a random token is associated with the login
1270 * session. If it's not passed back with the submission,
1271 * we won't save the page, or render user JavaScript and
1274 * For anon editors, who may not have a session, we just
1275 * include the constant suffix to prevent editing from
1276 * broken text-mangling proxies.
1278 if ( $wgUser->isLoggedIn() )
1279 $token = htmlspecialchars( $wgUser->editToken() );
1281 $token = EDIT_TOKEN_SUFFIX
;
1282 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1285 # If a blank edit summary was previously provided, and the appropriate
1286 # user preference is active, pass a hidden tag here. This will stop the
1287 # user being bounced back more than once in the event that a summary
1289 if( $this->missingSummary
) {
1290 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1293 # For a bit more sophisticated detection of blank summaries, hash the
1294 # automatic one and pass that in a hidden field.
1295 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1296 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1298 if ( $this->isConflict
) {
1299 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1301 $de = new DifferenceEngine( $this->mTitle
);
1302 $de->setText( $this->textbox2
, $this->textbox1
);
1303 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1305 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1306 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1307 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1309 $wgOut->addHTML( $this->editFormTextBottom
);
1310 $wgOut->addHTML( "</form>\n" );
1311 if ( !$wgUser->getOption( 'previewontop' ) ) {
1313 if ( $this->formtype
== 'preview') {
1314 $this->showPreview( $previewOutput );
1316 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1319 if ( $this->formtype
== 'diff') {
1320 $wgOut->addHTML( $this->getDiff() );
1325 wfProfileOut( $fname );
1329 * Append preview output to $wgOut.
1330 * Includes category rendering if this is a category page.
1332 * @param string $text The HTML to be output for the preview.
1334 private function showPreview( $text ) {
1337 $wgOut->addHTML( '<div id="wikiPreview">' );
1338 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1339 $this->mArticle
->openShowCategory();
1341 $wgOut->addHTML( $text );
1342 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1343 $this->mArticle
->closeShowCategory();
1345 $wgOut->addHTML( '</div>' );
1349 * Live Preview lets us fetch rendered preview page content and
1350 * add it to the page without refreshing the whole page.
1351 * If not supported by the browser it will fall through to the normal form
1352 * submission method.
1354 * This function outputs a script tag to support live preview, and
1355 * returns an onclick handler which should be added to the attributes
1356 * of the preview button
1358 function doLivePreviewScript() {
1359 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1360 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1361 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1362 '"></script>' . "\n" );
1363 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1364 return "return !livePreview(" .
1365 "getElementById('wikiPreview')," .
1366 "editform.wpTextbox1.value," .
1367 '"' . $liveAction . '"' . ")";
1370 function getLastDelete() {
1371 $dbr =& wfGetDB( DB_SLAVE
);
1372 $fname = 'EditPage::getLastDelete';
1373 $res = $dbr->select(
1374 array( 'logging', 'user' ),
1384 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1385 'log_title' => $this->mTitle
->getDBkey(),
1386 'log_type' => 'delete',
1387 'log_action' => 'delete',
1388 'user_id=log_user' ),
1390 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1392 if($dbr->numRows($res) == 1) {
1393 while ( $x = $dbr->fetchObject ( $res ) )
1395 $dbr->freeResult ( $res ) ;
1405 function getPreviewText() {
1406 global $wgOut, $wgUser, $wgTitle, $wgParser;
1408 $fname = 'EditPage::getPreviewText';
1409 wfProfileIn( $fname );
1411 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1412 $msg = 'session_fail_preview';
1414 $msg = 'previewnote';
1416 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1417 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1418 if ( $this->isConflict
) {
1419 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1422 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1423 $parserOptions->setEditSection( false );
1426 if( $wgRawHtml && !$this->mTokenOk
) {
1427 // Could be an offsite preview attempt. This is very unsafe if
1428 // HTML is enabled, as it could be an attack.
1429 return $wgOut->parse( "<div class='previewnote'>" .
1430 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1433 # don't parse user css/js, show message about preview
1434 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1436 if ( $this->isCssJsSubpage
) {
1437 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1438 $previewtext = wfMsg('usercsspreview');
1439 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1440 $previewtext = wfMsg('userjspreview');
1442 $parserOptions->setTidy(true);
1443 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1444 $wgOut->addHTML( $parserOutput->mText
);
1445 wfProfileOut( $fname );
1446 return $previewhead;
1448 $toparse = $this->textbox1
;
1450 # If we're adding a comment, we need to show the
1451 # summary as the headline
1452 if($this->section
=="new" && $this->summary
!="") {
1453 $toparse="== {$this->summary} ==\n\n".$toparse;
1456 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1457 $parserOptions->setTidy(true);
1458 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1459 $wgTitle, $parserOptions );
1461 $previewHTML = $parserOutput->getText();
1462 $wgOut->addParserOutputNoText( $parserOutput );
1464 foreach ( $parserOutput->getTemplates() as $ns => $template)
1465 foreach ( array_keys( $template ) as $dbk)
1466 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1468 wfProfileOut( $fname );
1469 return $previewhead . $previewHTML;
1474 * Call the stock "user is blocked" page
1476 function blockedPage() {
1477 global $wgOut, $wgUser;
1478 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1480 # If the user made changes, preserve them when showing the markup
1481 # (This happens when a user is blocked during edit, for instance)
1482 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1484 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1486 $source = $this->textbox1
;
1489 # Spit out the source or the user's modified version
1490 if( $source !== false ) {
1491 $rows = $wgUser->getOption( 'rows' );
1492 $cols = $wgUser->getOption( 'cols' );
1493 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1494 $wgOut->addHtml( '<hr />' );
1495 $wgOut->addWikiText( wfMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() ) );
1496 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1501 * Produce the stock "please login to edit pages" page
1503 function userNotLoggedInPage() {
1504 global $wgUser, $wgOut;
1505 $skin = $wgUser->getSkin();
1507 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1508 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle
->getPrefixedUrl() );
1510 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1511 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1512 $wgOut->setArticleRelated( false );
1514 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1515 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1519 * Creates a basic error page which informs the user that
1520 * they have to validate their email address before being
1523 function userNotConfirmedPage() {
1526 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1527 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1528 $wgOut->setArticleRelated( false );
1530 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1531 $wgOut->returnToMain( false );
1535 * Produce the stock "your edit contains spam" page
1537 * @param $match Text which triggered one or more filters
1539 function spamPage( $match = false ) {
1542 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1543 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1544 $wgOut->setArticleRelated( false );
1546 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1548 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1550 $wgOut->returnToMain( false );
1557 function mergeChangesInto( &$editText ){
1558 $fname = 'EditPage::mergeChangesInto';
1559 wfProfileIn( $fname );
1561 $db =& wfGetDB( DB_MASTER
);
1563 // This is the revision the editor started from
1564 $baseRevision = Revision
::loadFromTimestamp(
1565 $db, $this->mArticle
->mTitle
, $this->edittime
);
1566 if( is_null( $baseRevision ) ) {
1567 wfProfileOut( $fname );
1570 $baseText = $baseRevision->getText();
1572 // The current state, we want to merge updates into it
1573 $currentRevision = Revision
::loadFromTitle(
1574 $db, $this->mArticle
->mTitle
);
1575 if( is_null( $currentRevision ) ) {
1576 wfProfileOut( $fname );
1579 $currentText = $currentRevision->getText();
1582 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1583 $editText = $result;
1584 wfProfileOut( $fname );
1587 wfProfileOut( $fname );
1593 * Check if the browser is on a blacklist of user-agents known to
1594 * mangle UTF-8 data on form submission. Returns true if Unicode
1595 * should make it through, false if it's known to be a problem.
1599 function checkUnicodeCompliantBrowser() {
1600 global $wgBrowserBlackList;
1601 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1602 // No User-Agent header sent? Trust it by default...
1605 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1606 foreach ( $wgBrowserBlackList as $browser ) {
1607 if ( preg_match($browser, $currentbrowser) ) {
1615 * Format an anchor fragment as it would appear for a given section name
1616 * @param string $text
1620 function sectionAnchor( $text ) {
1621 $headline = Sanitizer
::decodeCharReferences( $text );
1623 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1624 $headline = trim( $headline );
1625 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1626 $replacearray = array(
1631 array_keys( $replacearray ),
1632 array_values( $replacearray ),
1637 * Shows a bulletin board style toolbar for common editing functions.
1638 * It can be disabled in the user preferences.
1639 * The necessary JavaScript code can be found in style/wikibits.js.
1641 function getEditToolbar() {
1642 global $wgStylePath, $wgContLang, $wgJsMimeType;
1645 * toolarray an array of arrays which each include the filename of
1646 * the button image (without path), the opening tag, the closing tag,
1647 * and optionally a sample text that is inserted between the two when no
1648 * selection is highlighted.
1649 * The tip text is shown when the user moves the mouse over the button.
1651 * Already here are accesskeys (key), which are not used yet until someone
1652 * can figure out a way to make them work in IE. However, we should make
1653 * sure these keys are not defined on the edit page.
1656 array( 'image'=>'button_bold.png',
1657 'open' => '\\\'\\\'\\\'',
1658 'close' => '\\\'\\\'\\\'',
1659 'sample'=> wfMsg('bold_sample'),
1660 'tip' => wfMsg('bold_tip'),
1663 array( 'image'=>'button_italic.png',
1664 'open' => '\\\'\\\'',
1665 'close' => '\\\'\\\'',
1666 'sample'=> wfMsg('italic_sample'),
1667 'tip' => wfMsg('italic_tip'),
1670 array( 'image'=>'button_link.png',
1673 'sample'=> wfMsg('link_sample'),
1674 'tip' => wfMsg('link_tip'),
1677 array( 'image'=>'button_extlink.png',
1680 'sample'=> wfMsg('extlink_sample'),
1681 'tip' => wfMsg('extlink_tip'),
1684 array( 'image'=>'button_headline.png',
1686 'close' => " ==\\n",
1687 'sample'=> wfMsg('headline_sample'),
1688 'tip' => wfMsg('headline_tip'),
1691 array( 'image'=>'button_image.png',
1692 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1694 'sample'=> wfMsg('image_sample'),
1695 'tip' => wfMsg('image_tip'),
1698 array( 'image' =>'button_media.png',
1699 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1701 'sample'=> wfMsg('media_sample'),
1702 'tip' => wfMsg('media_tip'),
1705 array( 'image' =>'button_math.png',
1707 'close' => "<\\/math>",
1708 'sample'=> wfMsg('math_sample'),
1709 'tip' => wfMsg('math_tip'),
1712 array( 'image' =>'button_nowiki.png',
1713 'open' => "<nowiki>",
1714 'close' => "<\\/nowiki>",
1715 'sample'=> wfMsg('nowiki_sample'),
1716 'tip' => wfMsg('nowiki_tip'),
1719 array( 'image' =>'button_sig.png',
1723 'tip' => wfMsg('sig_tip'),
1726 array( 'image' =>'button_hr.png',
1727 'open' => "\\n----\\n",
1730 'tip' => wfMsg('hr_tip'),
1734 $toolbar = "<div id='toolbar'>\n";
1735 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1737 foreach($toolarray as $tool) {
1739 $image=$wgStylePath.'/common/images/'.$tool['image'];
1740 $open=$tool['open'];
1741 $close=$tool['close'];
1742 $sample = wfEscapeJsString( $tool['sample'] );
1744 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1745 // Older browsers show a "speedtip" type message only for ALT.
1746 // Ideally these should be different, realistically they
1747 // probably don't need to be.
1748 $tip = wfEscapeJsString( $tool['tip'] );
1750 #$key = $tool["key"];
1752 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1755 $toolbar.="/*]]>*/\n</script>";
1756 $toolbar.="\n</div>";
1761 * Output preview text only. This can be sucked into the edit page
1762 * via JavaScript, and saves the server time rendering the skin as
1763 * well as theoretically being more robust on the client (doesn't
1764 * disturb the edit box's undo history, won't eat your text on
1767 * @todo This doesn't include category or interlanguage links.
1768 * Would need to enhance it a bit, maybe wrap them in XML
1769 * or something... that might also require more skin
1770 * initialization, so check whether that's a problem.
1772 function livePreview() {
1775 header( 'Content-type: text/xml' );
1776 header( 'Cache-control: no-cache' );
1778 echo $this->getPreviewText( );
1779 /* To not shake screen up and down between preview and live-preview */
1780 echo "<br style=\"clear:both;\" />\n";
1785 * Get a diff between the current contents of the edit box and the
1786 * version of the page we're editing from.
1788 * If this is a section edit, we'll replace the section as for final
1789 * save and then make a comparison.
1791 * @return string HTML
1793 function getDiff() {
1794 $oldtext = $this->mArticle
->fetchContent();
1795 $newtext = $this->mArticle
->replaceSection(
1796 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1797 $newtext = $this->mArticle
->preSaveTransform( $newtext );
1798 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1799 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1800 if ( $oldtext !== false ||
$newtext != '' ) {
1801 $de = new DifferenceEngine( $this->mTitle
);
1802 $de->setText( $oldtext, $newtext );
1803 $difftext = $de->getDiff( $oldtitle, $newtitle );
1808 return '<div id="wikiDiff">' . $difftext . '</div>';
1812 * Filter an input field through a Unicode de-armoring process if it
1813 * came from an old browser with known broken Unicode editing issues.
1815 * @param WebRequest $request
1816 * @param string $field
1820 function safeUnicodeInput( $request, $field ) {
1821 $text = rtrim( $request->getText( $field ) );
1822 return $request->getBool( 'safemode' )
1823 ?
$this->unmakesafe( $text )
1828 * Filter an output field through a Unicode armoring process if it is
1829 * going to an old browser with known broken Unicode editing issues.
1831 * @param string $text
1835 function safeUnicodeOutput( $text ) {
1837 $codedText = $wgContLang->recodeForEdit( $text );
1838 return $this->checkUnicodeCompliantBrowser()
1840 : $this->makesafe( $codedText );
1844 * A number of web browsers are known to corrupt non-ASCII characters
1845 * in a UTF-8 text editing environment. To protect against this,
1846 * detected browsers will be served an armored version of the text,
1847 * with non-ASCII chars converted to numeric HTML character references.
1849 * Preexisting such character references will have a 0 added to them
1850 * to ensure that round-trips do not alter the original data.
1852 * @param string $invalue
1856 function makesafe( $invalue ) {
1857 // Armor existing references for reversability.
1858 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1863 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1864 $bytevalue = ord( $invalue{$i} );
1865 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1866 $result .= chr( $bytevalue );
1868 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1869 $working = $working << 6;
1870 $working +
= ($bytevalue & 0x3F);
1872 if( $bytesleft <= 0 ) {
1873 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1875 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1876 $working = $bytevalue & 0x1F;
1878 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1879 $working = $bytevalue & 0x0F;
1881 } else { //1111 0xxx
1882 $working = $bytevalue & 0x07;
1890 * Reverse the previously applied transliteration of non-ASCII characters
1891 * back to UTF-8. Used to protect data from corruption by broken web browsers
1892 * as listed in $wgBrowserBlackList.
1894 * @param string $invalue
1898 function unmakesafe( $invalue ) {
1900 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1901 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
1905 $hexstring .= $invalue{$i};
1907 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1909 // Do some sanity checks. These aren't needed for reversability,
1910 // but should help keep the breakage down if the editor
1911 // breaks one of the entities whilst editing.
1912 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1913 $codepoint = hexdec($hexstring);
1914 $result .= codepointToUtf8( $codepoint );
1916 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1919 $result .= substr( $invalue, $i, 1 );
1922 // reverse the transform that we made for reversability reasons.
1923 return strtr( $result, array( "�" => "&#x" ) );
1926 function noCreatePermission() {
1928 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1929 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );