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 wfdebug("CONFLICT: edittime=".$this->edittime
." article timestamp=".$this->mArticle
->getTimestamp()."\n");
444 if( ( $this->section
!= 'new' ) &&
445 ($this->mArticle
->getTimestamp() != $this->edittime
) ) {
448 $userid = $wgUser->getID();
451 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
452 $this->mArticle
->getTimestamp() . "'\n" );
453 $text = $this->mArticle
->getTextOfLastEditWithSectionReplacedOrAdded(
454 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
457 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
458 $text = $this->mArticle
->getTextOfLastEditWithSectionReplacedOrAdded(
459 $this->section
, $this->textbox1
, $this->summary
);
461 # Suppress edit conflict with self
463 if ( ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
464 wfDebug( "Suppressing edit conflict, same user.\n" );
467 # switch from section editing to normal editing in edit conflict
470 if( $this->mergeChangesInto( $text ) ){
471 // Successful merge! Maybe we should tell the user the good news?
473 wfDebug( "Suppressing edit conflict, successful merge.\n" );
476 $this->textbox1
= $text;
477 wfDebug( "Keeping edit conflict, failed merge.\n" );
481 if ( ! $isConflict ) {
484 if( $this->section
== 'new' ) {
485 if( $this->summary
!= '' ) {
486 $sectionanchor = $this->sectionAnchor( $this->summary
);
488 } elseif( $this->section
!= '' ) {
489 # Try to get a section anchor from the section source, redirect to edited section if header found
490 # XXX: might be better to integrate this into Article::getTextOfLastEditWithSectionReplacedOrAdded
491 # for duplicate heading checking and maybe parsing
492 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
493 # we can't deal with anchors, includes, html etc in the header for now,
494 # headline would need to be parsed to improve this
495 #if($hasmatch and strlen($matches[2]) > 0 and !preg_match( "/[\\['{<>]/", $matches[2])) {
496 if($hasmatch and strlen($matches[2]) > 0) {
497 $sectionanchor = $this->sectionAnchor( $matches[2] );
501 // Save errors may fall down to the edit form, but we've now
502 // merged the section into full text. Clear the section field
503 // so that later submission of conflict forms won't try to
504 // replace that into a duplicated mess.
505 $this->textbox1
= $text;
508 if (wfRunHooks('ArticleSave', array(&$this->mArticle
, &$wgUser, &$text,
509 &$this->summary
, &$this->minoredit
,
510 &$this->watchthis
, &$sectionanchor)))
512 # update the article here
513 if($this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
514 $this->watchthis
, '', $sectionanchor ))
516 wfRunHooks('ArticleSaveComplete',
517 array(&$this->mArticle
, &$wgUser, $text,
518 $this->summary
, $this->minoredit
,
519 $this->watchthis
, $sectionanchor));
528 # First time through: get contents, set time for conflict
531 if ( 'initial' == $formtype ||
$firsttime ) {
532 $this->edittime
= $this->mArticle
->getTimestamp();
533 $this->textbox1
= $this->mArticle
->getContent( true );
537 $wgOut->setRobotpolicy( 'noindex,nofollow' );
539 # Enabled article-related sidebar, toplinks, etc.
540 $wgOut->setArticleRelated( true );
543 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
544 $wgOut->setPageTitle( $s );
545 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
547 $this->textbox2
= $this->textbox1
;
548 $this->textbox1
= $this->mArticle
->getContent( true );
549 $this->edittime
= $this->mArticle
->getTimestamp();
552 if( $this->section
!= '' ) {
553 if( $this->section
== 'new' ) {
554 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
556 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
557 if( !$this->preview
&& !$this->diff
) {
558 preg_match( "/^(=+)(.+)\\1/mi",
561 if( !empty( $matches[2] ) ) {
562 $this->summary
= "/* ". trim($matches[2])." */ ";
567 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
569 $wgOut->setPageTitle( $s );
570 if ( !$this->checkUnicodeCompliantBrowser() ) {
571 $this->mArticle
->setOldSubtitle();
572 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
574 if ( isset( $this->mArticle
)
575 && isset( $this->mArticle
->mRevision
)
576 && !$this->mArticle
->mRevision
->isCurrent() ) {
577 $this->mArticle
->setOldSubtitle();
578 $wgOut->addWikiText( wfMsg( 'editingold' ) );
583 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
584 } else if ( $isCssJsSubpage and 'preview' != $formtype) {
585 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
587 if( $this->mTitle
->isProtected('edit') ) {
588 $wgOut->addWikiText( wfMsg( 'protectedpagewarning' ) );
591 $kblength = (int)(strlen( $this->textbox1
) / 1024);
592 if( $kblength > 29 ) {
593 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
596 $rows = $wgUser->getOption( 'rows' );
597 $cols = $wgUser->getOption( 'cols' );
599 $ew = $wgUser->getOption( 'editwidth' );
600 if ( $ew ) $ew = " style=\"width:100%\"";
603 $q = 'action=submit';
604 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
605 $action = $this->mTitle
->escapeLocalURL( $q );
607 $summary = wfMsg('summary');
608 $subject = wfMsg('subject');
609 $minor = wfMsg('minoredit');
610 $watchthis = wfMsg ('watchthis');
611 $save = wfMsg('savearticle');
612 $prev = wfMsg('showpreview');
613 $diff = wfMsg('showdiff');
615 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
617 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
618 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
619 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
620 htmlspecialchars( wfMsg( 'newwindow' ) );
622 global $wgRightsText;
623 $copywarn = "<div id=\"editpage-copywarn\">\n" .
624 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
625 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
626 $wgRightsText ) . "\n</div>";
628 if( $wgUser->getOption('showtoolbar') and !$isCssJsSubpage ) {
629 # prepare toolbar for edit buttons
630 $toolbar = $this->getEditToolbar();
635 // activate checkboxes if user wants them to be always active
636 if( !$this->preview
&& !$this->diff
) {
637 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis
= true;
638 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
640 // activate checkbox also if user is already watching the page,
641 // require wpWatchthis to be unset so that second condition is not
642 // checked unnecessarily
643 if( !$this->watchthis
&& $this->mTitle
->userIsWatching() ) $this->watchthis
= true;
648 if ( $wgUser->isLoggedIn() ||
$wgAllowAnonymousMinor ) {
650 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?
" checked='checked'":"").
651 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
652 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
657 if ( $wgUser->isLoggedIn() ) {
658 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
659 ($this->watchthis?
" checked='checked'":"").
660 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
661 "<label for='wpWatchthis' title=\"" .
662 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
665 $checkboxhtml = $minoredithtml . $watchhtml . '<br />';
667 $wgOut->addHTML( '<div id="wikiPreview">' );
668 if ( 'preview' == $formtype) {
669 $previewOutput = $this->getPreviewText( $isConflict, $isCssJsSubpage );
670 if ( $wgUser->getOption('previewontop' ) ) {
671 $wgOut->addHTML( $previewOutput );
672 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
673 $this->mArticle
->closeShowCategory();
675 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
678 $wgOut->addHTML( '</div>' );
679 if ( 'diff' == $formtype ) {
680 if ( $wgUser->getOption('previewontop' ) ) {
681 $wgOut->addHTML( $this->getDiff() );
686 # if this is a comment, show a subject line at the top, which is also the edit summary.
687 # Otherwise, show a summary field at the bottom
688 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
689 if( $this->section
== 'new' ) {
690 $commentsubject="{$subject}: <input tabindex='1' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
693 $commentsubject = '';
694 $editsummary="{$summary}: <input tabindex='2' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
697 if( !$this->preview
&& !$this->diff
) {
698 # Don't select the edit box on preview; this interferes with seeing what's going on.
699 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
701 # Prepare a list of templates used by this page
703 $articleTemplates = $this->mArticle
->getUsedTemplates();
704 if ( count( $articleTemplates ) > 0 ) {
705 $templates = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
706 foreach ( $articleTemplates as $tpl ) {
707 if ( $titleObj = Title
::makeTitle( NS_TEMPLATE
, $tpl ) ) {
708 $templates .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
711 $templates .= '</ul>';
714 global $wgLivePreview, $wgStylePath;
716 * Live Preview lets us fetch rendered preview page content and
717 * add it to the page without refreshing the whole page.
718 * Set up the button for it; if not supported by the browser
719 * it will fall through to the normal form submission method.
721 if( $wgLivePreview ) {
722 global $wgJsMimeType;
723 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
724 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
725 '"></script>' . "\n" );
726 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
727 $liveOnclick = 'onclick="return !livePreview('.
728 'getElementById(\'wikiPreview\'),' .
729 'editform.wpTextbox1.value,' .
730 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
735 global $wgUseMetadataEdit ;
736 if ( $wgUseMetadataEdit )
738 $metadata = $this->mMetaData
;
739 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
740 $helppage = Title
::newFromText ( wfmsg("metadata_page") ) ;
741 $top = str_replace ( "$1" , $helppage->getInternalURL() , wfmsg("metadata") ) ;
742 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
744 else $metadata = "" ;
748 if ($confirmdelete) {
749 if ( 'save' != $formtype ) {
750 $wgOut->addWikiText( wfMsg('bw_deletedwhileediting'));
752 // Hide the toolbar and edit area, use can click preview to get it back
753 // Add an confirmation checkbox and explanation.
755 $hidden = 'type="hidden" style="display:none;"';
756 $recreate = $wgOut->parse( wfMsg( 'bw_confirmrecreate', $query->user_name
, $query->log_comment
));
758 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
759 "<label for='wpRecreate' title='".wfMsg('bw_tooltip-recreate')."'>". wfMsg('bw_recreate')."</label>";
763 $safemodehtml = $this->checkUnicodeCompliantBrowser()
765 : "<input type='hidden' name=\"safemode\" value='1' />\n";
767 $wgOut->addHTML( <<<END
769 <form id="editform" name="editform" method="post" action="$action"
770 enctype="multipart/form-data">
773 <textarea tabindex='1' accesskey="," name="wpTextbox1" rows='{$rows}'
774 cols='{$cols}'{$ew} $hidden>
776 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
783 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
784 " title=\"".wfMsg('tooltip-save')."\"/>
785 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
786 " title=\"".wfMsg('tooltip-preview')."\"/>
787 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
788 " title=\"".wfMsg('tooltip-diff')."\"/>
789 <em>{$cancel}</em> | <em>{$edithelp}</em>{$templates}" );
790 $wgOut->addWikiText( $copywarn );
792 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
793 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
794 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
796 if ( $wgUser->isLoggedIn() ) {
798 * To make it harder for someone to slip a user a page
799 * which submits an edit form to the wiki without their
800 * knowledge, a random token is associated with the login
801 * session. If it's not passed back with the submission,
802 * we won't save the page, or render user JavaScript and
805 $token = htmlspecialchars( $wgUser->editToken() );
807 <input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
812 require_once( "DifferenceEngine.php" );
813 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
814 DifferenceEngine
::showDiff( $this->textbox2
, $this->textbox1
,
815 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
817 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
818 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
819 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) .
823 $wgOut->addHTML( "</form>\n" );
824 if ( $formtype == 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
825 $wgOut->addHTML( '<div id="wikiPreview">' . $previewOutput . '</div>' );
827 if ( $formtype == 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
828 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
829 $wgOut->addHTML( $this->getDiff() );
833 function getLastDelete() {
834 $dbr =& wfGetDB( DB_SLAVE
);
837 array( 'logging', 'user' ),
847 array( 'log_namespace="' . $this->mTitle
->getNamespace() . '"',
848 'log_title="' . $this->mTitle
->getDBkey() . '"',
850 'log_action="delete"',
851 'user_id=log_user' ),
852 'EditPage::getLastDelete',
853 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
855 if($dbr->numRows($res) == 1) {
856 while ( $x = $dbr->fetchObject ( $res ) )
858 $dbr->freeResult ( $res ) ;
868 function getPreviewText( $isConflict, $isCssJsSubpage ) {
869 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
870 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
871 "<p class='previewnote'>" . htmlspecialchars( wfMsg( 'previewnote' ) ) . "</p>\n";
873 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) .
877 $parserOptions = ParserOptions
::newFromUser( $wgUser );
878 $parserOptions->setEditSection( false );
880 # don't parse user css/js, show message about preview
881 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
883 if ( $isCssJsSubpage ) {
884 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
885 $previewtext = wfMsg('usercsspreview');
886 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
887 $previewtext = wfMsg('userjspreview');
889 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
890 $wgOut->addHTML( $parserOutput->mText
);
893 # if user want to see preview when he edit an article
894 if( $wgUser->getOption('previewonfirst') and ($this->textbox1
== '')) {
895 $this->textbox1
= $this->mArticle
->getContent(true);
898 $toparse = $this->textbox1
;
900 # If we're adding a comment, we need to show the
901 # summary as the headline
902 if($this->section
=="new" && $this->summary
!="") {
903 $toparse="== {$this->summary} ==\n\n".$toparse;
906 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
908 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
909 $wgTitle, $parserOptions );
911 $previewHTML = $parserOutput->mText
;
913 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
914 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
915 return $previewhead . $previewHTML;
922 function blockedIPpage() {
923 global $wgOut, $wgUser, $wgContLang, $wgIP;
925 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
926 $wgOut->setRobotpolicy( 'noindex,nofollow' );
927 $wgOut->setArticleRelated( false );
929 $id = $wgUser->blockedBy();
930 $reason = $wgUser->blockedFor();
933 if ( is_numeric( $id ) ) {
934 $name = User
::whoIs( $id );
938 $link = '[[' . $wgContLang->getNsText( NS_USER
) .
939 ":{$name}|{$name}]]";
941 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
942 $wgOut->returnToMain( false );
948 function userNotLoggedInPage() {
951 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
952 $wgOut->setRobotpolicy( 'noindex,nofollow' );
953 $wgOut->setArticleRelated( false );
955 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
956 $wgOut->returnToMain( false );
962 function spamPage ( $match = false )
965 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
966 $wgOut->setRobotpolicy( 'noindex,nofollow' );
967 $wgOut->setArticleRelated( false );
969 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
971 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
973 $wgOut->returnToMain( false );
977 * Forks processes to scan the originating IP for an open proxy server
978 * MemCached can be used to skip IPs that have already been scanned
980 function proxyCheck() {
981 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
982 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
984 if ( !$wgBlockOpenProxies ) {
990 if ( $wgUseMemCached ) {
991 $mcKey = $wgDBname.':proxy:ip:'.$wgIP;
992 $mcValue = $wgMemc->get( $mcKey );
1000 $title = Title
::makeTitle( NS_SPECIAL
, 'Blockme' );
1001 $iphash = md5( $wgIP . $wgProxyKey );
1002 $url = $title->getFullURL( 'ip='.$iphash );
1004 foreach ( $wgProxyPorts as $port ) {
1005 $params = implode( ' ', array(
1006 escapeshellarg( $wgProxyScriptPath ),
1007 escapeshellarg( $wgIP ),
1008 escapeshellarg( $port ),
1009 escapeshellarg( $url )
1011 exec( "php $params &>/dev/null &" );
1014 if ( $wgUseMemCached ) {
1015 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
1024 function mergeChangesInto( &$editText ){
1025 $fname = 'EditPage::mergeChangesInto';
1026 wfProfileIn( $fname );
1028 $db =& wfGetDB( DB_MASTER
);
1030 // This is the revision the editor started from
1031 $baseRevision = Revision
::loadFromTimestamp(
1032 $db, $this->mArticle
->mTitle
, $this->edittime
);
1033 if( is_null( $baseRevision ) ) {
1034 wfProfileOut( $fname );
1037 $baseText = $baseRevision->getText();
1039 // The current state, we want to merge updates into it
1040 $currentRevision = Revision
::loadFromTitle(
1041 $db, $this->mArticle
->mTitle
);
1042 if( is_null( $currentRevision ) ) {
1043 wfProfileOut( $fname );
1046 $currentText = $currentRevision->getText();
1048 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1049 $editText = $result;
1050 wfProfileOut( $fname );
1053 wfProfileOut( $fname );
1059 function checkUnicodeCompliantBrowser() {
1060 global $wgBrowserBlackList;
1061 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1062 foreach ( $wgBrowserBlackList as $browser ) {
1063 if ( preg_match($browser, $currentbrowser) ) {
1071 * Format an anchor fragment as it would appear for a given section name
1072 * @param string $text
1076 function sectionAnchor( $text ) {
1077 $headline = Sanitizer
::decodeCharReferences( $text );
1079 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1080 $headline = trim( $headline );
1081 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1082 $replacearray = array(
1087 array_keys( $replacearray ),
1088 array_values( $replacearray ),
1093 * Shows a bulletin board style toolbar for common editing functions.
1094 * It can be disabled in the user preferences.
1095 * The necessary JavaScript code can be found in style/wikibits.js.
1097 function getEditToolbar() {
1098 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
1101 * toolarray an array of arrays which each include the filename of
1102 * the button image (without path), the opening tag, the closing tag,
1103 * and optionally a sample text that is inserted between the two when no
1104 * selection is highlighted.
1105 * The tip text is shown when the user moves the mouse over the button.
1107 * Already here are accesskeys (key), which are not used yet until someone
1108 * can figure out a way to make them work in IE. However, we should make
1109 * sure these keys are not defined on the edit page.
1112 array( 'image'=>'button_bold.png',
1114 'close' => "\'\'\'",
1115 'sample'=> wfMsg('bold_sample'),
1116 'tip' => wfMsg('bold_tip'),
1119 array( 'image'=>'button_italic.png',
1122 'sample'=> wfMsg('italic_sample'),
1123 'tip' => wfMsg('italic_tip'),
1126 array( 'image'=>'button_link.png',
1129 'sample'=> wfMsg('link_sample'),
1130 'tip' => wfMsg('link_tip'),
1133 array( 'image'=>'button_extlink.png',
1136 'sample'=> wfMsg('extlink_sample'),
1137 'tip' => wfMsg('extlink_tip'),
1140 array( 'image'=>'button_headline.png',
1142 'close' => " ==\\n",
1143 'sample'=> wfMsg('headline_sample'),
1144 'tip' => wfMsg('headline_tip'),
1147 array( 'image'=>'button_image.png',
1148 'open' => '[['.$wgLang->getNsText(NS_IMAGE
).":",
1150 'sample'=> wfMsg('image_sample'),
1151 'tip' => wfMsg('image_tip'),
1154 array( 'image' =>'button_media.png',
1155 'open' => '[['.$wgLang->getNsText(NS_MEDIA
).':',
1157 'sample'=> wfMsg('media_sample'),
1158 'tip' => wfMsg('media_tip'),
1161 array( 'image' =>'button_math.png',
1162 'open' => "\\<math\\>",
1163 'close' => "\\</math\\>",
1164 'sample'=> wfMsg('math_sample'),
1165 'tip' => wfMsg('math_tip'),
1168 array( 'image' =>'button_nowiki.png',
1169 'open' => "\\<nowiki\\>",
1170 'close' => "\\</nowiki\\>",
1171 'sample'=> wfMsg('nowiki_sample'),
1172 'tip' => wfMsg('nowiki_tip'),
1175 array( 'image' =>'button_sig.png',
1179 'tip' => wfMsg('sig_tip'),
1182 array( 'image' =>'button_hr.png',
1183 'open' => "\\n----\\n",
1186 'tip' => wfMsg('hr_tip'),
1190 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1192 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1193 foreach($toolarray as $tool) {
1195 $image=$wgStylePath.'/common/images/'.$tool['image'];
1196 $open=$tool['open'];
1197 $close=$tool['close'];
1198 $sample = wfEscapeJsString( $tool['sample'] );
1200 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1201 // Older browsers show a "speedtip" type message only for ALT.
1202 // Ideally these should be different, realistically they
1203 // probably don't need to be.
1204 $tip = wfEscapeJsString( $tool['tip'] );
1206 #$key = $tool["key"];
1208 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1211 $toolbar.="addInfobox('" . wfEscapeJsString( wfMsg( "infobox" ) ) .
1212 "','" . wfEscapeJsString( wfMsg( "infobox_alert" ) ) . "');\n";
1213 $toolbar.="document.writeln(\"</div>\");\n";
1215 $toolbar.="/*]]>*/\n</script>";
1220 * Output preview text only. This can be sucked into the edit page
1221 * via JavaScript, and saves the server time rendering the skin as
1222 * well as theoretically being more robust on the client (doesn't
1223 * disturb the edit box's undo history, won't eat your text on
1226 * @todo This doesn't include category or interlanguage links.
1227 * Would need to enhance it a bit, maybe wrap them in XML
1228 * or something... that might also require more skin
1229 * initialization, so check whether that's a problem.
1231 function livePreview() {
1234 header( 'Content-type: text/xml' );
1235 header( 'Cache-control: no-cache' );
1237 echo $this->getPreviewText( false, false );
1242 * Get a diff between the current contents of the edit box and the
1243 * version of the page we're editing from.
1245 * If this is a section edit, we'll replace the section as for final
1246 * save and then make a comparison.
1248 * @return string HTML
1250 function getDiff() {
1251 require_once( 'DifferenceEngine.php' );
1252 $oldtext = $this->mArticle
->fetchContent();
1253 $newtext = $this->mArticle
->getTextOfLastEditWithSectionReplacedOrAdded(
1254 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1255 $oldtitle = wfMsg( 'currentrev' );
1256 $newtitle = wfMsg( 'yourtext' );
1257 if ( $oldtext != wfMsg( 'noarticletext' ) ||
$newtext != '' ) {
1258 $difftext = DifferenceEngine
::getDiff( $oldtext, $newtext, $oldtitle, $newtitle );
1261 return '<div id="wikiDiff">' . $difftext . '</div>';
1265 * Filter an input field through a Unicode de-armoring process if it
1266 * came from an old browser with known broken Unicode editing issues.
1268 * @param WebRequest $request
1269 * @param string $field
1273 function safeUnicodeInput( $request, $field ) {
1274 $text = rtrim( $request->getText( $field ) );
1275 return $request->getBool( 'safemode' )
1276 ?
$this->unmakesafe( $text )
1281 * Filter an output field through a Unicode armoring process if it is
1282 * going to an old browser with known broken Unicode editing issues.
1284 * @param string $text
1288 function safeUnicodeOutput( $text ) {
1290 $codedText = $wgContLang->recodeForEdit( $text );
1291 return $this->checkUnicodeCompliantBrowser()
1293 : $this->makesafe( $codedText );
1297 * A number of web browsers are known to corrupt non-ASCII characters
1298 * in a UTF-8 text editing environment. To protect against this,
1299 * detected browsers will be served an armored version of the text,
1300 * with non-ASCII chars converted to numeric HTML character references.
1302 * Preexisting such character references will have a 0 added to them
1303 * to ensure that round-trips do not alter the original data.
1305 * @param string $invalue
1309 function makesafe( $invalue ) {
1310 // Armor existing references for reversability.
1311 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1316 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1317 $bytevalue = ord( $invalue{$i} );
1318 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1319 $result .= chr( $bytevalue );
1321 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1322 $working = $working << 6;
1323 $working +
= ($bytevalue & 0x3F);
1325 if( $bytesleft <= 0 ) {
1326 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1328 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1329 $working = $bytevalue & 0x1F;
1331 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1332 $working = $bytevalue & 0x0F;
1334 } else { //1111 0xxx
1335 $working = $bytevalue & 0x07;
1343 * Reverse the previously applied transliteration of non-ASCII characters
1344 * back to UTF-8. Used to protect data from corruption by broken web browsers
1345 * as listed in $wgBrowserBlackList.
1347 * @param string $invalue
1351 function unmakesafe( $invalue ) {
1353 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1354 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
1358 $hexstring .= $invalue{$i};
1360 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1362 // Do some sanity checks. These aren't needed for reversability,
1363 // but should help keep the breakage down if the editor
1364 // breaks one of the entities whilst editing.
1365 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1366 $codepoint = hexdec($hexstring);
1367 $result .= codepointToUtf8( $codepoint );
1369 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1372 $result .= substr( $invalue, $i, 1 );
1375 // reverse the transform that we made for reversability reasons.
1376 return strtr( $result, array( "�" => "&#x" ) );