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, $wgMessageCache;
115 # Get variables from query string :P
116 $section = $wgRequest->getVal( 'section' );
117 $preload = $wgRequest->getVal( 'preload' );
118 $undoafter = $wgRequest->getVal( 'undoafter' );
119 $undo = $wgRequest->getVal( 'undo' );
121 wfProfileIn( __METHOD__
);
124 if( !$this->mTitle
->exists() ) {
125 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
126 $wgMessageCache->loadAllMessages();
127 # If this is a system message, get the default text.
128 $text = wfMsgWeirdKey( $this->mTitle
->getText() ) ;
130 # If requested, preload some text.
131 $text = $this->getPreloadedText( $preload );
133 # We used to put MediaWiki:Newarticletext here if
134 # $text was empty at this point.
135 # This is now shown above the edit box instead.
137 // FIXME: may be better to use Revision class directly
138 // But don't mess with it just yet. Article knows how to
139 // fetch the page record from the high-priority server,
140 // which is needed to guarantee we don't pick up lagged
143 $text = $this->mArticle
->getContent();
145 if ($undo > 0 && $undoafter > 0 && $undo < $undoafter) {
146 # If they got undoafter and undo round the wrong way, switch them
147 list( $undo, $undoafter ) = array( $undoafter, $undo );
150 if ( $undo > 0 && $undo > $undoafter ) {
151 # Undoing a specific edit overrides section editing; section-editing
152 # doesn't work with undoing.
154 $undorev = Revision
::newFromId($undo);
155 $oldrev = Revision
::newFromId($undoafter);
157 $undorev = Revision
::newFromId($undo);
158 $oldrev = $undorev ?
$undorev->getPrevious() : null;
161 # Sanity check, make sure it's the right page,
162 # the revisions exist and they were not deleted.
163 # Otherwise, $text will be left as-is.
164 if( !is_null( $undorev ) && !is_null( $oldrev ) &&
165 $undorev->getPage() == $oldrev->getPage() &&
166 $undorev->getPage() == $this->mArticle
->getID() &&
167 !$undorev->isDeleted( Revision
::DELETED_TEXT
) &&
168 !$oldrev->isDeleted( Revision
::DELETED_TEXT
) ) {
169 $undorev_text = $undorev->getText();
170 $oldrev_text = $oldrev->getText();
171 $currev_text = $text;
173 if ( $currev_text != $undorev_text ) {
174 $result = wfMerge( $undorev_text, $oldrev_text, $currev_text, $text );
176 # No use doing a merge if it's just a straight revert.
177 $text = $oldrev_text;
181 # Inform the user of our success and set an automatic edit summary
182 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
183 $firstrev = $oldrev->getNext();
184 # If we just undid one rev, use an autosummary
185 if( $firstrev->mId
== $undo ) {
186 $this->summary
= wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
188 $this->formtype
= 'diff';
190 # Warn the user that something went wrong
191 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
194 // Failed basic sanity checks.
195 // Older revisions may have been removed since the link
196 // was created, or we may simply have got bogus input.
197 $this->editFormPageTop
.= $wgOut->parse( wfMsgNoTrans( 'undo-norev' ) );
199 } else if( $section != '' ) {
200 if( $section == 'new' ) {
201 $text = $this->getPreloadedText( $preload );
203 $text = $wgParser->getSection( $text, $section, $def_text );
208 wfProfileOut( __METHOD__
);
213 * Get the contents of a page from its title and remove includeonly tags
215 * @param $preload String: the title of the page.
216 * @return string The contents of the page.
218 protected function getPreloadedText($preload) {
219 if ( $preload === '' )
222 $preloadTitle = Title
::newFromText( $preload );
223 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
224 $rev=Revision
::newFromTitle($preloadTitle);
225 if ( is_object( $rev ) ) {
226 $text = $rev->getText();
227 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
228 // its own mini-parser! -ævar
229 $text = preg_replace( '~</?includeonly>~', '', $text );
238 * This is the function that extracts metadata from the article body on the first view.
239 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
240 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
242 function extractMetaDataFromArticle () {
243 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
244 $this->mMetaData
= '' ;
245 if ( !$wgUseMetadataEdit ) return ;
246 if ( $wgMetadataWhitelist == '' ) return ;
248 $t = $this->getContent();
250 # MISSING : <nowiki> filtering
252 # Categories and language links
253 $t = explode ( "\n" , $t ) ;
254 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
255 $cat = $ll = array() ;
256 foreach ( $t AS $key => $x )
258 $y = trim ( strtolower ( $x ) ) ;
259 while ( substr ( $y , 0 , 2 ) == '[[' )
261 $y = explode ( ']]' , trim ( $x ) ) ;
262 $first = array_shift ( $y ) ;
263 $first = explode ( ':' , $first ) ;
264 $ns = array_shift ( $first ) ;
265 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
266 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
268 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
269 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
271 $x = implode ( ']]' , $y ) ;
273 $y = trim ( strtolower ( $x ) ) ;
277 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
278 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
279 $t = implode ( "\n" , $t ) ;
282 $sat = array () ; # stand-alone-templates; must be lowercase
283 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
284 $wl_article = new Article ( $wl_title ) ;
285 $wl = explode ( "\n" , $wl_article->getContent() ) ;
286 foreach ( $wl AS $x )
290 while ( substr ( $x , 0 , 1 ) == '*' )
293 $x = trim ( substr ( $x , 1 ) ) ;
297 $sat[] = strtolower ( $x ) ;
302 # Templates, but only some
303 $t = explode ( '{{' , $t ) ;
305 foreach ( $t AS $key => $x )
307 $y = explode ( '}}' , $x , 2 ) ;
308 if ( count ( $y ) == 2 )
311 $z = explode ( '|' , $z ) ;
312 $tn = array_shift ( $z ) ;
313 if ( in_array ( strtolower ( $tn ) , $sat ) )
315 $tl[] = '{{' . $y[0] . '}}' ;
317 $y = explode ( '}}' , $y[1] , 2 ) ;
319 else $t[$key] = '{{' . $x ;
321 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
324 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
325 $t = implode ( '' , $t ) ;
327 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
328 $this->mArticle
->mContent
= $t ;
329 $this->mMetaData
= $s ;
332 protected function wasDeletedSinceLastEdit() {
333 /* Note that we rely on the logging table, which hasn't been always there,
334 * but that doesn't matter, because this only applies to brand new
337 if ( $this->deletedSinceEdit
)
339 if ( $this->mTitle
->isDeleted() ) {
340 $this->lastDelete
= $this->getLastDelete();
341 if ( !is_null($this->lastDelete
) ) {
342 $deletetime = $this->lastDelete
->log_timestamp
;
343 if ( ($deletetime - $this->starttime
) > 0 ) {
344 $this->deletedSinceEdit
= true;
348 return $this->deletedSinceEdit
;
356 * This is the function that gets called for "action=edit". It
357 * sets up various member variables, then passes execution to
358 * another function, usually showEditForm()
360 * The edit form is self-submitting, so that when things like
361 * preview and edit conflicts occur, we get the same form back
362 * with the extra stuff added. Only when the final submission
363 * is made and all is well do we actually save and redirect to
364 * the newly-edited page.
367 global $wgOut, $wgUser, $wgRequest;
369 if ( !wfRunHooks( 'AlternateEdit', array( &$this ) ) )
372 wfProfileIn( __METHOD__
);
373 wfDebug( __METHOD__
.": enter\n" );
375 // this is not an article
376 $wgOut->setArticleFlag( false );
378 $this->importFormData( $wgRequest );
379 $this->firsttime
= false;
382 $this->livePreview();
383 wfProfileOut( __METHOD__
);
391 $this->preview
= true;
392 } elseif( $this->preview ||
$this->diff
){
393 // A warning will be displayed instead
395 $this->readOnlyPage( $this->getContent() );
396 wfProfileOut( __METHOD__
);
401 $wgOut->addScriptFile( 'edit.js' );
403 $permErrors = $this->mTitle
->getUserPermissionsErrors( 'edit', $wgUser );
405 if( !$this->mTitle
->exists() ) {
406 $permErrors = array_merge( $permErrors,
407 wfArrayDiff2( $this->mTitle
->getUserPermissionsErrors( 'create', $wgUser ), $permErrors ) );
410 # Ignore some permissions errors.
412 foreach( $permErrors as $error ) {
413 if ( ( $this->preview ||
$this->diff
) &&
414 ($error[0] == 'blockedtext' ||
$error[0] == 'autoblockedtext'))
416 // Don't worry about blocks when previewing/diffing
420 $permErrors = wfArrayDiff2( $permErrors, $remove );
423 wfDebug( __METHOD__
.": User can't edit\n" );
424 $this->readOnlyPage( $this->getContent(), true, $permErrors, 'edit' );
425 wfProfileOut( __METHOD__
);
429 $this->formtype
= 'save';
430 } else if( $this->preview
) {
431 $this->formtype
= 'preview';
432 } else if ( $this->diff
) {
433 $this->formtype
= 'diff';
434 } else { # First time through
435 $this->firsttime
= true;
436 if( $this->previewOnOpen() ) {
437 $this->formtype
= 'preview';
439 $this->extractMetaDataFromArticle () ;
440 $this->formtype
= 'initial';
445 wfProfileIn( __METHOD__
."-business-end" );
447 $this->isConflict
= false;
448 // css / js subpages of user pages get a special treatment
449 $this->isCssJsSubpage
= $this->mTitle
->isCssJsSubpage();
450 $this->isValidCssJsSubpage
= $this->mTitle
->isValidCssJsSubpage();
452 # Show applicable editing introductions
453 if( $this->formtype
== 'initial' ||
$this->firsttime
)
456 if( $this->mTitle
->isTalkPage() ) {
457 $wgOut->addWikiMsg( 'talkpagetext' );
460 # Optional notices on a per-namespace and per-page basis
461 $editnotice_ns = 'editnotice-'.$this->mTitle
->getNamespace();
462 $editnotice_page = $editnotice_ns.'-'.$this->mTitle
->getDBkey();
463 if ( !wfEmptyMsg( $editnotice_ns, wfMsgForContent( $editnotice_ns ) ) ) {
464 $wgOut->addWikiText( wfMsgForContent( $editnotice_ns ) );
466 if ( MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() ) ) {
467 $parts = explode( '/', $this->mTitle
->getDBkey() );
468 $editnotice_base = $editnotice_ns;
469 while ( count( $parts ) > 0 ) {
470 $editnotice_base .= '-'.array_shift( $parts );
471 if ( !wfEmptyMsg( $editnotice_base, wfMsgForContent( $editnotice_base ) ) ) {
472 $wgOut->addWikiText( wfMsgForContent( $editnotice_base ) );
475 } else if ( !wfEmptyMsg( $editnotice_page, wfMsgForContent( $editnotice_page ) ) ) {
476 $wgOut->addWikiText( wfMsgForContent( $editnotice_page ) );
479 # Attempt submission here. This will check for edit conflicts,
480 # and redundantly check for locked database, blocked IPs, etc.
481 # that edit() already checked just in case someone tries to sneak
482 # in the back door with a hand-edited submission URL.
484 if ( 'save' == $this->formtype
) {
485 if ( !$this->attemptSave() ) {
486 wfProfileOut( __METHOD__
."-business-end" );
487 wfProfileOut( __METHOD__
);
492 # First time through: get contents, set time for conflict
494 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
495 if ($this->initialiseForm() === false) {
496 $this->noSuchSectionPage();
497 wfProfileOut( __METHOD__
."-business-end" );
498 wfProfileOut( __METHOD__
);
501 if( !$this->mTitle
->getArticleId() )
502 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1
, &$this->mTitle
) );
505 $this->showEditForm();
506 wfProfileOut( __METHOD__
."-business-end" );
507 wfProfileOut( __METHOD__
);
511 * Show a read-only error
512 * Parameters are the same as OutputPage:readOnlyPage()
513 * Redirect to the article page if redlink=1
515 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
516 global $wgRequest, $wgOut;
517 if ( $wgRequest->getBool( 'redlink' ) ) {
518 // The edit page was reached via a red link.
519 // Redirect to the article page and let them click the edit tab if
520 // they really want a permission error.
521 $wgOut->redirect( $this->mTitle
->getFullUrl() );
523 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
528 * Should we show a preview when the edit form is first shown?
532 protected function previewOnOpen() {
533 global $wgRequest, $wgUser;
534 if( $wgRequest->getVal( 'preview' ) == 'yes' ) {
535 // Explicit override from request
537 } elseif( $wgRequest->getVal( 'preview' ) == 'no' ) {
538 // Explicit override from request
540 } elseif( $this->section
== 'new' ) {
541 // Nothing *to* preview for new sections
543 } elseif( ( $wgRequest->getVal( 'preload' ) !== '' ||
$this->mTitle
->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
544 // Standard preference behaviour
546 } elseif( !$this->mTitle
->exists() && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
547 // Categories are special
558 function importFormData( &$request ) {
559 global $wgLang, $wgUser;
560 $fname = 'EditPage::importFormData';
561 wfProfileIn( $fname );
563 # Section edit can come from either the form or a link
564 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
566 if( $request->wasPosted() ) {
567 # These fields need to be checked for encoding.
568 # Also remove trailing whitespace, but don't remove _initial_
569 # whitespace from the text boxes. This may be significant formatting.
570 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
571 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
572 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
573 # Truncate for whole multibyte characters. +5 bytes for ellipsis
574 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
576 # Remove extra headings from summaries and new sections.
577 $this->summary
= preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary
);
579 $this->edittime
= $request->getVal( 'wpEdittime' );
580 $this->starttime
= $request->getVal( 'wpStarttime' );
582 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
584 if( is_null( $this->edittime
) ) {
585 # If the form is incomplete, force to preview.
586 wfDebug( "$fname: Form data appears to be incomplete\n" );
587 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
588 $this->preview
= true;
590 /* Fallback for live preview */
591 $this->preview
= $request->getCheck( 'wpPreview' ) ||
$request->getCheck( 'wpLivePreview' );
592 $this->diff
= $request->getCheck( 'wpDiff' );
594 // Remember whether a save was requested, so we can indicate
595 // if we forced preview due to session failure.
596 $this->mTriedSave
= !$this->preview
;
598 if ( $this->tokenOk( $request ) ) {
599 # Some browsers will not report any submit button
600 # if the user hits enter in the comment box.
601 # The unmarked state will be assumed to be a save,
602 # if the form seems otherwise complete.
603 wfDebug( "$fname: Passed token check.\n" );
604 } else if ( $this->diff
) {
605 # Failed token check, but only requested "Show Changes".
606 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
608 # Page might be a hack attempt posted from
609 # an external site. Preview instead of saving.
610 wfDebug( "$fname: Failed token check; forcing preview\n" );
611 $this->preview
= true;
614 $this->save
= !$this->preview
&& !$this->diff
;
615 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
616 $this->edittime
= null;
619 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
620 $this->starttime
= null;
623 $this->recreate
= $request->getCheck( 'wpRecreate' );
625 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
626 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
628 # Don't force edit summaries when a user is editing their own user or talk page
629 if( ( $this->mTitle
->mNamespace
== NS_USER ||
$this->mTitle
->mNamespace
== NS_USER_TALK
) && $this->mTitle
->getText() == $wgUser->getName() ) {
630 $this->allowBlankSummary
= true;
632 $this->allowBlankSummary
= $request->getBool( 'wpIgnoreBlankSummary' );
635 $this->autoSumm
= $request->getText( 'wpAutoSummary' );
637 # Not a posted form? Start with nothing.
638 wfDebug( "$fname: Not a posted form.\n" );
639 $this->textbox1
= '';
640 $this->textbox2
= '';
641 $this->mMetaData
= '';
643 $this->edittime
= '';
644 $this->starttime
= wfTimestampNow();
646 $this->preview
= false;
649 $this->minoredit
= false;
650 $this->watchthis
= false;
651 $this->recreate
= false;
653 if ( $this->section
== 'new' && $request->getVal( 'preloadtitle' ) ) {
654 $this->summary
= $request->getVal( 'preloadtitle' );
658 $this->oldid
= $request->getInt( 'oldid' );
660 $this->live
= $request->getCheck( 'live' );
661 $this->editintro
= $request->getText( 'editintro' );
663 wfProfileOut( $fname );
667 * Make sure the form isn't faking a user's credentials.
669 * @param $request WebRequest
673 function tokenOk( &$request ) {
675 $token = $request->getVal( 'wpEditToken' );
676 $this->mTokenOk
= $wgUser->matchEditToken( $token );
677 $this->mTokenOkExceptSuffix
= $wgUser->matchEditTokenNoSuffix( $token );
678 return $this->mTokenOk
;
682 * Show all applicable editing introductions
684 protected function showIntro() {
685 global $wgOut, $wgUser;
686 if( $this->suppressIntro
)
689 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
690 if( $this->mTitle
->getNamespace() == NS_USER ||
$this->mTitle
->getNamespace() == NS_USER_TALK
) {
691 $parts = explode( '/', $this->mTitle
->getText(), 2 );
692 $username = $parts[0];
693 $id = User
::idFromName( $username );
694 $ip = User
::isIP( $username );
696 if ( $id == 0 && !$ip ) {
697 $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
698 array( 'userpage-userdoesnotexist', $username ) );
702 if( !$this->showCustomIntro() && !$this->mTitle
->exists() ) {
703 if( $wgUser->isLoggedIn() ) {
704 $wgOut->wrapWikiMsg( '<div class="mw-newarticletext">$1</div>', 'newarticletext' );
706 $wgOut->wrapWikiMsg( '<div class="mw-newarticletextanon">$1</div>', 'newarticletextanon' );
708 $this->showDeletionLog( $wgOut );
713 * Attempt to show a custom editing introduction, if supplied
717 protected function showCustomIntro() {
718 if( $this->editintro
) {
719 $title = Title
::newFromText( $this->editintro
);
720 if( $title instanceof Title
&& $title->exists() && $title->userCanRead() ) {
722 $revision = Revision
::newFromTitle( $title );
723 $wgOut->addWikiTextTitleTidy( $revision->getText(), $this->mTitle
);
734 * Attempt submission (no UI)
735 * @return one of the constants describing the result
737 function internalAttemptSave( &$result, $bot = false ) {
738 global $wgFilterCallback, $wgUser, $wgOut, $wgParser;
739 global $wgMaxArticleSize;
741 $fname = 'EditPage::attemptSave';
742 wfProfileIn( $fname );
743 wfProfileIn( "$fname-checks" );
745 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
747 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
748 return self
::AS_HOOK_ERROR
;
751 # Check image redirect
752 if ( $this->mTitle
->getNamespace() == NS_IMAGE
&&
753 Title
::newFromRedirect( $this->textbox1
) instanceof Title
&&
754 !$wgUser->isAllowed( 'upload' ) ) {
755 if( $wgUser->isAnon() ) {
756 return self
::AS_IMAGE_REDIRECT_ANON
;
758 return self
::AS_IMAGE_REDIRECT_LOGGED
;
762 # Reintegrate metadata
763 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
764 $this->mMetaData
= '' ;
767 $match = self
::matchSpamRegex( $this->summary
);
768 if( $match === false ) {
769 $match = self
::matchSpamRegex( $this->textbox1
);
771 if( $match !== false ) {
772 $result['spam'] = $match;
774 $pdbk = $this->mTitle
->getPrefixedDBkey();
775 $match = str_replace( "\n", '', $match );
776 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
777 wfProfileOut( "$fname-checks" );
778 wfProfileOut( $fname );
779 return self
::AS_SPAM_ERROR
;
781 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
, $this->hookError
, $this->summary
) ) {
782 # Error messages or other handling should be performed by the filter function
783 wfProfileOut( "$fname-checks" );
784 wfProfileOut( $fname );
785 return self
::AS_FILTERING
;
787 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1
, $this->section
, &$this->hookError
, $this->summary
) ) ) {
788 # Error messages etc. could be handled within the hook...
789 wfProfileOut( "$fname-checks" );
790 wfProfileOut( $fname );
791 return self
::AS_HOOK_ERROR
;
792 } elseif( $this->hookError
!= '' ) {
793 # ...or the hook could be expecting us to produce an error
794 wfProfileOut( "$fname-checks" );
795 wfProfileOut( $fname );
796 return self
::AS_HOOK_ERROR_EXPECTED
;
798 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
799 # Check block state against master, thus 'false'.
800 wfProfileOut( "$fname-checks" );
801 wfProfileOut( $fname );
802 return self
::AS_BLOCKED_PAGE_FOR_USER
;
804 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
805 if ( $this->kblength
> $wgMaxArticleSize ) {
806 // Error will be displayed by showEditForm()
807 $this->tooBig
= true;
808 wfProfileOut( "$fname-checks" );
809 wfProfileOut( $fname );
810 return self
::AS_CONTENT_TOO_BIG
;
813 if ( !$wgUser->isAllowed('edit') ) {
814 if ( $wgUser->isAnon() ) {
815 wfProfileOut( "$fname-checks" );
816 wfProfileOut( $fname );
817 return self
::AS_READ_ONLY_PAGE_ANON
;
820 wfProfileOut( "$fname-checks" );
821 wfProfileOut( $fname );
822 return self
::AS_READ_ONLY_PAGE_LOGGED
;
826 if ( wfReadOnly() ) {
827 wfProfileOut( "$fname-checks" );
828 wfProfileOut( $fname );
829 return self
::AS_READ_ONLY_PAGE
;
831 if ( $wgUser->pingLimiter() ) {
832 wfProfileOut( "$fname-checks" );
833 wfProfileOut( $fname );
834 return self
::AS_RATE_LIMITED
;
837 # If the article has been deleted while editing, don't save it without
839 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate
) {
840 wfProfileOut( "$fname-checks" );
841 wfProfileOut( $fname );
842 return self
::AS_ARTICLE_WAS_DELETED
;
845 wfProfileOut( "$fname-checks" );
847 # If article is new, insert it.
848 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
851 // Late check for create permission, just in case *PARANOIA*
852 if ( !$this->mTitle
->userCan( 'create' ) ) {
853 wfDebug( "$fname: no create permission\n" );
854 wfProfileOut( $fname );
855 return self
::AS_NO_CREATE_PERMISSION
;
858 # Don't save a new article if it's blank.
859 if ( '' == $this->textbox1
) {
860 wfProfileOut( $fname );
861 return self
::AS_BLANK_ARTICLE
;
864 // Run post-section-merge edit filter
865 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1
, &$this->hookError
, $this->summary
) ) ) {
866 # Error messages etc. could be handled within the hook...
867 wfProfileOut( $fname );
868 return self
::AS_HOOK_ERROR
;
871 $isComment = ( $this->section
== 'new' );
873 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
874 $this->minoredit
, $this->watchthis
, false, $isComment, $bot);
876 wfProfileOut( $fname );
877 return self
::AS_SUCCESS_NEW_ARTICLE
;
880 # Article exists. Check for edit conflict.
882 $this->mArticle
->clear(); # Force reload of dates, etc.
883 $this->mArticle
->forUpdate( true ); # Lock the article
885 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
887 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
888 $this->isConflict
= true;
889 if( $this->section
== 'new' ) {
890 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
891 $this->mArticle
->getComment() == $this->summary
) {
892 // Probably a duplicate submission of a new comment.
893 // This can happen when squid resends a request after
894 // a timeout but the first one actually went through.
895 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
897 // New comment; suppress conflict.
898 $this->isConflict
= false;
899 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
903 $userid = $wgUser->getId();
905 if ( $this->isConflict
) {
906 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
907 $this->mArticle
->getTimestamp() . "')\n" );
908 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
911 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
912 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
914 if( is_null( $text ) ) {
915 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
916 $this->isConflict
= true;
917 $text = $this->textbox1
;
920 # Suppress edit conflict with self, except for section edits where merging is required.
921 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
922 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
923 $this->isConflict
= false;
925 # switch from section editing to normal editing in edit conflict
926 if($this->isConflict
) {
928 if( $this->mergeChangesInto( $text ) ){
929 // Successful merge! Maybe we should tell the user the good news?
930 $this->isConflict
= false;
931 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
934 $this->textbox1
= $text;
935 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
940 if ( $this->isConflict
) {
941 wfProfileOut( $fname );
942 return self
::AS_CONFLICT_DETECTED
;
945 $oldtext = $this->mArticle
->getContent();
947 // Run post-section-merge edit filter
948 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError
, $this->summary
) ) ) {
949 # Error messages etc. could be handled within the hook...
950 wfProfileOut( $fname );
951 return self
::AS_HOOK_ERROR
;
954 # Handle the user preference to force summaries here, but not for null edits
955 if( $this->section
!= 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary') &&
956 0 != strcmp($oldtext, $text) &&
957 !is_object( Title
::newFromRedirect( $text ) ) # check if it's not a redirect
960 if( md5( $this->summary
) == $this->autoSumm
) {
961 $this->missingSummary
= true;
962 wfProfileOut( $fname );
963 return self
::AS_SUMMARY_NEEDED
;
967 # And a similar thing for new sections
968 if( $this->section
== 'new' && !$this->allowBlankSummary
&& $wgUser->getOption( 'forceeditsummary' ) ) {
969 if (trim($this->summary
) == '') {
970 $this->missingSummary
= true;
971 wfProfileOut( $fname );
972 return self
::AS_SUMMARY_NEEDED
;
977 wfProfileIn( "$fname-sectionanchor" );
979 if( $this->section
== 'new' ) {
980 if ( $this->textbox1
== '' ) {
981 $this->missingComment
= true;
982 return self
::AS_TEXTBOX_EMPTY
;
984 if( $this->summary
!= '' ) {
985 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary
);
986 # This is a new section, so create a link to the new section
987 # in the revision summary.
988 $cleanSummary = $wgParser->stripSectionName( $this->summary
);
989 $this->summary
= wfMsgForContent( 'newsectionsummary', $cleanSummary );
991 } elseif( $this->section
!= '' ) {
992 # Try to get a section anchor from the section source, redirect to edited section if header found
993 # XXX: might be better to integrate this into Article::replaceSection
994 # for duplicate heading checking and maybe parsing
995 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
996 # we can't deal with anchors, includes, html etc in the header for now,
997 # headline would need to be parsed to improve this
998 if($hasmatch and strlen($matches[2]) > 0) {
999 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
1002 wfProfileOut( "$fname-sectionanchor" );
1004 // Save errors may fall down to the edit form, but we've now
1005 // merged the section into full text. Clear the section field
1006 // so that later submission of conflict forms won't try to
1007 // replace that into a duplicated mess.
1008 $this->textbox1
= $text;
1009 $this->section
= '';
1011 // Check for length errors again now that the section is merged in
1012 $this->kblength
= (int)(strlen( $text ) / 1024);
1013 if ( $this->kblength
> $wgMaxArticleSize ) {
1014 $this->tooBig
= true;
1015 wfProfileOut( $fname );
1016 return self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
;
1019 # update the article here
1020 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
1021 $this->watchthis
, $bot, $sectionanchor ) ) {
1022 wfProfileOut( $fname );
1023 return self
::AS_SUCCESS_UPDATE
;
1025 $this->isConflict
= true;
1027 wfProfileOut( $fname );
1028 return self
::AS_END
;
1032 * Check given input text against $wgSpamRegex, and return the text of the first match.
1033 * @return mixed -- matching string or false
1035 public static function matchSpamRegex( $text ) {
1036 global $wgSpamRegex;
1037 if( $wgSpamRegex ) {
1038 // For back compatibility, $wgSpamRegex may be a single string or an array of regexes.
1039 $regexes = (array)$wgSpamRegex;
1040 foreach( $regexes as $regex ) {
1042 if ( preg_match( $regex, $text, $matches ) ) {
1051 * Initialise form fields in the object
1052 * Called on the first invocation, e.g. when a user clicks an edit link
1054 function initialiseForm() {
1055 $this->edittime
= $this->mArticle
->getTimestamp();
1056 $this->textbox1
= $this->getContent(false);
1057 if ($this->textbox1
=== false) return false;
1059 if ( !$this->mArticle
->exists() && $this->mTitle
->getNamespace() == NS_MEDIAWIKI
)
1060 $this->textbox1
= wfMsgWeirdKey( $this->mTitle
->getText() );
1065 function setHeaders() {
1066 global $wgOut, $wgTitle;
1067 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1068 if ( $this->formtype
== 'preview' ) {
1069 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1071 if ( $this->isConflict
) {
1072 $wgOut->setPageTitle( wfMsg( 'editconflict', $wgTitle->getPrefixedText() ) );
1074 if( $this->section
!= '' ) {
1075 $msg = $this->section
== 'new' ?
'editingcomment' : 'editingsection';
1076 $wgOut->setPageTitle( wfMsg( $msg, $wgTitle->getPrefixedText() ) );
1078 # Use the title defined by DISPLAYTITLE magic word when present
1079 if( isset($this->mParserOutput
)
1080 && ( $dt = $this->mParserOutput
->getDisplayTitle() ) !== false ) {
1083 $title = $wgTitle->getPrefixedText();
1085 $wgOut->setPageTitle( wfMsg( 'editing', $title ) );
1090 * Send the edit form and related headers to $wgOut
1091 * @param $formCallback Optional callable that takes an OutputPage
1092 * parameter; will be called during form output
1093 * near the top, for captchas and the like.
1095 function showEditForm( $formCallback=null ) {
1096 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle;
1098 # If $wgTitle is null, that means we're in API mode.
1099 # Some hook probably called this function without checking
1100 # for is_null($wgTitle) first. Bail out right here so we don't
1101 # do lots of work just to discard it right after.
1102 if(is_null($wgTitle))
1105 $fname = 'EditPage::showEditForm';
1106 wfProfileIn( $fname );
1108 $sk = $wgUser->getSkin();
1110 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
1112 #need to parse the preview early so that we know which templates are used,
1113 #otherwise users with "show preview after edit box" will get a blank list
1114 #we parse this near the beginning so that setHeaders can do the title
1115 #setting work instead of leaving it in getPreviewText
1116 $previewOutput = '';
1117 if ( $this->formtype
== 'preview' ) {
1118 $previewOutput = $this->getPreviewText();
1121 $this->setHeaders();
1123 # Enabled article-related sidebar, toplinks, etc.
1124 $wgOut->setArticleRelated( true );
1126 if ( $this->isConflict
) {
1127 $wgOut->addWikiMsg( 'explainconflict' );
1129 $this->textbox2
= $this->textbox1
;
1130 $this->textbox1
= $this->getContent();
1131 $this->edittime
= $this->mArticle
->getTimestamp();
1133 if( $this->section
!= '' && $this->section
!= 'new' ) {
1135 if( !$this->summary
&& !$this->preview
&& !$this->diff
) {
1136 preg_match( "/^(=+)(.+)\\1/mi",
1139 if( !empty( $matches[2] ) ) {
1141 $this->summary
= "/* " .
1142 $wgParser->stripSectionName(trim($matches[2])) .
1148 if ( $this->missingComment
) {
1149 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1152 if( $this->missingSummary
&& $this->section
!= 'new' ) {
1153 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1156 if( $this->missingSummary
&& $this->section
== 'new' ) {
1157 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1160 if( $this->hookError
!== '' ) {
1161 $wgOut->addWikiText( $this->hookError
);
1164 if ( !$this->checkUnicodeCompliantBrowser() ) {
1165 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1167 if ( isset( $this->mArticle
) && isset( $this->mArticle
->mRevision
) ) {
1168 // Let sysop know that this will make private content public if saved
1170 if( !$this->mArticle
->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
1171 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
1172 } else if( $this->mArticle
->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
1173 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
1176 if( !$this->mArticle
->mRevision
->isCurrent() ) {
1177 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
1178 $wgOut->addWikiMsg( 'editingold' );
1183 if( wfReadOnly() ) {
1184 $wgOut->wrapWikiMsg( "<div id=\"mw-read-only-warning\">\n$1\n</div>", array( 'readonlywarning', wfReadOnlyReason() ) );
1185 } elseif( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
1186 $wgOut->wrapWikiMsg( '<div id="mw-anon-edit-warning">$1</div>', 'anoneditwarning' );
1188 if( $this->isCssJsSubpage
&& $this->formtype
!= 'preview' ) {
1189 # Check the skin exists
1190 if( $this->isValidCssJsSubpage
) {
1191 $wgOut->addWikiMsg( 'usercssjsyoucanpreview' );
1193 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1198 if( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1199 # Show a warning if editing an interface message
1200 $wgOut->addWikiMsg( 'editinginterface' );
1201 } elseif( $this->mTitle
->isProtected( 'edit' ) ) {
1202 # Is the title semi-protected?
1203 if( $this->mTitle
->isSemiProtected() ) {
1204 $noticeMsg = 'semiprotectedpagewarning';
1206 # Then it must be protected based on static groups (regular)
1207 $noticeMsg = 'protectedpagewarning';
1209 $wgOut->addHTML( "<div id='mw-edit-$noticeMsg'>\n" );
1210 $wgOut->addWikiMsg( $noticeMsg );
1211 $wgOut->addHTML( "</div>\n" );
1213 if ( $this->mTitle
->isCascadeProtected() ) {
1214 # Is this page under cascading protection from some source pages?
1215 list($cascadeSources, /* $restrictions */) = $this->mTitle
->getCascadeProtectionSources();
1217 if ( count($cascadeSources) > 0 ) {
1218 # Explain, and list the titles responsible
1219 foreach( $cascadeSources as $page ) {
1220 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1223 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', count($cascadeSources) ) );
1225 if( !$this->mTitle
->exists() && $this->mTitle
->getRestrictions( 'create' ) != array() ){
1226 $wgOut->addWikiMsg( 'titleprotectedwarning' );
1229 if ( $this->kblength
=== false ) {
1230 $this->kblength
= (int)(strlen( $this->textbox1
) / 1024);
1232 if ( $this->tooBig ||
$this->kblength
> $wgMaxArticleSize ) {
1233 $wgOut->addHTML( "<div id='mw-edit-longpageerror'>\n" );
1234 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength
), $wgLang->formatNum( $wgMaxArticleSize ) );
1235 $wgOut->addHTML( "</div>\n" );
1236 } elseif( $this->kblength
> 29 ) {
1237 $wgOut->addHTML( "<div id='mw-edit-longpagewarning'>\n" );
1238 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength
) );
1239 $wgOut->addHTML( "</div>\n" );
1242 $q = 'action='.$this->action
;
1243 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1244 $action = $wgTitle->escapeLocalURL( $q );
1246 $colonSep = wfMsg( 'colon-separator' );
1247 $summary = wfMsg( 'summary' ) . $colonSep;
1248 $subject = wfMsg( 'subject' ) . $colonSep;
1250 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedText(),
1251 wfMsgExt('cancel', array('parseinline')) );
1252 $edithelpurl = Skin
::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1253 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1254 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1255 htmlspecialchars( wfMsg( 'newwindow' ) );
1257 global $wgRightsText;
1258 if ( $wgRightsText ) {
1259 $copywarnMsg = array( 'copyrightwarning',
1260 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1263 $copywarnMsg = array( 'copyrightwarning2',
1264 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1267 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
1268 # prepare toolbar for edit buttons
1269 $toolbar = EditPage
::getEditToolbar();
1274 // activate checkboxes if user wants them to be always active
1275 if( !$this->preview
&& !$this->diff
) {
1276 # Sort out the "watch" checkbox
1277 if( $wgUser->getOption( 'watchdefault' ) ) {
1279 $this->watchthis
= true;
1280 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle
->exists() ) {
1282 $this->watchthis
= true;
1283 } elseif( $this->mTitle
->userIsWatching() ) {
1285 $this->watchthis
= true;
1288 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
1291 $wgOut->addHTML( $this->editFormPageTop
);
1293 if ( $wgUser->getOption( 'previewontop' ) ) {
1294 $this->displayPreviewArea( $previewOutput );
1295 // Spacer for the edit toolbar
1296 $wgOut->addHTML( '<p><br /></p>' );
1300 $wgOut->addHTML( $this->editFormTextTop
);
1302 # if this is a comment, show a subject line at the top, which is also the edit summary.
1303 # Otherwise, show a summary field at the bottom
1304 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
1306 # If a blank edit summary was previously provided, and the appropriate
1307 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1308 # user being bounced back more than once in the event that a summary
1311 # For a bit more sophisticated detection of blank summaries, hash the
1312 # automatic one and pass that in the hidden field wpAutoSummary.
1313 $summaryhiddens = '';
1314 if( $this->missingSummary
) $summaryhiddens .= Xml
::hidden( 'wpIgnoreBlankSummary', true );
1315 $autosumm = $this->autoSumm ?
$this->autoSumm
: md5( $this->summary
);
1316 $summaryhiddens .= Xml
::hidden( 'wpAutoSummary', $autosumm );
1317 if( $this->section
== 'new' ) {
1318 $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 />";
1319 $editsummary = "<div class='editOptions'>\n";
1321 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary
) );
1322 $subjectpreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('subject-preview').$colonSep.$sk->commentBlock( $formattedSummary, $this->mTitle
, true )."</div>\n" : '';
1323 $summarypreview = '';
1325 $commentsubject = '';
1326 $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 />";
1327 $summarypreview = $summarytext && $this->preview ?
"<div class=\"mw-summary-preview\">".wfMsg('summary-preview').$colonSep.$sk->commentBlock( $this->summary
, $this->mTitle
)."</div>\n" : '';
1328 $subjectpreview = '';
1331 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1332 if( !$this->preview
&& !$this->diff
) {
1333 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1335 $templates = $this->getTemplates();
1336 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview
, $this->section
!= '');
1338 $hiddencats = $this->mArticle
->getHiddenCategories();
1339 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1341 global $wgUseMetadataEdit ;
1342 if ( $wgUseMetadataEdit ) {
1343 $metadata = $this->mMetaData
;
1344 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1345 $top = wfMsgWikiHtml( 'metadata_help' );
1346 /* ToDo: Replace with clean code */
1347 $ew = $wgUser->getOption( 'editwidth' );
1348 if ( $ew ) $ew = " style=\"width:100%\"";
1351 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1353 else $metadata = "" ;
1356 if ($this->wasDeletedSinceLastEdit()) {
1357 if ( 'save' != $this->formtype
) {
1358 $wgOut->addWikiMsg('deletedwhileediting');
1360 // Hide the toolbar and edit area, use can click preview to get it back
1361 // Add an confirmation checkbox and explanation.
1363 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
1365 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1366 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1372 $checkboxes = self
::getCheckboxes( $tabindex, $sk,
1373 array( 'minor' => $this->minoredit
, 'watch' => $this->watchthis
) );
1375 $checkboxhtml = implode( $checkboxes, "\n" );
1377 $buttons = $this->getEditButtons( $tabindex );
1378 $buttonshtml = implode( $buttons, "\n" );
1380 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1381 ?
'' : Xml
::hidden( 'safemode', '1' );
1383 $wgOut->addHTML( <<<END
1385 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1389 if( is_callable( $formCallback ) ) {
1390 call_user_func_array( $formCallback, array( &$wgOut ) );
1393 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1395 // Put these up at the top to ensure they aren't lost on early form submission
1396 $this->showFormBeforeText();
1398 $wgOut->addHTML( <<<END
1402 {$this->editFormTextBeforeContent}
1405 $this->showTextbox1();
1407 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1408 $wgOut->addHTML( <<<END
1409 {$this->editFormTextAfterWarn}
1419 "<div class='editButtons'>
1421 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1422 </div><!-- editButtons -->
1423 </div><!-- editOptions -->");
1426 * To make it harder for someone to slip a user a page
1427 * which submits an edit form to the wiki without their
1428 * knowledge, a random token is associated with the login
1429 * session. If it's not passed back with the submission,
1430 * we won't save the page, or render user JavaScript and
1433 * For anon editors, who may not have a session, we just
1434 * include the constant suffix to prevent editing from
1435 * broken text-mangling proxies.
1437 $token = htmlspecialchars( $wgUser->editToken() );
1438 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1440 $this->showEditTools();
1442 $wgOut->addHTML( <<<END
1443 {$this->editFormTextAfterTools}
1444 <div class='templatesUsed'>
1445 {$formattedtemplates}
1447 <div class='hiddencats'>
1448 {$formattedhiddencats}
1453 if ( $this->isConflict
&& wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1454 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1456 $de = new DifferenceEngine( $this->mTitle
);
1457 $de->setText( $this->textbox2
, $this->textbox1
);
1458 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1460 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1461 $this->showTextbox2();
1463 $wgOut->addHTML( $this->editFormTextBottom
);
1464 $wgOut->addHTML( "</form>\n" );
1465 if ( !$wgUser->getOption( 'previewontop' ) ) {
1466 $this->displayPreviewArea( $previewOutput );
1469 wfProfileOut( $fname );
1472 protected function showFormBeforeText() {
1474 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
1475 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1476 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1477 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n";
1480 protected function showTextbox1() {
1481 $attribs = array( 'tabindex' => 1 );
1483 if( $this->wasDeletedSinceLastEdit() )
1484 $attribs['type'] = 'hidden';
1486 $this->showTextbox( $this->textbox1
, 'wpTextbox1', $attribs );
1489 protected function showTextbox2() {
1490 $this->showTextbox( $encodedtext, 'wpTextbox2', array( 'tabindex' => 6 ) );
1493 protected function showTextbox( $content, $name, $attribs = array() ) {
1494 global $wgOut, $wgUser;
1496 $encodedtext = htmlspecialchars( $this->safeUnicodeOutput( $content ) );
1497 if( $encodedtext !== '' ) {
1498 // Ensure there's a newline at the end, otherwise adding lines
1500 // But don't add a newline if the ext is empty, or Firefox in XHTML
1501 // mode will show an extra newline. A bit annoying.
1502 $encodedtext .= "\n";
1510 if( $wgUser->getOption( 'editwidth' ) )
1511 $attribs['style'] = 'width: 100%';
1513 $wgOut->addHTML( Xml
::textarea(
1516 $wgUser->getIntOption( 'cols' ), $wgUser->getIntOption( 'rows' ),
1520 protected function displayPreviewArea( $previewOutput ) {
1522 if ( $this->formtype
== 'preview') {
1523 $this->showPreview( $previewOutput );
1525 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1528 if ( $this->formtype
== 'diff') {
1533 protected function displayPreviewArea( $previewOutput ) {
1535 if ( $this->formtype
== 'preview') {
1536 $this->showPreview( $previewOutput );
1538 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1541 if ( $this->formtype
== 'diff') {
1547 * Append preview output to $wgOut.
1548 * Includes category rendering if this is a category page.
1550 * @param string $text The HTML to be output for the preview.
1552 protected function showPreview( $text ) {
1555 $wgOut->addHTML( '<div id="wikiPreview">' );
1556 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1557 $this->mArticle
->openShowCategory();
1559 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1560 $wgOut->addHTML( $text );
1561 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
1562 $this->mArticle
->closeShowCategory();
1564 $wgOut->addHTML( '</div>' );
1568 * Live Preview lets us fetch rendered preview page content and
1569 * add it to the page without refreshing the whole page.
1570 * If not supported by the browser it will fall through to the normal form
1571 * submission method.
1573 * This function outputs a script tag to support live preview, and
1574 * returns an onclick handler which should be added to the attributes
1575 * of the preview button
1577 function doLivePreviewScript() {
1578 global $wgOut, $wgTitle;
1579 $wgOut->addScriptFile( 'preview.js' );
1580 $liveAction = $wgTitle->getLocalUrl( "action={$this->action}&wpPreview=true&live=true" );
1581 return "return !lpDoPreview(" .
1582 "editform.wpTextbox1.value," .
1583 '"' . $liveAction . '"' . ")";
1586 protected function showEditTools() {
1588 $wgOut->addHtml( '<div class="mw-editTools">' );
1589 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1590 $wgOut->addHtml( '</div>' );
1593 function getLastDelete() {
1594 $dbr = wfGetDB( DB_SLAVE
);
1595 $fname = 'EditPage::getLastDelete';
1596 $res = $dbr->select(
1597 array( 'logging', 'user' ),
1607 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1608 'log_title' => $this->mTitle
->getDBkey(),
1609 'log_type' => 'delete',
1610 'log_action' => 'delete',
1611 'user_id=log_user' ),
1613 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1615 if($dbr->numRows($res) == 1) {
1616 while ( $x = $dbr->fetchObject ( $res ) )
1618 $dbr->freeResult ( $res ) ;
1626 * Get the rendered text for previewing.
1629 function getPreviewText() {
1630 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang;
1632 wfProfileIn( __METHOD__
);
1634 if ( $this->mTriedSave
&& !$this->mTokenOk
) {
1635 if ( $this->mTokenOkExceptSuffix
) {
1636 $note = wfMsg( 'token_suffix_mismatch' );
1638 $note = wfMsg( 'session_fail_preview' );
1641 $note = wfMsg( 'previewnote' );
1644 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1645 $parserOptions->setEditSection( false );
1648 if( $wgRawHtml && !$this->mTokenOk
) {
1649 // Could be an offsite preview attempt. This is very unsafe if
1650 // HTML is enabled, as it could be an attack.
1651 return $wgOut->parse( "<div class='previewnote'>" .
1652 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1655 # don't parse user css/js, show message about preview
1656 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1658 if ( $this->isCssJsSubpage
) {
1659 if(preg_match("/\\.css$/", $this->mTitle
->getText() ) ) {
1660 $previewtext = wfMsg('usercsspreview');
1661 } else if(preg_match("/\\.js$/", $this->mTitle
->getText() ) ) {
1662 $previewtext = wfMsg('userjspreview');
1664 $parserOptions->setTidy(true);
1665 $parserOutput = $wgParser->parse( $previewtext , $this->mTitle
, $parserOptions );
1666 //$wgOut->addHTML( $parserOutput->mText );
1668 } elseif( $rt = Title
::newFromRedirect( $this->textbox1
) ) {
1669 $previewHTML = $this->mArticle
->viewRedirect( $rt, false );
1671 $toparse = $this->textbox1
;
1673 # If we're adding a comment, we need to show the
1674 # summary as the headline
1675 if($this->section
=="new" && $this->summary
!="") {
1676 $toparse="== {$this->summary} ==\n\n".$toparse;
1679 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1681 // Parse mediawiki messages with correct target language
1682 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
1683 $pos = strrpos( $this->mTitle
->getText(), '/' );
1684 if ( $pos !== false ) {
1685 $code = substr( $this->mTitle
->getText(), $pos+
1 );
1687 case $wgLang->getCode():
1688 $obj = $wgLang; break;
1689 case $wgContLang->getCode():
1690 $obj = $wgContLang; break;
1692 $obj = Language
::factory( $code );
1694 $parserOptions->setTargetLanguage( $obj );
1699 $parserOptions->setTidy(true);
1700 $parserOptions->enableLimitReport();
1701 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ),
1702 $this->mTitle
, $parserOptions );
1704 $previewHTML = $parserOutput->getText();
1705 $this->mParserOutput
= $parserOutput;
1706 $wgOut->addParserOutputNoText( $parserOutput );
1708 if ( count( $parserOutput->getWarnings() ) ) {
1709 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1713 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1714 "<div class='previewnote'>" . $wgOut->parse( $note ) . "</div>\n";
1715 if ( $this->isConflict
) {
1716 $previewhead .='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1719 wfProfileOut( __METHOD__
);
1720 return $previewhead . $previewHTML;
1723 function getTemplates() {
1724 if( $this->preview ||
$this->section
!= '' ) {
1725 $templates = array();
1726 if( !isset($this->mParserOutput
) ) return $templates;
1727 foreach( $this->mParserOutput
->getTemplates() as $ns => $template) {
1728 foreach( array_keys( $template ) as $dbk ) {
1729 $templates[] = Title
::makeTitle($ns, $dbk);
1734 return $this->mArticle
->getUsedTemplates();
1739 * Call the stock "user is blocked" page
1741 function blockedPage() {
1742 global $wgOut, $wgUser;
1743 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1745 # If the user made changes, preserve them when showing the markup
1746 # (This happens when a user is blocked during edit, for instance)
1747 $first = $this->firsttime ||
( !$this->save
&& $this->textbox1
== '' );
1749 $source = $this->mTitle
->exists() ?
$this->getContent() : false;
1751 $source = $this->textbox1
;
1754 # Spit out the source or the user's modified version
1755 if( $source !== false ) {
1756 $rows = $wgUser->getIntOption( 'rows' );
1757 $cols = $wgUser->getIntOption( 'cols' );
1758 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1759 $wgOut->addHtml( '<hr />' );
1760 $wgOut->addWikiMsg( $first ?
'blockedoriginalsource' : 'blockededitsource', $this->mTitle
->getPrefixedText() );
1761 # Why we don't use Xml::element here?
1762 # Is it because if $source is '', it returns <textarea />?
1763 $wgOut->addHtml( Xml
::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml
::closeElement( 'textarea' ) );
1768 * Produce the stock "please login to edit pages" page
1770 function userNotLoggedInPage() {
1771 global $wgUser, $wgOut, $wgTitle;
1772 $skin = $wgUser->getSkin();
1774 $loginTitle = SpecialPage
::getTitleFor( 'Userlogin' );
1775 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1777 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1778 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1779 $wgOut->setArticleRelated( false );
1781 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1782 $wgOut->returnToMain( false, $wgTitle );
1786 * Creates a basic error page which informs the user that
1787 * they have attempted to edit a nonexistant section.
1789 function noSuchSectionPage() {
1790 global $wgOut, $wgTitle;
1792 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1793 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1794 $wgOut->setArticleRelated( false );
1796 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section
);
1797 $wgOut->returnToMain( false, $wgTitle );
1801 * Produce the stock "your edit contains spam" page
1803 * @param $match Text which triggered one or more filters
1805 function spamPage( $match = false ) {
1806 global $wgOut, $wgTitle;
1808 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1809 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1810 $wgOut->setArticleRelated( false );
1812 $wgOut->addHtml( '<div id="spamprotected">' );
1813 $wgOut->addWikiMsg( 'spamprotectiontext' );
1815 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1816 $wgOut->addHtml( '</div>' );
1818 $wgOut->returnToMain( false, $wgTitle );
1825 function mergeChangesInto( &$editText ){
1826 $fname = 'EditPage::mergeChangesInto';
1827 wfProfileIn( $fname );
1829 $db = wfGetDB( DB_MASTER
);
1831 // This is the revision the editor started from
1832 $baseRevision = $this->getBaseRevision();
1833 if( is_null( $baseRevision ) ) {
1834 wfProfileOut( $fname );
1837 $baseText = $baseRevision->getText();
1839 // The current state, we want to merge updates into it
1840 $currentRevision = Revision
::loadFromTitle(
1841 $db, $this->mTitle
);
1842 if( is_null( $currentRevision ) ) {
1843 wfProfileOut( $fname );
1846 $currentText = $currentRevision->getText();
1849 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1850 $editText = $result;
1851 wfProfileOut( $fname );
1854 wfProfileOut( $fname );
1860 * Check if the browser is on a blacklist of user-agents known to
1861 * mangle UTF-8 data on form submission. Returns true if Unicode
1862 * should make it through, false if it's known to be a problem.
1866 function checkUnicodeCompliantBrowser() {
1867 global $wgBrowserBlackList;
1868 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1869 // No User-Agent header sent? Trust it by default...
1872 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1873 foreach ( $wgBrowserBlackList as $browser ) {
1874 if ( preg_match($browser, $currentbrowser) ) {
1882 * @deprecated use $wgParser->stripSectionName()
1884 function pseudoParseSectionAnchor( $text ) {
1886 return $wgParser->stripSectionName( $text );
1890 * Format an anchor fragment as it would appear for a given section name
1891 * @param string $text
1895 function sectionAnchor( $text ) {
1897 return $wgParser->guessSectionNameFromWikiText( $text );
1901 * Shows a bulletin board style toolbar for common editing functions.
1902 * It can be disabled in the user preferences.
1903 * The necessary JavaScript code can be found in skins/common/edit.js.
1907 static function getEditToolbar() {
1908 global $wgStylePath, $wgContLang, $wgLang, $wgJsMimeType;
1911 * toolarray an array of arrays which each include the filename of
1912 * the button image (without path), the opening tag, the closing tag,
1913 * and optionally a sample text that is inserted between the two when no
1914 * selection is highlighted.
1915 * The tip text is shown when the user moves the mouse over the button.
1917 * Already here are accesskeys (key), which are not used yet until someone
1918 * can figure out a way to make them work in IE. However, we should make
1919 * sure these keys are not defined on the edit page.
1923 'image' => $wgLang->getImageFile('button-bold'),
1924 'id' => 'mw-editbutton-bold',
1926 'close' => '\'\'\'',
1927 'sample' => wfMsg('bold_sample'),
1928 'tip' => wfMsg('bold_tip'),
1932 'image' => $wgLang->getImageFile('button-italic'),
1933 'id' => 'mw-editbutton-italic',
1936 'sample' => wfMsg('italic_sample'),
1937 'tip' => wfMsg('italic_tip'),
1941 'image' => $wgLang->getImageFile('button-link'),
1942 'id' => 'mw-editbutton-link',
1945 'sample' => wfMsg('link_sample'),
1946 'tip' => wfMsg('link_tip'),
1950 'image' => $wgLang->getImageFile('button-extlink'),
1951 'id' => 'mw-editbutton-extlink',
1954 'sample' => wfMsg('extlink_sample'),
1955 'tip' => wfMsg('extlink_tip'),
1959 'image' => $wgLang->getImageFile('button-headline'),
1960 'id' => 'mw-editbutton-headline',
1963 'sample' => wfMsg('headline_sample'),
1964 'tip' => wfMsg('headline_tip'),
1968 'image' => $wgLang->getImageFile('button-image'),
1969 'id' => 'mw-editbutton-image',
1970 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).':',
1972 'sample' => wfMsg('image_sample'),
1973 'tip' => wfMsg('image_tip'),
1977 'image' => $wgLang->getImageFile('button-media'),
1978 'id' => 'mw-editbutton-media',
1979 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1981 'sample' => wfMsg('media_sample'),
1982 'tip' => wfMsg('media_tip'),
1986 'image' => $wgLang->getImageFile('button-math'),
1987 'id' => 'mw-editbutton-math',
1989 'close' => "</math>",
1990 'sample' => wfMsg('math_sample'),
1991 'tip' => wfMsg('math_tip'),
1995 'image' => $wgLang->getImageFile('button-nowiki'),
1996 'id' => 'mw-editbutton-nowiki',
1997 'open' => "<nowiki>",
1998 'close' => "</nowiki>",
1999 'sample' => wfMsg('nowiki_sample'),
2000 'tip' => wfMsg('nowiki_tip'),
2004 'image' => $wgLang->getImageFile('button-sig'),
2005 'id' => 'mw-editbutton-signature',
2009 'tip' => wfMsg('sig_tip'),
2013 'image' => $wgLang->getImageFile('button-hr'),
2014 'id' => 'mw-editbutton-hr',
2015 'open' => "\n----\n",
2018 'tip' => wfMsg('hr_tip'),
2022 $toolbar = "<div id='toolbar'>\n";
2023 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
2025 foreach($toolarray as $tool) {
2027 $image = $wgStylePath.'/common/images/'.$tool['image'],
2028 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
2029 // Older browsers show a "speedtip" type message only for ALT.
2030 // Ideally these should be different, realistically they
2031 // probably don't need to be.
2032 $tip = $tool['tip'],
2033 $open = $tool['open'],
2034 $close = $tool['close'],
2035 $sample = $tool['sample'],
2036 $cssId = $tool['id'],
2039 $paramList = implode( ',',
2040 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
2041 $toolbar.="addButton($paramList);\n";
2044 $toolbar.="/*]]>*/\n</script>";
2045 $toolbar.="\n</div>";
2050 * Returns an array of html code of the following checkboxes:
2053 * @param $tabindex Current tabindex
2054 * @param $skin Skin object
2055 * @param $checked Array of checkbox => bool, where bool indicates the checked
2056 * status of the checkbox
2060 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
2063 $checkboxes = array();
2065 $checkboxes['minor'] = '';
2066 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
2067 if ( $wgUser->isAllowed('minoredit') ) {
2069 'tabindex' => ++
$tabindex,
2070 'accesskey' => wfMsg( 'accesskey-minoredit' ),
2071 'id' => 'wpMinoredit',
2073 $checkboxes['minor'] =
2074 Xml
::check( 'wpMinoredit', $checked['minor'], $attribs ) .
2075 " <label for='wpMinoredit'".$skin->tooltip('minoredit', 'withaccess').">{$minorLabel}</label>";
2078 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
2079 $checkboxes['watch'] = '';
2080 if ( $wgUser->isLoggedIn() ) {
2082 'tabindex' => ++
$tabindex,
2083 'accesskey' => wfMsg( 'accesskey-watch' ),
2084 'id' => 'wpWatchthis',
2086 $checkboxes['watch'] =
2087 Xml
::check( 'wpWatchthis', $checked['watch'], $attribs ) .
2088 " <label for='wpWatchthis'".$skin->tooltip('watch', 'withaccess').">{$watchLabel}</label>";
2094 * Returns an array of html code of the following buttons:
2095 * save, diff, preview and live
2097 * @param $tabindex Current tabindex
2101 public function getEditButtons(&$tabindex) {
2102 global $wgLivePreview, $wgUser;
2110 'tabindex' => ++
$tabindex,
2111 'value' => wfMsg('savearticle'),
2112 'accesskey' => wfMsg('accesskey-save'),
2113 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2115 $buttons['save'] = Xml
::element('input', $temp, '');
2117 ++
$tabindex; // use the same for preview and live preview
2118 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2120 'id' => 'wpPreview',
2121 'name' => 'wpPreview',
2123 'tabindex' => $tabindex,
2124 'value' => wfMsg('showpreview'),
2126 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2127 'style' => 'display: none;',
2129 $buttons['preview'] = Xml
::element('input', $temp, '');
2132 'id' => 'wpLivePreview',
2133 'name' => 'wpLivePreview',
2135 'tabindex' => $tabindex,
2136 'value' => wfMsg('showlivepreview'),
2137 'accesskey' => wfMsg('accesskey-preview'),
2139 'onclick' => $this->doLivePreviewScript(),
2141 $buttons['live'] = Xml
::element('input', $temp, '');
2144 'id' => 'wpPreview',
2145 'name' => 'wpPreview',
2147 'tabindex' => $tabindex,
2148 'value' => wfMsg('showpreview'),
2149 'accesskey' => wfMsg('accesskey-preview'),
2150 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2152 $buttons['preview'] = Xml
::element('input', $temp, '');
2153 $buttons['live'] = '';
2160 'tabindex' => ++
$tabindex,
2161 'value' => wfMsg('showdiff'),
2162 'accesskey' => wfMsg('accesskey-diff'),
2163 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2165 $buttons['diff'] = Xml
::element('input', $temp, '');
2167 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons ) );
2172 * Output preview text only. This can be sucked into the edit page
2173 * via JavaScript, and saves the server time rendering the skin as
2174 * well as theoretically being more robust on the client (doesn't
2175 * disturb the edit box's undo history, won't eat your text on
2178 * @todo This doesn't include category or interlanguage links.
2179 * Would need to enhance it a bit, <s>maybe wrap them in XML
2180 * or something...</s> that might also require more skin
2181 * initialization, so check whether that's a problem.
2183 function livePreview() {
2186 header( 'Content-type: text/xml; charset=utf-8' );
2187 header( 'Cache-control: no-cache' );
2189 $previewText = $this->getPreviewText();
2190 #$categories = $skin->getCategoryLinks();
2193 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2194 Xml
::tags( 'livepreview', null,
2195 Xml
::element( 'preview', null, $previewText )
2196 #. Xml::element( 'category', null, $categories )
2203 * Get a diff between the current contents of the edit box and the
2204 * version of the page we're editing from.
2206 * If this is a section edit, we'll replace the section as for final
2207 * save and then make a comparison.
2209 function showDiff() {
2210 $oldtext = $this->mArticle
->fetchContent();
2211 $newtext = $this->mArticle
->replaceSection(
2212 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
2213 $newtext = $this->mArticle
->preSaveTransform( $newtext );
2214 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2215 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2216 if ( $oldtext !== false ||
$newtext != '' ) {
2217 $de = new DifferenceEngine( $this->mTitle
);
2218 $de->setText( $oldtext, $newtext );
2219 $difftext = $de->getDiff( $oldtitle, $newtitle );
2220 $de->showDiffStyle();
2226 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
2230 * Filter an input field through a Unicode de-armoring process if it
2231 * came from an old browser with known broken Unicode editing issues.
2233 * @param WebRequest $request
2234 * @param string $field
2238 function safeUnicodeInput( $request, $field ) {
2239 $text = rtrim( $request->getText( $field ) );
2240 return $request->getBool( 'safemode' )
2241 ?
$this->unmakesafe( $text )
2246 * Filter an output field through a Unicode armoring process if it is
2247 * going to an old browser with known broken Unicode editing issues.
2249 * @param string $text
2253 function safeUnicodeOutput( $text ) {
2255 $codedText = $wgContLang->recodeForEdit( $text );
2256 return $this->checkUnicodeCompliantBrowser()
2258 : $this->makesafe( $codedText );
2262 * A number of web browsers are known to corrupt non-ASCII characters
2263 * in a UTF-8 text editing environment. To protect against this,
2264 * detected browsers will be served an armored version of the text,
2265 * with non-ASCII chars converted to numeric HTML character references.
2267 * Preexisting such character references will have a 0 added to them
2268 * to ensure that round-trips do not alter the original data.
2270 * @param string $invalue
2274 function makesafe( $invalue ) {
2275 // Armor existing references for reversability.
2276 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
2281 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2282 $bytevalue = ord( $invalue{$i} );
2283 if( $bytevalue <= 0x7F ) { //0xxx xxxx
2284 $result .= chr( $bytevalue );
2286 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
2287 $working = $working << 6;
2288 $working +
= ($bytevalue & 0x3F);
2290 if( $bytesleft <= 0 ) {
2291 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2293 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
2294 $working = $bytevalue & 0x1F;
2296 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
2297 $working = $bytevalue & 0x0F;
2299 } else { //1111 0xxx
2300 $working = $bytevalue & 0x07;
2308 * Reverse the previously applied transliteration of non-ASCII characters
2309 * back to UTF-8. Used to protect data from corruption by broken web browsers
2310 * as listed in $wgBrowserBlackList.
2312 * @param string $invalue
2316 function unmakesafe( $invalue ) {
2318 for( $i = 0; $i < strlen( $invalue ); $i++
) {
2319 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
2323 $hexstring .= $invalue{$i};
2325 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2327 // Do some sanity checks. These aren't needed for reversability,
2328 // but should help keep the breakage down if the editor
2329 // breaks one of the entities whilst editing.
2330 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2331 $codepoint = hexdec($hexstring);
2332 $result .= codepointToUtf8( $codepoint );
2334 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2337 $result .= substr( $invalue, $i, 1 );
2340 // reverse the transform that we made for reversability reasons.
2341 return strtr( $result, array( "�" => "&#x" ) );
2344 function noCreatePermission() {
2346 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2347 $wgOut->addWikiMsg( 'nocreatetext' );
2351 * If there are rows in the deletion log for this page, show them,
2352 * along with a nice little note for the user
2354 * @param OutputPage $out
2356 protected function showDeletionLog( $out ) {
2358 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
2359 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle
->getPrefixedText() );
2360 if( $pager->getNumRows() > 0 ) {
2361 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2362 $out->addWikiMsg( 'recreate-deleted-warn' );
2364 $loglist->beginLogEventsList() .
2366 $loglist->endLogEventsList()
2368 $out->addHtml( '</div>' );
2373 * Attempt submission
2374 * @return bool false if output is done, true if the rest of the form should be displayed
2376 function attemptSave() {
2377 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2379 $resultDetails = false;
2380 $value = $this->internalAttemptSave( $resultDetails, $wgUser->isAllowed('bot') && $wgRequest->getBool('bot', true) );
2382 if( $value == self
::AS_SUCCESS_UPDATE ||
$value == self
::AS_SUCCESS_NEW_ARTICLE
) {
2383 $this->didSave
= true;
2387 case self
::AS_HOOK_ERROR_EXPECTED
:
2388 case self
::AS_CONTENT_TOO_BIG
:
2389 case self
::AS_ARTICLE_WAS_DELETED
:
2390 case self
::AS_CONFLICT_DETECTED
:
2391 case self
::AS_SUMMARY_NEEDED
:
2392 case self
::AS_TEXTBOX_EMPTY
:
2393 case self
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
2397 case self
::AS_HOOK_ERROR
:
2398 case self
::AS_FILTERING
:
2399 case self
::AS_SUCCESS_NEW_ARTICLE
:
2400 case self
::AS_SUCCESS_UPDATE
:
2403 case self
::AS_SPAM_ERROR
:
2404 $this->spamPage ( $resultDetails['spam'] );
2407 case self
::AS_BLOCKED_PAGE_FOR_USER
:
2408 $this->blockedPage();
2411 case self
::AS_IMAGE_REDIRECT_ANON
:
2412 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2415 case self
::AS_READ_ONLY_PAGE_ANON
:
2416 $this->userNotLoggedInPage();
2419 case self
::AS_READ_ONLY_PAGE_LOGGED
:
2420 case self
::AS_READ_ONLY_PAGE
:
2421 $wgOut->readOnlyPage();
2424 case self
::AS_RATE_LIMITED
:
2425 $wgOut->rateLimited();
2428 case self
::AS_NO_CREATE_PERMISSION
;
2429 $this->noCreatePermission();
2432 case self
::AS_BLANK_ARTICLE
:
2433 $wgOut->redirect( $wgTitle->getFullURL() );
2436 case self
::AS_IMAGE_REDIRECT_LOGGED
:
2437 $wgOut->permissionRequired( 'upload' );
2442 function getBaseRevision() {
2443 if ($this->mBaseRevision
== false) {
2444 $db = wfGetDB( DB_MASTER
);
2445 $baseRevision = Revision
::loadFromTimestamp(
2446 $db, $this->mTitle
, $this->edittime
);
2447 return $this->mBaseRevision
= $baseRevision;
2449 return $this->mBaseRevision
;