Change id='wpSave' to correct id='wpPreview' (bug #981868)
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2
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.
7
8 class EditPage {
9 var $mArticle;
10 var $mTitle;
11
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;
18
19 function EditPage( $article ) {
20 $this->mArticle =& $article;
21 global $wgTitle;
22 $this->mTitle =& $wgTitle;
23 }
24
25 # This is the function that gets called for "action=edit".
26
27 function edit()
28 {
29 global $wgOut, $wgUser, $wgWhitelistEdit, $wgRequest;
30 // this is not an article
31 $wgOut->setArticleFlag(false);
32
33 $this->importFormData( $wgRequest );
34
35 if ( ! $this->mTitle->userCanEdit() ) {
36 $wgOut->readOnlyPage( $this->mArticle->getContent( true ), true );
37 return;
38 }
39 if ( $wgUser->isBlocked() ) {
40 $this->blockedIPpage();
41 return;
42 }
43 if ( !$wgUser->getID() && $wgWhitelistEdit ) {
44 $this->userNotLoggedInPage();
45 return;
46 }
47 if ( wfReadOnly() ) {
48 if( $this->save || $this->preview ) {
49 $this->editForm( "preview" );
50 } else {
51 $wgOut->readOnlyPage( $this->mArticle->getContent( true ) );
52 }
53 return;
54 }
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" );
61 }
62 }
63
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" ) );
71
72 $this->edittime = $request->getVal( 'wpEdittime' );
73 if( !preg_match( '/^\d{14}$/', $this->edittime )) $this->edittime = "";
74
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' );
79
80 $this->oldid = $request->getInt( 'oldid' );
81
82 # Section edit can come from either the form or a link
83 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
84 }
85
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.
91
92 function submit()
93 {
94 if( !$this->preview ) $this->save = true;
95
96 $this->edit();
97 }
98
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.
104
105 function editForm( $formtype )
106 {
107 global $wgOut, $wgUser;
108 global $wgLang, $wgParser, $wgTitle;
109 global $wgAllowAnonymousMinor;
110 global $wgWhitelistEdit;
111 global $wgSpamRegex, $wgFilterCallback;
112
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() ));
117
118 if(!$this->mTitle->getArticleID()) { # new article
119 $wgOut->addWikiText(wfmsg("newarticletext"));
120 }
121
122 if( Namespace::isTalk( $this->mTitle->getNamespace() ) ) {
123 $wgOut->addWikiText(wfmsg("talkpagetext"));
124 }
125
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.
130
131 if ( "save" == $formtype ) {
132 # Check for spam
133 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1 ) ) {
134 $this->spamPage();
135 return;
136 }
137 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
138 # Error messages or other handling should be performed by the filter function
139 return;
140 }
141 if ( $wgUser->isBlocked() ) {
142 $this->blockedIPpage();
143 return;
144 }
145 if ( !$wgUser->getID() && $wgWhitelistEdit ) {
146 $this->userNotLoggedInPage();
147 return;
148 }
149 if ( wfReadOnly() ) {
150 $wgOut->readOnlyPage();
151 return;
152 }
153
154 # If article is new, insert it.
155 $aid = $this->mTitle->getArticleID();
156 if ( 0 == $aid ) {
157 # Don't save a new article if it's blank.
158 if ( ( "" == $this->textbox1 ) ||
159 ( wfMsg( "newarticletext" ) == $this->textbox1 ) ) {
160 $wgOut->redirect( $this->mTitle->getFullURL() );
161 return;
162 }
163 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary, $this->minoredit, $this->watchthis );
164 return;
165 }
166
167 # Article exists. Check for edit conflict.
168
169 $this->mArticle->clear(); # Force reload of dates, etc.
170
171 if( ( $this->section != "new" ) &&
172 ($this->mArticle->getTimestamp() != $this->edittime ) ) {
173 $isConflict = true;
174 }
175 $userid = $wgUser->getID();
176
177 $text = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
178 $this->section, $this->textbox1, $this->summary);
179 # Suppress edit conflict with self
180
181 if ( ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
182 $isConflict = false;
183 } else {
184 # switch from section editing to normal editing in edit conflict
185 if($isConflict) {
186 # Attempt merge
187 if( $this->mergeChangesInto( $text ) ){
188 // Successful merge! Maybe we should tell the user the good news?
189 $isConflict = false;
190 } else {
191 $this->section = "";
192 $this->textbox1 = $text;
193 }
194 }
195 }
196 if ( ! $isConflict ) {
197 # All's well
198 $sectionanchor = '';
199 if( $this->section != '' ) {
200 # Try to get a section anchor from the section source, redirect to edited section if header found
201 # XXX: might be better to integrate this into Article::getTextOfLastEditWithSectionReplacedOrAdded
202 # for duplicate heading checking and maybe parsing
203 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
204 # we can't deal with anchors, includes, html etc in the header for now,
205 # headline would need to be parsed to improve this
206 #if($hasmatch and strlen($matches[2]) > 0 and !preg_match( "/[\\['{<>]/", $matches[2])) {
207 if($hasmatch and strlen($matches[2]) > 0) {
208 global $wgInputEncoding;
209 $headline = do_html_entity_decode( $matches[2], ENT_COMPAT, $wgInputEncoding );
210 # strip out HTML
211 $headline = preg_replace( "/<.*?" . ">/","",$headline );
212 $headline = trim( $headline );
213 $sectionanchor = '#'.urlencode( str_replace(' ', '_', $headline ) );
214 $replacearray = array(
215 '%3A' => ':',
216 '%' => '.'
217 );
218 $sectionanchor = str_replace(array_keys($replacearray),array_values($replacearray),$sectionanchor);
219 }
220 }
221
222 # update the article here
223 if($this->mArticle->updateArticle( $text, $this->summary, $this->minoredit, $this->watchthis, '', $sectionanchor ))
224 return;
225 else
226 $isConflict = true;
227 }
228 }
229 # First time through: get contents, set time for conflict
230 # checking, etc.
231
232 if ( "initial" == $formtype ) {
233 $this->edittime = $this->mArticle->getTimestamp();
234 $this->textbox1 = $this->mArticle->getContent( true );
235 $this->summary = "";
236 $this->proxyCheck();
237 }
238 $wgOut->setRobotpolicy( "noindex,nofollow" );
239
240 # Enabled article-related sidebar, toplinks, etc.
241 $wgOut->setArticleRelated( true );
242
243 if ( $isConflict ) {
244 $s = wfMsg( "editconflict", $this->mTitle->getPrefixedText() );
245 $wgOut->setPageTitle( $s );
246 $wgOut->addHTML( wfMsg( "explainconflict" ) );
247
248 $this->textbox2 = $this->textbox1;
249 $this->textbox1 = $this->mArticle->getContent( true );
250 $this->edittime = $this->mArticle->getTimestamp();
251 } else {
252 $s = wfMsg( "editing", $this->mTitle->getPrefixedText() );
253
254 if( $this->section != "" ) {
255 if( $this->section == "new" ) {
256 $s.=wfMsg("commentedit");
257 } else {
258 $s.=wfMsg("sectionedit");
259 }
260 if(!$this->preview) {
261 $sectitle=preg_match("/^=+(.*?)=+/mi",
262 $this->textbox1,
263 $matches);
264 if( !empty( $matches[1] ) ) {
265 $this->summary = "/* ". trim($matches[1])." */ ";
266 }
267 }
268 }
269 $wgOut->setPageTitle( $s );
270 if ( $this->oldid ) {
271 $this->mArticle->setOldSubtitle();
272 $wgOut->addHTML( wfMsg( "editingold" ) );
273 }
274 }
275
276 if( wfReadOnly() ) {
277 $wgOut->addHTML( "<strong>" .
278 wfMsg( "readonlywarning" ) .
279 "</strong>" );
280 } else if ( $isCssJsSubpage and "preview" != $formtype) {
281 $wgOut->addHTML( wfMsg( "usercssjsyoucanpreview" ));
282 }
283 if( $this->mTitle->isProtected() ) {
284 $wgOut->addHTML( "<strong>" . wfMsg( "protectedpagewarning" ) .
285 "</strong><br />\n" );
286 }
287
288 $kblength = (int)(strlen( $this->textbox1 ) / 1024);
289 if( $kblength > 29 ) {
290 $wgOut->addHTML( "<strong>" .
291 wfMsg( "longpagewarning", $kblength )
292 . "</strong>" );
293 }
294
295 $rows = $wgUser->getOption( "rows" );
296 $cols = $wgUser->getOption( "cols" );
297
298 $ew = $wgUser->getOption( "editwidth" );
299 if ( $ew ) $ew = " style=\"width:100%\"";
300 else $ew = "" ;
301
302 $q = "action=submit";
303 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
304 $action = $this->mTitle->escapeLocalURL( $q );
305
306 $summary = wfMsg( "summary" );
307 $subject = wfMsg("subject");
308 $minor = wfMsg( "minoredit" );
309 $watchthis = wfMsg ("watchthis");
310 $save = wfMsg( "savearticle" );
311 $prev = wfMsg( "showpreview" );
312
313 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
314 wfMsg( "cancel" ) );
315 $edithelpurl = $sk->makeUrl( wfMsg( 'edithelppage' ));
316 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
317 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
318 htmlspecialchars( wfMsg( 'newwindow' ) );
319 $copywarn = wfMsg( "copyrightwarning", $sk->makeKnownLink(
320 wfMsg( "copyrightpage" ) ) );
321
322 if( $wgUser->getOption("showtoolbar") and !$isCssJsSubpage ) {
323 # prepare toolbar for edit buttons
324 $toolbar = $sk->getEditToolbar();
325 } else {
326 $toolbar = "";
327 }
328
329 // activate checkboxes if user wants them to be always active
330 if( !$this->preview ) {
331 if( $wgUser->getOption( "watchdefault" ) ) $this->watchthis = true;
332 if( $wgUser->getOption( "minordefault" ) ) $this->minoredit = true;
333
334 // activate checkbox also if user is already watching the page,
335 // require wpWatchthis to be unset so that second condition is not
336 // checked unnecessarily
337 if( !$this->watchthis && $this->mTitle->userIsWatching() ) $this->watchthis = true;
338 }
339
340 $minoredithtml = "";
341
342 if ( 0 != $wgUser->getID() || $wgAllowAnonymousMinor ) {
343 $minoredithtml =
344 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
345 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
346 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
347 }
348
349 $watchhtml = "";
350
351 if ( 0 != $wgUser->getID() ) {
352 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".($this->watchthis?" checked='checked'":"").
353 " accesskey='".wfMsg('accesskey-watch')."' id='wpWatchthis' />".
354 "<label for='wpWatchthis' title='".wfMsg('tooltip-watch')."'>{$watchthis}</label>";
355 }
356
357 $checkboxhtml = $minoredithtml . $watchhtml . "<br />";
358
359 if ( "preview" == $formtype) {
360 $previewhead="<h2>" . wfMsg( "preview" ) . "</h2>\n<p><large><center><font color=\"#cc0000\">" .
361 wfMsg( "note" ) . wfMsg( "previewnote" ) . "</font></center></large></p>\n";
362 if ( $isConflict ) {
363 $previewhead.="<h2>" . wfMsg( "previewconflict" ) .
364 "</h2>\n";
365 }
366
367 $parserOptions = ParserOptions::newFromUser( $wgUser );
368 $parserOptions->setUseCategoryMagic( false );
369 $parserOptions->setEditSection( false );
370 $parserOptions->setEditSectionOnRightClick( false );
371 # don't parse user css/js, show message about preview
372 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
373 if ( $isCssJsSubpage ) {
374 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
375 $previewtext = wfMsg('usercsspreview');
376 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
377 $previewtext = wfMsg('userjspreview');
378 }
379 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
380 $wgOut->addHTML( $parserOutput->mText );
381 } else {
382 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $this->textbox1 ) ."\n\n",
383 $wgTitle, $parserOptions );
384 $previewHTML = $parserOutput->mText;
385
386 if($wgUser->getOption("previewontop")) {
387 $wgOut->addHTML($previewhead);
388 $wgOut->addHTML($previewHTML);
389 }
390 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
391 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
392 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
393 }
394 }
395
396 # if this is a comment, show a subject line at the top, which is also the edit summary.
397 # Otherwise, show a summary field at the bottom
398 $summarytext = htmlspecialchars( $wgLang->recodeForEdit( $this->summary ) ); # FIXME
399 if( $this->section == "new" ) {
400 $commentsubject="{$subject}: <input tabindex='1' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
401 $editsummary = "";
402 } else {
403 $commentsubject = "";
404 $editsummary="{$summary}: <input tabindex='3' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
405 }
406
407 if( !$this->preview ) {
408 # Don't select the edit box on preview; this interferes with seeing what's going on.
409 $wgOut->setOnloadHandler( "document.editform.wpTextbox1.focus()" );
410 }
411 $wgOut->addHTML( "
412 {$toolbar}
413 <form id=\"editform\" name=\"editform\" method=\"post\" action=\"$action\"
414 enctype=\"application/x-www-form-urlencoded\">
415 {$commentsubject}
416 <textarea tabindex='1' accesskey=\",\" name=\"wpTextbox1\" rows='{$rows}'
417 cols='{$cols}'{$ew}>" .
418 htmlspecialchars( $wgLang->recodeForEdit( $this->textbox1 ) ) .
419 "
420 </textarea>
421 <br />{$editsummary}
422 {$checkboxhtml}
423 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
424 " title=\"".wfMsg('tooltip-save')."\"/>
425 <input tabindex='6' id='wpPreview' type='submit' value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
426 " title=\"".wfMsg('tooltip-preview')."\"/>
427 <em>{$cancel}</em> | <em>{$edithelp}</em>
428 <br /><div id=\"editpage-copywarn\">{$copywarn}</div>
429 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
430 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
431
432 if ( $isConflict ) {
433 $wgOut->addHTML( "<h2>" . wfMsg( "yourdiff" ) . "</h2>\n" );
434 DifferenceEngine::showDiff( $this->textbox2, $this->textbox1,
435 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
436
437 $wgOut->addHTML( "<h2>" . wfMsg( "yourtext" ) . "</h2>
438 <textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
439 . htmlspecialchars( $wgLang->recodeForEdit( $this->textbox2 ) ) .
440 "
441 </textarea>" );
442 }
443 $wgOut->addHTML( "</form>\n" );
444 if($formtype =="preview" && !$wgUser->getOption("previewontop")) {
445 $wgOut->addHTML($previewhead);
446 $wgOut->addHTML($previewHTML);
447 }
448
449 }
450
451 function blockedIPpage()
452 {
453 global $wgOut, $wgUser, $wgLang, $wgIP;
454
455 $wgOut->setPageTitle( wfMsg( "blockedtitle" ) );
456 $wgOut->setRobotpolicy( "noindex,nofollow" );
457 $wgOut->setArticleRelated( false );
458
459 $id = $wgUser->blockedBy();
460 $reason = $wgUser->blockedFor();
461 $ip = $wgIP;
462
463 if ( is_string( $id ) ) {
464 $name = $id;
465 } else {
466 $name = User::whoIs( $id );
467 }
468 $link = "[[" . $wgLang->getNsText( Namespace::getUser() ) .
469 ":{$name}|{$name}]]";
470
471 $wgOut->addWikiText( wfMsg( "blockedtext", $link, $reason, $ip, $name ) );
472 $wgOut->returnToMain( false );
473 }
474
475
476
477 function userNotLoggedInPage()
478 {
479 global $wgOut, $wgUser, $wgLang;
480
481 $wgOut->setPageTitle( wfMsg( "whitelistedittitle" ) );
482 $wgOut->setRobotpolicy( "noindex,nofollow" );
483 $wgOut->setArticleRelated( false );
484
485 $wgOut->addWikiText( wfMsg( "whitelistedittext" ) );
486 $wgOut->returnToMain( false );
487 }
488
489 function spamPage()
490 {
491 global $wgOut;
492 $wgOut->setPageTitle( wfMsg( "spamprotectiontitle" ) );
493 $wgOut->setRobotpolicy( "noindex,nofollow" );
494 $wgOut->setArticleRelated( false );
495
496 $wgOut->addWikiText( wfMsg( "spamprotectiontext" ) );
497 $wgOut->returnToMain( false );
498 }
499
500 # Forks processes to scan the originating IP for an open proxy server
501 # MemCached can be used to skip IPs that have already been scanned
502 function proxyCheck()
503 {
504 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
505 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
506
507 if ( !$wgBlockOpenProxies ) {
508 return;
509 }
510
511 # Get MemCached key
512 $skip = false;
513 if ( $wgUseMemCached ) {
514 $mcKey = "$wgDBname:proxy:ip:$wgIP";
515 $mcValue = $wgMemc->get( $mcKey );
516 if ( $mcValue ) {
517 $skip = true;
518 }
519 }
520
521 # Fork the processes
522 if ( !$skip ) {
523 $title = Title::makeTitle( NS_SPECIAL, "Blockme" );
524 $iphash = md5( $wgIP . $wgProxyKey );
525 $url = $title->getFullURL( "ip=$iphash" );
526
527 foreach ( $wgProxyPorts as $port ) {
528 $params = implode( " ", array(
529 escapeshellarg( $wgProxyScriptPath ),
530 escapeshellarg( $wgIP ),
531 escapeshellarg( $port ),
532 escapeshellarg( $url )
533 ));
534 exec( "php $params &>/dev/null &" );
535 }
536 # Set MemCached key
537 if ( $wgUseMemCached ) {
538 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
539 }
540 }
541 }
542
543 /* private */ function mergeChangesInto( &$text ){
544 global $wgIsPg;
545 $oldDate = $this->edittime;
546 $res = wfQuery("SELECT cur_text FROM cur WHERE cur_id=" .
547 $this->mTitle->getArticleID() . " FOR UPDATE", DB_WRITE);
548 $obj = wfFetchObject($res);
549
550 $yourtext = $obj->cur_text;
551 $ns = $this->mTitle->getNamespace();
552 $title = wfStrencode( $this->mTitle->getDBkey() );
553 $oldtable=$wgIsPg?'"old"':'old';
554 $res = wfQuery("SELECT old_text,old_flags FROM $oldtable WHERE old_namespace = $ns AND ".
555 "old_title = '{$title}' AND old_timestamp = '{$oldDate}'", DB_WRITE);
556 $obj = wfFetchObject($res);
557 $oldText = Article::getRevisionText( $obj );
558
559 if(wfMerge($oldText, $text, $yourtext, $result)){
560 $text = $result;
561 return true;
562 } else {
563 return false;
564 }
565 }
566 }
567
568 ?>