ids on submits
[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;
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 if ( $wgUser->isSysop() ) {
135 $this->spamPage();
136 } else {
137 sleep(10);
138 $wgOut->redirect( $this->mTitle->getFullURL() );
139 }
140 return;
141 }
142 if ( $wgUser->isBlocked() ) {
143 $this->blockedIPpage();
144 return;
145 }
146 if ( !$wgUser->getID() && $wgWhitelistEdit ) {
147 $this->userNotLoggedInPage();
148 return;
149 }
150 if ( wfReadOnly() ) {
151 $wgOut->readOnlyPage();
152 return;
153 }
154
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;
163 }
164 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary, $this->minoredit, $this->watchthis );
165 return;
166 }
167
168 # Article exists. Check for edit conflict.
169
170 $this->mArticle->clear(); # Force reload of dates, etc.
171
172 if( ( $this->section != "new" ) &&
173 ($this->mArticle->getTimestamp() != $this->edittime ) ) {
174 $isConflict = true;
175 }
176 $userid = $wgUser->getID();
177
178 $text = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
179 $this->section, $this->textbox1, $this->summary);
180 # Suppress edit conflict with self
181
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;
194 }
195 }
196 }
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 if($hasmatch and strlen($matches[2]) > 0) {
209 global $wgInputEncoding;
210 $headline = do_html_entity_decode( $matches[2], ENT_COMPAT, $wgInputEncoding );
211 # strip out HTML
212 $headline = preg_replace( "/<.*?" . ">/","",$headline );
213 $headline = trim( $headline );
214 $sectionanchor = '#'.urlencode( str_replace(' ', '_', $headline ) );
215 $replacearray = array(
216 '%3A' => ':',
217 '%' => '.'
218 );
219 $sectionanchor = str_replace(array_keys($replacearray),array_values($replacearray),$sectionanchor);
220 }
221 }
222
223 # update the article here
224 if($this->mArticle->updateArticle( $text, $this->summary, $this->minoredit, $this->watchthis, '', $sectionanchor ))
225 return;
226 else
227 $isConflict = true;
228 }
229 }
230 # First time through: get contents, set time for conflict
231 # checking, etc.
232
233 if ( "initial" == $formtype ) {
234 $this->edittime = $this->mArticle->getTimestamp();
235 $this->textbox1 = $this->mArticle->getContent( true );
236 $this->summary = "";
237 $this->proxyCheck();
238 }
239 $wgOut->setRobotpolicy( "noindex,nofollow" );
240
241 # Enabled article-related sidebar, toplinks, etc.
242 $wgOut->setArticleRelated( true );
243
244 if ( $isConflict ) {
245 $s = wfMsg( "editconflict", $this->mTitle->getPrefixedText() );
246 $wgOut->setPageTitle( $s );
247 $wgOut->addHTML( wfMsg( "explainconflict" ) );
248
249 $this->textbox2 = $this->textbox1;
250 $this->textbox1 = $this->mArticle->getContent( true );
251 $this->edittime = $this->mArticle->getTimestamp();
252 } else {
253 $s = wfMsg( "editing", $this->mTitle->getPrefixedText() );
254
255 if( $this->section != "" ) {
256 if( $this->section == "new" ) {
257 $s.=wfMsg("commentedit");
258 } else {
259 $s.=wfMsg("sectionedit");
260 }
261 if(!$this->preview) {
262 $sectitle=preg_match("/^=+(.*?)=+/mi",
263 $this->textbox1,
264 $matches);
265 if( !empty( $matches[1] ) ) {
266 $this->summary = "/* ". trim($matches[1])." */ ";
267 }
268 }
269 }
270 $wgOut->setPageTitle( $s );
271 if ( $this->oldid ) {
272 $this->mArticle->setOldSubtitle();
273 $wgOut->addHTML( wfMsg( "editingold" ) );
274 }
275 }
276
277 if( wfReadOnly() ) {
278 $wgOut->addHTML( "<strong>" .
279 wfMsg( "readonlywarning" ) .
280 "</strong>" );
281 } else if ( $isCssJsSubpage and "preview" != $formtype) {
282 $wgOut->addHTML( wfMsg( "usercssjsyoucanpreview" ));
283 }
284 if( $this->mTitle->isProtected() ) {
285 $wgOut->addHTML( "<strong>" . wfMsg( "protectedpagewarning" ) .
286 "</strong><br />\n" );
287 }
288
289 $kblength = (int)(strlen( $this->textbox1 ) / 1024);
290 if( $kblength > 29 ) {
291 $wgOut->addHTML( "<strong>" .
292 wfMsg( "longpagewarning", $kblength )
293 . "</strong>" );
294 }
295
296 $rows = $wgUser->getOption( "rows" );
297 $cols = $wgUser->getOption( "cols" );
298
299 $ew = $wgUser->getOption( "editwidth" );
300 if ( $ew ) $ew = " style=\"width:100%\"";
301 else $ew = "" ;
302
303 $q = "action=submit";
304 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
305 $action = $this->mTitle->escapeLocalURL( $q );
306
307 $summary = wfMsg( "summary" );
308 $subject = wfMsg("subject");
309 $minor = wfMsg( "minoredit" );
310 $watchthis = wfMsg ("watchthis");
311 $save = wfMsg( "savearticle" );
312 $prev = wfMsg( "showpreview" );
313
314 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
315 wfMsg( "cancel" ) );
316 $edithelpurl = $sk->makeUrl( wfMsg( 'edithelppage' ));
317 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
318 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
319 htmlspecialchars( wfMsg( 'newwindow' ) );
320 $copywarn = wfMsg( "copyrightwarning", $sk->makeKnownLink(
321 wfMsg( "copyrightpage" ) ) );
322
323 if( $wgUser->getOption("showtoolbar") and !$isCssJsSubpage ) {
324 # prepare toolbar for edit buttons
325 $toolbar = $sk->getEditToolbar();
326 } else {
327 $toolbar = "";
328 }
329
330 // activate checkboxes if user wants them to be always active
331 if( !$this->preview ) {
332 if( $wgUser->getOption( "watchdefault" ) ) $this->watchthis = true;
333 if( $wgUser->getOption( "minordefault" ) ) $this->minoredit = true;
334
335 // activate checkbox also if user is already watching the page,
336 // require wpWatchthis to be unset so that second condition is not
337 // checked unnecessarily
338 if( !$this->watchthis && $this->mTitle->userIsWatching() ) $this->watchthis = true;
339 }
340
341 $minoredithtml = "";
342
343 if ( 0 != $wgUser->getID() || $wgAllowAnonymousMinor ) {
344 $minoredithtml =
345 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
346 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
347 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
348 }
349
350 $watchhtml = "";
351
352 if ( 0 != $wgUser->getID() ) {
353 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".($this->watchthis?" checked='checked'":"").
354 " accesskey='".wfMsg('accesskey-watch')."' id='wpWatchthis' />".
355 "<label for='wpWatchthis' title='".wfMsg('tooltip-watch')."'>{$watchthis}</label>";
356 }
357
358 $checkboxhtml = $minoredithtml . $watchhtml . "<br />";
359
360 if ( "preview" == $formtype) {
361 $previewhead="<h2>" . wfMsg( "preview" ) . "</h2>\n<p><large><center><font color=\"#cc0000\">" .
362 wfMsg( "note" ) . wfMsg( "previewnote" ) . "</font></center></large></p>\n";
363 if ( $isConflict ) {
364 $previewhead.="<h2>" . wfMsg( "previewconflict" ) .
365 "</h2>\n";
366 }
367
368 $parserOptions = ParserOptions::newFromUser( $wgUser );
369 $parserOptions->setUseCategoryMagic( false );
370 $parserOptions->setEditSection( false );
371 $parserOptions->setEditSectionOnRightClick( false );
372 # don't parse user css/js, show message about preview
373 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
374 if ( $isCssJsSubpage ) {
375 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
376 $previewtext = wfMsg('usercsspreview');
377 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
378 $previewtext = wfMsg('userjspreview');
379 }
380 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
381 $wgOut->addHTML( $parserOutput->mText );
382 } else {
383 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $this->textbox1 ) ."\n\n",
384 $wgTitle, $parserOptions );
385 $previewHTML = $parserOutput->mText;
386
387 if($wgUser->getOption("previewontop")) {
388 $wgOut->addHTML($previewhead);
389 $wgOut->addHTML($previewHTML);
390 }
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='wpSave' type='submit' value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
426 " title=\"".wfMsg('tooltip-preview')."\"/>
427 <em>{$cancel}</em> | <em>{$edithelp}</em>
428 <br /><br />{$copywarn}
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 $name = User::whoIs( $id );
464 $link = "[[" . $wgLang->getNsText( Namespace::getUser() ) .
465 ":{$name}|{$name}]]";
466
467 $wgOut->addWikiText( wfMsg( "blockedtext", $link, $reason, $ip, $name ) );
468 $wgOut->returnToMain( false );
469 }
470
471
472
473 function userNotLoggedInPage()
474 {
475 global $wgOut, $wgUser, $wgLang;
476
477 $wgOut->setPageTitle( wfMsg( "whitelistedittitle" ) );
478 $wgOut->setRobotpolicy( "noindex,nofollow" );
479 $wgOut->setArticleRelated( false );
480
481 $wgOut->addWikiText( wfMsg( "whitelistedittext" ) );
482 $wgOut->returnToMain( false );
483 }
484
485 function spamPage()
486 {
487 global $wgOut, $wgSpamRegex;
488 $wgOut->setPageTitle( wfMsg( "spamprotectiontitle" ) );
489 $wgOut->setRobotpolicy( "noindex,nofollow" );
490 $wgOut->setArticleRelated( false );
491
492 $wgOut->addWikiText( wfMsg( "spamprotectiontext" ) );
493 $wgOut->addWikiText( "<pre>".$wgSpamRegex."</pre>" );
494 $wgOut->returnToMain( false );
495 }
496
497 # Forks processes to scan the originating IP for an open proxy server
498 # MemCached can be used to skip IPs that have already been scanned
499 function proxyCheck()
500 {
501 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
502 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
503
504 if ( !$wgBlockOpenProxies ) {
505 return;
506 }
507
508 # Get MemCached key
509 $skip = false;
510 if ( $wgUseMemCached ) {
511 $mcKey = "$wgDBname:proxy:ip:$wgIP";
512 $mcValue = $wgMemc->get( $mcKey );
513 if ( $mcValue ) {
514 $skip = true;
515 }
516 }
517
518 # Fork the processes
519 if ( !$skip ) {
520 $title = Title::makeTitle( NS_SPECIAL, "Blockme" );
521 $iphash = md5( $wgIP . $wgProxyKey );
522 $url = $title->getFullURL( "ip=$iphash" );
523
524 foreach ( $wgProxyPorts as $port ) {
525 $params = implode( " ", array(
526 escapeshellarg( $wgProxyScriptPath ),
527 escapeshellarg( $wgIP ),
528 escapeshellarg( $port ),
529 escapeshellarg( $url )
530 ));
531 exec( "php $params &>/dev/null &" );
532 }
533 # Set MemCached key
534 if ( $wgUseMemCached ) {
535 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
536 }
537 }
538 }
539
540 /* private */ function mergeChangesInto( &$text ){
541 $oldDate = $this->edittime;
542 $res = wfQuery("SELECT cur_text FROM cur WHERE cur_id=" .
543 $this->mTitle->getArticleID() . " FOR UPDATE", DB_WRITE);
544 $obj = wfFetchObject($res);
545
546 $yourtext = $obj->cur_text;
547 $ns = $this->mTitle->getNamespace();
548 $title = wfStrencode( $this->mTitle->getDBkey() );
549 $res = wfQuery("SELECT old_text,old_flags FROM old WHERE old_namespace = $ns AND ".
550 "old_title = '{$title}' AND old_timestamp = '{$oldDate}'", DB_WRITE);
551 $obj = wfFetchObject($res);
552 $oldText = Article::getRevisionText( $obj );
553
554 if(wfMerge($oldText, $text, $yourtext, $result)){
555 $text = $result;
556 return true;
557 } else {
558 return false;
559 }
560 }
561 }
562
563 ?>