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
22 var $save = false, $preview = false, $diff = false;
23 var $minoredit = false, $watchthis = false, $recreate = false;
24 var $textbox1 = '', $textbox2 = '', $summary = '';
25 var $edittime = '', $section = '', $starttime = '';
32 function EditPage( $article ) {
33 $this->mArticle
=& $article;
35 $this->mTitle
=& $wgTitle;
39 * This is the function that extracts metadata from the article body on the first view.
40 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
41 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
43 function extractMetaDataFromArticle () {
44 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
45 $this->mMetaData
= '' ;
46 if ( !$wgUseMetadataEdit ) return ;
47 if ( $wgMetadataWhitelist == '' ) return ;
49 $t = $this->mArticle
->getContent ( true ) ;
51 # MISSING : <nowiki> filtering
53 # Categories and language links
54 $t = explode ( "\n" , $t ) ;
55 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
56 $cat = $ll = array() ;
57 foreach ( $t AS $key => $x )
59 $y = trim ( strtolower ( $x ) ) ;
60 while ( substr ( $y , 0 , 2 ) == '[[' )
62 $y = explode ( ']]' , trim ( $x ) ) ;
63 $first = array_shift ( $y ) ;
64 $first = explode ( ':' , $first ) ;
65 $ns = array_shift ( $first ) ;
66 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
67 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
69 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
70 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
72 $x = implode ( ']]' , $y ) ;
74 $y = trim ( strtolower ( $x ) ) ;
78 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
79 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
80 $t = implode ( "\n" , $t ) ;
83 $sat = array () ; # stand-alone-templates; must be lowercase
84 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
85 $wl_article = new Article ( $wl_title ) ;
86 $wl = explode ( "\n" , $wl_article->getContent(true) ) ;
91 while ( substr ( $x , 0 , 1 ) == '*' )
94 $x = trim ( substr ( $x , 1 ) ) ;
98 $sat[] = strtolower ( $x ) ;
103 # Templates, but only some
104 $t = explode ( '{{' , $t ) ;
106 foreach ( $t AS $key => $x )
108 $y = explode ( '}}' , $x , 2 ) ;
109 if ( count ( $y ) == 2 )
112 $z = explode ( '|' , $z ) ;
113 $tn = array_shift ( $z ) ;
114 if ( in_array ( strtolower ( $tn ) , $sat ) )
116 $tl[] = '{{' . $y[0] . '}}' ;
118 $y = explode ( '}}' , $y[1] , 2 ) ;
120 else $t[$key] = '{{' . $x ;
122 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
125 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
126 $t = implode ( '' , $t ) ;
128 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
129 $this->mArticle
->mContent
= $t ;
130 $this->mMetaData
= $s ;
134 * This is the function that gets called for "action=edit".
137 global $wgOut, $wgUser, $wgRequest;
138 // this is not an article
139 $wgOut->setArticleFlag(false);
141 $this->importFormData( $wgRequest );
144 $this->livePreview();
148 if ( ! $this->mTitle
->userCanEdit() ) {
149 $wgOut->readOnlyPage( $this->mArticle
->getContent( true ), true );
152 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
153 # When previewing, don't check blocked state - will get caught at save time.
154 # Also, check when starting edition is done against slave to improve performance.
155 $this->blockedIPpage();
158 if ( !$wgUser->isAllowed('edit') ) {
159 if ( $wgUser->isAnon() ) {
160 $this->userNotLoggedInPage();
163 $wgOut->readOnlyPage( $this->mArticle
->getContent( true ), true );
167 if ( wfReadOnly() ) {
168 if( $this->save ||
$this->preview
) {
169 $this->editForm( 'preview' );
170 } else if ( $this->diff
) {
171 $this->editForm( 'diff' );
173 $wgOut->readOnlyPage( $this->mArticle
->getContent( true ) );
178 $this->editForm( 'save' );
179 } else if ( $this->preview
) {
180 $this->editForm( 'preview' );
181 } else if ( $this->diff
) {
182 $this->editForm( 'diff' );
183 } else { # First time through
184 if( $this->previewOnOpen() ) {
185 $this->editForm( 'preview', true );
187 $this->extractMetaDataFromArticle () ;
188 $this->editForm( 'initial', true );
194 * Return true if this page should be previewed when the edit form
195 * is initially opened.
199 function previewOnOpen() {
201 return $wgUser->getOption( 'previewonfirst' ) ||
202 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
203 !$this->mTitle
->exists() );
209 function importFormData( &$request ) {
210 if( $request->wasPosted() ) {
211 # These fields need to be checked for encoding.
212 # Also remove trailing whitespace, but don't remove _initial_
213 # whitespace from the text boxes. This may be significant formatting.
214 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
215 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
216 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
217 $this->summary
= $request->getText( 'wpSummary' );
219 $this->edittime
= $request->getVal( 'wpEdittime' );
220 $this->starttime
= $request->getVal( 'wpStarttime' );
221 if( is_null( $this->edittime
) ) {
222 # If the form is incomplete, force to preview.
223 $this->preview
= true;
225 if( $this->tokenOk( $request ) ) {
226 # Some browsers will not report any submit button
227 # if the user hits enter in the comment box.
228 # The unmarked state will be assumed to be a save,
229 # if the form seems otherwise complete.
230 $this->preview
= $request->getCheck( 'wpPreview' );
231 $this->diff
= $request->getCheck( 'wpDiff' );
233 # Page might be a hack attempt posted from
234 # an external site. Preview instead of saving.
235 $this->preview
= true;
238 $this->save
= ! ( $this->preview
OR $this->diff
);
239 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
240 $this->edittime
= null;
243 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
244 $this->starttime
= null;
247 $this->recreate
= $request->getCheck( 'wpRecreate' );
249 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
250 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
252 # Not a posted form? Start with nothing.
253 $this->textbox1
= '';
254 $this->textbox2
= '';
255 $this->mMetaData
= '';
257 $this->edittime
= '';
258 $this->starttime
= wfTimestampNow();
259 $this->preview
= false;
262 $this->minoredit
= false;
263 $this->watchthis
= false;
264 $this->recreate
= false;
267 $this->oldid
= $request->getInt( 'oldid' );
269 # Section edit can come from either the form or a link
270 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
272 $this->live
= $request->getCheck( 'live' );
276 * Make sure the form isn't faking a user's credentials.
278 * @param WebRequest $request
282 function tokenOk( &$request ) {
284 if( $wgUser->isAnon() ) {
285 # Anonymous users may not have a session
286 # open. Don't tokenize.
289 return $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
298 * The edit form is self-submitting, so that when things like
299 * preview and edit conflicts occur, we get the same form back
300 * with the extra stuff added. Only when the final submission
301 * is made and all is well do we actually save and redirect to
302 * the newly-edited page.
304 * @param string $formtype Type of form either : save, initial, diff or preview
305 * @param bool $firsttime True to load form data from db
307 function editForm( $formtype, $firsttime = false ) {
308 global $wgOut, $wgUser;
309 global $wgLang, $wgContLang, $wgParser, $wgTitle;
310 global $wgAllowAnonymousMinor, $wgRequest;
311 global $wgSpamRegex, $wgFilterCallback;
313 $sk = $wgUser->getSkin();
315 // css / js subpages of user pages get a special treatment
316 $isCssJsSubpage = $wgTitle->isCssJsSubpage();
319 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
320 * no matter it's current state
323 $confirmdelete = false;
324 if ( $this->edittime
!= '' ) {
325 /* Note that we rely on logging table, which hasn't been always there,
326 * but that doesn't matter, because this only applies to brand new
327 * deletes. This is done on every preview and save request. Move it further down
328 * to only perform it on saves
330 if ( $this->mTitle
->isDeleted() ) {
331 $query = $this->getLastDelete();
332 if ( !is_null($query) ) {
333 $deletetime = $query->log_timestamp
;
334 if ( ($deletetime - $this->starttime
) > 0 ) {
335 $confirmdelete = true;
343 if(!$this->mTitle
->getArticleID() && ('initial' == $formtype ||
$firsttime )) { # new article
344 $editintro = $wgRequest->getText( 'editintro' );
345 $addstandardintro=true;
347 $introtitle=Title
::newFromText($editintro);
348 if(isset($introtitle) && $introtitle->userCanRead()) {
349 $rev=Revision
::newFromTitle($introtitle);
351 $wgOut->addWikiText($rev->getText());
352 $addstandardintro=false;
356 if($addstandardintro) {
357 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
361 if( $this->mTitle
->isTalkPage() ) {
362 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
365 # Attempt submission here. This will check for edit conflicts,
366 # and redundantly check for locked database, blocked IPs, etc.
367 # that edit() already checked just in case someone tries to sneak
368 # in the back door with a hand-edited submission URL.
370 if ( 'save' == $formtype ) {
371 # Reintegrate metadata
372 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
373 $this->mMetaData
= '' ;
376 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
377 $this->spamPage ( $matches[0] );
380 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
381 # Error messages or other handling should be performed by the filter function
384 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
385 # Check block state against master, thus 'false'.
386 $this->blockedIPpage();
390 if ( !$wgUser->isAllowed('edit') ) {
391 if ( $wgUser->isAnon() ) {
392 $this->userNotLoggedInPage();
396 $wgOut->readOnlyPage();
401 if ( wfReadOnly() ) {
402 $wgOut->readOnlyPage();
405 if ( $wgUser->pingLimiter() ) {
406 $wgOut->rateLimited();
410 # If the article has been deleted while editing, don't save it without
412 if ( !$confirmdelete ||
$this->recreate
) {
415 # If article is new, insert it.
416 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
418 # Don't save a new article if it's blank.
419 if ( ( '' == $this->textbox1
) ||
420 ( wfMsg( 'newarticletext' ) == $this->textbox1
) ) {
421 $wgOut->redirect( $this->mTitle
->getFullURL() );
424 if (wfRunHooks('ArticleSave', array(&$this->mArticle
, &$wgUser, &$this->textbox1
,
425 &$this->summary
, &$this->minoredit
, &$this->watchthis
, NULL)))
428 $isComment=($this->section
=='new');
429 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
430 $this->minoredit
, $this->watchthis
, false, $isComment);
431 wfRunHooks('ArticleSaveComplete', array(&$this->mArticle
, &$wgUser, $this->textbox1
,
432 $this->summary
, $this->minoredit
,
433 $this->watchthis
, NULL));
438 # Article exists. Check for edit conflict.
440 $this->mArticle
->clear(); # Force reload of dates, etc.
441 $this->mArticle
->forUpdate( true ); # Lock the article
443 if( ( $this->section
!= 'new' ) &&
444 ($this->mArticle
->getTimestamp() != $this->edittime
) ) {
447 $userid = $wgUser->getID();
450 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
451 $this->mArticle
->getTimestamp() . "'\n" );
452 $text = $this->mArticle
->getTextOfLastEditWithSectionReplacedOrAdded(
453 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
456 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
457 $text = $this->mArticle
->getTextOfLastEditWithSectionReplacedOrAdded(
458 $this->section
, $this->textbox1
, $this->summary
);
460 # Suppress edit conflict with self
462 if ( ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
463 wfDebug( "Suppressing edit conflict, same user.\n" );
466 # switch from section editing to normal editing in edit conflict
469 if( $this->mergeChangesInto( $text ) ){
470 // Successful merge! Maybe we should tell the user the good news?
472 wfDebug( "Suppressing edit conflict, successful merge.\n" );
475 $this->textbox1
= $text;
476 wfDebug( "Keeping edit conflict, failed merge.\n" );
480 if ( ! $isConflict ) {
483 if( $this->section
== 'new' ) {
484 if( $this->summary
!= '' ) {
485 $sectionanchor = $this->sectionAnchor( $this->summary
);
487 } elseif( $this->section
!= '' ) {
488 # Try to get a section anchor from the section source, redirect to edited section if header found
489 # XXX: might be better to integrate this into Article::getTextOfLastEditWithSectionReplacedOrAdded
490 # for duplicate heading checking and maybe parsing
491 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
492 # we can't deal with anchors, includes, html etc in the header for now,
493 # headline would need to be parsed to improve this
494 #if($hasmatch and strlen($matches[2]) > 0 and !preg_match( "/[\\['{<>]/", $matches[2])) {
495 if($hasmatch and strlen($matches[2]) > 0) {
496 $sectionanchor = $this->sectionAnchor( $matches[2] );
500 // Save errors may fall down to the edit form, but we've now
501 // merged the section into full text. Clear the section field
502 // so that later submission of conflict forms won't try to
503 // replace that into a duplicated mess.
504 $this->textbox1
= $text;
507 if (wfRunHooks('ArticleSave', array(&$this->mArticle
, &$wgUser, &$text,
508 &$this->summary
, &$this->minoredit
,
509 &$this->watchthis
, &$sectionanchor)))
511 # update the article here
512 if($this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
513 $this->watchthis
, '', $sectionanchor ))
515 wfRunHooks('ArticleSaveComplete',
516 array(&$this->mArticle
, &$wgUser, $text,
517 $this->summary
, $this->minoredit
,
518 $this->watchthis
, $sectionanchor));
527 # First time through: get contents, set time for conflict
530 if ( 'initial' == $formtype ||
$firsttime ) {
531 $this->edittime
= $this->mArticle
->getTimestamp();
532 $this->textbox1
= $this->mArticle
->getContent( true );
536 $wgOut->setRobotpolicy( 'noindex,nofollow' );
538 # Enabled article-related sidebar, toplinks, etc.
539 $wgOut->setArticleRelated( true );
542 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
543 $wgOut->setPageTitle( $s );
544 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
546 $this->textbox2
= $this->textbox1
;
547 $this->textbox1
= $this->mArticle
->getContent( true );
548 $this->edittime
= $this->mArticle
->getTimestamp();
551 if( $this->section
!= '' ) {
552 if( $this->section
== 'new' ) {
553 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
555 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
556 if( !$this->preview
&& !$this->diff
) {
557 preg_match( "/^(=+)(.+)\\1/mi",
560 if( !empty( $matches[2] ) ) {
561 $this->summary
= "/* ". trim($matches[2])." */ ";
566 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
568 $wgOut->setPageTitle( $s );
569 if ( !$this->checkUnicodeCompliantBrowser() ) {
570 $this->mArticle
->setOldSubtitle();
571 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
573 if ( isset( $this->mArticle
)
574 && isset( $this->mArticle
->mRevision
)
575 && !$this->mArticle
->mRevision
->isCurrent() ) {
576 $this->mArticle
->setOldSubtitle();
577 $wgOut->addWikiText( wfMsg( 'editingold' ) );
582 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
583 } else if ( $isCssJsSubpage and 'preview' != $formtype) {
584 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
586 if( $this->mTitle
->isProtected('edit') ) {
587 $wgOut->addWikiText( wfMsg( 'protectedpagewarning' ) );
590 $kblength = (int)(strlen( $this->textbox1
) / 1024);
591 if( $kblength > 29 ) {
592 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
595 $rows = $wgUser->getOption( 'rows' );
596 $cols = $wgUser->getOption( 'cols' );
598 $ew = $wgUser->getOption( 'editwidth' );
599 if ( $ew ) $ew = " style=\"width:100%\"";
602 $q = 'action=submit';
603 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
604 $action = $this->mTitle
->escapeLocalURL( $q );
606 $summary = wfMsg('summary');
607 $subject = wfMsg('subject');
608 $minor = wfMsg('minoredit');
609 $watchthis = wfMsg ('watchthis');
610 $save = wfMsg('savearticle');
611 $prev = wfMsg('showpreview');
612 $diff = wfMsg('showdiff');
614 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
616 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
617 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
618 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
619 htmlspecialchars( wfMsg( 'newwindow' ) );
621 global $wgRightsText;
622 $copywarn = "<div id=\"editpage-copywarn\">\n" .
623 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
624 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
625 $wgRightsText ) . "\n</div>";
627 if( $wgUser->getOption('showtoolbar') and !$isCssJsSubpage ) {
628 # prepare toolbar for edit buttons
629 $toolbar = $this->getEditToolbar();
634 // activate checkboxes if user wants them to be always active
635 if( !$this->preview
&& !$this->diff
) {
636 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis
= true;
637 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
639 // activate checkbox also if user is already watching the page,
640 // require wpWatchthis to be unset so that second condition is not
641 // checked unnecessarily
642 if( !$this->watchthis
&& $this->mTitle
->userIsWatching() ) $this->watchthis
= true;
647 if ( $wgUser->isLoggedIn() ||
$wgAllowAnonymousMinor ) {
649 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?
" checked='checked'":"").
650 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
651 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
656 if ( $wgUser->isLoggedIn() ) {
657 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
658 ($this->watchthis?
" checked='checked'":"").
659 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
660 "<label for='wpWatchthis' title=\"" .
661 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
664 $checkboxhtml = $minoredithtml . $watchhtml . '<br />';
666 $wgOut->addHTML( '<div id="wikiPreview">' );
667 if ( 'preview' == $formtype) {
668 $previewOutput = $this->getPreviewText( $isConflict, $isCssJsSubpage );
669 if ( $wgUser->getOption('previewontop' ) ) {
670 $wgOut->addHTML( $previewOutput );
671 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
672 $this->mArticle
->closeShowCategory();
674 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
677 $wgOut->addHTML( '</div>' );
678 if ( 'diff' == $formtype ) {
679 if ( $wgUser->getOption('previewontop' ) ) {
680 $wgOut->addHTML( $this->getDiff() );
685 # if this is a comment, show a subject line at the top, which is also the edit summary.
686 # Otherwise, show a summary field at the bottom
687 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
688 if( $this->section
== 'new' ) {
689 $commentsubject="{$subject}: <input tabindex='1' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
692 $commentsubject = '';
693 $editsummary="{$summary}: <input tabindex='2' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
696 if( !$this->preview
&& !$this->diff
) {
697 # Don't select the edit box on preview; this interferes with seeing what's going on.
698 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
700 # Prepare a list of templates used by this page
702 $articleTemplates = $this->mArticle
->getUsedTemplates();
703 if ( count( $articleTemplates ) > 0 ) {
704 $templates = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
705 foreach ( $articleTemplates as $tpl ) {
706 if ( $titleObj = Title
::makeTitle( NS_TEMPLATE
, $tpl ) ) {
707 $templates .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
710 $templates .= '</ul>';
713 global $wgLivePreview, $wgStylePath;
715 * Live Preview lets us fetch rendered preview page content and
716 * add it to the page without refreshing the whole page.
717 * Set up the button for it; if not supported by the browser
718 * it will fall through to the normal form submission method.
720 if( $wgLivePreview ) {
721 global $wgJsMimeType;
722 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
723 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
724 '"></script>' . "\n" );
725 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
726 $liveOnclick = 'onclick="return !livePreview('.
727 'getElementById(\'wikiPreview\'),' .
728 'editform.wpTextbox1.value,' .
729 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
734 global $wgUseMetadataEdit ;
735 if ( $wgUseMetadataEdit ) {
736 $metadata = $this->mMetaData
;
737 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
738 $helppage = Title
::newFromText( wfMsg( "metadata_page" ) ) ;
739 $top = wfMsg( 'metadata', $helppage->getInternalURL() );
740 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
742 else $metadata = "" ;
746 if ($confirmdelete) {
747 if ( 'save' != $formtype ) {
748 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
750 // Hide the toolbar and edit area, use can click preview to get it back
751 // Add an confirmation checkbox and explanation.
753 $hidden = 'type="hidden" style="display:none;"';
754 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $query->user_name
, $query->log_comment
));
756 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
757 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
761 $safemodehtml = $this->checkUnicodeCompliantBrowser()
763 : "<input type='hidden' name=\"safemode\" value='1' />\n";
765 $wgOut->addHTML( <<<END
767 <form id="editform" name="editform" method="post" action="$action"
768 enctype="multipart/form-data">
771 <textarea tabindex='1' accesskey="," name="wpTextbox1" rows='{$rows}'
772 cols='{$cols}'{$ew} $hidden>
774 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
781 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
782 " title=\"".wfMsg('tooltip-save')."\"/>
783 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
784 " title=\"".wfMsg('tooltip-preview')."\"/>
785 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
786 " title=\"".wfMsg('tooltip-diff')."\"/>
787 <em>{$cancel}</em> | <em>{$edithelp}</em>{$templates}" );
788 $wgOut->addWikiText( $copywarn );
790 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
791 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
792 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
794 if ( $wgUser->isLoggedIn() ) {
796 * To make it harder for someone to slip a user a page
797 * which submits an edit form to the wiki without their
798 * knowledge, a random token is associated with the login
799 * session. If it's not passed back with the submission,
800 * we won't save the page, or render user JavaScript and
803 $token = htmlspecialchars( $wgUser->editToken() );
805 <input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
810 require_once( "DifferenceEngine.php" );
811 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
812 DifferenceEngine
::showDiff( $this->textbox2
, $this->textbox1
,
813 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
815 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
816 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
817 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) .
821 $wgOut->addHTML( "</form>\n" );
822 if ( $formtype == 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
823 $wgOut->addHTML( '<div id="wikiPreview">' . $previewOutput . '</div>' );
825 if ( $formtype == 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
826 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
827 $wgOut->addHTML( $this->getDiff() );
831 function getLastDelete() {
832 $dbr =& wfGetDB( DB_SLAVE
);
833 $fname = 'EditPage::getLastDelete';
835 array( 'logging', 'user' ),
845 array( 'log_namespace="' . $this->mTitle
->getNamespace() . '"',
846 'log_title="' . $this->mTitle
->getDBkey() . '"',
848 'log_action="delete"',
849 'user_id=log_user' ),
851 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
853 if($dbr->numRows($res) == 1) {
854 while ( $x = $dbr->fetchObject ( $res ) )
856 $dbr->freeResult ( $res ) ;
866 function getPreviewText( $isConflict, $isCssJsSubpage ) {
867 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
868 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
869 "<p class='previewnote'>" . htmlspecialchars( wfMsg( 'previewnote' ) ) . "</p>\n";
871 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) .
875 $parserOptions = ParserOptions
::newFromUser( $wgUser );
876 $parserOptions->setEditSection( false );
878 # don't parse user css/js, show message about preview
879 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
881 if ( $isCssJsSubpage ) {
882 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
883 $previewtext = wfMsg('usercsspreview');
884 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
885 $previewtext = wfMsg('userjspreview');
887 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
888 $wgOut->addHTML( $parserOutput->mText
);
891 # if user want to see preview when he edit an article
892 if( $wgUser->getOption('previewonfirst') and ($this->textbox1
== '')) {
893 $this->textbox1
= $this->mArticle
->getContent(true);
896 $toparse = $this->textbox1
;
898 # If we're adding a comment, we need to show the
899 # summary as the headline
900 if($this->section
=="new" && $this->summary
!="") {
901 $toparse="== {$this->summary} ==\n\n".$toparse;
904 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
906 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
907 $wgTitle, $parserOptions );
909 $previewHTML = $parserOutput->mText
;
911 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
912 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
913 return $previewhead . $previewHTML;
920 function blockedIPpage() {
921 global $wgOut, $wgUser, $wgContLang, $wgIP;
923 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
924 $wgOut->setRobotpolicy( 'noindex,nofollow' );
925 $wgOut->setArticleRelated( false );
927 $id = $wgUser->blockedBy();
928 $reason = $wgUser->blockedFor();
931 if ( is_numeric( $id ) ) {
932 $name = User
::whoIs( $id );
936 $link = '[[' . $wgContLang->getNsText( NS_USER
) .
937 ":{$name}|{$name}]]";
939 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
940 $wgOut->returnToMain( false );
946 function userNotLoggedInPage() {
949 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
950 $wgOut->setRobotpolicy( 'noindex,nofollow' );
951 $wgOut->setArticleRelated( false );
953 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
954 $wgOut->returnToMain( false );
960 function spamPage ( $match = false )
963 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
964 $wgOut->setRobotpolicy( 'noindex,nofollow' );
965 $wgOut->setArticleRelated( false );
967 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
969 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
971 $wgOut->returnToMain( false );
975 * Forks processes to scan the originating IP for an open proxy server
976 * MemCached can be used to skip IPs that have already been scanned
978 function proxyCheck() {
979 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
980 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
982 if ( !$wgBlockOpenProxies ) {
988 if ( $wgUseMemCached ) {
989 $mcKey = $wgDBname.':proxy:ip:'.$wgIP;
990 $mcValue = $wgMemc->get( $mcKey );
998 $title = Title
::makeTitle( NS_SPECIAL
, 'Blockme' );
999 $iphash = md5( $wgIP . $wgProxyKey );
1000 $url = $title->getFullURL( 'ip='.$iphash );
1002 foreach ( $wgProxyPorts as $port ) {
1003 $params = implode( ' ', array(
1004 escapeshellarg( $wgProxyScriptPath ),
1005 escapeshellarg( $wgIP ),
1006 escapeshellarg( $port ),
1007 escapeshellarg( $url )
1009 exec( "php $params &>/dev/null &" );
1012 if ( $wgUseMemCached ) {
1013 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
1022 function mergeChangesInto( &$editText ){
1023 $fname = 'EditPage::mergeChangesInto';
1024 wfProfileIn( $fname );
1026 $db =& wfGetDB( DB_MASTER
);
1028 // This is the revision the editor started from
1029 $baseRevision = Revision
::loadFromTimestamp(
1030 $db, $this->mArticle
->mTitle
, $this->edittime
);
1031 if( is_null( $baseRevision ) ) {
1032 wfProfileOut( $fname );
1035 $baseText = $baseRevision->getText();
1037 // The current state, we want to merge updates into it
1038 $currentRevision = Revision
::loadFromTitle(
1039 $db, $this->mArticle
->mTitle
);
1040 if( is_null( $currentRevision ) ) {
1041 wfProfileOut( $fname );
1044 $currentText = $currentRevision->getText();
1046 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1047 $editText = $result;
1048 wfProfileOut( $fname );
1051 wfProfileOut( $fname );
1057 function checkUnicodeCompliantBrowser() {
1058 global $wgBrowserBlackList;
1059 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1060 foreach ( $wgBrowserBlackList as $browser ) {
1061 if ( preg_match($browser, $currentbrowser) ) {
1069 * Format an anchor fragment as it would appear for a given section name
1070 * @param string $text
1074 function sectionAnchor( $text ) {
1075 $headline = Sanitizer
::decodeCharReferences( $text );
1077 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1078 $headline = trim( $headline );
1079 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1080 $replacearray = array(
1085 array_keys( $replacearray ),
1086 array_values( $replacearray ),
1091 * Shows a bulletin board style toolbar for common editing functions.
1092 * It can be disabled in the user preferences.
1093 * The necessary JavaScript code can be found in style/wikibits.js.
1095 function getEditToolbar() {
1096 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
1099 * toolarray an array of arrays which each include the filename of
1100 * the button image (without path), the opening tag, the closing tag,
1101 * and optionally a sample text that is inserted between the two when no
1102 * selection is highlighted.
1103 * The tip text is shown when the user moves the mouse over the button.
1105 * Already here are accesskeys (key), which are not used yet until someone
1106 * can figure out a way to make them work in IE. However, we should make
1107 * sure these keys are not defined on the edit page.
1110 array( 'image'=>'button_bold.png',
1112 'close' => "\'\'\'",
1113 'sample'=> wfMsg('bold_sample'),
1114 'tip' => wfMsg('bold_tip'),
1117 array( 'image'=>'button_italic.png',
1120 'sample'=> wfMsg('italic_sample'),
1121 'tip' => wfMsg('italic_tip'),
1124 array( 'image'=>'button_link.png',
1127 'sample'=> wfMsg('link_sample'),
1128 'tip' => wfMsg('link_tip'),
1131 array( 'image'=>'button_extlink.png',
1134 'sample'=> wfMsg('extlink_sample'),
1135 'tip' => wfMsg('extlink_tip'),
1138 array( 'image'=>'button_headline.png',
1140 'close' => " ==\\n",
1141 'sample'=> wfMsg('headline_sample'),
1142 'tip' => wfMsg('headline_tip'),
1145 array( 'image'=>'button_image.png',
1146 'open' => '[['.$wgLang->getNsText(NS_IMAGE
).":",
1148 'sample'=> wfMsg('image_sample'),
1149 'tip' => wfMsg('image_tip'),
1152 array( 'image' =>'button_media.png',
1153 'open' => '[['.$wgLang->getNsText(NS_MEDIA
).':',
1155 'sample'=> wfMsg('media_sample'),
1156 'tip' => wfMsg('media_tip'),
1159 array( 'image' =>'button_math.png',
1160 'open' => "\\<math\\>",
1161 'close' => "\\</math\\>",
1162 'sample'=> wfMsg('math_sample'),
1163 'tip' => wfMsg('math_tip'),
1166 array( 'image' =>'button_nowiki.png',
1167 'open' => "\\<nowiki\\>",
1168 'close' => "\\</nowiki\\>",
1169 'sample'=> wfMsg('nowiki_sample'),
1170 'tip' => wfMsg('nowiki_tip'),
1173 array( 'image' =>'button_sig.png',
1177 'tip' => wfMsg('sig_tip'),
1180 array( 'image' =>'button_hr.png',
1181 'open' => "\\n----\\n",
1184 'tip' => wfMsg('hr_tip'),
1188 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1190 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1191 foreach($toolarray as $tool) {
1193 $image=$wgStylePath.'/common/images/'.$tool['image'];
1194 $open=$tool['open'];
1195 $close=$tool['close'];
1196 $sample = wfEscapeJsString( $tool['sample'] );
1198 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1199 // Older browsers show a "speedtip" type message only for ALT.
1200 // Ideally these should be different, realistically they
1201 // probably don't need to be.
1202 $tip = wfEscapeJsString( $tool['tip'] );
1204 #$key = $tool["key"];
1206 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1209 $toolbar.="addInfobox('" . wfEscapeJsString( wfMsg( "infobox" ) ) .
1210 "','" . wfEscapeJsString( wfMsg( "infobox_alert" ) ) . "');\n";
1211 $toolbar.="document.writeln(\"</div>\");\n";
1213 $toolbar.="/*]]>*/\n</script>";
1218 * Output preview text only. This can be sucked into the edit page
1219 * via JavaScript, and saves the server time rendering the skin as
1220 * well as theoretically being more robust on the client (doesn't
1221 * disturb the edit box's undo history, won't eat your text on
1224 * @todo This doesn't include category or interlanguage links.
1225 * Would need to enhance it a bit, maybe wrap them in XML
1226 * or something... that might also require more skin
1227 * initialization, so check whether that's a problem.
1229 function livePreview() {
1232 header( 'Content-type: text/xml' );
1233 header( 'Cache-control: no-cache' );
1235 echo $this->getPreviewText( false, false );
1240 * Get a diff between the current contents of the edit box and the
1241 * version of the page we're editing from.
1243 * If this is a section edit, we'll replace the section as for final
1244 * save and then make a comparison.
1246 * @return string HTML
1248 function getDiff() {
1249 require_once( 'DifferenceEngine.php' );
1250 $oldtext = $this->mArticle
->fetchContent();
1251 $newtext = $this->mArticle
->getTextOfLastEditWithSectionReplacedOrAdded(
1252 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1253 $oldtitle = wfMsg( 'currentrev' );
1254 $newtitle = wfMsg( 'yourtext' );
1255 if ( $oldtext != wfMsg( 'noarticletext' ) ||
$newtext != '' ) {
1256 $difftext = DifferenceEngine
::getDiff( $oldtext, $newtext, $oldtitle, $newtitle );
1259 return '<div id="wikiDiff">' . $difftext . '</div>';
1263 * Filter an input field through a Unicode de-armoring process if it
1264 * came from an old browser with known broken Unicode editing issues.
1266 * @param WebRequest $request
1267 * @param string $field
1271 function safeUnicodeInput( $request, $field ) {
1272 $text = rtrim( $request->getText( $field ) );
1273 return $request->getBool( 'safemode' )
1274 ?
$this->unmakesafe( $text )
1279 * Filter an output field through a Unicode armoring process if it is
1280 * going to an old browser with known broken Unicode editing issues.
1282 * @param string $text
1286 function safeUnicodeOutput( $text ) {
1288 $codedText = $wgContLang->recodeForEdit( $text );
1289 return $this->checkUnicodeCompliantBrowser()
1291 : $this->makesafe( $codedText );
1295 * A number of web browsers are known to corrupt non-ASCII characters
1296 * in a UTF-8 text editing environment. To protect against this,
1297 * detected browsers will be served an armored version of the text,
1298 * with non-ASCII chars converted to numeric HTML character references.
1300 * Preexisting such character references will have a 0 added to them
1301 * to ensure that round-trips do not alter the original data.
1303 * @param string $invalue
1307 function makesafe( $invalue ) {
1308 // Armor existing references for reversability.
1309 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1314 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1315 $bytevalue = ord( $invalue{$i} );
1316 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1317 $result .= chr( $bytevalue );
1319 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1320 $working = $working << 6;
1321 $working +
= ($bytevalue & 0x3F);
1323 if( $bytesleft <= 0 ) {
1324 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1326 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1327 $working = $bytevalue & 0x1F;
1329 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1330 $working = $bytevalue & 0x0F;
1332 } else { //1111 0xxx
1333 $working = $bytevalue & 0x07;
1341 * Reverse the previously applied transliteration of non-ASCII characters
1342 * back to UTF-8. Used to protect data from corruption by broken web browsers
1343 * as listed in $wgBrowserBlackList.
1345 * @param string $invalue
1349 function unmakesafe( $invalue ) {
1351 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1352 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
1356 $hexstring .= $invalue{$i};
1358 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1360 // Do some sanity checks. These aren't needed for reversability,
1361 // but should help keep the breakage down if the editor
1362 // breaks one of the entities whilst editing.
1363 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1364 $codepoint = hexdec($hexstring);
1365 $result .= codepointToUtf8( $codepoint );
1367 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1370 $result .= substr( $invalue, $i, 1 );
1373 // reverse the transform that we made for reversability reasons.
1374 return strtr( $result, array( "�" => "&#x" ) );