German translation of the title, c/o Leon
[mediawiki.git] / includes / EditPage.php
bloba3c98d676f1da11017e69c4030d2a1575c7d698d
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 = false;
27 var $mTriedSave = false;
28 var $tooBig = false;
29 var $kblength = false;
30 var $missingComment = false;
31 var $missingSummary = false;
32 var $allowBlankSummary = false;
33 var $autoSumm = '';
34 var $hookError = '';
36 # Form values
37 var $save = false, $preview = false, $diff = false;
38 var $minoredit = false, $watchthis = false, $recreate = false;
39 var $textbox1 = '', $textbox2 = '', $summary = '';
40 var $edittime = '', $section = '', $starttime = '';
41 var $oldid = 0, $editintro = '', $scrolltop = null;
43 /**
44 * @todo document
45 * @param $article
47 function EditPage( $article ) {
48 $this->mArticle =& $article;
49 global $wgTitle;
50 $this->mTitle =& $wgTitle;
53 /**
54 * This is the function that extracts metadata from the article body on the first view.
55 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
56 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
58 function extractMetaDataFromArticle () {
59 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
60 $this->mMetaData = '' ;
61 if ( !$wgUseMetadataEdit ) return ;
62 if ( $wgMetadataWhitelist == '' ) return ;
63 $s = '' ;
64 $t = $this->mArticle->getContent();
66 # MISSING : <nowiki> filtering
68 # Categories and language links
69 $t = explode ( "\n" , $t ) ;
70 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
71 $cat = $ll = array() ;
72 foreach ( $t AS $key => $x )
74 $y = trim ( strtolower ( $x ) ) ;
75 while ( substr ( $y , 0 , 2 ) == '[[' )
77 $y = explode ( ']]' , trim ( $x ) ) ;
78 $first = array_shift ( $y ) ;
79 $first = explode ( ':' , $first ) ;
80 $ns = array_shift ( $first ) ;
81 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
82 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
84 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
85 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
86 else $ll[] = $add ;
87 $x = implode ( ']]' , $y ) ;
88 $t[$key] = $x ;
89 $y = trim ( strtolower ( $x ) ) ;
93 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
94 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
95 $t = implode ( "\n" , $t ) ;
97 # Load whitelist
98 $sat = array () ; # stand-alone-templates; must be lowercase
99 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
100 $wl_article = new Article ( $wl_title ) ;
101 $wl = explode ( "\n" , $wl_article->getContent() ) ;
102 foreach ( $wl AS $x )
104 $isentry = false ;
105 $x = trim ( $x ) ;
106 while ( substr ( $x , 0 , 1 ) == '*' )
108 $isentry = true ;
109 $x = trim ( substr ( $x , 1 ) ) ;
111 if ( $isentry )
113 $sat[] = strtolower ( $x ) ;
118 # Templates, but only some
119 $t = explode ( '{{' , $t ) ;
120 $tl = array () ;
121 foreach ( $t AS $key => $x )
123 $y = explode ( '}}' , $x , 2 ) ;
124 if ( count ( $y ) == 2 )
126 $z = $y[0] ;
127 $z = explode ( '|' , $z ) ;
128 $tn = array_shift ( $z ) ;
129 if ( in_array ( strtolower ( $tn ) , $sat ) )
131 $tl[] = '{{' . $y[0] . '}}' ;
132 $t[$key] = $y[1] ;
133 $y = explode ( '}}' , $y[1] , 2 ) ;
135 else $t[$key] = '{{' . $x ;
137 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
138 else $t[$key] = $x ;
140 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
141 $t = implode ( '' , $t ) ;
143 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
144 $this->mArticle->mContent = $t ;
145 $this->mMetaData = $s ;
148 function submit() {
149 $this->edit();
153 * This is the function that gets called for "action=edit". It
154 * sets up various member variables, then passes execution to
155 * another function, usually showEditForm()
157 * The edit form is self-submitting, so that when things like
158 * preview and edit conflicts occur, we get the same form back
159 * with the extra stuff added. Only when the final submission
160 * is made and all is well do we actually save and redirect to
161 * the newly-edited page.
163 function edit() {
164 global $wgOut, $wgUser, $wgRequest, $wgTitle;
165 global $wgEmailConfirmToEdit;
167 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
168 return;
170 $fname = 'EditPage::edit';
171 wfProfileIn( $fname );
172 wfDebug( "$fname: enter\n" );
174 // this is not an article
175 $wgOut->setArticleFlag(false);
177 $this->importFormData( $wgRequest );
178 $this->firsttime = false;
180 if( $this->live ) {
181 $this->livePreview();
182 wfProfileOut( $fname );
183 return;
186 if ( ! $this->mTitle->userCanEdit() ) {
187 wfDebug( "$fname: user can't edit\n" );
188 $wgOut->readOnlyPage( $this->mArticle->getContent(), true );
189 wfProfileOut( $fname );
190 return;
192 wfDebug( "$fname: Checking blocks\n" );
193 if ( !$this->preview && !$this->diff && $wgUser->isBlockedFrom( $this->mTitle, !$this->save ) ) {
194 # When previewing, don't check blocked state - will get caught at save time.
195 # Also, check when starting edition is done against slave to improve performance.
196 wfDebug( "$fname: user is blocked\n" );
197 $wgOut->blockedPage();
198 wfProfileOut( $fname );
199 return;
201 if ( !$wgUser->isAllowed('edit') ) {
202 if ( $wgUser->isAnon() ) {
203 wfDebug( "$fname: user must log in\n" );
204 $this->userNotLoggedInPage();
205 wfProfileOut( $fname );
206 return;
207 } else {
208 wfDebug( "$fname: read-only page\n" );
209 $wgOut->readOnlyPage( $this->mArticle->getContent(), true );
210 wfProfileOut( $fname );
211 return;
214 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
215 wfDebug("$fname: user must confirm e-mail address\n");
216 $this->userNotConfirmedPage();
217 wfProfileOut($fname);
218 return;
220 if ( !$this->mTitle->userCan( 'create' ) && !$this->mTitle->exists() ) {
221 wfDebug( "$fname: no create permission\n" );
222 $this->noCreatePermission();
223 wfProfileOut( $fname );
224 return;
226 if ( wfReadOnly() ) {
227 wfDebug( "$fname: read-only mode is engaged\n" );
228 if( $this->save || $this->preview ) {
229 $this->formtype = 'preview';
230 } else if ( $this->diff ) {
231 $this->formtype = 'diff';
232 } else {
233 $wgOut->readOnlyPage( $this->mArticle->getContent() );
234 wfProfileOut( $fname );
235 return;
237 } else {
238 if ( $this->save ) {
239 $this->formtype = 'save';
240 } else if ( $this->preview ) {
241 $this->formtype = 'preview';
242 } else if ( $this->diff ) {
243 $this->formtype = 'diff';
244 } else { # First time through
245 $this->firsttime = true;
246 if( $this->previewOnOpen() ) {
247 $this->formtype = 'preview';
248 } else {
249 $this->extractMetaDataFromArticle () ;
250 $this->formtype = 'initial';
255 wfProfileIn( "$fname-business-end" );
257 $this->isConflict = false;
258 // css / js subpages of user pages get a special treatment
259 $this->isCssJsSubpage = $wgTitle->isCssJsSubpage();
260 $this->isValidCssJsSubpage = $wgTitle->isValidCssJsSubpage();
262 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
263 * no matter it's current state
265 $this->deletedSinceEdit = false;
266 if ( $this->edittime != '' ) {
267 /* Note that we rely on logging table, which hasn't been always there,
268 * but that doesn't matter, because this only applies to brand new
269 * deletes. This is done on every preview and save request. Move it further down
270 * to only perform it on saves
272 if ( $this->mTitle->isDeleted() ) {
273 $this->lastDelete = $this->getLastDelete();
274 if ( !is_null($this->lastDelete) ) {
275 $deletetime = $this->lastDelete->log_timestamp;
276 if ( ($deletetime - $this->starttime) > 0 ) {
277 $this->deletedSinceEdit = true;
283 if(!$this->mTitle->getArticleID() && ('initial' == $this->formtype || $this->firsttime )) { # new article
284 $this->showIntro();
286 if( $this->mTitle->isTalkPage() ) {
287 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
290 # Attempt submission here. This will check for edit conflicts,
291 # and redundantly check for locked database, blocked IPs, etc.
292 # that edit() already checked just in case someone tries to sneak
293 # in the back door with a hand-edited submission URL.
295 if ( 'save' == $this->formtype ) {
296 if ( !$this->attemptSave() ) {
297 wfProfileOut( "$fname-business-end" );
298 wfProfileOut( $fname );
299 return;
303 # First time through: get contents, set time for conflict
304 # checking, etc.
305 if ( 'initial' == $this->formtype || $this->firsttime ) {
306 $this->initialiseForm();
307 if( !$this->mTitle->getArticleId() )
308 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
311 $this->showEditForm();
312 wfProfileOut( "$fname-business-end" );
313 wfProfileOut( $fname );
317 * Return true if this page should be previewed when the edit form
318 * is initially opened.
319 * @return bool
320 * @private
322 function previewOnOpen() {
323 global $wgUser;
324 return $this->section != 'new' &&
325 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle->exists() ) ||
326 ( $this->mTitle->getNamespace() == NS_CATEGORY &&
327 !$this->mTitle->exists() ) );
331 * @todo document
332 * @param $request
334 function importFormData( &$request ) {
335 global $wgLang, $wgUser;
336 $fname = 'EditPage::importFormData';
337 wfProfileIn( $fname );
339 if( $request->wasPosted() ) {
340 # These fields need to be checked for encoding.
341 # Also remove trailing whitespace, but don't remove _initial_
342 # whitespace from the text boxes. This may be significant formatting.
343 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
344 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
345 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
346 # Truncate for whole multibyte characters. +5 bytes for ellipsis
347 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
349 $this->edittime = $request->getVal( 'wpEdittime' );
350 $this->starttime = $request->getVal( 'wpStarttime' );
352 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
354 if( is_null( $this->edittime ) ) {
355 # If the form is incomplete, force to preview.
356 wfDebug( "$fname: Form data appears to be incomplete\n" );
357 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
358 $this->preview = true;
359 } else {
360 /* Fallback for live preview */
361 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
362 $this->diff = $request->getCheck( 'wpDiff' );
364 // Remember whether a save was requested, so we can indicate
365 // if we forced preview due to session failure.
366 $this->mTriedSave = !$this->preview;
368 if ( $this->tokenOk( $request ) ) {
369 # Some browsers will not report any submit button
370 # if the user hits enter in the comment box.
371 # The unmarked state will be assumed to be a save,
372 # if the form seems otherwise complete.
373 wfDebug( "$fname: Passed token check.\n" );
374 } else {
375 # Page might be a hack attempt posted from
376 # an external site. Preview instead of saving.
377 wfDebug( "$fname: Failed token check; forcing preview\n" );
378 $this->preview = true;
381 $this->save = ! ( $this->preview OR $this->diff );
382 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
383 $this->edittime = null;
386 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
387 $this->starttime = null;
390 $this->recreate = $request->getCheck( 'wpRecreate' );
392 $this->minoredit = $request->getCheck( 'wpMinoredit' );
393 $this->watchthis = $request->getCheck( 'wpWatchthis' );
395 # Don't force edit summaries when a user is editing their own user or talk page
396 if( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) && $this->mTitle->getText() == $wgUser->getName() ) {
397 $this->allowBlankSummary = true;
398 } else {
399 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
402 $this->autoSumm = $request->getText( 'wpAutoSummary' );
403 } else {
404 # Not a posted form? Start with nothing.
405 wfDebug( "$fname: Not a posted form.\n" );
406 $this->textbox1 = '';
407 $this->textbox2 = '';
408 $this->mMetaData = '';
409 $this->summary = '';
410 $this->edittime = '';
411 $this->starttime = wfTimestampNow();
412 $this->preview = false;
413 $this->save = false;
414 $this->diff = false;
415 $this->minoredit = false;
416 $this->watchthis = false;
417 $this->recreate = false;
420 $this->oldid = $request->getInt( 'oldid' );
422 # Section edit can come from either the form or a link
423 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
425 $this->live = $request->getCheck( 'live' );
426 $this->editintro = $request->getText( 'editintro' );
428 wfProfileOut( $fname );
432 * Make sure the form isn't faking a user's credentials.
434 * @param $request WebRequest
435 * @return bool
436 * @private
438 function tokenOk( &$request ) {
439 global $wgUser;
440 if( $wgUser->isAnon() ) {
441 # Anonymous users may not have a session
442 # open. Don't tokenize.
443 $this->mTokenOk = true;
444 } else {
445 $this->mTokenOk = $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
447 return $this->mTokenOk;
450 /** */
451 function showIntro() {
452 global $wgOut, $wgUser;
453 $addstandardintro=true;
454 if($this->editintro) {
455 $introtitle=Title::newFromText($this->editintro);
456 if(isset($introtitle) && $introtitle->userCanRead()) {
457 $rev=Revision::newFromTitle($introtitle);
458 if($rev) {
459 $wgOut->addSecondaryWikiText($rev->getText());
460 $addstandardintro=false;
464 if($addstandardintro) {
465 if ( $wgUser->isLoggedIn() )
466 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
467 else
468 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
473 * Attempt submission
474 * @return bool false if output is done, true if the rest of the form should be displayed
476 function attemptSave() {
477 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
478 global $wgMaxArticleSize;
480 $fname = 'EditPage::attemptSave';
481 wfProfileIn( $fname );
482 wfProfileIn( "$fname-checks" );
484 # Reintegrate metadata
485 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
486 $this->mMetaData = '' ;
488 # Check for spam
489 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
490 $this->spamPage ( $matches[0] );
491 wfProfileOut( "$fname-checks" );
492 wfProfileOut( $fname );
493 return false;
495 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
496 # Error messages or other handling should be performed by the filter function
497 wfProfileOut( $fname );
498 wfProfileOut( "$fname-checks" );
499 return false;
501 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError ) ) ) {
502 # Error messages etc. could be handled within the hook...
503 wfProfileOut( $fname );
504 wfProfileOut( "$fname-checks" );
505 return false;
506 } elseif( $this->hookError != '' ) {
507 # ...or the hook could be expecting us to produce an error
508 wfProfileOut( "$fname-checks " );
509 wfProfileOut( $fname );
510 return true;
512 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
513 # Check block state against master, thus 'false'.
514 $this->blockedIPpage();
515 wfProfileOut( "$fname-checks" );
516 wfProfileOut( $fname );
517 return false;
519 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
520 if ( $this->kblength > $wgMaxArticleSize ) {
521 // Error will be displayed by showEditForm()
522 $this->tooBig = true;
523 wfProfileOut( "$fname-checks" );
524 wfProfileOut( $fname );
525 return true;
528 if ( !$wgUser->isAllowed('edit') ) {
529 if ( $wgUser->isAnon() ) {
530 $this->userNotLoggedInPage();
531 wfProfileOut( "$fname-checks" );
532 wfProfileOut( $fname );
533 return false;
535 else {
536 $wgOut->readOnlyPage();
537 wfProfileOut( "$fname-checks" );
538 wfProfileOut( $fname );
539 return false;
543 if ( wfReadOnly() ) {
544 $wgOut->readOnlyPage();
545 wfProfileOut( "$fname-checks" );
546 wfProfileOut( $fname );
547 return false;
549 if ( $wgUser->pingLimiter() ) {
550 $wgOut->rateLimited();
551 wfProfileOut( "$fname-checks" );
552 wfProfileOut( $fname );
553 return false;
556 # If the article has been deleted while editing, don't save it without
557 # confirmation
558 if ( $this->deletedSinceEdit && !$this->recreate ) {
559 wfProfileOut( "$fname-checks" );
560 wfProfileOut( $fname );
561 return true;
564 wfProfileOut( "$fname-checks" );
566 # If article is new, insert it.
567 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
568 if ( 0 == $aid ) {
569 // Late check for create permission, just in case *PARANOIA*
570 if ( !$this->mTitle->userCan( 'create' ) ) {
571 wfDebug( "$fname: no create permission\n" );
572 $this->noCreatePermission();
573 wfProfileOut( $fname );
574 return;
577 # Don't save a new article if it's blank.
578 if ( ( '' == $this->textbox1 ) ) {
579 $wgOut->redirect( $this->mTitle->getFullURL() );
580 wfProfileOut( $fname );
581 return false;
584 # If no edit comment was given when creating a new page, and what's being
585 # created is a redirect, be smart and fill in a neat auto-comment
586 if( $this->summary == '' ) {
587 $rt = Title::newFromRedirect( $this->textbox1 );
588 if( is_object( $rt ) )
589 $this->summary = wfMsgForContent( 'autoredircomment', $rt->getPrefixedText() );
592 $isComment=($this->section=='new');
593 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
594 $this->minoredit, $this->watchthis, false, $isComment);
596 wfProfileOut( $fname );
597 return false;
600 # Article exists. Check for edit conflict.
602 $this->mArticle->clear(); # Force reload of dates, etc.
603 $this->mArticle->forUpdate( true ); # Lock the article
605 if( $this->mArticle->getTimestamp() != $this->edittime ) {
606 $this->isConflict = true;
607 if( $this->section == 'new' ) {
608 if( $this->mArticle->getUserText() == $wgUser->getName() &&
609 $this->mArticle->getComment() == $this->summary ) {
610 // Probably a duplicate submission of a new comment.
611 // This can happen when squid resends a request after
612 // a timeout but the first one actually went through.
613 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
614 } else {
615 // New comment; suppress conflict.
616 $this->isConflict = false;
617 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
621 $userid = $wgUser->getID();
623 if ( $this->isConflict) {
624 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
625 $this->mArticle->getTimestamp() . "'\n" );
626 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
628 else {
629 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
630 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
632 if( is_null( $text ) ) {
633 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
634 $this->isConflict = true;
635 $text = $this->textbox1;
638 # Suppress edit conflict with self, except for section edits where merging is required.
639 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
640 wfDebug( "Suppressing edit conflict, same user.\n" );
641 $this->isConflict = false;
642 } else {
643 # switch from section editing to normal editing in edit conflict
644 if($this->isConflict) {
645 # Attempt merge
646 if( $this->mergeChangesInto( $text ) ){
647 // Successful merge! Maybe we should tell the user the good news?
648 $this->isConflict = false;
649 wfDebug( "Suppressing edit conflict, successful merge.\n" );
650 } else {
651 $this->section = '';
652 $this->textbox1 = $text;
653 wfDebug( "Keeping edit conflict, failed merge.\n" );
658 if ( $this->isConflict ) {
659 wfProfileOut( $fname );
660 return true;
663 # If no edit comment was given when turning a page into a redirect, be smart
664 # and fill in a neat auto-comment
665 if( $this->summary == '' ) {
666 $rt = Title::newFromRedirect( $this->textbox1 );
667 if( is_object( $rt ) )
668 $this->summary = wfMsgForContent( 'autoredircomment', $rt->getPrefixedText() );
671 # Handle the user preference to force summaries here
672 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
673 if( md5( $this->summary ) == $this->autoSumm ) {
674 $this->missingSummary = true;
675 wfProfileOut( $fname );
676 return( true );
680 # All's well
681 wfProfileIn( "$fname-sectionanchor" );
682 $sectionanchor = '';
683 if( $this->section == 'new' ) {
684 if ( $this->textbox1 == '' ) {
685 $this->missingComment = true;
686 return true;
688 if( $this->summary != '' ) {
689 $sectionanchor = $this->sectionAnchor( $this->summary );
691 } elseif( $this->section != '' ) {
692 # Try to get a section anchor from the section source, redirect to edited section if header found
693 # XXX: might be better to integrate this into Article::replaceSection
694 # for duplicate heading checking and maybe parsing
695 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
696 # we can't deal with anchors, includes, html etc in the header for now,
697 # headline would need to be parsed to improve this
698 if($hasmatch and strlen($matches[2]) > 0) {
699 $sectionanchor = $this->sectionAnchor( $matches[2] );
702 wfProfileOut( "$fname-sectionanchor" );
704 // Save errors may fall down to the edit form, but we've now
705 // merged the section into full text. Clear the section field
706 // so that later submission of conflict forms won't try to
707 // replace that into a duplicated mess.
708 $this->textbox1 = $text;
709 $this->section = '';
711 // Check for length errors again now that the section is merged in
712 $this->kblength = (int)(strlen( $text ) / 1024);
713 if ( $this->kblength > $wgMaxArticleSize ) {
714 $this->tooBig = true;
715 wfProfileOut( $fname );
716 return true;
719 # update the article here
720 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
721 $this->watchthis, '', $sectionanchor ) ) {
722 wfProfileOut( $fname );
723 return false;
724 } else {
725 $this->isConflict = true;
727 wfProfileOut( $fname );
728 return true;
732 * Initialise form fields in the object
733 * Called on the first invocation, e.g. when a user clicks an edit link
735 function initialiseForm() {
736 $this->edittime = $this->mArticle->getTimestamp();
737 $this->textbox1 = $this->mArticle->getContent();
738 $this->summary = '';
739 if ( !$this->mArticle->exists() && $this->mArticle->mTitle->getNamespace() == NS_MEDIAWIKI )
740 $this->textbox1 = wfMsgWeirdKey ( $this->mArticle->mTitle->getText() ) ;
741 wfProxyCheck();
745 * Send the edit form and related headers to $wgOut
746 * @param $formCallback Optional callable that takes an OutputPage
747 * parameter; will be called during form output
748 * near the top, for captchas and the like.
750 function showEditForm( $formCallback=null ) {
751 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
753 $fname = 'EditPage::showEditForm';
754 wfProfileIn( $fname );
756 $sk =& $wgUser->getSkin();
758 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
760 $wgOut->setRobotpolicy( 'noindex,nofollow' );
762 # Enabled article-related sidebar, toplinks, etc.
763 $wgOut->setArticleRelated( true );
765 if ( $this->isConflict ) {
766 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
767 $wgOut->setPageTitle( $s );
768 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
770 $this->textbox2 = $this->textbox1;
771 $this->textbox1 = $this->mArticle->getContent();
772 $this->edittime = $this->mArticle->getTimestamp();
773 } else {
775 if( $this->section != '' ) {
776 if( $this->section == 'new' ) {
777 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
778 } else {
779 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
780 if( !$this->preview && !$this->diff ) {
781 preg_match( "/^(=+)(.+)\\1/mi",
782 $this->textbox1,
783 $matches );
784 if( !empty( $matches[2] ) ) {
785 $this->summary = "/* ". trim($matches[2])." */ ";
789 } else {
790 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
792 $wgOut->setPageTitle( $s );
794 if ( $this->missingComment ) {
795 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
798 if( $this->missingSummary ) {
799 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
802 if( !$this->hookError == '' ) {
803 $wgOut->addWikiText( $this->hookError );
806 if ( !$this->checkUnicodeCompliantBrowser() ) {
807 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
809 if ( isset( $this->mArticle )
810 && isset( $this->mArticle->mRevision )
811 && !$this->mArticle->mRevision->isCurrent() ) {
812 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
813 $wgOut->addWikiText( wfMsg( 'editingold' ) );
817 if( wfReadOnly() ) {
818 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
819 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
820 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
821 } else {
822 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
823 # Check the skin exists
824 if( $this->isValidCssJsSubpage ) {
825 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
826 } else {
827 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
832 if( $this->mTitle->isProtected( 'edit' ) ) {
833 # Is the protection due to the namespace, e.g. interface text?
834 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
835 # Yes; remind the user
836 $notice = wfMsg( 'editinginterface' );
837 } elseif( $this->mTitle->isSemiProtected() ) {
838 # No; semi protected
839 $notice = wfMsg( 'semiprotectedpagewarning' );
840 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' ) {
841 $notice = '';
843 } else {
844 # No; regular protection
845 $notice = wfMsg( 'protectedpagewarning' );
847 $wgOut->addWikiText( $notice );
850 if ( $this->kblength === false ) {
851 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
853 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
854 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
855 } elseif( $this->kblength > 29 ) {
856 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
859 $rows = $wgUser->getIntOption( 'rows' );
860 $cols = $wgUser->getIntOption( 'cols' );
862 $ew = $wgUser->getOption( 'editwidth' );
863 if ( $ew ) $ew = " style=\"width:100%\"";
864 else $ew = '';
866 $q = 'action=submit';
867 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
868 $action = $this->mTitle->escapeLocalURL( $q );
870 $summary = wfMsg('summary');
871 $subject = wfMsg('subject');
872 $minor = wfMsgExt('minoredit', array('parseinline'));
873 $watchthis = wfMsgExt('watchthis', array('parseinline'));
875 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
876 wfMsgExt('cancel', array('parseinline')) );
877 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
878 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
879 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
880 htmlspecialchars( wfMsg( 'newwindow' ) );
882 global $wgRightsText;
883 $copywarn = "<div id=\"editpage-copywarn\">\n" .
884 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
885 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
886 $wgRightsText ) . "\n</div>";
888 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
889 # prepare toolbar for edit buttons
890 $toolbar = $this->getEditToolbar();
891 } else {
892 $toolbar = '';
895 // activate checkboxes if user wants them to be always active
896 if( !$this->preview && !$this->diff ) {
897 # Sort out the "watch" checkbox
898 if( $wgUser->getOption( 'watchdefault' ) ) {
899 # Watch all edits
900 $this->watchthis = true;
901 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
902 # Watch creations
903 $this->watchthis = true;
904 } elseif( $this->mTitle->userIsWatching() ) {
905 # Already watched
906 $this->watchthis = true;
909 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
912 $minoredithtml = '';
914 if ( $wgUser->isAllowed('minoredit') ) {
915 $minoredithtml =
916 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
917 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />\n".
918 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>\n";
921 $watchhtml = '';
923 if ( $wgUser->isLoggedIn() ) {
924 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
925 ($this->watchthis?" checked='checked'":"").
926 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />\n".
927 "<label for='wpWatchthis' title=\"" .
928 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>\n";
931 $checkboxhtml = $minoredithtml . $watchhtml;
933 if ( $wgUser->getOption( 'previewontop' ) ) {
935 if ( 'preview' == $this->formtype ) {
936 $this->showPreview();
937 } else {
938 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
941 if ( 'diff' == $this->formtype ) {
942 $wgOut->addHTML( $this->getDiff() );
947 # if this is a comment, show a subject line at the top, which is also the edit summary.
948 # Otherwise, show a summary field at the bottom
949 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
950 if( $this->section == 'new' ) {
951 $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 />";
952 $editsummary = '';
953 } else {
954 $commentsubject = '';
955 $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 />";
958 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
959 if( !$this->preview && !$this->diff ) {
960 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
962 $templates = $this->formatTemplates();
964 global $wgUseMetadataEdit ;
965 if ( $wgUseMetadataEdit ) {
966 $metadata = $this->mMetaData ;
967 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
968 $top = wfMsgWikiHtml( 'metadata_help' );
969 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
971 else $metadata = "" ;
973 $hidden = '';
974 $recreate = '';
975 if ($this->deletedSinceEdit) {
976 if ( 'save' != $this->formtype ) {
977 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
978 } else {
979 // Hide the toolbar and edit area, use can click preview to get it back
980 // Add an confirmation checkbox and explanation.
981 $toolbar = '';
982 $hidden = 'type="hidden" style="display:none;"';
983 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
984 $recreate .=
985 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
986 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
990 $temp = array(
991 'id' => 'wpSave',
992 'name' => 'wpSave',
993 'type' => 'submit',
994 'tabindex' => '5',
995 'value' => wfMsg('savearticle'),
996 'accesskey' => wfMsg('accesskey-save'),
997 'title' => wfMsg('tooltip-save'),
999 $buttons['save'] = wfElement('input', $temp, '');
1000 $temp = array(
1001 'id' => 'wpDiff',
1002 'name' => 'wpDiff',
1003 'type' => 'submit',
1004 'tabindex' => '7',
1005 'value' => wfMsg('showdiff'),
1006 'accesskey' => wfMsg('accesskey-diff'),
1007 'title' => wfMsg('tooltip-diff'),
1009 $buttons['diff'] = wfElement('input', $temp, '');
1011 global $wgLivePreview;
1012 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1013 $temp = array(
1014 'id' => 'wpPreview',
1015 'name' => 'wpPreview',
1016 'type' => 'submit',
1017 'tabindex' => '6',
1018 'value' => wfMsg('showpreview'),
1019 'accesskey' => '',
1020 'title' => wfMsg('tooltip-preview'),
1021 'style' => 'display: none;',
1023 $buttons['preview'] = wfElement('input', $temp, '');
1024 $temp = array(
1025 'id' => 'wpLivePreview',
1026 'name' => 'wpLivePreview',
1027 'type' => 'submit',
1028 'tabindex' => '6',
1029 'value' => wfMsg('showlivepreview'),
1030 'accesskey' => wfMsg('accesskey-preview'),
1031 'title' => '',
1032 'onclick' => $this->doLivePreviewScript(),
1034 $buttons['live'] = wfElement('input', $temp, '');
1035 } else {
1036 $temp = array(
1037 'id' => 'wpPreview',
1038 'name' => 'wpPreview',
1039 'type' => 'submit',
1040 'tabindex' => '6',
1041 'value' => wfMsg('showpreview'),
1042 'accesskey' => wfMsg('accesskey-preview'),
1043 'title' => wfMsg('tooltip-preview'),
1045 $buttons['preview'] = wfElement('input', $temp, '');
1046 $buttons['live'] = '';
1049 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1050 ? ""
1051 : "<input type='hidden' name=\"safemode\" value='1' />\n";
1053 $wgOut->addHTML( <<<END
1054 {$toolbar}
1055 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1059 if( is_callable( $formCallback ) ) {
1060 call_user_func_array( $formCallback, array( &$wgOut ) );
1063 // Put these up at the top to ensure they aren't lost on early form submission
1064 $wgOut->addHTML( "
1065 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1066 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1067 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1068 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1070 $wgOut->addHTML( <<<END
1071 $recreate
1072 {$commentsubject}
1073 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1074 cols='{$cols}'{$ew} $hidden>
1076 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1078 </textarea>
1079 " );
1081 $wgOut->addWikiText( $copywarn );
1082 $wgOut->addHTML( "
1083 {$metadata}
1084 {$editsummary}
1085 {$checkboxhtml}
1086 {$safemodehtml}
1089 $wgOut->addHTML(
1090 "<div class='editButtons'>
1091 {$buttons['save']}
1092 {$buttons['preview']}
1093 {$buttons['live']}
1094 {$buttons['diff']}
1095 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1096 </div><!-- editButtons -->
1097 </div><!-- editOptions -->");
1099 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1101 $wgOut->addHTML( "
1102 <div class='templatesUsed'>
1103 {$templates}
1104 </div>
1105 " );
1107 if ( $wgUser->isLoggedIn() ) {
1109 * To make it harder for someone to slip a user a page
1110 * which submits an edit form to the wiki without their
1111 * knowledge, a random token is associated with the login
1112 * session. If it's not passed back with the submission,
1113 * we won't save the page, or render user JavaScript and
1114 * CSS previews.
1116 $token = htmlspecialchars( $wgUser->editToken() );
1117 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1120 # If a blank edit summary was previously provided, and the appropriate
1121 # user preference is active, pass a hidden tag here. This will stop the
1122 # user being bounced back more than once in the event that a summary
1123 # is not required.
1124 if( $this->missingSummary ) {
1125 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1128 # For a bit more sophisticated detection of blank summaries, hash the
1129 # automatic one and pass that in a hidden field.
1130 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1131 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1133 if ( $this->isConflict ) {
1134 require_once( "DifferenceEngine.php" );
1135 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1137 $de = new DifferenceEngine( $this->mTitle );
1138 $de->setText( $this->textbox2, $this->textbox1 );
1139 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1141 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1142 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1143 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1145 $wgOut->addHTML( "</form>\n" );
1146 if ( !$wgUser->getOption( 'previewontop' ) ) {
1148 if ( $this->formtype == 'preview') {
1149 $this->showPreview();
1150 } else {
1151 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1154 if ( $this->formtype == 'diff') {
1155 $wgOut->addHTML( $this->getDiff() );
1160 wfProfileOut( $fname );
1164 * Append preview output to $wgOut.
1165 * Includes category rendering if this is a category page.
1166 * @private
1168 function showPreview() {
1169 global $wgOut;
1170 $wgOut->addHTML( '<div id="wikiPreview">' );
1171 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1172 $this->mArticle->openShowCategory();
1174 $previewOutput = $this->getPreviewText();
1175 $wgOut->addHTML( $previewOutput );
1176 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1177 $this->mArticle->closeShowCategory();
1179 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
1180 $wgOut->addHTML( '</div>' );
1184 * Prepare a list of templates used by this page. Returns HTML.
1186 function formatTemplates() {
1187 global $wgUser;
1189 $fname = 'EditPage::formatTemplates';
1190 wfProfileIn( $fname );
1192 $sk =& $wgUser->getSkin();
1194 $outText = '';
1195 $templates = $this->mArticle->getUsedTemplates();
1196 if ( count( $templates ) > 0 ) {
1197 # Do a batch existence check
1198 $batch = new LinkBatch;
1199 foreach( $templates as $title ) {
1200 $batch->addObj( $title );
1202 $batch->execute();
1204 # Construct the HTML
1205 $outText = '<br />'. wfMsgExt( 'templatesused', array( 'parseinline' ) ) . '<ul>';
1206 foreach ( $templates as $titleObj ) {
1207 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
1209 $outText .= '</ul>';
1211 wfProfileOut( $fname );
1212 return $outText;
1216 * Live Preview lets us fetch rendered preview page content and
1217 * add it to the page without refreshing the whole page.
1218 * If not supported by the browser it will fall through to the normal form
1219 * submission method.
1221 * This function outputs a script tag to support live preview, and
1222 * returns an onclick handler which should be added to the attributes
1223 * of the preview button
1225 function doLivePreviewScript() {
1226 global $wgStylePath, $wgJsMimeType, $wgOut, $wgTitle;
1227 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1228 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
1229 '"></script>' . "\n" );
1230 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1231 return "return !livePreview(" .
1232 "getElementById('wikiPreview')," .
1233 "editform.wpTextbox1.value," .
1234 '"' . $liveAction . '"' . ")";
1237 function getLastDelete() {
1238 $dbr =& wfGetDB( DB_SLAVE );
1239 $fname = 'EditPage::getLastDelete';
1240 $res = $dbr->select(
1241 array( 'logging', 'user' ),
1242 array( 'log_type',
1243 'log_action',
1244 'log_timestamp',
1245 'log_user',
1246 'log_namespace',
1247 'log_title',
1248 'log_comment',
1249 'log_params',
1250 'user_name', ),
1251 array( 'log_namespace' => $this->mTitle->getNamespace(),
1252 'log_title' => $this->mTitle->getDBkey(),
1253 'log_type' => 'delete',
1254 'log_action' => 'delete',
1255 'user_id=log_user' ),
1256 $fname,
1257 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1259 if($dbr->numRows($res) == 1) {
1260 while ( $x = $dbr->fetchObject ( $res ) )
1261 $data = $x;
1262 $dbr->freeResult ( $res ) ;
1263 } else {
1264 $data = null;
1266 return $data;
1270 * @todo document
1272 function getPreviewText() {
1273 global $wgOut, $wgUser, $wgTitle, $wgParser;
1275 $fname = 'EditPage::getPreviewText';
1276 wfProfileIn( $fname );
1278 if ( $this->mTriedSave && !$this->mTokenOk ) {
1279 $msg = 'session_fail_preview';
1280 } else {
1281 $msg = 'previewnote';
1283 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1284 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1285 if ( $this->isConflict ) {
1286 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1289 $parserOptions = ParserOptions::newFromUser( $wgUser );
1290 $parserOptions->setEditSection( false );
1292 global $wgRawHtml;
1293 if( $wgRawHtml && !$this->mTokenOk ) {
1294 // Could be an offsite preview attempt. This is very unsafe if
1295 // HTML is enabled, as it could be an attack.
1296 return $wgOut->parse( "<div class='previewnote'>" .
1297 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1300 # don't parse user css/js, show message about preview
1301 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1303 if ( $this->isCssJsSubpage ) {
1304 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1305 $previewtext = wfMsg('usercsspreview');
1306 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1307 $previewtext = wfMsg('userjspreview');
1309 $parserOptions->setTidy(true);
1310 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1311 $wgOut->addHTML( $parserOutput->mText );
1312 wfProfileOut( $fname );
1313 return $previewhead;
1314 } else {
1315 # if user want to see preview when he edit an article
1316 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
1317 $this->textbox1 = $this->mArticle->getContent();
1320 $toparse = $this->textbox1;
1322 # If we're adding a comment, we need to show the
1323 # summary as the headline
1324 if($this->section=="new" && $this->summary!="") {
1325 $toparse="== {$this->summary} ==\n\n".$toparse;
1328 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1329 $parserOptions->setTidy(true);
1330 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1331 $wgTitle, $parserOptions );
1333 $previewHTML = $parserOutput->getText();
1334 $wgOut->addParserOutputNoText( $parserOutput );
1336 wfProfileOut( $fname );
1337 return $previewhead . $previewHTML;
1342 * Call the stock "user is blocked" page
1344 function blockedIPpage() {
1345 global $wgOut;
1346 $wgOut->blockedPage();
1350 * Produce the stock "please login to edit pages" page
1352 function userNotLoggedInPage() {
1353 global $wgUser, $wgOut;
1354 $skin = $wgUser->getSkin();
1356 $loginTitle = Title::makeTitle( NS_SPECIAL, 'Userlogin' );
1357 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle->getPrefixedUrl() );
1359 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1360 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1361 $wgOut->setArticleRelated( false );
1363 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1364 $wgOut->returnToMain( false, $this->mTitle->getPrefixedUrl() );
1368 * Creates a basic error page which informs the user that
1369 * they have to validate their email address before being
1370 * allowed to edit.
1372 function userNotConfirmedPage() {
1373 global $wgOut;
1375 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1376 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1377 $wgOut->setArticleRelated( false );
1379 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1380 $wgOut->returnToMain( false );
1384 * Produce the stock "your edit contains spam" page
1386 * @param $match Text which triggered one or more filters
1388 function spamPage( $match = false ) {
1389 global $wgOut;
1391 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1392 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1393 $wgOut->setArticleRelated( false );
1395 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1396 if ( $match )
1397 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1399 $wgOut->returnToMain( false );
1403 * @private
1404 * @todo document
1406 function mergeChangesInto( &$editText ){
1407 $fname = 'EditPage::mergeChangesInto';
1408 wfProfileIn( $fname );
1410 $db =& wfGetDB( DB_MASTER );
1412 // This is the revision the editor started from
1413 $baseRevision = Revision::loadFromTimestamp(
1414 $db, $this->mArticle->mTitle, $this->edittime );
1415 if( is_null( $baseRevision ) ) {
1416 wfProfileOut( $fname );
1417 return false;
1419 $baseText = $baseRevision->getText();
1421 // The current state, we want to merge updates into it
1422 $currentRevision = Revision::loadFromTitle(
1423 $db, $this->mArticle->mTitle );
1424 if( is_null( $currentRevision ) ) {
1425 wfProfileOut( $fname );
1426 return false;
1428 $currentText = $currentRevision->getText();
1430 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1431 $editText = $result;
1432 wfProfileOut( $fname );
1433 return true;
1434 } else {
1435 wfProfileOut( $fname );
1436 return false;
1441 * Check if the browser is on a blacklist of user-agents known to
1442 * mangle UTF-8 data on form submission. Returns true if Unicode
1443 * should make it through, false if it's known to be a problem.
1444 * @return bool
1445 * @private
1447 function checkUnicodeCompliantBrowser() {
1448 global $wgBrowserBlackList;
1449 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1450 // No User-Agent header sent? Trust it by default...
1451 return true;
1453 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1454 foreach ( $wgBrowserBlackList as $browser ) {
1455 if ( preg_match($browser, $currentbrowser) ) {
1456 return false;
1459 return true;
1463 * Format an anchor fragment as it would appear for a given section name
1464 * @param string $text
1465 * @return string
1466 * @private
1468 function sectionAnchor( $text ) {
1469 $headline = Sanitizer::decodeCharReferences( $text );
1470 # strip out HTML
1471 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1472 $headline = trim( $headline );
1473 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1474 $replacearray = array(
1475 '%3A' => ':',
1476 '%' => '.'
1478 return str_replace(
1479 array_keys( $replacearray ),
1480 array_values( $replacearray ),
1481 $sectionanchor );
1485 * Shows a bulletin board style toolbar for common editing functions.
1486 * It can be disabled in the user preferences.
1487 * The necessary JavaScript code can be found in style/wikibits.js.
1489 function getEditToolbar() {
1490 global $wgStylePath, $wgContLang, $wgJsMimeType;
1493 * toolarray an array of arrays which each include the filename of
1494 * the button image (without path), the opening tag, the closing tag,
1495 * and optionally a sample text that is inserted between the two when no
1496 * selection is highlighted.
1497 * The tip text is shown when the user moves the mouse over the button.
1499 * Already here are accesskeys (key), which are not used yet until someone
1500 * can figure out a way to make them work in IE. However, we should make
1501 * sure these keys are not defined on the edit page.
1503 $toolarray=array(
1504 array( 'image'=>'button_bold.png',
1505 'open' => "\'\'\'",
1506 'close' => "\'\'\'",
1507 'sample'=> wfMsg('bold_sample'),
1508 'tip' => wfMsg('bold_tip'),
1509 'key' => 'B'
1511 array( 'image'=>'button_italic.png',
1512 'open' => "\'\'",
1513 'close' => "\'\'",
1514 'sample'=> wfMsg('italic_sample'),
1515 'tip' => wfMsg('italic_tip'),
1516 'key' => 'I'
1518 array( 'image'=>'button_link.png',
1519 'open' => '[[',
1520 'close' => ']]',
1521 'sample'=> wfMsg('link_sample'),
1522 'tip' => wfMsg('link_tip'),
1523 'key' => 'L'
1525 array( 'image'=>'button_extlink.png',
1526 'open' => '[',
1527 'close' => ']',
1528 'sample'=> wfMsg('extlink_sample'),
1529 'tip' => wfMsg('extlink_tip'),
1530 'key' => 'X'
1532 array( 'image'=>'button_headline.png',
1533 'open' => "\\n== ",
1534 'close' => " ==\\n",
1535 'sample'=> wfMsg('headline_sample'),
1536 'tip' => wfMsg('headline_tip'),
1537 'key' => 'H'
1539 array( 'image'=>'button_image.png',
1540 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1541 'close' => ']]',
1542 'sample'=> wfMsg('image_sample'),
1543 'tip' => wfMsg('image_tip'),
1544 'key' => 'D'
1546 array( 'image' =>'button_media.png',
1547 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1548 'close' => ']]',
1549 'sample'=> wfMsg('media_sample'),
1550 'tip' => wfMsg('media_tip'),
1551 'key' => 'M'
1553 array( 'image' =>'button_math.png',
1554 'open' => "<math>",
1555 'close' => "<\\/math>",
1556 'sample'=> wfMsg('math_sample'),
1557 'tip' => wfMsg('math_tip'),
1558 'key' => 'C'
1560 array( 'image' =>'button_nowiki.png',
1561 'open' => "<nowiki>",
1562 'close' => "<\\/nowiki>",
1563 'sample'=> wfMsg('nowiki_sample'),
1564 'tip' => wfMsg('nowiki_tip'),
1565 'key' => 'N'
1567 array( 'image' =>'button_sig.png',
1568 'open' => '--~~~~',
1569 'close' => '',
1570 'sample'=> '',
1571 'tip' => wfMsg('sig_tip'),
1572 'key' => 'Y'
1574 array( 'image' =>'button_hr.png',
1575 'open' => "\\n----\\n",
1576 'close' => '',
1577 'sample'=> '',
1578 'tip' => wfMsg('hr_tip'),
1579 'key' => 'R'
1582 $toolbar = "<div id='toolbar'>\n";
1583 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1585 foreach($toolarray as $tool) {
1587 $image=$wgStylePath.'/common/images/'.$tool['image'];
1588 $open=$tool['open'];
1589 $close=$tool['close'];
1590 $sample = wfEscapeJsString( $tool['sample'] );
1592 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1593 // Older browsers show a "speedtip" type message only for ALT.
1594 // Ideally these should be different, realistically they
1595 // probably don't need to be.
1596 $tip = wfEscapeJsString( $tool['tip'] );
1598 #$key = $tool["key"];
1600 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1603 $toolbar.="/*]]>*/\n</script>";
1604 $toolbar.="\n</div>";
1605 return $toolbar;
1609 * Output preview text only. This can be sucked into the edit page
1610 * via JavaScript, and saves the server time rendering the skin as
1611 * well as theoretically being more robust on the client (doesn't
1612 * disturb the edit box's undo history, won't eat your text on
1613 * failure, etc).
1615 * @todo This doesn't include category or interlanguage links.
1616 * Would need to enhance it a bit, maybe wrap them in XML
1617 * or something... that might also require more skin
1618 * initialization, so check whether that's a problem.
1620 function livePreview() {
1621 global $wgOut;
1622 $wgOut->disable();
1623 header( 'Content-type: text/xml' );
1624 header( 'Cache-control: no-cache' );
1625 # FIXME
1626 echo $this->getPreviewText( );
1627 /* To not shake screen up and down between preview and live-preview */
1628 echo "<br style=\"clear:both;\" />\n";
1633 * Get a diff between the current contents of the edit box and the
1634 * version of the page we're editing from.
1636 * If this is a section edit, we'll replace the section as for final
1637 * save and then make a comparison.
1639 * @return string HTML
1641 function getDiff() {
1642 require_once( 'DifferenceEngine.php' );
1643 $oldtext = $this->mArticle->fetchContent();
1644 $newtext = $this->mArticle->replaceSection(
1645 $this->section, $this->textbox1, $this->summary, $this->edittime );
1646 $newtext = $this->mArticle->preSaveTransform( $newtext );
1647 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1648 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1649 if ( $oldtext !== false || $newtext != '' ) {
1650 $de = new DifferenceEngine( $this->mTitle );
1651 $de->setText( $oldtext, $newtext );
1652 $difftext = $de->getDiff( $oldtitle, $newtitle );
1653 } else {
1654 $difftext = '';
1657 return '<div id="wikiDiff">' . $difftext . '</div>';
1661 * Filter an input field through a Unicode de-armoring process if it
1662 * came from an old browser with known broken Unicode editing issues.
1664 * @param WebRequest $request
1665 * @param string $field
1666 * @return string
1667 * @private
1669 function safeUnicodeInput( $request, $field ) {
1670 $text = rtrim( $request->getText( $field ) );
1671 return $request->getBool( 'safemode' )
1672 ? $this->unmakesafe( $text )
1673 : $text;
1677 * Filter an output field through a Unicode armoring process if it is
1678 * going to an old browser with known broken Unicode editing issues.
1680 * @param string $text
1681 * @return string
1682 * @private
1684 function safeUnicodeOutput( $text ) {
1685 global $wgContLang;
1686 $codedText = $wgContLang->recodeForEdit( $text );
1687 return $this->checkUnicodeCompliantBrowser()
1688 ? $codedText
1689 : $this->makesafe( $codedText );
1693 * A number of web browsers are known to corrupt non-ASCII characters
1694 * in a UTF-8 text editing environment. To protect against this,
1695 * detected browsers will be served an armored version of the text,
1696 * with non-ASCII chars converted to numeric HTML character references.
1698 * Preexisting such character references will have a 0 added to them
1699 * to ensure that round-trips do not alter the original data.
1701 * @param string $invalue
1702 * @return string
1703 * @private
1705 function makesafe( $invalue ) {
1706 // Armor existing references for reversability.
1707 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1709 $bytesleft = 0;
1710 $result = "";
1711 $working = 0;
1712 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1713 $bytevalue = ord( $invalue{$i} );
1714 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1715 $result .= chr( $bytevalue );
1716 $bytesleft = 0;
1717 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1718 $working = $working << 6;
1719 $working += ($bytevalue & 0x3F);
1720 $bytesleft--;
1721 if( $bytesleft <= 0 ) {
1722 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1724 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1725 $working = $bytevalue & 0x1F;
1726 $bytesleft = 1;
1727 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1728 $working = $bytevalue & 0x0F;
1729 $bytesleft = 2;
1730 } else { //1111 0xxx
1731 $working = $bytevalue & 0x07;
1732 $bytesleft = 3;
1735 return $result;
1739 * Reverse the previously applied transliteration of non-ASCII characters
1740 * back to UTF-8. Used to protect data from corruption by broken web browsers
1741 * as listed in $wgBrowserBlackList.
1743 * @param string $invalue
1744 * @return string
1745 * @private
1747 function unmakesafe( $invalue ) {
1748 $result = "";
1749 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1750 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1751 $i += 3;
1752 $hexstring = "";
1753 do {
1754 $hexstring .= $invalue{$i};
1755 $i++;
1756 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1758 // Do some sanity checks. These aren't needed for reversability,
1759 // but should help keep the breakage down if the editor
1760 // breaks one of the entities whilst editing.
1761 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1762 $codepoint = hexdec($hexstring);
1763 $result .= codepointToUtf8( $codepoint );
1764 } else {
1765 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1767 } else {
1768 $result .= substr( $invalue, $i, 1 );
1771 // reverse the transform that we made for reversability reasons.
1772 return strtr( $result, array( "&#x0" => "&#x" ) );
1775 function noCreatePermission() {
1776 global $wgOut;
1777 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1778 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );