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 );
415 # Reintegrate metadata
416 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
417 $this->mMetaData
= '' ;
420 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
421 $this->spamPage ( $matches[0] );
422 wfProfileOut( $fname );
425 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
426 # Error messages or other handling should be performed by the filter function
427 wfProfileOut( $fname );
430 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
431 # Check block state against master, thus 'false'.
432 $this->blockedIPpage();
433 wfProfileOut( $fname );
437 if ( !$wgUser->isAllowed('edit') ) {
438 if ( $wgUser->isAnon() ) {
439 $this->userNotLoggedInPage();
440 wfProfileOut( $fname );
444 $wgOut->readOnlyPage();
445 wfProfileOut( $fname );
450 if ( wfReadOnly() ) {
451 $wgOut->readOnlyPage();
452 wfProfileOut( $fname );
455 if ( $wgUser->pingLimiter() ) {
456 $wgOut->rateLimited();
457 wfProfileOut( $fname );
461 # If the article has been deleted while editing, don't save it without
463 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
464 wfProfileOut( $fname );
468 # If article is new, insert it.
469 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
471 # Don't save a new article if it's blank.
472 if ( ( '' == $this->textbox1
) ||
473 ( wfMsg( 'newarticletext' ) == $this->textbox1
) ) {
474 $wgOut->redirect( $this->mTitle
->getFullURL() );
475 wfProfileOut( $fname );
478 if (wfRunHooks('ArticleSave', array(&$this->mArticle
, &$wgUser, &$this->textbox1
,
479 &$this->summary
, &$this->minoredit
, &$this->watchthis
, NULL)))
482 $isComment=($this->section
=='new');
483 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
484 $this->minoredit
, $this->watchthis
, false, $isComment);
485 wfRunHooks('ArticleSaveComplete', array(&$this->mArticle
, &$wgUser, $this->textbox1
,
486 $this->summary
, $this->minoredit
,
487 $this->watchthis
, NULL));
489 wfProfileOut( $fname );
493 # Article exists. Check for edit conflict.
495 $this->mArticle
->clear(); # Force reload of dates, etc.
496 $this->mArticle
->forUpdate( true ); # Lock the article
498 if( ( $this->section
!= 'new' ) &&
499 ($this->mArticle
->getTimestamp() != $this->edittime
) )
501 $this->isConflict
= true;
503 $userid = $wgUser->getID();
505 if ( $this->isConflict
) {
506 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
507 $this->mArticle
->getTimestamp() . "'\n" );
508 $text = $this->mArticle
->getTextOfLastEditWithSectionReplacedOrAdded(
509 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
512 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
513 $text = $this->mArticle
->getTextOfLastEditWithSectionReplacedOrAdded(
514 $this->section
, $this->textbox1
, $this->summary
);
517 # Suppress edit conflict with self
518 if ( ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
519 wfDebug( "Suppressing edit conflict, same user.\n" );
520 $this->isConflict
= false;
522 # switch from section editing to normal editing in edit conflict
523 if($this->isConflict
) {
525 if( $this->mergeChangesInto( $text ) ){
526 // Successful merge! Maybe we should tell the user the good news?
527 $this->isConflict
= false;
528 wfDebug( "Suppressing edit conflict, successful merge.\n" );
531 $this->textbox1
= $text;
532 wfDebug( "Keeping edit conflict, failed merge.\n" );
537 if ( $this->isConflict
) {
538 wfProfileOut( $fname );
544 if( $this->section
== 'new' ) {
545 if( $this->summary
!= '' ) {
546 $sectionanchor = $this->sectionAnchor( $this->summary
);
548 } elseif( $this->section
!= '' ) {
549 # Try to get a section anchor from the section source, redirect to edited section if header found
550 # XXX: might be better to integrate this into Article::getTextOfLastEditWithSectionReplacedOrAdded
551 # for duplicate heading checking and maybe parsing
552 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
553 # we can't deal with anchors, includes, html etc in the header for now,
554 # headline would need to be parsed to improve this
555 if($hasmatch and strlen($matches[2]) > 0) {
556 $sectionanchor = $this->sectionAnchor( $matches[2] );
560 // Save errors may fall down to the edit form, but we've now
561 // merged the section into full text. Clear the section field
562 // so that later submission of conflict forms won't try to
563 // replace that into a duplicated mess.
564 $this->textbox1
= $text;
567 if (wfRunHooks('ArticleSave', array(&$this->mArticle
, &$wgUser, &$text,
568 &$this->summary
, &$this->minoredit
,
569 &$this->watchthis
, &$sectionanchor)))
571 # update the article here
572 if($this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
573 $this->watchthis
, '', $sectionanchor ))
575 wfRunHooks('ArticleSaveComplete',
576 array(&$this->mArticle
, &$wgUser, $text,
577 $this->summary
, $this->minoredit
,
578 $this->watchthis
, $sectionanchor));
579 wfProfileOut( $fname );
582 $this->isConflict
= true;
585 wfProfileOut( $fname );
590 * Initialise form fields in the object
591 * Called on the first invocation, e.g. when a user clicks an edit link
593 function initialiseForm() {
594 $this->edittime
= $this->mArticle
->getTimestamp();
595 $this->textbox1
= $this->mArticle
->getContent( true );
601 * Send the edit form and related headers to $wgOut
603 function showEditForm() {
604 global $wgOut, $wgUser, $wgAllowAnonymousMinor, $wgLang, $wgContLang;
606 $fname = 'EditPage::showEditForm';
607 wfProfileIn( $fname );
609 $sk =& $wgUser->getSkin();
611 $wgOut->setRobotpolicy( 'noindex,nofollow' );
613 # Enabled article-related sidebar, toplinks, etc.
614 $wgOut->setArticleRelated( true );
616 if ( $this->isConflict
) {
617 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
618 $wgOut->setPageTitle( $s );
619 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
621 $this->textbox2
= $this->textbox1
;
622 $this->textbox1
= $this->mArticle
->getContent( true );
623 $this->edittime
= $this->mArticle
->getTimestamp();
626 if( $this->section
!= '' ) {
627 if( $this->section
== 'new' ) {
628 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
630 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
631 if( !$this->preview
&& !$this->diff
) {
632 preg_match( "/^(=+)(.+)\\1/mi",
635 if( !empty( $matches[2] ) ) {
636 $this->summary
= "/* ". trim($matches[2])." */ ";
641 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
643 $wgOut->setPageTitle( $s );
644 if ( !$this->checkUnicodeCompliantBrowser() ) {
645 $this->mArticle
->setOldSubtitle();
646 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
648 if ( isset( $this->mArticle
)
649 && isset( $this->mArticle
->mRevision
)
650 && !$this->mArticle
->mRevision
->isCurrent() ) {
651 $this->mArticle
->setOldSubtitle();
652 $wgOut->addWikiText( wfMsg( 'editingold' ) );
657 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
658 } else if ( $this->isCssJsSubpage
and 'preview' != $this->formtype
) {
659 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
661 if( $this->mTitle
->isProtected('edit') ) {
662 $wgOut->addWikiText( wfMsg( 'protectedpagewarning' ) );
665 $kblength = (int)(strlen( $this->textbox1
) / 1024);
666 if( $kblength > 29 ) {
667 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
670 $rows = $wgUser->getOption( 'rows' );
671 $cols = $wgUser->getOption( 'cols' );
673 $ew = $wgUser->getOption( 'editwidth' );
674 if ( $ew ) $ew = " style=\"width:100%\"";
677 $q = 'action=submit';
678 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
679 $action = $this->mTitle
->escapeLocalURL( $q );
681 $summary = wfMsg('summary');
682 $subject = wfMsg('subject');
683 $minor = wfMsg('minoredit');
684 $watchthis = wfMsg ('watchthis');
685 $save = wfMsg('savearticle');
686 $prev = wfMsg('showpreview');
687 $diff = wfMsg('showdiff');
689 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
691 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
692 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
693 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
694 htmlspecialchars( wfMsg( 'newwindow' ) );
696 global $wgRightsText;
697 $copywarn = "<div id=\"editpage-copywarn\">\n" .
698 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
699 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
700 $wgRightsText ) . "\n</div>";
702 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
703 # prepare toolbar for edit buttons
704 $toolbar = $this->getEditToolbar();
709 // activate checkboxes if user wants them to be always active
710 if( !$this->preview
&& !$this->diff
) {
711 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis
= true;
712 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
714 // activate checkbox also if user is already watching the page,
715 // require wpWatchthis to be unset so that second condition is not
716 // checked unnecessarily
717 if( !$this->watchthis
&& $this->mTitle
->userIsWatching() ) $this->watchthis
= true;
722 if ( $wgUser->isLoggedIn() ||
$wgAllowAnonymousMinor ) {
724 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?
" checked='checked'":"").
725 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
726 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
731 if ( $wgUser->isLoggedIn() ) {
732 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
733 ($this->watchthis?
" checked='checked'":"").
734 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
735 "<label for='wpWatchthis' title=\"" .
736 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
739 $checkboxhtml = $minoredithtml . $watchhtml . '<br />';
741 $wgOut->addHTML( '<div id="wikiPreview">' );
742 if ( 'preview' == $this->formtype
) {
743 $previewOutput = $this->getPreviewText();
744 if ( $wgUser->getOption('previewontop' ) ) {
745 $wgOut->addHTML( $previewOutput );
746 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
747 $this->mArticle
->closeShowCategory();
749 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
752 $wgOut->addHTML( '</div>' );
753 if ( 'diff' == $this->formtype
) {
754 if ( $wgUser->getOption('previewontop' ) ) {
755 $wgOut->addHTML( $this->getDiff() );
760 # if this is a comment, show a subject line at the top, which is also the edit summary.
761 # Otherwise, show a summary field at the bottom
762 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
763 if( $this->section
== 'new' ) {
764 $commentsubject="{$subject}: <input tabindex='1' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
767 $commentsubject = '';
768 $editsummary="{$summary}: <input tabindex='2' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
771 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
772 if( !$this->preview
&& !$this->diff
) {
773 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
775 $templates = $this->getTemplatesUsed();
777 global $wgLivePreview;
778 if ( $wgLivePreview ) {
779 $liveOnclick = $this->doLivePreviewScript();
784 global $wgUseMetadataEdit ;
785 if ( $wgUseMetadataEdit ) {
786 $metadata = $this->mMetaData
;
787 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
788 $helppage = Title
::newFromText( wfMsg( "metadata_page" ) ) ;
789 $top = wfMsg( 'metadata', $helppage->getInternalURL() );
790 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
792 else $metadata = "" ;
796 if ($this->deletedSinceEdit
) {
797 if ( 'save' != $this->formtype
) {
798 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
800 // Hide the toolbar and edit area, use can click preview to get it back
801 // Add an confirmation checkbox and explanation.
803 $hidden = 'type="hidden" style="display:none;"';
804 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
806 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
807 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
811 $safemodehtml = $this->checkUnicodeCompliantBrowser()
813 : "<input type='hidden' name=\"safemode\" value='1' />\n";
815 $wgOut->addHTML( <<<END
817 <form id="editform" name="editform" method="post" action="$action"
818 enctype="multipart/form-data">
821 <textarea tabindex='1' accesskey="," name="wpTextbox1" rows='{$rows}'
822 cols='{$cols}'{$ew} $hidden>
824 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
831 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
832 " title=\"".wfMsg('tooltip-save')."\"/>
833 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
834 " title=\"".wfMsg('tooltip-preview')."\"/>
835 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
836 " title=\"".wfMsg('tooltip-diff')."\"/>
837 <em>{$cancel}</em> | <em>{$edithelp}</em>{$templates}" );
838 $wgOut->addWikiText( $copywarn );
840 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
841 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
842 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
844 if ( $wgUser->isLoggedIn() ) {
846 * To make it harder for someone to slip a user a page
847 * which submits an edit form to the wiki without their
848 * knowledge, a random token is associated with the login
849 * session. If it's not passed back with the submission,
850 * we won't save the page, or render user JavaScript and
853 $token = htmlspecialchars( $wgUser->editToken() );
854 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
858 if ( $this->isConflict
) {
859 require_once( "DifferenceEngine.php" );
860 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
861 DifferenceEngine
::showDiff( $this->textbox2
, $this->textbox1
,
862 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
864 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
865 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
866 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
868 $wgOut->addHTML( "</form>\n" );
869 if ( $this->formtype
== 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
870 $wgOut->addHTML( '<div id="wikiPreview">' . $previewOutput . '</div>' );
872 if ( $this->formtype
== 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
873 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
874 $wgOut->addHTML( $this->getDiff() );
877 wfProfileOut( $fname );
881 * Prepare a list of templates used by this page. Returns HTML.
883 function getTemplatesUsed() {
886 $fname = 'EditPage::getTemplatesUsed';
887 wfProfileIn( $fname );
889 $sk =& $wgUser->getSkin();
892 $articleTemplates = $this->mArticle
->getUsedTemplates();
893 if ( count( $articleTemplates ) > 0 ) {
894 $templates = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
895 foreach ( $articleTemplates as $tpl ) {
896 if ( $titleObj = Title
::makeTitle( NS_TEMPLATE
, $tpl ) ) {
897 $templates .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
900 $templates .= '</ul>';
902 wfProfileOut( $fname );
907 * Live Preview lets us fetch rendered preview page content and
908 * add it to the page without refreshing the whole page.
909 * If not supported by the browser it will fall through to the normal form
912 * This function outputs a script tag to support live preview, and
913 * returns an onclick handler which should be added to the attributes
914 * of the preview button
916 function doLivePreviewScript() {
917 global $wgStylePath, $wgJsMimeType, $wgOut;
918 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
919 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
920 '"></script>' . "\n" );
921 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
922 return 'onclick="return !livePreview('.
923 'getElementById(\'wikiPreview\'),' .
924 'editform.wpTextbox1.value,' .
925 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
928 function getLastDelete() {
929 $dbr =& wfGetDB( DB_SLAVE
);
930 $fname = 'EditPage::getLastDelete';
932 array( 'logging', 'user' ),
942 array( 'log_namespace="' . $this->mTitle
->getNamespace() . '"',
943 'log_title="' . $this->mTitle
->getDBkey() . '"',
945 'log_action="delete"',
946 'user_id=log_user' ),
948 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
950 if($dbr->numRows($res) == 1) {
951 while ( $x = $dbr->fetchObject ( $res ) )
953 $dbr->freeResult ( $res ) ;
963 function getPreviewText() {
964 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
966 $fname = 'EditPage::getPreviewText';
967 wfProfileIn( $fname );
969 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
970 "<p class='previewnote'>" . htmlspecialchars( wfMsg( 'previewnote' ) ) . "</p>\n";
971 if ( $this->isConflict
) {
972 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) .
976 $parserOptions = ParserOptions
::newFromUser( $wgUser );
977 $parserOptions->setEditSection( false );
979 # don't parse user css/js, show message about preview
980 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
982 if ( $this->isCssJsSubpage
) {
983 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
984 $previewtext = wfMsg('usercsspreview');
985 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
986 $previewtext = wfMsg('userjspreview');
988 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
989 $wgOut->addHTML( $parserOutput->mText
);
990 wfProfileOut( $fname );
993 # if user want to see preview when he edit an article
994 if( $wgUser->getOption('previewonfirst') and ($this->textbox1
== '')) {
995 $this->textbox1
= $this->mArticle
->getContent(true);
998 $toparse = $this->textbox1
;
1000 # If we're adding a comment, we need to show the
1001 # summary as the headline
1002 if($this->section
=="new" && $this->summary
!="") {
1003 $toparse="== {$this->summary} ==\n\n".$toparse;
1006 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1008 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1009 $wgTitle, $parserOptions );
1011 $previewHTML = $parserOutput->mText
;
1013 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
1014 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
1016 wfProfileOut( $fname );
1017 return $previewhead . $previewHTML;
1024 function blockedIPpage() {
1025 global $wgOut, $wgUser, $wgContLang, $wgIP;
1027 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
1028 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1029 $wgOut->setArticleRelated( false );
1031 $id = $wgUser->blockedBy();
1032 $reason = $wgUser->blockedFor();
1035 if ( is_numeric( $id ) ) {
1036 $name = User
::whoIs( $id );
1040 $link = '[[' . $wgContLang->getNsText( NS_USER
) .
1041 ":{$name}|{$name}]]";
1043 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
1044 $wgOut->returnToMain( false );
1050 function userNotLoggedInPage() {
1053 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1054 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1055 $wgOut->setArticleRelated( false );
1057 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
1058 $wgOut->returnToMain( false );
1064 function spamPage ( $match = false )
1067 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1068 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1069 $wgOut->setArticleRelated( false );
1071 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1073 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1075 $wgOut->returnToMain( false );
1079 * Forks processes to scan the originating IP for an open proxy server
1080 * MemCached can be used to skip IPs that have already been scanned
1082 function proxyCheck() {
1083 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
1084 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
1086 if ( !$wgBlockOpenProxies ) {
1092 if ( $wgUseMemCached ) {
1093 $mcKey = $wgDBname.':proxy:ip:'.$wgIP;
1094 $mcValue = $wgMemc->get( $mcKey );
1100 # Fork the processes
1102 $title = Title
::makeTitle( NS_SPECIAL
, 'Blockme' );
1103 $iphash = md5( $wgIP . $wgProxyKey );
1104 $url = $title->getFullURL( 'ip='.$iphash );
1106 foreach ( $wgProxyPorts as $port ) {
1107 $params = implode( ' ', array(
1108 escapeshellarg( $wgProxyScriptPath ),
1109 escapeshellarg( $wgIP ),
1110 escapeshellarg( $port ),
1111 escapeshellarg( $url )
1113 exec( "php $params &>/dev/null &" );
1116 if ( $wgUseMemCached ) {
1117 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
1126 function mergeChangesInto( &$editText ){
1127 $fname = 'EditPage::mergeChangesInto';
1128 wfProfileIn( $fname );
1130 $db =& wfGetDB( DB_MASTER
);
1132 // This is the revision the editor started from
1133 $baseRevision = Revision
::loadFromTimestamp(
1134 $db, $this->mArticle
->mTitle
, $this->edittime
);
1135 if( is_null( $baseRevision ) ) {
1136 wfProfileOut( $fname );
1139 $baseText = $baseRevision->getText();
1141 // The current state, we want to merge updates into it
1142 $currentRevision = Revision
::loadFromTitle(
1143 $db, $this->mArticle
->mTitle
);
1144 if( is_null( $currentRevision ) ) {
1145 wfProfileOut( $fname );
1148 $currentText = $currentRevision->getText();
1150 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1151 $editText = $result;
1152 wfProfileOut( $fname );
1155 wfProfileOut( $fname );
1161 function checkUnicodeCompliantBrowser() {
1162 global $wgBrowserBlackList;
1163 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1164 foreach ( $wgBrowserBlackList as $browser ) {
1165 if ( preg_match($browser, $currentbrowser) ) {
1173 * Format an anchor fragment as it would appear for a given section name
1174 * @param string $text
1178 function sectionAnchor( $text ) {
1179 $headline = Sanitizer
::decodeCharReferences( $text );
1181 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1182 $headline = trim( $headline );
1183 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1184 $replacearray = array(
1189 array_keys( $replacearray ),
1190 array_values( $replacearray ),
1195 * Shows a bulletin board style toolbar for common editing functions.
1196 * It can be disabled in the user preferences.
1197 * The necessary JavaScript code can be found in style/wikibits.js.
1199 function getEditToolbar() {
1200 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
1203 * toolarray an array of arrays which each include the filename of
1204 * the button image (without path), the opening tag, the closing tag,
1205 * and optionally a sample text that is inserted between the two when no
1206 * selection is highlighted.
1207 * The tip text is shown when the user moves the mouse over the button.
1209 * Already here are accesskeys (key), which are not used yet until someone
1210 * can figure out a way to make them work in IE. However, we should make
1211 * sure these keys are not defined on the edit page.
1214 array( 'image'=>'button_bold.png',
1216 'close' => "\'\'\'",
1217 'sample'=> wfMsg('bold_sample'),
1218 'tip' => wfMsg('bold_tip'),
1221 array( 'image'=>'button_italic.png',
1224 'sample'=> wfMsg('italic_sample'),
1225 'tip' => wfMsg('italic_tip'),
1228 array( 'image'=>'button_link.png',
1231 'sample'=> wfMsg('link_sample'),
1232 'tip' => wfMsg('link_tip'),
1235 array( 'image'=>'button_extlink.png',
1238 'sample'=> wfMsg('extlink_sample'),
1239 'tip' => wfMsg('extlink_tip'),
1242 array( 'image'=>'button_headline.png',
1244 'close' => " ==\\n",
1245 'sample'=> wfMsg('headline_sample'),
1246 'tip' => wfMsg('headline_tip'),
1249 array( 'image'=>'button_image.png',
1250 'open' => '[['.$wgLang->getNsText(NS_IMAGE
).":",
1252 'sample'=> wfMsg('image_sample'),
1253 'tip' => wfMsg('image_tip'),
1256 array( 'image' =>'button_media.png',
1257 'open' => '[['.$wgLang->getNsText(NS_MEDIA
).':',
1259 'sample'=> wfMsg('media_sample'),
1260 'tip' => wfMsg('media_tip'),
1263 array( 'image' =>'button_math.png',
1264 'open' => "\\<math\\>",
1265 'close' => "\\</math\\>",
1266 'sample'=> wfMsg('math_sample'),
1267 'tip' => wfMsg('math_tip'),
1270 array( 'image' =>'button_nowiki.png',
1271 'open' => "\\<nowiki\\>",
1272 'close' => "\\</nowiki\\>",
1273 'sample'=> wfMsg('nowiki_sample'),
1274 'tip' => wfMsg('nowiki_tip'),
1277 array( 'image' =>'button_sig.png',
1281 'tip' => wfMsg('sig_tip'),
1284 array( 'image' =>'button_hr.png',
1285 'open' => "\\n----\\n",
1288 'tip' => wfMsg('hr_tip'),
1292 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1294 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1295 foreach($toolarray as $tool) {
1297 $image=$wgStylePath.'/common/images/'.$tool['image'];
1298 $open=$tool['open'];
1299 $close=$tool['close'];
1300 $sample = wfEscapeJsString( $tool['sample'] );
1302 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1303 // Older browsers show a "speedtip" type message only for ALT.
1304 // Ideally these should be different, realistically they
1305 // probably don't need to be.
1306 $tip = wfEscapeJsString( $tool['tip'] );
1308 #$key = $tool["key"];
1310 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1313 $toolbar.="addInfobox('" . wfEscapeJsString( wfMsg( "infobox" ) ) .
1314 "','" . wfEscapeJsString( wfMsg( "infobox_alert" ) ) . "');\n";
1315 $toolbar.="document.writeln(\"</div>\");\n";
1317 $toolbar.="/*]]>*/\n</script>";
1322 * Output preview text only. This can be sucked into the edit page
1323 * via JavaScript, and saves the server time rendering the skin as
1324 * well as theoretically being more robust on the client (doesn't
1325 * disturb the edit box's undo history, won't eat your text on
1328 * @todo This doesn't include category or interlanguage links.
1329 * Would need to enhance it a bit, maybe wrap them in XML
1330 * or something... that might also require more skin
1331 * initialization, so check whether that's a problem.
1333 function livePreview() {
1336 header( 'Content-type: text/xml' );
1337 header( 'Cache-control: no-cache' );
1339 echo $this->getPreviewText( false, false );
1344 * Get a diff between the current contents of the edit box and the
1345 * version of the page we're editing from.
1347 * If this is a section edit, we'll replace the section as for final
1348 * save and then make a comparison.
1350 * @return string HTML
1352 function getDiff() {
1353 require_once( 'DifferenceEngine.php' );
1354 $oldtext = $this->mArticle
->fetchContent();
1355 $newtext = $this->mArticle
->getTextOfLastEditWithSectionReplacedOrAdded(
1356 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1357 $oldtitle = wfMsg( 'currentrev' );
1358 $newtitle = wfMsg( 'yourtext' );
1359 if ( $oldtext != wfMsg( 'noarticletext' ) ||
$newtext != '' ) {
1360 $difftext = DifferenceEngine
::getDiff( $oldtext, $newtext, $oldtitle, $newtitle );
1363 return '<div id="wikiDiff">' . $difftext . '</div>';
1367 * Filter an input field through a Unicode de-armoring process if it
1368 * came from an old browser with known broken Unicode editing issues.
1370 * @param WebRequest $request
1371 * @param string $field
1375 function safeUnicodeInput( $request, $field ) {
1376 $text = rtrim( $request->getText( $field ) );
1377 return $request->getBool( 'safemode' )
1378 ?
$this->unmakesafe( $text )
1383 * Filter an output field through a Unicode armoring process if it is
1384 * going to an old browser with known broken Unicode editing issues.
1386 * @param string $text
1390 function safeUnicodeOutput( $text ) {
1392 $codedText = $wgContLang->recodeForEdit( $text );
1393 return $this->checkUnicodeCompliantBrowser()
1395 : $this->makesafe( $codedText );
1399 * A number of web browsers are known to corrupt non-ASCII characters
1400 * in a UTF-8 text editing environment. To protect against this,
1401 * detected browsers will be served an armored version of the text,
1402 * with non-ASCII chars converted to numeric HTML character references.
1404 * Preexisting such character references will have a 0 added to them
1405 * to ensure that round-trips do not alter the original data.
1407 * @param string $invalue
1411 function makesafe( $invalue ) {
1412 // Armor existing references for reversability.
1413 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1418 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1419 $bytevalue = ord( $invalue{$i} );
1420 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1421 $result .= chr( $bytevalue );
1423 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1424 $working = $working << 6;
1425 $working +
= ($bytevalue & 0x3F);
1427 if( $bytesleft <= 0 ) {
1428 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1430 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1431 $working = $bytevalue & 0x1F;
1433 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1434 $working = $bytevalue & 0x0F;
1436 } else { //1111 0xxx
1437 $working = $bytevalue & 0x07;
1445 * Reverse the previously applied transliteration of non-ASCII characters
1446 * back to UTF-8. Used to protect data from corruption by broken web browsers
1447 * as listed in $wgBrowserBlackList.
1449 * @param string $invalue
1453 function unmakesafe( $invalue ) {
1455 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1456 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
1460 $hexstring .= $invalue{$i};
1462 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1464 // Do some sanity checks. These aren't needed for reversability,
1465 // but should help keep the breakage down if the editor
1466 // breaks one of the entities whilst editing.
1467 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1468 $codepoint = hexdec($hexstring);
1469 $result .= codepointToUtf8( $codepoint );
1471 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1474 $result .= substr( $invalue, $i, 1 );
1477 // reverse the transform that we made for reversability reasons.
1478 return strtr( $result, array( "�" => "&#x" ) );