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;
49 var $isConflict = false;
50 var $isCssJsSubpage = false;
51 var $isCssSubpage = false;
52 var $isJsSubpage = false;
53 var $deletedSinceEdit = false;
57 var $mTokenOk = false;
58 var $mTokenOkExceptSuffix = false;
59 var $mTriedSave = false;
61 var $kblength = false;
62 var $missingComment = false;
63 var $missingSummary = false;
64 var $allowBlankSummary = false;
67 #var $mPreviewTemplates;
69 var $mBaseRevision = false;
72 var $save = false, $preview = false, $diff = false;
73 var $minoredit = false, $watchthis = false, $recreate = false;
74 var $textbox1 = '', $textbox2 = '', $summary = '';
75 var $edittime = '', $section = '', $starttime = '';
76 var $oldid = 0, $editintro = '', $scrolltop = null;
78 # Placeholders for text injection by hooks (must be HTML)
79 # extensions should take care to _append_ to the present value
80 public $editFormPageTop; // Before even the preview
81 public $editFormTextTop;
82 public $editFormTextBeforeContent;
83 public $editFormTextAfterWarn;
84 public $editFormTextAfterTools;
85 public $editFormTextBottom;
86 public $editFormTextAfterContent;
87 public $previewTextAfterContent;
89 /* $didSave should be set to true whenever an article was succesfully altered. */
90 public $didSave = false;
93 public $suppressIntro = false;
99 function EditPage( $article ) {
100 $this->mArticle
=& $article;
101 $this->mTitle
= $article->getTitle();
102 $this->action
= 'submit';
104 # Placeholders for text injection by hooks (empty per default)
105 $this->editFormPageTop
=
106 $this->editFormTextTop
=
107 $this->editFormTextBeforeContent
=
108 $this->editFormTextAfterWarn
=
109 $this->editFormTextAfterTools
=
110 $this->editFormTextBottom
=
111 $this->editFormTextAfterContent
=
112 $this->previewTextAfterContent
=
113 $this->mPreloadText
= "";
116 function getArticle() {
117 return $this->mArticle
;
122 * Fetch initial editing page content.
125 function getContent( $def_text = '' ) {
126 global $wgOut, $wgRequest, $wgParser, $wgContLang, $wgMessageCache;
128 wfProfileIn( __METHOD__
);
129 # Get variables from query string :P
130 $section = $wgRequest->getVal( 'section' );
131 $preload = $wgRequest->getVal( 'preload' );
132 $undoafter = $wgRequest->getVal( 'undoafter' );
133 $undo = $wgRequest->getVal( 'undo' );
136 // For message page not locally set, use the i18n message.
137 // For other non-existent articles, use preload text if any.
138 if ( !$this->mTitle
->exists() ) {
139 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
140 # If this is a system message, get the default text.
141 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
142 $wgMessageCache->loadAllMessages( $lang );
143 $text = wfMsgGetKey( $message, false, $lang, false );
144 if( wfEmptyMsg( $message, $text ) )
145 $text = $this->getPreloadedText( $preload );
147 # If requested, preload some text.
148 $text = $this->getPreloadedText( $preload );
150 // For existing pages, get text based on "undo" or section parameters.
152 $text = $this->mArticle
->getContent();
153 if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
154 # If they got undoafter and undo round the wrong way, switch them
155 list( $undo, $undoafter ) = array( $undoafter, $undo );
157 if ( $undo > 0 && $undo > $undoafter ) {
158 # Undoing a specific edit overrides section editing; section-editing
159 # doesn't work with undoing.
161 $undorev = Revision
::newFromId($undo);
162 $oldrev = Revision
::newFromId($undoafter);
164 $undorev = Revision
::newFromId($undo);
165 $oldrev = $undorev ?
$undorev->getPrevious() : null;
168 # Sanity check, make sure it's the right page,
169 # the revisions exist and they were not deleted.
170 # Otherwise, $text will be left as-is.
171 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
172 $undorev->getPage() == $oldrev->getPage() &&
173 $undorev->getPage() == $this->mArticle
->getID() &&
174 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
175 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
177 $undotext = $this->mArticle
->getUndoText( $undorev, $oldrev );
178 if ( $undotext === false ) {
179 # Warn the user that something went wrong
180 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-failure">' . wfMsgNoTrans( 'undo-failure' ) . '</div>' );
183 # Inform the user of our success and set an automatic edit summary
184 $this->editFormPageTop
.= $wgOut->parse( '<div class="mw-undo-success">' . wfMsgNoTrans( 'undo-success' ) . '</div>' );
185 $firstrev = $oldrev->getNext();
186 # If we just undid one rev, use an autosummary
187 if ( $firstrev->mId
== $undo ) {
188 $this->summary
= wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
189 $this->undidRev
= $undo;
191 $this->formtype
= 'diff';
194 // Failed basic sanity checks.
195 // Older revisions may have been removed since the link
196 // was created, or we may simply have got bogus input.
197 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-norev">' . wfMsgNoTrans( 'undo-norev' ) . '</div>' );
199 } else if ( $section != '' ) {
200 if ( $section == 'new' ) {
201 $text = $this->getPreloadedText( $preload );
203 $text = $wgParser->getSection( $text, $section, $def_text );
208 wfProfileOut( __METHOD__
);
212 /** Use this method before edit() to preload some text into the edit box */
213 public function setPreloadedText( $text ) {
214 $this->mPreloadText
= $text;
218 * Get the contents of a page from its title and remove includeonly tags
220 * @param $preload String: the title of the page.
221 * @return string The contents of the page.
223 protected function getPreloadedText( $preload ) {
224 if ( !empty($this->mPreloadText
) ) {
225 return $this->mPreloadText
;
226 } elseif ( $preload === '' ) {
229 $preloadTitle = Title
::newFromText( $preload );
230 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
231 $rev = Revision
::newFromTitle($preloadTitle);
232 if ( is_object( $rev ) ) {
233 $text = $rev->getText();
234 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
235 // its own mini-parser! -ævar
236 $text = preg_replace( '~</?includeonly>~', '', $text );
245 * This is the function that extracts metadata from the article body on the first view.
246 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
247 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
249 function extractMetaDataFromArticle () {
250 global $wgUseMetadataEdit, $wgMetadataWhitelist, $wgContLang;
251 $this->mMetaData
= '';
252 if ( !$wgUseMetadataEdit ) return;
253 if ( $wgMetadataWhitelist == '' ) return;
255 $t = $this->getContent();
257 # MISSING : <nowiki> filtering
259 # Categories and language links
260 $t = explode ( "\n" , $t );
261 $catlow = strtolower ( $wgContLang->getNsText( NS_CATEGORY
) );
262 $cat = $ll = array();
263 foreach ( $t AS $key => $x ) {
264 $y = trim ( strtolower ( $x ) );
265 while ( substr ( $y , 0 , 2 ) == '[[' ) {
266 $y = explode ( ']]' , trim ( $x ) );
267 $first = array_shift ( $y );
268 $first = explode ( ':' , $first );
269 $ns = array_shift ( $first );
270 $ns = trim ( str_replace ( '[' , '' , $ns ) );
271 if ( $wgContLang->getLanguageName( $ns ) ||
strtolower ( $ns ) == $catlow ) {
272 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]';
273 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add;
275 $x = implode ( ']]' , $y );
277 $y = trim ( strtolower ( $x ) );
279 $x = implode ( ']]' , $y );
280 $y = trim ( strtolower ( $x ) );
284 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n";
285 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n";
286 $t = implode ( "\n" , $t );
289 $sat = array () ; # stand-alone-templates; must be lowercase
290 $wl_title = Title
::newFromText ( $wgMetadataWhitelist );
291 $wl_article = new Article ( $wl_title );
292 $wl = explode ( "\n" , $wl_article->getContent() );
293 foreach ( $wl AS $x ) {
296 while ( substr ( $x , 0 , 1 ) == '*' ) {
298 $x = trim ( substr ( $x , 1 ) );
301 $sat[] = strtolower ( $x );
306 # Templates, but only some
307 $t = explode ( '{{' , $t );
309 foreach ( $t AS $key => $x ) {
310 $y = explode ( '}}' , $x , 2 );
311 if ( count ( $y ) == 2 ) {
313 $z = explode ( '|' , $z );
314 $tn = array_shift ( $z );
315 if ( in_array ( strtolower ( $tn ) , $sat ) ) {
316 $tl[] = '{{' . $y[0] . '}}';
318 $y = explode ( '}}' , $y[1] , 2 );
320 else $t[$key] = '{{' . $x;
322 else if ( $key != 0 ) $t[$key] = '{{' . $x;
325 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl );
326 $t = implode ( '' , $t );
328 $t = str_replace ( "\n\n\n" , "\n" , $t );
329 $this->mArticle
->mContent
= $t;
330 $this->mMetaData
= $s;
334 * Check if a page was deleted while the user was editing it, before submit.
335 * Note that we rely on the logging table, which hasn't been always there,
336 * but that doesn't matter, because this only applies to brand new
339 protected function wasDeletedSinceLastEdit() {
340 if ( $this->deletedSinceEdit
)
342 if ( $this->mTitle
->isDeletedQuick() ) {
343 $this->lastDelete
= $this->getLastDelete();
344 if ( $this->lastDelete
) {
345 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
346 if ( $deleteTime > $this->starttime
) {
347 $this->deletedSinceEdit
= true;
351 return $this->deletedSinceEdit
;
359 * This is the function that gets called for "action=edit". It
360 * sets up various member variables, then passes execution to
361 * another function, usually showEditForm()
363 * The edit form is self-submitting, so that when things like
364 * preview and edit conflicts occur, we get the same form back
365 * with the extra stuff added. Only when the final submission
366 * is made and all is well do we actually save and redirect to
367 * the newly-edited page.
370 global $wgOut, $wgRequest, $wgEnableJS2system;
371 // Allow extensions to modify/prevent this form or submission
372 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
376 wfProfileIn( __METHOD__
);
377 wfDebug( __METHOD__
.": enter\n" );
379 // This is not an article
380 $wgOut->setArticleFlag( false );
382 $this->importFormData( $wgRequest );
383 $this->firsttime
= false;
386 $this->livePreview();
387 wfProfileOut( __METHOD__
);
391 if ( wfReadOnly() && $this->save
) {
394 $this->preview
= true;
397 $wgOut->addScriptFile( 'edit.js' );
399 if( $wgEnableJS2system )
400 $wgOut->addScriptClass( 'editPage' );
402 $permErrors = $this->getEditPermissionErrors();
404 wfDebug( __METHOD__
.": User can't edit\n" );
405 $this->readOnlyPage( $this->getContent(), true, $permErrors, 'edit' );
406 wfProfileOut( __METHOD__
);
410 $this->formtype
= 'save';
411 } else if ( $this->preview
) {
412 $this->formtype
= 'preview';
413 } else if ( $this->diff
) {
414 $this->formtype
= 'diff';
415 } else { # First time through
416 $this->firsttime
= true;
417 if ( $this->previewOnOpen() ) {
418 $this->formtype
= 'preview';
420 $this->extractMetaDataFromArticle () ;
421 $this->formtype
= 'initial';
426 // If they used redlink=1 and the page exists, redirect to the main article
427 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
428 $wgOut->redirect( $this->mTitle
->getFullURL() );
431 wfProfileIn( __METHOD__
."-business-end" );
433 $this->isConflict
= false;
434 // css / js subpages of user pages get a special treatment
435 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
436 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
437 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
438 $this->isValidCssJsSubpage
= $this->mTitle
->isValidCssJsSubpage();
440 # Show applicable editing introductions
441 if ( $this->formtype
== 'initial' ||
$this->firsttime
)
444 if ( $this->mTitle
->isTalkPage() ) {
445 $wgOut->addWikiMsg( 'talkpagetext' );
448 # Optional notices on a per-namespace and per-page basis
449 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
450 if ( !wfEmptyMsg( $editnotice_ns, wfMsgForContent( $editnotice_ns ) ) ) {
451 $wgOut->addWikiText( wfMsgForContent( $editnotice_ns ) );
453 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
454 $parts = explode( '/', $this->mTitle
->getDBkey() );
455 $editnotice_base = $editnotice_ns;
456 while ( count( $parts ) > 0 ) {
457 $editnotice_base .= '-'.array_shift( $parts );
458 if ( !wfEmptyMsg( $editnotice_base, wfMsgForContent( $editnotice_base ) ) ) {
459 $wgOut->addWikiText( wfMsgForContent( $editnotice_base ) );
464 # Attempt submission here. This will check for edit conflicts,
465 # and redundantly check for locked database, blocked IPs, etc.
466 # that edit() already checked just in case someone tries to sneak
467 # in the back door with a hand-edited submission URL.
469 if ( 'save' == $this->formtype
) {
470 if ( !$this->attemptSave() ) {
471 wfProfileOut( __METHOD__
."-business-end" );
472 wfProfileOut( __METHOD__
);
477 # First time through: get contents, set time for conflict
479 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
480 if ( $this->initialiseForm() === false) {
481 $this->noSuchSectionPage();
482 wfProfileOut( __METHOD__
."-business-end" );
483 wfProfileOut( __METHOD__
);
486 if ( !$this->mTitle
->getArticleId() )
487 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
490 $this->showEditForm();
491 wfProfileOut( __METHOD__
."-business-end" );
492 wfProfileOut( __METHOD__
);
495 protected function getEditPermissionErrors() {
497 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
498 # Can this title be created?
499 if ( !$this->mTitle
->exists() ) {
500 $permErrors = array_merge( $permErrors,
501 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
503 # Ignore some permissions errors when a user is just previewing/viewing diffs
505 foreach( $permErrors as $error ) {
506 if ( ($this->preview ||
$this->diff
) &&
507 ($error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext') )
512 $permErrors = wfArrayDiff2( $permErrors, $remove );
517 * Show a read-only error
518 * Parameters are the same as OutputPage:readOnlyPage()
519 * Redirect to the article page if redlink=1
521 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
522 global $wgRequest, $wgOut;
523 if ( $wgRequest->getBool( 'redlink' ) ) {
524 // The edit page was reached via a red link.
525 // Redirect to the article page and let them click the edit tab if
526 // they really want a permission error.
527 $wgOut->redirect( $this->mTitle
->getFullUrl() );
529 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
534 * Should we show a preview when the edit form is first shown?
538 protected function previewOnOpen() {
539 global $wgRequest, $wgUser;
540 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
541 // Explicit override from request
543 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
544 // Explicit override from request
546 } elseif ( $this->section
== 'new' ) {
547 // Nothing *to* preview for new sections
549 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
550 // Standard preference behaviour
552 } elseif ( !$this->mTitle
->exists() && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
553 // Categories are special
564 function importFormData( &$request ) {
565 global $wgLang, $wgUser;
566 $fname = 'EditPage::importFormData';
567 wfProfileIn( $fname );
569 # Section edit can come from either the form or a link
570 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
572 if ( $request->wasPosted() ) {
573 # These fields need to be checked for encoding.
574 # Also remove trailing whitespace, but don't remove _initial_
575 # whitespace from the text boxes. This may be significant formatting.
576 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
577 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
578 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
579 # Truncate for whole multibyte characters. +5 bytes for ellipsis
580 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250, '' );
582 # Remove extra headings from summaries and new sections.
583 $this->summary
= preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
585 $this->edittime
= $request->getVal( 'wpEdittime' );
586 $this->starttime
= $request->getVal( 'wpStarttime' );
588 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
590 if ( is_null( $this->edittime
) ) {
591 # If the form is incomplete, force to preview.
592 wfDebug( "$fname: Form data appears to be incomplete\n" );
593 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
594 $this->preview
= true;
596 /* Fallback for live preview */
597 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
598 $this->diff
= $request->getCheck( 'wpDiff' );
600 // Remember whether a save was requested, so we can indicate
601 // if we forced preview due to session failure.
602 $this->mTriedSave
= !$this->preview
;
604 if ( $this->tokenOk( $request ) ) {
605 # Some browsers will not report any submit button
606 # if the user hits enter in the comment box.
607 # The unmarked state will be assumed to be a save,
608 # if the form seems otherwise complete.
609 wfDebug( "$fname: Passed token check.\n" );
610 } else if ( $this->diff
) {
611 # Failed token check, but only requested "Show Changes".
612 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
614 # Page might be a hack attempt posted from
615 # an external site. Preview instead of saving.
616 wfDebug( "$fname: Failed token check; forcing preview\n" );
617 $this->preview
= true;
620 $this->save
= !$this->preview
&& !$this->diff
;
621 if ( !preg_match( '/^\d{14}$/', $this->edittime
)) {
622 $this->edittime
= null;
625 if ( !preg_match( '/^\d{14}$/', $this->starttime
)) {
626 $this->starttime
= null;
629 $this->recreate
= $request->getCheck( 'wpRecreate' );
631 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
632 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
634 # Don't force edit summaries when a user is editing their own user or talk page
635 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
636 $this->mTitle
->getText() == $wgUser->getName() )
638 $this->allowBlankSummary
= true;
640 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
643 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
645 # Not a posted form? Start with nothing.
646 wfDebug( "$fname: Not a posted form.\n" );
647 $this->textbox1
= '';
648 $this->textbox2
= '';
649 $this->mMetaData
= '';
651 $this->edittime
= '';
652 $this->starttime
= wfTimestampNow();
654 $this->preview
= false;
657 $this->minoredit
= false;
658 $this->watchthis
= false;
659 $this->recreate
= false;
661 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
662 $this->summary
= $request->getVal( 'preloadtitle' );
664 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
665 $this->summary
= $request->getText( 'summary' );
668 if ( $request->getVal( 'minor' ) ) {
669 $this->minoredit
= true;
673 // FIXME: unused variable?
674 $this->oldid
= $request->getInt( 'oldid' );
676 $this->live
= $request->getCheck( 'live' );
677 $this->editintro
= $request->getText( 'editintro' );
679 wfProfileOut( $fname );
681 // Allow extensions to modify form data
682 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
686 * Make sure the form isn't faking a user's credentials.
688 * @param $request WebRequest
692 function tokenOk( &$request ) {
694 $token = $request->getVal( 'wpEditToken' );
695 $this->mTokenOk
= $wgUser->matchEditToken( $token );
696 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
697 return $this->mTokenOk
;
701 * Show all applicable editing introductions
703 protected function showIntro() {
704 global $wgOut, $wgUser;
705 if ( $this->suppressIntro
) {
709 $namespace = $this->mTitle
->getNamespace();
711 if ( $namespace == NS_MEDIAWIKI
) {
712 # Show a warning if editing an interface message
713 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1</div>", 'editinginterface' );
716 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
717 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
718 $parts = explode( '/', $this->mTitle
->getText(), 2 );
719 $username = $parts[0];
720 $id = User
::idFromName( $username );
721 $ip = User
::isIP( $username );
722 if ( $id == 0 && !$ip ) {
723 $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
724 array( 'userpage-userdoesnotexist', $username ) );
727 # Try to add a custom edit intro, or use the standard one if this is not possible.
728 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
729 if ( $wgUser->isLoggedIn() ) {
730 $wgOut->wrapWikiMsg( '<div class="mw-newarticletext">$1</div>', 'newarticletext' );
732 $wgOut->wrapWikiMsg( '<div class="mw-newarticletextanon">$1</div>', 'newarticletextanon' );
735 # Give a notice if the user is editing a deleted/moved page...
736 if ( !$this->mTitle
->exists() ) {
737 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(),
738 '', array( 'lim' => 10,
739 'conds' => array( "log_action != 'revision'" ),
740 'showIfEmpty' => false,
741 'msgKey' => array( 'recreate-moveddeleted-warn') )
747 * Attempt to show a custom editing introduction, if supplied
751 protected function showCustomIntro() {
752 if ( $this->editintro
) {
753 $title = Title
::newFromText( $this->editintro
);
754 if ( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
756 $revision = Revision
::newFromTitle( $title );
757 $wgOut->addWikiTextTitleTidy( $revision->getText(), $this->mTitle
);
768 * Attempt submission (no UI)
769 * @return one of the constants describing the result
771 function internalAttemptSave( &$result, $bot = false ) {
772 global $wgFilterCallback, $wgUser, $wgOut, $wgParser;
773 global $wgMaxArticleSize;
775 $fname = 'EditPage::attemptSave';
776 wfProfileIn( $fname );
777 wfProfileIn( "$fname-checks" );
779 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) )
781 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
782 return self
::AS_HOOK_ERROR
;
785 # Check image redirect
786 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
787 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
788 !$wgUser->isAllowed( 'upload' ) ) {
789 if ( $wgUser->isAnon() ) {
790 return self
::AS_IMAGE_REDIRECT_ANON
;
792 return self
::AS_IMAGE_REDIRECT_LOGGED
;
796 # Reintegrate metadata
797 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
798 $this->mMetaData
= '' ;
801 $match = self
::matchSummarySpamRegex( $this->summary
);
802 if ( $match === false ) {
803 $match = self
::matchSpamRegex( $this->textbox1
);
805 if ( $match !== false ) {
806 $result['spam'] = $match;
808 $pdbk = $this->mTitle
->getPrefixedDBkey();
809 $match = str_replace( "\n", '', $match );
810 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
811 wfProfileOut( "$fname-checks" );
812 wfProfileOut( $fname );
813 return self
::AS_SPAM_ERROR
;
815 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
816 # Error messages or other handling should be performed by the filter function
817 wfProfileOut( "$fname-checks" );
818 wfProfileOut( $fname );
819 return self
::AS_FILTERING
;
821 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
822 # Error messages etc. could be handled within the hook...
823 wfProfileOut( "$fname-checks" );
824 wfProfileOut( $fname );
825 return self
::AS_HOOK_ERROR
;
826 } elseif ( $this->hookError
!= '' ) {
827 # ...or the hook could be expecting us to produce an error
828 wfProfileOut( "$fname-checks" );
829 wfProfileOut( $fname );
830 return self
::AS_HOOK_ERROR_EXPECTED
;
832 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
833 # Check block state against master, thus 'false'.
834 wfProfileOut( "$fname-checks" );
835 wfProfileOut( $fname );
836 return self
::AS_BLOCKED_PAGE_FOR_USER
;
838 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
839 if ( $this->kblength
> $wgMaxArticleSize ) {
840 // Error will be displayed by showEditForm()
841 $this->tooBig
= true;
842 wfProfileOut( "$fname-checks" );
843 wfProfileOut( $fname );
844 return self
::AS_CONTENT_TOO_BIG
;
847 if ( !$wgUser->isAllowed('edit') ) {
848 if ( $wgUser->isAnon() ) {
849 wfProfileOut( "$fname-checks" );
850 wfProfileOut( $fname );
851 return self
::AS_READ_ONLY_PAGE_ANON
;
854 wfProfileOut( "$fname-checks" );
855 wfProfileOut( $fname );
856 return self
::AS_READ_ONLY_PAGE_LOGGED
;
860 if ( wfReadOnly() ) {
861 wfProfileOut( "$fname-checks" );
862 wfProfileOut( $fname );
863 return self
::AS_READ_ONLY_PAGE
;
865 if ( $wgUser->pingLimiter() ) {
866 wfProfileOut( "$fname-checks" );
867 wfProfileOut( $fname );
868 return self
::AS_RATE_LIMITED
;
871 # If the article has been deleted while editing, don't save it without
873 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
874 wfProfileOut( "$fname-checks" );
875 wfProfileOut( $fname );
876 return self
::AS_ARTICLE_WAS_DELETED
;
879 wfProfileOut( "$fname-checks" );
881 # If article is new, insert it.
882 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
884 // Late check for create permission, just in case *PARANOIA*
885 if ( !$this->mTitle
->userCan( 'create' ) ) {
886 wfDebug( "$fname: no create permission\n" );
887 wfProfileOut( $fname );
888 return self
::AS_NO_CREATE_PERMISSION
;
891 # Don't save a new article if it's blank.
892 if ( '' == $this->textbox1
) {
893 wfProfileOut( $fname );
894 return self
::AS_BLANK_ARTICLE
;
897 // Run post-section-merge edit filter
898 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
899 # Error messages etc. could be handled within the hook...
900 wfProfileOut( $fname );
901 return self
::AS_HOOK_ERROR
;
902 } elseif ( $this->hookError
!= '' ) {
903 # ...or the hook could be expecting us to produce an error
904 wfProfileOut( $fname );
905 return self
::AS_HOOK_ERROR_EXPECTED
;
908 # Handle the user preference to force summaries here. Check if it's not a redirect.
909 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
910 if ( md5( $this->summary
) == $this->autoSumm
) {
911 $this->missingSummary
= true;
912 wfProfileOut( $fname );
913 return self
::AS_SUMMARY_NEEDED
;
917 $isComment = ( $this->section
== 'new' );
919 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
920 $this->minoredit
, $this->watchthis
, false, $isComment, $bot );
922 wfProfileOut( $fname );
923 return self
::AS_SUCCESS_NEW_ARTICLE
;
926 # Article exists. Check for edit conflict.
928 $this->mArticle
->clear(); # Force reload of dates, etc.
929 $this->mArticle
->forUpdate( true ); # Lock the article
931 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
933 if ( $this->mArticle
->getTimestamp() != $this->edittime
) {
934 $this->isConflict
= true;
935 if ( $this->section
== 'new' ) {
936 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
937 $this->mArticle
->getComment() == $this->summary
) {
938 // Probably a duplicate submission of a new comment.
939 // This can happen when squid resends a request after
940 // a timeout but the first one actually went through.
941 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
943 // New comment; suppress conflict.
944 $this->isConflict
= false;
945 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
949 $userid = $wgUser->getId();
951 # Suppress edit conflict with self, except for section edits where merging is required.
952 if ( $this->isConflict
&& $this->section
== '' && $this->userWasLastToEdit($userid,$this->edittime
) ) {
953 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
954 $this->isConflict
= false;
957 if ( $this->isConflict
) {
958 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
959 $this->mArticle
->getTimestamp() . "')\n" );
960 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
962 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
963 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
965 if ( is_null( $text ) ) {
966 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
967 $this->isConflict
= true;
968 $text = $this->textbox1
; // do not try to merge here!
969 } else if ( $this->isConflict
) {
971 if ( $this->mergeChangesInto( $text ) ) {
972 // Successful merge! Maybe we should tell the user the good news?
973 $this->isConflict
= false;
974 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
977 $this->textbox1
= $text;
978 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
982 if ( $this->isConflict
) {
983 wfProfileOut( $fname );
984 return self
::AS_CONFLICT_DETECTED
;
987 $oldtext = $this->mArticle
->getContent();
989 // Run post-section-merge edit filter
990 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
991 # Error messages etc. could be handled within the hook...
992 wfProfileOut( $fname );
993 return self
::AS_HOOK_ERROR
;
994 } elseif ( $this->hookError
!= '' ) {
995 # ...or the hook could be expecting us to produce an error
996 wfProfileOut( $fname );
997 return self
::AS_HOOK_ERROR_EXPECTED
;
1000 # Handle the user preference to force summaries here, but not for null edits
1001 if ( $this->section
!= 'new' && !$this->allowBlankSummary
&& 0 != strcmp($oldtext,$text)
1002 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1004 if ( md5( $this->summary
) == $this->autoSumm
) {
1005 $this->missingSummary
= true;
1006 wfProfileOut( $fname );
1007 return self
::AS_SUMMARY_NEEDED
;
1011 # And a similar thing for new sections
1012 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1013 if (trim($this->summary
) == '') {
1014 $this->missingSummary
= true;
1015 wfProfileOut( $fname );
1016 return self
::AS_SUMMARY_NEEDED
;
1021 wfProfileIn( "$fname-sectionanchor" );
1022 $sectionanchor = '';
1023 if ( $this->section
== 'new' ) {
1024 if ( $this->textbox1
== '' ) {
1025 $this->missingComment
= true;
1026 return self
::AS_TEXTBOX_EMPTY
;
1028 if ( $this->summary
!= '' ) {
1029 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary
);
1030 # This is a new section, so create a link to the new section
1031 # in the revision summary.
1032 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1033 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1035 } elseif ( $this->section
!= '' ) {
1036 # Try to get a section anchor from the section source, redirect to edited section if header found
1037 # XXX: might be better to integrate this into Article::replaceSection
1038 # for duplicate heading checking and maybe parsing
1039 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1040 # we can't deal with anchors, includes, html etc in the header for now,
1041 # headline would need to be parsed to improve this
1042 if ( $hasmatch and strlen($matches[2]) > 0 ) {
1043 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
1046 wfProfileOut( "$fname-sectionanchor" );
1048 // Save errors may fall down to the edit form, but we've now
1049 // merged the section into full text. Clear the section field
1050 // so that later submission of conflict forms won't try to
1051 // replace that into a duplicated mess.
1052 $this->textbox1
= $text;
1053 $this->section
= '';
1055 // Check for length errors again now that the section is merged in
1056 $this->kblength
= (int)(strlen( $text ) / 1024);
1057 if ( $this->kblength
> $wgMaxArticleSize ) {
1058 $this->tooBig
= true;
1059 wfProfileOut( $fname );
1060 return self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
;
1063 # update the article here
1064 if ( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
1065 $this->watchthis
, $bot, $sectionanchor ) )
1067 wfProfileOut( $fname );
1068 return self
::AS_SUCCESS_UPDATE
;
1070 $this->isConflict
= true;
1072 wfProfileOut( $fname );
1073 return self
::AS_END
;
1077 * Check if no edits were made by other users since
1078 * the time a user started editing the page. Limit to
1079 * 50 revisions for the sake of performance.
1081 protected function userWasLastToEdit( $id, $edittime ) {
1082 if( !$id ) return false;
1083 $dbw = wfGetDB( DB_MASTER
);
1084 $res = $dbw->select( 'revision',
1087 'rev_page' => $this->mArticle
->getId(),
1088 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1091 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1092 while( $row = $res->fetchObject() ) {
1093 if( $row->rev_user
!= $id ) {
1101 * Check given input text against $wgSpamRegex, and return the text of the first match.
1102 * @return mixed -- matching string or false
1104 public static function matchSpamRegex( $text ) {
1105 global $wgSpamRegex;
1106 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1107 $regexes = (array)$wgSpamRegex;
1108 return self
::matchSpamRegexInternal( $text, $regexes );
1112 * Check given input text against $wgSpamRegex, and return the text of the first match.
1113 * @return mixed -- matching string or false
1115 public static function matchSummarySpamRegex( $text ) {
1116 global $wgSummarySpamRegex;
1117 $regexes = (array)$wgSummarySpamRegex;
1118 return self
::matchSpamRegexInternal( $text, $regexes );
1121 protected static function matchSpamRegexInternal( $text, $regexes ) {
1122 foreach( $regexes as $regex ) {
1124 if( preg_match( $regex, $text, $matches ) ) {
1132 * Initialise form fields in the object
1133 * Called on the first invocation, e.g. when a user clicks an edit link
1135 function initialiseForm() {
1136 $this->edittime
= $this->mArticle
->getTimestamp();
1137 $this->textbox1
= $this->getContent( false );
1138 if ( $this->textbox1
=== false ) return false;
1143 function setHeaders() {
1144 global $wgOut, $wgTitle;
1145 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1146 if ( $this->formtype
== 'preview' ) {
1147 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1149 if ( $this->isConflict
) {
1150 $wgOut->setPageTitle( wfMsg( 'editconflict', $wgTitle->getPrefixedText() ) );
1151 } elseif ( $this->section
!= '' ) {
1152 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1153 $wgOut->setPageTitle( wfMsg( $msg, $wgTitle->getPrefixedText() ) );
1155 # Use the title defined by DISPLAYTITLE magic word when present
1156 if ( isset($this->mParserOutput
)
1157 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1160 $title = $wgTitle->getPrefixedText();
1162 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1167 * Send the edit form and related headers to $wgOut
1168 * @param $formCallback Optional callable that takes an OutputPage
1169 * parameter; will be called during form output
1170 * near the top, for captchas and the like.
1172 function showEditForm( $formCallback=null ) {
1173 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle, $wgRequest;
1175 # If $wgTitle is null, that means we're in API mode.
1176 # Some hook probably called this function without checking
1177 # for is_null($wgTitle) first. Bail out right here so we don't
1178 # do lots of work just to discard it right after.
1179 if (is_null($wgTitle))
1182 $fname = 'EditPage::showEditForm';
1183 wfProfileIn( $fname );
1185 $sk = $wgUser->getSkin();
1187 #need to parse the preview early so that we know which templates are used,
1188 #otherwise users with "show preview after edit box" will get a blank list
1189 #we parse this near the beginning so that setHeaders can do the title
1190 #setting work instead of leaving it in getPreviewText
1191 $previewOutput = '';
1192 if ( $this->formtype
== 'preview' ) {
1193 $previewOutput = $this->getPreviewText();
1196 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
1198 $this->setHeaders();
1200 # Enabled article-related sidebar, toplinks, etc.
1201 $wgOut->setArticleRelated( true );
1203 $cancelParams = array();
1205 if ( $this->isConflict
) {
1206 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1</div>", 'explainconflict' );
1208 $this->textbox2
= $this->textbox1
;
1209 $this->textbox1
= $this->getContent();
1210 $this->edittime
= $this->mArticle
->getTimestamp();
1212 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1214 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1215 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1
, $matches );
1216 if ( !empty( $matches[2] ) ) {
1218 $this->summary
= "/* " .
1219 $wgParser->stripSectionName(trim($matches[2])) .
1225 if ( $this->missingComment
) {
1226 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1229 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1230 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1233 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1234 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1237 if ( $this->hookError
!== '' ) {
1238 $wgOut->addWikiText( $this->hookError
);
1241 if ( !$this->checkUnicodeCompliantBrowser() ) {
1242 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1244 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1245 // Let sysop know that this will make private content public if saved
1247 if ( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1248 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
1249 } else if ( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1250 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
1253 if ( !$this->mArticle
->mRevision
->isCurrent() ) {
1254 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1255 $cancelParams['oldid'] = $this->mArticle
->mRevision
->getId();
1256 $wgOut->addWikiMsg( 'editingold' );
1261 if ( wfReadOnly() ) {
1262 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1263 } elseif ( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
1264 $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' );
1266 if ( $this->isCssJsSubpage
) {
1267 # Check the skin exists
1268 if ( !$this->isValidCssJsSubpage
) {
1269 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1271 if ( $this->formtype
!== 'preview' ) {
1272 if ( $this->isCssSubpage
)
1273 $wgOut->addWikiMsg( 'usercssyoucanpreview' );
1274 if ( $this->isJsSubpage
)
1275 $wgOut->addWikiMsg( 'userjsyoucanpreview' );
1280 $classes = array(); // Textarea CSS
1281 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1282 } elseif ( $this->mTitle
->isProtected( 'edit' ) ) {
1283 # Is the title semi-protected?
1284 if ( $this->mTitle
->isSemiProtected() ) {
1285 $noticeMsg = 'semiprotectedpagewarning';
1286 $classes[] = 'mw-textarea-sprotected';
1288 # Then it must be protected based on static groups (regular)
1289 $noticeMsg = 'protectedpagewarning';
1290 $classes[] = 'mw-textarea-protected';
1292 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
->getPrefixedText(), '',
1293 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1295 if ( $this->mTitle
->isCascadeProtected() ) {
1296 # Is this page under cascading protection from some source pages?
1297 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1298 $notice = "<div class='mw-cascadeprotectedwarning'>$1\n";
1299 $cascadeSourcesCount = count( $cascadeSources );
1300 if ( $cascadeSourcesCount > 0 ) {
1301 # Explain, and list the titles responsible
1302 foreach( $cascadeSources as $page ) {
1303 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1306 $notice .= '</div>';
1307 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1309 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1310 $wgOut->wrapWikiMsg( '<div class="mw-titleprotectedwarning">$1</div>', 'titleprotectedwarning' );
1313 if ( $this->kblength
=== false ) {
1314 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1316 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1317 $wgOut->addHTML( "<div class='error' id='mw-edit-longpageerror'>\n" );
1318 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) );
1319 $wgOut->addHTML( "</div>\n" );
1320 } elseif ( $this->kblength
> 29 ) {
1321 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1322 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) );
1323 $wgOut->addHTML( "</div>\n" );
1326 $action = $wgTitle->escapeLocalURL( array( 'action' => $this->action
) );
1328 $summary = wfMsgExt( 'summary', 'parseinline' );
1329 $subject = wfMsgExt( 'subject', 'parseinline' );
1331 $cancel = $sk->link(
1333 wfMsgExt( 'cancel', array( 'parseinline' ) ),
1334 array( 'id' => 'mw-editform-cancel' ),
1336 array( 'known', 'noclasses' )
1338 $separator = wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1339 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1340 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1341 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1342 htmlspecialchars( wfMsg( 'newwindow' ) );
1344 global $wgRightsText;
1345 if ( $wgRightsText ) {
1346 $copywarnMsg = array( 'copyrightwarning',
1347 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1350 $copywarnMsg = array( 'copyrightwarning2',
1351 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1353 // Allow for site and per-namespace customization of contribution/copyright notice.
1354 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
1356 if ( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1357 # prepare toolbar for edit buttons
1358 $toolbar = EditPage
::getEditToolbar();
1364 // activate checkboxes if user wants them to be always active
1365 if ( !$this->preview
&& !$this->diff
) {
1366 # Sort out the "watch" checkbox
1367 if ( $wgUser->getOption( 'watchdefault' ) ) {
1369 $this->watchthis
= true;
1370 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1372 $this->watchthis
= true;
1373 } elseif ( $this->mTitle
->userIsWatching() ) {
1375 $this->watchthis
= true;
1378 # May be overriden by request parameters
1379 if( $wgRequest->getBool( 'watchthis' ) ) {
1380 $this->watchthis
= true;
1383 if ( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1386 $wgOut->addHTML( $this->editFormPageTop
);
1388 if ( $wgUser->getOption( 'previewontop' ) ) {
1389 $this->displayPreviewArea( $previewOutput, true );
1393 $wgOut->addHTML( $this->editFormTextTop
);
1395 # if this is a comment, show a subject line at the top, which is also the edit summary.
1396 # Otherwise, show a summary field at the bottom
1397 $summarytext = $wgContLang->recodeForEdit( $this->summary
);
1399 # If a blank edit summary was previously provided, and the appropriate
1400 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1401 # user being bounced back more than once in the event that a summary
1404 # For a bit more sophisticated detection of blank summaries, hash the
1405 # automatic one and pass that in the hidden field wpAutoSummary.
1406 $summaryhiddens = '';
1407 if ( $this->missingSummary
) $summaryhiddens .= Xml
::hidden( 'wpIgnoreBlankSummary', true );
1408 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1409 $summaryhiddens .= Xml
::hidden( 'wpAutoSummary', $autosumm );
1410 if ( $this->section
== 'new' ) {
1411 $commentsubject = '';
1412 if ( !$wgRequest->getBool( 'nosummary' ) ) {
1413 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1414 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1417 Xml
::tags( 'label', array( 'for' => 'wpSummary' ), $subject );
1419 Xml
::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1421 $commentsubject .= ' ';
1422 $commentsubject .= Xml
::input( 'wpSummary',
1426 'id' => 'wpSummary',
1427 'maxlength' => '200',
1431 $summaryhiddens .= Xml
::hidden( 'wpIgnoreBlankSummary', true ); # bug 18699
1433 $editsummary = "<div class='editOptions'>\n";
1435 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary
) );
1436 $subjectpreview = $summarytext && ( $this->preview ||
$this->diff
) ?
1437 "<div class=\"mw-summary-preview\">". wfMsgExt('subject-preview', 'parseinline') . $sk->commentBlock( $formattedSummary, $this->mTitle
, true )."</div>\n" : '';
1438 $summarypreview = '';
1440 $commentsubject = '';
1442 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1443 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1445 $editsummary = Xml
::tags( 'label', array( 'for' => 'wpSummary' ), $summary );
1446 $editsummary = Xml
::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1447 $editsummary ) . ' ';
1449 $editsummary .= Xml
::input( 'wpSummary',
1453 'id' => 'wpSummary',
1454 'maxlength' => '200',
1458 // No idea where this is closed.
1459 $editsummary = Xml
::openElement( 'div', array( 'class' => 'editOptions' ) )
1460 . $editsummary . '<br/>';
1462 $summarypreview = '';
1463 if ( $summarytext && ( $this->preview ||
$this->diff
) ) {
1466 array( 'class' => 'mw-summary-preview' ),
1467 wfMsgExt( 'summary-preview', 'parseinline' ) .
1468 $sk->commentBlock( $this->summary
, $this->mTitle
)
1471 $subjectpreview = '';
1473 $commentsubject .= $summaryhiddens;
1475 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1476 if ( !$this->preview
&& !$this->diff
) {
1477 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1479 $templates = $this->getTemplates();
1480 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1482 $hiddencats = $this->mArticle
->getHiddenCategories();
1483 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1485 global $wgUseMetadataEdit ;
1486 if ( $wgUseMetadataEdit ) {
1487 $metadata = $this->mMetaData
;
1488 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1489 $top = wfMsgWikiHtml( 'metadata_help' );
1490 /* ToDo: Replace with clean code */
1491 $ew = $wgUser->getOption( 'editwidth' );
1492 if ( $ew ) $ew = " style=\"width:100%\"";
1494 $cols = $wgUser->getIntOption( 'cols' );
1496 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1498 else $metadata = "" ;
1501 if ( $this->wasDeletedSinceLastEdit() ) {
1502 if ( 'save' != $this->formtype
) {
1503 $wgOut->wrapWikiMsg(
1504 "<div class='error mw-deleted-while-editing'>\n$1</div>",
1505 'deletedwhileediting' );
1507 // Hide the toolbar and edit area, user can click preview to get it back
1508 // Add an confirmation checkbox and explanation.
1510 $recreate = '<div class="mw-confirm-recreate">' .
1511 $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
) ) .
1512 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1513 array( 'title' => $sk->titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1520 $checkboxes = $this->getCheckboxes( $tabindex, $sk,
1521 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1523 $checkboxhtml = implode( $checkboxes, "\n" );
1525 $buttons = $this->getEditButtons( $tabindex );
1526 $buttonshtml = implode( $buttons, "\n" );
1528 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1529 ?
'' : Xml
::hidden( 'safemode', '1' );
1531 $wgOut->addHTML( <<<END
1533 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1537 if ( is_callable( $formCallback ) ) {
1538 call_user_func_array( $formCallback, array( &$wgOut ) );
1541 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1543 // Put these up at the top to ensure they aren't lost on early form submission
1544 $this->showFormBeforeText();
1546 $wgOut->addHTML( <<<END
1550 {$this->editFormTextBeforeContent}
1553 $this->showTextbox1( $classes );
1555 $wgOut->addHTML( $this->editFormTextAfterContent
);
1557 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1558 $wgOut->addHTML( <<<END
1559 {$this->editFormTextAfterWarn}
1569 "<div class='editButtons'>
1571 <span class='editHelp'>{$cancel}{$separator}{$edithelp}</span>
1572 </div><!-- editButtons -->
1573 </div><!-- editOptions -->");
1576 * To make it harder for someone to slip a user a page
1577 * which submits an edit form to the wiki without their
1578 * knowledge, a random token is associated with the login
1579 * session. If it's not passed back with the submission,
1580 * we won't save the page, or render user JavaScript and
1583 * For anon editors, who may not have a session, we just
1584 * include the constant suffix to prevent editing from
1585 * broken text-mangling proxies.
1587 $token = htmlspecialchars( $wgUser->editToken() );
1588 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1590 $this->showTosSummary();
1591 $this->showEditTools();
1593 $wgOut->addHTML( <<<END
1594 {$this->editFormTextAfterTools}
1595 <div class='templatesUsed'>
1596 {$formattedtemplates}
1598 <div class='hiddencats'>
1599 {$formattedhiddencats}
1604 if ( $this->isConflict
&& wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1605 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1607 $de = new DifferenceEngine( $this->mTitle
);
1608 $de->setText( $this->textbox2
, $this->textbox1
);
1609 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1611 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1612 $this->showTextbox2();
1614 $wgOut->addHTML( $this->editFormTextBottom
);
1615 $wgOut->addHTML( "</form>\n" );
1616 if ( !$wgUser->getOption( 'previewontop' ) ) {
1617 $this->displayPreviewArea( $previewOutput, false );
1620 wfProfileOut( $fname );
1623 protected function showFormBeforeText() {
1626 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1627 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1628 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1629 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1632 protected function showTextbox1( $classes ) {
1633 $attribs = array( 'tabindex' => 1 );
1635 if ( $this->wasDeletedSinceLastEdit() )
1636 $attribs['type'] = 'hidden';
1637 if ( !empty($classes) )
1638 $attribs['class'] = implode(' ',$classes);
1640 $this->showTextbox( $this->textbox1
, 'wpTextbox1', $attribs );
1643 protected function showTextbox2() {
1644 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6 ) );
1647 protected function showTextbox( $content, $name, $attribs = array() ) {
1648 global $wgOut, $wgUser;
1650 $wikitext = $this->safeUnicodeOutput( $content );
1651 if ( $wikitext !== '' ) {
1652 // Ensure there's a newline at the end, otherwise adding lines
1654 // But don't add a newline if the ext is empty, or Firefox in XHTML
1655 // mode will show an extra newline. A bit annoying.
1659 $attribs['accesskey'] = ',';
1660 $attribs['id'] = $name;
1662 if ( $wgUser->getOption( 'editwidth' ) )
1663 $attribs['style'] = 'width: 100%';
1665 $wgOut->addHTML( Xml
::textarea(
1668 $wgUser->getIntOption( 'cols' ), $wgUser->getIntOption( 'rows' ),
1672 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1676 $classes[] = 'ontop';
1678 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1680 if ( $this->formtype
!= 'preview' )
1681 $attribs['style'] = 'display: none;';
1683 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
1685 if ( $this->formtype
== 'preview' ) {
1686 $this->showPreview( $previewOutput );
1689 $wgOut->addHTML( '</div>' );
1691 if ( $this->formtype
== 'diff') {
1697 * Append preview output to $wgOut.
1698 * Includes category rendering if this is a category page.
1700 * @param string $text The HTML to be output for the preview.
1702 protected function showPreview( $text ) {
1704 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1705 $this->mArticle
->openShowCategory();
1707 # This hook seems slightly odd here, but makes things more
1708 # consistent for extensions.
1709 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1710 $wgOut->addHTML( $text );
1711 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1712 $this->mArticle
->closeShowCategory();
1717 * Live Preview lets us fetch rendered preview page content and
1718 * add it to the page without refreshing the whole page.
1719 * If not supported by the browser it will fall through to the normal form
1720 * submission method.
1722 * This function outputs a script tag to support live preview, and
1723 * returns an onclick handler which should be added to the attributes
1724 * of the preview button
1726 function doLivePreviewScript() {
1727 global $wgOut, $wgTitle;
1728 $wgOut->addScriptFile( 'preview.js' );
1732 protected function showTosSummary() {
1733 $msg = 'editpage-tos-summary';
1734 // Give a chance for site and per-namespace customizations of
1735 // terms of service summary link that might exist separately
1736 // from the copyright notice.
1738 // This will display between the save button and the edit tools,
1739 // so should remain short!
1740 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
1741 $text = wfMsg( $msg );
1742 if( !wfEmptyMsg( $msg, $text ) && $text !== '-' ) {
1744 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1745 $wgOut->addWikiMsgArray( $msg, array() );
1746 $wgOut->addHTML( '</div>' );
1750 protected function showEditTools() {
1752 $wgOut->addHTML( '<div class="mw-editTools">' );
1753 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1754 $wgOut->addHTML( '</div>' );
1757 protected function getLastDelete() {
1758 $dbr = wfGetDB( DB_SLAVE
);
1759 $data = $dbr->selectRow(
1760 array( 'logging', 'user' ),
1771 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1772 'log_title' => $this->mTitle
->getDBkey(),
1773 'log_type' => 'delete',
1774 'log_action' => 'delete',
1775 'user_id=log_user' ),
1777 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1779 // Quick paranoid permission checks...
1780 if( is_object($data) ) {
1781 if( $data->log_deleted
& LogPage
::DELETED_USER
)
1782 $data->user_name
= wfMsgHtml('rev-deleted-user');
1783 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
1784 $data->log_comment
= wfMsgHtml('rev-deleted-comment');
1790 * Get the rendered text for previewing.
1793 function getPreviewText() {
1794 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache;
1796 wfProfileIn( __METHOD__
);
1798 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1799 if ( $this->mTokenOkExceptSuffix
) {
1800 $note = wfMsg( 'token_suffix_mismatch' );
1802 $note = wfMsg( 'session_fail_preview' );
1805 $note = wfMsg( 'previewnote' );
1808 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1809 $parserOptions->setEditSection( false );
1810 $parserOptions->setIsPreview( true );
1811 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
1814 if ( $wgRawHtml && !$this->mTokenOk
) {
1815 // Could be an offsite preview attempt. This is very unsafe if
1816 // HTML is enabled, as it could be an attack.
1817 return $wgOut->parse( "<div class='previewnote'>" .
1818 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1821 # don't parse user css/js, show message about preview
1822 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1824 if ( $this->isCssJsSubpage
) {
1825 if (preg_match("/\\.css$/", $this->mTitle
->getText() ) ) {
1826 $previewtext = wfMsg('usercsspreview');
1827 } else if (preg_match("/\\.js$/", $this->mTitle
->getText() ) ) {
1828 $previewtext = wfMsg('userjspreview');
1830 $parserOptions->setTidy(true);
1831 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
1832 $previewHTML = $parserOutput->mText
;
1833 } elseif ( $rt = Title
::newFromRedirectArray( $this->textbox1
) ) {
1834 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
1836 $toparse = $this->textbox1
;
1838 # If we're adding a comment, we need to show the
1839 # summary as the headline
1840 if ( $this->section
=="new" && $this->summary
!="" ) {
1841 $toparse="== {$this->summary} ==\n\n".$toparse;
1844 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1846 // Parse mediawiki messages with correct target language
1847 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1848 list( /* $unused */, $lang ) = $wgMessageCache->figureMessage( $this->mTitle
->getText() );
1849 $obj = wfGetLangObj( $lang );
1850 $parserOptions->setTargetLanguage( $obj );
1854 $parserOptions->setTidy(true);
1855 $parserOptions->enableLimitReport();
1856 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ),
1857 $this->mTitle
, $parserOptions );
1859 $previewHTML = $parserOutput->getText();
1860 $this->mParserOutput
= $parserOutput;
1861 $wgOut->addParserOutputNoText( $parserOutput );
1863 if ( count( $parserOutput->getWarnings() ) ) {
1864 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1868 if( $this->isConflict
) {
1869 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1871 $conflict = '<hr />';
1874 $previewhead = "<div class='previewnote'>\n" .
1875 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
1876 $wgOut->parse( $note ) . $conflict . "</div>\n";
1878 wfProfileOut( __METHOD__
);
1879 return $previewhead . $previewHTML . $this->previewTextAfterContent
;
1882 function getTemplates() {
1883 if ( $this->preview ||
$this->section
!= '' ) {
1884 $templates = array();
1885 if ( !isset($this->mParserOutput
) ) return $templates;
1886 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
1887 foreach( array_keys( $template ) as $dbk ) {
1888 $templates[] = Title
::makeTitle($ns, $dbk);
1893 return $this->mArticle
->getUsedTemplates();
1898 * Call the stock "user is blocked" page
1900 function blockedPage() {
1901 global $wgOut, $wgUser;
1902 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1904 # If the user made changes, preserve them when showing the markup
1905 # (This happens when a user is blocked during edit, for instance)
1906 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1908 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1910 $source = $this->textbox1
;
1913 # Spit out the source or the user's modified version
1914 if ( $source !== false ) {
1915 $rows = $wgUser->getIntOption( 'rows' );
1916 $cols = $wgUser->getIntOption( 'cols' );
1917 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1918 $wgOut->addHTML( '<hr />' );
1919 $wgOut->addWikiMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() );
1920 # Why we don't use Xml::element here?
1921 # Is it because if $source is '', it returns <textarea />?
1922 $wgOut->addHTML( Xml
::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml
::closeElement( 'textarea' ) );
1927 * Produce the stock "please login to edit pages" page
1929 function userNotLoggedInPage() {
1930 global $wgUser, $wgOut, $wgTitle;
1931 $skin = $wgUser->getSkin();
1933 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1934 $loginLink = $skin->link(
1936 wfMsgHtml( 'loginreqlink' ),
1938 array( 'returnto' => $wgTitle->getPrefixedText() ),
1939 array( 'known', 'noclasses' )
1942 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1943 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1944 $wgOut->setArticleRelated( false );
1946 $wgOut->addHTML( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1947 $wgOut->returnToMain( false, $wgTitle );
1951 * Creates a basic error page which informs the user that
1952 * they have attempted to edit a nonexistent section.
1954 function noSuchSectionPage() {
1955 global $wgOut, $wgTitle;
1957 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1958 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1959 $wgOut->setArticleRelated( false );
1961 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section
);
1962 $wgOut->returnToMain( false, $wgTitle );
1966 * Produce the stock "your edit contains spam" page
1968 * @param $match Text which triggered one or more filters
1970 function spamPage( $match = false ) {
1971 global $wgOut, $wgTitle;
1973 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1974 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1975 $wgOut->setArticleRelated( false );
1977 $wgOut->addHTML( '<div id="spamprotected">' );
1978 $wgOut->addWikiMsg( 'spamprotectiontext' );
1980 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1981 $wgOut->addHTML( '</div>' );
1983 $wgOut->returnToMain( false, $wgTitle );
1990 function mergeChangesInto( &$editText ){
1991 $fname = 'EditPage::mergeChangesInto';
1992 wfProfileIn( $fname );
1994 $db = wfGetDB( DB_MASTER
);
1996 // This is the revision the editor started from
1997 $baseRevision = $this->getBaseRevision();
1998 if ( is_null( $baseRevision ) ) {
1999 wfProfileOut( $fname );
2002 $baseText = $baseRevision->getText();
2004 // The current state, we want to merge updates into it
2005 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2006 if ( is_null( $currentRevision ) ) {
2007 wfProfileOut( $fname );
2010 $currentText = $currentRevision->getText();
2013 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
2014 $editText = $result;
2015 wfProfileOut( $fname );
2018 wfProfileOut( $fname );
2024 * Check if the browser is on a blacklist of user-agents known to
2025 * mangle UTF-8 data on form submission. Returns true if Unicode
2026 * should make it through, false if it's known to be a problem.
2030 function checkUnicodeCompliantBrowser() {
2031 global $wgBrowserBlackList;
2032 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2033 // No User-Agent header sent? Trust it by default...
2036 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2037 foreach ( $wgBrowserBlackList as $browser ) {
2038 if ( preg_match($browser, $currentbrowser) ) {
2046 * @deprecated use $wgParser->stripSectionName()
2048 function pseudoParseSectionAnchor( $text ) {
2050 return $wgParser->stripSectionName( $text );
2054 * Format an anchor fragment as it would appear for a given section name
2055 * @param string $text
2059 function sectionAnchor( $text ) {
2061 return $wgParser->guessSectionNameFromWikiText( $text );
2065 * Shows a bulletin board style toolbar for common editing functions.
2066 * It can be disabled in the user preferences.
2067 * The necessary JavaScript code can be found in skins/common/edit.js.
2071 static function getEditToolbar() {
2072 global $wgStylePath, $wgContLang, $wgLang;
2075 * toolarray an array of arrays which each include the filename of
2076 * the button image (without path), the opening tag, the closing tag,
2077 * and optionally a sample text that is inserted between the two when no
2078 * selection is highlighted.
2079 * The tip text is shown when the user moves the mouse over the button.
2081 * Already here are accesskeys (key), which are not used yet until someone
2082 * can figure out a way to make them work in IE. However, we should make
2083 * sure these keys are not defined on the edit page.
2087 'image' => $wgLang->getImageFile('button-bold'),
2088 'id' => 'mw-editbutton-bold',
2090 'close' => '\'\'\'',
2091 'sample' => wfMsg('bold_sample'),
2092 'tip' => wfMsg('bold_tip'),
2096 'image' => $wgLang->getImageFile('button-italic'),
2097 'id' => 'mw-editbutton-italic',
2100 'sample' => wfMsg('italic_sample'),
2101 'tip' => wfMsg('italic_tip'),
2105 'image' => $wgLang->getImageFile('button-link'),
2106 'id' => 'mw-editbutton-link',
2109 'sample' => wfMsg('link_sample'),
2110 'tip' => wfMsg('link_tip'),
2114 'image' => $wgLang->getImageFile('button-extlink'),
2115 'id' => 'mw-editbutton-extlink',
2118 'sample' => wfMsg('extlink_sample'),
2119 'tip' => wfMsg('extlink_tip'),
2123 'image' => $wgLang->getImageFile('button-headline'),
2124 'id' => 'mw-editbutton-headline',
2127 'sample' => wfMsg('headline_sample'),
2128 'tip' => wfMsg('headline_tip'),
2132 'image' => $wgLang->getImageFile('button-image'),
2133 'id' => 'mw-editbutton-image',
2134 'open' => '[['.$wgContLang->getNsText(NS_FILE
).':',
2136 'sample' => wfMsg('image_sample'),
2137 'tip' => wfMsg('image_tip'),
2141 'image' => $wgLang->getImageFile('button-media'),
2142 'id' => 'mw-editbutton-media',
2143 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
2145 'sample' => wfMsg('media_sample'),
2146 'tip' => wfMsg('media_tip'),
2150 'image' => $wgLang->getImageFile('button-math'),
2151 'id' => 'mw-editbutton-math',
2153 'close' => "</math>",
2154 'sample' => wfMsg('math_sample'),
2155 'tip' => wfMsg('math_tip'),
2159 'image' => $wgLang->getImageFile('button-nowiki'),
2160 'id' => 'mw-editbutton-nowiki',
2161 'open' => "<nowiki>",
2162 'close' => "</nowiki>",
2163 'sample' => wfMsg('nowiki_sample'),
2164 'tip' => wfMsg('nowiki_tip'),
2168 'image' => $wgLang->getImageFile('button-sig'),
2169 'id' => 'mw-editbutton-signature',
2173 'tip' => wfMsg('sig_tip'),
2177 'image' => $wgLang->getImageFile('button-hr'),
2178 'id' => 'mw-editbutton-hr',
2179 'open' => "\n----\n",
2182 'tip' => wfMsg('hr_tip'),
2186 $toolbar = "<div id='toolbar'>\n";
2189 foreach ( $toolarray as $tool ) {
2191 $image = $wgStylePath.'/common/images/'.$tool['image'],
2192 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2193 // Older browsers show a "speedtip" type message only for ALT.
2194 // Ideally these should be different, realistically they
2195 // probably don't need to be.
2196 $tip = $tool['tip'],
2197 $open = $tool['open'],
2198 $close = $tool['close'],
2199 $sample = $tool['sample'],
2200 $cssId = $tool['id'],
2203 $paramList = implode( ',',
2204 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2205 $script .= "addButton($paramList);\n";
2207 $toolbar .= Html
::inlineScript( "\n$script\n" );
2209 $toolbar .= "\n</div>";
2211 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2217 * Returns an array of html code of the following checkboxes:
2220 * @param $tabindex Current tabindex
2221 * @param $skin Skin object
2222 * @param $checked Array of checkbox => bool, where bool indicates the checked
2223 * status of the checkbox
2227 public function getCheckboxes( &$tabindex, $skin, $checked ) {
2230 $checkboxes = array();
2232 $checkboxes['minor'] = '';
2233 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
2234 if ( $wgUser->isAllowed('minoredit') ) {
2236 'tabindex' => ++
$tabindex,
2237 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2238 'id' => 'wpMinoredit',
2240 $checkboxes['minor'] =
2241 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2242 " <label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
2245 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2246 $checkboxes['watch'] = '';
2247 if ( $wgUser->isLoggedIn() ) {
2249 'tabindex' => ++
$tabindex,
2250 'accesskey' => wfMsg( 'accesskey-watch' ),
2251 'id' => 'wpWatchthis',
2253 $checkboxes['watch'] =
2254 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2255 " <label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
2257 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2262 * Returns an array of html code of the following buttons:
2263 * save, diff, preview and live
2265 * @param $tabindex Current tabindex
2269 public function getEditButtons(&$tabindex) {
2276 'tabindex' => ++
$tabindex,
2277 'value' => wfMsg('savearticle'),
2278 'accesskey' => wfMsg('accesskey-save'),
2279 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2281 $buttons['save'] = Xml
::element('input', $temp, '');
2283 ++
$tabindex; // use the same for preview and live preview
2284 if ( $this->useLivePreview() ) {
2285 $this->doLivePreviewScript(); // Add to output
2288 'id' => 'wpPreview',
2289 'name' => 'wpPreview',
2291 'tabindex' => $tabindex,
2292 'value' => wfMsg('showpreview'),
2294 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2296 $buttons['preview'] = Xml
::element('input', $temp, '');
2299 'id' => 'wpLivePreview',
2300 'name' => 'wpLivePreview',
2302 'tabindex' => $tabindex,
2303 'value' => wfMsg('showlivepreview'),
2304 'accesskey' => wfMsg('accesskey-preview'),
2306 'style' => 'display: none;',
2309 $buttons['live'] = Xml
::element('input', $temp, '');
2312 'id' => 'wpPreview',
2313 'name' => 'wpPreview',
2315 'tabindex' => $tabindex,
2316 'value' => wfMsg('showpreview'),
2317 'accesskey' => wfMsg('accesskey-preview'),
2318 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2320 $buttons['preview'] = Xml
::element('input', $temp, '');
2321 $buttons['live'] = '';
2328 'tabindex' => ++
$tabindex,
2329 'value' => wfMsg('showdiff'),
2330 'accesskey' => wfMsg('accesskey-diff'),
2331 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2333 $buttons['diff'] = Xml
::element('input', $temp, '');
2335 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2340 * Whether to use live preview for this page
2341 * This disables live preview when editing css/js user subpages so that the
2342 * user can preview them (bug 3421)
2346 public function useLivePreview() {
2347 global $wgLivePreview, $wgUser;
2349 return $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) &&
2350 !( ( $this->mTitle
->isCssSubpage() && $this->mTitle
->userCanEditCssSubpage() ) ||
2351 ( $this->mTitle
->isJsSubpage() && $this->mTitle
->userCanEditCssSubpage() ) );
2355 * Output preview text only. This can be sucked into the edit page
2356 * via JavaScript, and saves the server time rendering the skin as
2357 * well as theoretically being more robust on the client (doesn't
2358 * disturb the edit box's undo history, won't eat your text on
2361 * @todo This doesn't include category or interlanguage links.
2362 * Would need to enhance it a bit, <s>maybe wrap them in XML
2363 * or something...</s> that might also require more skin
2364 * initialization, so check whether that's a problem.
2366 function livePreview() {
2369 header( 'Content-type: text/xml; charset=utf-8' );
2370 header( 'Cache-control: no-cache' );
2372 $previewText = $this->getPreviewText();
2373 #$categories = $skin->getCategoryLinks();
2376 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2377 Xml
::tags( 'livepreview', null,
2378 Xml
::element( 'preview', null, $previewText )
2379 #. Xml::element( 'category', null, $categories )
2386 * Get a diff between the current contents of the edit box and the
2387 * version of the page we're editing from.
2389 * If this is a section edit, we'll replace the section as for final
2390 * save and then make a comparison.
2392 function showDiff() {
2393 $oldtext = $this->mArticle
->fetchContent();
2394 $newtext = $this->mArticle
->replaceSection(
2395 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2396 $newtext = $this->mArticle
->preSaveTransform( $newtext );
2397 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2398 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2399 if ( $oldtext !== false ||
$newtext != '' ) {
2400 $de = new DifferenceEngine( $this->mTitle
);
2401 $de->setText( $oldtext, $newtext );
2402 $difftext = $de->getDiff( $oldtitle, $newtitle );
2403 $de->showDiffStyle();
2409 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2413 * Filter an input field through a Unicode de-armoring process if it
2414 * came from an old browser with known broken Unicode editing issues.
2416 * @param WebRequest $request
2417 * @param string $field
2421 function safeUnicodeInput( $request, $field ) {
2422 $text = rtrim( $request->getText( $field ) );
2423 return $request->getBool( 'safemode' )
2424 ?
$this->unmakesafe( $text )
2429 * Filter an output field through a Unicode armoring process if it is
2430 * going to an old browser with known broken Unicode editing issues.
2432 * @param string $text
2436 function safeUnicodeOutput( $text ) {
2438 $codedText = $wgContLang->recodeForEdit( $text );
2439 return $this->checkUnicodeCompliantBrowser()
2441 : $this->makesafe( $codedText );
2445 * A number of web browsers are known to corrupt non-ASCII characters
2446 * in a UTF-8 text editing environment. To protect against this,
2447 * detected browsers will be served an armored version of the text,
2448 * with non-ASCII chars converted to numeric HTML character references.
2450 * Preexisting such character references will have a 0 added to them
2451 * to ensure that round-trips do not alter the original data.
2453 * @param string $invalue
2457 function makesafe( $invalue ) {
2458 // Armor existing references for reversability.
2459 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2464 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2465 $bytevalue = ord( $invalue{$i} );
2466 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2467 $result .= chr( $bytevalue );
2469 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2470 $working = $working << 6;
2471 $working +
= ($bytevalue & 0x3F);
2473 if ( $bytesleft <= 0 ) {
2474 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2476 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2477 $working = $bytevalue & 0x1F;
2479 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2480 $working = $bytevalue & 0x0F;
2482 } else { //1111 0xxx
2483 $working = $bytevalue & 0x07;
2491 * Reverse the previously applied transliteration of non-ASCII characters
2492 * back to UTF-8. Used to protect data from corruption by broken web browsers
2493 * as listed in $wgBrowserBlackList.
2495 * @param string $invalue
2499 function unmakesafe( $invalue ) {
2501 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2502 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2506 $hexstring .= $invalue{$i};
2508 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2510 // Do some sanity checks. These aren't needed for reversability,
2511 // but should help keep the breakage down if the editor
2512 // breaks one of the entities whilst editing.
2513 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2514 $codepoint = hexdec($hexstring);
2515 $result .= codepointToUtf8( $codepoint );
2517 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2520 $result .= substr( $invalue, $i, 1 );
2523 // reverse the transform that we made for reversability reasons.
2524 return strtr( $result, array( "�" => "&#x" ) );
2527 function noCreatePermission() {
2529 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2530 $wgOut->addWikiMsg( 'nocreatetext' );
2534 * Attempt submission
2535 * @return bool false if output is done, true if the rest of the form should be displayed
2537 function attemptSave() {
2538 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2540 $resultDetails = false;
2541 # Allow bots to exempt some edits from bot flagging
2542 $bot = $wgUser->isAllowed('bot') && $wgRequest->getBool('bot',true);
2543 $value = $this->internalAttemptSave( $resultDetails, $bot );
2545 if ( $value == self
::AS_SUCCESS_UPDATE ||
$value == self
::AS_SUCCESS_NEW_ARTICLE
) {
2546 $this->didSave
= true;
2550 case self
::AS_HOOK_ERROR_EXPECTED
:
2551 case self
::AS_CONTENT_TOO_BIG
:
2552 case self
::AS_ARTICLE_WAS_DELETED
:
2553 case self
::AS_CONFLICT_DETECTED
:
2554 case self
::AS_SUMMARY_NEEDED
:
2555 case self
::AS_TEXTBOX_EMPTY
:
2556 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
2560 case self
::AS_HOOK_ERROR
:
2561 case self
::AS_FILTERING
:
2562 case self
::AS_SUCCESS_NEW_ARTICLE
:
2563 case self
::AS_SUCCESS_UPDATE
:
2566 case self
::AS_SPAM_ERROR
:
2567 $this->spamPage ( $resultDetails['spam'] );
2570 case self
::AS_BLOCKED_PAGE_FOR_USER
:
2571 $this->blockedPage();
2574 case self
::AS_IMAGE_REDIRECT_ANON
:
2575 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2578 case self
::AS_READ_ONLY_PAGE_ANON
:
2579 $this->userNotLoggedInPage();
2582 case self
::AS_READ_ONLY_PAGE_LOGGED
:
2583 case self
::AS_READ_ONLY_PAGE
:
2584 $wgOut->readOnlyPage();
2587 case self
::AS_RATE_LIMITED
:
2588 $wgOut->rateLimited();
2591 case self
::AS_NO_CREATE_PERMISSION
;
2592 $this->noCreatePermission();
2595 case self
::AS_BLANK_ARTICLE
:
2596 $wgOut->redirect( $wgTitle->getFullURL() );
2599 case self
::AS_IMAGE_REDIRECT_LOGGED
:
2600 $wgOut->permissionRequired( 'upload' );
2605 function getBaseRevision() {
2606 if ( $this->mBaseRevision
== false ) {
2607 $db = wfGetDB( DB_MASTER
);
2608 $baseRevision = Revision
::loadFromTimestamp(
2609 $db, $this->mTitle
, $this->edittime
);
2610 return $this->mBaseRevision
= $baseRevision;
2612 return $this->mBaseRevision
;