The cancel-button of edit pages did not work for UTF-8 encoded articles with special...
[mediawiki.git] / includes / EditPage.php
blob5a488fa43a99f2e5c2cb60ccd398cfa971144bf3
1 <?php
3 # Splitting edit page/HTML interface from Article...
4 # The actual database and text munging is still in Article,
5 # but it should get easier to call those from alternate
6 # interfaces.
8 class EditPage {
9 var $mArticle;
10 var $mTitle;
12 # Form values
13 var $save = false, $preview = false;
14 var $minoredit = false, $watchthis = false;
15 var $textbox1 = "", $textbox2 = "", $summary = "";
16 var $edittime = "", $section = "";
17 var $oldid = 0;
19 function EditPage( $article ) {
20 $this->mArticle =& $article;
21 global $wgTitle;
22 $this->mTitle =& $wgTitle;
25 # This is the function that gets called for "action=edit".
27 function edit()
29 global $wgOut, $wgUser, $wgWhitelistEdit, $wgRequest;
30 // this is not an article
31 $wgOut->setArticleFlag(false);
33 $this->importFormData( $wgRequest );
35 if ( ! $this->mTitle->userCanEdit() ) {
36 $wgOut->readOnlyPage( $this->mArticle->getContent( true ), true );
37 return;
39 if ( $wgUser->isBlocked() ) {
40 $this->blockedIPpage();
41 return;
43 if ( !$wgUser->getID() && $wgWhitelistEdit ) {
44 $this->userNotLoggedInPage();
45 return;
47 if ( wfReadOnly() ) {
48 if( $this->save || $this->preview ) {
49 $this->editForm( "preview" );
50 } else {
51 $wgOut->readOnlyPage( $this->mArticle->getContent( true ) );
53 return;
55 if ( $this->save ) {
56 $this->editForm( "save" );
57 } else if ( $this->preview ) {
58 $this->editForm( "preview" );
59 } else { # First time through
60 $this->editForm( "initial" );
64 function importFormData( &$request ) {
65 # These fields need to be checked for encoding.
66 # Also remove trailing whitespace, but don't remove _initial_
67 # whitespace from the text boxes. This may be significant formatting.
68 $this->textbox1 = rtrim( $request->getText( "wpTextbox1" ) );
69 $this->textbox2 = rtrim( $request->getText( "wpTextbox2" ) );
70 $this->summary = trim( $request->getText( "wpSummary" ) );
72 $this->edittime = $request->getVal( 'wpEdittime' );
73 if( !preg_match( '/^\d{14}$/', $this->edittime ) ) $this->edittime = "";
75 $this->preview = $request->getCheck( 'wpPreview' );
76 $this->save = $request->wasPosted() && !$this->preview;
77 $this->minoredit = $request->getCheck( 'wpMinoredit' );
78 $this->watchthis = $request->getCheck( 'wpWatchthis' );
80 $this->oldid = $request->getInt( 'oldid' );
82 # Section edit can come from either the form or a link
83 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
86 # Since there is only one text field on the edit form,
87 # pressing <enter> will cause the form to be submitted, but
88 # the submit button value won't appear in the query, so we
89 # Fake it here before going back to edit(). This is kind of
90 # ugly, but it helps some old URLs to still work.
92 function submit()
94 if( !$this->preview ) $this->save = true;
96 $this->edit();
99 # The edit form is self-submitting, so that when things like
100 # preview and edit conflicts occur, we get the same form back
101 # with the extra stuff added. Only when the final submission
102 # is made and all is well do we actually save and redirect to
103 # the newly-edited page.
105 function editForm( $formtype )
107 global $wgOut, $wgUser;
108 global $wgLang, $wgParser, $wgTitle;
109 global $wgAllowAnonymousMinor;
110 global $wgWhitelistEdit;
111 global $wgSpamRegex;
113 $sk = $wgUser->getSkin();
114 $isConflict = false;
115 // css / js subpages of user pages get a special treatment
116 $isCssJsSubpage = (Namespace::getUser() == $wgTitle->getNamespace() and preg_match("/\\.(css|js)$/", $wgTitle->getText() ));
118 if(!$this->mTitle->getArticleID()) { # new article
119 $wgOut->addWikiText(wfmsg("newarticletext"));
122 if( Namespace::isTalk( $this->mTitle->getNamespace() ) ) {
123 $wgOut->addWikiText(wfmsg("talkpagetext"));
126 # Attempt submission here. This will check for edit conflicts,
127 # and redundantly check for locked database, blocked IPs, etc.
128 # that edit() already checked just in case someone tries to sneak
129 # in the back door with a hand-edited submission URL.
131 if ( "save" == $formtype ) {
132 # Check for spam
133 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1 ) ) {
134 if ( $wgUser->isSysop() ) {
135 $this->spamPage();
136 } else {
137 sleep(10);
138 $wgOut->redirect( $this->mTitle->getFullURL() );
140 return;
142 if ( $wgUser->isBlocked() ) {
143 $this->blockedIPpage();
144 return;
146 if ( !$wgUser->getID() && $wgWhitelistEdit ) {
147 $this->userNotLoggedInPage();
148 return;
150 if ( wfReadOnly() ) {
151 $wgOut->readOnlyPage();
152 return;
155 # If article is new, insert it.
156 $aid = $this->mTitle->getArticleID();
157 if ( 0 == $aid ) {
158 # Don't save a new article if it's blank.
159 if ( ( "" == $this->textbox1 ) ||
160 ( wfMsg( "newarticletext" ) == $this->textbox1 ) ) {
161 $wgOut->redirect( $this->mTitle->getFullURL() );
162 return;
164 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary, $this->minoredit, $this->watchthis );
165 return;
168 # Article exists. Check for edit conflict.
170 $this->mArticle->clear(); # Force reload of dates, etc.
172 if( ( $this->section != "new" ) &&
173 ($this->mArticle->getTimestamp() != $this->edittime ) ) {
174 $isConflict = true;
176 $userid = $wgUser->getID();
178 $text = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
179 $this->section, $this->textbox1, $this->summary);
180 # Suppress edit conflict with self
182 if ( ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
183 $isConflict = false;
184 } else {
185 # switch from section editing to normal editing in edit conflict
186 if($isConflict) {
187 # Attempt merge
188 if( $this->mergeChangesInto( $text ) ){
189 // Successful merge! Maybe we should tell the user the good news?
190 $isConflict = false;
191 } else {
192 $this->section = "";
193 $this->textbox1 = $text;
197 if ( ! $isConflict ) {
198 # All's well
199 $sectionanchor = '';
200 if( $this->section != '' ) {
201 # Try to get a section anchor from the section source, redirect to edited section if header found
202 # XXX: might be better to integrate this into Article::getTextOfLastEditWithSectionReplacedOrAdded
203 # for duplicate heading checking and maybe parsing
204 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
205 # we can't deal with anchors, includes, html etc in the header for now,
206 # headline would need to be parsed to improve this
207 if($hasmatch and strlen($matches[2]) > 0 and !preg_match( "/[\\['{<>]/", $matches[2])) {
208 global $wgInputEncoding;
209 $headline = do_html_entity_decode( $matches[2], ENT_COMPAT, $wgInputEncoding );
210 # strip out HTML, will be useful when
211 # $headline = preg_replace( "/<.*?" . ">/","",$headline );
212 $headline = trim( $headline );
213 $sectionanchor = '#'.preg_replace("/[ \\?&\\/<>\\(\\)\\[\\]=,+']+/", '_', urlencode( $headline ) );
217 # update the article here
218 if($this->mArticle->updateArticle( $text, $this->summary, $this->minoredit, $this->watchthis, '', $sectionanchor ))
219 return;
220 else
221 $isConflict = true;
224 # First time through: get contents, set time for conflict
225 # checking, etc.
227 if ( "initial" == $formtype ) {
228 $this->edittime = $this->mArticle->getTimestamp();
229 $this->textbox1 = $this->mArticle->getContent( true );
230 $this->summary = "";
231 $this->proxyCheck();
233 $wgOut->setRobotpolicy( "noindex,nofollow" );
235 # Enabled article-related sidebar, toplinks, etc.
236 $wgOut->setArticleRelated( true );
238 if ( $isConflict ) {
239 $s = wfMsg( "editconflict", $this->mTitle->getPrefixedText() );
240 $wgOut->setPageTitle( $s );
241 $wgOut->addHTML( wfMsg( "explainconflict" ) );
243 $this->textbox2 = $this->textbox1;
244 $this->textbox1 = $this->mArticle->getContent( true );
245 $this->edittime = $this->mArticle->getTimestamp();
246 } else {
247 $s = wfMsg( "editing", $this->mTitle->getPrefixedText() );
249 if( $this->section != "" ) {
250 if( $this->section == "new" ) {
251 $s.=wfMsg("commentedit");
252 } else {
253 $s.=wfMsg("sectionedit");
255 if(!$this->preview) {
256 $sectitle=preg_match("/^=+(.*?)=+/mi",
257 $this->textbox1,
258 $matches);
259 if( !empty( $matches[1] ) ) {
260 $this->summary = "/* ". trim($matches[1])." */ ";
264 $wgOut->setPageTitle( $s );
265 if ( $this->oldid ) {
266 $this->mArticle->setOldSubtitle();
267 $wgOut->addHTML( wfMsg( "editingold" ) );
271 if( wfReadOnly() ) {
272 $wgOut->addHTML( "<strong>" .
273 wfMsg( "readonlywarning" ) .
274 "</strong>" );
275 } else if ( $isCssJsSubpage and "preview" != $formtype) {
276 $wgOut->addHTML( wfMsg( "usercssjsyoucanpreview" ));
278 if( $this->mTitle->isProtected() ) {
279 $wgOut->addHTML( "<strong>" . wfMsg( "protectedpagewarning" ) .
280 "</strong><br />\n" );
283 $kblength = (int)(strlen( $this->textbox1 ) / 1024);
284 if( $kblength > 29 ) {
285 $wgOut->addHTML( "<strong>" .
286 wfMsg( "longpagewarning", $kblength )
287 . "</strong>" );
290 $rows = $wgUser->getOption( "rows" );
291 $cols = $wgUser->getOption( "cols" );
293 $ew = $wgUser->getOption( "editwidth" );
294 if ( $ew ) $ew = " style=\"width:100%\"";
295 else $ew = "" ;
297 $q = "action=submit";
298 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
299 $action = $this->mTitle->escapeLocalURL( $q );
301 $summary = wfMsg( "summary" );
302 $subject = wfMsg("subject");
303 $minor = wfMsg( "minoredit" );
304 $watchthis = wfMsg ("watchthis");
305 $save = wfMsg( "savearticle" );
306 $prev = wfMsg( "showpreview" );
308 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
309 wfMsg( "cancel" ) );
310 $edithelpurl = $sk->makeUrl( wfMsg( "edithelppage" ));
311 $edithelp = '<a onclick="window.open('.
312 "'$edithelpurl', 'helpwindow', 'width=610,height=400,left=10,top=10'".'); return false;" href="'.$edithelpurl.'">'.
313 wfMsg( "edithelp" ).'</a>';
314 $copywarn = wfMsg( "copyrightwarning", $sk->makeKnownLink(
315 wfMsg( "copyrightpage" ) ) );
317 if( $wgUser->getOption("showtoolbar") and !$isCssJsSubpage ) {
318 # prepare toolbar for edit buttons
319 $toolbar = $sk->getEditToolbar();
320 } else {
321 $toolbar = "";
324 // activate checkboxes if user wants them to be always active
325 if( !$this->preview ) {
326 if( $wgUser->getOption( "watchdefault" ) ) $this->watchthis = true;
327 if( $wgUser->getOption( "minordefault" ) ) $this->minoredit = true;
329 // activate checkbox also if user is already watching the page,
330 // require wpWatchthis to be unset so that second condition is not
331 // checked unnecessarily
332 if( !$this->watchthis && $this->mTitle->userIsWatching() ) $this->watchthis = true;
335 $minoredithtml = "";
337 if ( 0 != $wgUser->getID() || $wgAllowAnonymousMinor ) {
338 $minoredithtml =
339 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
340 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
341 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
344 $watchhtml = "";
346 if ( 0 != $wgUser->getID() ) {
347 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".($this->watchthis?" checked='checked'":"").
348 " accesskey='".wfMsg('accesskey-watch')."' id='wpWatchthis' />".
349 "<label for='wpWatchthis' title='".wfMsg('tooltip-watch')."'>{$watchthis}</label>";
352 $checkboxhtml = $minoredithtml . $watchhtml . "<br />";
354 if ( "preview" == $formtype) {
355 $previewhead="<h2>" . wfMsg( "preview" ) . "</h2>\n<p><large><center><font color=\"#cc0000\">" .
356 wfMsg( "note" ) . wfMsg( "previewnote" ) . "</font></center></large></p>\n";
357 if ( $isConflict ) {
358 $previewhead.="<h2>" . wfMsg( "previewconflict" ) .
359 "</h2>\n";
362 $parserOptions = ParserOptions::newFromUser( $wgUser );
363 $parserOptions->setUseCategoryMagic( false );
364 $parserOptions->setEditSection( false );
365 $parserOptions->setEditSectionOnRightClick( false );
366 # don't parse user css/js, show message about preview
367 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
368 if ( $isCssJsSubpage ) {
369 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
370 $previewtext = wfMsg('usercsspreview');
371 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
372 $previewtext = wfMsg('userjspreview');
374 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
375 $wgOut->addHTML( $parserOutput->mText );
376 } else {
377 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $this->textbox1 ) ."\n\n",
378 $wgTitle, $parserOptions );
379 $previewHTML = $parserOutput->mText;
381 if($wgUser->getOption("previewontop")) {
382 $wgOut->addHTML($previewhead);
383 $wgOut->addHTML($previewHTML);
385 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
389 # if this is a comment, show a subject line at the top, which is also the edit summary.
390 # Otherwise, show a summary field at the bottom
391 $summarytext = htmlspecialchars( $wgLang->recodeForEdit( $this->summary ) ); # FIXME
392 if( $this->section == "new" ) {
393 $commentsubject="{$subject}: <input tabindex='1' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
394 $editsummary = "";
395 } else {
396 $commentsubject = "";
397 $editsummary="{$summary}: <input tabindex='3' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
400 if( !$this->preview ) {
401 # Don't select the edit box on preview; this interferes with seeing what's going on.
402 $wgOut->setOnloadHandler( "document.editform.wpTextbox1.focus()" );
404 $wgOut->addHTML( "
405 {$toolbar}
406 <form id=\"editform\" name=\"editform\" method=\"post\" action=\"$action\"
407 enctype=\"application/x-www-form-urlencoded\">
408 {$commentsubject}
409 <textarea tabindex='1' accesskey=\",\" name=\"wpTextbox1\" rows='{$rows}'
410 cols='{$cols}'{$ew}>" .
411 htmlspecialchars( $wgLang->recodeForEdit( $this->textbox1 ) ) .
413 </textarea>
414 <br />{$editsummary}
415 {$checkboxhtml}
416 <input tabindex='5' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
417 " title=\"".wfMsg('tooltip-save')."\"/>
418 <input tabindex='6' type='submit' value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
419 " title=\"".wfMsg('tooltip-preview')."\"/>
420 <em>{$cancel}</em> | <em>{$edithelp}</em>
421 <br /><br />{$copywarn}
422 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
423 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
425 if ( $isConflict ) {
426 $wgOut->addHTML( "<h2>" . wfMsg( "yourdiff" ) . "</h2>\n" );
427 DifferenceEngine::showDiff( $this->textbox2, $this->textbox1,
428 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
430 $wgOut->addHTML( "<h2>" . wfMsg( "yourtext" ) . "</h2>
431 <textarea tabindex=6 name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
432 . htmlspecialchars( $wgLang->recodeForEdit( $this->textbox2 ) ) .
434 </textarea>" );
436 $wgOut->addHTML( "</form>\n" );
437 if($formtype =="preview" && !$wgUser->getOption("previewontop")) {
438 $wgOut->addHTML($previewhead);
439 $wgOut->addHTML($previewHTML);
444 function blockedIPpage()
446 global $wgOut, $wgUser, $wgLang, $wgIP;
448 $wgOut->setPageTitle( wfMsg( "blockedtitle" ) );
449 $wgOut->setRobotpolicy( "noindex,nofollow" );
450 $wgOut->setArticleRelated( false );
452 $id = $wgUser->blockedBy();
453 $reason = $wgUser->blockedFor();
454 $ip = $wgIP;
456 $name = User::whoIs( $id );
457 $link = "[[" . $wgLang->getNsText( Namespace::getUser() ) .
458 ":{$name}|{$name}]]";
460 $wgOut->addWikiText( wfMsg( "blockedtext", $link, $reason, $ip, $name ) );
461 $wgOut->returnToMain( false );
466 function userNotLoggedInPage()
468 global $wgOut, $wgUser, $wgLang;
470 $wgOut->setPageTitle( wfMsg( "whitelistedittitle" ) );
471 $wgOut->setRobotpolicy( "noindex,nofollow" );
472 $wgOut->setArticleRelated( false );
474 $wgOut->addWikiText( wfMsg( "whitelistedittext" ) );
475 $wgOut->returnToMain( false );
478 function spamPage()
480 global $wgOut, $wgSpamRegex;
481 $wgOut->setPageTitle( wfMsg( "spamprotectiontitle" ) );
482 $wgOut->setRobotpolicy( "noindex,nofollow" );
483 $wgOut->setArticleRelated( false );
485 $wgOut->addWikiText( wfMsg( "spamprotectiontext" ) );
486 $wgOut->addWikiText( "<pre>".$wgSpamRegex."</pre>" );
487 $wgOut->returnToMain( false );
490 # Forks processes to scan the originating IP for an open proxy server
491 # MemCached can be used to skip IPs that have already been scanned
492 function proxyCheck()
494 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
495 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
497 if ( !$wgBlockOpenProxies ) {
498 return;
501 # Get MemCached key
502 $skip = false;
503 if ( $wgUseMemCached ) {
504 $mcKey = "$wgDBname:proxy:ip:$wgIP";
505 $mcValue = $wgMemc->get( $mcKey );
506 if ( $mcValue ) {
507 $skip = true;
511 # Fork the processes
512 if ( !$skip ) {
513 $title = Title::makeTitle( NS_SPECIAL, "Blockme" );
514 $iphash = md5( $wgIP . $wgProxyKey );
515 $url = $title->getFullURL( "ip=$iphash" );
517 foreach ( $wgProxyPorts as $port ) {
518 $params = implode( " ", array(
519 escapeshellarg( $wgProxyScriptPath ),
520 escapeshellarg( $wgIP ),
521 escapeshellarg( $port ),
522 escapeshellarg( $url )
524 exec( "php $params &>/dev/null &" );
526 # Set MemCached key
527 if ( $wgUseMemCached ) {
528 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
533 /* private */ function mergeChangesInto( &$text ){
534 $oldDate = $this->edittime;
535 $res = wfQuery("SELECT cur_text FROM cur WHERE cur_id=" .
536 $this->mTitle->getArticleID() . " FOR UPDATE", DB_WRITE);
537 $obj = wfFetchObject($res);
539 $yourtext = $obj->cur_text;
540 $ns = $this->mTitle->getNamespace();
541 $title = wfStrencode( $this->mTitle->getDBkey() );
542 $res = wfQuery("SELECT old_text,old_flags FROM old WHERE old_namespace = $ns AND ".
543 "old_title = '{$title}' AND old_timestamp = '{$oldDate}'", DB_WRITE);
544 $obj = wfFetchObject($res);
545 $oldText = Article::getRevisionText( $obj );
547 if(wfMerge($oldText, $text, $yourtext, $result)){
548 $text = $result;
549 return true;
550 } else {
551 return false;