*Call OutputPageBeforeHTML on preview (bug 7050)
[mediawiki.git] / includes / EditPage.php
blobf244b3928cc00f7812a74577c632acd2d6fe6e31
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 class EditPage {
13 var $mArticle;
14 var $mTitle;
15 var $mMetaData = '';
16 var $isConflict = false;
17 var $isCssJsSubpage = false;
18 var $deletedSinceEdit = false;
19 var $formtype;
20 var $firsttime;
21 var $lastDelete;
22 var $mTokenOk = false;
23 var $mTokenOkExceptSuffix = false;
24 var $mTriedSave = false;
25 var $tooBig = false;
26 var $kblength = false;
27 var $missingComment = false;
28 var $missingSummary = false;
29 var $allowBlankSummary = false;
30 var $autoSumm = '';
31 var $hookError = '';
32 var $mPreviewTemplates;
34 # Form values
35 var $save = false, $preview = false, $diff = false;
36 var $minoredit = false, $watchthis = false, $recreate = false;
37 var $textbox1 = '', $textbox2 = '', $summary = '';
38 var $edittime = '', $section = '', $starttime = '';
39 var $oldid = 0, $editintro = '', $scrolltop = null;
41 # Placeholders for text injection by hooks (must be HTML)
42 # extensions should take care to _append_ to the present value
43 public $editFormPageTop; // Before even the preview
44 public $editFormTextTop;
45 public $editFormTextAfterWarn;
46 public $editFormTextAfterTools;
47 public $editFormTextBottom;
49 /**
50 * @todo document
51 * @param $article
53 function EditPage( $article ) {
54 $this->mArticle =& $article;
55 global $wgTitle;
56 $this->mTitle =& $wgTitle;
58 # Placeholders for text injection by hooks (empty per default)
59 $this->editFormPageTop =
60 $this->editFormTextTop =
61 $this->editFormTextAfterWarn =
62 $this->editFormTextAfterTools =
63 $this->editFormTextBottom = "";
66 /**
67 * Fetch initial editing page content.
69 private function getContent( $def_text = '' ) {
70 global $wgOut, $wgRequest, $wgParser;
72 # Get variables from query string :P
73 $section = $wgRequest->getVal( 'section' );
74 $preload = $wgRequest->getVal( 'preload' );
75 $undoafter = $wgRequest->getVal( 'undoafter' );
76 $undo = $wgRequest->getVal( 'undo' );
78 wfProfileIn( __METHOD__ );
80 $text = '';
81 if( !$this->mTitle->exists() ) {
82 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
83 # If this is a system message, get the default text.
84 $text = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
85 } else {
86 # If requested, preload some text.
87 $text = $this->getPreloadedText( $preload );
89 # We used to put MediaWiki:Newarticletext here if
90 # $text was empty at this point.
91 # This is now shown above the edit box instead.
92 } else {
93 // FIXME: may be better to use Revision class directly
94 // But don't mess with it just yet. Article knows how to
95 // fetch the page record from the high-priority server,
96 // which is needed to guarantee we don't pick up lagged
97 // information.
99 $text = $this->mArticle->getContent();
101 if ($undo > 0 && $undoafter > 0 && $undo < $undoafter) {
102 # If they got undoafter and undo round the wrong way, switch them
103 list( $undo, $undoafter ) = array( $undoafter, $undo );
106 if ( $undo > 0 && $undo > $undoafter ) {
107 # Undoing a specific edit overrides section editing; section-editing
108 # doesn't work with undoing.
109 if ( $undoafter ) {
110 $undorev = Revision::newFromId($undo);
111 $oldrev = Revision::newFromId($undoafter);
112 } else {
113 $undorev = Revision::newFromId($undo);
114 $oldrev = $undorev ? $undorev->getPrevious() : null;
117 #Sanity check, make sure it's the right page.
118 # Otherwise, $text will be left as-is.
119 if ( !is_null($undorev) && !is_null($oldrev) && $undorev->getPage()==$oldrev->getPage() && $undorev->getPage()==$this->mArticle->getID() ) {
120 $undorev_text = $undorev->getText();
121 $oldrev_text = $oldrev->getText();
122 $currev_text = $text;
124 #No use doing a merge if it's just a straight revert.
125 if ( $currev_text != $undorev_text ) {
126 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
127 } else {
128 $text = $oldrev_text;
129 $result = true;
131 } else {
132 // Failed basic sanity checks.
133 // Older revisions may have been removed since the link
134 // was created, or we may simply have got bogus input.
135 $result = false;
138 if( $result ) {
139 # Inform the user of our success and set an automatic edit summary
140 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
141 $firstrev = $oldrev->getNext();
142 # If we just undid one rev, use an autosummary
143 if ( $firstrev->mId == $undo ) {
144 $this->summary = wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
146 $this->formtype = 'diff';
147 } else {
148 # Warn the user that something went wrong
149 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
151 } else if( $section != '' ) {
152 if( $section == 'new' ) {
153 $text = $this->getPreloadedText( $preload );
154 } else {
155 $text = $wgParser->getSection( $text, $section, $def_text );
160 wfProfileOut( __METHOD__ );
161 return $text;
165 * Get the contents of a page from its title and remove includeonly tags
167 * @param $preload String: the title of the page.
168 * @return string The contents of the page.
170 private function getPreloadedText($preload) {
171 if ( $preload === '' )
172 return '';
173 else {
174 $preloadTitle = Title::newFromText( $preload );
175 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
176 $rev=Revision::newFromTitle($preloadTitle);
177 if ( is_object( $rev ) ) {
178 $text = $rev->getText();
179 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
180 // its own mini-parser! -ævar
181 $text = preg_replace( '~</?includeonly>~', '', $text );
182 return $text;
183 } else
184 return '';
190 * This is the function that extracts metadata from the article body on the first view.
191 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
192 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
194 function extractMetaDataFromArticle () {
195 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
196 $this->mMetaData = '' ;
197 if ( !$wgUseMetadataEdit ) return ;
198 if ( $wgMetadataWhitelist == '' ) return ;
199 $s = '' ;
200 $t = $this->getContent();
202 # MISSING : <nowiki> filtering
204 # Categories and language links
205 $t = explode ( "\n" , $t ) ;
206 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
207 $cat = $ll = array() ;
208 foreach ( $t AS $key => $x )
210 $y = trim ( strtolower ( $x ) ) ;
211 while ( substr ( $y , 0 , 2 ) == '[[' )
213 $y = explode ( ']]' , trim ( $x ) ) ;
214 $first = array_shift ( $y ) ;
215 $first = explode ( ':' , $first ) ;
216 $ns = array_shift ( $first ) ;
217 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
218 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
220 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
221 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
222 else $ll[] = $add ;
223 $x = implode ( ']]' , $y ) ;
224 $t[$key] = $x ;
225 $y = trim ( strtolower ( $x ) ) ;
229 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
230 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
231 $t = implode ( "\n" , $t ) ;
233 # Load whitelist
234 $sat = array () ; # stand-alone-templates; must be lowercase
235 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
236 $wl_article = new Article ( $wl_title ) ;
237 $wl = explode ( "\n" , $wl_article->getContent() ) ;
238 foreach ( $wl AS $x )
240 $isentry = false ;
241 $x = trim ( $x ) ;
242 while ( substr ( $x , 0 , 1 ) == '*' )
244 $isentry = true ;
245 $x = trim ( substr ( $x , 1 ) ) ;
247 if ( $isentry )
249 $sat[] = strtolower ( $x ) ;
254 # Templates, but only some
255 $t = explode ( '{{' , $t ) ;
256 $tl = array () ;
257 foreach ( $t AS $key => $x )
259 $y = explode ( '}}' , $x , 2 ) ;
260 if ( count ( $y ) == 2 )
262 $z = $y[0] ;
263 $z = explode ( '|' , $z ) ;
264 $tn = array_shift ( $z ) ;
265 if ( in_array ( strtolower ( $tn ) , $sat ) )
267 $tl[] = '{{' . $y[0] . '}}' ;
268 $t[$key] = $y[1] ;
269 $y = explode ( '}}' , $y[1] , 2 ) ;
271 else $t[$key] = '{{' . $x ;
273 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
274 else $t[$key] = $x ;
276 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
277 $t = implode ( '' , $t ) ;
279 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
280 $this->mArticle->mContent = $t ;
281 $this->mMetaData = $s ;
284 function submit() {
285 $this->edit();
289 * This is the function that gets called for "action=edit". It
290 * sets up various member variables, then passes execution to
291 * another function, usually showEditForm()
293 * The edit form is self-submitting, so that when things like
294 * preview and edit conflicts occur, we get the same form back
295 * with the extra stuff added. Only when the final submission
296 * is made and all is well do we actually save and redirect to
297 * the newly-edited page.
299 function edit() {
300 global $wgOut, $wgUser, $wgRequest, $wgTitle;
302 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
303 return;
305 $fname = 'EditPage::edit';
306 wfProfileIn( $fname );
307 wfDebug( "$fname: enter\n" );
309 // this is not an article
310 $wgOut->setArticleFlag(false);
312 $this->importFormData( $wgRequest );
313 $this->firsttime = false;
315 if( $this->live ) {
316 $this->livePreview();
317 wfProfileOut( $fname );
318 return;
321 $permErrors = $this->mTitle->getUserPermissionsErrors( 'edit', $wgUser);
323 # Ignore some permissions errors.
324 $remove = array();
325 foreach( $permErrors as $error ) {
326 if ($this->preview || $this->diff &&
327 ($error[0] == 'blockedtext' || $error[0] == 'autoblockedtext'))
329 // Don't worry about blocks when previewing/diffing
330 $remove[] = $error;
333 if ($error[0] == 'readonlytext')
335 if ($this->edit) {
336 $this->formtype = 'preview';
337 } elseif ($this->save || $this->preview || $this->diff) {
338 $remove[] = $error;
342 # array_diff returns elements in $permErrors that are not in $remove.
343 $permErrors = array_diff( $permErrors, $remove );
345 if ($permErrors != array())
347 wfDebug( "$fname: User can't edit\n" );
348 $wgOut->readOnlyPage( $this->getContent(), true, $permErrors );
349 wfProfileOut( $fname );
350 return;
351 } else {
352 if ( $this->save ) {
353 $this->formtype = 'save';
354 } else if ( $this->preview ) {
355 $this->formtype = 'preview';
356 } else if ( $this->diff ) {
357 $this->formtype = 'diff';
358 } else { # First time through
359 $this->firsttime = true;
360 if( $this->previewOnOpen() ) {
361 $this->formtype = 'preview';
362 } else {
363 $this->extractMetaDataFromArticle () ;
364 $this->formtype = 'initial';
369 wfProfileIn( "$fname-business-end" );
371 $this->isConflict = false;
372 // css / js subpages of user pages get a special treatment
373 $this->isCssJsSubpage = $wgTitle->isCssJsSubpage();
374 $this->isValidCssJsSubpage = $wgTitle->isValidCssJsSubpage();
376 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
377 * no matter it's current state
379 $this->deletedSinceEdit = false;
380 if ( $this->edittime != '' ) {
381 /* Note that we rely on logging table, which hasn't been always there,
382 * but that doesn't matter, because this only applies to brand new
383 * deletes. This is done on every preview and save request. Move it further down
384 * to only perform it on saves
386 if ( $this->mTitle->isDeleted() ) {
387 $this->lastDelete = $this->getLastDelete();
388 if ( !is_null($this->lastDelete) ) {
389 $deletetime = $this->lastDelete->log_timestamp;
390 if ( ($deletetime - $this->starttime) > 0 ) {
391 $this->deletedSinceEdit = true;
397 # Show applicable editing introductions
398 if( $this->formtype == 'initial' || $this->firsttime )
399 $this->showIntro();
401 if( $this->mTitle->isTalkPage() ) {
402 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
405 # Attempt submission here. This will check for edit conflicts,
406 # and redundantly check for locked database, blocked IPs, etc.
407 # that edit() already checked just in case someone tries to sneak
408 # in the back door with a hand-edited submission URL.
410 if ( 'save' == $this->formtype ) {
411 if ( !$this->attemptSave() ) {
412 wfProfileOut( "$fname-business-end" );
413 wfProfileOut( $fname );
414 return;
418 # First time through: get contents, set time for conflict
419 # checking, etc.
420 if ( 'initial' == $this->formtype || $this->firsttime ) {
421 if ($this->initialiseForm() === false) {
422 $this->noSuchSectionPage();
423 wfProfileOut( "$fname-business-end" );
424 wfProfileOut( $fname );
425 return;
427 if( !$this->mTitle->getArticleId() )
428 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
431 $this->showEditForm();
432 wfProfileOut( "$fname-business-end" );
433 wfProfileOut( $fname );
437 * Should we show a preview when the edit form is first shown?
439 * @return bool
441 private function previewOnOpen() {
442 global $wgRequest, $wgUser;
443 if( $wgRequest->getVal( 'preview' ) == 'yes' ) {
444 // Explicit override from request
445 return true;
446 } elseif( $wgRequest->getVal( 'preview' ) == 'no' ) {
447 // Explicit override from request
448 return false;
449 } elseif( $this->section == 'new' ) {
450 // Nothing *to* preview for new sections
451 return false;
452 } elseif( ( $wgRequest->getVal( 'preload' ) !== '' || $this->mTitle->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
453 // Standard preference behaviour
454 return true;
455 } elseif( !$this->mTitle->exists() && $this->mTitle->getNamespace() == NS_CATEGORY ) {
456 // Categories are special
457 return true;
458 } else {
459 return false;
464 * @todo document
465 * @param $request
467 function importFormData( &$request ) {
468 global $wgLang, $wgUser;
469 $fname = 'EditPage::importFormData';
470 wfProfileIn( $fname );
472 if( $request->wasPosted() ) {
473 # These fields need to be checked for encoding.
474 # Also remove trailing whitespace, but don't remove _initial_
475 # whitespace from the text boxes. This may be significant formatting.
476 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
477 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
478 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
479 # Truncate for whole multibyte characters. +5 bytes for ellipsis
480 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
482 $this->edittime = $request->getVal( 'wpEdittime' );
483 $this->starttime = $request->getVal( 'wpStarttime' );
485 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
487 if( is_null( $this->edittime ) ) {
488 # If the form is incomplete, force to preview.
489 wfDebug( "$fname: Form data appears to be incomplete\n" );
490 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
491 $this->preview = true;
492 } else {
493 /* Fallback for live preview */
494 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
495 $this->diff = $request->getCheck( 'wpDiff' );
497 // Remember whether a save was requested, so we can indicate
498 // if we forced preview due to session failure.
499 $this->mTriedSave = !$this->preview;
501 if ( $this->tokenOk( $request ) ) {
502 # Some browsers will not report any submit button
503 # if the user hits enter in the comment box.
504 # The unmarked state will be assumed to be a save,
505 # if the form seems otherwise complete.
506 wfDebug( "$fname: Passed token check.\n" );
507 } else if ( $this->diff ) {
508 # Failed token check, but only requested "Show Changes".
509 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
510 } else {
511 # Page might be a hack attempt posted from
512 # an external site. Preview instead of saving.
513 wfDebug( "$fname: Failed token check; forcing preview\n" );
514 $this->preview = true;
517 $this->save = ! ( $this->preview OR $this->diff );
518 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
519 $this->edittime = null;
522 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
523 $this->starttime = null;
526 $this->recreate = $request->getCheck( 'wpRecreate' );
528 $this->minoredit = $request->getCheck( 'wpMinoredit' );
529 $this->watchthis = $request->getCheck( 'wpWatchthis' );
531 # Don't force edit summaries when a user is editing their own user or talk page
532 if( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) && $this->mTitle->getText() == $wgUser->getName() ) {
533 $this->allowBlankSummary = true;
534 } else {
535 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
538 $this->autoSumm = $request->getText( 'wpAutoSummary' );
539 } else {
540 # Not a posted form? Start with nothing.
541 wfDebug( "$fname: Not a posted form.\n" );
542 $this->textbox1 = '';
543 $this->textbox2 = '';
544 $this->mMetaData = '';
545 $this->summary = '';
546 $this->edittime = '';
547 $this->starttime = wfTimestampNow();
548 $this->edit = false;
549 $this->preview = false;
550 $this->save = false;
551 $this->diff = false;
552 $this->minoredit = false;
553 $this->watchthis = false;
554 $this->recreate = false;
557 $this->oldid = $request->getInt( 'oldid' );
559 # Section edit can come from either the form or a link
560 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
562 $this->live = $request->getCheck( 'live' );
563 $this->editintro = $request->getText( 'editintro' );
565 wfProfileOut( $fname );
569 * Make sure the form isn't faking a user's credentials.
571 * @param $request WebRequest
572 * @return bool
573 * @private
575 function tokenOk( &$request ) {
576 global $wgUser;
577 $token = $request->getVal( 'wpEditToken' );
578 $this->mTokenOk = $wgUser->matchEditToken( $token );
579 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
580 return $this->mTokenOk;
584 * Show all applicable editing introductions
586 private function showIntro() {
587 global $wgOut, $wgUser;
588 if( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
589 if( $wgUser->isLoggedIn() ) {
590 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
591 } else {
592 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
594 $this->showDeletionLog( $wgOut );
599 * Attempt to show a custom editing introduction, if supplied
601 * @return bool
603 private function showCustomIntro() {
604 if( $this->editintro ) {
605 $title = Title::newFromText( $this->editintro );
606 if( $title instanceof Title && $title->exists() && $title->userCanRead() ) {
607 global $wgOut;
608 $revision = Revision::newFromTitle( $title );
609 $wgOut->addSecondaryWikiText( $revision->getText() );
610 return true;
611 } else {
612 return false;
614 } else {
615 return false;
620 * Attempt submission
621 * @return bool false if output is done, true if the rest of the form should be displayed
623 function attemptSave() {
624 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
625 global $wgMaxArticleSize;
627 $fname = 'EditPage::attemptSave';
628 wfProfileIn( $fname );
629 wfProfileIn( "$fname-checks" );
631 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
633 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
634 return false;
637 # Reintegrate metadata
638 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
639 $this->mMetaData = '' ;
641 # Check for spam
642 $matches = array();
643 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
644 $this->spamPage ( $matches[0] );
645 wfProfileOut( "$fname-checks" );
646 wfProfileOut( $fname );
647 return false;
649 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
650 # Error messages or other handling should be performed by the filter function
651 wfProfileOut( $fname );
652 wfProfileOut( "$fname-checks" );
653 return false;
655 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError ) ) ) {
656 # Error messages etc. could be handled within the hook...
657 wfProfileOut( $fname );
658 wfProfileOut( "$fname-checks" );
659 return false;
660 } elseif( $this->hookError != '' ) {
661 # ...or the hook could be expecting us to produce an error
662 wfProfileOut( "$fname-checks " );
663 wfProfileOut( $fname );
664 return true;
666 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
667 # Check block state against master, thus 'false'.
668 $this->blockedPage();
669 wfProfileOut( "$fname-checks" );
670 wfProfileOut( $fname );
671 return false;
673 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
674 if ( $this->kblength > $wgMaxArticleSize ) {
675 // Error will be displayed by showEditForm()
676 $this->tooBig = true;
677 wfProfileOut( "$fname-checks" );
678 wfProfileOut( $fname );
679 return true;
682 if ( !$wgUser->isAllowed('edit') ) {
683 if ( $wgUser->isAnon() ) {
684 $this->userNotLoggedInPage();
685 wfProfileOut( "$fname-checks" );
686 wfProfileOut( $fname );
687 return false;
689 else {
690 $wgOut->readOnlyPage();
691 wfProfileOut( "$fname-checks" );
692 wfProfileOut( $fname );
693 return false;
697 if ( wfReadOnly() ) {
698 $wgOut->readOnlyPage();
699 wfProfileOut( "$fname-checks" );
700 wfProfileOut( $fname );
701 return false;
703 if ( $wgUser->pingLimiter() ) {
704 $wgOut->rateLimited();
705 wfProfileOut( "$fname-checks" );
706 wfProfileOut( $fname );
707 return false;
710 # If the article has been deleted while editing, don't save it without
711 # confirmation
712 if ( $this->deletedSinceEdit && !$this->recreate ) {
713 wfProfileOut( "$fname-checks" );
714 wfProfileOut( $fname );
715 return true;
718 wfProfileOut( "$fname-checks" );
720 # If article is new, insert it.
721 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
722 if ( 0 == $aid ) {
724 // Late check for create permission, just in case *PARANOIA*
725 if ( !$this->mTitle->userCan( 'create' ) ) {
726 wfDebug( "$fname: no create permission\n" );
727 $this->noCreatePermission();
728 wfProfileOut( $fname );
729 return;
732 # Don't save a new article if it's blank.
733 if ( ( '' == $this->textbox1 ) ) {
734 $wgOut->redirect( $this->mTitle->getFullURL() );
735 wfProfileOut( $fname );
736 return false;
739 $isComment=($this->section=='new');
740 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
741 $this->minoredit, $this->watchthis, false, $isComment);
743 wfProfileOut( $fname );
744 return false;
747 # Article exists. Check for edit conflict.
749 $this->mArticle->clear(); # Force reload of dates, etc.
750 $this->mArticle->forUpdate( true ); # Lock the article
752 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
754 if( $this->mArticle->getTimestamp() != $this->edittime ) {
755 $this->isConflict = true;
756 if( $this->section == 'new' ) {
757 if( $this->mArticle->getUserText() == $wgUser->getName() &&
758 $this->mArticle->getComment() == $this->summary ) {
759 // Probably a duplicate submission of a new comment.
760 // This can happen when squid resends a request after
761 // a timeout but the first one actually went through.
762 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
763 } else {
764 // New comment; suppress conflict.
765 $this->isConflict = false;
766 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
770 $userid = $wgUser->getID();
772 if ( $this->isConflict) {
773 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
774 $this->mArticle->getTimestamp() . "')\n" );
775 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
777 else {
778 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
779 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
781 if( is_null( $text ) ) {
782 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
783 $this->isConflict = true;
784 $text = $this->textbox1;
787 # Suppress edit conflict with self, except for section edits where merging is required.
788 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
789 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
790 $this->isConflict = false;
791 } else {
792 # switch from section editing to normal editing in edit conflict
793 if($this->isConflict) {
794 # Attempt merge
795 if( $this->mergeChangesInto( $text ) ){
796 // Successful merge! Maybe we should tell the user the good news?
797 $this->isConflict = false;
798 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
799 } else {
800 $this->section = '';
801 $this->textbox1 = $text;
802 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
807 if ( $this->isConflict ) {
808 wfProfileOut( $fname );
809 return true;
812 $oldtext = $this->mArticle->getContent();
814 # Handle the user preference to force summaries here, but not for null edits
815 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary')
816 && 0 != strcmp($oldtext, $text) && !Article::getRedirectAutosummary( $text )) {
817 if( md5( $this->summary ) == $this->autoSumm ) {
818 $this->missingSummary = true;
819 wfProfileOut( $fname );
820 return( true );
824 #And a similar thing for new sections
825 if( $this->section == 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
826 if (trim($this->summary) == '') {
827 $this->missingSummary = true;
828 wfProfileOut( $fname );
829 return( true );
833 # All's well
834 wfProfileIn( "$fname-sectionanchor" );
835 $sectionanchor = '';
836 if( $this->section == 'new' ) {
837 if ( $this->textbox1 == '' ) {
838 $this->missingComment = true;
839 return true;
841 if( $this->summary != '' ) {
842 $sectionanchor = $this->sectionAnchor( $this->summary );
844 } elseif( $this->section != '' ) {
845 # Try to get a section anchor from the section source, redirect to edited section if header found
846 # XXX: might be better to integrate this into Article::replaceSection
847 # for duplicate heading checking and maybe parsing
848 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
849 # we can't deal with anchors, includes, html etc in the header for now,
850 # headline would need to be parsed to improve this
851 if($hasmatch and strlen($matches[2]) > 0) {
852 $sectionanchor = $this->sectionAnchor( $matches[2] );
855 wfProfileOut( "$fname-sectionanchor" );
857 // Save errors may fall down to the edit form, but we've now
858 // merged the section into full text. Clear the section field
859 // so that later submission of conflict forms won't try to
860 // replace that into a duplicated mess.
861 $this->textbox1 = $text;
862 $this->section = '';
864 // Check for length errors again now that the section is merged in
865 $this->kblength = (int)(strlen( $text ) / 1024);
866 if ( $this->kblength > $wgMaxArticleSize ) {
867 $this->tooBig = true;
868 wfProfileOut( $fname );
869 return true;
872 # update the article here
873 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
874 $this->watchthis, '', $sectionanchor ) ) {
875 wfProfileOut( $fname );
876 return false;
877 } else {
878 $this->isConflict = true;
880 wfProfileOut( $fname );
881 return true;
885 * Initialise form fields in the object
886 * Called on the first invocation, e.g. when a user clicks an edit link
888 function initialiseForm() {
889 $this->edittime = $this->mArticle->getTimestamp();
890 $this->summary = '';
891 $this->textbox1 = $this->getContent(false);
892 if ($this->textbox1 === false) return false;
894 if ( !$this->mArticle->exists() && $this->mArticle->mTitle->getNamespace() == NS_MEDIAWIKI )
895 $this->textbox1 = wfMsgWeirdKey( $this->mArticle->mTitle->getText() );
896 wfProxyCheck();
897 return true;
901 * Send the edit form and related headers to $wgOut
902 * @param $formCallback Optional callable that takes an OutputPage
903 * parameter; will be called during form output
904 * near the top, for captchas and the like.
906 function showEditForm( $formCallback=null ) {
907 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
909 $fname = 'EditPage::showEditForm';
910 wfProfileIn( $fname );
912 $sk = $wgUser->getSkin();
914 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
916 $wgOut->setRobotpolicy( 'noindex,nofollow' );
918 # Enabled article-related sidebar, toplinks, etc.
919 $wgOut->setArticleRelated( true );
921 if ( $this->formtype == 'preview' ) {
922 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
925 if ( $this->isConflict ) {
926 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
927 $wgOut->setPageTitle( $s );
928 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
930 $this->textbox2 = $this->textbox1;
931 $this->textbox1 = $this->getContent();
932 $this->edittime = $this->mArticle->getTimestamp();
933 } else {
935 if( $this->section != '' ) {
936 if( $this->section == 'new' ) {
937 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
938 } else {
939 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
940 $matches = array();
941 if( !$this->summary && !$this->preview && !$this->diff ) {
942 preg_match( "/^(=+)(.+)\\1/mi",
943 $this->textbox1,
944 $matches );
945 if( !empty( $matches[2] ) ) {
946 $this->summary = "/* ". trim($matches[2])." */ ";
950 } else {
951 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
953 $wgOut->setPageTitle( $s );
955 if ( $this->missingComment ) {
956 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
959 if( $this->missingSummary && $this->section != 'new' ) {
960 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
963 if( $this->missingSummary && $this->section == 'new' ) {
964 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
967 if( !$this->hookError == '' ) {
968 $wgOut->addWikiText( $this->hookError );
971 if ( !$this->checkUnicodeCompliantBrowser() ) {
972 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
974 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
975 // Let sysop know that this will make private content public if saved
976 if( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
977 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
979 if( !$this->mArticle->mRevision->isCurrent() ) {
980 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
981 $wgOut->addWikiText( wfMsg( 'editingold' ) );
986 if( wfReadOnly() ) {
987 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
988 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
989 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
990 } else {
991 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
992 # Check the skin exists
993 if( $this->isValidCssJsSubpage ) {
994 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
995 } else {
996 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
1001 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1002 # Show a warning if editing an interface message
1003 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
1004 } elseif( $this->mTitle->isProtected( 'edit' ) ) {
1005 # Is the title semi-protected?
1006 if( $this->mTitle->isSemiProtected() ) {
1007 $notice = wfMsg( 'semiprotectedpagewarning' );
1008 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' )
1009 $notice = '';
1010 } else {
1011 # Then it must be protected based on static groups (regular)
1012 $notice = wfMsg( 'protectedpagewarning' );
1014 $wgOut->addWikiText( $notice );
1016 if ( $this->mTitle->isCascadeProtected() ) {
1017 # Is this page under cascading protection from some source pages?
1018 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1019 if ( count($cascadeSources) > 0 ) {
1020 # Explain, and list the titles responsible
1021 $notice = wfMsgExt( 'cascadeprotectedwarning', array('parsemag'), count($cascadeSources) ) . "\n";
1022 foreach( $cascadeSources as $page ) {
1023 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1026 $wgOut->addWikiText( $notice );
1029 if ( $this->kblength === false ) {
1030 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
1032 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1033 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
1034 } elseif( $this->kblength > 29 ) {
1035 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
1038 #need to parse the preview early so that we know which templates are used,
1039 #otherwise users with "show preview after edit box" will get a blank list
1040 if ( $this->formtype == 'preview' ) {
1041 $previewOutput = $this->getPreviewText();
1044 $rows = $wgUser->getIntOption( 'rows' );
1045 $cols = $wgUser->getIntOption( 'cols' );
1047 $ew = $wgUser->getOption( 'editwidth' );
1048 if ( $ew ) $ew = " style=\"width:100%\"";
1049 else $ew = '';
1051 $q = 'action=submit';
1052 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1053 $action = $this->mTitle->escapeLocalURL( $q );
1055 $summary = wfMsg('summary');
1056 $subject = wfMsg('subject');
1058 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
1059 wfMsgExt('cancel', array('parseinline')) );
1060 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1061 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1062 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1063 htmlspecialchars( wfMsg( 'newwindow' ) );
1065 global $wgRightsText;
1066 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1067 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
1068 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1069 $wgRightsText ) . "\n</div>";
1071 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1072 # prepare toolbar for edit buttons
1073 $toolbar = $this->getEditToolbar();
1074 } else {
1075 $toolbar = '';
1078 // activate checkboxes if user wants them to be always active
1079 if( !$this->preview && !$this->diff ) {
1080 # Sort out the "watch" checkbox
1081 if( $wgUser->getOption( 'watchdefault' ) ) {
1082 # Watch all edits
1083 $this->watchthis = true;
1084 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1085 # Watch creations
1086 $this->watchthis = true;
1087 } elseif( $this->mTitle->userIsWatching() ) {
1088 # Already watched
1089 $this->watchthis = true;
1092 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1095 $wgOut->addHTML( $this->editFormPageTop );
1097 if ( $wgUser->getOption( 'previewontop' ) ) {
1099 if ( 'preview' == $this->formtype ) {
1100 $this->showPreview( $previewOutput );
1101 } else {
1102 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1105 if ( 'diff' == $this->formtype ) {
1106 $this->showDiff();
1111 $wgOut->addHTML( $this->editFormTextTop );
1113 # if this is a comment, show a subject line at the top, which is also the edit summary.
1114 # Otherwise, show a summary field at the bottom
1115 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1116 if( $this->section == 'new' ) {
1117 $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 />";
1118 $editsummary = '';
1119 $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1120 $summarypreview = '';
1121 } else {
1122 $commentsubject = '';
1123 $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 />";
1124 $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1125 $subjectpreview = '';
1128 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1129 if( !$this->preview && !$this->diff ) {
1130 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1132 $templates = ($this->preview || $this->section != '') ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
1133 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1135 global $wgUseMetadataEdit ;
1136 if ( $wgUseMetadataEdit ) {
1137 $metadata = $this->mMetaData ;
1138 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1139 $top = wfMsgWikiHtml( 'metadata_help' );
1140 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1142 else $metadata = "" ;
1144 $hidden = '';
1145 $recreate = '';
1146 if ($this->deletedSinceEdit) {
1147 if ( 'save' != $this->formtype ) {
1148 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1149 } else {
1150 // Hide the toolbar and edit area, use can click preview to get it back
1151 // Add an confirmation checkbox and explanation.
1152 $toolbar = '';
1153 $hidden = 'type="hidden" style="display:none;"';
1154 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1155 $recreate .=
1156 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1157 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1161 $tabindex = 2;
1163 $checkboxes = self::getCheckboxes( $tabindex, $sk,
1164 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1166 $checkboxhtml = implode( $checkboxes, "\n" );
1168 $buttons = $this->getEditButtons( $tabindex );
1169 $buttonshtml = implode( $buttons, "\n" );
1171 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1172 ? '' : Xml::hidden( 'safemode', '1' );
1174 $wgOut->addHTML( <<<END
1175 {$toolbar}
1176 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1180 if( is_callable( $formCallback ) ) {
1181 call_user_func_array( $formCallback, array( &$wgOut ) );
1184 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1186 // Put these up at the top to ensure they aren't lost on early form submission
1187 $wgOut->addHTML( "
1188 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1189 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1190 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1191 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1193 $wgOut->addHTML( <<<END
1194 $recreate
1195 {$commentsubject}
1196 {$subjectpreview}
1197 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1198 cols='{$cols}'{$ew} $hidden>
1200 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1202 </textarea>
1203 " );
1205 $wgOut->addWikiText( $copywarn );
1206 $wgOut->addHTML( $this->editFormTextAfterWarn );
1207 $wgOut->addHTML( "
1208 {$metadata}
1209 {$editsummary}
1210 {$summarypreview}
1211 {$checkboxhtml}
1212 {$safemodehtml}
1215 $wgOut->addHTML(
1216 "<div class='editButtons'>
1217 {$buttonshtml}
1218 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1219 </div><!-- editButtons -->
1220 </div><!-- editOptions -->");
1222 $wgOut->addHtml( '<div class="mw-editTools">' );
1223 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1224 $wgOut->addHtml( '</div>' );
1226 $wgOut->addHTML( $this->editFormTextAfterTools );
1228 $wgOut->addHTML( "
1229 <div class='templatesUsed'>
1230 {$formattedtemplates}
1231 </div>
1232 " );
1235 * To make it harder for someone to slip a user a page
1236 * which submits an edit form to the wiki without their
1237 * knowledge, a random token is associated with the login
1238 * session. If it's not passed back with the submission,
1239 * we won't save the page, or render user JavaScript and
1240 * CSS previews.
1242 * For anon editors, who may not have a session, we just
1243 * include the constant suffix to prevent editing from
1244 * broken text-mangling proxies.
1246 $token = htmlspecialchars( $wgUser->editToken() );
1247 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1250 # If a blank edit summary was previously provided, and the appropriate
1251 # user preference is active, pass a hidden tag here. This will stop the
1252 # user being bounced back more than once in the event that a summary
1253 # is not required.
1254 if( $this->missingSummary ) {
1255 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1258 # For a bit more sophisticated detection of blank summaries, hash the
1259 # automatic one and pass that in a hidden field.
1260 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1261 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1263 if ( $this->isConflict ) {
1264 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1266 $de = new DifferenceEngine( $this->mTitle );
1267 $de->setText( $this->textbox2, $this->textbox1 );
1268 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1270 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1271 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1272 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1274 $wgOut->addHTML( $this->editFormTextBottom );
1275 $wgOut->addHTML( "</form>\n" );
1276 if ( !$wgUser->getOption( 'previewontop' ) ) {
1278 if ( $this->formtype == 'preview') {
1279 $this->showPreview( $previewOutput );
1280 } else {
1281 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1284 if ( $this->formtype == 'diff') {
1285 $this->showDiff();
1290 wfProfileOut( $fname );
1294 * Append preview output to $wgOut.
1295 * Includes category rendering if this is a category page.
1297 * @param string $text The HTML to be output for the preview.
1299 private function showPreview( $text ) {
1300 global $wgOut;
1302 $wgOut->addHTML( '<div id="wikiPreview">' );
1303 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1304 $this->mArticle->openShowCategory();
1306 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1307 $wgOut->addHTML( $text );
1308 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1309 $this->mArticle->closeShowCategory();
1311 $wgOut->addHTML( '</div>' );
1315 * Live Preview lets us fetch rendered preview page content and
1316 * add it to the page without refreshing the whole page.
1317 * If not supported by the browser it will fall through to the normal form
1318 * submission method.
1320 * This function outputs a script tag to support live preview, and
1321 * returns an onclick handler which should be added to the attributes
1322 * of the preview button
1324 function doLivePreviewScript() {
1325 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1326 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1327 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1328 '"></script>' . "\n" );
1329 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1330 return "return !livePreview(" .
1331 "getElementById('wikiPreview')," .
1332 "editform.wpTextbox1.value," .
1333 '"' . $liveAction . '"' . ")";
1336 function getLastDelete() {
1337 $dbr = wfGetDB( DB_SLAVE );
1338 $fname = 'EditPage::getLastDelete';
1339 $res = $dbr->select(
1340 array( 'logging', 'user' ),
1341 array( 'log_type',
1342 'log_action',
1343 'log_timestamp',
1344 'log_user',
1345 'log_namespace',
1346 'log_title',
1347 'log_comment',
1348 'log_params',
1349 'user_name', ),
1350 array( 'log_namespace' => $this->mTitle->getNamespace(),
1351 'log_title' => $this->mTitle->getDBkey(),
1352 'log_type' => 'delete',
1353 'log_action' => 'delete',
1354 'user_id=log_user' ),
1355 $fname,
1356 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1358 if($dbr->numRows($res) == 1) {
1359 while ( $x = $dbr->fetchObject ( $res ) )
1360 $data = $x;
1361 $dbr->freeResult ( $res ) ;
1362 } else {
1363 $data = null;
1365 return $data;
1369 * @todo document
1371 function getPreviewText() {
1372 global $wgOut, $wgUser, $wgTitle, $wgParser;
1374 $fname = 'EditPage::getPreviewText';
1375 wfProfileIn( $fname );
1377 if ( $this->mTriedSave && !$this->mTokenOk ) {
1378 if ( $this->mTokenOkExceptSuffix ) {
1379 $msg = 'token_suffix_mismatch';
1380 } else {
1381 $msg = 'session_fail_preview';
1383 } else {
1384 $msg = 'previewnote';
1386 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1387 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1388 if ( $this->isConflict ) {
1389 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1392 $parserOptions = ParserOptions::newFromUser( $wgUser );
1393 $parserOptions->setEditSection( false );
1395 global $wgRawHtml;
1396 if( $wgRawHtml && !$this->mTokenOk ) {
1397 // Could be an offsite preview attempt. This is very unsafe if
1398 // HTML is enabled, as it could be an attack.
1399 return $wgOut->parse( "<div class='previewnote'>" .
1400 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1403 # don't parse user css/js, show message about preview
1404 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1406 if ( $this->isCssJsSubpage ) {
1407 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1408 $previewtext = wfMsg('usercsspreview');
1409 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1410 $previewtext = wfMsg('userjspreview');
1412 $parserOptions->setTidy(true);
1413 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1414 $wgOut->addHTML( $parserOutput->mText );
1415 wfProfileOut( $fname );
1416 return $previewhead;
1417 } else {
1418 $toparse = $this->textbox1;
1420 # If we're adding a comment, we need to show the
1421 # summary as the headline
1422 if($this->section=="new" && $this->summary!="") {
1423 $toparse="== {$this->summary} ==\n\n".$toparse;
1426 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1427 $parserOptions->setTidy(true);
1428 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1429 $wgTitle, $parserOptions );
1431 $previewHTML = $parserOutput->getText();
1432 $wgOut->addParserOutputNoText( $parserOutput );
1434 # ParserOutput might have altered the page title, so reset it
1435 $wgOut->setPageTitle( wfMsg( 'editing', $this->mTitle->getPrefixedText() ) );
1437 foreach ( $parserOutput->getTemplates() as $ns => $template)
1438 foreach ( array_keys( $template ) as $dbk)
1439 $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
1441 wfProfileOut( $fname );
1442 return $previewhead . $previewHTML;
1447 * Call the stock "user is blocked" page
1449 function blockedPage() {
1450 global $wgOut, $wgUser;
1451 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1453 # If the user made changes, preserve them when showing the markup
1454 # (This happens when a user is blocked during edit, for instance)
1455 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1456 if( $first ) {
1457 $source = $this->mTitle->exists() ? $this->getContent() : false;
1458 } else {
1459 $source = $this->textbox1;
1462 # Spit out the source or the user's modified version
1463 if( $source !== false ) {
1464 $rows = $wgUser->getOption( 'rows' );
1465 $cols = $wgUser->getOption( 'cols' );
1466 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1467 $wgOut->addHtml( '<hr />' );
1468 $wgOut->addWikiText( wfMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ) );
1469 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1474 * Produce the stock "please login to edit pages" page
1476 function userNotLoggedInPage() {
1477 global $wgUser, $wgOut;
1478 $skin = $wgUser->getSkin();
1480 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1481 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle->getPrefixedUrl() );
1483 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1484 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1485 $wgOut->setArticleRelated( false );
1487 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1488 $wgOut->returnToMain( false, $this->mTitle->getPrefixedUrl() );
1492 * Creates a basic error page which informs the user that
1493 * they have to validate their email address before being
1494 * allowed to edit.
1496 function userNotConfirmedPage() {
1497 global $wgOut;
1499 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1500 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1501 $wgOut->setArticleRelated( false );
1503 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1504 $wgOut->returnToMain( false );
1508 * Creates a basic error page which informs the user that
1509 * they have attempted to edit a nonexistant section.
1511 function noSuchSectionPage() {
1512 global $wgOut;
1514 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1515 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1516 $wgOut->setArticleRelated( false );
1518 $wgOut->addWikiText( wfMsg( 'nosuchsectiontext', $this->section ) );
1519 $wgOut->returnToMain( false, $this->mTitle->getPrefixedUrl() );
1523 * Produce the stock "your edit contains spam" page
1525 * @param $match Text which triggered one or more filters
1527 function spamPage( $match = false ) {
1528 global $wgOut;
1530 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1531 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1532 $wgOut->setArticleRelated( false );
1534 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1535 if ( $match )
1536 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1538 $wgOut->returnToMain( false );
1542 * @private
1543 * @todo document
1545 function mergeChangesInto( &$editText ){
1546 $fname = 'EditPage::mergeChangesInto';
1547 wfProfileIn( $fname );
1549 $db = wfGetDB( DB_MASTER );
1551 // This is the revision the editor started from
1552 $baseRevision = Revision::loadFromTimestamp(
1553 $db, $this->mArticle->mTitle, $this->edittime );
1554 if( is_null( $baseRevision ) ) {
1555 wfProfileOut( $fname );
1556 return false;
1558 $baseText = $baseRevision->getText();
1560 // The current state, we want to merge updates into it
1561 $currentRevision = Revision::loadFromTitle(
1562 $db, $this->mArticle->mTitle );
1563 if( is_null( $currentRevision ) ) {
1564 wfProfileOut( $fname );
1565 return false;
1567 $currentText = $currentRevision->getText();
1569 $result = '';
1570 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1571 $editText = $result;
1572 wfProfileOut( $fname );
1573 return true;
1574 } else {
1575 wfProfileOut( $fname );
1576 return false;
1581 * Check if the browser is on a blacklist of user-agents known to
1582 * mangle UTF-8 data on form submission. Returns true if Unicode
1583 * should make it through, false if it's known to be a problem.
1584 * @return bool
1585 * @private
1587 function checkUnicodeCompliantBrowser() {
1588 global $wgBrowserBlackList;
1589 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1590 // No User-Agent header sent? Trust it by default...
1591 return true;
1593 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1594 foreach ( $wgBrowserBlackList as $browser ) {
1595 if ( preg_match($browser, $currentbrowser) ) {
1596 return false;
1599 return true;
1603 * Format an anchor fragment as it would appear for a given section name
1604 * @param string $text
1605 * @return string
1606 * @private
1608 function sectionAnchor( $text ) {
1609 $headline = Sanitizer::decodeCharReferences( $text );
1610 # strip out HTML
1611 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1612 $headline = trim( $headline );
1613 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1614 $replacearray = array(
1615 '%3A' => ':',
1616 '%' => '.'
1618 return str_replace(
1619 array_keys( $replacearray ),
1620 array_values( $replacearray ),
1621 $sectionanchor );
1625 * Shows a bulletin board style toolbar for common editing functions.
1626 * It can be disabled in the user preferences.
1627 * The necessary JavaScript code can be found in style/wikibits.js.
1629 function getEditToolbar() {
1630 global $wgStylePath, $wgContLang, $wgJsMimeType;
1633 * toolarray an array of arrays which each include the filename of
1634 * the button image (without path), the opening tag, the closing tag,
1635 * and optionally a sample text that is inserted between the two when no
1636 * selection is highlighted.
1637 * The tip text is shown when the user moves the mouse over the button.
1639 * Already here are accesskeys (key), which are not used yet until someone
1640 * can figure out a way to make them work in IE. However, we should make
1641 * sure these keys are not defined on the edit page.
1643 $toolarray = array(
1644 array( 'image' => 'button_bold.png',
1645 'id' => 'mw-editbutton-bold',
1646 'open' => '\\\'\\\'\\\'',
1647 'close' => '\\\'\\\'\\\'',
1648 'sample'=> wfMsg('bold_sample'),
1649 'tip' => wfMsg('bold_tip'),
1650 'key' => 'B'
1652 array( 'image' => 'button_italic.png',
1653 'id' => 'mw-editbutton-italic',
1654 'open' => '\\\'\\\'',
1655 'close' => '\\\'\\\'',
1656 'sample'=> wfMsg('italic_sample'),
1657 'tip' => wfMsg('italic_tip'),
1658 'key' => 'I'
1660 array( 'image' => 'button_link.png',
1661 'id' => 'mw-editbutton-link',
1662 'open' => '[[',
1663 'close' => ']]',
1664 'sample'=> wfMsg('link_sample'),
1665 'tip' => wfMsg('link_tip'),
1666 'key' => 'L'
1668 array( 'image' => 'button_extlink.png',
1669 'id' => 'mw-editbutton-extlink',
1670 'open' => '[',
1671 'close' => ']',
1672 'sample'=> wfMsg('extlink_sample'),
1673 'tip' => wfMsg('extlink_tip'),
1674 'key' => 'X'
1676 array( 'image' => 'button_headline.png',
1677 'id' => 'mw-editbutton-headline',
1678 'open' => "\\n== ",
1679 'close' => " ==\\n",
1680 'sample'=> wfMsg('headline_sample'),
1681 'tip' => wfMsg('headline_tip'),
1682 'key' => 'H'
1684 array( 'image' => 'button_image.png',
1685 'id' => 'mw-editbutton-image',
1686 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1687 'close' => ']]',
1688 'sample'=> wfMsg('image_sample'),
1689 'tip' => wfMsg('image_tip'),
1690 'key' => 'D'
1692 array( 'image' => 'button_media.png',
1693 'id' => 'mw-editbutton-media',
1694 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1695 'close' => ']]',
1696 'sample'=> wfMsg('media_sample'),
1697 'tip' => wfMsg('media_tip'),
1698 'key' => 'M'
1700 array( 'image' => 'button_math.png',
1701 'id' => 'mw-editbutton-math',
1702 'open' => "<math>",
1703 'close' => "<\\/math>",
1704 'sample'=> wfMsg('math_sample'),
1705 'tip' => wfMsg('math_tip'),
1706 'key' => 'C'
1708 array( 'image' => 'button_nowiki.png',
1709 'id' => 'mw-editbutton-nowiki',
1710 'open' => "<nowiki>",
1711 'close' => "<\\/nowiki>",
1712 'sample'=> wfMsg('nowiki_sample'),
1713 'tip' => wfMsg('nowiki_tip'),
1714 'key' => 'N'
1716 array( 'image' => 'button_sig.png',
1717 'id' => 'mw-editbutton-signature',
1718 'open' => '--~~~~',
1719 'close' => '',
1720 'sample'=> '',
1721 'tip' => wfMsg('sig_tip'),
1722 'key' => 'Y'
1724 array( 'image' => 'button_hr.png',
1725 'id' => 'mw-editbutton-hr',
1726 'open' => "\\n----\\n",
1727 'close' => '',
1728 'sample'=> '',
1729 'tip' => wfMsg('hr_tip'),
1730 'key' => 'R'
1733 $toolbar = "<div id='toolbar'>\n";
1734 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1736 foreach($toolarray as $tool) {
1738 $cssId = $tool['id'];
1739 $image=$wgStylePath.'/common/images/'.$tool['image'];
1740 $open=$tool['open'];
1741 $close=$tool['close'];
1742 $sample = wfEscapeJsString( $tool['sample'] );
1744 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1745 // Older browsers show a "speedtip" type message only for ALT.
1746 // Ideally these should be different, realistically they
1747 // probably don't need to be.
1748 $tip = wfEscapeJsString( $tool['tip'] );
1750 #$key = $tool["key"];
1752 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1755 $toolbar.="/*]]>*/\n</script>";
1756 $toolbar.="\n</div>";
1757 return $toolbar;
1761 * Returns an array of html code of the following checkboxes:
1762 * minor and watch
1764 * @param $tabindex Current tabindex
1765 * @param $skin Skin object
1766 * @param $checked Array of checkbox => bool, where bool indicates the checked
1767 * status of the checkbox
1769 * @return array
1771 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1772 global $wgUser;
1774 $checkboxes = array();
1776 $checkboxes['minor'] = '';
1777 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1778 if ( $wgUser->isAllowed('minoredit') ) {
1779 $attribs = array(
1780 'tabindex' => ++$tabindex,
1781 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1782 'id' => 'wpMinoredit',
1784 $checkboxes['minor'] =
1785 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1786 "&nbsp;<label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1789 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1790 $checkboxes['watch'] = '';
1791 if ( $wgUser->isLoggedIn() ) {
1792 $attribs = array(
1793 'tabindex' => ++$tabindex,
1794 'accesskey' => wfMsg( 'accesskey-watch' ),
1795 'id' => 'wpWatchthis',
1797 $checkboxes['watch'] =
1798 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1799 "&nbsp;<label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1801 return $checkboxes;
1805 * Returns an array of html code of the following buttons:
1806 * save, diff, preview and live
1808 * @param $tabindex Current tabindex
1810 * @return array
1812 public function getEditButtons(&$tabindex) {
1813 global $wgLivePreview, $wgUser;
1815 $buttons = array();
1817 $temp = array(
1818 'id' => 'wpSave',
1819 'name' => 'wpSave',
1820 'type' => 'submit',
1821 'tabindex' => ++$tabindex,
1822 'value' => wfMsg('savearticle'),
1823 'accesskey' => wfMsg('accesskey-save'),
1824 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1826 $buttons['save'] = wfElement('input', $temp, '');
1828 ++$tabindex; // use the same for preview and live preview
1829 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1830 $temp = array(
1831 'id' => 'wpPreview',
1832 'name' => 'wpPreview',
1833 'type' => 'submit',
1834 'tabindex' => $tabindex,
1835 'value' => wfMsg('showpreview'),
1836 'accesskey' => '',
1837 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1838 'style' => 'display: none;',
1840 $buttons['preview'] = wfElement('input', $temp, '');
1842 $temp = array(
1843 'id' => 'wpLivePreview',
1844 'name' => 'wpLivePreview',
1845 'type' => 'submit',
1846 'tabindex' => $tabindex,
1847 'value' => wfMsg('showlivepreview'),
1848 'accesskey' => wfMsg('accesskey-preview'),
1849 'title' => '',
1850 'onclick' => $this->doLivePreviewScript(),
1852 $buttons['live'] = wfElement('input', $temp, '');
1853 } else {
1854 $temp = array(
1855 'id' => 'wpPreview',
1856 'name' => 'wpPreview',
1857 'type' => 'submit',
1858 'tabindex' => $tabindex,
1859 'value' => wfMsg('showpreview'),
1860 'accesskey' => wfMsg('accesskey-preview'),
1861 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1863 $buttons['preview'] = wfElement('input', $temp, '');
1864 $buttons['live'] = '';
1867 $temp = array(
1868 'id' => 'wpDiff',
1869 'name' => 'wpDiff',
1870 'type' => 'submit',
1871 'tabindex' => ++$tabindex,
1872 'value' => wfMsg('showdiff'),
1873 'accesskey' => wfMsg('accesskey-diff'),
1874 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1876 $buttons['diff'] = wfElement('input', $temp, '');
1878 return $buttons;
1882 * Output preview text only. This can be sucked into the edit page
1883 * via JavaScript, and saves the server time rendering the skin as
1884 * well as theoretically being more robust on the client (doesn't
1885 * disturb the edit box's undo history, won't eat your text on
1886 * failure, etc).
1888 * @todo This doesn't include category or interlanguage links.
1889 * Would need to enhance it a bit, <s>maybe wrap them in XML
1890 * or something...</s> that might also require more skin
1891 * initialization, so check whether that's a problem.
1893 function livePreview() {
1894 global $wgOut;
1895 $wgOut->disable();
1896 header( 'Content-type: text/xml; charset=utf-8' );
1897 header( 'Cache-control: no-cache' );
1899 $s =
1900 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1901 Xml::openElement( 'livepreview' ) .
1902 Xml::element( 'preview', null, $this->getPreviewText() ) .
1903 Xml::element( 'br', array( 'style' => 'clear: both;' ) ) .
1904 Xml::closeElement( 'livepreview' );
1905 echo $s;
1910 * Get a diff between the current contents of the edit box and the
1911 * version of the page we're editing from.
1913 * If this is a section edit, we'll replace the section as for final
1914 * save and then make a comparison.
1916 function showDiff() {
1917 $oldtext = $this->mArticle->fetchContent();
1918 $newtext = $this->mArticle->replaceSection(
1919 $this->section, $this->textbox1, $this->summary, $this->edittime );
1920 $newtext = $this->mArticle->preSaveTransform( $newtext );
1921 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1922 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1923 if ( $oldtext !== false || $newtext != '' ) {
1924 $de = new DifferenceEngine( $this->mTitle );
1925 $de->setText( $oldtext, $newtext );
1926 $difftext = $de->getDiff( $oldtitle, $newtitle );
1927 $de->showDiffStyle();
1928 } else {
1929 $difftext = '';
1932 global $wgOut;
1933 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
1937 * Filter an input field through a Unicode de-armoring process if it
1938 * came from an old browser with known broken Unicode editing issues.
1940 * @param WebRequest $request
1941 * @param string $field
1942 * @return string
1943 * @private
1945 function safeUnicodeInput( $request, $field ) {
1946 $text = rtrim( $request->getText( $field ) );
1947 return $request->getBool( 'safemode' )
1948 ? $this->unmakesafe( $text )
1949 : $text;
1953 * Filter an output field through a Unicode armoring process if it is
1954 * going to an old browser with known broken Unicode editing issues.
1956 * @param string $text
1957 * @return string
1958 * @private
1960 function safeUnicodeOutput( $text ) {
1961 global $wgContLang;
1962 $codedText = $wgContLang->recodeForEdit( $text );
1963 return $this->checkUnicodeCompliantBrowser()
1964 ? $codedText
1965 : $this->makesafe( $codedText );
1969 * A number of web browsers are known to corrupt non-ASCII characters
1970 * in a UTF-8 text editing environment. To protect against this,
1971 * detected browsers will be served an armored version of the text,
1972 * with non-ASCII chars converted to numeric HTML character references.
1974 * Preexisting such character references will have a 0 added to them
1975 * to ensure that round-trips do not alter the original data.
1977 * @param string $invalue
1978 * @return string
1979 * @private
1981 function makesafe( $invalue ) {
1982 // Armor existing references for reversability.
1983 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1985 $bytesleft = 0;
1986 $result = "";
1987 $working = 0;
1988 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1989 $bytevalue = ord( $invalue{$i} );
1990 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1991 $result .= chr( $bytevalue );
1992 $bytesleft = 0;
1993 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1994 $working = $working << 6;
1995 $working += ($bytevalue & 0x3F);
1996 $bytesleft--;
1997 if( $bytesleft <= 0 ) {
1998 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2000 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
2001 $working = $bytevalue & 0x1F;
2002 $bytesleft = 1;
2003 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
2004 $working = $bytevalue & 0x0F;
2005 $bytesleft = 2;
2006 } else { //1111 0xxx
2007 $working = $bytevalue & 0x07;
2008 $bytesleft = 3;
2011 return $result;
2015 * Reverse the previously applied transliteration of non-ASCII characters
2016 * back to UTF-8. Used to protect data from corruption by broken web browsers
2017 * as listed in $wgBrowserBlackList.
2019 * @param string $invalue
2020 * @return string
2021 * @private
2023 function unmakesafe( $invalue ) {
2024 $result = "";
2025 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2026 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
2027 $i += 3;
2028 $hexstring = "";
2029 do {
2030 $hexstring .= $invalue{$i};
2031 $i++;
2032 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2034 // Do some sanity checks. These aren't needed for reversability,
2035 // but should help keep the breakage down if the editor
2036 // breaks one of the entities whilst editing.
2037 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2038 $codepoint = hexdec($hexstring);
2039 $result .= codepointToUtf8( $codepoint );
2040 } else {
2041 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2043 } else {
2044 $result .= substr( $invalue, $i, 1 );
2047 // reverse the transform that we made for reversability reasons.
2048 return strtr( $result, array( "&#x0" => "&#x" ) );
2051 function noCreatePermission() {
2052 global $wgOut;
2053 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2054 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
2058 * If there are rows in the deletion log for this page, show them,
2059 * along with a nice little note for the user
2061 * @param OutputPage $out
2063 private function showDeletionLog( $out ) {
2064 $title = $this->mArticle->getTitle();
2065 $reader = new LogReader(
2066 new FauxRequest(
2067 array(
2068 'page' => $title->getPrefixedText(),
2069 'type' => 'delete',
2073 if( $reader->hasRows() ) {
2074 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2075 $out->addWikiText( wfMsg( 'recreate-deleted-warn' ) );
2076 $viewer = new LogViewer( $reader );
2077 $viewer->showList( $out );
2078 $out->addHtml( '</div>' );