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 $undo = $wgRequest->getVal( 'undo' );
76 wfProfileIn( __METHOD__
);
79 if( !$this->mTitle
->exists() ) {
80 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
81 # If this is a system message, get the default text.
82 $text = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
84 # If requested, preload some text.
85 $text = $this->getPreloadedText( $preload );
87 # We used to put MediaWiki:Newarticletext here if
88 # $text was empty at this point.
89 # This is now shown above the edit box instead.
91 // FIXME: may be better to use Revision class directly
92 // But don't mess with it just yet. Article knows how to
93 // fetch the page record from the high-priority server,
94 // which is needed to guarantee we don't pick up lagged
97 $text = $this->mArticle
->getContent();
100 #Undoing a specific edit overrides section editing; section-editing
101 # doesn't work with undoing.
102 $undorev = Revision
::newFromId($undo);
103 $oldrev = $undorev ?
$undorev->getPrevious() : null;
105 #Sanity check, make sure it's the right page.
106 # Otherwise, $text will be left as-is.
107 if( !is_null($undorev)
108 && !is_null( $oldrev )
109 && $undorev->getPage() == $this->mArticle
->getID() ) {
111 $undorev_text = $undorev->getText();
112 $oldrev_text = $oldrev->getText();
113 $currev_text = $text;
115 #No use doing a merge if it's just a straight revert.
116 if ($currev_text != $undorev_text) {
117 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
119 $text = $oldrev_text;
123 // Failed basic sanity checks.
124 // Older revisions may have been removed since the link
125 // was created, or we may simply have got bogus input.
130 # Inform the user of our success and set an automatic edit summary
131 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
132 $firstrev = $oldrev->getNext();
133 # If we just undid one rev, use an autosummary
134 if ( $firstrev->mId
== $undo ) {
135 $this->summary
= wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
137 $this->formtype
= 'diff';
139 # Warn the user that something went wrong
140 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
142 } else if( $section != '' ) {
143 if( $section == 'new' ) {
144 $text = $this->getPreloadedText( $preload );
146 $text = $wgParser->getSection( $text, $section, $def_text );
151 wfProfileOut( __METHOD__
);
156 * Get the contents of a page from its title and remove includeonly tags
158 * @param $preload String: the title of the page.
159 * @return string The contents of the page.
161 private function getPreloadedText($preload) {
162 if ( $preload === '' )
165 $preloadTitle = Title
::newFromText( $preload );
166 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
167 $rev=Revision
::newFromTitle($preloadTitle);
168 if ( is_object( $rev ) ) {
169 $text = $rev->getText();
170 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
171 // its own mini-parser! -ævar
172 $text = preg_replace( '~</?includeonly>~', '', $text );
181 * This is the function that extracts metadata from the article body on the first view.
182 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
183 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
185 function extractMetaDataFromArticle () {
186 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
187 $this->mMetaData
= '' ;
188 if ( !$wgUseMetadataEdit ) return ;
189 if ( $wgMetadataWhitelist == '' ) return ;
191 $t = $this->getContent();
193 # MISSING : <nowiki> filtering
195 # Categories and language links
196 $t = explode ( "\n" , $t ) ;
197 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
198 $cat = $ll = array() ;
199 foreach ( $t AS $key => $x )
201 $y = trim ( strtolower ( $x ) ) ;
202 while ( substr ( $y , 0 , 2 ) == '[[' )
204 $y = explode ( ']]' , trim ( $x ) ) ;
205 $first = array_shift ( $y ) ;
206 $first = explode ( ':' , $first ) ;
207 $ns = array_shift ( $first ) ;
208 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
209 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
211 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
212 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
214 $x = implode ( ']]' , $y ) ;
216 $y = trim ( strtolower ( $x ) ) ;
220 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
221 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
222 $t = implode ( "\n" , $t ) ;
225 $sat = array () ; # stand-alone-templates; must be lowercase
226 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
227 $wl_article = new Article ( $wl_title ) ;
228 $wl = explode ( "\n" , $wl_article->getContent() ) ;
229 foreach ( $wl AS $x )
233 while ( substr ( $x , 0 , 1 ) == '*' )
236 $x = trim ( substr ( $x , 1 ) ) ;
240 $sat[] = strtolower ( $x ) ;
245 # Templates, but only some
246 $t = explode ( '{{' , $t ) ;
248 foreach ( $t AS $key => $x )
250 $y = explode ( '}}' , $x , 2 ) ;
251 if ( count ( $y ) == 2 )
254 $z = explode ( '|' , $z ) ;
255 $tn = array_shift ( $z ) ;
256 if ( in_array ( strtolower ( $tn ) , $sat ) )
258 $tl[] = '{{' . $y[0] . '}}' ;
260 $y = explode ( '}}' , $y[1] , 2 ) ;
262 else $t[$key] = '{{' . $x ;
264 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
267 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
268 $t = implode ( '' , $t ) ;
270 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
271 $this->mArticle
->mContent
= $t ;
272 $this->mMetaData
= $s ;
280 * This is the function that gets called for "action=edit". It
281 * sets up various member variables, then passes execution to
282 * another function, usually showEditForm()
284 * The edit form is self-submitting, so that when things like
285 * preview and edit conflicts occur, we get the same form back
286 * with the extra stuff added. Only when the final submission
287 * is made and all is well do we actually save and redirect to
288 * the newly-edited page.
291 global $wgOut, $wgUser, $wgRequest, $wgTitle;
292 global $wgEmailConfirmToEdit;
294 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
297 $fname = 'EditPage::edit';
298 wfProfileIn( $fname );
299 wfDebug( "$fname: enter\n" );
301 // this is not an article
302 $wgOut->setArticleFlag(false);
304 $this->importFormData( $wgRequest );
305 $this->firsttime
= false;
308 $this->livePreview();
309 wfProfileOut( $fname );
313 if ( ! $this->mTitle
->userCan( 'edit' ) ) {
314 wfDebug( "$fname: user can't edit\n" );
315 $wgOut->readOnlyPage( $this->getContent(), true );
316 wfProfileOut( $fname );
319 wfDebug( "$fname: Checking blocks\n" );
320 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
321 # When previewing, don't check blocked state - will get caught at save time.
322 # Also, check when starting edition is done against slave to improve performance.
323 wfDebug( "$fname: user is blocked\n" );
324 $this->blockedPage();
325 wfProfileOut( $fname );
328 if ( !$wgUser->isAllowed('edit') ) {
329 if ( $wgUser->isAnon() ) {
330 wfDebug( "$fname: user must log in\n" );
331 $this->userNotLoggedInPage();
332 wfProfileOut( $fname );
335 wfDebug( "$fname: read-only page\n" );
336 $wgOut->readOnlyPage( $this->getContent(), true );
337 wfProfileOut( $fname );
341 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
342 wfDebug("$fname: user must confirm e-mail address\n");
343 $this->userNotConfirmedPage();
344 wfProfileOut($fname);
347 if ( !$this->mTitle
->userCan( 'create' ) && !$this->mTitle
->exists() ) {
348 wfDebug( "$fname: no create permission\n" );
349 $this->noCreatePermission();
350 wfProfileOut( $fname );
353 if ( wfReadOnly() ) {
354 wfDebug( "$fname: read-only mode is engaged\n" );
355 if( $this->save ||
$this->preview
) {
356 $this->formtype
= 'preview';
357 } else if ( $this->diff
) {
358 $this->formtype
= 'diff';
360 $wgOut->readOnlyPage( $this->getContent() );
361 wfProfileOut( $fname );
366 $this->formtype
= 'save';
367 } else if ( $this->preview
) {
368 $this->formtype
= 'preview';
369 } else if ( $this->diff
) {
370 $this->formtype
= 'diff';
371 } else { # First time through
372 $this->firsttime
= true;
373 if( $this->previewOnOpen() ) {
374 $this->formtype
= 'preview';
376 $this->extractMetaDataFromArticle () ;
377 $this->formtype
= 'initial';
382 wfProfileIn( "$fname-business-end" );
384 $this->isConflict
= false;
385 // css / js subpages of user pages get a special treatment
386 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
387 $this->isValidCssJsSubpage
= $wgTitle->isValidCssJsSubpage();
389 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
390 * no matter it's current state
392 $this->deletedSinceEdit
= false;
393 if ( $this->edittime
!= '' ) {
394 /* Note that we rely on logging table, which hasn't been always there,
395 * but that doesn't matter, because this only applies to brand new
396 * deletes. This is done on every preview and save request. Move it further down
397 * to only perform it on saves
399 if ( $this->mTitle
->isDeleted() ) {
400 $this->lastDelete
= $this->getLastDelete();
401 if ( !is_null($this->lastDelete
) ) {
402 $deletetime = $this->lastDelete
->log_timestamp
;
403 if ( ($deletetime - $this->starttime
) > 0 ) {
404 $this->deletedSinceEdit
= true;
410 if(!$this->mTitle
->getArticleID() && ('initial' == $this->formtype ||
$this->firsttime
)) { # new article
413 if( $this->mTitle
->isTalkPage() ) {
414 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
417 # Attempt submission here. This will check for edit conflicts,
418 # and redundantly check for locked database, blocked IPs, etc.
419 # that edit() already checked just in case someone tries to sneak
420 # in the back door with a hand-edited submission URL.
422 if ( 'save' == $this->formtype
) {
423 if ( !$this->attemptSave() ) {
424 wfProfileOut( "$fname-business-end" );
425 wfProfileOut( $fname );
430 # First time through: get contents, set time for conflict
432 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
433 if ($this->initialiseForm() === false) {
434 $this->noSuchSectionPage();
435 wfProfileOut( "$fname-business-end" );
436 wfProfileOut( $fname );
439 if( !$this->mTitle
->getArticleId() )
440 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
443 $this->showEditForm();
444 wfProfileOut( "$fname-business-end" );
445 wfProfileOut( $fname );
449 * Return true if this page should be previewed when the edit form
450 * is initially opened.
454 function previewOnOpen() {
456 return $this->section
!= 'new' &&
457 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle
->exists() ) ||
458 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
459 !$this->mTitle
->exists() ) );
466 function importFormData( &$request ) {
467 global $wgLang, $wgUser;
468 $fname = 'EditPage::importFormData';
469 wfProfileIn( $fname );
471 if( $request->wasPosted() ) {
472 # These fields need to be checked for encoding.
473 # Also remove trailing whitespace, but don't remove _initial_
474 # whitespace from the text boxes. This may be significant formatting.
475 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
476 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
477 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
478 # Truncate for whole multibyte characters. +5 bytes for ellipsis
479 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
481 $this->edittime
= $request->getVal( 'wpEdittime' );
482 $this->starttime
= $request->getVal( 'wpStarttime' );
484 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
486 if( is_null( $this->edittime
) ) {
487 # If the form is incomplete, force to preview.
488 wfDebug( "$fname: Form data appears to be incomplete\n" );
489 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
490 $this->preview
= true;
492 /* Fallback for live preview */
493 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
494 $this->diff
= $request->getCheck( 'wpDiff' );
496 // Remember whether a save was requested, so we can indicate
497 // if we forced preview due to session failure.
498 $this->mTriedSave
= !$this->preview
;
500 if ( $this->tokenOk( $request ) ) {
501 # Some browsers will not report any submit button
502 # if the user hits enter in the comment box.
503 # The unmarked state will be assumed to be a save,
504 # if the form seems otherwise complete.
505 wfDebug( "$fname: Passed token check.\n" );
506 } else if ( $this->diff
) {
507 # Failed token check, but only requested "Show Changes".
508 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
510 # Page might be a hack attempt posted from
511 # an external site. Preview instead of saving.
512 wfDebug( "$fname: Failed token check; forcing preview\n" );
513 $this->preview
= true;
516 $this->save
= ! ( $this->preview
OR $this->diff
);
517 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
518 $this->edittime
= null;
521 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
522 $this->starttime
= null;
525 $this->recreate
= $request->getCheck( 'wpRecreate' );
527 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
528 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
530 # Don't force edit summaries when a user is editing their own user or talk page
531 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
532 $this->allowBlankSummary
= true;
534 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
537 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
539 # Not a posted form? Start with nothing.
540 wfDebug( "$fname: Not a posted form.\n" );
541 $this->textbox1
= '';
542 $this->textbox2
= '';
543 $this->mMetaData
= '';
545 $this->edittime
= '';
546 $this->starttime
= wfTimestampNow();
547 $this->preview
= false;
550 $this->minoredit
= false;
551 $this->watchthis
= false;
552 $this->recreate
= false;
555 $this->oldid
= $request->getInt( 'oldid' );
557 # Section edit can come from either the form or a link
558 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
560 $this->live
= $request->getCheck( 'live' );
561 $this->editintro
= $request->getText( 'editintro' );
563 wfProfileOut( $fname );
567 * Make sure the form isn't faking a user's credentials.
569 * @param $request WebRequest
573 function tokenOk( &$request ) {
575 if( $wgUser->isAnon() ) {
576 # Anonymous users may not have a session
577 # open. Check for suffix anyway.
578 $this->mTokenOk
= ( EDIT_TOKEN_SUFFIX
== $request->getVal( 'wpEditToken' ) );
580 $this->mTokenOk
= $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
582 return $this->mTokenOk
;
586 function showIntro() {
587 global $wgOut, $wgUser;
588 $addstandardintro=true;
589 if($this->editintro
) {
590 $introtitle=Title
::newFromText($this->editintro
);
591 if(isset($introtitle) && $introtitle->userCanRead()) {
592 $rev=Revision
::newFromTitle($introtitle);
594 $wgOut->addSecondaryWikiText($rev->getText());
595 $addstandardintro=false;
599 if($addstandardintro) {
600 if ( $wgUser->isLoggedIn() )
601 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
603 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
609 * @return bool false if output is done, true if the rest of the form should be displayed
611 function attemptSave() {
612 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
613 global $wgMaxArticleSize;
615 $fname = 'EditPage::attemptSave';
616 wfProfileIn( $fname );
617 wfProfileIn( "$fname-checks" );
619 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
621 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
625 # Reintegrate metadata
626 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
627 $this->mMetaData
= '' ;
631 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
632 $this->spamPage ( $matches[0] );
633 wfProfileOut( "$fname-checks" );
634 wfProfileOut( $fname );
637 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
638 # Error messages or other handling should be performed by the filter function
639 wfProfileOut( $fname );
640 wfProfileOut( "$fname-checks" );
643 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
) ) ) {
644 # Error messages etc. could be handled within the hook...
645 wfProfileOut( $fname );
646 wfProfileOut( "$fname-checks" );
648 } elseif( $this->hookError
!= '' ) {
649 # ...or the hook could be expecting us to produce an error
650 wfProfileOut( "$fname-checks " );
651 wfProfileOut( $fname );
654 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
655 # Check block state against master, thus 'false'.
656 $this->blockedPage();
657 wfProfileOut( "$fname-checks" );
658 wfProfileOut( $fname );
661 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
662 if ( $this->kblength
> $wgMaxArticleSize ) {
663 // Error will be displayed by showEditForm()
664 $this->tooBig
= true;
665 wfProfileOut( "$fname-checks" );
666 wfProfileOut( $fname );
670 if ( !$wgUser->isAllowed('edit') ) {
671 if ( $wgUser->isAnon() ) {
672 $this->userNotLoggedInPage();
673 wfProfileOut( "$fname-checks" );
674 wfProfileOut( $fname );
678 $wgOut->readOnlyPage();
679 wfProfileOut( "$fname-checks" );
680 wfProfileOut( $fname );
685 if ( wfReadOnly() ) {
686 $wgOut->readOnlyPage();
687 wfProfileOut( "$fname-checks" );
688 wfProfileOut( $fname );
691 if ( $wgUser->pingLimiter() ) {
692 $wgOut->rateLimited();
693 wfProfileOut( "$fname-checks" );
694 wfProfileOut( $fname );
698 # If the article has been deleted while editing, don't save it without
700 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
701 wfProfileOut( "$fname-checks" );
702 wfProfileOut( $fname );
706 wfProfileOut( "$fname-checks" );
708 # If article is new, insert it.
709 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
712 // Late check for create permission, just in case *PARANOIA*
713 if ( !$this->mTitle
->userCan( 'create' ) ) {
714 wfDebug( "$fname: no create permission\n" );
715 $this->noCreatePermission();
716 wfProfileOut( $fname );
720 # Don't save a new article if it's blank.
721 if ( ( '' == $this->textbox1
) ) {
722 $wgOut->redirect( $this->mTitle
->getFullURL() );
723 wfProfileOut( $fname );
727 $isComment=($this->section
=='new');
728 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
729 $this->minoredit
, $this->watchthis
, false, $isComment);
731 wfProfileOut( $fname );
735 # Article exists. Check for edit conflict.
737 $this->mArticle
->clear(); # Force reload of dates, etc.
738 $this->mArticle
->forUpdate( true ); # Lock the article
740 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
742 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
743 $this->isConflict
= true;
744 if( $this->section
== 'new' ) {
745 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
746 $this->mArticle
->getComment() == $this->summary
) {
747 // Probably a duplicate submission of a new comment.
748 // This can happen when squid resends a request after
749 // a timeout but the first one actually went through.
750 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
752 // New comment; suppress conflict.
753 $this->isConflict
= false;
754 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
758 $userid = $wgUser->getID();
760 if ( $this->isConflict
) {
761 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
762 $this->mArticle
->getTimestamp() . "'\n" );
763 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
766 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
767 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
769 if( is_null( $text ) ) {
770 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
771 $this->isConflict
= true;
772 $text = $this->textbox1
;
775 # Suppress edit conflict with self, except for section edits where merging is required.
776 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
777 wfDebug( "Suppressing edit conflict, same user.\n" );
778 $this->isConflict
= false;
780 # switch from section editing to normal editing in edit conflict
781 if($this->isConflict
) {
783 if( $this->mergeChangesInto( $text ) ){
784 // Successful merge! Maybe we should tell the user the good news?
785 $this->isConflict
= false;
786 wfDebug( "Suppressing edit conflict, successful merge.\n" );
789 $this->textbox1
= $text;
790 wfDebug( "Keeping edit conflict, failed merge.\n" );
795 if ( $this->isConflict
) {
796 wfProfileOut( $fname );
800 $oldtext = $this->mArticle
->getContent();
802 # Handle the user preference to force summaries here, but not for null edits
803 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary')
804 && 0 != strcmp($oldtext, $text) && !Article
::getRedirectAutosummary( $text )) {
805 if( md5( $this->summary
) == $this->autoSumm
) {
806 $this->missingSummary
= true;
807 wfProfileOut( $fname );
812 #And a similar thing for new sections
813 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
814 if (trim($this->summary
) == '') {
815 $this->missingSummary
= true;
816 wfProfileOut( $fname );
822 wfProfileIn( "$fname-sectionanchor" );
824 if( $this->section
== 'new' ) {
825 if ( $this->textbox1
== '' ) {
826 $this->missingComment
= true;
829 if( $this->summary
!= '' ) {
830 $sectionanchor = $this->sectionAnchor( $this->summary
);
832 } elseif( $this->section
!= '' ) {
833 # Try to get a section anchor from the section source, redirect to edited section if header found
834 # XXX: might be better to integrate this into Article::replaceSection
835 # for duplicate heading checking and maybe parsing
836 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
837 # we can't deal with anchors, includes, html etc in the header for now,
838 # headline would need to be parsed to improve this
839 if($hasmatch and strlen($matches[2]) > 0) {
840 $sectionanchor = $this->sectionAnchor( $matches[2] );
843 wfProfileOut( "$fname-sectionanchor" );
845 // Save errors may fall down to the edit form, but we've now
846 // merged the section into full text. Clear the section field
847 // so that later submission of conflict forms won't try to
848 // replace that into a duplicated mess.
849 $this->textbox1
= $text;
852 // Check for length errors again now that the section is merged in
853 $this->kblength
= (int)(strlen( $text ) / 1024);
854 if ( $this->kblength
> $wgMaxArticleSize ) {
855 $this->tooBig
= true;
856 wfProfileOut( $fname );
860 # update the article here
861 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
862 $this->watchthis
, '', $sectionanchor ) ) {
863 wfProfileOut( $fname );
866 $this->isConflict
= true;
868 wfProfileOut( $fname );
873 * Initialise form fields in the object
874 * Called on the first invocation, e.g. when a user clicks an edit link
876 function initialiseForm() {
877 $this->edittime
= $this->mArticle
->getTimestamp();
879 $this->textbox1
= $this->getContent(false);
880 if ($this->textbox1
=== false) return false;
882 if ( !$this->mArticle
->exists() && $this->mArticle
->mTitle
->getNamespace() == NS_MEDIAWIKI
)
883 $this->textbox1
= wfMsgWeirdKey( $this->mArticle
->mTitle
->getText() );
889 * Send the edit form and related headers to $wgOut
890 * @param $formCallback Optional callable that takes an OutputPage
891 * parameter; will be called during form output
892 * near the top, for captchas and the like.
894 function showEditForm( $formCallback=null ) {
895 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
897 $fname = 'EditPage::showEditForm';
898 wfProfileIn( $fname );
900 $sk = $wgUser->getSkin();
902 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
904 $wgOut->setRobotpolicy( 'noindex,nofollow' );
906 # Enabled article-related sidebar, toplinks, etc.
907 $wgOut->setArticleRelated( true );
909 if ( $this->isConflict
) {
910 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
911 $wgOut->setPageTitle( $s );
912 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
914 $this->textbox2
= $this->textbox1
;
915 $this->textbox1
= $this->getContent();
916 $this->edittime
= $this->mArticle
->getTimestamp();
919 if( $this->section
!= '' ) {
920 if( $this->section
== 'new' ) {
921 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
923 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
925 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
926 preg_match( "/^(=+)(.+)\\1/mi",
929 if( !empty( $matches[2] ) ) {
930 $this->summary
= "/* ". trim($matches[2])." */ ";
935 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
937 $wgOut->setPageTitle( $s );
939 if ( $this->missingComment
) {
940 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
943 if( $this->missingSummary
&& $this->section
!= 'new' ) {
944 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
947 if( $this->missingSummary
&& $this->section
== 'new' ) {
948 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
951 if( !$this->hookError
== '' ) {
952 $wgOut->addWikiText( $this->hookError
);
955 if ( !$this->checkUnicodeCompliantBrowser() ) {
956 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
958 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
959 // Let sysop know that this will make private content public if saved
960 if( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
961 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
963 if( !$this->mArticle
->mRevision
->isCurrent() ) {
964 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
965 $wgOut->addWikiText( wfMsg( 'editingold' ) );
971 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
972 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
973 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
975 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
976 # Check the skin exists
977 if( $this->isValidCssJsSubpage
) {
978 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
980 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
985 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
986 # Show a warning if editing an interface message
987 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
988 } elseif( $this->mTitle
->isProtected( 'edit' ) ) {
989 # Is the title semi-protected?
990 if( $this->mTitle
->isSemiProtected() ) {
991 $notice = wfMsg( 'semiprotectedpagewarning' );
992 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' )
995 # It's either cascading protection or regular protection; work out which
996 list($cascadeSources, $restrictions) = $this->mTitle
->getCascadeProtectionSources();
997 if ( !$cascadeSources ||
count( $cascadeSources ) == 0 ) {
999 $notice = wfMsg( 'protectedpagewarning' );
1001 # Cascading protection; explain, and list the titles responsible
1002 $notice = wfMsg( 'cascadeprotectedwarning' ) . "\n";
1003 foreach( $cascadeSources as $source )
1004 $notice .= '* [[:' . $source->getPrefixedText() . "]]\n";
1007 $wgOut->addWikiText( $notice );
1010 if ( $this->kblength
=== false ) {
1011 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1013 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1014 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgMaxArticleSize ) );
1015 } elseif( $this->kblength
> 29 ) {
1016 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) ) );
1019 #need to parse the preview early so that we know which templates are used,
1020 #otherwise users with "show preview after edit box" will get a blank list
1021 if ( $this->formtype
== 'preview' ) {
1022 $previewOutput = $this->getPreviewText();
1025 $rows = $wgUser->getIntOption( 'rows' );
1026 $cols = $wgUser->getIntOption( 'cols' );
1028 $ew = $wgUser->getOption( 'editwidth' );
1029 if ( $ew ) $ew = " style=\"width:100%\"";
1032 $q = 'action=submit';
1033 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1034 $action = $this->mTitle
->escapeLocalURL( $q );
1036 $summary = wfMsg('summary');
1037 $subject = wfMsg('subject');
1039 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
1040 wfMsgExt('cancel', array('parseinline')) );
1041 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1042 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1043 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1044 htmlspecialchars( wfMsg( 'newwindow' ) );
1046 global $wgRightsText;
1047 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1048 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
1049 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1050 $wgRightsText ) . "\n</div>";
1052 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1053 # prepare toolbar for edit buttons
1054 $toolbar = $this->getEditToolbar();
1059 // activate checkboxes if user wants them to be always active
1060 if( !$this->preview
&& !$this->diff
) {
1061 # Sort out the "watch" checkbox
1062 if( $wgUser->getOption( 'watchdefault' ) ) {
1064 $this->watchthis
= true;
1065 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1067 $this->watchthis
= true;
1068 } elseif( $this->mTitle
->userIsWatching() ) {
1070 $this->watchthis
= true;
1073 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1076 $wgOut->addHTML( $this->editFormPageTop
);
1078 if ( $wgUser->getOption( 'previewontop' ) ) {
1080 if ( 'preview' == $this->formtype
) {
1081 $this->showPreview( $previewOutput );
1083 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1086 if ( 'diff' == $this->formtype
) {
1087 $wgOut->addHTML( $this->getDiff() );
1092 $wgOut->addHTML( $this->editFormTextTop
);
1094 # if this is a comment, show a subject line at the top, which is also the edit summary.
1095 # Otherwise, show a summary field at the bottom
1096 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1097 if( $this->section
== 'new' ) {
1098 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span>\n<div class='editOptions'>\n<input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
1100 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1101 $summarypreview = '';
1103 $commentsubject = '';
1104 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span>\n<div class='editOptions'>\n<input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
1105 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1106 $subjectpreview = '';
1109 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1110 if( !$this->preview
&& !$this->diff
) {
1111 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1113 $templates = ($this->preview ||
$this->section
) ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1114 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1116 global $wgUseMetadataEdit ;
1117 if ( $wgUseMetadataEdit ) {
1118 $metadata = $this->mMetaData
;
1119 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1120 $top = wfMsgWikiHtml( 'metadata_help' );
1121 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1123 else $metadata = "" ;
1127 if ($this->deletedSinceEdit
) {
1128 if ( 'save' != $this->formtype
) {
1129 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1131 // Hide the toolbar and edit area, use can click preview to get it back
1132 // Add an confirmation checkbox and explanation.
1134 $hidden = 'type="hidden" style="display:none;"';
1135 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1137 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1138 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1144 $checkboxes = self
::getCheckboxes( $tabindex, $sk,
1145 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1147 $checkboxhtml = implode( $checkboxes, "\n" );
1149 $buttons = $this->getEditButtons( $tabindex );
1150 $buttonshtml = implode( $buttons, "\n" );
1152 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1153 ?
'' : Xml
::hidden( 'safemode', '1' );
1155 $wgOut->addHTML( <<<END
1157 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1161 if( is_callable( $formCallback ) ) {
1162 call_user_func_array( $formCallback, array( &$wgOut ) );
1165 // Put these up at the top to ensure they aren't lost on early form submission
1167 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1168 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1169 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1170 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1172 $wgOut->addHTML( <<<END
1176 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1177 cols='{$cols}'{$ew} $hidden>
1179 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
1184 $wgOut->addWikiText( $copywarn );
1185 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1195 "<div class='editButtons'>
1197 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1198 </div><!-- editButtons -->
1199 </div><!-- editOptions -->");
1201 $wgOut->addHtml( '<div class="mw-editTools">' );
1202 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1203 $wgOut->addHtml( '</div>' );
1205 $wgOut->addHTML( $this->editFormTextAfterTools
);
1208 <div class='templatesUsed'>
1209 {$formattedtemplates}
1214 * To make it harder for someone to slip a user a page
1215 * which submits an edit form to the wiki without their
1216 * knowledge, a random token is associated with the login
1217 * session. If it's not passed back with the submission,
1218 * we won't save the page, or render user JavaScript and
1221 * For anon editors, who may not have a session, we just
1222 * include the constant suffix to prevent editing from
1223 * broken text-mangling proxies.
1225 if ( $wgUser->isLoggedIn() )
1226 $token = htmlspecialchars( $wgUser->editToken() );
1228 $token = EDIT_TOKEN_SUFFIX
;
1229 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1232 # If a blank edit summary was previously provided, and the appropriate
1233 # user preference is active, pass a hidden tag here. This will stop the
1234 # user being bounced back more than once in the event that a summary
1236 if( $this->missingSummary
) {
1237 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1240 # For a bit more sophisticated detection of blank summaries, hash the
1241 # automatic one and pass that in a hidden field.
1242 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1243 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1245 if ( $this->isConflict
) {
1246 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1248 $de = new DifferenceEngine( $this->mTitle
);
1249 $de->setText( $this->textbox2
, $this->textbox1
);
1250 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1252 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1253 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1254 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1256 $wgOut->addHTML( $this->editFormTextBottom
);
1257 $wgOut->addHTML( "</form>\n" );
1258 if ( !$wgUser->getOption( 'previewontop' ) ) {
1260 if ( $this->formtype
== 'preview') {
1261 $this->showPreview( $previewOutput );
1263 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1266 if ( $this->formtype
== 'diff') {
1267 $wgOut->addHTML( $this->getDiff() );
1272 wfProfileOut( $fname );
1276 * Append preview output to $wgOut.
1277 * Includes category rendering if this is a category page.
1279 * @param string $text The HTML to be output for the preview.
1281 private function showPreview( $text ) {
1284 $wgOut->addHTML( '<div id="wikiPreview">' );
1285 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1286 $this->mArticle
->openShowCategory();
1288 $wgOut->addHTML( $text );
1289 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1290 $this->mArticle
->closeShowCategory();
1292 $wgOut->addHTML( '</div>' );
1296 * Live Preview lets us fetch rendered preview page content and
1297 * add it to the page without refreshing the whole page.
1298 * If not supported by the browser it will fall through to the normal form
1299 * submission method.
1301 * This function outputs a script tag to support live preview, and
1302 * returns an onclick handler which should be added to the attributes
1303 * of the preview button
1305 function doLivePreviewScript() {
1306 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1307 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1308 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1309 '"></script>' . "\n" );
1310 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1311 return "return !livePreview(" .
1312 "getElementById('wikiPreview')," .
1313 "editform.wpTextbox1.value," .
1314 '"' . $liveAction . '"' . ")";
1317 function getLastDelete() {
1318 $dbr = wfGetDB( DB_SLAVE
);
1319 $fname = 'EditPage::getLastDelete';
1320 $res = $dbr->select(
1321 array( 'logging', 'user' ),
1331 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1332 'log_title' => $this->mTitle
->getDBkey(),
1333 'log_type' => 'delete',
1334 'log_action' => 'delete',
1335 'user_id=log_user' ),
1337 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1339 if($dbr->numRows($res) == 1) {
1340 while ( $x = $dbr->fetchObject ( $res ) )
1342 $dbr->freeResult ( $res ) ;
1352 function getPreviewText() {
1353 global $wgOut, $wgUser, $wgTitle, $wgParser;
1355 $fname = 'EditPage::getPreviewText';
1356 wfProfileIn( $fname );
1358 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1359 $msg = 'session_fail_preview';
1361 $msg = 'previewnote';
1363 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1364 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1365 if ( $this->isConflict
) {
1366 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1369 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1370 $parserOptions->setEditSection( false );
1373 if( $wgRawHtml && !$this->mTokenOk
) {
1374 // Could be an offsite preview attempt. This is very unsafe if
1375 // HTML is enabled, as it could be an attack.
1376 return $wgOut->parse( "<div class='previewnote'>" .
1377 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1380 # don't parse user css/js, show message about preview
1381 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1383 if ( $this->isCssJsSubpage
) {
1384 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1385 $previewtext = wfMsg('usercsspreview');
1386 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1387 $previewtext = wfMsg('userjspreview');
1389 $parserOptions->setTidy(true);
1390 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1391 $wgOut->addHTML( $parserOutput->mText
);
1392 wfProfileOut( $fname );
1393 return $previewhead;
1395 $toparse = $this->textbox1
;
1397 # If we're adding a comment, we need to show the
1398 # summary as the headline
1399 if($this->section
=="new" && $this->summary
!="") {
1400 $toparse="== {$this->summary} ==\n\n".$toparse;
1403 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1404 $parserOptions->setTidy(true);
1405 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1406 $wgTitle, $parserOptions );
1408 $previewHTML = $parserOutput->getText();
1409 $wgOut->addParserOutputNoText( $parserOutput );
1411 foreach ( $parserOutput->getTemplates() as $ns => $template)
1412 foreach ( array_keys( $template ) as $dbk)
1413 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1415 wfProfileOut( $fname );
1416 return $previewhead . $previewHTML;
1421 * Call the stock "user is blocked" page
1423 function blockedPage() {
1424 global $wgOut, $wgUser;
1425 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1427 # If the user made changes, preserve them when showing the markup
1428 # (This happens when a user is blocked during edit, for instance)
1429 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1431 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1433 $source = $this->textbox1
;
1436 # Spit out the source or the user's modified version
1437 if( $source !== false ) {
1438 $rows = $wgUser->getOption( 'rows' );
1439 $cols = $wgUser->getOption( 'cols' );
1440 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1441 $wgOut->addHtml( '<hr />' );
1442 $wgOut->addWikiText( wfMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() ) );
1443 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1448 * Produce the stock "please login to edit pages" page
1450 function userNotLoggedInPage() {
1451 global $wgUser, $wgOut;
1452 $skin = $wgUser->getSkin();
1454 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1455 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle
->getPrefixedUrl() );
1457 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1458 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1459 $wgOut->setArticleRelated( false );
1461 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1462 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1466 * Creates a basic error page which informs the user that
1467 * they have to validate their email address before being
1470 function userNotConfirmedPage() {
1473 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1474 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1475 $wgOut->setArticleRelated( false );
1477 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1478 $wgOut->returnToMain( false );
1482 * Creates a basic error page which informs the user that
1483 * they have attempted to edit a nonexistant section.
1485 function noSuchSectionPage() {
1488 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1489 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1490 $wgOut->setArticleRelated( false );
1492 $wgOut->addWikiText( wfMsg( 'nosuchsectiontext', $this->section
) );
1493 $wgOut->returnToMain( false );
1497 * Produce the stock "your edit contains spam" page
1499 * @param $match Text which triggered one or more filters
1501 function spamPage( $match = false ) {
1504 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1505 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1506 $wgOut->setArticleRelated( false );
1508 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1510 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1512 $wgOut->returnToMain( false );
1519 function mergeChangesInto( &$editText ){
1520 $fname = 'EditPage::mergeChangesInto';
1521 wfProfileIn( $fname );
1523 $db = wfGetDB( DB_MASTER
);
1525 // This is the revision the editor started from
1526 $baseRevision = Revision
::loadFromTimestamp(
1527 $db, $this->mArticle
->mTitle
, $this->edittime
);
1528 if( is_null( $baseRevision ) ) {
1529 wfProfileOut( $fname );
1532 $baseText = $baseRevision->getText();
1534 // The current state, we want to merge updates into it
1535 $currentRevision = Revision
::loadFromTitle(
1536 $db, $this->mArticle
->mTitle
);
1537 if( is_null( $currentRevision ) ) {
1538 wfProfileOut( $fname );
1541 $currentText = $currentRevision->getText();
1544 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1545 $editText = $result;
1546 wfProfileOut( $fname );
1549 wfProfileOut( $fname );
1555 * Check if the browser is on a blacklist of user-agents known to
1556 * mangle UTF-8 data on form submission. Returns true if Unicode
1557 * should make it through, false if it's known to be a problem.
1561 function checkUnicodeCompliantBrowser() {
1562 global $wgBrowserBlackList;
1563 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1564 // No User-Agent header sent? Trust it by default...
1567 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1568 foreach ( $wgBrowserBlackList as $browser ) {
1569 if ( preg_match($browser, $currentbrowser) ) {
1577 * Format an anchor fragment as it would appear for a given section name
1578 * @param string $text
1582 function sectionAnchor( $text ) {
1583 $headline = Sanitizer
::decodeCharReferences( $text );
1585 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1586 $headline = trim( $headline );
1587 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1588 $replacearray = array(
1593 array_keys( $replacearray ),
1594 array_values( $replacearray ),
1599 * Shows a bulletin board style toolbar for common editing functions.
1600 * It can be disabled in the user preferences.
1601 * The necessary JavaScript code can be found in style/wikibits.js.
1603 function getEditToolbar() {
1604 global $wgStylePath, $wgContLang, $wgJsMimeType;
1607 * toolarray an array of arrays which each include the filename of
1608 * the button image (without path), the opening tag, the closing tag,
1609 * and optionally a sample text that is inserted between the two when no
1610 * selection is highlighted.
1611 * The tip text is shown when the user moves the mouse over the button.
1613 * Already here are accesskeys (key), which are not used yet until someone
1614 * can figure out a way to make them work in IE. However, we should make
1615 * sure these keys are not defined on the edit page.
1618 array( 'image' => 'button_bold.png',
1619 'id' => 'mw-editbutton-bold',
1620 'open' => '\\\'\\\'\\\'',
1621 'close' => '\\\'\\\'\\\'',
1622 'sample'=> wfMsg('bold_sample'),
1623 'tip' => wfMsg('bold_tip'),
1626 array( 'image' => 'button_italic.png',
1627 'id' => 'mw-editbutton-italic',
1628 'open' => '\\\'\\\'',
1629 'close' => '\\\'\\\'',
1630 'sample'=> wfMsg('italic_sample'),
1631 'tip' => wfMsg('italic_tip'),
1634 array( 'image' => 'button_link.png',
1635 'id' => 'mw-editbutton-link',
1638 'sample'=> wfMsg('link_sample'),
1639 'tip' => wfMsg('link_tip'),
1642 array( 'image' => 'button_extlink.png',
1643 'id' => 'mw-editbutton-extlink',
1646 'sample'=> wfMsg('extlink_sample'),
1647 'tip' => wfMsg('extlink_tip'),
1650 array( 'image' => 'button_headline.png',
1651 'id' => 'mw-editbutton-headline',
1653 'close' => " ==\\n",
1654 'sample'=> wfMsg('headline_sample'),
1655 'tip' => wfMsg('headline_tip'),
1658 array( 'image' => 'button_image.png',
1659 'id' => 'mw-editbutton-image',
1660 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1662 'sample'=> wfMsg('image_sample'),
1663 'tip' => wfMsg('image_tip'),
1666 array( 'image' => 'button_media.png',
1667 'id' => 'mw-editbutton-media',
1668 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1670 'sample'=> wfMsg('media_sample'),
1671 'tip' => wfMsg('media_tip'),
1674 array( 'image' => 'button_math.png',
1675 'id' => 'mw-editbutton-math',
1677 'close' => "<\\/math>",
1678 'sample'=> wfMsg('math_sample'),
1679 'tip' => wfMsg('math_tip'),
1682 array( 'image' => 'button_nowiki.png',
1683 'id' => 'mw-editbutton-nowiki',
1684 'open' => "<nowiki>",
1685 'close' => "<\\/nowiki>",
1686 'sample'=> wfMsg('nowiki_sample'),
1687 'tip' => wfMsg('nowiki_tip'),
1690 array( 'image' => 'button_sig.png',
1691 'id' => 'mw-editbutton-signature',
1695 'tip' => wfMsg('sig_tip'),
1698 array( 'image' => 'button_hr.png',
1699 'id' => 'mw-editbutton-hr',
1700 'open' => "\\n----\\n",
1703 'tip' => wfMsg('hr_tip'),
1707 $toolbar = "<div id='toolbar'>\n";
1708 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1710 foreach($toolarray as $tool) {
1712 $cssId = $tool['id'];
1713 $image=$wgStylePath.'/common/images/'.$tool['image'];
1714 $open=$tool['open'];
1715 $close=$tool['close'];
1716 $sample = wfEscapeJsString( $tool['sample'] );
1718 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1719 // Older browsers show a "speedtip" type message only for ALT.
1720 // Ideally these should be different, realistically they
1721 // probably don't need to be.
1722 $tip = wfEscapeJsString( $tool['tip'] );
1724 #$key = $tool["key"];
1726 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1729 $toolbar.="/*]]>*/\n</script>";
1730 $toolbar.="\n</div>";
1735 * Returns an array of html code of the following checkboxes:
1738 * @param $tabindex Current tabindex
1739 * @param $skin Skin object
1740 * @param $checked Array of checkbox => bool, where bool indicates the checked
1741 * status of the checkbox
1745 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1748 $checkboxes = array();
1750 $checkboxes['minor'] = '';
1751 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1752 if ( $wgUser->isAllowed('minoredit') ) {
1754 'tabindex' => ++
$tabindex,
1755 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1756 'id' => 'wpMinoredit',
1758 $checkboxes['minor'] =
1759 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1760 " <label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1763 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1764 $checkboxes['watch'] = '';
1765 if ( $wgUser->isLoggedIn() ) {
1767 'tabindex' => ++
$tabindex,
1768 'accesskey' => wfMsg( 'accesskey-watch' ),
1769 'id' => 'wpWatchthis',
1771 $checkboxes['watch'] =
1772 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1773 " <label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1779 * Returns an array of html code of the following buttons:
1780 * save, diff, preview and live
1782 * @param $tabindex Current tabindex
1786 public function getEditButtons(&$tabindex) {
1787 global $wgLivePreview, $wgUser;
1795 'tabindex' => ++
$tabindex,
1796 'value' => wfMsg('savearticle'),
1797 'accesskey' => wfMsg('accesskey-save'),
1798 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1800 $buttons['save'] = wfElement('input', $temp, '');
1802 ++
$tabindex; // use the same for preview and live preview
1803 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1805 'id' => 'wpPreview',
1806 'name' => 'wpPreview',
1808 'tabindex' => $tabindex,
1809 'value' => wfMsg('showpreview'),
1811 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1812 'style' => 'display: none;',
1814 $buttons['preview'] = wfElement('input', $temp, '');
1817 'id' => 'wpLivePreview',
1818 'name' => 'wpLivePreview',
1820 'tabindex' => $tabindex,
1821 'value' => wfMsg('showlivepreview'),
1822 'accesskey' => wfMsg('accesskey-preview'),
1824 'onclick' => $this->doLivePreviewScript(),
1826 $buttons['live'] = wfElement('input', $temp, '');
1829 'id' => 'wpPreview',
1830 'name' => 'wpPreview',
1832 'tabindex' => $tabindex,
1833 'value' => wfMsg('showpreview'),
1834 'accesskey' => wfMsg('accesskey-preview'),
1835 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1837 $buttons['preview'] = wfElement('input', $temp, '');
1838 $buttons['live'] = '';
1845 'tabindex' => ++
$tabindex,
1846 'value' => wfMsg('showdiff'),
1847 'accesskey' => wfMsg('accesskey-diff'),
1848 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1850 $buttons['diff'] = wfElement('input', $temp, '');
1856 * Output preview text only. This can be sucked into the edit page
1857 * via JavaScript, and saves the server time rendering the skin as
1858 * well as theoretically being more robust on the client (doesn't
1859 * disturb the edit box's undo history, won't eat your text on
1862 * @todo This doesn't include category or interlanguage links.
1863 * Would need to enhance it a bit, <s>maybe wrap them in XML
1864 * or something...</s> that might also require more skin
1865 * initialization, so check whether that's a problem.
1867 function livePreview() {
1870 header( 'Content-type: text/xml; charset=utf-8' );
1871 header( 'Cache-control: no-cache' );
1874 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1875 Xml
::openElement( 'livepreview' ) .
1876 Xml
::element( 'preview', null, $this->getPreviewText() ) .
1877 Xml
::element( 'br', array( 'style' => 'clear: both;' ) ) .
1878 Xml
::closeElement( 'livepreview' );
1884 * Get a diff between the current contents of the edit box and the
1885 * version of the page we're editing from.
1887 * If this is a section edit, we'll replace the section as for final
1888 * save and then make a comparison.
1890 * @return string HTML
1892 function getDiff() {
1893 $oldtext = $this->mArticle
->fetchContent();
1894 $newtext = $this->mArticle
->replaceSection(
1895 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1896 $newtext = $this->mArticle
->preSaveTransform( $newtext );
1897 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1898 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1899 if ( $oldtext !== false ||
$newtext != '' ) {
1900 $de = new DifferenceEngine( $this->mTitle
);
1901 $de->setText( $oldtext, $newtext );
1902 $difftext = $de->getDiff( $oldtitle, $newtitle );
1907 return '<div id="wikiDiff">' . $difftext . '</div>';
1911 * Filter an input field through a Unicode de-armoring process if it
1912 * came from an old browser with known broken Unicode editing issues.
1914 * @param WebRequest $request
1915 * @param string $field
1919 function safeUnicodeInput( $request, $field ) {
1920 $text = rtrim( $request->getText( $field ) );
1921 return $request->getBool( 'safemode' )
1922 ?
$this->unmakesafe( $text )
1927 * Filter an output field through a Unicode armoring process if it is
1928 * going to an old browser with known broken Unicode editing issues.
1930 * @param string $text
1934 function safeUnicodeOutput( $text ) {
1936 $codedText = $wgContLang->recodeForEdit( $text );
1937 return $this->checkUnicodeCompliantBrowser()
1939 : $this->makesafe( $codedText );
1943 * A number of web browsers are known to corrupt non-ASCII characters
1944 * in a UTF-8 text editing environment. To protect against this,
1945 * detected browsers will be served an armored version of the text,
1946 * with non-ASCII chars converted to numeric HTML character references.
1948 * Preexisting such character references will have a 0 added to them
1949 * to ensure that round-trips do not alter the original data.
1951 * @param string $invalue
1955 function makesafe( $invalue ) {
1956 // Armor existing references for reversability.
1957 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1962 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1963 $bytevalue = ord( $invalue{$i} );
1964 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1965 $result .= chr( $bytevalue );
1967 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1968 $working = $working << 6;
1969 $working +
= ($bytevalue & 0x3F);
1971 if( $bytesleft <= 0 ) {
1972 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1974 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1975 $working = $bytevalue & 0x1F;
1977 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1978 $working = $bytevalue & 0x0F;
1980 } else { //1111 0xxx
1981 $working = $bytevalue & 0x07;
1989 * Reverse the previously applied transliteration of non-ASCII characters
1990 * back to UTF-8. Used to protect data from corruption by broken web browsers
1991 * as listed in $wgBrowserBlackList.
1993 * @param string $invalue
1997 function unmakesafe( $invalue ) {
1999 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2000 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2004 $hexstring .= $invalue{$i};
2006 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2008 // Do some sanity checks. These aren't needed for reversability,
2009 // but should help keep the breakage down if the editor
2010 // breaks one of the entities whilst editing.
2011 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2012 $codepoint = hexdec($hexstring);
2013 $result .= codepointToUtf8( $codepoint );
2015 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2018 $result .= substr( $invalue, $i, 1 );
2021 // reverse the transform that we made for reversability reasons.
2022 return strtr( $result, array( "�" => "&#x" ) );
2025 function noCreatePermission() {
2027 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2028 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );