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