redundant file removal
[mediawiki.git] / includes / EditPage.php
blob3e8c46e0c459d9ad088e90be34258be0be477fa1
1 <?php
2 /**
3 * Contain the EditPage class
4 * @package MediaWiki
5 */
7 /**
8 * Splitting edit page/HTML interface 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 * @package MediaWiki
16 class EditPage {
17 var $mArticle;
18 var $mTitle;
19 var $mMetaData = '';
20 var $isConflict = false;
21 var $isCssJsSubpage = false;
22 var $deletedSinceEdit = false;
23 var $formtype;
24 var $firsttime;
25 var $lastDelete;
26 var $mTokenOk = true;
27 var $tooBig = false;
28 var $kblength = false;
29 var $missingComment = false;
30 var $missingSummary = false;
31 var $allowBlankSummary = false;
32 var $autoSumm = '';
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 /**
42 * @todo document
43 * @param $article
45 function EditPage( $article ) {
46 $this->mArticle =& $article;
47 global $wgTitle;
48 $this->mTitle =& $wgTitle;
51 /**
52 * This is the function that extracts metadata from the article body on the first view.
53 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
54 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
56 function extractMetaDataFromArticle () {
57 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
58 $this->mMetaData = '' ;
59 if ( !$wgUseMetadataEdit ) return ;
60 if ( $wgMetadataWhitelist == '' ) return ;
61 $s = '' ;
62 $t = $this->mArticle->getContent();
64 # MISSING : <nowiki> filtering
66 # Categories and language links
67 $t = explode ( "\n" , $t ) ;
68 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
69 $cat = $ll = array() ;
70 foreach ( $t AS $key => $x )
72 $y = trim ( strtolower ( $x ) ) ;
73 while ( substr ( $y , 0 , 2 ) == '[[' )
75 $y = explode ( ']]' , trim ( $x ) ) ;
76 $first = array_shift ( $y ) ;
77 $first = explode ( ':' , $first ) ;
78 $ns = array_shift ( $first ) ;
79 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
80 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
82 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
83 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
84 else $ll[] = $add ;
85 $x = implode ( ']]' , $y ) ;
86 $t[$key] = $x ;
87 $y = trim ( strtolower ( $x ) ) ;
91 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
92 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
93 $t = implode ( "\n" , $t ) ;
95 # Load whitelist
96 $sat = array () ; # stand-alone-templates; must be lowercase
97 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
98 $wl_article = new Article ( $wl_title ) ;
99 $wl = explode ( "\n" , $wl_article->getContent() ) ;
100 foreach ( $wl AS $x )
102 $isentry = false ;
103 $x = trim ( $x ) ;
104 while ( substr ( $x , 0 , 1 ) == '*' )
106 $isentry = true ;
107 $x = trim ( substr ( $x , 1 ) ) ;
109 if ( $isentry )
111 $sat[] = strtolower ( $x ) ;
116 # Templates, but only some
117 $t = explode ( '{{' , $t ) ;
118 $tl = array () ;
119 foreach ( $t AS $key => $x )
121 $y = explode ( '}}' , $x , 2 ) ;
122 if ( count ( $y ) == 2 )
124 $z = $y[0] ;
125 $z = explode ( '|' , $z ) ;
126 $tn = array_shift ( $z ) ;
127 if ( in_array ( strtolower ( $tn ) , $sat ) )
129 $tl[] = '{{' . $y[0] . '}}' ;
130 $t[$key] = $y[1] ;
131 $y = explode ( '}}' , $y[1] , 2 ) ;
133 else $t[$key] = '{{' . $x ;
135 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
136 else $t[$key] = $x ;
138 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
139 $t = implode ( '' , $t ) ;
141 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
142 $this->mArticle->mContent = $t ;
143 $this->mMetaData = $s ;
146 function submit() {
147 $this->edit();
151 * This is the function that gets called for "action=edit". It
152 * sets up various member variables, then passes execution to
153 * another function, usually showEditForm()
155 * The edit form is self-submitting, so that when things like
156 * preview and edit conflicts occur, we get the same form back
157 * with the extra stuff added. Only when the final submission
158 * is made and all is well do we actually save and redirect to
159 * the newly-edited page.
161 function edit() {
162 global $wgOut, $wgUser, $wgRequest, $wgTitle;
163 global $wgEmailConfirmToEdit;
165 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
166 return;
168 $fname = 'EditPage::edit';
169 wfProfileIn( $fname );
170 wfDebug( "$fname: enter\n" );
172 // this is not an article
173 $wgOut->setArticleFlag(false);
175 $this->importFormData( $wgRequest );
176 $this->firsttime = false;
178 if( $this->live ) {
179 $this->livePreview();
180 wfProfileOut( $fname );
181 return;
184 if ( ! $this->mTitle->userCanEdit() ) {
185 wfDebug( "$fname: user can't edit\n" );
186 $wgOut->readOnlyPage( $this->mArticle->getContent(), true );
187 wfProfileOut( $fname );
188 return;
190 wfDebug( "$fname: Checking blocks\n" );
191 if ( !$this->preview && !$this->diff && $wgUser->isBlockedFrom( $this->mTitle, !$this->save ) ) {
192 # When previewing, don't check blocked state - will get caught at save time.
193 # Also, check when starting edition is done against slave to improve performance.
194 wfDebug( "$fname: user is blocked\n" );
195 $wgOut->blockedPage();
196 wfProfileOut( $fname );
197 return;
199 if ( !$wgUser->isAllowed('edit') ) {
200 if ( $wgUser->isAnon() ) {
201 wfDebug( "$fname: user must log in\n" );
202 $this->userNotLoggedInPage();
203 wfProfileOut( $fname );
204 return;
205 } else {
206 wfDebug( "$fname: read-only page\n" );
207 $wgOut->readOnlyPage( $this->mArticle->getContent(), true );
208 wfProfileOut( $fname );
209 return;
212 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
213 wfDebug("$fname: user must confirm e-mail address\n");
214 $this->userNotConfirmedPage();
215 wfProfileOut($fname);
216 return;
218 if ( !$this->mTitle->userCan( 'create' ) && !$this->mTitle->exists() ) {
219 wfDebug( "$fname: no create permission\n" );
220 $this->noCreatePermission();
221 wfProfileOut( $fname );
222 return;
224 if ( wfReadOnly() ) {
225 wfDebug( "$fname: read-only mode is engaged\n" );
226 if( $this->save || $this->preview ) {
227 $this->formtype = 'preview';
228 } else if ( $this->diff ) {
229 $this->formtype = 'diff';
230 } else {
231 $wgOut->readOnlyPage( $this->mArticle->getContent() );
232 wfProfileOut( $fname );
233 return;
235 } else {
236 if ( $this->save ) {
237 $this->formtype = 'save';
238 } else if ( $this->preview ) {
239 $this->formtype = 'preview';
240 } else if ( $this->diff ) {
241 $this->formtype = 'diff';
242 } else { # First time through
243 $this->firsttime = true;
244 if( $this->previewOnOpen() ) {
245 $this->formtype = 'preview';
246 } else {
247 $this->extractMetaDataFromArticle () ;
248 $this->formtype = 'initial';
253 wfProfileIn( "$fname-business-end" );
255 $this->isConflict = false;
256 // css / js subpages of user pages get a special treatment
257 $this->isCssJsSubpage = $wgTitle->isCssJsSubpage();
258 $this->isValidCssJsSubpage = $wgTitle->isValidCssJsSubpage();
260 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
261 * no matter it's current state
263 $this->deletedSinceEdit = false;
264 if ( $this->edittime != '' ) {
265 /* Note that we rely on logging table, which hasn't been always there,
266 * but that doesn't matter, because this only applies to brand new
267 * deletes. This is done on every preview and save request. Move it further down
268 * to only perform it on saves
270 if ( $this->mTitle->isDeleted() ) {
271 $this->lastDelete = $this->getLastDelete();
272 if ( !is_null($this->lastDelete) ) {
273 $deletetime = $this->lastDelete->log_timestamp;
274 if ( ($deletetime - $this->starttime) > 0 ) {
275 $this->deletedSinceEdit = true;
281 if(!$this->mTitle->getArticleID() && ('initial' == $this->formtype || $this->firsttime )) { # new article
282 $this->showIntro();
284 if( $this->mTitle->isTalkPage() ) {
285 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
288 # Attempt submission here. This will check for edit conflicts,
289 # and redundantly check for locked database, blocked IPs, etc.
290 # that edit() already checked just in case someone tries to sneak
291 # in the back door with a hand-edited submission URL.
293 if ( 'save' == $this->formtype ) {
294 if ( !$this->attemptSave() ) {
295 wfProfileOut( "$fname-business-end" );
296 wfProfileOut( $fname );
297 return;
301 # First time through: get contents, set time for conflict
302 # checking, etc.
303 if ( 'initial' == $this->formtype || $this->firsttime ) {
304 $this->initialiseForm();
307 $this->showEditForm();
308 wfProfileOut( "$fname-business-end" );
309 wfProfileOut( $fname );
313 * Return true if this page should be previewed when the edit form
314 * is initially opened.
315 * @return bool
316 * @access private
318 function previewOnOpen() {
319 global $wgUser;
320 return $this->section != 'new' &&
321 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle->exists() ) ||
322 ( $this->mTitle->getNamespace() == NS_CATEGORY &&
323 !$this->mTitle->exists() ) );
327 * @todo document
329 function importFormData( &$request ) {
330 global $wgLang ;
331 $fname = 'EditPage::importFormData';
332 wfProfileIn( $fname );
334 if( $request->wasPosted() ) {
335 # These fields need to be checked for encoding.
336 # Also remove trailing whitespace, but don't remove _initial_
337 # whitespace from the text boxes. This may be significant formatting.
338 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
339 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
340 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
341 # Truncate for whole multibyte characters. +5 bytes for ellipsis
342 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
344 $this->edittime = $request->getVal( 'wpEdittime' );
345 $this->starttime = $request->getVal( 'wpStarttime' );
347 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
349 if( is_null( $this->edittime ) ) {
350 # If the form is incomplete, force to preview.
351 wfDebug( "$fname: Form data appears to be incomplete\n" );
352 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
353 $this->preview = true;
354 } else {
355 /* Fallback for live preview */
356 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
357 $this->diff = $request->getCheck( 'wpDiff' );
359 if( !$this->preview ) {
360 if ( $this->tokenOk( $request ) ) {
361 # Some browsers will not report any submit button
362 # if the user hits enter in the comment box.
363 # The unmarked state will be assumed to be a save,
364 # if the form seems otherwise complete.
365 wfDebug( "$fname: Passed token check.\n" );
366 } else {
367 # Page might be a hack attempt posted from
368 # an external site. Preview instead of saving.
369 wfDebug( "$fname: Failed token check; forcing preview\n" );
370 $this->preview = true;
374 $this->save = ! ( $this->preview OR $this->diff );
375 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
376 $this->edittime = null;
379 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
380 $this->starttime = null;
383 $this->recreate = $request->getCheck( 'wpRecreate' );
385 $this->minoredit = $request->getCheck( 'wpMinoredit' );
386 $this->watchthis = $request->getCheck( 'wpWatchthis' );
387 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
388 $this->autoSumm = $request->getText( 'wpAutoSummary' );
389 } else {
390 # Not a posted form? Start with nothing.
391 wfDebug( "$fname: Not a posted form.\n" );
392 $this->textbox1 = '';
393 $this->textbox2 = '';
394 $this->mMetaData = '';
395 $this->summary = '';
396 $this->edittime = '';
397 $this->starttime = wfTimestampNow();
398 $this->preview = false;
399 $this->save = false;
400 $this->diff = false;
401 $this->minoredit = false;
402 $this->watchthis = false;
403 $this->recreate = false;
406 $this->oldid = $request->getInt( 'oldid' );
408 # Section edit can come from either the form or a link
409 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
411 $this->live = $request->getCheck( 'live' );
412 $this->editintro = $request->getText( 'editintro' );
414 wfProfileOut( $fname );
418 * Make sure the form isn't faking a user's credentials.
420 * @param WebRequest $request
421 * @return bool
422 * @access private
424 function tokenOk( &$request ) {
425 global $wgUser;
426 if( $wgUser->isAnon() ) {
427 # Anonymous users may not have a session
428 # open. Don't tokenize.
429 $this->mTokenOk = true;
430 } else {
431 $this->mTokenOk = $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
433 return $this->mTokenOk;
436 function showIntro() {
437 global $wgOut, $wgUser;
438 $addstandardintro=true;
439 if($this->editintro) {
440 $introtitle=Title::newFromText($this->editintro);
441 if(isset($introtitle) && $introtitle->userCanRead()) {
442 $rev=Revision::newFromTitle($introtitle);
443 if($rev) {
444 $wgOut->addSecondaryWikiText($rev->getText());
445 $addstandardintro=false;
449 if($addstandardintro) {
450 if ( $wgUser->isLoggedIn() )
451 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
452 else
453 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
458 * Attempt submission
459 * @return bool false if output is done, true if the rest of the form should be displayed
461 function attemptSave() {
462 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
463 global $wgMaxArticleSize;
465 $fname = 'EditPage::attemptSave';
466 wfProfileIn( $fname );
467 wfProfileIn( "$fname-checks" );
469 # Reintegrate metadata
470 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
471 $this->mMetaData = '' ;
473 # Check for spam
474 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
475 $this->spamPage ( $matches[0] );
476 wfProfileOut( "$fname-checks" );
477 wfProfileOut( $fname );
478 return false;
480 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
481 # Error messages or other handling should be performed by the filter function
482 wfProfileOut( $fname );
483 wfProfileOut( "$fname-checks" );
484 return false;
486 if ( !wfRunHooks( 'EditFilter', array( &$this, $this->textbox1, $this->section ) ) ) {
487 # Error messages or other handling should be performed by the filter function
488 wfProfileOut( $fname );
489 wfProfileOut( "$fname-checks" );
490 return false;
492 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
493 # Check block state against master, thus 'false'.
494 $this->blockedIPpage();
495 wfProfileOut( "$fname-checks" );
496 wfProfileOut( $fname );
497 return false;
499 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
500 if ( $this->kblength > $wgMaxArticleSize ) {
501 // Error will be displayed by showEditForm()
502 $this->tooBig = true;
503 wfProfileOut( "$fname-checks" );
504 wfProfileOut( $fname );
505 return true;
508 if ( !$wgUser->isAllowed('edit') ) {
509 if ( $wgUser->isAnon() ) {
510 $this->userNotLoggedInPage();
511 wfProfileOut( "$fname-checks" );
512 wfProfileOut( $fname );
513 return false;
515 else {
516 $wgOut->readOnlyPage();
517 wfProfileOut( "$fname-checks" );
518 wfProfileOut( $fname );
519 return false;
523 if ( wfReadOnly() ) {
524 $wgOut->readOnlyPage();
525 wfProfileOut( "$fname-checks" );
526 wfProfileOut( $fname );
527 return false;
529 if ( $wgUser->pingLimiter() ) {
530 $wgOut->rateLimited();
531 wfProfileOut( "$fname-checks" );
532 wfProfileOut( $fname );
533 return false;
536 # If the article has been deleted while editing, don't save it without
537 # confirmation
538 if ( $this->deletedSinceEdit && !$this->recreate ) {
539 wfProfileOut( "$fname-checks" );
540 wfProfileOut( $fname );
541 return true;
544 wfProfileOut( "$fname-checks" );
546 # If article is new, insert it.
547 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
548 if ( 0 == $aid ) {
549 // Late check for create permission, just in case *PARANOIA*
550 if ( !$this->mTitle->userCan( 'create' ) ) {
551 wfDebug( "$fname: no create permission\n" );
552 $this->noCreatePermission();
553 wfProfileOut( $fname );
554 return;
557 # Don't save a new article if it's blank.
558 if ( ( '' == $this->textbox1 ) ) {
559 $wgOut->redirect( $this->mTitle->getFullURL() );
560 wfProfileOut( $fname );
561 return false;
564 $isComment=($this->section=='new');
565 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
566 $this->minoredit, $this->watchthis, false, $isComment);
568 wfProfileOut( $fname );
569 return false;
572 # Article exists. Check for edit conflict.
574 $this->mArticle->clear(); # Force reload of dates, etc.
575 $this->mArticle->forUpdate( true ); # Lock the article
577 if( $this->mArticle->getTimestamp() != $this->edittime ) {
578 $this->isConflict = true;
579 if( $this->section == 'new' ) {
580 if( $this->mArticle->getUserText() == $wgUser->getName() &&
581 $this->mArticle->getComment() == $this->summary ) {
582 // Probably a duplicate submission of a new comment.
583 // This can happen when squid resends a request after
584 // a timeout but the first one actually went through.
585 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
586 } else {
587 // New comment; suppress conflict.
588 $this->isConflict = false;
589 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
593 $userid = $wgUser->getID();
595 if ( $this->isConflict) {
596 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
597 $this->mArticle->getTimestamp() . "'\n" );
598 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
600 else {
601 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
602 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
604 if( is_null( $text ) ) {
605 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
606 $this->isConflict = true;
607 $text = $this->textbox1;
610 # Suppress edit conflict with self, except for section edits where merging is required.
611 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
612 wfDebug( "Suppressing edit conflict, same user.\n" );
613 $this->isConflict = false;
614 } else {
615 # switch from section editing to normal editing in edit conflict
616 if($this->isConflict) {
617 # Attempt merge
618 if( $this->mergeChangesInto( $text ) ){
619 // Successful merge! Maybe we should tell the user the good news?
620 $this->isConflict = false;
621 wfDebug( "Suppressing edit conflict, successful merge.\n" );
622 } else {
623 $this->section = '';
624 $this->textbox1 = $text;
625 wfDebug( "Keeping edit conflict, failed merge.\n" );
630 if ( $this->isConflict ) {
631 wfProfileOut( $fname );
632 return true;
635 # Handle the user preference to force summaries here
636 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
637 if( md5( $this->summary ) == $this->autoSumm ) {
638 $this->missingSummary = true;
639 wfProfileOut( $fname );
640 return( true );
644 # All's well
645 wfProfileIn( "$fname-sectionanchor" );
646 $sectionanchor = '';
647 if( $this->section == 'new' ) {
648 if ( $this->textbox1 == '' ) {
649 $this->missingComment = true;
650 return true;
652 if( $this->summary != '' ) {
653 $sectionanchor = $this->sectionAnchor( $this->summary );
655 } elseif( $this->section != '' ) {
656 # Try to get a section anchor from the section source, redirect to edited section if header found
657 # XXX: might be better to integrate this into Article::replaceSection
658 # for duplicate heading checking and maybe parsing
659 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
660 # we can't deal with anchors, includes, html etc in the header for now,
661 # headline would need to be parsed to improve this
662 if($hasmatch and strlen($matches[2]) > 0) {
663 $sectionanchor = $this->sectionAnchor( $matches[2] );
666 wfProfileOut( "$fname-sectionanchor" );
668 // Save errors may fall down to the edit form, but we've now
669 // merged the section into full text. Clear the section field
670 // so that later submission of conflict forms won't try to
671 // replace that into a duplicated mess.
672 $this->textbox1 = $text;
673 $this->section = '';
675 // Check for length errors again now that the section is merged in
676 $this->kblength = (int)(strlen( $text ) / 1024);
677 if ( $this->kblength > $wgMaxArticleSize ) {
678 $this->tooBig = true;
679 wfProfileOut( $fname );
680 return true;
683 # update the article here
684 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
685 $this->watchthis, '', $sectionanchor ) ) {
686 wfProfileOut( $fname );
687 return false;
688 } else {
689 $this->isConflict = true;
691 wfProfileOut( $fname );
692 return true;
696 * Initialise form fields in the object
697 * Called on the first invocation, e.g. when a user clicks an edit link
699 function initialiseForm() {
700 $this->edittime = $this->mArticle->getTimestamp();
701 $this->textbox1 = $this->mArticle->getContent();
702 $this->summary = '';
703 if ( !$this->mArticle->exists() && $this->mArticle->mTitle->getNamespace() == NS_MEDIAWIKI )
704 $this->textbox1 = wfMsgWeirdKey ( $this->mArticle->mTitle->getText() ) ;
705 wfProxyCheck();
709 * Send the edit form and related headers to $wgOut
710 * @param $formCallback Optional callable that takes an OutputPage
711 * parameter; will be called during form output
712 * near the top, for captchas and the like.
714 function showEditForm( $formCallback=null ) {
715 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
717 $fname = 'EditPage::showEditForm';
718 wfProfileIn( $fname );
720 $sk =& $wgUser->getSkin();
722 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
724 $wgOut->setRobotpolicy( 'noindex,nofollow' );
726 # Enabled article-related sidebar, toplinks, etc.
727 $wgOut->setArticleRelated( true );
729 if ( $this->isConflict ) {
730 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
731 $wgOut->setPageTitle( $s );
732 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
734 $this->textbox2 = $this->textbox1;
735 $this->textbox1 = $this->mArticle->getContent();
736 $this->edittime = $this->mArticle->getTimestamp();
737 } else {
739 if( $this->section != '' ) {
740 if( $this->section == 'new' ) {
741 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
742 } else {
743 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
744 if( !$this->preview && !$this->diff ) {
745 preg_match( "/^(=+)(.+)\\1/mi",
746 $this->textbox1,
747 $matches );
748 if( !empty( $matches[2] ) ) {
749 $this->summary = "/* ". trim($matches[2])." */ ";
753 } else {
754 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
756 $wgOut->setPageTitle( $s );
758 if ( $this->missingComment ) {
759 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
762 if( $this->missingSummary ) {
763 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
766 if ( !$this->checkUnicodeCompliantBrowser() ) {
767 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
769 if ( isset( $this->mArticle )
770 && isset( $this->mArticle->mRevision )
771 && !$this->mArticle->mRevision->isCurrent() ) {
772 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
773 $wgOut->addWikiText( wfMsg( 'editingold' ) );
777 if( wfReadOnly() ) {
778 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
779 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
780 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
781 } else {
782 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
783 # Check the skin exists
784 if( $this->isValidCssJsSubpage ) {
785 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
786 } else {
787 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
792 if( $this->mTitle->isProtected( 'edit' ) ) {
793 if( $this->mTitle->isSemiProtected() ) {
794 $notice = wfMsg( 'semiprotectedpagewarning' );
795 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' ) {
796 $notice = '';
798 } else {
799 $notice = wfMsg( 'protectedpagewarning' );
801 $wgOut->addWikiText( $notice );
804 if ( $this->kblength === false ) {
805 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
807 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
808 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
809 } elseif( $this->kblength > 29 ) {
810 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
813 $rows = $wgUser->getOption( 'rows' );
814 $cols = $wgUser->getOption( 'cols' );
816 $ew = $wgUser->getOption( 'editwidth' );
817 if ( $ew ) $ew = " style=\"width:100%\"";
818 else $ew = '';
820 $q = 'action=submit';
821 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
822 $action = $this->mTitle->escapeLocalURL( $q );
824 $summary = wfMsg('summary');
825 $subject = wfMsg('subject');
826 $minor = wfMsg('minoredit');
827 $watchthis = wfMsg ('watchthis');
829 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
830 wfMsg('cancel') );
831 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
832 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
833 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
834 htmlspecialchars( wfMsg( 'newwindow' ) );
836 global $wgRightsText;
837 $copywarn = "<div id=\"editpage-copywarn\">\n" .
838 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
839 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
840 $wgRightsText ) . "\n</div>";
842 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
843 # prepare toolbar for edit buttons
844 $toolbar = $this->getEditToolbar();
845 } else {
846 $toolbar = '';
849 // activate checkboxes if user wants them to be always active
850 if( !$this->preview && !$this->diff ) {
851 # Sort out the "watch" checkbox
852 if( $wgUser->getOption( 'watchdefault' ) ) {
853 # Watch all edits
854 $this->watchthis = true;
855 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
856 # Watch creations
857 $this->watchthis = true;
858 } elseif( $this->mTitle->userIsWatching() ) {
859 # Already watched
860 $this->watchthis = true;
863 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
866 $minoredithtml = '';
868 if ( $wgUser->isAllowed('minoredit') ) {
869 $minoredithtml =
870 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
871 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
872 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
875 $watchhtml = '';
877 if ( $wgUser->isLoggedIn() ) {
878 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
879 ($this->watchthis?" checked='checked'":"").
880 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
881 "<label for='wpWatchthis' title=\"" .
882 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
885 $checkboxhtml = $minoredithtml . $watchhtml;
887 if ( $wgUser->getOption( 'previewontop' ) ) {
889 if ( 'preview' == $this->formtype ) {
890 $this->showPreview();
891 } else {
892 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
895 if ( 'diff' == $this->formtype ) {
896 $wgOut->addHTML( $this->getDiff() );
901 # if this is a comment, show a subject line at the top, which is also the edit summary.
902 # Otherwise, show a summary field at the bottom
903 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
904 if( $this->section == 'new' ) {
905 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span> <div class='editOptions'><input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
906 $editsummary = '';
907 } else {
908 $commentsubject = '';
909 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span> <div class='editOptions'><input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
912 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
913 if( !$this->preview && !$this->diff ) {
914 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
916 $templates = $this->formatTemplates();
918 global $wgUseMetadataEdit ;
919 if ( $wgUseMetadataEdit ) {
920 $metadata = $this->mMetaData ;
921 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
922 $helppage = Title::newFromText( wfMsg( "metadata_page" ) ) ;
923 $top = wfMsg( 'metadata', $helppage->getLocalURL() );
924 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
926 else $metadata = "" ;
928 $hidden = '';
929 $recreate = '';
930 if ($this->deletedSinceEdit) {
931 if ( 'save' != $this->formtype ) {
932 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
933 } else {
934 // Hide the toolbar and edit area, use can click preview to get it back
935 // Add an confirmation checkbox and explanation.
936 $toolbar = '';
937 $hidden = 'type="hidden" style="display:none;"';
938 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
939 $recreate .=
940 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
941 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
945 $temp = array(
946 'id' => 'wpSave',
947 'name' => 'wpSave',
948 'type' => 'submit',
949 'tabindex' => '5',
950 'value' => wfMsg('savearticle'),
951 'accesskey' => wfMsg('accesskey-save'),
952 'title' => wfMsg('tooltip-save'),
954 $buttons['save'] = wfElement('input', $temp, '');
955 $temp = array(
956 'id' => 'wpDiff',
957 'name' => 'wpDiff',
958 'type' => 'submit',
959 'tabindex' => '7',
960 'value' => wfMsg('showdiff'),
961 'accesskey' => wfMsg('accesskey-diff'),
962 'title' => wfMsg('tooltip-diff'),
964 $buttons['diff'] = wfElement('input', $temp, '');
966 global $wgLivePreview;
967 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
968 $temp = array(
969 'id' => 'wpPreview',
970 'name' => 'wpPreview',
971 'type' => 'submit',
972 'tabindex' => '6',
973 'value' => wfMsg('showpreview'),
974 'accesskey' => '',
975 'title' => wfMsg('tooltip-preview'),
976 'style' => 'display: none;',
978 $buttons['preview'] = wfElement('input', $temp, '');
979 $temp = array(
980 'id' => 'wpLivePreview',
981 'name' => 'wpLivePreview',
982 'type' => 'submit',
983 'tabindex' => '6',
984 'value' => wfMsg('showlivepreview'),
985 'accesskey' => wfMsg('accesskey-preview'),
986 'title' => '',
987 'onclick' => $this->doLivePreviewScript(),
989 $buttons['live'] = wfElement('input', $temp, '');
990 } else {
991 $temp = array(
992 'id' => 'wpPreview',
993 'name' => 'wpPreview',
994 'type' => 'submit',
995 'tabindex' => '6',
996 'value' => wfMsg('showpreview'),
997 'accesskey' => wfMsg('accesskey-preview'),
998 'title' => wfMsg('tooltip-preview'),
1000 $buttons['preview'] = wfElement('input', $temp, '');
1001 $buttons['live'] = '';
1004 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1005 ? ""
1006 : "<input type='hidden' name=\"safemode\" value='1' />\n";
1008 $wgOut->addHTML( <<<END
1009 {$toolbar}
1010 <form id="editform" name="editform" method="post" action="$action"
1011 enctype="multipart/form-data">
1015 if( is_callable( $formCallback ) ) {
1016 call_user_func_array( $formCallback, array( &$wgOut ) );
1019 // Put these up at the top to ensure they aren't lost on early form submission
1020 $wgOut->addHTML( "
1021 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1022 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1023 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1024 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1026 $wgOut->addHTML( <<<END
1027 $recreate
1028 {$commentsubject}
1029 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1030 cols='{$cols}'{$ew} $hidden>
1032 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1034 </textarea>
1035 " );
1037 $wgOut->addWikiText( $copywarn );
1038 $wgOut->addHTML( "
1039 {$metadata}
1040 {$editsummary}
1041 {$checkboxhtml}
1042 {$safemodehtml}
1045 $wgOut->addHTML("
1046 <div class='editButtons'>
1047 {$buttons['save']}
1048 {$buttons['preview']}
1049 {$buttons['live']}
1050 {$buttons['diff']}
1051 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1052 </div><!-- editButtons -->
1053 </div><!-- editOptions -->");
1055 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1057 $wgOut->addHTML( "
1058 <div class='templatesUsed'>
1059 {$templates}
1060 </div>
1061 " );
1063 if ( $wgUser->isLoggedIn() ) {
1065 * To make it harder for someone to slip a user a page
1066 * which submits an edit form to the wiki without their
1067 * knowledge, a random token is associated with the login
1068 * session. If it's not passed back with the submission,
1069 * we won't save the page, or render user JavaScript and
1070 * CSS previews.
1072 $token = htmlspecialchars( $wgUser->editToken() );
1073 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1076 # If a blank edit summary was previously provided, and the appropriate
1077 # user preference is active, pass a hidden tag here. This will stop the
1078 # user being bounced back more than once in the event that a summary
1079 # is not required.
1080 if( $this->missingSummary ) {
1081 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1084 # For a bit more sophisticated detection of blank summaries, hash the
1085 # automatic one and pass that in a hidden field.
1086 $autosumm = md5( $this->summary );
1087 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpAutoSummary\" value=\"$autosumm\" />\n" );
1089 if ( $this->isConflict ) {
1090 require_once( "DifferenceEngine.php" );
1091 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1093 $de = new DifferenceEngine( $this->mTitle );
1094 $de->setText( $this->textbox2, $this->textbox1 );
1095 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1097 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1098 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1099 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1101 $wgOut->addHTML( "</form>\n" );
1102 if ( !$wgUser->getOption( 'previewontop' ) ) {
1104 if ( $this->formtype == 'preview') {
1105 $this->showPreview();
1106 } else {
1107 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1110 if ( $this->formtype == 'diff') {
1111 $wgOut->addHTML( $this->getDiff() );
1116 wfProfileOut( $fname );
1120 * Append preview output to $wgOut.
1121 * Includes category rendering if this is a category page.
1122 * @access private
1124 function showPreview() {
1125 global $wgOut;
1126 $wgOut->addHTML( '<div id="wikiPreview">' );
1127 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1128 $this->mArticle->openShowCategory();
1130 $previewOutput = $this->getPreviewText();
1131 $wgOut->addHTML( $previewOutput );
1132 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1133 $this->mArticle->closeShowCategory();
1135 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
1136 $wgOut->addHTML( '</div>' );
1140 * Prepare a list of templates used by this page. Returns HTML.
1142 function formatTemplates() {
1143 global $wgUser;
1145 $fname = 'EditPage::formatTemplates';
1146 wfProfileIn( $fname );
1148 $sk =& $wgUser->getSkin();
1150 $outText = '';
1151 $templates = $this->mArticle->getUsedTemplates();
1152 if ( count( $templates ) > 0 ) {
1153 # Do a batch existence check
1154 $batch = new LinkBatch;
1155 foreach( $templates as $title ) {
1156 $batch->addObj( $title );
1158 $batch->execute();
1160 # Construct the HTML
1161 $outText = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
1162 foreach ( $templates as $titleObj ) {
1163 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
1165 $outText .= '</ul>';
1167 wfProfileOut( $fname );
1168 return $outText;
1172 * Live Preview lets us fetch rendered preview page content and
1173 * add it to the page without refreshing the whole page.
1174 * If not supported by the browser it will fall through to the normal form
1175 * submission method.
1177 * This function outputs a script tag to support live preview, and
1178 * returns an onclick handler which should be added to the attributes
1179 * of the preview button
1181 function doLivePreviewScript() {
1182 global $wgStylePath, $wgJsMimeType, $wgOut, $wgTitle;
1183 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1184 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
1185 '"></script>' . "\n" );
1186 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1187 return "return !livePreview(" .
1188 "getElementById('wikiPreview')," .
1189 "editform.wpTextbox1.value," .
1190 '"' . $liveAction . '"' . ")";
1193 function getLastDelete() {
1194 $dbr =& wfGetDB( DB_SLAVE );
1195 $fname = 'EditPage::getLastDelete';
1196 $res = $dbr->select(
1197 array( 'logging', 'user' ),
1198 array( 'log_type',
1199 'log_action',
1200 'log_timestamp',
1201 'log_user',
1202 'log_namespace',
1203 'log_title',
1204 'log_comment',
1205 'log_params',
1206 'user_name', ),
1207 array( 'log_namespace' => $this->mTitle->getNamespace(),
1208 'log_title' => $this->mTitle->getDBkey(),
1209 'log_type' => 'delete',
1210 'log_action' => 'delete',
1211 'user_id=log_user' ),
1212 $fname,
1213 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1215 if($dbr->numRows($res) == 1) {
1216 while ( $x = $dbr->fetchObject ( $res ) )
1217 $data = $x;
1218 $dbr->freeResult ( $res ) ;
1219 } else {
1220 $data = null;
1222 return $data;
1226 * @todo document
1228 function getPreviewText() {
1229 global $wgOut, $wgUser, $wgTitle, $wgParser;
1231 $fname = 'EditPage::getPreviewText';
1232 wfProfileIn( $fname );
1234 if ( $this->mTokenOk ) {
1235 $msg = 'previewnote';
1236 } else {
1237 $msg = 'session_fail_preview';
1239 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1240 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1241 if ( $this->isConflict ) {
1242 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1245 $parserOptions = ParserOptions::newFromUser( $wgUser );
1246 $parserOptions->setEditSection( false );
1248 # don't parse user css/js, show message about preview
1249 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1251 if ( $this->isCssJsSubpage ) {
1252 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1253 $previewtext = wfMsg('usercsspreview');
1254 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1255 $previewtext = wfMsg('userjspreview');
1257 $parserOptions->setTidy(true);
1258 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1259 $wgOut->addHTML( $parserOutput->mText );
1260 wfProfileOut( $fname );
1261 return $previewhead;
1262 } else {
1263 # if user want to see preview when he edit an article
1264 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
1265 $this->textbox1 = $this->mArticle->getContent();
1268 $toparse = $this->textbox1;
1270 # If we're adding a comment, we need to show the
1271 # summary as the headline
1272 if($this->section=="new" && $this->summary!="") {
1273 $toparse="== {$this->summary} ==\n\n".$toparse;
1276 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1277 $parserOptions->setTidy(true);
1278 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1279 $wgTitle, $parserOptions );
1281 $previewHTML = $parserOutput->getText();
1282 $wgOut->addParserOutputNoText( $parserOutput );
1284 wfProfileOut( $fname );
1285 return $previewhead . $previewHTML;
1290 * @todo document
1292 function blockedIPpage() {
1293 global $wgOut;
1294 $wgOut->blockedPage();
1298 * @todo document
1300 function userNotLoggedInPage() {
1301 global $wgOut;
1303 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1304 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1305 $wgOut->setArticleRelated( false );
1307 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
1308 $wgOut->returnToMain( false );
1312 * Creates a basic error page which informs the user that
1313 * they have to validate their email address before being
1314 * allowed to edit.
1316 function userNotConfirmedPage() {
1318 global $wgOut;
1320 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1321 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1322 $wgOut->setArticleRelated( false );
1323 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1324 $wgOut->returnToMain( false );
1328 * @todo document
1330 function spamPage ( $match = false )
1332 global $wgOut;
1333 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1334 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1335 $wgOut->setArticleRelated( false );
1337 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1338 if ( $match ) {
1339 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1341 $wgOut->returnToMain( false );
1345 * @access private
1346 * @todo document
1348 function mergeChangesInto( &$editText ){
1349 $fname = 'EditPage::mergeChangesInto';
1350 wfProfileIn( $fname );
1352 $db =& wfGetDB( DB_MASTER );
1354 // This is the revision the editor started from
1355 $baseRevision = Revision::loadFromTimestamp(
1356 $db, $this->mArticle->mTitle, $this->edittime );
1357 if( is_null( $baseRevision ) ) {
1358 wfProfileOut( $fname );
1359 return false;
1361 $baseText = $baseRevision->getText();
1363 // The current state, we want to merge updates into it
1364 $currentRevision = Revision::loadFromTitle(
1365 $db, $this->mArticle->mTitle );
1366 if( is_null( $currentRevision ) ) {
1367 wfProfileOut( $fname );
1368 return false;
1370 $currentText = $currentRevision->getText();
1372 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1373 $editText = $result;
1374 wfProfileOut( $fname );
1375 return true;
1376 } else {
1377 wfProfileOut( $fname );
1378 return false;
1383 * Check if the browser is on a blacklist of user-agents known to
1384 * mangle UTF-8 data on form submission. Returns true if Unicode
1385 * should make it through, false if it's known to be a problem.
1386 * @return bool
1387 * @access private
1389 function checkUnicodeCompliantBrowser() {
1390 global $wgBrowserBlackList;
1391 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1392 // No User-Agent header sent? Trust it by default...
1393 return true;
1395 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1396 foreach ( $wgBrowserBlackList as $browser ) {
1397 if ( preg_match($browser, $currentbrowser) ) {
1398 return false;
1401 return true;
1405 * Format an anchor fragment as it would appear for a given section name
1406 * @param string $text
1407 * @return string
1408 * @access private
1410 function sectionAnchor( $text ) {
1411 $headline = Sanitizer::decodeCharReferences( $text );
1412 # strip out HTML
1413 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1414 $headline = trim( $headline );
1415 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1416 $replacearray = array(
1417 '%3A' => ':',
1418 '%' => '.'
1420 return str_replace(
1421 array_keys( $replacearray ),
1422 array_values( $replacearray ),
1423 $sectionanchor );
1427 * Shows a bulletin board style toolbar for common editing functions.
1428 * It can be disabled in the user preferences.
1429 * The necessary JavaScript code can be found in style/wikibits.js.
1431 function getEditToolbar() {
1432 global $wgStylePath, $wgContLang, $wgJsMimeType;
1435 * toolarray an array of arrays which each include the filename of
1436 * the button image (without path), the opening tag, the closing tag,
1437 * and optionally a sample text that is inserted between the two when no
1438 * selection is highlighted.
1439 * The tip text is shown when the user moves the mouse over the button.
1441 * Already here are accesskeys (key), which are not used yet until someone
1442 * can figure out a way to make them work in IE. However, we should make
1443 * sure these keys are not defined on the edit page.
1445 $toolarray=array(
1446 array( 'image'=>'button_bold.png',
1447 'open' => "\'\'\'",
1448 'close' => "\'\'\'",
1449 'sample'=> wfMsg('bold_sample'),
1450 'tip' => wfMsg('bold_tip'),
1451 'key' => 'B'
1453 array( 'image'=>'button_italic.png',
1454 'open' => "\'\'",
1455 'close' => "\'\'",
1456 'sample'=> wfMsg('italic_sample'),
1457 'tip' => wfMsg('italic_tip'),
1458 'key' => 'I'
1460 array( 'image'=>'button_link.png',
1461 'open' => '[[',
1462 'close' => ']]',
1463 'sample'=> wfMsg('link_sample'),
1464 'tip' => wfMsg('link_tip'),
1465 'key' => 'L'
1467 array( 'image'=>'button_extlink.png',
1468 'open' => '[',
1469 'close' => ']',
1470 'sample'=> wfMsg('extlink_sample'),
1471 'tip' => wfMsg('extlink_tip'),
1472 'key' => 'X'
1474 array( 'image'=>'button_headline.png',
1475 'open' => "\\n== ",
1476 'close' => " ==\\n",
1477 'sample'=> wfMsg('headline_sample'),
1478 'tip' => wfMsg('headline_tip'),
1479 'key' => 'H'
1481 array( 'image'=>'button_image.png',
1482 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1483 'close' => ']]',
1484 'sample'=> wfMsg('image_sample'),
1485 'tip' => wfMsg('image_tip'),
1486 'key' => 'D'
1488 array( 'image' =>'button_media.png',
1489 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1490 'close' => ']]',
1491 'sample'=> wfMsg('media_sample'),
1492 'tip' => wfMsg('media_tip'),
1493 'key' => 'M'
1495 array( 'image' =>'button_math.png',
1496 'open' => "\\<math\\>",
1497 'close' => "\\</math\\>",
1498 'sample'=> wfMsg('math_sample'),
1499 'tip' => wfMsg('math_tip'),
1500 'key' => 'C'
1502 array( 'image' =>'button_nowiki.png',
1503 'open' => "\\<nowiki\\>",
1504 'close' => "\\</nowiki\\>",
1505 'sample'=> wfMsg('nowiki_sample'),
1506 'tip' => wfMsg('nowiki_tip'),
1507 'key' => 'N'
1509 array( 'image' =>'button_sig.png',
1510 'open' => '--~~~~',
1511 'close' => '',
1512 'sample'=> '',
1513 'tip' => wfMsg('sig_tip'),
1514 'key' => 'Y'
1516 array( 'image' =>'button_hr.png',
1517 'open' => "\\n----\\n",
1518 'close' => '',
1519 'sample'=> '',
1520 'tip' => wfMsg('hr_tip'),
1521 'key' => 'R'
1524 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1526 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1527 foreach($toolarray as $tool) {
1529 $image=$wgStylePath.'/common/images/'.$tool['image'];
1530 $open=$tool['open'];
1531 $close=$tool['close'];
1532 $sample = wfEscapeJsString( $tool['sample'] );
1534 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1535 // Older browsers show a "speedtip" type message only for ALT.
1536 // Ideally these should be different, realistically they
1537 // probably don't need to be.
1538 $tip = wfEscapeJsString( $tool['tip'] );
1540 #$key = $tool["key"];
1542 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1545 $toolbar.="document.writeln(\"</div>\");\n";
1546 $toolbar.="/*]]>*/\n</script>";
1547 return $toolbar;
1551 * Output preview text only. This can be sucked into the edit page
1552 * via JavaScript, and saves the server time rendering the skin as
1553 * well as theoretically being more robust on the client (doesn't
1554 * disturb the edit box's undo history, won't eat your text on
1555 * failure, etc).
1557 * @todo This doesn't include category or interlanguage links.
1558 * Would need to enhance it a bit, maybe wrap them in XML
1559 * or something... that might also require more skin
1560 * initialization, so check whether that's a problem.
1562 function livePreview() {
1563 global $wgOut;
1564 $wgOut->disable();
1565 header( 'Content-type: text/xml' );
1566 header( 'Cache-control: no-cache' );
1567 # FIXME
1568 echo $this->getPreviewText( );
1569 /* To not shake screen up and down between preview and live-preview */
1570 echo "<br style=\"clear:both;\" />\n";
1575 * Get a diff between the current contents of the edit box and the
1576 * version of the page we're editing from.
1578 * If this is a section edit, we'll replace the section as for final
1579 * save and then make a comparison.
1581 * @return string HTML
1583 function getDiff() {
1584 require_once( 'DifferenceEngine.php' );
1585 $oldtext = $this->mArticle->fetchContent();
1586 $newtext = $this->mArticle->replaceSection(
1587 $this->section, $this->textbox1, $this->summary, $this->edittime );
1588 $oldtitle = wfMsg( 'currentrev' );
1589 $newtitle = wfMsg( 'yourtext' );
1590 if ( $oldtext !== false || $newtext != '' ) {
1591 $de = new DifferenceEngine( $this->mTitle );
1592 $de->setText( $oldtext, $newtext );
1593 $difftext = $de->getDiff( $oldtitle, $newtitle );
1594 } else {
1595 $difftext = '';
1598 return '<div id="wikiDiff">' . $difftext . '</div>';
1602 * Filter an input field through a Unicode de-armoring process if it
1603 * came from an old browser with known broken Unicode editing issues.
1605 * @param WebRequest $request
1606 * @param string $field
1607 * @return string
1608 * @access private
1610 function safeUnicodeInput( $request, $field ) {
1611 $text = rtrim( $request->getText( $field ) );
1612 return $request->getBool( 'safemode' )
1613 ? $this->unmakesafe( $text )
1614 : $text;
1618 * Filter an output field through a Unicode armoring process if it is
1619 * going to an old browser with known broken Unicode editing issues.
1621 * @param string $text
1622 * @return string
1623 * @access private
1625 function safeUnicodeOutput( $text ) {
1626 global $wgContLang;
1627 $codedText = $wgContLang->recodeForEdit( $text );
1628 return $this->checkUnicodeCompliantBrowser()
1629 ? $codedText
1630 : $this->makesafe( $codedText );
1634 * A number of web browsers are known to corrupt non-ASCII characters
1635 * in a UTF-8 text editing environment. To protect against this,
1636 * detected browsers will be served an armored version of the text,
1637 * with non-ASCII chars converted to numeric HTML character references.
1639 * Preexisting such character references will have a 0 added to them
1640 * to ensure that round-trips do not alter the original data.
1642 * @param string $invalue
1643 * @return string
1644 * @access private
1646 function makesafe( $invalue ) {
1647 // Armor existing references for reversability.
1648 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1650 $bytesleft = 0;
1651 $result = "";
1652 $working = 0;
1653 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1654 $bytevalue = ord( $invalue{$i} );
1655 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1656 $result .= chr( $bytevalue );
1657 $bytesleft = 0;
1658 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1659 $working = $working << 6;
1660 $working += ($bytevalue & 0x3F);
1661 $bytesleft--;
1662 if( $bytesleft <= 0 ) {
1663 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1665 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1666 $working = $bytevalue & 0x1F;
1667 $bytesleft = 1;
1668 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1669 $working = $bytevalue & 0x0F;
1670 $bytesleft = 2;
1671 } else { //1111 0xxx
1672 $working = $bytevalue & 0x07;
1673 $bytesleft = 3;
1676 return $result;
1680 * Reverse the previously applied transliteration of non-ASCII characters
1681 * back to UTF-8. Used to protect data from corruption by broken web browsers
1682 * as listed in $wgBrowserBlackList.
1684 * @param string $invalue
1685 * @return string
1686 * @access private
1688 function unmakesafe( $invalue ) {
1689 $result = "";
1690 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1691 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1692 $i += 3;
1693 $hexstring = "";
1694 do {
1695 $hexstring .= $invalue{$i};
1696 $i++;
1697 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1699 // Do some sanity checks. These aren't needed for reversability,
1700 // but should help keep the breakage down if the editor
1701 // breaks one of the entities whilst editing.
1702 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1703 $codepoint = hexdec($hexstring);
1704 $result .= codepointToUtf8( $codepoint );
1705 } else {
1706 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1708 } else {
1709 $result .= substr( $invalue, $i, 1 );
1712 // reverse the transform that we made for reversability reasons.
1713 return strtr( $result, array( "&#x0" => "&#x" ) );
1716 function noCreatePermission() {
1717 global $wgOut;
1718 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1719 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );