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
47 var $editFormTextAfterWarn;
48 var $editFormTextAfterTools;
49 var $editFormTextBottom;
55 function EditPage( $article ) {
56 $this->mArticle
=& $article;
58 $this->mTitle
=& $wgTitle;
60 # Placeholders for text injection by hooks (empty per default)
61 $this->editFormTextTop
= "";
62 $this->editFormTextAfterWarn
= "";
63 $this->editFormTextAfterTools
= "";
64 $this->editFormTextBottom
= "";
68 * Fetch initial editing page content.
70 private function getContent() {
71 global $wgRequest, $wgParser;
73 # Get variables from query string :P
74 $section = $wgRequest->getVal( 'section' );
75 $preload = $wgRequest->getVal( 'preload' );
76 $undo = $wgRequest->getVal( 'undo' );
78 wfProfileIn( __METHOD__
);
81 if( !$this->mTitle
->exists() ) {
83 # If requested, preload some text.
84 $text = $this->getPreloadedText( $preload );
86 # We used to put MediaWiki:Newarticletext here if
87 # $text was empty at this point.
88 # This is now shown above the edit box instead.
90 // FIXME: may be better to use Revision class directly
91 // But don't mess with it just yet. Article knows how to
92 // fetch the page record from the high-priority server,
93 // which is needed to guarantee we don't pick up lagged
96 $text = $this->mArticle
->getContent();
99 #Undoing a specific edit overrides section editing; section-editing
100 # doesn't work with undoing.
101 $undorev = Revision
::newFromId($undo);
102 $oldrev = $undorev->getPrevious();
104 #Sanity check, make sure it's the right page.
105 # Otherwise, $text will be left as-is.
106 if ($undorev->getPage() == $this->mArticle
->getID()) {
107 $undorev_text = $undorev->getText();
108 $oldrev_text = $oldrev->getText();
109 $currev_text = $text;
111 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, &$text);
114 #Undoing failed. Bailing out with regular revision text.
115 $text = $currev_text;
118 $this->editFormTextTop
= "<h2>" . wfMsg('undofailed') . "</h2>\n" .
119 '<p>'.wfMsg('explainundofailed').'</p>';
123 else if( $section != '' ) {
124 if( $section == 'new' ) {
125 $text = $this->getPreloadedText( $preload );
127 $text = $wgParser->getSection( $text, $section );
132 wfProfileOut( __METHOD__
);
137 * Get the contents of a page from its title and remove includeonly tags
139 * @param $preload String: the title of the page.
140 * @return string The contents of the page.
142 private function getPreloadedText($preload) {
143 if ( $preload === '' )
146 $preloadTitle = Title
::newFromText( $preload );
147 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
148 $rev=Revision
::newFromTitle($preloadTitle);
149 if ( is_object( $rev ) ) {
150 $text = $rev->getText();
151 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
152 // its own mini-parser! -ævar
153 $text = preg_replace( '~</?includeonly>~', '', $text );
162 * This is the function that extracts metadata from the article body on the first view.
163 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
164 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
166 function extractMetaDataFromArticle () {
167 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
168 $this->mMetaData
= '' ;
169 if ( !$wgUseMetadataEdit ) return ;
170 if ( $wgMetadataWhitelist == '' ) return ;
172 $t = $this->getContent();
174 # MISSING : <nowiki> filtering
176 # Categories and language links
177 $t = explode ( "\n" , $t ) ;
178 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
179 $cat = $ll = array() ;
180 foreach ( $t AS $key => $x )
182 $y = trim ( strtolower ( $x ) ) ;
183 while ( substr ( $y , 0 , 2 ) == '[[' )
185 $y = explode ( ']]' , trim ( $x ) ) ;
186 $first = array_shift ( $y ) ;
187 $first = explode ( ':' , $first ) ;
188 $ns = array_shift ( $first ) ;
189 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
190 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
192 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
193 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
195 $x = implode ( ']]' , $y ) ;
197 $y = trim ( strtolower ( $x ) ) ;
201 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
202 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
203 $t = implode ( "\n" , $t ) ;
206 $sat = array () ; # stand-alone-templates; must be lowercase
207 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
208 $wl_article = new Article ( $wl_title ) ;
209 $wl = explode ( "\n" , $wl_article->getContent() ) ;
210 foreach ( $wl AS $x )
214 while ( substr ( $x , 0 , 1 ) == '*' )
217 $x = trim ( substr ( $x , 1 ) ) ;
221 $sat[] = strtolower ( $x ) ;
226 # Templates, but only some
227 $t = explode ( '{{' , $t ) ;
229 foreach ( $t AS $key => $x )
231 $y = explode ( '}}' , $x , 2 ) ;
232 if ( count ( $y ) == 2 )
235 $z = explode ( '|' , $z ) ;
236 $tn = array_shift ( $z ) ;
237 if ( in_array ( strtolower ( $tn ) , $sat ) )
239 $tl[] = '{{' . $y[0] . '}}' ;
241 $y = explode ( '}}' , $y[1] , 2 ) ;
243 else $t[$key] = '{{' . $x ;
245 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
248 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
249 $t = implode ( '' , $t ) ;
251 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
252 $this->mArticle
->mContent
= $t ;
253 $this->mMetaData
= $s ;
261 * This is the function that gets called for "action=edit". It
262 * sets up various member variables, then passes execution to
263 * another function, usually showEditForm()
265 * The edit form is self-submitting, so that when things like
266 * preview and edit conflicts occur, we get the same form back
267 * with the extra stuff added. Only when the final submission
268 * is made and all is well do we actually save and redirect to
269 * the newly-edited page.
272 global $wgOut, $wgUser, $wgRequest, $wgTitle;
273 global $wgEmailConfirmToEdit;
275 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
278 $fname = 'EditPage::edit';
279 wfProfileIn( $fname );
280 wfDebug( "$fname: enter\n" );
282 // this is not an article
283 $wgOut->setArticleFlag(false);
285 $this->importFormData( $wgRequest );
286 $this->firsttime
= false;
289 $this->livePreview();
290 wfProfileOut( $fname );
294 if ( ! $this->mTitle
->userCanEdit() ) {
295 wfDebug( "$fname: user can't edit\n" );
296 $wgOut->readOnlyPage( $this->getContent(), true );
297 wfProfileOut( $fname );
300 wfDebug( "$fname: Checking blocks\n" );
301 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
302 # When previewing, don't check blocked state - will get caught at save time.
303 # Also, check when starting edition is done against slave to improve performance.
304 wfDebug( "$fname: user is blocked\n" );
305 $this->blockedPage();
306 wfProfileOut( $fname );
309 if ( !$wgUser->isAllowed('edit') ) {
310 if ( $wgUser->isAnon() ) {
311 wfDebug( "$fname: user must log in\n" );
312 $this->userNotLoggedInPage();
313 wfProfileOut( $fname );
316 wfDebug( "$fname: read-only page\n" );
317 $wgOut->readOnlyPage( $this->getContent(), true );
318 wfProfileOut( $fname );
322 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
323 wfDebug("$fname: user must confirm e-mail address\n");
324 $this->userNotConfirmedPage();
325 wfProfileOut($fname);
328 if ( !$this->mTitle
->userCanCreate() && !$this->mTitle
->exists() ) {
329 wfDebug( "$fname: no create permission\n" );
330 $this->noCreatePermission();
331 wfProfileOut( $fname );
334 if ( wfReadOnly() ) {
335 wfDebug( "$fname: read-only mode is engaged\n" );
336 if( $this->save ||
$this->preview
) {
337 $this->formtype
= 'preview';
338 } else if ( $this->diff
) {
339 $this->formtype
= 'diff';
341 $wgOut->readOnlyPage( $this->getContent() );
342 wfProfileOut( $fname );
347 $this->formtype
= 'save';
348 } else if ( $this->preview
) {
349 $this->formtype
= 'preview';
350 } else if ( $this->diff
) {
351 $this->formtype
= 'diff';
352 } else { # First time through
353 $this->firsttime
= true;
354 if( $this->previewOnOpen() ) {
355 $this->formtype
= 'preview';
357 $this->extractMetaDataFromArticle () ;
358 $this->formtype
= 'initial';
363 wfProfileIn( "$fname-business-end" );
365 $this->isConflict
= false;
366 // css / js subpages of user pages get a special treatment
367 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
368 $this->isValidCssJsSubpage
= $wgTitle->isValidCssJsSubpage();
370 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
371 * no matter it's current state
373 $this->deletedSinceEdit
= false;
374 if ( $this->edittime
!= '' ) {
375 /* Note that we rely on logging table, which hasn't been always there,
376 * but that doesn't matter, because this only applies to brand new
377 * deletes. This is done on every preview and save request. Move it further down
378 * to only perform it on saves
380 if ( $this->mTitle
->isDeleted() ) {
381 $this->lastDelete
= $this->getLastDelete();
382 if ( !is_null($this->lastDelete
) ) {
383 $deletetime = $this->lastDelete
->log_timestamp
;
384 if ( ($deletetime - $this->starttime
) > 0 ) {
385 $this->deletedSinceEdit
= true;
391 if(!$this->mTitle
->getArticleID() && ('initial' == $this->formtype ||
$this->firsttime
)) { # new article
394 if( $this->mTitle
->isTalkPage() ) {
395 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
398 # Attempt submission here. This will check for edit conflicts,
399 # and redundantly check for locked database, blocked IPs, etc.
400 # that edit() already checked just in case someone tries to sneak
401 # in the back door with a hand-edited submission URL.
403 if ( 'save' == $this->formtype
) {
404 if ( !$this->attemptSave() ) {
405 wfProfileOut( "$fname-business-end" );
406 wfProfileOut( $fname );
411 # First time through: get contents, set time for conflict
413 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
414 $this->initialiseForm();
415 if( !$this->mTitle
->getArticleId() )
416 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
419 $this->showEditForm();
420 wfProfileOut( "$fname-business-end" );
421 wfProfileOut( $fname );
425 * Return true if this page should be previewed when the edit form
426 * is initially opened.
430 function previewOnOpen() {
432 return $this->section
!= 'new' &&
433 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle
->exists() ) ||
434 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
435 !$this->mTitle
->exists() ) );
442 function importFormData( &$request ) {
443 global $wgLang, $wgUser;
444 $fname = 'EditPage::importFormData';
445 wfProfileIn( $fname );
447 if( $request->wasPosted() ) {
448 # These fields need to be checked for encoding.
449 # Also remove trailing whitespace, but don't remove _initial_
450 # whitespace from the text boxes. This may be significant formatting.
451 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
452 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
453 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
454 # Truncate for whole multibyte characters. +5 bytes for ellipsis
455 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
457 $this->edittime
= $request->getVal( 'wpEdittime' );
458 $this->starttime
= $request->getVal( 'wpStarttime' );
460 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
462 if( is_null( $this->edittime
) ) {
463 # If the form is incomplete, force to preview.
464 wfDebug( "$fname: Form data appears to be incomplete\n" );
465 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
466 $this->preview
= true;
468 /* Fallback for live preview */
469 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
470 $this->diff
= $request->getCheck( 'wpDiff' );
472 // Remember whether a save was requested, so we can indicate
473 // if we forced preview due to session failure.
474 $this->mTriedSave
= !$this->preview
;
476 if ( $this->tokenOk( $request ) ) {
477 # Some browsers will not report any submit button
478 # if the user hits enter in the comment box.
479 # The unmarked state will be assumed to be a save,
480 # if the form seems otherwise complete.
481 wfDebug( "$fname: Passed token check.\n" );
482 } else if ( $this->diff
) {
483 # Failed token check, but only requested "Show Changes".
484 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
486 # Page might be a hack attempt posted from
487 # an external site. Preview instead of saving.
488 wfDebug( "$fname: Failed token check; forcing preview\n" );
489 $this->preview
= true;
492 $this->save
= ! ( $this->preview
OR $this->diff
);
493 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
494 $this->edittime
= null;
497 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
498 $this->starttime
= null;
501 $this->recreate
= $request->getCheck( 'wpRecreate' );
503 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
504 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
506 # Don't force edit summaries when a user is editing their own user or talk page
507 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
508 $this->allowBlankSummary
= true;
510 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
513 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
515 # Not a posted form? Start with nothing.
516 wfDebug( "$fname: Not a posted form.\n" );
517 $this->textbox1
= '';
518 $this->textbox2
= '';
519 $this->mMetaData
= '';
521 $this->edittime
= '';
522 $this->starttime
= wfTimestampNow();
523 $this->preview
= false;
526 $this->minoredit
= false;
527 $this->watchthis
= false;
528 $this->recreate
= false;
531 $this->oldid
= $request->getInt( 'oldid' );
533 # Section edit can come from either the form or a link
534 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
536 $this->live
= $request->getCheck( 'live' );
537 $this->editintro
= $request->getText( 'editintro' );
539 wfProfileOut( $fname );
543 * Make sure the form isn't faking a user's credentials.
545 * @param $request WebRequest
549 function tokenOk( &$request ) {
551 if( $wgUser->isAnon() ) {
552 # Anonymous users may not have a session
553 # open. Don't tokenize.
554 $this->mTokenOk
= true;
556 $this->mTokenOk
= $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
558 return $this->mTokenOk
;
562 function showIntro() {
563 global $wgOut, $wgUser;
564 $addstandardintro=true;
565 if($this->editintro
) {
566 $introtitle=Title
::newFromText($this->editintro
);
567 if(isset($introtitle) && $introtitle->userCanRead()) {
568 $rev=Revision
::newFromTitle($introtitle);
570 $wgOut->addSecondaryWikiText($rev->getText());
571 $addstandardintro=false;
575 if($addstandardintro) {
576 if ( $wgUser->isLoggedIn() )
577 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
579 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
585 * @return bool false if output is done, true if the rest of the form should be displayed
587 function attemptSave() {
588 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
589 global $wgMaxArticleSize;
591 $fname = 'EditPage::attemptSave';
592 wfProfileIn( $fname );
593 wfProfileIn( "$fname-checks" );
595 # Reintegrate metadata
596 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
597 $this->mMetaData
= '' ;
601 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
602 $this->spamPage ( $matches[0] );
603 wfProfileOut( "$fname-checks" );
604 wfProfileOut( $fname );
607 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
608 # Error messages or other handling should be performed by the filter function
609 wfProfileOut( $fname );
610 wfProfileOut( "$fname-checks" );
613 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
) ) ) {
614 # Error messages etc. could be handled within the hook...
615 wfProfileOut( $fname );
616 wfProfileOut( "$fname-checks" );
618 } elseif( $this->hookError
!= '' ) {
619 # ...or the hook could be expecting us to produce an error
620 wfProfileOut( "$fname-checks " );
621 wfProfileOut( $fname );
624 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
625 # Check block state against master, thus 'false'.
626 $this->blockedPage();
627 wfProfileOut( "$fname-checks" );
628 wfProfileOut( $fname );
631 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
632 if ( $this->kblength
> $wgMaxArticleSize ) {
633 // Error will be displayed by showEditForm()
634 $this->tooBig
= true;
635 wfProfileOut( "$fname-checks" );
636 wfProfileOut( $fname );
640 if ( !$wgUser->isAllowed('edit') ) {
641 if ( $wgUser->isAnon() ) {
642 $this->userNotLoggedInPage();
643 wfProfileOut( "$fname-checks" );
644 wfProfileOut( $fname );
648 $wgOut->readOnlyPage();
649 wfProfileOut( "$fname-checks" );
650 wfProfileOut( $fname );
655 if ( wfReadOnly() ) {
656 $wgOut->readOnlyPage();
657 wfProfileOut( "$fname-checks" );
658 wfProfileOut( $fname );
661 if ( $wgUser->pingLimiter() ) {
662 $wgOut->rateLimited();
663 wfProfileOut( "$fname-checks" );
664 wfProfileOut( $fname );
668 # If the article has been deleted while editing, don't save it without
670 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
671 wfProfileOut( "$fname-checks" );
672 wfProfileOut( $fname );
676 wfProfileOut( "$fname-checks" );
678 # If article is new, insert it.
679 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
681 // Late check for create permission, just in case *PARANOIA*
682 if ( !$this->mTitle
->userCanCreate() ) {
683 wfDebug( "$fname: no create permission\n" );
684 $this->noCreatePermission();
685 wfProfileOut( $fname );
689 # Don't save a new article if it's blank.
690 if ( ( '' == $this->textbox1
) ) {
691 $wgOut->redirect( $this->mTitle
->getFullURL() );
692 wfProfileOut( $fname );
696 $isComment=($this->section
=='new');
697 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
698 $this->minoredit
, $this->watchthis
, false, $isComment);
700 wfProfileOut( $fname );
704 # Article exists. Check for edit conflict.
706 $this->mArticle
->clear(); # Force reload of dates, etc.
707 $this->mArticle
->forUpdate( true ); # Lock the article
709 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
710 $this->isConflict
= true;
711 if( $this->section
== 'new' ) {
712 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
713 $this->mArticle
->getComment() == $this->summary
) {
714 // Probably a duplicate submission of a new comment.
715 // This can happen when squid resends a request after
716 // a timeout but the first one actually went through.
717 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
719 // New comment; suppress conflict.
720 $this->isConflict
= false;
721 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
725 $userid = $wgUser->getID();
727 if ( $this->isConflict
) {
728 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
729 $this->mArticle
->getTimestamp() . "'\n" );
730 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
733 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
734 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
736 if( is_null( $text ) ) {
737 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
738 $this->isConflict
= true;
739 $text = $this->textbox1
;
742 # Suppress edit conflict with self, except for section edits where merging is required.
743 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
744 wfDebug( "Suppressing edit conflict, same user.\n" );
745 $this->isConflict
= false;
747 # switch from section editing to normal editing in edit conflict
748 if($this->isConflict
) {
750 if( $this->mergeChangesInto( $text ) ){
751 // Successful merge! Maybe we should tell the user the good news?
752 $this->isConflict
= false;
753 wfDebug( "Suppressing edit conflict, successful merge.\n" );
756 $this->textbox1
= $text;
757 wfDebug( "Keeping edit conflict, failed merge.\n" );
762 if ( $this->isConflict
) {
763 wfProfileOut( $fname );
767 $oldtext = $this->mArticle
->getContent();
769 # Handle the user preference to force summaries here, but not for null edits
770 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary')
771 && 0 != strcmp($oldtext, $text) && !Article
::getRedirectAutosummary( $text )) {
772 if( md5( $this->summary
) == $this->autoSumm
) {
773 $this->missingSummary
= true;
774 wfProfileOut( $fname );
779 #And a similar thing for new sections
780 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
781 if (trim($this->summary
) == '') {
782 $this->missingSummary
= true;
783 wfProfileOut( $fname );
789 wfProfileIn( "$fname-sectionanchor" );
791 if( $this->section
== 'new' ) {
792 if ( $this->textbox1
== '' ) {
793 $this->missingComment
= true;
796 if( $this->summary
!= '' ) {
797 $sectionanchor = $this->sectionAnchor( $this->summary
);
799 } elseif( $this->section
!= '' ) {
800 # Try to get a section anchor from the section source, redirect to edited section if header found
801 # XXX: might be better to integrate this into Article::replaceSection
802 # for duplicate heading checking and maybe parsing
803 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
804 # we can't deal with anchors, includes, html etc in the header for now,
805 # headline would need to be parsed to improve this
806 if($hasmatch and strlen($matches[2]) > 0) {
807 $sectionanchor = $this->sectionAnchor( $matches[2] );
810 wfProfileOut( "$fname-sectionanchor" );
812 // Save errors may fall down to the edit form, but we've now
813 // merged the section into full text. Clear the section field
814 // so that later submission of conflict forms won't try to
815 // replace that into a duplicated mess.
816 $this->textbox1
= $text;
819 // Check for length errors again now that the section is merged in
820 $this->kblength
= (int)(strlen( $text ) / 1024);
821 if ( $this->kblength
> $wgMaxArticleSize ) {
822 $this->tooBig
= true;
823 wfProfileOut( $fname );
827 # update the article here
828 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
829 $this->watchthis
, '', $sectionanchor ) ) {
830 wfProfileOut( $fname );
833 $this->isConflict
= true;
835 wfProfileOut( $fname );
840 * Initialise form fields in the object
841 * Called on the first invocation, e.g. when a user clicks an edit link
843 function initialiseForm() {
844 $this->edittime
= $this->mArticle
->getTimestamp();
845 $this->textbox1
= $this->getContent();
847 if ( !$this->mArticle
->exists() && $this->mArticle
->mTitle
->getNamespace() == NS_MEDIAWIKI
)
848 $this->textbox1
= wfMsgWeirdKey( $this->mArticle
->mTitle
->getText() ) ;
853 * Send the edit form and related headers to $wgOut
854 * @param $formCallback Optional callable that takes an OutputPage
855 * parameter; will be called during form output
856 * near the top, for captchas and the like.
858 function showEditForm( $formCallback=null ) {
859 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
861 $fname = 'EditPage::showEditForm';
862 wfProfileIn( $fname );
864 $sk =& $wgUser->getSkin();
866 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
868 $wgOut->setRobotpolicy( 'noindex,nofollow' );
870 # Enabled article-related sidebar, toplinks, etc.
871 $wgOut->setArticleRelated( true );
873 if ( $this->isConflict
) {
874 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
875 $wgOut->setPageTitle( $s );
876 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
878 $this->textbox2
= $this->textbox1
;
879 $this->textbox1
= $this->getContent();
880 $this->edittime
= $this->mArticle
->getTimestamp();
883 if( $this->section
!= '' ) {
884 if( $this->section
== 'new' ) {
885 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
887 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
889 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
890 preg_match( "/^(=+)(.+)\\1/mi",
893 if( !empty( $matches[2] ) ) {
894 $this->summary
= "/* ". trim($matches[2])." */ ";
899 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
901 $wgOut->setPageTitle( $s );
903 if ( $this->missingComment
) {
904 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
907 if( $this->missingSummary
&& $this->section
!= 'new' ) {
908 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
911 if( $this->missingSummary
&& $this->section
== 'new' ) {
912 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
915 if( !$this->hookError
== '' ) {
916 $wgOut->addWikiText( $this->hookError
);
919 if ( !$this->checkUnicodeCompliantBrowser() ) {
920 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
922 if ( isset( $this->mArticle
)
923 && isset( $this->mArticle
->mRevision
)
924 && !$this->mArticle
->mRevision
->isCurrent() ) {
925 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
926 $wgOut->addWikiText( wfMsg( 'editingold' ) );
931 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
932 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
933 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
935 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
936 # Check the skin exists
937 if( $this->isValidCssJsSubpage
) {
938 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
940 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
945 if( $this->mTitle
->isProtected( 'edit' ) ) {
946 # Is the protection due to the namespace, e.g. interface text?
947 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
948 # Yes; remind the user
949 $notice = wfMsg( 'editinginterface' );
950 } elseif( $this->mTitle
->isSemiProtected() ) {
952 $notice = wfMsg( 'semiprotectedpagewarning' );
953 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' ) {
957 # No; regular protection
958 $notice = wfMsg( 'protectedpagewarning' );
960 $wgOut->addWikiText( $notice );
963 if ( $this->kblength
=== false ) {
964 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
966 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
967 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgMaxArticleSize ) );
968 } elseif( $this->kblength
> 29 ) {
969 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) ) );
972 #need to parse the preview early so that we know which templates are used,
973 #otherwise users with "show preview after edit box" will get a blank list
974 $previewOutput = $this->getPreviewText();
976 $rows = $wgUser->getIntOption( 'rows' );
977 $cols = $wgUser->getIntOption( 'cols' );
979 $ew = $wgUser->getOption( 'editwidth' );
980 if ( $ew ) $ew = " style=\"width:100%\"";
983 $q = 'action=submit';
984 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
985 $action = $this->mTitle
->escapeLocalURL( $q );
987 $summary = wfMsg('summary');
988 $subject = wfMsg('subject');
989 $minor = wfMsgExt('minoredit', array('parseinline'));
990 $watchthis = wfMsgExt('watchthis', array('parseinline'));
992 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
993 wfMsgExt('cancel', array('parseinline')) );
994 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
995 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
996 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
997 htmlspecialchars( wfMsg( 'newwindow' ) );
999 global $wgRightsText;
1000 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1001 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
1002 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1003 $wgRightsText ) . "\n</div>";
1005 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1006 # prepare toolbar for edit buttons
1007 $toolbar = $this->getEditToolbar();
1012 // activate checkboxes if user wants them to be always active
1013 if( !$this->preview
&& !$this->diff
) {
1014 # Sort out the "watch" checkbox
1015 if( $wgUser->getOption( 'watchdefault' ) ) {
1017 $this->watchthis
= true;
1018 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1020 $this->watchthis
= true;
1021 } elseif( $this->mTitle
->userIsWatching() ) {
1023 $this->watchthis
= true;
1026 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1029 $minoredithtml = '';
1031 if ( $wgUser->isAllowed('minoredit') ) {
1033 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?
" checked='checked'":"").
1034 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />\n".
1035 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>\n";
1040 if ( $wgUser->isLoggedIn() ) {
1041 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
1042 ($this->watchthis?
" checked='checked'":"").
1043 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />\n".
1044 "<label for='wpWatchthis' title=\"" .
1045 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>\n";
1048 $checkboxhtml = $minoredithtml . $watchhtml;
1050 if ( $wgUser->getOption( 'previewontop' ) ) {
1052 if ( 'preview' == $this->formtype
) {
1053 $this->showPreview( $previewOutput );
1055 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1058 if ( 'diff' == $this->formtype
) {
1059 $wgOut->addHTML( $this->getDiff() );
1064 $wgOut->addHTML( $this->editFormTextTop
);
1066 # if this is a comment, show a subject line at the top, which is also the edit summary.
1067 # Otherwise, show a summary field at the bottom
1068 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1069 if( $this->section
== 'new' ) {
1070 $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 />";
1072 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1073 $summarypreview = '';
1075 $commentsubject = '';
1076 $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 />";
1077 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1078 $subjectpreview = '';
1081 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1082 if( !$this->preview
&& !$this->diff
) {
1083 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1085 $templates = ($this->preview ||
$this->section
) ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1086 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1088 global $wgUseMetadataEdit ;
1089 if ( $wgUseMetadataEdit ) {
1090 $metadata = $this->mMetaData
;
1091 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1092 $top = wfMsgWikiHtml( 'metadata_help' );
1093 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1095 else $metadata = "" ;
1099 if ($this->deletedSinceEdit
) {
1100 if ( 'save' != $this->formtype
) {
1101 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1103 // Hide the toolbar and edit area, use can click preview to get it back
1104 // Add an confirmation checkbox and explanation.
1106 $hidden = 'type="hidden" style="display:none;"';
1107 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1109 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1110 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1119 'value' => wfMsg('savearticle'),
1120 'accesskey' => wfMsg('accesskey-save'),
1121 'title' => wfMsg('tooltip-save'),
1123 $buttons['save'] = wfElement('input', $temp, '');
1129 'value' => wfMsg('showdiff'),
1130 'accesskey' => wfMsg('accesskey-diff'),
1131 'title' => wfMsg('tooltip-diff'),
1133 $buttons['diff'] = wfElement('input', $temp, '');
1135 global $wgLivePreview;
1136 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1138 'id' => 'wpPreview',
1139 'name' => 'wpPreview',
1142 'value' => wfMsg('showpreview'),
1144 'title' => wfMsg('tooltip-preview'),
1145 'style' => 'display: none;',
1147 $buttons['preview'] = wfElement('input', $temp, '');
1149 'id' => 'wpLivePreview',
1150 'name' => 'wpLivePreview',
1153 'value' => wfMsg('showlivepreview'),
1154 'accesskey' => wfMsg('accesskey-preview'),
1156 'onclick' => $this->doLivePreviewScript(),
1158 $buttons['live'] = wfElement('input', $temp, '');
1161 'id' => 'wpPreview',
1162 'name' => 'wpPreview',
1165 'value' => wfMsg('showpreview'),
1166 'accesskey' => wfMsg('accesskey-preview'),
1167 'title' => wfMsg('tooltip-preview'),
1169 $buttons['preview'] = wfElement('input', $temp, '');
1170 $buttons['live'] = '';
1173 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1175 : "<input type='hidden' name=\"safemode\" value='1' />\n";
1177 $wgOut->addHTML( <<<END
1179 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1183 if( is_callable( $formCallback ) ) {
1184 call_user_func_array( $formCallback, array( &$wgOut ) );
1187 // Put these up at the top to ensure they aren't lost on early form submission
1189 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1190 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1191 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1192 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1194 $wgOut->addHTML( <<<END
1198 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1199 cols='{$cols}'{$ew} $hidden>
1201 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
1206 $wgOut->addWikiText( $copywarn );
1207 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1217 "<div class='editButtons'>
1219 {$buttons['preview']}
1222 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1223 </div><!-- editButtons -->
1224 </div><!-- editOptions -->");
1226 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1227 $wgOut->addHTML( $this->editFormTextAfterTools
);
1230 <div class='templatesUsed'>
1231 {$formattedtemplates}
1235 if ( $wgUser->isLoggedIn() ) {
1237 * To make it harder for someone to slip a user a page
1238 * which submits an edit form to the wiki without their
1239 * knowledge, a random token is associated with the login
1240 * session. If it's not passed back with the submission,
1241 * we won't save the page, or render user JavaScript and
1244 $token = htmlspecialchars( $wgUser->editToken() );
1245 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1248 # If a blank edit summary was previously provided, and the appropriate
1249 # user preference is active, pass a hidden tag here. This will stop the
1250 # user being bounced back more than once in the event that a summary
1252 if( $this->missingSummary
) {
1253 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1256 # For a bit more sophisticated detection of blank summaries, hash the
1257 # automatic one and pass that in a hidden field.
1258 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1259 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1261 if ( $this->isConflict
) {
1262 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1264 $de = new DifferenceEngine( $this->mTitle
);
1265 $de->setText( $this->textbox2
, $this->textbox1
);
1266 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1268 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1269 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1270 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1272 $wgOut->addHTML( $this->editFormTextBottom
);
1273 $wgOut->addHTML( "</form>\n" );
1274 if ( !$wgUser->getOption( 'previewontop' ) ) {
1276 if ( $this->formtype
== 'preview') {
1277 $this->showPreview( $previewOutput );
1279 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1282 if ( $this->formtype
== 'diff') {
1283 $wgOut->addHTML( $this->getDiff() );
1288 wfProfileOut( $fname );
1292 * Append preview output to $wgOut.
1293 * Includes category rendering if this is a category page.
1295 * @param string $text The HTML to be output for the preview.
1297 private function showPreview( $text ) {
1300 $wgOut->addHTML( '<div id="wikiPreview">' );
1301 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1302 $this->mArticle
->openShowCategory();
1304 $wgOut->addHTML( $text );
1305 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1306 $this->mArticle
->closeShowCategory();
1308 $wgOut->addHTML( '</div>' );
1312 * Live Preview lets us fetch rendered preview page content and
1313 * add it to the page without refreshing the whole page.
1314 * If not supported by the browser it will fall through to the normal form
1315 * submission method.
1317 * This function outputs a script tag to support live preview, and
1318 * returns an onclick handler which should be added to the attributes
1319 * of the preview button
1321 function doLivePreviewScript() {
1322 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1323 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1324 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1325 '"></script>' . "\n" );
1326 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1327 return "return !livePreview(" .
1328 "getElementById('wikiPreview')," .
1329 "editform.wpTextbox1.value," .
1330 '"' . $liveAction . '"' . ")";
1333 function getLastDelete() {
1334 $dbr =& wfGetDB( DB_SLAVE
);
1335 $fname = 'EditPage::getLastDelete';
1336 $res = $dbr->select(
1337 array( 'logging', 'user' ),
1347 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1348 'log_title' => $this->mTitle
->getDBkey(),
1349 'log_type' => 'delete',
1350 'log_action' => 'delete',
1351 'user_id=log_user' ),
1353 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1355 if($dbr->numRows($res) == 1) {
1356 while ( $x = $dbr->fetchObject ( $res ) )
1358 $dbr->freeResult ( $res ) ;
1368 function getPreviewText() {
1369 global $wgOut, $wgUser, $wgTitle, $wgParser;
1371 $fname = 'EditPage::getPreviewText';
1372 wfProfileIn( $fname );
1374 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1375 $msg = 'session_fail_preview';
1377 $msg = 'previewnote';
1379 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1380 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1381 if ( $this->isConflict
) {
1382 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1385 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1386 $parserOptions->setEditSection( false );
1389 if( $wgRawHtml && !$this->mTokenOk
) {
1390 // Could be an offsite preview attempt. This is very unsafe if
1391 // HTML is enabled, as it could be an attack.
1392 return $wgOut->parse( "<div class='previewnote'>" .
1393 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1396 # don't parse user css/js, show message about preview
1397 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1399 if ( $this->isCssJsSubpage
) {
1400 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1401 $previewtext = wfMsg('usercsspreview');
1402 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1403 $previewtext = wfMsg('userjspreview');
1405 $parserOptions->setTidy(true);
1406 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1407 $wgOut->addHTML( $parserOutput->mText
);
1408 wfProfileOut( $fname );
1409 return $previewhead;
1411 $toparse = $this->textbox1
;
1413 # If we're adding a comment, we need to show the
1414 # summary as the headline
1415 if($this->section
=="new" && $this->summary
!="") {
1416 $toparse="== {$this->summary} ==\n\n".$toparse;
1419 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1420 $parserOptions->setTidy(true);
1421 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1422 $wgTitle, $parserOptions );
1424 $previewHTML = $parserOutput->getText();
1425 $wgOut->addParserOutputNoText( $parserOutput );
1427 foreach ( $parserOutput->getTemplates() as $ns => $template)
1428 foreach ( array_keys( $template ) as $dbk)
1429 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1431 wfProfileOut( $fname );
1432 return $previewhead . $previewHTML;
1437 * Call the stock "user is blocked" page
1439 function blockedPage() {
1440 global $wgOut, $wgUser;
1441 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1443 # If the user made changes, preserve them when showing the markup
1444 # (This happens when a user is blocked during edit, for instance)
1445 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1447 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1449 $source = $this->textbox1
;
1452 # Spit out the source or the user's modified version
1453 if( $source !== false ) {
1454 $rows = $wgUser->getOption( 'rows' );
1455 $cols = $wgUser->getOption( 'cols' );
1456 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1457 $wgOut->addHtml( '<hr />' );
1458 $wgOut->addWikiText( wfMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() ) );
1459 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1464 * Produce the stock "please login to edit pages" page
1466 function userNotLoggedInPage() {
1467 global $wgUser, $wgOut;
1468 $skin = $wgUser->getSkin();
1470 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1471 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle
->getPrefixedUrl() );
1473 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1474 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1475 $wgOut->setArticleRelated( false );
1477 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1478 $wgOut->returnToMain( false, $this->mTitle
->getPrefixedUrl() );
1482 * Creates a basic error page which informs the user that
1483 * they have to validate their email address before being
1486 function userNotConfirmedPage() {
1489 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1490 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1491 $wgOut->setArticleRelated( false );
1493 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1494 $wgOut->returnToMain( false );
1498 * Produce the stock "your edit contains spam" page
1500 * @param $match Text which triggered one or more filters
1502 function spamPage( $match = false ) {
1505 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1506 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1507 $wgOut->setArticleRelated( false );
1509 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1511 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1513 $wgOut->returnToMain( false );
1520 function mergeChangesInto( &$editText ){
1521 $fname = 'EditPage::mergeChangesInto';
1522 wfProfileIn( $fname );
1524 $db =& wfGetDB( DB_MASTER
);
1526 // This is the revision the editor started from
1527 $baseRevision = Revision
::loadFromTimestamp(
1528 $db, $this->mArticle
->mTitle
, $this->edittime
);
1529 if( is_null( $baseRevision ) ) {
1530 wfProfileOut( $fname );
1533 $baseText = $baseRevision->getText();
1535 // The current state, we want to merge updates into it
1536 $currentRevision = Revision
::loadFromTitle(
1537 $db, $this->mArticle
->mTitle
);
1538 if( is_null( $currentRevision ) ) {
1539 wfProfileOut( $fname );
1542 $currentText = $currentRevision->getText();
1545 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1546 $editText = $result;
1547 wfProfileOut( $fname );
1550 wfProfileOut( $fname );
1556 * Check if the browser is on a blacklist of user-agents known to
1557 * mangle UTF-8 data on form submission. Returns true if Unicode
1558 * should make it through, false if it's known to be a problem.
1562 function checkUnicodeCompliantBrowser() {
1563 global $wgBrowserBlackList;
1564 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1565 // No User-Agent header sent? Trust it by default...
1568 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1569 foreach ( $wgBrowserBlackList as $browser ) {
1570 if ( preg_match($browser, $currentbrowser) ) {
1578 * Format an anchor fragment as it would appear for a given section name
1579 * @param string $text
1583 function sectionAnchor( $text ) {
1584 $headline = Sanitizer
::decodeCharReferences( $text );
1586 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1587 $headline = trim( $headline );
1588 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1589 $replacearray = array(
1594 array_keys( $replacearray ),
1595 array_values( $replacearray ),
1600 * Shows a bulletin board style toolbar for common editing functions.
1601 * It can be disabled in the user preferences.
1602 * The necessary JavaScript code can be found in style/wikibits.js.
1604 function getEditToolbar() {
1605 global $wgStylePath, $wgContLang, $wgJsMimeType;
1608 * toolarray an array of arrays which each include the filename of
1609 * the button image (without path), the opening tag, the closing tag,
1610 * and optionally a sample text that is inserted between the two when no
1611 * selection is highlighted.
1612 * The tip text is shown when the user moves the mouse over the button.
1614 * Already here are accesskeys (key), which are not used yet until someone
1615 * can figure out a way to make them work in IE. However, we should make
1616 * sure these keys are not defined on the edit page.
1619 array( 'image'=>'button_bold.png',
1621 'close' => "\'\'\'",
1622 'sample'=> wfMsg('bold_sample'),
1623 'tip' => wfMsg('bold_tip'),
1626 array( 'image'=>'button_italic.png',
1629 'sample'=> wfMsg('italic_sample'),
1630 'tip' => wfMsg('italic_tip'),
1633 array( 'image'=>'button_link.png',
1636 'sample'=> wfMsg('link_sample'),
1637 'tip' => wfMsg('link_tip'),
1640 array( 'image'=>'button_extlink.png',
1643 'sample'=> wfMsg('extlink_sample'),
1644 'tip' => wfMsg('extlink_tip'),
1647 array( 'image'=>'button_headline.png',
1649 'close' => " ==\\n",
1650 'sample'=> wfMsg('headline_sample'),
1651 'tip' => wfMsg('headline_tip'),
1654 array( 'image'=>'button_image.png',
1655 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1657 'sample'=> wfMsg('image_sample'),
1658 'tip' => wfMsg('image_tip'),
1661 array( 'image' =>'button_media.png',
1662 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1664 'sample'=> wfMsg('media_sample'),
1665 'tip' => wfMsg('media_tip'),
1668 array( 'image' =>'button_math.png',
1670 'close' => "<\\/math>",
1671 'sample'=> wfMsg('math_sample'),
1672 'tip' => wfMsg('math_tip'),
1675 array( 'image' =>'button_nowiki.png',
1676 'open' => "<nowiki>",
1677 'close' => "<\\/nowiki>",
1678 'sample'=> wfMsg('nowiki_sample'),
1679 'tip' => wfMsg('nowiki_tip'),
1682 array( 'image' =>'button_sig.png',
1686 'tip' => wfMsg('sig_tip'),
1689 array( 'image' =>'button_hr.png',
1690 'open' => "\\n----\\n",
1693 'tip' => wfMsg('hr_tip'),
1697 $toolbar = "<div id='toolbar'>\n";
1698 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1700 foreach($toolarray as $tool) {
1702 $image=$wgStylePath.'/common/images/'.$tool['image'];
1703 $open=$tool['open'];
1704 $close=$tool['close'];
1705 $sample = wfEscapeJsString( $tool['sample'] );
1707 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1708 // Older browsers show a "speedtip" type message only for ALT.
1709 // Ideally these should be different, realistically they
1710 // probably don't need to be.
1711 $tip = wfEscapeJsString( $tool['tip'] );
1713 #$key = $tool["key"];
1715 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1718 $toolbar.="/*]]>*/\n</script>";
1719 $toolbar.="\n</div>";
1724 * Output preview text only. This can be sucked into the edit page
1725 * via JavaScript, and saves the server time rendering the skin as
1726 * well as theoretically being more robust on the client (doesn't
1727 * disturb the edit box's undo history, won't eat your text on
1730 * @todo This doesn't include category or interlanguage links.
1731 * Would need to enhance it a bit, maybe wrap them in XML
1732 * or something... that might also require more skin
1733 * initialization, so check whether that's a problem.
1735 function livePreview() {
1738 header( 'Content-type: text/xml' );
1739 header( 'Cache-control: no-cache' );
1741 echo $this->getPreviewText( );
1742 /* To not shake screen up and down between preview and live-preview */
1743 echo "<br style=\"clear:both;\" />\n";
1748 * Get a diff between the current contents of the edit box and the
1749 * version of the page we're editing from.
1751 * If this is a section edit, we'll replace the section as for final
1752 * save and then make a comparison.
1754 * @return string HTML
1756 function getDiff() {
1757 $oldtext = $this->mArticle
->fetchContent();
1758 $newtext = $this->mArticle
->replaceSection(
1759 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1760 $newtext = $this->mArticle
->preSaveTransform( $newtext );
1761 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1762 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1763 if ( $oldtext !== false ||
$newtext != '' ) {
1764 $de = new DifferenceEngine( $this->mTitle
);
1765 $de->setText( $oldtext, $newtext );
1766 $difftext = $de->getDiff( $oldtitle, $newtitle );
1771 return '<div id="wikiDiff">' . $difftext . '</div>';
1775 * Filter an input field through a Unicode de-armoring process if it
1776 * came from an old browser with known broken Unicode editing issues.
1778 * @param WebRequest $request
1779 * @param string $field
1783 function safeUnicodeInput( $request, $field ) {
1784 $text = rtrim( $request->getText( $field ) );
1785 return $request->getBool( 'safemode' )
1786 ?
$this->unmakesafe( $text )
1791 * Filter an output field through a Unicode armoring process if it is
1792 * going to an old browser with known broken Unicode editing issues.
1794 * @param string $text
1798 function safeUnicodeOutput( $text ) {
1800 $codedText = $wgContLang->recodeForEdit( $text );
1801 return $this->checkUnicodeCompliantBrowser()
1803 : $this->makesafe( $codedText );
1807 * A number of web browsers are known to corrupt non-ASCII characters
1808 * in a UTF-8 text editing environment. To protect against this,
1809 * detected browsers will be served an armored version of the text,
1810 * with non-ASCII chars converted to numeric HTML character references.
1812 * Preexisting such character references will have a 0 added to them
1813 * to ensure that round-trips do not alter the original data.
1815 * @param string $invalue
1819 function makesafe( $invalue ) {
1820 // Armor existing references for reversability.
1821 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1826 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1827 $bytevalue = ord( $invalue{$i} );
1828 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1829 $result .= chr( $bytevalue );
1831 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1832 $working = $working << 6;
1833 $working +
= ($bytevalue & 0x3F);
1835 if( $bytesleft <= 0 ) {
1836 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1838 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1839 $working = $bytevalue & 0x1F;
1841 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1842 $working = $bytevalue & 0x0F;
1844 } else { //1111 0xxx
1845 $working = $bytevalue & 0x07;
1853 * Reverse the previously applied transliteration of non-ASCII characters
1854 * back to UTF-8. Used to protect data from corruption by broken web browsers
1855 * as listed in $wgBrowserBlackList.
1857 * @param string $invalue
1861 function unmakesafe( $invalue ) {
1863 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1864 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
1868 $hexstring .= $invalue{$i};
1870 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1872 // Do some sanity checks. These aren't needed for reversability,
1873 // but should help keep the breakage down if the editor
1874 // breaks one of the entities whilst editing.
1875 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1876 $codepoint = hexdec($hexstring);
1877 $result .= codepointToUtf8( $codepoint );
1879 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1882 $result .= substr( $invalue, $i, 1 );
1885 // reverse the transform that we made for reversability reasons.
1886 return strtr( $result, array( "�" => "&#x" ) );
1889 function noCreatePermission() {
1891 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1892 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );