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;
87 /* $didSave should be set to true whenever an article was succesfully altered. */
88 public $didSave = false;
91 public $suppressIntro = false;
97 function EditPage( $article ) {
98 $this->mArticle
=& $article;
99 $this->mTitle
= $article->getTitle();
100 $this->action
= 'submit';
102 # Placeholders for text injection by hooks (empty per default)
103 $this->editFormPageTop
=
104 $this->editFormTextTop
=
105 $this->editFormTextBeforeContent
=
106 $this->editFormTextAfterWarn
=
107 $this->editFormTextAfterTools
=
108 $this->editFormTextBottom
=
109 $this->mPreloadText
= "";
112 function getArticle() {
113 return $this->mArticle
;
118 * Fetch initial editing page content.
121 function getContent( $def_text = '' ) {
122 global $wgOut, $wgRequest, $wgParser, $wgContLang, $wgMessageCache;
124 wfProfileIn( __METHOD__
);
125 # Get variables from query string :P
126 $section = $wgRequest->getVal( 'section' );
127 $preload = $wgRequest->getVal( 'preload' );
128 $undoafter = $wgRequest->getVal( 'undoafter' );
129 $undo = $wgRequest->getVal( 'undo' );
132 // For message page not locally set, use the i18n message.
133 // For other non-existent articles, use preload text if any.
134 if ( !$this->mTitle
->exists() ) {
135 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
136 # If this is a system message, get the default text.
137 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
138 $wgMessageCache->loadAllMessages( $lang );
139 $text = wfMsgGetKey( $message, false, $lang, false );
140 if( wfEmptyMsg( $message, $text ) )
141 $text = $this->getPreloadedText( $preload );
143 # If requested, preload some text.
144 $text = $this->getPreloadedText( $preload );
146 // For existing pages, get text based on "undo" or section parameters.
148 $text = $this->mArticle
->getContent();
149 if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
150 # If they got undoafter and undo round the wrong way, switch them
151 list( $undo, $undoafter ) = array( $undoafter, $undo );
153 if ( $undo > 0 && $undo > $undoafter ) {
154 # Undoing a specific edit overrides section editing; section-editing
155 # doesn't work with undoing.
157 $undorev = Revision
::newFromId($undo);
158 $oldrev = Revision
::newFromId($undoafter);
160 $undorev = Revision
::newFromId($undo);
161 $oldrev = $undorev ?
$undorev->getPrevious() : null;
164 # Sanity check, make sure it's the right page,
165 # the revisions exist and they were not deleted.
166 # Otherwise, $text will be left as-is.
167 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
168 $undorev->getPage() == $oldrev->getPage() &&
169 $undorev->getPage() == $this->mArticle
->getID() &&
170 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
171 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
173 $undotext = $this->mArticle
->getUndoText( $undorev, $oldrev );
174 if ( $undotext === false ) {
175 # Warn the user that something went wrong
176 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-failure">' . wfMsgNoTrans( 'undo-failure' ) . '</div>' );
179 # Inform the user of our success and set an automatic edit summary
180 $this->editFormPageTop
.= $wgOut->parse( '<div class="mw-undo-success">' . wfMsgNoTrans( 'undo-success' ) . '</div>' );
181 $firstrev = $oldrev->getNext();
182 # If we just undid one rev, use an autosummary
183 if ( $firstrev->mId
== $undo ) {
184 $this->summary
= wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
185 $this->undidRev
= $undo;
187 $this->formtype
= 'diff';
190 // Failed basic sanity checks.
191 // Older revisions may have been removed since the link
192 // was created, or we may simply have got bogus input.
193 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-norev">' . wfMsgNoTrans( 'undo-norev' ) . '</div>' );
195 } else if ( $section != '' ) {
196 if ( $section == 'new' ) {
197 $text = $this->getPreloadedText( $preload );
199 $text = $wgParser->getSection( $text, $section, $def_text );
204 wfProfileOut( __METHOD__
);
208 /** Use this method before edit() to preload some text into the edit box */
209 public function setPreloadedText( $text ) {
210 $this->mPreloadText
= $text;
214 * Get the contents of a page from its title and remove includeonly tags
216 * @param $preload String: the title of the page.
217 * @return string The contents of the page.
219 protected function getPreloadedText( $preload ) {
220 if ( !empty($this->mPreloadText
) ) {
221 return $this->mPreloadText
;
222 } elseif ( $preload === '' ) {
225 $preloadTitle = Title
::newFromText( $preload );
226 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
227 $rev = Revision
::newFromTitle($preloadTitle);
228 if ( is_object( $rev ) ) {
229 $text = $rev->getText();
230 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
231 // its own mini-parser! -ævar
232 $text = preg_replace( '~</?includeonly>~', '', $text );
241 * This is the function that extracts metadata from the article body on the first view.
242 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
243 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
245 function extractMetaDataFromArticle () {
246 global $wgUseMetadataEdit, $wgMetadataWhitelist, $wgContLang;
247 $this->mMetaData
= '';
248 if ( !$wgUseMetadataEdit ) return;
249 if ( $wgMetadataWhitelist == '' ) return;
251 $t = $this->getContent();
253 # MISSING : <nowiki> filtering
255 # Categories and language links
256 $t = explode ( "\n" , $t );
257 $catlow = strtolower ( $wgContLang->getNsText( NS_CATEGORY
) );
258 $cat = $ll = array();
259 foreach ( $t AS $key => $x ) {
260 $y = trim ( strtolower ( $x ) );
261 while ( substr ( $y , 0 , 2 ) == '[[' ) {
262 $y = explode ( ']]' , trim ( $x ) );
263 $first = array_shift ( $y );
264 $first = explode ( ':' , $first );
265 $ns = array_shift ( $first );
266 $ns = trim ( str_replace ( '[' , '' , $ns ) );
267 if ( $wgContLang->getLanguageName( $ns ) ||
strtolower ( $ns ) == $catlow ) {
268 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]';
269 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add;
271 $x = implode ( ']]' , $y );
273 $y = trim ( strtolower ( $x ) );
275 $x = implode ( ']]' , $y );
276 $y = trim ( strtolower ( $x ) );
280 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n";
281 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n";
282 $t = implode ( "\n" , $t );
285 $sat = array () ; # stand-alone-templates; must be lowercase
286 $wl_title = Title
::newFromText ( $wgMetadataWhitelist );
287 $wl_article = new Article ( $wl_title );
288 $wl = explode ( "\n" , $wl_article->getContent() );
289 foreach ( $wl AS $x ) {
292 while ( substr ( $x , 0 , 1 ) == '*' ) {
294 $x = trim ( substr ( $x , 1 ) );
297 $sat[] = strtolower ( $x );
302 # Templates, but only some
303 $t = explode ( '{{' , $t );
305 foreach ( $t AS $key => $x ) {
306 $y = explode ( '}}' , $x , 2 );
307 if ( count ( $y ) == 2 ) {
309 $z = explode ( '|' , $z );
310 $tn = array_shift ( $z );
311 if ( in_array ( strtolower ( $tn ) , $sat ) ) {
312 $tl[] = '{{' . $y[0] . '}}';
314 $y = explode ( '}}' , $y[1] , 2 );
316 else $t[$key] = '{{' . $x;
318 else if ( $key != 0 ) $t[$key] = '{{' . $x;
321 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl );
322 $t = implode ( '' , $t );
324 $t = str_replace ( "\n\n\n" , "\n" , $t );
325 $this->mArticle
->mContent
= $t;
326 $this->mMetaData
= $s;
330 * Check if a page was deleted while the user was editing it, before submit.
331 * Note that we rely on the logging table, which hasn't been always there,
332 * but that doesn't matter, because this only applies to brand new
335 protected function wasDeletedSinceLastEdit() {
336 if ( $this->deletedSinceEdit
)
338 if ( $this->mTitle
->isDeletedQuick() ) {
339 $this->lastDelete
= $this->getLastDelete();
340 if ( $this->lastDelete
) {
341 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
342 if ( $deleteTime > $this->starttime
) {
343 $this->deletedSinceEdit
= true;
347 return $this->deletedSinceEdit
;
355 * This is the function that gets called for "action=edit". It
356 * sets up various member variables, then passes execution to
357 * another function, usually showEditForm()
359 * The edit form is self-submitting, so that when things like
360 * preview and edit conflicts occur, we get the same form back
361 * with the extra stuff added. Only when the final submission
362 * is made and all is well do we actually save and redirect to
363 * the newly-edited page.
366 global $wgOut, $wgRequest, $wgEnableJS2system;
367 // Allow extensions to modify/prevent this form or submission
368 if ( !wfRunHooks( 'AlternateEdit', array( $this ) ) ) {
372 wfProfileIn( __METHOD__
);
373 wfDebug( __METHOD__
.": enter\n" );
375 // This is not an article
376 $wgOut->setArticleFlag( false );
378 $this->importFormData( $wgRequest );
379 $this->firsttime
= false;
382 $this->livePreview();
383 wfProfileOut( __METHOD__
);
387 if ( wfReadOnly() && $this->save
) {
390 $this->preview
= true;
393 $wgOut->addScriptFile( 'edit.js' );
395 if( $wgEnableJS2system )
396 $wgOut->addScriptClass( 'editPage' );
398 $permErrors = $this->getEditPermissionErrors();
400 wfDebug( __METHOD__
.": User can't edit\n" );
401 $this->readOnlyPage( $this->getContent(), true, $permErrors, 'edit' );
402 wfProfileOut( __METHOD__
);
406 $this->formtype
= 'save';
407 } else if ( $this->preview
) {
408 $this->formtype
= 'preview';
409 } else if ( $this->diff
) {
410 $this->formtype
= 'diff';
411 } else { # First time through
412 $this->firsttime
= true;
413 if ( $this->previewOnOpen() ) {
414 $this->formtype
= 'preview';
416 $this->extractMetaDataFromArticle () ;
417 $this->formtype
= 'initial';
422 // If they used redlink=1 and the page exists, redirect to the main article
423 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
424 $wgOut->redirect( $this->mTitle
->getFullURL() );
427 wfProfileIn( __METHOD__
."-business-end" );
429 $this->isConflict
= false;
430 // css / js subpages of user pages get a special treatment
431 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
432 $this->isCssSubpage
= $this->mTitle
->isCssSubpage();
433 $this->isJsSubpage
= $this->mTitle
->isJsSubpage();
434 $this->isValidCssJsSubpage
= $this->mTitle
->isValidCssJsSubpage();
436 # Show applicable editing introductions
437 if ( $this->formtype
== 'initial' ||
$this->firsttime
)
440 if ( $this->mTitle
->isTalkPage() ) {
441 $wgOut->addWikiMsg( 'talkpagetext' );
444 # Optional notices on a per-namespace and per-page basis
445 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
446 if ( !wfEmptyMsg( $editnotice_ns, wfMsgForContent( $editnotice_ns ) ) ) {
447 $wgOut->addWikiText( wfMsgForContent( $editnotice_ns ) );
449 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
450 $parts = explode( '/', $this->mTitle
->getDBkey() );
451 $editnotice_base = $editnotice_ns;
452 while ( count( $parts ) > 0 ) {
453 $editnotice_base .= '-'.array_shift( $parts );
454 if ( !wfEmptyMsg( $editnotice_base, wfMsgForContent( $editnotice_base ) ) ) {
455 $wgOut->addWikiText( wfMsgForContent( $editnotice_base ) );
460 # Attempt submission here. This will check for edit conflicts,
461 # and redundantly check for locked database, blocked IPs, etc.
462 # that edit() already checked just in case someone tries to sneak
463 # in the back door with a hand-edited submission URL.
465 if ( 'save' == $this->formtype
) {
466 if ( !$this->attemptSave() ) {
467 wfProfileOut( __METHOD__
."-business-end" );
468 wfProfileOut( __METHOD__
);
473 # First time through: get contents, set time for conflict
475 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
476 if ( $this->initialiseForm() === false) {
477 $this->noSuchSectionPage();
478 wfProfileOut( __METHOD__
."-business-end" );
479 wfProfileOut( __METHOD__
);
482 if ( !$this->mTitle
->getArticleId() )
483 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
486 $this->showEditForm();
487 wfProfileOut( __METHOD__
."-business-end" );
488 wfProfileOut( __METHOD__
);
491 protected function getEditPermissionErrors() {
493 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
494 # Can this title be created?
495 if ( !$this->mTitle
->exists() ) {
496 $permErrors = array_merge( $permErrors,
497 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
499 # Ignore some permissions errors when a user is just previewing/viewing diffs
501 foreach( $permErrors as $error ) {
502 if ( ($this->preview ||
$this->diff
) &&
503 ($error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext') )
508 $permErrors = wfArrayDiff2( $permErrors, $remove );
513 * Show a read-only error
514 * Parameters are the same as OutputPage:readOnlyPage()
515 * Redirect to the article page if redlink=1
517 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
518 global $wgRequest, $wgOut;
519 if ( $wgRequest->getBool( 'redlink' ) ) {
520 // The edit page was reached via a red link.
521 // Redirect to the article page and let them click the edit tab if
522 // they really want a permission error.
523 $wgOut->redirect( $this->mTitle
->getFullUrl() );
525 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
530 * Should we show a preview when the edit form is first shown?
534 protected function previewOnOpen() {
535 global $wgRequest, $wgUser;
536 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
537 // Explicit override from request
539 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
540 // Explicit override from request
542 } elseif ( $this->section
== 'new' ) {
543 // Nothing *to* preview for new sections
545 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
546 // Standard preference behaviour
548 } elseif ( !$this->mTitle
->exists() && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
549 // Categories are special
560 function importFormData( &$request ) {
561 global $wgLang, $wgUser;
562 $fname = 'EditPage::importFormData';
563 wfProfileIn( $fname );
565 # Section edit can come from either the form or a link
566 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
568 if ( $request->wasPosted() ) {
569 # These fields need to be checked for encoding.
570 # Also remove trailing whitespace, but don't remove _initial_
571 # whitespace from the text boxes. This may be significant formatting.
572 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
573 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
574 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
575 # Truncate for whole multibyte characters. +5 bytes for ellipsis
576 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250, '' );
578 # Remove extra headings from summaries and new sections.
579 $this->summary
= preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
581 $this->edittime
= $request->getVal( 'wpEdittime' );
582 $this->starttime
= $request->getVal( 'wpStarttime' );
584 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
586 if ( is_null( $this->edittime
) ) {
587 # If the form is incomplete, force to preview.
588 wfDebug( "$fname: Form data appears to be incomplete\n" );
589 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
590 $this->preview
= true;
592 /* Fallback for live preview */
593 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
594 $this->diff
= $request->getCheck( 'wpDiff' );
596 // Remember whether a save was requested, so we can indicate
597 // if we forced preview due to session failure.
598 $this->mTriedSave
= !$this->preview
;
600 if ( $this->tokenOk( $request ) ) {
601 # Some browsers will not report any submit button
602 # if the user hits enter in the comment box.
603 # The unmarked state will be assumed to be a save,
604 # if the form seems otherwise complete.
605 wfDebug( "$fname: Passed token check.\n" );
606 } else if ( $this->diff
) {
607 # Failed token check, but only requested "Show Changes".
608 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
610 # Page might be a hack attempt posted from
611 # an external site. Preview instead of saving.
612 wfDebug( "$fname: Failed token check; forcing preview\n" );
613 $this->preview
= true;
616 $this->save
= !$this->preview
&& !$this->diff
;
617 if ( !preg_match( '/^\d{14}$/', $this->edittime
)) {
618 $this->edittime
= null;
621 if ( !preg_match( '/^\d{14}$/', $this->starttime
)) {
622 $this->starttime
= null;
625 $this->recreate
= $request->getCheck( 'wpRecreate' );
627 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
628 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
630 # Don't force edit summaries when a user is editing their own user or talk page
631 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
632 $this->mTitle
->getText() == $wgUser->getName() )
634 $this->allowBlankSummary
= true;
636 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
639 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
641 # Not a posted form? Start with nothing.
642 wfDebug( "$fname: Not a posted form.\n" );
643 $this->textbox1
= '';
644 $this->textbox2
= '';
645 $this->mMetaData
= '';
647 $this->edittime
= '';
648 $this->starttime
= wfTimestampNow();
650 $this->preview
= false;
653 $this->minoredit
= false;
654 $this->watchthis
= false;
655 $this->recreate
= false;
657 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
658 $this->summary
= $request->getVal( 'preloadtitle' );
660 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
661 $this->summary
= $request->getText( 'summary' );
664 if ( $request->getVal( 'minor' ) ) {
665 $this->minoredit
= true;
669 // FIXME: unused variable?
670 $this->oldid
= $request->getInt( 'oldid' );
672 $this->live
= $request->getCheck( 'live' );
673 $this->editintro
= $request->getText( 'editintro' );
675 wfProfileOut( $fname );
677 // Allow extensions to modify form data
678 wfRunHooks( 'EditPage::importFormData', array( $this, $request ) );
682 * Make sure the form isn't faking a user's credentials.
684 * @param $request WebRequest
688 function tokenOk( &$request ) {
690 $token = $request->getVal( 'wpEditToken' );
691 $this->mTokenOk
= $wgUser->matchEditToken( $token );
692 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
693 return $this->mTokenOk
;
697 * Show all applicable editing introductions
699 protected function showIntro() {
700 global $wgOut, $wgUser;
701 if ( $this->suppressIntro
) {
705 $namespace = $this->mTitle
->getNamespace();
707 if ( $namespace == NS_MEDIAWIKI
) {
708 # Show a warning if editing an interface message
709 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1</div>", 'editinginterface' );
712 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
713 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
714 $parts = explode( '/', $this->mTitle
->getText(), 2 );
715 $username = $parts[0];
716 $id = User
::idFromName( $username );
717 $ip = User
::isIP( $username );
718 if ( $id == 0 && !$ip ) {
719 $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
720 array( 'userpage-userdoesnotexist', $username ) );
723 # Try to add a custom edit intro, or use the standard one if this is not possible.
724 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
725 if ( $wgUser->isLoggedIn() ) {
726 $wgOut->wrapWikiMsg( '<div class="mw-newarticletext">$1</div>', 'newarticletext' );
728 $wgOut->wrapWikiMsg( '<div class="mw-newarticletextanon">$1</div>', 'newarticletextanon' );
731 # Give a notice if the user is editing a deleted/moved page...
732 if ( !$this->mTitle
->exists() ) {
733 LogEventsList
::showLogExtract( $wgOut, array( 'delete', 'move' ), $this->mTitle
->getPrefixedText(),
734 '', array( 'lim' => 10,
735 'conds' => array( "log_action != 'revision'" ),
736 'showIfEmpty' => false,
737 'msgKey' => array( 'recreate-moveddeleted-warn') )
743 * Attempt to show a custom editing introduction, if supplied
747 protected function showCustomIntro() {
748 if ( $this->editintro
) {
749 $title = Title
::newFromText( $this->editintro
);
750 if ( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
752 $revision = Revision
::newFromTitle( $title );
753 $wgOut->addWikiTextTitleTidy( $revision->getText(), $this->mTitle
);
764 * Attempt submission (no UI)
765 * @return one of the constants describing the result
767 function internalAttemptSave( &$result, $bot = false ) {
768 global $wgFilterCallback, $wgUser, $wgOut, $wgParser;
769 global $wgMaxArticleSize;
771 $fname = 'EditPage::attemptSave';
772 wfProfileIn( $fname );
773 wfProfileIn( "$fname-checks" );
775 if ( !wfRunHooks( 'EditPage::attemptSave', array( $this ) ) )
777 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
778 return self
::AS_HOOK_ERROR
;
781 # Check image redirect
782 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
783 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
784 !$wgUser->isAllowed( 'upload' ) ) {
785 if ( $wgUser->isAnon() ) {
786 return self
::AS_IMAGE_REDIRECT_ANON
;
788 return self
::AS_IMAGE_REDIRECT_LOGGED
;
792 # Reintegrate metadata
793 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
794 $this->mMetaData
= '' ;
797 $match = self
::matchSummarySpamRegex( $this->summary
);
798 if ( $match === false ) {
799 $match = self
::matchSpamRegex( $this->textbox1
);
801 if ( $match !== false ) {
802 $result['spam'] = $match;
804 $pdbk = $this->mTitle
->getPrefixedDBkey();
805 $match = str_replace( "\n", '', $match );
806 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
807 wfProfileOut( "$fname-checks" );
808 wfProfileOut( $fname );
809 return self
::AS_SPAM_ERROR
;
811 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
812 # Error messages or other handling should be performed by the filter function
813 wfProfileOut( "$fname-checks" );
814 wfProfileOut( $fname );
815 return self
::AS_FILTERING
;
817 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
818 # Error messages etc. could be handled within the hook...
819 wfProfileOut( "$fname-checks" );
820 wfProfileOut( $fname );
821 return self
::AS_HOOK_ERROR
;
822 } elseif ( $this->hookError
!= '' ) {
823 # ...or the hook could be expecting us to produce an error
824 wfProfileOut( "$fname-checks" );
825 wfProfileOut( $fname );
826 return self
::AS_HOOK_ERROR_EXPECTED
;
828 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
829 # Check block state against master, thus 'false'.
830 wfProfileOut( "$fname-checks" );
831 wfProfileOut( $fname );
832 return self
::AS_BLOCKED_PAGE_FOR_USER
;
834 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
835 if ( $this->kblength
> $wgMaxArticleSize ) {
836 // Error will be displayed by showEditForm()
837 $this->tooBig
= true;
838 wfProfileOut( "$fname-checks" );
839 wfProfileOut( $fname );
840 return self
::AS_CONTENT_TOO_BIG
;
843 if ( !$wgUser->isAllowed('edit') ) {
844 if ( $wgUser->isAnon() ) {
845 wfProfileOut( "$fname-checks" );
846 wfProfileOut( $fname );
847 return self
::AS_READ_ONLY_PAGE_ANON
;
850 wfProfileOut( "$fname-checks" );
851 wfProfileOut( $fname );
852 return self
::AS_READ_ONLY_PAGE_LOGGED
;
856 if ( wfReadOnly() ) {
857 wfProfileOut( "$fname-checks" );
858 wfProfileOut( $fname );
859 return self
::AS_READ_ONLY_PAGE
;
861 if ( $wgUser->pingLimiter() ) {
862 wfProfileOut( "$fname-checks" );
863 wfProfileOut( $fname );
864 return self
::AS_RATE_LIMITED
;
867 # If the article has been deleted while editing, don't save it without
869 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
870 wfProfileOut( "$fname-checks" );
871 wfProfileOut( $fname );
872 return self
::AS_ARTICLE_WAS_DELETED
;
875 wfProfileOut( "$fname-checks" );
877 # If article is new, insert it.
878 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
880 // Late check for create permission, just in case *PARANOIA*
881 if ( !$this->mTitle
->userCan( 'create' ) ) {
882 wfDebug( "$fname: no create permission\n" );
883 wfProfileOut( $fname );
884 return self
::AS_NO_CREATE_PERMISSION
;
887 # Don't save a new article if it's blank.
888 if ( '' == $this->textbox1
) {
889 wfProfileOut( $fname );
890 return self
::AS_BLANK_ARTICLE
;
893 // Run post-section-merge edit filter
894 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
895 # Error messages etc. could be handled within the hook...
896 wfProfileOut( $fname );
897 return self
::AS_HOOK_ERROR
;
898 } elseif ( $this->hookError
!= '' ) {
899 # ...or the hook could be expecting us to produce an error
900 wfProfileOut( $fname );
901 return self
::AS_HOOK_ERROR_EXPECTED
;
904 # Handle the user preference to force summaries here. Check if it's not a redirect.
905 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
906 if ( md5( $this->summary
) == $this->autoSumm
) {
907 $this->missingSummary
= true;
908 wfProfileOut( $fname );
909 return self
::AS_SUMMARY_NEEDED
;
913 $isComment = ( $this->section
== 'new' );
915 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
916 $this->minoredit
, $this->watchthis
, false, $isComment, $bot );
918 wfProfileOut( $fname );
919 return self
::AS_SUCCESS_NEW_ARTICLE
;
922 # Article exists. Check for edit conflict.
924 $this->mArticle
->clear(); # Force reload of dates, etc.
925 $this->mArticle
->forUpdate( true ); # Lock the article
927 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
929 if ( $this->mArticle
->getTimestamp() != $this->edittime
) {
930 $this->isConflict
= true;
931 if ( $this->section
== 'new' ) {
932 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
933 $this->mArticle
->getComment() == $this->summary
) {
934 // Probably a duplicate submission of a new comment.
935 // This can happen when squid resends a request after
936 // a timeout but the first one actually went through.
937 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
939 // New comment; suppress conflict.
940 $this->isConflict
= false;
941 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
945 $userid = $wgUser->getId();
947 # Suppress edit conflict with self, except for section edits where merging is required.
948 if ( $this->isConflict
&& $this->section
== '' && $this->userWasLastToEdit($userid,$this->edittime
) ) {
949 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
950 $this->isConflict
= false;
953 if ( $this->isConflict
) {
954 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
955 $this->mArticle
->getTimestamp() . "')\n" );
956 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
958 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
959 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
961 if ( is_null( $text ) ) {
962 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
963 $this->isConflict
= true;
964 $text = $this->textbox1
; // do not try to merge here!
965 } else if ( $this->isConflict
) {
967 if ( $this->mergeChangesInto( $text ) ) {
968 // Successful merge! Maybe we should tell the user the good news?
969 $this->isConflict
= false;
970 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
973 $this->textbox1
= $text;
974 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
978 if ( $this->isConflict
) {
979 wfProfileOut( $fname );
980 return self
::AS_CONFLICT_DETECTED
;
983 $oldtext = $this->mArticle
->getContent();
985 // Run post-section-merge edit filter
986 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
987 # Error messages etc. could be handled within the hook...
988 wfProfileOut( $fname );
989 return self
::AS_HOOK_ERROR
;
990 } elseif ( $this->hookError
!= '' ) {
991 # ...or the hook could be expecting us to produce an error
992 wfProfileOut( $fname );
993 return self
::AS_HOOK_ERROR_EXPECTED
;
996 # Handle the user preference to force summaries here, but not for null edits
997 if ( $this->section
!= 'new' && !$this->allowBlankSummary
&& 0 != strcmp($oldtext,$text)
998 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
1000 if ( md5( $this->summary
) == $this->autoSumm
) {
1001 $this->missingSummary
= true;
1002 wfProfileOut( $fname );
1003 return self
::AS_SUMMARY_NEEDED
;
1007 # And a similar thing for new sections
1008 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
1009 if (trim($this->summary
) == '') {
1010 $this->missingSummary
= true;
1011 wfProfileOut( $fname );
1012 return self
::AS_SUMMARY_NEEDED
;
1017 wfProfileIn( "$fname-sectionanchor" );
1018 $sectionanchor = '';
1019 if ( $this->section
== 'new' ) {
1020 if ( $this->textbox1
== '' ) {
1021 $this->missingComment
= true;
1022 return self
::AS_TEXTBOX_EMPTY
;
1024 if ( $this->summary
!= '' ) {
1025 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary
);
1026 # This is a new section, so create a link to the new section
1027 # in the revision summary.
1028 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1029 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1031 } elseif ( $this->section
!= '' ) {
1032 # Try to get a section anchor from the section source, redirect to edited section if header found
1033 # XXX: might be better to integrate this into Article::replaceSection
1034 # for duplicate heading checking and maybe parsing
1035 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1036 # we can't deal with anchors, includes, html etc in the header for now,
1037 # headline would need to be parsed to improve this
1038 if ( $hasmatch and strlen($matches[2]) > 0 ) {
1039 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
1042 wfProfileOut( "$fname-sectionanchor" );
1044 // Save errors may fall down to the edit form, but we've now
1045 // merged the section into full text. Clear the section field
1046 // so that later submission of conflict forms won't try to
1047 // replace that into a duplicated mess.
1048 $this->textbox1
= $text;
1049 $this->section
= '';
1051 // Check for length errors again now that the section is merged in
1052 $this->kblength
= (int)(strlen( $text ) / 1024);
1053 if ( $this->kblength
> $wgMaxArticleSize ) {
1054 $this->tooBig
= true;
1055 wfProfileOut( $fname );
1056 return self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
;
1059 # update the article here
1060 if ( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
1061 $this->watchthis
, $bot, $sectionanchor ) )
1063 wfProfileOut( $fname );
1064 return self
::AS_SUCCESS_UPDATE
;
1066 $this->isConflict
= true;
1068 wfProfileOut( $fname );
1069 return self
::AS_END
;
1073 * Check if no edits were made by other users since
1074 * the time a user started editing the page. Limit to
1075 * 50 revisions for the sake of performance.
1077 protected function userWasLastToEdit( $id, $edittime ) {
1078 if( !$id ) return false;
1079 $dbw = wfGetDB( DB_MASTER
);
1080 $res = $dbw->select( 'revision',
1083 'rev_page' => $this->mArticle
->getId(),
1084 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1087 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1088 while( $row = $res->fetchObject() ) {
1089 if( $row->rev_user
!= $id ) {
1097 * Check given input text against $wgSpamRegex, and return the text of the first match.
1098 * @return mixed -- matching string or false
1100 public static function matchSpamRegex( $text ) {
1101 global $wgSpamRegex;
1102 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1103 $regexes = (array)$wgSpamRegex;
1104 return self
::matchSpamRegexInternal( $text, $regexes );
1108 * Check given input text against $wgSpamRegex, and return the text of the first match.
1109 * @return mixed -- matching string or false
1111 public static function matchSummarySpamRegex( $text ) {
1112 global $wgSummarySpamRegex;
1113 $regexes = (array)$wgSummarySpamRegex;
1114 return self
::matchSpamRegexInternal( $text, $regexes );
1117 protected static function matchSpamRegexInternal( $text, $regexes ) {
1118 foreach( $regexes as $regex ) {
1120 if( preg_match( $regex, $text, $matches ) ) {
1128 * Initialise form fields in the object
1129 * Called on the first invocation, e.g. when a user clicks an edit link
1131 function initialiseForm() {
1132 $this->edittime
= $this->mArticle
->getTimestamp();
1133 $this->textbox1
= $this->getContent( false );
1134 if ( $this->textbox1
=== false ) return false;
1139 function setHeaders() {
1140 global $wgOut, $wgTitle;
1141 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1142 if ( $this->formtype
== 'preview' ) {
1143 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1145 if ( $this->isConflict
) {
1146 $wgOut->setPageTitle( wfMsg( 'editconflict', $wgTitle->getPrefixedText() ) );
1147 } elseif ( $this->section
!= '' ) {
1148 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1149 $wgOut->setPageTitle( wfMsg( $msg, $wgTitle->getPrefixedText() ) );
1151 # Use the title defined by DISPLAYTITLE magic word when present
1152 if ( isset($this->mParserOutput
)
1153 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1156 $title = $wgTitle->getPrefixedText();
1158 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1163 * Send the edit form and related headers to $wgOut
1164 * @param $formCallback Optional callable that takes an OutputPage
1165 * parameter; will be called during form output
1166 * near the top, for captchas and the like.
1168 function showEditForm( $formCallback=null ) {
1169 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle, $wgRequest;
1171 # If $wgTitle is null, that means we're in API mode.
1172 # Some hook probably called this function without checking
1173 # for is_null($wgTitle) first. Bail out right here so we don't
1174 # do lots of work just to discard it right after.
1175 if (is_null($wgTitle))
1178 $fname = 'EditPage::showEditForm';
1179 wfProfileIn( $fname );
1181 $sk = $wgUser->getSkin();
1183 #need to parse the preview early so that we know which templates are used,
1184 #otherwise users with "show preview after edit box" will get a blank list
1185 #we parse this near the beginning so that setHeaders can do the title
1186 #setting work instead of leaving it in getPreviewText
1187 $previewOutput = '';
1188 if ( $this->formtype
== 'preview' ) {
1189 $previewOutput = $this->getPreviewText();
1192 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
1194 $this->setHeaders();
1196 # Enabled article-related sidebar, toplinks, etc.
1197 $wgOut->setArticleRelated( true );
1199 $cancelParams = array();
1201 if ( $this->isConflict
) {
1202 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1</div>", 'explainconflict' );
1204 $this->textbox2
= $this->textbox1
;
1205 $this->textbox1
= $this->getContent();
1206 $this->edittime
= $this->mArticle
->getTimestamp();
1208 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1210 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1211 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1
, $matches );
1212 if ( !empty( $matches[2] ) ) {
1214 $this->summary
= "/* " .
1215 $wgParser->stripSectionName(trim($matches[2])) .
1221 if ( $this->missingComment
) {
1222 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1225 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1226 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1229 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1230 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1233 if ( $this->hookError
!== '' ) {
1234 $wgOut->addWikiText( $this->hookError
);
1237 if ( !$this->checkUnicodeCompliantBrowser() ) {
1238 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1240 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1241 // Let sysop know that this will make private content public if saved
1243 if ( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1244 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
1245 } else if ( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1246 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
1249 if ( !$this->mArticle
->mRevision
->isCurrent() ) {
1250 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1251 $cancelParams['oldid'] = $this->mArticle
->mRevision
->getId();
1252 $wgOut->addWikiMsg( 'editingold' );
1257 if ( wfReadOnly() ) {
1258 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1259 } elseif ( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
1260 $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' );
1262 if ( $this->isCssJsSubpage
) {
1263 # Check the skin exists
1264 if ( !$this->isValidCssJsSubpage
) {
1265 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1267 if ( $this->formtype
!== 'preview' ) {
1268 if ( $this->isCssSubpage
)
1269 $wgOut->addWikiMsg( 'usercssyoucanpreview' );
1270 if ( $this->isJsSubpage
)
1271 $wgOut->addWikiMsg( 'userjsyoucanpreview' );
1276 $classes = array(); // Textarea CSS
1277 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1278 } elseif ( $this->mTitle
->isProtected( 'edit' ) ) {
1279 # Is the title semi-protected?
1280 if ( $this->mTitle
->isSemiProtected() ) {
1281 $noticeMsg = 'semiprotectedpagewarning';
1282 $classes[] = 'mw-textarea-sprotected';
1284 # Then it must be protected based on static groups (regular)
1285 $noticeMsg = 'protectedpagewarning';
1286 $classes[] = 'mw-textarea-protected';
1288 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
->getPrefixedText(), '',
1289 array( 'lim' => 1, 'msgKey' => array( $noticeMsg ) ) );
1291 if ( $this->mTitle
->isCascadeProtected() ) {
1292 # Is this page under cascading protection from some source pages?
1293 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1294 $notice = "<div class='mw-cascadeprotectedwarning'>$1\n";
1295 $cascadeSourcesCount = count( $cascadeSources );
1296 if ( $cascadeSourcesCount > 0 ) {
1297 # Explain, and list the titles responsible
1298 foreach( $cascadeSources as $page ) {
1299 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1302 $notice .= '</div>';
1303 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1305 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1306 $wgOut->wrapWikiMsg( '<div class="mw-titleprotectedwarning">$1</div>', 'titleprotectedwarning' );
1309 if ( $this->kblength
=== false ) {
1310 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1312 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1313 $wgOut->addHTML( "<div class='error' id='mw-edit-longpageerror'>\n" );
1314 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) );
1315 $wgOut->addHTML( "</div>\n" );
1316 } elseif ( $this->kblength
> 29 ) {
1317 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1318 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) );
1319 $wgOut->addHTML( "</div>\n" );
1322 $action = $wgTitle->escapeLocalURL( array( 'action' => $this->action
) );
1324 $summary = wfMsgExt( 'summary', 'parseinline' );
1325 $subject = wfMsgExt( 'subject', 'parseinline' );
1327 $cancel = $sk->link(
1329 wfMsgExt( 'cancel', array( 'parseinline' ) ),
1330 array( 'id' => 'mw-editform-cancel' ),
1332 array( 'known', 'noclasses' )
1334 $separator = wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1335 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1336 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1337 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1338 htmlspecialchars( wfMsg( 'newwindow' ) );
1340 global $wgRightsText;
1341 if ( $wgRightsText ) {
1342 $copywarnMsg = array( 'copyrightwarning',
1343 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1346 $copywarnMsg = array( 'copyrightwarning2',
1347 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1349 // Allow for site and per-namespace customization of contribution/copyright notice.
1350 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
1352 if ( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1353 # prepare toolbar for edit buttons
1354 $toolbar = EditPage
::getEditToolbar();
1360 // activate checkboxes if user wants them to be always active
1361 if ( !$this->preview
&& !$this->diff
) {
1362 # Sort out the "watch" checkbox
1363 if ( $wgUser->getOption( 'watchdefault' ) ) {
1365 $this->watchthis
= true;
1366 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1368 $this->watchthis
= true;
1369 } elseif ( $this->mTitle
->userIsWatching() ) {
1371 $this->watchthis
= true;
1374 # May be overriden by request parameters
1375 if( $wgRequest->getBool( 'watchthis' ) ) {
1376 $this->watchthis
= true;
1379 if ( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1382 $wgOut->addHTML( $this->editFormPageTop
);
1384 if ( $wgUser->getOption( 'previewontop' ) ) {
1385 $this->displayPreviewArea( $previewOutput, true );
1389 $wgOut->addHTML( $this->editFormTextTop
);
1391 # if this is a comment, show a subject line at the top, which is also the edit summary.
1392 # Otherwise, show a summary field at the bottom
1393 $summarytext = $wgContLang->recodeForEdit( $this->summary
);
1395 # If a blank edit summary was previously provided, and the appropriate
1396 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1397 # user being bounced back more than once in the event that a summary
1400 # For a bit more sophisticated detection of blank summaries, hash the
1401 # automatic one and pass that in the hidden field wpAutoSummary.
1402 $summaryhiddens = '';
1403 if ( $this->missingSummary
) $summaryhiddens .= Xml
::hidden( 'wpIgnoreBlankSummary', true );
1404 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1405 $summaryhiddens .= Xml
::hidden( 'wpAutoSummary', $autosumm );
1406 if ( $this->section
== 'new' ) {
1407 $commentsubject = '';
1408 if ( !$wgRequest->getBool( 'nosummary' ) ) {
1409 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1410 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1413 Xml
::tags( 'label', array( 'for' => 'wpSummary' ), $subject );
1415 Xml
::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1417 $commentsubject .= ' ';
1418 $commentsubject .= Xml
::input( 'wpSummary',
1422 'id' => 'wpSummary',
1423 'maxlength' => '200',
1427 $summaryhiddens .= Xml
::hidden( 'wpIgnoreBlankSummary', true ); # bug 18699
1429 $editsummary = "<div class='editOptions'>\n";
1431 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary
) );
1432 $subjectpreview = $summarytext && ( $this->preview ||
$this->diff
) ?
1433 "<div class=\"mw-summary-preview\">". wfMsgExt('subject-preview', 'parseinline') . $sk->commentBlock( $formattedSummary, $this->mTitle
, true )."</div>\n" : '';
1434 $summarypreview = '';
1436 $commentsubject = '';
1438 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1439 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1441 $editsummary = Xml
::tags( 'label', array( 'for' => 'wpSummary' ), $summary );
1442 $editsummary = Xml
::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1443 $editsummary ) . ' ';
1445 $editsummary .= Xml
::input( 'wpSummary',
1449 'id' => 'wpSummary',
1450 'maxlength' => '200',
1454 // No idea where this is closed.
1455 $editsummary = Xml
::openElement( 'div', array( 'class' => 'editOptions' ) )
1456 . $editsummary . '<br/>';
1458 $summarypreview = '';
1459 if ( $summarytext && ( $this->preview ||
$this->diff
) ) {
1462 array( 'class' => 'mw-summary-preview' ),
1463 wfMsgExt( 'summary-preview', 'parseinline' ) .
1464 $sk->commentBlock( $this->summary
, $this->mTitle
)
1467 $subjectpreview = '';
1469 $commentsubject .= $summaryhiddens;
1471 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1472 if ( !$this->preview
&& !$this->diff
) {
1473 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1475 $templates = $this->getTemplates();
1476 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1478 $hiddencats = $this->mArticle
->getHiddenCategories();
1479 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1481 global $wgUseMetadataEdit ;
1482 if ( $wgUseMetadataEdit ) {
1483 $metadata = $this->mMetaData
;
1484 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1485 $top = wfMsgWikiHtml( 'metadata_help' );
1486 /* ToDo: Replace with clean code */
1487 $ew = $wgUser->getOption( 'editwidth' );
1488 if ( $ew ) $ew = " style=\"width:100%\"";
1490 $cols = $wgUser->getIntOption( 'cols' );
1492 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1494 else $metadata = "" ;
1497 if ( $this->wasDeletedSinceLastEdit() ) {
1498 if ( 'save' != $this->formtype
) {
1499 $wgOut->wrapWikiMsg(
1500 "<div class='error mw-deleted-while-editing'>\n$1</div>",
1501 'deletedwhileediting' );
1503 // Hide the toolbar and edit area, user can click preview to get it back
1504 // Add an confirmation checkbox and explanation.
1506 $recreate = '<div class="mw-confirm-recreate">' .
1507 $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
) ) .
1508 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1509 array( 'title' => $sk->titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1516 $checkboxes = $this->getCheckboxes( $tabindex, $sk,
1517 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1519 $checkboxhtml = implode( $checkboxes, "\n" );
1521 $buttons = $this->getEditButtons( $tabindex );
1522 $buttonshtml = implode( $buttons, "\n" );
1524 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1525 ?
'' : Xml
::hidden( 'safemode', '1' );
1527 $wgOut->addHTML( <<<END
1529 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1533 if ( is_callable( $formCallback ) ) {
1534 call_user_func_array( $formCallback, array( &$wgOut ) );
1537 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1539 // Put these up at the top to ensure they aren't lost on early form submission
1540 $this->showFormBeforeText();
1542 $wgOut->addHTML( <<<END
1546 {$this->editFormTextBeforeContent}
1549 $this->showTextbox1( $classes );
1551 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1552 $wgOut->addHTML( <<<END
1553 {$this->editFormTextAfterWarn}
1563 "<div class='editButtons'>
1565 <span class='editHelp'>{$cancel}{$separator}{$edithelp}</span>
1566 </div><!-- editButtons -->
1567 </div><!-- editOptions -->");
1570 * To make it harder for someone to slip a user a page
1571 * which submits an edit form to the wiki without their
1572 * knowledge, a random token is associated with the login
1573 * session. If it's not passed back with the submission,
1574 * we won't save the page, or render user JavaScript and
1577 * For anon editors, who may not have a session, we just
1578 * include the constant suffix to prevent editing from
1579 * broken text-mangling proxies.
1581 $token = htmlspecialchars( $wgUser->editToken() );
1582 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1584 $this->showTosSummary();
1585 $this->showEditTools();
1587 $wgOut->addHTML( <<<END
1588 {$this->editFormTextAfterTools}
1589 <div class='templatesUsed'>
1590 {$formattedtemplates}
1592 <div class='hiddencats'>
1593 {$formattedhiddencats}
1598 if ( $this->isConflict
&& wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1599 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1601 $de = new DifferenceEngine( $this->mTitle
);
1602 $de->setText( $this->textbox2
, $this->textbox1
);
1603 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1605 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1606 $this->showTextbox2();
1608 $wgOut->addHTML( $this->editFormTextBottom
);
1609 $wgOut->addHTML( "</form>\n" );
1610 if ( !$wgUser->getOption( 'previewontop' ) ) {
1611 $this->displayPreviewArea( $previewOutput, false );
1614 wfProfileOut( $fname );
1617 protected function showFormBeforeText() {
1620 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1621 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1622 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1623 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1626 protected function showTextbox1( $classes ) {
1627 $attribs = array( 'tabindex' => 1 );
1629 if ( $this->wasDeletedSinceLastEdit() )
1630 $attribs['type'] = 'hidden';
1631 if ( !empty($classes) )
1632 $attribs['class'] = implode(' ',$classes);
1634 $this->showTextbox( $this->textbox1
, 'wpTextbox1', $attribs );
1637 protected function showTextbox2() {
1638 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6 ) );
1641 protected function showTextbox( $content, $name, $attribs = array() ) {
1642 global $wgOut, $wgUser;
1644 $wikitext = $this->safeUnicodeOutput( $content );
1645 if ( $wikitext !== '' ) {
1646 // Ensure there's a newline at the end, otherwise adding lines
1648 // But don't add a newline if the ext is empty, or Firefox in XHTML
1649 // mode will show an extra newline. A bit annoying.
1653 $attribs['accesskey'] = ',';
1654 $attribs['id'] = $name;
1656 if ( $wgUser->getOption( 'editwidth' ) )
1657 $attribs['style'] = 'width: 100%';
1659 $wgOut->addHTML( Xml
::textarea(
1662 $wgUser->getIntOption( 'cols' ), $wgUser->getIntOption( 'rows' ),
1666 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1670 $classes[] = 'ontop';
1672 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1674 if ( $this->formtype
!= 'preview' )
1675 $attribs['style'] = 'display: none;';
1677 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
1679 if ( $this->formtype
== 'preview' ) {
1680 $this->showPreview( $previewOutput );
1683 $wgOut->addHTML( '</div>' );
1685 if ( $this->formtype
== 'diff') {
1691 * Append preview output to $wgOut.
1692 * Includes category rendering if this is a category page.
1694 * @param string $text The HTML to be output for the preview.
1696 protected function showPreview( $text ) {
1698 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1699 $this->mArticle
->openShowCategory();
1701 # This hook seems slightly odd here, but makes things more
1702 # consistent for extensions.
1703 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1704 $wgOut->addHTML( $text );
1705 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1706 $this->mArticle
->closeShowCategory();
1711 * Live Preview lets us fetch rendered preview page content and
1712 * add it to the page without refreshing the whole page.
1713 * If not supported by the browser it will fall through to the normal form
1714 * submission method.
1716 * This function outputs a script tag to support live preview, and
1717 * returns an onclick handler which should be added to the attributes
1718 * of the preview button
1720 function doLivePreviewScript() {
1721 global $wgOut, $wgTitle;
1722 $wgOut->addScriptFile( 'preview.js' );
1726 protected function showTosSummary() {
1727 $msg = 'editpage-tos-summary';
1728 // Give a chance for site and per-namespace customizations of
1729 // terms of service summary link that might exist separately
1730 // from the copyright notice.
1732 // This will display between the save button and the edit tools,
1733 // so should remain short!
1734 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
1735 $text = wfMsg( $msg );
1736 if( !wfEmptyMsg( $msg, $text ) && $text !== '-' ) {
1738 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1739 $wgOut->addWikiMsgArray( $msg, array() );
1740 $wgOut->addHTML( '</div>' );
1744 protected function showEditTools() {
1746 $wgOut->addHTML( '<div class="mw-editTools">' );
1747 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1748 $wgOut->addHTML( '</div>' );
1751 protected function getLastDelete() {
1752 $dbr = wfGetDB( DB_SLAVE
);
1753 $data = $dbr->selectRow(
1754 array( 'logging', 'user' ),
1765 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1766 'log_title' => $this->mTitle
->getDBkey(),
1767 'log_type' => 'delete',
1768 'log_action' => 'delete',
1769 'user_id=log_user' ),
1771 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1773 // Quick paranoid permission checks...
1774 if( is_object($data) ) {
1775 if( $data->log_deleted
& LogPage
::DELETED_USER
)
1776 $data->user_name
= wfMsgHtml('rev-deleted-user');
1777 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
1778 $data->log_comment
= wfMsgHtml('rev-deleted-comment');
1784 * Get the rendered text for previewing.
1787 function getPreviewText() {
1788 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache;
1790 wfProfileIn( __METHOD__
);
1792 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1793 if ( $this->mTokenOkExceptSuffix
) {
1794 $note = wfMsg( 'token_suffix_mismatch' );
1796 $note = wfMsg( 'session_fail_preview' );
1799 $note = wfMsg( 'previewnote' );
1802 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1803 $parserOptions->setEditSection( false );
1804 $parserOptions->setIsPreview( true );
1805 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
1808 if ( $wgRawHtml && !$this->mTokenOk
) {
1809 // Could be an offsite preview attempt. This is very unsafe if
1810 // HTML is enabled, as it could be an attack.
1811 return $wgOut->parse( "<div class='previewnote'>" .
1812 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1815 # don't parse user css/js, show message about preview
1816 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1818 if ( $this->isCssJsSubpage
) {
1819 if (preg_match("/\\.css$/", $this->mTitle
->getText() ) ) {
1820 $previewtext = wfMsg('usercsspreview');
1821 } else if (preg_match("/\\.js$/", $this->mTitle
->getText() ) ) {
1822 $previewtext = wfMsg('userjspreview');
1824 $parserOptions->setTidy(true);
1825 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
1826 $previewHTML = $parserOutput->mText
;
1827 } elseif ( $rt = Title
::newFromRedirectArray( $this->textbox1
) ) {
1828 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
1830 $toparse = $this->textbox1
;
1832 # If we're adding a comment, we need to show the
1833 # summary as the headline
1834 if ( $this->section
=="new" && $this->summary
!="" ) {
1835 $toparse="== {$this->summary} ==\n\n".$toparse;
1838 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1840 // Parse mediawiki messages with correct target language
1841 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1842 list( /* $unused */, $lang ) = $wgMessageCache->figureMessage( $this->mTitle
->getText() );
1843 $obj = wfGetLangObj( $lang );
1844 $parserOptions->setTargetLanguage( $obj );
1848 $parserOptions->setTidy(true);
1849 $parserOptions->enableLimitReport();
1850 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ),
1851 $this->mTitle
, $parserOptions );
1853 $previewHTML = $parserOutput->getText();
1854 $this->mParserOutput
= $parserOutput;
1855 $wgOut->addParserOutputNoText( $parserOutput );
1857 if ( count( $parserOutput->getWarnings() ) ) {
1858 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1862 if( $this->isConflict
) {
1863 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1865 $conflict = '<hr />';
1868 $previewhead = "<div class='previewnote'>\n" .
1869 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
1870 $wgOut->parse( $note ) . $conflict . "</div>\n";
1872 wfProfileOut( __METHOD__
);
1873 return $previewhead . $previewHTML;
1876 function getTemplates() {
1877 if ( $this->preview ||
$this->section
!= '' ) {
1878 $templates = array();
1879 if ( !isset($this->mParserOutput
) ) return $templates;
1880 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
1881 foreach( array_keys( $template ) as $dbk ) {
1882 $templates[] = Title
::makeTitle($ns, $dbk);
1887 return $this->mArticle
->getUsedTemplates();
1892 * Call the stock "user is blocked" page
1894 function blockedPage() {
1895 global $wgOut, $wgUser;
1896 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1898 # If the user made changes, preserve them when showing the markup
1899 # (This happens when a user is blocked during edit, for instance)
1900 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1902 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1904 $source = $this->textbox1
;
1907 # Spit out the source or the user's modified version
1908 if ( $source !== false ) {
1909 $rows = $wgUser->getIntOption( 'rows' );
1910 $cols = $wgUser->getIntOption( 'cols' );
1911 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1912 $wgOut->addHTML( '<hr />' );
1913 $wgOut->addWikiMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() );
1914 # Why we don't use Xml::element here?
1915 # Is it because if $source is '', it returns <textarea />?
1916 $wgOut->addHTML( Xml
::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml
::closeElement( 'textarea' ) );
1921 * Produce the stock "please login to edit pages" page
1923 function userNotLoggedInPage() {
1924 global $wgUser, $wgOut, $wgTitle;
1925 $skin = $wgUser->getSkin();
1927 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1928 $loginLink = $skin->link(
1930 wfMsgHtml( 'loginreqlink' ),
1932 array( 'returnto' => $wgTitle->getPrefixedText() ),
1933 array( 'known', 'noclasses' )
1936 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1937 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1938 $wgOut->setArticleRelated( false );
1940 $wgOut->addHTML( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1941 $wgOut->returnToMain( false, $wgTitle );
1945 * Creates a basic error page which informs the user that
1946 * they have attempted to edit a nonexistent section.
1948 function noSuchSectionPage() {
1949 global $wgOut, $wgTitle;
1951 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1952 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1953 $wgOut->setArticleRelated( false );
1955 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section
);
1956 $wgOut->returnToMain( false, $wgTitle );
1960 * Produce the stock "your edit contains spam" page
1962 * @param $match Text which triggered one or more filters
1964 function spamPage( $match = false ) {
1965 global $wgOut, $wgTitle;
1967 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1968 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1969 $wgOut->setArticleRelated( false );
1971 $wgOut->addHTML( '<div id="spamprotected">' );
1972 $wgOut->addWikiMsg( 'spamprotectiontext' );
1974 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1975 $wgOut->addHTML( '</div>' );
1977 $wgOut->returnToMain( false, $wgTitle );
1984 function mergeChangesInto( &$editText ){
1985 $fname = 'EditPage::mergeChangesInto';
1986 wfProfileIn( $fname );
1988 $db = wfGetDB( DB_MASTER
);
1990 // This is the revision the editor started from
1991 $baseRevision = $this->getBaseRevision();
1992 if ( is_null( $baseRevision ) ) {
1993 wfProfileOut( $fname );
1996 $baseText = $baseRevision->getText();
1998 // The current state, we want to merge updates into it
1999 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
2000 if ( is_null( $currentRevision ) ) {
2001 wfProfileOut( $fname );
2004 $currentText = $currentRevision->getText();
2007 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
2008 $editText = $result;
2009 wfProfileOut( $fname );
2012 wfProfileOut( $fname );
2018 * Check if the browser is on a blacklist of user-agents known to
2019 * mangle UTF-8 data on form submission. Returns true if Unicode
2020 * should make it through, false if it's known to be a problem.
2024 function checkUnicodeCompliantBrowser() {
2025 global $wgBrowserBlackList;
2026 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2027 // No User-Agent header sent? Trust it by default...
2030 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2031 foreach ( $wgBrowserBlackList as $browser ) {
2032 if ( preg_match($browser, $currentbrowser) ) {
2040 * @deprecated use $wgParser->stripSectionName()
2042 function pseudoParseSectionAnchor( $text ) {
2044 return $wgParser->stripSectionName( $text );
2048 * Format an anchor fragment as it would appear for a given section name
2049 * @param string $text
2053 function sectionAnchor( $text ) {
2055 return $wgParser->guessSectionNameFromWikiText( $text );
2059 * Shows a bulletin board style toolbar for common editing functions.
2060 * It can be disabled in the user preferences.
2061 * The necessary JavaScript code can be found in skins/common/edit.js.
2065 static function getEditToolbar() {
2066 global $wgStylePath, $wgContLang, $wgLang;
2069 * toolarray an array of arrays which each include the filename of
2070 * the button image (without path), the opening tag, the closing tag,
2071 * and optionally a sample text that is inserted between the two when no
2072 * selection is highlighted.
2073 * The tip text is shown when the user moves the mouse over the button.
2075 * Already here are accesskeys (key), which are not used yet until someone
2076 * can figure out a way to make them work in IE. However, we should make
2077 * sure these keys are not defined on the edit page.
2081 'image' => $wgLang->getImageFile('button-bold'),
2082 'id' => 'mw-editbutton-bold',
2084 'close' => '\'\'\'',
2085 'sample' => wfMsg('bold_sample'),
2086 'tip' => wfMsg('bold_tip'),
2090 'image' => $wgLang->getImageFile('button-italic'),
2091 'id' => 'mw-editbutton-italic',
2094 'sample' => wfMsg('italic_sample'),
2095 'tip' => wfMsg('italic_tip'),
2099 'image' => $wgLang->getImageFile('button-link'),
2100 'id' => 'mw-editbutton-link',
2103 'sample' => wfMsg('link_sample'),
2104 'tip' => wfMsg('link_tip'),
2108 'image' => $wgLang->getImageFile('button-extlink'),
2109 'id' => 'mw-editbutton-extlink',
2112 'sample' => wfMsg('extlink_sample'),
2113 'tip' => wfMsg('extlink_tip'),
2117 'image' => $wgLang->getImageFile('button-headline'),
2118 'id' => 'mw-editbutton-headline',
2121 'sample' => wfMsg('headline_sample'),
2122 'tip' => wfMsg('headline_tip'),
2126 'image' => $wgLang->getImageFile('button-image'),
2127 'id' => 'mw-editbutton-image',
2128 'open' => '[['.$wgContLang->getNsText(NS_FILE
).':',
2130 'sample' => wfMsg('image_sample'),
2131 'tip' => wfMsg('image_tip'),
2135 'image' => $wgLang->getImageFile('button-media'),
2136 'id' => 'mw-editbutton-media',
2137 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
2139 'sample' => wfMsg('media_sample'),
2140 'tip' => wfMsg('media_tip'),
2144 'image' => $wgLang->getImageFile('button-math'),
2145 'id' => 'mw-editbutton-math',
2147 'close' => "</math>",
2148 'sample' => wfMsg('math_sample'),
2149 'tip' => wfMsg('math_tip'),
2153 'image' => $wgLang->getImageFile('button-nowiki'),
2154 'id' => 'mw-editbutton-nowiki',
2155 'open' => "<nowiki>",
2156 'close' => "</nowiki>",
2157 'sample' => wfMsg('nowiki_sample'),
2158 'tip' => wfMsg('nowiki_tip'),
2162 'image' => $wgLang->getImageFile('button-sig'),
2163 'id' => 'mw-editbutton-signature',
2167 'tip' => wfMsg('sig_tip'),
2171 'image' => $wgLang->getImageFile('button-hr'),
2172 'id' => 'mw-editbutton-hr',
2173 'open' => "\n----\n",
2176 'tip' => wfMsg('hr_tip'),
2180 $toolbar = "<div id='toolbar'>\n";
2183 foreach ( $toolarray as $tool ) {
2185 $image = $wgStylePath.'/common/images/'.$tool['image'],
2186 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2187 // Older browsers show a "speedtip" type message only for ALT.
2188 // Ideally these should be different, realistically they
2189 // probably don't need to be.
2190 $tip = $tool['tip'],
2191 $open = $tool['open'],
2192 $close = $tool['close'],
2193 $sample = $tool['sample'],
2194 $cssId = $tool['id'],
2197 $paramList = implode( ',',
2198 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2199 $script .= "addButton($paramList);\n";
2201 $toolbar .= Html
::inlineScript( "\n$script\n" );
2203 $toolbar .= "\n</div>";
2205 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2211 * Returns an array of html code of the following checkboxes:
2214 * @param $tabindex Current tabindex
2215 * @param $skin Skin object
2216 * @param $checked Array of checkbox => bool, where bool indicates the checked
2217 * status of the checkbox
2221 public function getCheckboxes( &$tabindex, $skin, $checked ) {
2224 $checkboxes = array();
2226 $checkboxes['minor'] = '';
2227 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
2228 if ( $wgUser->isAllowed('minoredit') ) {
2230 'tabindex' => ++
$tabindex,
2231 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2232 'id' => 'wpMinoredit',
2234 $checkboxes['minor'] =
2235 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2236 " <label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
2239 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2240 $checkboxes['watch'] = '';
2241 if ( $wgUser->isLoggedIn() ) {
2243 'tabindex' => ++
$tabindex,
2244 'accesskey' => wfMsg( 'accesskey-watch' ),
2245 'id' => 'wpWatchthis',
2247 $checkboxes['watch'] =
2248 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2249 " <label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
2251 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2256 * Returns an array of html code of the following buttons:
2257 * save, diff, preview and live
2259 * @param $tabindex Current tabindex
2263 public function getEditButtons(&$tabindex) {
2270 'tabindex' => ++
$tabindex,
2271 'value' => wfMsg('savearticle'),
2272 'accesskey' => wfMsg('accesskey-save'),
2273 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2275 $buttons['save'] = Xml
::element('input', $temp, '');
2277 ++
$tabindex; // use the same for preview and live preview
2278 if ( $this->useLivePreview() ) {
2279 $this->doLivePreviewScript(); // Add to output
2282 'id' => 'wpPreview',
2283 'name' => 'wpPreview',
2285 'tabindex' => $tabindex,
2286 'value' => wfMsg('showpreview'),
2288 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2290 $buttons['preview'] = Xml
::element('input', $temp, '');
2293 'id' => 'wpLivePreview',
2294 'name' => 'wpLivePreview',
2296 'tabindex' => $tabindex,
2297 'value' => wfMsg('showlivepreview'),
2298 'accesskey' => wfMsg('accesskey-preview'),
2300 'style' => 'display: none;',
2303 $buttons['live'] = Xml
::element('input', $temp, '');
2306 'id' => 'wpPreview',
2307 'name' => 'wpPreview',
2309 'tabindex' => $tabindex,
2310 'value' => wfMsg('showpreview'),
2311 'accesskey' => wfMsg('accesskey-preview'),
2312 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2314 $buttons['preview'] = Xml
::element('input', $temp, '');
2315 $buttons['live'] = '';
2322 'tabindex' => ++
$tabindex,
2323 'value' => wfMsg('showdiff'),
2324 'accesskey' => wfMsg('accesskey-diff'),
2325 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2327 $buttons['diff'] = Xml
::element('input', $temp, '');
2329 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2334 * Whether to use live preview for this page
2335 * This disables live preview when editing css/js user subpages so that the
2336 * user can preview them (bug 3421)
2340 public function useLivePreview() {
2341 global $wgLivePreview, $wgUser;
2343 return $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) &&
2344 !( ( $this->mTitle
->isCssSubpage() && $this->mTitle
->userCanEditCssSubpage() ) ||
2345 ( $this->mTitle
->isJsSubpage() && $this->mTitle
->userCanEditCssSubpage() ) );
2349 * Output preview text only. This can be sucked into the edit page
2350 * via JavaScript, and saves the server time rendering the skin as
2351 * well as theoretically being more robust on the client (doesn't
2352 * disturb the edit box's undo history, won't eat your text on
2355 * @todo This doesn't include category or interlanguage links.
2356 * Would need to enhance it a bit, <s>maybe wrap them in XML
2357 * or something...</s> that might also require more skin
2358 * initialization, so check whether that's a problem.
2360 function livePreview() {
2363 header( 'Content-type: text/xml; charset=utf-8' );
2364 header( 'Cache-control: no-cache' );
2366 $previewText = $this->getPreviewText();
2367 #$categories = $skin->getCategoryLinks();
2370 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2371 Xml
::tags( 'livepreview', null,
2372 Xml
::element( 'preview', null, $previewText )
2373 #. Xml::element( 'category', null, $categories )
2380 * Get a diff between the current contents of the edit box and the
2381 * version of the page we're editing from.
2383 * If this is a section edit, we'll replace the section as for final
2384 * save and then make a comparison.
2386 function showDiff() {
2387 $oldtext = $this->mArticle
->fetchContent();
2388 $newtext = $this->mArticle
->replaceSection(
2389 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2390 $newtext = $this->mArticle
->preSaveTransform( $newtext );
2391 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2392 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2393 if ( $oldtext !== false ||
$newtext != '' ) {
2394 $de = new DifferenceEngine( $this->mTitle
);
2395 $de->setText( $oldtext, $newtext );
2396 $difftext = $de->getDiff( $oldtitle, $newtitle );
2397 $de->showDiffStyle();
2403 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2407 * Filter an input field through a Unicode de-armoring process if it
2408 * came from an old browser with known broken Unicode editing issues.
2410 * @param WebRequest $request
2411 * @param string $field
2415 function safeUnicodeInput( $request, $field ) {
2416 $text = rtrim( $request->getText( $field ) );
2417 return $request->getBool( 'safemode' )
2418 ?
$this->unmakesafe( $text )
2423 * Filter an output field through a Unicode armoring process if it is
2424 * going to an old browser with known broken Unicode editing issues.
2426 * @param string $text
2430 function safeUnicodeOutput( $text ) {
2432 $codedText = $wgContLang->recodeForEdit( $text );
2433 return $this->checkUnicodeCompliantBrowser()
2435 : $this->makesafe( $codedText );
2439 * A number of web browsers are known to corrupt non-ASCII characters
2440 * in a UTF-8 text editing environment. To protect against this,
2441 * detected browsers will be served an armored version of the text,
2442 * with non-ASCII chars converted to numeric HTML character references.
2444 * Preexisting such character references will have a 0 added to them
2445 * to ensure that round-trips do not alter the original data.
2447 * @param string $invalue
2451 function makesafe( $invalue ) {
2452 // Armor existing references for reversability.
2453 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2458 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2459 $bytevalue = ord( $invalue{$i} );
2460 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2461 $result .= chr( $bytevalue );
2463 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2464 $working = $working << 6;
2465 $working +
= ($bytevalue & 0x3F);
2467 if ( $bytesleft <= 0 ) {
2468 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2470 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2471 $working = $bytevalue & 0x1F;
2473 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2474 $working = $bytevalue & 0x0F;
2476 } else { //1111 0xxx
2477 $working = $bytevalue & 0x07;
2485 * Reverse the previously applied transliteration of non-ASCII characters
2486 * back to UTF-8. Used to protect data from corruption by broken web browsers
2487 * as listed in $wgBrowserBlackList.
2489 * @param string $invalue
2493 function unmakesafe( $invalue ) {
2495 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2496 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2500 $hexstring .= $invalue{$i};
2502 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2504 // Do some sanity checks. These aren't needed for reversability,
2505 // but should help keep the breakage down if the editor
2506 // breaks one of the entities whilst editing.
2507 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2508 $codepoint = hexdec($hexstring);
2509 $result .= codepointToUtf8( $codepoint );
2511 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2514 $result .= substr( $invalue, $i, 1 );
2517 // reverse the transform that we made for reversability reasons.
2518 return strtr( $result, array( "�" => "&#x" ) );
2521 function noCreatePermission() {
2523 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2524 $wgOut->addWikiMsg( 'nocreatetext' );
2528 * Attempt submission
2529 * @return bool false if output is done, true if the rest of the form should be displayed
2531 function attemptSave() {
2532 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2534 $resultDetails = false;
2535 # Allow bots to exempt some edits from bot flagging
2536 $bot = $wgUser->isAllowed('bot') && $wgRequest->getBool('bot',true);
2537 $value = $this->internalAttemptSave( $resultDetails, $bot );
2539 if ( $value == self
::AS_SUCCESS_UPDATE ||
$value == self
::AS_SUCCESS_NEW_ARTICLE
) {
2540 $this->didSave
= true;
2544 case self
::AS_HOOK_ERROR_EXPECTED
:
2545 case self
::AS_CONTENT_TOO_BIG
:
2546 case self
::AS_ARTICLE_WAS_DELETED
:
2547 case self
::AS_CONFLICT_DETECTED
:
2548 case self
::AS_SUMMARY_NEEDED
:
2549 case self
::AS_TEXTBOX_EMPTY
:
2550 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
2554 case self
::AS_HOOK_ERROR
:
2555 case self
::AS_FILTERING
:
2556 case self
::AS_SUCCESS_NEW_ARTICLE
:
2557 case self
::AS_SUCCESS_UPDATE
:
2560 case self
::AS_SPAM_ERROR
:
2561 $this->spamPage ( $resultDetails['spam'] );
2564 case self
::AS_BLOCKED_PAGE_FOR_USER
:
2565 $this->blockedPage();
2568 case self
::AS_IMAGE_REDIRECT_ANON
:
2569 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2572 case self
::AS_READ_ONLY_PAGE_ANON
:
2573 $this->userNotLoggedInPage();
2576 case self
::AS_READ_ONLY_PAGE_LOGGED
:
2577 case self
::AS_READ_ONLY_PAGE
:
2578 $wgOut->readOnlyPage();
2581 case self
::AS_RATE_LIMITED
:
2582 $wgOut->rateLimited();
2585 case self
::AS_NO_CREATE_PERMISSION
;
2586 $this->noCreatePermission();
2589 case self
::AS_BLANK_ARTICLE
:
2590 $wgOut->redirect( $wgTitle->getFullURL() );
2593 case self
::AS_IMAGE_REDIRECT_LOGGED
:
2594 $wgOut->permissionRequired( 'upload' );
2599 function getBaseRevision() {
2600 if ( $this->mBaseRevision
== false ) {
2601 $db = wfGetDB( DB_MASTER
);
2602 $baseRevision = Revision
::loadFromTimestamp(
2603 $db, $this->mTitle
, $this->edittime
);
2604 return $this->mBaseRevision
= $baseRevision;
2606 return $this->mBaseRevision
;