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 );
668 // Allow extensions to modify form data
669 wfRunHooks( 'EditPage::importFormData', array( &$this, $request ) );
673 * Make sure the form isn't faking a user's credentials.
675 * @param $request WebRequest
679 function tokenOk( &$request ) {
681 $token = $request->getVal( 'wpEditToken' );
682 $this->mTokenOk
= $wgUser->matchEditToken( $token );
683 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
684 return $this->mTokenOk
;
688 * Show all applicable editing introductions
690 protected function showIntro() {
691 global $wgOut, $wgUser;
692 if ( $this->suppressIntro
) {
696 $namespace = $this->mTitle
->getNamespace();
698 if ( $namespace == NS_MEDIAWIKI
) {
699 # Show a warning if editing an interface message
700 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1</div>", 'editinginterface' );
703 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
704 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
705 $parts = explode( '/', $this->mTitle
->getText(), 2 );
706 $username = $parts[0];
707 $id = User
::idFromName( $username );
708 $ip = User
::isIP( $username );
709 if ( $id == 0 && !$ip ) {
710 $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
711 array( 'userpage-userdoesnotexist', $username ) );
714 # Try to add a custom edit intro, or use the standard one if this is not possible.
715 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
716 if ( $wgUser->isLoggedIn() ) {
717 $wgOut->wrapWikiMsg( '<div class="mw-newarticletext">$1</div>', 'newarticletext' );
719 $wgOut->wrapWikiMsg( '<div class="mw-newarticletextanon">$1</div>', 'newarticletextanon' );
722 # Give a notice if the user is editing a deleted/moved page...
723 if ( !$this->mTitle
->exists() ) {
724 $this->showLogs( $wgOut );
729 * Attempt to show a custom editing introduction, if supplied
733 protected function showCustomIntro() {
734 if ( $this->editintro
) {
735 $title = Title
::newFromText( $this->editintro
);
736 if ( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
738 $revision = Revision
::newFromTitle( $title );
739 $wgOut->addWikiTextTitleTidy( $revision->getText(), $this->mTitle
);
750 * Attempt submission (no UI)
751 * @return one of the constants describing the result
753 function internalAttemptSave( &$result, $bot = false ) {
754 global $wgFilterCallback, $wgUser, $wgOut, $wgParser;
755 global $wgMaxArticleSize;
757 $fname = 'EditPage::attemptSave';
758 wfProfileIn( $fname );
759 wfProfileIn( "$fname-checks" );
761 if ( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
763 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
764 return self
::AS_HOOK_ERROR
;
767 # Check image redirect
768 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
769 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
770 !$wgUser->isAllowed( 'upload' ) ) {
771 if ( $wgUser->isAnon() ) {
772 return self
::AS_IMAGE_REDIRECT_ANON
;
774 return self
::AS_IMAGE_REDIRECT_LOGGED
;
778 # Reintegrate metadata
779 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
780 $this->mMetaData
= '' ;
783 $match = self
::matchSummarySpamRegex( $this->summary
);
784 if ( $match === false ) {
785 $match = self
::matchSpamRegex( $this->textbox1
);
787 if ( $match !== false ) {
788 $result['spam'] = $match;
790 $pdbk = $this->mTitle
->getPrefixedDBkey();
791 $match = str_replace( "\n", '', $match );
792 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
793 wfProfileOut( "$fname-checks" );
794 wfProfileOut( $fname );
795 return self
::AS_SPAM_ERROR
;
797 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
798 # Error messages or other handling should be performed by the filter function
799 wfProfileOut( "$fname-checks" );
800 wfProfileOut( $fname );
801 return self
::AS_FILTERING
;
803 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
804 # Error messages etc. could be handled within the hook...
805 wfProfileOut( "$fname-checks" );
806 wfProfileOut( $fname );
807 return self
::AS_HOOK_ERROR
;
808 } elseif ( $this->hookError
!= '' ) {
809 # ...or the hook could be expecting us to produce an error
810 wfProfileOut( "$fname-checks" );
811 wfProfileOut( $fname );
812 return self
::AS_HOOK_ERROR_EXPECTED
;
814 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
815 # Check block state against master, thus 'false'.
816 wfProfileOut( "$fname-checks" );
817 wfProfileOut( $fname );
818 return self
::AS_BLOCKED_PAGE_FOR_USER
;
820 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
821 if ( $this->kblength
> $wgMaxArticleSize ) {
822 // Error will be displayed by showEditForm()
823 $this->tooBig
= true;
824 wfProfileOut( "$fname-checks" );
825 wfProfileOut( $fname );
826 return self
::AS_CONTENT_TOO_BIG
;
829 if ( !$wgUser->isAllowed('edit') ) {
830 if ( $wgUser->isAnon() ) {
831 wfProfileOut( "$fname-checks" );
832 wfProfileOut( $fname );
833 return self
::AS_READ_ONLY_PAGE_ANON
;
836 wfProfileOut( "$fname-checks" );
837 wfProfileOut( $fname );
838 return self
::AS_READ_ONLY_PAGE_LOGGED
;
842 if ( wfReadOnly() ) {
843 wfProfileOut( "$fname-checks" );
844 wfProfileOut( $fname );
845 return self
::AS_READ_ONLY_PAGE
;
847 if ( $wgUser->pingLimiter() ) {
848 wfProfileOut( "$fname-checks" );
849 wfProfileOut( $fname );
850 return self
::AS_RATE_LIMITED
;
853 # If the article has been deleted while editing, don't save it without
855 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
856 wfProfileOut( "$fname-checks" );
857 wfProfileOut( $fname );
858 return self
::AS_ARTICLE_WAS_DELETED
;
861 wfProfileOut( "$fname-checks" );
863 # If article is new, insert it.
864 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
866 // Late check for create permission, just in case *PARANOIA*
867 if ( !$this->mTitle
->userCan( 'create' ) ) {
868 wfDebug( "$fname: no create permission\n" );
869 wfProfileOut( $fname );
870 return self
::AS_NO_CREATE_PERMISSION
;
873 # Don't save a new article if it's blank.
874 if ( '' == $this->textbox1
) {
875 wfProfileOut( $fname );
876 return self
::AS_BLANK_ARTICLE
;
879 // Run post-section-merge edit filter
880 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
881 # Error messages etc. could be handled within the hook...
882 wfProfileOut( $fname );
883 return self
::AS_HOOK_ERROR
;
886 # Handle the user preference to force summaries here. Check if it's not a redirect.
887 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
888 if ( md5( $this->summary
) == $this->autoSumm
) {
889 $this->missingSummary
= true;
890 wfProfileOut( $fname );
891 return self
::AS_SUMMARY_NEEDED
;
895 $isComment = ( $this->section
== 'new' );
897 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
898 $this->minoredit
, $this->watchthis
, false, $isComment, $bot );
900 wfProfileOut( $fname );
901 return self
::AS_SUCCESS_NEW_ARTICLE
;
904 # Article exists. Check for edit conflict.
906 $this->mArticle
->clear(); # Force reload of dates, etc.
907 $this->mArticle
->forUpdate( true ); # Lock the article
909 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
911 if ( $this->mArticle
->getTimestamp() != $this->edittime
) {
912 $this->isConflict
= true;
913 if ( $this->section
== 'new' ) {
914 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
915 $this->mArticle
->getComment() == $this->summary
) {
916 // Probably a duplicate submission of a new comment.
917 // This can happen when squid resends a request after
918 // a timeout but the first one actually went through.
919 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
921 // New comment; suppress conflict.
922 $this->isConflict
= false;
923 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
927 $userid = $wgUser->getId();
929 # Suppress edit conflict with self, except for section edits where merging is required.
930 if ( $this->isConflict
&& $this->section
== '' && $this->userWasLastToEdit($userid,$this->edittime
) ) {
931 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
932 $this->isConflict
= false;
935 if ( $this->isConflict
) {
936 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
937 $this->mArticle
->getTimestamp() . "')\n" );
938 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
940 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
941 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
943 if ( is_null( $text ) ) {
944 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
945 $this->isConflict
= true;
946 $text = $this->textbox1
; // do not try to merge here!
947 } else if ( $this->isConflict
) {
949 if ( $this->mergeChangesInto( $text ) ) {
950 // Successful merge! Maybe we should tell the user the good news?
951 $this->isConflict
= false;
952 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
955 $this->textbox1
= $text;
956 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
960 if ( $this->isConflict
) {
961 wfProfileOut( $fname );
962 return self
::AS_CONFLICT_DETECTED
;
965 $oldtext = $this->mArticle
->getContent();
967 // Run post-section-merge edit filter
968 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
969 # Error messages etc. could be handled within the hook...
970 wfProfileOut( $fname );
971 return self
::AS_HOOK_ERROR
;
974 # Handle the user preference to force summaries here, but not for null edits
975 if ( $this->section
!= 'new' && !$this->allowBlankSummary
&& 0 != strcmp($oldtext,$text)
976 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
978 if ( md5( $this->summary
) == $this->autoSumm
) {
979 $this->missingSummary
= true;
980 wfProfileOut( $fname );
981 return self
::AS_SUMMARY_NEEDED
;
985 # And a similar thing for new sections
986 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
987 if (trim($this->summary
) == '') {
988 $this->missingSummary
= true;
989 wfProfileOut( $fname );
990 return self
::AS_SUMMARY_NEEDED
;
995 wfProfileIn( "$fname-sectionanchor" );
997 if ( $this->section
== 'new' ) {
998 if ( $this->textbox1
== '' ) {
999 $this->missingComment
= true;
1000 return self
::AS_TEXTBOX_EMPTY
;
1002 if ( $this->summary
!= '' ) {
1003 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary
);
1004 # This is a new section, so create a link to the new section
1005 # in the revision summary.
1006 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1007 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1009 } elseif ( $this->section
!= '' ) {
1010 # Try to get a section anchor from the section source, redirect to edited section if header found
1011 # XXX: might be better to integrate this into Article::replaceSection
1012 # for duplicate heading checking and maybe parsing
1013 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1014 # we can't deal with anchors, includes, html etc in the header for now,
1015 # headline would need to be parsed to improve this
1016 if ( $hasmatch and strlen($matches[2]) > 0 ) {
1017 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
1020 wfProfileOut( "$fname-sectionanchor" );
1022 // Save errors may fall down to the edit form, but we've now
1023 // merged the section into full text. Clear the section field
1024 // so that later submission of conflict forms won't try to
1025 // replace that into a duplicated mess.
1026 $this->textbox1
= $text;
1027 $this->section
= '';
1029 // Check for length errors again now that the section is merged in
1030 $this->kblength
= (int)(strlen( $text ) / 1024);
1031 if ( $this->kblength
> $wgMaxArticleSize ) {
1032 $this->tooBig
= true;
1033 wfProfileOut( $fname );
1034 return self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
;
1037 # update the article here
1038 if ( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
1039 $this->watchthis
, $bot, $sectionanchor ) )
1041 wfProfileOut( $fname );
1042 return self
::AS_SUCCESS_UPDATE
;
1044 $this->isConflict
= true;
1046 wfProfileOut( $fname );
1047 return self
::AS_END
;
1051 * Check if no edits were made by other users since
1052 * the time a user started editing the page. Limit to
1053 * 50 revisions for the sake of performance.
1055 protected function userWasLastToEdit( $id, $edittime ) {
1056 if( !$id ) return false;
1057 $dbw = wfGetDB( DB_MASTER
);
1058 $res = $dbw->select( 'revision',
1061 'rev_page' => $this->mArticle
->getId(),
1062 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1065 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1066 while( $row = $res->fetchObject() ) {
1067 if( $row->rev_user
!= $id ) {
1075 * Check given input text against $wgSpamRegex, and return the text of the first match.
1076 * @return mixed -- matching string or false
1078 public static function matchSpamRegex( $text ) {
1079 global $wgSpamRegex;
1080 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1081 $regexes = (array)$wgSpamRegex;
1082 return self
::matchSpamRegexInternal( $text, $regexes );
1086 * Check given input text against $wgSpamRegex, and return the text of the first match.
1087 * @return mixed -- matching string or false
1089 public static function matchSummarySpamRegex( $text ) {
1090 global $wgSummarySpamRegex;
1091 $regexes = (array)$wgSummarySpamRegex;
1092 return self
::matchSpamRegexInternal( $text, $regexes );
1095 protected static function matchSpamRegexInternal( $text, $regexes ) {
1096 foreach( $regexes as $regex ) {
1098 if( preg_match( $regex, $text, $matches ) ) {
1106 * Initialise form fields in the object
1107 * Called on the first invocation, e.g. when a user clicks an edit link
1109 function initialiseForm() {
1110 $this->edittime
= $this->mArticle
->getTimestamp();
1111 $this->textbox1
= $this->getContent( false );
1112 if ( $this->textbox1
=== false ) return false;
1117 function setHeaders() {
1118 global $wgOut, $wgTitle;
1119 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1120 if ( $this->formtype
== 'preview' ) {
1121 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1123 if ( $this->isConflict
) {
1124 $wgOut->setPageTitle( wfMsg( 'editconflict', $wgTitle->getPrefixedText() ) );
1125 } elseif ( $this->section
!= '' ) {
1126 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1127 $wgOut->setPageTitle( wfMsg( $msg, $wgTitle->getPrefixedText() ) );
1129 # Use the title defined by DISPLAYTITLE magic word when present
1130 if ( isset($this->mParserOutput
)
1131 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1134 $title = $wgTitle->getPrefixedText();
1136 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1141 * Send the edit form and related headers to $wgOut
1142 * @param $formCallback Optional callable that takes an OutputPage
1143 * parameter; will be called during form output
1144 * near the top, for captchas and the like.
1146 function showEditForm( $formCallback=null ) {
1147 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle, $wgRequest;
1149 # If $wgTitle is null, that means we're in API mode.
1150 # Some hook probably called this function without checking
1151 # for is_null($wgTitle) first. Bail out right here so we don't
1152 # do lots of work just to discard it right after.
1153 if (is_null($wgTitle))
1156 $fname = 'EditPage::showEditForm';
1157 wfProfileIn( $fname );
1159 $sk = $wgUser->getSkin();
1161 #need to parse the preview early so that we know which templates are used,
1162 #otherwise users with "show preview after edit box" will get a blank list
1163 #we parse this near the beginning so that setHeaders can do the title
1164 #setting work instead of leaving it in getPreviewText
1165 $previewOutput = '';
1166 if ( $this->formtype
== 'preview' ) {
1167 $previewOutput = $this->getPreviewText();
1170 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
1172 $this->setHeaders();
1174 # Enabled article-related sidebar, toplinks, etc.
1175 $wgOut->setArticleRelated( true );
1177 if ( $this->isConflict
) {
1178 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1</div>", 'explainconflict' );
1180 $this->textbox2
= $this->textbox1
;
1181 $this->textbox1
= $this->getContent();
1182 $this->edittime
= $this->mArticle
->getTimestamp();
1184 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1186 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1187 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1
, $matches );
1188 if ( !empty( $matches[2] ) ) {
1190 $this->summary
= "/* " .
1191 $wgParser->stripSectionName(trim($matches[2])) .
1197 if ( $this->missingComment
) {
1198 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1201 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1202 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1205 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1206 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1209 if ( $this->hookError
!== '' ) {
1210 $wgOut->addWikiText( $this->hookError
);
1213 if ( !$this->checkUnicodeCompliantBrowser() ) {
1214 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1216 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1217 // Let sysop know that this will make private content public if saved
1219 if ( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1220 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
1221 } else if ( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1222 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
1225 if ( !$this->mArticle
->mRevision
->isCurrent() ) {
1226 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1227 $wgOut->addWikiMsg( 'editingold' );
1232 if ( wfReadOnly() ) {
1233 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1234 } elseif ( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
1235 $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' );
1237 if ( $this->isCssJsSubpage
) {
1238 # Check the skin exists
1239 if ( $this->isValidCssJsSubpage
) {
1240 if ( $this->formtype
!== 'preview' ) {
1241 $wgOut->addWikiMsg( 'usercssjsyoucanpreview' );
1244 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1249 $classes = array(); // Textarea CSS
1250 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1251 } elseif ( $this->mTitle
->isProtected( 'edit' ) ) {
1252 # Is the title semi-protected?
1253 if ( $this->mTitle
->isSemiProtected() ) {
1254 $noticeMsg = 'semiprotectedpagewarning';
1255 $classes[] = 'mw-textarea-sprotected';
1257 # Then it must be protected based on static groups (regular)
1258 $noticeMsg = 'protectedpagewarning';
1259 $classes[] = 'mw-textarea-protected';
1261 $wgOut->addHTML( "<div class='mw-warning-with-logexcerpt'>\n" );
1262 $wgOut->addWikiMsg( $noticeMsg );
1263 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
->getPrefixedText(), '', 1 );
1264 $wgOut->addHTML( "</div>\n" );
1266 if ( $this->mTitle
->isCascadeProtected() ) {
1267 # Is this page under cascading protection from some source pages?
1268 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1269 $notice = "<div class='mw-cascadeprotectedwarning'>$1\n";
1270 $cascadeSourcesCount = count( $cascadeSources );
1271 if ( $cascadeSourcesCount > 0 ) {
1272 # Explain, and list the titles responsible
1273 foreach( $cascadeSources as $page ) {
1274 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1277 $notice .= '</div>';
1278 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1280 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1281 $wgOut->wrapWikiMsg( '<div class="mw-titleprotectedwarning">$1</div>', 'titleprotectedwarning' );
1284 if ( $this->kblength
=== false ) {
1285 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1287 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1288 $wgOut->addHTML( "<div class='error' id='mw-edit-longpageerror'>\n" );
1289 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) );
1290 $wgOut->addHTML( "</div>\n" );
1291 } elseif ( $this->kblength
> 29 ) {
1292 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1293 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) );
1294 $wgOut->addHTML( "</div>\n" );
1297 $action = $wgTitle->escapeLocalURL( array( 'action' => $this->action
) );
1299 $summary = wfMsgExt( 'summary', 'parseinline' );
1300 $subject = wfMsgExt( 'subject', 'parseinline' );
1302 $cancel = $sk->link(
1304 wfMsgExt( 'cancel', array( 'parseinline' ) ),
1307 array( 'known', 'noclasses' )
1309 $separator = wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1310 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1311 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1312 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1313 htmlspecialchars( wfMsg( 'newwindow' ) );
1315 global $wgRightsText;
1316 if ( $wgRightsText ) {
1317 $copywarnMsg = array( 'copyrightwarning',
1318 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1321 $copywarnMsg = array( 'copyrightwarning2',
1322 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1324 // Allow for site and per-namespace customization of contribution/copyright notice.
1325 wfRunHooks( 'EditPageCopyrightWarning', array( $this->mTitle
, &$copywarnMsg ) );
1327 if ( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1328 # prepare toolbar for edit buttons
1329 $toolbar = EditPage
::getEditToolbar();
1334 // activate checkboxes if user wants them to be always active
1335 if ( !$this->preview
&& !$this->diff
) {
1336 # Sort out the "watch" checkbox
1337 if ( $wgUser->getOption( 'watchdefault' ) ) {
1339 $this->watchthis
= true;
1340 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1342 $this->watchthis
= true;
1343 } elseif ( $this->mTitle
->userIsWatching() ) {
1345 $this->watchthis
= true;
1348 # May be overriden by request parameters
1349 if( $wgRequest->getBool( 'watchthis' ) ) {
1350 $this->watchthis
= true;
1353 if ( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1356 $wgOut->addHTML( $this->editFormPageTop
);
1358 if ( $wgUser->getOption( 'previewontop' ) ) {
1359 $this->displayPreviewArea( $previewOutput, true );
1363 $wgOut->addHTML( $this->editFormTextTop
);
1365 # if this is a comment, show a subject line at the top, which is also the edit summary.
1366 # Otherwise, show a summary field at the bottom
1367 $summarytext = $wgContLang->recodeForEdit( $this->summary
);
1369 # If a blank edit summary was previously provided, and the appropriate
1370 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1371 # user being bounced back more than once in the event that a summary
1374 # For a bit more sophisticated detection of blank summaries, hash the
1375 # automatic one and pass that in the hidden field wpAutoSummary.
1376 $summaryhiddens = '';
1377 if ( $this->missingSummary
) $summaryhiddens .= Xml
::hidden( 'wpIgnoreBlankSummary', true );
1378 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1379 $summaryhiddens .= Xml
::hidden( 'wpAutoSummary', $autosumm );
1380 if ( $this->section
== 'new' ) {
1381 $commentsubject = '';
1382 if ( !$wgRequest->getBool( 'nosummary' ) ) {
1383 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1384 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1387 Xml
::tags( 'label', array( 'for' => 'wpSummary' ), $subject );
1389 Xml
::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1391 $commentsubject .= ' ';
1392 $commentsubject .= Xml
::input( 'wpSummary',
1396 'id' => 'wpSummary',
1397 'maxlength' => '200',
1401 $editsummary = "<div class='editOptions'>\n";
1403 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary
) );
1404 $subjectpreview = $summarytext && $this->preview ?
1405 "<div class=\"mw-summary-preview\">". wfMsgExt('subject-preview', 'parseinline') . $sk->commentBlock( $formattedSummary, $this->mTitle
, true )."</div>\n" : '';
1406 $summarypreview = '';
1408 $commentsubject = '';
1410 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1411 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1413 $editsummary = Xml
::tags( 'label', array( 'for' => 'wpSummary' ), $summary );
1414 $editsummary = Xml
::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1415 $editsummary ) . ' ';
1417 $editsummary .= Xml
::input( 'wpSummary',
1421 'id' => 'wpSummary',
1422 'maxlength' => '200',
1426 // No idea where this is closed.
1427 $editsummary = Xml
::openElement( 'div', array( 'class' => 'editOptions' ) )
1428 . $editsummary . '<br/>';
1430 $summarypreview = '';
1431 if ( $summarytext && $this->preview
) {
1434 array( 'class' => 'mw-summary-preview' ),
1435 wfMsgExt( 'summary-preview', 'parseinline' ) .
1436 $sk->commentBlock( $this->summary
, $this->mTitle
)
1439 $subjectpreview = '';
1441 $commentsubject .= $summaryhiddens;
1443 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1444 if ( !$this->preview
&& !$this->diff
) {
1445 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1447 $templates = $this->getTemplates();
1448 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1450 $hiddencats = $this->mArticle
->getHiddenCategories();
1451 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1453 global $wgUseMetadataEdit ;
1454 if ( $wgUseMetadataEdit ) {
1455 $metadata = $this->mMetaData
;
1456 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1457 $top = wfMsgWikiHtml( 'metadata_help' );
1458 /* ToDo: Replace with clean code */
1459 $ew = $wgUser->getOption( 'editwidth' );
1460 if ( $ew ) $ew = " style=\"width:100%\"";
1462 $cols = $wgUser->getIntOption( 'cols' );
1464 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1466 else $metadata = "" ;
1469 if ( $this->wasDeletedSinceLastEdit() ) {
1470 if ( 'save' != $this->formtype
) {
1471 $wgOut->wrapWikiMsg(
1472 "<div class='error mw-deleted-while-editing'>\n$1</div>",
1473 'deletedwhileediting' );
1475 // Hide the toolbar and edit area, user can click preview to get it back
1476 // Add an confirmation checkbox and explanation.
1478 $recreate = '<div class="mw-confirm-recreate">' .
1479 $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
) ) .
1480 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1481 array( 'title' => $sk->titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1488 $checkboxes = $this->getCheckboxes( $tabindex, $sk,
1489 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1491 $checkboxhtml = implode( $checkboxes, "\n" );
1493 $buttons = $this->getEditButtons( $tabindex );
1494 $buttonshtml = implode( $buttons, "\n" );
1496 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1497 ?
'' : Xml
::hidden( 'safemode', '1' );
1499 $wgOut->addHTML( <<<END
1501 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1505 if ( is_callable( $formCallback ) ) {
1506 call_user_func_array( $formCallback, array( &$wgOut ) );
1509 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1511 // Put these up at the top to ensure they aren't lost on early form submission
1512 $this->showFormBeforeText();
1514 $wgOut->addHTML( <<<END
1518 {$this->editFormTextBeforeContent}
1521 $this->showTextbox1( $classes );
1523 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1524 $wgOut->addHTML( <<<END
1525 {$this->editFormTextAfterWarn}
1535 "<div class='editButtons'>
1537 <span class='editHelp'>{$cancel}{$separator}{$edithelp}</span>
1538 </div><!-- editButtons -->
1539 </div><!-- editOptions -->");
1542 * To make it harder for someone to slip a user a page
1543 * which submits an edit form to the wiki without their
1544 * knowledge, a random token is associated with the login
1545 * session. If it's not passed back with the submission,
1546 * we won't save the page, or render user JavaScript and
1549 * For anon editors, who may not have a session, we just
1550 * include the constant suffix to prevent editing from
1551 * broken text-mangling proxies.
1553 $token = htmlspecialchars( $wgUser->editToken() );
1554 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1556 $this->showTosSummary();
1557 $this->showEditTools();
1559 $wgOut->addHTML( <<<END
1560 {$this->editFormTextAfterTools}
1561 <div class='templatesUsed'>
1562 {$formattedtemplates}
1564 <div class='hiddencats'>
1565 {$formattedhiddencats}
1570 if ( $this->isConflict
&& wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1571 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1573 $de = new DifferenceEngine( $this->mTitle
);
1574 $de->setText( $this->textbox2
, $this->textbox1
);
1575 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1577 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1578 $this->showTextbox2();
1580 $wgOut->addHTML( $this->editFormTextBottom
);
1581 $wgOut->addHTML( "</form>\n" );
1582 if ( !$wgUser->getOption( 'previewontop' ) ) {
1583 $this->displayPreviewArea( $previewOutput, false );
1586 wfProfileOut( $fname );
1589 protected function showFormBeforeText() {
1592 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1593 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1594 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1595 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1598 protected function showTextbox1( $classes ) {
1599 $attribs = array( 'tabindex' => 1 );
1601 if ( $this->wasDeletedSinceLastEdit() )
1602 $attribs['type'] = 'hidden';
1603 if ( !empty($classes) )
1604 $attribs['class'] = implode(' ',$classes);
1606 $this->showTextbox( $this->textbox1
, 'wpTextbox1', $attribs );
1609 protected function showTextbox2() {
1610 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6 ) );
1613 protected function showTextbox( $content, $name, $attribs = array() ) {
1614 global $wgOut, $wgUser;
1616 $wikitext = $this->safeUnicodeOutput( $content );
1617 if ( $wikitext !== '' ) {
1618 // Ensure there's a newline at the end, otherwise adding lines
1620 // But don't add a newline if the ext is empty, or Firefox in XHTML
1621 // mode will show an extra newline. A bit annoying.
1625 $attribs['accesskey'] = ',';
1626 $attribs['id'] = $name;
1628 if ( $wgUser->getOption( 'editwidth' ) )
1629 $attribs['style'] = 'width: 100%';
1631 $wgOut->addHTML( Xml
::textarea(
1634 $wgUser->getIntOption( 'cols' ), $wgUser->getIntOption( 'rows' ),
1638 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1642 $classes[] = 'ontop';
1644 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1646 if ( $this->formtype
!= 'preview' )
1647 $attribs['style'] = 'display: none;';
1649 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
1651 if ( $this->formtype
== 'preview' ) {
1652 $this->showPreview( $previewOutput );
1655 $wgOut->addHTML( '</div>' );
1657 if ( $this->formtype
== 'diff') {
1663 * Append preview output to $wgOut.
1664 * Includes category rendering if this is a category page.
1666 * @param string $text The HTML to be output for the preview.
1668 protected function showPreview( $text ) {
1670 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1671 $this->mArticle
->openShowCategory();
1673 # This hook seems slightly odd here, but makes things more
1674 # consistent for extensions.
1675 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1676 $wgOut->addHTML( $text );
1677 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1678 $this->mArticle
->closeShowCategory();
1683 * Live Preview lets us fetch rendered preview page content and
1684 * add it to the page without refreshing the whole page.
1685 * If not supported by the browser it will fall through to the normal form
1686 * submission method.
1688 * This function outputs a script tag to support live preview, and
1689 * returns an onclick handler which should be added to the attributes
1690 * of the preview button
1692 function doLivePreviewScript() {
1693 global $wgOut, $wgTitle;
1694 $wgOut->addScriptFile( 'preview.js' );
1695 $liveAction = $wgTitle->getLocalUrl( array(
1696 'action' => $this->action
,
1697 'wpPreview' => 'true',
1700 return "return !lpDoPreview(" .
1701 "editform.wpTextbox1.value," .
1702 '"' . $liveAction . '"' . ")";
1705 protected function showTosSummary() {
1706 $msg = 'editpage-tos-summary';
1707 // Give a chance for site and per-namespace customizations of
1708 // terms of service summary link that might exist separately
1709 // from the copyright notice.
1711 // This will display between the save button and the edit tools,
1712 // so should remain short!
1713 wfRunHooks( 'EditPageTosSummary', array( $this->mTitle
, &$msg ) );
1714 $text = wfMsg( $msg );
1715 if( !wfEmptyMsg( $msg, $text ) && $text !== '-' ) {
1717 $wgOut->addHTML( '<div class="mw-tos-summary">' );
1718 $wgOut->addWikiMsgArray( $msg, array() );
1719 $wgOut->addHTML( '</div>' );
1723 protected function showEditTools() {
1725 $wgOut->addHTML( '<div class="mw-editTools">' );
1726 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1727 $wgOut->addHTML( '</div>' );
1730 protected function getLastDelete() {
1731 $dbr = wfGetDB( DB_SLAVE
);
1732 $data = $dbr->selectRow(
1733 array( 'logging', 'user' ),
1744 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1745 'log_title' => $this->mTitle
->getDBkey(),
1746 'log_type' => 'delete',
1747 'log_action' => 'delete',
1748 'user_id=log_user' ),
1750 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1752 // Quick paranoid permission checks...
1753 if( is_object($data) ) {
1754 if( $data->log_deleted
& LogPage
::DELETED_USER
)
1755 $data->user_name
= wfMsgHtml('rev-deleted-user');
1756 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
1757 $data->log_comment
= wfMsgHtml('rev-deleted-comment');
1763 * Get the rendered text for previewing.
1766 function getPreviewText() {
1767 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache;
1769 wfProfileIn( __METHOD__
);
1771 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1772 if ( $this->mTokenOkExceptSuffix
) {
1773 $note = wfMsg( 'token_suffix_mismatch' );
1775 $note = wfMsg( 'session_fail_preview' );
1778 $note = wfMsg( 'previewnote' );
1781 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1782 $parserOptions->setEditSection( false );
1783 $parserOptions->setIsPreview( true );
1784 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
1787 if ( $wgRawHtml && !$this->mTokenOk
) {
1788 // Could be an offsite preview attempt. This is very unsafe if
1789 // HTML is enabled, as it could be an attack.
1790 return $wgOut->parse( "<div class='previewnote'>" .
1791 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1794 # don't parse user css/js, show message about preview
1795 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1797 if ( $this->isCssJsSubpage
) {
1798 if (preg_match("/\\.css$/", $this->mTitle
->getText() ) ) {
1799 $previewtext = wfMsg('usercsspreview');
1800 } else if (preg_match("/\\.js$/", $this->mTitle
->getText() ) ) {
1801 $previewtext = wfMsg('userjspreview');
1803 $parserOptions->setTidy(true);
1804 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
1805 $previewHTML = $parserOutput->mText
;
1806 } elseif ( $rt = Title
::newFromRedirectArray( $this->textbox1
) ) {
1807 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
1809 $toparse = $this->textbox1
;
1811 # If we're adding a comment, we need to show the
1812 # summary as the headline
1813 if ( $this->section
=="new" && $this->summary
!="" ) {
1814 $toparse="== {$this->summary} ==\n\n".$toparse;
1817 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1819 // Parse mediawiki messages with correct target language
1820 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1821 list( /* $unused */, $lang ) = $wgMessageCache->figureMessage( $this->mTitle
->getText() );
1822 $obj = wfGetLangObj( $lang );
1823 $parserOptions->setTargetLanguage( $obj );
1827 $parserOptions->setTidy(true);
1828 $parserOptions->enableLimitReport();
1829 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ),
1830 $this->mTitle
, $parserOptions );
1832 $previewHTML = $parserOutput->getText();
1833 $this->mParserOutput
= $parserOutput;
1834 $wgOut->addParserOutputNoText( $parserOutput );
1836 if ( count( $parserOutput->getWarnings() ) ) {
1837 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1841 if( $this->isConflict
) {
1842 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1844 $conflict = '<hr />';
1847 $previewhead = "<div class='previewnote'>\n" .
1848 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
1849 $wgOut->parse( $note ) . $conflict . "</div>\n";
1851 wfProfileOut( __METHOD__
);
1852 return $previewhead . $previewHTML;
1855 function getTemplates() {
1856 if ( $this->preview ||
$this->section
!= '' ) {
1857 $templates = array();
1858 if ( !isset($this->mParserOutput
) ) return $templates;
1859 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
1860 foreach( array_keys( $template ) as $dbk ) {
1861 $templates[] = Title
::makeTitle($ns, $dbk);
1866 return $this->mArticle
->getUsedTemplates();
1871 * Call the stock "user is blocked" page
1873 function blockedPage() {
1874 global $wgOut, $wgUser;
1875 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1877 # If the user made changes, preserve them when showing the markup
1878 # (This happens when a user is blocked during edit, for instance)
1879 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1881 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1883 $source = $this->textbox1
;
1886 # Spit out the source or the user's modified version
1887 if ( $source !== false ) {
1888 $rows = $wgUser->getIntOption( 'rows' );
1889 $cols = $wgUser->getIntOption( 'cols' );
1890 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1891 $wgOut->addHTML( '<hr />' );
1892 $wgOut->addWikiMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() );
1893 # Why we don't use Xml::element here?
1894 # Is it because if $source is '', it returns <textarea />?
1895 $wgOut->addHTML( Xml
::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml
::closeElement( 'textarea' ) );
1900 * Produce the stock "please login to edit pages" page
1902 function userNotLoggedInPage() {
1903 global $wgUser, $wgOut, $wgTitle;
1904 $skin = $wgUser->getSkin();
1906 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1907 $loginLink = $skin->link(
1909 wfMsgHtml( 'loginreqlink' ),
1911 array( 'returnto' => $wgTitle->getPrefixedText() ),
1912 array( 'known', 'noclasses' )
1915 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1916 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1917 $wgOut->setArticleRelated( false );
1919 $wgOut->addHTML( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1920 $wgOut->returnToMain( false, $wgTitle );
1924 * Creates a basic error page which informs the user that
1925 * they have attempted to edit a nonexistent section.
1927 function noSuchSectionPage() {
1928 global $wgOut, $wgTitle;
1930 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1931 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1932 $wgOut->setArticleRelated( false );
1934 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section
);
1935 $wgOut->returnToMain( false, $wgTitle );
1939 * Produce the stock "your edit contains spam" page
1941 * @param $match Text which triggered one or more filters
1943 function spamPage( $match = false ) {
1944 global $wgOut, $wgTitle;
1946 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1947 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1948 $wgOut->setArticleRelated( false );
1950 $wgOut->addHTML( '<div id="spamprotected">' );
1951 $wgOut->addWikiMsg( 'spamprotectiontext' );
1953 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1954 $wgOut->addHTML( '</div>' );
1956 $wgOut->returnToMain( false, $wgTitle );
1963 function mergeChangesInto( &$editText ){
1964 $fname = 'EditPage::mergeChangesInto';
1965 wfProfileIn( $fname );
1967 $db = wfGetDB( DB_MASTER
);
1969 // This is the revision the editor started from
1970 $baseRevision = $this->getBaseRevision();
1971 if ( is_null( $baseRevision ) ) {
1972 wfProfileOut( $fname );
1975 $baseText = $baseRevision->getText();
1977 // The current state, we want to merge updates into it
1978 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1979 if ( is_null( $currentRevision ) ) {
1980 wfProfileOut( $fname );
1983 $currentText = $currentRevision->getText();
1986 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1987 $editText = $result;
1988 wfProfileOut( $fname );
1991 wfProfileOut( $fname );
1997 * Check if the browser is on a blacklist of user-agents known to
1998 * mangle UTF-8 data on form submission. Returns true if Unicode
1999 * should make it through, false if it's known to be a problem.
2003 function checkUnicodeCompliantBrowser() {
2004 global $wgBrowserBlackList;
2005 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
2006 // No User-Agent header sent? Trust it by default...
2009 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
2010 foreach ( $wgBrowserBlackList as $browser ) {
2011 if ( preg_match($browser, $currentbrowser) ) {
2019 * @deprecated use $wgParser->stripSectionName()
2021 function pseudoParseSectionAnchor( $text ) {
2023 return $wgParser->stripSectionName( $text );
2027 * Format an anchor fragment as it would appear for a given section name
2028 * @param string $text
2032 function sectionAnchor( $text ) {
2034 return $wgParser->guessSectionNameFromWikiText( $text );
2038 * Shows a bulletin board style toolbar for common editing functions.
2039 * It can be disabled in the user preferences.
2040 * The necessary JavaScript code can be found in skins/common/edit.js.
2044 static function getEditToolbar() {
2045 global $wgStylePath, $wgContLang, $wgLang, $wgJsMimeType;
2048 * toolarray an array of arrays which each include the filename of
2049 * the button image (without path), the opening tag, the closing tag,
2050 * and optionally a sample text that is inserted between the two when no
2051 * selection is highlighted.
2052 * The tip text is shown when the user moves the mouse over the button.
2054 * Already here are accesskeys (key), which are not used yet until someone
2055 * can figure out a way to make them work in IE. However, we should make
2056 * sure these keys are not defined on the edit page.
2060 'image' => $wgLang->getImageFile('button-bold'),
2061 'id' => 'mw-editbutton-bold',
2063 'close' => '\'\'\'',
2064 'sample' => wfMsg('bold_sample'),
2065 'tip' => wfMsg('bold_tip'),
2069 'image' => $wgLang->getImageFile('button-italic'),
2070 'id' => 'mw-editbutton-italic',
2073 'sample' => wfMsg('italic_sample'),
2074 'tip' => wfMsg('italic_tip'),
2078 'image' => $wgLang->getImageFile('button-link'),
2079 'id' => 'mw-editbutton-link',
2082 'sample' => wfMsg('link_sample'),
2083 'tip' => wfMsg('link_tip'),
2087 'image' => $wgLang->getImageFile('button-extlink'),
2088 'id' => 'mw-editbutton-extlink',
2091 'sample' => wfMsg('extlink_sample'),
2092 'tip' => wfMsg('extlink_tip'),
2096 'image' => $wgLang->getImageFile('button-headline'),
2097 'id' => 'mw-editbutton-headline',
2100 'sample' => wfMsg('headline_sample'),
2101 'tip' => wfMsg('headline_tip'),
2105 'image' => $wgLang->getImageFile('button-image'),
2106 'id' => 'mw-editbutton-image',
2107 'open' => '[['.$wgContLang->getNsText(NS_FILE
).':',
2109 'sample' => wfMsg('image_sample'),
2110 'tip' => wfMsg('image_tip'),
2114 'image' => $wgLang->getImageFile('button-media'),
2115 'id' => 'mw-editbutton-media',
2116 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
2118 'sample' => wfMsg('media_sample'),
2119 'tip' => wfMsg('media_tip'),
2123 'image' => $wgLang->getImageFile('button-math'),
2124 'id' => 'mw-editbutton-math',
2126 'close' => "</math>",
2127 'sample' => wfMsg('math_sample'),
2128 'tip' => wfMsg('math_tip'),
2132 'image' => $wgLang->getImageFile('button-nowiki'),
2133 'id' => 'mw-editbutton-nowiki',
2134 'open' => "<nowiki>",
2135 'close' => "</nowiki>",
2136 'sample' => wfMsg('nowiki_sample'),
2137 'tip' => wfMsg('nowiki_tip'),
2141 'image' => $wgLang->getImageFile('button-sig'),
2142 'id' => 'mw-editbutton-signature',
2146 'tip' => wfMsg('sig_tip'),
2150 'image' => $wgLang->getImageFile('button-hr'),
2151 'id' => 'mw-editbutton-hr',
2152 'open' => "\n----\n",
2155 'tip' => wfMsg('hr_tip'),
2159 $toolbar = "<div id='toolbar'>\n";
2160 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
2162 foreach($toolarray as $tool) {
2164 $image = $wgStylePath.'/common/images/'.$tool['image'],
2165 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2166 // Older browsers show a "speedtip" type message only for ALT.
2167 // Ideally these should be different, realistically they
2168 // probably don't need to be.
2169 $tip = $tool['tip'],
2170 $open = $tool['open'],
2171 $close = $tool['close'],
2172 $sample = $tool['sample'],
2173 $cssId = $tool['id'],
2176 $paramList = implode( ',',
2177 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2178 $toolbar.="addButton($paramList);\n";
2181 $toolbar.="/*]]>*/\n</script>";
2182 $toolbar.="\n</div>";
2184 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2190 * Returns an array of html code of the following checkboxes:
2193 * @param $tabindex Current tabindex
2194 * @param $skin Skin object
2195 * @param $checked Array of checkbox => bool, where bool indicates the checked
2196 * status of the checkbox
2200 public function getCheckboxes( &$tabindex, $skin, $checked ) {
2203 $checkboxes = array();
2205 $checkboxes['minor'] = '';
2206 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
2207 if ( $wgUser->isAllowed('minoredit') ) {
2209 'tabindex' => ++
$tabindex,
2210 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2211 'id' => 'wpMinoredit',
2213 $checkboxes['minor'] =
2214 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2215 " <label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
2218 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2219 $checkboxes['watch'] = '';
2220 if ( $wgUser->isLoggedIn() ) {
2222 'tabindex' => ++
$tabindex,
2223 'accesskey' => wfMsg( 'accesskey-watch' ),
2224 'id' => 'wpWatchthis',
2226 $checkboxes['watch'] =
2227 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2228 " <label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
2230 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2235 * Returns an array of html code of the following buttons:
2236 * save, diff, preview and live
2238 * @param $tabindex Current tabindex
2242 public function getEditButtons(&$tabindex) {
2243 global $wgLivePreview, $wgUser;
2251 'tabindex' => ++
$tabindex,
2252 'value' => wfMsg('savearticle'),
2253 'accesskey' => wfMsg('accesskey-save'),
2254 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2256 $buttons['save'] = Xml
::element('input', $temp, '');
2258 ++
$tabindex; // use the same for preview and live preview
2259 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2261 'id' => 'wpPreview',
2262 'name' => 'wpPreview',
2264 'tabindex' => $tabindex,
2265 'value' => wfMsg('showpreview'),
2267 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2268 'style' => 'display: none;',
2270 $buttons['preview'] = Xml
::element('input', $temp, '');
2273 'id' => 'wpLivePreview',
2274 'name' => 'wpLivePreview',
2276 'tabindex' => $tabindex,
2277 'value' => wfMsg('showlivepreview'),
2278 'accesskey' => wfMsg('accesskey-preview'),
2280 'onclick' => $this->doLivePreviewScript(),
2282 $buttons['live'] = Xml
::element('input', $temp, '');
2285 'id' => 'wpPreview',
2286 'name' => 'wpPreview',
2288 'tabindex' => $tabindex,
2289 'value' => wfMsg('showpreview'),
2290 'accesskey' => wfMsg('accesskey-preview'),
2291 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2293 $buttons['preview'] = Xml
::element('input', $temp, '');
2294 $buttons['live'] = '';
2301 'tabindex' => ++
$tabindex,
2302 'value' => wfMsg('showdiff'),
2303 'accesskey' => wfMsg('accesskey-diff'),
2304 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2306 $buttons['diff'] = Xml
::element('input', $temp, '');
2308 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2313 * Output preview text only. This can be sucked into the edit page
2314 * via JavaScript, and saves the server time rendering the skin as
2315 * well as theoretically being more robust on the client (doesn't
2316 * disturb the edit box's undo history, won't eat your text on
2319 * @todo This doesn't include category or interlanguage links.
2320 * Would need to enhance it a bit, <s>maybe wrap them in XML
2321 * or something...</s> that might also require more skin
2322 * initialization, so check whether that's a problem.
2324 function livePreview() {
2327 header( 'Content-type: text/xml; charset=utf-8' );
2328 header( 'Cache-control: no-cache' );
2330 $previewText = $this->getPreviewText();
2331 #$categories = $skin->getCategoryLinks();
2334 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2335 Xml
::tags( 'livepreview', null,
2336 Xml
::element( 'preview', null, $previewText )
2337 #. Xml::element( 'category', null, $categories )
2344 * Get a diff between the current contents of the edit box and the
2345 * version of the page we're editing from.
2347 * If this is a section edit, we'll replace the section as for final
2348 * save and then make a comparison.
2350 function showDiff() {
2351 $oldtext = $this->mArticle
->fetchContent();
2352 $newtext = $this->mArticle
->replaceSection(
2353 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2354 $newtext = $this->mArticle
->preSaveTransform( $newtext );
2355 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2356 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2357 if ( $oldtext !== false ||
$newtext != '' ) {
2358 $de = new DifferenceEngine( $this->mTitle
);
2359 $de->setText( $oldtext, $newtext );
2360 $difftext = $de->getDiff( $oldtitle, $newtitle );
2361 $de->showDiffStyle();
2367 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2371 * Filter an input field through a Unicode de-armoring process if it
2372 * came from an old browser with known broken Unicode editing issues.
2374 * @param WebRequest $request
2375 * @param string $field
2379 function safeUnicodeInput( $request, $field ) {
2380 $text = rtrim( $request->getText( $field ) );
2381 return $request->getBool( 'safemode' )
2382 ?
$this->unmakesafe( $text )
2387 * Filter an output field through a Unicode armoring process if it is
2388 * going to an old browser with known broken Unicode editing issues.
2390 * @param string $text
2394 function safeUnicodeOutput( $text ) {
2396 $codedText = $wgContLang->recodeForEdit( $text );
2397 return $this->checkUnicodeCompliantBrowser()
2399 : $this->makesafe( $codedText );
2403 * A number of web browsers are known to corrupt non-ASCII characters
2404 * in a UTF-8 text editing environment. To protect against this,
2405 * detected browsers will be served an armored version of the text,
2406 * with non-ASCII chars converted to numeric HTML character references.
2408 * Preexisting such character references will have a 0 added to them
2409 * to ensure that round-trips do not alter the original data.
2411 * @param string $invalue
2415 function makesafe( $invalue ) {
2416 // Armor existing references for reversability.
2417 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2422 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2423 $bytevalue = ord( $invalue{$i} );
2424 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2425 $result .= chr( $bytevalue );
2427 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2428 $working = $working << 6;
2429 $working +
= ($bytevalue & 0x3F);
2431 if ( $bytesleft <= 0 ) {
2432 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2434 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2435 $working = $bytevalue & 0x1F;
2437 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2438 $working = $bytevalue & 0x0F;
2440 } else { //1111 0xxx
2441 $working = $bytevalue & 0x07;
2449 * Reverse the previously applied transliteration of non-ASCII characters
2450 * back to UTF-8. Used to protect data from corruption by broken web browsers
2451 * as listed in $wgBrowserBlackList.
2453 * @param string $invalue
2457 function unmakesafe( $invalue ) {
2459 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2460 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2464 $hexstring .= $invalue{$i};
2466 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2468 // Do some sanity checks. These aren't needed for reversability,
2469 // but should help keep the breakage down if the editor
2470 // breaks one of the entities whilst editing.
2471 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2472 $codepoint = hexdec($hexstring);
2473 $result .= codepointToUtf8( $codepoint );
2475 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2478 $result .= substr( $invalue, $i, 1 );
2481 // reverse the transform that we made for reversability reasons.
2482 return strtr( $result, array( "�" => "&#x" ) );
2485 function noCreatePermission() {
2487 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2488 $wgOut->addWikiMsg( 'nocreatetext' );
2492 * If there are rows in the deletion/move log for this page, show them,
2493 * along with a nice little note for the user
2495 * @param OutputPage $out
2497 protected function showLogs( $out ) {
2499 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
2500 $pager = new LogPager( $loglist, array('move', 'delete'), false,
2501 $this->mTitle
->getPrefixedText(), '', array( "log_action != 'revision'" ) );
2503 $count = $pager->getNumRows();
2505 $pager->mLimit
= 10;
2506 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
2507 $out->addWikiMsg( 'recreate-moveddeleted-warn' );
2509 $loglist->beginLogEventsList() .
2511 $loglist->endLogEventsList()
2514 $out->addHTML( $wgUser->getSkin()->link(
2515 SpecialPage
::getTitleFor( 'Log' ),
2516 wfMsgHtml( 'log-fulllog' ),
2518 array( 'page' => $this->mTitle
->getPrefixedText() ) ) );
2520 $out->addHTML( '</div>' );
2528 * Attempt submission
2529 * @return bool false if output is done, true if the rest of the form should be displayed
2531 function attemptSave() {
2532 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2534 $resultDetails = false;
2535 # Allow bots to exempt some edits from bot flagging
2536 $bot = $wgUser->isAllowed('bot') && $wgRequest->getBool('bot',true);
2537 $value = $this->internalAttemptSave( $resultDetails, $bot );
2539 if ( $value == self
::AS_SUCCESS_UPDATE ||
$value == self
::AS_SUCCESS_NEW_ARTICLE
) {
2540 $this->didSave
= true;
2544 case self
::AS_HOOK_ERROR_EXPECTED
:
2545 case self
::AS_CONTENT_TOO_BIG
:
2546 case self
::AS_ARTICLE_WAS_DELETED
:
2547 case self
::AS_CONFLICT_DETECTED
:
2548 case self
::AS_SUMMARY_NEEDED
:
2549 case self
::AS_TEXTBOX_EMPTY
:
2550 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
2554 case self
::AS_HOOK_ERROR
:
2555 case self
::AS_FILTERING
:
2556 case self
::AS_SUCCESS_NEW_ARTICLE
:
2557 case self
::AS_SUCCESS_UPDATE
:
2560 case self
::AS_SPAM_ERROR
:
2561 $this->spamPage ( $resultDetails['spam'] );
2564 case self
::AS_BLOCKED_PAGE_FOR_USER
:
2565 $this->blockedPage();
2568 case self
::AS_IMAGE_REDIRECT_ANON
:
2569 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2572 case self
::AS_READ_ONLY_PAGE_ANON
:
2573 $this->userNotLoggedInPage();
2576 case self
::AS_READ_ONLY_PAGE_LOGGED
:
2577 case self
::AS_READ_ONLY_PAGE
:
2578 $wgOut->readOnlyPage();
2581 case self
::AS_RATE_LIMITED
:
2582 $wgOut->rateLimited();
2585 case self
::AS_NO_CREATE_PERMISSION
;
2586 $this->noCreatePermission();
2589 case self
::AS_BLANK_ARTICLE
:
2590 $wgOut->redirect( $wgTitle->getFullURL() );
2593 case self
::AS_IMAGE_REDIRECT_LOGGED
:
2594 $wgOut->permissionRequired( 'upload' );
2599 function getBaseRevision() {
2600 if ( $this->mBaseRevision
== false ) {
2601 $db = wfGetDB( DB_MASTER
);
2602 $baseRevision = Revision
::loadFromTimestamp(
2603 $db, $this->mTitle
, $this->edittime
);
2604 return $this->mBaseRevision
= $baseRevision;
2606 return $this->mBaseRevision
;