3 * Contains the EditPage class
7 * The edit page/HTML interface (split from Article)
8 * The actual database and text munging is still in Article,
9 * but it should get easier to call those from alternate
16 var $isConflict = false;
17 var $isCssJsSubpage = false;
18 var $deletedSinceEdit = false;
22 var $mTokenOk = false;
23 var $mTriedSave = false;
25 var $kblength = false;
26 var $missingComment = false;
27 var $missingSummary = false;
28 var $allowBlankSummary = false;
31 var $mPreviewTemplates;
34 var $save = false, $preview = false, $diff = false;
35 var $minoredit = false, $watchthis = false, $recreate = false;
36 var $textbox1 = '', $textbox2 = '', $summary = '';
37 var $edittime = '', $section = '', $starttime = '';
38 var $oldid = 0, $editintro = '', $scrolltop = null;
40 # Placeholders for text injection by hooks (must be HTML)
41 # extensions should take care to _append_ to the present value
42 public $editFormPageTop; // Before even the preview
43 public $editFormTextTop;
44 public $editFormTextAfterWarn;
45 public $editFormTextAfterTools;
46 public $editFormTextBottom;
52 function EditPage( $article ) {
53 $this->mArticle
=& $article;
55 $this->mTitle
=& $wgTitle;
57 # Placeholders for text injection by hooks (empty per default)
58 $this->editFormPageTop
=
59 $this->editFormTextTop
=
60 $this->editFormTextAfterWarn
=
61 $this->editFormTextAfterTools
=
62 $this->editFormTextBottom
= "";
66 * Fetch initial editing page content.
68 private function getContent( $def_text = '' ) {
69 global $wgOut, $wgRequest, $wgParser;
71 # Get variables from query string :P
72 $section = $wgRequest->getVal( 'section' );
73 $preload = $wgRequest->getVal( 'preload' );
74 $undoafter = $wgRequest->getVal( 'undoafter' );
75 $undo = $wgRequest->getVal( 'undo' );
77 wfProfileIn( __METHOD__
);
80 if( !$this->mTitle
->exists() ) {
81 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
82 # If this is a system message, get the default text.
83 $text = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
85 # If requested, preload some text.
86 $text = $this->getPreloadedText( $preload );
88 # We used to put MediaWiki:Newarticletext here if
89 # $text was empty at this point.
90 # This is now shown above the edit box instead.
92 // FIXME: may be better to use Revision class directly
93 // But don't mess with it just yet. Article knows how to
94 // fetch the page record from the high-priority server,
95 // which is needed to guarantee we don't pick up lagged
98 $text = $this->mArticle
->getContent();
100 if ( $undo > 0 && $undo > $undoafter ) {
101 # Undoing a specific edit overrides section editing; section-editing
102 # doesn't work with undoing.
104 $undorev = Revision
::newFromId($undo);
105 $oldrev = Revision
::newFromId($undoafter);
107 $undorev = Revision
::newFromId($undo);
108 $oldrev = $undorev ?
$undorev->getPrevious() : null;
111 #Sanity check, make sure it's the right page.
112 # Otherwise, $text will be left as-is.
113 if ( !is_null($undorev) && !is_null($oldrev) && $undorev->getPage()==$oldrev->getPage() && $undorev->getPage()==$this->mArticle
->getID() ) {
114 $undorev_text = $undorev->getText();
115 $oldrev_text = $oldrev->getText();
116 $currev_text = $text;
118 #No use doing a merge if it's just a straight revert.
119 if ( $currev_text != $undorev_text ) {
120 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
122 $text = $oldrev_text;
126 // Failed basic sanity checks.
127 // Older revisions may have been removed since the link
128 // was created, or we may simply have got bogus input.
133 # Inform the user of our success and set an automatic edit summary
134 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
135 $firstrev = $oldrev->getNext();
136 # If we just undid one rev, use an autosummary
137 if ( $firstrev->mId
== $undo ) {
138 $this->summary
= wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
140 $this->formtype
= 'diff';
142 # Warn the user that something went wrong
143 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
145 } else if( $section != '' ) {
146 if( $section == 'new' ) {
147 $text = $this->getPreloadedText( $preload );
149 $text = $wgParser->getSection( $text, $section, $def_text );
154 wfProfileOut( __METHOD__
);
159 * Get the contents of a page from its title and remove includeonly tags
161 * @param $preload String: the title of the page.
162 * @return string The contents of the page.
164 private function getPreloadedText($preload) {
165 if ( $preload === '' )
168 $preloadTitle = Title
::newFromText( $preload );
169 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
170 $rev=Revision
::newFromTitle($preloadTitle);
171 if ( is_object( $rev ) ) {
172 $text = $rev->getText();
173 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
174 // its own mini-parser! -ævar
175 $text = preg_replace( '~</?includeonly>~', '', $text );
184 * This is the function that extracts metadata from the article body on the first view.
185 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
186 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
188 function extractMetaDataFromArticle () {
189 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
190 $this->mMetaData
= '' ;
191 if ( !$wgUseMetadataEdit ) return ;
192 if ( $wgMetadataWhitelist == '' ) return ;
194 $t = $this->getContent();
196 # MISSING : <nowiki> filtering
198 # Categories and language links
199 $t = explode ( "\n" , $t ) ;
200 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
201 $cat = $ll = array() ;
202 foreach ( $t AS $key => $x )
204 $y = trim ( strtolower ( $x ) ) ;
205 while ( substr ( $y , 0 , 2 ) == '[[' )
207 $y = explode ( ']]' , trim ( $x ) ) ;
208 $first = array_shift ( $y ) ;
209 $first = explode ( ':' , $first ) ;
210 $ns = array_shift ( $first ) ;
211 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
212 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
214 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
215 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
217 $x = implode ( ']]' , $y ) ;
219 $y = trim ( strtolower ( $x ) ) ;
223 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
224 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
225 $t = implode ( "\n" , $t ) ;
228 $sat = array () ; # stand-alone-templates; must be lowercase
229 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
230 $wl_article = new Article ( $wl_title ) ;
231 $wl = explode ( "\n" , $wl_article->getContent() ) ;
232 foreach ( $wl AS $x )
236 while ( substr ( $x , 0 , 1 ) == '*' )
239 $x = trim ( substr ( $x , 1 ) ) ;
243 $sat[] = strtolower ( $x ) ;
248 # Templates, but only some
249 $t = explode ( '{{' , $t ) ;
251 foreach ( $t AS $key => $x )
253 $y = explode ( '}}' , $x , 2 ) ;
254 if ( count ( $y ) == 2 )
257 $z = explode ( '|' , $z ) ;
258 $tn = array_shift ( $z ) ;
259 if ( in_array ( strtolower ( $tn ) , $sat ) )
261 $tl[] = '{{' . $y[0] . '}}' ;
263 $y = explode ( '}}' , $y[1] , 2 ) ;
265 else $t[$key] = '{{' . $x ;
267 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
270 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
271 $t = implode ( '' , $t ) ;
273 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
274 $this->mArticle
->mContent
= $t ;
275 $this->mMetaData
= $s ;
283 * This is the function that gets called for "action=edit". It
284 * sets up various member variables, then passes execution to
285 * another function, usually showEditForm()
287 * The edit form is self-submitting, so that when things like
288 * preview and edit conflicts occur, we get the same form back
289 * with the extra stuff added. Only when the final submission
290 * is made and all is well do we actually save and redirect to
291 * the newly-edited page.
294 global $wgOut, $wgUser, $wgRequest, $wgTitle;
295 global $wgEmailConfirmToEdit;
297 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
300 $fname = 'EditPage::edit';
301 wfProfileIn( $fname );
302 wfDebug( "$fname: enter\n" );
304 // this is not an article
305 $wgOut->setArticleFlag(false);
307 $this->importFormData( $wgRequest );
308 $this->firsttime
= false;
311 $this->livePreview();
312 wfProfileOut( $fname );
316 if ( ! $this->mTitle
->userCan( 'edit' ) ) {
317 wfDebug( "$fname: user can't edit\n" );
318 $wgOut->readOnlyPage( $this->getContent(), true );
319 wfProfileOut( $fname );
322 wfDebug( "$fname: Checking blocks\n" );
323 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
324 # When previewing, don't check blocked state - will get caught at save time.
325 # Also, check when starting edition is done against slave to improve performance.
326 wfDebug( "$fname: user is blocked\n" );
327 $this->blockedPage();
328 wfProfileOut( $fname );
331 if ( !$wgUser->isAllowed('edit') ) {
332 if ( $wgUser->isAnon() ) {
333 wfDebug( "$fname: user must log in\n" );
334 $this->userNotLoggedInPage();
335 wfProfileOut( $fname );
338 wfDebug( "$fname: read-only page\n" );
339 $wgOut->readOnlyPage( $this->getContent(), true );
340 wfProfileOut( $fname );
344 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
345 wfDebug("$fname: user must confirm e-mail address\n");
346 $this->userNotConfirmedPage();
347 wfProfileOut($fname);
350 if ( !$this->mTitle
->userCan( 'create' ) && !$this->mTitle
->exists() ) {
351 wfDebug( "$fname: no create permission\n" );
352 $this->noCreatePermission();
353 wfProfileOut( $fname );
356 if ( wfReadOnly() ) {
357 wfDebug( "$fname: read-only mode is engaged\n" );
358 if( $this->save ||
$this->preview
) {
359 $this->formtype
= 'preview';
360 } else if ( $this->diff
) {
361 $this->formtype
= 'diff';
363 $wgOut->readOnlyPage( $this->getContent() );
364 wfProfileOut( $fname );
369 $this->formtype
= 'save';
370 } else if ( $this->preview
) {
371 $this->formtype
= 'preview';
372 } else if ( $this->diff
) {
373 $this->formtype
= 'diff';
374 } else { # First time through
375 $this->firsttime
= true;
376 if( $this->previewOnOpen() ) {
377 $this->formtype
= 'preview';
379 $this->extractMetaDataFromArticle () ;
380 $this->formtype
= 'initial';
385 wfProfileIn( "$fname-business-end" );
387 $this->isConflict
= false;
388 // css / js subpages of user pages get a special treatment
389 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
390 $this->isValidCssJsSubpage
= $wgTitle->isValidCssJsSubpage();
392 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
393 * no matter it's current state
395 $this->deletedSinceEdit
= false;
396 if ( $this->edittime
!= '' ) {
397 /* Note that we rely on logging table, which hasn't been always there,
398 * but that doesn't matter, because this only applies to brand new
399 * deletes. This is done on every preview and save request. Move it further down
400 * to only perform it on saves
402 if ( $this->mTitle
->isDeleted() ) {
403 $this->lastDelete
= $this->getLastDelete();
404 if ( !is_null($this->lastDelete
) ) {
405 $deletetime = $this->lastDelete
->log_timestamp
;
406 if ( ($deletetime - $this->starttime
) > 0 ) {
407 $this->deletedSinceEdit
= true;
413 if(!$this->mTitle
->getArticleID() && ('initial' == $this->formtype ||
$this->firsttime
)) { # new article
416 if( $this->mTitle
->isTalkPage() ) {
417 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
420 # Attempt submission here. This will check for edit conflicts,
421 # and redundantly check for locked database, blocked IPs, etc.
422 # that edit() already checked just in case someone tries to sneak
423 # in the back door with a hand-edited submission URL.
425 if ( 'save' == $this->formtype
) {
426 if ( !$this->attemptSave() ) {
427 wfProfileOut( "$fname-business-end" );
428 wfProfileOut( $fname );
433 # First time through: get contents, set time for conflict
435 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
436 if ($this->initialiseForm() === false) {
437 $this->noSuchSectionPage();
438 wfProfileOut( "$fname-business-end" );
439 wfProfileOut( $fname );
442 if( !$this->mTitle
->getArticleId() )
443 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
446 $this->showEditForm();
447 wfProfileOut( "$fname-business-end" );
448 wfProfileOut( $fname );
452 * Return true if this page should be previewed when the edit form
453 * is initially opened.
457 function previewOnOpen() {
459 return $this->section
!= 'new' &&
460 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle
->exists() ) ||
461 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
462 !$this->mTitle
->exists() ) );
469 function importFormData( &$request ) {
470 global $wgLang, $wgUser;
471 $fname = 'EditPage::importFormData';
472 wfProfileIn( $fname );
474 if( $request->wasPosted() ) {
475 # These fields need to be checked for encoding.
476 # Also remove trailing whitespace, but don't remove _initial_
477 # whitespace from the text boxes. This may be significant formatting.
478 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
479 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
480 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
481 # Truncate for whole multibyte characters. +5 bytes for ellipsis
482 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
484 $this->edittime
= $request->getVal( 'wpEdittime' );
485 $this->starttime
= $request->getVal( 'wpStarttime' );
487 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
489 if( is_null( $this->edittime
) ) {
490 # If the form is incomplete, force to preview.
491 wfDebug( "$fname: Form data appears to be incomplete\n" );
492 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
493 $this->preview
= true;
495 /* Fallback for live preview */
496 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
497 $this->diff
= $request->getCheck( 'wpDiff' );
499 // Remember whether a save was requested, so we can indicate
500 // if we forced preview due to session failure.
501 $this->mTriedSave
= !$this->preview
;
503 if ( $this->tokenOk( $request ) ) {
504 # Some browsers will not report any submit button
505 # if the user hits enter in the comment box.
506 # The unmarked state will be assumed to be a save,
507 # if the form seems otherwise complete.
508 wfDebug( "$fname: Passed token check.\n" );
509 } else if ( $this->diff
) {
510 # Failed token check, but only requested "Show Changes".
511 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
513 # Page might be a hack attempt posted from
514 # an external site. Preview instead of saving.
515 wfDebug( "$fname: Failed token check; forcing preview\n" );
516 $this->preview
= true;
519 $this->save
= ! ( $this->preview
OR $this->diff
);
520 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
521 $this->edittime
= null;
524 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
525 $this->starttime
= null;
528 $this->recreate
= $request->getCheck( 'wpRecreate' );
530 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
531 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
533 # Don't force edit summaries when a user is editing their own user or talk page
534 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
535 $this->allowBlankSummary
= true;
537 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
540 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
542 # Not a posted form? Start with nothing.
543 wfDebug( "$fname: Not a posted form.\n" );
544 $this->textbox1
= '';
545 $this->textbox2
= '';
546 $this->mMetaData
= '';
548 $this->edittime
= '';
549 $this->starttime
= wfTimestampNow();
550 $this->preview
= false;
553 $this->minoredit
= false;
554 $this->watchthis
= false;
555 $this->recreate
= false;
558 $this->oldid
= $request->getInt( 'oldid' );
560 # Section edit can come from either the form or a link
561 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
563 $this->live
= $request->getCheck( 'live' );
564 $this->editintro
= $request->getText( 'editintro' );
566 wfProfileOut( $fname );
570 * Make sure the form isn't faking a user's credentials.
572 * @param $request WebRequest
576 function tokenOk( &$request ) {
578 if( $wgUser->isAnon() ) {
579 # Anonymous users may not have a session
580 # open. Check for suffix anyway.
581 $this->mTokenOk
= ( EDIT_TOKEN_SUFFIX
== $request->getVal( 'wpEditToken' ) );
583 $this->mTokenOk
= $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
585 return $this->mTokenOk
;
589 function showIntro() {
590 global $wgOut, $wgUser;
591 $addstandardintro=true;
592 if($this->editintro
) {
593 $introtitle=Title
::newFromText($this->editintro
);
594 if(isset($introtitle) && $introtitle->userCanRead()) {
595 $rev=Revision
::newFromTitle($introtitle);
597 $wgOut->addSecondaryWikiText($rev->getText());
598 $addstandardintro=false;
602 if($addstandardintro) {
603 if ( $wgUser->isLoggedIn() )
604 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
606 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
607 # Let the user know about previous deletions if applicable
608 $this->showDeletionLog( $wgOut );
614 * @return bool false if output is done, true if the rest of the form should be displayed
616 function attemptSave() {
617 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
618 global $wgMaxArticleSize;
620 $fname = 'EditPage::attemptSave';
621 wfProfileIn( $fname );
622 wfProfileIn( "$fname-checks" );
624 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
626 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
630 # Reintegrate metadata
631 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
632 $this->mMetaData
= '' ;
636 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
637 $this->spamPage ( $matches[0] );
638 wfProfileOut( "$fname-checks" );
639 wfProfileOut( $fname );
642 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
643 # Error messages or other handling should be performed by the filter function
644 wfProfileOut( $fname );
645 wfProfileOut( "$fname-checks" );
648 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
) ) ) {
649 # Error messages etc. could be handled within the hook...
650 wfProfileOut( $fname );
651 wfProfileOut( "$fname-checks" );
653 } elseif( $this->hookError
!= '' ) {
654 # ...or the hook could be expecting us to produce an error
655 wfProfileOut( "$fname-checks " );
656 wfProfileOut( $fname );
659 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
660 # Check block state against master, thus 'false'.
661 $this->blockedPage();
662 wfProfileOut( "$fname-checks" );
663 wfProfileOut( $fname );
666 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
667 if ( $this->kblength
> $wgMaxArticleSize ) {
668 // Error will be displayed by showEditForm()
669 $this->tooBig
= true;
670 wfProfileOut( "$fname-checks" );
671 wfProfileOut( $fname );
675 if ( !$wgUser->isAllowed('edit') ) {
676 if ( $wgUser->isAnon() ) {
677 $this->userNotLoggedInPage();
678 wfProfileOut( "$fname-checks" );
679 wfProfileOut( $fname );
683 $wgOut->readOnlyPage();
684 wfProfileOut( "$fname-checks" );
685 wfProfileOut( $fname );
690 if ( wfReadOnly() ) {
691 $wgOut->readOnlyPage();
692 wfProfileOut( "$fname-checks" );
693 wfProfileOut( $fname );
696 if ( $wgUser->pingLimiter() ) {
697 $wgOut->rateLimited();
698 wfProfileOut( "$fname-checks" );
699 wfProfileOut( $fname );
703 # If the article has been deleted while editing, don't save it without
705 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
706 wfProfileOut( "$fname-checks" );
707 wfProfileOut( $fname );
711 wfProfileOut( "$fname-checks" );
713 # If article is new, insert it.
714 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
717 // Late check for create permission, just in case *PARANOIA*
718 if ( !$this->mTitle
->userCan( 'create' ) ) {
719 wfDebug( "$fname: no create permission\n" );
720 $this->noCreatePermission();
721 wfProfileOut( $fname );
725 # Don't save a new article if it's blank.
726 if ( ( '' == $this->textbox1
) ) {
727 $wgOut->redirect( $this->mTitle
->getFullURL() );
728 wfProfileOut( $fname );
732 $isComment=($this->section
=='new');
733 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
734 $this->minoredit
, $this->watchthis
, false, $isComment);
736 wfProfileOut( $fname );
740 # Article exists. Check for edit conflict.
742 $this->mArticle
->clear(); # Force reload of dates, etc.
743 $this->mArticle
->forUpdate( true ); # Lock the article
745 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
747 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
748 $this->isConflict
= true;
749 if( $this->section
== 'new' ) {
750 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
751 $this->mArticle
->getComment() == $this->summary
) {
752 // Probably a duplicate submission of a new comment.
753 // This can happen when squid resends a request after
754 // a timeout but the first one actually went through.
755 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
757 // New comment; suppress conflict.
758 $this->isConflict
= false;
759 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
763 $userid = $wgUser->getID();
765 if ( $this->isConflict
) {
766 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
767 $this->mArticle
->getTimestamp() . "'\n" );
768 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
771 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
772 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
774 if( is_null( $text ) ) {
775 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
776 $this->isConflict
= true;
777 $text = $this->textbox1
;
780 # Suppress edit conflict with self, except for section edits where merging is required.
781 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
782 wfDebug( "Suppressing edit conflict, same user.\n" );
783 $this->isConflict
= false;
785 # switch from section editing to normal editing in edit conflict
786 if($this->isConflict
) {
788 if( $this->mergeChangesInto( $text ) ){
789 // Successful merge! Maybe we should tell the user the good news?
790 $this->isConflict
= false;
791 wfDebug( "Suppressing edit conflict, successful merge.\n" );
794 $this->textbox1
= $text;
795 wfDebug( "Keeping edit conflict, failed merge.\n" );
800 if ( $this->isConflict
) {
801 wfProfileOut( $fname );
805 $oldtext = $this->mArticle
->getContent();
807 # Handle the user preference to force summaries here, but not for null edits
808 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary')
809 && 0 != strcmp($oldtext, $text) && !Article
::getRedirectAutosummary( $text )) {
810 if( md5( $this->summary
) == $this->autoSumm
) {
811 $this->missingSummary
= true;
812 wfProfileOut( $fname );
817 #And a similar thing for new sections
818 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
819 if (trim($this->summary
) == '') {
820 $this->missingSummary
= true;
821 wfProfileOut( $fname );
827 wfProfileIn( "$fname-sectionanchor" );
829 if( $this->section
== 'new' ) {
830 if ( $this->textbox1
== '' ) {
831 $this->missingComment
= true;
834 if( $this->summary
!= '' ) {
835 $sectionanchor = $this->sectionAnchor( $this->summary
);
837 } elseif( $this->section
!= '' ) {
838 # Try to get a section anchor from the section source, redirect to edited section if header found
839 # XXX: might be better to integrate this into Article::replaceSection
840 # for duplicate heading checking and maybe parsing
841 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
842 # we can't deal with anchors, includes, html etc in the header for now,
843 # headline would need to be parsed to improve this
844 if($hasmatch and strlen($matches[2]) > 0) {
845 $sectionanchor = $this->sectionAnchor( $matches[2] );
848 wfProfileOut( "$fname-sectionanchor" );
850 // Save errors may fall down to the edit form, but we've now
851 // merged the section into full text. Clear the section field
852 // so that later submission of conflict forms won't try to
853 // replace that into a duplicated mess.
854 $this->textbox1
= $text;
857 // Check for length errors again now that the section is merged in
858 $this->kblength
= (int)(strlen( $text ) / 1024);
859 if ( $this->kblength
> $wgMaxArticleSize ) {
860 $this->tooBig
= true;
861 wfProfileOut( $fname );
865 # update the article here
866 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
867 $this->watchthis
, '', $sectionanchor ) ) {
868 wfProfileOut( $fname );
871 $this->isConflict
= true;
873 wfProfileOut( $fname );
878 * Initialise form fields in the object
879 * Called on the first invocation, e.g. when a user clicks an edit link
881 function initialiseForm() {
882 $this->edittime
= $this->mArticle
->getTimestamp();
884 $this->textbox1
= $this->getContent(false);
885 if ($this->textbox1
=== false) return false;
887 if ( !$this->mArticle
->exists() && $this->mArticle
->mTitle
->getNamespace() == NS_MEDIAWIKI
)
888 $this->textbox1
= wfMsgWeirdKey( $this->mArticle
->mTitle
->getText() );
894 * Send the edit form and related headers to $wgOut
895 * @param $formCallback Optional callable that takes an OutputPage
896 * parameter; will be called during form output
897 * near the top, for captchas and the like.
899 function showEditForm( $formCallback=null ) {
900 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
902 $fname = 'EditPage::showEditForm';
903 wfProfileIn( $fname );
905 $sk = $wgUser->getSkin();
907 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
909 $wgOut->setRobotpolicy( 'noindex,nofollow' );
911 # Enabled article-related sidebar, toplinks, etc.
912 $wgOut->setArticleRelated( true );
914 if ( $this->isConflict
) {
915 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
916 $wgOut->setPageTitle( $s );
917 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
919 $this->textbox2
= $this->textbox1
;
920 $this->textbox1
= $this->getContent();
921 $this->edittime
= $this->mArticle
->getTimestamp();
924 if( $this->section
!= '' ) {
925 if( $this->section
== 'new' ) {
926 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
928 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
930 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
931 preg_match( "/^(=+)(.+)\\1/mi",
934 if( !empty( $matches[2] ) ) {
935 $this->summary
= "/* ". trim($matches[2])." */ ";
940 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
942 $wgOut->setPageTitle( $s );
944 if ( $this->missingComment
) {
945 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
948 if( $this->missingSummary
&& $this->section
!= 'new' ) {
949 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
952 if( $this->missingSummary
&& $this->section
== 'new' ) {
953 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
956 if( !$this->hookError
== '' ) {
957 $wgOut->addWikiText( $this->hookError
);
960 if ( !$this->checkUnicodeCompliantBrowser() ) {
961 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
963 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
964 // Let sysop know that this will make private content public if saved
965 if( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
966 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
968 if( !$this->mArticle
->mRevision
->isCurrent() ) {
969 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
970 $wgOut->addWikiText( wfMsg( 'editingold' ) );
976 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
977 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
978 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
980 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
981 # Check the skin exists
982 if( $this->isValidCssJsSubpage
) {
983 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
985 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
990 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
991 # Show a warning if editing an interface message
992 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
993 } elseif( $this->mTitle
->isProtected( 'edit' ) ) {
994 # Is the title semi-protected?
995 if( $this->mTitle
->isSemiProtected() ) {
996 $notice = wfMsg( 'semiprotectedpagewarning' );
997 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' )
1000 # Then it must be protected based on static groups (regular)
1001 $notice = wfMsg( 'protectedpagewarning' );
1003 $wgOut->addWikiText( $notice );
1005 if ( $this->mTitle
->isCascadeProtected() ) {
1006 # Is this page under cascading protection from some source pages?
1007 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1008 if ( count($cascadeSources) > 0 ) {
1009 # Explain, and list the titles responsible
1010 $notice = wfMsgExt( 'cascadeprotectedwarning', array('parsemag'), count($cascadeSources) ) . "\n";
1011 foreach( $cascadeSources as $id => $page )
1012 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1014 $wgOut->addWikiText( $notice );
1017 if ( $this->kblength
=== false ) {
1018 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1020 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1021 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgMaxArticleSize ) );
1022 } elseif( $this->kblength
> 29 ) {
1023 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) ) );
1026 #need to parse the preview early so that we know which templates are used,
1027 #otherwise users with "show preview after edit box" will get a blank list
1028 if ( $this->formtype
== 'preview' ) {
1029 $previewOutput = $this->getPreviewText();
1032 $rows = $wgUser->getIntOption( 'rows' );
1033 $cols = $wgUser->getIntOption( 'cols' );
1035 $ew = $wgUser->getOption( 'editwidth' );
1036 if ( $ew ) $ew = " style=\"width:100%\"";
1039 $q = 'action=submit';
1040 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1041 $action = $this->mTitle
->escapeLocalURL( $q );
1043 $summary = wfMsg('summary');
1044 $subject = wfMsg('subject');
1046 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
1047 wfMsgExt('cancel', array('parseinline')) );
1048 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1049 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1050 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1051 htmlspecialchars( wfMsg( 'newwindow' ) );
1053 global $wgRightsText;
1054 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1055 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
1056 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1057 $wgRightsText ) . "\n</div>";
1059 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1060 # prepare toolbar for edit buttons
1061 $toolbar = $this->getEditToolbar();
1066 // activate checkboxes if user wants them to be always active
1067 if( !$this->preview
&& !$this->diff
) {
1068 # Sort out the "watch" checkbox
1069 if( $wgUser->getOption( 'watchdefault' ) ) {
1071 $this->watchthis
= true;
1072 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1074 $this->watchthis
= true;
1075 } elseif( $this->mTitle
->userIsWatching() ) {
1077 $this->watchthis
= true;
1080 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1083 $wgOut->addHTML( $this->editFormPageTop
);
1085 if ( $wgUser->getOption( 'previewontop' ) ) {
1087 if ( 'preview' == $this->formtype
) {
1088 $this->showPreview( $previewOutput );
1090 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1093 if ( 'diff' == $this->formtype
) {
1094 $wgOut->addStyle( 'common/diff.css' );
1095 $wgOut->addHTML( $this->getDiff() );
1100 $wgOut->addHTML( $this->editFormTextTop
);
1102 # if this is a comment, show a subject line at the top, which is also the edit summary.
1103 # Otherwise, show a summary field at the bottom
1104 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1105 if( $this->section
== 'new' ) {
1106 $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 />";
1108 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1109 $summarypreview = '';
1111 $commentsubject = '';
1112 $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 />";
1113 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1114 $subjectpreview = '';
1117 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1118 if( !$this->preview
&& !$this->diff
) {
1119 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1121 $templates = ($this->preview ||
$this->section
!= '') ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1122 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1124 global $wgUseMetadataEdit ;
1125 if ( $wgUseMetadataEdit ) {
1126 $metadata = $this->mMetaData
;
1127 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1128 $top = wfMsgWikiHtml( 'metadata_help' );
1129 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1131 else $metadata = "" ;
1135 if ($this->deletedSinceEdit
) {
1136 if ( 'save' != $this->formtype
) {
1137 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1139 // Hide the toolbar and edit area, use can click preview to get it back
1140 // Add an confirmation checkbox and explanation.
1142 $hidden = 'type="hidden" style="display:none;"';
1143 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1145 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1146 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1152 $checkboxes = self
::getCheckboxes( $tabindex, $sk,
1153 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1155 $checkboxhtml = implode( $checkboxes, "\n" );
1157 $buttons = $this->getEditButtons( $tabindex );
1158 $buttonshtml = implode( $buttons, "\n" );
1160 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1161 ?
'' : Xml
::hidden( 'safemode', '1' );
1163 $wgOut->addHTML( <<<END
1165 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1169 if( is_callable( $formCallback ) ) {
1170 call_user_func_array( $formCallback, array( &$wgOut ) );
1173 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1175 // Put these up at the top to ensure they aren't lost on early form submission
1177 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1178 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1179 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1180 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1182 $wgOut->addHTML( <<<END
1186 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1187 cols='{$cols}'{$ew} $hidden>
1189 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
1194 $wgOut->addWikiText( $copywarn );
1195 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1205 "<div class='editButtons'>
1207 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1208 </div><!-- editButtons -->
1209 </div><!-- editOptions -->");
1211 $wgOut->addHtml( '<div class="mw-editTools">' );
1212 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1213 $wgOut->addHtml( '</div>' );
1215 $wgOut->addHTML( $this->editFormTextAfterTools
);
1218 <div class='templatesUsed'>
1219 {$formattedtemplates}
1224 * To make it harder for someone to slip a user a page
1225 * which submits an edit form to the wiki without their
1226 * knowledge, a random token is associated with the login
1227 * session. If it's not passed back with the submission,
1228 * we won't save the page, or render user JavaScript and
1231 * For anon editors, who may not have a session, we just
1232 * include the constant suffix to prevent editing from
1233 * broken text-mangling proxies.
1235 if ( $wgUser->isLoggedIn() )
1236 $token = htmlspecialchars( $wgUser->editToken() );
1238 $token = EDIT_TOKEN_SUFFIX
;
1239 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1242 # If a blank edit summary was previously provided, and the appropriate
1243 # user preference is active, pass a hidden tag here. This will stop the
1244 # user being bounced back more than once in the event that a summary
1246 if( $this->missingSummary
) {
1247 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1250 # For a bit more sophisticated detection of blank summaries, hash the
1251 # automatic one and pass that in a hidden field.
1252 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1253 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1255 if ( $this->isConflict
) {
1256 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1258 $de = new DifferenceEngine( $this->mTitle
);
1259 $de->setText( $this->textbox2
, $this->textbox1
);
1260 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1262 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1263 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1264 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1266 $wgOut->addHTML( $this->editFormTextBottom
);
1267 $wgOut->addHTML( "</form>\n" );
1268 if ( !$wgUser->getOption( 'previewontop' ) ) {
1270 if ( $this->formtype
== 'preview') {
1271 $this->showPreview( $previewOutput );
1273 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1276 if ( $this->formtype
== 'diff') {
1277 $wgOut->addStyle( 'common/diff.css' );
1278 $wgOut->addHTML( $this->getDiff() );
1283 wfProfileOut( $fname );
1287 * Append preview output to $wgOut.
1288 * Includes category rendering if this is a category page.
1290 * @param string $text The HTML to be output for the preview.
1292 private function showPreview( $text ) {
1295 $wgOut->addHTML( '<div id="wikiPreview">' );
1296 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1297 $this->mArticle
->openShowCategory();
1299 $wgOut->addHTML( $text );
1300 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1301 $this->mArticle
->closeShowCategory();
1303 $wgOut->addHTML( '</div>' );
1307 * Live Preview lets us fetch rendered preview page content and
1308 * add it to the page without refreshing the whole page.
1309 * If not supported by the browser it will fall through to the normal form
1310 * submission method.
1312 * This function outputs a script tag to support live preview, and
1313 * returns an onclick handler which should be added to the attributes
1314 * of the preview button
1316 function doLivePreviewScript() {
1317 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1318 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1319 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1320 '"></script>' . "\n" );
1321 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1322 return "return !livePreview(" .
1323 "getElementById('wikiPreview')," .
1324 "editform.wpTextbox1.value," .
1325 '"' . $liveAction . '"' . ")";
1328 function getLastDelete() {
1329 $dbr = wfGetDB( DB_SLAVE
);
1330 $fname = 'EditPage::getLastDelete';
1331 $res = $dbr->select(
1332 array( 'logging', 'user' ),
1342 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1343 'log_title' => $this->mTitle
->getDBkey(),
1344 'log_type' => 'delete',
1345 'log_action' => 'delete',
1346 'user_id=log_user' ),
1348 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1350 if($dbr->numRows($res) == 1) {
1351 while ( $x = $dbr->fetchObject ( $res ) )
1353 $dbr->freeResult ( $res ) ;
1363 function getPreviewText() {
1364 global $wgOut, $wgUser, $wgTitle, $wgParser;
1366 $fname = 'EditPage::getPreviewText';
1367 wfProfileIn( $fname );
1369 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1370 $msg = 'session_fail_preview';
1372 $msg = 'previewnote';
1374 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1375 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1376 if ( $this->isConflict
) {
1377 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1380 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1381 $parserOptions->setEditSection( false );
1384 if( $wgRawHtml && !$this->mTokenOk
) {
1385 // Could be an offsite preview attempt. This is very unsafe if
1386 // HTML is enabled, as it could be an attack.
1387 return $wgOut->parse( "<div class='previewnote'>" .
1388 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1391 # don't parse user css/js, show message about preview
1392 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1394 if ( $this->isCssJsSubpage
) {
1395 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1396 $previewtext = wfMsg('usercsspreview');
1397 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1398 $previewtext = wfMsg('userjspreview');
1400 $parserOptions->setTidy(true);
1401 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1402 $wgOut->addHTML( $parserOutput->mText
);
1403 wfProfileOut( $fname );
1404 return $previewhead;
1406 $toparse = $this->textbox1
;
1408 # If we're adding a comment, we need to show the
1409 # summary as the headline
1410 if($this->section
=="new" && $this->summary
!="") {
1411 $toparse="== {$this->summary} ==\n\n".$toparse;
1414 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1415 $parserOptions->setTidy(true);
1416 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1417 $wgTitle, $parserOptions );
1419 $previewHTML = $parserOutput->getText();
1420 $wgOut->addParserOutputNoText( $parserOutput );
1422 foreach ( $parserOutput->getTemplates() as $ns => $template)
1423 foreach ( array_keys( $template ) as $dbk)
1424 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1426 wfProfileOut( $fname );
1427 return $previewhead . $previewHTML;
1432 * Call the stock "user is blocked" page
1434 function blockedPage() {
1435 global $wgOut, $wgUser;
1436 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1438 # If the user made changes, preserve them when showing the markup
1439 # (This happens when a user is blocked during edit, for instance)
1440 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1442 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1444 $source = $this->textbox1
;
1447 # Spit out the source or the user's modified version
1448 if( $source !== false ) {
1449 $rows = $wgUser->getOption( 'rows' );
1450 $cols = $wgUser->getOption( 'cols' );
1451 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1452 $wgOut->addHtml( '<hr />' );
1453 $wgOut->addWikiText( wfMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() ) );
1454 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1459 * Produce the stock "please login to edit pages" page
1461 function userNotLoggedInPage() {
1462 global $wgUser, $wgOut;
1463 $skin = $wgUser->getSkin();
1465 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1466 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle
->getPrefixedUrl() );
1468 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1469 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1470 $wgOut->setArticleRelated( false );
1472 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1473 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1477 * Creates a basic error page which informs the user that
1478 * they have to validate their email address before being
1481 function userNotConfirmedPage() {
1484 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1485 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1486 $wgOut->setArticleRelated( false );
1488 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1489 $wgOut->returnToMain( false );
1493 * Creates a basic error page which informs the user that
1494 * they have attempted to edit a nonexistant section.
1496 function noSuchSectionPage() {
1499 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1500 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1501 $wgOut->setArticleRelated( false );
1503 $wgOut->addWikiText( wfMsg( 'nosuchsectiontext', $this->section
) );
1504 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1508 * Produce the stock "your edit contains spam" page
1510 * @param $match Text which triggered one or more filters
1512 function spamPage( $match = false ) {
1515 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1516 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1517 $wgOut->setArticleRelated( false );
1519 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1521 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1523 $wgOut->returnToMain( false );
1530 function mergeChangesInto( &$editText ){
1531 $fname = 'EditPage::mergeChangesInto';
1532 wfProfileIn( $fname );
1534 $db = wfGetDB( DB_MASTER
);
1536 // This is the revision the editor started from
1537 $baseRevision = Revision
::loadFromTimestamp(
1538 $db, $this->mArticle
->mTitle
, $this->edittime
);
1539 if( is_null( $baseRevision ) ) {
1540 wfProfileOut( $fname );
1543 $baseText = $baseRevision->getText();
1545 // The current state, we want to merge updates into it
1546 $currentRevision = Revision
::loadFromTitle(
1547 $db, $this->mArticle
->mTitle
);
1548 if( is_null( $currentRevision ) ) {
1549 wfProfileOut( $fname );
1552 $currentText = $currentRevision->getText();
1555 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1556 $editText = $result;
1557 wfProfileOut( $fname );
1560 wfProfileOut( $fname );
1566 * Check if the browser is on a blacklist of user-agents known to
1567 * mangle UTF-8 data on form submission. Returns true if Unicode
1568 * should make it through, false if it's known to be a problem.
1572 function checkUnicodeCompliantBrowser() {
1573 global $wgBrowserBlackList;
1574 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1575 // No User-Agent header sent? Trust it by default...
1578 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1579 foreach ( $wgBrowserBlackList as $browser ) {
1580 if ( preg_match($browser, $currentbrowser) ) {
1588 * Format an anchor fragment as it would appear for a given section name
1589 * @param string $text
1593 function sectionAnchor( $text ) {
1594 $headline = Sanitizer
::decodeCharReferences( $text );
1596 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1597 $headline = trim( $headline );
1598 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1599 $replacearray = array(
1604 array_keys( $replacearray ),
1605 array_values( $replacearray ),
1610 * Shows a bulletin board style toolbar for common editing functions.
1611 * It can be disabled in the user preferences.
1612 * The necessary JavaScript code can be found in style/wikibits.js.
1614 function getEditToolbar() {
1615 global $wgStylePath, $wgContLang, $wgJsMimeType;
1618 * toolarray an array of arrays which each include the filename of
1619 * the button image (without path), the opening tag, the closing tag,
1620 * and optionally a sample text that is inserted between the two when no
1621 * selection is highlighted.
1622 * The tip text is shown when the user moves the mouse over the button.
1624 * Already here are accesskeys (key), which are not used yet until someone
1625 * can figure out a way to make them work in IE. However, we should make
1626 * sure these keys are not defined on the edit page.
1629 array( 'image' => 'button_bold.png',
1630 'id' => 'mw-editbutton-bold',
1631 'open' => '\\\'\\\'\\\'',
1632 'close' => '\\\'\\\'\\\'',
1633 'sample'=> wfMsg('bold_sample'),
1634 'tip' => wfMsg('bold_tip'),
1637 array( 'image' => 'button_italic.png',
1638 'id' => 'mw-editbutton-italic',
1639 'open' => '\\\'\\\'',
1640 'close' => '\\\'\\\'',
1641 'sample'=> wfMsg('italic_sample'),
1642 'tip' => wfMsg('italic_tip'),
1645 array( 'image' => 'button_link.png',
1646 'id' => 'mw-editbutton-link',
1649 'sample'=> wfMsg('link_sample'),
1650 'tip' => wfMsg('link_tip'),
1653 array( 'image' => 'button_extlink.png',
1654 'id' => 'mw-editbutton-extlink',
1657 'sample'=> wfMsg('extlink_sample'),
1658 'tip' => wfMsg('extlink_tip'),
1661 array( 'image' => 'button_headline.png',
1662 'id' => 'mw-editbutton-headline',
1664 'close' => " ==\\n",
1665 'sample'=> wfMsg('headline_sample'),
1666 'tip' => wfMsg('headline_tip'),
1669 array( 'image' => 'button_image.png',
1670 'id' => 'mw-editbutton-image',
1671 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1673 'sample'=> wfMsg('image_sample'),
1674 'tip' => wfMsg('image_tip'),
1677 array( 'image' => 'button_media.png',
1678 'id' => 'mw-editbutton-media',
1679 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1681 'sample'=> wfMsg('media_sample'),
1682 'tip' => wfMsg('media_tip'),
1685 array( 'image' => 'button_math.png',
1686 'id' => 'mw-editbutton-math',
1688 'close' => "<\\/math>",
1689 'sample'=> wfMsg('math_sample'),
1690 'tip' => wfMsg('math_tip'),
1693 array( 'image' => 'button_nowiki.png',
1694 'id' => 'mw-editbutton-nowiki',
1695 'open' => "<nowiki>",
1696 'close' => "<\\/nowiki>",
1697 'sample'=> wfMsg('nowiki_sample'),
1698 'tip' => wfMsg('nowiki_tip'),
1701 array( 'image' => 'button_sig.png',
1702 'id' => 'mw-editbutton-signature',
1706 'tip' => wfMsg('sig_tip'),
1709 array( 'image' => 'button_hr.png',
1710 'id' => 'mw-editbutton-hr',
1711 'open' => "\\n----\\n",
1714 'tip' => wfMsg('hr_tip'),
1718 $toolbar = "<div id='toolbar'>\n";
1719 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1721 foreach($toolarray as $tool) {
1723 $cssId = $tool['id'];
1724 $image=$wgStylePath.'/common/images/'.$tool['image'];
1725 $open=$tool['open'];
1726 $close=$tool['close'];
1727 $sample = wfEscapeJsString( $tool['sample'] );
1729 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1730 // Older browsers show a "speedtip" type message only for ALT.
1731 // Ideally these should be different, realistically they
1732 // probably don't need to be.
1733 $tip = wfEscapeJsString( $tool['tip'] );
1735 #$key = $tool["key"];
1737 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1740 $toolbar.="/*]]>*/\n</script>";
1741 $toolbar.="\n</div>";
1746 * Returns an array of html code of the following checkboxes:
1749 * @param $tabindex Current tabindex
1750 * @param $skin Skin object
1751 * @param $checked Array of checkbox => bool, where bool indicates the checked
1752 * status of the checkbox
1756 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1759 $checkboxes = array();
1761 $checkboxes['minor'] = '';
1762 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1763 if ( $wgUser->isAllowed('minoredit') ) {
1765 'tabindex' => ++
$tabindex,
1766 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1767 'id' => 'wpMinoredit',
1769 $checkboxes['minor'] =
1770 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1771 " <label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1774 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1775 $checkboxes['watch'] = '';
1776 if ( $wgUser->isLoggedIn() ) {
1778 'tabindex' => ++
$tabindex,
1779 'accesskey' => wfMsg( 'accesskey-watch' ),
1780 'id' => 'wpWatchthis',
1782 $checkboxes['watch'] =
1783 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1784 " <label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1790 * Returns an array of html code of the following buttons:
1791 * save, diff, preview and live
1793 * @param $tabindex Current tabindex
1797 public function getEditButtons(&$tabindex) {
1798 global $wgLivePreview, $wgUser;
1806 'tabindex' => ++
$tabindex,
1807 'value' => wfMsg('savearticle'),
1808 'accesskey' => wfMsg('accesskey-save'),
1809 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1811 $buttons['save'] = wfElement('input', $temp, '');
1813 ++
$tabindex; // use the same for preview and live preview
1814 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1816 'id' => 'wpPreview',
1817 'name' => 'wpPreview',
1819 'tabindex' => $tabindex,
1820 'value' => wfMsg('showpreview'),
1822 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1823 'style' => 'display: none;',
1825 $buttons['preview'] = wfElement('input', $temp, '');
1828 'id' => 'wpLivePreview',
1829 'name' => 'wpLivePreview',
1831 'tabindex' => $tabindex,
1832 'value' => wfMsg('showlivepreview'),
1833 'accesskey' => wfMsg('accesskey-preview'),
1835 'onclick' => $this->doLivePreviewScript(),
1837 $buttons['live'] = wfElement('input', $temp, '');
1840 'id' => 'wpPreview',
1841 'name' => 'wpPreview',
1843 'tabindex' => $tabindex,
1844 'value' => wfMsg('showpreview'),
1845 'accesskey' => wfMsg('accesskey-preview'),
1846 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1848 $buttons['preview'] = wfElement('input', $temp, '');
1849 $buttons['live'] = '';
1856 'tabindex' => ++
$tabindex,
1857 'value' => wfMsg('showdiff'),
1858 'accesskey' => wfMsg('accesskey-diff'),
1859 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1861 $buttons['diff'] = wfElement('input', $temp, '');
1867 * Output preview text only. This can be sucked into the edit page
1868 * via JavaScript, and saves the server time rendering the skin as
1869 * well as theoretically being more robust on the client (doesn't
1870 * disturb the edit box's undo history, won't eat your text on
1873 * @todo This doesn't include category or interlanguage links.
1874 * Would need to enhance it a bit, <s>maybe wrap them in XML
1875 * or something...</s> that might also require more skin
1876 * initialization, so check whether that's a problem.
1878 function livePreview() {
1881 header( 'Content-type: text/xml; charset=utf-8' );
1882 header( 'Cache-control: no-cache' );
1885 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1886 Xml
::openElement( 'livepreview' ) .
1887 Xml
::element( 'preview', null, $this->getPreviewText() ) .
1888 Xml
::element( 'br', array( 'style' => 'clear: both;' ) ) .
1889 Xml
::closeElement( 'livepreview' );
1895 * Get a diff between the current contents of the edit box and the
1896 * version of the page we're editing from.
1898 * If this is a section edit, we'll replace the section as for final
1899 * save and then make a comparison.
1901 * @return string HTML
1903 function getDiff() {
1904 $oldtext = $this->mArticle
->fetchContent();
1905 $newtext = $this->mArticle
->replaceSection(
1906 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1907 $newtext = $this->mArticle
->preSaveTransform( $newtext );
1908 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1909 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1910 if ( $oldtext !== false ||
$newtext != '' ) {
1911 $de = new DifferenceEngine( $this->mTitle
);
1912 $de->setText( $oldtext, $newtext );
1913 $difftext = $de->getDiff( $oldtitle, $newtitle );
1918 return '<div id="wikiDiff">' . $difftext . '</div>';
1922 * Filter an input field through a Unicode de-armoring process if it
1923 * came from an old browser with known broken Unicode editing issues.
1925 * @param WebRequest $request
1926 * @param string $field
1930 function safeUnicodeInput( $request, $field ) {
1931 $text = rtrim( $request->getText( $field ) );
1932 return $request->getBool( 'safemode' )
1933 ?
$this->unmakesafe( $text )
1938 * Filter an output field through a Unicode armoring process if it is
1939 * going to an old browser with known broken Unicode editing issues.
1941 * @param string $text
1945 function safeUnicodeOutput( $text ) {
1947 $codedText = $wgContLang->recodeForEdit( $text );
1948 return $this->checkUnicodeCompliantBrowser()
1950 : $this->makesafe( $codedText );
1954 * A number of web browsers are known to corrupt non-ASCII characters
1955 * in a UTF-8 text editing environment. To protect against this,
1956 * detected browsers will be served an armored version of the text,
1957 * with non-ASCII chars converted to numeric HTML character references.
1959 * Preexisting such character references will have a 0 added to them
1960 * to ensure that round-trips do not alter the original data.
1962 * @param string $invalue
1966 function makesafe( $invalue ) {
1967 // Armor existing references for reversability.
1968 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1973 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1974 $bytevalue = ord( $invalue{$i} );
1975 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1976 $result .= chr( $bytevalue );
1978 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1979 $working = $working << 6;
1980 $working +
= ($bytevalue & 0x3F);
1982 if( $bytesleft <= 0 ) {
1983 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1985 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1986 $working = $bytevalue & 0x1F;
1988 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1989 $working = $bytevalue & 0x0F;
1991 } else { //1111 0xxx
1992 $working = $bytevalue & 0x07;
2000 * Reverse the previously applied transliteration of non-ASCII characters
2001 * back to UTF-8. Used to protect data from corruption by broken web browsers
2002 * as listed in $wgBrowserBlackList.
2004 * @param string $invalue
2008 function unmakesafe( $invalue ) {
2010 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2011 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2015 $hexstring .= $invalue{$i};
2017 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2019 // Do some sanity checks. These aren't needed for reversability,
2020 // but should help keep the breakage down if the editor
2021 // breaks one of the entities whilst editing.
2022 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2023 $codepoint = hexdec($hexstring);
2024 $result .= codepointToUtf8( $codepoint );
2026 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2029 $result .= substr( $invalue, $i, 1 );
2032 // reverse the transform that we made for reversability reasons.
2033 return strtr( $result, array( "�" => "&#x" ) );
2036 function noCreatePermission() {
2038 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2039 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
2043 * If there are rows in the deletion log for this page, show them,
2044 * along with a nice little note for the user
2046 * @param OutputPage $out
2048 private function showDeletionLog( $out ) {
2049 $title = $this->mArticle
->getTitle();
2050 $reader = new LogReader(
2053 'page' => $title->getPrefixedText(),
2058 if( $reader->hasRows() ) {
2059 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2060 $out->addHtml( $this->buildWarningDismisser() );
2061 $out->addWikiText( wfMsg( 'recreate-deleted-warn' ) );
2062 $viewer = new LogViewer( $reader );
2063 $viewer->showList( $out );
2064 $out->addHtml( '</div>' );
2069 * Builds a JavaScript fragment that injects a link to dismiss the
2070 * "recreating deleted" warning
2074 private function buildWarningDismisser() {
2075 return '<script type="text/javascript">'
2076 . 'document.write( \'<div class="mw-recreate-deleted-control">'
2077 . '<a href="javascript:dismissRecreateWarning();">'
2078 . wfMsgHtml( 'recreate-deleted-dismiss' ) . '</a></div>\' );'