3 * Contain the EditPage class
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
20 var $isConflict = false;
21 var $isCssJsSubpage = false;
22 var $deletedSinceEdit = false;
28 var $save = false, $preview = false, $diff = false;
29 var $minoredit = false, $watchthis = false, $recreate = false;
30 var $textbox1 = '', $textbox2 = '', $summary = '';
31 var $edittime = '', $section = '', $starttime = '';
32 var $oldid = 0, $editintro = '';
38 function EditPage( $article ) {
39 $this->mArticle
=& $article;
41 $this->mTitle
=& $wgTitle;
45 * This is the function that extracts metadata from the article body on the first view.
46 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
47 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
49 function extractMetaDataFromArticle () {
50 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
51 $this->mMetaData
= '' ;
52 if ( !$wgUseMetadataEdit ) return ;
53 if ( $wgMetadataWhitelist == '' ) return ;
55 $t = $this->mArticle
->getContent ( true ) ;
57 # MISSING : <nowiki> filtering
59 # Categories and language links
60 $t = explode ( "\n" , $t ) ;
61 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
62 $cat = $ll = array() ;
63 foreach ( $t AS $key => $x )
65 $y = trim ( strtolower ( $x ) ) ;
66 while ( substr ( $y , 0 , 2 ) == '[[' )
68 $y = explode ( ']]' , trim ( $x ) ) ;
69 $first = array_shift ( $y ) ;
70 $first = explode ( ':' , $first ) ;
71 $ns = array_shift ( $first ) ;
72 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
73 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
75 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
76 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
78 $x = implode ( ']]' , $y ) ;
80 $y = trim ( strtolower ( $x ) ) ;
84 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
85 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
86 $t = implode ( "\n" , $t ) ;
89 $sat = array () ; # stand-alone-templates; must be lowercase
90 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
91 $wl_article = new Article ( $wl_title ) ;
92 $wl = explode ( "\n" , $wl_article->getContent(true) ) ;
97 while ( substr ( $x , 0 , 1 ) == '*' )
100 $x = trim ( substr ( $x , 1 ) ) ;
104 $sat[] = strtolower ( $x ) ;
109 # Templates, but only some
110 $t = explode ( '{{' , $t ) ;
112 foreach ( $t AS $key => $x )
114 $y = explode ( '}}' , $x , 2 ) ;
115 if ( count ( $y ) == 2 )
118 $z = explode ( '|' , $z ) ;
119 $tn = array_shift ( $z ) ;
120 if ( in_array ( strtolower ( $tn ) , $sat ) )
122 $tl[] = '{{' . $y[0] . '}}' ;
124 $y = explode ( '}}' , $y[1] , 2 ) ;
126 else $t[$key] = '{{' . $x ;
128 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
131 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
132 $t = implode ( '' , $t ) ;
134 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
135 $this->mArticle
->mContent
= $t ;
136 $this->mMetaData
= $s ;
144 * This is the function that gets called for "action=edit". It
145 * sets up various member variables, then passes execution to
146 * another function, usually showEditForm()
148 * The edit form is self-submitting, so that when things like
149 * preview and edit conflicts occur, we get the same form back
150 * with the extra stuff added. Only when the final submission
151 * is made and all is well do we actually save and redirect to
152 * the newly-edited page.
155 global $wgOut, $wgUser, $wgRequest, $wgTitle;
157 $fname = 'EditPage::edit';
158 wfProfileIn( $fname );
160 // this is not an article
161 $wgOut->setArticleFlag(false);
163 $this->importFormData( $wgRequest );
164 $this->firsttime
= false;
167 $this->livePreview();
168 wfProfileOut( $fname );
172 if ( ! $this->mTitle
->userCanEdit() ) {
173 $wgOut->readOnlyPage( $this->mArticle
->getContent( true ), true );
174 wfProfileOut( $fname );
177 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
178 # When previewing, don't check blocked state - will get caught at save time.
179 # Also, check when starting edition is done against slave to improve performance.
180 $this->blockedIPpage();
181 wfProfileOut( $fname );
184 if ( !$wgUser->isAllowed('edit') ) {
185 if ( $wgUser->isAnon() ) {
186 $this->userNotLoggedInPage();
187 wfProfileOut( $fname );
190 $wgOut->readOnlyPage( $this->mArticle
->getContent( true ), true );
191 wfProfileOut( $fname );
195 if ( wfReadOnly() ) {
196 if( $this->save ||
$this->preview
) {
197 $this->formtype
= 'preview';
198 } else if ( $this->diff
) {
199 $this->formtype
= 'diff';
201 $wgOut->readOnlyPage( $this->mArticle
->getContent( true ) );
202 wfProfileOut( $fname );
207 $this->formtype
= 'save';
208 } else if ( $this->preview
) {
209 $this->formtype
= 'preview';
210 } else if ( $this->diff
) {
211 $this->formtype
= 'diff';
212 } else { # First time through
213 $this->firsttime
= true;
214 if( $this->previewOnOpen() ) {
215 $this->formtype
= 'preview';
217 $this->extractMetaDataFromArticle () ;
218 $this->formtype
= 'initial';
223 wfProfileIn( "$fname-business-end" );
225 $this->isConflict
= false;
226 // css / js subpages of user pages get a special treatment
227 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
229 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
230 * no matter it's current state
232 $this->deletedSinceEdit
= false;
233 if ( $this->edittime
!= '' ) {
234 /* Note that we rely on logging table, which hasn't been always there,
235 * but that doesn't matter, because this only applies to brand new
236 * deletes. This is done on every preview and save request. Move it further down
237 * to only perform it on saves
239 if ( $this->mTitle
->isDeleted() ) {
240 $this->lastDelete
= $this->getLastDelete();
241 if ( !is_null($this->lastDelete
) ) {
242 $deletetime = $this->lastDelete
->log_timestamp
;
243 if ( ($deletetime - $this->starttime
) > 0 ) {
244 $this->deletedSinceEdit
= true;
250 if(!$this->mTitle
->getArticleID() && ('initial' == $this->formtype ||
$this->firsttime
)) { # new article
253 if( $this->mTitle
->isTalkPage() ) {
254 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
257 # Attempt submission here. This will check for edit conflicts,
258 # and redundantly check for locked database, blocked IPs, etc.
259 # that edit() already checked just in case someone tries to sneak
260 # in the back door with a hand-edited submission URL.
262 if ( 'save' == $this->formtype
) {
263 if ( !$this->attemptSave() ) {
264 wfProfileOut( "$fname-business-end" );
265 wfProfileOut( $fname );
270 # First time through: get contents, set time for conflict
272 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
273 $this->initialiseForm();
276 $this->showEditForm();
277 wfProfileOut( "$fname-business-end" );
278 wfProfileOut( $fname );
282 * Return true if this page should be previewed when the edit form
283 * is initially opened.
287 function previewOnOpen() {
289 return $wgUser->getOption( 'previewonfirst' ) ||
290 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
291 !$this->mTitle
->exists() );
297 function importFormData( &$request ) {
298 $fname = 'EditPage::importFormData';
299 wfProfileIn( $fname );
301 if( $request->wasPosted() ) {
302 # These fields need to be checked for encoding.
303 # Also remove trailing whitespace, but don't remove _initial_
304 # whitespace from the text boxes. This may be significant formatting.
305 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
306 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
307 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
308 $this->summary
= $request->getText( 'wpSummary' );
310 $this->edittime
= $request->getVal( 'wpEdittime' );
311 $this->starttime
= $request->getVal( 'wpStarttime' );
312 if( is_null( $this->edittime
) ) {
313 # If the form is incomplete, force to preview.
314 $this->preview
= true;
316 if( $this->tokenOk( $request ) ) {
317 # Some browsers will not report any submit button
318 # if the user hits enter in the comment box.
319 # The unmarked state will be assumed to be a save,
320 # if the form seems otherwise complete.
321 $this->preview
= $request->getCheck( 'wpPreview' );
322 $this->diff
= $request->getCheck( 'wpDiff' );
324 # Page might be a hack attempt posted from
325 # an external site. Preview instead of saving.
326 $this->preview
= true;
329 $this->save
= ! ( $this->preview
OR $this->diff
);
330 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
331 $this->edittime
= null;
334 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
335 $this->starttime
= null;
338 $this->recreate
= $request->getCheck( 'wpRecreate' );
340 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
341 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
343 # Not a posted form? Start with nothing.
344 $this->textbox1
= '';
345 $this->textbox2
= '';
346 $this->mMetaData
= '';
348 $this->edittime
= '';
349 $this->starttime
= wfTimestampNow();
350 $this->preview
= false;
353 $this->minoredit
= false;
354 $this->watchthis
= false;
355 $this->recreate
= false;
358 $this->oldid
= $request->getInt( 'oldid' );
360 # Section edit can come from either the form or a link
361 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
363 $this->live
= $request->getCheck( 'live' );
364 $this->editintro
= $request->getText( 'editintro' );
366 wfProfileOut( $fname );
370 * Make sure the form isn't faking a user's credentials.
372 * @param WebRequest $request
376 function tokenOk( &$request ) {
378 if( $wgUser->isAnon() ) {
379 # Anonymous users may not have a session
380 # open. Don't tokenize.
383 return $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
387 function showIntro() {
389 $addstandardintro=true;
390 if($this->editintro
) {
391 $introtitle=Title
::newFromText($this->editintro
);
392 if(isset($introtitle) && $introtitle->userCanRead()) {
393 $rev=Revision
::newFromTitle($introtitle);
395 $wgOut->addWikiText($rev->getText());
396 $addstandardintro=false;
400 if($addstandardintro) {
401 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
407 * @return bool false if output is done, true if the rest of the form should be displayed
409 function attemptSave() {
410 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
412 $fname = 'EditPage::attemptSave';
413 wfProfileIn( $fname );
414 wfProfileIn( "$fname-checks" );
416 # Reintegrate metadata
417 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
418 $this->mMetaData
= '' ;
421 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
422 $this->spamPage ( $matches[0] );
423 wfProfileOut( "$fname-checks" );
424 wfProfileOut( $fname );
427 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
428 # Error messages or other handling should be performed by the filter function
429 wfProfileOut( $fname );
430 wfProfileOut( "$fname-checks" );
433 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
434 # Check block state against master, thus 'false'.
435 $this->blockedIPpage();
436 wfProfileOut( "$fname-checks" );
437 wfProfileOut( $fname );
441 if ( !$wgUser->isAllowed('edit') ) {
442 if ( $wgUser->isAnon() ) {
443 $this->userNotLoggedInPage();
444 wfProfileOut( "$fname-checks" );
445 wfProfileOut( $fname );
449 $wgOut->readOnlyPage();
450 wfProfileOut( $fname );
455 if ( wfReadOnly() ) {
456 $wgOut->readOnlyPage();
457 wfProfileOut( "$fname-checks" );
458 wfProfileOut( $fname );
461 if ( $wgUser->pingLimiter() ) {
462 $wgOut->rateLimited();
463 wfProfileOut( "$fname-checks" );
464 wfProfileOut( $fname );
468 # If the article has been deleted while editing, don't save it without
470 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
471 wfProfileOut( "$fname-checks" );
472 wfProfileOut( $fname );
476 wfProfileOut( "$fname-checks" );
478 # If article is new, insert it.
479 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
481 # Don't save a new article if it's blank.
482 if ( ( '' == $this->textbox1
) ||
483 ( wfMsg( 'newarticletext' ) == $this->textbox1
) ) {
484 $wgOut->redirect( $this->mTitle
->getFullURL() );
485 wfProfileOut( $fname );
488 if (wfRunHooks('ArticleSave', array(&$this->mArticle
, &$wgUser, &$this->textbox1
,
489 &$this->summary
, &$this->minoredit
, &$this->watchthis
, NULL)))
492 $isComment=($this->section
=='new');
493 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
494 $this->minoredit
, $this->watchthis
, false, $isComment);
495 wfRunHooks('ArticleSaveComplete', array(&$this->mArticle
, &$wgUser, $this->textbox1
,
496 $this->summary
, $this->minoredit
,
497 $this->watchthis
, NULL));
499 wfProfileOut( $fname );
503 # Article exists. Check for edit conflict.
505 $this->mArticle
->clear(); # Force reload of dates, etc.
506 $this->mArticle
->forUpdate( true ); # Lock the article
508 if( ( $this->section
!= 'new' ) &&
509 ($this->mArticle
->getTimestamp() != $this->edittime
) )
511 $this->isConflict
= true;
513 $userid = $wgUser->getID();
515 if ( $this->isConflict
) {
516 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
517 $this->mArticle
->getTimestamp() . "'\n" );
518 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
521 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
522 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
525 # Suppress edit conflict with self
526 if ( ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
527 wfDebug( "Suppressing edit conflict, same user.\n" );
528 $this->isConflict
= false;
530 # switch from section editing to normal editing in edit conflict
531 if($this->isConflict
) {
533 if( $this->mergeChangesInto( $text ) ){
534 // Successful merge! Maybe we should tell the user the good news?
535 $this->isConflict
= false;
536 wfDebug( "Suppressing edit conflict, successful merge.\n" );
539 $this->textbox1
= $text;
540 wfDebug( "Keeping edit conflict, failed merge.\n" );
545 if ( $this->isConflict
) {
546 wfProfileOut( $fname );
551 wfProfileIn( "$fname-sectionanchor" );
553 if( $this->section
== 'new' ) {
554 if( $this->summary
!= '' ) {
555 $sectionanchor = $this->sectionAnchor( $this->summary
);
557 } elseif( $this->section
!= '' ) {
558 # Try to get a section anchor from the section source, redirect to edited section if header found
559 # XXX: might be better to integrate this into Article::replaceSection
560 # for duplicate heading checking and maybe parsing
561 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
562 # we can't deal with anchors, includes, html etc in the header for now,
563 # headline would need to be parsed to improve this
564 if($hasmatch and strlen($matches[2]) > 0) {
565 $sectionanchor = $this->sectionAnchor( $matches[2] );
568 wfProfileOut( "$fname-sectionanchor" );
570 // Save errors may fall down to the edit form, but we've now
571 // merged the section into full text. Clear the section field
572 // so that later submission of conflict forms won't try to
573 // replace that into a duplicated mess.
574 $this->textbox1
= $text;
577 if (wfRunHooks('ArticleSave', array(&$this->mArticle
, &$wgUser, &$text,
578 &$this->summary
, &$this->minoredit
,
579 &$this->watchthis
, &$sectionanchor)))
581 # update the article here
582 if($this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
583 $this->watchthis
, '', $sectionanchor ))
585 wfRunHooks('ArticleSaveComplete',
586 array(&$this->mArticle
, &$wgUser, $text,
587 $this->summary
, $this->minoredit
,
588 $this->watchthis
, $sectionanchor));
589 wfProfileOut( $fname );
592 $this->isConflict
= true;
595 wfProfileOut( $fname );
600 * Initialise form fields in the object
601 * Called on the first invocation, e.g. when a user clicks an edit link
603 function initialiseForm() {
604 $this->edittime
= $this->mArticle
->getTimestamp();
605 $this->textbox1
= $this->mArticle
->getContent( true );
611 * Send the edit form and related headers to $wgOut
613 function showEditForm() {
614 global $wgOut, $wgUser, $wgAllowAnonymousMinor, $wgLang, $wgContLang;
616 $fname = 'EditPage::showEditForm';
617 wfProfileIn( $fname );
619 $sk =& $wgUser->getSkin();
621 $wgOut->setRobotpolicy( 'noindex,nofollow' );
623 # Enabled article-related sidebar, toplinks, etc.
624 $wgOut->setArticleRelated( true );
626 if ( $this->isConflict
) {
627 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
628 $wgOut->setPageTitle( $s );
629 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
631 $this->textbox2
= $this->textbox1
;
632 $this->textbox1
= $this->mArticle
->getContent( true );
633 $this->edittime
= $this->mArticle
->getTimestamp();
636 if( $this->section
!= '' ) {
637 if( $this->section
== 'new' ) {
638 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
640 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
641 if( !$this->preview
&& !$this->diff
) {
642 preg_match( "/^(=+)(.+)\\1/mi",
645 if( !empty( $matches[2] ) ) {
646 $this->summary
= "/* ". trim($matches[2])." */ ";
651 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
653 $wgOut->setPageTitle( $s );
654 if ( !$this->checkUnicodeCompliantBrowser() ) {
655 $this->mArticle
->setOldSubtitle();
656 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
658 if ( isset( $this->mArticle
)
659 && isset( $this->mArticle
->mRevision
)
660 && !$this->mArticle
->mRevision
->isCurrent() ) {
661 $this->mArticle
->setOldSubtitle();
662 $wgOut->addWikiText( wfMsg( 'editingold' ) );
667 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
668 } else if ( $this->isCssJsSubpage
and 'preview' != $this->formtype
) {
669 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
671 if( $this->mTitle
->isProtected('edit') ) {
672 $wgOut->addWikiText( wfMsg( 'protectedpagewarning' ) );
675 $kblength = (int)(strlen( $this->textbox1
) / 1024);
676 if( $kblength > 29 ) {
677 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
680 $rows = $wgUser->getOption( 'rows' );
681 $cols = $wgUser->getOption( 'cols' );
683 $ew = $wgUser->getOption( 'editwidth' );
684 if ( $ew ) $ew = " style=\"width:100%\"";
687 $q = 'action=submit';
688 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
689 $action = $this->mTitle
->escapeLocalURL( $q );
691 $summary = wfMsg('summary');
692 $subject = wfMsg('subject');
693 $minor = wfMsg('minoredit');
694 $watchthis = wfMsg ('watchthis');
695 $save = wfMsg('savearticle');
696 $prev = wfMsg('showpreview');
697 $diff = wfMsg('showdiff');
699 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
701 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
702 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
703 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
704 htmlspecialchars( wfMsg( 'newwindow' ) );
706 global $wgRightsText;
707 $copywarn = "<div id=\"editpage-copywarn\">\n" .
708 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
709 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
710 $wgRightsText ) . "\n</div>";
712 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
713 # prepare toolbar for edit buttons
714 $toolbar = $this->getEditToolbar();
719 // activate checkboxes if user wants them to be always active
720 if( !$this->preview
&& !$this->diff
) {
721 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis
= true;
722 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
724 // activate checkbox also if user is already watching the page,
725 // require wpWatchthis to be unset so that second condition is not
726 // checked unnecessarily
727 if( !$this->watchthis
&& $this->mTitle
->userIsWatching() ) $this->watchthis
= true;
732 if ( $wgUser->isLoggedIn() ||
$wgAllowAnonymousMinor ) {
734 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?
" checked='checked'":"").
735 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
736 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
741 if ( $wgUser->isLoggedIn() ) {
742 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
743 ($this->watchthis?
" checked='checked'":"").
744 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
745 "<label for='wpWatchthis' title=\"" .
746 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
749 $checkboxhtml = $minoredithtml . $watchhtml . '<br />';
751 $wgOut->addHTML( '<div id="wikiPreview">' );
752 if ( 'preview' == $this->formtype
) {
753 $previewOutput = $this->getPreviewText();
754 if ( $wgUser->getOption('previewontop' ) ) {
755 $wgOut->addHTML( $previewOutput );
756 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
757 $this->mArticle
->closeShowCategory();
759 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
762 $wgOut->addHTML( '</div>' );
763 if ( 'diff' == $this->formtype
) {
764 if ( $wgUser->getOption('previewontop' ) ) {
765 $wgOut->addHTML( $this->getDiff() );
770 # if this is a comment, show a subject line at the top, which is also the edit summary.
771 # Otherwise, show a summary field at the bottom
772 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
773 if( $this->section
== 'new' ) {
774 $commentsubject="{$subject}: <input tabindex='1' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
777 $commentsubject = '';
778 $editsummary="{$summary}: <input tabindex='2' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
781 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
782 if( !$this->preview
&& !$this->diff
) {
783 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
785 $templates = $this->getTemplatesUsed();
787 global $wgLivePreview;
788 if ( $wgLivePreview ) {
789 $liveOnclick = $this->doLivePreviewScript();
794 global $wgUseMetadataEdit ;
795 if ( $wgUseMetadataEdit ) {
796 $metadata = $this->mMetaData
;
797 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
798 $helppage = Title
::newFromText( wfMsg( "metadata_page" ) ) ;
799 $top = wfMsg( 'metadata', $helppage->getInternalURL() );
800 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
802 else $metadata = "" ;
806 if ($this->deletedSinceEdit
) {
807 if ( 'save' != $this->formtype
) {
808 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
810 // Hide the toolbar and edit area, use can click preview to get it back
811 // Add an confirmation checkbox and explanation.
813 $hidden = 'type="hidden" style="display:none;"';
814 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
816 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
817 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
821 $safemodehtml = $this->checkUnicodeCompliantBrowser()
823 : "<input type='hidden' name=\"safemode\" value='1' />\n";
825 $wgOut->addHTML( <<<END
827 <form id="editform" name="editform" method="post" action="$action"
828 enctype="multipart/form-data">
831 <textarea tabindex='1' accesskey="," name="wpTextbox1" rows='{$rows}'
832 cols='{$cols}'{$ew} $hidden>
834 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
841 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
842 " title=\"".wfMsg('tooltip-save')."\"/>
843 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
844 " title=\"".wfMsg('tooltip-preview')."\"/>
845 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
846 " title=\"".wfMsg('tooltip-diff')."\"/>
847 <em>{$cancel}</em> | <em>{$edithelp}</em>{$templates}" );
848 $wgOut->addWikiText( $copywarn );
850 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
851 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
852 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
854 if ( $wgUser->isLoggedIn() ) {
856 * To make it harder for someone to slip a user a page
857 * which submits an edit form to the wiki without their
858 * knowledge, a random token is associated with the login
859 * session. If it's not passed back with the submission,
860 * we won't save the page, or render user JavaScript and
863 $token = htmlspecialchars( $wgUser->editToken() );
864 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
868 if ( $this->isConflict
) {
869 require_once( "DifferenceEngine.php" );
870 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
871 DifferenceEngine
::showDiff( $this->textbox2
, $this->textbox1
,
872 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
874 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
875 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
876 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
878 $wgOut->addHTML( "</form>\n" );
879 if ( $this->formtype
== 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
880 $wgOut->addHTML( '<div id="wikiPreview">' . $previewOutput . '</div>' );
882 if ( $this->formtype
== 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
883 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
884 $wgOut->addHTML( $this->getDiff() );
887 wfProfileOut( $fname );
891 * Prepare a list of templates used by this page. Returns HTML.
893 function getTemplatesUsed() {
896 $fname = 'EditPage::getTemplatesUsed';
897 wfProfileIn( $fname );
899 $sk =& $wgUser->getSkin();
902 $articleTemplates = $this->mArticle
->getUsedTemplates();
903 if ( count( $articleTemplates ) > 0 ) {
904 $templates = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
905 foreach ( $articleTemplates as $tpl ) {
906 if ( $titleObj = Title
::makeTitle( NS_TEMPLATE
, $tpl ) ) {
907 $templates .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
910 $templates .= '</ul>';
912 wfProfileOut( $fname );
917 * Live Preview lets us fetch rendered preview page content and
918 * add it to the page without refreshing the whole page.
919 * If not supported by the browser it will fall through to the normal form
922 * This function outputs a script tag to support live preview, and
923 * returns an onclick handler which should be added to the attributes
924 * of the preview button
926 function doLivePreviewScript() {
927 global $wgStylePath, $wgJsMimeType, $wgOut;
928 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
929 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
930 '"></script>' . "\n" );
931 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
932 return 'onclick="return !livePreview('.
933 'getElementById(\'wikiPreview\'),' .
934 'editform.wpTextbox1.value,' .
935 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
938 function getLastDelete() {
939 $dbr =& wfGetDB( DB_SLAVE
);
940 $fname = 'EditPage::getLastDelete';
942 array( 'logging', 'user' ),
952 array( 'log_namespace' => $this->mTitle
->getNamespace(),
953 'log_title' => $this->mTitle
->getDBkey(),
954 'log_type' => 'delete',
955 'log_action' => 'delete',
956 'user_id=log_user' ),
958 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
960 if($dbr->numRows($res) == 1) {
961 while ( $x = $dbr->fetchObject ( $res ) )
963 $dbr->freeResult ( $res ) ;
973 function getPreviewText() {
974 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
976 $fname = 'EditPage::getPreviewText';
977 wfProfileIn( $fname );
979 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
980 "<p class='previewnote'>" . htmlspecialchars( wfMsg( 'previewnote' ) ) . "</p>\n";
981 if ( $this->isConflict
) {
982 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) .
986 $parserOptions = ParserOptions
::newFromUser( $wgUser );
987 $parserOptions->setEditSection( false );
989 # don't parse user css/js, show message about preview
990 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
992 if ( $this->isCssJsSubpage
) {
993 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
994 $previewtext = wfMsg('usercsspreview');
995 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
996 $previewtext = wfMsg('userjspreview');
998 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
999 $wgOut->addHTML( $parserOutput->mText
);
1000 wfProfileOut( $fname );
1001 return $previewhead;
1003 # if user want to see preview when he edit an article
1004 if( $wgUser->getOption('previewonfirst') and ($this->textbox1
== '')) {
1005 $this->textbox1
= $this->mArticle
->getContent(true);
1008 $toparse = $this->textbox1
;
1010 # If we're adding a comment, we need to show the
1011 # summary as the headline
1012 if($this->section
=="new" && $this->summary
!="") {
1013 $toparse="== {$this->summary} ==\n\n".$toparse;
1016 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1018 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1019 $wgTitle, $parserOptions );
1021 $previewHTML = $parserOutput->mText
;
1023 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
1024 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
1026 wfProfileOut( $fname );
1027 return $previewhead . $previewHTML;
1034 function blockedIPpage() {
1035 global $wgOut, $wgUser, $wgContLang, $wgIP;
1037 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
1038 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1039 $wgOut->setArticleRelated( false );
1041 $id = $wgUser->blockedBy();
1042 $reason = $wgUser->blockedFor();
1045 if ( is_numeric( $id ) ) {
1046 $name = User
::whoIs( $id );
1050 $link = '[[' . $wgContLang->getNsText( NS_USER
) .
1051 ":{$name}|{$name}]]";
1053 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
1054 $wgOut->returnToMain( false );
1060 function userNotLoggedInPage() {
1063 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1064 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1065 $wgOut->setArticleRelated( false );
1067 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
1068 $wgOut->returnToMain( false );
1074 function spamPage ( $match = false )
1077 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1078 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1079 $wgOut->setArticleRelated( false );
1081 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1083 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1085 $wgOut->returnToMain( false );
1089 * Forks processes to scan the originating IP for an open proxy server
1090 * MemCached can be used to skip IPs that have already been scanned
1092 function proxyCheck() {
1093 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
1094 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
1096 if ( !$wgBlockOpenProxies ) {
1102 if ( $wgUseMemCached ) {
1103 $mcKey = $wgDBname.':proxy:ip:'.$wgIP;
1104 $mcValue = $wgMemc->get( $mcKey );
1110 # Fork the processes
1112 $title = Title
::makeTitle( NS_SPECIAL
, 'Blockme' );
1113 $iphash = md5( $wgIP . $wgProxyKey );
1114 $url = $title->getFullURL( 'ip='.$iphash );
1116 foreach ( $wgProxyPorts as $port ) {
1117 $params = implode( ' ', array(
1118 escapeshellarg( $wgProxyScriptPath ),
1119 escapeshellarg( $wgIP ),
1120 escapeshellarg( $port ),
1121 escapeshellarg( $url )
1123 exec( "php $params &>/dev/null &" );
1126 if ( $wgUseMemCached ) {
1127 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
1136 function mergeChangesInto( &$editText ){
1137 $fname = 'EditPage::mergeChangesInto';
1138 wfProfileIn( $fname );
1140 $db =& wfGetDB( DB_MASTER
);
1142 // This is the revision the editor started from
1143 $baseRevision = Revision
::loadFromTimestamp(
1144 $db, $this->mArticle
->mTitle
, $this->edittime
);
1145 if( is_null( $baseRevision ) ) {
1146 wfProfileOut( $fname );
1149 $baseText = $baseRevision->getText();
1151 // The current state, we want to merge updates into it
1152 $currentRevision = Revision
::loadFromTitle(
1153 $db, $this->mArticle
->mTitle
);
1154 if( is_null( $currentRevision ) ) {
1155 wfProfileOut( $fname );
1158 $currentText = $currentRevision->getText();
1160 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1161 $editText = $result;
1162 wfProfileOut( $fname );
1165 wfProfileOut( $fname );
1171 function checkUnicodeCompliantBrowser() {
1172 global $wgBrowserBlackList;
1173 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1174 foreach ( $wgBrowserBlackList as $browser ) {
1175 if ( preg_match($browser, $currentbrowser) ) {
1183 * Format an anchor fragment as it would appear for a given section name
1184 * @param string $text
1188 function sectionAnchor( $text ) {
1189 $headline = Sanitizer
::decodeCharReferences( $text );
1191 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1192 $headline = trim( $headline );
1193 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1194 $replacearray = array(
1199 array_keys( $replacearray ),
1200 array_values( $replacearray ),
1205 * Shows a bulletin board style toolbar for common editing functions.
1206 * It can be disabled in the user preferences.
1207 * The necessary JavaScript code can be found in style/wikibits.js.
1209 function getEditToolbar() {
1210 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
1213 * toolarray an array of arrays which each include the filename of
1214 * the button image (without path), the opening tag, the closing tag,
1215 * and optionally a sample text that is inserted between the two when no
1216 * selection is highlighted.
1217 * The tip text is shown when the user moves the mouse over the button.
1219 * Already here are accesskeys (key), which are not used yet until someone
1220 * can figure out a way to make them work in IE. However, we should make
1221 * sure these keys are not defined on the edit page.
1224 array( 'image'=>'button_bold.png',
1226 'close' => "\'\'\'",
1227 'sample'=> wfMsg('bold_sample'),
1228 'tip' => wfMsg('bold_tip'),
1231 array( 'image'=>'button_italic.png',
1234 'sample'=> wfMsg('italic_sample'),
1235 'tip' => wfMsg('italic_tip'),
1238 array( 'image'=>'button_link.png',
1241 'sample'=> wfMsg('link_sample'),
1242 'tip' => wfMsg('link_tip'),
1245 array( 'image'=>'button_extlink.png',
1248 'sample'=> wfMsg('extlink_sample'),
1249 'tip' => wfMsg('extlink_tip'),
1252 array( 'image'=>'button_headline.png',
1254 'close' => " ==\\n",
1255 'sample'=> wfMsg('headline_sample'),
1256 'tip' => wfMsg('headline_tip'),
1259 array( 'image'=>'button_image.png',
1260 'open' => '[['.$wgLang->getNsText(NS_IMAGE
).":",
1262 'sample'=> wfMsg('image_sample'),
1263 'tip' => wfMsg('image_tip'),
1266 array( 'image' =>'button_media.png',
1267 'open' => '[['.$wgLang->getNsText(NS_MEDIA
).':',
1269 'sample'=> wfMsg('media_sample'),
1270 'tip' => wfMsg('media_tip'),
1273 array( 'image' =>'button_math.png',
1274 'open' => "\\<math\\>",
1275 'close' => "\\</math\\>",
1276 'sample'=> wfMsg('math_sample'),
1277 'tip' => wfMsg('math_tip'),
1280 array( 'image' =>'button_nowiki.png',
1281 'open' => "\\<nowiki\\>",
1282 'close' => "\\</nowiki\\>",
1283 'sample'=> wfMsg('nowiki_sample'),
1284 'tip' => wfMsg('nowiki_tip'),
1287 array( 'image' =>'button_sig.png',
1291 'tip' => wfMsg('sig_tip'),
1294 array( 'image' =>'button_hr.png',
1295 'open' => "\\n----\\n",
1298 'tip' => wfMsg('hr_tip'),
1302 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1304 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1305 foreach($toolarray as $tool) {
1307 $image=$wgStylePath.'/common/images/'.$tool['image'];
1308 $open=$tool['open'];
1309 $close=$tool['close'];
1310 $sample = wfEscapeJsString( $tool['sample'] );
1312 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1313 // Older browsers show a "speedtip" type message only for ALT.
1314 // Ideally these should be different, realistically they
1315 // probably don't need to be.
1316 $tip = wfEscapeJsString( $tool['tip'] );
1318 #$key = $tool["key"];
1320 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1323 $toolbar.="addInfobox('" . wfEscapeJsString( wfMsg( "infobox" ) ) .
1324 "','" . wfEscapeJsString( wfMsg( "infobox_alert" ) ) . "');\n";
1325 $toolbar.="document.writeln(\"</div>\");\n";
1327 $toolbar.="/*]]>*/\n</script>";
1332 * Output preview text only. This can be sucked into the edit page
1333 * via JavaScript, and saves the server time rendering the skin as
1334 * well as theoretically being more robust on the client (doesn't
1335 * disturb the edit box's undo history, won't eat your text on
1338 * @todo This doesn't include category or interlanguage links.
1339 * Would need to enhance it a bit, maybe wrap them in XML
1340 * or something... that might also require more skin
1341 * initialization, so check whether that's a problem.
1343 function livePreview() {
1346 header( 'Content-type: text/xml' );
1347 header( 'Cache-control: no-cache' );
1349 echo $this->getPreviewText( false, false );
1354 * Get a diff between the current contents of the edit box and the
1355 * version of the page we're editing from.
1357 * If this is a section edit, we'll replace the section as for final
1358 * save and then make a comparison.
1360 * @return string HTML
1362 function getDiff() {
1363 require_once( 'DifferenceEngine.php' );
1364 $oldtext = $this->mArticle
->fetchContent();
1365 $newtext = $this->mArticle
->replaceSection(
1366 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1367 $oldtitle = wfMsg( 'currentrev' );
1368 $newtitle = wfMsg( 'yourtext' );
1369 if ( $oldtext != wfMsg( 'noarticletext' ) ||
$newtext != '' ) {
1370 $difftext = DifferenceEngine
::getDiff( $oldtext, $newtext, $oldtitle, $newtitle );
1373 return '<div id="wikiDiff">' . $difftext . '</div>';
1377 * Filter an input field through a Unicode de-armoring process if it
1378 * came from an old browser with known broken Unicode editing issues.
1380 * @param WebRequest $request
1381 * @param string $field
1385 function safeUnicodeInput( $request, $field ) {
1386 $text = rtrim( $request->getText( $field ) );
1387 return $request->getBool( 'safemode' )
1388 ?
$this->unmakesafe( $text )
1393 * Filter an output field through a Unicode armoring process if it is
1394 * going to an old browser with known broken Unicode editing issues.
1396 * @param string $text
1400 function safeUnicodeOutput( $text ) {
1402 $codedText = $wgContLang->recodeForEdit( $text );
1403 return $this->checkUnicodeCompliantBrowser()
1405 : $this->makesafe( $codedText );
1409 * A number of web browsers are known to corrupt non-ASCII characters
1410 * in a UTF-8 text editing environment. To protect against this,
1411 * detected browsers will be served an armored version of the text,
1412 * with non-ASCII chars converted to numeric HTML character references.
1414 * Preexisting such character references will have a 0 added to them
1415 * to ensure that round-trips do not alter the original data.
1417 * @param string $invalue
1421 function makesafe( $invalue ) {
1422 // Armor existing references for reversability.
1423 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1428 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1429 $bytevalue = ord( $invalue{$i} );
1430 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1431 $result .= chr( $bytevalue );
1433 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1434 $working = $working << 6;
1435 $working +
= ($bytevalue & 0x3F);
1437 if( $bytesleft <= 0 ) {
1438 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1440 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1441 $working = $bytevalue & 0x1F;
1443 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1444 $working = $bytevalue & 0x0F;
1446 } else { //1111 0xxx
1447 $working = $bytevalue & 0x07;
1455 * Reverse the previously applied transliteration of non-ASCII characters
1456 * back to UTF-8. Used to protect data from corruption by broken web browsers
1457 * as listed in $wgBrowserBlackList.
1459 * @param string $invalue
1463 function unmakesafe( $invalue ) {
1465 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1466 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
1470 $hexstring .= $invalue{$i};
1472 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1474 // Do some sanity checks. These aren't needed for reversability,
1475 // but should help keep the breakage down if the editor
1476 // breaks one of the entities whilst editing.
1477 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1478 $codepoint = hexdec($hexstring);
1479 $result .= codepointToUtf8( $codepoint );
1481 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1484 $result .= substr( $invalue, $i, 1 );
1487 // reverse the transform that we made for reversability reasons.
1488 return strtr( $result, array( "�" => "&#x" ) );