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 $deletedSinceEdit = false;
55 var $mTokenOk = false;
56 var $mTokenOkExceptSuffix = false;
57 var $mTriedSave = false;
59 var $kblength = false;
60 var $missingComment = false;
61 var $missingSummary = false;
62 var $allowBlankSummary = false;
65 #var $mPreviewTemplates;
67 var $mBaseRevision = false;
70 var $save = false, $preview = false, $diff = false;
71 var $minoredit = false, $watchthis = false, $recreate = false;
72 var $textbox1 = '', $textbox2 = '', $summary = '';
73 var $edittime = '', $section = '', $starttime = '';
74 var $oldid = 0, $editintro = '', $scrolltop = null;
76 # Placeholders for text injection by hooks (must be HTML)
77 # extensions should take care to _append_ to the present value
78 public $editFormPageTop; // Before even the preview
79 public $editFormTextTop;
80 public $editFormTextBeforeContent;
81 public $editFormTextAfterWarn;
82 public $editFormTextAfterTools;
83 public $editFormTextBottom;
85 /* $didSave should be set to true whenever an article was succesfully altered. */
86 public $didSave = false;
89 public $suppressIntro = false;
95 function EditPage( $article ) {
96 $this->mArticle
=& $article;
97 $this->mTitle
= $article->getTitle();
98 $this->action
= 'submit';
100 # Placeholders for text injection by hooks (empty per default)
101 $this->editFormPageTop
=
102 $this->editFormTextTop
=
103 $this->editFormTextBeforeContent
=
104 $this->editFormTextAfterWarn
=
105 $this->editFormTextAfterTools
=
106 $this->editFormTextBottom
=
107 $this->mPreloadText
= "";
110 function getArticle() {
111 return $this->mArticle
;
116 * Fetch initial editing page content.
119 function getContent( $def_text = '' ) {
120 global $wgOut, $wgRequest, $wgParser, $wgContLang, $wgMessageCache;
122 wfProfileIn( __METHOD__
);
123 # Get variables from query string :P
124 $section = $wgRequest->getVal( 'section' );
125 $preload = $wgRequest->getVal( 'preload' );
126 $undoafter = $wgRequest->getVal( 'undoafter' );
127 $undo = $wgRequest->getVal( 'undo' );
130 // For message page not locally set, use the i18n message.
131 // For other non-existent articles, use preload text if any.
132 if ( !$this->mTitle
->exists() ) {
133 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
134 # If this is a system message, get the default text.
135 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
136 $wgMessageCache->loadAllMessages( $lang );
137 $text = wfMsgGetKey( $message, false, $lang, false );
138 if( wfEmptyMsg( $message, $text ) )
141 # If requested, preload some text.
142 $text = $this->getPreloadedText( $preload );
144 // For existing pages, get text based on "undo" or section parameters.
146 $text = $this->mArticle
->getContent();
147 if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
148 # If they got undoafter and undo round the wrong way, switch them
149 list( $undo, $undoafter ) = array( $undoafter, $undo );
151 if ( $undo > 0 && $undo > $undoafter ) {
152 # Undoing a specific edit overrides section editing; section-editing
153 # doesn't work with undoing.
155 $undorev = Revision
::newFromId($undo);
156 $oldrev = Revision
::newFromId($undoafter);
158 $undorev = Revision
::newFromId($undo);
159 $oldrev = $undorev ?
$undorev->getPrevious() : null;
162 # Sanity check, make sure it's the right page,
163 # the revisions exist and they were not deleted.
164 # Otherwise, $text will be left as-is.
165 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
166 $undorev->getPage() == $oldrev->getPage() &&
167 $undorev->getPage() == $this->mArticle
->getID() &&
168 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
169 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
171 $undotext = $this->mArticle
->getUndoText( $undorev, $oldrev );
172 if ( $undotext === false ) {
173 # Warn the user that something went wrong
174 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-failure">' . wfMsgNoTrans( 'undo-failure' ) . '</div>' );
177 # Inform the user of our success and set an automatic edit summary
178 $this->editFormPageTop
.= $wgOut->parse( '<div class="mw-undo-success">' . wfMsgNoTrans( 'undo-success' ) . '</div>' );
179 $firstrev = $oldrev->getNext();
180 # If we just undid one rev, use an autosummary
181 if ( $firstrev->mId
== $undo ) {
182 $this->summary
= wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
183 $this->undidRev
= $undo;
185 $this->formtype
= 'diff';
188 // Failed basic sanity checks.
189 // Older revisions may have been removed since the link
190 // was created, or we may simply have got bogus input.
191 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-norev">' . wfMsgNoTrans( 'undo-norev' ) . '</div>' );
193 } else if ( $section != '' ) {
194 if ( $section == 'new' ) {
195 $text = $this->getPreloadedText( $preload );
197 $text = $wgParser->getSection( $text, $section, $def_text );
202 wfProfileOut( __METHOD__
);
206 /** Use this method before edit() to preload some text into the edit box */
207 public function setPreloadedText( $text ) {
208 $this->mPreloadText
= $text;
212 * Get the contents of a page from its title and remove includeonly tags
214 * @param $preload String: the title of the page.
215 * @return string The contents of the page.
217 protected function getPreloadedText( $preload ) {
218 if ( !empty($this->mPreloadText
) ) {
219 return $this->mPreloadText
;
220 } elseif ( $preload === '' ) {
223 $preloadTitle = Title
::newFromText( $preload );
224 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
225 $rev = Revision
::newFromTitle($preloadTitle);
226 if ( is_object( $rev ) ) {
227 $text = $rev->getText();
228 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
229 // its own mini-parser! -ævar
230 $text = preg_replace( '~</?includeonly>~', '', $text );
239 * This is the function that extracts metadata from the article body on the first view.
240 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
241 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
243 function extractMetaDataFromArticle () {
244 global $wgUseMetadataEdit, $wgMetadataWhitelist, $wgContLang;
245 $this->mMetaData
= '';
246 if ( !$wgUseMetadataEdit ) return;
247 if ( $wgMetadataWhitelist == '' ) return;
249 $t = $this->getContent();
251 # MISSING : <nowiki> filtering
253 # Categories and language links
254 $t = explode ( "\n" , $t );
255 $catlow = strtolower ( $wgContLang->getNsText( NS_CATEGORY
) );
256 $cat = $ll = array();
257 foreach ( $t AS $key => $x ) {
258 $y = trim ( strtolower ( $x ) );
259 while ( substr ( $y , 0 , 2 ) == '[[' ) {
260 $y = explode ( ']]' , trim ( $x ) );
261 $first = array_shift ( $y );
262 $first = explode ( ':' , $first );
263 $ns = array_shift ( $first );
264 $ns = trim ( str_replace ( '[' , '' , $ns ) );
265 if ( $wgContLang->getLanguageName( $ns ) ||
strtolower ( $ns ) == $catlow ) {
266 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]';
267 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add;
269 $x = implode ( ']]' , $y );
271 $y = trim ( strtolower ( $x ) );
273 $x = implode ( ']]' , $y );
274 $y = trim ( strtolower ( $x ) );
278 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n";
279 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n";
280 $t = implode ( "\n" , $t );
283 $sat = array () ; # stand-alone-templates; must be lowercase
284 $wl_title = Title
::newFromText ( $wgMetadataWhitelist );
285 $wl_article = new Article ( $wl_title );
286 $wl = explode ( "\n" , $wl_article->getContent() );
287 foreach ( $wl AS $x ) {
290 while ( substr ( $x , 0 , 1 ) == '*' ) {
292 $x = trim ( substr ( $x , 1 ) );
295 $sat[] = strtolower ( $x );
300 # Templates, but only some
301 $t = explode ( '{{' , $t );
303 foreach ( $t AS $key => $x ) {
304 $y = explode ( '}}' , $x , 2 );
305 if ( count ( $y ) == 2 ) {
307 $z = explode ( '|' , $z );
308 $tn = array_shift ( $z );
309 if ( in_array ( strtolower ( $tn ) , $sat ) ) {
310 $tl[] = '{{' . $y[0] . '}}';
312 $y = explode ( '}}' , $y[1] , 2 );
314 else $t[$key] = '{{' . $x;
316 else if ( $key != 0 ) $t[$key] = '{{' . $x;
319 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl );
320 $t = implode ( '' , $t );
322 $t = str_replace ( "\n\n\n" , "\n" , $t );
323 $this->mArticle
->mContent
= $t;
324 $this->mMetaData
= $s;
328 * Check if a page was deleted while the user was editing it, before submit.
329 * Note that we rely on the logging table, which hasn't been always there,
330 * but that doesn't matter, because this only applies to brand new
333 protected function wasDeletedSinceLastEdit() {
334 if ( $this->deletedSinceEdit
)
336 if ( $this->mTitle
->isDeletedQuick() ) {
337 $this->lastDelete
= $this->getLastDelete();
338 if ( $this->lastDelete
) {
339 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
340 if ( $deleteTime > $this->starttime
) {
341 $this->deletedSinceEdit
= true;
345 return $this->deletedSinceEdit
;
353 * This is the function that gets called for "action=edit". It
354 * sets up various member variables, then passes execution to
355 * another function, usually showEditForm()
357 * The edit form is self-submitting, so that when things like
358 * preview and edit conflicts occur, we get the same form back
359 * with the extra stuff added. Only when the final submission
360 * is made and all is well do we actually save and redirect to
361 * the newly-edited page.
364 global $wgOut, $wgRequest, $wgEnableJS2system;
365 // Allow extensions to modify/prevent this form or submission
366 if ( !wfRunHooks( 'AlternateEdit', array( &$this ) ) ) {
370 wfProfileIn( __METHOD__
);
371 wfDebug( __METHOD__
.": enter\n" );
373 // This is not an article
374 $wgOut->setArticleFlag( false );
376 $this->importFormData( $wgRequest );
377 $this->firsttime
= false;
380 $this->livePreview();
381 wfProfileOut( __METHOD__
);
385 if ( wfReadOnly() && $this->save
) {
388 $this->preview
= true;
391 $wgOut->addScriptFile( 'edit.js' );
393 if($wgEnableJS2system)
394 $wgOut->addScriptClass( 'editPage' );
396 $permErrors = $this->getEditPermissionErrors();
398 wfDebug( __METHOD__
.": User can't edit\n" );
399 $this->readOnlyPage( $this->getContent(), true, $permErrors, 'edit' );
400 wfProfileOut( __METHOD__
);
404 $this->formtype
= 'save';
405 } else if ( $this->preview
) {
406 $this->formtype
= 'preview';
407 } else if ( $this->diff
) {
408 $this->formtype
= 'diff';
409 } else { # First time through
410 $this->firsttime
= true;
411 if ( $this->previewOnOpen() ) {
412 $this->formtype
= 'preview';
414 $this->extractMetaDataFromArticle () ;
415 $this->formtype
= 'initial';
420 // If they used redlink=1 and the page exists, redirect to the main article
421 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
422 $wgOut->redirect( $this->mTitle
->getFullURL() );
425 wfProfileIn( __METHOD__
."-business-end" );
427 $this->isConflict
= false;
428 // css / js subpages of user pages get a special treatment
429 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
430 $this->isValidCssJsSubpage
= $this->mTitle
->isValidCssJsSubpage();
432 # Show applicable editing introductions
433 if ( $this->formtype
== 'initial' ||
$this->firsttime
)
436 if ( $this->mTitle
->isTalkPage() ) {
437 $wgOut->addWikiMsg( 'talkpagetext' );
440 # Optional notices on a per-namespace and per-page basis
441 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
442 if ( !wfEmptyMsg( $editnotice_ns, wfMsgForContent( $editnotice_ns ) ) ) {
443 $wgOut->addWikiText( wfMsgForContent( $editnotice_ns ) );
445 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
446 $parts = explode( '/', $this->mTitle
->getDBkey() );
447 $editnotice_base = $editnotice_ns;
448 while ( count( $parts ) > 0 ) {
449 $editnotice_base .= '-'.array_shift( $parts );
450 if ( !wfEmptyMsg( $editnotice_base, wfMsgForContent( $editnotice_base ) ) ) {
451 $wgOut->addWikiText( wfMsgForContent( $editnotice_base ) );
456 # Attempt submission here. This will check for edit conflicts,
457 # and redundantly check for locked database, blocked IPs, etc.
458 # that edit() already checked just in case someone tries to sneak
459 # in the back door with a hand-edited submission URL.
461 if ( 'save' == $this->formtype
) {
462 if ( !$this->attemptSave() ) {
463 wfProfileOut( __METHOD__
."-business-end" );
464 wfProfileOut( __METHOD__
);
469 # First time through: get contents, set time for conflict
471 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
472 if ( $this->initialiseForm() === false) {
473 $this->noSuchSectionPage();
474 wfProfileOut( __METHOD__
."-business-end" );
475 wfProfileOut( __METHOD__
);
478 if ( !$this->mTitle
->getArticleId() )
479 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
482 $this->showEditForm();
483 wfProfileOut( __METHOD__
."-business-end" );
484 wfProfileOut( __METHOD__
);
487 protected function getEditPermissionErrors() {
489 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
490 # Can this title be created?
491 if ( !$this->mTitle
->exists() ) {
492 $permErrors = array_merge( $permErrors,
493 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
495 # Ignore some permissions errors when a user is just previewing/viewing diffs
497 foreach( $permErrors as $error ) {
498 if ( ($this->preview ||
$this->diff
) &&
499 ($error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext') )
504 $permErrors = wfArrayDiff2( $permErrors, $remove );
509 * Show a read-only error
510 * Parameters are the same as OutputPage:readOnlyPage()
511 * Redirect to the article page if redlink=1
513 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
514 global $wgRequest, $wgOut;
515 if ( $wgRequest->getBool( 'redlink' ) ) {
516 // The edit page was reached via a red link.
517 // Redirect to the article page and let them click the edit tab if
518 // they really want a permission error.
519 $wgOut->redirect( $this->mTitle
->getFullUrl() );
521 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
526 * Should we show a preview when the edit form is first shown?
530 protected function previewOnOpen() {
531 global $wgRequest, $wgUser;
532 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
533 // Explicit override from request
535 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
536 // Explicit override from request
538 } elseif ( $this->section
== 'new' ) {
539 // Nothing *to* preview for new sections
541 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
542 // Standard preference behaviour
544 } elseif ( !$this->mTitle
->exists() && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
545 // Categories are special
556 function importFormData( &$request ) {
557 global $wgLang, $wgUser;
558 $fname = 'EditPage::importFormData';
559 wfProfileIn( $fname );
561 # Section edit can come from either the form or a link
562 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
564 if ( $request->wasPosted() ) {
565 # These fields need to be checked for encoding.
566 # Also remove trailing whitespace, but don't remove _initial_
567 # whitespace from the text boxes. This may be significant formatting.
568 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
569 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
570 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
571 # Truncate for whole multibyte characters. +5 bytes for ellipsis
572 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250, '' );
574 # Remove extra headings from summaries and new sections.
575 $this->summary
= preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
577 $this->edittime
= $request->getVal( 'wpEdittime' );
578 $this->starttime
= $request->getVal( 'wpStarttime' );
580 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
582 if ( is_null( $this->edittime
) ) {
583 # If the form is incomplete, force to preview.
584 wfDebug( "$fname: Form data appears to be incomplete\n" );
585 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
586 $this->preview
= true;
588 /* Fallback for live preview */
589 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
590 $this->diff
= $request->getCheck( 'wpDiff' );
592 // Remember whether a save was requested, so we can indicate
593 // if we forced preview due to session failure.
594 $this->mTriedSave
= !$this->preview
;
596 if ( $this->tokenOk( $request ) ) {
597 # Some browsers will not report any submit button
598 # if the user hits enter in the comment box.
599 # The unmarked state will be assumed to be a save,
600 # if the form seems otherwise complete.
601 wfDebug( "$fname: Passed token check.\n" );
602 } else if ( $this->diff
) {
603 # Failed token check, but only requested "Show Changes".
604 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
606 # Page might be a hack attempt posted from
607 # an external site. Preview instead of saving.
608 wfDebug( "$fname: Failed token check; forcing preview\n" );
609 $this->preview
= true;
612 $this->save
= !$this->preview
&& !$this->diff
;
613 if ( !preg_match( '/^\d{14}$/', $this->edittime
)) {
614 $this->edittime
= null;
617 if ( !preg_match( '/^\d{14}$/', $this->starttime
)) {
618 $this->starttime
= null;
621 $this->recreate
= $request->getCheck( 'wpRecreate' );
623 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
624 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
626 # Don't force edit summaries when a user is editing their own user or talk page
627 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
628 $this->mTitle
->getText() == $wgUser->getName() )
630 $this->allowBlankSummary
= true;
632 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
635 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
637 # Not a posted form? Start with nothing.
638 wfDebug( "$fname: Not a posted form.\n" );
639 $this->textbox1
= '';
640 $this->textbox2
= '';
641 $this->mMetaData
= '';
643 $this->edittime
= '';
644 $this->starttime
= wfTimestampNow();
646 $this->preview
= false;
649 $this->minoredit
= false;
650 $this->watchthis
= false;
651 $this->recreate
= false;
653 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
654 $this->summary
= $request->getVal( 'preloadtitle' );
656 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
657 $this->summary
= $request->getText( 'summary' );
660 if ( $request->getVal( 'minor' ) ) {
661 $this->minoredit
= true;
665 // FIXME: unused variable?
666 $this->oldid
= $request->getInt( 'oldid' );
668 $this->live
= $request->getCheck( 'live' );
669 $this->editintro
= $request->getText( 'editintro' );
671 wfProfileOut( $fname );
673 // Allow extensions to modify form data
674 wfRunHooks( 'EditPage::importFormData', array( &$this, $request ) );
678 * Make sure the form isn't faking a user's credentials.
680 * @param $request WebRequest
684 function tokenOk( &$request ) {
686 $token = $request->getVal( 'wpEditToken' );
687 $this->mTokenOk
= $wgUser->matchEditToken( $token );
688 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
689 return $this->mTokenOk
;
693 * Show all applicable editing introductions
695 protected function showIntro() {
696 global $wgOut, $wgUser;
697 if ( $this->suppressIntro
) {
701 $namespace = $this->mTitle
->getNamespace();
703 if ( $namespace == NS_MEDIAWIKI
) {
704 # Show a warning if editing an interface message
705 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1</div>", 'editinginterface' );
708 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
709 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
710 $parts = explode( '/', $this->mTitle
->getText(), 2 );
711 $username = $parts[0];
712 $id = User
::idFromName( $username );
713 $ip = User
::isIP( $username );
714 if ( $id == 0 && !$ip ) {
715 $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
716 array( 'userpage-userdoesnotexist', $username ) );
719 # Try to add a custom edit intro, or use the standard one if this is not possible.
720 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
721 if ( $wgUser->isLoggedIn() ) {
722 $wgOut->wrapWikiMsg( '<div class="mw-newarticletext">$1</div>', 'newarticletext' );
724 $wgOut->wrapWikiMsg( '<div class="mw-newarticletextanon">$1</div>', 'newarticletextanon' );
727 # Give a notice if the user is editing a deleted/moved page...
728 if ( !$this->mTitle
->exists() ) {
729 $this->showLogs( $wgOut );
734 * Attempt to show a custom editing introduction, if supplied
738 protected function showCustomIntro() {
739 if ( $this->editintro
) {
740 $title = Title
::newFromText( $this->editintro
);
741 if ( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
743 $revision = Revision
::newFromTitle( $title );
744 $wgOut->addWikiTextTitleTidy( $revision->getText(), $this->mTitle
);
755 * Attempt submission (no UI)
756 * @return one of the constants describing the result
758 function internalAttemptSave( &$result, $bot = false ) {
759 global $wgFilterCallback, $wgUser, $wgOut, $wgParser;
760 global $wgMaxArticleSize;
762 $fname = 'EditPage::attemptSave';
763 wfProfileIn( $fname );
764 wfProfileIn( "$fname-checks" );
766 if ( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
768 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
769 return self
::AS_HOOK_ERROR
;
772 # Check image redirect
773 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
774 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
775 !$wgUser->isAllowed( 'upload' ) ) {
776 if ( $wgUser->isAnon() ) {
777 return self
::AS_IMAGE_REDIRECT_ANON
;
779 return self
::AS_IMAGE_REDIRECT_LOGGED
;
783 # Reintegrate metadata
784 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
785 $this->mMetaData
= '' ;
788 $match = self
::matchSummarySpamRegex( $this->summary
);
789 if ( $match === false ) {
790 $match = self
::matchSpamRegex( $this->textbox1
);
792 if ( $match !== false ) {
793 $result['spam'] = $match;
795 $pdbk = $this->mTitle
->getPrefixedDBkey();
796 $match = str_replace( "\n", '', $match );
797 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
798 wfProfileOut( "$fname-checks" );
799 wfProfileOut( $fname );
800 return self
::AS_SPAM_ERROR
;
802 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
803 # Error messages or other handling should be performed by the filter function
804 wfProfileOut( "$fname-checks" );
805 wfProfileOut( $fname );
806 return self
::AS_FILTERING
;
808 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
809 # Error messages etc. could be handled within the hook...
810 wfProfileOut( "$fname-checks" );
811 wfProfileOut( $fname );
812 return self
::AS_HOOK_ERROR
;
813 } elseif ( $this->hookError
!= '' ) {
814 # ...or the hook could be expecting us to produce an error
815 wfProfileOut( "$fname-checks" );
816 wfProfileOut( $fname );
817 return self
::AS_HOOK_ERROR_EXPECTED
;
819 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
820 # Check block state against master, thus 'false'.
821 wfProfileOut( "$fname-checks" );
822 wfProfileOut( $fname );
823 return self
::AS_BLOCKED_PAGE_FOR_USER
;
825 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
826 if ( $this->kblength
> $wgMaxArticleSize ) {
827 // Error will be displayed by showEditForm()
828 $this->tooBig
= true;
829 wfProfileOut( "$fname-checks" );
830 wfProfileOut( $fname );
831 return self
::AS_CONTENT_TOO_BIG
;
834 if ( !$wgUser->isAllowed('edit') ) {
835 if ( $wgUser->isAnon() ) {
836 wfProfileOut( "$fname-checks" );
837 wfProfileOut( $fname );
838 return self
::AS_READ_ONLY_PAGE_ANON
;
841 wfProfileOut( "$fname-checks" );
842 wfProfileOut( $fname );
843 return self
::AS_READ_ONLY_PAGE_LOGGED
;
847 if ( wfReadOnly() ) {
848 wfProfileOut( "$fname-checks" );
849 wfProfileOut( $fname );
850 return self
::AS_READ_ONLY_PAGE
;
852 if ( $wgUser->pingLimiter() ) {
853 wfProfileOut( "$fname-checks" );
854 wfProfileOut( $fname );
855 return self
::AS_RATE_LIMITED
;
858 # If the article has been deleted while editing, don't save it without
860 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
861 wfProfileOut( "$fname-checks" );
862 wfProfileOut( $fname );
863 return self
::AS_ARTICLE_WAS_DELETED
;
866 wfProfileOut( "$fname-checks" );
868 # If article is new, insert it.
869 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
871 // Late check for create permission, just in case *PARANOIA*
872 if ( !$this->mTitle
->userCan( 'create' ) ) {
873 wfDebug( "$fname: no create permission\n" );
874 wfProfileOut( $fname );
875 return self
::AS_NO_CREATE_PERMISSION
;
878 # Don't save a new article if it's blank.
879 if ( '' == $this->textbox1
) {
880 wfProfileOut( $fname );
881 return self
::AS_BLANK_ARTICLE
;
884 // Run post-section-merge edit filter
885 if ( !wfRunHooks( 'EditFilterMerged', array( &$this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
886 # Error messages etc. could be handled within the hook...
887 wfProfileOut( $fname );
888 return self
::AS_HOOK_ERROR
;
891 # Handle the user preference to force summaries here. Check if it's not a redirect.
892 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
893 if ( md5( $this->summary
) == $this->autoSumm
) {
894 $this->missingSummary
= true;
895 wfProfileOut( $fname );
896 return self
::AS_SUMMARY_NEEDED
;
900 $isComment = ( $this->section
== 'new' );
902 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
903 $this->minoredit
, $this->watchthis
, false, $isComment, $bot );
905 wfProfileOut( $fname );
906 return self
::AS_SUCCESS_NEW_ARTICLE
;
909 # Article exists. Check for edit conflict.
911 $this->mArticle
->clear(); # Force reload of dates, etc.
912 $this->mArticle
->forUpdate( true ); # Lock the article
914 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
916 if ( $this->mArticle
->getTimestamp() != $this->edittime
) {
917 $this->isConflict
= true;
918 if ( $this->section
== 'new' ) {
919 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
920 $this->mArticle
->getComment() == $this->summary
) {
921 // Probably a duplicate submission of a new comment.
922 // This can happen when squid resends a request after
923 // a timeout but the first one actually went through.
924 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
926 // New comment; suppress conflict.
927 $this->isConflict
= false;
928 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
932 $userid = $wgUser->getId();
934 # Suppress edit conflict with self, except for section edits where merging is required.
935 if ( $this->isConflict
&& $this->section
== '' && $this->userWasLastToEdit($userid,$this->edittime
) ) {
936 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
937 $this->isConflict
= false;
940 if ( $this->isConflict
) {
941 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
942 $this->mArticle
->getTimestamp() . "')\n" );
943 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
945 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
946 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
948 if ( is_null( $text ) ) {
949 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
950 $this->isConflict
= true;
951 $text = $this->textbox1
; // do not try to merge here!
952 } else if ( $this->isConflict
) {
954 if ( $this->mergeChangesInto( $text ) ) {
955 // Successful merge! Maybe we should tell the user the good news?
956 $this->isConflict
= false;
957 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
960 $this->textbox1
= $text;
961 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
965 if ( $this->isConflict
) {
966 wfProfileOut( $fname );
967 return self
::AS_CONFLICT_DETECTED
;
970 $oldtext = $this->mArticle
->getContent();
972 // Run post-section-merge edit filter
973 if ( !wfRunHooks( 'EditFilterMerged', array( &$this, $text, &$this->hookError
, $this->summary
) ) ) {
974 # Error messages etc. could be handled within the hook...
975 wfProfileOut( $fname );
976 return self
::AS_HOOK_ERROR
;
979 # Handle the user preference to force summaries here, but not for null edits
980 if ( $this->section
!= 'new' && !$this->allowBlankSummary
&& 0 != strcmp($oldtext,$text)
981 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
983 if ( md5( $this->summary
) == $this->autoSumm
) {
984 $this->missingSummary
= true;
985 wfProfileOut( $fname );
986 return self
::AS_SUMMARY_NEEDED
;
990 # And a similar thing for new sections
991 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
992 if (trim($this->summary
) == '') {
993 $this->missingSummary
= true;
994 wfProfileOut( $fname );
995 return self
::AS_SUMMARY_NEEDED
;
1000 wfProfileIn( "$fname-sectionanchor" );
1001 $sectionanchor = '';
1002 if ( $this->section
== 'new' ) {
1003 if ( $this->textbox1
== '' ) {
1004 $this->missingComment
= true;
1005 return self
::AS_TEXTBOX_EMPTY
;
1007 if ( $this->summary
!= '' ) {
1008 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary
);
1009 # This is a new section, so create a link to the new section
1010 # in the revision summary.
1011 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1012 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1014 } elseif ( $this->section
!= '' ) {
1015 # Try to get a section anchor from the section source, redirect to edited section if header found
1016 # XXX: might be better to integrate this into Article::replaceSection
1017 # for duplicate heading checking and maybe parsing
1018 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1019 # we can't deal with anchors, includes, html etc in the header for now,
1020 # headline would need to be parsed to improve this
1021 if ( $hasmatch and strlen($matches[2]) > 0 ) {
1022 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
1025 wfProfileOut( "$fname-sectionanchor" );
1027 // Save errors may fall down to the edit form, but we've now
1028 // merged the section into full text. Clear the section field
1029 // so that later submission of conflict forms won't try to
1030 // replace that into a duplicated mess.
1031 $this->textbox1
= $text;
1032 $this->section
= '';
1034 // Check for length errors again now that the section is merged in
1035 $this->kblength
= (int)(strlen( $text ) / 1024);
1036 if ( $this->kblength
> $wgMaxArticleSize ) {
1037 $this->tooBig
= true;
1038 wfProfileOut( $fname );
1039 return self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
;
1042 # update the article here
1043 if ( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
1044 $this->watchthis
, $bot, $sectionanchor ) )
1046 wfProfileOut( $fname );
1047 return self
::AS_SUCCESS_UPDATE
;
1049 $this->isConflict
= true;
1051 wfProfileOut( $fname );
1052 return self
::AS_END
;
1056 * Check if no edits were made by other users since
1057 * the time a user started editing the page. Limit to
1058 * 50 revisions for the sake of performance.
1060 protected function userWasLastToEdit( $id, $edittime ) {
1061 if( !$id ) return false;
1062 $dbw = wfGetDB( DB_MASTER
);
1063 $res = $dbw->select( 'revision',
1066 'rev_page' => $this->mArticle
->getId(),
1067 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1070 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1071 while( $row = $res->fetchObject() ) {
1072 if( $row->rev_user
!= $id ) {
1080 * Check given input text against $wgSpamRegex, and return the text of the first match.
1081 * @return mixed -- matching string or false
1083 public static function matchSpamRegex( $text ) {
1084 global $wgSpamRegex;
1085 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1086 $regexes = (array)$wgSpamRegex;
1087 return self
::matchSpamRegexInternal( $text, $regexes );
1091 * Check given input text against $wgSpamRegex, and return the text of the first match.
1092 * @return mixed -- matching string or false
1094 public static function matchSummarySpamRegex( $text ) {
1095 global $wgSummarySpamRegex;
1096 $regexes = (array)$wgSummarySpamRegex;
1097 return self
::matchSpamRegexInternal( $text, $regexes );
1100 protected static function matchSpamRegexInternal( $text, $regexes ) {
1101 foreach( $regexes as $regex ) {
1103 if( preg_match( $regex, $text, $matches ) ) {
1111 * Initialise form fields in the object
1112 * Called on the first invocation, e.g. when a user clicks an edit link
1114 function initialiseForm() {
1115 $this->edittime
= $this->mArticle
->getTimestamp();
1116 $this->textbox1
= $this->getContent( false );
1117 if ( $this->textbox1
=== false ) return false;
1122 function setHeaders() {
1123 global $wgOut, $wgTitle;
1124 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1125 if ( $this->formtype
== 'preview' ) {
1126 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1128 if ( $this->isConflict
) {
1129 $wgOut->setPageTitle( wfMsg( 'editconflict', $wgTitle->getPrefixedText() ) );
1130 } elseif ( $this->section
!= '' ) {
1131 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1132 $wgOut->setPageTitle( wfMsg( $msg, $wgTitle->getPrefixedText() ) );
1134 # Use the title defined by DISPLAYTITLE magic word when present
1135 if ( isset($this->mParserOutput
)
1136 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1139 $title = $wgTitle->getPrefixedText();
1141 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1146 * Send the edit form and related headers to $wgOut
1147 * @param $formCallback Optional callable that takes an OutputPage
1148 * parameter; will be called during form output
1149 * near the top, for captchas and the like.
1151 function showEditForm( $formCallback=null ) {
1152 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle, $wgRequest;
1154 # If $wgTitle is null, that means we're in API mode.
1155 # Some hook probably called this function without checking
1156 # for is_null($wgTitle) first. Bail out right here so we don't
1157 # do lots of work just to discard it right after.
1158 if (is_null($wgTitle))
1161 $fname = 'EditPage::showEditForm';
1162 wfProfileIn( $fname );
1164 $sk = $wgUser->getSkin();
1166 #need to parse the preview early so that we know which templates are used,
1167 #otherwise users with "show preview after edit box" will get a blank list
1168 #we parse this near the beginning so that setHeaders can do the title
1169 #setting work instead of leaving it in getPreviewText
1170 $previewOutput = '';
1171 if ( $this->formtype
== 'preview' ) {
1172 $previewOutput = $this->getPreviewText();
1175 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
1177 $this->setHeaders();
1179 # Enabled article-related sidebar, toplinks, etc.
1180 $wgOut->setArticleRelated( true );
1182 if ( $this->isConflict
) {
1183 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1</div>", 'explainconflict' );
1185 $this->textbox2
= $this->textbox1
;
1186 $this->textbox1
= $this->getContent();
1187 $this->edittime
= $this->mArticle
->getTimestamp();
1189 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1191 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1192 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1
, $matches );
1193 if ( !empty( $matches[2] ) ) {
1195 $this->summary
= "/* " .
1196 $wgParser->stripSectionName(trim($matches[2])) .
1202 if ( $this->missingComment
) {
1203 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1206 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1207 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1210 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1211 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1214 if ( $this->hookError
!== '' ) {
1215 $wgOut->addWikiText( $this->hookError
);
1218 if ( !$this->checkUnicodeCompliantBrowser() ) {
1219 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1221 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1222 // Let sysop know that this will make private content public if saved
1224 if ( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1225 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
1226 } else if ( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1227 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
1230 if ( !$this->mArticle
->mRevision
->isCurrent() ) {
1231 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1232 $wgOut->addWikiMsg( 'editingold' );
1237 if ( wfReadOnly() ) {
1238 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1239 } elseif ( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
1240 $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' );
1242 if ( $this->isCssJsSubpage
) {
1243 # Check the skin exists
1244 if ( $this->isValidCssJsSubpage
) {
1245 if ( $this->formtype
!== 'preview' ) {
1246 $wgOut->addWikiMsg( 'usercssjsyoucanpreview' );
1249 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1254 $classes = array(); // Textarea CSS
1255 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1256 } elseif ( $this->mTitle
->isProtected( 'edit' ) ) {
1257 # Is the title semi-protected?
1258 if ( $this->mTitle
->isSemiProtected() ) {
1259 $noticeMsg = 'semiprotectedpagewarning';
1260 $classes[] = 'mw-textarea-sprotected';
1262 # Then it must be protected based on static groups (regular)
1263 $noticeMsg = 'protectedpagewarning';
1264 $classes[] = 'mw-textarea-protected';
1266 $wgOut->addHTML( "<div class='mw-warning-with-logexcerpt'>\n" );
1267 $wgOut->addWikiMsg( $noticeMsg );
1268 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
->getPrefixedText(), '', 1 );
1269 $wgOut->addHTML( "</div>\n" );
1271 if ( $this->mTitle
->isCascadeProtected() ) {
1272 # Is this page under cascading protection from some source pages?
1273 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1274 $notice = "<div class='mw-cascadeprotectedwarning'>$1\n";
1275 $cascadeSourcesCount = count( $cascadeSources );
1276 if ( $cascadeSourcesCount > 0 ) {
1277 # Explain, and list the titles responsible
1278 foreach( $cascadeSources as $page ) {
1279 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1282 $notice .= '</div>';
1283 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1285 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1286 $wgOut->wrapWikiMsg( '<div class="mw-titleprotectedwarning">$1</div>', 'titleprotectedwarning' );
1289 if ( $this->kblength
=== false ) {
1290 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1292 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1293 $wgOut->addHTML( "<div class='error' id='mw-edit-longpageerror'>\n" );
1294 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) );
1295 $wgOut->addHTML( "</div>\n" );
1296 } elseif ( $this->kblength
> 29 ) {
1297 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1298 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) );
1299 $wgOut->addHTML( "</div>\n" );
1302 $action = $wgTitle->escapeLocalURL( array( 'action' => $this->action
) );
1304 $summary = wfMsgExt( 'summary', 'parseinline' );
1305 $subject = wfMsgExt( 'subject', 'parseinline' );
1307 $cancel = $sk->link(
1309 wfMsgExt( 'cancel', array( 'parseinline' ) ),
1312 array( 'known', 'noclasses' )
1314 $separator = wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1315 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1316 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1317 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1318 htmlspecialchars( wfMsg( 'newwindow' ) );
1320 global $wgRightsText;
1321 if ( $wgRightsText ) {
1322 $copywarnMsg = array( 'copyrightwarning',
1323 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1326 $copywarnMsg = array( 'copyrightwarning2',
1327 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1329 // Allow for site and per-namespace customization of contribution/copyright notice.
1330 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
1332 if ( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1333 # prepare toolbar for edit buttons
1334 $toolbar = EditPage
::getEditToolbar();
1340 // activate checkboxes if user wants them to be always active
1341 if ( !$this->preview
&& !$this->diff
) {
1342 # Sort out the "watch" checkbox
1343 if ( $wgUser->getOption( 'watchdefault' ) ) {
1345 $this->watchthis
= true;
1346 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1348 $this->watchthis
= true;
1349 } elseif ( $this->mTitle
->userIsWatching() ) {
1351 $this->watchthis
= true;
1354 # May be overriden by request parameters
1355 if( $wgRequest->getBool( 'watchthis' ) ) {
1356 $this->watchthis
= true;
1359 if ( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1362 $wgOut->addHTML( $this->editFormPageTop
);
1364 if ( $wgUser->getOption( 'previewontop' ) ) {
1365 $this->displayPreviewArea( $previewOutput, true );
1369 $wgOut->addHTML( $this->editFormTextTop
);
1371 # if this is a comment, show a subject line at the top, which is also the edit summary.
1372 # Otherwise, show a summary field at the bottom
1373 $summarytext = $wgContLang->recodeForEdit( $this->summary
);
1375 # If a blank edit summary was previously provided, and the appropriate
1376 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1377 # user being bounced back more than once in the event that a summary
1380 # For a bit more sophisticated detection of blank summaries, hash the
1381 # automatic one and pass that in the hidden field wpAutoSummary.
1382 $summaryhiddens = '';
1383 if ( $this->missingSummary
) $summaryhiddens .= Xml
::hidden( 'wpIgnoreBlankSummary', true );
1384 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1385 $summaryhiddens .= Xml
::hidden( 'wpAutoSummary', $autosumm );
1386 if ( $this->section
== 'new' ) {
1387 $commentsubject = '';
1388 if ( !$wgRequest->getBool( 'nosummary' ) ) {
1389 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1390 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1393 Xml
::tags( 'label', array( 'for' => 'wpSummary' ), $subject );
1395 Xml
::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1397 $commentsubject .= ' ';
1398 $commentsubject .= Xml
::input( 'wpSummary',
1402 'id' => 'wpSummary',
1403 'maxlength' => '200',
1407 $editsummary = "<div class='editOptions'>\n";
1409 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary
) );
1410 $subjectpreview = $summarytext && $this->preview ?
1411 "<div class=\"mw-summary-preview\">". wfMsgExt('subject-preview', 'parseinline') . $sk->commentBlock( $formattedSummary, $this->mTitle
, true )."</div>\n" : '';
1412 $summarypreview = '';
1414 $commentsubject = '';
1416 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1417 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1419 $editsummary = Xml
::tags( 'label', array( 'for' => 'wpSummary' ), $summary );
1420 $editsummary = Xml
::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1421 $editsummary ) . ' ';
1423 $editsummary .= Xml
::input( 'wpSummary',
1427 'id' => 'wpSummary',
1428 'maxlength' => '200',
1432 // No idea where this is closed.
1433 $editsummary = Xml
::openElement( 'div', array( 'class' => 'editOptions' ) )
1434 . $editsummary . '<br/>';
1436 $summarypreview = '';
1437 if ( $summarytext && $this->preview
) {
1440 array( 'class' => 'mw-summary-preview' ),
1441 wfMsgExt( 'summary-preview', 'parseinline' ) .
1442 $sk->commentBlock( $this->summary
, $this->mTitle
)
1445 $subjectpreview = '';
1447 $commentsubject .= $summaryhiddens;
1449 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1450 if ( !$this->preview
&& !$this->diff
) {
1451 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1453 $templates = $this->getTemplates();
1454 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1456 $hiddencats = $this->mArticle
->getHiddenCategories();
1457 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1459 global $wgUseMetadataEdit ;
1460 if ( $wgUseMetadataEdit ) {
1461 $metadata = $this->mMetaData
;
1462 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1463 $top = wfMsgWikiHtml( 'metadata_help' );
1464 /* ToDo: Replace with clean code */
1465 $ew = $wgUser->getOption( 'editwidth' );
1466 if ( $ew ) $ew = " style=\"width:100%\"";
1468 $cols = $wgUser->getIntOption( 'cols' );
1470 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1472 else $metadata = "" ;
1475 if ( $this->wasDeletedSinceLastEdit() ) {
1476 if ( 'save' != $this->formtype
) {
1477 $wgOut->wrapWikiMsg(
1478 "<div class='error mw-deleted-while-editing'>\n$1</div>",
1479 'deletedwhileediting' );
1481 // Hide the toolbar and edit area, user can click preview to get it back
1482 // Add an confirmation checkbox and explanation.
1484 $recreate = '<div class="mw-confirm-recreate">' .
1485 $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
) ) .
1486 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1487 array( 'title' => $sk->titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1494 $checkboxes = $this->getCheckboxes( $tabindex, $sk,
1495 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1497 $checkboxhtml = implode( $checkboxes, "\n" );
1499 $buttons = $this->getEditButtons( $tabindex );
1500 $buttonshtml = implode( $buttons, "\n" );
1502 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1503 ?
'' : Xml
::hidden( 'safemode', '1' );
1505 $wgOut->addHTML( <<<END
1507 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1511 if ( is_callable( $formCallback ) ) {
1512 call_user_func_array( $formCallback, array( &$wgOut ) );
1515 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1517 // Put these up at the top to ensure they aren't lost on early form submission
1518 $this->showFormBeforeText();
1520 $wgOut->addHTML( <<<END
1524 {$this->editFormTextBeforeContent}
1527 $this->showTextbox1( $classes );
1529 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1530 $wgOut->addHTML( <<<END
1531 {$this->editFormTextAfterWarn}
1541 "<div class='editButtons'>
1543 <span class='editHelp'>{$cancel}{$separator}{$edithelp}</span>
1544 </div><!-- editButtons -->
1545 </div><!-- editOptions -->");
1548 * To make it harder for someone to slip a user a page
1549 * which submits an edit form to the wiki without their
1550 * knowledge, a random token is associated with the login
1551 * session. If it's not passed back with the submission,
1552 * we won't save the page, or render user JavaScript and
1555 * For anon editors, who may not have a session, we just
1556 * include the constant suffix to prevent editing from
1557 * broken text-mangling proxies.
1559 $token = htmlspecialchars( $wgUser->editToken() );
1560 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1562 $this->showTosSummary();
1563 $this->showEditTools();
1565 $wgOut->addHTML( <<<END
1566 {$this->editFormTextAfterTools}
1567 <div class='templatesUsed'>
1568 {$formattedtemplates}
1570 <div class='hiddencats'>
1571 {$formattedhiddencats}
1576 if ( $this->isConflict
&& wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1577 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1579 $de = new DifferenceEngine( $this->mTitle
);
1580 $de->setText( $this->textbox2
, $this->textbox1
);
1581 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1583 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1584 $this->showTextbox2();
1586 $wgOut->addHTML( $this->editFormTextBottom
);
1587 $wgOut->addHTML( "</form>\n" );
1588 if ( !$wgUser->getOption( 'previewontop' ) ) {
1589 $this->displayPreviewArea( $previewOutput, false );
1592 wfProfileOut( $fname );
1595 protected function showFormBeforeText() {
1598 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1599 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1600 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1601 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1604 protected function showTextbox1( $classes ) {
1605 $attribs = array( 'tabindex' => 1 );
1607 if ( $this->wasDeletedSinceLastEdit() )
1608 $attribs['type'] = 'hidden';
1609 if ( !empty($classes) )
1610 $attribs['class'] = implode(' ',$classes);
1612 $this->showTextbox( $this->textbox1
, 'wpTextbox1', $attribs );
1615 protected function showTextbox2() {
1616 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6 ) );
1619 protected function showTextbox( $content, $name, $attribs = array() ) {
1620 global $wgOut, $wgUser;
1622 $wikitext = $this->safeUnicodeOutput( $content );
1623 if ( $wikitext !== '' ) {
1624 // Ensure there's a newline at the end, otherwise adding lines
1626 // But don't add a newline if the ext is empty, or Firefox in XHTML
1627 // mode will show an extra newline. A bit annoying.
1631 $attribs['accesskey'] = ',';
1632 $attribs['id'] = $name;
1634 if ( $wgUser->getOption( 'editwidth' ) )
1635 $attribs['style'] = 'width: 100%';
1637 $wgOut->addHTML( Xml
::textarea(
1640 $wgUser->getIntOption( 'cols' ), $wgUser->getIntOption( 'rows' ),
1644 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1648 $classes[] = 'ontop';
1650 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1652 if ( $this->formtype
!= 'preview' )
1653 $attribs['style'] = 'display: none;';
1655 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
1657 if ( $this->formtype
== 'preview' ) {
1658 $this->showPreview( $previewOutput );
1661 $wgOut->addHTML( '</div>' );
1663 if ( $this->formtype
== 'diff') {
1669 * Append preview output to $wgOut.
1670 * Includes category rendering if this is a category page.
1672 * @param string $text The HTML to be output for the preview.
1674 protected function showPreview( $text ) {
1676 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1677 $this->mArticle
->openShowCategory();
1679 # This hook seems slightly odd here, but makes things more
1680 # consistent for extensions.
1681 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1682 $wgOut->addHTML( $text );
1683 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1684 $this->mArticle
->closeShowCategory();
1689 * Live Preview lets us fetch rendered preview page content and
1690 * add it to the page without refreshing the whole page.
1691 * If not supported by the browser it will fall through to the normal form
1692 * submission method.
1694 * This function outputs a script tag to support live preview, and
1695 * returns an onclick handler which should be added to the attributes
1696 * of the preview button
1698 function doLivePreviewScript() {
1699 global $wgOut, $wgTitle;
1700 $wgOut->addScriptFile( 'preview.js' );
1701 $liveAction = $wgTitle->getLocalUrl( array(
1702 'action' => $this->action
,
1703 'wpPreview' => 'true',
1706 return "return !lpDoPreview(" .
1707 "editform.wpTextbox1.value," .
1708 '"' . $liveAction . '"' . ")";
1711 protected function showTosSummary() {
1712 $msg = 'editpage-tos-summary';
1713 // Give a chance for site and per-namespace customizations of
1714 // terms of service summary link that might exist separately
1715 // from the copyright notice.
1717 // This will display between the save button and the edit tools,
1718 // so should remain short!
1719 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
1720 $text = wfMsg( $msg );
1721 if( !wfEmptyMsg( $msg, $text ) && $text !== '-' ) {
1723 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1724 $wgOut->addWikiMsgArray( $msg, array() );
1725 $wgOut->addHTML( '</div>' );
1729 protected function showEditTools() {
1731 $wgOut->addHTML( '<div class="mw-editTools">' );
1732 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1733 $wgOut->addHTML( '</div>' );
1736 protected function getLastDelete() {
1737 $dbr = wfGetDB( DB_SLAVE
);
1738 $data = $dbr->selectRow(
1739 array( 'logging', 'user' ),
1750 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1751 'log_title' => $this->mTitle
->getDBkey(),
1752 'log_type' => 'delete',
1753 'log_action' => 'delete',
1754 'user_id=log_user' ),
1756 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1758 // Quick paranoid permission checks...
1759 if( is_object($data) ) {
1760 if( $data->log_deleted
& LogPage
::DELETED_USER
)
1761 $data->user_name
= wfMsgHtml('rev-deleted-user');
1762 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
1763 $data->log_comment
= wfMsgHtml('rev-deleted-comment');
1769 * Get the rendered text for previewing.
1772 function getPreviewText() {
1773 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache;
1775 wfProfileIn( __METHOD__
);
1777 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1778 if ( $this->mTokenOkExceptSuffix
) {
1779 $note = wfMsg( 'token_suffix_mismatch' );
1781 $note = wfMsg( 'session_fail_preview' );
1784 $note = wfMsg( 'previewnote' );
1787 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1788 $parserOptions->setEditSection( false );
1789 $parserOptions->setIsPreview( true );
1790 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
1793 if ( $wgRawHtml && !$this->mTokenOk
) {
1794 // Could be an offsite preview attempt. This is very unsafe if
1795 // HTML is enabled, as it could be an attack.
1796 return $wgOut->parse( "<div class='previewnote'>" .
1797 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1800 # don't parse user css/js, show message about preview
1801 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1803 if ( $this->isCssJsSubpage
) {
1804 if (preg_match("/\\.css$/", $this->mTitle
->getText() ) ) {
1805 $previewtext = wfMsg('usercsspreview');
1806 } else if (preg_match("/\\.js$/", $this->mTitle
->getText() ) ) {
1807 $previewtext = wfMsg('userjspreview');
1809 $parserOptions->setTidy(true);
1810 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
1811 $previewHTML = $parserOutput->mText
;
1812 } elseif ( $rt = Title
::newFromRedirectArray( $this->textbox1
) ) {
1813 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
1815 $toparse = $this->textbox1
;
1817 # If we're adding a comment, we need to show the
1818 # summary as the headline
1819 if ( $this->section
=="new" && $this->summary
!="" ) {
1820 $toparse="== {$this->summary} ==\n\n".$toparse;
1823 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1825 // Parse mediawiki messages with correct target language
1826 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1827 list( /* $unused */, $lang ) = $wgMessageCache->figureMessage( $this->mTitle
->getText() );
1828 $obj = wfGetLangObj( $lang );
1829 $parserOptions->setTargetLanguage( $obj );
1833 $parserOptions->setTidy(true);
1834 $parserOptions->enableLimitReport();
1835 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ),
1836 $this->mTitle
, $parserOptions );
1838 $previewHTML = $parserOutput->getText();
1839 $this->mParserOutput
= $parserOutput;
1840 $wgOut->addParserOutputNoText( $parserOutput );
1842 if ( count( $parserOutput->getWarnings() ) ) {
1843 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1847 if( $this->isConflict
) {
1848 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1850 $conflict = '<hr />';
1853 $previewhead = "<div class='previewnote'>\n" .
1854 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
1855 $wgOut->parse( $note ) . $conflict . "</div>\n";
1857 wfProfileOut( __METHOD__
);
1858 return $previewhead . $previewHTML;
1861 function getTemplates() {
1862 if ( $this->preview ||
$this->section
!= '' ) {
1863 $templates = array();
1864 if ( !isset($this->mParserOutput
) ) return $templates;
1865 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
1866 foreach( array_keys( $template ) as $dbk ) {
1867 $templates[] = Title
::makeTitle($ns, $dbk);
1872 return $this->mArticle
->getUsedTemplates();
1877 * Call the stock "user is blocked" page
1879 function blockedPage() {
1880 global $wgOut, $wgUser;
1881 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1883 # If the user made changes, preserve them when showing the markup
1884 # (This happens when a user is blocked during edit, for instance)
1885 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1887 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1889 $source = $this->textbox1
;
1892 # Spit out the source or the user's modified version
1893 if ( $source !== false ) {
1894 $rows = $wgUser->getIntOption( 'rows' );
1895 $cols = $wgUser->getIntOption( 'cols' );
1896 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1897 $wgOut->addHTML( '<hr />' );
1898 $wgOut->addWikiMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() );
1899 # Why we don't use Xml::element here?
1900 # Is it because if $source is '', it returns <textarea />?
1901 $wgOut->addHTML( Xml
::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml
::closeElement( 'textarea' ) );
1906 * Produce the stock "please login to edit pages" page
1908 function userNotLoggedInPage() {
1909 global $wgUser, $wgOut, $wgTitle;
1910 $skin = $wgUser->getSkin();
1912 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1913 $loginLink = $skin->link(
1915 wfMsgHtml( 'loginreqlink' ),
1917 array( 'returnto' => $wgTitle->getPrefixedText() ),
1918 array( 'known', 'noclasses' )
1921 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1922 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1923 $wgOut->setArticleRelated( false );
1925 $wgOut->addHTML( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1926 $wgOut->returnToMain( false, $wgTitle );
1930 * Creates a basic error page which informs the user that
1931 * they have attempted to edit a nonexistent section.
1933 function noSuchSectionPage() {
1934 global $wgOut, $wgTitle;
1936 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1937 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1938 $wgOut->setArticleRelated( false );
1940 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section
);
1941 $wgOut->returnToMain( false, $wgTitle );
1945 * Produce the stock "your edit contains spam" page
1947 * @param $match Text which triggered one or more filters
1949 function spamPage( $match = false ) {
1950 global $wgOut, $wgTitle;
1952 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1953 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1954 $wgOut->setArticleRelated( false );
1956 $wgOut->addHTML( '<div id="spamprotected">' );
1957 $wgOut->addWikiMsg( 'spamprotectiontext' );
1959 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1960 $wgOut->addHTML( '</div>' );
1962 $wgOut->returnToMain( false, $wgTitle );
1969 function mergeChangesInto( &$editText ){
1970 $fname = 'EditPage::mergeChangesInto';
1971 wfProfileIn( $fname );
1973 $db = wfGetDB( DB_MASTER
);
1975 // This is the revision the editor started from
1976 $baseRevision = $this->getBaseRevision();
1977 if ( is_null( $baseRevision ) ) {
1978 wfProfileOut( $fname );
1981 $baseText = $baseRevision->getText();
1983 // The current state, we want to merge updates into it
1984 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1985 if ( is_null( $currentRevision ) ) {
1986 wfProfileOut( $fname );
1989 $currentText = $currentRevision->getText();
1992 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1993 $editText = $result;
1994 wfProfileOut( $fname );
1997 wfProfileOut( $fname );
2003 * Check if the browser is on a blacklist of user-agents known to
2004 * mangle UTF-8 data on form submission. Returns true if Unicode
2005 * should make it through, false if it's known to be a problem.
2009 function checkUnicodeCompliantBrowser() {
2010 global $wgBrowserBlackList;
2011 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2012 // No User-Agent header sent? Trust it by default...
2015 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2016 foreach ( $wgBrowserBlackList as $browser ) {
2017 if ( preg_match($browser, $currentbrowser) ) {
2025 * @deprecated use $wgParser->stripSectionName()
2027 function pseudoParseSectionAnchor( $text ) {
2029 return $wgParser->stripSectionName( $text );
2033 * Format an anchor fragment as it would appear for a given section name
2034 * @param string $text
2038 function sectionAnchor( $text ) {
2040 return $wgParser->guessSectionNameFromWikiText( $text );
2044 * Shows a bulletin board style toolbar for common editing functions.
2045 * It can be disabled in the user preferences.
2046 * The necessary JavaScript code can be found in skins/common/edit.js.
2050 static function getEditToolbar() {
2051 global $wgStylePath, $wgContLang, $wgLang, $wgJsMimeType;
2054 * toolarray an array of arrays which each include the filename of
2055 * the button image (without path), the opening tag, the closing tag,
2056 * and optionally a sample text that is inserted between the two when no
2057 * selection is highlighted.
2058 * The tip text is shown when the user moves the mouse over the button.
2060 * Already here are accesskeys (key), which are not used yet until someone
2061 * can figure out a way to make them work in IE. However, we should make
2062 * sure these keys are not defined on the edit page.
2066 'image' => $wgLang->getImageFile('button-bold'),
2067 'id' => 'mw-editbutton-bold',
2069 'close' => '\'\'\'',
2070 'sample' => wfMsg('bold_sample'),
2071 'tip' => wfMsg('bold_tip'),
2075 'image' => $wgLang->getImageFile('button-italic'),
2076 'id' => 'mw-editbutton-italic',
2079 'sample' => wfMsg('italic_sample'),
2080 'tip' => wfMsg('italic_tip'),
2084 'image' => $wgLang->getImageFile('button-link'),
2085 'id' => 'mw-editbutton-link',
2088 'sample' => wfMsg('link_sample'),
2089 'tip' => wfMsg('link_tip'),
2093 'image' => $wgLang->getImageFile('button-extlink'),
2094 'id' => 'mw-editbutton-extlink',
2097 'sample' => wfMsg('extlink_sample'),
2098 'tip' => wfMsg('extlink_tip'),
2102 'image' => $wgLang->getImageFile('button-headline'),
2103 'id' => 'mw-editbutton-headline',
2106 'sample' => wfMsg('headline_sample'),
2107 'tip' => wfMsg('headline_tip'),
2111 'image' => $wgLang->getImageFile('button-image'),
2112 'id' => 'mw-editbutton-image',
2113 'open' => '[['.$wgContLang->getNsText(NS_FILE
).':',
2115 'sample' => wfMsg('image_sample'),
2116 'tip' => wfMsg('image_tip'),
2120 'image' => $wgLang->getImageFile('button-media'),
2121 'id' => 'mw-editbutton-media',
2122 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
2124 'sample' => wfMsg('media_sample'),
2125 'tip' => wfMsg('media_tip'),
2129 'image' => $wgLang->getImageFile('button-math'),
2130 'id' => 'mw-editbutton-math',
2132 'close' => "</math>",
2133 'sample' => wfMsg('math_sample'),
2134 'tip' => wfMsg('math_tip'),
2138 'image' => $wgLang->getImageFile('button-nowiki'),
2139 'id' => 'mw-editbutton-nowiki',
2140 'open' => "<nowiki>",
2141 'close' => "</nowiki>",
2142 'sample' => wfMsg('nowiki_sample'),
2143 'tip' => wfMsg('nowiki_tip'),
2147 'image' => $wgLang->getImageFile('button-sig'),
2148 'id' => 'mw-editbutton-signature',
2152 'tip' => wfMsg('sig_tip'),
2156 'image' => $wgLang->getImageFile('button-hr'),
2157 'id' => 'mw-editbutton-hr',
2158 'open' => "\n----\n",
2161 'tip' => wfMsg('hr_tip'),
2165 $toolbar = "<div id='toolbar'>\n";
2166 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
2168 foreach($toolarray as $tool) {
2170 $image = $wgStylePath.'/common/images/'.$tool['image'],
2171 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2172 // Older browsers show a "speedtip" type message only for ALT.
2173 // Ideally these should be different, realistically they
2174 // probably don't need to be.
2175 $tip = $tool['tip'],
2176 $open = $tool['open'],
2177 $close = $tool['close'],
2178 $sample = $tool['sample'],
2179 $cssId = $tool['id'],
2182 $paramList = implode( ',',
2183 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2184 $toolbar.="addButton($paramList);\n";
2187 $toolbar.="/*]]>*/\n</script>";
2188 $toolbar.="\n</div>";
2190 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2196 * Returns an array of html code of the following checkboxes:
2199 * @param $tabindex Current tabindex
2200 * @param $skin Skin object
2201 * @param $checked Array of checkbox => bool, where bool indicates the checked
2202 * status of the checkbox
2206 public function getCheckboxes( &$tabindex, $skin, $checked ) {
2209 $checkboxes = array();
2211 $checkboxes['minor'] = '';
2212 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
2213 if ( $wgUser->isAllowed('minoredit') ) {
2215 'tabindex' => ++
$tabindex,
2216 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2217 'id' => 'wpMinoredit',
2219 $checkboxes['minor'] =
2220 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2221 " <label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
2224 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2225 $checkboxes['watch'] = '';
2226 if ( $wgUser->isLoggedIn() ) {
2228 'tabindex' => ++
$tabindex,
2229 'accesskey' => wfMsg( 'accesskey-watch' ),
2230 'id' => 'wpWatchthis',
2232 $checkboxes['watch'] =
2233 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2234 " <label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
2236 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2241 * Returns an array of html code of the following buttons:
2242 * save, diff, preview and live
2244 * @param $tabindex Current tabindex
2248 public function getEditButtons(&$tabindex) {
2249 global $wgLivePreview, $wgUser;
2257 'tabindex' => ++
$tabindex,
2258 'value' => wfMsg('savearticle'),
2259 'accesskey' => wfMsg('accesskey-save'),
2260 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2262 $buttons['save'] = Xml
::element('input', $temp, '');
2264 ++
$tabindex; // use the same for preview and live preview
2265 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2267 'id' => 'wpPreview',
2268 'name' => 'wpPreview',
2270 'tabindex' => $tabindex,
2271 'value' => wfMsg('showpreview'),
2273 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2274 'style' => 'display: none;',
2276 $buttons['preview'] = Xml
::element('input', $temp, '');
2279 'id' => 'wpLivePreview',
2280 'name' => 'wpLivePreview',
2282 'tabindex' => $tabindex,
2283 'value' => wfMsg('showlivepreview'),
2284 'accesskey' => wfMsg('accesskey-preview'),
2286 'onclick' => $this->doLivePreviewScript(),
2288 $buttons['live'] = Xml
::element('input', $temp, '');
2291 'id' => 'wpPreview',
2292 'name' => 'wpPreview',
2294 'tabindex' => $tabindex,
2295 'value' => wfMsg('showpreview'),
2296 'accesskey' => wfMsg('accesskey-preview'),
2297 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2299 $buttons['preview'] = Xml
::element('input', $temp, '');
2300 $buttons['live'] = '';
2307 'tabindex' => ++
$tabindex,
2308 'value' => wfMsg('showdiff'),
2309 'accesskey' => wfMsg('accesskey-diff'),
2310 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2312 $buttons['diff'] = Xml
::element('input', $temp, '');
2314 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2319 * Output preview text only. This can be sucked into the edit page
2320 * via JavaScript, and saves the server time rendering the skin as
2321 * well as theoretically being more robust on the client (doesn't
2322 * disturb the edit box's undo history, won't eat your text on
2325 * @todo This doesn't include category or interlanguage links.
2326 * Would need to enhance it a bit, <s>maybe wrap them in XML
2327 * or something...</s> that might also require more skin
2328 * initialization, so check whether that's a problem.
2330 function livePreview() {
2333 header( 'Content-type: text/xml; charset=utf-8' );
2334 header( 'Cache-control: no-cache' );
2336 $previewText = $this->getPreviewText();
2337 #$categories = $skin->getCategoryLinks();
2340 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2341 Xml
::tags( 'livepreview', null,
2342 Xml
::element( 'preview', null, $previewText )
2343 #. Xml::element( 'category', null, $categories )
2350 * Get a diff between the current contents of the edit box and the
2351 * version of the page we're editing from.
2353 * If this is a section edit, we'll replace the section as for final
2354 * save and then make a comparison.
2356 function showDiff() {
2357 $oldtext = $this->mArticle
->fetchContent();
2358 $newtext = $this->mArticle
->replaceSection(
2359 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2360 $newtext = $this->mArticle
->preSaveTransform( $newtext );
2361 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2362 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2363 if ( $oldtext !== false ||
$newtext != '' ) {
2364 $de = new DifferenceEngine( $this->mTitle
);
2365 $de->setText( $oldtext, $newtext );
2366 $difftext = $de->getDiff( $oldtitle, $newtitle );
2367 $de->showDiffStyle();
2373 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2377 * Filter an input field through a Unicode de-armoring process if it
2378 * came from an old browser with known broken Unicode editing issues.
2380 * @param WebRequest $request
2381 * @param string $field
2385 function safeUnicodeInput( $request, $field ) {
2386 $text = rtrim( $request->getText( $field ) );
2387 return $request->getBool( 'safemode' )
2388 ?
$this->unmakesafe( $text )
2393 * Filter an output field through a Unicode armoring process if it is
2394 * going to an old browser with known broken Unicode editing issues.
2396 * @param string $text
2400 function safeUnicodeOutput( $text ) {
2402 $codedText = $wgContLang->recodeForEdit( $text );
2403 return $this->checkUnicodeCompliantBrowser()
2405 : $this->makesafe( $codedText );
2409 * A number of web browsers are known to corrupt non-ASCII characters
2410 * in a UTF-8 text editing environment. To protect against this,
2411 * detected browsers will be served an armored version of the text,
2412 * with non-ASCII chars converted to numeric HTML character references.
2414 * Preexisting such character references will have a 0 added to them
2415 * to ensure that round-trips do not alter the original data.
2417 * @param string $invalue
2421 function makesafe( $invalue ) {
2422 // Armor existing references for reversability.
2423 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2428 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2429 $bytevalue = ord( $invalue{$i} );
2430 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2431 $result .= chr( $bytevalue );
2433 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2434 $working = $working << 6;
2435 $working +
= ($bytevalue & 0x3F);
2437 if ( $bytesleft <= 0 ) {
2438 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2440 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2441 $working = $bytevalue & 0x1F;
2443 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2444 $working = $bytevalue & 0x0F;
2446 } else { //1111 0xxx
2447 $working = $bytevalue & 0x07;
2455 * Reverse the previously applied transliteration of non-ASCII characters
2456 * back to UTF-8. Used to protect data from corruption by broken web browsers
2457 * as listed in $wgBrowserBlackList.
2459 * @param string $invalue
2463 function unmakesafe( $invalue ) {
2465 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2466 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2470 $hexstring .= $invalue{$i};
2472 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2474 // Do some sanity checks. These aren't needed for reversability,
2475 // but should help keep the breakage down if the editor
2476 // breaks one of the entities whilst editing.
2477 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2478 $codepoint = hexdec($hexstring);
2479 $result .= codepointToUtf8( $codepoint );
2481 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2484 $result .= substr( $invalue, $i, 1 );
2487 // reverse the transform that we made for reversability reasons.
2488 return strtr( $result, array( "�" => "&#x" ) );
2491 function noCreatePermission() {
2493 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2494 $wgOut->addWikiMsg( 'nocreatetext' );
2498 * If there are rows in the deletion/move log for this page, show them,
2499 * along with a nice little note for the user
2501 * @param OutputPage $out
2503 protected function showLogs( $out ) {
2505 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
2506 $pager = new LogPager( $loglist, array('move', 'delete'), false,
2507 $this->mTitle
->getPrefixedText(), '', array( "log_action != 'revision'" ) );
2509 $count = $pager->getNumRows();
2511 $pager->mLimit
= 10;
2512 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
2513 $out->addWikiMsg( 'recreate-moveddeleted-warn' );
2515 $loglist->beginLogEventsList() .
2517 $loglist->endLogEventsList()
2520 $out->addHTML( $wgUser->getSkin()->link(
2521 SpecialPage
::getTitleFor( 'Log' ),
2522 wfMsgHtml( 'log-fulllog' ),
2524 array( 'page' => $this->mTitle
->getPrefixedText() ) ) );
2526 $out->addHTML( '</div>' );
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
;