Update the Chinese conversion tables
[mediawiki.git] / includes / EditPage.php
blobdd3544cab7652b8cf7d73c5b181c679e6a6555a4
1 <?php
2 /**
3 * Contains the EditPage class
4 * @file
5 */
7 /**
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
11 * interfaces.
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.
19 class EditPage {
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;
39 const AS_OK = 230;
40 const AS_END = 231;
41 const AS_SPAM_ERROR = 232;
42 const AS_IMAGE_REDIRECT_ANON = 233;
43 const AS_IMAGE_REDIRECT_LOGGED = 234;
45 var $mArticle;
46 var $mTitle;
47 var $mMetaData = '';
48 var $isConflict = false;
49 var $isCssJsSubpage = false;
50 var $deletedSinceEdit = false;
51 var $formtype;
52 var $firsttime;
53 var $lastDelete;
54 var $mTokenOk = false;
55 var $mTokenOkExceptSuffix = false;
56 var $mTriedSave = false;
57 var $tooBig = false;
58 var $kblength = false;
59 var $missingComment = false;
60 var $missingSummary = false;
61 var $allowBlankSummary = false;
62 var $autoSumm = '';
63 var $hookError = '';
64 var $mPreviewTemplates;
65 var $mBaseRevision = false;
67 # Form values
68 var $save = false, $preview = false, $diff = false;
69 var $minoredit = false, $watchthis = false, $recreate = false;
70 var $textbox1 = '', $textbox2 = '', $summary = '';
71 var $edittime = '', $section = '', $starttime = '';
72 var $oldid = 0, $editintro = '', $scrolltop = null;
74 # Placeholders for text injection by hooks (must be HTML)
75 # extensions should take care to _append_ to the present value
76 public $editFormPageTop; // Before even the preview
77 public $editFormTextTop;
78 public $editFormTextBeforeContent;
79 public $editFormTextAfterWarn;
80 public $editFormTextAfterTools;
81 public $editFormTextBottom;
83 /* $didSave should be set to true whenever an article was succesfully altered. */
84 public $didSave = false;
86 public $suppressIntro = false;
88 /**
89 * @todo document
90 * @param $article
92 function EditPage( $article ) {
93 $this->mArticle =& $article;
94 $this->mTitle = $article->getTitle();
96 # Placeholders for text injection by hooks (empty per default)
97 $this->editFormPageTop =
98 $this->editFormTextTop =
99 $this->editFormTextBeforeContent =
100 $this->editFormTextAfterWarn =
101 $this->editFormTextAfterTools =
102 $this->editFormTextBottom = "";
106 * Fetch initial editing page content.
107 * @private
109 function getContent( $def_text = '' ) {
110 global $wgOut, $wgRequest, $wgParser, $wgMessageCache;
112 # Get variables from query string :P
113 $section = $wgRequest->getVal( 'section' );
114 $preload = $wgRequest->getVal( 'preload' );
115 $undoafter = $wgRequest->getVal( 'undoafter' );
116 $undo = $wgRequest->getVal( 'undo' );
118 wfProfileIn( __METHOD__ );
120 $text = '';
121 if( !$this->mTitle->exists() ) {
122 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
123 $wgMessageCache->loadAllMessages();
124 # If this is a system message, get the default text.
125 $text = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
126 } else {
127 # If requested, preload some text.
128 $text = $this->getPreloadedText( $preload );
130 # We used to put MediaWiki:Newarticletext here if
131 # $text was empty at this point.
132 # This is now shown above the edit box instead.
133 } else {
134 // FIXME: may be better to use Revision class directly
135 // But don't mess with it just yet. Article knows how to
136 // fetch the page record from the high-priority server,
137 // which is needed to guarantee we don't pick up lagged
138 // information.
140 $text = $this->mArticle->getContent();
142 if ($undo > 0 && $undoafter > 0 && $undo < $undoafter) {
143 # If they got undoafter and undo round the wrong way, switch them
144 list( $undo, $undoafter ) = array( $undoafter, $undo );
147 if ( $undo > 0 && $undo > $undoafter ) {
148 # Undoing a specific edit overrides section editing; section-editing
149 # doesn't work with undoing.
150 if ( $undoafter ) {
151 $undorev = Revision::newFromId($undo);
152 $oldrev = Revision::newFromId($undoafter);
153 } else {
154 $undorev = Revision::newFromId($undo);
155 $oldrev = $undorev ? $undorev->getPrevious() : null;
158 # Sanity check, make sure it's the right page,
159 # the revisions exist and they were not deleted.
160 # Otherwise, $text will be left as-is.
161 if( !is_null( $undorev ) && !is_null( $oldrev ) &&
162 $undorev->getPage() == $oldrev->getPage() &&
163 $undorev->getPage() == $this->mArticle->getID() &&
164 !$undorev->isDeleted( Revision::DELETED_TEXT ) &&
165 !$oldrev->isDeleted( Revision::DELETED_TEXT ) ) {
166 $undorev_text = $undorev->getText();
167 $oldrev_text = $oldrev->getText();
168 $currev_text = $text;
170 if ( $currev_text != $undorev_text ) {
171 $result = wfMerge( $undorev_text, $oldrev_text, $currev_text, $text );
172 } else {
173 # No use doing a merge if it's just a straight revert.
174 $text = $oldrev_text;
175 $result = true;
177 if( $result ) {
178 # Inform the user of our success and set an automatic edit summary
179 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
180 $firstrev = $oldrev->getNext();
181 # If we just undid one rev, use an autosummary
182 if( $firstrev->mId == $undo ) {
183 $this->summary = wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
185 $this->formtype = 'diff';
186 } else {
187 # Warn the user that something went wrong
188 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
190 } else {
191 // Failed basic sanity checks.
192 // Older revisions may have been removed since the link
193 // was created, or we may simply have got bogus input.
194 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-norev' ) );
196 } else if( $section != '' ) {
197 if( $section == 'new' ) {
198 $text = $this->getPreloadedText( $preload );
199 } else {
200 $text = $wgParser->getSection( $text, $section, $def_text );
205 wfProfileOut( __METHOD__ );
206 return $text;
210 * Get the contents of a page from its title and remove includeonly tags
212 * @param $preload String: the title of the page.
213 * @return string The contents of the page.
215 protected function getPreloadedText($preload) {
216 if ( $preload === '' )
217 return '';
218 else {
219 $preloadTitle = Title::newFromText( $preload );
220 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
221 $rev=Revision::newFromTitle($preloadTitle);
222 if ( is_object( $rev ) ) {
223 $text = $rev->getText();
224 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
225 // its own mini-parser! -ævar
226 $text = preg_replace( '~</?includeonly>~', '', $text );
227 return $text;
228 } else
229 return '';
235 * This is the function that extracts metadata from the article body on the first view.
236 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
237 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
239 function extractMetaDataFromArticle () {
240 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
241 $this->mMetaData = '' ;
242 if ( !$wgUseMetadataEdit ) return ;
243 if ( $wgMetadataWhitelist == '' ) return ;
244 $s = '' ;
245 $t = $this->getContent();
247 # MISSING : <nowiki> filtering
249 # Categories and language links
250 $t = explode ( "\n" , $t ) ;
251 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
252 $cat = $ll = array() ;
253 foreach ( $t AS $key => $x )
255 $y = trim ( strtolower ( $x ) ) ;
256 while ( substr ( $y , 0 , 2 ) == '[[' )
258 $y = explode ( ']]' , trim ( $x ) ) ;
259 $first = array_shift ( $y ) ;
260 $first = explode ( ':' , $first ) ;
261 $ns = array_shift ( $first ) ;
262 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
263 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
265 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
266 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
267 else $ll[] = $add ;
268 $x = implode ( ']]' , $y ) ;
269 $t[$key] = $x ;
270 $y = trim ( strtolower ( $x ) ) ;
274 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
275 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
276 $t = implode ( "\n" , $t ) ;
278 # Load whitelist
279 $sat = array () ; # stand-alone-templates; must be lowercase
280 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
281 $wl_article = new Article ( $wl_title ) ;
282 $wl = explode ( "\n" , $wl_article->getContent() ) ;
283 foreach ( $wl AS $x )
285 $isentry = false ;
286 $x = trim ( $x ) ;
287 while ( substr ( $x , 0 , 1 ) == '*' )
289 $isentry = true ;
290 $x = trim ( substr ( $x , 1 ) ) ;
292 if ( $isentry )
294 $sat[] = strtolower ( $x ) ;
299 # Templates, but only some
300 $t = explode ( '{{' , $t ) ;
301 $tl = array () ;
302 foreach ( $t AS $key => $x )
304 $y = explode ( '}}' , $x , 2 ) ;
305 if ( count ( $y ) == 2 )
307 $z = $y[0] ;
308 $z = explode ( '|' , $z ) ;
309 $tn = array_shift ( $z ) ;
310 if ( in_array ( strtolower ( $tn ) , $sat ) )
312 $tl[] = '{{' . $y[0] . '}}' ;
313 $t[$key] = $y[1] ;
314 $y = explode ( '}}' , $y[1] , 2 ) ;
316 else $t[$key] = '{{' . $x ;
318 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
319 else $t[$key] = $x ;
321 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
322 $t = implode ( '' , $t ) ;
324 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
325 $this->mArticle->mContent = $t ;
326 $this->mMetaData = $s ;
329 protected function wasDeletedSinceLastEdit() {
330 /* Note that we rely on the logging table, which hasn't been always there,
331 * but that doesn't matter, because this only applies to brand new
332 * deletes.
334 if ( $this->deletedSinceEdit )
335 return true;
336 if ( $this->mTitle->isDeleted() ) {
337 $this->lastDelete = $this->getLastDelete();
338 if ( !is_null($this->lastDelete) ) {
339 $deletetime = $this->lastDelete->log_timestamp;
340 if ( ($deletetime - $this->starttime) > 0 ) {
341 $this->deletedSinceEdit = true;
345 return $this->deletedSinceEdit;
348 function submit() {
349 $this->edit();
353 * This is the function that gets called for "action=edit". It
354 * sets up various member variables, then passes execution to
355 * another function, usually showEditForm()
357 * The edit form is self-submitting, so that when things like
358 * preview and edit conflicts occur, we get the same form back
359 * with the extra stuff added. Only when the final submission
360 * is made and all is well do we actually save and redirect to
361 * the newly-edited page.
363 function edit() {
364 global $wgOut, $wgUser, $wgRequest;
366 if ( !wfRunHooks( 'AlternateEdit', array( &$this ) ) )
367 return;
369 wfProfileIn( __METHOD__ );
370 wfDebug( __METHOD__.": enter\n" );
372 // this is not an article
373 $wgOut->setArticleFlag(false);
375 $this->importFormData( $wgRequest );
376 $this->firsttime = false;
378 if( $this->live ) {
379 $this->livePreview();
380 wfProfileOut( __METHOD__ );
381 return;
384 $wgOut->addScriptFile( 'edit.js' );
386 if( wfReadOnly() ) {
387 $this->readOnlyPage( $this->getContent() );
388 wfProfileOut( __METHOD__ );
389 return;
392 $permErrors = $this->mTitle->getUserPermissionsErrors('edit', $wgUser);
394 if( !$this->mTitle->exists() ) {
395 $permErrors = array_merge( $permErrors,
396 wfArrayDiff2( $this->mTitle->getUserPermissionsErrors('create', $wgUser), $permErrors ) );
399 # Ignore some permissions errors.
400 $remove = array();
401 foreach( $permErrors as $error ) {
402 if ( ( $this->preview || $this->diff ) &&
403 ($error[0] == 'blockedtext' || $error[0] == 'autoblockedtext'))
405 // Don't worry about blocks when previewing/diffing
406 $remove[] = $error;
409 if ($error[0] == 'readonlytext')
411 if ($this->edit) {
412 $this->formtype = 'preview';
413 } elseif ($this->save || $this->preview || $this->diff) {
414 $remove[] = $error;
418 $permErrors = wfArrayDiff2( $permErrors, $remove );
420 if ( $permErrors ) {
421 wfDebug( __METHOD__.": User can't edit\n" );
422 $this->readOnlyPage( $this->getContent(), true, $permErrors, 'edit' );
423 wfProfileOut( __METHOD__ );
424 return;
425 } else {
426 if ( $this->save ) {
427 $this->formtype = 'save';
428 } else if ( $this->preview ) {
429 $this->formtype = 'preview';
430 } else if ( $this->diff ) {
431 $this->formtype = 'diff';
432 } else { # First time through
433 $this->firsttime = true;
434 if( $this->previewOnOpen() ) {
435 $this->formtype = 'preview';
436 } else {
437 $this->extractMetaDataFromArticle () ;
438 $this->formtype = 'initial';
443 wfProfileIn( __METHOD__."-business-end" );
445 $this->isConflict = false;
446 // css / js subpages of user pages get a special treatment
447 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
448 $this->isValidCssJsSubpage = $this->mTitle->isValidCssJsSubpage();
450 # Show applicable editing introductions
451 if( $this->formtype == 'initial' || $this->firsttime )
452 $this->showIntro();
454 if( $this->mTitle->isTalkPage() ) {
455 $wgOut->addWikiMsg( 'talkpagetext' );
458 # Attempt submission here. This will check for edit conflicts,
459 # and redundantly check for locked database, blocked IPs, etc.
460 # that edit() already checked just in case someone tries to sneak
461 # in the back door with a hand-edited submission URL.
463 if ( 'save' == $this->formtype ) {
464 if ( !$this->attemptSave() ) {
465 wfProfileOut( __METHOD__."-business-end" );
466 wfProfileOut( __METHOD__ );
467 return;
471 # First time through: get contents, set time for conflict
472 # checking, etc.
473 if ( 'initial' == $this->formtype || $this->firsttime ) {
474 if ($this->initialiseForm() === false) {
475 $this->noSuchSectionPage();
476 wfProfileOut( __METHOD__."-business-end" );
477 wfProfileOut( __METHOD__ );
478 return;
480 if( !$this->mTitle->getArticleId() )
481 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
484 $this->showEditForm();
485 wfProfileOut( __METHOD__."-business-end" );
486 wfProfileOut( __METHOD__ );
490 * Show a read-only error
491 * Parameters are the same as OutputPage:readOnlyPage()
492 * Redirect to the article page if redlink=1
494 function readOnlyPage( $source = null, $protected = false, $reasons = array(), $action = null ) {
495 global $wgRequest, $wgOut;
496 if ( $wgRequest->getBool( 'redlink' ) ) {
497 // The edit page was reached via a red link.
498 // Redirect to the article page and let them click the edit tab if
499 // they really want a permission error.
500 $wgOut->redirect( $this->mTitle->getFullUrl() );
501 } else {
502 $wgOut->readOnlyPage( $source, $protected, $reasons, $action );
507 * Should we show a preview when the edit form is first shown?
509 * @return bool
511 protected function previewOnOpen() {
512 global $wgRequest, $wgUser;
513 if( $wgRequest->getVal( 'preview' ) == 'yes' ) {
514 // Explicit override from request
515 return true;
516 } elseif( $wgRequest->getVal( 'preview' ) == 'no' ) {
517 // Explicit override from request
518 return false;
519 } elseif( $this->section == 'new' ) {
520 // Nothing *to* preview for new sections
521 return false;
522 } elseif( ( $wgRequest->getVal( 'preload' ) !== '' || $this->mTitle->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
523 // Standard preference behaviour
524 return true;
525 } elseif( !$this->mTitle->exists() && $this->mTitle->getNamespace() == NS_CATEGORY ) {
526 // Categories are special
527 return true;
528 } else {
529 return false;
534 * @todo document
535 * @param $request
537 function importFormData( &$request ) {
538 global $wgLang, $wgUser;
539 $fname = 'EditPage::importFormData';
540 wfProfileIn( $fname );
542 # Section edit can come from either the form or a link
543 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
545 if( $request->wasPosted() ) {
546 # These fields need to be checked for encoding.
547 # Also remove trailing whitespace, but don't remove _initial_
548 # whitespace from the text boxes. This may be significant formatting.
549 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
550 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
551 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
552 # Truncate for whole multibyte characters. +5 bytes for ellipsis
553 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
555 # Remove extra headings from summaries and new sections.
556 $this->summary = preg_replace('/^\s*=+\s*(.*?)\s*=+\s*$/', '$1', $this->summary);
558 $this->edittime = $request->getVal( 'wpEdittime' );
559 $this->starttime = $request->getVal( 'wpStarttime' );
561 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
563 if( is_null( $this->edittime ) ) {
564 # If the form is incomplete, force to preview.
565 wfDebug( "$fname: Form data appears to be incomplete\n" );
566 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
567 $this->preview = true;
568 } else {
569 /* Fallback for live preview */
570 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
571 $this->diff = $request->getCheck( 'wpDiff' );
573 // Remember whether a save was requested, so we can indicate
574 // if we forced preview due to session failure.
575 $this->mTriedSave = !$this->preview;
577 if ( $this->tokenOk( $request ) ) {
578 # Some browsers will not report any submit button
579 # if the user hits enter in the comment box.
580 # The unmarked state will be assumed to be a save,
581 # if the form seems otherwise complete.
582 wfDebug( "$fname: Passed token check.\n" );
583 } else if ( $this->diff ) {
584 # Failed token check, but only requested "Show Changes".
585 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
586 } else {
587 # Page might be a hack attempt posted from
588 # an external site. Preview instead of saving.
589 wfDebug( "$fname: Failed token check; forcing preview\n" );
590 $this->preview = true;
593 $this->save = !$this->preview && !$this->diff;
594 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
595 $this->edittime = null;
598 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
599 $this->starttime = null;
602 $this->recreate = $request->getCheck( 'wpRecreate' );
604 $this->minoredit = $request->getCheck( 'wpMinoredit' );
605 $this->watchthis = $request->getCheck( 'wpWatchthis' );
607 # Don't force edit summaries when a user is editing their own user or talk page
608 if( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) && $this->mTitle->getText() == $wgUser->getName() ) {
609 $this->allowBlankSummary = true;
610 } else {
611 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
614 $this->autoSumm = $request->getText( 'wpAutoSummary' );
615 } else {
616 # Not a posted form? Start with nothing.
617 wfDebug( "$fname: Not a posted form.\n" );
618 $this->textbox1 = '';
619 $this->textbox2 = '';
620 $this->mMetaData = '';
621 $this->summary = '';
622 $this->edittime = '';
623 $this->starttime = wfTimestampNow();
624 $this->edit = false;
625 $this->preview = false;
626 $this->save = false;
627 $this->diff = false;
628 $this->minoredit = false;
629 $this->watchthis = false;
630 $this->recreate = false;
632 if ( $this->section == 'new' && $request->getVal( 'preloadtitle' ) ) {
633 $this->summary = $request->getVal( 'preloadtitle' );
637 $this->oldid = $request->getInt( 'oldid' );
639 $this->live = $request->getCheck( 'live' );
640 $this->editintro = $request->getText( 'editintro' );
642 wfProfileOut( $fname );
646 * Make sure the form isn't faking a user's credentials.
648 * @param $request WebRequest
649 * @return bool
650 * @private
652 function tokenOk( &$request ) {
653 global $wgUser;
654 $token = $request->getVal( 'wpEditToken' );
655 $this->mTokenOk = $wgUser->matchEditToken( $token );
656 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
657 return $this->mTokenOk;
661 * Show all applicable editing introductions
663 protected function showIntro() {
664 global $wgOut, $wgUser;
665 if( $this->suppressIntro )
666 return;
668 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
669 if( $this->mTitle->getNamespace() == NS_USER || $this->mTitle->getNamespace() == NS_USER_TALK ) {
670 $parts = explode( '/', $this->mTitle->getText(), 2 );
671 $username = $parts[0];
672 $id = User::idFromName( $username );
673 $ip = User::isIP( $username );
675 if ( $id == 0 && !$ip ) {
676 $wgOut->wrapWikiMsg( '<div class="mw-userpage-userdoesnotexist error">$1</div>',
677 array( 'userpage-userdoesnotexist', $username ) );
681 if( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
682 if( $wgUser->isLoggedIn() ) {
683 $wgOut->wrapWikiMsg( '<div class="mw-newarticletext">$1</div>', 'newarticletext' );
684 } else {
685 $wgOut->wrapWikiMsg( '<div class="mw-newarticletextanon">$1</div>', 'newarticletextanon' );
687 $this->showDeletionLog( $wgOut );
692 * Attempt to show a custom editing introduction, if supplied
694 * @return bool
696 protected function showCustomIntro() {
697 if( $this->editintro ) {
698 $title = Title::newFromText( $this->editintro );
699 if( $title instanceof Title && $title->exists() && $title->userCanRead() ) {
700 global $wgOut;
701 $revision = Revision::newFromTitle( $title );
702 $wgOut->addWikiTextTitleTidy( $revision->getText(), $this->mTitle );
703 return true;
704 } else {
705 return false;
707 } else {
708 return false;
713 * Attempt submission (no UI)
714 * @return one of the constants describing the result
716 function internalAttemptSave( &$result, $bot = false ) {
717 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut, $wgParser;
718 global $wgMaxArticleSize;
720 $fname = 'EditPage::attemptSave';
721 wfProfileIn( $fname );
722 wfProfileIn( "$fname-checks" );
724 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
726 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
727 return self::AS_HOOK_ERROR;
730 # Check image redirect
731 if ( $this->mTitle->getNamespace() == NS_IMAGE &&
732 Title::newFromRedirect( $this->textbox1 ) instanceof Title &&
733 !$wgUser->isAllowed( 'upload' ) ) {
734 if( $wgUser->isAnon() ) {
735 return self::AS_IMAGE_REDIRECT_ANON;
736 } else {
737 return self::AS_IMAGE_REDIRECT_LOGGED;
741 # Reintegrate metadata
742 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
743 $this->mMetaData = '' ;
745 # Check for spam
746 $matches = array();
747 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
748 $result['spam'] = $matches[0];
749 $ip = wfGetIP();
750 $pdbk = $this->mTitle->getPrefixedDBkey();
751 $match = str_replace( "\n", '', $matches[0] );
752 wfDebugLog( 'SpamRegex', "$ip spam regex hit [[$pdbk]]: \"$match\"" );
753 wfProfileOut( "$fname-checks" );
754 wfProfileOut( $fname );
755 return self::AS_SPAM_ERROR;
757 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section, $this->hookError, $this->summary ) ) {
758 # Error messages or other handling should be performed by the filter function
759 wfProfileOut( "$fname-checks" );
760 wfProfileOut( $fname );
761 return self::AS_FILTERING;
763 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError, $this->summary ) ) ) {
764 # Error messages etc. could be handled within the hook...
765 wfProfileOut( "$fname-checks" );
766 wfProfileOut( $fname );
767 return self::AS_HOOK_ERROR;
768 } elseif( $this->hookError != '' ) {
769 # ...or the hook could be expecting us to produce an error
770 wfProfileOut( "$fname-checks" );
771 wfProfileOut( $fname );
772 return self::AS_HOOK_ERROR_EXPECTED;
774 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
775 # Check block state against master, thus 'false'.
776 wfProfileOut( "$fname-checks" );
777 wfProfileOut( $fname );
778 return self::AS_BLOCKED_PAGE_FOR_USER;
780 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
781 if ( $this->kblength > $wgMaxArticleSize ) {
782 // Error will be displayed by showEditForm()
783 $this->tooBig = true;
784 wfProfileOut( "$fname-checks" );
785 wfProfileOut( $fname );
786 return self::AS_CONTENT_TOO_BIG;
789 if ( !$wgUser->isAllowed('edit') ) {
790 if ( $wgUser->isAnon() ) {
791 wfProfileOut( "$fname-checks" );
792 wfProfileOut( $fname );
793 return self::AS_READ_ONLY_PAGE_ANON;
795 else {
796 wfProfileOut( "$fname-checks" );
797 wfProfileOut( $fname );
798 return self::AS_READ_ONLY_PAGE_LOGGED;
802 if ( wfReadOnly() ) {
803 wfProfileOut( "$fname-checks" );
804 wfProfileOut( $fname );
805 return self::AS_READ_ONLY_PAGE;
807 if ( $wgUser->pingLimiter() ) {
808 wfProfileOut( "$fname-checks" );
809 wfProfileOut( $fname );
810 return self::AS_RATE_LIMITED;
813 # If the article has been deleted while editing, don't save it without
814 # confirmation
815 if ( $this->wasDeletedSinceLastEdit() && !$this->recreate ) {
816 wfProfileOut( "$fname-checks" );
817 wfProfileOut( $fname );
818 return self::AS_ARTICLE_WAS_DELETED;
821 wfProfileOut( "$fname-checks" );
823 # If article is new, insert it.
824 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
825 if ( 0 == $aid ) {
827 // Late check for create permission, just in case *PARANOIA*
828 if ( !$this->mTitle->userCan( 'create' ) ) {
829 wfDebug( "$fname: no create permission\n" );
830 wfProfileOut( $fname );
831 return self::AS_NO_CREATE_PERMISSION;
834 # Don't save a new article if it's blank.
835 if ( '' == $this->textbox1 ) {
836 wfProfileOut( $fname );
837 return self::AS_BLANK_ARTICLE;
840 // Run post-section-merge edit filter
841 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError, $this->summary ) ) ) {
842 # Error messages etc. could be handled within the hook...
843 wfProfileOut( $fname );
844 return self::AS_HOOK_ERROR;
847 $isComment = ( $this->section == 'new' );
849 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
850 $this->minoredit, $this->watchthis, false, $isComment, $bot);
852 wfProfileOut( $fname );
853 return self::AS_SUCCESS_NEW_ARTICLE;
856 # Article exists. Check for edit conflict.
858 $this->mArticle->clear(); # Force reload of dates, etc.
859 $this->mArticle->forUpdate( true ); # Lock the article
861 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
863 if( $this->mArticle->getTimestamp() != $this->edittime ) {
864 $this->isConflict = true;
865 if( $this->section == 'new' ) {
866 if( $this->mArticle->getUserText() == $wgUser->getName() &&
867 $this->mArticle->getComment() == $this->summary ) {
868 // Probably a duplicate submission of a new comment.
869 // This can happen when squid resends a request after
870 // a timeout but the first one actually went through.
871 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
872 } else {
873 // New comment; suppress conflict.
874 $this->isConflict = false;
875 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
879 $userid = $wgUser->getId();
881 if ( $this->isConflict) {
882 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
883 $this->mArticle->getTimestamp() . "')\n" );
884 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
886 else {
887 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
888 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
890 if( is_null( $text ) ) {
891 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
892 $this->isConflict = true;
893 $text = $this->textbox1;
896 # Suppress edit conflict with self, except for section edits where merging is required.
897 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
898 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
899 $this->isConflict = false;
900 } else {
901 # switch from section editing to normal editing in edit conflict
902 if($this->isConflict) {
903 # Attempt merge
904 if( $this->mergeChangesInto( $text ) ){
905 // Successful merge! Maybe we should tell the user the good news?
906 $this->isConflict = false;
907 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
908 } else {
909 $this->section = '';
910 $this->textbox1 = $text;
911 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
916 if ( $this->isConflict ) {
917 wfProfileOut( $fname );
918 return self::AS_CONFLICT_DETECTED;
921 $oldtext = $this->mArticle->getContent();
923 // Run post-section-merge edit filter
924 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError, $this->summary ) ) ) {
925 # Error messages etc. could be handled within the hook...
926 wfProfileOut( $fname );
927 return self::AS_HOOK_ERROR;
930 # Handle the user preference to force summaries here, but not for null edits
931 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary') &&
932 0 != strcmp($oldtext, $text) &&
933 !is_object( Title::newFromRedirect( $text ) ) # check if it's not a redirect
936 if( md5( $this->summary ) == $this->autoSumm ) {
937 $this->missingSummary = true;
938 wfProfileOut( $fname );
939 return self::AS_SUMMARY_NEEDED;
943 # And a similar thing for new sections
944 if( $this->section == 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
945 if (trim($this->summary) == '') {
946 $this->missingSummary = true;
947 wfProfileOut( $fname );
948 return self::AS_SUMMARY_NEEDED;
952 # All's well
953 wfProfileIn( "$fname-sectionanchor" );
954 $sectionanchor = '';
955 if( $this->section == 'new' ) {
956 if ( $this->textbox1 == '' ) {
957 $this->missingComment = true;
958 return self::AS_TEXTBOX_EMPTY;
960 if( $this->summary != '' ) {
961 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary );
962 # This is a new section, so create a link to the new section
963 # in the revision summary.
964 $cleanSummary = $wgParser->stripSectionName( $this->summary );
965 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
967 } elseif( $this->section != '' ) {
968 # Try to get a section anchor from the section source, redirect to edited section if header found
969 # XXX: might be better to integrate this into Article::replaceSection
970 # for duplicate heading checking and maybe parsing
971 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
972 # we can't deal with anchors, includes, html etc in the header for now,
973 # headline would need to be parsed to improve this
974 if($hasmatch and strlen($matches[2]) > 0) {
975 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
978 wfProfileOut( "$fname-sectionanchor" );
980 // Save errors may fall down to the edit form, but we've now
981 // merged the section into full text. Clear the section field
982 // so that later submission of conflict forms won't try to
983 // replace that into a duplicated mess.
984 $this->textbox1 = $text;
985 $this->section = '';
987 // Check for length errors again now that the section is merged in
988 $this->kblength = (int)(strlen( $text ) / 1024);
989 if ( $this->kblength > $wgMaxArticleSize ) {
990 $this->tooBig = true;
991 wfProfileOut( $fname );
992 return self::AS_MAX_ARTICLE_SIZE_EXCEEDED;
995 # update the article here
996 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
997 $this->watchthis, $bot, $sectionanchor ) ) {
998 wfProfileOut( $fname );
999 return self::AS_SUCCESS_UPDATE;
1000 } else {
1001 $this->isConflict = true;
1003 wfProfileOut( $fname );
1004 return self::AS_END;
1008 * Initialise form fields in the object
1009 * Called on the first invocation, e.g. when a user clicks an edit link
1011 function initialiseForm() {
1012 $this->edittime = $this->mArticle->getTimestamp();
1013 $this->textbox1 = $this->getContent(false);
1014 if ($this->textbox1 === false) return false;
1016 if ( !$this->mArticle->exists() && $this->mTitle->getNamespace() == NS_MEDIAWIKI )
1017 $this->textbox1 = wfMsgWeirdKey( $this->mTitle->getText() );
1018 wfProxyCheck();
1019 return true;
1023 * Send the edit form and related headers to $wgOut
1024 * @param $formCallback Optional callable that takes an OutputPage
1025 * parameter; will be called during form output
1026 * near the top, for captchas and the like.
1028 function showEditForm( $formCallback=null ) {
1029 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle;
1031 # If $wgTitle is null, that means we're in API mode.
1032 # Some hook probably called this function without checking
1033 # for is_null($wgTitle) first. Bail out right here so we don't
1034 # do lots of work just to discard it right after.
1035 if(is_null($wgTitle))
1036 return;
1038 $fname = 'EditPage::showEditForm';
1039 wfProfileIn( $fname );
1041 $sk = $wgUser->getSkin();
1043 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
1045 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1047 # Enabled article-related sidebar, toplinks, etc.
1048 $wgOut->setArticleRelated( true );
1050 if ( $this->formtype == 'preview' ) {
1051 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1054 if ( $this->isConflict ) {
1055 $s = wfMsg( 'editconflict', $wgTitle->getPrefixedText() );
1056 $wgOut->setPageTitle( $s );
1057 $wgOut->addWikiMsg( 'explainconflict' );
1059 $this->textbox2 = $this->textbox1;
1060 $this->textbox1 = $this->getContent();
1061 $this->edittime = $this->mArticle->getTimestamp();
1062 } else {
1063 if( $this->section != '' ) {
1064 if( $this->section == 'new' ) {
1065 $s = wfMsg('editingcomment', $wgTitle->getPrefixedText() );
1066 } else {
1067 $s = wfMsg('editingsection', $wgTitle->getPrefixedText() );
1068 $matches = array();
1069 if( !$this->summary && !$this->preview && !$this->diff ) {
1070 preg_match( "/^(=+)(.+)\\1/mi",
1071 $this->textbox1,
1072 $matches );
1073 if( !empty( $matches[2] ) ) {
1074 global $wgParser;
1075 $this->summary = "/* " .
1076 $wgParser->stripSectionName(trim($matches[2])) .
1077 " */ ";
1081 } else {
1082 $s = wfMsg( 'editing', $wgTitle->getPrefixedText() );
1084 $wgOut->setPageTitle( $s );
1086 if ( $this->missingComment ) {
1087 $wgOut->wrapWikiMsg( '<div id="mw-missingcommenttext">$1</div>', 'missingcommenttext' );
1090 if( $this->missingSummary && $this->section != 'new' ) {
1091 $wgOut->wrapWikiMsg( '<div id="mw-missingsummary">$1</div>', 'missingsummary' );
1094 if( $this->missingSummary && $this->section == 'new' ) {
1095 $wgOut->wrapWikiMsg( '<div id="mw-missingcommentheader">$1</div>', 'missingcommentheader' );
1098 if( $this->hookError !== '' ) {
1099 $wgOut->addWikiText( $this->hookError );
1102 if ( !$this->checkUnicodeCompliantBrowser() ) {
1103 $wgOut->addWikiMsg( 'nonunicodebrowser' );
1105 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
1106 // Let sysop know that this will make private content public if saved
1108 if( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1109 $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
1110 } else if( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1111 $wgOut->addWikiMsg( 'rev-deleted-text-view' );
1114 if( !$this->mArticle->mRevision->isCurrent() ) {
1115 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
1116 $wgOut->addWikiMsg( 'editingold' );
1121 if( wfReadOnly() ) {
1122 $wgOut->addHTML( '<div id="mw-read-only-warning">'.wfMsgWikiHTML( 'readonlywarning' ).'</div>' );
1123 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
1124 $wgOut->addHTML( '<div id="mw-anon-edit-warning">'.wfMsgWikiHTML( 'anoneditwarning' ).'</div>' );
1125 } else {
1126 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
1127 # Check the skin exists
1128 if( $this->isValidCssJsSubpage ) {
1129 $wgOut->addWikiMsg( 'usercssjsyoucanpreview' );
1130 } else {
1131 $wgOut->addWikiMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() );
1136 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1137 # Show a warning if editing an interface message
1138 $wgOut->addWikiMsg( 'editinginterface' );
1139 } elseif( $this->mTitle->isProtected( 'edit' ) ) {
1140 # Is the title semi-protected?
1141 if( $this->mTitle->isSemiProtected() ) {
1142 $noticeMsg = 'semiprotectedpagewarning';
1143 } else {
1144 # Then it must be protected based on static groups (regular)
1145 $noticeMsg = 'protectedpagewarning';
1147 $wgOut->addWikiMsg( $noticeMsg );
1149 if ( $this->mTitle->isCascadeProtected() ) {
1150 # Is this page under cascading protection from some source pages?
1151 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1152 $notice = "$1\n";
1153 if ( count($cascadeSources) > 0 ) {
1154 # Explain, and list the titles responsible
1155 foreach( $cascadeSources as $page ) {
1156 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1159 $wgOut->wrapWikiMsg( $notice, array( 'cascadeprotectedwarning', count($cascadeSources) ) );
1161 if( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) != array() ){
1162 $wgOut->addWikiMsg( 'titleprotectedwarning' );
1165 if ( $this->kblength === false ) {
1166 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
1168 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1169 $wgOut->addWikiMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize );
1170 } elseif( $this->kblength > 29 ) {
1171 $wgOut->addWikiMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) );
1174 #need to parse the preview early so that we know which templates are used,
1175 #otherwise users with "show preview after edit box" will get a blank list
1176 if ( $this->formtype == 'preview' ) {
1177 $previewOutput = $this->getPreviewText();
1180 $rows = $wgUser->getIntOption( 'rows' );
1181 $cols = $wgUser->getIntOption( 'cols' );
1183 $ew = $wgUser->getOption( 'editwidth' );
1184 if ( $ew ) $ew = " style=\"width:100%\"";
1185 else $ew = '';
1187 $q = 'action=submit';
1188 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1189 $action = $wgTitle->escapeLocalURL( $q );
1191 $summary = wfMsg('summary');
1192 $subject = wfMsg('subject');
1194 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedText(),
1195 wfMsgExt('cancel', array('parseinline')) );
1196 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1197 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1198 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1199 htmlspecialchars( wfMsg( 'newwindow' ) );
1201 global $wgRightsText;
1202 if ( $wgRightsText ) {
1203 $copywarnMsg = array( 'copyrightwarning',
1204 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1205 $wgRightsText );
1206 } else {
1207 $copywarnMsg = array( 'copyrightwarning2',
1208 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]' );
1211 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1212 # prepare toolbar for edit buttons
1213 $toolbar = EditPage::getEditToolbar();
1214 } else {
1215 $toolbar = '';
1218 // activate checkboxes if user wants them to be always active
1219 if( !$this->preview && !$this->diff ) {
1220 # Sort out the "watch" checkbox
1221 if( $wgUser->getOption( 'watchdefault' ) ) {
1222 # Watch all edits
1223 $this->watchthis = true;
1224 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1225 # Watch creations
1226 $this->watchthis = true;
1227 } elseif( $this->mTitle->userIsWatching() ) {
1228 # Already watched
1229 $this->watchthis = true;
1232 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1235 $wgOut->addHTML( $this->editFormPageTop );
1237 if ( $wgUser->getOption( 'previewontop' ) ) {
1239 if ( 'preview' == $this->formtype ) {
1240 $this->showPreview( $previewOutput );
1241 } else {
1242 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1245 if ( 'diff' == $this->formtype ) {
1246 $this->showDiff();
1251 $wgOut->addHTML( $this->editFormTextTop );
1253 # if this is a comment, show a subject line at the top, which is also the edit summary.
1254 # Otherwise, show a summary field at the bottom
1255 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1257 # If a blank edit summary was previously provided, and the appropriate
1258 # user preference is active, pass a hidden tag as wpIgnoreBlankSummary. This will stop the
1259 # user being bounced back more than once in the event that a summary
1260 # is not required.
1261 #####
1262 # For a bit more sophisticated detection of blank summaries, hash the
1263 # automatic one and pass that in the hidden field wpAutoSummary.
1264 $summaryhiddens = '';
1265 if( $this->missingSummary ) $summaryhiddens .= Xml::hidden( 'wpIgnoreBlankSummary', true );
1266 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1267 $summaryhiddens .= Xml::hidden( 'wpAutoSummary', $autosumm );
1268 if( $this->section == 'new' ) {
1269 $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 />";
1270 $editsummary = "<div class='editOptions'>\n";
1271 global $wgParser;
1272 $formattedSummary = wfMsgForContent( 'newsectionsummary', $wgParser->stripSectionName( $this->summary ) );
1273 $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $formattedSummary, $this->mTitle, true )."</div>\n" : '';
1274 $summarypreview = '';
1275 } else {
1276 $commentsubject = '';
1277 $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 />";
1278 $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1279 $subjectpreview = '';
1282 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1283 if( !$this->preview && !$this->diff ) {
1284 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1286 $templates = ($this->preview || $this->section != '') ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
1287 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1289 $hiddencats = $this->mArticle->getHiddenCategories();
1290 $formattedhiddencats = $sk->formatHiddenCategories( $hiddencats );
1292 global $wgUseMetadataEdit ;
1293 if ( $wgUseMetadataEdit ) {
1294 $metadata = $this->mMetaData ;
1295 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1296 $top = wfMsgWikiHtml( 'metadata_help' );
1297 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1299 else $metadata = "" ;
1301 $hidden = '';
1302 $recreate = '';
1303 if ($this->wasDeletedSinceLastEdit()) {
1304 if ( 'save' != $this->formtype ) {
1305 $wgOut->addWikiMsg('deletedwhileediting');
1306 } else {
1307 // Hide the toolbar and edit area, use can click preview to get it back
1308 // Add an confirmation checkbox and explanation.
1309 $toolbar = '';
1310 $hidden = 'type="hidden" style="display:none;"';
1311 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1312 $recreate .=
1313 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1314 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1318 $tabindex = 2;
1320 $checkboxes = self::getCheckboxes( $tabindex, $sk,
1321 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1323 $checkboxhtml = implode( $checkboxes, "\n" );
1325 $buttons = $this->getEditButtons( $tabindex );
1326 $buttonshtml = implode( $buttons, "\n" );
1328 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1329 ? '' : Xml::hidden( 'safemode', '1' );
1331 $wgOut->addHTML( <<<END
1332 {$toolbar}
1333 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1337 if( is_callable( $formCallback ) ) {
1338 call_user_func_array( $formCallback, array( &$wgOut ) );
1341 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1343 // Put these up at the top to ensure they aren't lost on early form submission
1344 $wgOut->addHTML( "
1345 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1346 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1347 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1348 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1350 $encodedtext = htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) );
1351 if( $encodedtext !== '' ) {
1352 // Ensure there's a newline at the end, otherwise adding lines
1353 // is awkward.
1354 // But don't add a newline if the ext is empty, or Firefox in XHTML
1355 // mode will show an extra newline. A bit annoying.
1356 $encodedtext .= "\n";
1359 $wgOut->addHTML( <<<END
1360 $recreate
1361 {$commentsubject}
1362 {$subjectpreview}
1363 {$this->editFormTextBeforeContent}
1364 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1365 cols='{$cols}'{$ew} $hidden>{$encodedtext}</textarea>
1369 $wgOut->wrapWikiMsg( "<div id=\"editpage-copywarn\">\n$1\n</div>", $copywarnMsg );
1370 $wgOut->addHTML( $this->editFormTextAfterWarn );
1371 $wgOut->addHTML( "
1372 {$metadata}
1373 {$editsummary}
1374 {$summarypreview}
1375 {$checkboxhtml}
1376 {$safemodehtml}
1379 $wgOut->addHTML(
1380 "<div class='editButtons'>
1381 {$buttonshtml}
1382 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1383 </div><!-- editButtons -->
1384 </div><!-- editOptions -->");
1387 * To make it harder for someone to slip a user a page
1388 * which submits an edit form to the wiki without their
1389 * knowledge, a random token is associated with the login
1390 * session. If it's not passed back with the submission,
1391 * we won't save the page, or render user JavaScript and
1392 * CSS previews.
1394 * For anon editors, who may not have a session, we just
1395 * include the constant suffix to prevent editing from
1396 * broken text-mangling proxies.
1398 $token = htmlspecialchars( $wgUser->editToken() );
1399 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1401 $wgOut->addHtml( '<div class="mw-editTools">' );
1402 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1403 $wgOut->addHtml( '</div>' );
1405 $wgOut->addHTML( $this->editFormTextAfterTools );
1407 $wgOut->addHTML( "
1408 <div class='templatesUsed'>
1409 {$formattedtemplates}
1410 </div>
1411 <div class='hiddencats'>
1412 {$formattedhiddencats}
1413 </div>
1416 if ( $this->isConflict && wfRunHooks( 'EditPageBeforeConflictDiff', array( &$this, &$wgOut ) ) ) {
1417 $wgOut->wrapWikiMsg( '==$1==', "yourdiff" );
1419 $de = new DifferenceEngine( $this->mTitle );
1420 $de->setText( $this->textbox2, $this->textbox1 );
1421 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1423 $wgOut->wrapWikiMsg( '==$1==', "yourtext" );
1424 $wgOut->addHTML( "<textarea tabindex='6' id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}'>"
1425 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1427 $wgOut->addHTML( $this->editFormTextBottom );
1428 $wgOut->addHTML( "</form>\n" );
1429 if ( !$wgUser->getOption( 'previewontop' ) ) {
1431 if ( $this->formtype == 'preview') {
1432 $this->showPreview( $previewOutput );
1433 } else {
1434 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1437 if ( $this->formtype == 'diff') {
1438 $this->showDiff();
1443 wfProfileOut( $fname );
1447 * Append preview output to $wgOut.
1448 * Includes category rendering if this is a category page.
1450 * @param string $text The HTML to be output for the preview.
1452 protected function showPreview( $text ) {
1453 global $wgOut;
1455 $wgOut->addHTML( '<div id="wikiPreview">' );
1456 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1457 $this->mArticle->openShowCategory();
1459 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1460 $wgOut->addHTML( $text );
1461 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1462 $this->mArticle->closeShowCategory();
1464 $wgOut->addHTML( '</div>' );
1468 * Live Preview lets us fetch rendered preview page content and
1469 * add it to the page without refreshing the whole page.
1470 * If not supported by the browser it will fall through to the normal form
1471 * submission method.
1473 * This function outputs a script tag to support live preview, and
1474 * returns an onclick handler which should be added to the attributes
1475 * of the preview button
1477 function doLivePreviewScript() {
1478 global $wgOut, $wgTitle;
1479 $wgOut->addScriptFile( 'preview.js' );
1480 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1481 return "return !lpDoPreview(" .
1482 "editform.wpTextbox1.value," .
1483 '"' . $liveAction . '"' . ")";
1486 function getLastDelete() {
1487 $dbr = wfGetDB( DB_SLAVE );
1488 $fname = 'EditPage::getLastDelete';
1489 $res = $dbr->select(
1490 array( 'logging', 'user' ),
1491 array( 'log_type',
1492 'log_action',
1493 'log_timestamp',
1494 'log_user',
1495 'log_namespace',
1496 'log_title',
1497 'log_comment',
1498 'log_params',
1499 'user_name', ),
1500 array( 'log_namespace' => $this->mTitle->getNamespace(),
1501 'log_title' => $this->mTitle->getDBkey(),
1502 'log_type' => 'delete',
1503 'log_action' => 'delete',
1504 'user_id=log_user' ),
1505 $fname,
1506 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1508 if($dbr->numRows($res) == 1) {
1509 while ( $x = $dbr->fetchObject ( $res ) )
1510 $data = $x;
1511 $dbr->freeResult ( $res ) ;
1512 } else {
1513 $data = null;
1515 return $data;
1519 * @todo document
1521 function getPreviewText() {
1522 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgLang, $wgContLang;
1524 $fname = 'EditPage::getPreviewText';
1525 wfProfileIn( $fname );
1527 if ( $this->mTriedSave && !$this->mTokenOk ) {
1528 if ( $this->mTokenOkExceptSuffix ) {
1529 $note = wfMsg( 'token_suffix_mismatch' );
1530 } else {
1531 $note = wfMsg( 'session_fail_preview' );
1533 } else {
1534 $note = wfMsg( 'previewnote' );
1537 $parserOptions = ParserOptions::newFromUser( $wgUser );
1538 $parserOptions->setEditSection( false );
1540 global $wgRawHtml;
1541 if( $wgRawHtml && !$this->mTokenOk ) {
1542 // Could be an offsite preview attempt. This is very unsafe if
1543 // HTML is enabled, as it could be an attack.
1544 return $wgOut->parse( "<div class='previewnote'>" .
1545 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1548 # don't parse user css/js, show message about preview
1549 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1551 if ( $this->isCssJsSubpage ) {
1552 if(preg_match("/\\.css$/", $this->mTitle->getText() ) ) {
1553 $previewtext = wfMsg('usercsspreview');
1554 } else if(preg_match("/\\.js$/", $this->mTitle->getText() ) ) {
1555 $previewtext = wfMsg('userjspreview');
1557 $parserOptions->setTidy(true);
1558 $parserOutput = $wgParser->parse( $previewtext , $this->mTitle, $parserOptions );
1559 $wgOut->addHTML( $parserOutput->mText );
1560 $previewHTML = '';
1561 } else {
1562 $toparse = $this->textbox1;
1564 # If we're adding a comment, we need to show the
1565 # summary as the headline
1566 if($this->section=="new" && $this->summary!="") {
1567 $toparse="== {$this->summary} ==\n\n".$toparse;
1570 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData;
1572 // Parse mediawiki messages with correct target language
1573 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1574 $pos = strrpos( $this->mTitle->getText(), '/' );
1575 if ( $pos !== false ) {
1576 $code = substr( $this->mTitle->getText(), $pos+1 );
1577 switch ($code) {
1578 case $wgLang->getCode():
1579 $obj = $wgLang; break;
1580 case $wgContLang->getCode():
1581 $obj = $wgContLang; break;
1582 default:
1583 $obj = Language::factory( $code );
1585 $parserOptions->setTargetLanguage( $obj );
1590 $parserOptions->setTidy(true);
1591 $parserOptions->enableLimitReport();
1592 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ),
1593 $this->mTitle, $parserOptions );
1595 $previewHTML = $parserOutput->getText();
1596 $wgOut->addParserOutputNoText( $parserOutput );
1598 # ParserOutput might have altered the page title, so reset it
1599 # Also, use the title defined by DISPLAYTITLE magic word when present
1600 if( ( $dt = $parserOutput->getDisplayTitle() ) !== false ) {
1601 $wgOut->setPageTitle( wfMsg( 'editing', $dt ) );
1602 } else {
1603 $wgOut->setPageTitle( wfMsg( 'editing', $wgTitle->getPrefixedText() ) );
1606 foreach ( $parserOutput->getTemplates() as $ns => $template)
1607 foreach ( array_keys( $template ) as $dbk)
1608 $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
1610 if ( count( $parserOutput->getWarnings() ) ) {
1611 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1615 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1616 "<div class='previewnote'>" . $wgOut->parse( $note ) . "</div>\n";
1617 if ( $this->isConflict ) {
1618 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1621 if( $wgUser->getOption( 'previewontop' ) ) {
1622 // Spacer for the edit toolbar
1623 $previewfoot = '<p><br /></p>';
1624 } else {
1625 $previewfoot = '';
1628 wfProfileOut( $fname );
1629 return $previewhead . $previewHTML . $previewfoot;
1633 * Call the stock "user is blocked" page
1635 function blockedPage() {
1636 global $wgOut, $wgUser;
1637 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1639 # If the user made changes, preserve them when showing the markup
1640 # (This happens when a user is blocked during edit, for instance)
1641 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1642 if( $first ) {
1643 $source = $this->mTitle->exists() ? $this->getContent() : false;
1644 } else {
1645 $source = $this->textbox1;
1648 # Spit out the source or the user's modified version
1649 if( $source !== false ) {
1650 $rows = $wgUser->getOption( 'rows' );
1651 $cols = $wgUser->getOption( 'cols' );
1652 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1653 $wgOut->addHtml( '<hr />' );
1654 $wgOut->addWikiMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() );
1655 # Why we don't use Xml::element here?
1656 # Is it because if $source is '', it returns <textarea />?
1657 $wgOut->addHtml( Xml::openElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . Xml::closeElement( 'textarea' ) );
1662 * Produce the stock "please login to edit pages" page
1664 function userNotLoggedInPage() {
1665 global $wgUser, $wgOut, $wgTitle;
1666 $skin = $wgUser->getSkin();
1668 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1669 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1671 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1672 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1673 $wgOut->setArticleRelated( false );
1675 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1676 $wgOut->returnToMain( false, $wgTitle );
1680 * Creates a basic error page which informs the user that
1681 * they have attempted to edit a nonexistant section.
1683 function noSuchSectionPage() {
1684 global $wgOut, $wgTitle;
1686 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1687 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1688 $wgOut->setArticleRelated( false );
1690 $wgOut->addWikiMsg( 'nosuchsectiontext', $this->section );
1691 $wgOut->returnToMain( false, $wgTitle );
1695 * Produce the stock "your edit contains spam" page
1697 * @param $match Text which triggered one or more filters
1699 function spamPage( $match = false ) {
1700 global $wgOut, $wgTitle;
1702 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1703 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1704 $wgOut->setArticleRelated( false );
1706 $wgOut->addHtml( '<div id="spamprotected">' );
1707 $wgOut->addWikiMsg( 'spamprotectiontext' );
1708 if ( $match )
1709 $wgOut->addWikiMsg( 'spamprotectionmatch', wfEscapeWikiText( $match ) );
1710 $wgOut->addHtml( '</div>' );
1712 $wgOut->returnToMain( false, $wgTitle );
1716 * @private
1717 * @todo document
1719 function mergeChangesInto( &$editText ){
1720 $fname = 'EditPage::mergeChangesInto';
1721 wfProfileIn( $fname );
1723 $db = wfGetDB( DB_MASTER );
1725 // This is the revision the editor started from
1726 $baseRevision = $this->getBaseRevision();
1727 if( is_null( $baseRevision ) ) {
1728 wfProfileOut( $fname );
1729 return false;
1731 $baseText = $baseRevision->getText();
1733 // The current state, we want to merge updates into it
1734 $currentRevision = Revision::loadFromTitle(
1735 $db, $this->mTitle );
1736 if( is_null( $currentRevision ) ) {
1737 wfProfileOut( $fname );
1738 return false;
1740 $currentText = $currentRevision->getText();
1742 $result = '';
1743 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1744 $editText = $result;
1745 wfProfileOut( $fname );
1746 return true;
1747 } else {
1748 wfProfileOut( $fname );
1749 return false;
1754 * Check if the browser is on a blacklist of user-agents known to
1755 * mangle UTF-8 data on form submission. Returns true if Unicode
1756 * should make it through, false if it's known to be a problem.
1757 * @return bool
1758 * @private
1760 function checkUnicodeCompliantBrowser() {
1761 global $wgBrowserBlackList;
1762 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1763 // No User-Agent header sent? Trust it by default...
1764 return true;
1766 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1767 foreach ( $wgBrowserBlackList as $browser ) {
1768 if ( preg_match($browser, $currentbrowser) ) {
1769 return false;
1772 return true;
1776 * @deprecated use $wgParser->stripSectionName()
1778 function pseudoParseSectionAnchor( $text ) {
1779 global $wgParser;
1780 return $wgParser->stripSectionName( $text );
1784 * Format an anchor fragment as it would appear for a given section name
1785 * @param string $text
1786 * @return string
1787 * @private
1789 function sectionAnchor( $text ) {
1790 global $wgParser;
1791 return $wgParser->guessSectionNameFromWikiText( $text );
1795 * Shows a bulletin board style toolbar for common editing functions.
1796 * It can be disabled in the user preferences.
1797 * The necessary JavaScript code can be found in skins/common/edit.js.
1799 * @return string
1801 static function getEditToolbar() {
1802 global $wgStylePath, $wgContLang, $wgLang, $wgJsMimeType;
1805 * toolarray an array of arrays which each include the filename of
1806 * the button image (without path), the opening tag, the closing tag,
1807 * and optionally a sample text that is inserted between the two when no
1808 * selection is highlighted.
1809 * The tip text is shown when the user moves the mouse over the button.
1811 * Already here are accesskeys (key), which are not used yet until someone
1812 * can figure out a way to make them work in IE. However, we should make
1813 * sure these keys are not defined on the edit page.
1815 $toolarray = array(
1816 array(
1817 'image' => $wgLang->getImageFile('button-bold'),
1818 'id' => 'mw-editbutton-bold',
1819 'open' => '\'\'\'',
1820 'close' => '\'\'\'',
1821 'sample' => wfMsg('bold_sample'),
1822 'tip' => wfMsg('bold_tip'),
1823 'key' => 'B'
1825 array(
1826 'image' => $wgLang->getImageFile('button-italic'),
1827 'id' => 'mw-editbutton-italic',
1828 'open' => '\'\'',
1829 'close' => '\'\'',
1830 'sample' => wfMsg('italic_sample'),
1831 'tip' => wfMsg('italic_tip'),
1832 'key' => 'I'
1834 array(
1835 'image' => $wgLang->getImageFile('button-link'),
1836 'id' => 'mw-editbutton-link',
1837 'open' => '[[',
1838 'close' => ']]',
1839 'sample' => wfMsg('link_sample'),
1840 'tip' => wfMsg('link_tip'),
1841 'key' => 'L'
1843 array(
1844 'image' => $wgLang->getImageFile('button-extlink'),
1845 'id' => 'mw-editbutton-extlink',
1846 'open' => '[',
1847 'close' => ']',
1848 'sample' => wfMsg('extlink_sample'),
1849 'tip' => wfMsg('extlink_tip'),
1850 'key' => 'X'
1852 array(
1853 'image' => $wgLang->getImageFile('button-headline'),
1854 'id' => 'mw-editbutton-headline',
1855 'open' => "\n== ",
1856 'close' => " ==\n",
1857 'sample' => wfMsg('headline_sample'),
1858 'tip' => wfMsg('headline_tip'),
1859 'key' => 'H'
1861 array(
1862 'image' => $wgLang->getImageFile('button-image'),
1863 'id' => 'mw-editbutton-image',
1864 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).':',
1865 'close' => ']]',
1866 'sample' => wfMsg('image_sample'),
1867 'tip' => wfMsg('image_tip'),
1868 'key' => 'D'
1870 array(
1871 'image' => $wgLang->getImageFile('button-media'),
1872 'id' => 'mw-editbutton-media',
1873 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1874 'close' => ']]',
1875 'sample' => wfMsg('media_sample'),
1876 'tip' => wfMsg('media_tip'),
1877 'key' => 'M'
1879 array(
1880 'image' => $wgLang->getImageFile('button-math'),
1881 'id' => 'mw-editbutton-math',
1882 'open' => "<math>",
1883 'close' => "</math>",
1884 'sample' => wfMsg('math_sample'),
1885 'tip' => wfMsg('math_tip'),
1886 'key' => 'C'
1888 array(
1889 'image' => $wgLang->getImageFile('button-nowiki'),
1890 'id' => 'mw-editbutton-nowiki',
1891 'open' => "<nowiki>",
1892 'close' => "</nowiki>",
1893 'sample' => wfMsg('nowiki_sample'),
1894 'tip' => wfMsg('nowiki_tip'),
1895 'key' => 'N'
1897 array(
1898 'image' => $wgLang->getImageFile('button-sig'),
1899 'id' => 'mw-editbutton-signature',
1900 'open' => '--~~~~',
1901 'close' => '',
1902 'sample' => '',
1903 'tip' => wfMsg('sig_tip'),
1904 'key' => 'Y'
1906 array(
1907 'image' => $wgLang->getImageFile('button-hr'),
1908 'id' => 'mw-editbutton-hr',
1909 'open' => "\n----\n",
1910 'close' => '',
1911 'sample' => '',
1912 'tip' => wfMsg('hr_tip'),
1913 'key' => 'R'
1916 $toolbar = "<div id='toolbar'>\n";
1917 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1919 foreach($toolarray as $tool) {
1920 $params = array(
1921 $image = $wgStylePath.'/common/images/'.$tool['image'],
1922 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1923 // Older browsers show a "speedtip" type message only for ALT.
1924 // Ideally these should be different, realistically they
1925 // probably don't need to be.
1926 $tip = $tool['tip'],
1927 $open = $tool['open'],
1928 $close = $tool['close'],
1929 $sample = $tool['sample'],
1930 $cssId = $tool['id'],
1933 $paramList = implode( ',',
1934 array_map( array( 'Xml', 'encodeJsVar' ), $params ) );
1935 $toolbar.="addButton($paramList);\n";
1938 $toolbar.="/*]]>*/\n</script>";
1939 $toolbar.="\n</div>";
1940 return $toolbar;
1944 * Returns an array of html code of the following checkboxes:
1945 * minor and watch
1947 * @param $tabindex Current tabindex
1948 * @param $skin Skin object
1949 * @param $checked Array of checkbox => bool, where bool indicates the checked
1950 * status of the checkbox
1952 * @return array
1954 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1955 global $wgUser;
1957 $checkboxes = array();
1959 $checkboxes['minor'] = '';
1960 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1961 if ( $wgUser->isAllowed('minoredit') ) {
1962 $attribs = array(
1963 'tabindex' => ++$tabindex,
1964 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1965 'id' => 'wpMinoredit',
1967 $checkboxes['minor'] =
1968 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1969 "&nbsp;<label for='wpMinoredit'".$skin->tooltip('minoredit').">{$minorLabel}</label>";
1972 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1973 $checkboxes['watch'] = '';
1974 if ( $wgUser->isLoggedIn() ) {
1975 $attribs = array(
1976 'tabindex' => ++$tabindex,
1977 'accesskey' => wfMsg( 'accesskey-watch' ),
1978 'id' => 'wpWatchthis',
1980 $checkboxes['watch'] =
1981 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1982 "&nbsp;<label for='wpWatchthis'".$skin->tooltip('watch').">{$watchLabel}</label>";
1984 return $checkboxes;
1988 * Returns an array of html code of the following buttons:
1989 * save, diff, preview and live
1991 * @param $tabindex Current tabindex
1993 * @return array
1995 public function getEditButtons(&$tabindex) {
1996 global $wgLivePreview, $wgUser;
1998 $buttons = array();
2000 $temp = array(
2001 'id' => 'wpSave',
2002 'name' => 'wpSave',
2003 'type' => 'submit',
2004 'tabindex' => ++$tabindex,
2005 'value' => wfMsg('savearticle'),
2006 'accesskey' => wfMsg('accesskey-save'),
2007 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
2009 $buttons['save'] = Xml::element('input', $temp, '');
2011 ++$tabindex; // use the same for preview and live preview
2012 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
2013 $temp = array(
2014 'id' => 'wpPreview',
2015 'name' => 'wpPreview',
2016 'type' => 'submit',
2017 'tabindex' => $tabindex,
2018 'value' => wfMsg('showpreview'),
2019 'accesskey' => '',
2020 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2021 'style' => 'display: none;',
2023 $buttons['preview'] = Xml::element('input', $temp, '');
2025 $temp = array(
2026 'id' => 'wpLivePreview',
2027 'name' => 'wpLivePreview',
2028 'type' => 'submit',
2029 'tabindex' => $tabindex,
2030 'value' => wfMsg('showlivepreview'),
2031 'accesskey' => wfMsg('accesskey-preview'),
2032 'title' => '',
2033 'onclick' => $this->doLivePreviewScript(),
2035 $buttons['live'] = Xml::element('input', $temp, '');
2036 } else {
2037 $temp = array(
2038 'id' => 'wpPreview',
2039 'name' => 'wpPreview',
2040 'type' => 'submit',
2041 'tabindex' => $tabindex,
2042 'value' => wfMsg('showpreview'),
2043 'accesskey' => wfMsg('accesskey-preview'),
2044 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
2046 $buttons['preview'] = Xml::element('input', $temp, '');
2047 $buttons['live'] = '';
2050 $temp = array(
2051 'id' => 'wpDiff',
2052 'name' => 'wpDiff',
2053 'type' => 'submit',
2054 'tabindex' => ++$tabindex,
2055 'value' => wfMsg('showdiff'),
2056 'accesskey' => wfMsg('accesskey-diff'),
2057 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
2059 $buttons['diff'] = Xml::element('input', $temp, '');
2061 wfRunHooks( 'EditPageBeforeEditButtons', array( &$this, &$buttons ) );
2062 return $buttons;
2066 * Output preview text only. This can be sucked into the edit page
2067 * via JavaScript, and saves the server time rendering the skin as
2068 * well as theoretically being more robust on the client (doesn't
2069 * disturb the edit box's undo history, won't eat your text on
2070 * failure, etc).
2072 * @todo This doesn't include category or interlanguage links.
2073 * Would need to enhance it a bit, <s>maybe wrap them in XML
2074 * or something...</s> that might also require more skin
2075 * initialization, so check whether that's a problem.
2077 function livePreview() {
2078 global $wgOut;
2079 $wgOut->disable();
2080 header( 'Content-type: text/xml; charset=utf-8' );
2081 header( 'Cache-control: no-cache' );
2083 $previewText = $this->getPreviewText();
2084 #$categories = $skin->getCategoryLinks();
2086 $s =
2087 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
2088 Xml::tags( 'livepreview', null,
2089 Xml::element( 'preview', null, $previewText )
2090 #. Xml::element( 'category', null, $categories )
2092 echo $s;
2097 * Get a diff between the current contents of the edit box and the
2098 * version of the page we're editing from.
2100 * If this is a section edit, we'll replace the section as for final
2101 * save and then make a comparison.
2103 function showDiff() {
2104 $oldtext = $this->mArticle->fetchContent();
2105 $newtext = $this->mArticle->replaceSection(
2106 $this->section, $this->textbox1, $this->summary, $this->edittime );
2107 $newtext = $this->mArticle->preSaveTransform( $newtext );
2108 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
2109 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2110 if ( $oldtext !== false || $newtext != '' ) {
2111 $de = new DifferenceEngine( $this->mTitle );
2112 $de->setText( $oldtext, $newtext );
2113 $difftext = $de->getDiff( $oldtitle, $newtitle );
2114 $de->showDiffStyle();
2115 } else {
2116 $difftext = '';
2119 global $wgOut;
2120 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
2124 * Filter an input field through a Unicode de-armoring process if it
2125 * came from an old browser with known broken Unicode editing issues.
2127 * @param WebRequest $request
2128 * @param string $field
2129 * @return string
2130 * @private
2132 function safeUnicodeInput( $request, $field ) {
2133 $text = rtrim( $request->getText( $field ) );
2134 return $request->getBool( 'safemode' )
2135 ? $this->unmakesafe( $text )
2136 : $text;
2140 * Filter an output field through a Unicode armoring process if it is
2141 * going to an old browser with known broken Unicode editing issues.
2143 * @param string $text
2144 * @return string
2145 * @private
2147 function safeUnicodeOutput( $text ) {
2148 global $wgContLang;
2149 $codedText = $wgContLang->recodeForEdit( $text );
2150 return $this->checkUnicodeCompliantBrowser()
2151 ? $codedText
2152 : $this->makesafe( $codedText );
2156 * A number of web browsers are known to corrupt non-ASCII characters
2157 * in a UTF-8 text editing environment. To protect against this,
2158 * detected browsers will be served an armored version of the text,
2159 * with non-ASCII chars converted to numeric HTML character references.
2161 * Preexisting such character references will have a 0 added to them
2162 * to ensure that round-trips do not alter the original data.
2164 * @param string $invalue
2165 * @return string
2166 * @private
2168 function makesafe( $invalue ) {
2169 // Armor existing references for reversability.
2170 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2172 $bytesleft = 0;
2173 $result = "";
2174 $working = 0;
2175 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2176 $bytevalue = ord( $invalue{$i} );
2177 if( $bytevalue <= 0x7F ) { //0xxx xxxx
2178 $result .= chr( $bytevalue );
2179 $bytesleft = 0;
2180 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
2181 $working = $working << 6;
2182 $working += ($bytevalue & 0x3F);
2183 $bytesleft--;
2184 if( $bytesleft <= 0 ) {
2185 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2187 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
2188 $working = $bytevalue & 0x1F;
2189 $bytesleft = 1;
2190 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
2191 $working = $bytevalue & 0x0F;
2192 $bytesleft = 2;
2193 } else { //1111 0xxx
2194 $working = $bytevalue & 0x07;
2195 $bytesleft = 3;
2198 return $result;
2202 * Reverse the previously applied transliteration of non-ASCII characters
2203 * back to UTF-8. Used to protect data from corruption by broken web browsers
2204 * as listed in $wgBrowserBlackList.
2206 * @param string $invalue
2207 * @return string
2208 * @private
2210 function unmakesafe( $invalue ) {
2211 $result = "";
2212 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2213 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
2214 $i += 3;
2215 $hexstring = "";
2216 do {
2217 $hexstring .= $invalue{$i};
2218 $i++;
2219 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2221 // Do some sanity checks. These aren't needed for reversability,
2222 // but should help keep the breakage down if the editor
2223 // breaks one of the entities whilst editing.
2224 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2225 $codepoint = hexdec($hexstring);
2226 $result .= codepointToUtf8( $codepoint );
2227 } else {
2228 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2230 } else {
2231 $result .= substr( $invalue, $i, 1 );
2234 // reverse the transform that we made for reversability reasons.
2235 return strtr( $result, array( "&#x0" => "&#x" ) );
2238 function noCreatePermission() {
2239 global $wgOut;
2240 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2241 $wgOut->addWikiMsg( 'nocreatetext' );
2245 * If there are rows in the deletion log for this page, show them,
2246 * along with a nice little note for the user
2248 * @param OutputPage $out
2250 protected function showDeletionLog( $out ) {
2251 global $wgUser;
2252 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
2253 $pager = new LogPager( $loglist, 'delete', false, $this->mTitle->getPrefixedText() );
2254 if( $pager->getNumRows() > 0 ) {
2255 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2256 $out->addWikiMsg( 'recreate-deleted-warn' );
2257 $out->addHTML(
2258 $loglist->beginLogEventsList() .
2259 $pager->getBody() .
2260 $loglist->endLogEventsList()
2262 $out->addHtml( '</div>' );
2267 * Attempt submission
2268 * @return bool false if output is done, true if the rest of the form should be displayed
2270 function attemptSave() {
2271 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2273 $resultDetails = false;
2274 $value = $this->internalAttemptSave( $resultDetails, $wgUser->isAllowed('bot') && $wgRequest->getBool('bot', true) );
2276 if( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
2277 $this->didSave = true;
2280 switch ($value) {
2281 case self::AS_HOOK_ERROR_EXPECTED:
2282 case self::AS_CONTENT_TOO_BIG:
2283 case self::AS_ARTICLE_WAS_DELETED:
2284 case self::AS_CONFLICT_DETECTED:
2285 case self::AS_SUMMARY_NEEDED:
2286 case self::AS_TEXTBOX_EMPTY:
2287 case self::AS_MAX_ARTICLE_SIZE_EXCEEDED:
2288 case self::AS_END:
2289 return true;
2291 case self::AS_HOOK_ERROR:
2292 case self::AS_FILTERING:
2293 case self::AS_SUCCESS_NEW_ARTICLE:
2294 case self::AS_SUCCESS_UPDATE:
2295 return false;
2297 case self::AS_SPAM_ERROR:
2298 $this->spamPage ( $resultDetails['spam'] );
2299 return false;
2301 case self::AS_BLOCKED_PAGE_FOR_USER:
2302 $this->blockedPage();
2303 return false;
2305 case self::AS_IMAGE_REDIRECT_ANON:
2306 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
2307 return false;
2309 case self::AS_READ_ONLY_PAGE_ANON:
2310 $this->userNotLoggedInPage();
2311 return false;
2313 case self::AS_READ_ONLY_PAGE_LOGGED:
2314 case self::AS_READ_ONLY_PAGE:
2315 $wgOut->readOnlyPage();
2316 return false;
2318 case self::AS_RATE_LIMITED:
2319 $wgOut->rateLimited();
2320 return false;
2322 case self::AS_NO_CREATE_PERMISSION;
2323 $this->noCreatePermission();
2324 return;
2326 case self::AS_BLANK_ARTICLE:
2327 $wgOut->redirect( $wgTitle->getFullURL() );
2328 return false;
2330 case self::AS_IMAGE_REDIRECT_LOGGED:
2331 $wgOut->permissionRequired( 'upload' );
2332 return false;
2336 function getBaseRevision() {
2337 if ($this->mBaseRevision == false) {
2338 $db = wfGetDB( DB_MASTER );
2339 $baseRevision = Revision::loadFromTimestamp(
2340 $db, $this->mTitle, $this->edittime );
2341 return $this->mBaseRevision = $baseRevision;
2342 } else {
2343 return $this->mBaseRevision;