3 * Contains the EditPage class
8 * The edit page/HTML interface (split from Article)
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
13 * EditPage cares about two distinct titles:
14 * $wgTitle is the page that forms submit to, links point to,
15 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
16 * page in the database that is actually being edited. These are
17 * usually the same, but they are now allowed to be different.
20 const AS_SUCCESS_UPDATE
= 200;
21 const AS_SUCCESS_NEW_ARTICLE
= 201;
22 const AS_HOOK_ERROR
= 210;
23 const AS_FILTERING
= 211;
24 const AS_HOOK_ERROR_EXPECTED
= 212;
25 const AS_BLOCKED_PAGE_FOR_USER
= 215;
26 const AS_CONTENT_TOO_BIG
= 216;
27 const AS_USER_CANNOT_EDIT
= 217;
28 const AS_READ_ONLY_PAGE_ANON
= 218;
29 const AS_READ_ONLY_PAGE_LOGGED
= 219;
30 const AS_READ_ONLY_PAGE
= 220;
31 const AS_RATE_LIMITED
= 221;
32 const AS_ARTICLE_WAS_DELETED
= 222;
33 const AS_NO_CREATE_PERMISSION
= 223;
34 const AS_BLANK_ARTICLE
= 224;
35 const AS_CONFLICT_DETECTED
= 225;
36 const AS_SUMMARY_NEEDED
= 226;
37 const AS_TEXTBOX_EMPTY
= 228;
38 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
41 const AS_SPAM_ERROR
= 232;
42 const AS_IMAGE_REDIRECT_ANON
= 233;
43 const AS_IMAGE_REDIRECT_LOGGED
= 234;
48 var $isConflict = false;
49 var $isCssJsSubpage = false;
50 var $deletedSinceEdit = false;
54 var $mTokenOk = false;
55 var $mTokenOkExceptSuffix = false;
56 var $mTriedSave = false;
58 var $kblength = false;
59 var $missingComment = false;
60 var $missingSummary = false;
61 var $allowBlankSummary = false;
64 var $mPreviewTemplates;
65 var $mBaseRevision = false;
68 var $save = false, $preview = false, $diff = false;
69 var $minoredit = false, $watchthis = false, $recreate = false;
70 var $textbox1 = '', $textbox2 = '', $summary = '';
71 var $edittime = '', $section = '', $starttime = '';
72 var $oldid = 0, $editintro = '', $scrolltop = null;
74 # Placeholders for text injection by hooks (must be HTML)
75 # extensions should take care to _append_ to the present value
76 public $editFormPageTop; // Before even the preview
77 public $editFormTextTop;
78 public $editFormTextBeforeContent;
79 public $editFormTextAfterWarn;
80 public $editFormTextAfterTools;
81 public $editFormTextBottom;
83 /* $didSave should be set to true whenever an article was succesfully altered. */
84 public $didSave = false;
86 public $suppressIntro = false;
92 function EditPage( $article ) {
93 $this->mArticle
=& $article;
94 $this->mTitle
= $article->getTitle();
96 # Placeholders for text injection by hooks (empty per default)
97 $this->editFormPageTop
=
98 $this->editFormTextTop
=
99 $this->editFormTextBeforeContent
=
100 $this->editFormTextAfterWarn
=
101 $this->editFormTextAfterTools
=
102 $this->editFormTextBottom
= "";
106 * Fetch initial editing page content.
109 function getContent( $def_text = '' ) {
110 global $wgOut, $wgRequest, $wgParser, $wgMessageCache;
112 # Get variables from query string :P
113 $section = $wgRequest->getVal( 'section' );
114 $preload = $wgRequest->getVal( 'preload' );
115 $undoafter = $wgRequest->getVal( 'undoafter' );
116 $undo = $wgRequest->getVal( 'undo' );
118 wfProfileIn( __METHOD__
);
121 if( !$this->mTitle
->exists() ) {
122 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
123 $wgMessageCache->loadAllMessages();
124 # If this is a system message, get the default text.
125 $text = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
127 # If requested, preload some text.
128 $text = $this->getPreloadedText( $preload );
130 # We used to put MediaWiki:Newarticletext here if
131 # $text was empty at this point.
132 # This is now shown above the edit box instead.
134 // FIXME: may be better to use Revision class directly
135 // But don't mess with it just yet. Article knows how to
136 // fetch the page record from the high-priority server,
137 // which is needed to guarantee we don't pick up lagged
140 $text = $this->mArticle
->getContent();
142 if ($undo > 0 && $undoafter > 0 && $undo < $undoafter) {
143 # If they got undoafter and undo round the wrong way, switch them
144 list( $undo, $undoafter ) = array( $undoafter, $undo );
147 if ( $undo > 0 && $undo > $undoafter ) {
148 # Undoing a specific edit overrides section editing; section-editing
149 # doesn't work with undoing.
151 $undorev = Revision
::newFromId($undo);
152 $oldrev = Revision
::newFromId($undoafter);
154 $undorev = Revision
::newFromId($undo);
155 $oldrev = $undorev ?
$undorev->getPrevious() : null;
158 # Sanity check, make sure it's the right page,
159 # the revisions exist and they were not deleted.
160 # Otherwise, $text will be left as-is.
161 if( !is_null( $undorev ) && !is_null( $oldrev ) &&
162 $undorev->getPage() == $oldrev->getPage() &&
163 $undorev->getPage() == $this->mArticle
->getID() &&
164 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
165 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
166 $undorev_text = $undorev->getText();
167 $oldrev_text = $oldrev->getText();
168 $currev_text = $text;
170 if ( $currev_text != $undorev_text ) {
171 $result = wfMerge( $undorev_text, $oldrev_text, $currev_text, $text );
173 # No use doing a merge if it's just a straight revert.
174 $text = $oldrev_text;
178 # Inform the user of our success and set an automatic edit summary
179 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
180 $firstrev = $oldrev->getNext();
181 # If we just undid one rev, use an autosummary
182 if( $firstrev->mId
== $undo ) {
183 $this->summary
= wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
185 $this->formtype
= 'diff';
187 # Warn the user that something went wrong
188 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
191 // Failed basic sanity checks.
192 // Older revisions may have been removed since the link
193 // was created, or we may simply have got bogus input.
194 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-norev' ) );
196 } else if( $section != '' ) {
197 if( $section == 'new' ) {
198 $text = $this->getPreloadedText( $preload );
200 $text = $wgParser->getSection( $text, $section, $def_text );
205 wfProfileOut( __METHOD__
);
210 * Get the contents of a page from its title and remove includeonly tags
212 * @param $preload String: the title of the page.
213 * @return string The contents of the page.
215 protected function getPreloadedText($preload) {
216 if ( $preload === '' )
219 $preloadTitle = Title
::newFromText( $preload );
220 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
221 $rev=Revision
::newFromTitle($preloadTitle);
222 if ( is_object( $rev ) ) {
223 $text = $rev->getText();
224 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
225 // its own mini-parser! -ævar
226 $text = preg_replace( '~</?includeonly>~', '', $text );
235 * This is the function that extracts metadata from the article body on the first view.
236 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
237 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
239 function extractMetaDataFromArticle () {
240 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
241 $this->mMetaData
= '' ;
242 if ( !$wgUseMetadataEdit ) return ;
243 if ( $wgMetadataWhitelist == '' ) return ;
245 $t = $this->getContent();
247 # MISSING : <nowiki> filtering
249 # Categories and language links
250 $t = explode ( "\n" , $t ) ;
251 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
252 $cat = $ll = array() ;
253 foreach ( $t AS $key => $x )
255 $y = trim ( strtolower ( $x ) ) ;
256 while ( substr ( $y , 0 , 2 ) == '[[' )
258 $y = explode ( ']]' , trim ( $x ) ) ;
259 $first = array_shift ( $y ) ;
260 $first = explode ( ':' , $first ) ;
261 $ns = array_shift ( $first ) ;
262 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
263 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
265 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
266 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
268 $x = implode ( ']]' , $y ) ;
270 $y = trim ( strtolower ( $x ) ) ;
274 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
275 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
276 $t = implode ( "\n" , $t ) ;
279 $sat = array () ; # stand-alone-templates; must be lowercase
280 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
281 $wl_article = new Article ( $wl_title ) ;
282 $wl = explode ( "\n" , $wl_article->getContent() ) ;
283 foreach ( $wl AS $x )
287 while ( substr ( $x , 0 , 1 ) == '*' )
290 $x = trim ( substr ( $x , 1 ) ) ;
294 $sat[] = strtolower ( $x ) ;
299 # Templates, but only some
300 $t = explode ( '{{' , $t ) ;
302 foreach ( $t AS $key => $x )
304 $y = explode ( '}}' , $x , 2 ) ;
305 if ( count ( $y ) == 2 )
308 $z = explode ( '|' , $z ) ;
309 $tn = array_shift ( $z ) ;
310 if ( in_array ( strtolower ( $tn ) , $sat ) )
312 $tl[] = '{{' . $y[0] . '}}' ;
314 $y = explode ( '}}' , $y[1] , 2 ) ;
316 else $t[$key] = '{{' . $x ;
318 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
321 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
322 $t = implode ( '' , $t ) ;
324 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
325 $this->mArticle
->mContent
= $t ;
326 $this->mMetaData
= $s ;
329 protected function wasDeletedSinceLastEdit() {
330 /* Note that we rely on the logging table, which hasn't been always there,
331 * but that doesn't matter, because this only applies to brand new
334 if ( $this->deletedSinceEdit
)
336 if ( $this->mTitle
->isDeleted() ) {
337 $this->lastDelete
= $this->getLastDelete();
338 if ( !is_null($this->lastDelete
) ) {
339 $deletetime = $this->lastDelete
->log_timestamp
;
340 if ( ($deletetime - $this->starttime
) > 0 ) {
341 $this->deletedSinceEdit
= true;
345 return $this->deletedSinceEdit
;
353 * This is the function that gets called for "action=edit". It
354 * sets up various member variables, then passes execution to
355 * another function, usually showEditForm()
357 * The edit form is self-submitting, so that when things like
358 * preview and edit conflicts occur, we get the same form back
359 * with the extra stuff added. Only when the final submission
360 * is made and all is well do we actually save and redirect to
361 * the newly-edited page.
364 global $wgOut, $wgUser, $wgRequest;
366 if ( !wfRunHooks( 'AlternateEdit', array( &$this ) ) )
369 wfProfileIn( __METHOD__
);
370 wfDebug( __METHOD__
.": enter\n" );
372 // this is not an article
373 $wgOut->setArticleFlag(false);
375 $this->importFormData( $wgRequest );
376 $this->firsttime
= false;
379 $this->livePreview();
380 wfProfileOut( __METHOD__
);
384 $wgOut->addScriptFile( 'edit.js' );
387 $this->readOnlyPage( $this->getContent() );
388 wfProfileOut( __METHOD__
);
392 $permErrors = $this->mTitle
->getUserPermissionsErrors('edit', $wgUser);
394 if( !$this->mTitle
->exists() ) {
395 $permErrors = array_merge( $permErrors,
396 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors('create', $wgUser), $permErrors ) );
399 # Ignore some permissions errors.
401 foreach( $permErrors as $error ) {
402 if ( ( $this->preview ||
$this->diff
) &&
403 ($error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext'))
405 // Don't worry about blocks when previewing/diffing
409 if ($error[0] == 'readonlytext')
412 $this->formtype
= 'preview';
413 } elseif ($this->save ||
$this->preview ||
$this->diff
) {
418 $permErrors = wfArrayDiff2( $permErrors, $remove );
421 wfDebug( __METHOD__
.": User can't edit\n" );
422 $this->readOnlyPage( $this->getContent(), true, $permErrors, 'edit' );
423 wfProfileOut( __METHOD__
);
427 $this->formtype
= 'save';
428 } else if ( $this->preview
) {
429 $this->formtype
= 'preview';
430 } else if ( $this->diff
) {
431 $this->formtype
= 'diff';
432 } else { # First time through
433 $this->firsttime
= true;
434 if( $this->previewOnOpen() ) {
435 $this->formtype
= 'preview';
437 $this->extractMetaDataFromArticle () ;
438 $this->formtype
= 'initial';
443 wfProfileIn( __METHOD__
."-business-end" );
445 $this->isConflict
= false;
446 // css / js subpages of user pages get a special treatment
447 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
448 $this->isValidCssJsSubpage
= $this->mTitle
->isValidCssJsSubpage();
450 # Show applicable editing introductions
451 if( $this->formtype
== 'initial' ||
$this->firsttime
)
454 if( $this->mTitle
->isTalkPage() ) {
455 $wgOut->addWikiMsg( 'talkpagetext' );
458 # Optional notices on a per-namespace and per-page basis
459 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
460 $editnotice_page = $editnotice_ns.'-'.$this->mTitle
->getDBkey();
461 if ( !wfEmptyMsg( $editnotice_ns, wfMsgForContent( $editnotice_ns ) ) ) {
462 $wgOut->addWikiText( wfMsgForContent( $editnotice_ns ) );
464 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
465 $parts = explode( '/', $this->mTitle
->getDBkey() );
466 $editnotice_base = $editnotice_ns;
467 while ( count( $parts ) > 0 ) {
468 $editnotice_base .= '-'.array_shift( $parts );
469 if ( !wfEmptyMsg( $editnotice_base, wfMsgForContent( $editnotice_base ) ) ) {
470 $wgOut->addWikiText( wfMsgForContent( $editnotice_base ) );
473 } else if ( !wfEmptyMsg( $editnotice_page, wfMsgForContent( $editnotice_page ) ) ) {
474 $wgOut->addWikiText( wfMsgForContent( $editnotice_page ) );
477 # Attempt submission here. This will check for edit conflicts,
478 # and redundantly check for locked database, blocked IPs, etc.
479 # that edit() already checked just in case someone tries to sneak
480 # in the back door with a hand-edited submission URL.
482 if ( 'save' == $this->formtype
) {
483 if ( !$this->attemptSave() ) {
484 wfProfileOut( __METHOD__
."-business-end" );
485 wfProfileOut( __METHOD__
);
490 # First time through: get contents, set time for conflict
492 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
493 if ($this->initialiseForm() === false) {
494 $this->noSuchSectionPage();
495 wfProfileOut( __METHOD__
."-business-end" );
496 wfProfileOut( __METHOD__
);
499 if( !$this->mTitle
->getArticleId() )
500 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
503 $this->showEditForm();
504 wfProfileOut( __METHOD__
."-business-end" );
505 wfProfileOut( __METHOD__
);
509 * Show a read-only error
510 * Parameters are the same as OutputPage:readOnlyPage()
511 * Redirect to the article page if redlink=1
513 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
514 global $wgRequest, $wgOut;
515 if ( $wgRequest->getBool( 'redlink' ) ) {
516 // The edit page was reached via a red link.
517 // Redirect to the article page and let them click the edit tab if
518 // they really want a permission error.
519 $wgOut->redirect( $this->mTitle
->getFullUrl() );
521 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
526 * Should we show a preview when the edit form is first shown?
530 protected function previewOnOpen() {
531 global $wgRequest, $wgUser;
532 if( $wgRequest->getVal( 'preview' ) == 'yes' ) {
533 // Explicit override from request
535 } elseif( $wgRequest->getVal( 'preview' ) == 'no' ) {
536 // Explicit override from request
538 } elseif( $this->section
== 'new' ) {
539 // Nothing *to* preview for new sections
541 } elseif( ( $wgRequest->getVal( 'preload' ) !== '' ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
542 // Standard preference behaviour
544 } elseif( !$this->mTitle
->exists() && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
545 // Categories are special
556 function importFormData( &$request ) {
557 global $wgLang, $wgUser;
558 $fname = 'EditPage::importFormData';
559 wfProfileIn( $fname );
561 # Section edit can come from either the form or a link
562 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
564 if( $request->wasPosted() ) {
565 # These fields need to be checked for encoding.
566 # Also remove trailing whitespace, but don't remove _initial_
567 # whitespace from the text boxes. This may be significant formatting.
568 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
569 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
570 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
571 # Truncate for whole multibyte characters. +5 bytes for ellipsis
572 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
574 # Remove extra headings from summaries and new sections.
575 $this->summary
= preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
577 $this->edittime
= $request->getVal( 'wpEdittime' );
578 $this->starttime
= $request->getVal( 'wpStarttime' );
580 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
582 if( is_null( $this->edittime
) ) {
583 # If the form is incomplete, force to preview.
584 wfDebug( "$fname: Form data appears to be incomplete\n" );
585 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
586 $this->preview
= true;
588 /* Fallback for live preview */
589 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
590 $this->diff
= $request->getCheck( 'wpDiff' );
592 // Remember whether a save was requested, so we can indicate
593 // if we forced preview due to session failure.
594 $this->mTriedSave
= !$this->preview
;
596 if ( $this->tokenOk( $request ) ) {
597 # Some browsers will not report any submit button
598 # if the user hits enter in the comment box.
599 # The unmarked state will be assumed to be a save,
600 # if the form seems otherwise complete.
601 wfDebug( "$fname: Passed token check.\n" );
602 } else if ( $this->diff
) {
603 # Failed token check, but only requested "Show Changes".
604 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
606 # Page might be a hack attempt posted from
607 # an external site. Preview instead of saving.
608 wfDebug( "$fname: Failed token check; forcing preview\n" );
609 $this->preview
= true;
612 $this->save
= !$this->preview
&& !$this->diff
;
613 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
614 $this->edittime
= null;
617 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
618 $this->starttime
= null;
621 $this->recreate
= $request->getCheck( 'wpRecreate' );
623 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
624 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
626 # Don't force edit summaries when a user is editing their own user or talk page
627 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
628 $this->allowBlankSummary
= true;
630 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
633 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
635 # Not a posted form? Start with nothing.
636 wfDebug( "$fname: Not a posted form.\n" );
637 $this->textbox1
= '';
638 $this->textbox2
= '';
639 $this->mMetaData
= '';
641 $this->edittime
= '';
642 $this->starttime
= wfTimestampNow();
644 $this->preview
= false;
647 $this->minoredit
= false;
648 $this->watchthis
= false;
649 $this->recreate
= false;
651 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
652 $this->summary
= $request->getVal( 'preloadtitle' );
656 $this->oldid
= $request->getInt( 'oldid' );
658 $this->live
= $request->getCheck( 'live' );
659 $this->editintro
= $request->getText( 'editintro' );
661 wfProfileOut( $fname );
665 * Make sure the form isn't faking a user's credentials.
667 * @param $request WebRequest
671 function tokenOk( &$request ) {
673 $token = $request->getVal( 'wpEditToken' );
674 $this->mTokenOk
= $wgUser->matchEditToken( $token );
675 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
676 return $this->mTokenOk
;
680 * Show all applicable editing introductions
682 protected function showIntro() {
683 global $wgOut, $wgUser;
684 if( $this->suppressIntro
)
687 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
688 if( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
689 $parts = explode( '/', $this->mTitle
->getText(), 2 );
690 $username = $parts[0];
691 $id = User
::idFromName( $username );
692 $ip = User
::isIP( $username );
694 if ( $id == 0 && !$ip ) {
695 $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
696 array( 'userpage-userdoesnotexist', $username ) );
700 if( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
701 if( $wgUser->isLoggedIn() ) {
702 $wgOut->wrapWikiMsg( '<div class="mw-newarticletext">$1</div>', 'newarticletext' );
704 $wgOut->wrapWikiMsg( '<div class="mw-newarticletextanon">$1</div>', 'newarticletextanon' );
706 $this->showDeletionLog( $wgOut );
711 * Attempt to show a custom editing introduction, if supplied
715 protected function showCustomIntro() {
716 if( $this->editintro
) {
717 $title = Title
::newFromText( $this->editintro
);
718 if( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
720 $revision = Revision
::newFromTitle( $title );
721 $wgOut->addWikiTextTitleTidy( $revision->getText(), $this->mTitle
);
732 * Attempt submission (no UI)
733 * @return one of the constants describing the result
735 function internalAttemptSave( &$result, $bot = false ) {
736 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut, $wgParser;
737 global $wgMaxArticleSize;
739 $fname = 'EditPage::attemptSave';
740 wfProfileIn( $fname );
741 wfProfileIn( "$fname-checks" );
743 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
745 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
746 return self
::AS_HOOK_ERROR
;
749 # Check image redirect
750 if ( $this->mTitle
->getNamespace() == NS_IMAGE
&&
751 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
752 !$wgUser->isAllowed( 'upload' ) ) {
753 if( $wgUser->isAnon() ) {
754 return self
::AS_IMAGE_REDIRECT_ANON
;
756 return self
::AS_IMAGE_REDIRECT_LOGGED
;
760 # Reintegrate metadata
761 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
762 $this->mMetaData
= '' ;
766 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
767 $result['spam'] = $matches[0];
769 $pdbk = $this->mTitle
->getPrefixedDBkey();
770 $match = str_replace( "\n", '', $matches[0] );
771 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
772 wfProfileOut( "$fname-checks" );
773 wfProfileOut( $fname );
774 return self
::AS_SPAM_ERROR
;
776 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
777 # Error messages or other handling should be performed by the filter function
778 wfProfileOut( "$fname-checks" );
779 wfProfileOut( $fname );
780 return self
::AS_FILTERING
;
782 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
783 # Error messages etc. could be handled within the hook...
784 wfProfileOut( "$fname-checks" );
785 wfProfileOut( $fname );
786 return self
::AS_HOOK_ERROR
;
787 } elseif( $this->hookError
!= '' ) {
788 # ...or the hook could be expecting us to produce an error
789 wfProfileOut( "$fname-checks" );
790 wfProfileOut( $fname );
791 return self
::AS_HOOK_ERROR_EXPECTED
;
793 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
794 # Check block state against master, thus 'false'.
795 wfProfileOut( "$fname-checks" );
796 wfProfileOut( $fname );
797 return self
::AS_BLOCKED_PAGE_FOR_USER
;
799 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
800 if ( $this->kblength
> $wgMaxArticleSize ) {
801 // Error will be displayed by showEditForm()
802 $this->tooBig
= true;
803 wfProfileOut( "$fname-checks" );
804 wfProfileOut( $fname );
805 return self
::AS_CONTENT_TOO_BIG
;
808 if ( !$wgUser->isAllowed('edit') ) {
809 if ( $wgUser->isAnon() ) {
810 wfProfileOut( "$fname-checks" );
811 wfProfileOut( $fname );
812 return self
::AS_READ_ONLY_PAGE_ANON
;
815 wfProfileOut( "$fname-checks" );
816 wfProfileOut( $fname );
817 return self
::AS_READ_ONLY_PAGE_LOGGED
;
821 if ( wfReadOnly() ) {
822 wfProfileOut( "$fname-checks" );
823 wfProfileOut( $fname );
824 return self
::AS_READ_ONLY_PAGE
;
826 if ( $wgUser->pingLimiter() ) {
827 wfProfileOut( "$fname-checks" );
828 wfProfileOut( $fname );
829 return self
::AS_RATE_LIMITED
;
832 # If the article has been deleted while editing, don't save it without
834 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
835 wfProfileOut( "$fname-checks" );
836 wfProfileOut( $fname );
837 return self
::AS_ARTICLE_WAS_DELETED
;
840 wfProfileOut( "$fname-checks" );
842 # If article is new, insert it.
843 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
846 // Late check for create permission, just in case *PARANOIA*
847 if ( !$this->mTitle
->userCan( 'create' ) ) {
848 wfDebug( "$fname: no create permission\n" );
849 wfProfileOut( $fname );
850 return self
::AS_NO_CREATE_PERMISSION
;
853 # Don't save a new article if it's blank.
854 if ( '' == $this->textbox1
) {
855 wfProfileOut( $fname );
856 return self
::AS_BLANK_ARTICLE
;
859 // Run post-section-merge edit filter
860 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
861 # Error messages etc. could be handled within the hook...
862 wfProfileOut( $fname );
863 return self
::AS_HOOK_ERROR
;
866 $isComment = ( $this->section
== 'new' );
868 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
869 $this->minoredit
, $this->watchthis
, false, $isComment, $bot);
871 wfProfileOut( $fname );
872 return self
::AS_SUCCESS_NEW_ARTICLE
;
875 # Article exists. Check for edit conflict.
877 $this->mArticle
->clear(); # Force reload of dates, etc.
878 $this->mArticle
->forUpdate( true ); # Lock the article
880 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
882 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
883 $this->isConflict
= true;
884 if( $this->section
== 'new' ) {
885 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
886 $this->mArticle
->getComment() == $this->summary
) {
887 // Probably a duplicate submission of a new comment.
888 // This can happen when squid resends a request after
889 // a timeout but the first one actually went through.
890 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
892 // New comment; suppress conflict.
893 $this->isConflict
= false;
894 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
898 $userid = $wgUser->getId();
900 if ( $this->isConflict
) {
901 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
902 $this->mArticle
->getTimestamp() . "')\n" );
903 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
906 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
907 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
909 if( is_null( $text ) ) {
910 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
911 $this->isConflict
= true;
912 $text = $this->textbox1
;
915 # Suppress edit conflict with self, except for section edits where merging is required.
916 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
917 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
918 $this->isConflict
= false;
920 # switch from section editing to normal editing in edit conflict
921 if($this->isConflict
) {
923 if( $this->mergeChangesInto( $text ) ){
924 // Successful merge! Maybe we should tell the user the good news?
925 $this->isConflict
= false;
926 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
929 $this->textbox1
= $text;
930 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
935 if ( $this->isConflict
) {
936 wfProfileOut( $fname );
937 return self
::AS_CONFLICT_DETECTED
;
940 $oldtext = $this->mArticle
->getContent();
942 // Run post-section-merge edit filter
943 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
944 # Error messages etc. could be handled within the hook...
945 wfProfileOut( $fname );
946 return self
::AS_HOOK_ERROR
;
949 # Handle the user preference to force summaries here, but not for null edits
950 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary') &&
951 0 != strcmp($oldtext, $text) &&
952 !is_object( Title
::newFromRedirect( $text ) ) # check if it's not a redirect
955 if( md5( $this->summary
) == $this->autoSumm
) {
956 $this->missingSummary
= true;
957 wfProfileOut( $fname );
958 return self
::AS_SUMMARY_NEEDED
;
962 # And a similar thing for new sections
963 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
964 if (trim($this->summary
) == '') {
965 $this->missingSummary
= true;
966 wfProfileOut( $fname );
967 return self
::AS_SUMMARY_NEEDED
;
972 wfProfileIn( "$fname-sectionanchor" );
974 if( $this->section
== 'new' ) {
975 if ( $this->textbox1
== '' ) {
976 $this->missingComment
= true;
977 return self
::AS_TEXTBOX_EMPTY
;
979 if( $this->summary
!= '' ) {
980 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary
);
981 # This is a new section, so create a link to the new section
982 # in the revision summary.
983 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
984 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
986 } elseif( $this->section
!= '' ) {
987 # Try to get a section anchor from the section source, redirect to edited section if header found
988 # XXX: might be better to integrate this into Article::replaceSection
989 # for duplicate heading checking and maybe parsing
990 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
991 # we can't deal with anchors, includes, html etc in the header for now,
992 # headline would need to be parsed to improve this
993 if($hasmatch and strlen($matches[2]) > 0) {
994 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
997 wfProfileOut( "$fname-sectionanchor" );
999 // Save errors may fall down to the edit form, but we've now
1000 // merged the section into full text. Clear the section field
1001 // so that later submission of conflict forms won't try to
1002 // replace that into a duplicated mess.
1003 $this->textbox1
= $text;
1004 $this->section
= '';
1006 // Check for length errors again now that the section is merged in
1007 $this->kblength
= (int)(strlen( $text ) / 1024);
1008 if ( $this->kblength
> $wgMaxArticleSize ) {
1009 $this->tooBig
= true;
1010 wfProfileOut( $fname );
1011 return self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
;
1014 # update the article here
1015 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
1016 $this->watchthis
, $bot, $sectionanchor ) ) {
1017 wfProfileOut( $fname );
1018 return self
::AS_SUCCESS_UPDATE
;
1020 $this->isConflict
= true;
1022 wfProfileOut( $fname );
1023 return self
::AS_END
;
1027 * Initialise form fields in the object
1028 * Called on the first invocation, e.g. when a user clicks an edit link
1030 function initialiseForm() {
1031 $this->edittime
= $this->mArticle
->getTimestamp();
1032 $this->textbox1
= $this->getContent(false);
1033 if ($this->textbox1
=== false) return false;
1035 if ( !$this->mArticle
->exists() && $this->mTitle
->getNamespace() == NS_MEDIAWIKI
)
1036 $this->textbox1
= wfMsgWeirdKey( $this->mTitle
->getText() );
1042 * Send the edit form and related headers to $wgOut
1043 * @param $formCallback Optional callable that takes an OutputPage
1044 * parameter; will be called during form output
1045 * near the top, for captchas and the like.
1047 function showEditForm( $formCallback=null ) {
1048 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle;
1050 # If $wgTitle is null, that means we're in API mode.
1051 # Some hook probably called this function without checking
1052 # for is_null($wgTitle) first. Bail out right here so we don't
1053 # do lots of work just to discard it right after.
1054 if(is_null($wgTitle))
1057 $fname = 'EditPage::showEditForm';
1058 wfProfileIn( $fname );
1060 $sk = $wgUser->getSkin();
1062 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
1064 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1066 # Enabled article-related sidebar, toplinks, etc.
1067 $wgOut->setArticleRelated( true );
1069 if ( $this->formtype
== 'preview' ) {
1070 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1073 if ( $this->isConflict
) {
1074 $s = wfMsg( 'editconflict', $wgTitle->getPrefixedText() );
1075 $wgOut->setPageTitle( $s );
1076 $wgOut->addWikiMsg( 'explainconflict' );
1078 $this->textbox2
= $this->textbox1
;
1079 $this->textbox1
= $this->getContent();
1080 $this->edittime
= $this->mArticle
->getTimestamp();
1082 if( $this->section
!= '' ) {
1083 if( $this->section
== 'new' ) {
1084 $s = wfMsg('editingcomment', $wgTitle->getPrefixedText() );
1086 $s = wfMsg('editingsection', $wgTitle->getPrefixedText() );
1088 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1089 preg_match( "/^(=+)(.+)\\1/mi",
1092 if( !empty( $matches[2] ) ) {
1094 $this->summary
= "/* " .
1095 $wgParser->stripSectionName(trim($matches[2])) .
1101 $s = wfMsg( 'editing', $wgTitle->getPrefixedText() );
1103 $wgOut->setPageTitle( $s );
1105 if ( $this->missingComment
) {
1106 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1109 if( $this->missingSummary
&& $this->section
!= 'new' ) {
1110 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1113 if( $this->missingSummary
&& $this->section
== 'new' ) {
1114 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1117 if( $this->hookError
!== '' ) {
1118 $wgOut->addWikiText( $this->hookError
);
1121 if ( !$this->checkUnicodeCompliantBrowser() ) {
1122 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1124 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1125 // Let sysop know that this will make private content public if saved
1127 if( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1128 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
1129 } else if( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1130 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
1133 if( !$this->mArticle
->mRevision
->isCurrent() ) {
1134 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1135 $wgOut->addWikiMsg( 'editingold' );
1140 if( wfReadOnly() ) {
1141 $wgOut->addHTML( '<div id="mw-read-only-warning">'.wfMsgWikiHTML( 'readonlywarning' ).'</div>' );
1142 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
1143 $wgOut->addHTML( '<div id="mw-anon-edit-warning">'.wfMsgWikiHTML( 'anoneditwarning' ).'</div>' );
1145 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
1146 # Check the skin exists
1147 if( $this->isValidCssJsSubpage
) {
1148 $wgOut->addWikiMsg( 'usercssjsyoucanpreview' );
1150 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1155 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1156 # Show a warning if editing an interface message
1157 $wgOut->addWikiMsg( 'editinginterface' );
1158 } elseif( $this->mTitle
->isProtected( 'edit' ) ) {
1159 # Is the title semi-protected?
1160 if( $this->mTitle
->isSemiProtected() ) {
1161 $noticeMsg = 'semiprotectedpagewarning';
1163 # Then it must be protected based on static groups (regular)
1164 $noticeMsg = 'protectedpagewarning';
1166 $wgOut->addHTML( "<div id='mw-edit-$noticeMsg'>\n" );
1167 $wgOut->addWikiMsg( $noticeMsg );
1168 $wgOut->addHTML( "</div>\n" );
1170 if ( $this->mTitle
->isCascadeProtected() ) {
1171 # Is this page under cascading protection from some source pages?
1172 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1174 if ( count($cascadeSources) > 0 ) {
1175 # Explain, and list the titles responsible
1176 foreach( $cascadeSources as $page ) {
1177 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1180 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', count($cascadeSources) ) );
1182 if( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) != array() ){
1183 $wgOut->addWikiMsg( 'titleprotectedwarning' );
1186 if ( $this->kblength
=== false ) {
1187 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1189 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1190 $wgOut->addHTML( "<div id='mw-edit-longpageerror'>\n" );
1191 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) );
1192 $wgOut->addHTML( "</div>\n" );
1193 } elseif( $this->kblength
> 29 ) {
1194 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1195 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) );
1196 $wgOut->addHTML( "</div>\n" );
1199 #need to parse the preview early so that we know which templates are used,
1200 #otherwise users with "show preview after edit box" will get a blank list
1201 if ( $this->formtype
== 'preview' ) {
1202 $previewOutput = $this->getPreviewText();
1205 $rows = $wgUser->getIntOption( 'rows' );
1206 $cols = $wgUser->getIntOption( 'cols' );
1208 $ew = $wgUser->getOption( 'editwidth' );
1209 if ( $ew ) $ew = " style=\"width:100%\"";
1212 $q = 'action=submit';
1213 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1214 $action = $wgTitle->escapeLocalURL( $q );
1216 $summary = wfMsg('summary');
1217 $subject = wfMsg('subject');
1219 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedText(),
1220 wfMsgExt('cancel', array('parseinline')) );
1221 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1222 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1223 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1224 htmlspecialchars( wfMsg( 'newwindow' ) );
1226 global $wgRightsText;
1227 if ( $wgRightsText ) {
1228 $copywarnMsg = array( 'copyrightwarning',
1229 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1232 $copywarnMsg = array( 'copyrightwarning2',
1233 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1236 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1237 # prepare toolbar for edit buttons
1238 $toolbar = EditPage
::getEditToolbar();
1243 // activate checkboxes if user wants them to be always active
1244 if( !$this->preview
&& !$this->diff
) {
1245 # Sort out the "watch" checkbox
1246 if( $wgUser->getOption( 'watchdefault' ) ) {
1248 $this->watchthis
= true;
1249 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1251 $this->watchthis
= true;
1252 } elseif( $this->mTitle
->userIsWatching() ) {
1254 $this->watchthis
= true;
1257 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1260 $wgOut->addHTML( $this->editFormPageTop
);
1262 if ( $wgUser->getOption( 'previewontop' ) ) {
1264 if ( 'preview' == $this->formtype
) {
1265 $this->showPreview( $previewOutput );
1267 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1270 if ( 'diff' == $this->formtype
) {
1276 $wgOut->addHTML( $this->editFormTextTop
);
1278 # if this is a comment, show a subject line at the top, which is also the edit summary.
1279 # Otherwise, show a summary field at the bottom
1280 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1282 # If a blank edit summary was previously provided, and the appropriate
1283 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1284 # user being bounced back more than once in the event that a summary
1287 # For a bit more sophisticated detection of blank summaries, hash the
1288 # automatic one and pass that in the hidden field wpAutoSummary.
1289 $summaryhiddens = '';
1290 if( $this->missingSummary
) $summaryhiddens .= Xml
::hidden( 'wpIgnoreBlankSummary', true );
1291 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1292 $summaryhiddens .= Xml
::hidden( 'wpAutoSummary', $autosumm );
1293 if( $this->section
== 'new' ) {
1294 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span>\n<input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' />{$summaryhiddens}<br />";
1295 $editsummary = "<div class='editOptions'>\n";
1297 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary
) );
1298 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $formattedSummary, $this->mTitle
, true )."</div>\n" : '';
1299 $summarypreview = '';
1301 $commentsubject = '';
1302 $editsummary="<div class='editOptions'>\n<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span>\n<input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' />{$summaryhiddens}<br />";
1303 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1304 $subjectpreview = '';
1307 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1308 if( !$this->preview
&& !$this->diff
) {
1309 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1311 $templates = ($this->preview ||
$this->section
!= '') ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1312 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1314 $hiddencats = $this->mArticle
->getHiddenCategories();
1315 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1317 global $wgUseMetadataEdit ;
1318 if ( $wgUseMetadataEdit ) {
1319 $metadata = $this->mMetaData
;
1320 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1321 $top = wfMsgWikiHtml( 'metadata_help' );
1322 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1324 else $metadata = "" ;
1328 if ($this->wasDeletedSinceLastEdit()) {
1329 if ( 'save' != $this->formtype
) {
1330 $wgOut->addWikiMsg('deletedwhileediting');
1332 // Hide the toolbar and edit area, use can click preview to get it back
1333 // Add an confirmation checkbox and explanation.
1335 $hidden = 'type="hidden" style="display:none;"';
1336 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1338 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1339 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1345 $checkboxes = self
::getCheckboxes( $tabindex, $sk,
1346 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1348 $checkboxhtml = implode( $checkboxes, "\n" );
1350 $buttons = $this->getEditButtons( $tabindex );
1351 $buttonshtml = implode( $buttons, "\n" );
1353 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1354 ?
'' : Xml
::hidden( 'safemode', '1' );
1356 $wgOut->addHTML( <<<END
1358 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1362 if( is_callable( $formCallback ) ) {
1363 call_user_func_array( $formCallback, array( &$wgOut ) );
1366 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1368 // Put these up at the top to ensure they aren't lost on early form submission
1370 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1371 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1372 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1373 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1375 $encodedtext = htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) );
1376 if( $encodedtext !== '' ) {
1377 // Ensure there's a newline at the end, otherwise adding lines
1379 // But don't add a newline if the ext is empty, or Firefox in XHTML
1380 // mode will show an extra newline. A bit annoying.
1381 $encodedtext .= "\n";
1384 $wgOut->addHTML( <<<END
1388 {$this->editFormTextBeforeContent}
1389 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1390 cols='{$cols}'{$ew} $hidden>{$encodedtext}</textarea>
1394 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1395 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1405 "<div class='editButtons'>
1407 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1408 </div><!-- editButtons -->
1409 </div><!-- editOptions -->");
1412 * To make it harder for someone to slip a user a page
1413 * which submits an edit form to the wiki without their
1414 * knowledge, a random token is associated with the login
1415 * session. If it's not passed back with the submission,
1416 * we won't save the page, or render user JavaScript and
1419 * For anon editors, who may not have a session, we just
1420 * include the constant suffix to prevent editing from
1421 * broken text-mangling proxies.
1423 $token = htmlspecialchars( $wgUser->editToken() );
1424 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1426 $wgOut->addHtml( '<div class="mw-editTools">' );
1427 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1428 $wgOut->addHtml( '</div>' );
1430 $wgOut->addHTML( $this->editFormTextAfterTools
);
1433 <div class='templatesUsed'>
1434 {$formattedtemplates}
1436 <div class='hiddencats'>
1437 {$formattedhiddencats}
1441 if ( $this->isConflict
&& wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1442 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1444 $de = new DifferenceEngine( $this->mTitle
);
1445 $de->setText( $this->textbox2
, $this->textbox1
);
1446 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1448 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1449 $wgOut->addHTML( "<textarea tabindex='6' id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}'>"
1450 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1452 $wgOut->addHTML( $this->editFormTextBottom
);
1453 $wgOut->addHTML( "</form>\n" );
1454 if ( !$wgUser->getOption( 'previewontop' ) ) {
1456 if ( $this->formtype
== 'preview') {
1457 $this->showPreview( $previewOutput );
1459 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1462 if ( $this->formtype
== 'diff') {
1468 wfProfileOut( $fname );
1472 * Append preview output to $wgOut.
1473 * Includes category rendering if this is a category page.
1475 * @param string $text The HTML to be output for the preview.
1477 protected function showPreview( $text ) {
1480 $wgOut->addHTML( '<div id="wikiPreview">' );
1481 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1482 $this->mArticle
->openShowCategory();
1484 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1485 $wgOut->addHTML( $text );
1486 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1487 $this->mArticle
->closeShowCategory();
1489 $wgOut->addHTML( '</div>' );
1493 * Live Preview lets us fetch rendered preview page content and
1494 * add it to the page without refreshing the whole page.
1495 * If not supported by the browser it will fall through to the normal form
1496 * submission method.
1498 * This function outputs a script tag to support live preview, and
1499 * returns an onclick handler which should be added to the attributes
1500 * of the preview button
1502 function doLivePreviewScript() {
1503 global $wgOut, $wgTitle;
1504 $wgOut->addScriptFile( 'preview.js' );
1505 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1506 return "return !lpDoPreview(" .
1507 "editform.wpTextbox1.value," .
1508 '"' . $liveAction . '"' . ")";
1511 function getLastDelete() {
1512 $dbr = wfGetDB( DB_SLAVE
);
1513 $fname = 'EditPage::getLastDelete';
1514 $res = $dbr->select(
1515 array( 'logging', 'user' ),
1525 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1526 'log_title' => $this->mTitle
->getDBkey(),
1527 'log_type' => 'delete',
1528 'log_action' => 'delete',
1529 'user_id=log_user' ),
1531 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1533 if($dbr->numRows($res) == 1) {
1534 while ( $x = $dbr->fetchObject ( $res ) )
1536 $dbr->freeResult ( $res ) ;
1544 * Get the rendered text for previewing.
1547 function getPreviewText() {
1548 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang;
1550 $fname = 'EditPage::getPreviewText';
1551 wfProfileIn( $fname );
1553 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1554 if ( $this->mTokenOkExceptSuffix
) {
1555 $note = wfMsg( 'token_suffix_mismatch' );
1557 $note = wfMsg( 'session_fail_preview' );
1560 $note = wfMsg( 'previewnote' );
1563 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1564 $parserOptions->setEditSection( false );
1567 if( $wgRawHtml && !$this->mTokenOk
) {
1568 // Could be an offsite preview attempt. This is very unsafe if
1569 // HTML is enabled, as it could be an attack.
1570 return $wgOut->parse( "<div class='previewnote'>" .
1571 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1574 # don't parse user css/js, show message about preview
1575 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1577 if ( $this->isCssJsSubpage
) {
1578 if(preg_match("/\\.css$/", $this->mTitle
->getText() ) ) {
1579 $previewtext = wfMsg('usercsspreview');
1580 } else if(preg_match("/\\.js$/", $this->mTitle
->getText() ) ) {
1581 $previewtext = wfMsg('userjspreview');
1583 $parserOptions->setTidy(true);
1584 $parserOutput = $wgParser->parse( $previewtext , $this->mTitle
, $parserOptions );
1585 $wgOut->addHTML( $parserOutput->mText
);
1587 } else if( $rt = Title
::newFromRedirect( $this->textbox1
) ) {
1588 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
1590 $toparse = $this->textbox1
;
1592 # If we're adding a comment, we need to show the
1593 # summary as the headline
1594 if($this->section
=="new" && $this->summary
!="") {
1595 $toparse="== {$this->summary} ==\n\n".$toparse;
1598 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1600 // Parse mediawiki messages with correct target language
1601 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1602 $pos = strrpos( $this->mTitle
->getText(), '/' );
1603 if ( $pos !== false ) {
1604 $code = substr( $this->mTitle
->getText(), $pos+
1 );
1606 case $wgLang->getCode():
1607 $obj = $wgLang; break;
1608 case $wgContLang->getCode():
1609 $obj = $wgContLang; break;
1611 $obj = Language
::factory( $code );
1613 $parserOptions->setTargetLanguage( $obj );
1618 $parserOptions->setTidy(true);
1619 $parserOptions->enableLimitReport();
1620 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ),
1621 $this->mTitle
, $parserOptions );
1623 $previewHTML = $parserOutput->getText();
1624 $wgOut->addParserOutputNoText( $parserOutput );
1626 # ParserOutput might have altered the page title, so reset it
1627 # Also, use the title defined by DISPLAYTITLE magic word when present
1628 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false ) {
1629 $wgOut->setPageTitle( wfMsg( 'editing', $dt ) );
1631 $wgOut->setPageTitle( wfMsg( 'editing', $wgTitle->getPrefixedText() ) );
1634 foreach ( $parserOutput->getTemplates() as $ns => $template)
1635 foreach ( array_keys( $template ) as $dbk)
1636 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1638 if ( count( $parserOutput->getWarnings() ) ) {
1639 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1643 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1644 "<div class='previewnote'>" . $wgOut->parse( $note ) . "</div>\n";
1645 if ( $this->isConflict
) {
1646 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1649 if( $wgUser->getOption( 'previewontop' ) ) {
1650 // Spacer for the edit toolbar
1651 $previewfoot = '<p><br /></p>';
1656 wfProfileOut( $fname );
1657 return $previewhead . $previewHTML . $previewfoot;
1661 * Call the stock "user is blocked" page
1663 function blockedPage() {
1664 global $wgOut, $wgUser;
1665 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1667 # If the user made changes, preserve them when showing the markup
1668 # (This happens when a user is blocked during edit, for instance)
1669 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1671 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1673 $source = $this->textbox1
;
1676 # Spit out the source or the user's modified version
1677 if( $source !== false ) {
1678 $rows = $wgUser->getOption( 'rows' );
1679 $cols = $wgUser->getOption( 'cols' );
1680 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1681 $wgOut->addHtml( '<hr />' );
1682 $wgOut->addWikiMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() );
1683 # Why we don't use Xml::element here?
1684 # Is it because if $source is '', it returns <textarea />?
1685 $wgOut->addHtml( Xml
::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml
::closeElement( 'textarea' ) );
1690 * Produce the stock "please login to edit pages" page
1692 function userNotLoggedInPage() {
1693 global $wgUser, $wgOut, $wgTitle;
1694 $skin = $wgUser->getSkin();
1696 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1697 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1699 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1700 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1701 $wgOut->setArticleRelated( false );
1703 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1704 $wgOut->returnToMain( false, $wgTitle );
1708 * Creates a basic error page which informs the user that
1709 * they have attempted to edit a nonexistant section.
1711 function noSuchSectionPage() {
1712 global $wgOut, $wgTitle;
1714 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1715 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1716 $wgOut->setArticleRelated( false );
1718 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section
);
1719 $wgOut->returnToMain( false, $wgTitle );
1723 * Produce the stock "your edit contains spam" page
1725 * @param $match Text which triggered one or more filters
1727 function spamPage( $match = false ) {
1728 global $wgOut, $wgTitle;
1730 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1731 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1732 $wgOut->setArticleRelated( false );
1734 $wgOut->addHtml( '<div id="spamprotected">' );
1735 $wgOut->addWikiMsg( 'spamprotectiontext' );
1737 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1738 $wgOut->addHtml( '</div>' );
1740 $wgOut->returnToMain( false, $wgTitle );
1747 function mergeChangesInto( &$editText ){
1748 $fname = 'EditPage::mergeChangesInto';
1749 wfProfileIn( $fname );
1751 $db = wfGetDB( DB_MASTER
);
1753 // This is the revision the editor started from
1754 $baseRevision = $this->getBaseRevision();
1755 if( is_null( $baseRevision ) ) {
1756 wfProfileOut( $fname );
1759 $baseText = $baseRevision->getText();
1761 // The current state, we want to merge updates into it
1762 $currentRevision = Revision
::loadFromTitle(
1763 $db, $this->mTitle
);
1764 if( is_null( $currentRevision ) ) {
1765 wfProfileOut( $fname );
1768 $currentText = $currentRevision->getText();
1771 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1772 $editText = $result;
1773 wfProfileOut( $fname );
1776 wfProfileOut( $fname );
1782 * Check if the browser is on a blacklist of user-agents known to
1783 * mangle UTF-8 data on form submission. Returns true if Unicode
1784 * should make it through, false if it's known to be a problem.
1788 function checkUnicodeCompliantBrowser() {
1789 global $wgBrowserBlackList;
1790 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1791 // No User-Agent header sent? Trust it by default...
1794 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1795 foreach ( $wgBrowserBlackList as $browser ) {
1796 if ( preg_match($browser, $currentbrowser) ) {
1804 * @deprecated use $wgParser->stripSectionName()
1806 function pseudoParseSectionAnchor( $text ) {
1808 return $wgParser->stripSectionName( $text );
1812 * Format an anchor fragment as it would appear for a given section name
1813 * @param string $text
1817 function sectionAnchor( $text ) {
1819 return $wgParser->guessSectionNameFromWikiText( $text );
1823 * Shows a bulletin board style toolbar for common editing functions.
1824 * It can be disabled in the user preferences.
1825 * The necessary JavaScript code can be found in skins/common/edit.js.
1829 static function getEditToolbar() {
1830 global $wgStylePath, $wgContLang, $wgLang, $wgJsMimeType;
1833 * toolarray an array of arrays which each include the filename of
1834 * the button image (without path), the opening tag, the closing tag,
1835 * and optionally a sample text that is inserted between the two when no
1836 * selection is highlighted.
1837 * The tip text is shown when the user moves the mouse over the button.
1839 * Already here are accesskeys (key), which are not used yet until someone
1840 * can figure out a way to make them work in IE. However, we should make
1841 * sure these keys are not defined on the edit page.
1845 'image' => $wgLang->getImageFile('button-bold'),
1846 'id' => 'mw-editbutton-bold',
1848 'close' => '\'\'\'',
1849 'sample' => wfMsg('bold_sample'),
1850 'tip' => wfMsg('bold_tip'),
1854 'image' => $wgLang->getImageFile('button-italic'),
1855 'id' => 'mw-editbutton-italic',
1858 'sample' => wfMsg('italic_sample'),
1859 'tip' => wfMsg('italic_tip'),
1863 'image' => $wgLang->getImageFile('button-link'),
1864 'id' => 'mw-editbutton-link',
1867 'sample' => wfMsg('link_sample'),
1868 'tip' => wfMsg('link_tip'),
1872 'image' => $wgLang->getImageFile('button-extlink'),
1873 'id' => 'mw-editbutton-extlink',
1876 'sample' => wfMsg('extlink_sample'),
1877 'tip' => wfMsg('extlink_tip'),
1881 'image' => $wgLang->getImageFile('button-headline'),
1882 'id' => 'mw-editbutton-headline',
1885 'sample' => wfMsg('headline_sample'),
1886 'tip' => wfMsg('headline_tip'),
1890 'image' => $wgLang->getImageFile('button-image'),
1891 'id' => 'mw-editbutton-image',
1892 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).':',
1894 'sample' => wfMsg('image_sample'),
1895 'tip' => wfMsg('image_tip'),
1899 'image' => $wgLang->getImageFile('button-media'),
1900 'id' => 'mw-editbutton-media',
1901 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1903 'sample' => wfMsg('media_sample'),
1904 'tip' => wfMsg('media_tip'),
1908 'image' => $wgLang->getImageFile('button-math'),
1909 'id' => 'mw-editbutton-math',
1911 'close' => "</math>",
1912 'sample' => wfMsg('math_sample'),
1913 'tip' => wfMsg('math_tip'),
1917 'image' => $wgLang->getImageFile('button-nowiki'),
1918 'id' => 'mw-editbutton-nowiki',
1919 'open' => "<nowiki>",
1920 'close' => "</nowiki>",
1921 'sample' => wfMsg('nowiki_sample'),
1922 'tip' => wfMsg('nowiki_tip'),
1926 'image' => $wgLang->getImageFile('button-sig'),
1927 'id' => 'mw-editbutton-signature',
1931 'tip' => wfMsg('sig_tip'),
1935 'image' => $wgLang->getImageFile('button-hr'),
1936 'id' => 'mw-editbutton-hr',
1937 'open' => "\n----\n",
1940 'tip' => wfMsg('hr_tip'),
1944 $toolbar = "<div id='toolbar'>\n";
1945 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1947 foreach($toolarray as $tool) {
1949 $image = $wgStylePath.'/common/images/'.$tool['image'],
1950 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1951 // Older browsers show a "speedtip" type message only for ALT.
1952 // Ideally these should be different, realistically they
1953 // probably don't need to be.
1954 $tip = $tool['tip'],
1955 $open = $tool['open'],
1956 $close = $tool['close'],
1957 $sample = $tool['sample'],
1958 $cssId = $tool['id'],
1961 $paramList = implode( ',',
1962 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
1963 $toolbar.="addButton($paramList);\n";
1966 $toolbar.="/*]]>*/\n</script>";
1967 $toolbar.="\n</div>";
1972 * Returns an array of html code of the following checkboxes:
1975 * @param $tabindex Current tabindex
1976 * @param $skin Skin object
1977 * @param $checked Array of checkbox => bool, where bool indicates the checked
1978 * status of the checkbox
1982 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1985 $checkboxes = array();
1987 $checkboxes['minor'] = '';
1988 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1989 if ( $wgUser->isAllowed('minoredit') ) {
1991 'tabindex' => ++
$tabindex,
1992 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1993 'id' => 'wpMinoredit',
1995 $checkboxes['minor'] =
1996 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1997 " <label for='wpMinoredit'".$skin->tooltip('minoredit').">{$minorLabel}</label>";
2000 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2001 $checkboxes['watch'] = '';
2002 if ( $wgUser->isLoggedIn() ) {
2004 'tabindex' => ++
$tabindex,
2005 'accesskey' => wfMsg( 'accesskey-watch' ),
2006 'id' => 'wpWatchthis',
2008 $checkboxes['watch'] =
2009 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2010 " <label for='wpWatchthis'".$skin->tooltip('watch').">{$watchLabel}</label>";
2016 * Returns an array of html code of the following buttons:
2017 * save, diff, preview and live
2019 * @param $tabindex Current tabindex
2023 public function getEditButtons(&$tabindex) {
2024 global $wgLivePreview, $wgUser;
2032 'tabindex' => ++
$tabindex,
2033 'value' => wfMsg('savearticle'),
2034 'accesskey' => wfMsg('accesskey-save'),
2035 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2037 $buttons['save'] = Xml
::element('input', $temp, '');
2039 ++
$tabindex; // use the same for preview and live preview
2040 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2042 'id' => 'wpPreview',
2043 'name' => 'wpPreview',
2045 'tabindex' => $tabindex,
2046 'value' => wfMsg('showpreview'),
2048 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2049 'style' => 'display: none;',
2051 $buttons['preview'] = Xml
::element('input', $temp, '');
2054 'id' => 'wpLivePreview',
2055 'name' => 'wpLivePreview',
2057 'tabindex' => $tabindex,
2058 'value' => wfMsg('showlivepreview'),
2059 'accesskey' => wfMsg('accesskey-preview'),
2061 'onclick' => $this->doLivePreviewScript(),
2063 $buttons['live'] = Xml
::element('input', $temp, '');
2066 'id' => 'wpPreview',
2067 'name' => 'wpPreview',
2069 'tabindex' => $tabindex,
2070 'value' => wfMsg('showpreview'),
2071 'accesskey' => wfMsg('accesskey-preview'),
2072 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2074 $buttons['preview'] = Xml
::element('input', $temp, '');
2075 $buttons['live'] = '';
2082 'tabindex' => ++
$tabindex,
2083 'value' => wfMsg('showdiff'),
2084 'accesskey' => wfMsg('accesskey-diff'),
2085 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2087 $buttons['diff'] = Xml
::element('input', $temp, '');
2089 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons ) );
2094 * Output preview text only. This can be sucked into the edit page
2095 * via JavaScript, and saves the server time rendering the skin as
2096 * well as theoretically being more robust on the client (doesn't
2097 * disturb the edit box's undo history, won't eat your text on
2100 * @todo This doesn't include category or interlanguage links.
2101 * Would need to enhance it a bit, <s>maybe wrap them in XML
2102 * or something...</s> that might also require more skin
2103 * initialization, so check whether that's a problem.
2105 function livePreview() {
2108 header( 'Content-type: text/xml; charset=utf-8' );
2109 header( 'Cache-control: no-cache' );
2111 $previewText = $this->getPreviewText();
2112 #$categories = $skin->getCategoryLinks();
2115 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2116 Xml
::tags( 'livepreview', null,
2117 Xml
::element( 'preview', null, $previewText )
2118 #. Xml::element( 'category', null, $categories )
2125 * Get a diff between the current contents of the edit box and the
2126 * version of the page we're editing from.
2128 * If this is a section edit, we'll replace the section as for final
2129 * save and then make a comparison.
2131 function showDiff() {
2132 $oldtext = $this->mArticle
->fetchContent();
2133 $newtext = $this->mArticle
->replaceSection(
2134 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2135 $newtext = $this->mArticle
->preSaveTransform( $newtext );
2136 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2137 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2138 if ( $oldtext !== false ||
$newtext != '' ) {
2139 $de = new DifferenceEngine( $this->mTitle
);
2140 $de->setText( $oldtext, $newtext );
2141 $difftext = $de->getDiff( $oldtitle, $newtitle );
2142 $de->showDiffStyle();
2148 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
2152 * Filter an input field through a Unicode de-armoring process if it
2153 * came from an old browser with known broken Unicode editing issues.
2155 * @param WebRequest $request
2156 * @param string $field
2160 function safeUnicodeInput( $request, $field ) {
2161 $text = rtrim( $request->getText( $field ) );
2162 return $request->getBool( 'safemode' )
2163 ?
$this->unmakesafe( $text )
2168 * Filter an output field through a Unicode armoring process if it is
2169 * going to an old browser with known broken Unicode editing issues.
2171 * @param string $text
2175 function safeUnicodeOutput( $text ) {
2177 $codedText = $wgContLang->recodeForEdit( $text );
2178 return $this->checkUnicodeCompliantBrowser()
2180 : $this->makesafe( $codedText );
2184 * A number of web browsers are known to corrupt non-ASCII characters
2185 * in a UTF-8 text editing environment. To protect against this,
2186 * detected browsers will be served an armored version of the text,
2187 * with non-ASCII chars converted to numeric HTML character references.
2189 * Preexisting such character references will have a 0 added to them
2190 * to ensure that round-trips do not alter the original data.
2192 * @param string $invalue
2196 function makesafe( $invalue ) {
2197 // Armor existing references for reversability.
2198 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2203 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2204 $bytevalue = ord( $invalue{$i} );
2205 if( $bytevalue <= 0x7F ) { //0xxx xxxx
2206 $result .= chr( $bytevalue );
2208 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
2209 $working = $working << 6;
2210 $working +
= ($bytevalue & 0x3F);
2212 if( $bytesleft <= 0 ) {
2213 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2215 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
2216 $working = $bytevalue & 0x1F;
2218 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
2219 $working = $bytevalue & 0x0F;
2221 } else { //1111 0xxx
2222 $working = $bytevalue & 0x07;
2230 * Reverse the previously applied transliteration of non-ASCII characters
2231 * back to UTF-8. Used to protect data from corruption by broken web browsers
2232 * as listed in $wgBrowserBlackList.
2234 * @param string $invalue
2238 function unmakesafe( $invalue ) {
2240 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2241 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2245 $hexstring .= $invalue{$i};
2247 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2249 // Do some sanity checks. These aren't needed for reversability,
2250 // but should help keep the breakage down if the editor
2251 // breaks one of the entities whilst editing.
2252 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2253 $codepoint = hexdec($hexstring);
2254 $result .= codepointToUtf8( $codepoint );
2256 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2259 $result .= substr( $invalue, $i, 1 );
2262 // reverse the transform that we made for reversability reasons.
2263 return strtr( $result, array( "�" => "&#x" ) );
2266 function noCreatePermission() {
2268 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2269 $wgOut->addWikiMsg( 'nocreatetext' );
2273 * If there are rows in the deletion log for this page, show them,
2274 * along with a nice little note for the user
2276 * @param OutputPage $out
2278 protected function showDeletionLog( $out ) {
2280 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
2281 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle
->getPrefixedText() );
2282 if( $pager->getNumRows() > 0 ) {
2283 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2284 $out->addWikiMsg( 'recreate-deleted-warn' );
2286 $loglist->beginLogEventsList() .
2288 $loglist->endLogEventsList()
2290 $out->addHtml( '</div>' );
2295 * Attempt submission
2296 * @return bool false if output is done, true if the rest of the form should be displayed
2298 function attemptSave() {
2299 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2301 $resultDetails = false;
2302 $value = $this->internalAttemptSave( $resultDetails, $wgUser->isAllowed('bot') && $wgRequest->getBool('bot', true) );
2304 if( $value == self
::AS_SUCCESS_UPDATE ||
$value == self
::AS_SUCCESS_NEW_ARTICLE
) {
2305 $this->didSave
= true;
2309 case self
::AS_HOOK_ERROR_EXPECTED
:
2310 case self
::AS_CONTENT_TOO_BIG
:
2311 case self
::AS_ARTICLE_WAS_DELETED
:
2312 case self
::AS_CONFLICT_DETECTED
:
2313 case self
::AS_SUMMARY_NEEDED
:
2314 case self
::AS_TEXTBOX_EMPTY
:
2315 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
2319 case self
::AS_HOOK_ERROR
:
2320 case self
::AS_FILTERING
:
2321 case self
::AS_SUCCESS_NEW_ARTICLE
:
2322 case self
::AS_SUCCESS_UPDATE
:
2325 case self
::AS_SPAM_ERROR
:
2326 $this->spamPage ( $resultDetails['spam'] );
2329 case self
::AS_BLOCKED_PAGE_FOR_USER
:
2330 $this->blockedPage();
2333 case self
::AS_IMAGE_REDIRECT_ANON
:
2334 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2337 case self
::AS_READ_ONLY_PAGE_ANON
:
2338 $this->userNotLoggedInPage();
2341 case self
::AS_READ_ONLY_PAGE_LOGGED
:
2342 case self
::AS_READ_ONLY_PAGE
:
2343 $wgOut->readOnlyPage();
2346 case self
::AS_RATE_LIMITED
:
2347 $wgOut->rateLimited();
2350 case self
::AS_NO_CREATE_PERMISSION
;
2351 $this->noCreatePermission();
2354 case self
::AS_BLANK_ARTICLE
:
2355 $wgOut->redirect( $wgTitle->getFullURL() );
2358 case self
::AS_IMAGE_REDIRECT_LOGGED
:
2359 $wgOut->permissionRequired( 'upload' );
2364 function getBaseRevision() {
2365 if ($this->mBaseRevision
== false) {
2366 $db = wfGetDB( DB_MASTER
);
2367 $baseRevision = Revision
::loadFromTimestamp(
2368 $db, $this->mTitle
, $this->edittime
);
2369 return $this->mBaseRevision
= $baseRevision;
2371 return $this->mBaseRevision
;