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;
88 public $suppressIntro = false;
94 function EditPage( $article ) {
95 $this->mArticle
=& $article;
96 $this->mTitle
= $article->getTitle();
97 $this->action
= 'submit';
99 # Placeholders for text injection by hooks (empty per default)
100 $this->editFormPageTop
=
101 $this->editFormTextTop
=
102 $this->editFormTextBeforeContent
=
103 $this->editFormTextAfterWarn
=
104 $this->editFormTextAfterTools
=
105 $this->editFormTextBottom
= "";
109 * Fetch initial editing page content.
112 function getContent( $def_text = '' ) {
113 global $wgOut, $wgRequest, $wgParser, $wgContLang, $wgMessageCache;
115 wfProfileIn( __METHOD__
);
116 # Get variables from query string :P
117 $section = $wgRequest->getVal( 'section' );
118 $preload = $wgRequest->getVal( 'preload' );
119 $undoafter = $wgRequest->getVal( 'undoafter' );
120 $undo = $wgRequest->getVal( 'undo' );
123 // For message page not locally set, use the i18n message.
124 // For other non-existent articles, use preload text if any.
125 if ( !$this->mTitle
->exists() ) {
126 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
127 # If this is a system message, get the default text.
128 list( $message, $lang ) = $wgMessageCache->figureMessage( $wgContLang->lcfirst( $this->mTitle
->getText() ) );
129 $wgMessageCache->loadAllMessages( $lang );
130 $text = wfMsgGetKey( $message, false, $lang, false );
131 if( wfEmptyMsg( $message, $text ) )
134 # If requested, preload some text.
135 $text = $this->getPreloadedText( $preload );
137 // For existing pages, get text based on "undo" or section parameters.
139 $text = $this->mArticle
->getContent();
140 if ( $undo > 0 && $undoafter > 0 && $undo < $undoafter ) {
141 # If they got undoafter and undo round the wrong way, switch them
142 list( $undo, $undoafter ) = array( $undoafter, $undo );
144 if ( $undo > 0 && $undo > $undoafter ) {
145 # Undoing a specific edit overrides section editing; section-editing
146 # doesn't work with undoing.
148 $undorev = Revision
::newFromId($undo);
149 $oldrev = Revision
::newFromId($undoafter);
151 $undorev = Revision
::newFromId($undo);
152 $oldrev = $undorev ?
$undorev->getPrevious() : null;
155 # Sanity check, make sure it's the right page,
156 # the revisions exist and they were not deleted.
157 # Otherwise, $text will be left as-is.
158 if ( !is_null( $undorev ) && !is_null( $oldrev ) &&
159 $undorev->getPage() == $oldrev->getPage() &&
160 $undorev->getPage() == $this->mArticle
->getID() &&
161 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
162 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
163 $undorev_text = $undorev->getText();
164 $oldrev_text = $oldrev->getText();
165 $currev_text = $text;
167 if ( $currev_text != $undorev_text ) {
168 $result = wfMerge( $undorev_text, $oldrev_text, $currev_text, $text );
170 # No use doing a merge if it's just a straight revert.
171 $text = $oldrev_text;
175 # Inform the user of our success and set an automatic edit summary
176 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
177 $firstrev = $oldrev->getNext();
178 # If we just undid one rev, use an autosummary
179 if ( $firstrev->mId
== $undo ) {
180 $this->summary
= wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
182 $this->formtype
= 'diff';
184 # Warn the user that something went wrong
185 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
188 // Failed basic sanity checks.
189 // Older revisions may have been removed since the link
190 // was created, or we may simply have got bogus input.
191 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-norev' ) );
193 } else if ( $section != '' ) {
194 if ( $section == 'new' ) {
195 $text = $this->getPreloadedText( $preload );
197 $text = $wgParser->getSection( $text, $section, $def_text );
202 wfProfileOut( __METHOD__
);
207 * Get the contents of a page from its title and remove includeonly tags
209 * @param $preload String: the title of the page.
210 * @return string The contents of the page.
212 protected function getPreloadedText( $preload ) {
213 if ( $preload === '' ) {
216 $preloadTitle = Title
::newFromText( $preload );
217 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
218 $rev = Revision
::newFromTitle($preloadTitle);
219 if ( is_object( $rev ) ) {
220 $text = $rev->getText();
221 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
222 // its own mini-parser! -ævar
223 $text = preg_replace( '~</?includeonly>~', '', $text );
232 * This is the function that extracts metadata from the article body on the first view.
233 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
234 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
236 function extractMetaDataFromArticle () {
237 global $wgUseMetadataEdit, $wgMetadataWhitelist, $wgContLang;
238 $this->mMetaData
= '';
239 if ( !$wgUseMetadataEdit ) return;
240 if ( $wgMetadataWhitelist == '' ) return;
242 $t = $this->getContent();
244 # MISSING : <nowiki> filtering
246 # Categories and language links
247 $t = explode ( "\n" , $t );
248 $catlow = strtolower ( $wgContLang->getNsText( NS_CATEGORY
) );
249 $cat = $ll = array();
250 foreach ( $t AS $key => $x ) {
251 $y = trim ( strtolower ( $x ) );
252 while ( substr ( $y , 0 , 2 ) == '[[' ) {
253 $y = explode ( ']]' , trim ( $x ) );
254 $first = array_shift ( $y );
255 $first = explode ( ':' , $first );
256 $ns = array_shift ( $first );
257 $ns = trim ( str_replace ( '[' , '' , $ns ) );
258 if ( $wgContLang->getLanguageName( $ns ) ||
strtolower ( $ns ) == $catlow ) {
259 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]';
260 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add;
262 $x = implode ( ']]' , $y );
264 $y = trim ( strtolower ( $x ) );
266 $x = implode ( ']]' , $y );
267 $y = trim ( strtolower ( $x ) );
271 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n";
272 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n";
273 $t = implode ( "\n" , $t );
276 $sat = array () ; # stand-alone-templates; must be lowercase
277 $wl_title = Title
::newFromText ( $wgMetadataWhitelist );
278 $wl_article = new Article ( $wl_title );
279 $wl = explode ( "\n" , $wl_article->getContent() );
280 foreach ( $wl AS $x ) {
283 while ( substr ( $x , 0 , 1 ) == '*' ) {
285 $x = trim ( substr ( $x , 1 ) );
288 $sat[] = strtolower ( $x );
293 # Templates, but only some
294 $t = explode ( '{{' , $t );
296 foreach ( $t AS $key => $x ) {
297 $y = explode ( '}}' , $x , 2 );
298 if ( count ( $y ) == 2 ) {
300 $z = explode ( '|' , $z );
301 $tn = array_shift ( $z );
302 if ( in_array ( strtolower ( $tn ) , $sat ) ) {
303 $tl[] = '{{' . $y[0] . '}}';
305 $y = explode ( '}}' , $y[1] , 2 );
307 else $t[$key] = '{{' . $x;
309 else if ( $key != 0 ) $t[$key] = '{{' . $x;
312 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl );
313 $t = implode ( '' , $t );
315 $t = str_replace ( "\n\n\n" , "\n" , $t );
316 $this->mArticle
->mContent
= $t;
317 $this->mMetaData
= $s;
321 * Check if a page was deleted while the user was editing it, before submit.
322 * Note that we rely on the logging table, which hasn't been always there,
323 * but that doesn't matter, because this only applies to brand new
326 protected function wasDeletedSinceLastEdit() {
327 if ( $this->deletedSinceEdit
)
329 if ( $this->mTitle
->isDeleted() ) {
330 $this->lastDelete
= $this->getLastDelete();
331 if ( $this->lastDelete
) {
332 $deleteTime = wfTimestamp( TS_MW
, $this->lastDelete
->log_timestamp
);
333 if ( $deleteTime > $this->starttime
) {
334 $this->deletedSinceEdit
= true;
338 return $this->deletedSinceEdit
;
346 * This is the function that gets called for "action=edit". It
347 * sets up various member variables, then passes execution to
348 * another function, usually showEditForm()
350 * The edit form is self-submitting, so that when things like
351 * preview and edit conflicts occur, we get the same form back
352 * with the extra stuff added. Only when the final submission
353 * is made and all is well do we actually save and redirect to
354 * the newly-edited page.
357 global $wgOut, $wgUser, $wgRequest;
358 // Allow extensions to modify/prevent this form or submission
359 if ( !wfRunHooks( 'AlternateEdit', array( &$this ) ) ) {
363 wfProfileIn( __METHOD__
);
364 wfDebug( __METHOD__
.": enter\n" );
366 // This is not an article
367 $wgOut->setArticleFlag( false );
369 $this->importFormData( $wgRequest );
370 $this->firsttime
= false;
373 $this->livePreview();
374 wfProfileOut( __METHOD__
);
378 if ( wfReadOnly() ) {
382 $this->preview
= true;
383 } elseif ( $this->preview ||
$this->diff
) {
384 // A warning will be displayed instead
386 $this->readOnlyPage( $this->getContent() );
387 wfProfileOut( __METHOD__
);
392 $wgOut->addScriptFile( 'edit.js' );
393 $permErrors = $this->getEditPermissionErrors();
395 wfDebug( __METHOD__
.": User can't edit\n" );
396 $this->readOnlyPage( $this->getContent(), true, $permErrors, 'edit' );
397 wfProfileOut( __METHOD__
);
401 $this->formtype
= 'save';
402 } else if ( $this->preview
) {
403 $this->formtype
= 'preview';
404 } else if ( $this->diff
) {
405 $this->formtype
= 'diff';
406 } else { # First time through
407 $this->firsttime
= true;
408 if ( $this->previewOnOpen() ) {
409 $this->formtype
= 'preview';
411 $this->extractMetaDataFromArticle () ;
412 $this->formtype
= 'initial';
417 wfProfileIn( __METHOD__
."-business-end" );
419 $this->isConflict
= false;
420 // css / js subpages of user pages get a special treatment
421 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
422 $this->isValidCssJsSubpage
= $this->mTitle
->isValidCssJsSubpage();
424 # Show applicable editing introductions
425 if ( $this->formtype
== 'initial' ||
$this->firsttime
)
428 if ( $this->mTitle
->isTalkPage() ) {
429 $wgOut->addWikiMsg( 'talkpagetext' );
432 # Optional notices on a per-namespace and per-page basis
433 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
434 $editnotice_page = $editnotice_ns.'-'.$this->mTitle
->getDBkey();
435 if ( !wfEmptyMsg( $editnotice_ns, wfMsgForContent( $editnotice_ns ) ) ) {
436 $wgOut->addWikiText( wfMsgForContent( $editnotice_ns ) );
438 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
439 $parts = explode( '/', $this->mTitle
->getDBkey() );
440 $editnotice_base = $editnotice_ns;
441 while ( count( $parts ) > 0 ) {
442 $editnotice_base .= '-'.array_shift( $parts );
443 if ( !wfEmptyMsg( $editnotice_base, wfMsgForContent( $editnotice_base ) ) ) {
444 $wgOut->addWikiText( wfMsgForContent( $editnotice_base ) );
447 } else if ( !wfEmptyMsg( $editnotice_page, wfMsgForContent( $editnotice_page ) ) ) {
448 $wgOut->addWikiText( wfMsgForContent( $editnotice_page ) );
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' ) !== '' ||
$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' );
653 $this->oldid
= $request->getInt( 'oldid' );
655 $this->live
= $request->getCheck( 'live' );
656 $this->editintro
= $request->getText( 'editintro' );
658 wfProfileOut( $fname );
662 * Make sure the form isn't faking a user's credentials.
664 * @param $request WebRequest
668 function tokenOk( &$request ) {
670 $token = $request->getVal( 'wpEditToken' );
671 $this->mTokenOk
= $wgUser->matchEditToken( $token );
672 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
673 return $this->mTokenOk
;
677 * Show all applicable editing introductions
679 protected function showIntro() {
680 global $wgOut, $wgUser;
681 if ( $this->suppressIntro
) {
684 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
685 if ( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
686 $parts = explode( '/', $this->mTitle
->getText(), 2 );
687 $username = $parts[0];
688 $id = User
::idFromName( $username );
689 $ip = User
::isIP( $username );
690 if ( $id == 0 && !$ip ) {
691 $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
692 array( 'userpage-userdoesnotexist', $username ) );
695 # Try to add a custom edit intro, or use the standard one if this is not possible.
696 if ( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
697 if ( $wgUser->isLoggedIn() ) {
698 $wgOut->wrapWikiMsg( '<div class="mw-newarticletext">$1</div>', 'newarticletext' );
700 $wgOut->wrapWikiMsg( '<div class="mw-newarticletextanon">$1</div>', 'newarticletextanon' );
703 # Give a notice if the user is editing a deleted page...
704 if ( !$this->mTitle
->exists() ) {
705 $this->showDeletionLog( $wgOut );
710 * Attempt to show a custom editing introduction, if supplied
714 protected function showCustomIntro() {
715 if ( $this->editintro
) {
716 $title = Title
::newFromText( $this->editintro
);
717 if ( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
719 $revision = Revision
::newFromTitle( $title );
720 $wgOut->addWikiTextTitleTidy( $revision->getText(), $this->mTitle
);
731 * Attempt submission (no UI)
732 * @return one of the constants describing the result
734 function internalAttemptSave( &$result, $bot = false ) {
735 global $wgFilterCallback, $wgUser, $wgOut, $wgParser;
736 global $wgMaxArticleSize;
738 $fname = 'EditPage::attemptSave';
739 wfProfileIn( $fname );
740 wfProfileIn( "$fname-checks" );
742 if ( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
744 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
745 return self
::AS_HOOK_ERROR
;
748 # Check image redirect
749 if ( $this->mTitle
->getNamespace() == NS_IMAGE
&&
750 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
751 !$wgUser->isAllowed( 'upload' ) ) {
752 if ( $wgUser->isAnon() ) {
753 return self
::AS_IMAGE_REDIRECT_ANON
;
755 return self
::AS_IMAGE_REDIRECT_LOGGED
;
759 # Reintegrate metadata
760 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
761 $this->mMetaData
= '' ;
764 $match = self
::matchSpamRegex( $this->summary
);
765 if ( $match === false ) {
766 $match = self
::matchSpamRegex( $this->textbox1
);
768 if ( $match !== false ) {
769 $result['spam'] = $match;
771 $pdbk = $this->mTitle
->getPrefixedDBkey();
772 $match = str_replace( "\n", '', $match );
773 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
774 wfProfileOut( "$fname-checks" );
775 wfProfileOut( $fname );
776 return self
::AS_SPAM_ERROR
;
778 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
779 # Error messages or other handling should be performed by the filter function
780 wfProfileOut( "$fname-checks" );
781 wfProfileOut( $fname );
782 return self
::AS_FILTERING
;
784 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
785 # Error messages etc. could be handled within the hook...
786 wfProfileOut( "$fname-checks" );
787 wfProfileOut( $fname );
788 return self
::AS_HOOK_ERROR
;
789 } elseif ( $this->hookError
!= '' ) {
790 # ...or the hook could be expecting us to produce an error
791 wfProfileOut( "$fname-checks" );
792 wfProfileOut( $fname );
793 return self
::AS_HOOK_ERROR_EXPECTED
;
795 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
796 # Check block state against master, thus 'false'.
797 wfProfileOut( "$fname-checks" );
798 wfProfileOut( $fname );
799 return self
::AS_BLOCKED_PAGE_FOR_USER
;
801 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
802 if ( $this->kblength
> $wgMaxArticleSize ) {
803 // Error will be displayed by showEditForm()
804 $this->tooBig
= true;
805 wfProfileOut( "$fname-checks" );
806 wfProfileOut( $fname );
807 return self
::AS_CONTENT_TOO_BIG
;
810 if ( !$wgUser->isAllowed('edit') ) {
811 if ( $wgUser->isAnon() ) {
812 wfProfileOut( "$fname-checks" );
813 wfProfileOut( $fname );
814 return self
::AS_READ_ONLY_PAGE_ANON
;
817 wfProfileOut( "$fname-checks" );
818 wfProfileOut( $fname );
819 return self
::AS_READ_ONLY_PAGE_LOGGED
;
823 if ( wfReadOnly() ) {
824 wfProfileOut( "$fname-checks" );
825 wfProfileOut( $fname );
826 return self
::AS_READ_ONLY_PAGE
;
828 if ( $wgUser->pingLimiter() ) {
829 wfProfileOut( "$fname-checks" );
830 wfProfileOut( $fname );
831 return self
::AS_RATE_LIMITED
;
834 # If the article has been deleted while editing, don't save it without
836 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
837 wfProfileOut( "$fname-checks" );
838 wfProfileOut( $fname );
839 return self
::AS_ARTICLE_WAS_DELETED
;
842 wfProfileOut( "$fname-checks" );
844 # If article is new, insert it.
845 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
847 // Late check for create permission, just in case *PARANOIA*
848 if ( !$this->mTitle
->userCan( 'create' ) ) {
849 wfDebug( "$fname: no create permission\n" );
850 wfProfileOut( $fname );
851 return self
::AS_NO_CREATE_PERMISSION
;
854 # Don't save a new article if it's blank.
855 if ( '' == $this->textbox1
) {
856 wfProfileOut( $fname );
857 return self
::AS_BLANK_ARTICLE
;
860 // Run post-section-merge edit filter
861 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
862 # Error messages etc. could be handled within the hook...
863 wfProfileOut( $fname );
864 return self
::AS_HOOK_ERROR
;
867 $isComment = ( $this->section
== 'new' );
869 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
870 $this->minoredit
, $this->watchthis
, false, $isComment, $bot);
872 wfProfileOut( $fname );
873 return self
::AS_SUCCESS_NEW_ARTICLE
;
876 # Article exists. Check for edit conflict.
878 $this->mArticle
->clear(); # Force reload of dates, etc.
879 $this->mArticle
->forUpdate( true ); # Lock the article
881 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
883 if ( $this->mArticle
->getTimestamp() != $this->edittime
) {
884 $this->isConflict
= true;
885 if ( $this->section
== 'new' ) {
886 if ( $this->mArticle
->getUserText() == $wgUser->getName() &&
887 $this->mArticle
->getComment() == $this->summary
) {
888 // Probably a duplicate submission of a new comment.
889 // This can happen when squid resends a request after
890 // a timeout but the first one actually went through.
891 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
893 // New comment; suppress conflict.
894 $this->isConflict
= false;
895 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
899 $userid = $wgUser->getId();
901 if ( $this->isConflict
) {
902 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
903 $this->mArticle
->getTimestamp() . "')\n" );
904 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
907 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
908 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
910 if ( is_null( $text ) ) {
911 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
912 $this->isConflict
= true;
913 $text = $this->textbox1
;
916 # Suppress edit conflict with self, except for section edits where merging is required.
917 if ( $this->section
== '' && $userid && $this->userWasLastToEdit($userid,$this->edittime
) ) {
918 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
919 $this->isConflict
= false;
921 # switch from section editing to normal editing in edit conflict
922 if ( $this->isConflict
) {
924 if ( $this->mergeChangesInto( $text ) ) {
925 // Successful merge! Maybe we should tell the user the good news?
926 $this->isConflict
= false;
927 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
930 $this->textbox1
= $text;
931 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
936 if ( $this->isConflict
) {
937 wfProfileOut( $fname );
938 return self
::AS_CONFLICT_DETECTED
;
941 $oldtext = $this->mArticle
->getContent();
943 // Run post-section-merge edit filter
944 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
945 # Error messages etc. could be handled within the hook...
946 wfProfileOut( $fname );
947 return self
::AS_HOOK_ERROR
;
950 # Handle the user preference to force summaries here, but not for null edits
951 if ( $this->section
!= 'new' && !$this->allowBlankSummary
&& 0 != strcmp($oldtext, $text) &&
952 !is_object( Title
::newFromRedirect( $text ) ) # check if it's not a redirect
954 if ( md5( $this->summary
) == $this->autoSumm
) {
955 $this->missingSummary
= true;
956 wfProfileOut( $fname );
957 return self
::AS_SUMMARY_NEEDED
;
961 # And a similar thing for new sections
962 if ( $this->section
== 'new' && !$this->allowBlankSummary
) {
963 if (trim($this->summary
) == '') {
964 $this->missingSummary
= true;
965 wfProfileOut( $fname );
966 return self
::AS_SUMMARY_NEEDED
;
971 wfProfileIn( "$fname-sectionanchor" );
973 if ( $this->section
== 'new' ) {
974 if ( $this->textbox1
== '' ) {
975 $this->missingComment
= true;
976 return self
::AS_TEXTBOX_EMPTY
;
978 if ( $this->summary
!= '' ) {
979 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary
);
980 # This is a new section, so create a link to the new section
981 # in the revision summary.
982 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
983 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
985 } elseif ( $this->section
!= '' ) {
986 # Try to get a section anchor from the section source, redirect to edited section if header found
987 # XXX: might be better to integrate this into Article::replaceSection
988 # for duplicate heading checking and maybe parsing
989 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
990 # we can't deal with anchors, includes, html etc in the header for now,
991 # headline would need to be parsed to improve this
992 if ( $hasmatch and strlen($matches[2]) > 0 ) {
993 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
996 wfProfileOut( "$fname-sectionanchor" );
998 // Save errors may fall down to the edit form, but we've now
999 // merged the section into full text. Clear the section field
1000 // so that later submission of conflict forms won't try to
1001 // replace that into a duplicated mess.
1002 $this->textbox1
= $text;
1003 $this->section
= '';
1005 // Check for length errors again now that the section is merged in
1006 $this->kblength
= (int)(strlen( $text ) / 1024);
1007 if ( $this->kblength
> $wgMaxArticleSize ) {
1008 $this->tooBig
= true;
1009 wfProfileOut( $fname );
1010 return self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
;
1013 # update the article here
1014 if ( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
1015 $this->watchthis
, $bot, $sectionanchor ) ) {
1016 wfProfileOut( $fname );
1017 return self
::AS_SUCCESS_UPDATE
;
1019 $this->isConflict
= true;
1021 wfProfileOut( $fname );
1022 return self
::AS_END
;
1026 * Check if no edits were made by other users since
1027 * the time a user started editing the page. Limit to
1028 * 20 revisions for the sake of sanity.
1030 protected function userWasLastToEdit( $id, $edittime ) {
1031 $dbw = wfGetDB( DB_MASTER
);
1032 $res = $dbw->select( 'revision',
1034 array( 'rev_page' => $this->mArticle
->getId(),
1035 'rev_timestamp > '.$dbw->timestamp($edittime) ),
1037 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 20 ) );
1038 while( $row = $res->fetchObject() ) {
1039 if( $row->rev_user
!= $id ) {
1047 * Check given input text against $wgSpamRegex, and return the text of the first match.
1048 * @return mixed -- matching string or false
1050 public static function matchSpamRegex( $text ) {
1051 global $wgSpamRegex;
1052 if ( $wgSpamRegex ) {
1053 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1054 $regexes = (array)$wgSpamRegex;
1055 foreach( $regexes as $regex ) {
1057 if ( preg_match( $regex, $text, $matches ) ) {
1066 * Initialise form fields in the object
1067 * Called on the first invocation, e.g. when a user clicks an edit link
1069 function initialiseForm() {
1070 $this->edittime
= $this->mArticle
->getTimestamp();
1071 $this->textbox1
= $this->getContent( false );
1072 if ( $this->textbox1
=== false ) return false;
1077 function setHeaders() {
1078 global $wgOut, $wgTitle;
1079 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1080 if ( $this->formtype
== 'preview' ) {
1081 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1083 if ( $this->isConflict
) {
1084 $wgOut->setPageTitle( wfMsg( 'editconflict', $wgTitle->getPrefixedText() ) );
1085 } elseif ( $this->section
!= '' ) {
1086 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1087 $wgOut->setPageTitle( wfMsg( $msg, $wgTitle->getPrefixedText() ) );
1089 # Use the title defined by DISPLAYTITLE magic word when present
1090 if ( isset($this->mParserOutput
)
1091 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1094 $title = $wgTitle->getPrefixedText();
1096 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1101 * Send the edit form and related headers to $wgOut
1102 * @param $formCallback Optional callable that takes an OutputPage
1103 * parameter; will be called during form output
1104 * near the top, for captchas and the like.
1106 function showEditForm( $formCallback=null ) {
1107 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle;
1109 # If $wgTitle is null, that means we're in API mode.
1110 # Some hook probably called this function without checking
1111 # for is_null($wgTitle) first. Bail out right here so we don't
1112 # do lots of work just to discard it right after.
1113 if (is_null($wgTitle))
1116 $fname = 'EditPage::showEditForm';
1117 wfProfileIn( $fname );
1119 $sk = $wgUser->getSkin();
1121 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
1123 #need to parse the preview early so that we know which templates are used,
1124 #otherwise users with "show preview after edit box" will get a blank list
1125 #we parse this near the beginning so that setHeaders can do the title
1126 #setting work instead of leaving it in getPreviewText
1127 $previewOutput = '';
1128 if ( $this->formtype
== 'preview' ) {
1129 $previewOutput = $this->getPreviewText();
1132 $this->setHeaders();
1134 # Enabled article-related sidebar, toplinks, etc.
1135 $wgOut->setArticleRelated( true );
1137 if ( $this->isConflict
) {
1138 $wgOut->addWikiMsg( 'explainconflict' );
1140 $this->textbox2
= $this->textbox1
;
1141 $this->textbox1
= $this->getContent();
1142 $this->edittime
= $this->mArticle
->getTimestamp();
1144 if ( $this->section
!= '' && $this->section
!= 'new' ) {
1146 if ( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1147 preg_match( "/^(=+)(.+)\\1/mi",
1150 if ( !empty( $matches[2] ) ) {
1152 $this->summary
= "/* " .
1153 $wgParser->stripSectionName(trim($matches[2])) .
1159 if ( $this->missingComment
) {
1160 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1163 if ( $this->missingSummary
&& $this->section
!= 'new' ) {
1164 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1167 if ( $this->missingSummary
&& $this->section
== 'new' ) {
1168 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1171 if ( $this->hookError
!== '' ) {
1172 $wgOut->addWikiText( $this->hookError
);
1175 if ( !$this->checkUnicodeCompliantBrowser() ) {
1176 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1178 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1179 // Let sysop know that this will make private content public if saved
1181 if ( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1182 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
1183 } else if ( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1184 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
1187 if ( !$this->mArticle
->mRevision
->isCurrent() ) {
1188 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1189 $wgOut->addWikiMsg( 'editingold' );
1194 if ( wfReadOnly() ) {
1195 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1196 } elseif ( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
1197 $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' );
1199 if ( $this->isCssJsSubpage
) {
1200 # Check the skin exists
1201 if ( $this->isValidCssJsSubpage
) {
1202 if ( $this->formtype
!== 'preview' ) {
1203 $wgOut->addWikiMsg( 'usercssjsyoucanpreview' );
1206 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1211 $classes = array(); // Textarea CSS
1212 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1213 # Show a warning if editing an interface message
1214 $wgOut->addWikiMsg( 'editinginterface' );
1215 } elseif ( $this->mTitle
->isProtected( 'edit' ) ) {
1216 # Is the title semi-protected?
1217 if ( $this->mTitle
->isSemiProtected() ) {
1218 $noticeMsg = 'semiprotectedpagewarning';
1219 $classes[] = 'mw-textarea-sprotected';
1221 # Then it must be protected based on static groups (regular)
1222 $noticeMsg = 'protectedpagewarning';
1223 $classes[] = 'mw-textarea-protected';
1225 $wgOut->addHTML( "<div class='mw-warning-with-logexcerpt'>\n" );
1226 $wgOut->addWikiMsg( $noticeMsg );
1227 LogEventsList
::showLogExtract( $wgOut, 'protect', $this->mTitle
->getPrefixedText(), '', 1 );
1228 $wgOut->addHTML( "</div>\n" );
1230 if ( $this->mTitle
->isCascadeProtected() ) {
1231 # Is this page under cascading protection from some source pages?
1232 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1234 if ( count($cascadeSources) > 0 ) {
1235 # Explain, and list the titles responsible
1236 foreach( $cascadeSources as $page ) {
1237 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1240 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', count($cascadeSources) ) );
1242 if ( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) ) {
1243 $wgOut->addWikiMsg( 'titleprotectedwarning' );
1246 if ( $this->kblength
=== false ) {
1247 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1249 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1250 $wgOut->addHTML( "<div id='mw-edit-longpageerror'>\n" );
1251 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) );
1252 $wgOut->addHTML( "</div>\n" );
1253 } elseif ( $this->kblength
> 29 ) {
1254 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1255 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) );
1256 $wgOut->addHTML( "</div>\n" );
1259 $q = 'action='.$this->action
;
1260 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1261 $action = $wgTitle->escapeLocalURL( $q );
1263 $colonSep = wfMsg( 'colon-separator' );
1264 $summary = wfMsg( 'summary' ) . $colonSep;
1265 $subject = wfMsg( 'subject' ) . $colonSep;
1267 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedText(),
1268 wfMsgExt('cancel', array('parseinline')) );
1269 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1270 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1271 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1272 htmlspecialchars( wfMsg( 'newwindow' ) );
1274 global $wgRightsText;
1275 if ( $wgRightsText ) {
1276 $copywarnMsg = array( 'copyrightwarning',
1277 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1280 $copywarnMsg = array( 'copyrightwarning2',
1281 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1284 if ( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1285 # prepare toolbar for edit buttons
1286 $toolbar = EditPage
::getEditToolbar();
1291 // activate checkboxes if user wants them to be always active
1292 if ( !$this->preview
&& !$this->diff
) {
1293 # Sort out the "watch" checkbox
1294 if ( $wgUser->getOption( 'watchdefault' ) ) {
1296 $this->watchthis
= true;
1297 } elseif ( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1299 $this->watchthis
= true;
1300 } elseif ( $this->mTitle
->userIsWatching() ) {
1302 $this->watchthis
= true;
1305 if ( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1308 $wgOut->addHTML( $this->editFormPageTop
);
1310 if ( $wgUser->getOption( 'previewontop' ) ) {
1311 $this->displayPreviewArea( $previewOutput, true );
1315 $wgOut->addHTML( $this->editFormTextTop
);
1317 # if this is a comment, show a subject line at the top, which is also the edit summary.
1318 # Otherwise, show a summary field at the bottom
1319 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1321 # If a blank edit summary was previously provided, and the appropriate
1322 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1323 # user being bounced back more than once in the event that a summary
1326 # For a bit more sophisticated detection of blank summaries, hash the
1327 # automatic one and pass that in the hidden field wpAutoSummary.
1328 $summaryhiddens = '';
1329 if ( $this->missingSummary
) $summaryhiddens .= Xml
::hidden( 'wpIgnoreBlankSummary', true );
1330 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1331 $summaryhiddens .= Xml
::hidden( 'wpAutoSummary', $autosumm );
1332 if ( $this->section
== 'new' ) {
1333 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}</label></span>\n<input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' />{$summaryhiddens}<br />";
1334 $editsummary = "<div class='editOptions'>\n";
1336 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary
) );
1337 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').$colonSep.$sk->commentBlock( $formattedSummary, $this->mTitle
, true )."</div>\n" : '';
1338 $summarypreview = '';
1340 $commentsubject = '';
1341 $editsummary="<div class='editOptions'>\n<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}</label></span>\n<input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' />{$summaryhiddens}<br />";
1342 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').$colonSep.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1343 $subjectpreview = '';
1346 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1347 if ( !$this->preview
&& !$this->diff
) {
1348 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1350 $templates = $this->getTemplates();
1351 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1353 $hiddencats = $this->mArticle
->getHiddenCategories();
1354 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1356 global $wgUseMetadataEdit ;
1357 if ( $wgUseMetadataEdit ) {
1358 $metadata = $this->mMetaData
;
1359 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1360 $top = wfMsgWikiHtml( 'metadata_help' );
1361 /* ToDo: Replace with clean code */
1362 $ew = $wgUser->getOption( 'editwidth' );
1363 if ( $ew ) $ew = " style=\"width:100%\"";
1365 $cols = $wgUser->getIntOption( 'cols' );
1367 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1369 else $metadata = "" ;
1372 if ( $this->wasDeletedSinceLastEdit() ) {
1373 if ( 'save' != $this->formtype
) {
1374 $wgOut->addWikiMsg('deletedwhileediting');
1376 // Hide the toolbar and edit area, use can click preview to get it back
1377 // Add an confirmation checkbox and explanation.
1379 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1381 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1382 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1388 $checkboxes = self
::getCheckboxes( $tabindex, $sk,
1389 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1391 $checkboxhtml = implode( $checkboxes, "\n" );
1393 $buttons = $this->getEditButtons( $tabindex );
1394 $buttonshtml = implode( $buttons, "\n" );
1396 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1397 ?
'' : Xml
::hidden( 'safemode', '1' );
1399 $wgOut->addHTML( <<<END
1401 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1405 if ( is_callable( $formCallback ) ) {
1406 call_user_func_array( $formCallback, array( &$wgOut ) );
1409 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1411 // Put these up at the top to ensure they aren't lost on early form submission
1412 $this->showFormBeforeText();
1414 $wgOut->addHTML( <<<END
1418 {$this->editFormTextBeforeContent}
1421 $this->showTextbox1( $classes );
1423 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1424 $wgOut->addHTML( <<<END
1425 {$this->editFormTextAfterWarn}
1435 "<div class='editButtons'>
1437 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1438 </div><!-- editButtons -->
1439 </div><!-- editOptions -->");
1442 * To make it harder for someone to slip a user a page
1443 * which submits an edit form to the wiki without their
1444 * knowledge, a random token is associated with the login
1445 * session. If it's not passed back with the submission,
1446 * we won't save the page, or render user JavaScript and
1449 * For anon editors, who may not have a session, we just
1450 * include the constant suffix to prevent editing from
1451 * broken text-mangling proxies.
1453 $token = htmlspecialchars( $wgUser->editToken() );
1454 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1456 $this->showEditTools();
1458 $wgOut->addHTML( <<<END
1459 {$this->editFormTextAfterTools}
1460 <div class='templatesUsed'>
1461 {$formattedtemplates}
1463 <div class='hiddencats'>
1464 {$formattedhiddencats}
1469 if ( $this->isConflict
&& wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1470 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1472 $de = new DifferenceEngine( $this->mTitle
);
1473 $de->setText( $this->textbox2
, $this->textbox1
);
1474 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1476 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1477 $this->showTextbox2();
1479 $wgOut->addHTML( $this->editFormTextBottom
);
1480 $wgOut->addHTML( "</form>\n" );
1481 if ( !$wgUser->getOption( 'previewontop' ) ) {
1482 $this->displayPreviewArea( $previewOutput, false );
1485 wfProfileOut( $fname );
1488 protected function showFormBeforeText() {
1491 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1492 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1493 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1494 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1497 protected function showTextbox1( $classes ) {
1498 $attribs = array( 'tabindex' => 1 );
1500 if ( $this->wasDeletedSinceLastEdit() )
1501 $attribs['type'] = 'hidden';
1502 if ( !empty($classes) )
1503 $attribs['class'] = implode(' ',$classes);
1505 $this->showTextbox( $this->textbox1
, 'wpTextbox1', $attribs );
1508 protected function showTextbox2() {
1509 $this->showTextbox( $this->textbox2
, 'wpTextbox2', array( 'tabindex' => 6 ) );
1512 protected function showTextbox( $content, $name, $attribs = array() ) {
1513 global $wgOut, $wgUser;
1515 $wikitext = $this->safeUnicodeOutput( $content );
1516 if ( $wikitext !== '' ) {
1517 // Ensure there's a newline at the end, otherwise adding lines
1519 // But don't add a newline if the ext is empty, or Firefox in XHTML
1520 // mode will show an extra newline. A bit annoying.
1524 $attribs['accesskey'] = ',';
1525 $attribs['id'] = $name;
1527 if ( $wgUser->getOption( 'editwidth' ) )
1528 $attribs['style'] = 'width: 100%';
1530 $wgOut->addHTML( Xml
::textarea(
1533 $wgUser->getIntOption( 'cols' ), $wgUser->getIntOption( 'rows' ),
1537 protected function displayPreviewArea( $previewOutput, $isOnTop = false ) {
1541 $classes[] = 'ontop';
1543 $attribs = array( 'id' => 'wikiPreview', 'class' => implode( ' ', $classes ) );
1545 if ( $this->formtype
!= 'preview' )
1546 $attribs['style'] = 'display: none;';
1548 $wgOut->addHTML( Xml
::openElement( 'div', $attribs ) );
1550 if ( $this->formtype
== 'preview' ) {
1551 $this->showPreview( $previewOutput );
1554 $wgOut->addHTML( '</div>' );
1556 if ( $this->formtype
== 'diff') {
1562 * Append preview output to $wgOut.
1563 * Includes category rendering if this is a category page.
1565 * @param string $text The HTML to be output for the preview.
1567 protected function showPreview( $text ) {
1569 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1570 $this->mArticle
->openShowCategory();
1572 # This hook seems slightly odd here, but makes things more
1573 # consistent for extensions.
1574 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1575 $wgOut->addHTML( $text );
1576 if ( $this->mTitle
->getNamespace() == NS_CATEGORY
) {
1577 $this->mArticle
->closeShowCategory();
1582 * Live Preview lets us fetch rendered preview page content and
1583 * add it to the page without refreshing the whole page.
1584 * If not supported by the browser it will fall through to the normal form
1585 * submission method.
1587 * This function outputs a script tag to support live preview, and
1588 * returns an onclick handler which should be added to the attributes
1589 * of the preview button
1591 function doLivePreviewScript() {
1592 global $wgOut, $wgTitle;
1593 $wgOut->addScriptFile( 'preview.js' );
1594 $liveAction = $wgTitle->getLocalUrl( "action={$this->action}&wpPreview=true&live=true" );
1595 return "return !lpDoPreview(" .
1596 "editform.wpTextbox1.value," .
1597 '"' . $liveAction . '"' . ")";
1600 protected function showEditTools() {
1602 $wgOut->addHtml( '<div class="mw-editTools">' );
1603 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1604 $wgOut->addHtml( '</div>' );
1607 function getLastDelete() {
1608 $dbr = wfGetDB( DB_SLAVE
);
1609 $data = $dbr->selectRow(
1610 array( 'logging', 'user' ),
1620 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1621 'log_title' => $this->mTitle
->getDBkey(),
1622 'log_type' => 'delete',
1623 'log_action' => 'delete',
1624 'user_id=log_user' ),
1626 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1632 * Get the rendered text for previewing.
1635 function getPreviewText() {
1636 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang;
1638 wfProfileIn( __METHOD__
);
1640 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1641 if ( $this->mTokenOkExceptSuffix
) {
1642 $note = wfMsg( 'token_suffix_mismatch' );
1644 $note = wfMsg( 'session_fail_preview' );
1647 $note = wfMsg( 'previewnote' );
1650 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1651 $parserOptions->setEditSection( false );
1654 if ( $wgRawHtml && !$this->mTokenOk
) {
1655 // Could be an offsite preview attempt. This is very unsafe if
1656 // HTML is enabled, as it could be an attack.
1657 return $wgOut->parse( "<div class='previewnote'>" .
1658 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1661 # don't parse user css/js, show message about preview
1662 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1664 if ( $this->isCssJsSubpage
) {
1665 if (preg_match("/\\.css$/", $this->mTitle
->getText() ) ) {
1666 $previewtext = wfMsg('usercsspreview');
1667 } else if (preg_match("/\\.js$/", $this->mTitle
->getText() ) ) {
1668 $previewtext = wfMsg('userjspreview');
1670 $parserOptions->setTidy(true);
1671 $parserOutput = $wgParser->parse( $previewtext, $this->mTitle
, $parserOptions );
1672 $previewHTML = $parserOutput->mText
;
1673 } elseif ( $rt = Title
::newFromRedirect( $this->textbox1
) ) {
1674 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
1676 $toparse = $this->textbox1
;
1678 # If we're adding a comment, we need to show the
1679 # summary as the headline
1680 if ( $this->section
=="new" && $this->summary
!="" ) {
1681 $toparse="== {$this->summary} ==\n\n".$toparse;
1684 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1686 // Parse mediawiki messages with correct target language
1687 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1688 $pos = strrpos( $this->mTitle
->getText(), '/' );
1689 if ( $pos !== false ) {
1690 $code = substr( $this->mTitle
->getText(), $pos+
1 );
1692 case $wgLang->getCode():
1693 $obj = $wgLang; break;
1694 case $wgContLang->getCode():
1695 $obj = $wgContLang; break;
1697 $obj = Language
::factory( $code );
1699 $parserOptions->setTargetLanguage( $obj );
1704 $parserOptions->setTidy(true);
1705 $parserOptions->enableLimitReport();
1706 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ),
1707 $this->mTitle
, $parserOptions );
1709 $previewHTML = $parserOutput->getText();
1710 $this->mParserOutput
= $parserOutput;
1711 $wgOut->addParserOutputNoText( $parserOutput );
1713 if ( count( $parserOutput->getWarnings() ) ) {
1714 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1718 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1719 "<div class='previewnote'>" . $wgOut->parse( $note ) . "</div>\n";
1720 if ( $this->isConflict
) {
1721 $previewhead .='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1724 wfProfileOut( __METHOD__
);
1725 return $previewhead . $previewHTML;
1728 function getTemplates() {
1729 if ( $this->preview ||
$this->section
!= '' ) {
1730 $templates = array();
1731 if ( !isset($this->mParserOutput
) ) return $templates;
1732 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
1733 foreach( array_keys( $template ) as $dbk ) {
1734 $templates[] = Title
::makeTitle($ns, $dbk);
1739 return $this->mArticle
->getUsedTemplates();
1744 * Call the stock "user is blocked" page
1746 function blockedPage() {
1747 global $wgOut, $wgUser;
1748 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1750 # If the user made changes, preserve them when showing the markup
1751 # (This happens when a user is blocked during edit, for instance)
1752 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1754 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1756 $source = $this->textbox1
;
1759 # Spit out the source or the user's modified version
1760 if ( $source !== false ) {
1761 $rows = $wgUser->getIntOption( 'rows' );
1762 $cols = $wgUser->getIntOption( 'cols' );
1763 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1764 $wgOut->addHtml( '<hr />' );
1765 $wgOut->addWikiMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() );
1766 # Why we don't use Xml::element here?
1767 # Is it because if $source is '', it returns <textarea />?
1768 $wgOut->addHtml( Xml
::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml
::closeElement( 'textarea' ) );
1773 * Produce the stock "please login to edit pages" page
1775 function userNotLoggedInPage() {
1776 global $wgUser, $wgOut, $wgTitle;
1777 $skin = $wgUser->getSkin();
1779 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1780 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1782 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1783 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1784 $wgOut->setArticleRelated( false );
1786 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1787 $wgOut->returnToMain( false, $wgTitle );
1791 * Creates a basic error page which informs the user that
1792 * they have attempted to edit a nonexistant section.
1794 function noSuchSectionPage() {
1795 global $wgOut, $wgTitle;
1797 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1798 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1799 $wgOut->setArticleRelated( false );
1801 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section
);
1802 $wgOut->returnToMain( false, $wgTitle );
1806 * Produce the stock "your edit contains spam" page
1808 * @param $match Text which triggered one or more filters
1810 function spamPage( $match = false ) {
1811 global $wgOut, $wgTitle;
1813 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1814 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1815 $wgOut->setArticleRelated( false );
1817 $wgOut->addHtml( '<div id="spamprotected">' );
1818 $wgOut->addWikiMsg( 'spamprotectiontext' );
1820 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1821 $wgOut->addHtml( '</div>' );
1823 $wgOut->returnToMain( false, $wgTitle );
1830 function mergeChangesInto( &$editText ){
1831 $fname = 'EditPage::mergeChangesInto';
1832 wfProfileIn( $fname );
1834 $db = wfGetDB( DB_MASTER
);
1836 // This is the revision the editor started from
1837 $baseRevision = $this->getBaseRevision();
1838 if ( is_null( $baseRevision ) ) {
1839 wfProfileOut( $fname );
1842 $baseText = $baseRevision->getText();
1844 // The current state, we want to merge updates into it
1845 $currentRevision = Revision
::loadFromTitle(
1846 $db, $this->mTitle
);
1847 if ( is_null( $currentRevision ) ) {
1848 wfProfileOut( $fname );
1851 $currentText = $currentRevision->getText();
1854 if ( wfMerge( $baseText, $editText, $currentText, $result ) ) {
1855 $editText = $result;
1856 wfProfileOut( $fname );
1859 wfProfileOut( $fname );
1865 * Check if the browser is on a blacklist of user-agents known to
1866 * mangle UTF-8 data on form submission. Returns true if Unicode
1867 * should make it through, false if it's known to be a problem.
1871 function checkUnicodeCompliantBrowser() {
1872 global $wgBrowserBlackList;
1873 if ( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1874 // No User-Agent header sent? Trust it by default...
1877 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1878 foreach ( $wgBrowserBlackList as $browser ) {
1879 if ( preg_match($browser, $currentbrowser) ) {
1887 * @deprecated use $wgParser->stripSectionName()
1889 function pseudoParseSectionAnchor( $text ) {
1891 return $wgParser->stripSectionName( $text );
1895 * Format an anchor fragment as it would appear for a given section name
1896 * @param string $text
1900 function sectionAnchor( $text ) {
1902 return $wgParser->guessSectionNameFromWikiText( $text );
1906 * Shows a bulletin board style toolbar for common editing functions.
1907 * It can be disabled in the user preferences.
1908 * The necessary JavaScript code can be found in skins/common/edit.js.
1912 static function getEditToolbar() {
1913 global $wgStylePath, $wgContLang, $wgLang, $wgJsMimeType;
1916 * toolarray an array of arrays which each include the filename of
1917 * the button image (without path), the opening tag, the closing tag,
1918 * and optionally a sample text that is inserted between the two when no
1919 * selection is highlighted.
1920 * The tip text is shown when the user moves the mouse over the button.
1922 * Already here are accesskeys (key), which are not used yet until someone
1923 * can figure out a way to make them work in IE. However, we should make
1924 * sure these keys are not defined on the edit page.
1928 'image' => $wgLang->getImageFile('button-bold'),
1929 'id' => 'mw-editbutton-bold',
1931 'close' => '\'\'\'',
1932 'sample' => wfMsg('bold_sample'),
1933 'tip' => wfMsg('bold_tip'),
1937 'image' => $wgLang->getImageFile('button-italic'),
1938 'id' => 'mw-editbutton-italic',
1941 'sample' => wfMsg('italic_sample'),
1942 'tip' => wfMsg('italic_tip'),
1946 'image' => $wgLang->getImageFile('button-link'),
1947 'id' => 'mw-editbutton-link',
1950 'sample' => wfMsg('link_sample'),
1951 'tip' => wfMsg('link_tip'),
1955 'image' => $wgLang->getImageFile('button-extlink'),
1956 'id' => 'mw-editbutton-extlink',
1959 'sample' => wfMsg('extlink_sample'),
1960 'tip' => wfMsg('extlink_tip'),
1964 'image' => $wgLang->getImageFile('button-headline'),
1965 'id' => 'mw-editbutton-headline',
1968 'sample' => wfMsg('headline_sample'),
1969 'tip' => wfMsg('headline_tip'),
1973 'image' => $wgLang->getImageFile('button-image'),
1974 'id' => 'mw-editbutton-image',
1975 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).':',
1977 'sample' => wfMsg('image_sample'),
1978 'tip' => wfMsg('image_tip'),
1982 'image' => $wgLang->getImageFile('button-media'),
1983 'id' => 'mw-editbutton-media',
1984 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1986 'sample' => wfMsg('media_sample'),
1987 'tip' => wfMsg('media_tip'),
1991 'image' => $wgLang->getImageFile('button-math'),
1992 'id' => 'mw-editbutton-math',
1994 'close' => "</math>",
1995 'sample' => wfMsg('math_sample'),
1996 'tip' => wfMsg('math_tip'),
2000 'image' => $wgLang->getImageFile('button-nowiki'),
2001 'id' => 'mw-editbutton-nowiki',
2002 'open' => "<nowiki>",
2003 'close' => "</nowiki>",
2004 'sample' => wfMsg('nowiki_sample'),
2005 'tip' => wfMsg('nowiki_tip'),
2009 'image' => $wgLang->getImageFile('button-sig'),
2010 'id' => 'mw-editbutton-signature',
2014 'tip' => wfMsg('sig_tip'),
2018 'image' => $wgLang->getImageFile('button-hr'),
2019 'id' => 'mw-editbutton-hr',
2020 'open' => "\n----\n",
2023 'tip' => wfMsg('hr_tip'),
2027 $toolbar = "<div id='toolbar'>\n";
2028 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
2030 foreach($toolarray as $tool) {
2032 $image = $wgStylePath.'/common/images/'.$tool['image'],
2033 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2034 // Older browsers show a "speedtip" type message only for ALT.
2035 // Ideally these should be different, realistically they
2036 // probably don't need to be.
2037 $tip = $tool['tip'],
2038 $open = $tool['open'],
2039 $close = $tool['close'],
2040 $sample = $tool['sample'],
2041 $cssId = $tool['id'],
2044 $paramList = implode( ',',
2045 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2046 $toolbar.="addButton($paramList);\n";
2049 $toolbar.="/*]]>*/\n</script>";
2050 $toolbar.="\n</div>";
2055 * Returns an array of html code of the following checkboxes:
2058 * @param $tabindex Current tabindex
2059 * @param $skin Skin object
2060 * @param $checked Array of checkbox => bool, where bool indicates the checked
2061 * status of the checkbox
2065 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
2068 $checkboxes = array();
2070 $checkboxes['minor'] = '';
2071 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
2072 if ( $wgUser->isAllowed('minoredit') ) {
2074 'tabindex' => ++
$tabindex,
2075 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2076 'id' => 'wpMinoredit',
2078 $checkboxes['minor'] =
2079 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2080 " <label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
2083 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2084 $checkboxes['watch'] = '';
2085 if ( $wgUser->isLoggedIn() ) {
2087 'tabindex' => ++
$tabindex,
2088 'accesskey' => wfMsg( 'accesskey-watch' ),
2089 'id' => 'wpWatchthis',
2091 $checkboxes['watch'] =
2092 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2093 " <label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
2099 * Returns an array of html code of the following buttons:
2100 * save, diff, preview and live
2102 * @param $tabindex Current tabindex
2106 public function getEditButtons(&$tabindex) {
2107 global $wgLivePreview, $wgUser;
2115 'tabindex' => ++
$tabindex,
2116 'value' => wfMsg('savearticle'),
2117 'accesskey' => wfMsg('accesskey-save'),
2118 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2120 $buttons['save'] = Xml
::element('input', $temp, '');
2122 ++
$tabindex; // use the same for preview and live preview
2123 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2125 'id' => 'wpPreview',
2126 'name' => 'wpPreview',
2128 'tabindex' => $tabindex,
2129 'value' => wfMsg('showpreview'),
2131 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2132 'style' => 'display: none;',
2134 $buttons['preview'] = Xml
::element('input', $temp, '');
2137 'id' => 'wpLivePreview',
2138 'name' => 'wpLivePreview',
2140 'tabindex' => $tabindex,
2141 'value' => wfMsg('showlivepreview'),
2142 'accesskey' => wfMsg('accesskey-preview'),
2144 'onclick' => $this->doLivePreviewScript(),
2146 $buttons['live'] = Xml
::element('input', $temp, '');
2149 'id' => 'wpPreview',
2150 'name' => 'wpPreview',
2152 'tabindex' => $tabindex,
2153 'value' => wfMsg('showpreview'),
2154 'accesskey' => wfMsg('accesskey-preview'),
2155 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2157 $buttons['preview'] = Xml
::element('input', $temp, '');
2158 $buttons['live'] = '';
2165 'tabindex' => ++
$tabindex,
2166 'value' => wfMsg('showdiff'),
2167 'accesskey' => wfMsg('accesskey-diff'),
2168 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2170 $buttons['diff'] = Xml
::element('input', $temp, '');
2172 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons ) );
2177 * Output preview text only. This can be sucked into the edit page
2178 * via JavaScript, and saves the server time rendering the skin as
2179 * well as theoretically being more robust on the client (doesn't
2180 * disturb the edit box's undo history, won't eat your text on
2183 * @todo This doesn't include category or interlanguage links.
2184 * Would need to enhance it a bit, <s>maybe wrap them in XML
2185 * or something...</s> that might also require more skin
2186 * initialization, so check whether that's a problem.
2188 function livePreview() {
2191 header( 'Content-type: text/xml; charset=utf-8' );
2192 header( 'Cache-control: no-cache' );
2194 $previewText = $this->getPreviewText();
2195 #$categories = $skin->getCategoryLinks();
2198 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2199 Xml
::tags( 'livepreview', null,
2200 Xml
::element( 'preview', null, $previewText )
2201 #. Xml::element( 'category', null, $categories )
2208 * Get a diff between the current contents of the edit box and the
2209 * version of the page we're editing from.
2211 * If this is a section edit, we'll replace the section as for final
2212 * save and then make a comparison.
2214 function showDiff() {
2215 $oldtext = $this->mArticle
->fetchContent();
2216 $newtext = $this->mArticle
->replaceSection(
2217 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2218 $newtext = $this->mArticle
->preSaveTransform( $newtext );
2219 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2220 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2221 if ( $oldtext !== false ||
$newtext != '' ) {
2222 $de = new DifferenceEngine( $this->mTitle
);
2223 $de->setText( $oldtext, $newtext );
2224 $difftext = $de->getDiff( $oldtitle, $newtitle );
2225 $de->showDiffStyle();
2231 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
2235 * Filter an input field through a Unicode de-armoring process if it
2236 * came from an old browser with known broken Unicode editing issues.
2238 * @param WebRequest $request
2239 * @param string $field
2243 function safeUnicodeInput( $request, $field ) {
2244 $text = rtrim( $request->getText( $field ) );
2245 return $request->getBool( 'safemode' )
2246 ?
$this->unmakesafe( $text )
2251 * Filter an output field through a Unicode armoring process if it is
2252 * going to an old browser with known broken Unicode editing issues.
2254 * @param string $text
2258 function safeUnicodeOutput( $text ) {
2260 $codedText = $wgContLang->recodeForEdit( $text );
2261 return $this->checkUnicodeCompliantBrowser()
2263 : $this->makesafe( $codedText );
2267 * A number of web browsers are known to corrupt non-ASCII characters
2268 * in a UTF-8 text editing environment. To protect against this,
2269 * detected browsers will be served an armored version of the text,
2270 * with non-ASCII chars converted to numeric HTML character references.
2272 * Preexisting such character references will have a 0 added to them
2273 * to ensure that round-trips do not alter the original data.
2275 * @param string $invalue
2279 function makesafe( $invalue ) {
2280 // Armor existing references for reversability.
2281 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2286 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2287 $bytevalue = ord( $invalue{$i} );
2288 if ( $bytevalue <= 0x7F ) { //0xxx xxxx
2289 $result .= chr( $bytevalue );
2291 } elseif ( $bytevalue <= 0xBF ) { //10xx xxxx
2292 $working = $working << 6;
2293 $working +
= ($bytevalue & 0x3F);
2295 if ( $bytesleft <= 0 ) {
2296 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2298 } elseif ( $bytevalue <= 0xDF ) { //110x xxxx
2299 $working = $bytevalue & 0x1F;
2301 } elseif ( $bytevalue <= 0xEF ) { //1110 xxxx
2302 $working = $bytevalue & 0x0F;
2304 } else { //1111 0xxx
2305 $working = $bytevalue & 0x07;
2313 * Reverse the previously applied transliteration of non-ASCII characters
2314 * back to UTF-8. Used to protect data from corruption by broken web browsers
2315 * as listed in $wgBrowserBlackList.
2317 * @param string $invalue
2321 function unmakesafe( $invalue ) {
2323 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2324 if ( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2328 $hexstring .= $invalue{$i};
2330 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2332 // Do some sanity checks. These aren't needed for reversability,
2333 // but should help keep the breakage down if the editor
2334 // breaks one of the entities whilst editing.
2335 if ( (substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6) ) {
2336 $codepoint = hexdec($hexstring);
2337 $result .= codepointToUtf8( $codepoint );
2339 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2342 $result .= substr( $invalue, $i, 1 );
2345 // reverse the transform that we made for reversability reasons.
2346 return strtr( $result, array( "�" => "&#x" ) );
2349 function noCreatePermission() {
2351 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2352 $wgOut->addWikiMsg( 'nocreatetext' );
2356 * If there are rows in the deletion log for this page, show them,
2357 * along with a nice little note for the user
2359 * @param OutputPage $out
2361 protected function showDeletionLog( $out ) {
2363 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
2364 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle
->getPrefixedText() );
2365 $count = $pager->getNumRows();
2367 $pager->mLimit
= 10;
2368 $out->addHtml( '<div class="mw-warning-with-logexcerpt">' );
2369 $out->addWikiMsg( 'recreate-deleted-warn' );
2371 $loglist->beginLogEventsList() .
2373 $loglist->endLogEventsList()
2376 $out->addHtml( $wgUser->getSkin()->link(
2377 SpecialPage
::getTitleFor( 'Log' ),
2378 wfMsgHtml( 'deletelog-fulllog' ),
2382 'page' => $this->mTitle
->getPrefixedText() ) ) );
2384 $out->addHtml( '</div>' );
2392 * Attempt submission
2393 * @return bool false if output is done, true if the rest of the form should be displayed
2395 function attemptSave() {
2396 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2398 $resultDetails = false;
2399 $value = $this->internalAttemptSave( $resultDetails, $wgUser->isAllowed('bot') && $wgRequest->getBool('bot', true) );
2401 if ( $value == self
::AS_SUCCESS_UPDATE ||
$value == self
::AS_SUCCESS_NEW_ARTICLE
) {
2402 $this->didSave
= true;
2406 case self
::AS_HOOK_ERROR_EXPECTED
:
2407 case self
::AS_CONTENT_TOO_BIG
:
2408 case self
::AS_ARTICLE_WAS_DELETED
:
2409 case self
::AS_CONFLICT_DETECTED
:
2410 case self
::AS_SUMMARY_NEEDED
:
2411 case self
::AS_TEXTBOX_EMPTY
:
2412 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
2416 case self
::AS_HOOK_ERROR
:
2417 case self
::AS_FILTERING
:
2418 case self
::AS_SUCCESS_NEW_ARTICLE
:
2419 case self
::AS_SUCCESS_UPDATE
:
2422 case self
::AS_SPAM_ERROR
:
2423 $this->spamPage ( $resultDetails['spam'] );
2426 case self
::AS_BLOCKED_PAGE_FOR_USER
:
2427 $this->blockedPage();
2430 case self
::AS_IMAGE_REDIRECT_ANON
:
2431 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2434 case self
::AS_READ_ONLY_PAGE_ANON
:
2435 $this->userNotLoggedInPage();
2438 case self
::AS_READ_ONLY_PAGE_LOGGED
:
2439 case self
::AS_READ_ONLY_PAGE
:
2440 $wgOut->readOnlyPage();
2443 case self
::AS_RATE_LIMITED
:
2444 $wgOut->rateLimited();
2447 case self
::AS_NO_CREATE_PERMISSION
;
2448 $this->noCreatePermission();
2451 case self
::AS_BLANK_ARTICLE
:
2452 $wgOut->redirect( $wgTitle->getFullURL() );
2455 case self
::AS_IMAGE_REDIRECT_LOGGED
:
2456 $wgOut->permissionRequired( 'upload' );
2461 function getBaseRevision() {
2462 if ( $this->mBaseRevision
== false ) {
2463 $db = wfGetDB( DB_MASTER
);
2464 $baseRevision = Revision
::loadFromTimestamp(
2465 $db, $this->mTitle
, $this->edittime
);
2466 return $this->mBaseRevision
= $baseRevision;
2468 return $this->mBaseRevision
;