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 $this->oldid
= $request->getInt( 'oldid' );
662 $this->live
= $request->getCheck( 'live' );
663 $this->editintro
= $request->getText( 'editintro' );
665 wfProfileOut( $fname );
669 * Make sure the form isn't faking a user's credentials.
671 * @param $request WebRequest
675 function tokenOk( &$request ) {
677 $token = $request->getVal( 'wpEditToken' );
678 $this->mTokenOk
= $wgUser->matchEditToken( $token );
679 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
680 return $this->mTokenOk
;
684 * Show all applicable editing introductions
686 protected function showIntro() {
687 global $wgOut, $wgUser;
688 if ( $this->suppressIntro
) {
692 $namespace = $this->mTitle
->getNamespace();
694 if ( $namespace == NS_MEDIAWIKI
) {
695 # Show a warning if editing an interface message
696 $wgOut->wrapWikiMsg( "<div class='mw-editinginterface'>\n$1</div>", 'editinginterface' );
699 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
700 if ( $namespace == NS_USER ||
$namespace == NS_USER_TALK
) {
701 $parts = explode( '/', $this->mTitle
->getText(), 2 );
702 $username = $parts[0];
703 $id = User
::idFromName( $username );
704 $ip = User
::isIP( $username );
705 if ( $id == 0 && !$ip ) {
706 $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
707 array( 'userpage-userdoesnotexist', $username ) );
710 # Try to add a custom edit intro, or use the standard one if this is not possible.
711 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
712 if ( $wgUser->isLoggedIn() ) {
713 $wgOut->wrapWikiMsg( '<div class="mw-newarticletext">$1</div>', 'newarticletext' );
715 $wgOut->wrapWikiMsg( '<div class="mw-newarticletextanon">$1</div>', 'newarticletextanon' );
718 # Give a notice if the user is editing a deleted/moved page...
719 if ( !$this->mTitle
->exists() ) {
720 $this->showLogs( $wgOut );
725 * Attempt to show a custom editing introduction, if supplied
729 protected function showCustomIntro() {
730 if ( $this->editintro
) {
731 $title = Title
::newFromText( $this->editintro
);
732 if ( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
734 $revision = Revision
::newFromTitle( $title );
735 $wgOut->addWikiTextTitleTidy( $revision->getText(), $this->mTitle
);
746 * Attempt submission (no UI)
747 * @return one of the constants describing the result
749 function internalAttemptSave( &$result, $bot = false ) {
750 global $wgFilterCallback, $wgUser, $wgOut, $wgParser;
751 global $wgMaxArticleSize;
753 $fname = 'EditPage::attemptSave';
754 wfProfileIn( $fname );
755 wfProfileIn( "$fname-checks" );
757 if ( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
759 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving\n" );
760 return self
::AS_HOOK_ERROR
;
763 # Check image redirect
764 if ( $this->mTitle
->getNamespace() == NS_FILE
&&
765 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
766 !$wgUser->isAllowed( 'upload' ) ) {
767 if ( $wgUser->isAnon() ) {
768 return self
::AS_IMAGE_REDIRECT_ANON
;
770 return self
::AS_IMAGE_REDIRECT_LOGGED
;
774 # Reintegrate metadata
775 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
776 $this->mMetaData
= '' ;
779 $match = self
::matchSummarySpamRegex( $this->summary
);
780 if ( $match === false ) {
781 $match = self
::matchSpamRegex( $this->textbox1
);
783 if ( $match !== false ) {
784 $result['spam'] = $match;
786 $pdbk = $this->mTitle
->getPrefixedDBkey();
787 $match = str_replace( "\n", '', $match );
788 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
789 wfProfileOut( "$fname-checks" );
790 wfProfileOut( $fname );
791 return self
::AS_SPAM_ERROR
;
793 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
794 # Error messages or other handling should be performed by the filter function
795 wfProfileOut( "$fname-checks" );
796 wfProfileOut( $fname );
797 return self
::AS_FILTERING
;
799 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
800 # Error messages etc. could be handled within the hook...
801 wfProfileOut( "$fname-checks" );
802 wfProfileOut( $fname );
803 return self
::AS_HOOK_ERROR
;
804 } elseif ( $this->hookError
!= '' ) {
805 # ...or the hook could be expecting us to produce an error
806 wfProfileOut( "$fname-checks" );
807 wfProfileOut( $fname );
808 return self
::AS_HOOK_ERROR_EXPECTED
;
810 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
811 # Check block state against master, thus 'false'.
812 wfProfileOut( "$fname-checks" );
813 wfProfileOut( $fname );
814 return self
::AS_BLOCKED_PAGE_FOR_USER
;
816 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
817 if ( $this->kblength
> $wgMaxArticleSize ) {
818 // Error will be displayed by showEditForm()
819 $this->tooBig
= true;
820 wfProfileOut( "$fname-checks" );
821 wfProfileOut( $fname );
822 return self
::AS_CONTENT_TOO_BIG
;
825 if ( !$wgUser->isAllowed('edit') ) {
826 if ( $wgUser->isAnon() ) {
827 wfProfileOut( "$fname-checks" );
828 wfProfileOut( $fname );
829 return self
::AS_READ_ONLY_PAGE_ANON
;
832 wfProfileOut( "$fname-checks" );
833 wfProfileOut( $fname );
834 return self
::AS_READ_ONLY_PAGE_LOGGED
;
838 if ( wfReadOnly() ) {
839 wfProfileOut( "$fname-checks" );
840 wfProfileOut( $fname );
841 return self
::AS_READ_ONLY_PAGE
;
843 if ( $wgUser->pingLimiter() ) {
844 wfProfileOut( "$fname-checks" );
845 wfProfileOut( $fname );
846 return self
::AS_RATE_LIMITED
;
849 # If the article has been deleted while editing, don't save it without
851 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
852 wfProfileOut( "$fname-checks" );
853 wfProfileOut( $fname );
854 return self
::AS_ARTICLE_WAS_DELETED
;
857 wfProfileOut( "$fname-checks" );
859 # If article is new, insert it.
860 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
862 // Late check for create permission, just in case *PARANOIA*
863 if ( !$this->mTitle
->userCan( 'create' ) ) {
864 wfDebug( "$fname: no create permission\n" );
865 wfProfileOut( $fname );
866 return self
::AS_NO_CREATE_PERMISSION
;
869 # Don't save a new article if it's blank.
870 if ( '' == $this->textbox1
) {
871 wfProfileOut( $fname );
872 return self
::AS_BLANK_ARTICLE
;
875 // Run post-section-merge edit filter
876 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
877 # Error messages etc. could be handled within the hook...
878 wfProfileOut( $fname );
879 return self
::AS_HOOK_ERROR
;
882 # Handle the user preference to force summaries here. Check if it's not a redirect.
883 if ( !$this->allowBlankSummary
&& !Title
::newFromRedirect( $this->textbox1
) ) {
884 if ( md5( $this->summary
) == $this->autoSumm
) {
885 $this->missingSummary
= true;
886 wfProfileOut( $fname );
887 return self
::AS_SUMMARY_NEEDED
;
891 $isComment = ( $this->section
== 'new' );
893 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
894 $this->minoredit
, $this->watchthis
, false, $isComment, $bot );
896 wfProfileOut( $fname );
897 return self
::AS_SUCCESS_NEW_ARTICLE
;
900 # Article exists. Check for edit conflict.
902 $this->mArticle
->clear(); # Force reload of dates, etc.
903 $this->mArticle
->forUpdate( true ); # Lock the article
905 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
907 if ( $this->mArticle
->getTimestamp() != $this->edittime
) {
908 $this->isConflict
= true;
909 if ( $this->section
== 'new' ) {
910 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
911 $this->mArticle
->getComment() == $this->summary
) {
912 // Probably a duplicate submission of a new comment.
913 // This can happen when squid resends a request after
914 // a timeout but the first one actually went through.
915 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
917 // New comment; suppress conflict.
918 $this->isConflict
= false;
919 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
923 $userid = $wgUser->getId();
925 # Suppress edit conflict with self, except for section edits where merging is required.
926 if ( $this->isConflict
&& $this->section
== '' && $this->userWasLastToEdit($userid,$this->edittime
) ) {
927 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
928 $this->isConflict
= false;
931 if ( $this->isConflict
) {
932 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
933 $this->mArticle
->getTimestamp() . "')\n" );
934 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
936 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
937 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
939 if ( is_null( $text ) ) {
940 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
941 $this->isConflict
= true;
942 $text = $this->textbox1
; // do not try to merge here!
943 } else if ( $this->isConflict
) {
945 if ( $this->mergeChangesInto( $text ) ) {
946 // Successful merge! Maybe we should tell the user the good news?
947 $this->isConflict
= false;
948 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
951 $this->textbox1
= $text;
952 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
956 if ( $this->isConflict
) {
957 wfProfileOut( $fname );
958 return self
::AS_CONFLICT_DETECTED
;
961 $oldtext = $this->mArticle
->getContent();
963 // Run post-section-merge edit filter
964 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
965 # Error messages etc. could be handled within the hook...
966 wfProfileOut( $fname );
967 return self
::AS_HOOK_ERROR
;
970 # Handle the user preference to force summaries here, but not for null edits
971 if ( $this->section
!= 'new' && !$this->allowBlankSummary
&& 0 != strcmp($oldtext,$text)
972 && !Title
::newFromRedirect( $text ) ) # check if it's not a redirect
974 if ( md5( $this->summary
) == $this->autoSumm
) {
975 $this->missingSummary
= true;
976 wfProfileOut( $fname );
977 return self
::AS_SUMMARY_NEEDED
;
981 # And a similar thing for new sections
982 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
983 if (trim($this->summary
) == '') {
984 $this->missingSummary
= true;
985 wfProfileOut( $fname );
986 return self
::AS_SUMMARY_NEEDED
;
991 wfProfileIn( "$fname-sectionanchor" );
993 if ( $this->section
== 'new' ) {
994 if ( $this->textbox1
== '' ) {
995 $this->missingComment
= true;
996 return self
::AS_TEXTBOX_EMPTY
;
998 if ( $this->summary
!= '' ) {
999 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary
);
1000 # This is a new section, so create a link to the new section
1001 # in the revision summary.
1002 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
1003 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
1005 } elseif ( $this->section
!= '' ) {
1006 # Try to get a section anchor from the section source, redirect to edited section if header found
1007 # XXX: might be better to integrate this into Article::replaceSection
1008 # for duplicate heading checking and maybe parsing
1009 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
1010 # we can't deal with anchors, includes, html etc in the header for now,
1011 # headline would need to be parsed to improve this
1012 if ( $hasmatch and strlen($matches[2]) > 0 ) {
1013 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
1016 wfProfileOut( "$fname-sectionanchor" );
1018 // Save errors may fall down to the edit form, but we've now
1019 // merged the section into full text. Clear the section field
1020 // so that later submission of conflict forms won't try to
1021 // replace that into a duplicated mess.
1022 $this->textbox1
= $text;
1023 $this->section
= '';
1025 // Check for length errors again now that the section is merged in
1026 $this->kblength
= (int)(strlen( $text ) / 1024);
1027 if ( $this->kblength
> $wgMaxArticleSize ) {
1028 $this->tooBig
= true;
1029 wfProfileOut( $fname );
1030 return self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
;
1033 # update the article here
1034 if ( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
1035 $this->watchthis
, $bot, $sectionanchor ) )
1037 wfProfileOut( $fname );
1038 return self
::AS_SUCCESS_UPDATE
;
1040 $this->isConflict
= true;
1042 wfProfileOut( $fname );
1043 return self
::AS_END
;
1047 * Check if no edits were made by other users since
1048 * the time a user started editing the page. Limit to
1049 * 50 revisions for the sake of performance.
1051 protected function userWasLastToEdit( $id, $edittime ) {
1052 if( !$id ) return false;
1053 $dbw = wfGetDB( DB_MASTER
);
1054 $res = $dbw->select( 'revision',
1057 'rev_page' => $this->mArticle
->getId(),
1058 'rev_timestamp > '.$dbw->addQuotes( $dbw->timestamp($edittime) )
1061 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 50 ) );
1062 while( $row = $res->fetchObject() ) {
1063 if( $row->rev_user
!= $id ) {
1071 * Check given input text against $wgSpamRegex, and return the text of the first match.
1072 * @return mixed -- matching string or false
1074 public static function matchSpamRegex( $text ) {
1075 global $wgSpamRegex;
1076 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1077 $regexes = (array)$wgSpamRegex;
1078 return self
::matchSpamRegexInternal( $text, $regexes );
1082 * Check given input text against $wgSpamRegex, and return the text of the first match.
1083 * @return mixed -- matching string or false
1085 public static function matchSummarySpamRegex( $text ) {
1086 global $wgSummarySpamRegex;
1087 $regexes = (array)$wgSummarySpamRegex;
1088 return self
::matchSpamRegexInternal( $text, $regexes );
1091 protected static function matchSpamRegexInternal( $text, $regexes ) {
1092 foreach( $regexes as $regex ) {
1094 if( preg_match( $regex, $text, $matches ) ) {
1102 * Initialise form fields in the object
1103 * Called on the first invocation, e.g. when a user clicks an edit link
1105 function initialiseForm() {
1106 $this->edittime
= $this->mArticle
->getTimestamp();
1107 $this->textbox1
= $this->getContent( false );
1108 if ( $this->textbox1
=== false ) return false;
1113 function setHeaders() {
1114 global $wgOut, $wgTitle;
1115 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1116 if ( $this->formtype
== 'preview' ) {
1117 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1119 if ( $this->isConflict
) {
1120 $wgOut->setPageTitle( wfMsg( 'editconflict', $wgTitle->getPrefixedText() ) );
1121 } elseif ( $this->section
!= '' ) {
1122 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1123 $wgOut->setPageTitle( wfMsg( $msg, $wgTitle->getPrefixedText() ) );
1125 # Use the title defined by DISPLAYTITLE magic word when present
1126 if ( isset($this->mParserOutput
)
1127 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1130 $title = $wgTitle->getPrefixedText();
1132 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1137 * Send the edit form and related headers to $wgOut
1138 * @param $formCallback Optional callable that takes an OutputPage
1139 * parameter; will be called during form output
1140 * near the top, for captchas and the like.
1142 function showEditForm( $formCallback=null ) {
1143 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle, $wgRequest;
1145 # If $wgTitle is null, that means we're in API mode.
1146 # Some hook probably called this function without checking
1147 # for is_null($wgTitle) first. Bail out right here so we don't
1148 # do lots of work just to discard it right after.
1149 if (is_null($wgTitle))
1152 $fname = 'EditPage::showEditForm';
1153 wfProfileIn( $fname );
1155 $sk = $wgUser->getSkin();
1157 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
1159 #need to parse the preview early so that we know which templates are used,
1160 #otherwise users with "show preview after edit box" will get a blank list
1161 #we parse this near the beginning so that setHeaders can do the title
1162 #setting work instead of leaving it in getPreviewText
1163 $previewOutput = '';
1164 if ( $this->formtype
== 'preview' ) {
1165 $previewOutput = $this->getPreviewText();
1168 $this->setHeaders();
1170 # Enabled article-related sidebar, toplinks, etc.
1171 $wgOut->setArticleRelated( true );
1173 if ( $this->isConflict
) {
1174 $wgOut->wrapWikiMsg( "<div class='mw-explainconflict'>\n$1</div>", 'explainconflict' );
1176 $this->textbox2
= $this->textbox1
;
1177 $this->textbox1
= $this->getContent();
1178 $this->edittime
= $this->mArticle
->getTimestamp();
1180 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1182 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1183 preg_match( "/^(=+)(.+)\\1/mi", $this->textbox1
, $matches );
1184 if ( !empty( $matches[2] ) ) {
1186 $this->summary
= "/* " .
1187 $wgParser->stripSectionName(trim($matches[2])) .
1193 if ( $this->missingComment
) {
1194 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1197 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1198 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1201 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1202 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1205 if ( $this->hookError
!== '' ) {
1206 $wgOut->addWikiText( $this->hookError
);
1209 if ( !$this->checkUnicodeCompliantBrowser() ) {
1210 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1212 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1213 // Let sysop know that this will make private content public if saved
1215 if ( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1216 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-permission' );
1217 } else if ( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1218 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n", 'rev-deleted-text-view' );
1221 if ( !$this->mArticle
->mRevision
->isCurrent() ) {
1222 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1223 $wgOut->addWikiMsg( 'editingold' );
1228 if ( wfReadOnly() ) {
1229 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1230 } elseif ( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
1231 $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' );
1233 if ( $this->isCssJsSubpage
) {
1234 # Check the skin exists
1235 if ( $this->isValidCssJsSubpage
) {
1236 if ( $this->formtype
!== 'preview' ) {
1237 $wgOut->addWikiMsg( 'usercssjsyoucanpreview' );
1240 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1245 $classes = array(); // Textarea CSS
1246 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1247 } elseif ( $this->mTitle
->isProtected( 'edit' ) ) {
1248 # Is the title semi-protected?
1249 if ( $this->mTitle
->isSemiProtected() ) {
1250 $noticeMsg = 'semiprotectedpagewarning';
1251 $classes[] = 'mw-textarea-sprotected';
1253 # Then it must be protected based on static groups (regular)
1254 $noticeMsg = 'protectedpagewarning';
1255 $classes[] = 'mw-textarea-protected';
1257 $wgOut->addHTML( "<div class='mw-warning-with-logexcerpt'>\n" );
1258 $wgOut->addWikiMsg( $noticeMsg );
1259 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
->getPrefixedText(), '', 1 );
1260 $wgOut->addHTML( "</div>\n" );
1262 if ( $this->mTitle
->isCascadeProtected() ) {
1263 # Is this page under cascading protection from some source pages?
1264 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1265 $notice = "<div class='mw-cascadeprotectedwarning'>$1\n";
1266 $cascadeSourcesCount = count( $cascadeSources );
1267 if ( $cascadeSourcesCount > 0 ) {
1268 # Explain, and list the titles responsible
1269 foreach( $cascadeSources as $page ) {
1270 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1273 $notice .= '</div>';
1274 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', $cascadeSourcesCount ) );
1276 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1277 $wgOut->wrapWikiMsg( '<div class="mw-titleprotectedwarning">$1</div>', 'titleprotectedwarning' );
1280 if ( $this->kblength
=== false ) {
1281 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1283 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1284 $wgOut->addHTML( "<div class='error' id='mw-edit-longpageerror'>\n" );
1285 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) );
1286 $wgOut->addHTML( "</div>\n" );
1287 } elseif ( $this->kblength
> 29 ) {
1288 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1289 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) );
1290 $wgOut->addHTML( "</div>\n" );
1293 $action = $wgTitle->escapeLocalURL( array( 'action' => $this->action
) );
1295 $summary = wfMsgExt( 'summary', 'parseinline' );
1296 $subject = wfMsgExt( 'subject', 'parseinline' );
1298 $cancel = $sk->link(
1300 wfMsgExt( 'cancel', array( 'parseinline' ) ),
1303 array( 'known', 'noclasses' )
1305 $separator = wfMsgExt( 'pipe-separator' , 'escapenoentities' );
1306 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1307 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1308 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1309 htmlspecialchars( wfMsg( 'newwindow' ) );
1311 global $wgRightsText;
1312 if ( $wgRightsText ) {
1313 $copywarnMsg = array( 'copyrightwarning',
1314 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1317 $copywarnMsg = array( 'copyrightwarning2',
1318 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1321 if ( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1322 # prepare toolbar for edit buttons
1323 $toolbar = EditPage
::getEditToolbar();
1328 // activate checkboxes if user wants them to be always active
1329 if ( !$this->preview
&& !$this->diff
) {
1330 # Sort out the "watch" checkbox
1331 if ( $wgUser->getOption( 'watchdefault' ) ) {
1333 $this->watchthis
= true;
1334 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1336 $this->watchthis
= true;
1337 } elseif ( $this->mTitle
->userIsWatching() ) {
1339 $this->watchthis
= true;
1342 # May be overriden by request parameters
1343 if( $wgRequest->getBool( 'watchthis' ) ) {
1344 $this->watchthis
= true;
1347 if ( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1350 $wgOut->addHTML( $this->editFormPageTop
);
1352 if ( $wgUser->getOption( 'previewontop' ) ) {
1353 $this->displayPreviewArea( $previewOutput, true );
1357 $wgOut->addHTML( $this->editFormTextTop
);
1359 # if this is a comment, show a subject line at the top, which is also the edit summary.
1360 # Otherwise, show a summary field at the bottom
1361 $summarytext = $wgContLang->recodeForEdit( $this->summary
);
1363 # If a blank edit summary was previously provided, and the appropriate
1364 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1365 # user being bounced back more than once in the event that a summary
1368 # For a bit more sophisticated detection of blank summaries, hash the
1369 # automatic one and pass that in the hidden field wpAutoSummary.
1370 $summaryhiddens = '';
1371 if ( $this->missingSummary
) $summaryhiddens .= Xml
::hidden( 'wpIgnoreBlankSummary', true );
1372 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1373 $summaryhiddens .= Xml
::hidden( 'wpAutoSummary', $autosumm );
1374 if ( $this->section
== 'new' ) {
1375 $commentsubject = '';
1376 if ( !$wgRequest->getBool( 'nosummary' ) ) {
1377 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1378 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1381 Xml
::tags( 'label', array( 'for' => 'wpSummary' ), $subject );
1383 Xml
::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1385 $commentsubject .= ' ';
1386 $commentsubject .= Xml
::input( 'wpSummary',
1390 'id' => 'wpSummary',
1391 'maxlength' => '200',
1395 $editsummary = "<div class='editOptions'>\n";
1397 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary
) );
1398 $subjectpreview = $summarytext && $this->preview ?
1399 "<div class=\"mw-summary-preview\">". wfMsgExt('subject-preview', 'parseinline') . $sk->commentBlock( $formattedSummary, $this->mTitle
, true )."</div>\n" : '';
1400 $summarypreview = '';
1402 $commentsubject = '';
1404 # Add a class if 'missingsummary' is triggered to allow styling of the summary line
1405 $summaryClass = $this->missingSummary ?
'mw-summarymissed' : 'mw-summary';
1407 $editsummary = Xml
::tags( 'label', array( 'for' => 'wpSummary' ), $summary );
1408 $editsummary = Xml
::tags( 'span', array( 'class' => $summaryClass, 'id' => "wpSummaryLabel" ),
1409 $editsummary ) . ' ';
1411 $editsummary .= Xml
::input( 'wpSummary',
1415 'id' => 'wpSummary',
1416 'maxlength' => '200',
1420 // No idea where this is closed.
1421 $editsummary = Xml
::openElement( 'div', array( 'class' => 'editOptions' ) )
1422 . $editsummary . '<br/>';
1424 $summarypreview = '';
1425 if ( $summarytext && $this->preview
) {
1428 array( 'class' => 'mw-summary-preview' ),
1429 wfMsgExt( 'summary-preview', 'parseinline' ) .
1430 $sk->commentBlock( $this->summary
, $this->mTitle
)
1433 $subjectpreview = '';
1435 $commentsubject .= $summaryhiddens;
1437 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1438 if ( !$this->preview
&& !$this->diff
) {
1439 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1441 $templates = $this->getTemplates();
1442 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1444 $hiddencats = $this->mArticle
->getHiddenCategories();
1445 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1447 global $wgUseMetadataEdit ;
1448 if ( $wgUseMetadataEdit ) {
1449 $metadata = $this->mMetaData
;
1450 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1451 $top = wfMsgWikiHtml( 'metadata_help' );
1452 /* ToDo: Replace with clean code */
1453 $ew = $wgUser->getOption( 'editwidth' );
1454 if ( $ew ) $ew = " style=\"width:100%\"";
1456 $cols = $wgUser->getIntOption( 'cols' );
1458 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1460 else $metadata = "" ;
1463 if ( $this->wasDeletedSinceLastEdit() ) {
1464 if ( 'save' != $this->formtype
) {
1465 $wgOut->wrapWikiMsg(
1466 "<div class='error mw-deleted-while-editing'>\n$1</div>",
1467 'deletedwhileediting' );
1469 // Hide the toolbar and edit area, user can click preview to get it back
1470 // Add an confirmation checkbox and explanation.
1472 $recreate = '<div class="mw-confirm-recreate">' .
1473 $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
) ) .
1474 Xml
::checkLabel( wfMsg( 'recreate' ), 'wpRecreate', 'wpRecreate', false,
1475 array( 'title' => $sk->titleAttrib( 'recreate' ), 'tabindex' => 1, 'id' => 'wpRecreate' )
1482 $checkboxes = $this->getCheckboxes( $tabindex, $sk,
1483 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1485 $checkboxhtml = implode( $checkboxes, "\n" );
1487 $buttons = $this->getEditButtons( $tabindex );
1488 $buttonshtml = implode( $buttons, "\n" );
1490 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1491 ?
'' : Xml
::hidden( 'safemode', '1' );
1493 $wgOut->addHTML( <<<END
1495 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1499 if ( is_callable( $formCallback ) ) {
1500 call_user_func_array( $formCallback, array( &$wgOut ) );
1503 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1505 // Put these up at the top to ensure they aren't lost on early form submission
1506 $this->showFormBeforeText();
1508 $wgOut->addHTML( <<<END
1512 {$this->editFormTextBeforeContent}
1515 $this->showTextbox1( $classes );
1517 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1518 $wgOut->addHTML( <<<END
1519 {$this->editFormTextAfterWarn}
1529 "<div class='editButtons'>
1531 <span class='editHelp'>{$cancel}{$separator}{$edithelp}</span>
1532 </div><!-- editButtons -->
1533 </div><!-- editOptions -->");
1536 * To make it harder for someone to slip a user a page
1537 * which submits an edit form to the wiki without their
1538 * knowledge, a random token is associated with the login
1539 * session. If it's not passed back with the submission,
1540 * we won't save the page, or render user JavaScript and
1543 * For anon editors, who may not have a session, we just
1544 * include the constant suffix to prevent editing from
1545 * broken text-mangling proxies.
1547 $token = htmlspecialchars( $wgUser->editToken() );
1548 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1550 $this->showEditTools();
1552 $wgOut->addHTML( <<<END
1553 {$this->editFormTextAfterTools}
1554 <div class='templatesUsed'>
1555 {$formattedtemplates}
1557 <div class='hiddencats'>
1558 {$formattedhiddencats}
1563 if ( $this->isConflict
&& wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1564 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1566 $de = new DifferenceEngine( $this->mTitle
);
1567 $de->setText( $this->textbox2
, $this->textbox1
);
1568 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1570 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1571 $this->showTextbox2();
1573 $wgOut->addHTML( $this->editFormTextBottom
);
1574 $wgOut->addHTML( "</form>\n" );
1575 if ( !$wgUser->getOption( 'previewontop' ) ) {
1576 $this->displayPreviewArea( $previewOutput, false );
1579 wfProfileOut( $fname );
1582 protected function showFormBeforeText() {
1585 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1586 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1587 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1588 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1591 protected function showTextbox1( $classes ) {
1592 $attribs = array( 'tabindex' => 1 );
1594 if ( $this->wasDeletedSinceLastEdit() )
1595 $attribs['type'] = 'hidden';
1596 if ( !empty($classes) )
1597 $attribs['class'] = implode(' ',$classes);
1599 $this->showTextbox( $this->textbox1
, 'wpTextbox1', $attribs );
1602 protected function showTextbox2() {
1603 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6 ) );
1606 protected function showTextbox( $content, $name, $attribs = array() ) {
1607 global $wgOut, $wgUser;
1609 $wikitext = $this->safeUnicodeOutput( $content );
1610 if ( $wikitext !== '' ) {
1611 // Ensure there's a newline at the end, otherwise adding lines
1613 // But don't add a newline if the ext is empty, or Firefox in XHTML
1614 // mode will show an extra newline. A bit annoying.
1618 $attribs['accesskey'] = ',';
1619 $attribs['id'] = $name;
1621 if ( $wgUser->getOption( 'editwidth' ) )
1622 $attribs['style'] = 'width: 100%';
1624 $wgOut->addHTML( Xml
::textarea(
1627 $wgUser->getIntOption( 'cols' ), $wgUser->getIntOption( 'rows' ),
1631 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1635 $classes[] = 'ontop';
1637 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1639 if ( $this->formtype
!= 'preview' )
1640 $attribs['style'] = 'display: none;';
1642 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
1644 if ( $this->formtype
== 'preview' ) {
1645 $this->showPreview( $previewOutput );
1648 $wgOut->addHTML( '</div>' );
1650 if ( $this->formtype
== 'diff') {
1656 * Append preview output to $wgOut.
1657 * Includes category rendering if this is a category page.
1659 * @param string $text The HTML to be output for the preview.
1661 protected function showPreview( $text ) {
1663 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1664 $this->mArticle
->openShowCategory();
1666 # This hook seems slightly odd here, but makes things more
1667 # consistent for extensions.
1668 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1669 $wgOut->addHTML( $text );
1670 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1671 $this->mArticle
->closeShowCategory();
1676 * Live Preview lets us fetch rendered preview page content and
1677 * add it to the page without refreshing the whole page.
1678 * If not supported by the browser it will fall through to the normal form
1679 * submission method.
1681 * This function outputs a script tag to support live preview, and
1682 * returns an onclick handler which should be added to the attributes
1683 * of the preview button
1685 function doLivePreviewScript() {
1686 global $wgOut, $wgTitle;
1687 $wgOut->addScriptFile( 'preview.js' );
1688 $liveAction = $wgTitle->getLocalUrl( array(
1689 'action' => $this->action
,
1690 'wpPreview' => 'true',
1693 return "return !lpDoPreview(" .
1694 "editform.wpTextbox1.value," .
1695 '"' . $liveAction . '"' . ")";
1698 protected function showEditTools() {
1700 $wgOut->addHTML( '<div class="mw-editTools">' );
1701 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1702 $wgOut->addHTML( '</div>' );
1705 protected function getLastDelete() {
1706 $dbr = wfGetDB( DB_SLAVE
);
1707 $data = $dbr->selectRow(
1708 array( 'logging', 'user' ),
1719 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1720 'log_title' => $this->mTitle
->getDBkey(),
1721 'log_type' => 'delete',
1722 'log_action' => 'delete',
1723 'user_id=log_user' ),
1725 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' )
1727 // Quick paranoid permission checks...
1728 if( is_object($data) ) {
1729 if( $data->log_deleted
& LogPage
::DELETED_USER
)
1730 $data->user_name
= wfMsgHtml('rev-deleted-user');
1731 if( $data->log_deleted
& LogPage
::DELETED_COMMENT
)
1732 $data->log_comment
= wfMsgHtml('rev-deleted-comment');
1738 * Get the rendered text for previewing.
1741 function getPreviewText() {
1742 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang, $wgMessageCache;
1744 wfProfileIn( __METHOD__
);
1746 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1747 if ( $this->mTokenOkExceptSuffix
) {
1748 $note = wfMsg( 'token_suffix_mismatch' );
1750 $note = wfMsg( 'session_fail_preview' );
1753 $note = wfMsg( 'previewnote' );
1756 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1757 $parserOptions->setEditSection( false );
1758 $parserOptions->setIsPreview( true );
1759 $parserOptions->setIsSectionPreview( !is_null($this->section
) && $this->section
!== '' );
1762 if ( $wgRawHtml && !$this->mTokenOk
) {
1763 // Could be an offsite preview attempt. This is very unsafe if
1764 // HTML is enabled, as it could be an attack.
1765 return $wgOut->parse( "<div class='previewnote'>" .
1766 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1769 # don't parse user css/js, show message about preview
1770 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1772 if ( $this->isCssJsSubpage
) {
1773 if (preg_match("/\\.css$/", $this->mTitle
->getText() ) ) {
1774 $previewtext = wfMsg('usercsspreview');
1775 } else if (preg_match("/\\.js$/", $this->mTitle
->getText() ) ) {
1776 $previewtext = wfMsg('userjspreview');
1778 $parserOptions->setTidy(true);
1779 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
1780 $previewHTML = $parserOutput->mText
;
1781 } elseif ( $rt = Title
::newFromRedirectArray( $this->textbox1
) ) {
1782 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
1784 $toparse = $this->textbox1
;
1786 # If we're adding a comment, we need to show the
1787 # summary as the headline
1788 if ( $this->section
=="new" && $this->summary
!="" ) {
1789 $toparse="== {$this->summary} ==\n\n".$toparse;
1792 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1794 // Parse mediawiki messages with correct target language
1795 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1796 list( /* $unused */, $lang ) = $wgMessageCache->figureMessage( $this->mTitle
->getText() );
1797 $obj = wfGetLangObj( $lang );
1798 $parserOptions->setTargetLanguage( $obj );
1802 $parserOptions->setTidy(true);
1803 $parserOptions->enableLimitReport();
1804 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ),
1805 $this->mTitle
, $parserOptions );
1807 $previewHTML = $parserOutput->getText();
1808 $this->mParserOutput
= $parserOutput;
1809 $wgOut->addParserOutputNoText( $parserOutput );
1811 if ( count( $parserOutput->getWarnings() ) ) {
1812 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1816 if( $this->isConflict
) {
1817 $conflict = '<h2 id="mw-previewconflict">' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1819 $conflict = '<hr />';
1822 $previewhead = "<div class='previewnote'>\n" .
1823 '<h2 id="mw-previewheader">' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>" .
1824 $wgOut->parse( $note ) . $conflict . "</div>\n";
1826 wfProfileOut( __METHOD__
);
1827 return $previewhead . $previewHTML;
1830 function getTemplates() {
1831 if ( $this->preview ||
$this->section
!= '' ) {
1832 $templates = array();
1833 if ( !isset($this->mParserOutput
) ) return $templates;
1834 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
1835 foreach( array_keys( $template ) as $dbk ) {
1836 $templates[] = Title
::makeTitle($ns, $dbk);
1841 return $this->mArticle
->getUsedTemplates();
1846 * Call the stock "user is blocked" page
1848 function blockedPage() {
1849 global $wgOut, $wgUser;
1850 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1852 # If the user made changes, preserve them when showing the markup
1853 # (This happens when a user is blocked during edit, for instance)
1854 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1856 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1858 $source = $this->textbox1
;
1861 # Spit out the source or the user's modified version
1862 if ( $source !== false ) {
1863 $rows = $wgUser->getIntOption( 'rows' );
1864 $cols = $wgUser->getIntOption( 'cols' );
1865 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1866 $wgOut->addHTML( '<hr />' );
1867 $wgOut->addWikiMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() );
1868 # Why we don't use Xml::element here?
1869 # Is it because if $source is '', it returns <textarea />?
1870 $wgOut->addHTML( Xml
::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml
::closeElement( 'textarea' ) );
1875 * Produce the stock "please login to edit pages" page
1877 function userNotLoggedInPage() {
1878 global $wgUser, $wgOut, $wgTitle;
1879 $skin = $wgUser->getSkin();
1881 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1882 $loginLink = $skin->link(
1884 wfMsgHtml( 'loginreqlink' ),
1886 array( 'returnto' => $wgTitle->getPrefixedText() ),
1887 array( 'known', 'noclasses' )
1890 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1891 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1892 $wgOut->setArticleRelated( false );
1894 $wgOut->addHTML( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1895 $wgOut->returnToMain( false, $wgTitle );
1899 * Creates a basic error page which informs the user that
1900 * they have attempted to edit a nonexistent section.
1902 function noSuchSectionPage() {
1903 global $wgOut, $wgTitle;
1905 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1906 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1907 $wgOut->setArticleRelated( false );
1909 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section
);
1910 $wgOut->returnToMain( false, $wgTitle );
1914 * Produce the stock "your edit contains spam" page
1916 * @param $match Text which triggered one or more filters
1918 function spamPage( $match = false ) {
1919 global $wgOut, $wgTitle;
1921 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1922 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1923 $wgOut->setArticleRelated( false );
1925 $wgOut->addHTML( '<div id="spamprotected">' );
1926 $wgOut->addWikiMsg( 'spamprotectiontext' );
1928 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1929 $wgOut->addHTML( '</div>' );
1931 $wgOut->returnToMain( false, $wgTitle );
1938 function mergeChangesInto( &$editText ){
1939 $fname = 'EditPage::mergeChangesInto';
1940 wfProfileIn( $fname );
1942 $db = wfGetDB( DB_MASTER
);
1944 // This is the revision the editor started from
1945 $baseRevision = $this->getBaseRevision();
1946 if ( is_null( $baseRevision ) ) {
1947 wfProfileOut( $fname );
1950 $baseText = $baseRevision->getText();
1952 // The current state, we want to merge updates into it
1953 $currentRevision = Revision
::loadFromTitle( $db, $this->mTitle
);
1954 if ( is_null( $currentRevision ) ) {
1955 wfProfileOut( $fname );
1958 $currentText = $currentRevision->getText();
1961 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1962 $editText = $result;
1963 wfProfileOut( $fname );
1966 wfProfileOut( $fname );
1972 * Check if the browser is on a blacklist of user-agents known to
1973 * mangle UTF-8 data on form submission. Returns true if Unicode
1974 * should make it through, false if it's known to be a problem.
1978 function checkUnicodeCompliantBrowser() {
1979 global $wgBrowserBlackList;
1980 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1981 // No User-Agent header sent? Trust it by default...
1984 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1985 foreach ( $wgBrowserBlackList as $browser ) {
1986 if ( preg_match($browser, $currentbrowser) ) {
1994 * @deprecated use $wgParser->stripSectionName()
1996 function pseudoParseSectionAnchor( $text ) {
1998 return $wgParser->stripSectionName( $text );
2002 * Format an anchor fragment as it would appear for a given section name
2003 * @param string $text
2007 function sectionAnchor( $text ) {
2009 return $wgParser->guessSectionNameFromWikiText( $text );
2013 * Shows a bulletin board style toolbar for common editing functions.
2014 * It can be disabled in the user preferences.
2015 * The necessary JavaScript code can be found in skins/common/edit.js.
2019 static function getEditToolbar() {
2020 global $wgStylePath, $wgContLang, $wgLang, $wgJsMimeType;
2023 * toolarray an array of arrays which each include the filename of
2024 * the button image (without path), the opening tag, the closing tag,
2025 * and optionally a sample text that is inserted between the two when no
2026 * selection is highlighted.
2027 * The tip text is shown when the user moves the mouse over the button.
2029 * Already here are accesskeys (key), which are not used yet until someone
2030 * can figure out a way to make them work in IE. However, we should make
2031 * sure these keys are not defined on the edit page.
2035 'image' => $wgLang->getImageFile('button-bold'),
2036 'id' => 'mw-editbutton-bold',
2038 'close' => '\'\'\'',
2039 'sample' => wfMsg('bold_sample'),
2040 'tip' => wfMsg('bold_tip'),
2044 'image' => $wgLang->getImageFile('button-italic'),
2045 'id' => 'mw-editbutton-italic',
2048 'sample' => wfMsg('italic_sample'),
2049 'tip' => wfMsg('italic_tip'),
2053 'image' => $wgLang->getImageFile('button-link'),
2054 'id' => 'mw-editbutton-link',
2057 'sample' => wfMsg('link_sample'),
2058 'tip' => wfMsg('link_tip'),
2062 'image' => $wgLang->getImageFile('button-extlink'),
2063 'id' => 'mw-editbutton-extlink',
2066 'sample' => wfMsg('extlink_sample'),
2067 'tip' => wfMsg('extlink_tip'),
2071 'image' => $wgLang->getImageFile('button-headline'),
2072 'id' => 'mw-editbutton-headline',
2075 'sample' => wfMsg('headline_sample'),
2076 'tip' => wfMsg('headline_tip'),
2080 'image' => $wgLang->getImageFile('button-image'),
2081 'id' => 'mw-editbutton-image',
2082 'open' => '[['.$wgContLang->getNsText(NS_FILE
).':',
2084 'sample' => wfMsg('image_sample'),
2085 'tip' => wfMsg('image_tip'),
2089 'image' => $wgLang->getImageFile('button-media'),
2090 'id' => 'mw-editbutton-media',
2091 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
2093 'sample' => wfMsg('media_sample'),
2094 'tip' => wfMsg('media_tip'),
2098 'image' => $wgLang->getImageFile('button-math'),
2099 'id' => 'mw-editbutton-math',
2101 'close' => "</math>",
2102 'sample' => wfMsg('math_sample'),
2103 'tip' => wfMsg('math_tip'),
2107 'image' => $wgLang->getImageFile('button-nowiki'),
2108 'id' => 'mw-editbutton-nowiki',
2109 'open' => "<nowiki>",
2110 'close' => "</nowiki>",
2111 'sample' => wfMsg('nowiki_sample'),
2112 'tip' => wfMsg('nowiki_tip'),
2116 'image' => $wgLang->getImageFile('button-sig'),
2117 'id' => 'mw-editbutton-signature',
2121 'tip' => wfMsg('sig_tip'),
2125 'image' => $wgLang->getImageFile('button-hr'),
2126 'id' => 'mw-editbutton-hr',
2127 'open' => "\n----\n",
2130 'tip' => wfMsg('hr_tip'),
2134 $toolbar = "<div id='toolbar'>\n";
2135 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
2137 foreach($toolarray as $tool) {
2139 $image = $wgStylePath.'/common/images/'.$tool['image'],
2140 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2141 // Older browsers show a "speedtip" type message only for ALT.
2142 // Ideally these should be different, realistically they
2143 // probably don't need to be.
2144 $tip = $tool['tip'],
2145 $open = $tool['open'],
2146 $close = $tool['close'],
2147 $sample = $tool['sample'],
2148 $cssId = $tool['id'],
2151 $paramList = implode( ',',
2152 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2153 $toolbar.="addButton($paramList);\n";
2156 $toolbar.="/*]]>*/\n</script>";
2157 $toolbar.="\n</div>";
2159 wfRunHooks( 'EditPageBeforeEditToolbar', array( &$toolbar ) );
2165 * Returns an array of html code of the following checkboxes:
2168 * @param $tabindex Current tabindex
2169 * @param $skin Skin object
2170 * @param $checked Array of checkbox => bool, where bool indicates the checked
2171 * status of the checkbox
2175 public function getCheckboxes( &$tabindex, $skin, $checked ) {
2178 $checkboxes = array();
2180 $checkboxes['minor'] = '';
2181 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
2182 if ( $wgUser->isAllowed('minoredit') ) {
2184 'tabindex' => ++
$tabindex,
2185 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2186 'id' => 'wpMinoredit',
2188 $checkboxes['minor'] =
2189 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2190 " <label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
2193 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2194 $checkboxes['watch'] = '';
2195 if ( $wgUser->isLoggedIn() ) {
2197 'tabindex' => ++
$tabindex,
2198 'accesskey' => wfMsg( 'accesskey-watch' ),
2199 'id' => 'wpWatchthis',
2201 $checkboxes['watch'] =
2202 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2203 " <label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
2205 wfRunHooks( 'EditPageBeforeEditChecks', array( &$this, &$checkboxes, &$tabindex ) );
2210 * Returns an array of html code of the following buttons:
2211 * save, diff, preview and live
2213 * @param $tabindex Current tabindex
2217 public function getEditButtons(&$tabindex) {
2218 global $wgLivePreview, $wgUser;
2226 'tabindex' => ++
$tabindex,
2227 'value' => wfMsg('savearticle'),
2228 'accesskey' => wfMsg('accesskey-save'),
2229 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2231 $buttons['save'] = Xml
::element('input', $temp, '');
2233 ++
$tabindex; // use the same for preview and live preview
2234 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2236 'id' => 'wpPreview',
2237 'name' => 'wpPreview',
2239 'tabindex' => $tabindex,
2240 'value' => wfMsg('showpreview'),
2242 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2243 'style' => 'display: none;',
2245 $buttons['preview'] = Xml
::element('input', $temp, '');
2248 'id' => 'wpLivePreview',
2249 'name' => 'wpLivePreview',
2251 'tabindex' => $tabindex,
2252 'value' => wfMsg('showlivepreview'),
2253 'accesskey' => wfMsg('accesskey-preview'),
2255 'onclick' => $this->doLivePreviewScript(),
2257 $buttons['live'] = Xml
::element('input', $temp, '');
2260 'id' => 'wpPreview',
2261 'name' => 'wpPreview',
2263 'tabindex' => $tabindex,
2264 'value' => wfMsg('showpreview'),
2265 'accesskey' => wfMsg('accesskey-preview'),
2266 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2268 $buttons['preview'] = Xml
::element('input', $temp, '');
2269 $buttons['live'] = '';
2276 'tabindex' => ++
$tabindex,
2277 'value' => wfMsg('showdiff'),
2278 'accesskey' => wfMsg('accesskey-diff'),
2279 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2281 $buttons['diff'] = Xml
::element('input', $temp, '');
2283 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons, &$tabindex ) );
2288 * Output preview text only. This can be sucked into the edit page
2289 * via JavaScript, and saves the server time rendering the skin as
2290 * well as theoretically being more robust on the client (doesn't
2291 * disturb the edit box's undo history, won't eat your text on
2294 * @todo This doesn't include category or interlanguage links.
2295 * Would need to enhance it a bit, <s>maybe wrap them in XML
2296 * or something...</s> that might also require more skin
2297 * initialization, so check whether that's a problem.
2299 function livePreview() {
2302 header( 'Content-type: text/xml; charset=utf-8' );
2303 header( 'Cache-control: no-cache' );
2305 $previewText = $this->getPreviewText();
2306 #$categories = $skin->getCategoryLinks();
2309 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2310 Xml
::tags( 'livepreview', null,
2311 Xml
::element( 'preview', null, $previewText )
2312 #. Xml::element( 'category', null, $categories )
2319 * Get a diff between the current contents of the edit box and the
2320 * version of the page we're editing from.
2322 * If this is a section edit, we'll replace the section as for final
2323 * save and then make a comparison.
2325 function showDiff() {
2326 $oldtext = $this->mArticle
->fetchContent();
2327 $newtext = $this->mArticle
->replaceSection(
2328 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2329 $newtext = $this->mArticle
->preSaveTransform( $newtext );
2330 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2331 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2332 if ( $oldtext !== false ||
$newtext != '' ) {
2333 $de = new DifferenceEngine( $this->mTitle
);
2334 $de->setText( $oldtext, $newtext );
2335 $difftext = $de->getDiff( $oldtitle, $newtitle );
2336 $de->showDiffStyle();
2342 $wgOut->addHTML( '<div id="wikiDiff">' . $difftext . '</div>' );
2346 * Filter an input field through a Unicode de-armoring process if it
2347 * came from an old browser with known broken Unicode editing issues.
2349 * @param WebRequest $request
2350 * @param string $field
2354 function safeUnicodeInput( $request, $field ) {
2355 $text = rtrim( $request->getText( $field ) );
2356 return $request->getBool( 'safemode' )
2357 ?
$this->unmakesafe( $text )
2362 * Filter an output field through a Unicode armoring process if it is
2363 * going to an old browser with known broken Unicode editing issues.
2365 * @param string $text
2369 function safeUnicodeOutput( $text ) {
2371 $codedText = $wgContLang->recodeForEdit( $text );
2372 return $this->checkUnicodeCompliantBrowser()
2374 : $this->makesafe( $codedText );
2378 * A number of web browsers are known to corrupt non-ASCII characters
2379 * in a UTF-8 text editing environment. To protect against this,
2380 * detected browsers will be served an armored version of the text,
2381 * with non-ASCII chars converted to numeric HTML character references.
2383 * Preexisting such character references will have a 0 added to them
2384 * to ensure that round-trips do not alter the original data.
2386 * @param string $invalue
2390 function makesafe( $invalue ) {
2391 // Armor existing references for reversability.
2392 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2397 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2398 $bytevalue = ord( $invalue{$i} );
2399 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2400 $result .= chr( $bytevalue );
2402 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2403 $working = $working << 6;
2404 $working +
= ($bytevalue & 0x3F);
2406 if ( $bytesleft <= 0 ) {
2407 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2409 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2410 $working = $bytevalue & 0x1F;
2412 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2413 $working = $bytevalue & 0x0F;
2415 } else { //1111 0xxx
2416 $working = $bytevalue & 0x07;
2424 * Reverse the previously applied transliteration of non-ASCII characters
2425 * back to UTF-8. Used to protect data from corruption by broken web browsers
2426 * as listed in $wgBrowserBlackList.
2428 * @param string $invalue
2432 function unmakesafe( $invalue ) {
2434 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2435 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2439 $hexstring .= $invalue{$i};
2441 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2443 // Do some sanity checks. These aren't needed for reversability,
2444 // but should help keep the breakage down if the editor
2445 // breaks one of the entities whilst editing.
2446 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2447 $codepoint = hexdec($hexstring);
2448 $result .= codepointToUtf8( $codepoint );
2450 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2453 $result .= substr( $invalue, $i, 1 );
2456 // reverse the transform that we made for reversability reasons.
2457 return strtr( $result, array( "�" => "&#x" ) );
2460 function noCreatePermission() {
2462 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2463 $wgOut->addWikiMsg( 'nocreatetext' );
2467 * If there are rows in the deletion/move log for this page, show them,
2468 * along with a nice little note for the user
2470 * @param OutputPage $out
2472 protected function showLogs( $out ) {
2474 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
2475 $pager = new LogPager( $loglist, array('move', 'delete'), false,
2476 $this->mTitle
->getPrefixedText(), '', array( "log_action != 'revision'" ) );
2478 $count = $pager->getNumRows();
2480 $pager->mLimit
= 10;
2481 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
2482 $out->addWikiMsg( 'recreate-moveddeleted-warn' );
2484 $loglist->beginLogEventsList() .
2486 $loglist->endLogEventsList()
2489 $out->addHTML( $wgUser->getSkin()->link(
2490 SpecialPage
::getTitleFor( 'Log' ),
2491 wfMsgHtml( 'log-fulllog' ),
2493 array( 'page' => $this->mTitle
->getPrefixedText() ) ) );
2495 $out->addHTML( '</div>' );
2503 * Attempt submission
2504 * @return bool false if output is done, true if the rest of the form should be displayed
2506 function attemptSave() {
2507 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2509 $resultDetails = false;
2510 # Allow bots to exempt some edits from bot flagging
2511 $bot = $wgUser->isAllowed('bot') && $wgRequest->getBool('bot',true);
2512 $value = $this->internalAttemptSave( $resultDetails, $bot );
2514 if ( $value == self
::AS_SUCCESS_UPDATE ||
$value == self
::AS_SUCCESS_NEW_ARTICLE
) {
2515 $this->didSave
= true;
2519 case self
::AS_HOOK_ERROR_EXPECTED
:
2520 case self
::AS_CONTENT_TOO_BIG
:
2521 case self
::AS_ARTICLE_WAS_DELETED
:
2522 case self
::AS_CONFLICT_DETECTED
:
2523 case self
::AS_SUMMARY_NEEDED
:
2524 case self
::AS_TEXTBOX_EMPTY
:
2525 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
2529 case self
::AS_HOOK_ERROR
:
2530 case self
::AS_FILTERING
:
2531 case self
::AS_SUCCESS_NEW_ARTICLE
:
2532 case self
::AS_SUCCESS_UPDATE
:
2535 case self
::AS_SPAM_ERROR
:
2536 $this->spamPage ( $resultDetails['spam'] );
2539 case self
::AS_BLOCKED_PAGE_FOR_USER
:
2540 $this->blockedPage();
2543 case self
::AS_IMAGE_REDIRECT_ANON
:
2544 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2547 case self
::AS_READ_ONLY_PAGE_ANON
:
2548 $this->userNotLoggedInPage();
2551 case self
::AS_READ_ONLY_PAGE_LOGGED
:
2552 case self
::AS_READ_ONLY_PAGE
:
2553 $wgOut->readOnlyPage();
2556 case self
::AS_RATE_LIMITED
:
2557 $wgOut->rateLimited();
2560 case self
::AS_NO_CREATE_PERMISSION
;
2561 $this->noCreatePermission();
2564 case self
::AS_BLANK_ARTICLE
:
2565 $wgOut->redirect( $wgTitle->getFullURL() );
2568 case self
::AS_IMAGE_REDIRECT_LOGGED
:
2569 $wgOut->permissionRequired( 'upload' );
2574 function getBaseRevision() {
2575 if ( $this->mBaseRevision
== false ) {
2576 $db = wfGetDB( DB_MASTER
);
2577 $baseRevision = Revision
::loadFromTimestamp(
2578 $db, $this->mTitle
, $this->edittime
);
2579 return $this->mBaseRevision
= $baseRevision;
2581 return $this->mBaseRevision
;