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 * $this->mContextTitle 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.
19 * Surgeon General's Warning: prolonged exposure to this class is known to cause
20 * headaches, which may be fatal.
23 const AS_SUCCESS_UPDATE
= 200;
24 const AS_SUCCESS_NEW_ARTICLE
= 201;
25 const AS_HOOK_ERROR
= 210;
26 const AS_FILTERING
= 211;
27 const AS_HOOK_ERROR_EXPECTED
= 212;
28 const AS_BLOCKED_PAGE_FOR_USER
= 215;
29 const AS_CONTENT_TOO_BIG
= 216;
30 const AS_USER_CANNOT_EDIT
= 217;
31 const AS_READ_ONLY_PAGE_ANON
= 218;
32 const AS_READ_ONLY_PAGE_LOGGED
= 219;
33 const AS_READ_ONLY_PAGE
= 220;
34 const AS_RATE_LIMITED
= 221;
35 const AS_ARTICLE_WAS_DELETED
= 222;
36 const AS_NO_CREATE_PERMISSION
= 223;
37 const AS_BLANK_ARTICLE
= 224;
38 const AS_CONFLICT_DETECTED
= 225;
39 const AS_SUMMARY_NEEDED
= 226;
40 const AS_TEXTBOX_EMPTY
= 228;
41 const AS_MAX_ARTICLE_SIZE_EXCEEDED
= 229;
44 const AS_SPAM_ERROR
= 232;
45 const AS_IMAGE_REDIRECT_ANON
= 233;
46 const AS_IMAGE_REDIRECT_LOGGED
= 234;
57 private $mContextTitle = null;
59 var $isConflict = false;
60 var $isCssJsSubpage = false;
61 var $isCssSubpage = false;
62 var $isJsSubpage = false;
63 var $isWrongCaseCssJsPage = false;
64 var $isNew = false; // new page or new section
65 var $deletedSinceEdit;
69 var $mTokenOk = false;
70 var $mTokenOkExceptSuffix = false;
71 var $mTriedSave = false;
72 var $incompleteForm = false;
74 var $kblength = false;
75 var $missingComment = false;
76 var $missingSummary = false;
77 var $allowBlankSummary = false;
80 #var $mPreviewTemplates;
87 var $mBaseRevision = false;
88 var $mShowSummaryField = true;
91 var $save = false, $preview = false, $diff = false;
92 var $minoredit = false, $watchthis = false, $recreate = false;
93 var $textbox1 = '', $textbox2 = '', $summary = '', $nosummary = false;
94 var $edittime = '', $section = '', $starttime = '';
95 var $oldid = 0, $editintro = '', $scrolltop = null, $bot = true;
97 # Placeholders for text injection by hooks (must be HTML)
98 # extensions should take care to _append_ to the present value
99 public $editFormPageTop; // Before even the preview
100 public $editFormTextTop;
101 public $editFormTextBeforeContent;
102 public $editFormTextAfterWarn;
103 public $editFormTextAfterTools;
104 public $editFormTextBottom;
105 public $editFormTextAfterContent;
106 public $previewTextAfterContent;
107 public $mPreloadText;
109 /* $didSave should be set to true whenever an article was succesfully altered. */
110 public $didSave = false;
111 public $undidRev = 0;
113 public $suppressIntro = false;
117 * @param $article Article
119 function __construct( $article ) {
120 $this->mArticle
=& $article;
121 $this->mTitle
= $article->getTitle();
122 $this->action
= 'submit';
124 # Placeholders for text injection by hooks (empty per default)
125 $this->editFormPageTop
=
126 $this->editFormTextTop
=
127 $this->editFormTextBeforeContent
=
128 $this->editFormTextAfterWarn
=
129 $this->editFormTextAfterTools
=
130 $this->editFormTextBottom
=
131 $this->editFormTextAfterContent
=
132 $this->previewTextAfterContent
=
133 $this->mPreloadText
= "";
139 function getArticle() {
140 return $this->mArticle
;
144 * Set the context Title object
146 * @param $title Title object or null
148 public function setContextTitle( $title ) {
149 $this->mContextTitle
= $title;
153 * Get the context title object.
154 * If not set, $wgTitle will be returned. This behavior might changed in
155 * the future to return $this->mTitle instead.
157 * @return Title object
159 public function getContextTitle() {
160 if ( is_null( $this->mContextTitle
) ) {
164 return $this->mContextTitle
;
169 * Fetch initial editing page content.
171 * @param $def_text string
172 * @returns mixed string on success, $def_text for invalid sections
175 function getContent( $def_text = '' ) {
176 global $wgOut, $wgRequest, $wgParser;
178 wfProfileIn( __METHOD__
);
179 # Get variables from query string :P
180 $section = $wgRequest->getVal( 'section' );
182 $preload = $wgRequest->getVal( 'preload',
183 // Custom preload text for new sections
184 $section === 'new' ?
'MediaWiki:addsection-preload' : '' );
185 $undoafter = $wgRequest->getVal( 'undoafter' );
186 $undo = $wgRequest->getVal( 'undo' );
188 // For message page not locally set, use the i18n message.
189 // For other non-existent articles, use preload text if any.
190 if ( !$this->mTitle
->exists() ) {
191 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
192 # If this is a system message, get the default text.
193 $text = $this->mTitle
->getDefaultMessageText();
194 if( $text === false ) {
195 $text = $this->getPreloadedText( $preload );
198 # If requested, preload some text.
199 $text = $this->getPreloadedText( $preload );
201 // For existing pages, get text based on "undo" or section parameters.
203 $text = $this->mArticle
->getContent();
204 if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
205 # If they got undoafter and undo round the wrong way, switch them
206 list( $undo, $undoafter ) = array( $undoafter, $undo );
208 if ( $undo > 0 && $undo > $undoafter ) {
209 # Undoing a specific edit overrides section editing; section-editing
210 # doesn't work with undoing.
212 $undorev = Revision
::newFromId( $undo );
213 $oldrev = Revision
::newFromId( $undoafter );
215 $undorev = Revision
::newFromId( $undo );
216 $oldrev = $undorev ?
$undorev->getPrevious() : null;
219 # Sanity check, make sure it's the right page,
220 # the revisions exist and they were not deleted.
221 # Otherwise, $text will be left as-is.
222 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
223 $undorev->getPage() == $oldrev->getPage() &&
224 $undorev->getPage() == $this->mArticle
->getID() &&
225 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
226 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
228 $undotext = $this->mArticle
->getUndoText( $undorev, $oldrev );
229 if ( $undotext === false ) {
230 # Warn the user that something went wrong
231 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-failure">' .
232 wfMsgNoTrans( 'undo-failure' ) . '</div>', true, /* interface */true );
235 # Inform the user of our success and set an automatic edit summary
236 $this->editFormPageTop
.= $wgOut->parse( '<div class="mw-undo-success">' .
237 wfMsgNoTrans( 'undo-success' ) . '</div>', true, /* interface */true );
238 $firstrev = $oldrev->getNext();
239 # If we just undid one rev, use an autosummary
240 if ( $firstrev->mId
== $undo ) {
241 $this->summary
= wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
242 $this->undidRev
= $undo;
244 $this->formtype
= 'diff';
247 // Failed basic sanity checks.
248 // Older revisions may have been removed since the link
249 // was created, or we may simply have got bogus input.
250 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-norev">' .
251 wfMsgNoTrans( 'undo-norev' ) . '</div>', true, /* interface */true );
253 } elseif ( $section != '' ) {
254 if ( $section == 'new' ) {
255 $text = $this->getPreloadedText( $preload );
257 // Get section edit text (returns $def_text for invalid sections)
258 $text = $wgParser->getSection( $text, $section, $def_text );
263 wfProfileOut( __METHOD__
);
268 * Use this method before edit() to preload some text into the edit box
270 * @param $text string
272 public function setPreloadedText( $text ) {
273 $this->mPreloadText
= $text;
277 * Get the contents to be preloaded into the box, either set by
278 * an earlier setPreloadText() or by loading the given page.
280 * @param $preload String: representing the title to preload from.
283 protected function getPreloadedText( $preload ) {
284 global $wgUser, $wgParser;
285 if ( !empty( $this->mPreloadText
) ) {
286 return $this->mPreloadText
;
287 } elseif ( $preload !== '' ) {
288 $title = Title
::newFromText( $preload );
289 # Check for existence to avoid getting MediaWiki:Noarticletext
290 if ( isset( $title ) && $title->exists() && $title->userCanRead() ) {
291 $article = new Article( $title );
293 if ( $article->isRedirect() ) {
294 $title = Title
::newFromRedirectRecurse( $article->getContent() );
295 # Redirects to missing titles are displayed, to hidden pages are followed
296 # Copying observed behaviour from ?action=view
297 if ( $title->exists() ) {
298 if ($title->userCanRead() ) {
299 $article = new Article( $title );
305 $parserOptions = ParserOptions
::newFromUser( $wgUser );
306 return $wgParser->getPreloadText( $article->getContent(), $title, $parserOptions );
313 * Check if a page was deleted while the user was editing it, before submit.
314 * Note that we rely on the logging table, which hasn't been always there,
315 * but that doesn't matter, because this only applies to brand new
318 protected function wasDeletedSinceLastEdit() {
319 if ( $this->deletedSinceEdit
!== null ) {
320 return $this->deletedSinceEdit
;
323 $this->deletedSinceEdit
= false;
325 if ( $this->mTitle
->isDeletedQuick() ) {
326 $this->lastDelete
= $this->getLastDelete();
327 if ( $this->lastDelete
) {
328 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
329 if ( $deleteTime > $this->starttime
) {
330 $this->deletedSinceEdit
= true;
335 return $this->deletedSinceEdit
;
339 * Checks whether the user entered a skin name in uppercase,
340 * e.g. "User:Example/Monobook.css" instead of "monobook.css"
344 protected function isWrongCaseCssJsPage() {
345 if( $this->mTitle
->isCssJsSubpage() ) {
346 $name = $this->mTitle
->getSkinFromCssJsSubpage();
347 $skins = array_merge(
348 array_keys( Skin
::getSkinNames() ),
351 return !in_array( $name, $skins )
352 && in_array( strtolower( $name ), $skins );
363 * This is the function that gets called for "action=edit". It
364 * sets up various member variables, then passes execution to
365 * another function, usually showEditForm()
367 * The edit form is self-submitting, so that when things like
368 * preview and edit conflicts occur, we get the same form back
369 * with the extra stuff added. Only when the final submission
370 * is made and all is well do we actually save and redirect to
371 * the newly-edited page.
374 global $wgOut, $wgRequest, $wgUser;
375 // Allow extensions to modify/prevent this form or submission
376 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
380 wfProfileIn( __METHOD__
);
381 wfDebug( __METHOD__
.": enter\n" );
383 $this->importFormData( $wgRequest );
384 $this->firsttime
= false;
387 $this->livePreview();
388 wfProfileOut( __METHOD__
);
392 if ( wfReadOnly() && $this->save
) {
395 $this->preview
= true;
398 $wgOut->addModules( array( 'mediawiki.action.edit' ) );
400 if ( $wgUser->getOption( 'uselivepreview', false ) ) {
401 $wgOut->addModules( 'mediawiki.legacy.preview' );
403 // Bug #19334: textarea jumps when editing articles in IE8
404 $wgOut->addStyle( 'common/IE80Fixes.css', 'screen', 'IE 8' );
406 $permErrors = $this->getEditPermissionErrors();
408 // Auto-block user's IP if the account was "hard" blocked
409 $wgUser->spreadAnyEditBlock();
411 wfDebug( __METHOD__
. ": User can't edit\n" );
412 $content = $this->getContent( null );
413 $content = $content === '' ?
null : $content;
414 $this->readOnlyPage( $content, true, $permErrors, 'edit' );
415 wfProfileOut( __METHOD__
);
419 $this->formtype
= 'save';
420 } elseif ( $this->preview
) {
421 $this->formtype
= 'preview';
422 } elseif ( $this->diff
) {
423 $this->formtype
= 'diff';
424 } else { # First time through
425 $this->firsttime
= true;
426 if ( $this->previewOnOpen() ) {
427 $this->formtype
= 'preview';
429 $this->formtype
= 'initial';
434 // If they used redlink=1 and the page exists, redirect to the main article
435 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
436 $wgOut->redirect( $this->mTitle
->getFullURL() );
439 wfProfileIn( __METHOD__
."-business-end" );
441 $this->isConflict
= false;
442 // css / js subpages of user pages get a special treatment
443 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
444 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
445 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
446 $this->isWrongCaseCssJsPage
= $this->isWrongCaseCssJsPage();
447 $this->isNew
= !$this->mTitle
->exists() ||
$this->section
== 'new';
449 # Show applicable editing introductions
450 if ( $this->formtype
== 'initial' ||
$this->firsttime
)
453 if ( $this->mTitle
->isTalkPage() ) {
454 $wgOut->addWikiMsg( 'talkpagetext' );
457 # Optional notices on a per-namespace and per-page basis
458 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
459 $editnotice_ns_message = wfMessage( $editnotice_ns )->inContentLanguage();
460 if ( $editnotice_ns_message->exists() ) {
461 $wgOut->addWikiText( $editnotice_ns_message->plain() );
463 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
464 $parts = explode( '/', $this->mTitle
->getDBkey() );
465 $editnotice_base = $editnotice_ns;
466 while ( count( $parts ) > 0 ) {
467 $editnotice_base .= '-'.array_shift( $parts );
468 $editnotice_base_msg = wfMessage( $editnotice_base )->inContentLanguage();
469 if ( $editnotice_base_msg->exists() ) {
470 $wgOut->addWikiText( $editnotice_base_msg->plain() );
474 # Even if there are no subpages in namespace, we still don't want / in MW ns.
475 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->mTitle
->getDBkey() );
476 $editnoticeMsg = wfMessage( $editnoticeText )->inContentLanguage();
477 if ( $editnoticeMsg->exists() ) {
478 $wgOut->addWikiText( $editnoticeMsg->plain() );
482 # Attempt submission here. This will check for edit conflicts,
483 # and redundantly check for locked database, blocked IPs, etc.
484 # that edit() already checked just in case someone tries to sneak
485 # in the back door with a hand-edited submission URL.
487 if ( 'save' == $this->formtype
) {
488 if ( !$this->attemptSave() ) {
489 wfProfileOut( __METHOD__
."-business-end" );
490 wfProfileOut( __METHOD__
);
495 # First time through: get contents, set time for conflict
497 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
498 if ( $this->initialiseForm() === false ) {
499 $this->noSuchSectionPage();
500 wfProfileOut( __METHOD__
."-business-end" );
501 wfProfileOut( __METHOD__
);
504 if ( !$this->mTitle
->getArticleId() )
505 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
507 wfRunHooks( 'EditFormInitialText', array( $this ) );
510 $this->showEditForm();
511 wfProfileOut( __METHOD__
."-business-end" );
512 wfProfileOut( __METHOD__
);
518 protected function getEditPermissionErrors() {
520 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
521 # Can this title be created?
522 if ( !$this->mTitle
->exists() ) {
523 $permErrors = array_merge( $permErrors,
524 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
526 # Ignore some permissions errors when a user is just previewing/viewing diffs
528 foreach( $permErrors as $error ) {
529 if ( ( $this->preview ||
$this->diff
) &&
530 ( $error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext' ) )
535 $permErrors = wfArrayDiff2( $permErrors, $remove );
540 * Show a read-only error
541 * Parameters are the same as OutputPage:readOnlyPage()
542 * Redirect to the article page if redlink=1
544 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
545 global $wgRequest, $wgOut;
546 if ( $wgRequest->getBool( 'redlink' ) ) {
547 // The edit page was reached via a red link.
548 // Redirect to the article page and let them click the edit tab if
549 // they really want a permission error.
550 $wgOut->redirect( $this->mTitle
->getFullUrl() );
552 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
557 * Should we show a preview when the edit form is first shown?
561 protected function previewOnOpen() {
562 global $wgRequest, $wgUser, $wgPreviewOnOpenNamespaces;
563 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
564 // Explicit override from request
566 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
567 // Explicit override from request
569 } elseif ( $this->section
== 'new' ) {
570 // Nothing *to* preview for new sections
572 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
573 // Standard preference behaviour
575 } elseif ( !$this->mTitle
->exists() &&
576 isset($wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()]) &&
577 $wgPreviewOnOpenNamespaces[$this->mTitle
->getNamespace()] )
579 // Categories are special
587 * Does this EditPage class support section editing?
588 * This is used by EditPage subclasses to indicate their ui cannot handle section edits
592 protected function isSectionEditSupported() {
597 * Returns the URL to use in the form's action attribute.
598 * This is used by EditPage subclasses when simply customizing the action
599 * variable in the constructor is not enough. This can be used when the
600 * EditPage lives inside of a Special page rather than a custom page action.
602 * @param $title Title object for which is being edited (where we go to for &action= links)
605 protected function getActionURL( Title
$title ) {
606 return $title->getLocalURL( array( 'action' => $this->action
) );
611 * @param $request WebRequest
613 function importFormData( &$request ) {
614 global $wgLang, $wgUser;
616 wfProfileIn( __METHOD__
);
618 # Section edit can come from either the form or a link
619 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
621 if ( $request->wasPosted() ) {
622 # These fields need to be checked for encoding.
623 # Also remove trailing whitespace, but don't remove _initial_
624 # whitespace from the text boxes. This may be significant formatting.
625 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
626 if ( !$request->getCheck('wpTextbox2') ) {
627 // Skip this if wpTextbox2 has input, it indicates that we came
628 // from a conflict page with raw page text, not a custom form
629 // modified by subclasses
630 wfProfileIn( get_class($this)."::importContentFormData" );
631 $textbox1 = $this->importContentFormData( $request );
632 if ( isset($textbox1) )
633 $this->textbox1
= $textbox1;
634 wfProfileOut( get_class($this)."::importContentFormData" );
637 # Truncate for whole multibyte characters. +5 bytes for ellipsis
638 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
640 # Remove extra headings from summaries and new sections.
641 $this->summary
= preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
643 $this->edittime
= $request->getVal( 'wpEdittime' );
644 $this->starttime
= $request->getVal( 'wpStarttime' );
646 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
648 if ($this->textbox1
=== '' && $request->getVal( 'wpTextbox1' ) === null) {
649 // wpTextbox1 field is missing, possibly due to being "too big"
650 // according to some filter rules such as Suhosin's setting for
651 // suhosin.request.max_value_length (d'oh)
652 $this->incompleteForm
= true;
654 // edittime should be one of our last fields; if it's missing,
655 // the submission probably broke somewhere in the middle.
656 $this->incompleteForm
= is_null( $this->edittime
);
658 if ( $this->incompleteForm
) {
659 # If the form is incomplete, force to preview.
660 wfDebug( __METHOD__
. ": Form data appears to be incomplete\n" );
661 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
662 $this->preview
= true;
664 /* Fallback for live preview */
665 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
666 $this->diff
= $request->getCheck( 'wpDiff' );
668 // Remember whether a save was requested, so we can indicate
669 // if we forced preview due to session failure.
670 $this->mTriedSave
= !$this->preview
;
672 if ( $this->tokenOk( $request ) ) {
673 # Some browsers will not report any submit button
674 # if the user hits enter in the comment box.
675 # The unmarked state will be assumed to be a save,
676 # if the form seems otherwise complete.
677 wfDebug( __METHOD__
. ": Passed token check.\n" );
678 } elseif ( $this->diff
) {
679 # Failed token check, but only requested "Show Changes".
680 wfDebug( __METHOD__
. ": Failed token check; Show Changes requested.\n" );
682 # Page might be a hack attempt posted from
683 # an external site. Preview instead of saving.
684 wfDebug( __METHOD__
. ": Failed token check; forcing preview\n" );
685 $this->preview
= true;
688 $this->save
= !$this->preview
&& !$this->diff
;
689 if ( !preg_match( '/^\d{14}$/', $this->edittime
) ) {
690 $this->edittime
= null;
693 if ( !preg_match( '/^\d{14}$/', $this->starttime
) ) {
694 $this->starttime
= null;
697 $this->recreate
= $request->getCheck( 'wpRecreate' );
699 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
700 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
702 # Don't force edit summaries when a user is editing their own user or talk page
703 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
704 $this->mTitle
->getText() == $wgUser->getName() )
706 $this->allowBlankSummary
= true;
708 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
711 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
713 # Not a posted form? Start with nothing.
714 wfDebug( __METHOD__
. ": Not a posted form.\n" );
715 $this->textbox1
= '';
717 $this->edittime
= '';
718 $this->starttime
= wfTimestampNow();
720 $this->preview
= false;
723 $this->minoredit
= false;
724 $this->watchthis
= $request->getBool( 'watchthis', false ); // Watch may be overriden by request parameters
725 $this->recreate
= false;
727 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
728 $this->summary
= $request->getVal( 'preloadtitle' );
730 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
731 $this->summary
= $request->getText( 'summary' );
734 if ( $request->getVal( 'minor' ) ) {
735 $this->minoredit
= true;
739 $this->bot
= $request->getBool( 'bot', true );
740 $this->nosummary
= $request->getBool( 'nosummary' );
742 // @todo FIXME: Unused variable?
743 $this->oldid
= $request->getInt( 'oldid' );
745 $this->live
= $request->getCheck( 'live' );
746 $this->editintro
= $request->getText( 'editintro',
747 // Custom edit intro for new sections
748 $this->section
=== 'new' ?
'MediaWiki:addsection-editintro' : '' );
750 // Allow extensions to modify form data
751 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
753 wfProfileOut( __METHOD__
);
757 * Subpage overridable method for extracting the page content data from the
758 * posted form to be placed in $this->textbox1, if using customized input
759 * this method should be overrided and return the page text that will be used
760 * for saving, preview parsing and so on...
762 * @param $request WebRequest
764 protected function importContentFormData( &$request ) {
765 return; // Don't do anything, EditPage already extracted wpTextbox1
769 * Make sure the form isn't faking a user's credentials.
771 * @param $request WebRequest
775 function tokenOk( &$request ) {
777 $token = $request->getVal( 'wpEditToken' );
778 $this->mTokenOk
= $wgUser->matchEditToken( $token );
779 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
780 return $this->mTokenOk
;
784 * Show all applicable editing introductions
786 protected function showIntro() {
787 global $wgOut, $wgUser;
788 if ( $this->suppressIntro
) {
792 $namespace = $this->mTitle
->getNamespace();
794 if ( $namespace == NS_MEDIAWIKI
) {
795 # Show a warning if editing an interface message
796 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1\n</div>", 'editinginterface' );
799 # Show a warning message when someone creates/edits a user (talk) page but the user does not exist
800 # Show log extract when the user is currently blocked
801 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
802 $parts = explode( '/', $this->mTitle
->getText(), 2 );
803 $username = $parts[0];
804 $user = User
::newFromName( $username, false /* allow IP users*/ );
805 $ip = User
::isIP( $username );
806 if ( !$user->isLoggedIn() && !$ip ) { # User does not exist
807 $wgOut->wrapWikiMsg( "<div class=\"mw-userpage-userdoesnotexist error\">\n$1\n</div>",
808 array( 'userpage-userdoesnotexist', wfEscapeWikiText( $username ) ) );
809 } elseif ( $user->isBlocked() ) { # Show log extract if the user is currently blocked
810 LogEventsList
::showLogExtract(
813 $user->getUserPage(),
817 'showIfEmpty' => false,
819 'blocked-notice-logextract',
820 $user->getName() # Support GENDER in notice
826 # Try to add a custom edit intro, or use the standard one if this is not possible.
827 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
828 if ( $wgUser->isLoggedIn() ) {
829 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletext\">\n$1\n</div>", 'newarticletext' );
831 $wgOut->wrapWikiMsg( "<div class=\"mw-newarticletextanon\">\n$1\n</div>", 'newarticletextanon' );
834 # Give a notice if the user is editing a deleted/moved page...
835 if ( !$this->mTitle
->exists() ) {
836 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
,
837 '', array( 'lim' => 10,
838 'conds' => array( "log_action != 'revision'" ),
839 'showIfEmpty' => false,
840 'msgKey' => array( 'recreate-moveddeleted-warn') )
846 * Attempt to show a custom editing introduction, if supplied
850 protected function showCustomIntro() {
851 if ( $this->editintro
) {
852 $title = Title
::newFromText( $this->editintro
);
853 if ( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
855 // Added using template syntax, to take <noinclude>'s into account.
856 $wgOut->addWikiTextTitleTidy( '{{:' . $title->getFullText() . '}}', $this->mTitle
);
867 * Attempt submission (no UI)
872 * @return Status object, possibly with a message, but always with one of the AS_* constants in $status->value,
874 * FIXME: This interface is TERRIBLE, but hard to get rid of due to various error display idiosyncrasies. There are
875 * also lots of cases where error metadata is set in the object and retrieved later instead of being returned, e.g.
876 * AS_CONTENT_TOO_BIG and AS_BLOCKED_PAGE_FOR_USER. All that stuff needs to be cleaned up some time.
878 function internalAttemptSave( &$result, $bot = false ) {
879 global $wgFilterCallback, $wgUser, $wgRequest, $wgParser;
880 global $wgMaxArticleSize;
882 $status = Status
::newGood();
884 wfProfileIn( __METHOD__
);
885 wfProfileIn( __METHOD__
. '-checks' );
887 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) ) {
888 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
889 $status->fatal( 'hookaborted' );
890 $status->value
= self
::AS_HOOK_ERROR
;
891 wfProfileOut( __METHOD__
. '-checks' );
892 wfProfileOut( __METHOD__
);
896 # Check image redirect
897 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
898 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
899 !$wgUser->isAllowed( 'upload' ) ) {
900 $code = $wgUser->isAnon() ? self
::AS_IMAGE_REDIRECT_ANON
: self
::AS_IMAGE_REDIRECT_LOGGED
;
901 $status->setResult( false, $code );
903 wfProfileOut( __METHOD__
. '-checks' );
904 wfProfileOut( __METHOD__
);
910 $match = self
::matchSummarySpamRegex( $this->summary
);
911 if ( $match === false ) {
912 $match = self
::matchSpamRegex( $this->textbox1
);
914 if ( $match !== false ) {
915 $result['spam'] = $match;
916 $ip = $wgRequest->getIP();
917 $pdbk = $this->mTitle
->getPrefixedDBkey();
918 $match = str_replace( "\n", '', $match );
919 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
920 $status->fatal( 'spamprotectionmatch', $match );
921 $status->value
= self
::AS_SPAM_ERROR
;
922 wfProfileOut( __METHOD__
. '-checks' );
923 wfProfileOut( __METHOD__
);
926 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
927 # Error messages or other handling should be performed by the filter function
928 $status->setResult( false, self
::AS_FILTERING
);
929 wfProfileOut( __METHOD__
. '-checks' );
930 wfProfileOut( __METHOD__
);
933 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
934 # Error messages etc. could be handled within the hook...
935 $status->fatal( 'hookaborted' );
936 $status->value
= self
::AS_HOOK_ERROR
;
937 wfProfileOut( __METHOD__
. '-checks' );
938 wfProfileOut( __METHOD__
);
940 } elseif ( $this->hookError
!= '' ) {
941 # ...or the hook could be expecting us to produce an error
942 $status->fatal( 'hookaborted' );
943 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
944 wfProfileOut( __METHOD__
. '-checks' );
945 wfProfileOut( __METHOD__
);
949 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
950 # Check block state against master, thus 'false'.
951 $status->setResult( false, self
::AS_BLOCKED_PAGE_FOR_USER
);
952 wfProfileOut( __METHOD__
. '-checks' );
953 wfProfileOut( __METHOD__
);
957 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
958 if ( $this->kblength
> $wgMaxArticleSize ) {
959 // Error will be displayed by showEditForm()
960 $this->tooBig
= true;
961 $status->setResult( false, self
::AS_CONTENT_TOO_BIG
);
962 wfProfileOut( __METHOD__
. '-checks' );
963 wfProfileOut( __METHOD__
);
967 if ( !$wgUser->isAllowed( 'edit' ) ) {
968 if ( $wgUser->isAnon() ) {
969 $status->setResult( false, self
::AS_READ_ONLY_PAGE_ANON
);
970 wfProfileOut( __METHOD__
. '-checks' );
971 wfProfileOut( __METHOD__
);
974 $status->fatal( 'readonlytext' );
975 $status->value
= self
::AS_READ_ONLY_PAGE_LOGGED
;
976 wfProfileOut( __METHOD__
. '-checks' );
977 wfProfileOut( __METHOD__
);
982 if ( wfReadOnly() ) {
983 $status->fatal( 'readonlytext' );
984 $status->value
= self
::AS_READ_ONLY_PAGE
;
985 wfProfileOut( __METHOD__
. '-checks' );
986 wfProfileOut( __METHOD__
);
989 if ( $wgUser->pingLimiter() ) {
990 $status->fatal( 'actionthrottledtext' );
991 $status->value
= self
::AS_RATE_LIMITED
;
992 wfProfileOut( __METHOD__
. '-checks' );
993 wfProfileOut( __METHOD__
);
997 # If the article has been deleted while editing, don't save it without
999 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
1000 $status->setResult( false, self
::AS_ARTICLE_WAS_DELETED
);
1001 wfProfileOut( __METHOD__
. '-checks' );
1002 wfProfileOut( __METHOD__
);
1006 wfProfileOut( __METHOD__
. '-checks' );
1008 # If article is new, insert it.
1009 $aid = $this->mTitle
->getArticleID( Title
::GAID_FOR_UPDATE
);
1010 $new = ( $aid == 0 );
1013 // Late check for create permission, just in case *PARANOIA*
1014 if ( !$this->mTitle
->userCan( 'create' ) ) {
1015 $status->fatal( 'nocreatetext' );
1016 $status->value
= self
::AS_NO_CREATE_PERMISSION
;
1017 wfDebug( __METHOD__
. ": no create permission\n" );
1018 wfProfileOut( __METHOD__
);
1022 # Don't save a new article if it's blank.
1023 if ( $this->textbox1
== '' ) {
1024 $status->setResult( false, self
::AS_BLANK_ARTICLE
);
1025 wfProfileOut( __METHOD__
);
1029 // Run post-section-merge edit filter
1030 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
1031 # Error messages etc. could be handled within the hook...
1032 $status->fatal( 'hookaborted' );
1033 $status->value
= self
::AS_HOOK_ERROR
;
1034 wfProfileOut( __METHOD__
);
1036 } elseif ( $this->hookError
!= '' ) {
1037 # ...or the hook could be expecting us to produce an error
1038 $status->fatal( 'hookaborted' );
1039 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1040 wfProfileOut( __METHOD__
);
1044 # Handle the user preference to force summaries here. Check if it's not a redirect.
1045 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
1046 if ( md5( $this->summary
) == $this->autoSumm
) {
1047 $this->missingSummary
= true;
1048 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1049 $status->value
= self
::AS_SUMMARY_NEEDED
;
1050 wfProfileOut( __METHOD__
);
1055 $text = $this->textbox1
;
1056 if ( $this->section
== 'new' && $this->summary
!= '' ) {
1057 $text = wfMsgForContent( 'newsectionheaderdefaultlevel', $this->summary
) . "\n\n" . $text;
1060 $status->value
= self
::AS_SUCCESS_NEW_ARTICLE
;
1064 # Article exists. Check for edit conflict.
1066 $this->mArticle
->clear(); # Force reload of dates, etc.
1068 wfDebug( "timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n" );
1070 if ( $this->mArticle
->getTimestamp() != $this->edittime
) {
1071 $this->isConflict
= true;
1072 if ( $this->section
== 'new' ) {
1073 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
1074 $this->mArticle
->getComment() == $this->summary
) {
1075 // Probably a duplicate submission of a new comment.
1076 // This can happen when squid resends a request after
1077 // a timeout but the first one actually went through.
1078 wfDebug( __METHOD__
. ": duplicate new section submission; trigger edit conflict!\n" );
1080 // New comment; suppress conflict.
1081 $this->isConflict
= false;
1082 wfDebug( __METHOD__
.": conflict suppressed; new section\n" );
1084 } elseif ( $this->section
== '' && $this->userWasLastToEdit( $wgUser->getId(), $this->edittime
) ) {
1085 # Suppress edit conflict with self, except for section edits where merging is required.
1086 wfDebug( __METHOD__
. ": Suppressing edit conflict, same user.\n" );
1087 $this->isConflict
= false;
1091 if ( $this->isConflict
) {
1092 wfDebug( __METHOD__
. ": conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
1093 $this->mArticle
->getTimestamp() . "')\n" );
1094 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1096 wfDebug( __METHOD__
. ": getting section '$this->section'\n" );
1097 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
1099 if ( is_null( $text ) ) {
1100 wfDebug( __METHOD__
. ": activating conflict; section replace failed.\n" );
1101 $this->isConflict
= true;
1102 $text = $this->textbox1
; // do not try to merge here!
1103 } elseif ( $this->isConflict
) {
1105 if ( $this->mergeChangesInto( $text ) ) {
1106 // Successful merge! Maybe we should tell the user the good news?
1107 $this->isConflict
= false;
1108 wfDebug( __METHOD__
. ": Suppressing edit conflict, successful merge.\n" );
1110 $this->section
= '';
1111 $this->textbox1
= $text;
1112 wfDebug( __METHOD__
. ": Keeping edit conflict, failed merge.\n" );
1116 if ( $this->isConflict
) {
1117 $status->setResult( false, self
::AS_CONFLICT_DETECTED
);
1118 wfProfileOut( __METHOD__
);
1122 // Run post-section-merge edit filter
1123 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
1124 # Error messages etc. could be handled within the hook...
1125 $status->fatal( 'hookaborted' );
1126 $status->value
= self
::AS_HOOK_ERROR
;
1127 wfProfileOut( __METHOD__
);
1129 } elseif ( $this->hookError
!= '' ) {
1130 # ...or the hook could be expecting us to produce an error
1131 $status->fatal( 'hookaborted' );
1132 $status->value
= self
::AS_HOOK_ERROR_EXPECTED
;
1133 wfProfileOut( __METHOD__
);
1137 # Handle the user preference to force summaries here, but not for null edits
1138 if ( $this->section
!= 'new' && !$this->allowBlankSummary
1139 && 0 != strcmp( $this->mArticle
->getContent(), $text )
1140 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1142 if ( md5( $this->summary
) == $this->autoSumm
) {
1143 $this->missingSummary
= true;
1144 $status->fatal( 'missingsummary' );
1145 $status->value
= self
::AS_SUMMARY_NEEDED
;
1146 wfProfileOut( __METHOD__
);
1151 # And a similar thing for new sections
1152 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1153 if ( trim( $this->summary
) == '' ) {
1154 $this->missingSummary
= true;
1155 $status->fatal( 'missingsummary' ); // or 'missingcommentheader' if $section == 'new'. Blegh
1156 $status->value
= self
::AS_SUMMARY_NEEDED
;
1157 wfProfileOut( __METHOD__
);
1163 wfProfileIn( __METHOD__
. '-sectionanchor' );
1164 $sectionanchor = '';
1165 if ( $this->section
== 'new' ) {
1166 if ( $this->textbox1
== '' ) {
1167 $this->missingComment
= true;
1168 $status->fatal( 'missingcommenttext' );
1169 $status->value
= self
::AS_TEXTBOX_EMPTY
;
1170 wfProfileOut( __METHOD__
. '-sectionanchor' );
1171 wfProfileOut( __METHOD__
);
1174 if ( $this->summary
!= '' ) {
1175 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $this->summary
);
1176 # This is a new section, so create a link to the new section
1177 # in the revision summary.
1178 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1179 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1181 } elseif ( $this->section
!= '' ) {
1182 # Try to get a section anchor from the section source, redirect to edited section if header found
1183 # XXX: might be better to integrate this into Article::replaceSection
1184 # for duplicate heading checking and maybe parsing
1185 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1186 # we can't deal with anchors, includes, html etc in the header for now,
1187 # headline would need to be parsed to improve this
1188 if ( $hasmatch && strlen( $matches[2] ) > 0 ) {
1189 $sectionanchor = $wgParser->guessLegacySectionNameFromWikiText( $matches[2] );
1192 $result['sectionanchor'] = $sectionanchor;
1193 wfProfileOut( __METHOD__
. '-sectionanchor' );
1195 // Save errors may fall down to the edit form, but we've now
1196 // merged the section into full text. Clear the section field
1197 // so that later submission of conflict forms won't try to
1198 // replace that into a duplicated mess.
1199 $this->textbox1
= $text;
1200 $this->section
= '';
1202 $status->value
= self
::AS_SUCCESS_UPDATE
;
1205 // Check for length errors again now that the section is merged in
1206 $this->kblength
= (int)( strlen( $text ) / 1024 );
1207 if ( $this->kblength
> $wgMaxArticleSize ) {
1208 $this->tooBig
= true;
1209 $status->setResult( false, self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
);
1210 wfProfileOut( __METHOD__
);
1214 $flags = EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1215 ( $new ? EDIT_NEW
: EDIT_UPDATE
) |
1216 ( ( $this->minoredit
&& !$this->isNew
) ? EDIT_MINOR
: 0 ) |
1217 ( $bot ? EDIT_FORCE_BOT
: 0 );
1219 $doEditStatus = $this->mArticle
->doEdit( $text, $this->summary
, $flags );
1221 if ( $doEditStatus->isOK() ) {
1222 $result['redirect'] = Title
::newFromRedirect( $text ) !== null;
1223 $this->commitWatch();
1224 wfProfileOut( __METHOD__
);
1227 $this->isConflict
= true;
1228 $doEditStatus->value
= self
::AS_END
; // Destroys data doEdit() put in $status->value but who cares
1229 wfProfileOut( __METHOD__
);
1230 return $doEditStatus;
1235 * Commit the change of watch status
1237 protected function commitWatch() {
1239 if ( $this->watchthis
xor $this->mTitle
->userIsWatching() ) {
1240 $dbw = wfGetDB( DB_MASTER
);
1242 if ( $this->watchthis
) {
1243 WatchAction
::doWatch( $this->mTitle
, $wgUser );
1245 WatchAction
::doUnwatch( $this->mTitle
, $wgUser );
1252 * Check if no edits were made by other users since
1253 * the time a user started editing the page. Limit to
1254 * 50 revisions for the sake of performance.
1257 * @param $edittime string
1261 protected function userWasLastToEdit( $id, $edittime ) {
1262 if( !$id ) return false;
1263 $dbw = wfGetDB( DB_MASTER
);
1264 $res = $dbw->select( 'revision',
1267 'rev_page' => $this->mArticle
->getId(),
1268 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1271 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1272 foreach ( $res as $row ) {
1273 if( $row->rev_user
!= $id ) {
1281 * Check given input text against $wgSpamRegex, and return the text of the first match.
1283 * @param $text string
1285 * @return string|false matching string or false
1287 public static function matchSpamRegex( $text ) {
1288 global $wgSpamRegex;
1289 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1290 $regexes = (array)$wgSpamRegex;
1291 return self
::matchSpamRegexInternal( $text, $regexes );
1295 * Check given input text against $wgSpamRegex, and return the text of the first match.
1297 * @parma $text string
1299 * @return string|false matching string or false
1301 public static function matchSummarySpamRegex( $text ) {
1302 global $wgSummarySpamRegex;
1303 $regexes = (array)$wgSummarySpamRegex;
1304 return self
::matchSpamRegexInternal( $text, $regexes );
1308 * @param $text string
1309 * @param $regexes array
1310 * @return bool|string
1312 protected static function matchSpamRegexInternal( $text, $regexes ) {
1313 foreach( $regexes as $regex ) {
1315 if( preg_match( $regex, $text, $matches ) ) {
1323 * Initialise form fields in the object
1324 * Called on the first invocation, e.g. when a user clicks an edit link
1325 * @return bool -- if the requested section is valid
1327 function initialiseForm() {
1329 $this->edittime
= $this->mArticle
->getTimestamp();
1330 $this->textbox1
= $this->getContent( false );
1331 // activate checkboxes if user wants them to be always active
1332 # Sort out the "watch" checkbox
1333 if ( $wgUser->getOption( 'watchdefault' ) ) {
1335 $this->watchthis
= true;
1336 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1338 $this->watchthis
= true;
1339 } elseif ( $this->mTitle
->userIsWatching() ) {
1341 $this->watchthis
= true;
1343 if ( $wgUser->getOption( 'minordefault' ) && !$this->isNew
) {
1344 $this->minoredit
= true;
1346 if ( $this->textbox1
=== false ) {
1353 function setHeaders() {
1355 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1356 if ( $this->formtype
== 'preview' ) {
1357 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1359 if ( $this->isConflict
) {
1360 $wgOut->setPageTitle( wfMsg( 'editconflict', $this->getContextTitle()->getPrefixedText() ) );
1361 } elseif ( $this->section
!= '' ) {
1362 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1363 $wgOut->setPageTitle( wfMsg( $msg, $this->getContextTitle()->getPrefixedText() ) );
1365 # Use the title defined by DISPLAYTITLE magic word when present
1366 if ( isset( $this->mParserOutput
)
1367 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1370 $title = $this->getContextTitle()->getPrefixedText();
1372 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1377 * Send the edit form and related headers to $wgOut
1378 * @param $formCallback Callback that takes an OutputPage parameter; will be called
1379 * during form output near the top, for captchas and the like.
1381 function showEditForm( $formCallback = null ) {
1382 global $wgOut, $wgUser;
1384 wfProfileIn( __METHOD__
);
1386 #need to parse the preview early so that we know which templates are used,
1387 #otherwise users with "show preview after edit box" will get a blank list
1388 #we parse this near the beginning so that setHeaders can do the title
1389 #setting work instead of leaving it in getPreviewText
1390 $previewOutput = '';
1391 if ( $this->formtype
== 'preview' ) {
1392 $previewOutput = $this->getPreviewText();
1395 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) );
1397 $this->setHeaders();
1399 # Enabled article-related sidebar, toplinks, etc.
1400 $wgOut->setArticleRelated( true );
1402 if ( $this->showHeader() === false ) {
1403 wfProfileOut( __METHOD__
);
1407 $action = htmlspecialchars( $this->getActionURL( $this->getContextTitle() ) );
1409 if ( $wgUser->getOption( 'showtoolbar' ) and !$this->isCssJsSubpage
) {
1410 # prepare toolbar for edit buttons
1411 $toolbar = EditPage
::getEditToolbar();
1417 $wgOut->addHTML( $this->editFormPageTop
);
1419 if ( $wgUser->getOption( 'previewontop' ) ) {
1420 $this->displayPreviewArea( $previewOutput, true );
1423 $wgOut->addHTML( $this->editFormTextTop
);
1425 $templates = $this->getTemplates();
1426 $formattedtemplates = Linker
::formatTemplates( $templates, $this->preview
, $this->section
!= '');
1428 $hiddencats = $this->mArticle
->getHiddenCategories();
1429 $formattedhiddencats = Linker
::formatHiddenCategories( $hiddencats );
1431 if ( $this->wasDeletedSinceLastEdit() && 'save' != $this->formtype
) {
1432 $wgOut->wrapWikiMsg(
1433 "<div class='error mw-deleted-while-editing'>\n$1\n</div>",
1434 'deletedwhileediting' );
1435 } elseif ( $this->wasDeletedSinceLastEdit() ) {
1436 // Hide the toolbar and edit area, user can click preview to get it back
1437 // Add an confirmation checkbox and explanation.
1439 // @todo move this to a cleaner conditional instead of blanking a variable
1441 $wgOut->addHTML( <<<HTML
1442 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1446 if ( is_callable( $formCallback ) ) {
1447 call_user_func_array( $formCallback, array( &$wgOut ) );
1450 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1452 // Put these up at the top to ensure they aren't lost on early form submission
1453 $this->showFormBeforeText();
1455 if ( $this->wasDeletedSinceLastEdit() && 'save' == $this->formtype
) {
1456 $username = $this->lastDelete
->user_name
;
1457 $comment = $this->lastDelete
->log_comment
;
1459 // It is better to not parse the comment at all than to have templates expanded in the middle
1460 // TODO: can the checkLabel be moved outside of the div so that wrapWikiMsg could be used?
1461 $key = $comment === ''
1462 ?
'confirmrecreate-noreason'
1463 : 'confirmrecreate';
1465 '<div class="mw-confirm-recreate">' .
1466 wfMsgExt( $key, 'parseinline', $username, "<nowiki>$comment</nowiki>" ) .
1467 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1468 array( 'title' => Linker
::titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1474 # If a blank edit summary was previously provided, and the appropriate
1475 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1476 # user being bounced back more than once in the event that a summary
1479 # For a bit more sophisticated detection of blank summaries, hash the
1480 # automatic one and pass that in the hidden field wpAutoSummary.
1481 if ( $this->missingSummary ||
1482 ( $this->section
== 'new' && $this->nosummary
) )
1483 $wgOut->addHTML( Html
::hidden( 'wpIgnoreBlankSummary', true ) );
1484 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1485 $wgOut->addHTML( Html
::hidden( 'wpAutoSummary', $autosumm ) );
1487 $wgOut->addHTML( Html
::hidden( 'oldid', $this->mArticle
->getOldID() ) );
1489 if ( $this->section
== 'new' ) {
1490 $this->showSummaryInput( true, $this->summary
);
1491 $wgOut->addHTML( $this->getSummaryPreview( true, $this->summary
) );
1494 $wgOut->addHTML( $this->editFormTextBeforeContent
);
1496 $wgOut->addHTML( $toolbar );
1498 if ( $this->isConflict
) {
1499 // In an edit conflict bypass the overrideable content form method
1500 // and fallback to the raw wpTextbox1 since editconflicts can't be
1501 // resolved between page source edits and custom ui edits using the
1503 $this->showTextbox1( null, $this->getContent() );
1505 $this->showContentForm();
1508 $wgOut->addHTML( $this->editFormTextAfterContent
);
1510 $wgOut->addWikiText( $this->getCopywarn() );
1511 if ( isset($this->editFormTextAfterWarn
) && $this->editFormTextAfterWarn
!== '' )
1512 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1514 $this->showStandardInputs();
1516 $this->showFormAfterText();
1518 $this->showTosSummary();
1519 $this->showEditTools();
1521 $wgOut->addHTML( <<<HTML
1522 {$this->editFormTextAfterTools}
1523 <div class='templatesUsed'>
1524 {$formattedtemplates}
1526 <div class='hiddencats'>
1527 {$formattedhiddencats}
1532 if ( $this->isConflict
)
1533 $this->showConflict();
1535 $wgOut->addHTML( $this->editFormTextBottom
);
1536 $wgOut->addHTML( "</form>\n" );
1537 if ( !$wgUser->getOption( 'previewontop' ) ) {
1538 $this->displayPreviewArea( $previewOutput, false );
1541 wfProfileOut( __METHOD__
);
1544 protected function showHeader() {
1545 global $wgOut, $wgUser, $wgMaxArticleSize, $wgLang;
1546 if ( $this->isConflict
) {
1547 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1\n</div>", 'explainconflict' );
1548 $this->edittime
= $this->mArticle
->getTimestamp();
1550 if ( $this->section
!= '' && !$this->isSectionEditSupported() ) {
1551 // We use $this->section to much before this and getVal('wgSection') directly in other places
1552 // at this point we can't reset $this->section to '' to fallback to non-section editing.
1553 // Someone is welcome to try refactoring though
1554 $wgOut->showErrorPage( 'sectioneditnotsupported-title', 'sectioneditnotsupported-text' );
1558 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1560 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1561 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1
, $matches );
1562 if ( !empty( $matches[2] ) ) {
1564 $this->summary
= "/* " .
1565 $wgParser->stripSectionName(trim($matches[2])) .
1571 if ( $this->missingComment
) {
1572 $wgOut->wrapWikiMsg( "<div id='mw-missingcommenttext'>\n$1\n</div>", 'missingcommenttext' );
1575 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1576 $wgOut->wrapWikiMsg( "<div id='mw-missingsummary'>\n$1\n</div>", 'missingsummary' );
1579 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1580 $wgOut->wrapWikiMsg( "<div id='mw-missingcommentheader'>\n$1\n</div>", 'missingcommentheader' );
1583 if ( $this->hookError
!== '' ) {
1584 $wgOut->addWikiText( $this->hookError
);
1587 if ( !$this->checkUnicodeCompliantBrowser() ) {
1588 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1591 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1592 // Let sysop know that this will make private content public if saved
1594 if ( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1595 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
1596 } elseif ( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1597 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
1600 if ( !$this->mArticle
->mRevision
->isCurrent() ) {
1601 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1602 $wgOut->addWikiMsg( 'editingold' );
1607 if ( wfReadOnly() ) {
1608 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1609 } elseif ( $wgUser->isAnon() ) {
1610 if ( $this->formtype
!= 'preview' ) {
1611 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-edit-warning\">\n$1</div>", 'anoneditwarning' );
1613 $wgOut->wrapWikiMsg( "<div id=\"mw-anon-preview-warning\">\n$1</div>", 'anonpreviewwarning' );
1616 if ( $this->isCssJsSubpage
) {
1617 # Check the skin exists
1618 if ( $this->isWrongCaseCssJsPage
) {
1619 $wgOut->wrapWikiMsg( "<div class='error' id='mw-userinvalidcssjstitle'>\n$1\n</div>", array( 'userinvalidcssjstitle', $this->mTitle
->getSkinFromCssJsSubpage() ) );
1621 if ( $this->formtype
!== 'preview' ) {
1622 if ( $this->isCssSubpage
)
1623 $wgOut->wrapWikiMsg( "<div id='mw-usercssyoucanpreview'>\n$1\n</div>", array( 'usercssyoucanpreview' ) );
1624 if ( $this->isJsSubpage
)
1625 $wgOut->wrapWikiMsg( "<div id='mw-userjsyoucanpreview'>\n$1\n</div>", array( 'userjsyoucanpreview' ) );
1630 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
1631 # Is the title semi-protected?
1632 if ( $this->mTitle
->isSemiProtected() ) {
1633 $noticeMsg = 'semiprotectedpagewarning';
1635 # Then it must be protected based on static groups (regular)
1636 $noticeMsg = 'protectedpagewarning';
1638 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1639 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1641 if ( $this->mTitle
->isCascadeProtected() ) {
1642 # Is this page under cascading protection from some source pages?
1643 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1644 $notice = "<div class='mw-cascadeprotectedwarning'>\n$1\n";
1645 $cascadeSourcesCount = count( $cascadeSources );
1646 if ( $cascadeSourcesCount > 0 ) {
1647 # Explain, and list the titles responsible
1648 foreach( $cascadeSources as $page ) {
1649 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1652 $notice .= '</div>';
1653 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1655 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1656 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
, '',
1658 'showIfEmpty' => false,
1659 'msgKey' => array( 'titleprotectedwarning' ),
1660 'wrap' => "<div class=\"mw-titleprotectedwarning\">\n$1</div>" ) );
1663 if ( $this->kblength
=== false ) {
1664 $this->kblength
= (int)( strlen( $this->textbox1
) / 1024 );
1667 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1668 $wgOut->wrapWikiMsg( "<div class='error' id='mw-edit-longpageerror'>\n$1\n</div>",
1669 array( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) ) );
1671 if( !wfMessage('longpage-hint')->isDisabled() ) {
1672 $wgOut->wrapWikiMsg( "<div id='mw-edit-longpage-hint'>\n$1\n</div>",
1673 array( 'longpage-hint', $wgLang->formatSize( strlen( $this->textbox1
) ), strlen( $this->textbox1
) )
1680 * Standard summary input and label (wgSummary), abstracted so EditPage
1681 * subclasses may reorganize the form.
1682 * Note that you do not need to worry about the label's for=, it will be
1683 * inferred by the id given to the input. You can remove them both by
1684 * passing array( 'id' => false ) to $userInputAttrs.
1686 * @param $summary string The value of the summary input
1687 * @param $labelText string The html to place inside the label
1688 * @param $inputAttrs array of attrs to use on the input
1689 * @param $spanLabelAttrs array of attrs to use on the span inside the label
1691 * @return array An array in the format array( $label, $input )
1693 function getSummaryInput($summary = "", $labelText = null, $inputAttrs = null, $spanLabelAttrs = null) {
1694 //Note: the maxlength is overriden in JS to 250 and to make it use UTF-8 bytes, not characters.
1695 $inputAttrs = ( is_array($inputAttrs) ?
$inputAttrs : array() ) +
array(
1696 'id' => 'wpSummary',
1697 'maxlength' => '200',
1700 'spellcheck' => 'true',
1701 ) + Linker
::tooltipAndAccesskeyAttribs( 'summary' );
1703 $spanLabelAttrs = ( is_array($spanLabelAttrs) ?
$spanLabelAttrs : array() ) +
array(
1704 'class' => $this->missingSummary ?
'mw-summarymissed' : 'mw-summary',
1705 'id' => "wpSummaryLabel"
1710 $label = Xml
::tags( 'label', $inputAttrs['id'] ?
array( 'for' => $inputAttrs['id'] ) : null, $labelText );
1711 $label = Xml
::tags( 'span', $spanLabelAttrs, $label );
1714 $input = Html
::input( 'wpSummary', $summary, 'text', $inputAttrs );
1716 return array( $label, $input );
1720 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1721 * up top, or false if this is the comment summary
1722 * down below the textarea
1723 * @param $summary String: The text of the summary to display
1726 protected function showSummaryInput( $isSubjectPreview, $summary = "" ) {
1727 global $wgOut, $wgContLang;
1728 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1729 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1730 if ( $isSubjectPreview ) {
1731 if ( $this->nosummary
) {
1735 if ( !$this->mShowSummaryField
) {
1739 $summary = $wgContLang->recodeForEdit( $summary );
1740 $labelText = wfMsgExt( $isSubjectPreview ?
'subject' : 'summary', 'parseinline' );
1741 list($label, $input) = $this->getSummaryInput($summary, $labelText, array( 'class' => $summaryClass ), array());
1742 $wgOut->addHTML("{$label} {$input}");
1746 * @param $isSubjectPreview Boolean: true if this is the section subject/title
1747 * up top, or false if this is the comment summary
1748 * down below the textarea
1749 * @param $summary String: the text of the summary to display
1752 protected function getSummaryPreview( $isSubjectPreview, $summary = "" ) {
1753 if ( !$summary ||
( !$this->preview
&& !$this->diff
) )
1758 if ( $isSubjectPreview )
1759 $summary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $summary ) );
1761 $message = $isSubjectPreview ?
'subject-preview' : 'summary-preview';
1763 $summary = wfMsgExt( $message, 'parseinline' ) . Linker
::commentBlock( $summary, $this->mTitle
, $isSubjectPreview );
1764 return Xml
::tags( 'div', array( 'class' => 'mw-summary-preview' ), $summary );
1767 protected function showFormBeforeText() {
1769 $section = htmlspecialchars( $this->section
);
1770 $wgOut->addHTML( <<<HTML
1771 <input type='hidden' value="{$section}" name="wpSection" />
1772 <input type='hidden' value="{$this->starttime}" name="wpStarttime" />
1773 <input type='hidden' value="{$this->edittime}" name="wpEdittime" />
1774 <input type='hidden' value="{$this->scrolltop}" name="wpScrolltop" id="wpScrolltop" />
1778 if ( !$this->checkUnicodeCompliantBrowser() )
1779 $wgOut->addHTML(Html
::hidden( 'safemode', '1' ));
1782 protected function showFormAfterText() {
1783 global $wgOut, $wgUser;
1785 * To make it harder for someone to slip a user a page
1786 * which submits an edit form to the wiki without their
1787 * knowledge, a random token is associated with the login
1788 * session. If it's not passed back with the submission,
1789 * we won't save the page, or render user JavaScript and
1792 * For anon editors, who may not have a session, we just
1793 * include the constant suffix to prevent editing from
1794 * broken text-mangling proxies.
1796 $wgOut->addHTML( "\n" . Html
::hidden( "wpEditToken", $wgUser->editToken() ) . "\n" );
1800 * Subpage overridable method for printing the form for page content editing
1801 * By default this simply outputs wpTextbox1
1802 * Subclasses can override this to provide a custom UI for editing;
1803 * be it a form, or simply wpTextbox1 with a modified content that will be
1804 * reverse modified when extracted from the post data.
1805 * Note that this is basically the inverse for importContentFormData
1807 protected function showContentForm() {
1808 $this->showTextbox1();
1812 * Method to output wpTextbox1
1813 * The $textoverride method can be used by subclasses overriding showContentForm
1814 * to pass back to this method.
1816 * @param $customAttribs An array of html attributes to use in the textarea
1817 * @param $textoverride String: optional text to override $this->textarea1 with
1819 protected function showTextbox1($customAttribs = null, $textoverride = null) {
1820 $classes = array(); // Textarea CSS
1821 if ( $this->mTitle
->getNamespace() != NS_MEDIAWIKI
&& $this->mTitle
->isProtected( 'edit' ) ) {
1822 # Is the title semi-protected?
1823 if ( $this->mTitle
->isSemiProtected() ) {
1824 $classes[] = 'mw-textarea-sprotected';
1826 # Then it must be protected based on static groups (regular)
1827 $classes[] = 'mw-textarea-protected';
1829 # Is the title cascade-protected?
1830 if ( $this->mTitle
->isCascadeProtected() ) {
1831 $classes[] = 'mw-textarea-cprotected';
1834 $attribs = array( 'tabindex' => 1 );
1835 if ( is_array($customAttribs) )
1836 $attribs +
= $customAttribs;
1838 if ( $this->wasDeletedSinceLastEdit() )
1839 $attribs['type'] = 'hidden';
1840 if ( !empty( $classes ) ) {
1841 if ( isset($attribs['class']) )
1842 $classes[] = $attribs['class'];
1843 $attribs['class'] = implode( ' ', $classes );
1846 $this->showTextbox( isset($textoverride) ?
$textoverride : $this->textbox1
, 'wpTextbox1', $attribs );
1849 protected function showTextbox2() {
1850 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6, 'readonly' ) );
1853 protected function showTextbox( $content, $name, $customAttribs = array() ) {
1854 global $wgOut, $wgUser;
1856 $wikitext = $this->safeUnicodeOutput( $content );
1857 if ( strval($wikitext) !== '' ) {
1858 // Ensure there's a newline at the end, otherwise adding lines
1860 // But don't add a newline if the ext is empty, or Firefox in XHTML
1861 // mode will show an extra newline. A bit annoying.
1865 $attribs = $customAttribs +
array(
1868 'cols' => $wgUser->getIntOption( 'cols' ),
1869 'rows' => $wgUser->getIntOption( 'rows' ),
1870 'style' => '' // avoid php notices when appending preferences (appending allows customAttribs['style'] to still work
1873 $pageLang = $this->mTitle
->getPageLanguage();
1874 $attribs['lang'] = $pageLang->getCode();
1875 $attribs['dir'] = $pageLang->getDir();
1877 $wgOut->addHTML( Html
::textarea( $name, $wikitext, $attribs ) );
1880 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1884 $classes[] = 'ontop';
1886 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1888 if ( $this->formtype
!= 'preview' )
1889 $attribs['style'] = 'display: none;';
1891 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
1893 if ( $this->formtype
== 'preview' ) {
1894 $this->showPreview( $previewOutput );
1897 $wgOut->addHTML( '</div>' );
1899 if ( $this->formtype
== 'diff') {
1905 * Append preview output to $wgOut.
1906 * Includes category rendering if this is a category page.
1908 * @param $text String: the HTML to be output for the preview.
1910 protected function showPreview( $text ) {
1912 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1913 $this->mArticle
->openShowCategory();
1915 # This hook seems slightly odd here, but makes things more
1916 # consistent for extensions.
1917 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1918 $wgOut->addHTML( $text );
1919 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1920 $this->mArticle
->closeShowCategory();
1925 * Give a chance for site and per-namespace customizations of
1926 * terms of service summary link that might exist separately
1927 * from the copyright notice.
1929 * This will display between the save button and the edit tools,
1930 * so should remain short!
1932 protected function showTosSummary() {
1933 $msg = 'editpage-tos-summary';
1934 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
1935 if( !wfMessage( $msg )->isDisabled() ) {
1937 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1938 $wgOut->addWikiMsg( $msg );
1939 $wgOut->addHTML( '</div>' );
1943 protected function showEditTools() {
1945 $wgOut->addHTML( '<div class="mw-editTools">' .
1946 wfMessage( 'edittools' )->inContentLanguage()->parse() .
1950 protected function getCopywarn() {
1951 global $wgRightsText;
1952 if ( $wgRightsText ) {
1953 $copywarnMsg = array( 'copyrightwarning',
1954 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1957 $copywarnMsg = array( 'copyrightwarning2',
1958 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1960 // Allow for site and per-namespace customization of contribution/copyright notice.
1961 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
1963 return "<div id=\"editpage-copywarn\">\n" .
1964 call_user_func_array("wfMsgNoTrans", $copywarnMsg) . "\n</div>";
1967 protected function showStandardInputs( &$tabindex = 2 ) {
1969 $wgOut->addHTML( "<div class='editOptions'>\n" );
1971 if ( $this->section
!= 'new' ) {
1972 $this->showSummaryInput( false, $this->summary
);
1973 $wgOut->addHTML( $this->getSummaryPreview( false, $this->summary
) );
1976 $checkboxes = $this->getCheckboxes( $tabindex,
1977 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1978 $wgOut->addHTML( "<div class='editCheckboxes'>" . implode( $checkboxes, "\n" ) . "</div>\n" );
1979 $wgOut->addHTML( "<div class='editButtons'>\n" );
1980 $wgOut->addHTML( implode( $this->getEditButtons( $tabindex ), "\n" ) . "\n" );
1982 $cancel = $this->getCancelLink();
1983 if ( $cancel !== '' ) {
1984 $cancel .= wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1986 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ) );
1987 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1988 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1989 htmlspecialchars( wfMsg( 'newwindow' ) );
1990 $wgOut->addHTML( " <span class='editHelp'>{$cancel}{$edithelp}</span>\n" );
1991 $wgOut->addHTML( "</div><!-- editButtons -->\n</div><!-- editOptions -->\n" );
1995 * Show an edit conflict. textbox1 is already shown in showEditForm().
1996 * If you want to use another entry point to this function, be careful.
1998 protected function showConflict() {
2000 $this->textbox2
= $this->textbox1
;
2001 $this->textbox1
= $this->getContent();
2002 if ( wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
2003 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2005 $de = new DifferenceEngine( $this->mTitle
);
2006 $de->setText( $this->textbox2
, $this->textbox1
);
2007 $de->showDiff( wfMsgExt( 'yourtext', 'parseinline' ), wfMsg( 'storedversion' ) );
2009 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2010 $this->showTextbox2();
2014 protected function getLastDelete() {
2015 $dbr = wfGetDB( DB_SLAVE
);
2016 $data = $dbr->selectRow(
2017 array( 'logging', 'user' ),
2028 array( 'log_namespace' => $this->mTitle
->getNamespace(),
2029 'log_title' => $this->mTitle
->getDBkey(),
2030 'log_type' => 'delete',
2031 'log_action' => 'delete',
2032 'user_id=log_user' ),
2034 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
2036 // Quick paranoid permission checks...
2037 if( is_object( $data ) ) {
2038 if( $data->log_deleted
& LogPage
::DELETED_USER
)
2039 $data->user_name
= wfMsgHtml( 'rev-deleted-user' );
2040 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
2041 $data->log_comment
= wfMsgHtml( 'rev-deleted-comment' );
2047 * Get the rendered text for previewing.
2050 function getPreviewText() {
2051 global $wgOut, $wgUser, $wgParser;
2053 wfProfileIn( __METHOD__
);
2055 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
2056 if ( $this->mTokenOkExceptSuffix
) {
2057 $note = wfMsg( 'token_suffix_mismatch' );
2059 $note = wfMsg( 'session_fail_preview' );
2061 } elseif ( $this->incompleteForm
) {
2062 $note = wfMsg( 'edit_form_incomplete' );
2064 $note = wfMsg( 'previewnote' );
2067 $parserOptions = ParserOptions
::newFromUser( $wgUser );
2068 $parserOptions->setEditSection( false );
2069 $parserOptions->setIsPreview( true );
2070 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
2073 if ( $wgRawHtml && !$this->mTokenOk
) {
2074 // Could be an offsite preview attempt. This is very unsafe if
2075 // HTML is enabled, as it could be an attack.
2077 if ( $this->textbox1
!== '' ) {
2078 // Do not put big scary notice, if previewing the empty
2079 // string, which happens when you initially edit
2080 // a category page, due to automatic preview-on-open.
2081 $parsedNote = $wgOut->parse( "<div class='previewnote'>" .
2082 wfMsg( 'session_fail_preview_html' ) . "</div>", true, /* interface */true );
2084 wfProfileOut( __METHOD__
);
2088 # don't parse non-wikitext pages, show message about preview
2089 # XXX: stupid php bug won't let us use $this->getContextTitle()->isCssJsSubpage() here -- This note has been there since r3530. Sure the bug was fixed time ago?
2091 if ( $this->isCssJsSubpage ||
!$this->mTitle
->isWikitextPage() ) {
2092 if( $this->mTitle
->isCssJsSubpage() ) {
2094 } elseif( $this->mTitle
->isCssOrJsPage() ) {
2100 # Used messages to make sure grep find them:
2101 # Messages: usercsspreview, userjspreview, sitecsspreview, sitejspreview
2103 if (preg_match( "/\\.css$/", $this->mTitle
->getText() ) ) {
2104 $previewtext = "<div id='mw-{$level}csspreview'>\n" . wfMsg( "{$level}csspreview" ) . "\n</div>";
2105 $class = "mw-code mw-css";
2106 } elseif (preg_match( "/\\.js$/", $this->mTitle
->getText() ) ) {
2107 $previewtext = "<div id='mw-{$level}jspreview'>\n" . wfMsg( "{$level}jspreview" ) . "\n</div>";
2108 $class = "mw-code mw-js";
2110 throw new MWException( 'A CSS/JS (sub)page but which is not css nor js!' );
2114 $parserOptions->setTidy( true );
2115 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
2116 $previewHTML = $parserOutput->mText
;
2117 $previewHTML .= "<pre class=\"$class\" dir=\"ltr\">\n" . htmlspecialchars( $this->textbox1
) . "\n</pre>\n";
2119 $rt = Title
::newFromRedirectArray( $this->textbox1
);
2121 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
2123 $toparse = $this->textbox1
;
2125 # If we're adding a comment, we need to show the
2126 # summary as the headline
2127 if ( $this->section
== "new" && $this->summary
!= "" ) {
2128 $toparse = "== {$this->summary} ==\n\n" . $toparse;
2131 wfRunHooks( 'EditPageGetPreviewText', array( $this, &$toparse ) );
2133 $parserOptions->setTidy( true );
2134 $parserOptions->enableLimitReport();
2135 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ),
2136 $this->mTitle
, $parserOptions );
2138 $previewHTML = $parserOutput->getText();
2139 $this->mParserOutput
= $parserOutput;
2140 $wgOut->addParserOutputNoText( $parserOutput );
2142 if ( count( $parserOutput->getWarnings() ) ) {
2143 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
2148 if( $this->isConflict
) {
2149 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
2151 $conflict = '<hr />';
2154 $previewhead = "<div class='previewnote'>\n" .
2155 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
2156 $wgOut->parse( $note, true, /* interface */true ) . $conflict . "</div>\n";
2158 $pageLang = $this->mTitle
->getPageLanguage();
2159 $attribs = array( 'lang' => $pageLang->getCode(), 'dir' => $pageLang->getDir(),
2160 'class' => 'mw-content-'.$pageLang->getDir() );
2161 $previewHTML = Html
::rawElement( 'div', $attribs, $previewHTML );
2163 wfProfileOut( __METHOD__
);
2164 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
2170 function getTemplates() {
2171 if ( $this->preview ||
$this->section
!= '' ) {
2172 $templates = array();
2173 if ( !isset( $this->mParserOutput
) ) {
2176 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
2177 foreach( array_keys( $template ) as $dbk ) {
2178 $templates[] = Title
::makeTitle($ns, $dbk);
2183 return $this->mArticle
->getUsedTemplates();
2188 * Call the stock "user is blocked" page
2190 function blockedPage() {
2192 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
2194 # If the user made changes, preserve them when showing the markup
2195 # (This happens when a user is blocked during edit, for instance)
2196 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
2198 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
2200 $source = $this->textbox1
;
2203 # Spit out the source or the user's modified version
2204 if ( $source !== false ) {
2205 $wgOut->addHTML( '<hr />' );
2206 $wgOut->addWikiMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() );
2207 $this->showTextbox1( array( 'readonly' ), $source );
2212 * Produce the stock "please login to edit pages" page
2214 function userNotLoggedInPage() {
2217 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
2218 $loginLink = Linker
::linkKnown(
2220 wfMsgHtml( 'loginreqlink' ),
2222 array( 'returnto' => $this->getContextTitle()->getPrefixedText() )
2225 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
2226 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2227 $wgOut->setArticleRelated( false );
2229 $wgOut->addHTML( wfMessage( 'whitelistedittext' )->rawParams( $loginLink )->parse() );
2230 $wgOut->returnToMain( false, $this->getContextTitle() );
2234 * Creates a basic error page which informs the user that
2235 * they have attempted to edit a nonexistent section.
2237 function noSuchSectionPage() {
2240 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
2241 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2242 $wgOut->setArticleRelated( false );
2244 $res = wfMsgExt( 'nosuchsectiontext', 'parse', $this->section
);
2245 wfRunHooks( 'EditPageNoSuchSection', array( &$this, &$res ) );
2246 $wgOut->addHTML( $res );
2248 $wgOut->returnToMain( false, $this->mTitle
);
2252 * Produce the stock "your edit contains spam" page
2254 * @param $match Text which triggered one or more filters
2255 * @deprecated since 1.17 Use method spamPageWithContent() instead
2257 static function spamPage( $match = false ) {
2258 global $wgOut, $wgTitle;
2260 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
2261 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2262 $wgOut->setArticleRelated( false );
2264 $wgOut->addHTML( '<div id="spamprotected">' );
2265 $wgOut->addWikiMsg( 'spamprotectiontext' );
2267 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2269 $wgOut->addHTML( '</div>' );
2271 $wgOut->returnToMain( false, $wgTitle );
2275 * Show "your edit contains spam" page with your diff and text
2277 * @param $match Text which triggered one or more filters
2279 public function spamPageWithContent( $match = false ) {
2281 $this->textbox2
= $this->textbox1
;
2283 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
2284 $wgOut->setRobotPolicy( 'noindex,nofollow' );
2285 $wgOut->setArticleRelated( false );
2287 $wgOut->addHTML( '<div id="spamprotected">' );
2288 $wgOut->addWikiMsg( 'spamprotectiontext' );
2290 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
2292 $wgOut->addHTML( '</div>' );
2294 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourdiff" );
2295 $de = new DifferenceEngine( $this->mTitle
);
2296 $de->setText( $this->getContent(), $this->textbox2
);
2297 $de->showDiff( wfMsg( "storedversion" ), wfMsgExt( 'yourtext', 'parseinline' ) );
2299 $wgOut->wrapWikiMsg( '<h2>$1</h2>', "yourtext" );
2300 $this->showTextbox2();
2302 $wgOut->addReturnTo( $this->getContextTitle(), array( 'action' => 'edit' ) );
2310 * @parma $editText string
2314 function mergeChangesInto( &$editText ){
2315 wfProfileIn( __METHOD__
);
2317 $db = wfGetDB( DB_MASTER
);
2319 // This is the revision the editor started from
2320 $baseRevision = $this->getBaseRevision();
2321 if ( is_null( $baseRevision ) ) {
2322 wfProfileOut( __METHOD__
);
2325 $baseText = $baseRevision->getText();
2327 // The current state, we want to merge updates into it
2328 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2329 if ( is_null( $currentRevision ) ) {
2330 wfProfileOut( __METHOD__
);
2333 $currentText = $currentRevision->getText();
2336 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
2337 $editText = $result;
2338 wfProfileOut( __METHOD__
);
2341 wfProfileOut( __METHOD__
);
2347 * Check if the browser is on a blacklist of user-agents known to
2348 * mangle UTF-8 data on form submission. Returns true if Unicode
2349 * should make it through, false if it's known to be a problem.
2353 function checkUnicodeCompliantBrowser() {
2354 global $wgBrowserBlackList;
2355 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2356 // No User-Agent header sent? Trust it by default...
2359 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2360 foreach ( $wgBrowserBlackList as $browser ) {
2361 if ( preg_match($browser, $currentbrowser) ) {
2369 * Format an anchor fragment as it would appear for a given section name
2370 * @param $text String
2374 function sectionAnchor( $text ) {
2376 return $wgParser->guessSectionNameFromWikiText( $text );
2380 * Shows a bulletin board style toolbar for common editing functions.
2381 * It can be disabled in the user preferences.
2382 * The necessary JavaScript code can be found in skins/common/edit.js.
2386 static function getEditToolbar() {
2387 global $wgStylePath, $wgContLang, $wgLang, $wgOut;
2388 global $wgUseTeX, $wgEnableUploads, $wgForeignFileRepos;
2390 $imagesAvailable = $wgEnableUploads ||
count( $wgForeignFileRepos );
2393 * $toolarray is an array of arrays each of which includes the
2394 * filename of the button image (without path), the opening
2395 * tag, the closing tag, optionally a sample text that is
2396 * inserted between the two when no selection is highlighted
2397 * and. The tip text is shown when the user moves the mouse
2400 * Also here: accesskeys (key), which are not used yet until
2401 * someone can figure out a way to make them work in
2402 * IE. However, we should make sure these keys are not defined
2407 'image' => $wgLang->getImageFile( 'button-bold' ),
2408 'id' => 'mw-editbutton-bold',
2410 'close' => '\'\'\'',
2411 'sample' => wfMsg( 'bold_sample' ),
2412 'tip' => wfMsg( 'bold_tip' ),
2416 'image' => $wgLang->getImageFile( 'button-italic' ),
2417 'id' => 'mw-editbutton-italic',
2420 'sample' => wfMsg( 'italic_sample' ),
2421 'tip' => wfMsg( 'italic_tip' ),
2425 'image' => $wgLang->getImageFile( 'button-link' ),
2426 'id' => 'mw-editbutton-link',
2429 'sample' => wfMsg( 'link_sample' ),
2430 'tip' => wfMsg( 'link_tip' ),
2434 'image' => $wgLang->getImageFile( 'button-extlink' ),
2435 'id' => 'mw-editbutton-extlink',
2438 'sample' => wfMsg( 'extlink_sample' ),
2439 'tip' => wfMsg( 'extlink_tip' ),
2443 'image' => $wgLang->getImageFile( 'button-headline' ),
2444 'id' => 'mw-editbutton-headline',
2447 'sample' => wfMsg( 'headline_sample' ),
2448 'tip' => wfMsg( 'headline_tip' ),
2451 $imagesAvailable ?
array(
2452 'image' => $wgLang->getImageFile( 'button-image' ),
2453 'id' => 'mw-editbutton-image',
2454 'open' => '[[' . $wgContLang->getNsText( NS_FILE
) . ':',
2456 'sample' => wfMsg( 'image_sample' ),
2457 'tip' => wfMsg( 'image_tip' ),
2460 $imagesAvailable ?
array(
2461 'image' => $wgLang->getImageFile( 'button-media' ),
2462 'id' => 'mw-editbutton-media',
2463 'open' => '[[' . $wgContLang->getNsText( NS_MEDIA
) . ':',
2465 'sample' => wfMsg( 'media_sample' ),
2466 'tip' => wfMsg( 'media_tip' ),
2470 'image' => $wgLang->getImageFile( 'button-math' ),
2471 'id' => 'mw-editbutton-math',
2473 'close' => "</math>",
2474 'sample' => wfMsg( 'math_sample' ),
2475 'tip' => wfMsg( 'math_tip' ),
2479 'image' => $wgLang->getImageFile( 'button-nowiki' ),
2480 'id' => 'mw-editbutton-nowiki',
2481 'open' => "<nowiki>",
2482 'close' => "</nowiki>",
2483 'sample' => wfMsg( 'nowiki_sample' ),
2484 'tip' => wfMsg( 'nowiki_tip' ),
2488 'image' => $wgLang->getImageFile( 'button-sig' ),
2489 'id' => 'mw-editbutton-signature',
2493 'tip' => wfMsg( 'sig_tip' ),
2497 'image' => $wgLang->getImageFile( 'button-hr' ),
2498 'id' => 'mw-editbutton-hr',
2499 'open' => "\n----\n",
2502 'tip' => wfMsg( 'hr_tip' ),
2508 foreach ( $toolarray as $tool ) {
2514 $image = $wgStylePath . '/common/images/' . $tool['image'],
2515 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2516 // Older browsers show a "speedtip" type message only for ALT.
2517 // Ideally these should be different, realistically they
2518 // probably don't need to be.
2519 $tip = $tool['tip'],
2520 $open = $tool['open'],
2521 $close = $tool['close'],
2522 $sample = $tool['sample'],
2523 $cssId = $tool['id'],
2526 $script .= Xml
::encodeJsCall( 'mw.toolbar.addButton', $params );
2528 $wgOut->addScript( Html
::inlineScript( ResourceLoader
::makeLoaderConditionalScript( $script ) ) );
2530 $toolbar = '<div id="toolbar"></div>';
2532 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2538 * Returns an array of html code of the following checkboxes:
2541 * @param $tabindex Current tabindex
2542 * @param $checked Array of checkbox => bool, where bool indicates the checked
2543 * status of the checkbox
2547 public function getCheckboxes( &$tabindex, $checked ) {
2550 $checkboxes = array();
2552 // don't show the minor edit checkbox if it's a new page or section
2553 if ( !$this->isNew
) {
2554 $checkboxes['minor'] = '';
2555 $minorLabel = wfMsgExt( 'minoredit', array( 'parseinline' ) );
2556 if ( $wgUser->isAllowed( 'minoredit' ) ) {
2558 'tabindex' => ++
$tabindex,
2559 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2560 'id' => 'wpMinoredit',
2562 $checkboxes['minor'] =
2563 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2564 " <label for='wpMinoredit' id='mw-editpage-minoredit'" .
2565 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'minoredit', 'withaccess' ) ) ) .
2566 ">{$minorLabel}</label>";
2570 $watchLabel = wfMsgExt( 'watchthis', array( 'parseinline' ) );
2571 $checkboxes['watch'] = '';
2572 if ( $wgUser->isLoggedIn() ) {
2574 'tabindex' => ++
$tabindex,
2575 'accesskey' => wfMsg( 'accesskey-watch' ),
2576 'id' => 'wpWatchthis',
2578 $checkboxes['watch'] =
2579 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2580 " <label for='wpWatchthis' id='mw-editpage-watch'" .
2581 Xml
::expandAttributes( array( 'title' => Linker
::titleAttrib( 'watch', 'withaccess' ) ) ) .
2582 ">{$watchLabel}</label>";
2584 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2589 * Returns an array of html code of the following buttons:
2590 * save, diff, preview and live
2592 * @param $tabindex Current tabindex
2596 public function getEditButtons( &$tabindex ) {
2603 'tabindex' => ++
$tabindex,
2604 'value' => wfMsg( 'savearticle' ),
2605 'accesskey' => wfMsg( 'accesskey-save' ),
2606 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2608 $buttons['save'] = Xml
::element('input', $temp, '');
2610 ++
$tabindex; // use the same for preview and live preview
2612 'id' => 'wpPreview',
2613 'name' => 'wpPreview',
2615 'tabindex' => $tabindex,
2616 'value' => wfMsg( 'showpreview' ),
2617 'accesskey' => wfMsg( 'accesskey-preview' ),
2618 'title' => wfMsg( 'tooltip-preview' ) . ' [' . wfMsg( 'accesskey-preview' ) . ']',
2620 $buttons['preview'] = Xml
::element( 'input', $temp, '' );
2621 $buttons['live'] = '';
2627 'tabindex' => ++
$tabindex,
2628 'value' => wfMsg( 'showdiff' ),
2629 'accesskey' => wfMsg( 'accesskey-diff' ),
2630 'title' => wfMsg( 'tooltip-diff' ) . ' [' . wfMsg( 'accesskey-diff' ) . ']',
2632 $buttons['diff'] = Xml
::element( 'input', $temp, '' );
2634 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2639 * Output preview text only. This can be sucked into the edit page
2640 * via JavaScript, and saves the server time rendering the skin as
2641 * well as theoretically being more robust on the client (doesn't
2642 * disturb the edit box's undo history, won't eat your text on
2645 * @todo This doesn't include category or interlanguage links.
2646 * Would need to enhance it a bit, <s>maybe wrap them in XML
2647 * or something...</s> that might also require more skin
2648 * initialization, so check whether that's a problem.
2650 function livePreview() {
2653 header( 'Content-type: text/xml; charset=utf-8' );
2654 header( 'Cache-control: no-cache' );
2656 $previewText = $this->getPreviewText();
2657 #$categories = $skin->getCategoryLinks();
2660 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2661 Xml
::tags( 'livepreview', null,
2662 Xml
::element( 'preview', null, $previewText )
2663 #. Xml::element( 'category', null, $categories )
2671 public function getCancelLink() {
2672 $cancelParams = array();
2673 if ( !$this->isConflict
&& $this->mArticle
->getOldID() > 0 ) {
2674 $cancelParams['oldid'] = $this->mArticle
->getOldID();
2677 return Linker
::linkKnown(
2678 $this->getContextTitle(),
2679 wfMsgExt( 'cancel', array( 'parseinline' ) ),
2680 array( 'id' => 'mw-editform-cancel' ),
2686 * Get a diff between the current contents of the edit box and the
2687 * version of the page we're editing from.
2689 * If this is a section edit, we'll replace the section as for final
2690 * save and then make a comparison.
2692 function showDiff() {
2693 $oldtext = $this->mArticle
->fetchContent();
2694 $newtext = $this->mArticle
->replaceSection(
2695 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2697 wfRunHooks( 'EditPageGetDiffText', array( $this, &$newtext ) );
2699 $newtext = $this->mArticle
->preSaveTransform( $newtext );
2700 $oldtitle = wfMsgExt( 'currentrev', array( 'parseinline' ) );
2701 $newtitle = wfMsgExt( 'yourtext', array( 'parseinline' ) );
2702 if ( $oldtext !== false ||
$newtext != '' ) {
2703 $de = new DifferenceEngine( $this->mTitle
);
2704 $de->setText( $oldtext, $newtext );
2705 $difftext = $de->getDiff( $oldtitle, $newtitle );
2706 $de->showDiffStyle();
2712 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2716 * Filter an input field through a Unicode de-armoring process if it
2717 * came from an old browser with known broken Unicode editing issues.
2719 * @param $request WebRequest
2720 * @param $field String
2724 function safeUnicodeInput( $request, $field ) {
2725 $text = rtrim( $request->getText( $field ) );
2726 return $request->getBool( 'safemode' )
2727 ?
$this->unmakesafe( $text )
2732 * @param $request WebRequest
2733 * @param $text string
2736 function safeUnicodeText( $request, $text ) {
2737 $text = rtrim( $text );
2738 return $request->getBool( 'safemode' )
2739 ?
$this->unmakesafe( $text )
2744 * Filter an output field through a Unicode armoring process if it is
2745 * going to an old browser with known broken Unicode editing issues.
2747 * @param $text String
2751 function safeUnicodeOutput( $text ) {
2753 $codedText = $wgContLang->recodeForEdit( $text );
2754 return $this->checkUnicodeCompliantBrowser()
2756 : $this->makesafe( $codedText );
2760 * A number of web browsers are known to corrupt non-ASCII characters
2761 * in a UTF-8 text editing environment. To protect against this,
2762 * detected browsers will be served an armored version of the text,
2763 * with non-ASCII chars converted to numeric HTML character references.
2765 * Preexisting such character references will have a 0 added to them
2766 * to ensure that round-trips do not alter the original data.
2768 * @param $invalue String
2772 function makesafe( $invalue ) {
2773 // Armor existing references for reversability.
2774 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2779 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2780 $bytevalue = ord( $invalue[$i] );
2781 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2782 $result .= chr( $bytevalue );
2784 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2785 $working = $working << 6;
2786 $working +
= ($bytevalue & 0x3F);
2788 if ( $bytesleft <= 0 ) {
2789 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2791 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2792 $working = $bytevalue & 0x1F;
2794 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2795 $working = $bytevalue & 0x0F;
2797 } else { //1111 0xxx
2798 $working = $bytevalue & 0x07;
2806 * Reverse the previously applied transliteration of non-ASCII characters
2807 * back to UTF-8. Used to protect data from corruption by broken web browsers
2808 * as listed in $wgBrowserBlackList.
2810 * @param $invalue String
2814 function unmakesafe( $invalue ) {
2816 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2817 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue[$i+
3] != '0' ) ) {
2821 $hexstring .= $invalue[$i];
2823 } while( ctype_xdigit( $invalue[$i] ) && ( $i < strlen( $invalue ) ) );
2825 // Do some sanity checks. These aren't needed for reversability,
2826 // but should help keep the breakage down if the editor
2827 // breaks one of the entities whilst editing.
2828 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2829 $codepoint = hexdec($hexstring);
2830 $result .= codepointToUtf8( $codepoint );
2832 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2835 $result .= substr( $invalue, $i, 1 );
2838 // reverse the transform that we made for reversability reasons.
2839 return strtr( $result, array( "�" => "&#x" ) );
2842 function noCreatePermission() {
2844 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2845 $wgOut->addWikiMsg( 'nocreatetext' );
2849 * Attempt submission
2850 * @return bool false if output is done, true if the rest of the form should be displayed
2852 function attemptSave() {
2853 global $wgUser, $wgOut;
2855 $resultDetails = false;
2856 # Allow bots to exempt some edits from bot flagging
2857 $bot = $wgUser->isAllowed( 'bot' ) && $this->bot
;
2858 $status = $this->internalAttemptSave( $resultDetails, $bot );
2859 // FIXME: once the interface for internalAttemptSave() is made nicer, this should use the message in $status
2861 if ( $status->value
== self
::AS_SUCCESS_UPDATE ||
$status->value
== self
::AS_SUCCESS_NEW_ARTICLE
) {
2862 $this->didSave
= true;
2865 switch ( $status->value
) {
2866 case self
::AS_HOOK_ERROR_EXPECTED
:
2867 case self
::AS_CONTENT_TOO_BIG
:
2868 case self
::AS_ARTICLE_WAS_DELETED
:
2869 case self
::AS_CONFLICT_DETECTED
:
2870 case self
::AS_SUMMARY_NEEDED
:
2871 case self
::AS_TEXTBOX_EMPTY
:
2872 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
2876 case self
::AS_HOOK_ERROR
:
2877 case self
::AS_FILTERING
:
2880 case self
::AS_SUCCESS_NEW_ARTICLE
:
2881 $query = $resultDetails['redirect'] ?
'redirect=no' : '';
2882 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) );
2885 case self
::AS_SUCCESS_UPDATE
:
2887 $sectionanchor = $resultDetails['sectionanchor'];
2889 // Give extensions a chance to modify URL query on update
2890 wfRunHooks( 'ArticleUpdateBeforeRedirect', array( $this->mArticle
, &$sectionanchor, &$extraQuery ) );
2892 if ( $resultDetails['redirect'] ) {
2893 if ( $extraQuery == '' ) {
2894 $extraQuery = 'redirect=no';
2896 $extraQuery = 'redirect=no&' . $extraQuery;
2899 $wgOut->redirect( $this->mTitle
->getFullURL( $extraQuery ) . $sectionanchor );
2902 case self
::AS_SPAM_ERROR
:
2903 $this->spamPageWithContent( $resultDetails['spam'] );
2906 case self
::AS_BLOCKED_PAGE_FOR_USER
:
2907 $this->blockedPage();
2910 case self
::AS_IMAGE_REDIRECT_ANON
:
2911 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2914 case self
::AS_READ_ONLY_PAGE_ANON
:
2915 $this->userNotLoggedInPage();
2918 case self
::AS_READ_ONLY_PAGE_LOGGED
:
2919 case self
::AS_READ_ONLY_PAGE
:
2920 $wgOut->readOnlyPage();
2923 case self
::AS_RATE_LIMITED
:
2924 $wgOut->rateLimited();
2927 case self
::AS_NO_CREATE_PERMISSION
:
2928 $this->noCreatePermission();
2931 case self
::AS_BLANK_ARTICLE
:
2932 $wgOut->redirect( $this->getContextTitle()->getFullURL() );
2935 case self
::AS_IMAGE_REDIRECT_LOGGED
:
2936 $wgOut->permissionRequired( 'upload' );
2944 function getBaseRevision() {
2945 if ( !$this->mBaseRevision
) {
2946 $db = wfGetDB( DB_MASTER
);
2947 $baseRevision = Revision
::loadFromTimestamp(
2948 $db, $this->mTitle
, $this->edittime
);
2949 return $this->mBaseRevision
= $baseRevision;
2951 return $this->mBaseRevision
;