3 * Contain the EditPage class
8 * Splitting edit page/HTML interface from Article...
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
20 var $isConflict = false;
21 var $isCssJsSubpage = false;
22 var $deletedSinceEdit = false;
26 var $mTokenOk = false;
27 var $mTriedSave = false;
29 var $kblength = false;
30 var $missingComment = false;
31 var $missingSummary = false;
32 var $allowBlankSummary = false;
35 var $mPreviewTemplates;
38 var $save = false, $preview = false, $diff = false;
39 var $minoredit = false, $watchthis = false, $recreate = false;
40 var $textbox1 = '', $textbox2 = '', $summary = '';
41 var $edittime = '', $section = '', $starttime = '';
42 var $oldid = 0, $editintro = '', $scrolltop = null;
44 # Placeholders for text injection by hooks (must be HTML)
45 # extensions should take care to _append_ to the present value
46 public $editFormPageTop; // Before even the preview
47 public $editFormTextTop;
48 public $editFormTextAfterWarn;
49 public $editFormTextAfterTools;
50 public $editFormTextBottom;
56 function EditPage( $article ) {
57 $this->mArticle
=& $article;
59 $this->mTitle
=& $wgTitle;
61 # Placeholders for text injection by hooks (empty per default)
62 $this->editFormPageTop
=
63 $this->editFormTextTop
=
64 $this->editFormTextAfterWarn
=
65 $this->editFormTextAfterTools
=
66 $this->editFormTextBottom
= "";
70 * Fetch initial editing page content.
72 private function getContent() {
73 global $wgOut, $wgRequest, $wgParser;
75 # Get variables from query string :P
76 $section = $wgRequest->getVal( 'section' );
77 $preload = $wgRequest->getVal( 'preload' );
78 $undo = $wgRequest->getVal( 'undo' );
80 wfProfileIn( __METHOD__
);
83 if( !$this->mTitle
->exists() ) {
84 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
85 # If this is a system message, get the default text.
86 $text = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
88 # If requested, preload some text.
89 $text = $this->getPreloadedText( $preload );
91 # We used to put MediaWiki:Newarticletext here if
92 # $text was empty at this point.
93 # This is now shown above the edit box instead.
95 // FIXME: may be better to use Revision class directly
96 // But don't mess with it just yet. Article knows how to
97 // fetch the page record from the high-priority server,
98 // which is needed to guarantee we don't pick up lagged
101 $text = $this->mArticle
->getContent();
104 #Undoing a specific edit overrides section editing; section-editing
105 # doesn't work with undoing.
106 $undorev = Revision
::newFromId($undo);
108 #Sanity check, make sure it's the right page.
109 # Otherwise, $text will be left as-is.
110 if (!is_null($undorev) && $undorev->getPage() == $this->mArticle
->getID()) {
111 $oldrev = $undorev->getPrevious();
112 $undorev_text = $undorev->getText();
113 $oldrev_text = $oldrev->getText();
114 $currev_text = $text;
116 #No use doing a merge if it's just a straight revert.
117 if ($currev_text != $undorev_text) {
118 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
120 $text = $oldrev_text;
125 # Inform the user of our success and set an automatic edit summary
126 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
127 $this->summary
= wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
128 $this->formtype
= 'diff';
130 # Warn the user that something went wrong
131 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
136 else if( $section != '' ) {
137 if( $section == 'new' ) {
138 $text = $this->getPreloadedText( $preload );
140 $text = $wgParser->getSection( $text, $section );
145 wfProfileOut( __METHOD__
);
150 * Get the contents of a page from its title and remove includeonly tags
152 * @param $preload String: the title of the page.
153 * @return string The contents of the page.
155 private function getPreloadedText($preload) {
156 if ( $preload === '' )
159 $preloadTitle = Title
::newFromText( $preload );
160 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
161 $rev=Revision
::newFromTitle($preloadTitle);
162 if ( is_object( $rev ) ) {
163 $text = $rev->getText();
164 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
165 // its own mini-parser! -ævar
166 $text = preg_replace( '~</?includeonly>~', '', $text );
175 * This is the function that extracts metadata from the article body on the first view.
176 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
177 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
179 function extractMetaDataFromArticle () {
180 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
181 $this->mMetaData
= '' ;
182 if ( !$wgUseMetadataEdit ) return ;
183 if ( $wgMetadataWhitelist == '' ) return ;
185 $t = $this->getContent();
187 # MISSING : <nowiki> filtering
189 # Categories and language links
190 $t = explode ( "\n" , $t ) ;
191 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
192 $cat = $ll = array() ;
193 foreach ( $t AS $key => $x )
195 $y = trim ( strtolower ( $x ) ) ;
196 while ( substr ( $y , 0 , 2 ) == '[[' )
198 $y = explode ( ']]' , trim ( $x ) ) ;
199 $first = array_shift ( $y ) ;
200 $first = explode ( ':' , $first ) ;
201 $ns = array_shift ( $first ) ;
202 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
203 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
205 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
206 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
208 $x = implode ( ']]' , $y ) ;
210 $y = trim ( strtolower ( $x ) ) ;
214 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
215 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
216 $t = implode ( "\n" , $t ) ;
219 $sat = array () ; # stand-alone-templates; must be lowercase
220 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
221 $wl_article = new Article ( $wl_title ) ;
222 $wl = explode ( "\n" , $wl_article->getContent() ) ;
223 foreach ( $wl AS $x )
227 while ( substr ( $x , 0 , 1 ) == '*' )
230 $x = trim ( substr ( $x , 1 ) ) ;
234 $sat[] = strtolower ( $x ) ;
239 # Templates, but only some
240 $t = explode ( '{{' , $t ) ;
242 foreach ( $t AS $key => $x )
244 $y = explode ( '}}' , $x , 2 ) ;
245 if ( count ( $y ) == 2 )
248 $z = explode ( '|' , $z ) ;
249 $tn = array_shift ( $z ) ;
250 if ( in_array ( strtolower ( $tn ) , $sat ) )
252 $tl[] = '{{' . $y[0] . '}}' ;
254 $y = explode ( '}}' , $y[1] , 2 ) ;
256 else $t[$key] = '{{' . $x ;
258 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
261 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
262 $t = implode ( '' , $t ) ;
264 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
265 $this->mArticle
->mContent
= $t ;
266 $this->mMetaData
= $s ;
274 * This is the function that gets called for "action=edit". It
275 * sets up various member variables, then passes execution to
276 * another function, usually showEditForm()
278 * The edit form is self-submitting, so that when things like
279 * preview and edit conflicts occur, we get the same form back
280 * with the extra stuff added. Only when the final submission
281 * is made and all is well do we actually save and redirect to
282 * the newly-edited page.
285 global $wgOut, $wgUser, $wgRequest, $wgTitle;
286 global $wgEmailConfirmToEdit;
288 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
291 $fname = 'EditPage::edit';
292 wfProfileIn( $fname );
293 wfDebug( "$fname: enter\n" );
295 // this is not an article
296 $wgOut->setArticleFlag(false);
298 $this->importFormData( $wgRequest );
299 $this->firsttime
= false;
302 $this->livePreview();
303 wfProfileOut( $fname );
307 if ( ! $this->mTitle
->userCanEdit() ) {
308 wfDebug( "$fname: user can't edit\n" );
309 $wgOut->readOnlyPage( $this->getContent(), true );
310 wfProfileOut( $fname );
313 wfDebug( "$fname: Checking blocks\n" );
314 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
315 # When previewing, don't check blocked state - will get caught at save time.
316 # Also, check when starting edition is done against slave to improve performance.
317 wfDebug( "$fname: user is blocked\n" );
318 $this->blockedPage();
319 wfProfileOut( $fname );
322 if ( !$wgUser->isAllowed('edit') ) {
323 if ( $wgUser->isAnon() ) {
324 wfDebug( "$fname: user must log in\n" );
325 $this->userNotLoggedInPage();
326 wfProfileOut( $fname );
329 wfDebug( "$fname: read-only page\n" );
330 $wgOut->readOnlyPage( $this->getContent(), true );
331 wfProfileOut( $fname );
335 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
336 wfDebug("$fname: user must confirm e-mail address\n");
337 $this->userNotConfirmedPage();
338 wfProfileOut($fname);
341 if ( !$this->mTitle
->userCanCreate() && !$this->mTitle
->exists() ) {
342 wfDebug( "$fname: no create permission\n" );
343 $this->noCreatePermission();
344 wfProfileOut( $fname );
347 if ( wfReadOnly() ) {
348 wfDebug( "$fname: read-only mode is engaged\n" );
349 if( $this->save ||
$this->preview
) {
350 $this->formtype
= 'preview';
351 } else if ( $this->diff
) {
352 $this->formtype
= 'diff';
354 $wgOut->readOnlyPage( $this->getContent() );
355 wfProfileOut( $fname );
360 $this->formtype
= 'save';
361 } else if ( $this->preview
) {
362 $this->formtype
= 'preview';
363 } else if ( $this->diff
) {
364 $this->formtype
= 'diff';
365 } else { # First time through
366 $this->firsttime
= true;
367 if( $this->previewOnOpen() ) {
368 $this->formtype
= 'preview';
370 $this->extractMetaDataFromArticle () ;
371 $this->formtype
= 'initial';
376 wfProfileIn( "$fname-business-end" );
378 $this->isConflict
= false;
379 // css / js subpages of user pages get a special treatment
380 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
381 $this->isValidCssJsSubpage
= $wgTitle->isValidCssJsSubpage();
383 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
384 * no matter it's current state
386 $this->deletedSinceEdit
= false;
387 if ( $this->edittime
!= '' ) {
388 /* Note that we rely on logging table, which hasn't been always there,
389 * but that doesn't matter, because this only applies to brand new
390 * deletes. This is done on every preview and save request. Move it further down
391 * to only perform it on saves
393 if ( $this->mTitle
->isDeleted() ) {
394 $this->lastDelete
= $this->getLastDelete();
395 if ( !is_null($this->lastDelete
) ) {
396 $deletetime = $this->lastDelete
->log_timestamp
;
397 if ( ($deletetime - $this->starttime
) > 0 ) {
398 $this->deletedSinceEdit
= true;
404 if(!$this->mTitle
->getArticleID() && ('initial' == $this->formtype ||
$this->firsttime
)) { # new article
407 if( $this->mTitle
->isTalkPage() ) {
408 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
411 # Attempt submission here. This will check for edit conflicts,
412 # and redundantly check for locked database, blocked IPs, etc.
413 # that edit() already checked just in case someone tries to sneak
414 # in the back door with a hand-edited submission URL.
416 if ( 'save' == $this->formtype
) {
417 if ( !$this->attemptSave() ) {
418 wfProfileOut( "$fname-business-end" );
419 wfProfileOut( $fname );
424 # First time through: get contents, set time for conflict
426 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
427 $this->initialiseForm();
428 if( !$this->mTitle
->getArticleId() )
429 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
432 $this->showEditForm();
433 wfProfileOut( "$fname-business-end" );
434 wfProfileOut( $fname );
438 * Return true if this page should be previewed when the edit form
439 * is initially opened.
443 function previewOnOpen() {
445 return $this->section
!= 'new' &&
446 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle
->exists() ) ||
447 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
448 !$this->mTitle
->exists() ) );
455 function importFormData( &$request ) {
456 global $wgLang, $wgUser;
457 $fname = 'EditPage::importFormData';
458 wfProfileIn( $fname );
460 if( $request->wasPosted() ) {
461 # These fields need to be checked for encoding.
462 # Also remove trailing whitespace, but don't remove _initial_
463 # whitespace from the text boxes. This may be significant formatting.
464 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
465 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
466 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
467 # Truncate for whole multibyte characters. +5 bytes for ellipsis
468 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
470 $this->edittime
= $request->getVal( 'wpEdittime' );
471 $this->starttime
= $request->getVal( 'wpStarttime' );
473 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
475 if( is_null( $this->edittime
) ) {
476 # If the form is incomplete, force to preview.
477 wfDebug( "$fname: Form data appears to be incomplete\n" );
478 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
479 $this->preview
= true;
481 /* Fallback for live preview */
482 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
483 $this->diff
= $request->getCheck( 'wpDiff' );
485 // Remember whether a save was requested, so we can indicate
486 // if we forced preview due to session failure.
487 $this->mTriedSave
= !$this->preview
;
489 if ( $this->tokenOk( $request ) ) {
490 # Some browsers will not report any submit button
491 # if the user hits enter in the comment box.
492 # The unmarked state will be assumed to be a save,
493 # if the form seems otherwise complete.
494 wfDebug( "$fname: Passed token check.\n" );
495 } else if ( $this->diff
) {
496 # Failed token check, but only requested "Show Changes".
497 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
499 # Page might be a hack attempt posted from
500 # an external site. Preview instead of saving.
501 wfDebug( "$fname: Failed token check; forcing preview\n" );
502 $this->preview
= true;
505 $this->save
= ! ( $this->preview
OR $this->diff
);
506 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
507 $this->edittime
= null;
510 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
511 $this->starttime
= null;
514 $this->recreate
= $request->getCheck( 'wpRecreate' );
516 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
517 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
519 # Don't force edit summaries when a user is editing their own user or talk page
520 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
521 $this->allowBlankSummary
= true;
523 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
526 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
528 # Not a posted form? Start with nothing.
529 wfDebug( "$fname: Not a posted form.\n" );
530 $this->textbox1
= '';
531 $this->textbox2
= '';
532 $this->mMetaData
= '';
534 $this->edittime
= '';
535 $this->starttime
= wfTimestampNow();
536 $this->preview
= false;
539 $this->minoredit
= false;
540 $this->watchthis
= false;
541 $this->recreate
= false;
544 $this->oldid
= $request->getInt( 'oldid' );
546 # Section edit can come from either the form or a link
547 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
549 $this->live
= $request->getCheck( 'live' );
550 $this->editintro
= $request->getText( 'editintro' );
552 wfProfileOut( $fname );
556 * Make sure the form isn't faking a user's credentials.
558 * @param $request WebRequest
562 function tokenOk( &$request ) {
564 if( $wgUser->isAnon() ) {
565 # Anonymous users may not have a session
566 # open. Check for suffix anyway.
567 $this->mTokenOk
= ( EDIT_TOKEN_SUFFIX
== $request->getVal( 'wpEditToken' ) );
569 $this->mTokenOk
= $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
571 return $this->mTokenOk
;
575 function showIntro() {
576 global $wgOut, $wgUser;
577 $addstandardintro=true;
578 if($this->editintro
) {
579 $introtitle=Title
::newFromText($this->editintro
);
580 if(isset($introtitle) && $introtitle->userCanRead()) {
581 $rev=Revision
::newFromTitle($introtitle);
583 $wgOut->addSecondaryWikiText($rev->getText());
584 $addstandardintro=false;
588 if($addstandardintro) {
589 if ( $wgUser->isLoggedIn() )
590 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
592 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
598 * @return bool false if output is done, true if the rest of the form should be displayed
600 function attemptSave() {
601 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
602 global $wgMaxArticleSize;
604 $fname = 'EditPage::attemptSave';
605 wfProfileIn( $fname );
606 wfProfileIn( "$fname-checks" );
608 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
610 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
614 # Reintegrate metadata
615 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
616 $this->mMetaData
= '' ;
620 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
621 $this->spamPage ( $matches[0] );
622 wfProfileOut( "$fname-checks" );
623 wfProfileOut( $fname );
626 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
627 # Error messages or other handling should be performed by the filter function
628 wfProfileOut( $fname );
629 wfProfileOut( "$fname-checks" );
632 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
) ) ) {
633 # Error messages etc. could be handled within the hook...
634 wfProfileOut( $fname );
635 wfProfileOut( "$fname-checks" );
637 } elseif( $this->hookError
!= '' ) {
638 # ...or the hook could be expecting us to produce an error
639 wfProfileOut( "$fname-checks " );
640 wfProfileOut( $fname );
643 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
644 # Check block state against master, thus 'false'.
645 $this->blockedPage();
646 wfProfileOut( "$fname-checks" );
647 wfProfileOut( $fname );
650 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
651 if ( $this->kblength
> $wgMaxArticleSize ) {
652 // Error will be displayed by showEditForm()
653 $this->tooBig
= true;
654 wfProfileOut( "$fname-checks" );
655 wfProfileOut( $fname );
659 if ( !$wgUser->isAllowed('edit') ) {
660 if ( $wgUser->isAnon() ) {
661 $this->userNotLoggedInPage();
662 wfProfileOut( "$fname-checks" );
663 wfProfileOut( $fname );
667 $wgOut->readOnlyPage();
668 wfProfileOut( "$fname-checks" );
669 wfProfileOut( $fname );
674 if ( wfReadOnly() ) {
675 $wgOut->readOnlyPage();
676 wfProfileOut( "$fname-checks" );
677 wfProfileOut( $fname );
680 if ( $wgUser->pingLimiter() ) {
681 $wgOut->rateLimited();
682 wfProfileOut( "$fname-checks" );
683 wfProfileOut( $fname );
687 # If the article has been deleted while editing, don't save it without
689 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
690 wfProfileOut( "$fname-checks" );
691 wfProfileOut( $fname );
695 wfProfileOut( "$fname-checks" );
697 # If article is new, insert it.
698 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
701 // Late check for create permission, just in case *PARANOIA*
702 if ( !$this->mTitle
->userCanCreate() ) {
703 wfDebug( "$fname: no create permission\n" );
704 $this->noCreatePermission();
705 wfProfileOut( $fname );
709 # Don't save a new article if it's blank.
710 if ( ( '' == $this->textbox1
) ) {
711 $wgOut->redirect( $this->mTitle
->getFullURL() );
712 wfProfileOut( $fname );
716 $isComment=($this->section
=='new');
717 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
718 $this->minoredit
, $this->watchthis
, false, $isComment);
720 wfProfileOut( $fname );
724 # Article exists. Check for edit conflict.
726 $this->mArticle
->clear(); # Force reload of dates, etc.
727 $this->mArticle
->forUpdate( true ); # Lock the article
729 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
730 $this->isConflict
= true;
731 if( $this->section
== 'new' ) {
732 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
733 $this->mArticle
->getComment() == $this->summary
) {
734 // Probably a duplicate submission of a new comment.
735 // This can happen when squid resends a request after
736 // a timeout but the first one actually went through.
737 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
739 // New comment; suppress conflict.
740 $this->isConflict
= false;
741 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
745 $userid = $wgUser->getID();
747 if ( $this->isConflict
) {
748 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
749 $this->mArticle
->getTimestamp() . "'\n" );
750 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
753 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
754 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
756 if( is_null( $text ) ) {
757 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
758 $this->isConflict
= true;
759 $text = $this->textbox1
;
762 # Suppress edit conflict with self, except for section edits where merging is required.
763 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
764 wfDebug( "Suppressing edit conflict, same user.\n" );
765 $this->isConflict
= false;
767 # switch from section editing to normal editing in edit conflict
768 if($this->isConflict
) {
770 if( $this->mergeChangesInto( $text ) ){
771 // Successful merge! Maybe we should tell the user the good news?
772 $this->isConflict
= false;
773 wfDebug( "Suppressing edit conflict, successful merge.\n" );
776 $this->textbox1
= $text;
777 wfDebug( "Keeping edit conflict, failed merge.\n" );
782 if ( $this->isConflict
) {
783 wfProfileOut( $fname );
787 $oldtext = $this->mArticle
->getContent();
789 # Handle the user preference to force summaries here, but not for null edits
790 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary')
791 && 0 != strcmp($oldtext, $text) && !Article
::getRedirectAutosummary( $text )) {
792 if( md5( $this->summary
) == $this->autoSumm
) {
793 $this->missingSummary
= true;
794 wfProfileOut( $fname );
799 #And a similar thing for new sections
800 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
801 if (trim($this->summary
) == '') {
802 $this->missingSummary
= true;
803 wfProfileOut( $fname );
809 wfProfileIn( "$fname-sectionanchor" );
811 if( $this->section
== 'new' ) {
812 if ( $this->textbox1
== '' ) {
813 $this->missingComment
= true;
816 if( $this->summary
!= '' ) {
817 $sectionanchor = $this->sectionAnchor( $this->summary
);
819 } elseif( $this->section
!= '' ) {
820 # Try to get a section anchor from the section source, redirect to edited section if header found
821 # XXX: might be better to integrate this into Article::replaceSection
822 # for duplicate heading checking and maybe parsing
823 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
824 # we can't deal with anchors, includes, html etc in the header for now,
825 # headline would need to be parsed to improve this
826 if($hasmatch and strlen($matches[2]) > 0) {
827 $sectionanchor = $this->sectionAnchor( $matches[2] );
830 wfProfileOut( "$fname-sectionanchor" );
832 // Save errors may fall down to the edit form, but we've now
833 // merged the section into full text. Clear the section field
834 // so that later submission of conflict forms won't try to
835 // replace that into a duplicated mess.
836 $this->textbox1
= $text;
839 // Check for length errors again now that the section is merged in
840 $this->kblength
= (int)(strlen( $text ) / 1024);
841 if ( $this->kblength
> $wgMaxArticleSize ) {
842 $this->tooBig
= true;
843 wfProfileOut( $fname );
847 # update the article here
848 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
849 $this->watchthis
, '', $sectionanchor ) ) {
850 wfProfileOut( $fname );
853 $this->isConflict
= true;
855 wfProfileOut( $fname );
860 * Initialise form fields in the object
861 * Called on the first invocation, e.g. when a user clicks an edit link
863 function initialiseForm() {
864 $this->edittime
= $this->mArticle
->getTimestamp();
866 $this->textbox1
= $this->getContent();
867 if ( !$this->mArticle
->exists() && $this->mArticle
->mTitle
->getNamespace() == NS_MEDIAWIKI
)
868 $this->textbox1
= wfMsgWeirdKey( $this->mArticle
->mTitle
->getText() ) ;
873 * Send the edit form and related headers to $wgOut
874 * @param $formCallback Optional callable that takes an OutputPage
875 * parameter; will be called during form output
876 * near the top, for captchas and the like.
878 function showEditForm( $formCallback=null ) {
879 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
881 $fname = 'EditPage::showEditForm';
882 wfProfileIn( $fname );
884 $sk =& $wgUser->getSkin();
886 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
888 $wgOut->setRobotpolicy( 'noindex,nofollow' );
890 # Enabled article-related sidebar, toplinks, etc.
891 $wgOut->setArticleRelated( true );
893 if ( $this->isConflict
) {
894 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
895 $wgOut->setPageTitle( $s );
896 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
898 $this->textbox2
= $this->textbox1
;
899 $this->textbox1
= $this->getContent();
900 $this->edittime
= $this->mArticle
->getTimestamp();
903 if( $this->section
!= '' ) {
904 if( $this->section
== 'new' ) {
905 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
907 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
909 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
910 preg_match( "/^(=+)(.+)\\1/mi",
913 if( !empty( $matches[2] ) ) {
914 $this->summary
= "/* ". trim($matches[2])." */ ";
919 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
921 $wgOut->setPageTitle( $s );
923 if ( $this->missingComment
) {
924 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
927 if( $this->missingSummary
&& $this->section
!= 'new' ) {
928 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
931 if( $this->missingSummary
&& $this->section
== 'new' ) {
932 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
935 if( !$this->hookError
== '' ) {
936 $wgOut->addWikiText( $this->hookError
);
939 if ( !$this->checkUnicodeCompliantBrowser() ) {
940 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
942 if ( isset( $this->mArticle
)
943 && isset( $this->mArticle
->mRevision
)
944 && !$this->mArticle
->mRevision
->isCurrent() ) {
945 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
946 $wgOut->addWikiText( wfMsg( 'editingold' ) );
951 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
952 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
953 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
955 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
956 # Check the skin exists
957 if( $this->isValidCssJsSubpage
) {
958 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
960 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
965 if( $this->mTitle
->isProtected( 'edit' ) ) {
966 # Is the protection due to the namespace, e.g. interface text?
967 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
968 # Yes; remind the user
969 $notice = wfMsg( 'editinginterface' );
970 } elseif( $this->mTitle
->isSemiProtected() ) {
972 $notice = wfMsg( 'semiprotectedpagewarning' );
973 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' ) {
977 # No; regular protection
978 $notice = wfMsg( 'protectedpagewarning' );
980 $wgOut->addWikiText( $notice );
983 if ( $this->kblength
=== false ) {
984 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
986 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
987 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgMaxArticleSize ) );
988 } elseif( $this->kblength
> 29 ) {
989 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) ) );
992 #need to parse the preview early so that we know which templates are used,
993 #otherwise users with "show preview after edit box" will get a blank list
994 if ( $this->formtype
== 'preview' ) {
995 $previewOutput = $this->getPreviewText();
998 $rows = $wgUser->getIntOption( 'rows' );
999 $cols = $wgUser->getIntOption( 'cols' );
1001 $ew = $wgUser->getOption( 'editwidth' );
1002 if ( $ew ) $ew = " style=\"width:100%\"";
1005 $q = 'action=submit';
1006 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1007 $action = $this->mTitle
->escapeLocalURL( $q );
1009 $summary = wfMsg('summary');
1010 $subject = wfMsg('subject');
1011 $minor = wfMsgExt('minoredit', array('parseinline'));
1012 $watchthis = wfMsgExt('watchthis', array('parseinline'));
1014 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
1015 wfMsgExt('cancel', array('parseinline')) );
1016 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1017 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1018 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1019 htmlspecialchars( wfMsg( 'newwindow' ) );
1021 global $wgRightsText;
1022 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1023 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
1024 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1025 $wgRightsText ) . "\n</div>";
1027 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1028 # prepare toolbar for edit buttons
1029 $toolbar = $this->getEditToolbar();
1034 // activate checkboxes if user wants them to be always active
1035 if( !$this->preview
&& !$this->diff
) {
1036 # Sort out the "watch" checkbox
1037 if( $wgUser->getOption( 'watchdefault' ) ) {
1039 $this->watchthis
= true;
1040 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1042 $this->watchthis
= true;
1043 } elseif( $this->mTitle
->userIsWatching() ) {
1045 $this->watchthis
= true;
1048 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1051 $minoredithtml = '';
1053 if ( $wgUser->isAllowed('minoredit') ) {
1055 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?
" checked='checked'":"").
1056 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />\n".
1057 "<label for='wpMinoredit'".$sk->tooltipAndAccesskey('minoredit').">{$minor}</label>\n";
1062 if ( $wgUser->isLoggedIn() ) {
1063 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
1064 ($this->watchthis?
" checked='checked'":"").
1065 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />\n".
1066 "<label for='wpWatchthis'".$sk->tooltipAndAccesskey('watch').">{$watchthis}</label>\n";
1069 $checkboxhtml = $minoredithtml . $watchhtml;
1071 $wgOut->addHTML( $this->editFormPageTop
);
1073 if ( $wgUser->getOption( 'previewontop' ) ) {
1075 if ( 'preview' == $this->formtype
) {
1076 $this->showPreview( $previewOutput );
1078 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1081 if ( 'diff' == $this->formtype
) {
1082 $wgOut->addHTML( $this->getDiff() );
1087 $wgOut->addHTML( $this->editFormTextTop
);
1089 # if this is a comment, show a subject line at the top, which is also the edit summary.
1090 # Otherwise, show a summary field at the bottom
1091 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1092 if( $this->section
== 'new' ) {
1093 $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 />";
1095 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1096 $summarypreview = '';
1098 $commentsubject = '';
1099 $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 />";
1100 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1101 $subjectpreview = '';
1104 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1105 if( !$this->preview
&& !$this->diff
) {
1106 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1108 $templates = ($this->preview ||
$this->section
) ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1109 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1111 global $wgUseMetadataEdit ;
1112 if ( $wgUseMetadataEdit ) {
1113 $metadata = $this->mMetaData
;
1114 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1115 $top = wfMsgWikiHtml( 'metadata_help' );
1116 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1118 else $metadata = "" ;
1122 if ($this->deletedSinceEdit
) {
1123 if ( 'save' != $this->formtype
) {
1124 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1126 // Hide the toolbar and edit area, use can click preview to get it back
1127 // Add an confirmation checkbox and explanation.
1129 $hidden = 'type="hidden" style="display:none;"';
1130 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1132 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1133 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1142 'value' => wfMsg('savearticle'),
1143 'accesskey' => wfMsg('accesskey-save'),
1144 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1146 $buttons['save'] = wfElement('input', $temp, '');
1152 'value' => wfMsg('showdiff'),
1153 'accesskey' => wfMsg('accesskey-diff'),
1154 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1156 $buttons['diff'] = wfElement('input', $temp, '');
1158 global $wgLivePreview;
1159 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1161 'id' => 'wpPreview',
1162 'name' => 'wpPreview',
1165 'value' => wfMsg('showpreview'),
1167 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1168 'style' => 'display: none;',
1170 $buttons['preview'] = wfElement('input', $temp, '');
1172 'id' => 'wpLivePreview',
1173 'name' => 'wpLivePreview',
1176 'value' => wfMsg('showlivepreview'),
1177 'accesskey' => wfMsg('accesskey-preview'),
1179 'onclick' => $this->doLivePreviewScript(),
1181 $buttons['live'] = wfElement('input', $temp, '');
1184 'id' => 'wpPreview',
1185 'name' => 'wpPreview',
1188 'value' => wfMsg('showpreview'),
1189 'accesskey' => wfMsg('accesskey-preview'),
1190 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1192 $buttons['preview'] = wfElement('input', $temp, '');
1193 $buttons['live'] = '';
1196 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1198 : "<input type='hidden' name=\"safemode\" value='1' />\n";
1200 $wgOut->addHTML( <<<END
1202 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1206 if( is_callable( $formCallback ) ) {
1207 call_user_func_array( $formCallback, array( &$wgOut ) );
1210 // Put these up at the top to ensure they aren't lost on early form submission
1212 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1213 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1214 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1215 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1217 $wgOut->addHTML( <<<END
1221 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1222 cols='{$cols}'{$ew} $hidden>
1224 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
1229 $wgOut->addWikiText( $copywarn );
1230 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1240 "<div class='editButtons'>
1242 {$buttons['preview']}
1245 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1246 </div><!-- editButtons -->
1247 </div><!-- editOptions -->");
1249 $wgOut->addHtml( '<div class="mw-editTools">' );
1250 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1251 $wgOut->addHtml( '</div>' );
1253 $wgOut->addHTML( $this->editFormTextAfterTools
);
1256 <div class='templatesUsed'>
1257 {$formattedtemplates}
1262 * To make it harder for someone to slip a user a page
1263 * which submits an edit form to the wiki without their
1264 * knowledge, a random token is associated with the login
1265 * session. If it's not passed back with the submission,
1266 * we won't save the page, or render user JavaScript and
1269 * For anon editors, who may not have a session, we just
1270 * include the constant suffix to prevent editing from
1271 * broken text-mangling proxies.
1273 if ( $wgUser->isLoggedIn() )
1274 $token = htmlspecialchars( $wgUser->editToken() );
1276 $token = EDIT_TOKEN_SUFFIX
;
1277 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1280 # If a blank edit summary was previously provided, and the appropriate
1281 # user preference is active, pass a hidden tag here. This will stop the
1282 # user being bounced back more than once in the event that a summary
1284 if( $this->missingSummary
) {
1285 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1288 # For a bit more sophisticated detection of blank summaries, hash the
1289 # automatic one and pass that in a hidden field.
1290 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1291 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1293 if ( $this->isConflict
) {
1294 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1296 $de = new DifferenceEngine( $this->mTitle
);
1297 $de->setText( $this->textbox2
, $this->textbox1
);
1298 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1300 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1301 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1302 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1304 $wgOut->addHTML( $this->editFormTextBottom
);
1305 $wgOut->addHTML( "</form>\n" );
1306 if ( !$wgUser->getOption( 'previewontop' ) ) {
1308 if ( $this->formtype
== 'preview') {
1309 $this->showPreview( $previewOutput );
1311 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1314 if ( $this->formtype
== 'diff') {
1315 $wgOut->addHTML( $this->getDiff() );
1320 wfProfileOut( $fname );
1324 * Append preview output to $wgOut.
1325 * Includes category rendering if this is a category page.
1327 * @param string $text The HTML to be output for the preview.
1329 private function showPreview( $text ) {
1332 $wgOut->addHTML( '<div id="wikiPreview">' );
1333 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1334 $this->mArticle
->openShowCategory();
1336 $wgOut->addHTML( $text );
1337 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1338 $this->mArticle
->closeShowCategory();
1340 $wgOut->addHTML( '</div>' );
1344 * Live Preview lets us fetch rendered preview page content and
1345 * add it to the page without refreshing the whole page.
1346 * If not supported by the browser it will fall through to the normal form
1347 * submission method.
1349 * This function outputs a script tag to support live preview, and
1350 * returns an onclick handler which should be added to the attributes
1351 * of the preview button
1353 function doLivePreviewScript() {
1354 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1355 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1356 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1357 '"></script>' . "\n" );
1358 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1359 return "return !livePreview(" .
1360 "getElementById('wikiPreview')," .
1361 "editform.wpTextbox1.value," .
1362 '"' . $liveAction . '"' . ")";
1365 function getLastDelete() {
1366 $dbr =& wfGetDB( DB_SLAVE
);
1367 $fname = 'EditPage::getLastDelete';
1368 $res = $dbr->select(
1369 array( 'logging', 'user' ),
1379 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1380 'log_title' => $this->mTitle
->getDBkey(),
1381 'log_type' => 'delete',
1382 'log_action' => 'delete',
1383 'user_id=log_user' ),
1385 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1387 if($dbr->numRows($res) == 1) {
1388 while ( $x = $dbr->fetchObject ( $res ) )
1390 $dbr->freeResult ( $res ) ;
1400 function getPreviewText() {
1401 global $wgOut, $wgUser, $wgTitle, $wgParser;
1403 $fname = 'EditPage::getPreviewText';
1404 wfProfileIn( $fname );
1406 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1407 $msg = 'session_fail_preview';
1409 $msg = 'previewnote';
1411 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1412 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1413 if ( $this->isConflict
) {
1414 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1417 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1418 $parserOptions->setEditSection( false );
1421 if( $wgRawHtml && !$this->mTokenOk
) {
1422 // Could be an offsite preview attempt. This is very unsafe if
1423 // HTML is enabled, as it could be an attack.
1424 return $wgOut->parse( "<div class='previewnote'>" .
1425 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1428 # don't parse user css/js, show message about preview
1429 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1431 if ( $this->isCssJsSubpage
) {
1432 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1433 $previewtext = wfMsg('usercsspreview');
1434 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1435 $previewtext = wfMsg('userjspreview');
1437 $parserOptions->setTidy(true);
1438 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1439 $wgOut->addHTML( $parserOutput->mText
);
1440 wfProfileOut( $fname );
1441 return $previewhead;
1443 $toparse = $this->textbox1
;
1445 # If we're adding a comment, we need to show the
1446 # summary as the headline
1447 if($this->section
=="new" && $this->summary
!="") {
1448 $toparse="== {$this->summary} ==\n\n".$toparse;
1451 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1452 $parserOptions->setTidy(true);
1453 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1454 $wgTitle, $parserOptions );
1456 $previewHTML = $parserOutput->getText();
1457 $wgOut->addParserOutputNoText( $parserOutput );
1459 foreach ( $parserOutput->getTemplates() as $ns => $template)
1460 foreach ( array_keys( $template ) as $dbk)
1461 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1463 wfProfileOut( $fname );
1464 return $previewhead . $previewHTML;
1469 * Call the stock "user is blocked" page
1471 function blockedPage() {
1472 global $wgOut, $wgUser;
1473 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1475 # If the user made changes, preserve them when showing the markup
1476 # (This happens when a user is blocked during edit, for instance)
1477 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1479 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1481 $source = $this->textbox1
;
1484 # Spit out the source or the user's modified version
1485 if( $source !== false ) {
1486 $rows = $wgUser->getOption( 'rows' );
1487 $cols = $wgUser->getOption( 'cols' );
1488 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1489 $wgOut->addHtml( '<hr />' );
1490 $wgOut->addWikiText( wfMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() ) );
1491 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1496 * Produce the stock "please login to edit pages" page
1498 function userNotLoggedInPage() {
1499 global $wgUser, $wgOut;
1500 $skin = $wgUser->getSkin();
1502 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1503 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle
->getPrefixedUrl() );
1505 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1506 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1507 $wgOut->setArticleRelated( false );
1509 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1510 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1514 * Creates a basic error page which informs the user that
1515 * they have to validate their email address before being
1518 function userNotConfirmedPage() {
1521 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1522 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1523 $wgOut->setArticleRelated( false );
1525 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1526 $wgOut->returnToMain( false );
1530 * Produce the stock "your edit contains spam" page
1532 * @param $match Text which triggered one or more filters
1534 function spamPage( $match = false ) {
1537 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1538 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1539 $wgOut->setArticleRelated( false );
1541 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1543 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1545 $wgOut->returnToMain( false );
1552 function mergeChangesInto( &$editText ){
1553 $fname = 'EditPage::mergeChangesInto';
1554 wfProfileIn( $fname );
1556 $db =& wfGetDB( DB_MASTER
);
1558 // This is the revision the editor started from
1559 $baseRevision = Revision
::loadFromTimestamp(
1560 $db, $this->mArticle
->mTitle
, $this->edittime
);
1561 if( is_null( $baseRevision ) ) {
1562 wfProfileOut( $fname );
1565 $baseText = $baseRevision->getText();
1567 // The current state, we want to merge updates into it
1568 $currentRevision = Revision
::loadFromTitle(
1569 $db, $this->mArticle
->mTitle
);
1570 if( is_null( $currentRevision ) ) {
1571 wfProfileOut( $fname );
1574 $currentText = $currentRevision->getText();
1577 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1578 $editText = $result;
1579 wfProfileOut( $fname );
1582 wfProfileOut( $fname );
1588 * Check if the browser is on a blacklist of user-agents known to
1589 * mangle UTF-8 data on form submission. Returns true if Unicode
1590 * should make it through, false if it's known to be a problem.
1594 function checkUnicodeCompliantBrowser() {
1595 global $wgBrowserBlackList;
1596 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1597 // No User-Agent header sent? Trust it by default...
1600 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1601 foreach ( $wgBrowserBlackList as $browser ) {
1602 if ( preg_match($browser, $currentbrowser) ) {
1610 * Format an anchor fragment as it would appear for a given section name
1611 * @param string $text
1615 function sectionAnchor( $text ) {
1616 $headline = Sanitizer
::decodeCharReferences( $text );
1618 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1619 $headline = trim( $headline );
1620 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1621 $replacearray = array(
1626 array_keys( $replacearray ),
1627 array_values( $replacearray ),
1632 * Shows a bulletin board style toolbar for common editing functions.
1633 * It can be disabled in the user preferences.
1634 * The necessary JavaScript code can be found in style/wikibits.js.
1636 function getEditToolbar() {
1637 global $wgStylePath, $wgContLang, $wgJsMimeType;
1640 * toolarray an array of arrays which each include the filename of
1641 * the button image (without path), the opening tag, the closing tag,
1642 * and optionally a sample text that is inserted between the two when no
1643 * selection is highlighted.
1644 * The tip text is shown when the user moves the mouse over the button.
1646 * Already here are accesskeys (key), which are not used yet until someone
1647 * can figure out a way to make them work in IE. However, we should make
1648 * sure these keys are not defined on the edit page.
1651 array( 'image'=>'button_bold.png',
1652 'open' => '\\\'\\\'\\\'',
1653 'close' => '\\\'\\\'\\\'',
1654 'sample'=> wfMsg('bold_sample'),
1655 'tip' => wfMsg('bold_tip'),
1658 array( 'image'=>'button_italic.png',
1659 'open' => '\\\'\\\'',
1660 'close' => '\\\'\\\'',
1661 'sample'=> wfMsg('italic_sample'),
1662 'tip' => wfMsg('italic_tip'),
1665 array( 'image'=>'button_link.png',
1668 'sample'=> wfMsg('link_sample'),
1669 'tip' => wfMsg('link_tip'),
1672 array( 'image'=>'button_extlink.png',
1675 'sample'=> wfMsg('extlink_sample'),
1676 'tip' => wfMsg('extlink_tip'),
1679 array( 'image'=>'button_headline.png',
1681 'close' => " ==\\n",
1682 'sample'=> wfMsg('headline_sample'),
1683 'tip' => wfMsg('headline_tip'),
1686 array( 'image'=>'button_image.png',
1687 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1689 'sample'=> wfMsg('image_sample'),
1690 'tip' => wfMsg('image_tip'),
1693 array( 'image' =>'button_media.png',
1694 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1696 'sample'=> wfMsg('media_sample'),
1697 'tip' => wfMsg('media_tip'),
1700 array( 'image' =>'button_math.png',
1702 'close' => "<\\/math>",
1703 'sample'=> wfMsg('math_sample'),
1704 'tip' => wfMsg('math_tip'),
1707 array( 'image' =>'button_nowiki.png',
1708 'open' => "<nowiki>",
1709 'close' => "<\\/nowiki>",
1710 'sample'=> wfMsg('nowiki_sample'),
1711 'tip' => wfMsg('nowiki_tip'),
1714 array( 'image' =>'button_sig.png',
1718 'tip' => wfMsg('sig_tip'),
1721 array( 'image' =>'button_hr.png',
1722 'open' => "\\n----\\n",
1725 'tip' => wfMsg('hr_tip'),
1729 $toolbar = "<div id='toolbar'>\n";
1730 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1732 foreach($toolarray as $tool) {
1734 $image=$wgStylePath.'/common/images/'.$tool['image'];
1735 $open=$tool['open'];
1736 $close=$tool['close'];
1737 $sample = wfEscapeJsString( $tool['sample'] );
1739 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1740 // Older browsers show a "speedtip" type message only for ALT.
1741 // Ideally these should be different, realistically they
1742 // probably don't need to be.
1743 $tip = wfEscapeJsString( $tool['tip'] );
1745 #$key = $tool["key"];
1747 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1750 $toolbar.="/*]]>*/\n</script>";
1751 $toolbar.="\n</div>";
1756 * Output preview text only. This can be sucked into the edit page
1757 * via JavaScript, and saves the server time rendering the skin as
1758 * well as theoretically being more robust on the client (doesn't
1759 * disturb the edit box's undo history, won't eat your text on
1762 * @todo This doesn't include category or interlanguage links.
1763 * Would need to enhance it a bit, maybe wrap them in XML
1764 * or something... that might also require more skin
1765 * initialization, so check whether that's a problem.
1767 function livePreview() {
1770 header( 'Content-type: text/xml' );
1771 header( 'Cache-control: no-cache' );
1773 echo $this->getPreviewText( );
1774 /* To not shake screen up and down between preview and live-preview */
1775 echo "<br style=\"clear:both;\" />\n";
1780 * Get a diff between the current contents of the edit box and the
1781 * version of the page we're editing from.
1783 * If this is a section edit, we'll replace the section as for final
1784 * save and then make a comparison.
1786 * @return string HTML
1788 function getDiff() {
1789 $oldtext = $this->mArticle
->fetchContent();
1790 $newtext = $this->mArticle
->replaceSection(
1791 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1792 $newtext = $this->mArticle
->preSaveTransform( $newtext );
1793 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1794 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1795 if ( $oldtext !== false ||
$newtext != '' ) {
1796 $de = new DifferenceEngine( $this->mTitle
);
1797 $de->setText( $oldtext, $newtext );
1798 $difftext = $de->getDiff( $oldtitle, $newtitle );
1803 return '<div id="wikiDiff">' . $difftext . '</div>';
1807 * Filter an input field through a Unicode de-armoring process if it
1808 * came from an old browser with known broken Unicode editing issues.
1810 * @param WebRequest $request
1811 * @param string $field
1815 function safeUnicodeInput( $request, $field ) {
1816 $text = rtrim( $request->getText( $field ) );
1817 return $request->getBool( 'safemode' )
1818 ?
$this->unmakesafe( $text )
1823 * Filter an output field through a Unicode armoring process if it is
1824 * going to an old browser with known broken Unicode editing issues.
1826 * @param string $text
1830 function safeUnicodeOutput( $text ) {
1832 $codedText = $wgContLang->recodeForEdit( $text );
1833 return $this->checkUnicodeCompliantBrowser()
1835 : $this->makesafe( $codedText );
1839 * A number of web browsers are known to corrupt non-ASCII characters
1840 * in a UTF-8 text editing environment. To protect against this,
1841 * detected browsers will be served an armored version of the text,
1842 * with non-ASCII chars converted to numeric HTML character references.
1844 * Preexisting such character references will have a 0 added to them
1845 * to ensure that round-trips do not alter the original data.
1847 * @param string $invalue
1851 function makesafe( $invalue ) {
1852 // Armor existing references for reversability.
1853 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1858 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1859 $bytevalue = ord( $invalue{$i} );
1860 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1861 $result .= chr( $bytevalue );
1863 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1864 $working = $working << 6;
1865 $working +
= ($bytevalue & 0x3F);
1867 if( $bytesleft <= 0 ) {
1868 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1870 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1871 $working = $bytevalue & 0x1F;
1873 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1874 $working = $bytevalue & 0x0F;
1876 } else { //1111 0xxx
1877 $working = $bytevalue & 0x07;
1885 * Reverse the previously applied transliteration of non-ASCII characters
1886 * back to UTF-8. Used to protect data from corruption by broken web browsers
1887 * as listed in $wgBrowserBlackList.
1889 * @param string $invalue
1893 function unmakesafe( $invalue ) {
1895 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1896 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
1900 $hexstring .= $invalue{$i};
1902 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1904 // Do some sanity checks. These aren't needed for reversability,
1905 // but should help keep the breakage down if the editor
1906 // breaks one of the entities whilst editing.
1907 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1908 $codepoint = hexdec($hexstring);
1909 $result .= codepointToUtf8( $codepoint );
1911 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1914 $result .= substr( $invalue, $i, 1 );
1917 // reverse the transform that we made for reversability reasons.
1918 return strtr( $result, array( "�" => "&#x" ) );
1921 function noCreatePermission() {
1923 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1924 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );