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
;
115 * Fetch initial editing page content.
118 function getContent( $def_text = '' ) {
119 global $wgOut, $wgRequest, $wgParser, $wgContLang, $wgMessageCache;
121 wfProfileIn( __METHOD__
);
122 # Get variables from query string :P
123 $section = $wgRequest->getVal( 'section' );
124 $preload = $wgRequest->getVal( 'preload' );
125 $undoafter = $wgRequest->getVal( 'undoafter' );
126 $undo = $wgRequest->getVal( 'undo' );
129 // For message page not locally set, use the i18n message.
130 // For other non-existent articles, use preload text if any.
131 if ( !$this->mTitle
->exists() ) {
132 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
133 # If this is a system message, get the default text.
134 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
135 $wgMessageCache->loadAllMessages( $lang );
136 $text = wfMsgGetKey( $message, false, $lang, false );
137 if( wfEmptyMsg( $message, $text ) )
140 # If requested, preload some text.
141 $text = $this->getPreloadedText( $preload );
143 // For existing pages, get text based on "undo" or section parameters.
145 $text = $this->mArticle
->getContent();
146 if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
147 # If they got undoafter and undo round the wrong way, switch them
148 list( $undo, $undoafter ) = array( $undoafter, $undo );
150 if ( $undo > 0 && $undo > $undoafter ) {
151 # Undoing a specific edit overrides section editing; section-editing
152 # doesn't work with undoing.
154 $undorev = Revision
::newFromId($undo);
155 $oldrev = Revision
::newFromId($undoafter);
157 $undorev = Revision
::newFromId($undo);
158 $oldrev = $undorev ?
$undorev->getPrevious() : null;
161 # Sanity check, make sure it's the right page,
162 # the revisions exist and they were not deleted.
163 # Otherwise, $text will be left as-is.
164 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
165 $undorev->getPage() == $oldrev->getPage() &&
166 $undorev->getPage() == $this->mArticle
->getID() &&
167 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
168 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
170 $undotext = $this->mArticle
->getUndoText( $undorev, $oldrev );
171 if ( $undotext === false ) {
172 # Warn the user that something went wrong
173 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-failure">' . wfMsgNoTrans( 'undo-failure' ) . '</div>' );
176 # Inform the user of our success and set an automatic edit summary
177 $this->editFormPageTop
.= $wgOut->parse( '<div class="mw-undo-success">' . wfMsgNoTrans( 'undo-success' ) . '</div>' );
178 $firstrev = $oldrev->getNext();
179 # If we just undid one rev, use an autosummary
180 if ( $firstrev->mId
== $undo ) {
181 $this->summary
= wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
182 $this->undidRev
= $undo;
184 $this->formtype
= 'diff';
187 // Failed basic sanity checks.
188 // Older revisions may have been removed since the link
189 // was created, or we may simply have got bogus input.
190 $this->editFormPageTop
.= $wgOut->parse( '<div class="error mw-undo-norev">' . wfMsgNoTrans( 'undo-norev' ) . '</div>' );
192 } else if ( $section != '' ) {
193 if ( $section == 'new' ) {
194 $text = $this->getPreloadedText( $preload );
196 $text = $wgParser->getSection( $text, $section, $def_text );
201 wfProfileOut( __METHOD__
);
205 /** Use this method before edit() to preload some text into the edit box */
206 public function setPreloadedText( $text ) {
207 $this->mPreloadText
= $text;
211 * Get the contents of a page from its title and remove includeonly tags
213 * @param $preload String: the title of the page.
214 * @return string The contents of the page.
216 protected function getPreloadedText( $preload ) {
217 if ( !empty($this->mPreloadText
) ) {
218 return $this->mPreloadText
;
219 } elseif ( $preload === '' ) {
222 $preloadTitle = Title
::newFromText( $preload );
223 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
224 $rev = Revision
::newFromTitle($preloadTitle);
225 if ( is_object( $rev ) ) {
226 $text = $rev->getText();
227 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
228 // its own mini-parser! -ævar
229 $text = preg_replace( '~</?includeonly>~', '', $text );
238 * This is the function that extracts metadata from the article body on the first view.
239 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
240 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
242 function extractMetaDataFromArticle () {
243 global $wgUseMetadataEdit, $wgMetadataWhitelist, $wgContLang;
244 $this->mMetaData
= '';
245 if ( !$wgUseMetadataEdit ) return;
246 if ( $wgMetadataWhitelist == '' ) return;
248 $t = $this->getContent();
250 # MISSING : <nowiki> filtering
252 # Categories and language links
253 $t = explode ( "\n" , $t );
254 $catlow = strtolower ( $wgContLang->getNsText( NS_CATEGORY
) );
255 $cat = $ll = array();
256 foreach ( $t AS $key => $x ) {
257 $y = trim ( strtolower ( $x ) );
258 while ( substr ( $y , 0 , 2 ) == '[[' ) {
259 $y = explode ( ']]' , trim ( $x ) );
260 $first = array_shift ( $y );
261 $first = explode ( ':' , $first );
262 $ns = array_shift ( $first );
263 $ns = trim ( str_replace ( '[' , '' , $ns ) );
264 if ( $wgContLang->getLanguageName( $ns ) ||
strtolower ( $ns ) == $catlow ) {
265 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]';
266 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add;
268 $x = implode ( ']]' , $y );
270 $y = trim ( strtolower ( $x ) );
272 $x = implode ( ']]' , $y );
273 $y = trim ( strtolower ( $x ) );
277 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n";
278 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n";
279 $t = implode ( "\n" , $t );
282 $sat = array () ; # stand-alone-templates; must be lowercase
283 $wl_title = Title
::newFromText ( $wgMetadataWhitelist );
284 $wl_article = new Article ( $wl_title );
285 $wl = explode ( "\n" , $wl_article->getContent() );
286 foreach ( $wl AS $x ) {
289 while ( substr ( $x , 0 , 1 ) == '*' ) {
291 $x = trim ( substr ( $x , 1 ) );
294 $sat[] = strtolower ( $x );
299 # Templates, but only some
300 $t = explode ( '{{' , $t );
302 foreach ( $t AS $key => $x ) {
303 $y = explode ( '}}' , $x , 2 );
304 if ( count ( $y ) == 2 ) {
306 $z = explode ( '|' , $z );
307 $tn = array_shift ( $z );
308 if ( in_array ( strtolower ( $tn ) , $sat ) ) {
309 $tl[] = '{{' . $y[0] . '}}';
311 $y = explode ( '}}' , $y[1] , 2 );
313 else $t[$key] = '{{' . $x;
315 else if ( $key != 0 ) $t[$key] = '{{' . $x;
318 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl );
319 $t = implode ( '' , $t );
321 $t = str_replace ( "\n\n\n" , "\n" , $t );
322 $this->mArticle
->mContent
= $t;
323 $this->mMetaData
= $s;
327 * Check if a page was deleted while the user was editing it, before submit.
328 * Note that we rely on the logging table, which hasn't been always there,
329 * but that doesn't matter, because this only applies to brand new
332 protected function wasDeletedSinceLastEdit() {
333 if ( $this->deletedSinceEdit
)
335 if ( $this->mTitle
->isDeletedQuick() ) {
336 $this->lastDelete
= $this->getLastDelete();
337 if ( $this->lastDelete
) {
338 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
339 if ( $deleteTime > $this->starttime
) {
340 $this->deletedSinceEdit
= true;
344 return $this->deletedSinceEdit
;
352 * This is the function that gets called for "action=edit". It
353 * sets up various member variables, then passes execution to
354 * another function, usually showEditForm()
356 * The edit form is self-submitting, so that when things like
357 * preview and edit conflicts occur, we get the same form back
358 * with the extra stuff added. Only when the final submission
359 * is made and all is well do we actually save and redirect to
360 * the newly-edited page.
363 global $wgOut, $wgRequest;
364 // Allow extensions to modify/prevent this form or submission
365 if ( !wfRunHooks( 'AlternateEdit', array( &$this ) ) ) {
369 wfProfileIn( __METHOD__
);
370 wfDebug( __METHOD__
.": enter\n" );
372 // This is not an article
373 $wgOut->setArticleFlag( false );
375 $this->importFormData( $wgRequest );
376 $this->firsttime
= false;
379 $this->livePreview();
380 wfProfileOut( __METHOD__
);
384 if ( wfReadOnly() && $this->save
) {
387 $this->preview
= true;
390 $wgOut->addScriptFile( 'edit.js' );
391 $permErrors = $this->getEditPermissionErrors();
393 wfDebug( __METHOD__
.": User can't edit\n" );
394 $this->readOnlyPage( $this->getContent(), true, $permErrors, 'edit' );
395 wfProfileOut( __METHOD__
);
399 $this->formtype
= 'save';
400 } else if ( $this->preview
) {
401 $this->formtype
= 'preview';
402 } else if ( $this->diff
) {
403 $this->formtype
= 'diff';
404 } else { # First time through
405 $this->firsttime
= true;
406 if ( $this->previewOnOpen() ) {
407 $this->formtype
= 'preview';
409 $this->extractMetaDataFromArticle () ;
410 $this->formtype
= 'initial';
415 // If they used redlink=1 and the page exists, redirect to the main article
416 if ( $wgRequest->getBool( 'redlink' ) && $this->mTitle
->exists() ) {
417 $wgOut->redirect( $this->mTitle
->getFullURL() );
420 wfProfileIn( __METHOD__
."-business-end" );
422 $this->isConflict
= false;
423 // css / js subpages of user pages get a special treatment
424 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
425 $this->isValidCssJsSubpage
= $this->mTitle
->isValidCssJsSubpage();
427 # Show applicable editing introductions
428 if ( $this->formtype
== 'initial' ||
$this->firsttime
)
431 if ( $this->mTitle
->isTalkPage() ) {
432 $wgOut->addWikiMsg( 'talkpagetext' );
435 # Optional notices on a per-namespace and per-page basis
436 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
437 if ( !wfEmptyMsg( $editnotice_ns, wfMsgForContent( $editnotice_ns ) ) ) {
438 $wgOut->addWikiText( wfMsgForContent( $editnotice_ns ) );
440 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
441 $parts = explode( '/', $this->mTitle
->getDBkey() );
442 $editnotice_base = $editnotice_ns;
443 while ( count( $parts ) > 0 ) {
444 $editnotice_base .= '-'.array_shift( $parts );
445 if ( !wfEmptyMsg( $editnotice_base, wfMsgForContent( $editnotice_base ) ) ) {
446 $wgOut->addWikiText( wfMsgForContent( $editnotice_base ) );
451 # Attempt submission here. This will check for edit conflicts,
452 # and redundantly check for locked database, blocked IPs, etc.
453 # that edit() already checked just in case someone tries to sneak
454 # in the back door with a hand-edited submission URL.
456 if ( 'save' == $this->formtype
) {
457 if ( !$this->attemptSave() ) {
458 wfProfileOut( __METHOD__
."-business-end" );
459 wfProfileOut( __METHOD__
);
464 # First time through: get contents, set time for conflict
466 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
467 if ( $this->initialiseForm() === false) {
468 $this->noSuchSectionPage();
469 wfProfileOut( __METHOD__
."-business-end" );
470 wfProfileOut( __METHOD__
);
473 if ( !$this->mTitle
->getArticleId() )
474 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
477 $this->showEditForm();
478 wfProfileOut( __METHOD__
."-business-end" );
479 wfProfileOut( __METHOD__
);
482 protected function getEditPermissionErrors() {
484 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
485 # Can this title be created?
486 if ( !$this->mTitle
->exists() ) {
487 $permErrors = array_merge( $permErrors,
488 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
490 # Ignore some permissions errors when a user is just previewing/viewing diffs
492 foreach( $permErrors as $error ) {
493 if ( ($this->preview ||
$this->diff
) &&
494 ($error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext') )
499 $permErrors = wfArrayDiff2( $permErrors, $remove );
504 * Show a read-only error
505 * Parameters are the same as OutputPage:readOnlyPage()
506 * Redirect to the article page if redlink=1
508 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
509 global $wgRequest, $wgOut;
510 if ( $wgRequest->getBool( 'redlink' ) ) {
511 // The edit page was reached via a red link.
512 // Redirect to the article page and let them click the edit tab if
513 // they really want a permission error.
514 $wgOut->redirect( $this->mTitle
->getFullUrl() );
516 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
521 * Should we show a preview when the edit form is first shown?
525 protected function previewOnOpen() {
526 global $wgRequest, $wgUser;
527 if ( $wgRequest->getVal( 'preview' ) == 'yes' ) {
528 // Explicit override from request
530 } elseif ( $wgRequest->getVal( 'preview' ) == 'no' ) {
531 // Explicit override from request
533 } elseif ( $this->section
== 'new' ) {
534 // Nothing *to* preview for new sections
536 } elseif ( ( $wgRequest->getVal( 'preload' ) !== null ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
537 // Standard preference behaviour
539 } elseif ( !$this->mTitle
->exists() && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
540 // Categories are special
551 function importFormData( &$request ) {
552 global $wgLang, $wgUser;
553 $fname = 'EditPage::importFormData';
554 wfProfileIn( $fname );
556 # Section edit can come from either the form or a link
557 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
559 if ( $request->wasPosted() ) {
560 # These fields need to be checked for encoding.
561 # Also remove trailing whitespace, but don't remove _initial_
562 # whitespace from the text boxes. This may be significant formatting.
563 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
564 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
565 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
566 # Truncate for whole multibyte characters. +5 bytes for ellipsis
567 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250, '' );
569 # Remove extra headings from summaries and new sections.
570 $this->summary
= preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
572 $this->edittime
= $request->getVal( 'wpEdittime' );
573 $this->starttime
= $request->getVal( 'wpStarttime' );
575 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
577 if ( is_null( $this->edittime
) ) {
578 # If the form is incomplete, force to preview.
579 wfDebug( "$fname: Form data appears to be incomplete\n" );
580 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
581 $this->preview
= true;
583 /* Fallback for live preview */
584 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
585 $this->diff
= $request->getCheck( 'wpDiff' );
587 // Remember whether a save was requested, so we can indicate
588 // if we forced preview due to session failure.
589 $this->mTriedSave
= !$this->preview
;
591 if ( $this->tokenOk( $request ) ) {
592 # Some browsers will not report any submit button
593 # if the user hits enter in the comment box.
594 # The unmarked state will be assumed to be a save,
595 # if the form seems otherwise complete.
596 wfDebug( "$fname: Passed token check.\n" );
597 } else if ( $this->diff
) {
598 # Failed token check, but only requested "Show Changes".
599 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
601 # Page might be a hack attempt posted from
602 # an external site. Preview instead of saving.
603 wfDebug( "$fname: Failed token check; forcing preview\n" );
604 $this->preview
= true;
607 $this->save
= !$this->preview
&& !$this->diff
;
608 if ( !preg_match( '/^\d{14}$/', $this->edittime
)) {
609 $this->edittime
= null;
612 if ( !preg_match( '/^\d{14}$/', $this->starttime
)) {
613 $this->starttime
= null;
616 $this->recreate
= $request->getCheck( 'wpRecreate' );
618 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
619 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
621 # Don't force edit summaries when a user is editing their own user or talk page
622 if ( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) &&
623 $this->mTitle
->getText() == $wgUser->getName() )
625 $this->allowBlankSummary
= true;
627 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' ) ||
!$wgUser->getOption( 'forceeditsummary');
630 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
632 # Not a posted form? Start with nothing.
633 wfDebug( "$fname: Not a posted form.\n" );
634 $this->textbox1
= '';
635 $this->textbox2
= '';
636 $this->mMetaData
= '';
638 $this->edittime
= '';
639 $this->starttime
= wfTimestampNow();
641 $this->preview
= false;
644 $this->minoredit
= false;
645 $this->watchthis
= false;
646 $this->recreate
= false;
648 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
649 $this->summary
= $request->getVal( 'preloadtitle' );
651 elseif ( $this->section
!= 'new' && $request->getVal( 'summary' ) ) {
652 $this->summary
= $request->getText( 'summary' );
655 if ( $request->getVal( 'minor' ) ) {
656 $this->minoredit
= true;
660 // FIXME: unused variable?
661 $this->oldid
= $request->getInt( 'oldid' );
663 $this->live
= $request->getCheck( 'live' );
664 $this->editintro
= $request->getText( 'editintro' );
666 wfProfileOut( $fname );
670 * Make sure the form isn't faking a user's credentials.
672 * @param $request WebRequest
676 function tokenOk( &$request ) {
678 $token = $request->getVal( 'wpEditToken' );
679 $this->mTokenOk
= $wgUser->matchEditToken( $token );
680 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
681 return $this->mTokenOk
;
685 * Show all applicable editing introductions
687 protected function showIntro() {
688 global $wgOut, $wgUser;
689 if ( $this->suppressIntro
) {
693 $namespace = $this->mTitle
->getNamespace();
695 if ( $namespace == NS_MEDIAWIKI
) {
696 # Show a warning if editing an interface message
697 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1</div>", 'editinginterface' );
700 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
701 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
702 $parts = explode( '/', $this->mTitle
->getText(), 2 );
703 $username = $parts[0];
704 $id = User
::idFromName( $username );
705 $ip = User
::isIP( $username );
706 if ( $id == 0 && !$ip ) {
707 $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
708 array( 'userpage-userdoesnotexist', $username ) );
711 # Try to add a custom edit intro, or use the standard one if this is not possible.
712 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
713 if ( $wgUser->isLoggedIn() ) {
714 $wgOut->wrapWikiMsg( '<div class="mw-newarticletext">$1</div>', 'newarticletext' );
716 $wgOut->wrapWikiMsg( '<div class="mw-newarticletextanon">$1</div>', 'newarticletextanon' );
719 # Give a notice if the user is editing a deleted/moved page...
720 if ( !$this->mTitle
->exists() ) {
721 $this->showLogs( $wgOut );
726 * Attempt to show a custom editing introduction, if supplied
730 protected function showCustomIntro() {
731 if ( $this->editintro
) {
732 $title = Title
::newFromText( $this->editintro
);
733 if ( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
735 $revision = Revision
::newFromTitle( $title );
736 $wgOut->addWikiTextTitleTidy( $revision->getText(), $this->mTitle
);
747 * Attempt submission (no UI)
748 * @return one of the constants describing the result
750 function internalAttemptSave( &$result, $bot = false ) {
751 global $wgFilterCallback, $wgUser, $wgOut, $wgParser;
752 global $wgMaxArticleSize;
754 $fname = 'EditPage::attemptSave';
755 wfProfileIn( $fname );
756 wfProfileIn( "$fname-checks" );
758 if ( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
760 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
761 return self
::AS_HOOK_ERROR
;
764 # Check image redirect
765 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
766 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
767 !$wgUser->isAllowed( 'upload' ) ) {
768 if ( $wgUser->isAnon() ) {
769 return self
::AS_IMAGE_REDIRECT_ANON
;
771 return self
::AS_IMAGE_REDIRECT_LOGGED
;
775 # Reintegrate metadata
776 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
777 $this->mMetaData
= '' ;
780 $match = self
::matchSummarySpamRegex( $this->summary
);
781 if ( $match === false ) {
782 $match = self
::matchSpamRegex( $this->textbox1
);
784 if ( $match !== false ) {
785 $result['spam'] = $match;
787 $pdbk = $this->mTitle
->getPrefixedDBkey();
788 $match = str_replace( "\n", '', $match );
789 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
790 wfProfileOut( "$fname-checks" );
791 wfProfileOut( $fname );
792 return self
::AS_SPAM_ERROR
;
794 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
795 # Error messages or other handling should be performed by the filter function
796 wfProfileOut( "$fname-checks" );
797 wfProfileOut( $fname );
798 return self
::AS_FILTERING
;
800 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
801 # Error messages etc. could be handled within the hook...
802 wfProfileOut( "$fname-checks" );
803 wfProfileOut( $fname );
804 return self
::AS_HOOK_ERROR
;
805 } elseif ( $this->hookError
!= '' ) {
806 # ...or the hook could be expecting us to produce an error
807 wfProfileOut( "$fname-checks" );
808 wfProfileOut( $fname );
809 return self
::AS_HOOK_ERROR_EXPECTED
;
811 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
812 # Check block state against master, thus 'false'.
813 wfProfileOut( "$fname-checks" );
814 wfProfileOut( $fname );
815 return self
::AS_BLOCKED_PAGE_FOR_USER
;
817 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
818 if ( $this->kblength
> $wgMaxArticleSize ) {
819 // Error will be displayed by showEditForm()
820 $this->tooBig
= true;
821 wfProfileOut( "$fname-checks" );
822 wfProfileOut( $fname );
823 return self
::AS_CONTENT_TOO_BIG
;
826 if ( !$wgUser->isAllowed('edit') ) {
827 if ( $wgUser->isAnon() ) {
828 wfProfileOut( "$fname-checks" );
829 wfProfileOut( $fname );
830 return self
::AS_READ_ONLY_PAGE_ANON
;
833 wfProfileOut( "$fname-checks" );
834 wfProfileOut( $fname );
835 return self
::AS_READ_ONLY_PAGE_LOGGED
;
839 if ( wfReadOnly() ) {
840 wfProfileOut( "$fname-checks" );
841 wfProfileOut( $fname );
842 return self
::AS_READ_ONLY_PAGE
;
844 if ( $wgUser->pingLimiter() ) {
845 wfProfileOut( "$fname-checks" );
846 wfProfileOut( $fname );
847 return self
::AS_RATE_LIMITED
;
850 # If the article has been deleted while editing, don't save it without
852 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
853 wfProfileOut( "$fname-checks" );
854 wfProfileOut( $fname );
855 return self
::AS_ARTICLE_WAS_DELETED
;
858 wfProfileOut( "$fname-checks" );
860 # If article is new, insert it.
861 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
863 // Late check for create permission, just in case *PARANOIA*
864 if ( !$this->mTitle
->userCan( 'create' ) ) {
865 wfDebug( "$fname: no create permission\n" );
866 wfProfileOut( $fname );
867 return self
::AS_NO_CREATE_PERMISSION
;
870 # Don't save a new article if it's blank.
871 if ( '' == $this->textbox1
) {
872 wfProfileOut( $fname );
873 return self
::AS_BLANK_ARTICLE
;
876 // Run post-section-merge edit filter
877 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
878 # Error messages etc. could be handled within the hook...
879 wfProfileOut( $fname );
880 return self
::AS_HOOK_ERROR
;
883 # Handle the user preference to force summaries here. Check if it's not a redirect.
884 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
885 if ( md5( $this->summary
) == $this->autoSumm
) {
886 $this->missingSummary
= true;
887 wfProfileOut( $fname );
888 return self
::AS_SUMMARY_NEEDED
;
892 $isComment = ( $this->section
== 'new' );
894 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
895 $this->minoredit
, $this->watchthis
, false, $isComment, $bot );
897 wfProfileOut( $fname );
898 return self
::AS_SUCCESS_NEW_ARTICLE
;
901 # Article exists. Check for edit conflict.
903 $this->mArticle
->clear(); # Force reload of dates, etc.
904 $this->mArticle
->forUpdate( true ); # Lock the article
906 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
908 if ( $this->mArticle
->getTimestamp() != $this->edittime
) {
909 $this->isConflict
= true;
910 if ( $this->section
== 'new' ) {
911 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
912 $this->mArticle
->getComment() == $this->summary
) {
913 // Probably a duplicate submission of a new comment.
914 // This can happen when squid resends a request after
915 // a timeout but the first one actually went through.
916 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
918 // New comment; suppress conflict.
919 $this->isConflict
= false;
920 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
924 $userid = $wgUser->getId();
926 # Suppress edit conflict with self, except for section edits where merging is required.
927 if ( $this->isConflict
&& $this->section
== '' && $this->userWasLastToEdit($userid,$this->edittime
) ) {
928 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
929 $this->isConflict
= false;
932 if ( $this->isConflict
) {
933 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
934 $this->mArticle
->getTimestamp() . "')\n" );
935 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
937 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
938 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
940 if ( is_null( $text ) ) {
941 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
942 $this->isConflict
= true;
943 $text = $this->textbox1
; // do not try to merge here!
944 } else if ( $this->isConflict
) {
946 if ( $this->mergeChangesInto( $text ) ) {
947 // Successful merge! Maybe we should tell the user the good news?
948 $this->isConflict
= false;
949 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
952 $this->textbox1
= $text;
953 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
957 if ( $this->isConflict
) {
958 wfProfileOut( $fname );
959 return self
::AS_CONFLICT_DETECTED
;
962 $oldtext = $this->mArticle
->getContent();
964 // Run post-section-merge edit filter
965 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
966 # Error messages etc. could be handled within the hook...
967 wfProfileOut( $fname );
968 return self
::AS_HOOK_ERROR
;
971 # Handle the user preference to force summaries here, but not for null edits
972 if ( $this->section
!= 'new' && !$this->allowBlankSummary
&& 0 != strcmp($oldtext,$text)
973 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
975 if ( md5( $this->summary
) == $this->autoSumm
) {
976 $this->missingSummary
= true;
977 wfProfileOut( $fname );
978 return self
::AS_SUMMARY_NEEDED
;
982 # And a similar thing for new sections
983 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
984 if (trim($this->summary
) == '') {
985 $this->missingSummary
= true;
986 wfProfileOut( $fname );
987 return self
::AS_SUMMARY_NEEDED
;
992 wfProfileIn( "$fname-sectionanchor" );
994 if ( $this->section
== 'new' ) {
995 if ( $this->textbox1
== '' ) {
996 $this->missingComment
= true;
997 return self
::AS_TEXTBOX_EMPTY
;
999 if ( $this->summary
!= '' ) {
1000 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary
);
1001 # This is a new section, so create a link to the new section
1002 # in the revision summary.
1003 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1004 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1006 } elseif ( $this->section
!= '' ) {
1007 # Try to get a section anchor from the section source, redirect to edited section if header found
1008 # XXX: might be better to integrate this into Article::replaceSection
1009 # for duplicate heading checking and maybe parsing
1010 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1011 # we can't deal with anchors, includes, html etc in the header for now,
1012 # headline would need to be parsed to improve this
1013 if ( $hasmatch and strlen($matches[2]) > 0 ) {
1014 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
1017 wfProfileOut( "$fname-sectionanchor" );
1019 // Save errors may fall down to the edit form, but we've now
1020 // merged the section into full text. Clear the section field
1021 // so that later submission of conflict forms won't try to
1022 // replace that into a duplicated mess.
1023 $this->textbox1
= $text;
1024 $this->section
= '';
1026 // Check for length errors again now that the section is merged in
1027 $this->kblength
= (int)(strlen( $text ) / 1024);
1028 if ( $this->kblength
> $wgMaxArticleSize ) {
1029 $this->tooBig
= true;
1030 wfProfileOut( $fname );
1031 return self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
;
1034 # update the article here
1035 if ( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
1036 $this->watchthis
, $bot, $sectionanchor ) )
1038 wfProfileOut( $fname );
1039 return self
::AS_SUCCESS_UPDATE
;
1041 $this->isConflict
= true;
1043 wfProfileOut( $fname );
1044 return self
::AS_END
;
1048 * Check if no edits were made by other users since
1049 * the time a user started editing the page. Limit to
1050 * 50 revisions for the sake of performance.
1052 protected function userWasLastToEdit( $id, $edittime ) {
1053 if( !$id ) return false;
1054 $dbw = wfGetDB( DB_MASTER
);
1055 $res = $dbw->select( 'revision',
1058 'rev_page' => $this->mArticle
->getId(),
1059 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1062 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1063 while( $row = $res->fetchObject() ) {
1064 if( $row->rev_user
!= $id ) {
1072 * Check given input text against $wgSpamRegex, and return the text of the first match.
1073 * @return mixed -- matching string or false
1075 public static function matchSpamRegex( $text ) {
1076 global $wgSpamRegex;
1077 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1078 $regexes = (array)$wgSpamRegex;
1079 return self
::matchSpamRegexInternal( $text, $regexes );
1083 * Check given input text against $wgSpamRegex, and return the text of the first match.
1084 * @return mixed -- matching string or false
1086 public static function matchSummarySpamRegex( $text ) {
1087 global $wgSummarySpamRegex;
1088 $regexes = (array)$wgSummarySpamRegex;
1089 return self
::matchSpamRegexInternal( $text, $regexes );
1092 protected static function matchSpamRegexInternal( $text, $regexes ) {
1093 foreach( $regexes as $regex ) {
1095 if( preg_match( $regex, $text, $matches ) ) {
1103 * Initialise form fields in the object
1104 * Called on the first invocation, e.g. when a user clicks an edit link
1106 function initialiseForm() {
1107 $this->edittime
= $this->mArticle
->getTimestamp();
1108 $this->textbox1
= $this->getContent( false );
1109 if ( $this->textbox1
=== false ) return false;
1114 function setHeaders() {
1115 global $wgOut, $wgTitle;
1116 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1117 if ( $this->formtype
== 'preview' ) {
1118 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1120 if ( $this->isConflict
) {
1121 $wgOut->setPageTitle( wfMsg( 'editconflict', $wgTitle->getPrefixedText() ) );
1122 } elseif ( $this->section
!= '' ) {
1123 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1124 $wgOut->setPageTitle( wfMsg( $msg, $wgTitle->getPrefixedText() ) );
1126 # Use the title defined by DISPLAYTITLE magic word when present
1127 if ( isset($this->mParserOutput
)
1128 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1131 $title = $wgTitle->getPrefixedText();
1133 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1138 * Send the edit form and related headers to $wgOut
1139 * @param $formCallback Optional callable that takes an OutputPage
1140 * parameter; will be called during form output
1141 * near the top, for captchas and the like.
1143 function showEditForm( $formCallback=null ) {
1144 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle, $wgRequest;
1146 # If $wgTitle is null, that means we're in API mode.
1147 # Some hook probably called this function without checking
1148 # for is_null($wgTitle) first. Bail out right here so we don't
1149 # do lots of work just to discard it right after.
1150 if (is_null($wgTitle))
1153 $fname = 'EditPage::showEditForm';
1154 wfProfileIn( $fname );
1156 $sk = $wgUser->getSkin();
1158 #need to parse the preview early so that we know which templates are used,
1159 #otherwise users with "show preview after edit box" will get a blank list
1160 #we parse this near the beginning so that setHeaders can do the title
1161 #setting work instead of leaving it in getPreviewText
1162 $previewOutput = '';
1163 if ( $this->formtype
== 'preview' ) {
1164 $previewOutput = $this->getPreviewText();
1167 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
1169 $this->setHeaders();
1171 # Enabled article-related sidebar, toplinks, etc.
1172 $wgOut->setArticleRelated( true );
1174 if ( $this->isConflict
) {
1175 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1</div>", 'explainconflict' );
1177 $this->textbox2
= $this->textbox1
;
1178 $this->textbox1
= $this->getContent();
1179 $this->edittime
= $this->mArticle
->getTimestamp();
1181 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1183 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1184 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1
, $matches );
1185 if ( !empty( $matches[2] ) ) {
1187 $this->summary
= "/* " .
1188 $wgParser->stripSectionName(trim($matches[2])) .
1194 if ( $this->missingComment
) {
1195 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1198 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1199 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1202 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1203 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1206 if ( $this->hookError
!== '' ) {
1207 $wgOut->addWikiText( $this->hookError
);
1210 if ( !$this->checkUnicodeCompliantBrowser() ) {
1211 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1213 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1214 // Let sysop know that this will make private content public if saved
1216 if ( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1217 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
1218 } else if ( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1219 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
1222 if ( !$this->mArticle
->mRevision
->isCurrent() ) {
1223 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1224 $wgOut->addWikiMsg( 'editingold' );
1229 if ( wfReadOnly() ) {
1230 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1231 } elseif ( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
1232 $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' );
1234 if ( $this->isCssJsSubpage
) {
1235 # Check the skin exists
1236 if ( $this->isValidCssJsSubpage
) {
1237 if ( $this->formtype
!== 'preview' ) {
1238 $wgOut->addWikiMsg( 'usercssjsyoucanpreview' );
1241 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1246 $classes = array(); // Textarea CSS
1247 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1248 } elseif ( $this->mTitle
->isProtected( 'edit' ) ) {
1249 # Is the title semi-protected?
1250 if ( $this->mTitle
->isSemiProtected() ) {
1251 $noticeMsg = 'semiprotectedpagewarning';
1252 $classes[] = 'mw-textarea-sprotected';
1254 # Then it must be protected based on static groups (regular)
1255 $noticeMsg = 'protectedpagewarning';
1256 $classes[] = 'mw-textarea-protected';
1258 $wgOut->addHTML( "<div class='mw-warning-with-logexcerpt'>\n" );
1259 $wgOut->addWikiMsg( $noticeMsg );
1260 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
->getPrefixedText(), '', 1 );
1261 $wgOut->addHTML( "</div>\n" );
1263 if ( $this->mTitle
->isCascadeProtected() ) {
1264 # Is this page under cascading protection from some source pages?
1265 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1266 $notice = "<div class='mw-cascadeprotectedwarning'>$1\n";
1267 $cascadeSourcesCount = count( $cascadeSources );
1268 if ( $cascadeSourcesCount > 0 ) {
1269 # Explain, and list the titles responsible
1270 foreach( $cascadeSources as $page ) {
1271 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1274 $notice .= '</div>';
1275 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1277 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1278 $wgOut->wrapWikiMsg( '<div class="mw-titleprotectedwarning">$1</div>', 'titleprotectedwarning' );
1281 if ( $this->kblength
=== false ) {
1282 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1284 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1285 $wgOut->addHTML( "<div class='error' id='mw-edit-longpageerror'>\n" );
1286 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) );
1287 $wgOut->addHTML( "</div>\n" );
1288 } elseif ( $this->kblength
> 29 ) {
1289 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1290 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) );
1291 $wgOut->addHTML( "</div>\n" );
1294 $action = $wgTitle->escapeLocalURL( array( 'action' => $this->action
) );
1296 $summary = wfMsgExt( 'summary', 'parseinline' );
1297 $subject = wfMsgExt( 'subject', 'parseinline' );
1299 $cancel = $sk->link(
1301 wfMsgExt( 'cancel', array( 'parseinline' ) ),
1304 array( 'known', 'noclasses' )
1306 $separator = wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1307 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1308 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1309 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1310 htmlspecialchars( wfMsg( 'newwindow' ) );
1312 global $wgRightsText;
1313 if ( $wgRightsText ) {
1314 $copywarnMsg = array( 'copyrightwarning',
1315 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1318 $copywarnMsg = array( 'copyrightwarning2',
1319 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1321 // Allow for site and per-namespace customization of contribution/copyright notice.
1322 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
1324 if ( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1325 # prepare toolbar for edit buttons
1326 $toolbar = EditPage
::getEditToolbar();
1331 // activate checkboxes if user wants them to be always active
1332 if ( !$this->preview
&& !$this->diff
) {
1333 # Sort out the "watch" checkbox
1334 if ( $wgUser->getOption( 'watchdefault' ) ) {
1336 $this->watchthis
= true;
1337 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1339 $this->watchthis
= true;
1340 } elseif ( $this->mTitle
->userIsWatching() ) {
1342 $this->watchthis
= true;
1345 # May be overriden by request parameters
1346 if( $wgRequest->getBool( 'watchthis' ) ) {
1347 $this->watchthis
= true;
1350 if ( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1353 $wgOut->addHTML( $this->editFormPageTop
);
1355 if ( $wgUser->getOption( 'previewontop' ) ) {
1356 $this->displayPreviewArea( $previewOutput, true );
1360 $wgOut->addHTML( $this->editFormTextTop
);
1362 # if this is a comment, show a subject line at the top, which is also the edit summary.
1363 # Otherwise, show a summary field at the bottom
1364 $summarytext = $wgContLang->recodeForEdit( $this->summary
);
1366 # If a blank edit summary was previously provided, and the appropriate
1367 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1368 # user being bounced back more than once in the event that a summary
1371 # For a bit more sophisticated detection of blank summaries, hash the
1372 # automatic one and pass that in the hidden field wpAutoSummary.
1373 $summaryhiddens = '';
1374 if ( $this->missingSummary
) $summaryhiddens .= Xml
::hidden( 'wpIgnoreBlankSummary', true );
1375 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1376 $summaryhiddens .= Xml
::hidden( 'wpAutoSummary', $autosumm );
1377 if ( $this->section
== 'new' ) {
1378 $commentsubject = '';
1379 if ( !$wgRequest->getBool( 'nosummary' ) ) {
1380 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1381 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1384 Xml
::tags( 'label', array( 'for' => 'wpSummary' ), $subject );
1386 Xml
::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1388 $commentsubject .= ' ';
1389 $commentsubject .= Xml
::input( 'wpSummary',
1393 'id' => 'wpSummary',
1394 'maxlength' => '200',
1398 $editsummary = "<div class='editOptions'>\n";
1400 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary
) );
1401 $subjectpreview = $summarytext && $this->preview ?
1402 "<div class=\"mw-summary-preview\">". wfMsgExt('subject-preview', 'parseinline') . $sk->commentBlock( $formattedSummary, $this->mTitle
, true )."</div>\n" : '';
1403 $summarypreview = '';
1405 $commentsubject = '';
1407 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1408 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1410 $editsummary = Xml
::tags( 'label', array( 'for' => 'wpSummary' ), $summary );
1411 $editsummary = Xml
::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1412 $editsummary ) . ' ';
1414 $editsummary .= Xml
::input( 'wpSummary',
1418 'id' => 'wpSummary',
1419 'maxlength' => '200',
1423 // No idea where this is closed.
1424 $editsummary = Xml
::openElement( 'div', array( 'class' => 'editOptions' ) )
1425 . $editsummary . '<br/>';
1427 $summarypreview = '';
1428 if ( $summarytext && $this->preview
) {
1431 array( 'class' => 'mw-summary-preview' ),
1432 wfMsgExt( 'summary-preview', 'parseinline' ) .
1433 $sk->commentBlock( $this->summary
, $this->mTitle
)
1436 $subjectpreview = '';
1438 $commentsubject .= $summaryhiddens;
1440 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1441 if ( !$this->preview
&& !$this->diff
) {
1442 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1444 $templates = $this->getTemplates();
1445 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1447 $hiddencats = $this->mArticle
->getHiddenCategories();
1448 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1450 global $wgUseMetadataEdit ;
1451 if ( $wgUseMetadataEdit ) {
1452 $metadata = $this->mMetaData
;
1453 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1454 $top = wfMsgWikiHtml( 'metadata_help' );
1455 /* ToDo: Replace with clean code */
1456 $ew = $wgUser->getOption( 'editwidth' );
1457 if ( $ew ) $ew = " style=\"width:100%\"";
1459 $cols = $wgUser->getIntOption( 'cols' );
1461 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1463 else $metadata = "" ;
1466 if ( $this->wasDeletedSinceLastEdit() ) {
1467 if ( 'save' != $this->formtype
) {
1468 $wgOut->wrapWikiMsg(
1469 "<div class='error mw-deleted-while-editing'>\n$1</div>",
1470 'deletedwhileediting' );
1472 // Hide the toolbar and edit area, user can click preview to get it back
1473 // Add an confirmation checkbox and explanation.
1475 $recreate = '<div class="mw-confirm-recreate">' .
1476 $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
) ) .
1477 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1478 array( 'title' => $sk->titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1485 $checkboxes = $this->getCheckboxes( $tabindex, $sk,
1486 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1488 $checkboxhtml = implode( $checkboxes, "\n" );
1490 $buttons = $this->getEditButtons( $tabindex );
1491 $buttonshtml = implode( $buttons, "\n" );
1493 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1494 ?
'' : Xml
::hidden( 'safemode', '1' );
1496 $wgOut->addHTML( <<<END
1498 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1502 if ( is_callable( $formCallback ) ) {
1503 call_user_func_array( $formCallback, array( &$wgOut ) );
1506 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1508 // Put these up at the top to ensure they aren't lost on early form submission
1509 $this->showFormBeforeText();
1511 $wgOut->addHTML( <<<END
1515 {$this->editFormTextBeforeContent}
1518 $this->showTextbox1( $classes );
1520 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1521 $wgOut->addHTML( <<<END
1522 {$this->editFormTextAfterWarn}
1532 "<div class='editButtons'>
1534 <span class='editHelp'>{$cancel}{$separator}{$edithelp}</span>
1535 </div><!-- editButtons -->
1536 </div><!-- editOptions -->");
1539 * To make it harder for someone to slip a user a page
1540 * which submits an edit form to the wiki without their
1541 * knowledge, a random token is associated with the login
1542 * session. If it's not passed back with the submission,
1543 * we won't save the page, or render user JavaScript and
1546 * For anon editors, who may not have a session, we just
1547 * include the constant suffix to prevent editing from
1548 * broken text-mangling proxies.
1550 $token = htmlspecialchars( $wgUser->editToken() );
1551 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1553 $this->showTosSummary();
1554 $this->showEditTools();
1556 $wgOut->addHTML( <<<END
1557 {$this->editFormTextAfterTools}
1558 <div class='templatesUsed'>
1559 {$formattedtemplates}
1561 <div class='hiddencats'>
1562 {$formattedhiddencats}
1567 if ( $this->isConflict
&& wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1568 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1570 $de = new DifferenceEngine( $this->mTitle
);
1571 $de->setText( $this->textbox2
, $this->textbox1
);
1572 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1574 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1575 $this->showTextbox2();
1577 $wgOut->addHTML( $this->editFormTextBottom
);
1578 $wgOut->addHTML( "</form>\n" );
1579 if ( !$wgUser->getOption( 'previewontop' ) ) {
1580 $this->displayPreviewArea( $previewOutput, false );
1583 wfProfileOut( $fname );
1586 protected function showFormBeforeText() {
1589 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1590 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1591 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1592 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1595 protected function showTextbox1( $classes ) {
1596 $attribs = array( 'tabindex' => 1 );
1598 if ( $this->wasDeletedSinceLastEdit() )
1599 $attribs['type'] = 'hidden';
1600 if ( !empty($classes) )
1601 $attribs['class'] = implode(' ',$classes);
1603 $this->showTextbox( $this->textbox1
, 'wpTextbox1', $attribs );
1606 protected function showTextbox2() {
1607 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6 ) );
1610 protected function showTextbox( $content, $name, $attribs = array() ) {
1611 global $wgOut, $wgUser;
1613 $wikitext = $this->safeUnicodeOutput( $content );
1614 if ( $wikitext !== '' ) {
1615 // Ensure there's a newline at the end, otherwise adding lines
1617 // But don't add a newline if the ext is empty, or Firefox in XHTML
1618 // mode will show an extra newline. A bit annoying.
1622 $attribs['accesskey'] = ',';
1623 $attribs['id'] = $name;
1625 if ( $wgUser->getOption( 'editwidth' ) )
1626 $attribs['style'] = 'width: 100%';
1628 $wgOut->addHTML( Xml
::textarea(
1631 $wgUser->getIntOption( 'cols' ), $wgUser->getIntOption( 'rows' ),
1635 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1639 $classes[] = 'ontop';
1641 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1643 if ( $this->formtype
!= 'preview' )
1644 $attribs['style'] = 'display: none;';
1646 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
1648 if ( $this->formtype
== 'preview' ) {
1649 $this->showPreview( $previewOutput );
1652 $wgOut->addHTML( '</div>' );
1654 if ( $this->formtype
== 'diff') {
1660 * Append preview output to $wgOut.
1661 * Includes category rendering if this is a category page.
1663 * @param string $text The HTML to be output for the preview.
1665 protected function showPreview( $text ) {
1667 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1668 $this->mArticle
->openShowCategory();
1670 # This hook seems slightly odd here, but makes things more
1671 # consistent for extensions.
1672 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1673 $wgOut->addHTML( $text );
1674 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1675 $this->mArticle
->closeShowCategory();
1680 * Live Preview lets us fetch rendered preview page content and
1681 * add it to the page without refreshing the whole page.
1682 * If not supported by the browser it will fall through to the normal form
1683 * submission method.
1685 * This function outputs a script tag to support live preview, and
1686 * returns an onclick handler which should be added to the attributes
1687 * of the preview button
1689 function doLivePreviewScript() {
1690 global $wgOut, $wgTitle;
1691 $wgOut->addScriptFile( 'preview.js' );
1692 $liveAction = $wgTitle->getLocalUrl( array(
1693 'action' => $this->action
,
1694 'wpPreview' => 'true',
1697 return "return !lpDoPreview(" .
1698 "editform.wpTextbox1.value," .
1699 '"' . $liveAction . '"' . ")";
1702 protected function showTosSummary() {
1703 $msg = 'editpage-tos-summary';
1704 // Give a chance for site and per-namespace customizations of
1705 // terms of service summary link that might exist separately
1706 // from the copyright notice.
1708 // This will display between the save button and the edit tools,
1709 // so should remain short!
1710 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
1711 $text = wfMsg( $msg );
1712 if( !wfEmptyMsg( $msg, $text ) && $text !== '-' ) {
1714 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1715 $wgOut->addWikiMsgArray( $msg, array() );
1716 $wgOut->addHTML( '</div>' );
1720 protected function showEditTools() {
1722 $wgOut->addHTML( '<div class="mw-editTools">' );
1723 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1724 $wgOut->addHTML( '</div>' );
1727 protected function getLastDelete() {
1728 $dbr = wfGetDB( DB_SLAVE
);
1729 $data = $dbr->selectRow(
1730 array( 'logging', 'user' ),
1741 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1742 'log_title' => $this->mTitle
->getDBkey(),
1743 'log_type' => 'delete',
1744 'log_action' => 'delete',
1745 'user_id=log_user' ),
1747 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1749 // Quick paranoid permission checks...
1750 if( is_object($data) ) {
1751 if( $data->log_deleted
& LogPage
::DELETED_USER
)
1752 $data->user_name
= wfMsgHtml('rev-deleted-user');
1753 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
1754 $data->log_comment
= wfMsgHtml('rev-deleted-comment');
1760 * Get the rendered text for previewing.
1763 function getPreviewText() {
1764 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache;
1766 wfProfileIn( __METHOD__
);
1768 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1769 if ( $this->mTokenOkExceptSuffix
) {
1770 $note = wfMsg( 'token_suffix_mismatch' );
1772 $note = wfMsg( 'session_fail_preview' );
1775 $note = wfMsg( 'previewnote' );
1778 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1779 $parserOptions->setEditSection( false );
1780 $parserOptions->setIsPreview( true );
1781 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
1784 if ( $wgRawHtml && !$this->mTokenOk
) {
1785 // Could be an offsite preview attempt. This is very unsafe if
1786 // HTML is enabled, as it could be an attack.
1787 return $wgOut->parse( "<div class='previewnote'>" .
1788 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1791 # don't parse user css/js, show message about preview
1792 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1794 if ( $this->isCssJsSubpage
) {
1795 if (preg_match("/\\.css$/", $this->mTitle
->getText() ) ) {
1796 $previewtext = wfMsg('usercsspreview');
1797 } else if (preg_match("/\\.js$/", $this->mTitle
->getText() ) ) {
1798 $previewtext = wfMsg('userjspreview');
1800 $parserOptions->setTidy(true);
1801 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
1802 $previewHTML = $parserOutput->mText
;
1803 } elseif ( $rt = Title
::newFromRedirectArray( $this->textbox1
) ) {
1804 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
1806 $toparse = $this->textbox1
;
1808 # If we're adding a comment, we need to show the
1809 # summary as the headline
1810 if ( $this->section
=="new" && $this->summary
!="" ) {
1811 $toparse="== {$this->summary} ==\n\n".$toparse;
1814 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1816 // Parse mediawiki messages with correct target language
1817 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1818 list( /* $unused */, $lang ) = $wgMessageCache->figureMessage( $this->mTitle
->getText() );
1819 $obj = wfGetLangObj( $lang );
1820 $parserOptions->setTargetLanguage( $obj );
1824 $parserOptions->setTidy(true);
1825 $parserOptions->enableLimitReport();
1826 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ),
1827 $this->mTitle
, $parserOptions );
1829 $previewHTML = $parserOutput->getText();
1830 $this->mParserOutput
= $parserOutput;
1831 $wgOut->addParserOutputNoText( $parserOutput );
1833 if ( count( $parserOutput->getWarnings() ) ) {
1834 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1838 if( $this->isConflict
) {
1839 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1841 $conflict = '<hr />';
1844 $previewhead = "<div class='previewnote'>\n" .
1845 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
1846 $wgOut->parse( $note ) . $conflict . "</div>\n";
1848 wfProfileOut( __METHOD__
);
1849 return $previewhead . $previewHTML;
1852 function getTemplates() {
1853 if ( $this->preview ||
$this->section
!= '' ) {
1854 $templates = array();
1855 if ( !isset($this->mParserOutput
) ) return $templates;
1856 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
1857 foreach( array_keys( $template ) as $dbk ) {
1858 $templates[] = Title
::makeTitle($ns, $dbk);
1863 return $this->mArticle
->getUsedTemplates();
1868 * Call the stock "user is blocked" page
1870 function blockedPage() {
1871 global $wgOut, $wgUser;
1872 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1874 # If the user made changes, preserve them when showing the markup
1875 # (This happens when a user is blocked during edit, for instance)
1876 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1878 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1880 $source = $this->textbox1
;
1883 # Spit out the source or the user's modified version
1884 if ( $source !== false ) {
1885 $rows = $wgUser->getIntOption( 'rows' );
1886 $cols = $wgUser->getIntOption( 'cols' );
1887 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1888 $wgOut->addHTML( '<hr />' );
1889 $wgOut->addWikiMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() );
1890 # Why we don't use Xml::element here?
1891 # Is it because if $source is '', it returns <textarea />?
1892 $wgOut->addHTML( Xml
::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml
::closeElement( 'textarea' ) );
1897 * Produce the stock "please login to edit pages" page
1899 function userNotLoggedInPage() {
1900 global $wgUser, $wgOut, $wgTitle;
1901 $skin = $wgUser->getSkin();
1903 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1904 $loginLink = $skin->link(
1906 wfMsgHtml( 'loginreqlink' ),
1908 array( 'returnto' => $wgTitle->getPrefixedText() ),
1909 array( 'known', 'noclasses' )
1912 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1913 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1914 $wgOut->setArticleRelated( false );
1916 $wgOut->addHTML( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1917 $wgOut->returnToMain( false, $wgTitle );
1921 * Creates a basic error page which informs the user that
1922 * they have attempted to edit a nonexistent section.
1924 function noSuchSectionPage() {
1925 global $wgOut, $wgTitle;
1927 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1928 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1929 $wgOut->setArticleRelated( false );
1931 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section
);
1932 $wgOut->returnToMain( false, $wgTitle );
1936 * Produce the stock "your edit contains spam" page
1938 * @param $match Text which triggered one or more filters
1940 function spamPage( $match = false ) {
1941 global $wgOut, $wgTitle;
1943 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1944 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1945 $wgOut->setArticleRelated( false );
1947 $wgOut->addHTML( '<div id="spamprotected">' );
1948 $wgOut->addWikiMsg( 'spamprotectiontext' );
1950 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1951 $wgOut->addHTML( '</div>' );
1953 $wgOut->returnToMain( false, $wgTitle );
1960 function mergeChangesInto( &$editText ){
1961 $fname = 'EditPage::mergeChangesInto';
1962 wfProfileIn( $fname );
1964 $db = wfGetDB( DB_MASTER
);
1966 // This is the revision the editor started from
1967 $baseRevision = $this->getBaseRevision();
1968 if ( is_null( $baseRevision ) ) {
1969 wfProfileOut( $fname );
1972 $baseText = $baseRevision->getText();
1974 // The current state, we want to merge updates into it
1975 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1976 if ( is_null( $currentRevision ) ) {
1977 wfProfileOut( $fname );
1980 $currentText = $currentRevision->getText();
1983 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1984 $editText = $result;
1985 wfProfileOut( $fname );
1988 wfProfileOut( $fname );
1994 * Check if the browser is on a blacklist of user-agents known to
1995 * mangle UTF-8 data on form submission. Returns true if Unicode
1996 * should make it through, false if it's known to be a problem.
2000 function checkUnicodeCompliantBrowser() {
2001 global $wgBrowserBlackList;
2002 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2003 // No User-Agent header sent? Trust it by default...
2006 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2007 foreach ( $wgBrowserBlackList as $browser ) {
2008 if ( preg_match($browser, $currentbrowser) ) {
2016 * @deprecated use $wgParser->stripSectionName()
2018 function pseudoParseSectionAnchor( $text ) {
2020 return $wgParser->stripSectionName( $text );
2024 * Format an anchor fragment as it would appear for a given section name
2025 * @param string $text
2029 function sectionAnchor( $text ) {
2031 return $wgParser->guessSectionNameFromWikiText( $text );
2035 * Shows a bulletin board style toolbar for common editing functions.
2036 * It can be disabled in the user preferences.
2037 * The necessary JavaScript code can be found in skins/common/edit.js.
2041 static function getEditToolbar() {
2042 global $wgStylePath, $wgContLang, $wgLang, $wgJsMimeType;
2045 * toolarray an array of arrays which each include the filename of
2046 * the button image (without path), the opening tag, the closing tag,
2047 * and optionally a sample text that is inserted between the two when no
2048 * selection is highlighted.
2049 * The tip text is shown when the user moves the mouse over the button.
2051 * Already here are accesskeys (key), which are not used yet until someone
2052 * can figure out a way to make them work in IE. However, we should make
2053 * sure these keys are not defined on the edit page.
2057 'image' => $wgLang->getImageFile('button-bold'),
2058 'id' => 'mw-editbutton-bold',
2060 'close' => '\'\'\'',
2061 'sample' => wfMsg('bold_sample'),
2062 'tip' => wfMsg('bold_tip'),
2066 'image' => $wgLang->getImageFile('button-italic'),
2067 'id' => 'mw-editbutton-italic',
2070 'sample' => wfMsg('italic_sample'),
2071 'tip' => wfMsg('italic_tip'),
2075 'image' => $wgLang->getImageFile('button-link'),
2076 'id' => 'mw-editbutton-link',
2079 'sample' => wfMsg('link_sample'),
2080 'tip' => wfMsg('link_tip'),
2084 'image' => $wgLang->getImageFile('button-extlink'),
2085 'id' => 'mw-editbutton-extlink',
2088 'sample' => wfMsg('extlink_sample'),
2089 'tip' => wfMsg('extlink_tip'),
2093 'image' => $wgLang->getImageFile('button-headline'),
2094 'id' => 'mw-editbutton-headline',
2097 'sample' => wfMsg('headline_sample'),
2098 'tip' => wfMsg('headline_tip'),
2102 'image' => $wgLang->getImageFile('button-image'),
2103 'id' => 'mw-editbutton-image',
2104 'open' => '[['.$wgContLang->getNsText(NS_FILE
).':',
2106 'sample' => wfMsg('image_sample'),
2107 'tip' => wfMsg('image_tip'),
2111 'image' => $wgLang->getImageFile('button-media'),
2112 'id' => 'mw-editbutton-media',
2113 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
2115 'sample' => wfMsg('media_sample'),
2116 'tip' => wfMsg('media_tip'),
2120 'image' => $wgLang->getImageFile('button-math'),
2121 'id' => 'mw-editbutton-math',
2123 'close' => "</math>",
2124 'sample' => wfMsg('math_sample'),
2125 'tip' => wfMsg('math_tip'),
2129 'image' => $wgLang->getImageFile('button-nowiki'),
2130 'id' => 'mw-editbutton-nowiki',
2131 'open' => "<nowiki>",
2132 'close' => "</nowiki>",
2133 'sample' => wfMsg('nowiki_sample'),
2134 'tip' => wfMsg('nowiki_tip'),
2138 'image' => $wgLang->getImageFile('button-sig'),
2139 'id' => 'mw-editbutton-signature',
2143 'tip' => wfMsg('sig_tip'),
2147 'image' => $wgLang->getImageFile('button-hr'),
2148 'id' => 'mw-editbutton-hr',
2149 'open' => "\n----\n",
2152 'tip' => wfMsg('hr_tip'),
2156 $toolbar = "<div id='toolbar'>\n";
2157 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
2159 foreach($toolarray as $tool) {
2161 $image = $wgStylePath.'/common/images/'.$tool['image'],
2162 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2163 // Older browsers show a "speedtip" type message only for ALT.
2164 // Ideally these should be different, realistically they
2165 // probably don't need to be.
2166 $tip = $tool['tip'],
2167 $open = $tool['open'],
2168 $close = $tool['close'],
2169 $sample = $tool['sample'],
2170 $cssId = $tool['id'],
2173 $paramList = implode( ',',
2174 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2175 $toolbar.="addButton($paramList);\n";
2178 $toolbar.="/*]]>*/\n</script>";
2179 $toolbar.="\n</div>";
2181 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2187 * Returns an array of html code of the following checkboxes:
2190 * @param $tabindex Current tabindex
2191 * @param $skin Skin object
2192 * @param $checked Array of checkbox => bool, where bool indicates the checked
2193 * status of the checkbox
2197 public function getCheckboxes( &$tabindex, $skin, $checked ) {
2200 $checkboxes = array();
2202 $checkboxes['minor'] = '';
2203 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
2204 if ( $wgUser->isAllowed('minoredit') ) {
2206 'tabindex' => ++
$tabindex,
2207 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2208 'id' => 'wpMinoredit',
2210 $checkboxes['minor'] =
2211 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2212 " <label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
2215 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2216 $checkboxes['watch'] = '';
2217 if ( $wgUser->isLoggedIn() ) {
2219 'tabindex' => ++
$tabindex,
2220 'accesskey' => wfMsg( 'accesskey-watch' ),
2221 'id' => 'wpWatchthis',
2223 $checkboxes['watch'] =
2224 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2225 " <label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
2227 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2232 * Returns an array of html code of the following buttons:
2233 * save, diff, preview and live
2235 * @param $tabindex Current tabindex
2239 public function getEditButtons(&$tabindex) {
2240 global $wgLivePreview, $wgUser;
2248 'tabindex' => ++
$tabindex,
2249 'value' => wfMsg('savearticle'),
2250 'accesskey' => wfMsg('accesskey-save'),
2251 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2253 $buttons['save'] = Xml
::element('input', $temp, '');
2255 ++
$tabindex; // use the same for preview and live preview
2256 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2258 'id' => 'wpPreview',
2259 'name' => 'wpPreview',
2261 'tabindex' => $tabindex,
2262 'value' => wfMsg('showpreview'),
2264 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2265 'style' => 'display: none;',
2267 $buttons['preview'] = Xml
::element('input', $temp, '');
2270 'id' => 'wpLivePreview',
2271 'name' => 'wpLivePreview',
2273 'tabindex' => $tabindex,
2274 'value' => wfMsg('showlivepreview'),
2275 'accesskey' => wfMsg('accesskey-preview'),
2277 'onclick' => $this->doLivePreviewScript(),
2279 $buttons['live'] = Xml
::element('input', $temp, '');
2282 'id' => 'wpPreview',
2283 'name' => 'wpPreview',
2285 'tabindex' => $tabindex,
2286 'value' => wfMsg('showpreview'),
2287 'accesskey' => wfMsg('accesskey-preview'),
2288 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2290 $buttons['preview'] = Xml
::element('input', $temp, '');
2291 $buttons['live'] = '';
2298 'tabindex' => ++
$tabindex,
2299 'value' => wfMsg('showdiff'),
2300 'accesskey' => wfMsg('accesskey-diff'),
2301 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2303 $buttons['diff'] = Xml
::element('input', $temp, '');
2305 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2310 * Output preview text only. This can be sucked into the edit page
2311 * via JavaScript, and saves the server time rendering the skin as
2312 * well as theoretically being more robust on the client (doesn't
2313 * disturb the edit box's undo history, won't eat your text on
2316 * @todo This doesn't include category or interlanguage links.
2317 * Would need to enhance it a bit, <s>maybe wrap them in XML
2318 * or something...</s> that might also require more skin
2319 * initialization, so check whether that's a problem.
2321 function livePreview() {
2324 header( 'Content-type: text/xml; charset=utf-8' );
2325 header( 'Cache-control: no-cache' );
2327 $previewText = $this->getPreviewText();
2328 #$categories = $skin->getCategoryLinks();
2331 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2332 Xml
::tags( 'livepreview', null,
2333 Xml
::element( 'preview', null, $previewText )
2334 #. Xml::element( 'category', null, $categories )
2341 * Get a diff between the current contents of the edit box and the
2342 * version of the page we're editing from.
2344 * If this is a section edit, we'll replace the section as for final
2345 * save and then make a comparison.
2347 function showDiff() {
2348 $oldtext = $this->mArticle
->fetchContent();
2349 $newtext = $this->mArticle
->replaceSection(
2350 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2351 $newtext = $this->mArticle
->preSaveTransform( $newtext );
2352 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2353 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2354 if ( $oldtext !== false ||
$newtext != '' ) {
2355 $de = new DifferenceEngine( $this->mTitle
);
2356 $de->setText( $oldtext, $newtext );
2357 $difftext = $de->getDiff( $oldtitle, $newtitle );
2358 $de->showDiffStyle();
2364 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2368 * Filter an input field through a Unicode de-armoring process if it
2369 * came from an old browser with known broken Unicode editing issues.
2371 * @param WebRequest $request
2372 * @param string $field
2376 function safeUnicodeInput( $request, $field ) {
2377 $text = rtrim( $request->getText( $field ) );
2378 return $request->getBool( 'safemode' )
2379 ?
$this->unmakesafe( $text )
2384 * Filter an output field through a Unicode armoring process if it is
2385 * going to an old browser with known broken Unicode editing issues.
2387 * @param string $text
2391 function safeUnicodeOutput( $text ) {
2393 $codedText = $wgContLang->recodeForEdit( $text );
2394 return $this->checkUnicodeCompliantBrowser()
2396 : $this->makesafe( $codedText );
2400 * A number of web browsers are known to corrupt non-ASCII characters
2401 * in a UTF-8 text editing environment. To protect against this,
2402 * detected browsers will be served an armored version of the text,
2403 * with non-ASCII chars converted to numeric HTML character references.
2405 * Preexisting such character references will have a 0 added to them
2406 * to ensure that round-trips do not alter the original data.
2408 * @param string $invalue
2412 function makesafe( $invalue ) {
2413 // Armor existing references for reversability.
2414 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2419 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2420 $bytevalue = ord( $invalue{$i} );
2421 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2422 $result .= chr( $bytevalue );
2424 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2425 $working = $working << 6;
2426 $working +
= ($bytevalue & 0x3F);
2428 if ( $bytesleft <= 0 ) {
2429 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2431 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2432 $working = $bytevalue & 0x1F;
2434 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2435 $working = $bytevalue & 0x0F;
2437 } else { //1111 0xxx
2438 $working = $bytevalue & 0x07;
2446 * Reverse the previously applied transliteration of non-ASCII characters
2447 * back to UTF-8. Used to protect data from corruption by broken web browsers
2448 * as listed in $wgBrowserBlackList.
2450 * @param string $invalue
2454 function unmakesafe( $invalue ) {
2456 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2457 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2461 $hexstring .= $invalue{$i};
2463 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2465 // Do some sanity checks. These aren't needed for reversability,
2466 // but should help keep the breakage down if the editor
2467 // breaks one of the entities whilst editing.
2468 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2469 $codepoint = hexdec($hexstring);
2470 $result .= codepointToUtf8( $codepoint );
2472 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2475 $result .= substr( $invalue, $i, 1 );
2478 // reverse the transform that we made for reversability reasons.
2479 return strtr( $result, array( "�" => "&#x" ) );
2482 function noCreatePermission() {
2484 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2485 $wgOut->addWikiMsg( 'nocreatetext' );
2489 * If there are rows in the deletion/move log for this page, show them,
2490 * along with a nice little note for the user
2492 * @param OutputPage $out
2494 protected function showLogs( $out ) {
2496 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
2497 $pager = new LogPager( $loglist, array('move', 'delete'), false,
2498 $this->mTitle
->getPrefixedText(), '', array( "log_action != 'revision'" ) );
2500 $count = $pager->getNumRows();
2502 $pager->mLimit
= 10;
2503 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
2504 $out->addWikiMsg( 'recreate-moveddeleted-warn' );
2506 $loglist->beginLogEventsList() .
2508 $loglist->endLogEventsList()
2511 $out->addHTML( $wgUser->getSkin()->link(
2512 SpecialPage
::getTitleFor( 'Log' ),
2513 wfMsgHtml( 'log-fulllog' ),
2515 array( 'page' => $this->mTitle
->getPrefixedText() ) ) );
2517 $out->addHTML( '</div>' );
2525 * Attempt submission
2526 * @return bool false if output is done, true if the rest of the form should be displayed
2528 function attemptSave() {
2529 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2531 $resultDetails = false;
2532 # Allow bots to exempt some edits from bot flagging
2533 $bot = $wgUser->isAllowed('bot') && $wgRequest->getBool('bot',true);
2534 $value = $this->internalAttemptSave( $resultDetails, $bot );
2536 if ( $value == self
::AS_SUCCESS_UPDATE ||
$value == self
::AS_SUCCESS_NEW_ARTICLE
) {
2537 $this->didSave
= true;
2541 case self
::AS_HOOK_ERROR_EXPECTED
:
2542 case self
::AS_CONTENT_TOO_BIG
:
2543 case self
::AS_ARTICLE_WAS_DELETED
:
2544 case self
::AS_CONFLICT_DETECTED
:
2545 case self
::AS_SUMMARY_NEEDED
:
2546 case self
::AS_TEXTBOX_EMPTY
:
2547 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
2551 case self
::AS_HOOK_ERROR
:
2552 case self
::AS_FILTERING
:
2553 case self
::AS_SUCCESS_NEW_ARTICLE
:
2554 case self
::AS_SUCCESS_UPDATE
:
2557 case self
::AS_SPAM_ERROR
:
2558 $this->spamPage ( $resultDetails['spam'] );
2561 case self
::AS_BLOCKED_PAGE_FOR_USER
:
2562 $this->blockedPage();
2565 case self
::AS_IMAGE_REDIRECT_ANON
:
2566 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2569 case self
::AS_READ_ONLY_PAGE_ANON
:
2570 $this->userNotLoggedInPage();
2573 case self
::AS_READ_ONLY_PAGE_LOGGED
:
2574 case self
::AS_READ_ONLY_PAGE
:
2575 $wgOut->readOnlyPage();
2578 case self
::AS_RATE_LIMITED
:
2579 $wgOut->rateLimited();
2582 case self
::AS_NO_CREATE_PERMISSION
;
2583 $this->noCreatePermission();
2586 case self
::AS_BLANK_ARTICLE
:
2587 $wgOut->redirect( $wgTitle->getFullURL() );
2590 case self
::AS_IMAGE_REDIRECT_LOGGED
:
2591 $wgOut->permissionRequired( 'upload' );
2596 function getBaseRevision() {
2597 if ( $this->mBaseRevision
== false ) {
2598 $db = wfGetDB( DB_MASTER
);
2599 $baseRevision = Revision
::loadFromTimestamp(
2600 $db, $this->mTitle
, $this->edittime
);
2601 return $this->mBaseRevision
= $baseRevision;
2603 return $this->mBaseRevision
;