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;
48 var $isConflict = false;
49 var $isCssJsSubpage = false;
50 var $deletedSinceEdit = false;
54 var $mTokenOk = false;
55 var $mTokenOkExceptSuffix = false;
56 var $mTriedSave = false;
58 var $kblength = false;
59 var $missingComment = false;
60 var $missingSummary = false;
61 var $allowBlankSummary = false;
64 var $mPreviewTemplates;
65 var $mBaseRevision = false;
68 var $save = false, $preview = false, $diff = false;
69 var $minoredit = false, $watchthis = false, $recreate = false;
70 var $textbox1 = '', $textbox2 = '', $summary = '';
71 var $edittime = '', $section = '', $starttime = '';
72 var $oldid = 0, $editintro = '', $scrolltop = null;
74 # Placeholders for text injection by hooks (must be HTML)
75 # extensions should take care to _append_ to the present value
76 public $editFormPageTop; // Before even the preview
77 public $editFormTextTop;
78 public $editFormTextBeforeContent;
79 public $editFormTextAfterWarn;
80 public $editFormTextAfterTools;
81 public $editFormTextBottom;
83 /* $didSave should be set to true whenever an article was succesfully altered. */
84 public $didSave = false;
86 public $suppressIntro = false;
92 function EditPage( $article ) {
93 $this->mArticle
=& $article;
94 $this->mTitle
= $article->getTitle();
96 # Placeholders for text injection by hooks (empty per default)
97 $this->editFormPageTop
=
98 $this->editFormTextTop
=
99 $this->editFormTextBeforeContent
=
100 $this->editFormTextAfterWarn
=
101 $this->editFormTextAfterTools
=
102 $this->editFormTextBottom
= "";
106 * Fetch initial editing page content.
109 function getContent( $def_text = '' ) {
110 global $wgOut, $wgRequest, $wgParser, $wgMessageCache;
112 # Get variables from query string :P
113 $section = $wgRequest->getVal( 'section' );
114 $preload = $wgRequest->getVal( 'preload' );
115 $undoafter = $wgRequest->getVal( 'undoafter' );
116 $undo = $wgRequest->getVal( 'undo' );
118 wfProfileIn( __METHOD__
);
121 if( !$this->mTitle
->exists() ) {
122 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
123 $wgMessageCache->loadAllMessages();
124 # If this is a system message, get the default text.
125 $text = wfMsgWeirdKey( $this->mTitle
->getText() ) ;
127 # If requested, preload some text.
128 $text = $this->getPreloadedText( $preload );
130 # We used to put MediaWiki:Newarticletext here if
131 # $text was empty at this point.
132 # This is now shown above the edit box instead.
134 // FIXME: may be better to use Revision class directly
135 // But don't mess with it just yet. Article knows how to
136 // fetch the page record from the high-priority server,
137 // which is needed to guarantee we don't pick up lagged
140 $text = $this->mArticle
->getContent();
142 if ($undo > 0 && $undoafter > 0 && $undo < $undoafter) {
143 # If they got undoafter and undo round the wrong way, switch them
144 list( $undo, $undoafter ) = array( $undoafter, $undo );
147 if ( $undo > 0 && $undo > $undoafter ) {
148 # Undoing a specific edit overrides section editing; section-editing
149 # doesn't work with undoing.
151 $undorev = Revision
::newFromId($undo);
152 $oldrev = Revision
::newFromId($undoafter);
154 $undorev = Revision
::newFromId($undo);
155 $oldrev = $undorev ?
$undorev->getPrevious() : null;
158 # Sanity check, make sure it's the right page,
159 # the revisions exist and they were not deleted.
160 # Otherwise, $text will be left as-is.
161 if( !is_null( $undorev ) && !is_null( $oldrev ) &&
162 $undorev->getPage() == $oldrev->getPage() &&
163 $undorev->getPage() == $this->mArticle
->getID() &&
164 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
165 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
166 $undorev_text = $undorev->getText();
167 $oldrev_text = $oldrev->getText();
168 $currev_text = $text;
170 if ( $currev_text != $undorev_text ) {
171 $result = wfMerge( $undorev_text, $oldrev_text, $currev_text, $text );
173 # No use doing a merge if it's just a straight revert.
174 $text = $oldrev_text;
178 # Inform the user of our success and set an automatic edit summary
179 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
180 $firstrev = $oldrev->getNext();
181 # If we just undid one rev, use an autosummary
182 if( $firstrev->mId
== $undo ) {
183 $this->summary
= wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
185 $this->formtype
= 'diff';
187 # Warn the user that something went wrong
188 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
191 // Failed basic sanity checks.
192 // Older revisions may have been removed since the link
193 // was created, or we may simply have got bogus input.
194 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-norev' ) );
196 } else if( $section != '' ) {
197 if( $section == 'new' ) {
198 $text = $this->getPreloadedText( $preload );
200 $text = $wgParser->getSection( $text, $section, $def_text );
205 wfProfileOut( __METHOD__
);
210 * Get the contents of a page from its title and remove includeonly tags
212 * @param $preload String: the title of the page.
213 * @return string The contents of the page.
215 protected function getPreloadedText($preload) {
216 if ( $preload === '' )
219 $preloadTitle = Title
::newFromText( $preload );
220 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
221 $rev=Revision
::newFromTitle($preloadTitle);
222 if ( is_object( $rev ) ) {
223 $text = $rev->getText();
224 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
225 // its own mini-parser! -ævar
226 $text = preg_replace( '~</?includeonly>~', '', $text );
235 * This is the function that extracts metadata from the article body on the first view.
236 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
237 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
239 function extractMetaDataFromArticle () {
240 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
241 $this->mMetaData
= '' ;
242 if ( !$wgUseMetadataEdit ) return ;
243 if ( $wgMetadataWhitelist == '' ) return ;
245 $t = $this->getContent();
247 # MISSING : <nowiki> filtering
249 # Categories and language links
250 $t = explode ( "\n" , $t ) ;
251 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
252 $cat = $ll = array() ;
253 foreach ( $t AS $key => $x )
255 $y = trim ( strtolower ( $x ) ) ;
256 while ( substr ( $y , 0 , 2 ) == '[[' )
258 $y = explode ( ']]' , trim ( $x ) ) ;
259 $first = array_shift ( $y ) ;
260 $first = explode ( ':' , $first ) ;
261 $ns = array_shift ( $first ) ;
262 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
263 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
265 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
266 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
268 $x = implode ( ']]' , $y ) ;
270 $y = trim ( strtolower ( $x ) ) ;
274 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
275 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
276 $t = implode ( "\n" , $t ) ;
279 $sat = array () ; # stand-alone-templates; must be lowercase
280 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
281 $wl_article = new Article ( $wl_title ) ;
282 $wl = explode ( "\n" , $wl_article->getContent() ) ;
283 foreach ( $wl AS $x )
287 while ( substr ( $x , 0 , 1 ) == '*' )
290 $x = trim ( substr ( $x , 1 ) ) ;
294 $sat[] = strtolower ( $x ) ;
299 # Templates, but only some
300 $t = explode ( '{{' , $t ) ;
302 foreach ( $t AS $key => $x )
304 $y = explode ( '}}' , $x , 2 ) ;
305 if ( count ( $y ) == 2 )
308 $z = explode ( '|' , $z ) ;
309 $tn = array_shift ( $z ) ;
310 if ( in_array ( strtolower ( $tn ) , $sat ) )
312 $tl[] = '{{' . $y[0] . '}}' ;
314 $y = explode ( '}}' , $y[1] , 2 ) ;
316 else $t[$key] = '{{' . $x ;
318 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
321 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
322 $t = implode ( '' , $t ) ;
324 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
325 $this->mArticle
->mContent
= $t ;
326 $this->mMetaData
= $s ;
329 protected function wasDeletedSinceLastEdit() {
330 /* Note that we rely on the logging table, which hasn't been always there,
331 * but that doesn't matter, because this only applies to brand new
334 if ( $this->deletedSinceEdit
)
336 if ( $this->mTitle
->isDeleted() ) {
337 $this->lastDelete
= $this->getLastDelete();
338 if ( !is_null($this->lastDelete
) ) {
339 $deletetime = $this->lastDelete
->log_timestamp
;
340 if ( ($deletetime - $this->starttime
) > 0 ) {
341 $this->deletedSinceEdit
= true;
345 return $this->deletedSinceEdit
;
353 * This is the function that gets called for "action=edit". It
354 * sets up various member variables, then passes execution to
355 * another function, usually showEditForm()
357 * The edit form is self-submitting, so that when things like
358 * preview and edit conflicts occur, we get the same form back
359 * with the extra stuff added. Only when the final submission
360 * is made and all is well do we actually save and redirect to
361 * the newly-edited page.
364 global $wgOut, $wgUser, $wgRequest;
366 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__
);
388 $this->preview
= true;
389 } elseif( $this->preview ||
$this->diff
){
390 // A warning will be displayed instead
392 $this->readOnlyPage( $this->getContent() );
393 wfProfileOut( __METHOD__
);
398 $wgOut->addScriptFile( 'edit.js' );
400 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
402 if( !$this->mTitle
->exists() ) {
403 $permErrors = array_merge( $permErrors,
404 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
407 # Ignore some permissions errors.
409 foreach( $permErrors as $error ) {
410 if ( ( $this->preview ||
$this->diff
) &&
411 ($error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext'))
413 // Don't worry about blocks when previewing/diffing
417 $permErrors = wfArrayDiff2( $permErrors, $remove );
420 wfDebug( __METHOD__
.": User can't edit\n" );
421 $this->readOnlyPage( $this->getContent(), true, $permErrors, 'edit' );
422 wfProfileOut( __METHOD__
);
426 $this->formtype
= 'save';
427 } else if( $this->preview
) {
428 $this->formtype
= 'preview';
429 } else if ( $this->diff
) {
430 $this->formtype
= 'diff';
431 } else { # First time through
432 $this->firsttime
= true;
433 if( $this->previewOnOpen() ) {
434 $this->formtype
= 'preview';
436 $this->extractMetaDataFromArticle () ;
437 $this->formtype
= 'initial';
442 wfProfileIn( __METHOD__
."-business-end" );
444 $this->isConflict
= false;
445 // css / js subpages of user pages get a special treatment
446 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
447 $this->isValidCssJsSubpage
= $this->mTitle
->isValidCssJsSubpage();
449 # Show applicable editing introductions
450 if( $this->formtype
== 'initial' ||
$this->firsttime
)
453 if( $this->mTitle
->isTalkPage() ) {
454 $wgOut->addWikiMsg( 'talkpagetext' );
457 # Optional notices on a per-namespace and per-page basis
458 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
459 $editnotice_page = $editnotice_ns.'-'.$this->mTitle
->getDBkey();
460 if ( !wfEmptyMsg( $editnotice_ns, wfMsgForContent( $editnotice_ns ) ) ) {
461 $wgOut->addWikiText( wfMsgForContent( $editnotice_ns ) );
463 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
464 $parts = explode( '/', $this->mTitle
->getDBkey() );
465 $editnotice_base = $editnotice_ns;
466 while ( count( $parts ) > 0 ) {
467 $editnotice_base .= '-'.array_shift( $parts );
468 if ( !wfEmptyMsg( $editnotice_base, wfMsgForContent( $editnotice_base ) ) ) {
469 $wgOut->addWikiText( wfMsgForContent( $editnotice_base ) );
472 } else if ( !wfEmptyMsg( $editnotice_page, wfMsgForContent( $editnotice_page ) ) ) {
473 $wgOut->addWikiText( wfMsgForContent( $editnotice_page ) );
476 # Attempt submission here. This will check for edit conflicts,
477 # and redundantly check for locked database, blocked IPs, etc.
478 # that edit() already checked just in case someone tries to sneak
479 # in the back door with a hand-edited submission URL.
481 if ( 'save' == $this->formtype
) {
482 if ( !$this->attemptSave() ) {
483 wfProfileOut( __METHOD__
."-business-end" );
484 wfProfileOut( __METHOD__
);
489 # First time through: get contents, set time for conflict
491 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
492 if ($this->initialiseForm() === false) {
493 $this->noSuchSectionPage();
494 wfProfileOut( __METHOD__
."-business-end" );
495 wfProfileOut( __METHOD__
);
498 if( !$this->mTitle
->getArticleId() )
499 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
502 $this->showEditForm();
503 wfProfileOut( __METHOD__
."-business-end" );
504 wfProfileOut( __METHOD__
);
508 * Show a read-only error
509 * Parameters are the same as OutputPage:readOnlyPage()
510 * Redirect to the article page if redlink=1
512 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
513 global $wgRequest, $wgOut;
514 if ( $wgRequest->getBool( 'redlink' ) ) {
515 // The edit page was reached via a red link.
516 // Redirect to the article page and let them click the edit tab if
517 // they really want a permission error.
518 $wgOut->redirect( $this->mTitle
->getFullUrl() );
520 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
525 * Should we show a preview when the edit form is first shown?
529 protected function previewOnOpen() {
530 global $wgRequest, $wgUser;
531 if( $wgRequest->getVal( 'preview' ) == 'yes' ) {
532 // Explicit override from request
534 } elseif( $wgRequest->getVal( 'preview' ) == 'no' ) {
535 // Explicit override from request
537 } elseif( $this->section
== 'new' ) {
538 // Nothing *to* preview for new sections
540 } elseif( ( $wgRequest->getVal( 'preload' ) !== '' ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
541 // Standard preference behaviour
543 } elseif( !$this->mTitle
->exists() && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
544 // Categories are special
555 function importFormData( &$request ) {
556 global $wgLang, $wgUser;
557 $fname = 'EditPage::importFormData';
558 wfProfileIn( $fname );
560 # Section edit can come from either the form or a link
561 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
563 if( $request->wasPosted() ) {
564 # These fields need to be checked for encoding.
565 # Also remove trailing whitespace, but don't remove _initial_
566 # whitespace from the text boxes. This may be significant formatting.
567 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
568 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
569 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
570 # Truncate for whole multibyte characters. +5 bytes for ellipsis
571 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
573 # Remove extra headings from summaries and new sections.
574 $this->summary
= preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
576 $this->edittime
= $request->getVal( 'wpEdittime' );
577 $this->starttime
= $request->getVal( 'wpStarttime' );
579 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
581 if( is_null( $this->edittime
) ) {
582 # If the form is incomplete, force to preview.
583 wfDebug( "$fname: Form data appears to be incomplete\n" );
584 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
585 $this->preview
= true;
587 /* Fallback for live preview */
588 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
589 $this->diff
= $request->getCheck( 'wpDiff' );
591 // Remember whether a save was requested, so we can indicate
592 // if we forced preview due to session failure.
593 $this->mTriedSave
= !$this->preview
;
595 if ( $this->tokenOk( $request ) ) {
596 # Some browsers will not report any submit button
597 # if the user hits enter in the comment box.
598 # The unmarked state will be assumed to be a save,
599 # if the form seems otherwise complete.
600 wfDebug( "$fname: Passed token check.\n" );
601 } else if ( $this->diff
) {
602 # Failed token check, but only requested "Show Changes".
603 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
605 # Page might be a hack attempt posted from
606 # an external site. Preview instead of saving.
607 wfDebug( "$fname: Failed token check; forcing preview\n" );
608 $this->preview
= true;
611 $this->save
= !$this->preview
&& !$this->diff
;
612 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
613 $this->edittime
= null;
616 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
617 $this->starttime
= null;
620 $this->recreate
= $request->getCheck( 'wpRecreate' );
622 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
623 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
625 # Don't force edit summaries when a user is editing their own user or talk page
626 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
627 $this->allowBlankSummary
= true;
629 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
632 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
634 # Not a posted form? Start with nothing.
635 wfDebug( "$fname: Not a posted form.\n" );
636 $this->textbox1
= '';
637 $this->textbox2
= '';
638 $this->mMetaData
= '';
640 $this->edittime
= '';
641 $this->starttime
= wfTimestampNow();
643 $this->preview
= false;
646 $this->minoredit
= false;
647 $this->watchthis
= false;
648 $this->recreate
= false;
650 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
651 $this->summary
= $request->getVal( 'preloadtitle' );
655 $this->oldid
= $request->getInt( 'oldid' );
657 $this->live
= $request->getCheck( 'live' );
658 $this->editintro
= $request->getText( 'editintro' );
660 wfProfileOut( $fname );
664 * Make sure the form isn't faking a user's credentials.
666 * @param $request WebRequest
670 function tokenOk( &$request ) {
672 $token = $request->getVal( 'wpEditToken' );
673 $this->mTokenOk
= $wgUser->matchEditToken( $token );
674 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
675 return $this->mTokenOk
;
679 * Show all applicable editing introductions
681 protected function showIntro() {
682 global $wgOut, $wgUser;
683 if( $this->suppressIntro
)
686 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
687 if( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
688 $parts = explode( '/', $this->mTitle
->getText(), 2 );
689 $username = $parts[0];
690 $id = User
::idFromName( $username );
691 $ip = User
::isIP( $username );
693 if ( $id == 0 && !$ip ) {
694 $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
695 array( 'userpage-userdoesnotexist', $username ) );
699 if( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
700 if( $wgUser->isLoggedIn() ) {
701 $wgOut->wrapWikiMsg( '<div class="mw-newarticletext">$1</div>', 'newarticletext' );
703 $wgOut->wrapWikiMsg( '<div class="mw-newarticletextanon">$1</div>', 'newarticletextanon' );
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
);
848 // Late check for create permission, just in case *PARANOIA*
849 if ( !$this->mTitle
->userCan( 'create' ) ) {
850 wfDebug( "$fname: no create permission\n" );
851 wfProfileOut( $fname );
852 return self
::AS_NO_CREATE_PERMISSION
;
855 # Don't save a new article if it's blank.
856 if ( '' == $this->textbox1
) {
857 wfProfileOut( $fname );
858 return self
::AS_BLANK_ARTICLE
;
861 // Run post-section-merge edit filter
862 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
863 # Error messages etc. could be handled within the hook...
864 wfProfileOut( $fname );
865 return self
::AS_HOOK_ERROR
;
868 $isComment = ( $this->section
== 'new' );
870 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
871 $this->minoredit
, $this->watchthis
, false, $isComment, $bot);
873 wfProfileOut( $fname );
874 return self
::AS_SUCCESS_NEW_ARTICLE
;
877 # Article exists. Check for edit conflict.
879 $this->mArticle
->clear(); # Force reload of dates, etc.
880 $this->mArticle
->forUpdate( true ); # Lock the article
882 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
884 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
885 $this->isConflict
= true;
886 if( $this->section
== 'new' ) {
887 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
888 $this->mArticle
->getComment() == $this->summary
) {
889 // Probably a duplicate submission of a new comment.
890 // This can happen when squid resends a request after
891 // a timeout but the first one actually went through.
892 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
894 // New comment; suppress conflict.
895 $this->isConflict
= false;
896 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
900 $userid = $wgUser->getId();
902 if ( $this->isConflict
) {
903 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
904 $this->mArticle
->getTimestamp() . "')\n" );
905 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
908 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
909 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
911 if( is_null( $text ) ) {
912 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
913 $this->isConflict
= true;
914 $text = $this->textbox1
;
917 # Suppress edit conflict with self, except for section edits where merging is required.
918 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
919 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
920 $this->isConflict
= false;
922 # switch from section editing to normal editing in edit conflict
923 if($this->isConflict
) {
925 if( $this->mergeChangesInto( $text ) ){
926 // Successful merge! Maybe we should tell the user the good news?
927 $this->isConflict
= false;
928 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
931 $this->textbox1
= $text;
932 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
937 if ( $this->isConflict
) {
938 wfProfileOut( $fname );
939 return self
::AS_CONFLICT_DETECTED
;
942 $oldtext = $this->mArticle
->getContent();
944 // Run post-section-merge edit filter
945 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
946 # Error messages etc. could be handled within the hook...
947 wfProfileOut( $fname );
948 return self
::AS_HOOK_ERROR
;
951 # Handle the user preference to force summaries here, but not for null edits
952 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary') &&
953 0 != strcmp($oldtext, $text) &&
954 !is_object( Title
::newFromRedirect( $text ) ) # check if it's not a redirect
957 if( md5( $this->summary
) == $this->autoSumm
) {
958 $this->missingSummary
= true;
959 wfProfileOut( $fname );
960 return self
::AS_SUMMARY_NEEDED
;
964 # And a similar thing for new sections
965 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
966 if (trim($this->summary
) == '') {
967 $this->missingSummary
= true;
968 wfProfileOut( $fname );
969 return self
::AS_SUMMARY_NEEDED
;
974 wfProfileIn( "$fname-sectionanchor" );
976 if( $this->section
== 'new' ) {
977 if ( $this->textbox1
== '' ) {
978 $this->missingComment
= true;
979 return self
::AS_TEXTBOX_EMPTY
;
981 if( $this->summary
!= '' ) {
982 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary
);
983 # This is a new section, so create a link to the new section
984 # in the revision summary.
985 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
986 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
988 } elseif( $this->section
!= '' ) {
989 # Try to get a section anchor from the section source, redirect to edited section if header found
990 # XXX: might be better to integrate this into Article::replaceSection
991 # for duplicate heading checking and maybe parsing
992 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
993 # we can't deal with anchors, includes, html etc in the header for now,
994 # headline would need to be parsed to improve this
995 if($hasmatch and strlen($matches[2]) > 0) {
996 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
999 wfProfileOut( "$fname-sectionanchor" );
1001 // Save errors may fall down to the edit form, but we've now
1002 // merged the section into full text. Clear the section field
1003 // so that later submission of conflict forms won't try to
1004 // replace that into a duplicated mess.
1005 $this->textbox1
= $text;
1006 $this->section
= '';
1008 // Check for length errors again now that the section is merged in
1009 $this->kblength
= (int)(strlen( $text ) / 1024);
1010 if ( $this->kblength
> $wgMaxArticleSize ) {
1011 $this->tooBig
= true;
1012 wfProfileOut( $fname );
1013 return self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
;
1016 # update the article here
1017 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
1018 $this->watchthis
, $bot, $sectionanchor ) ) {
1019 wfProfileOut( $fname );
1020 return self
::AS_SUCCESS_UPDATE
;
1022 $this->isConflict
= true;
1024 wfProfileOut( $fname );
1025 return self
::AS_END
;
1029 * Check given input text against $wgSpamRegex, and return the text of the first match.
1030 * @return mixed -- matching string or false
1032 public static function matchSpamRegex( $text ) {
1033 global $wgSpamRegex;
1034 if( $wgSpamRegex ) {
1035 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1036 $regexes = (array)$wgSpamRegex;
1037 foreach( $regexes as $regex ) {
1039 if ( preg_match( $regex, $text, $matches ) ) {
1048 * Initialise form fields in the object
1049 * Called on the first invocation, e.g. when a user clicks an edit link
1051 function initialiseForm() {
1052 $this->edittime
= $this->mArticle
->getTimestamp();
1053 $this->textbox1
= $this->getContent(false);
1054 if ($this->textbox1
=== false) return false;
1056 if ( !$this->mArticle
->exists() && $this->mTitle
->getNamespace() == NS_MEDIAWIKI
)
1057 $this->textbox1
= wfMsgWeirdKey( $this->mTitle
->getText() );
1063 * Send the edit form and related headers to $wgOut
1064 * @param $formCallback Optional callable that takes an OutputPage
1065 * parameter; will be called during form output
1066 * near the top, for captchas and the like.
1068 function showEditForm( $formCallback=null ) {
1069 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle;
1071 # If $wgTitle is null, that means we're in API mode.
1072 # Some hook probably called this function without checking
1073 # for is_null($wgTitle) first. Bail out right here so we don't
1074 # do lots of work just to discard it right after.
1075 if(is_null($wgTitle))
1078 $fname = 'EditPage::showEditForm';
1079 wfProfileIn( $fname );
1081 $sk = $wgUser->getSkin();
1083 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
1085 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1087 # Enabled article-related sidebar, toplinks, etc.
1088 $wgOut->setArticleRelated( true );
1090 if ( $this->formtype
== 'preview' ) {
1091 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1094 if ( $this->isConflict
) {
1095 $s = wfMsg( 'editconflict', $wgTitle->getPrefixedText() );
1096 $wgOut->setPageTitle( $s );
1097 $wgOut->addWikiMsg( 'explainconflict' );
1099 $this->textbox2
= $this->textbox1
;
1100 $this->textbox1
= $this->getContent();
1101 $this->edittime
= $this->mArticle
->getTimestamp();
1103 if( $this->section
!= '' ) {
1104 if( $this->section
== 'new' ) {
1105 $s = wfMsg('editingcomment', $wgTitle->getPrefixedText() );
1107 $s = wfMsg('editingsection', $wgTitle->getPrefixedText() );
1109 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1110 preg_match( "/^(=+)(.+)\\1/mi",
1113 if( !empty( $matches[2] ) ) {
1115 $this->summary
= "/* " .
1116 $wgParser->stripSectionName(trim($matches[2])) .
1122 $s = wfMsg( 'editing', $wgTitle->getPrefixedText() );
1124 $wgOut->setPageTitle( $s );
1126 if ( $this->missingComment
) {
1127 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1130 if( $this->missingSummary
&& $this->section
!= 'new' ) {
1131 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1134 if( $this->missingSummary
&& $this->section
== 'new' ) {
1135 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1138 if( $this->hookError
!== '' ) {
1139 $wgOut->addWikiText( $this->hookError
);
1142 if ( !$this->checkUnicodeCompliantBrowser() ) {
1143 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1145 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1146 // Let sysop know that this will make private content public if saved
1148 if( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1149 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
1150 } else if( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1151 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
1154 if( !$this->mArticle
->mRevision
->isCurrent() ) {
1155 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1156 $wgOut->addWikiMsg( 'editingold' );
1161 if( wfReadOnly() ) {
1162 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1163 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
1164 $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' );
1166 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
1167 # Check the skin exists
1168 if( $this->isValidCssJsSubpage
) {
1169 $wgOut->addWikiMsg( 'usercssjsyoucanpreview' );
1171 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1176 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1177 # Show a warning if editing an interface message
1178 $wgOut->addWikiMsg( 'editinginterface' );
1179 } elseif( $this->mTitle
->isProtected( 'edit' ) ) {
1180 # Is the title semi-protected?
1181 if( $this->mTitle
->isSemiProtected() ) {
1182 $noticeMsg = 'semiprotectedpagewarning';
1184 # Then it must be protected based on static groups (regular)
1185 $noticeMsg = 'protectedpagewarning';
1187 $wgOut->addHTML( "<div id='mw-edit-$noticeMsg'>\n" );
1188 $wgOut->addWikiMsg( $noticeMsg );
1189 $wgOut->addHTML( "</div>\n" );
1191 if ( $this->mTitle
->isCascadeProtected() ) {
1192 # Is this page under cascading protection from some source pages?
1193 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1195 if ( count($cascadeSources) > 0 ) {
1196 # Explain, and list the titles responsible
1197 foreach( $cascadeSources as $page ) {
1198 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1201 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', count($cascadeSources) ) );
1203 if( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) != array() ){
1204 $wgOut->addWikiMsg( 'titleprotectedwarning' );
1207 if ( $this->kblength
=== false ) {
1208 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1210 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1211 $wgOut->addHTML( "<div id='mw-edit-longpageerror'>\n" );
1212 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) );
1213 $wgOut->addHTML( "</div>\n" );
1214 } elseif( $this->kblength
> 29 ) {
1215 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1216 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) );
1217 $wgOut->addHTML( "</div>\n" );
1220 #need to parse the preview early so that we know which templates are used,
1221 #otherwise users with "show preview after edit box" will get a blank list
1222 if ( $this->formtype
== 'preview' ) {
1223 $previewOutput = $this->getPreviewText();
1226 $rows = $wgUser->getIntOption( 'rows' );
1227 $cols = $wgUser->getIntOption( 'cols' );
1229 $ew = $wgUser->getOption( 'editwidth' );
1230 if ( $ew ) $ew = " style=\"width:100%\"";
1233 $q = 'action=submit';
1234 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1235 $action = $wgTitle->escapeLocalURL( $q );
1237 $colonSep = wfMsg( 'colon-separator' );
1238 $summary = wfMsg( 'summary' ) . $colonSep;
1239 $subject = wfMsg( 'subject' ) . $colonSep;
1241 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedText(),
1242 wfMsgExt('cancel', array('parseinline')) );
1243 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1244 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1245 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1246 htmlspecialchars( wfMsg( 'newwindow' ) );
1248 global $wgRightsText;
1249 if ( $wgRightsText ) {
1250 $copywarnMsg = array( 'copyrightwarning',
1251 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1254 $copywarnMsg = array( 'copyrightwarning2',
1255 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1258 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1259 # prepare toolbar for edit buttons
1260 $toolbar = EditPage
::getEditToolbar();
1265 // activate checkboxes if user wants them to be always active
1266 if( !$this->preview
&& !$this->diff
) {
1267 # Sort out the "watch" checkbox
1268 if( $wgUser->getOption( 'watchdefault' ) ) {
1270 $this->watchthis
= true;
1271 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1273 $this->watchthis
= true;
1274 } elseif( $this->mTitle
->userIsWatching() ) {
1276 $this->watchthis
= true;
1279 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1282 $wgOut->addHTML( $this->editFormPageTop
);
1284 if ( $wgUser->getOption( 'previewontop' ) ) {
1286 if ( 'preview' == $this->formtype
) {
1287 $this->showPreview( $previewOutput );
1289 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1292 if ( 'diff' == $this->formtype
) {
1298 $wgOut->addHTML( $this->editFormTextTop
);
1300 # if this is a comment, show a subject line at the top, which is also the edit summary.
1301 # Otherwise, show a summary field at the bottom
1302 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1304 # If a blank edit summary was previously provided, and the appropriate
1305 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1306 # user being bounced back more than once in the event that a summary
1309 # For a bit more sophisticated detection of blank summaries, hash the
1310 # automatic one and pass that in the hidden field wpAutoSummary.
1311 $summaryhiddens = '';
1312 if( $this->missingSummary
) $summaryhiddens .= Xml
::hidden( 'wpIgnoreBlankSummary', true );
1313 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1314 $summaryhiddens .= Xml
::hidden( 'wpAutoSummary', $autosumm );
1315 if( $this->section
== 'new' ) {
1316 $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 />";
1317 $editsummary = "<div class='editOptions'>\n";
1319 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary
) );
1320 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').$colonSep.$sk->commentBlock( $formattedSummary, $this->mTitle
, true )."</div>\n" : '';
1321 $summarypreview = '';
1323 $commentsubject = '';
1324 $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 />";
1325 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').$colonSep.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1326 $subjectpreview = '';
1329 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1330 if( !$this->preview
&& !$this->diff
) {
1331 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1333 $templates = ($this->preview ||
$this->section
!= '') ?
$this->mPreviewTemplates
: $this->mArticle
->getUsedTemplates();
1334 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1336 $hiddencats = $this->mArticle
->getHiddenCategories();
1337 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1339 global $wgUseMetadataEdit ;
1340 if ( $wgUseMetadataEdit ) {
1341 $metadata = $this->mMetaData
;
1342 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1343 $top = wfMsgWikiHtml( 'metadata_help' );
1344 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1346 else $metadata = "" ;
1350 if ($this->wasDeletedSinceLastEdit()) {
1351 if ( 'save' != $this->formtype
) {
1352 $wgOut->addWikiMsg('deletedwhileediting');
1354 // Hide the toolbar and edit area, use can click preview to get it back
1355 // Add an confirmation checkbox and explanation.
1357 $hidden = 'type="hidden" style="display:none;"';
1358 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1360 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1361 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1367 $checkboxes = self
::getCheckboxes( $tabindex, $sk,
1368 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1370 $checkboxhtml = implode( $checkboxes, "\n" );
1372 $buttons = $this->getEditButtons( $tabindex );
1373 $buttonshtml = implode( $buttons, "\n" );
1375 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1376 ?
'' : Xml
::hidden( 'safemode', '1' );
1378 $wgOut->addHTML( <<<END
1380 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1384 if( is_callable( $formCallback ) ) {
1385 call_user_func_array( $formCallback, array( &$wgOut ) );
1388 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1390 // Put these up at the top to ensure they aren't lost on early form submission
1392 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1393 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1394 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1395 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1397 $encodedtext = htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) );
1398 if( $encodedtext !== '' ) {
1399 // Ensure there's a newline at the end, otherwise adding lines
1401 // But don't add a newline if the ext is empty, or Firefox in XHTML
1402 // mode will show an extra newline. A bit annoying.
1403 $encodedtext .= "\n";
1406 $wgOut->addHTML( <<<END
1410 {$this->editFormTextBeforeContent}
1411 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1412 cols='{$cols}'{$ew} $hidden>{$encodedtext}</textarea>
1416 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1417 $wgOut->addHTML( $this->editFormTextAfterWarn
);
1427 "<div class='editButtons'>
1429 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1430 </div><!-- editButtons -->
1431 </div><!-- editOptions -->");
1434 * To make it harder for someone to slip a user a page
1435 * which submits an edit form to the wiki without their
1436 * knowledge, a random token is associated with the login
1437 * session. If it's not passed back with the submission,
1438 * we won't save the page, or render user JavaScript and
1441 * For anon editors, who may not have a session, we just
1442 * include the constant suffix to prevent editing from
1443 * broken text-mangling proxies.
1445 $token = htmlspecialchars( $wgUser->editToken() );
1446 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1448 $wgOut->addHtml( '<div class="mw-editTools">' );
1449 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1450 $wgOut->addHtml( '</div>' );
1452 $wgOut->addHTML( $this->editFormTextAfterTools
);
1455 <div class='templatesUsed'>
1456 {$formattedtemplates}
1458 <div class='hiddencats'>
1459 {$formattedhiddencats}
1463 if ( $this->isConflict
&& wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1464 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1466 $de = new DifferenceEngine( $this->mTitle
);
1467 $de->setText( $this->textbox2
, $this->textbox1
);
1468 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1470 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1471 $wgOut->addHTML( "<textarea tabindex='6' id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}'>"
1472 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
1474 $wgOut->addHTML( $this->editFormTextBottom
);
1475 $wgOut->addHTML( "</form>\n" );
1476 if ( !$wgUser->getOption( 'previewontop' ) ) {
1478 if ( $this->formtype
== 'preview') {
1479 $this->showPreview( $previewOutput );
1481 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1484 if ( $this->formtype
== 'diff') {
1490 wfProfileOut( $fname );
1494 * Append preview output to $wgOut.
1495 * Includes category rendering if this is a category page.
1497 * @param string $text The HTML to be output for the preview.
1499 protected function showPreview( $text ) {
1502 $wgOut->addHTML( '<div id="wikiPreview">' );
1503 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1504 $this->mArticle
->openShowCategory();
1506 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1507 $wgOut->addHTML( $text );
1508 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1509 $this->mArticle
->closeShowCategory();
1511 $wgOut->addHTML( '</div>' );
1515 * Live Preview lets us fetch rendered preview page content and
1516 * add it to the page without refreshing the whole page.
1517 * If not supported by the browser it will fall through to the normal form
1518 * submission method.
1520 * This function outputs a script tag to support live preview, and
1521 * returns an onclick handler which should be added to the attributes
1522 * of the preview button
1524 function doLivePreviewScript() {
1525 global $wgOut, $wgTitle;
1526 $wgOut->addScriptFile( 'preview.js' );
1527 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1528 return "return !lpDoPreview(" .
1529 "editform.wpTextbox1.value," .
1530 '"' . $liveAction . '"' . ")";
1533 function getLastDelete() {
1534 $dbr = wfGetDB( DB_SLAVE
);
1535 $fname = 'EditPage::getLastDelete';
1536 $res = $dbr->select(
1537 array( 'logging', 'user' ),
1547 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1548 'log_title' => $this->mTitle
->getDBkey(),
1549 'log_type' => 'delete',
1550 'log_action' => 'delete',
1551 'user_id=log_user' ),
1553 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1555 if($dbr->numRows($res) == 1) {
1556 while ( $x = $dbr->fetchObject ( $res ) )
1558 $dbr->freeResult ( $res ) ;
1566 * Get the rendered text for previewing.
1569 function getPreviewText() {
1570 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang;
1572 $fname = 'EditPage::getPreviewText';
1573 wfProfileIn( $fname );
1575 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1576 if ( $this->mTokenOkExceptSuffix
) {
1577 $note = wfMsg( 'token_suffix_mismatch' );
1579 $note = wfMsg( 'session_fail_preview' );
1582 $note = wfMsg( 'previewnote' );
1585 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1586 $parserOptions->setEditSection( false );
1589 if( $wgRawHtml && !$this->mTokenOk
) {
1590 // Could be an offsite preview attempt. This is very unsafe if
1591 // HTML is enabled, as it could be an attack.
1592 return $wgOut->parse( "<div class='previewnote'>" .
1593 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1596 # don't parse user css/js, show message about preview
1597 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1599 if ( $this->isCssJsSubpage
) {
1600 if(preg_match("/\\.css$/", $this->mTitle
->getText() ) ) {
1601 $previewtext = wfMsg('usercsspreview');
1602 } else if(preg_match("/\\.js$/", $this->mTitle
->getText() ) ) {
1603 $previewtext = wfMsg('userjspreview');
1605 $parserOptions->setTidy(true);
1606 $parserOutput = $wgParser->parse( $previewtext , $this->mTitle
, $parserOptions );
1607 $wgOut->addHTML( $parserOutput->mText
);
1609 } else if( $rt = Title
::newFromRedirect( $this->textbox1
) ) {
1610 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
1612 $toparse = $this->textbox1
;
1614 # If we're adding a comment, we need to show the
1615 # summary as the headline
1616 if($this->section
=="new" && $this->summary
!="") {
1617 $toparse="== {$this->summary} ==\n\n".$toparse;
1620 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1622 // Parse mediawiki messages with correct target language
1623 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1624 $pos = strrpos( $this->mTitle
->getText(), '/' );
1625 if ( $pos !== false ) {
1626 $code = substr( $this->mTitle
->getText(), $pos+
1 );
1628 case $wgLang->getCode():
1629 $obj = $wgLang; break;
1630 case $wgContLang->getCode():
1631 $obj = $wgContLang; break;
1633 $obj = Language
::factory( $code );
1635 $parserOptions->setTargetLanguage( $obj );
1640 $parserOptions->setTidy(true);
1641 $parserOptions->enableLimitReport();
1642 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ),
1643 $this->mTitle
, $parserOptions );
1645 $previewHTML = $parserOutput->getText();
1646 $wgOut->addParserOutputNoText( $parserOutput );
1648 # ParserOutput might have altered the page title, so reset it
1649 # Also, use the title defined by DISPLAYTITLE magic word when present
1650 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false ) {
1651 $wgOut->setPageTitle( wfMsg( 'editing', $dt ) );
1653 $wgOut->setPageTitle( wfMsg( 'editing', $wgTitle->getPrefixedText() ) );
1656 foreach ( $parserOutput->getTemplates() as $ns => $template)
1657 foreach ( array_keys( $template ) as $dbk)
1658 $this->mPreviewTemplates
[] = Title
::makeTitle($ns, $dbk);
1660 if ( count( $parserOutput->getWarnings() ) ) {
1661 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1665 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1666 "<div class='previewnote'>" . $wgOut->parse( $note ) . "</div>\n";
1667 if ( $this->isConflict
) {
1668 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1671 if( $wgUser->getOption( 'previewontop' ) ) {
1672 // Spacer for the edit toolbar
1673 $previewfoot = '<p><br /></p>';
1678 wfProfileOut( $fname );
1679 return $previewhead . $previewHTML . $previewfoot;
1683 * Call the stock "user is blocked" page
1685 function blockedPage() {
1686 global $wgOut, $wgUser;
1687 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1689 # If the user made changes, preserve them when showing the markup
1690 # (This happens when a user is blocked during edit, for instance)
1691 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1693 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1695 $source = $this->textbox1
;
1698 # Spit out the source or the user's modified version
1699 if( $source !== false ) {
1700 $rows = $wgUser->getOption( 'rows' );
1701 $cols = $wgUser->getOption( 'cols' );
1702 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1703 $wgOut->addHtml( '<hr />' );
1704 $wgOut->addWikiMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() );
1705 # Why we don't use Xml::element here?
1706 # Is it because if $source is '', it returns <textarea />?
1707 $wgOut->addHtml( Xml
::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml
::closeElement( 'textarea' ) );
1712 * Produce the stock "please login to edit pages" page
1714 function userNotLoggedInPage() {
1715 global $wgUser, $wgOut, $wgTitle;
1716 $skin = $wgUser->getSkin();
1718 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1719 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1721 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1722 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1723 $wgOut->setArticleRelated( false );
1725 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1726 $wgOut->returnToMain( false, $wgTitle );
1730 * Creates a basic error page which informs the user that
1731 * they have attempted to edit a nonexistant section.
1733 function noSuchSectionPage() {
1734 global $wgOut, $wgTitle;
1736 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1737 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1738 $wgOut->setArticleRelated( false );
1740 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section
);
1741 $wgOut->returnToMain( false, $wgTitle );
1745 * Produce the stock "your edit contains spam" page
1747 * @param $match Text which triggered one or more filters
1749 function spamPage( $match = false ) {
1750 global $wgOut, $wgTitle;
1752 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1753 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1754 $wgOut->setArticleRelated( false );
1756 $wgOut->addHtml( '<div id="spamprotected">' );
1757 $wgOut->addWikiMsg( 'spamprotectiontext' );
1759 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1760 $wgOut->addHtml( '</div>' );
1762 $wgOut->returnToMain( false, $wgTitle );
1769 function mergeChangesInto( &$editText ){
1770 $fname = 'EditPage::mergeChangesInto';
1771 wfProfileIn( $fname );
1773 $db = wfGetDB( DB_MASTER
);
1775 // This is the revision the editor started from
1776 $baseRevision = $this->getBaseRevision();
1777 if( is_null( $baseRevision ) ) {
1778 wfProfileOut( $fname );
1781 $baseText = $baseRevision->getText();
1783 // The current state, we want to merge updates into it
1784 $currentRevision = Revision
::loadFromTitle(
1785 $db, $this->mTitle
);
1786 if( is_null( $currentRevision ) ) {
1787 wfProfileOut( $fname );
1790 $currentText = $currentRevision->getText();
1793 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1794 $editText = $result;
1795 wfProfileOut( $fname );
1798 wfProfileOut( $fname );
1804 * Check if the browser is on a blacklist of user-agents known to
1805 * mangle UTF-8 data on form submission. Returns true if Unicode
1806 * should make it through, false if it's known to be a problem.
1810 function checkUnicodeCompliantBrowser() {
1811 global $wgBrowserBlackList;
1812 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1813 // No User-Agent header sent? Trust it by default...
1816 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1817 foreach ( $wgBrowserBlackList as $browser ) {
1818 if ( preg_match($browser, $currentbrowser) ) {
1826 * @deprecated use $wgParser->stripSectionName()
1828 function pseudoParseSectionAnchor( $text ) {
1830 return $wgParser->stripSectionName( $text );
1834 * Format an anchor fragment as it would appear for a given section name
1835 * @param string $text
1839 function sectionAnchor( $text ) {
1841 return $wgParser->guessSectionNameFromWikiText( $text );
1845 * Shows a bulletin board style toolbar for common editing functions.
1846 * It can be disabled in the user preferences.
1847 * The necessary JavaScript code can be found in skins/common/edit.js.
1851 static function getEditToolbar() {
1852 global $wgStylePath, $wgContLang, $wgLang, $wgJsMimeType;
1855 * toolarray an array of arrays which each include the filename of
1856 * the button image (without path), the opening tag, the closing tag,
1857 * and optionally a sample text that is inserted between the two when no
1858 * selection is highlighted.
1859 * The tip text is shown when the user moves the mouse over the button.
1861 * Already here are accesskeys (key), which are not used yet until someone
1862 * can figure out a way to make them work in IE. However, we should make
1863 * sure these keys are not defined on the edit page.
1867 'image' => $wgLang->getImageFile('button-bold'),
1868 'id' => 'mw-editbutton-bold',
1870 'close' => '\'\'\'',
1871 'sample' => wfMsg('bold_sample'),
1872 'tip' => wfMsg('bold_tip'),
1876 'image' => $wgLang->getImageFile('button-italic'),
1877 'id' => 'mw-editbutton-italic',
1880 'sample' => wfMsg('italic_sample'),
1881 'tip' => wfMsg('italic_tip'),
1885 'image' => $wgLang->getImageFile('button-link'),
1886 'id' => 'mw-editbutton-link',
1889 'sample' => wfMsg('link_sample'),
1890 'tip' => wfMsg('link_tip'),
1894 'image' => $wgLang->getImageFile('button-extlink'),
1895 'id' => 'mw-editbutton-extlink',
1898 'sample' => wfMsg('extlink_sample'),
1899 'tip' => wfMsg('extlink_tip'),
1903 'image' => $wgLang->getImageFile('button-headline'),
1904 'id' => 'mw-editbutton-headline',
1907 'sample' => wfMsg('headline_sample'),
1908 'tip' => wfMsg('headline_tip'),
1912 'image' => $wgLang->getImageFile('button-image'),
1913 'id' => 'mw-editbutton-image',
1914 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).':',
1916 'sample' => wfMsg('image_sample'),
1917 'tip' => wfMsg('image_tip'),
1921 'image' => $wgLang->getImageFile('button-media'),
1922 'id' => 'mw-editbutton-media',
1923 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1925 'sample' => wfMsg('media_sample'),
1926 'tip' => wfMsg('media_tip'),
1930 'image' => $wgLang->getImageFile('button-math'),
1931 'id' => 'mw-editbutton-math',
1933 'close' => "</math>",
1934 'sample' => wfMsg('math_sample'),
1935 'tip' => wfMsg('math_tip'),
1939 'image' => $wgLang->getImageFile('button-nowiki'),
1940 'id' => 'mw-editbutton-nowiki',
1941 'open' => "<nowiki>",
1942 'close' => "</nowiki>",
1943 'sample' => wfMsg('nowiki_sample'),
1944 'tip' => wfMsg('nowiki_tip'),
1948 'image' => $wgLang->getImageFile('button-sig'),
1949 'id' => 'mw-editbutton-signature',
1953 'tip' => wfMsg('sig_tip'),
1957 'image' => $wgLang->getImageFile('button-hr'),
1958 'id' => 'mw-editbutton-hr',
1959 'open' => "\n----\n",
1962 'tip' => wfMsg('hr_tip'),
1966 $toolbar = "<div id='toolbar'>\n";
1967 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1969 foreach($toolarray as $tool) {
1971 $image = $wgStylePath.'/common/images/'.$tool['image'],
1972 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1973 // Older browsers show a "speedtip" type message only for ALT.
1974 // Ideally these should be different, realistically they
1975 // probably don't need to be.
1976 $tip = $tool['tip'],
1977 $open = $tool['open'],
1978 $close = $tool['close'],
1979 $sample = $tool['sample'],
1980 $cssId = $tool['id'],
1983 $paramList = implode( ',',
1984 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
1985 $toolbar.="addButton($paramList);\n";
1988 $toolbar.="/*]]>*/\n</script>";
1989 $toolbar.="\n</div>";
1994 * Returns an array of html code of the following checkboxes:
1997 * @param $tabindex Current tabindex
1998 * @param $skin Skin object
1999 * @param $checked Array of checkbox => bool, where bool indicates the checked
2000 * status of the checkbox
2004 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
2007 $checkboxes = array();
2009 $checkboxes['minor'] = '';
2010 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
2011 if ( $wgUser->isAllowed('minoredit') ) {
2013 'tabindex' => ++
$tabindex,
2014 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2015 'id' => 'wpMinoredit',
2017 $checkboxes['minor'] =
2018 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2019 " <label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
2022 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2023 $checkboxes['watch'] = '';
2024 if ( $wgUser->isLoggedIn() ) {
2026 'tabindex' => ++
$tabindex,
2027 'accesskey' => wfMsg( 'accesskey-watch' ),
2028 'id' => 'wpWatchthis',
2030 $checkboxes['watch'] =
2031 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2032 " <label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
2038 * Returns an array of html code of the following buttons:
2039 * save, diff, preview and live
2041 * @param $tabindex Current tabindex
2045 public function getEditButtons(&$tabindex) {
2046 global $wgLivePreview, $wgUser;
2054 'tabindex' => ++
$tabindex,
2055 'value' => wfMsg('savearticle'),
2056 'accesskey' => wfMsg('accesskey-save'),
2057 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2059 $buttons['save'] = Xml
::element('input', $temp, '');
2061 ++
$tabindex; // use the same for preview and live preview
2062 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2064 'id' => 'wpPreview',
2065 'name' => 'wpPreview',
2067 'tabindex' => $tabindex,
2068 'value' => wfMsg('showpreview'),
2070 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2071 'style' => 'display: none;',
2073 $buttons['preview'] = Xml
::element('input', $temp, '');
2076 'id' => 'wpLivePreview',
2077 'name' => 'wpLivePreview',
2079 'tabindex' => $tabindex,
2080 'value' => wfMsg('showlivepreview'),
2081 'accesskey' => wfMsg('accesskey-preview'),
2083 'onclick' => $this->doLivePreviewScript(),
2085 $buttons['live'] = Xml
::element('input', $temp, '');
2088 'id' => 'wpPreview',
2089 'name' => 'wpPreview',
2091 'tabindex' => $tabindex,
2092 'value' => wfMsg('showpreview'),
2093 'accesskey' => wfMsg('accesskey-preview'),
2094 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2096 $buttons['preview'] = Xml
::element('input', $temp, '');
2097 $buttons['live'] = '';
2104 'tabindex' => ++
$tabindex,
2105 'value' => wfMsg('showdiff'),
2106 'accesskey' => wfMsg('accesskey-diff'),
2107 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2109 $buttons['diff'] = Xml
::element('input', $temp, '');
2111 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons ) );
2116 * Output preview text only. This can be sucked into the edit page
2117 * via JavaScript, and saves the server time rendering the skin as
2118 * well as theoretically being more robust on the client (doesn't
2119 * disturb the edit box's undo history, won't eat your text on
2122 * @todo This doesn't include category or interlanguage links.
2123 * Would need to enhance it a bit, <s>maybe wrap them in XML
2124 * or something...</s> that might also require more skin
2125 * initialization, so check whether that's a problem.
2127 function livePreview() {
2130 header( 'Content-type: text/xml; charset=utf-8' );
2131 header( 'Cache-control: no-cache' );
2133 $previewText = $this->getPreviewText();
2134 #$categories = $skin->getCategoryLinks();
2137 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2138 Xml
::tags( 'livepreview', null,
2139 Xml
::element( 'preview', null, $previewText )
2140 #. Xml::element( 'category', null, $categories )
2147 * Get a diff between the current contents of the edit box and the
2148 * version of the page we're editing from.
2150 * If this is a section edit, we'll replace the section as for final
2151 * save and then make a comparison.
2153 function showDiff() {
2154 $oldtext = $this->mArticle
->fetchContent();
2155 $newtext = $this->mArticle
->replaceSection(
2156 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2157 $newtext = $this->mArticle
->preSaveTransform( $newtext );
2158 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2159 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2160 if ( $oldtext !== false ||
$newtext != '' ) {
2161 $de = new DifferenceEngine( $this->mTitle
);
2162 $de->setText( $oldtext, $newtext );
2163 $difftext = $de->getDiff( $oldtitle, $newtitle );
2164 $de->showDiffStyle();
2170 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
2174 * Filter an input field through a Unicode de-armoring process if it
2175 * came from an old browser with known broken Unicode editing issues.
2177 * @param WebRequest $request
2178 * @param string $field
2182 function safeUnicodeInput( $request, $field ) {
2183 $text = rtrim( $request->getText( $field ) );
2184 return $request->getBool( 'safemode' )
2185 ?
$this->unmakesafe( $text )
2190 * Filter an output field through a Unicode armoring process if it is
2191 * going to an old browser with known broken Unicode editing issues.
2193 * @param string $text
2197 function safeUnicodeOutput( $text ) {
2199 $codedText = $wgContLang->recodeForEdit( $text );
2200 return $this->checkUnicodeCompliantBrowser()
2202 : $this->makesafe( $codedText );
2206 * A number of web browsers are known to corrupt non-ASCII characters
2207 * in a UTF-8 text editing environment. To protect against this,
2208 * detected browsers will be served an armored version of the text,
2209 * with non-ASCII chars converted to numeric HTML character references.
2211 * Preexisting such character references will have a 0 added to them
2212 * to ensure that round-trips do not alter the original data.
2214 * @param string $invalue
2218 function makesafe( $invalue ) {
2219 // Armor existing references for reversability.
2220 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2225 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2226 $bytevalue = ord( $invalue{$i} );
2227 if( $bytevalue <= 0x7F ) { //0xxx xxxx
2228 $result .= chr( $bytevalue );
2230 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
2231 $working = $working << 6;
2232 $working +
= ($bytevalue & 0x3F);
2234 if( $bytesleft <= 0 ) {
2235 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2237 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
2238 $working = $bytevalue & 0x1F;
2240 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
2241 $working = $bytevalue & 0x0F;
2243 } else { //1111 0xxx
2244 $working = $bytevalue & 0x07;
2252 * Reverse the previously applied transliteration of non-ASCII characters
2253 * back to UTF-8. Used to protect data from corruption by broken web browsers
2254 * as listed in $wgBrowserBlackList.
2256 * @param string $invalue
2260 function unmakesafe( $invalue ) {
2262 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2263 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2267 $hexstring .= $invalue{$i};
2269 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2271 // Do some sanity checks. These aren't needed for reversability,
2272 // but should help keep the breakage down if the editor
2273 // breaks one of the entities whilst editing.
2274 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2275 $codepoint = hexdec($hexstring);
2276 $result .= codepointToUtf8( $codepoint );
2278 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2281 $result .= substr( $invalue, $i, 1 );
2284 // reverse the transform that we made for reversability reasons.
2285 return strtr( $result, array( "�" => "&#x" ) );
2288 function noCreatePermission() {
2290 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2291 $wgOut->addWikiMsg( 'nocreatetext' );
2295 * If there are rows in the deletion log for this page, show them,
2296 * along with a nice little note for the user
2298 * @param OutputPage $out
2300 protected function showDeletionLog( $out ) {
2302 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
2303 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle
->getPrefixedText() );
2304 if( $pager->getNumRows() > 0 ) {
2305 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2306 $out->addWikiMsg( 'recreate-deleted-warn' );
2308 $loglist->beginLogEventsList() .
2310 $loglist->endLogEventsList()
2312 $out->addHtml( '</div>' );
2317 * Attempt submission
2318 * @return bool false if output is done, true if the rest of the form should be displayed
2320 function attemptSave() {
2321 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2323 $resultDetails = false;
2324 $value = $this->internalAttemptSave( $resultDetails, $wgUser->isAllowed('bot') && $wgRequest->getBool('bot', true) );
2326 if( $value == self
::AS_SUCCESS_UPDATE ||
$value == self
::AS_SUCCESS_NEW_ARTICLE
) {
2327 $this->didSave
= true;
2331 case self
::AS_HOOK_ERROR_EXPECTED
:
2332 case self
::AS_CONTENT_TOO_BIG
:
2333 case self
::AS_ARTICLE_WAS_DELETED
:
2334 case self
::AS_CONFLICT_DETECTED
:
2335 case self
::AS_SUMMARY_NEEDED
:
2336 case self
::AS_TEXTBOX_EMPTY
:
2337 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
2341 case self
::AS_HOOK_ERROR
:
2342 case self
::AS_FILTERING
:
2343 case self
::AS_SUCCESS_NEW_ARTICLE
:
2344 case self
::AS_SUCCESS_UPDATE
:
2347 case self
::AS_SPAM_ERROR
:
2348 $this->spamPage ( $resultDetails['spam'] );
2351 case self
::AS_BLOCKED_PAGE_FOR_USER
:
2352 $this->blockedPage();
2355 case self
::AS_IMAGE_REDIRECT_ANON
:
2356 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2359 case self
::AS_READ_ONLY_PAGE_ANON
:
2360 $this->userNotLoggedInPage();
2363 case self
::AS_READ_ONLY_PAGE_LOGGED
:
2364 case self
::AS_READ_ONLY_PAGE
:
2365 $wgOut->readOnlyPage();
2368 case self
::AS_RATE_LIMITED
:
2369 $wgOut->rateLimited();
2372 case self
::AS_NO_CREATE_PERMISSION
;
2373 $this->noCreatePermission();
2376 case self
::AS_BLANK_ARTICLE
:
2377 $wgOut->redirect( $wgTitle->getFullURL() );
2380 case self
::AS_IMAGE_REDIRECT_LOGGED
:
2381 $wgOut->permissionRequired( 'upload' );
2386 function getBaseRevision() {
2387 if ($this->mBaseRevision
== false) {
2388 $db = wfGetDB( DB_MASTER
);
2389 $baseRevision = Revision
::loadFromTimestamp(
2390 $db, $this->mTitle
, $this->edittime
);
2391 return $this->mBaseRevision
= $baseRevision;
2393 return $this->mBaseRevision
;