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