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;
27 var $save = false, $preview = false, $diff = false;
28 var $minoredit = false, $watchthis = false, $recreate = false;
29 var $textbox1 = '', $textbox2 = '', $summary = '';
30 var $edittime = '', $section = '', $starttime = '';
31 var $oldid = 0, $editintro = '';
37 function EditPage( $article ) {
38 $this->mArticle
=& $article;
40 $this->mTitle
=& $wgTitle;
44 * This is the function that extracts metadata from the article body on the first view.
45 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
46 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
48 function extractMetaDataFromArticle () {
49 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
50 $this->mMetaData
= '' ;
51 if ( !$wgUseMetadataEdit ) return ;
52 if ( $wgMetadataWhitelist == '' ) return ;
54 $t = $this->mArticle
->getContent ( true ) ;
56 # MISSING : <nowiki> filtering
58 # Categories and language links
59 $t = explode ( "\n" , $t ) ;
60 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
61 $cat = $ll = array() ;
62 foreach ( $t AS $key => $x )
64 $y = trim ( strtolower ( $x ) ) ;
65 while ( substr ( $y , 0 , 2 ) == '[[' )
67 $y = explode ( ']]' , trim ( $x ) ) ;
68 $first = array_shift ( $y ) ;
69 $first = explode ( ':' , $first ) ;
70 $ns = array_shift ( $first ) ;
71 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
72 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
74 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
75 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
77 $x = implode ( ']]' , $y ) ;
79 $y = trim ( strtolower ( $x ) ) ;
83 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
84 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
85 $t = implode ( "\n" , $t ) ;
88 $sat = array () ; # stand-alone-templates; must be lowercase
89 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
90 $wl_article = new Article ( $wl_title ) ;
91 $wl = explode ( "\n" , $wl_article->getContent(true) ) ;
96 while ( substr ( $x , 0 , 1 ) == '*' )
99 $x = trim ( substr ( $x , 1 ) ) ;
103 $sat[] = strtolower ( $x ) ;
108 # Templates, but only some
109 $t = explode ( '{{' , $t ) ;
111 foreach ( $t AS $key => $x )
113 $y = explode ( '}}' , $x , 2 ) ;
114 if ( count ( $y ) == 2 )
117 $z = explode ( '|' , $z ) ;
118 $tn = array_shift ( $z ) ;
119 if ( in_array ( strtolower ( $tn ) , $sat ) )
121 $tl[] = '{{' . $y[0] . '}}' ;
123 $y = explode ( '}}' , $y[1] , 2 ) ;
125 else $t[$key] = '{{' . $x ;
127 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
130 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
131 $t = implode ( '' , $t ) ;
133 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
134 $this->mArticle
->mContent
= $t ;
135 $this->mMetaData
= $s ;
143 * This is the function that gets called for "action=edit". It
144 * sets up various member variables, then passes execution to
145 * another function, usually showEditForm()
147 * The edit form is self-submitting, so that when things like
148 * preview and edit conflicts occur, we get the same form back
149 * with the extra stuff added. Only when the final submission
150 * is made and all is well do we actually save and redirect to
151 * the newly-edited page.
154 global $wgOut, $wgUser, $wgRequest, $wgTitle;
155 // this is not an article
156 $wgOut->setArticleFlag(false);
158 $this->importFormData( $wgRequest );
159 $this->firsttime
= false;
162 $this->livePreview();
166 if ( ! $this->mTitle
->userCanEdit() ) {
167 $wgOut->readOnlyPage( $this->mArticle
->getContent( true ), true );
170 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
171 # When previewing, don't check blocked state - will get caught at save time.
172 # Also, check when starting edition is done against slave to improve performance.
173 $this->blockedIPpage();
176 if ( !$wgUser->isAllowed('edit') ) {
177 if ( $wgUser->isAnon() ) {
178 $this->userNotLoggedInPage();
181 $wgOut->readOnlyPage( $this->mArticle
->getContent( true ), true );
185 if ( wfReadOnly() ) {
186 if( $this->save ||
$this->preview
) {
187 $this->formtype
= 'preview';
188 } else if ( $this->diff
) {
189 $this->formtype
= 'diff';
191 $wgOut->readOnlyPage( $this->mArticle
->getContent( true ) );
196 $this->formtype
= 'save';
197 } else if ( $this->preview
) {
198 $this->formtype
= 'preview';
199 } else if ( $this->diff
) {
200 $this->formtype
= 'diff';
201 } else { # First time through
202 $this->firsttime
= true;
203 if( $this->previewOnOpen() ) {
204 $this->formtype
= 'preview';
206 $this->extractMetaDataFromArticle () ;
207 $this->formtype
= 'initial';
212 $this->isConflict
= false;
213 // css / js subpages of user pages get a special treatment
214 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
216 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
217 * no matter it's current state
219 $this->deletedSinceEdit
= false;
220 if ( $this->edittime
!= '' ) {
221 /* Note that we rely on logging table, which hasn't been always there,
222 * but that doesn't matter, because this only applies to brand new
223 * deletes. This is done on every preview and save request. Move it further down
224 * to only perform it on saves
226 if ( $this->mTitle
->isDeleted() ) {
227 $query = $this->getLastDelete();
228 if ( !is_null($query) ) {
229 $deletetime = $query->log_timestamp
;
230 if ( ($deletetime - $this->starttime
) > 0 ) {
231 $this->deletedSinceEdit
= true;
237 if(!$this->mTitle
->getArticleID() && ('initial' == $this->formtype ||
$this->firsttime
)) { # new article
240 if( $this->mTitle
->isTalkPage() ) {
241 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
244 # Attempt submission here. This will check for edit conflicts,
245 # and redundantly check for locked database, blocked IPs, etc.
246 # that edit() already checked just in case someone tries to sneak
247 # in the back door with a hand-edited submission URL.
249 if ( 'save' == $this->formtype
) {
250 if ( !$this->attemptSave() ) {
255 # First time through: get contents, set time for conflict
257 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
258 $this->initialiseForm();
261 $this->showEditForm();
265 * Return true if this page should be previewed when the edit form
266 * is initially opened.
270 function previewOnOpen() {
272 return $wgUser->getOption( 'previewonfirst' ) ||
273 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
274 !$this->mTitle
->exists() );
280 function importFormData( &$request ) {
281 if( $request->wasPosted() ) {
282 # These fields need to be checked for encoding.
283 # Also remove trailing whitespace, but don't remove _initial_
284 # whitespace from the text boxes. This may be significant formatting.
285 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
286 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
287 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
288 $this->summary
= $request->getText( 'wpSummary' );
290 $this->edittime
= $request->getVal( 'wpEdittime' );
291 $this->starttime
= $request->getVal( 'wpStarttime' );
292 if( is_null( $this->edittime
) ) {
293 # If the form is incomplete, force to preview.
294 $this->preview
= true;
296 if( $this->tokenOk( $request ) ) {
297 # Some browsers will not report any submit button
298 # if the user hits enter in the comment box.
299 # The unmarked state will be assumed to be a save,
300 # if the form seems otherwise complete.
301 $this->preview
= $request->getCheck( 'wpPreview' );
302 $this->diff
= $request->getCheck( 'wpDiff' );
304 # Page might be a hack attempt posted from
305 # an external site. Preview instead of saving.
306 $this->preview
= true;
309 $this->save
= ! ( $this->preview
OR $this->diff
);
310 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
311 $this->edittime
= null;
314 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
315 $this->starttime
= null;
318 $this->recreate
= $request->getCheck( 'wpRecreate' );
320 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
321 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
323 # Not a posted form? Start with nothing.
324 $this->textbox1
= '';
325 $this->textbox2
= '';
326 $this->mMetaData
= '';
328 $this->edittime
= '';
329 $this->starttime
= wfTimestampNow();
330 $this->preview
= false;
333 $this->minoredit
= false;
334 $this->watchthis
= false;
335 $this->recreate
= false;
338 $this->oldid
= $request->getInt( 'oldid' );
340 # Section edit can come from either the form or a link
341 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
343 $this->live
= $request->getCheck( 'live' );
344 $this->editintro
= $request->getText( 'editintro' );
349 * Make sure the form isn't faking a user's credentials.
351 * @param WebRequest $request
355 function tokenOk( &$request ) {
357 if( $wgUser->isAnon() ) {
358 # Anonymous users may not have a session
359 # open. Don't tokenize.
362 return $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
366 function showIntro() {
368 $addstandardintro=true;
369 if($this->editintro
) {
370 $introtitle=Title
::newFromText($this->editintro
);
371 if(isset($introtitle) && $introtitle->userCanRead()) {
372 $rev=Revision
::newFromTitle($introtitle);
374 $wgOut->addWikiText($rev->getText());
375 $addstandardintro=false;
379 if($addstandardintro) {
380 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
386 * @return bool false if output is done, true if the rest of the form should be displayed
388 function attemptSave() {
389 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
391 # Reintegrate metadata
392 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
393 $this->mMetaData
= '' ;
396 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
397 $this->spamPage ( $matches[0] );
400 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
401 # Error messages or other handling should be performed by the filter function
404 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
405 # Check block state against master, thus 'false'.
406 $this->blockedIPpage();
410 if ( !$wgUser->isAllowed('edit') ) {
411 if ( $wgUser->isAnon() ) {
412 $this->userNotLoggedInPage();
416 $wgOut->readOnlyPage();
421 if ( wfReadOnly() ) {
422 $wgOut->readOnlyPage();
425 if ( $wgUser->pingLimiter() ) {
426 $wgOut->rateLimited();
430 # If the article has been deleted while editing, don't save it without
432 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
436 # If article is new, insert it.
437 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
439 # Don't save a new article if it's blank.
440 if ( ( '' == $this->textbox1
) ||
441 ( wfMsg( 'newarticletext' ) == $this->textbox1
) ) {
442 $wgOut->redirect( $this->mTitle
->getFullURL() );
445 if (wfRunHooks('ArticleSave', array(&$this->mArticle
, &$wgUser, &$this->textbox1
,
446 &$this->summary
, &$this->minoredit
, &$this->watchthis
, NULL)))
449 $isComment=($this->section
=='new');
450 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
451 $this->minoredit
, $this->watchthis
, false, $isComment);
452 wfRunHooks('ArticleSaveComplete', array(&$this->mArticle
, &$wgUser, $this->textbox1
,
453 $this->summary
, $this->minoredit
,
454 $this->watchthis
, NULL));
459 # Article exists. Check for edit conflict.
461 $this->mArticle
->clear(); # Force reload of dates, etc.
462 $this->mArticle
->forUpdate( true ); # Lock the article
464 if( ( $this->section
!= 'new' ) &&
465 ($this->mArticle
->getTimestamp() != $this->edittime
) )
467 $this->isConflict
= true;
469 $userid = $wgUser->getID();
471 if ( $this->isConflict
) {
472 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
473 $this->mArticle
->getTimestamp() . "'\n" );
474 $text = $this->mArticle
->getTextOfLastEditWithSectionReplacedOrAdded(
475 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
478 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
479 $text = $this->mArticle
->getTextOfLastEditWithSectionReplacedOrAdded(
480 $this->section
, $this->textbox1
, $this->summary
);
483 # Suppress edit conflict with self
484 if ( ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
485 wfDebug( "Suppressing edit conflict, same user.\n" );
486 $this->isConflict
= false;
488 # switch from section editing to normal editing in edit conflict
489 if($this->isConflict
) {
491 if( $this->mergeChangesInto( $text ) ){
492 // Successful merge! Maybe we should tell the user the good news?
493 $this->isConflict
= false;
494 wfDebug( "Suppressing edit conflict, successful merge.\n" );
497 $this->textbox1
= $text;
498 wfDebug( "Keeping edit conflict, failed merge.\n" );
503 if ( $this->isConflict
) {
509 if( $this->section
== 'new' ) {
510 if( $this->summary
!= '' ) {
511 $sectionanchor = $this->sectionAnchor( $this->summary
);
513 } elseif( $this->section
!= '' ) {
514 # Try to get a section anchor from the section source, redirect to edited section if header found
515 # XXX: might be better to integrate this into Article::getTextOfLastEditWithSectionReplacedOrAdded
516 # for duplicate heading checking and maybe parsing
517 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
518 # we can't deal with anchors, includes, html etc in the header for now,
519 # headline would need to be parsed to improve this
520 if($hasmatch and strlen($matches[2]) > 0) {
521 $sectionanchor = $this->sectionAnchor( $matches[2] );
525 // Save errors may fall down to the edit form, but we've now
526 // merged the section into full text. Clear the section field
527 // so that later submission of conflict forms won't try to
528 // replace that into a duplicated mess.
529 $this->textbox1
= $text;
532 if (wfRunHooks('ArticleSave', array(&$this->mArticle
, &$wgUser, &$text,
533 &$this->summary
, &$this->minoredit
,
534 &$this->watchthis
, &$sectionanchor)))
536 # update the article here
537 if($this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
538 $this->watchthis
, '', $sectionanchor ))
540 wfRunHooks('ArticleSaveComplete',
541 array(&$this->mArticle
, &$wgUser, $text,
542 $this->summary
, $this->minoredit
,
543 $this->watchthis
, $sectionanchor));
546 $this->isConflict
= true;
553 * Initialise form fields in the object
554 * Called on the first invocation, e.g. when a user clicks an edit link
556 function initialiseForm() {
557 $this->edittime
= $this->mArticle
->getTimestamp();
558 $this->textbox1
= $this->mArticle
->getContent( true );
564 * Send the edit form and related headers to $wgOut
566 function showEditForm() {
567 global $wgOut, $wgUser, $wgAllowAnonymousMinor, $wgLang, $wgContLang;
569 $sk =& $wgUser->getSkin();
571 $wgOut->setRobotpolicy( 'noindex,nofollow' );
573 # Enabled article-related sidebar, toplinks, etc.
574 $wgOut->setArticleRelated( true );
576 if ( $this->isConflict
) {
577 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
578 $wgOut->setPageTitle( $s );
579 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
581 $this->textbox2
= $this->textbox1
;
582 $this->textbox1
= $this->mArticle
->getContent( true );
583 $this->edittime
= $this->mArticle
->getTimestamp();
586 if( $this->section
!= '' ) {
587 if( $this->section
== 'new' ) {
588 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
590 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
591 if( !$this->preview
&& !$this->diff
) {
592 preg_match( "/^(=+)(.+)\\1/mi",
595 if( !empty( $matches[2] ) ) {
596 $this->summary
= "/* ". trim($matches[2])." */ ";
601 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
603 $wgOut->setPageTitle( $s );
604 if ( !$this->checkUnicodeCompliantBrowser() ) {
605 $this->mArticle
->setOldSubtitle();
606 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
608 if ( isset( $this->mArticle
)
609 && isset( $this->mArticle
->mRevision
)
610 && !$this->mArticle
->mRevision
->isCurrent() ) {
611 $this->mArticle
->setOldSubtitle();
612 $wgOut->addWikiText( wfMsg( 'editingold' ) );
617 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
618 } else if ( $this->isCssJsSubpage
and 'preview' != $this->formtype
) {
619 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
621 if( $this->mTitle
->isProtected('edit') ) {
622 $wgOut->addWikiText( wfMsg( 'protectedpagewarning' ) );
625 $kblength = (int)(strlen( $this->textbox1
) / 1024);
626 if( $kblength > 29 ) {
627 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
630 $rows = $wgUser->getOption( 'rows' );
631 $cols = $wgUser->getOption( 'cols' );
633 $ew = $wgUser->getOption( 'editwidth' );
634 if ( $ew ) $ew = " style=\"width:100%\"";
637 $q = 'action=submit';
638 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
639 $action = $this->mTitle
->escapeLocalURL( $q );
641 $summary = wfMsg('summary');
642 $subject = wfMsg('subject');
643 $minor = wfMsg('minoredit');
644 $watchthis = wfMsg ('watchthis');
645 $save = wfMsg('savearticle');
646 $prev = wfMsg('showpreview');
647 $diff = wfMsg('showdiff');
649 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
651 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
652 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
653 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
654 htmlspecialchars( wfMsg( 'newwindow' ) );
656 global $wgRightsText;
657 $copywarn = "<div id=\"editpage-copywarn\">\n" .
658 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
659 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
660 $wgRightsText ) . "\n</div>";
662 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
663 # prepare toolbar for edit buttons
664 $toolbar = $this->getEditToolbar();
669 // activate checkboxes if user wants them to be always active
670 if( !$this->preview
&& !$this->diff
) {
671 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis
= true;
672 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
674 // activate checkbox also if user is already watching the page,
675 // require wpWatchthis to be unset so that second condition is not
676 // checked unnecessarily
677 if( !$this->watchthis
&& $this->mTitle
->userIsWatching() ) $this->watchthis
= true;
682 if ( $wgUser->isLoggedIn() ||
$wgAllowAnonymousMinor ) {
684 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?
" checked='checked'":"").
685 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
686 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
691 if ( $wgUser->isLoggedIn() ) {
692 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
693 ($this->watchthis?
" checked='checked'":"").
694 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
695 "<label for='wpWatchthis' title=\"" .
696 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
699 $checkboxhtml = $minoredithtml . $watchhtml . '<br />';
701 $wgOut->addHTML( '<div id="wikiPreview">' );
702 if ( 'preview' == $this->formtype
) {
703 $previewOutput = $this->getPreviewText();
704 if ( $wgUser->getOption('previewontop' ) ) {
705 $wgOut->addHTML( $previewOutput );
706 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
707 $this->mArticle
->closeShowCategory();
709 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
712 $wgOut->addHTML( '</div>' );
713 if ( 'diff' == $this->formtype
) {
714 if ( $wgUser->getOption('previewontop' ) ) {
715 $wgOut->addHTML( $this->getDiff() );
720 # if this is a comment, show a subject line at the top, which is also the edit summary.
721 # Otherwise, show a summary field at the bottom
722 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
723 if( $this->section
== 'new' ) {
724 $commentsubject="{$subject}: <input tabindex='1' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
727 $commentsubject = '';
728 $editsummary="{$summary}: <input tabindex='2' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
731 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
732 if( !$this->preview
&& !$this->diff
) {
733 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
735 $templates = $this->getTemplatesUsed();
737 global $wgLivePreview;
738 if ( $wgLivePreview ) {
739 $liveOnclick = $this->doLivePreviewScript();
744 global $wgUseMetadataEdit ;
745 if ( $wgUseMetadataEdit ) {
746 $metadata = $this->mMetaData
;
747 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
748 $helppage = Title
::newFromText( wfMsg( "metadata_page" ) ) ;
749 $top = wfMsg( 'metadata', $helppage->getInternalURL() );
750 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
752 else $metadata = "" ;
756 if ($this->deletedSinceEdit
) {
757 if ( 'save' != $this->formtype
) {
758 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
760 // Hide the toolbar and edit area, use can click preview to get it back
761 // Add an confirmation checkbox and explanation.
763 $hidden = 'type="hidden" style="display:none;"';
764 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $query->user_name
, $query->log_comment
));
766 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
767 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
771 $safemodehtml = $this->checkUnicodeCompliantBrowser()
773 : "<input type='hidden' name=\"safemode\" value='1' />\n";
775 $wgOut->addHTML( <<<END
777 <form id="editform" name="editform" method="post" action="$action"
778 enctype="multipart/form-data">
781 <textarea tabindex='1' accesskey="," name="wpTextbox1" rows='{$rows}'
782 cols='{$cols}'{$ew} $hidden>
784 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
791 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
792 " title=\"".wfMsg('tooltip-save')."\"/>
793 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
794 " title=\"".wfMsg('tooltip-preview')."\"/>
795 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
796 " title=\"".wfMsg('tooltip-diff')."\"/>
797 <em>{$cancel}</em> | <em>{$edithelp}</em>{$templates}" );
798 $wgOut->addWikiText( $copywarn );
800 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
801 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
802 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
804 if ( $wgUser->isLoggedIn() ) {
806 * To make it harder for someone to slip a user a page
807 * which submits an edit form to the wiki without their
808 * knowledge, a random token is associated with the login
809 * session. If it's not passed back with the submission,
810 * we won't save the page, or render user JavaScript and
813 $token = htmlspecialchars( $wgUser->editToken() );
814 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
818 if ( $this->isConflict
) {
819 require_once( "DifferenceEngine.php" );
820 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
821 DifferenceEngine
::showDiff( $this->textbox2
, $this->textbox1
,
822 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
824 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
825 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
826 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
828 $wgOut->addHTML( "</form>\n" );
829 if ( $this->formtype
== 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
830 $wgOut->addHTML( '<div id="wikiPreview">' . $previewOutput . '</div>' );
832 if ( $this->formtype
== 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
833 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
834 $wgOut->addHTML( $this->getDiff() );
839 * Prepare a list of templates used by this page. Returns HTML.
841 function getTemplatesUsed() {
843 $sk =& $wgUser->getSkin();
846 $articleTemplates = $this->mArticle
->getUsedTemplates();
847 if ( count( $articleTemplates ) > 0 ) {
848 $templates = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
849 foreach ( $articleTemplates as $tpl ) {
850 if ( $titleObj = Title
::makeTitle( NS_TEMPLATE
, $tpl ) ) {
851 $templates .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
854 $templates .= '</ul>';
860 * Live Preview lets us fetch rendered preview page content and
861 * add it to the page without refreshing the whole page.
862 * If not supported by the browser it will fall through to the normal form
865 * This function outputs a script tag to support live preview, and
866 * returns an onclick handler which should be added to the attributes
867 * of the preview button
869 function doLivePreviewScript() {
870 global $wgStylePath, $wgJsMimeType, $wgOut;
871 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
872 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
873 '"></script>' . "\n" );
874 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
875 return 'onclick="return !livePreview('.
876 'getElementById(\'wikiPreview\'),' .
877 'editform.wpTextbox1.value,' .
878 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
881 function getLastDelete() {
882 $dbr =& wfGetDB( DB_SLAVE
);
883 $fname = 'EditPage::getLastDelete';
885 array( 'logging', 'user' ),
895 array( 'log_namespace="' . $this->mTitle
->getNamespace() . '"',
896 'log_title="' . $this->mTitle
->getDBkey() . '"',
898 'log_action="delete"',
899 'user_id=log_user' ),
901 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
903 if($dbr->numRows($res) == 1) {
904 while ( $x = $dbr->fetchObject ( $res ) )
906 $dbr->freeResult ( $res ) ;
916 function getPreviewText() {
917 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
918 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
919 "<p class='previewnote'>" . htmlspecialchars( wfMsg( 'previewnote' ) ) . "</p>\n";
920 if ( $this->isConflict
) {
921 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) .
925 $parserOptions = ParserOptions
::newFromUser( $wgUser );
926 $parserOptions->setEditSection( false );
928 # don't parse user css/js, show message about preview
929 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
931 if ( $this->isCssJsSubpage
) {
932 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
933 $previewtext = wfMsg('usercsspreview');
934 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
935 $previewtext = wfMsg('userjspreview');
937 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
938 $wgOut->addHTML( $parserOutput->mText
);
941 # if user want to see preview when he edit an article
942 if( $wgUser->getOption('previewonfirst') and ($this->textbox1
== '')) {
943 $this->textbox1
= $this->mArticle
->getContent(true);
946 $toparse = $this->textbox1
;
948 # If we're adding a comment, we need to show the
949 # summary as the headline
950 if($this->section
=="new" && $this->summary
!="") {
951 $toparse="== {$this->summary} ==\n\n".$toparse;
954 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
956 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
957 $wgTitle, $parserOptions );
959 $previewHTML = $parserOutput->mText
;
961 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
962 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
963 return $previewhead . $previewHTML;
970 function blockedIPpage() {
971 global $wgOut, $wgUser, $wgContLang, $wgIP;
973 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
974 $wgOut->setRobotpolicy( 'noindex,nofollow' );
975 $wgOut->setArticleRelated( false );
977 $id = $wgUser->blockedBy();
978 $reason = $wgUser->blockedFor();
981 if ( is_numeric( $id ) ) {
982 $name = User
::whoIs( $id );
986 $link = '[[' . $wgContLang->getNsText( NS_USER
) .
987 ":{$name}|{$name}]]";
989 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
990 $wgOut->returnToMain( false );
996 function userNotLoggedInPage() {
999 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1000 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1001 $wgOut->setArticleRelated( false );
1003 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
1004 $wgOut->returnToMain( false );
1010 function spamPage ( $match = false )
1013 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1014 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1015 $wgOut->setArticleRelated( false );
1017 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1019 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1021 $wgOut->returnToMain( false );
1025 * Forks processes to scan the originating IP for an open proxy server
1026 * MemCached can be used to skip IPs that have already been scanned
1028 function proxyCheck() {
1029 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
1030 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
1032 if ( !$wgBlockOpenProxies ) {
1038 if ( $wgUseMemCached ) {
1039 $mcKey = $wgDBname.':proxy:ip:'.$wgIP;
1040 $mcValue = $wgMemc->get( $mcKey );
1046 # Fork the processes
1048 $title = Title
::makeTitle( NS_SPECIAL
, 'Blockme' );
1049 $iphash = md5( $wgIP . $wgProxyKey );
1050 $url = $title->getFullURL( 'ip='.$iphash );
1052 foreach ( $wgProxyPorts as $port ) {
1053 $params = implode( ' ', array(
1054 escapeshellarg( $wgProxyScriptPath ),
1055 escapeshellarg( $wgIP ),
1056 escapeshellarg( $port ),
1057 escapeshellarg( $url )
1059 exec( "php $params &>/dev/null &" );
1062 if ( $wgUseMemCached ) {
1063 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
1072 function mergeChangesInto( &$editText ){
1073 $fname = 'EditPage::mergeChangesInto';
1074 wfProfileIn( $fname );
1076 $db =& wfGetDB( DB_MASTER
);
1078 // This is the revision the editor started from
1079 $baseRevision = Revision
::loadFromTimestamp(
1080 $db, $this->mArticle
->mTitle
, $this->edittime
);
1081 if( is_null( $baseRevision ) ) {
1082 wfProfileOut( $fname );
1085 $baseText = $baseRevision->getText();
1087 // The current state, we want to merge updates into it
1088 $currentRevision = Revision
::loadFromTitle(
1089 $db, $this->mArticle
->mTitle
);
1090 if( is_null( $currentRevision ) ) {
1091 wfProfileOut( $fname );
1094 $currentText = $currentRevision->getText();
1096 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1097 $editText = $result;
1098 wfProfileOut( $fname );
1101 wfProfileOut( $fname );
1107 function checkUnicodeCompliantBrowser() {
1108 global $wgBrowserBlackList;
1109 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1110 foreach ( $wgBrowserBlackList as $browser ) {
1111 if ( preg_match($browser, $currentbrowser) ) {
1119 * Format an anchor fragment as it would appear for a given section name
1120 * @param string $text
1124 function sectionAnchor( $text ) {
1125 $headline = Sanitizer
::decodeCharReferences( $text );
1127 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1128 $headline = trim( $headline );
1129 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1130 $replacearray = array(
1135 array_keys( $replacearray ),
1136 array_values( $replacearray ),
1141 * Shows a bulletin board style toolbar for common editing functions.
1142 * It can be disabled in the user preferences.
1143 * The necessary JavaScript code can be found in style/wikibits.js.
1145 function getEditToolbar() {
1146 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
1149 * toolarray an array of arrays which each include the filename of
1150 * the button image (without path), the opening tag, the closing tag,
1151 * and optionally a sample text that is inserted between the two when no
1152 * selection is highlighted.
1153 * The tip text is shown when the user moves the mouse over the button.
1155 * Already here are accesskeys (key), which are not used yet until someone
1156 * can figure out a way to make them work in IE. However, we should make
1157 * sure these keys are not defined on the edit page.
1160 array( 'image'=>'button_bold.png',
1162 'close' => "\'\'\'",
1163 'sample'=> wfMsg('bold_sample'),
1164 'tip' => wfMsg('bold_tip'),
1167 array( 'image'=>'button_italic.png',
1170 'sample'=> wfMsg('italic_sample'),
1171 'tip' => wfMsg('italic_tip'),
1174 array( 'image'=>'button_link.png',
1177 'sample'=> wfMsg('link_sample'),
1178 'tip' => wfMsg('link_tip'),
1181 array( 'image'=>'button_extlink.png',
1184 'sample'=> wfMsg('extlink_sample'),
1185 'tip' => wfMsg('extlink_tip'),
1188 array( 'image'=>'button_headline.png',
1190 'close' => " ==\\n",
1191 'sample'=> wfMsg('headline_sample'),
1192 'tip' => wfMsg('headline_tip'),
1195 array( 'image'=>'button_image.png',
1196 'open' => '[['.$wgLang->getNsText(NS_IMAGE
).":",
1198 'sample'=> wfMsg('image_sample'),
1199 'tip' => wfMsg('image_tip'),
1202 array( 'image' =>'button_media.png',
1203 'open' => '[['.$wgLang->getNsText(NS_MEDIA
).':',
1205 'sample'=> wfMsg('media_sample'),
1206 'tip' => wfMsg('media_tip'),
1209 array( 'image' =>'button_math.png',
1210 'open' => "\\<math\\>",
1211 'close' => "\\</math\\>",
1212 'sample'=> wfMsg('math_sample'),
1213 'tip' => wfMsg('math_tip'),
1216 array( 'image' =>'button_nowiki.png',
1217 'open' => "\\<nowiki\\>",
1218 'close' => "\\</nowiki\\>",
1219 'sample'=> wfMsg('nowiki_sample'),
1220 'tip' => wfMsg('nowiki_tip'),
1223 array( 'image' =>'button_sig.png',
1227 'tip' => wfMsg('sig_tip'),
1230 array( 'image' =>'button_hr.png',
1231 'open' => "\\n----\\n",
1234 'tip' => wfMsg('hr_tip'),
1238 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1240 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1241 foreach($toolarray as $tool) {
1243 $image=$wgStylePath.'/common/images/'.$tool['image'];
1244 $open=$tool['open'];
1245 $close=$tool['close'];
1246 $sample = wfEscapeJsString( $tool['sample'] );
1248 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1249 // Older browsers show a "speedtip" type message only for ALT.
1250 // Ideally these should be different, realistically they
1251 // probably don't need to be.
1252 $tip = wfEscapeJsString( $tool['tip'] );
1254 #$key = $tool["key"];
1256 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1259 $toolbar.="addInfobox('" . wfEscapeJsString( wfMsg( "infobox" ) ) .
1260 "','" . wfEscapeJsString( wfMsg( "infobox_alert" ) ) . "');\n";
1261 $toolbar.="document.writeln(\"</div>\");\n";
1263 $toolbar.="/*]]>*/\n</script>";
1268 * Output preview text only. This can be sucked into the edit page
1269 * via JavaScript, and saves the server time rendering the skin as
1270 * well as theoretically being more robust on the client (doesn't
1271 * disturb the edit box's undo history, won't eat your text on
1274 * @todo This doesn't include category or interlanguage links.
1275 * Would need to enhance it a bit, maybe wrap them in XML
1276 * or something... that might also require more skin
1277 * initialization, so check whether that's a problem.
1279 function livePreview() {
1282 header( 'Content-type: text/xml' );
1283 header( 'Cache-control: no-cache' );
1285 echo $this->getPreviewText( false, false );
1290 * Get a diff between the current contents of the edit box and the
1291 * version of the page we're editing from.
1293 * If this is a section edit, we'll replace the section as for final
1294 * save and then make a comparison.
1296 * @return string HTML
1298 function getDiff() {
1299 require_once( 'DifferenceEngine.php' );
1300 $oldtext = $this->mArticle
->fetchContent();
1301 $newtext = $this->mArticle
->getTextOfLastEditWithSectionReplacedOrAdded(
1302 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1303 $oldtitle = wfMsg( 'currentrev' );
1304 $newtitle = wfMsg( 'yourtext' );
1305 if ( $oldtext != wfMsg( 'noarticletext' ) ||
$newtext != '' ) {
1306 $difftext = DifferenceEngine
::getDiff( $oldtext, $newtext, $oldtitle, $newtitle );
1309 return '<div id="wikiDiff">' . $difftext . '</div>';
1313 * Filter an input field through a Unicode de-armoring process if it
1314 * came from an old browser with known broken Unicode editing issues.
1316 * @param WebRequest $request
1317 * @param string $field
1321 function safeUnicodeInput( $request, $field ) {
1322 $text = rtrim( $request->getText( $field ) );
1323 return $request->getBool( 'safemode' )
1324 ?
$this->unmakesafe( $text )
1329 * Filter an output field through a Unicode armoring process if it is
1330 * going to an old browser with known broken Unicode editing issues.
1332 * @param string $text
1336 function safeUnicodeOutput( $text ) {
1338 $codedText = $wgContLang->recodeForEdit( $text );
1339 return $this->checkUnicodeCompliantBrowser()
1341 : $this->makesafe( $codedText );
1345 * A number of web browsers are known to corrupt non-ASCII characters
1346 * in a UTF-8 text editing environment. To protect against this,
1347 * detected browsers will be served an armored version of the text,
1348 * with non-ASCII chars converted to numeric HTML character references.
1350 * Preexisting such character references will have a 0 added to them
1351 * to ensure that round-trips do not alter the original data.
1353 * @param string $invalue
1357 function makesafe( $invalue ) {
1358 // Armor existing references for reversability.
1359 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1364 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1365 $bytevalue = ord( $invalue{$i} );
1366 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1367 $result .= chr( $bytevalue );
1369 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1370 $working = $working << 6;
1371 $working +
= ($bytevalue & 0x3F);
1373 if( $bytesleft <= 0 ) {
1374 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1376 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1377 $working = $bytevalue & 0x1F;
1379 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1380 $working = $bytevalue & 0x0F;
1382 } else { //1111 0xxx
1383 $working = $bytevalue & 0x07;
1391 * Reverse the previously applied transliteration of non-ASCII characters
1392 * back to UTF-8. Used to protect data from corruption by broken web browsers
1393 * as listed in $wgBrowserBlackList.
1395 * @param string $invalue
1399 function unmakesafe( $invalue ) {
1401 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1402 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
1406 $hexstring .= $invalue{$i};
1408 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1410 // Do some sanity checks. These aren't needed for reversability,
1411 // but should help keep the breakage down if the editor
1412 // breaks one of the entities whilst editing.
1413 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1414 $codepoint = hexdec($hexstring);
1415 $result .= codepointToUtf8( $codepoint );
1417 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1420 $result .= substr( $invalue, $i, 1 );
1423 // reverse the transform that we made for reversability reasons.
1424 return strtr( $result, array( "�" => "&#x" ) );