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' ) );
612 * @return bool false if output is done, true if the rest of the form should be displayed
614 function attemptSave() {
615 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
616 global $wgMaxArticleSize;
618 $fname = 'EditPage::attemptSave';
619 wfProfileIn( $fname );
620 wfProfileIn( "$fname-checks" );
622 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
624 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
628 # Reintegrate metadata
629 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
630 $this->mMetaData
= '' ;
634 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
635 $this->spamPage ( $matches[0] );
636 wfProfileOut( "$fname-checks" );
637 wfProfileOut( $fname );
640 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
641 # Error messages or other handling should be performed by the filter function
642 wfProfileOut( $fname );
643 wfProfileOut( "$fname-checks" );
646 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
) ) ) {
647 # Error messages etc. could be handled within the hook...
648 wfProfileOut( $fname );
649 wfProfileOut( "$fname-checks" );
651 } elseif( $this->hookError
!= '' ) {
652 # ...or the hook could be expecting us to produce an error
653 wfProfileOut( "$fname-checks " );
654 wfProfileOut( $fname );
657 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
658 # Check block state against master, thus 'false'.
659 $this->blockedPage();
660 wfProfileOut( "$fname-checks" );
661 wfProfileOut( $fname );
664 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
665 if ( $this->kblength
> $wgMaxArticleSize ) {
666 // Error will be displayed by showEditForm()
667 $this->tooBig
= true;
668 wfProfileOut( "$fname-checks" );
669 wfProfileOut( $fname );
673 if ( !$wgUser->isAllowed('edit') ) {
674 if ( $wgUser->isAnon() ) {
675 $this->userNotLoggedInPage();
676 wfProfileOut( "$fname-checks" );
677 wfProfileOut( $fname );
681 $wgOut->readOnlyPage();
682 wfProfileOut( "$fname-checks" );
683 wfProfileOut( $fname );
688 if ( wfReadOnly() ) {
689 $wgOut->readOnlyPage();
690 wfProfileOut( "$fname-checks" );
691 wfProfileOut( $fname );
694 if ( $wgUser->pingLimiter() ) {
695 $wgOut->rateLimited();
696 wfProfileOut( "$fname-checks" );
697 wfProfileOut( $fname );
701 # If the article has been deleted while editing, don't save it without
703 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
704 wfProfileOut( "$fname-checks" );
705 wfProfileOut( $fname );
709 wfProfileOut( "$fname-checks" );
711 # If article is new, insert it.
712 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
715 // Late check for create permission, just in case *PARANOIA*
716 if ( !$this->mTitle
->userCan( 'create' ) ) {
717 wfDebug( "$fname: no create permission\n" );
718 $this->noCreatePermission();
719 wfProfileOut( $fname );
723 # Don't save a new article if it's blank.
724 if ( ( '' == $this->textbox1
) ) {
725 $wgOut->redirect( $this->mTitle
->getFullURL() );
726 wfProfileOut( $fname );
730 $isComment=($this->section
=='new');
731 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
732 $this->minoredit
, $this->watchthis
, false, $isComment);
734 wfProfileOut( $fname );
738 # Article exists. Check for edit conflict.
740 $this->mArticle
->clear(); # Force reload of dates, etc.
741 $this->mArticle
->forUpdate( true ); # Lock the article
743 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
745 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
746 $this->isConflict
= true;
747 if( $this->section
== 'new' ) {
748 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
749 $this->mArticle
->getComment() == $this->summary
) {
750 // Probably a duplicate submission of a new comment.
751 // This can happen when squid resends a request after
752 // a timeout but the first one actually went through.
753 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
755 // New comment; suppress conflict.
756 $this->isConflict
= false;
757 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
761 $userid = $wgUser->getID();
763 if ( $this->isConflict
) {
764 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
765 $this->mArticle
->getTimestamp() . "'\n" );
766 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
769 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
770 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
772 if( is_null( $text ) ) {
773 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
774 $this->isConflict
= true;
775 $text = $this->textbox1
;
778 # Suppress edit conflict with self, except for section edits where merging is required.
779 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
780 wfDebug( "Suppressing edit conflict, same user.\n" );
781 $this->isConflict
= false;
783 # switch from section editing to normal editing in edit conflict
784 if($this->isConflict
) {
786 if( $this->mergeChangesInto( $text ) ){
787 // Successful merge! Maybe we should tell the user the good news?
788 $this->isConflict
= false;
789 wfDebug( "Suppressing edit conflict, successful merge.\n" );
792 $this->textbox1
= $text;
793 wfDebug( "Keeping edit conflict, failed merge.\n" );
798 if ( $this->isConflict
) {
799 wfProfileOut( $fname );
803 $oldtext = $this->mArticle
->getContent();
805 # Handle the user preference to force summaries here, but not for null edits
806 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary')
807 && 0 != strcmp($oldtext, $text) && !Article
::getRedirectAutosummary( $text )) {
808 if( md5( $this->summary
) == $this->autoSumm
) {
809 $this->missingSummary
= true;
810 wfProfileOut( $fname );
815 #And a similar thing for new sections
816 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
817 if (trim($this->summary
) == '') {
818 $this->missingSummary
= true;
819 wfProfileOut( $fname );
825 wfProfileIn( "$fname-sectionanchor" );
827 if( $this->section
== 'new' ) {
828 if ( $this->textbox1
== '' ) {
829 $this->missingComment
= true;
832 if( $this->summary
!= '' ) {
833 $sectionanchor = $this->sectionAnchor( $this->summary
);
835 } elseif( $this->section
!= '' ) {
836 # Try to get a section anchor from the section source, redirect to edited section if header found
837 # XXX: might be better to integrate this into Article::replaceSection
838 # for duplicate heading checking and maybe parsing
839 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
840 # we can't deal with anchors, includes, html etc in the header for now,
841 # headline would need to be parsed to improve this
842 if($hasmatch and strlen($matches[2]) > 0) {
843 $sectionanchor = $this->sectionAnchor( $matches[2] );
846 wfProfileOut( "$fname-sectionanchor" );
848 // Save errors may fall down to the edit form, but we've now
849 // merged the section into full text. Clear the section field
850 // so that later submission of conflict forms won't try to
851 // replace that into a duplicated mess.
852 $this->textbox1
= $text;
855 // Check for length errors again now that the section is merged in
856 $this->kblength
= (int)(strlen( $text ) / 1024);
857 if ( $this->kblength
> $wgMaxArticleSize ) {
858 $this->tooBig
= true;
859 wfProfileOut( $fname );
863 # update the article here
864 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
865 $this->watchthis
, '', $sectionanchor ) ) {
866 wfProfileOut( $fname );
869 $this->isConflict
= true;
871 wfProfileOut( $fname );
876 * Initialise form fields in the object
877 * Called on the first invocation, e.g. when a user clicks an edit link
879 function initialiseForm() {
880 $this->edittime
= $this->mArticle
->getTimestamp();
882 $this->textbox1
= $this->getContent(false);
883 if ($this->textbox1
=== false) return false;
885 if ( !$this->mArticle
->exists() && $this->mArticle
->mTitle
->getNamespace() == NS_MEDIAWIKI
)
886 $this->textbox1
= wfMsgWeirdKey( $this->mArticle
->mTitle
->getText() );
892 * Send the edit form and related headers to $wgOut
893 * @param $formCallback Optional callable that takes an OutputPage
894 * parameter; will be called during form output
895 * near the top, for captchas and the like.
897 function showEditForm( $formCallback=null ) {
898 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
900 $fname = 'EditPage::showEditForm';
901 wfProfileIn( $fname );
903 $sk = $wgUser->getSkin();
905 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
907 $wgOut->setRobotpolicy( 'noindex,nofollow' );
909 # Enabled article-related sidebar, toplinks, etc.
910 $wgOut->setArticleRelated( true );
912 if ( $this->isConflict
) {
913 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
914 $wgOut->setPageTitle( $s );
915 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
917 $this->textbox2
= $this->textbox1
;
918 $this->textbox1
= $this->getContent();
919 $this->edittime
= $this->mArticle
->getTimestamp();
922 if( $this->section
!= '' ) {
923 if( $this->section
== 'new' ) {
924 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
926 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
928 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
929 preg_match( "/^(=+)(.+)\\1/mi",
932 if( !empty( $matches[2] ) ) {
933 $this->summary
= "/* ". trim($matches[2])." */ ";
938 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
940 $wgOut->setPageTitle( $s );
942 if ( $this->missingComment
) {
943 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
946 if( $this->missingSummary
&& $this->section
!= 'new' ) {
947 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
950 if( $this->missingSummary
&& $this->section
== 'new' ) {
951 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
954 if( !$this->hookError
== '' ) {
955 $wgOut->addWikiText( $this->hookError
);
958 if ( !$this->checkUnicodeCompliantBrowser() ) {
959 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
961 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
962 // Let sysop know that this will make private content public if saved
963 if( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
964 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
966 if( !$this->mArticle
->mRevision
->isCurrent() ) {
967 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
968 $wgOut->addWikiText( wfMsg( 'editingold' ) );
974 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
975 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
976 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
978 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
979 # Check the skin exists
980 if( $this->isValidCssJsSubpage
) {
981 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
983 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
988 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
989 # Show a warning if editing an interface message
990 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
991 } elseif( $this->mTitle
->isProtected( 'edit' ) ) {
992 # Is the title semi-protected?
993 if( $this->mTitle
->isSemiProtected() ) {
994 $notice = wfMsg( 'semiprotectedpagewarning' );
995 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' )
998 # Then it must be protected based on static groups (regular)
999 $notice = wfMsg( 'protectedpagewarning' );
1001 $wgOut->addWikiText( $notice );
1003 if ( $this->mTitle
->isCascadeProtected() ) {
1004 # Is this page under cascading protection from some source pages?
1005 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1006 if ( count($cascadeSources) > 0 ) {
1007 # Explain, and list the titles responsible
1008 $notice = wfMsgExt( 'cascadeprotectedwarning', array('parsemag'), count($cascadeSources) ) . "\n";
1009 foreach( $cascadeSources as $id => $page )
1010 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1012 $wgOut->addWikiText( $notice );
1015 if ( $this->kblength
=== false ) {
1016 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1018 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1019 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgMaxArticleSize ) );
1020 } elseif( $this->kblength
> 29 ) {
1021 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) ) );
1024 #need to parse the preview early so that we know which templates are used,
1025 #otherwise users with "show preview after edit box" will get a blank list
1026 if ( $this->formtype
== 'preview' ) {
1027 $previewOutput = $this->getPreviewText();
1030 $rows = $wgUser->getIntOption( 'rows' );
1031 $cols = $wgUser->getIntOption( 'cols' );
1033 $ew = $wgUser->getOption( 'editwidth' );
1034 if ( $ew ) $ew = " style=\"width:100%\"";
1037 $q = 'action=submit';
1038 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1039 $action = $this->mTitle
->escapeLocalURL( $q );
1041 $summary = wfMsg('summary');
1042 $subject = wfMsg('subject');
1044 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
1045 wfMsgExt('cancel', array('parseinline')) );
1046 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1047 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1048 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1049 htmlspecialchars( wfMsg( 'newwindow' ) );
1051 global $wgRightsText;
1052 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1053 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
1054 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1055 $wgRightsText ) . "\n</div>";
1057 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1058 # prepare toolbar for edit buttons
1059 $toolbar = $this->getEditToolbar();
1064 // activate checkboxes if user wants them to be always active
1065 if( !$this->preview
&& !$this->diff
) {
1066 # Sort out the "watch" checkbox
1067 if( $wgUser->getOption( 'watchdefault' ) ) {
1069 $this->watchthis
= true;
1070 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1072 $this->watchthis
= true;
1073 } elseif( $this->mTitle
->userIsWatching() ) {
1075 $this->watchthis
= true;
1078 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1081 $wgOut->addHTML( $this->editFormPageTop
);
1083 if ( $wgUser->getOption( 'previewontop' ) ) {
1085 if ( 'preview' == $this->formtype
) {
1086 $this->showPreview( $previewOutput );
1088 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1091 if ( 'diff' == $this->formtype
) {
1092 $wgOut->addStyle( 'common/diff.css' );
1093 $wgOut->addHTML( $this->getDiff() );
1098 $wgOut->addHTML( $this->editFormTextTop
);
1100 # if this is a comment, show a subject line at the top, which is also the edit summary.
1101 # Otherwise, show a summary field at the bottom
1102 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1103 if( $this->section
== 'new' ) {
1104 $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 />";
1106 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1107 $summarypreview = '';
1109 $commentsubject = '';
1110 $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 />";
1111 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1112 $subjectpreview = '';
1115 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1116 if( !$this->preview
&& !$this->diff
) {
1117 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1119 $templates = ($this->preview ||
$this->section
) ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1120 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1122 global $wgUseMetadataEdit ;
1123 if ( $wgUseMetadataEdit ) {
1124 $metadata = $this->mMetaData
;
1125 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1126 $top = wfMsgWikiHtml( 'metadata_help' );
1127 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1129 else $metadata = "" ;
1133 if ($this->deletedSinceEdit
) {
1134 if ( 'save' != $this->formtype
) {
1135 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1137 // Hide the toolbar and edit area, use can click preview to get it back
1138 // Add an confirmation checkbox and explanation.
1140 $hidden = 'type="hidden" style="display:none;"';
1141 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1143 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1144 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1150 $checkboxes = self
::getCheckboxes( $tabindex, $sk,
1151 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1153 $checkboxhtml = implode( $checkboxes, "\n" );
1155 $buttons = $this->getEditButtons( $tabindex );
1156 $buttonshtml = implode( $buttons, "\n" );
1158 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1159 ?
'' : Xml
::hidden( 'safemode', '1' );
1161 $wgOut->addHTML( <<<END
1163 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1167 if( is_callable( $formCallback ) ) {
1168 call_user_func_array( $formCallback, array( &$wgOut ) );
1171 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1173 // Put these up at the top to ensure they aren't lost on early form submission
1175 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1176 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1177 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1178 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1180 $wgOut->addHTML( <<<END
1184 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1185 cols='{$cols}'{$ew} $hidden>
1187 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
1192 $wgOut->addWikiText( $copywarn );
1193 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1203 "<div class='editButtons'>
1205 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1206 </div><!-- editButtons -->
1207 </div><!-- editOptions -->");
1209 $wgOut->addHtml( '<div class="mw-editTools">' );
1210 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1211 $wgOut->addHtml( '</div>' );
1213 $wgOut->addHTML( $this->editFormTextAfterTools
);
1216 <div class='templatesUsed'>
1217 {$formattedtemplates}
1222 * To make it harder for someone to slip a user a page
1223 * which submits an edit form to the wiki without their
1224 * knowledge, a random token is associated with the login
1225 * session. If it's not passed back with the submission,
1226 * we won't save the page, or render user JavaScript and
1229 * For anon editors, who may not have a session, we just
1230 * include the constant suffix to prevent editing from
1231 * broken text-mangling proxies.
1233 if ( $wgUser->isLoggedIn() )
1234 $token = htmlspecialchars( $wgUser->editToken() );
1236 $token = EDIT_TOKEN_SUFFIX
;
1237 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1240 # If a blank edit summary was previously provided, and the appropriate
1241 # user preference is active, pass a hidden tag here. This will stop the
1242 # user being bounced back more than once in the event that a summary
1244 if( $this->missingSummary
) {
1245 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1248 # For a bit more sophisticated detection of blank summaries, hash the
1249 # automatic one and pass that in a hidden field.
1250 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1251 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1253 if ( $this->isConflict
) {
1254 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1256 $de = new DifferenceEngine( $this->mTitle
);
1257 $de->setText( $this->textbox2
, $this->textbox1
);
1258 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1260 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1261 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1262 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1264 $wgOut->addHTML( $this->editFormTextBottom
);
1265 $wgOut->addHTML( "</form>\n" );
1266 if ( !$wgUser->getOption( 'previewontop' ) ) {
1268 if ( $this->formtype
== 'preview') {
1269 $this->showPreview( $previewOutput );
1271 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1274 if ( $this->formtype
== 'diff') {
1275 $wgOut->addStyle( 'common/diff.css' );
1276 $wgOut->addHTML( $this->getDiff() );
1281 wfProfileOut( $fname );
1285 * Append preview output to $wgOut.
1286 * Includes category rendering if this is a category page.
1288 * @param string $text The HTML to be output for the preview.
1290 private function showPreview( $text ) {
1293 $wgOut->addHTML( '<div id="wikiPreview">' );
1294 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1295 $this->mArticle
->openShowCategory();
1297 $wgOut->addHTML( $text );
1298 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1299 $this->mArticle
->closeShowCategory();
1301 $wgOut->addHTML( '</div>' );
1305 * Live Preview lets us fetch rendered preview page content and
1306 * add it to the page without refreshing the whole page.
1307 * If not supported by the browser it will fall through to the normal form
1308 * submission method.
1310 * This function outputs a script tag to support live preview, and
1311 * returns an onclick handler which should be added to the attributes
1312 * of the preview button
1314 function doLivePreviewScript() {
1315 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1316 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1317 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1318 '"></script>' . "\n" );
1319 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1320 return "return !livePreview(" .
1321 "getElementById('wikiPreview')," .
1322 "editform.wpTextbox1.value," .
1323 '"' . $liveAction . '"' . ")";
1326 function getLastDelete() {
1327 $dbr = wfGetDB( DB_SLAVE
);
1328 $fname = 'EditPage::getLastDelete';
1329 $res = $dbr->select(
1330 array( 'logging', 'user' ),
1340 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1341 'log_title' => $this->mTitle
->getDBkey(),
1342 'log_type' => 'delete',
1343 'log_action' => 'delete',
1344 'user_id=log_user' ),
1346 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1348 if($dbr->numRows($res) == 1) {
1349 while ( $x = $dbr->fetchObject ( $res ) )
1351 $dbr->freeResult ( $res ) ;
1361 function getPreviewText() {
1362 global $wgOut, $wgUser, $wgTitle, $wgParser;
1364 $fname = 'EditPage::getPreviewText';
1365 wfProfileIn( $fname );
1367 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1368 $msg = 'session_fail_preview';
1370 $msg = 'previewnote';
1372 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1373 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1374 if ( $this->isConflict
) {
1375 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1378 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1379 $parserOptions->setEditSection( false );
1382 if( $wgRawHtml && !$this->mTokenOk
) {
1383 // Could be an offsite preview attempt. This is very unsafe if
1384 // HTML is enabled, as it could be an attack.
1385 return $wgOut->parse( "<div class='previewnote'>" .
1386 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1389 # don't parse user css/js, show message about preview
1390 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1392 if ( $this->isCssJsSubpage
) {
1393 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1394 $previewtext = wfMsg('usercsspreview');
1395 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1396 $previewtext = wfMsg('userjspreview');
1398 $parserOptions->setTidy(true);
1399 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1400 $wgOut->addHTML( $parserOutput->mText
);
1401 wfProfileOut( $fname );
1402 return $previewhead;
1404 $toparse = $this->textbox1
;
1406 # If we're adding a comment, we need to show the
1407 # summary as the headline
1408 if($this->section
=="new" && $this->summary
!="") {
1409 $toparse="== {$this->summary} ==\n\n".$toparse;
1412 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1413 $parserOptions->setTidy(true);
1414 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1415 $wgTitle, $parserOptions );
1417 $previewHTML = $parserOutput->getText();
1418 $wgOut->addParserOutputNoText( $parserOutput );
1420 foreach ( $parserOutput->getTemplates() as $ns => $template)
1421 foreach ( array_keys( $template ) as $dbk)
1422 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1424 wfProfileOut( $fname );
1425 return $previewhead . $previewHTML;
1430 * Call the stock "user is blocked" page
1432 function blockedPage() {
1433 global $wgOut, $wgUser;
1434 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1436 # If the user made changes, preserve them when showing the markup
1437 # (This happens when a user is blocked during edit, for instance)
1438 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1440 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1442 $source = $this->textbox1
;
1445 # Spit out the source or the user's modified version
1446 if( $source !== false ) {
1447 $rows = $wgUser->getOption( 'rows' );
1448 $cols = $wgUser->getOption( 'cols' );
1449 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1450 $wgOut->addHtml( '<hr />' );
1451 $wgOut->addWikiText( wfMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() ) );
1452 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1457 * Produce the stock "please login to edit pages" page
1459 function userNotLoggedInPage() {
1460 global $wgUser, $wgOut;
1461 $skin = $wgUser->getSkin();
1463 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1464 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle
->getPrefixedUrl() );
1466 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1467 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1468 $wgOut->setArticleRelated( false );
1470 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1471 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1475 * Creates a basic error page which informs the user that
1476 * they have to validate their email address before being
1479 function userNotConfirmedPage() {
1482 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1483 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1484 $wgOut->setArticleRelated( false );
1486 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1487 $wgOut->returnToMain( false );
1491 * Creates a basic error page which informs the user that
1492 * they have attempted to edit a nonexistant section.
1494 function noSuchSectionPage() {
1497 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1498 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1499 $wgOut->setArticleRelated( false );
1501 $wgOut->addWikiText( wfMsg( 'nosuchsectiontext', $this->section
) );
1502 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1506 * Produce the stock "your edit contains spam" page
1508 * @param $match Text which triggered one or more filters
1510 function spamPage( $match = false ) {
1513 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1514 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1515 $wgOut->setArticleRelated( false );
1517 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1519 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1521 $wgOut->returnToMain( false );
1528 function mergeChangesInto( &$editText ){
1529 $fname = 'EditPage::mergeChangesInto';
1530 wfProfileIn( $fname );
1532 $db = wfGetDB( DB_MASTER
);
1534 // This is the revision the editor started from
1535 $baseRevision = Revision
::loadFromTimestamp(
1536 $db, $this->mArticle
->mTitle
, $this->edittime
);
1537 if( is_null( $baseRevision ) ) {
1538 wfProfileOut( $fname );
1541 $baseText = $baseRevision->getText();
1543 // The current state, we want to merge updates into it
1544 $currentRevision = Revision
::loadFromTitle(
1545 $db, $this->mArticle
->mTitle
);
1546 if( is_null( $currentRevision ) ) {
1547 wfProfileOut( $fname );
1550 $currentText = $currentRevision->getText();
1553 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1554 $editText = $result;
1555 wfProfileOut( $fname );
1558 wfProfileOut( $fname );
1564 * Check if the browser is on a blacklist of user-agents known to
1565 * mangle UTF-8 data on form submission. Returns true if Unicode
1566 * should make it through, false if it's known to be a problem.
1570 function checkUnicodeCompliantBrowser() {
1571 global $wgBrowserBlackList;
1572 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1573 // No User-Agent header sent? Trust it by default...
1576 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1577 foreach ( $wgBrowserBlackList as $browser ) {
1578 if ( preg_match($browser, $currentbrowser) ) {
1586 * Format an anchor fragment as it would appear for a given section name
1587 * @param string $text
1591 function sectionAnchor( $text ) {
1592 $headline = Sanitizer
::decodeCharReferences( $text );
1594 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1595 $headline = trim( $headline );
1596 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1597 $replacearray = array(
1602 array_keys( $replacearray ),
1603 array_values( $replacearray ),
1608 * Shows a bulletin board style toolbar for common editing functions.
1609 * It can be disabled in the user preferences.
1610 * The necessary JavaScript code can be found in style/wikibits.js.
1612 function getEditToolbar() {
1613 global $wgStylePath, $wgContLang, $wgJsMimeType;
1616 * toolarray an array of arrays which each include the filename of
1617 * the button image (without path), the opening tag, the closing tag,
1618 * and optionally a sample text that is inserted between the two when no
1619 * selection is highlighted.
1620 * The tip text is shown when the user moves the mouse over the button.
1622 * Already here are accesskeys (key), which are not used yet until someone
1623 * can figure out a way to make them work in IE. However, we should make
1624 * sure these keys are not defined on the edit page.
1627 array( 'image' => 'button_bold.png',
1628 'id' => 'mw-editbutton-bold',
1629 'open' => '\\\'\\\'\\\'',
1630 'close' => '\\\'\\\'\\\'',
1631 'sample'=> wfMsg('bold_sample'),
1632 'tip' => wfMsg('bold_tip'),
1635 array( 'image' => 'button_italic.png',
1636 'id' => 'mw-editbutton-italic',
1637 'open' => '\\\'\\\'',
1638 'close' => '\\\'\\\'',
1639 'sample'=> wfMsg('italic_sample'),
1640 'tip' => wfMsg('italic_tip'),
1643 array( 'image' => 'button_link.png',
1644 'id' => 'mw-editbutton-link',
1647 'sample'=> wfMsg('link_sample'),
1648 'tip' => wfMsg('link_tip'),
1651 array( 'image' => 'button_extlink.png',
1652 'id' => 'mw-editbutton-extlink',
1655 'sample'=> wfMsg('extlink_sample'),
1656 'tip' => wfMsg('extlink_tip'),
1659 array( 'image' => 'button_headline.png',
1660 'id' => 'mw-editbutton-headline',
1662 'close' => " ==\\n",
1663 'sample'=> wfMsg('headline_sample'),
1664 'tip' => wfMsg('headline_tip'),
1667 array( 'image' => 'button_image.png',
1668 'id' => 'mw-editbutton-image',
1669 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1671 'sample'=> wfMsg('image_sample'),
1672 'tip' => wfMsg('image_tip'),
1675 array( 'image' => 'button_media.png',
1676 'id' => 'mw-editbutton-media',
1677 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1679 'sample'=> wfMsg('media_sample'),
1680 'tip' => wfMsg('media_tip'),
1683 array( 'image' => 'button_math.png',
1684 'id' => 'mw-editbutton-math',
1686 'close' => "<\\/math>",
1687 'sample'=> wfMsg('math_sample'),
1688 'tip' => wfMsg('math_tip'),
1691 array( 'image' => 'button_nowiki.png',
1692 'id' => 'mw-editbutton-nowiki',
1693 'open' => "<nowiki>",
1694 'close' => "<\\/nowiki>",
1695 'sample'=> wfMsg('nowiki_sample'),
1696 'tip' => wfMsg('nowiki_tip'),
1699 array( 'image' => 'button_sig.png',
1700 'id' => 'mw-editbutton-signature',
1704 'tip' => wfMsg('sig_tip'),
1707 array( 'image' => 'button_hr.png',
1708 'id' => 'mw-editbutton-hr',
1709 'open' => "\\n----\\n",
1712 'tip' => wfMsg('hr_tip'),
1716 $toolbar = "<div id='toolbar'>\n";
1717 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1719 foreach($toolarray as $tool) {
1721 $cssId = $tool['id'];
1722 $image=$wgStylePath.'/common/images/'.$tool['image'];
1723 $open=$tool['open'];
1724 $close=$tool['close'];
1725 $sample = wfEscapeJsString( $tool['sample'] );
1727 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1728 // Older browsers show a "speedtip" type message only for ALT.
1729 // Ideally these should be different, realistically they
1730 // probably don't need to be.
1731 $tip = wfEscapeJsString( $tool['tip'] );
1733 #$key = $tool["key"];
1735 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1738 $toolbar.="/*]]>*/\n</script>";
1739 $toolbar.="\n</div>";
1744 * Returns an array of html code of the following checkboxes:
1747 * @param $tabindex Current tabindex
1748 * @param $skin Skin object
1749 * @param $checked Array of checkbox => bool, where bool indicates the checked
1750 * status of the checkbox
1754 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1757 $checkboxes = array();
1759 $checkboxes['minor'] = '';
1760 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1761 if ( $wgUser->isAllowed('minoredit') ) {
1763 'tabindex' => ++
$tabindex,
1764 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1765 'id' => 'wpMinoredit',
1767 $checkboxes['minor'] =
1768 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1769 " <label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1772 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1773 $checkboxes['watch'] = '';
1774 if ( $wgUser->isLoggedIn() ) {
1776 'tabindex' => ++
$tabindex,
1777 'accesskey' => wfMsg( 'accesskey-watch' ),
1778 'id' => 'wpWatchthis',
1780 $checkboxes['watch'] =
1781 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1782 " <label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1788 * Returns an array of html code of the following buttons:
1789 * save, diff, preview and live
1791 * @param $tabindex Current tabindex
1795 public function getEditButtons(&$tabindex) {
1796 global $wgLivePreview, $wgUser;
1804 'tabindex' => ++
$tabindex,
1805 'value' => wfMsg('savearticle'),
1806 'accesskey' => wfMsg('accesskey-save'),
1807 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1809 $buttons['save'] = wfElement('input', $temp, '');
1811 ++
$tabindex; // use the same for preview and live preview
1812 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1814 'id' => 'wpPreview',
1815 'name' => 'wpPreview',
1817 'tabindex' => $tabindex,
1818 'value' => wfMsg('showpreview'),
1820 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1821 'style' => 'display: none;',
1823 $buttons['preview'] = wfElement('input', $temp, '');
1826 'id' => 'wpLivePreview',
1827 'name' => 'wpLivePreview',
1829 'tabindex' => $tabindex,
1830 'value' => wfMsg('showlivepreview'),
1831 'accesskey' => wfMsg('accesskey-preview'),
1833 'onclick' => $this->doLivePreviewScript(),
1835 $buttons['live'] = wfElement('input', $temp, '');
1838 'id' => 'wpPreview',
1839 'name' => 'wpPreview',
1841 'tabindex' => $tabindex,
1842 'value' => wfMsg('showpreview'),
1843 'accesskey' => wfMsg('accesskey-preview'),
1844 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1846 $buttons['preview'] = wfElement('input', $temp, '');
1847 $buttons['live'] = '';
1854 'tabindex' => ++
$tabindex,
1855 'value' => wfMsg('showdiff'),
1856 'accesskey' => wfMsg('accesskey-diff'),
1857 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1859 $buttons['diff'] = wfElement('input', $temp, '');
1865 * Output preview text only. This can be sucked into the edit page
1866 * via JavaScript, and saves the server time rendering the skin as
1867 * well as theoretically being more robust on the client (doesn't
1868 * disturb the edit box's undo history, won't eat your text on
1871 * @todo This doesn't include category or interlanguage links.
1872 * Would need to enhance it a bit, <s>maybe wrap them in XML
1873 * or something...</s> that might also require more skin
1874 * initialization, so check whether that's a problem.
1876 function livePreview() {
1879 header( 'Content-type: text/xml; charset=utf-8' );
1880 header( 'Cache-control: no-cache' );
1883 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1884 Xml
::openElement( 'livepreview' ) .
1885 Xml
::element( 'preview', null, $this->getPreviewText() ) .
1886 Xml
::element( 'br', array( 'style' => 'clear: both;' ) ) .
1887 Xml
::closeElement( 'livepreview' );
1893 * Get a diff between the current contents of the edit box and the
1894 * version of the page we're editing from.
1896 * If this is a section edit, we'll replace the section as for final
1897 * save and then make a comparison.
1899 * @return string HTML
1901 function getDiff() {
1902 $oldtext = $this->mArticle
->fetchContent();
1903 $newtext = $this->mArticle
->replaceSection(
1904 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1905 $newtext = $this->mArticle
->preSaveTransform( $newtext );
1906 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1907 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1908 if ( $oldtext !== false ||
$newtext != '' ) {
1909 $de = new DifferenceEngine( $this->mTitle
);
1910 $de->setText( $oldtext, $newtext );
1911 $difftext = $de->getDiff( $oldtitle, $newtitle );
1916 return '<div id="wikiDiff">' . $difftext . '</div>';
1920 * Filter an input field through a Unicode de-armoring process if it
1921 * came from an old browser with known broken Unicode editing issues.
1923 * @param WebRequest $request
1924 * @param string $field
1928 function safeUnicodeInput( $request, $field ) {
1929 $text = rtrim( $request->getText( $field ) );
1930 return $request->getBool( 'safemode' )
1931 ?
$this->unmakesafe( $text )
1936 * Filter an output field through a Unicode armoring process if it is
1937 * going to an old browser with known broken Unicode editing issues.
1939 * @param string $text
1943 function safeUnicodeOutput( $text ) {
1945 $codedText = $wgContLang->recodeForEdit( $text );
1946 return $this->checkUnicodeCompliantBrowser()
1948 : $this->makesafe( $codedText );
1952 * A number of web browsers are known to corrupt non-ASCII characters
1953 * in a UTF-8 text editing environment. To protect against this,
1954 * detected browsers will be served an armored version of the text,
1955 * with non-ASCII chars converted to numeric HTML character references.
1957 * Preexisting such character references will have a 0 added to them
1958 * to ensure that round-trips do not alter the original data.
1960 * @param string $invalue
1964 function makesafe( $invalue ) {
1965 // Armor existing references for reversability.
1966 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1971 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1972 $bytevalue = ord( $invalue{$i} );
1973 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1974 $result .= chr( $bytevalue );
1976 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1977 $working = $working << 6;
1978 $working +
= ($bytevalue & 0x3F);
1980 if( $bytesleft <= 0 ) {
1981 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1983 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1984 $working = $bytevalue & 0x1F;
1986 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1987 $working = $bytevalue & 0x0F;
1989 } else { //1111 0xxx
1990 $working = $bytevalue & 0x07;
1998 * Reverse the previously applied transliteration of non-ASCII characters
1999 * back to UTF-8. Used to protect data from corruption by broken web browsers
2000 * as listed in $wgBrowserBlackList.
2002 * @param string $invalue
2006 function unmakesafe( $invalue ) {
2008 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2009 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2013 $hexstring .= $invalue{$i};
2015 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2017 // Do some sanity checks. These aren't needed for reversability,
2018 // but should help keep the breakage down if the editor
2019 // breaks one of the entities whilst editing.
2020 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2021 $codepoint = hexdec($hexstring);
2022 $result .= codepointToUtf8( $codepoint );
2024 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2027 $result .= substr( $invalue, $i, 1 );
2030 // reverse the transform that we made for reversability reasons.
2031 return strtr( $result, array( "�" => "&#x" ) );
2034 function noCreatePermission() {
2036 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2037 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );