Make a note about the reserved word problem.
[mediawiki.git] / includes / EditPage.php
blobba0482e945a4453ce62cc830ba0b37b9fb134a18
1 <?php
2 /**
3 * Contains the EditPage class
4 */
6 /**
7 * The edit page/HTML interface (split from Article)
8 * The actual database and text munging is still in Article,
9 * but it should get easier to call those from alternate
10 * interfaces.
12 * EditPage cares about two distinct titles:
13 * $wgTitle is the page that forms submit to, links point to,
14 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
15 * page in the database that is actually being edited. These are
16 * usually the same, but they are now allowed to be different.
18 class EditPage {
19 const AS_SUCCESS_UPDATE = 200;
20 const AS_SUCCESS_NEW_ARTICLE = 201;
21 const AS_HOOK_ERROR = 210;
22 const AS_FILTERING = 211;
23 const AS_HOOK_ERROR_EXPECTED = 212;
24 const AS_BLOCKED_PAGE_FOR_USER = 215;
25 const AS_CONTENT_TOO_BIG = 216;
26 const AS_USER_CANNOT_EDIT = 217;
27 const AS_READ_ONLY_PAGE_ANON = 218;
28 const AS_READ_ONLY_PAGE_LOGGED = 219;
29 const AS_READ_ONLY_PAGE = 220;
30 const AS_RATE_LIMITED = 221;
31 const AS_ARTICLE_WAS_DELETED = 222;
32 const AS_NO_CREATE_PERMISSION = 223;
33 const AS_BLANK_ARTICLE = 224;
34 const AS_CONFLICT_DETECTED = 225;
35 const AS_SUMMARY_NEEDED = 226;
36 const AS_TEXTBOX_EMPTY = 228;
37 const AS_MAX_ARTICLE_SIZE_EXCEDED = 229;
38 const AS_OK = 230;
39 const AS_END = 231;
40 const AS_SPAM_ERROR = 232;
42 var $mArticle;
43 var $mTitle;
44 var $mMetaData = '';
45 var $isConflict = false;
46 var $isCssJsSubpage = false;
47 var $deletedSinceEdit = false;
48 var $formtype;
49 var $firsttime;
50 var $lastDelete;
51 var $mTokenOk = false;
52 var $mTokenOkExceptSuffix = false;
53 var $mTriedSave = false;
54 var $tooBig = false;
55 var $kblength = false;
56 var $missingComment = false;
57 var $missingSummary = false;
58 var $allowBlankSummary = false;
59 var $autoSumm = '';
60 var $hookError = '';
61 var $mPreviewTemplates;
63 # Form values
64 var $save = false, $preview = false, $diff = false;
65 var $minoredit = false, $watchthis = false, $recreate = false;
66 var $textbox1 = '', $textbox2 = '', $summary = '';
67 var $edittime = '', $section = '', $starttime = '';
68 var $oldid = 0, $editintro = '', $scrolltop = null;
70 # Placeholders for text injection by hooks (must be HTML)
71 # extensions should take care to _append_ to the present value
72 public $editFormPageTop; // Before even the preview
73 public $editFormTextTop;
74 public $editFormTextBeforeContent;
75 public $editFormTextAfterWarn;
76 public $editFormTextAfterTools;
77 public $editFormTextBottom;
79 /* $didSave should be set to true whenever an article was succesfully altered. */
80 public $didSave = false;
82 public $suppressIntro = false;
84 /**
85 * @todo document
86 * @param $article
88 function EditPage( $article ) {
89 global $wgTitle;
90 $this->mArticle =& $article;
91 $this->mTitle = $article->getTitle();
93 # Placeholders for text injection by hooks (empty per default)
94 $this->editFormPageTop =
95 $this->editFormTextTop =
96 $this->editFormTextBeforeContent =
97 $this->editFormTextAfterWarn =
98 $this->editFormTextAfterTools =
99 $this->editFormTextBottom = "";
103 * Fetch initial editing page content.
105 private function getContent( $def_text = '' ) {
106 global $wgOut, $wgRequest, $wgParser;
108 # Get variables from query string :P
109 $section = $wgRequest->getVal( 'section' );
110 $preload = $wgRequest->getVal( 'preload' );
111 $undoafter = $wgRequest->getVal( 'undoafter' );
112 $undo = $wgRequest->getVal( 'undo' );
114 wfProfileIn( __METHOD__ );
116 $text = '';
117 if( !$this->mTitle->exists() ) {
118 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
119 # If this is a system message, get the default text.
120 $text = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
121 } else {
122 # If requested, preload some text.
123 $text = $this->getPreloadedText( $preload );
125 # We used to put MediaWiki:Newarticletext here if
126 # $text was empty at this point.
127 # This is now shown above the edit box instead.
128 } else {
129 // FIXME: may be better to use Revision class directly
130 // But don't mess with it just yet. Article knows how to
131 // fetch the page record from the high-priority server,
132 // which is needed to guarantee we don't pick up lagged
133 // information.
135 $text = $this->mArticle->getContent();
137 if ($undo > 0 && $undoafter > 0 && $undo < $undoafter) {
138 # If they got undoafter and undo round the wrong way, switch them
139 list( $undo, $undoafter ) = array( $undoafter, $undo );
142 if ( $undo > 0 && $undo > $undoafter ) {
143 # Undoing a specific edit overrides section editing; section-editing
144 # doesn't work with undoing.
145 if ( $undoafter ) {
146 $undorev = Revision::newFromId($undo);
147 $oldrev = Revision::newFromId($undoafter);
148 } else {
149 $undorev = Revision::newFromId($undo);
150 $oldrev = $undorev ? $undorev->getPrevious() : null;
153 #Sanity check, make sure it's the right page.
154 # Otherwise, $text will be left as-is.
155 if ( !is_null($undorev) && !is_null($oldrev) && $undorev->getPage()==$oldrev->getPage() && $undorev->getPage()==$this->mArticle->getID() ) {
156 $undorev_text = $undorev->getText();
157 $oldrev_text = $oldrev->getText();
158 $currev_text = $text;
160 #No use doing a merge if it's just a straight revert.
161 if ( $currev_text != $undorev_text ) {
162 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
163 } else {
164 $text = $oldrev_text;
165 $result = true;
167 } else {
168 // Failed basic sanity checks.
169 // Older revisions may have been removed since the link
170 // was created, or we may simply have got bogus input.
171 $result = false;
174 if( $result ) {
175 # Inform the user of our success and set an automatic edit summary
176 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
177 $firstrev = $oldrev->getNext();
178 # If we just undid one rev, use an autosummary
179 if ( $firstrev->mId == $undo ) {
180 $this->summary = wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
182 $this->formtype = 'diff';
183 } else {
184 # Warn the user that something went wrong
185 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
187 } else if( $section != '' ) {
188 if( $section == 'new' ) {
189 $text = $this->getPreloadedText( $preload );
190 } else {
191 $text = $wgParser->getSection( $text, $section, $def_text );
196 wfProfileOut( __METHOD__ );
197 return $text;
201 * Get the contents of a page from its title and remove includeonly tags
203 * @param $preload String: the title of the page.
204 * @return string The contents of the page.
206 private function getPreloadedText($preload) {
207 if ( $preload === '' )
208 return '';
209 else {
210 $preloadTitle = Title::newFromText( $preload );
211 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
212 $rev=Revision::newFromTitle($preloadTitle);
213 if ( is_object( $rev ) ) {
214 $text = $rev->getText();
215 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
216 // its own mini-parser! -ævar
217 $text = preg_replace( '~</?includeonly>~', '', $text );
218 return $text;
219 } else
220 return '';
226 * This is the function that extracts metadata from the article body on the first view.
227 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
228 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
230 function extractMetaDataFromArticle () {
231 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
232 $this->mMetaData = '' ;
233 if ( !$wgUseMetadataEdit ) return ;
234 if ( $wgMetadataWhitelist == '' ) return ;
235 $s = '' ;
236 $t = $this->getContent();
238 # MISSING : <nowiki> filtering
240 # Categories and language links
241 $t = explode ( "\n" , $t ) ;
242 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
243 $cat = $ll = array() ;
244 foreach ( $t AS $key => $x )
246 $y = trim ( strtolower ( $x ) ) ;
247 while ( substr ( $y , 0 , 2 ) == '[[' )
249 $y = explode ( ']]' , trim ( $x ) ) ;
250 $first = array_shift ( $y ) ;
251 $first = explode ( ':' , $first ) ;
252 $ns = array_shift ( $first ) ;
253 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
254 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
256 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
257 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
258 else $ll[] = $add ;
259 $x = implode ( ']]' , $y ) ;
260 $t[$key] = $x ;
261 $y = trim ( strtolower ( $x ) ) ;
265 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
266 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
267 $t = implode ( "\n" , $t ) ;
269 # Load whitelist
270 $sat = array () ; # stand-alone-templates; must be lowercase
271 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
272 $wl_article = new Article ( $wl_title ) ;
273 $wl = explode ( "\n" , $wl_article->getContent() ) ;
274 foreach ( $wl AS $x )
276 $isentry = false ;
277 $x = trim ( $x ) ;
278 while ( substr ( $x , 0 , 1 ) == '*' )
280 $isentry = true ;
281 $x = trim ( substr ( $x , 1 ) ) ;
283 if ( $isentry )
285 $sat[] = strtolower ( $x ) ;
290 # Templates, but only some
291 $t = explode ( '{{' , $t ) ;
292 $tl = array () ;
293 foreach ( $t AS $key => $x )
295 $y = explode ( '}}' , $x , 2 ) ;
296 if ( count ( $y ) == 2 )
298 $z = $y[0] ;
299 $z = explode ( '|' , $z ) ;
300 $tn = array_shift ( $z ) ;
301 if ( in_array ( strtolower ( $tn ) , $sat ) )
303 $tl[] = '{{' . $y[0] . '}}' ;
304 $t[$key] = $y[1] ;
305 $y = explode ( '}}' , $y[1] , 2 ) ;
307 else $t[$key] = '{{' . $x ;
309 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
310 else $t[$key] = $x ;
312 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
313 $t = implode ( '' , $t ) ;
315 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
316 $this->mArticle->mContent = $t ;
317 $this->mMetaData = $s ;
320 function submit() {
321 $this->edit();
325 * This is the function that gets called for "action=edit". It
326 * sets up various member variables, then passes execution to
327 * another function, usually showEditForm()
329 * The edit form is self-submitting, so that when things like
330 * preview and edit conflicts occur, we get the same form back
331 * with the extra stuff added. Only when the final submission
332 * is made and all is well do we actually save and redirect to
333 * the newly-edited page.
335 function edit() {
336 global $wgOut, $wgUser, $wgRequest, $wgTitle;
338 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
339 return;
341 $fname = 'EditPage::edit';
342 wfProfileIn( $fname );
343 wfDebug( "$fname: enter\n" );
345 // this is not an article
346 $wgOut->setArticleFlag(false);
348 $this->importFormData( $wgRequest );
349 $this->firsttime = false;
351 if( $this->live ) {
352 $this->livePreview();
353 wfProfileOut( $fname );
354 return;
357 $permErrors = $this->mTitle->getUserPermissionsErrors('edit', $wgUser);
358 if( !$this->mTitle->exists() )
359 $permErrors += array_diff( $this->mTitle->getUserPermissionsErrors('create', $wgUser), $permErrors );
361 # Ignore some permissions errors.
362 $remove = array();
363 foreach( $permErrors as $error ) {
364 if ($this->preview || $this->diff &&
365 ($error[0] == 'blockedtext' || $error[0] == 'autoblockedtext'))
367 // Don't worry about blocks when previewing/diffing
368 $remove[] = $error;
371 if ($error[0] == 'readonlytext')
373 if ($this->edit) {
374 $this->formtype = 'preview';
375 } elseif ($this->save || $this->preview || $this->diff) {
376 $remove[] = $error;
380 # array_diff returns elements in $permErrors that are not in $remove.
381 $permErrors = array_diff( $permErrors, $remove );
383 if ( !empty($permErrors) )
385 wfDebug( "$fname: User can't edit\n" );
386 $wgOut->readOnlyPage( $this->getContent(), true, $permErrors );
387 wfProfileOut( $fname );
388 return;
389 } else {
390 if ( $this->save ) {
391 $this->formtype = 'save';
392 } else if ( $this->preview ) {
393 $this->formtype = 'preview';
394 } else if ( $this->diff ) {
395 $this->formtype = 'diff';
396 } else { # First time through
397 $this->firsttime = true;
398 if( $this->previewOnOpen() ) {
399 $this->formtype = 'preview';
400 } else {
401 $this->extractMetaDataFromArticle () ;
402 $this->formtype = 'initial';
407 wfProfileIn( "$fname-business-end" );
409 $this->isConflict = false;
410 // css / js subpages of user pages get a special treatment
411 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
412 $this->isValidCssJsSubpage = $this->mTitle->isValidCssJsSubpage();
414 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
415 * no matter it's current state
417 $this->deletedSinceEdit = false;
418 if ( $this->edittime != '' ) {
419 /* Note that we rely on logging table, which hasn't been always there,
420 * but that doesn't matter, because this only applies to brand new
421 * deletes. This is done on every preview and save request. Move it further down
422 * to only perform it on saves
424 if ( $this->mTitle->isDeleted() ) {
425 $this->lastDelete = $this->getLastDelete();
426 if ( !is_null($this->lastDelete) ) {
427 $deletetime = $this->lastDelete->log_timestamp;
428 if ( ($deletetime - $this->starttime) > 0 ) {
429 $this->deletedSinceEdit = true;
435 # Show applicable editing introductions
436 if( $this->formtype == 'initial' || $this->firsttime )
437 $this->showIntro();
439 if( $this->mTitle->isTalkPage() ) {
440 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
443 # Attempt submission here. This will check for edit conflicts,
444 # and redundantly check for locked database, blocked IPs, etc.
445 # that edit() already checked just in case someone tries to sneak
446 # in the back door with a hand-edited submission URL.
448 if ( 'save' == $this->formtype ) {
449 if ( !$this->attemptSave() ) {
450 wfProfileOut( "$fname-business-end" );
451 wfProfileOut( $fname );
452 return;
456 # First time through: get contents, set time for conflict
457 # checking, etc.
458 if ( 'initial' == $this->formtype || $this->firsttime ) {
459 if ($this->initialiseForm() === false) {
460 $this->noSuchSectionPage();
461 wfProfileOut( "$fname-business-end" );
462 wfProfileOut( $fname );
463 return;
465 if( !$this->mTitle->getArticleId() )
466 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
469 $this->showEditForm();
470 wfProfileOut( "$fname-business-end" );
471 wfProfileOut( $fname );
475 * Should we show a preview when the edit form is first shown?
477 * @return bool
479 private function previewOnOpen() {
480 global $wgRequest, $wgUser;
481 if( $wgRequest->getVal( 'preview' ) == 'yes' ) {
482 // Explicit override from request
483 return true;
484 } elseif( $wgRequest->getVal( 'preview' ) == 'no' ) {
485 // Explicit override from request
486 return false;
487 } elseif( $this->section == 'new' ) {
488 // Nothing *to* preview for new sections
489 return false;
490 } elseif( ( $wgRequest->getVal( 'preload' ) !== '' || $this->mTitle->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
491 // Standard preference behaviour
492 return true;
493 } elseif( !$this->mTitle->exists() && $this->mTitle->getNamespace() == NS_CATEGORY ) {
494 // Categories are special
495 return true;
496 } else {
497 return false;
502 * @todo document
503 * @param $request
505 function importFormData( &$request ) {
506 global $wgLang, $wgUser;
507 $fname = 'EditPage::importFormData';
508 wfProfileIn( $fname );
510 if( $request->wasPosted() ) {
511 # These fields need to be checked for encoding.
512 # Also remove trailing whitespace, but don't remove _initial_
513 # whitespace from the text boxes. This may be significant formatting.
514 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
515 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
516 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
517 # Truncate for whole multibyte characters. +5 bytes for ellipsis
518 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
520 $this->edittime = $request->getVal( 'wpEdittime' );
521 $this->starttime = $request->getVal( 'wpStarttime' );
523 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
525 if( is_null( $this->edittime ) ) {
526 # If the form is incomplete, force to preview.
527 wfDebug( "$fname: Form data appears to be incomplete\n" );
528 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
529 $this->preview = true;
530 } else {
531 /* Fallback for live preview */
532 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
533 $this->diff = $request->getCheck( 'wpDiff' );
535 // Remember whether a save was requested, so we can indicate
536 // if we forced preview due to session failure.
537 $this->mTriedSave = !$this->preview;
539 if ( $this->tokenOk( $request ) ) {
540 # Some browsers will not report any submit button
541 # if the user hits enter in the comment box.
542 # The unmarked state will be assumed to be a save,
543 # if the form seems otherwise complete.
544 wfDebug( "$fname: Passed token check.\n" );
545 } else if ( $this->diff ) {
546 # Failed token check, but only requested "Show Changes".
547 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
548 } else {
549 # Page might be a hack attempt posted from
550 # an external site. Preview instead of saving.
551 wfDebug( "$fname: Failed token check; forcing preview\n" );
552 $this->preview = true;
555 $this->save = ! ( $this->preview OR $this->diff );
556 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
557 $this->edittime = null;
560 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
561 $this->starttime = null;
564 $this->recreate = $request->getCheck( 'wpRecreate' );
566 $this->minoredit = $request->getCheck( 'wpMinoredit' );
567 $this->watchthis = $request->getCheck( 'wpWatchthis' );
569 # Don't force edit summaries when a user is editing their own user or talk page
570 if( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) && $this->mTitle->getText() == $wgUser->getName() ) {
571 $this->allowBlankSummary = true;
572 } else {
573 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
576 $this->autoSumm = $request->getText( 'wpAutoSummary' );
577 } else {
578 # Not a posted form? Start with nothing.
579 wfDebug( "$fname: Not a posted form.\n" );
580 $this->textbox1 = '';
581 $this->textbox2 = '';
582 $this->mMetaData = '';
583 $this->summary = '';
584 $this->edittime = '';
585 $this->starttime = wfTimestampNow();
586 $this->edit = false;
587 $this->preview = false;
588 $this->save = false;
589 $this->diff = false;
590 $this->minoredit = false;
591 $this->watchthis = false;
592 $this->recreate = false;
595 $this->oldid = $request->getInt( 'oldid' );
597 # Section edit can come from either the form or a link
598 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
600 $this->live = $request->getCheck( 'live' );
601 $this->editintro = $request->getText( 'editintro' );
603 wfProfileOut( $fname );
607 * Make sure the form isn't faking a user's credentials.
609 * @param $request WebRequest
610 * @return bool
611 * @private
613 function tokenOk( &$request ) {
614 global $wgUser;
615 $token = $request->getVal( 'wpEditToken' );
616 $this->mTokenOk = $wgUser->matchEditToken( $token );
617 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
618 return $this->mTokenOk;
622 * Show all applicable editing introductions
624 private function showIntro() {
625 global $wgOut, $wgUser;
626 if( $this->suppressIntro )
627 return;
629 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
630 if( $this->mTitle->getNamespace() == NS_USER || $this->mTitle->getNamespace() == NS_USER_TALK ) {
631 $parts = explode( '/', $this->mTitle->getText(), 2 );
632 $username = $parts[0];
633 $id = User::idFromName( $username );
634 $ip = User::isIP( $username );
636 if ( $id == 0 && !$ip ) {
637 $wgOut->addWikiText( '<div class="mw-userpage-userdoesnotexist error">' . wfMsg( 'userpage-userdoesnotexist', $username ) . '</div>' );
641 if( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
642 if( $wgUser->isLoggedIn() ) {
643 $wgOut->addWikiText( '<div class="mw-newarticletext">' . wfMsg( 'newarticletext' ) . '</div>' );
644 } else {
645 $wgOut->addWikiText( '<div class="mw-newarticletextanon">' . wfMsg( 'newarticletextanon' ) . '</div>' );
647 $this->showDeletionLog( $wgOut );
652 * Attempt to show a custom editing introduction, if supplied
654 * @return bool
656 private function showCustomIntro() {
657 if( $this->editintro ) {
658 $title = Title::newFromText( $this->editintro );
659 if( $title instanceof Title && $title->exists() && $title->userCanRead() ) {
660 global $wgOut;
661 $revision = Revision::newFromTitle( $title );
662 $wgOut->addSecondaryWikiText( $revision->getText() );
663 return true;
664 } else {
665 return false;
667 } else {
668 return false;
673 * Attempt submission (no UI)
674 * @return one of the constants describing the result
676 function internalAttemptSave( &$result ) {
677 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut, $wgParser;
678 global $wgMaxArticleSize, $wgTitle;
680 $fname = 'EditPage::attemptSave';
681 wfProfileIn( $fname );
682 wfProfileIn( "$fname-checks" );
684 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
686 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
687 return self::AS_HOOK_ERROR;
690 # Reintegrate metadata
691 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
692 $this->mMetaData = '' ;
694 # Check for spam
695 $matches = array();
696 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
697 $result['spam'] = $matches[0];
698 wfProfileOut( "$fname-checks" );
699 wfProfileOut( $fname );
700 return self::AS_SPAM_ERROR;
702 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
703 # Error messages or other handling should be performed by the filter function
704 wfProfileOut( "$fname-checks" );
705 wfProfileOut( $fname );
706 return self::AS_FILTERING;
708 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError ) ) ) {
709 # Error messages etc. could be handled within the hook...
710 wfProfileOut( "$fname-checks" );
711 wfProfileOut( $fname );
712 return self::AS_HOOK_ERROR;
713 } elseif( $this->hookError != '' ) {
714 # ...or the hook could be expecting us to produce an error
715 wfProfileOut( "$fname-checks" );
716 wfProfileOut( $fname );
717 return self::AS_HOOK_ERROR_EXPECTED;
719 if ( $wgUser->isBlockedFrom( $wgTitle, false ) ) {
720 # Check block state against master, thus 'false'.
721 wfProfileOut( "$fname-checks" );
722 wfProfileOut( $fname );
723 return self::AS_BLOCKED_PAGE_FOR_USER;
725 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
726 if ( $this->kblength > $wgMaxArticleSize ) {
727 // Error will be displayed by showEditForm()
728 $this->tooBig = true;
729 wfProfileOut( "$fname-checks" );
730 wfProfileOut( $fname );
731 return self::AS_CONTENT_TOO_BIG;
734 if ( !$wgUser->isAllowed('edit') ) {
735 if ( $wgUser->isAnon() ) {
736 wfProfileOut( "$fname-checks" );
737 wfProfileOut( $fname );
738 return self::AS_READ_ONLY_PAGE_ANON;
740 else {
741 wfProfileOut( "$fname-checks" );
742 wfProfileOut( $fname );
743 return self::AS_READ_ONLY_PAGE_LOGGED;
747 if ( wfReadOnly() ) {
748 wfProfileOut( "$fname-checks" );
749 wfProfileOut( $fname );
750 return self::AS_READ_ONLY_PAGE;
752 if ( $wgUser->pingLimiter() ) {
753 wfProfileOut( "$fname-checks" );
754 wfProfileOut( $fname );
755 return self::AS_RATE_LIMITED;
758 # If the article has been deleted while editing, don't save it without
759 # confirmation
760 if ( $this->deletedSinceEdit && !$this->recreate ) {
761 wfProfileOut( "$fname-checks" );
762 wfProfileOut( $fname );
763 return self::AS_ARTICLE_WAS_DELETED;
766 wfProfileOut( "$fname-checks" );
768 # If article is new, insert it.
769 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
770 if ( 0 == $aid ) {
772 // Late check for create permission, just in case *PARANOIA*
773 if ( !$this->mTitle->userCan( 'create' ) ) {
774 wfDebug( "$fname: no create permission\n" );
775 wfProfileOut( $fname );
776 return self::AS_NO_CREATE_PERMISSION;
779 # Don't save a new article if it's blank.
780 if ( ( '' == $this->textbox1 ) ) {
781 wfProfileOut( $fname );
782 return self::AS_BLANK_ARTICLE;
785 // Run post-section-merge edit filter
786 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError ) ) ) {
787 # Error messages etc. could be handled within the hook...
788 wfProfileOut( $fname );
789 return false;
792 $isComment = ( $this->section == 'new' );
794 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
795 $this->minoredit, $this->watchthis, false, $isComment);
797 wfProfileOut( $fname );
798 return self::AS_SUCCESS_NEW_ARTICLE;
801 # Article exists. Check for edit conflict.
803 $this->mArticle->clear(); # Force reload of dates, etc.
804 $this->mArticle->forUpdate( true ); # Lock the article
806 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
808 if( $this->mArticle->getTimestamp() != $this->edittime ) {
809 $this->isConflict = true;
810 if( $this->section == 'new' ) {
811 if( $this->mArticle->getUserText() == $wgUser->getName() &&
812 $this->mArticle->getComment() == $this->summary ) {
813 // Probably a duplicate submission of a new comment.
814 // This can happen when squid resends a request after
815 // a timeout but the first one actually went through.
816 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
817 } else {
818 // New comment; suppress conflict.
819 $this->isConflict = false;
820 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
824 $userid = $wgUser->getID();
826 if ( $this->isConflict) {
827 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
828 $this->mArticle->getTimestamp() . "')\n" );
829 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
831 else {
832 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
833 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
835 if( is_null( $text ) ) {
836 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
837 $this->isConflict = true;
838 $text = $this->textbox1;
841 # Suppress edit conflict with self, except for section edits where merging is required.
842 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
843 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
844 $this->isConflict = false;
845 } else {
846 # switch from section editing to normal editing in edit conflict
847 if($this->isConflict) {
848 # Attempt merge
849 if( $this->mergeChangesInto( $text ) ){
850 // Successful merge! Maybe we should tell the user the good news?
851 $this->isConflict = false;
852 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
853 } else {
854 $this->section = '';
855 $this->textbox1 = $text;
856 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
861 if ( $this->isConflict ) {
862 wfProfileOut( $fname );
863 return self::AS_CONFLICT_DETECTED;
866 $oldtext = $this->mArticle->getContent();
868 // Run post-section-merge edit filter
869 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError ) ) ) {
870 # Error messages etc. could be handled within the hook...
871 wfProfileOut( $fname );
872 return false;
875 # Handle the user preference to force summaries here, but not for null edits
876 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary')
877 && 0 != strcmp($oldtext, $text) && !Article::getRedirectAutosummary( $text )) {
878 if( md5( $this->summary ) == $this->autoSumm ) {
879 $this->missingSummary = true;
880 wfProfileOut( $fname );
881 return self::AS_SUMMARY_NEEDED;
885 #And a similar thing for new sections
886 if( $this->section == 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
887 if (trim($this->summary) == '') {
888 $this->missingSummary = true;
889 wfProfileOut( $fname );
890 return self::AS_SUMMARY_NEEDED;
894 # All's well
895 wfProfileIn( "$fname-sectionanchor" );
896 $sectionanchor = '';
897 if( $this->section == 'new' ) {
898 if ( $this->textbox1 == '' ) {
899 $this->missingComment = true;
900 return self::AS_TEXTBOX_EMPTY;
902 if( $this->summary != '' ) {
903 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary );
904 # This is a new section, so create a link to the new section
905 # in the revision summary.
906 $cleanSummary = $wgParser->stripSectionName( $this->summary );
907 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
909 } elseif( $this->section != '' ) {
910 # Try to get a section anchor from the section source, redirect to edited section if header found
911 # XXX: might be better to integrate this into Article::replaceSection
912 # for duplicate heading checking and maybe parsing
913 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
914 # we can't deal with anchors, includes, html etc in the header for now,
915 # headline would need to be parsed to improve this
916 if($hasmatch and strlen($matches[2]) > 0) {
917 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
920 wfProfileOut( "$fname-sectionanchor" );
922 // Save errors may fall down to the edit form, but we've now
923 // merged the section into full text. Clear the section field
924 // so that later submission of conflict forms won't try to
925 // replace that into a duplicated mess.
926 $this->textbox1 = $text;
927 $this->section = '';
929 // Check for length errors again now that the section is merged in
930 $this->kblength = (int)(strlen( $text ) / 1024);
931 if ( $this->kblength > $wgMaxArticleSize ) {
932 $this->tooBig = true;
933 wfProfileOut( $fname );
934 return self::AS_MAX_ARTICLE_SIZE_EXCEDED;
937 # update the article here
938 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
939 $this->watchthis, '', $sectionanchor ) ) {
940 wfProfileOut( $fname );
941 return self::AS_SUCCESS_UPDATE;
942 } else {
943 $this->isConflict = true;
945 wfProfileOut( $fname );
946 return self::AS_END;
950 * Initialise form fields in the object
951 * Called on the first invocation, e.g. when a user clicks an edit link
953 function initialiseForm() {
954 $this->edittime = $this->mArticle->getTimestamp();
955 $this->summary = '';
956 $this->textbox1 = $this->getContent(false);
957 if ($this->textbox1 === false) return false;
959 if ( !$this->mArticle->exists() && $this->mTitle->getNamespace() == NS_MEDIAWIKI )
960 $this->textbox1 = wfMsgWeirdKey( $this->mTitle->getText() );
961 wfProxyCheck();
962 return true;
966 * Send the edit form and related headers to $wgOut
967 * @param $formCallback Optional callable that takes an OutputPage
968 * parameter; will be called during form output
969 * near the top, for captchas and the like.
971 function showEditForm( $formCallback=null ) {
972 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle;
974 $fname = 'EditPage::showEditForm';
975 wfProfileIn( $fname );
977 $sk = $wgUser->getSkin();
979 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
981 $wgOut->setRobotpolicy( 'noindex,nofollow' );
983 # Enabled article-related sidebar, toplinks, etc.
984 $wgOut->setArticleRelated( true );
986 if ( $this->formtype == 'preview' ) {
987 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
990 if ( $this->isConflict ) {
991 $s = wfMsg( 'editconflict', $wgTitle->getPrefixedText() );
992 $wgOut->setPageTitle( $s );
993 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
995 $this->textbox2 = $this->textbox1;
996 $this->textbox1 = $this->getContent();
997 $this->edittime = $this->mArticle->getTimestamp();
998 } else {
1000 if( $this->section != '' ) {
1001 if( $this->section == 'new' ) {
1002 $s = wfMsg('editingcomment', $wgTitle->getPrefixedText() );
1003 } else {
1004 $s = wfMsg('editingsection', $wgTitle->getPrefixedText() );
1005 $matches = array();
1006 if( !$this->summary && !$this->preview && !$this->diff ) {
1007 preg_match( "/^(=+)(.+)\\1/mi",
1008 $this->textbox1,
1009 $matches );
1010 if( !empty( $matches[2] ) ) {
1011 global $wgParser;
1012 $this->summary = "/* " .
1013 $wgParser->stripSectionName(trim($matches[2])) .
1014 " */ ";
1018 } else {
1019 $s = wfMsg( 'editing', $wgTitle->getPrefixedText() );
1021 $wgOut->setPageTitle( $s );
1023 if ( $this->missingComment ) {
1024 $wgOut->addWikiText( '<div id="mw-missingcommenttext">' . wfMsg( 'missingcommenttext' ) . '</div>' );
1027 if( $this->missingSummary && $this->section != 'new' ) {
1028 $wgOut->addWikiText( '<div id="mw-missingsummary">' . wfMsg( 'missingsummary' ) . '</div>' );
1031 if( $this->missingSummary && $this->section == 'new' ) {
1032 $wgOut->addWikiText( '<div id="mw-missingcommentheader">' . wfMsg( 'missingcommentheader' ) . '</div>' );
1035 if( !$this->hookError == '' ) {
1036 $wgOut->addWikiText( $this->hookError );
1039 if ( !$this->checkUnicodeCompliantBrowser() ) {
1040 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
1042 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
1043 // Let sysop know that this will make private content public if saved
1045 if( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1046 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
1047 } else if( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1048 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
1051 if( !$this->mArticle->mRevision->isCurrent() ) {
1052 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
1053 $wgOut->addWikiText( wfMsg( 'editingold' ) );
1058 if( wfReadOnly() ) {
1059 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
1060 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
1061 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
1062 } else {
1063 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
1064 # Check the skin exists
1065 if( $this->isValidCssJsSubpage ) {
1066 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
1067 } else {
1068 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() ) );
1073 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1074 # Show a warning if editing an interface message
1075 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
1076 } elseif( $this->mTitle->isProtected( 'edit' ) ) {
1077 # Is the title semi-protected?
1078 if( $this->mTitle->isSemiProtected() ) {
1079 $notice = wfMsg( 'semiprotectedpagewarning' );
1080 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' )
1081 $notice = '';
1082 } else {
1083 # Then it must be protected based on static groups (regular)
1084 $notice = wfMsg( 'protectedpagewarning' );
1086 $wgOut->addWikiText( $notice );
1088 if ( $this->mTitle->isCascadeProtected() ) {
1089 # Is this page under cascading protection from some source pages?
1090 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1091 if ( count($cascadeSources) > 0 ) {
1092 # Explain, and list the titles responsible
1093 $notice = wfMsgExt( 'cascadeprotectedwarning', array('parsemag'), count($cascadeSources) ) . "\n";
1094 foreach( $cascadeSources as $page ) {
1095 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1098 $wgOut->addWikiText( $notice );
1101 if ( $this->kblength === false ) {
1102 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
1104 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1105 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
1106 } elseif( $this->kblength > 29 ) {
1107 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
1110 #need to parse the preview early so that we know which templates are used,
1111 #otherwise users with "show preview after edit box" will get a blank list
1112 if ( $this->formtype == 'preview' ) {
1113 $previewOutput = $this->getPreviewText();
1116 $rows = $wgUser->getIntOption( 'rows' );
1117 $cols = $wgUser->getIntOption( 'cols' );
1119 $ew = $wgUser->getOption( 'editwidth' );
1120 if ( $ew ) $ew = " style=\"width:100%\"";
1121 else $ew = '';
1123 $q = 'action=submit';
1124 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1125 $action = $wgTitle->escapeLocalURL( $q );
1127 $summary = wfMsg('summary');
1128 $subject = wfMsg('subject');
1130 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedText(),
1131 wfMsgExt('cancel', array('parseinline')) );
1132 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1133 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1134 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1135 htmlspecialchars( wfMsg( 'newwindow' ) );
1137 global $wgRightsText;
1138 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1139 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
1140 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1141 $wgRightsText ) . "\n</div>";
1143 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1144 # prepare toolbar for edit buttons
1145 $toolbar = $this->getEditToolbar();
1146 } else {
1147 $toolbar = '';
1150 // activate checkboxes if user wants them to be always active
1151 if( !$this->preview && !$this->diff ) {
1152 # Sort out the "watch" checkbox
1153 if( $wgUser->getOption( 'watchdefault' ) ) {
1154 # Watch all edits
1155 $this->watchthis = true;
1156 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1157 # Watch creations
1158 $this->watchthis = true;
1159 } elseif( $this->mTitle->userIsWatching() ) {
1160 # Already watched
1161 $this->watchthis = true;
1164 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1167 $wgOut->addHTML( $this->editFormPageTop );
1169 if ( $wgUser->getOption( 'previewontop' ) ) {
1171 if ( 'preview' == $this->formtype ) {
1172 $this->showPreview( $previewOutput );
1173 } else {
1174 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1177 if ( 'diff' == $this->formtype ) {
1178 $this->showDiff();
1183 $wgOut->addHTML( $this->editFormTextTop );
1185 # if this is a comment, show a subject line at the top, which is also the edit summary.
1186 # Otherwise, show a summary field at the bottom
1187 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1188 if( $this->section == 'new' ) {
1189 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span>\n<div class='editOptions'>\n<input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
1190 $editsummary = '';
1191 $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1192 $summarypreview = '';
1193 } else {
1194 $commentsubject = '';
1195 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span>\n<div class='editOptions'>\n<input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
1196 $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1197 $subjectpreview = '';
1200 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1201 if( !$this->preview && !$this->diff ) {
1202 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1204 $templates = ($this->preview || $this->section != '') ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
1205 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1207 global $wgUseMetadataEdit ;
1208 if ( $wgUseMetadataEdit ) {
1209 $metadata = $this->mMetaData ;
1210 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1211 $top = wfMsgWikiHtml( 'metadata_help' );
1212 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1214 else $metadata = "" ;
1216 $hidden = '';
1217 $recreate = '';
1218 if ($this->deletedSinceEdit) {
1219 if ( 'save' != $this->formtype ) {
1220 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1221 } else {
1222 // Hide the toolbar and edit area, use can click preview to get it back
1223 // Add an confirmation checkbox and explanation.
1224 $toolbar = '';
1225 $hidden = 'type="hidden" style="display:none;"';
1226 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1227 $recreate .=
1228 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1229 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1233 $tabindex = 2;
1235 $checkboxes = self::getCheckboxes( $tabindex, $sk,
1236 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1238 $checkboxhtml = implode( $checkboxes, "\n" );
1240 $buttons = $this->getEditButtons( $tabindex );
1241 $buttonshtml = implode( $buttons, "\n" );
1243 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1244 ? '' : Xml::hidden( 'safemode', '1' );
1246 $wgOut->addHTML( <<<END
1247 {$toolbar}
1248 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1252 if( is_callable( $formCallback ) ) {
1253 call_user_func_array( $formCallback, array( &$wgOut ) );
1256 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1258 // Put these up at the top to ensure they aren't lost on early form submission
1259 $wgOut->addHTML( "
1260 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1261 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1262 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1263 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1265 $wgOut->addHTML( <<<END
1266 $recreate
1267 {$commentsubject}
1268 {$subjectpreview}
1269 {$this->editFormTextBeforeContent}
1270 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1271 cols='{$cols}'{$ew} $hidden>
1273 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1275 </textarea>
1276 " );
1278 $wgOut->addWikiText( $copywarn );
1279 $wgOut->addHTML( $this->editFormTextAfterWarn );
1280 $wgOut->addHTML( "
1281 {$metadata}
1282 {$editsummary}
1283 {$summarypreview}
1284 {$checkboxhtml}
1285 {$safemodehtml}
1288 $wgOut->addHTML(
1289 "<div class='editButtons'>
1290 {$buttonshtml}
1291 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1292 </div><!-- editButtons -->
1293 </div><!-- editOptions -->");
1295 $wgOut->addHtml( '<div class="mw-editTools">' );
1296 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1297 $wgOut->addHtml( '</div>' );
1299 $wgOut->addHTML( $this->editFormTextAfterTools );
1301 $wgOut->addHTML( "
1302 <div class='templatesUsed'>
1303 {$formattedtemplates}
1304 </div>
1305 " );
1308 * To make it harder for someone to slip a user a page
1309 * which submits an edit form to the wiki without their
1310 * knowledge, a random token is associated with the login
1311 * session. If it's not passed back with the submission,
1312 * we won't save the page, or render user JavaScript and
1313 * CSS previews.
1315 * For anon editors, who may not have a session, we just
1316 * include the constant suffix to prevent editing from
1317 * broken text-mangling proxies.
1319 $token = htmlspecialchars( $wgUser->editToken() );
1320 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1323 # If a blank edit summary was previously provided, and the appropriate
1324 # user preference is active, pass a hidden tag here. This will stop the
1325 # user being bounced back more than once in the event that a summary
1326 # is not required.
1327 if( $this->missingSummary ) {
1328 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1331 # For a bit more sophisticated detection of blank summaries, hash the
1332 # automatic one and pass that in a hidden field.
1333 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1334 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1336 if ( $this->isConflict ) {
1337 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1339 $de = new DifferenceEngine( $this->mTitle );
1340 $de->setText( $this->textbox2, $this->textbox1 );
1341 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1343 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1344 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1345 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1347 $wgOut->addHTML( $this->editFormTextBottom );
1348 $wgOut->addHTML( "</form>\n" );
1349 if ( !$wgUser->getOption( 'previewontop' ) ) {
1351 if ( $this->formtype == 'preview') {
1352 $this->showPreview( $previewOutput );
1353 } else {
1354 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1357 if ( $this->formtype == 'diff') {
1358 $this->showDiff();
1363 wfProfileOut( $fname );
1367 * Append preview output to $wgOut.
1368 * Includes category rendering if this is a category page.
1370 * @param string $text The HTML to be output for the preview.
1372 private function showPreview( $text ) {
1373 global $wgOut;
1375 $wgOut->addHTML( '<div id="wikiPreview">' );
1376 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1377 $this->mArticle->openShowCategory();
1379 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1380 $wgOut->addHTML( $text );
1381 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1382 $this->mArticle->closeShowCategory();
1384 $wgOut->addHTML( '</div>' );
1388 * Live Preview lets us fetch rendered preview page content and
1389 * add it to the page without refreshing the whole page.
1390 * If not supported by the browser it will fall through to the normal form
1391 * submission method.
1393 * This function outputs a script tag to support live preview, and
1394 * returns an onclick handler which should be added to the attributes
1395 * of the preview button
1397 function doLivePreviewScript() {
1398 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1399 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1400 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1401 '"></script>' . "\n" );
1402 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1403 return "return !lpDoPreview(" .
1404 "editform.wpTextbox1.value," .
1405 '"' . $liveAction . '"' . ")";
1408 function getLastDelete() {
1409 $dbr = wfGetDB( DB_SLAVE );
1410 $fname = 'EditPage::getLastDelete';
1411 $res = $dbr->select(
1412 array( 'logging', 'user' ),
1413 array( 'log_type',
1414 'log_action',
1415 'log_timestamp',
1416 'log_user',
1417 'log_namespace',
1418 'log_title',
1419 'log_comment',
1420 'log_params',
1421 'user_name', ),
1422 array( 'log_namespace' => $this->mTitle->getNamespace(),
1423 'log_title' => $this->mTitle->getDBkey(),
1424 'log_type' => 'delete',
1425 'log_action' => 'delete',
1426 'user_id=log_user' ),
1427 $fname,
1428 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1430 if($dbr->numRows($res) == 1) {
1431 while ( $x = $dbr->fetchObject ( $res ) )
1432 $data = $x;
1433 $dbr->freeResult ( $res ) ;
1434 } else {
1435 $data = null;
1437 return $data;
1441 * @todo document
1443 function getPreviewText() {
1444 global $wgOut, $wgUser, $wgTitle, $wgParser;
1446 $fname = 'EditPage::getPreviewText';
1447 wfProfileIn( $fname );
1449 if ( $this->mTriedSave && !$this->mTokenOk ) {
1450 if ( $this->mTokenOkExceptSuffix ) {
1451 $note = wfMsg( 'token_suffix_mismatch' );
1452 } else {
1453 $note = wfMsg( 'session_fail_preview' );
1455 } else {
1456 $note = wfMsg( 'previewnote' );
1459 $parserOptions = ParserOptions::newFromUser( $wgUser );
1460 $parserOptions->setEditSection( false );
1462 global $wgRawHtml;
1463 if( $wgRawHtml && !$this->mTokenOk ) {
1464 // Could be an offsite preview attempt. This is very unsafe if
1465 // HTML is enabled, as it could be an attack.
1466 return $wgOut->parse( "<div class='previewnote'>" .
1467 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1470 # don't parse user css/js, show message about preview
1471 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1473 if ( $this->isCssJsSubpage ) {
1474 if(preg_match("/\\.css$/", $this->mTitle->getText() ) ) {
1475 $previewtext = wfMsg('usercsspreview');
1476 } else if(preg_match("/\\.js$/", $this->mTitle->getText() ) ) {
1477 $previewtext = wfMsg('userjspreview');
1479 $parserOptions->setTidy(true);
1480 $parserOutput = $wgParser->parse( $previewtext , $this->mTitle, $parserOptions );
1481 $wgOut->addHTML( $parserOutput->mText );
1482 $previewHTML = '';
1483 } else {
1484 $toparse = $this->textbox1;
1486 # If we're adding a comment, we need to show the
1487 # summary as the headline
1488 if($this->section=="new" && $this->summary!="") {
1489 $toparse="== {$this->summary} ==\n\n".$toparse;
1492 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1493 $parserOptions->setTidy(true);
1494 $parserOptions->enableLimitReport();
1495 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1496 $this->mTitle, $parserOptions );
1498 $previewHTML = $parserOutput->getText();
1499 $wgOut->addParserOutputNoText( $parserOutput );
1501 # ParserOutput might have altered the page title, so reset it
1502 $wgOut->setPageTitle( wfMsg( 'editing', $wgTitle->getPrefixedText() ) );
1504 foreach ( $parserOutput->getTemplates() as $ns => $template)
1505 foreach ( array_keys( $template ) as $dbk)
1506 $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
1508 if ( count( $parserOutput->getWarnings() ) ) {
1509 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1513 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1514 "<div class='previewnote'>" . $wgOut->parse( $note ) . "</div>\n";
1515 if ( $this->isConflict ) {
1516 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1519 wfProfileOut( $fname );
1520 return $previewhead . $previewHTML;
1524 * Call the stock "user is blocked" page
1526 function blockedPage() {
1527 global $wgOut, $wgUser;
1528 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1530 # If the user made changes, preserve them when showing the markup
1531 # (This happens when a user is blocked during edit, for instance)
1532 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1533 if( $first ) {
1534 $source = $this->mTitle->exists() ? $this->getContent() : false;
1535 } else {
1536 $source = $this->textbox1;
1539 # Spit out the source or the user's modified version
1540 if( $source !== false ) {
1541 $rows = $wgUser->getOption( 'rows' );
1542 $cols = $wgUser->getOption( 'cols' );
1543 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1544 $wgOut->addHtml( '<hr />' );
1545 $wgOut->addWikiText( wfMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ) );
1546 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1551 * Produce the stock "please login to edit pages" page
1553 function userNotLoggedInPage() {
1554 global $wgUser, $wgOut, $wgTitle;
1555 $skin = $wgUser->getSkin();
1557 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1558 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1560 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1561 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1562 $wgOut->setArticleRelated( false );
1564 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1565 $wgOut->returnToMain( false, $wgTitle );
1569 * Creates a basic error page which informs the user that
1570 * they have attempted to edit a nonexistant section.
1572 function noSuchSectionPage() {
1573 global $wgOut, $wgTitle;
1575 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1576 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1577 $wgOut->setArticleRelated( false );
1579 $wgOut->addWikiText( wfMsg( 'nosuchsectiontext', $this->section ) );
1580 $wgOut->returnToMain( false, $wgTitle );
1584 * Produce the stock "your edit contains spam" page
1586 * @param $match Text which triggered one or more filters
1588 function spamPage( $match = false ) {
1589 global $wgOut, $wgTitle;
1591 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1592 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1593 $wgOut->setArticleRelated( false );
1595 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1596 if ( $match )
1597 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1599 $wgOut->returnToMain( false, $wgTitle );
1603 * @private
1604 * @todo document
1606 function mergeChangesInto( &$editText ){
1607 $fname = 'EditPage::mergeChangesInto';
1608 wfProfileIn( $fname );
1610 $db = wfGetDB( DB_MASTER );
1612 // This is the revision the editor started from
1613 $baseRevision = Revision::loadFromTimestamp(
1614 $db, $this->mTitle, $this->edittime );
1615 if( is_null( $baseRevision ) ) {
1616 wfProfileOut( $fname );
1617 return false;
1619 $baseText = $baseRevision->getText();
1621 // The current state, we want to merge updates into it
1622 $currentRevision = Revision::loadFromTitle(
1623 $db, $this->mTitle );
1624 if( is_null( $currentRevision ) ) {
1625 wfProfileOut( $fname );
1626 return false;
1628 $currentText = $currentRevision->getText();
1630 $result = '';
1631 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1632 $editText = $result;
1633 wfProfileOut( $fname );
1634 return true;
1635 } else {
1636 wfProfileOut( $fname );
1637 return false;
1642 * Check if the browser is on a blacklist of user-agents known to
1643 * mangle UTF-8 data on form submission. Returns true if Unicode
1644 * should make it through, false if it's known to be a problem.
1645 * @return bool
1646 * @private
1648 function checkUnicodeCompliantBrowser() {
1649 global $wgBrowserBlackList;
1650 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1651 // No User-Agent header sent? Trust it by default...
1652 return true;
1654 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1655 foreach ( $wgBrowserBlackList as $browser ) {
1656 if ( preg_match($browser, $currentbrowser) ) {
1657 return false;
1660 return true;
1664 * @deprecated use $wgParser->stripSectionName()
1666 function pseudoParseSectionAnchor( $text ) {
1667 global $wgParser;
1668 return $wgParser->stripSectionName( $text );
1672 * Format an anchor fragment as it would appear for a given section name
1673 * @param string $text
1674 * @return string
1675 * @private
1677 function sectionAnchor( $text ) {
1678 global $wgParser;
1679 return $wgParser->guessSectionNameFromWikiText( $text );
1683 * Shows a bulletin board style toolbar for common editing functions.
1684 * It can be disabled in the user preferences.
1685 * The necessary JavaScript code can be found in style/wikibits.js.
1687 function getEditToolbar() {
1688 global $wgStylePath, $wgContLang, $wgJsMimeType;
1691 * toolarray an array of arrays which each include the filename of
1692 * the button image (without path), the opening tag, the closing tag,
1693 * and optionally a sample text that is inserted between the two when no
1694 * selection is highlighted.
1695 * The tip text is shown when the user moves the mouse over the button.
1697 * Already here are accesskeys (key), which are not used yet until someone
1698 * can figure out a way to make them work in IE. However, we should make
1699 * sure these keys are not defined on the edit page.
1701 $toolarray = array(
1702 array( 'image' => 'button_bold.png',
1703 'id' => 'mw-editbutton-bold',
1704 'open' => '\\\'\\\'\\\'',
1705 'close' => '\\\'\\\'\\\'',
1706 'sample'=> wfMsg('bold_sample'),
1707 'tip' => wfMsg('bold_tip'),
1708 'key' => 'B'
1710 array( 'image' => 'button_italic.png',
1711 'id' => 'mw-editbutton-italic',
1712 'open' => '\\\'\\\'',
1713 'close' => '\\\'\\\'',
1714 'sample'=> wfMsg('italic_sample'),
1715 'tip' => wfMsg('italic_tip'),
1716 'key' => 'I'
1718 array( 'image' => 'button_link.png',
1719 'id' => 'mw-editbutton-link',
1720 'open' => '[[',
1721 'close' => ']]',
1722 'sample'=> wfMsg('link_sample'),
1723 'tip' => wfMsg('link_tip'),
1724 'key' => 'L'
1726 array( 'image' => 'button_extlink.png',
1727 'id' => 'mw-editbutton-extlink',
1728 'open' => '[',
1729 'close' => ']',
1730 'sample'=> wfMsg('extlink_sample'),
1731 'tip' => wfMsg('extlink_tip'),
1732 'key' => 'X'
1734 array( 'image' => 'button_headline.png',
1735 'id' => 'mw-editbutton-headline',
1736 'open' => "\\n== ",
1737 'close' => " ==\\n",
1738 'sample'=> wfMsg('headline_sample'),
1739 'tip' => wfMsg('headline_tip'),
1740 'key' => 'H'
1742 array( 'image' => 'button_image.png',
1743 'id' => 'mw-editbutton-image',
1744 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1745 'close' => ']]',
1746 'sample'=> wfMsg('image_sample'),
1747 'tip' => wfMsg('image_tip'),
1748 'key' => 'D'
1750 array( 'image' => 'button_media.png',
1751 'id' => 'mw-editbutton-media',
1752 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1753 'close' => ']]',
1754 'sample'=> wfMsg('media_sample'),
1755 'tip' => wfMsg('media_tip'),
1756 'key' => 'M'
1758 array( 'image' => 'button_math.png',
1759 'id' => 'mw-editbutton-math',
1760 'open' => "<math>",
1761 'close' => "<\\/math>",
1762 'sample'=> wfMsg('math_sample'),
1763 'tip' => wfMsg('math_tip'),
1764 'key' => 'C'
1766 array( 'image' => 'button_nowiki.png',
1767 'id' => 'mw-editbutton-nowiki',
1768 'open' => "<nowiki>",
1769 'close' => "<\\/nowiki>",
1770 'sample'=> wfMsg('nowiki_sample'),
1771 'tip' => wfMsg('nowiki_tip'),
1772 'key' => 'N'
1774 array( 'image' => 'button_sig.png',
1775 'id' => 'mw-editbutton-signature',
1776 'open' => '--~~~~',
1777 'close' => '',
1778 'sample'=> '',
1779 'tip' => wfMsg('sig_tip'),
1780 'key' => 'Y'
1782 array( 'image' => 'button_hr.png',
1783 'id' => 'mw-editbutton-hr',
1784 'open' => "\\n----\\n",
1785 'close' => '',
1786 'sample'=> '',
1787 'tip' => wfMsg('hr_tip'),
1788 'key' => 'R'
1791 $toolbar = "<div id='toolbar'>\n";
1792 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1794 foreach($toolarray as $tool) {
1796 $cssId = $tool['id'];
1797 $image=$wgStylePath.'/common/images/'.$tool['image'];
1798 $open=$tool['open'];
1799 $close=$tool['close'];
1800 $sample = wfEscapeJsString( $tool['sample'] );
1802 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1803 // Older browsers show a "speedtip" type message only for ALT.
1804 // Ideally these should be different, realistically they
1805 // probably don't need to be.
1806 $tip = wfEscapeJsString( $tool['tip'] );
1808 #$key = $tool["key"];
1810 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1813 $toolbar.="/*]]>*/\n</script>";
1814 $toolbar.="\n</div>";
1815 return $toolbar;
1819 * Returns an array of html code of the following checkboxes:
1820 * minor and watch
1822 * @param $tabindex Current tabindex
1823 * @param $skin Skin object
1824 * @param $checked Array of checkbox => bool, where bool indicates the checked
1825 * status of the checkbox
1827 * @return array
1829 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1830 global $wgUser;
1832 $checkboxes = array();
1834 $checkboxes['minor'] = '';
1835 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1836 if ( $wgUser->isAllowed('minoredit') ) {
1837 $attribs = array(
1838 'tabindex' => ++$tabindex,
1839 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1840 'id' => 'wpMinoredit',
1842 $checkboxes['minor'] =
1843 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1844 "&nbsp;<label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1847 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1848 $checkboxes['watch'] = '';
1849 if ( $wgUser->isLoggedIn() ) {
1850 $attribs = array(
1851 'tabindex' => ++$tabindex,
1852 'accesskey' => wfMsg( 'accesskey-watch' ),
1853 'id' => 'wpWatchthis',
1855 $checkboxes['watch'] =
1856 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1857 "&nbsp;<label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1859 return $checkboxes;
1863 * Returns an array of html code of the following buttons:
1864 * save, diff, preview and live
1866 * @param $tabindex Current tabindex
1868 * @return array
1870 public function getEditButtons(&$tabindex) {
1871 global $wgLivePreview, $wgUser;
1873 $buttons = array();
1875 $temp = array(
1876 'id' => 'wpSave',
1877 'name' => 'wpSave',
1878 'type' => 'submit',
1879 'tabindex' => ++$tabindex,
1880 'value' => wfMsg('savearticle'),
1881 'accesskey' => wfMsg('accesskey-save'),
1882 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1884 $buttons['save'] = wfElement('input', $temp, '');
1886 ++$tabindex; // use the same for preview and live preview
1887 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1888 $temp = array(
1889 'id' => 'wpPreview',
1890 'name' => 'wpPreview',
1891 'type' => 'submit',
1892 'tabindex' => $tabindex,
1893 'value' => wfMsg('showpreview'),
1894 'accesskey' => '',
1895 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1896 'style' => 'display: none;',
1898 $buttons['preview'] = wfElement('input', $temp, '');
1900 $temp = array(
1901 'id' => 'wpLivePreview',
1902 'name' => 'wpLivePreview',
1903 'type' => 'submit',
1904 'tabindex' => $tabindex,
1905 'value' => wfMsg('showlivepreview'),
1906 'accesskey' => wfMsg('accesskey-preview'),
1907 'title' => '',
1908 'onclick' => $this->doLivePreviewScript(),
1910 $buttons['live'] = wfElement('input', $temp, '');
1911 } else {
1912 $temp = array(
1913 'id' => 'wpPreview',
1914 'name' => 'wpPreview',
1915 'type' => 'submit',
1916 'tabindex' => $tabindex,
1917 'value' => wfMsg('showpreview'),
1918 'accesskey' => wfMsg('accesskey-preview'),
1919 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1921 $buttons['preview'] = wfElement('input', $temp, '');
1922 $buttons['live'] = '';
1925 $temp = array(
1926 'id' => 'wpDiff',
1927 'name' => 'wpDiff',
1928 'type' => 'submit',
1929 'tabindex' => ++$tabindex,
1930 'value' => wfMsg('showdiff'),
1931 'accesskey' => wfMsg('accesskey-diff'),
1932 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1934 $buttons['diff'] = wfElement('input', $temp, '');
1936 return $buttons;
1940 * Output preview text only. This can be sucked into the edit page
1941 * via JavaScript, and saves the server time rendering the skin as
1942 * well as theoretically being more robust on the client (doesn't
1943 * disturb the edit box's undo history, won't eat your text on
1944 * failure, etc).
1946 * @todo This doesn't include category or interlanguage links.
1947 * Would need to enhance it a bit, <s>maybe wrap them in XML
1948 * or something...</s> that might also require more skin
1949 * initialization, so check whether that's a problem.
1951 function livePreview() {
1952 global $wgOut;
1953 $wgOut->disable();
1954 header( 'Content-type: text/xml; charset=utf-8' );
1955 header( 'Cache-control: no-cache' );
1957 $previewText = $this->getPreviewText();
1958 #$categories = $skin->getCategoryLinks();
1960 $s =
1961 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1962 Xml::tags( 'livepreview', null,
1963 Xml::element( 'preview', null, $previewText )
1964 #. Xml::element( 'category', null, $categories )
1966 echo $s;
1971 * Get a diff between the current contents of the edit box and the
1972 * version of the page we're editing from.
1974 * If this is a section edit, we'll replace the section as for final
1975 * save and then make a comparison.
1977 function showDiff() {
1978 $oldtext = $this->mArticle->fetchContent();
1979 $newtext = $this->mArticle->replaceSection(
1980 $this->section, $this->textbox1, $this->summary, $this->edittime );
1981 $newtext = $this->mArticle->preSaveTransform( $newtext );
1982 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1983 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1984 if ( $oldtext !== false || $newtext != '' ) {
1985 $de = new DifferenceEngine( $this->mTitle );
1986 $de->setText( $oldtext, $newtext );
1987 $difftext = $de->getDiff( $oldtitle, $newtitle );
1988 $de->showDiffStyle();
1989 } else {
1990 $difftext = '';
1993 global $wgOut;
1994 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
1998 * Filter an input field through a Unicode de-armoring process if it
1999 * came from an old browser with known broken Unicode editing issues.
2001 * @param WebRequest $request
2002 * @param string $field
2003 * @return string
2004 * @private
2006 function safeUnicodeInput( $request, $field ) {
2007 $text = rtrim( $request->getText( $field ) );
2008 return $request->getBool( 'safemode' )
2009 ? $this->unmakesafe( $text )
2010 : $text;
2014 * Filter an output field through a Unicode armoring process if it is
2015 * going to an old browser with known broken Unicode editing issues.
2017 * @param string $text
2018 * @return string
2019 * @private
2021 function safeUnicodeOutput( $text ) {
2022 global $wgContLang;
2023 $codedText = $wgContLang->recodeForEdit( $text );
2024 return $this->checkUnicodeCompliantBrowser()
2025 ? $codedText
2026 : $this->makesafe( $codedText );
2030 * A number of web browsers are known to corrupt non-ASCII characters
2031 * in a UTF-8 text editing environment. To protect against this,
2032 * detected browsers will be served an armored version of the text,
2033 * with non-ASCII chars converted to numeric HTML character references.
2035 * Preexisting such character references will have a 0 added to them
2036 * to ensure that round-trips do not alter the original data.
2038 * @param string $invalue
2039 * @return string
2040 * @private
2042 function makesafe( $invalue ) {
2043 // Armor existing references for reversability.
2044 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2046 $bytesleft = 0;
2047 $result = "";
2048 $working = 0;
2049 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2050 $bytevalue = ord( $invalue{$i} );
2051 if( $bytevalue <= 0x7F ) { //0xxx xxxx
2052 $result .= chr( $bytevalue );
2053 $bytesleft = 0;
2054 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
2055 $working = $working << 6;
2056 $working += ($bytevalue & 0x3F);
2057 $bytesleft--;
2058 if( $bytesleft <= 0 ) {
2059 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2061 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
2062 $working = $bytevalue & 0x1F;
2063 $bytesleft = 1;
2064 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
2065 $working = $bytevalue & 0x0F;
2066 $bytesleft = 2;
2067 } else { //1111 0xxx
2068 $working = $bytevalue & 0x07;
2069 $bytesleft = 3;
2072 return $result;
2076 * Reverse the previously applied transliteration of non-ASCII characters
2077 * back to UTF-8. Used to protect data from corruption by broken web browsers
2078 * as listed in $wgBrowserBlackList.
2080 * @param string $invalue
2081 * @return string
2082 * @private
2084 function unmakesafe( $invalue ) {
2085 $result = "";
2086 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2087 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
2088 $i += 3;
2089 $hexstring = "";
2090 do {
2091 $hexstring .= $invalue{$i};
2092 $i++;
2093 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2095 // Do some sanity checks. These aren't needed for reversability,
2096 // but should help keep the breakage down if the editor
2097 // breaks one of the entities whilst editing.
2098 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2099 $codepoint = hexdec($hexstring);
2100 $result .= codepointToUtf8( $codepoint );
2101 } else {
2102 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2104 } else {
2105 $result .= substr( $invalue, $i, 1 );
2108 // reverse the transform that we made for reversability reasons.
2109 return strtr( $result, array( "&#x0" => "&#x" ) );
2112 function noCreatePermission() {
2113 global $wgOut;
2114 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2115 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
2119 * If there are rows in the deletion log for this page, show them,
2120 * along with a nice little note for the user
2122 * @param OutputPage $out
2124 private function showDeletionLog( $out ) {
2125 $title = $this->mTitle;
2126 $reader = new LogReader(
2127 new FauxRequest(
2128 array(
2129 'page' => $title->getPrefixedText(),
2130 'type' => 'delete',
2134 if( $reader->hasRows() ) {
2135 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2136 $out->addWikiText( wfMsg( 'recreate-deleted-warn' ) );
2137 $viewer = new LogViewer( $reader );
2138 $viewer->showList( $out );
2139 $out->addHtml( '</div>' );
2144 * Attempt submission
2145 * @return bool false if output is done, true if the rest of the form should be displayed
2147 function attemptSave() {
2148 global $wgUser, $wgOut, $wgTitle;
2150 $resultDetails = false;
2151 $value = $this->internalAttemptSave( $resultDetails );
2153 if( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
2154 $this->didSave = true;
2157 switch ($value)
2159 case self::AS_HOOK_ERROR_EXPECTED:
2160 case self::AS_CONTENT_TOO_BIG:
2161 case self::AS_ARTICLE_WAS_DELETED:
2162 case self::AS_CONFLICT_DETECTED:
2163 case self::AS_SUMMARY_NEEDED:
2164 case self::AS_TEXTBOX_EMPTY:
2165 case self::AS_MAX_ARTICLE_SIZE_EXCEDED:
2166 case self::AS_END:
2167 return true;
2169 case self::AS_HOOK_ERROR:
2170 case self::AS_FILTERING:
2171 case self::AS_SUCCESS_NEW_ARTICLE:
2172 case self::AS_SUCCESS_UPDATE:
2173 return false;
2175 case self::AS_SPAM_ERROR:
2176 $this->spamPage ( $resultDetails['spam'] );
2177 return false;
2179 case self::AS_BLOCKED_PAGE_FOR_USER:
2180 $this->blockedPage();
2181 return false;
2183 case self::AS_READ_ONLY_PAGE_ANON:
2184 $this->userNotLoggedInPage();
2185 return false;
2187 case self::AS_READ_ONLY_PAGE_LOGGED:
2188 case self::AS_READ_ONLY_PAGE:
2189 $wgOut->readOnlyPage();
2190 return false;
2192 case self::AS_RATE_LIMITED:
2193 $wgOut->rateLimited();
2194 return false;
2196 case self::AS_NO_CREATE_PERMISSION;
2197 $this->noCreatePermission();
2198 return;
2200 case self::AS_BLANK_ARTICLE:
2201 $wgOut->redirect( $wgTitle->getFullURL() );
2202 return false;