bug fix
[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 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 ) );
214 }
215 }
216
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;
222 }
223 }
224 # First time through: get contents, set time for conflict
225 # checking, etc.
226
227 if ( "initial" == $formtype ) {
228 $this->edittime = $this->mArticle->getTimestamp();
229 $this->textbox1 = $this->mArticle->getContent( true );
230 $this->summary = "";
231 $this->proxyCheck();
232 }
233 $wgOut->setRobotpolicy( "noindex,nofollow" );
234
235 # Enabled article-related sidebar, toplinks, etc.
236 $wgOut->setArticleRelated( true );
237
238 if ( $isConflict ) {
239 $s = wfMsg( "editconflict", $this->mTitle->getPrefixedText() );
240 $wgOut->setPageTitle( $s );
241 $wgOut->addHTML( wfMsg( "explainconflict" ) );
242
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() );
248
249 if( $this->section != "" ) {
250 if( $this->section == "new" ) {
251 $s.=wfMsg("commentedit");
252 } else {
253 $s.=wfMsg("sectionedit");
254 }
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])." */ ";
261 }
262 }
263 }
264 $wgOut->setPageTitle( $s );
265 if ( $this->oldid ) {
266 $this->mArticle->setOldSubtitle();
267 $wgOut->addHTML( wfMsg( "editingold" ) );
268 }
269 }
270
271 if( wfReadOnly() ) {
272 $wgOut->addHTML( "<strong>" .
273 wfMsg( "readonlywarning" ) .
274 "</strong>" );
275 } else if ( $isCssJsSubpage and "preview" != $formtype) {
276 $wgOut->addHTML( wfMsg( "usercssjsyoucanpreview" ));
277 }
278 if( $this->mTitle->isProtected() ) {
279 $wgOut->addHTML( "<strong>" . wfMsg( "protectedpagewarning" ) .
280 "</strong><br />\n" );
281 }
282
283 $kblength = (int)(strlen( $this->textbox1 ) / 1024);
284 if( $kblength > 29 ) {
285 $wgOut->addHTML( "<strong>" .
286 wfMsg( "longpagewarning", $kblength )
287 . "</strong>" );
288 }
289
290 $rows = $wgUser->getOption( "rows" );
291 $cols = $wgUser->getOption( "cols" );
292
293 $ew = $wgUser->getOption( "editwidth" );
294 if ( $ew ) $ew = " style=\"width:100%\"";
295 else $ew = "" ;
296
297 $q = "action=submit";
298 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
299 $action = $this->mTitle->escapeLocalURL( $q );
300
301 $summary = wfMsg( "summary" );
302 $subject = wfMsg("subject");
303 $minor = wfMsg( "minoredit" );
304 $watchthis = wfMsg ("watchthis");
305 $save = wfMsg( "savearticle" );
306 $prev = wfMsg( "showpreview" );
307
308 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedURL(),
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" ) ) );
316
317 if( $wgUser->getOption("showtoolbar") and !$isCssJsSubpage ) {
318 # prepare toolbar for edit buttons
319 $toolbar = $sk->getEditToolbar();
320 } else {
321 $toolbar = "";
322 }
323
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;
328
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;
333 }
334
335 $minoredithtml = "";
336
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>";
342 }
343
344 $watchhtml = "";
345
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>";
350 }
351
352 $checkboxhtml = $minoredithtml . $watchhtml . "<br />";
353
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";
360 }
361
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');
373 }
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;
380
381 if($wgUser->getOption("previewontop")) {
382 $wgOut->addHTML($previewhead);
383 $wgOut->addHTML($previewHTML);
384 }
385 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
386 }
387 }
388
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 />";
398 }
399
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()" );
403 }
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 ) ) .
412 "
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" );
424
425 if ( $isConflict ) {
426 $wgOut->addHTML( "<h2>" . wfMsg( "yourdiff" ) . "</h2>\n" );
427 DifferenceEngine::showDiff( $this->textbox2, $this->textbox1,
428 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
429
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 ) ) .
433 "
434 </textarea>" );
435 }
436 $wgOut->addHTML( "</form>\n" );
437 if($formtype =="preview" && !$wgUser->getOption("previewontop")) {
438 $wgOut->addHTML($previewhead);
439 $wgOut->addHTML($previewHTML);
440 }
441
442 }
443
444 function blockedIPpage()
445 {
446 global $wgOut, $wgUser, $wgLang, $wgIP;
447
448 $wgOut->setPageTitle( wfMsg( "blockedtitle" ) );
449 $wgOut->setRobotpolicy( "noindex,nofollow" );
450 $wgOut->setArticleRelated( false );
451
452 $id = $wgUser->blockedBy();
453 $reason = $wgUser->blockedFor();
454 $ip = $wgIP;
455
456 $name = User::whoIs( $id );
457 $link = "[[" . $wgLang->getNsText( Namespace::getUser() ) .
458 ":{$name}|{$name}]]";
459
460 $wgOut->addWikiText( wfMsg( "blockedtext", $link, $reason, $ip, $name ) );
461 $wgOut->returnToMain( false );
462 }
463
464
465
466 function userNotLoggedInPage()
467 {
468 global $wgOut, $wgUser, $wgLang;
469
470 $wgOut->setPageTitle( wfMsg( "whitelistedittitle" ) );
471 $wgOut->setRobotpolicy( "noindex,nofollow" );
472 $wgOut->setArticleRelated( false );
473
474 $wgOut->addWikiText( wfMsg( "whitelistedittext" ) );
475 $wgOut->returnToMain( false );
476 }
477
478 function spamPage()
479 {
480 global $wgOut, $wgSpamRegex;
481 $wgOut->setPageTitle( wfMsg( "spamprotectiontitle" ) );
482 $wgOut->setRobotpolicy( "noindex,nofollow" );
483 $wgOut->setArticleRelated( false );
484
485 $wgOut->addWikiText( wfMsg( "spamprotectiontext" ) );
486 $wgOut->addWikiText( "<pre>".$wgSpamRegex."</pre>" );
487 $wgOut->returnToMain( false );
488 }
489
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()
493 {
494 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
495 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
496
497 if ( !$wgBlockOpenProxies ) {
498 return;
499 }
500
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;
508 }
509 }
510
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" );
516
517 foreach ( $wgProxyPorts as $port ) {
518 $params = implode( " ", array(
519 escapeshellarg( $wgProxyScriptPath ),
520 escapeshellarg( $wgIP ),
521 escapeshellarg( $port ),
522 escapeshellarg( $url )
523 ));
524 exec( "php $params &>/dev/null &" );
525 }
526 # Set MemCached key
527 if ( $wgUseMemCached ) {
528 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
529 }
530 }
531 }
532
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);
538
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 );
546
547 if(wfMerge($oldText, $text, $yourtext, $result)){
548 $text = $result;
549 return true;
550 } else {
551 return false;
552 }
553 }
554 }
555
556 ?>