* upgrade1_5.php uses insert ignore, allows to skip image info initialization
[mediawiki.git] / includes / EditPage.php
blob1291a4c59ea68f2bdcadb4e0a412a4f9d30e0e51
1 <?php
2 /**
3 * Contain the EditPage class
4 * @package MediaWiki
5 */
7 /**
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
11 * interfaces.
13 * @package MediaWiki
16 class EditPage {
17 var $mArticle;
18 var $mTitle;
19 var $mMetaData = '';
21 # Form values
22 var $save = false, $preview = false, $diff = false;
23 var $minoredit = false, $watchthis = false;
24 var $textbox1 = '', $textbox2 = '', $summary = '';
25 var $edittime = '', $section = '';
26 var $oldid = 0;
28 /**
29 * @todo document
30 * @param $article
32 function EditPage( $article ) {
33 $this->mArticle =& $article;
34 global $wgTitle;
35 $this->mTitle =& $wgTitle;
38 /**
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 ;
48 $s = '' ;
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 ;
71 else $ll[] = $add ;
72 $x = implode ( ']]' , $y ) ;
73 $t[$key] = $x ;
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 ) ;
82 # Load whitelist
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) ) ;
87 foreach ( $wl AS $x )
89 $isentry = false ;
90 $x = trim ( $x ) ;
91 while ( substr ( $x , 0 , 1 ) == '*' )
93 $isentry = true ;
94 $x = trim ( substr ( $x , 1 ) ) ;
96 if ( $isentry )
98 $sat[] = strtolower ( $x ) ;
103 # Templates, but only some
104 $t = explode ( '{{' , $t ) ;
105 $tl = array () ;
106 foreach ( $t AS $key => $x )
108 $y = explode ( '}}' , $x , 2 ) ;
109 if ( count ( $y ) == 2 )
111 $z = $y[0] ;
112 $z = explode ( '|' , $z ) ;
113 $tn = array_shift ( $z ) ;
114 if ( in_array ( strtolower ( $tn ) , $sat ) )
116 $tl[] = '{{' . $y[0] . '}}' ;
117 $t[$key] = $y[1] ;
118 $y = explode ( '}}' , $y[1] , 2 ) ;
120 else $t[$key] = '{{' . $x ;
122 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
123 else $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".
136 function edit() {
137 global $wgOut, $wgUser, $wgRequest;
138 // this is not an article
139 $wgOut->setArticleFlag(false);
141 $this->importFormData( $wgRequest );
143 if( $this->live ) {
144 $this->livePreview();
145 return;
148 if ( ! $this->mTitle->userCanEdit() ) {
149 $wgOut->readOnlyPage( $this->mArticle->getContent( true ), true );
150 return;
152 if ( !$this->preview && !$this->diff && $wgUser->isBlocked( !$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();
156 return;
158 if ( !$wgUser->isAllowed('edit') ) {
159 if ( $wgUser->isAnon() ) {
160 $this->userNotLoggedInPage();
161 return;
162 } else {
163 $wgOut->readOnlyPage( $this->mArticle->getContent( true ), true );
164 return;
167 if ( wfReadOnly() ) {
168 if( $this->save || $this->preview ) {
169 $this->editForm( 'preview' );
170 } else if ( $this->diff ) {
171 $this->editForm( 'diff' );
172 } else {
173 $wgOut->readOnlyPage( $this->mArticle->getContent( true ) );
175 return;
177 if ( $this->save ) {
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( $wgUser->getOption('previewonfirst')
185 or $this->mTitle->getNamespace() == NS_CATEGORY ) {
186 $this->editForm( 'preview', true );
187 } else {
188 $this->extractMetaDataFromArticle () ;
189 $this->editForm( 'initial', true );
195 * @todo document
197 function importFormData( &$request ) {
198 if( $request->wasPosted() ) {
199 # These fields need to be checked for encoding.
200 # Also remove trailing whitespace, but don't remove _initial_
201 # whitespace from the text boxes. This may be significant formatting.
202 $this->textbox1 = rtrim( $request->getText( 'wpTextbox1' ) );
203 $this->textbox2 = rtrim( $request->getText( 'wpTextbox2' ) );
204 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
205 $this->summary = $request->getText( 'wpSummary' );
207 $this->edittime = $request->getVal( 'wpEdittime' );
208 if( is_null( $this->edittime ) ) {
209 # If the form is incomplete, force to preview.
210 $this->preview = true;
211 } else {
212 if( $this->tokenOk( $request ) ) {
213 # Some browsers will not report any submit button
214 # if the user hits enter in the comment box.
215 # The unmarked state will be assumed to be a save,
216 # if the form seems otherwise complete.
217 $this->preview = $request->getCheck( 'wpPreview' );
218 $this->diff = $request->getCheck( 'wpDiff' );
219 } else {
220 # Page might be a hack attempt posted from
221 # an external site. Preview instead of saving.
222 $this->preview = true;
225 $this->save = ! ( $this->preview OR $this->diff );
226 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
227 $this->edittime = null;
230 $this->minoredit = $request->getCheck( 'wpMinoredit' );
231 $this->watchthis = $request->getCheck( 'wpWatchthis' );
232 } else {
233 # Not a posted form? Start with nothing.
234 $this->textbox1 = '';
235 $this->textbox2 = '';
236 $this->mMetaData = '';
237 $this->summary = '';
238 $this->edittime = '';
239 $this->preview = false;
240 $this->save = false;
241 $this->diff = false;
242 $this->minoredit = false;
243 $this->watchthis = false;
246 $this->oldid = $request->getInt( 'oldid' );
248 # Section edit can come from either the form or a link
249 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
251 $this->live = $request->getCheck( 'live' );
255 * Make sure the form isn't faking a user's credentials.
257 * @param WebRequest $request
258 * @return bool
259 * @access private
261 function tokenOk( &$request ) {
262 global $wgUser;
263 if( $wgUser->isAnon() ) {
264 # Anonymous users may not have a session
265 # open. Don't tokenize.
266 return true;
267 } else {
268 return $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
272 function submit() {
273 $this->edit();
277 * The edit form is self-submitting, so that when things like
278 * preview and edit conflicts occur, we get the same form back
279 * with the extra stuff added. Only when the final submission
280 * is made and all is well do we actually save and redirect to
281 * the newly-edited page.
283 * @param string $formtype Type of form either : save, initial, diff or preview
284 * @param bool $firsttime True to load form data from db
286 function editForm( $formtype, $firsttime = false ) {
287 global $wgOut, $wgUser;
288 global $wgLang, $wgContLang, $wgParser, $wgTitle;
289 global $wgAllowAnonymousMinor;
290 global $wgSpamRegex, $wgFilterCallback;
292 $sk = $wgUser->getSkin();
293 $isConflict = false;
294 // css / js subpages of user pages get a special treatment
295 $isCssJsSubpage = $wgTitle->isCssJsSubpage();
298 if(!$this->mTitle->getArticleID()) { # new article
299 $wgOut->addWikiText(wfmsg('newarticletext'));
302 if( $this->mTitle->isTalkPage() ) {
303 $wgOut->addWikiText(wfmsg('talkpagetext'));
306 # Attempt submission here. This will check for edit conflicts,
307 # and redundantly check for locked database, blocked IPs, etc.
308 # that edit() already checked just in case someone tries to sneak
309 # in the back door with a hand-edited submission URL.
311 if ( 'save' == $formtype ) {
312 # Reintegrate metadata
313 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
314 $this->mMetaData = '' ;
316 # Check for spam
317 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
318 $this->spamPage ( $matches[0] );
319 return;
321 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
322 # Error messages or other handling should be performed by the filter function
323 return;
325 if ( $wgUser->isBlocked( false ) ) {
326 # Check block state against master, thus 'false'.
327 $this->blockedIPpage();
328 return;
331 if ( !$wgUser->isAllowed('edit') ) {
332 if ( $wgUser->isAnon() ) {
333 $this->userNotLoggedInPage();
334 return;
336 else {
337 $wgOut->readOnlyPage();
338 return;
342 if ( wfReadOnly() ) {
343 $wgOut->readOnlyPage();
344 return;
346 if ( $wgUser->pingLimiter() ) {
347 $wgOut->rateLimited();
348 return;
351 # If article is new, insert it.
352 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
353 if ( 0 == $aid ) {
354 # Don't save a new article if it's blank.
355 if ( ( '' == $this->textbox1 ) ||
356 ( wfMsg( 'newarticletext' ) == $this->textbox1 ) ) {
357 $wgOut->redirect( $this->mTitle->getFullURL() );
358 return;
360 if (wfRunHooks('ArticleSave', array(&$this->mArticle, &$wgUser, &$this->textbox1,
361 &$this->summary, &$this->minoredit, &$this->watchthis, NULL)))
363 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
364 $this->minoredit, $this->watchthis );
365 wfRunHooks('ArticleSaveComplete', array(&$this->mArticle, &$wgUser, $this->textbox1,
366 $this->summary, $this->minoredit,
367 $this->watchthis, NULL));
369 return;
372 # Article exists. Check for edit conflict.
374 $this->mArticle->clear(); # Force reload of dates, etc.
375 $this->mArticle->forUpdate( true ); # Lock the article
377 if( ( $this->section != 'new' ) &&
378 ($this->mArticle->getTimestamp() != $this->edittime ) ) {
379 $isConflict = true;
381 $userid = $wgUser->getID();
383 if ( $isConflict) {
384 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime'\n" );
385 $text = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
386 $this->section, $this->textbox1, $this->summary, $this->edittime);
388 else {
389 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
390 $text = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
391 $this->section, $this->textbox1, $this->summary);
393 # Suppress edit conflict with self
395 if ( ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
396 $isConflict = false;
397 } else {
398 # switch from section editing to normal editing in edit conflict
399 if($isConflict) {
400 # Attempt merge
401 if( $this->mergeChangesInto( $text ) ){
402 // Successful merge! Maybe we should tell the user the good news?
403 $isConflict = false;
404 } else {
405 $this->section = '';
406 $this->textbox1 = $text;
410 if ( ! $isConflict ) {
411 # All's well
412 $sectionanchor = '';
413 if( $this->section == 'new' ) {
414 if( $this->summary != '' ) {
415 $sectionanchor = $this->sectionAnchor( $this->summary );
417 } elseif( $this->section != '' ) {
418 # Try to get a section anchor from the section source, redirect to edited section if header found
419 # XXX: might be better to integrate this into Article::getTextOfLastEditWithSectionReplacedOrAdded
420 # for duplicate heading checking and maybe parsing
421 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
422 # we can't deal with anchors, includes, html etc in the header for now,
423 # headline would need to be parsed to improve this
424 #if($hasmatch and strlen($matches[2]) > 0 and !preg_match( "/[\\['{<>]/", $matches[2])) {
425 if($hasmatch and strlen($matches[2]) > 0) {
426 $sectionanchor = $this->sectionAnchor( $matches[2] );
430 if (wfRunHooks('ArticleSave', array(&$this->mArticle, &$wgUser, &$text,
431 &$this->summary, &$this->minoredit,
432 &$this->watchthis, &$sectionanchor)))
434 # update the article here
435 if($this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
436 $this->watchthis, '', $sectionanchor ))
438 wfRunHooks('ArticleSaveComplete', array(&$this->mArticle, &$wgUser, $text,
439 $this->summary, $this->minoredit,
440 $this->watchthis, $sectionanchor));
441 return;
443 else
444 $isConflict = true;
448 # First time through: get contents, set time for conflict
449 # checking, etc.
451 if ( 'initial' == $formtype || $firsttime ) {
452 $this->edittime = $this->mArticle->getTimestamp();
453 $this->textbox1 = $this->mArticle->getContent( true );
454 $this->summary = '';
455 $this->proxyCheck();
457 $wgOut->setRobotpolicy( 'noindex,nofollow' );
459 # Enabled article-related sidebar, toplinks, etc.
460 $wgOut->setArticleRelated( true );
462 if ( $isConflict ) {
463 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
464 $wgOut->setPageTitle( $s );
465 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
467 $this->textbox2 = $this->textbox1;
468 $this->textbox1 = $this->mArticle->getContent( true );
469 $this->edittime = $this->mArticle->getTimestamp();
470 } else {
472 if( $this->section != '' ) {
473 if( $this->section == 'new' ) {
474 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
475 } else {
476 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
478 if(!$this->preview) {
479 preg_match( "/^(=+)(.+)\\1/mi",
480 $this->textbox1,
481 $matches );
482 if( !empty( $matches[2] ) ) {
483 $this->summary = "/* ". trim($matches[2])." */ ";
486 } else {
487 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
489 $wgOut->setPageTitle( $s );
490 if ( !$this->checkUnicodeCompliantBrowser() ) {
491 $this->mArticle->setOldSubtitle();
492 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
494 if ( $this->oldid ) {
495 $this->mArticle->setOldSubtitle();
496 $wgOut->addWikiText( wfMsg( 'editingold' ) );
500 if( wfReadOnly() ) {
501 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
502 } else if ( $isCssJsSubpage and 'preview' != $formtype) {
503 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
505 if( $this->mTitle->isProtected('edit') ) {
506 $wgOut->addWikiText( wfMsg( 'protectedpagewarning' ) );
509 $kblength = (int)(strlen( $this->textbox1 ) / 1024);
510 if( $kblength > 29 ) {
511 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
514 $rows = $wgUser->getOption( 'rows' );
515 $cols = $wgUser->getOption( 'cols' );
517 $ew = $wgUser->getOption( 'editwidth' );
518 if ( $ew ) $ew = " style=\"width:100%\"";
519 else $ew = '';
521 $q = 'action=submit';
522 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
523 $action = $this->mTitle->escapeLocalURL( $q );
525 $summary = wfMsg('summary');
526 $subject = wfMsg('subject');
527 $minor = wfMsg('minoredit');
528 $watchthis = wfMsg ('watchthis');
529 $save = wfMsg('savearticle');
530 $prev = wfMsg('showpreview');
531 $diff = wfMsg('showdiff');
533 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
534 wfMsg('cancel') );
535 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
536 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
537 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
538 htmlspecialchars( wfMsg( 'newwindow' ) );
540 global $wgRightsText;
541 $copywarn = "<div id=\"editpage-copywarn\">\n" .
542 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
543 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
544 $wgRightsText ) . "\n</div>";
546 if( $wgUser->getOption('showtoolbar') and !$isCssJsSubpage ) {
547 # prepare toolbar for edit buttons
548 $toolbar = $this->getEditToolbar();
549 } else {
550 $toolbar = '';
553 // activate checkboxes if user wants them to be always active
554 if( !$this->preview && !$this->diff ) {
555 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis = true;
556 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
558 // activate checkbox also if user is already watching the page,
559 // require wpWatchthis to be unset so that second condition is not
560 // checked unnecessarily
561 if( !$this->watchthis && $this->mTitle->userIsWatching() ) $this->watchthis = true;
564 $minoredithtml = '';
566 if ( $wgUser->isLoggedIn() || $wgAllowAnonymousMinor ) {
567 $minoredithtml =
568 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
569 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
570 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
573 $watchhtml = '';
575 if ( $wgUser->isLoggedIn() ) {
576 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".($this->watchthis?" checked='checked'":"").
577 " accesskey='".wfMsg('accesskey-watch')."' id='wpWatchthis' />".
578 "<label for='wpWatchthis' title='".wfMsg('tooltip-watch')."'>{$watchthis}</label>";
581 $checkboxhtml = $minoredithtml . $watchhtml . '<br />';
583 $wgOut->addHTML( '<div id="wikiPreview">' );
584 if ( 'preview' == $formtype) {
585 $previewOutput = $this->getPreviewText( $isConflict, $isCssJsSubpage );
586 if ( $wgUser->getOption('previewontop' ) ) {
587 $wgOut->addHTML( $previewOutput );
588 if($this->mTitle->getNamespace() == NS_CATEGORY) {
589 $this->mArticle->closeShowCategory();
591 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
594 $wgOut->addHTML( '</div>' );
595 if ( 'diff' == $formtype ) {
596 if ( $wgUser->getOption('previewontop' ) ) {
597 $wgOut->addHTML( $this->getDiff() );
602 # if this is a comment, show a subject line at the top, which is also the edit summary.
603 # Otherwise, show a summary field at the bottom
604 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
605 if( $this->section == 'new' ) {
606 $commentsubject="{$subject}: <input tabindex='1' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
607 $editsummary = '';
608 } else {
609 $commentsubject = '';
610 $editsummary="{$summary}: <input tabindex='2' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
613 if( !$this->preview && !$this->diff ) {
614 # Don't select the edit box on preview; this interferes with seeing what's going on.
615 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
617 # Prepare a list of templates used by this page
618 $templates = '';
619 $articleTemplates = $this->mArticle->getUsedTemplates();
620 if ( count( $articleTemplates ) > 0 ) {
621 $templates = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
622 foreach ( $articleTemplates as $tpl ) {
623 if ( $titleObj = Title::makeTitle( NS_TEMPLATE, $tpl ) ) {
624 $templates .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
627 $templates .= '</ul>';
630 global $wgLivePreview, $wgStylePath;
632 * Live Preview lets us fetch rendered preview page content and
633 * add it to the page without refreshing the whole page.
634 * Set up the button for it; if not supported by the browser
635 * it will fall through to the normal form submission method.
637 if( $wgLivePreview ) {
638 global $wgJsMimeType;
639 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
640 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
641 '"></script>' . "\n" );
642 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
643 $liveOnclick = 'onclick="return !livePreview('.
644 'getElementById(\'wikiPreview\'),' .
645 'editform.wpTextbox1.value,' .
646 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
647 } else {
648 $liveOnclick = '';
651 global $wgUseMetadataEdit ;
652 if ( $wgUseMetadataEdit )
654 $metadata = $this->mMetaData ;
655 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
656 $helppage = Title::newFromText ( wfmsg("metadata_page") ) ;
657 $top = str_replace ( "$1" , $helppage->getInternalURL() , wfmsg("metadata") ) ;
658 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
660 else $metadata = "" ;
663 $wgOut->addHTML( <<<END
664 {$toolbar}
665 <form id="editform" name="editform" method="post" action="$action"
666 enctype="multipart/form-data">
667 {$commentsubject}
668 <textarea tabindex='1' accesskey="," name="wpTextbox1" rows='{$rows}'
669 cols='{$cols}'{$ew}>
671 . htmlspecialchars( $wgContLang->recodeForEdit( $this->textbox1 ) ) .
673 </textarea>
674 {$metadata}
675 <br />{$editsummary}
676 {$checkboxhtml}
677 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
678 " title=\"".wfMsg('tooltip-save')."\"/>
679 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
680 " title=\"".wfMsg('tooltip-preview')."\"/>
681 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
682 " title=\"".wfMsg('tooltip-diff')."\"/>
683 <em>{$cancel}</em> | <em>{$edithelp}</em>{$templates}" );
684 $wgOut->addWikiText( $copywarn );
685 $wgOut->addHTML( "
686 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
687 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
689 if ( $wgUser->isLoggedIn() ) {
691 * To make it harder for someone to slip a user a page
692 * which submits an edit form to the wiki without their
693 * knowledge, a random token is associated with the login
694 * session. If it's not passed back with the submission,
695 * we won't save the page, or render user JavaScript and
696 * CSS previews.
698 $token = htmlspecialchars( $wgUser->editToken() );
699 $wgOut->addHTML( "
700 <input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
704 if ( $isConflict ) {
705 require_once( "DifferenceEngine.php" );
706 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
707 DifferenceEngine::showDiff( $this->textbox2, $this->textbox1,
708 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
710 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
711 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
712 . htmlspecialchars( $wgContLang->recodeForEdit( $this->textbox2 ) ) .
714 </textarea>" );
716 $wgOut->addHTML( "</form>\n" );
717 if ( $formtype == 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
718 $wgOut->addHTML( '<div id="wikiPreview">' . $previewOutput . '</div>' );
720 if ( $formtype == 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
721 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
722 $wgOut->addHTML( $this->getDiff() );
727 * @todo document
729 function getPreviewText( $isConflict, $isCssJsSubpage ) {
730 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
731 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
732 "<p class='previewnote'>" . htmlspecialchars( wfMsg( 'previewnote' ) ) . "</p>\n";
733 if ( $isConflict ) {
734 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) .
735 "</h2>\n";
738 $parserOptions = ParserOptions::newFromUser( $wgUser );
739 $parserOptions->setEditSection( false );
741 # don't parse user css/js, show message about preview
742 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
744 if ( $isCssJsSubpage ) {
745 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
746 $previewtext = wfMsg('usercsspreview');
747 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
748 $previewtext = wfMsg('userjspreview');
750 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
751 $wgOut->addHTML( $parserOutput->mText );
752 return $previewhead;
753 } else {
754 # if user want to see preview when he edit an article
755 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
756 $this->textbox1 = $this->mArticle->getContent(true);
759 $toparse = $this->textbox1 ;
760 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
762 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
763 $wgTitle, $parserOptions );
765 $previewHTML = $parserOutput->mText;
767 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
768 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
769 return $previewhead . $previewHTML;
774 * @todo document
776 function blockedIPpage() {
777 global $wgOut, $wgUser, $wgContLang, $wgIP;
779 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
780 $wgOut->setRobotpolicy( 'noindex,nofollow' );
781 $wgOut->setArticleRelated( false );
783 $id = $wgUser->blockedBy();
784 $reason = $wgUser->blockedFor();
785 $ip = $wgIP;
787 if ( is_numeric( $id ) ) {
788 $name = User::whoIs( $id );
789 } else {
790 $name = $id;
792 $link = '[[' . $wgContLang->getNsText( NS_USER ) .
793 ":{$name}|{$name}]]";
795 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
796 $wgOut->returnToMain( false );
800 * @todo document
802 function userNotLoggedInPage() {
803 global $wgOut;
805 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
806 $wgOut->setRobotpolicy( 'noindex,nofollow' );
807 $wgOut->setArticleRelated( false );
809 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
810 $wgOut->returnToMain( false );
814 * @todo document
816 function spamPage ( $match = false )
818 global $wgOut;
819 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
820 $wgOut->setRobotpolicy( 'noindex,nofollow' );
821 $wgOut->setArticleRelated( false );
823 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
824 if ( $match ) {
825 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
827 $wgOut->returnToMain( false );
831 * Forks processes to scan the originating IP for an open proxy server
832 * MemCached can be used to skip IPs that have already been scanned
834 function proxyCheck() {
835 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
836 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
838 if ( !$wgBlockOpenProxies ) {
839 return;
842 # Get MemCached key
843 $skip = false;
844 if ( $wgUseMemCached ) {
845 $mcKey = $wgDBname.':proxy:ip:'.$wgIP;
846 $mcValue = $wgMemc->get( $mcKey );
847 if ( $mcValue ) {
848 $skip = true;
852 # Fork the processes
853 if ( !$skip ) {
854 $title = Title::makeTitle( NS_SPECIAL, 'Blockme' );
855 $iphash = md5( $wgIP . $wgProxyKey );
856 $url = $title->getFullURL( 'ip='.$iphash );
858 foreach ( $wgProxyPorts as $port ) {
859 $params = implode( ' ', array(
860 escapeshellarg( $wgProxyScriptPath ),
861 escapeshellarg( $wgIP ),
862 escapeshellarg( $port ),
863 escapeshellarg( $url )
865 exec( "php $params &>/dev/null &" );
867 # Set MemCached key
868 if ( $wgUseMemCached ) {
869 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
875 * @access private
876 * @todo document
878 function mergeChangesInto( &$text ){
879 $yourtext = $this->mArticle->fetchRevisionText();
881 $db =& wfGetDB( DB_MASTER );
882 $oldText = $this->mArticle->fetchRevisionText(
883 $db->timestamp( $this->edittime ),
884 'rev_timestamp' );
886 if(wfMerge($oldText, $text, $yourtext, $result)){
887 $text = $result;
888 return true;
889 } else {
890 return false;
895 function checkUnicodeCompliantBrowser() {
896 global $wgBrowserBlackList;
897 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
898 foreach ( $wgBrowserBlackList as $browser ) {
899 if ( preg_match($browser, $currentbrowser) ) {
900 return false;
903 return true;
907 * Format an anchor fragment as it would appear for a given section name
908 * @param string $text
909 * @return string
910 * @access private
912 function sectionAnchor( $text ) {
913 $headline = Sanitizer::decodeCharReferences( $text );
914 # strip out HTML
915 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
916 $headline = trim( $headline );
917 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
918 $replacearray = array(
919 '%3A' => ':',
920 '%' => '.'
922 return str_replace(
923 array_keys( $replacearray ),
924 array_values( $replacearray ),
925 $sectionanchor );
929 * Shows a bulletin board style toolbar for common editing functions.
930 * It can be disabled in the user preferences.
931 * The necessary JavaScript code can be found in style/wikibits.js.
933 function getEditToolbar() {
934 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
937 * toolarray an array of arrays which each include the filename of
938 * the button image (without path), the opening tag, the closing tag,
939 * and optionally a sample text that is inserted between the two when no
940 * selection is highlighted.
941 * The tip text is shown when the user moves the mouse over the button.
943 * Already here are accesskeys (key), which are not used yet until someone
944 * can figure out a way to make them work in IE. However, we should make
945 * sure these keys are not defined on the edit page.
947 $toolarray=array(
948 array( 'image'=>'button_bold.png',
949 'open' => "\'\'\'",
950 'close' => "\'\'\'",
951 'sample'=> wfMsg('bold_sample'),
952 'tip' => wfMsg('bold_tip'),
953 'key' => 'B'
955 array( 'image'=>'button_italic.png',
956 'open' => "\'\'",
957 'close' => "\'\'",
958 'sample'=> wfMsg('italic_sample'),
959 'tip' => wfMsg('italic_tip'),
960 'key' => 'I'
962 array( 'image'=>'button_link.png',
963 'open' => '[[',
964 'close' => ']]',
965 'sample'=> wfMsg('link_sample'),
966 'tip' => wfMsg('link_tip'),
967 'key' => 'L'
969 array( 'image'=>'button_extlink.png',
970 'open' => '[',
971 'close' => ']',
972 'sample'=> wfMsg('extlink_sample'),
973 'tip' => wfMsg('extlink_tip'),
974 'key' => 'X'
976 array( 'image'=>'button_headline.png',
977 'open' => "\\n== ",
978 'close' => " ==\\n",
979 'sample'=> wfMsg('headline_sample'),
980 'tip' => wfMsg('headline_tip'),
981 'key' => 'H'
983 array( 'image'=>'button_image.png',
984 'open' => '[['.$wgLang->getNsText(NS_IMAGE).":",
985 'close' => ']]',
986 'sample'=> wfMsg('image_sample'),
987 'tip' => wfMsg('image_tip'),
988 'key' => 'D'
990 array( 'image' =>'button_media.png',
991 'open' => '[['.$wgLang->getNsText(NS_MEDIA).':',
992 'close' => ']]',
993 'sample'=> wfMsg('media_sample'),
994 'tip' => wfMsg('media_tip'),
995 'key' => 'M'
997 array( 'image' =>'button_math.png',
998 'open' => "\\<math\\>",
999 'close' => "\\</math\\>",
1000 'sample'=> wfMsg('math_sample'),
1001 'tip' => wfMsg('math_tip'),
1002 'key' => 'C'
1004 array( 'image' =>'button_nowiki.png',
1005 'open' => "\\<nowiki\\>",
1006 'close' => "\\</nowiki\\>",
1007 'sample'=> wfMsg('nowiki_sample'),
1008 'tip' => wfMsg('nowiki_tip'),
1009 'key' => 'N'
1011 array( 'image' =>'button_sig.png',
1012 'open' => '--~~~~',
1013 'close' => '',
1014 'sample'=> '',
1015 'tip' => wfMsg('sig_tip'),
1016 'key' => 'Y'
1018 array( 'image' =>'button_hr.png',
1019 'open' => "\\n----\\n",
1020 'close' => '',
1021 'sample'=> '',
1022 'tip' => wfMsg('hr_tip'),
1023 'key' => 'R'
1026 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1028 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1029 foreach($toolarray as $tool) {
1031 $image=$wgStylePath.'/common/images/'.$tool['image'];
1032 $open=$tool['open'];
1033 $close=$tool['close'];
1034 $sample = wfEscapeJsString( $tool['sample'] );
1036 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1037 // Older browsers show a "speedtip" type message only for ALT.
1038 // Ideally these should be different, realistically they
1039 // probably don't need to be.
1040 $tip = wfEscapeJsString( $tool['tip'] );
1042 #$key = $tool["key"];
1044 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1047 $toolbar.="addInfobox('" . wfEscapeJsString( wfMsg( "infobox" ) ) .
1048 "','" . wfEscapeJsString( wfMsg( "infobox_alert" ) ) . "');\n";
1049 $toolbar.="document.writeln(\"</div>\");\n";
1051 $toolbar.="/*]]>*/\n</script>";
1052 return $toolbar;
1056 * Output preview text only. This can be sucked into the edit page
1057 * via JavaScript, and saves the server time rendering the skin as
1058 * well as theoretically being more robust on the client (doesn't
1059 * disturb the edit box's undo history, won't eat your text on
1060 * failure, etc).
1062 * @todo This doesn't include category or interlanguage links.
1063 * Would need to enhance it a bit, maybe wrap them in XML
1064 * or something... that might also require more skin
1065 * initialization, so check whether that's a problem.
1067 function livePreview() {
1068 global $wgOut;
1069 $wgOut->disable();
1070 header( 'Content-type: text/xml' );
1071 header( 'Cache-control: no-cache' );
1072 # FIXME
1073 echo $this->getPreviewText( false, false );
1078 * Get a diff between the current contents of the edit box and the
1079 * version of the page we're editing from.
1081 * If this is a section edit, we'll replace the section as for final
1082 * save and then make a comparison.
1084 * @return string HTML
1086 function getDiff() {
1087 require_once( 'DifferenceEngine.php' );
1088 $oldtext = $this->mArticle->getContent( true );
1089 $newtext = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
1090 $this->section, $this->textbox1, $this->summary, $this->edittime );
1091 $oldtitle = wfMsg( 'currentrev' );
1092 $newtitle = wfMsg( 'yourtext' );
1093 if ( $oldtext != wfMsg( 'noarticletext' ) || $newtext != '' ) {
1094 $difftext = DifferenceEngine::getDiff( $oldtext, $newtext, $oldtitle, $newtitle );
1097 return '<div id="wikiDiff">' . $difftext . '</div>';