ffce076944f4ba647e6df34d2c0d67306b74b013
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 # Class representing a Wikipedia article and history.
3 # See design.doc for an overview.
4
5 # Note: edit user interface and cache support functions have been
6 # moved to separate EditPage and CacheManager classes.
7
8 include_once( "CacheManager.php" );
9
10 class Article {
11 /* private */ var $mContent, $mContentLoaded;
12 /* private */ var $mUser, $mTimestamp, $mUserText;
13 /* private */ var $mCounter, $mComment, $mCountAdjustment;
14 /* private */ var $mMinorEdit, $mRedirectedFrom;
15 /* private */ var $mTouched, $mFileCache, $mTitle;
16 /* private */ var $mId, $mTable;
17
18 function Article( &$title ) {
19 $this->mTitle =& $title;
20 $this->clear();
21 }
22
23 /* private */ function clear()
24 {
25 $this->mContentLoaded = false;
26 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
27 $this->mRedirectedFrom = $this->mUserText =
28 $this->mTimestamp = $this->mComment = $this->mFileCache = "";
29 $this->mCountAdjustment = 0;
30 $this->mTouched = "19700101000000";
31 }
32
33 /* static */ function getRevisionText( $row, $prefix = "old_" ) {
34 # Deal with optional compression of archived pages.
35 # This can be done periodically via maintenance/compressOld.php, and
36 # as pages are saved if $wgCompressRevisions is set.
37 $text = $prefix . "text";
38 $flags = $prefix . "flags";
39 if( isset( $row->$flags ) && (false !== strpos( $row->$flags, "gzip" ) ) ) {
40 return gzinflate( $row->$text );
41 }
42 if( isset( $row->$text ) ) {
43 return $row->$text;
44 }
45 return false;
46 }
47
48 /* static */ function compressRevisionText( &$text ) {
49 global $wgCompressRevisions;
50 if( !$wgCompressRevisions ) {
51 return "";
52 }
53 if( !function_exists( "gzdeflate" ) ) {
54 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
55 return "";
56 }
57 $text = gzdeflate( $text );
58 return "gzip";
59 }
60
61 # Note that getContent/loadContent may follow redirects if
62 # not told otherwise, and so may cause a change to mTitle.
63
64 # Return the text of this revision
65 function getContent( $noredir = false )
66 {
67 global $action,$section,$count; # From query string
68 $fname = "Article::getContent";
69 wfProfileIn( $fname );
70
71 if ( 0 == $this->getID() ) {
72 if ( "edit" == $action ) {
73 wfProfileOut( $fname );
74 return ""; # was "newarticletext", now moved above the box)
75 }
76 wfProfileOut( $fname );
77 return wfMsg( "noarticletext" );
78 } else {
79 $this->loadContent( $noredir );
80
81 if(
82 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
83 ( $this->mTitle->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
84 preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$this->mTitle->getText()) &&
85 $action=="view"
86 )
87 {
88 wfProfileOut( $fname );
89 return $this->mContent . "\n" .wfMsg("anontalkpagetext"); }
90 else {
91 if($action=="edit") {
92 if($section!="") {
93 if($section=="new") {
94 wfProfileOut( $fname );
95 return "";
96 }
97
98 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
99 $this->mContent, -1,
100 PREG_SPLIT_DELIM_CAPTURE);
101 if($section==0) {
102 wfProfileOut( $fname );
103 return trim($secs[0]);
104 } else {
105 wfProfileOut( $fname );
106 return trim($secs[$section*2-1] . $secs[$section*2]);
107 }
108 }
109 }
110 wfProfileOut( $fname );
111 return $this->mContent;
112 }
113 }
114 }
115
116 # Load the revision (including cur_text) into this object
117 function loadContent( $noredir = false )
118 {
119 global $wgOut, $wgMwRedir;
120 global $oldid, $redirect; # From query
121
122 if ( $this->mContentLoaded ) return;
123 $fname = "Article::loadContent";
124 $success = true;
125
126 if ( ! $oldid ) { # Retrieve current version
127 $id = $this->getID();
128 if ( 0 == $id ) return;
129
130 $sql = "SELECT " .
131 "cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched " .
132 "FROM cur WHERE cur_id={$id}";
133 wfDebug( "$sql\n" );
134 $res = wfQuery( $sql, DB_READ, $fname );
135 if ( 0 == wfNumRows( $res ) ) {
136 return;
137 }
138
139 $s = wfFetchObject( $res );
140 # If we got a redirect, follow it (unless we've been told
141 # not to by either the function parameter or the query
142 if ( ( "no" != $redirect ) && ( false == $noredir ) &&
143 ( $wgMwRedir->matchStart( $s->cur_text ) ) ) {
144 if ( preg_match( "/\\[\\[([^\\]\\|]+)[\\]\\|]/",
145 $s->cur_text, $m ) ) {
146 $rt = Title::newFromText( $m[1] );
147 if( $rt ) {
148 # Gotta hand redirects to special pages differently:
149 # Fill the HTTP response "Location" header and ignore
150 # the rest of the page we're on.
151
152 if ( $rt->getInterwiki() != "" ) {
153 $wgOut->redirect( $rt->getFullURL() ) ;
154 return;
155 }
156 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
157 $wgOut->redirect( $rt->getFullURL() );
158 return;
159 }
160 $rid = $rt->getArticleID();
161 if ( 0 != $rid ) {
162 $sql = "SELECT cur_text,cur_timestamp,cur_user," .
163 "cur_counter,cur_restrictions,cur_touched FROM cur WHERE cur_id={$rid}";
164 $res = wfQuery( $sql, DB_READ, $fname );
165
166 if ( 0 != wfNumRows( $res ) ) {
167 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
168 $this->mTitle = $rt;
169 $s = wfFetchObject( $res );
170 }
171 }
172 }
173 }
174 }
175
176 $this->mContent = $s->cur_text;
177 $this->mUser = $s->cur_user;
178 $this->mCounter = $s->cur_counter;
179 $this->mTimestamp = $s->cur_timestamp;
180 $this->mTouched = $s->cur_touched;
181 $this->mTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
182 $this->mTitle->mRestrictionsLoaded = true;
183 wfFreeResult( $res );
184 } else { # oldid set, retrieve historical version
185 $sql = "SELECT old_text,old_timestamp,old_user,old_flags FROM old " .
186 "WHERE old_id={$oldid}";
187 $res = wfQuery( $sql, DB_READ, $fname );
188 if ( 0 == wfNumRows( $res ) ) { return; }
189
190 $s = wfFetchObject( $res );
191 $this->mContent = Article::getRevisionText( $s );
192 $this->mUser = $s->old_user;
193 $this->mCounter = 0;
194 $this->mTimestamp = $s->old_timestamp;
195 wfFreeResult( $res );
196 }
197
198 # Return error message :P
199 # Horrible, confusing UI and data. I think this should return false on error -- TS
200 if ( !$success ) {
201 $t = $this->mTitle->getPrefixedText();
202 if ( isset( $oldid ) ) {
203 $oldid = IntVal( $oldid );
204 $t .= ",oldid={$oldid}";
205 }
206 if ( isset( $redirect ) ) {
207 $redirect = ($redirect == "no") ? "no" : "yes";
208 $t .= ",redirect={$redirect}";
209 }
210 $this->mContent = wfMsg( "missingarticle", $t );
211 }
212
213 $this->mContentLoaded = true;
214 }
215
216 function getID() {
217 if( $this->mTitle ) {
218 return $this->mTitle->getArticleID();
219 } else {
220 return 0;
221 }
222 }
223
224 function getCount()
225 {
226 if ( -1 == $this->mCounter ) {
227 $id = $this->getID();
228 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
229 }
230 return $this->mCounter;
231 }
232
233 # Would the given text make this article a "good" article (i.e.,
234 # suitable for including in the article count)?
235
236 function isCountable( $text )
237 {
238 global $wgUseCommaCount, $wgMwRedir;
239
240 if ( 0 != $this->mTitle->getNamespace() ) { return 0; }
241 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
242 $token = ($wgUseCommaCount ? "," : "[[" );
243 if ( false === strstr( $text, $token ) ) { return 0; }
244 return 1;
245 }
246
247 # Loads everything from cur except cur_text
248 # This isn't necessary for all uses, so it's only done if needed.
249
250 /* private */ function loadLastEdit()
251 {
252 global $wgOut;
253 if ( -1 != $this->mUser ) return;
254
255 $sql = "SELECT cur_user,cur_user_text,cur_timestamp," .
256 "cur_comment,cur_minor_edit FROM cur WHERE " .
257 "cur_id=" . $this->getID();
258 $res = wfQuery( $sql, DB_READ, "Article::loadLastEdit" );
259
260 if ( wfNumRows( $res ) > 0 ) {
261 $s = wfFetchObject( $res );
262 $this->mUser = $s->cur_user;
263 $this->mUserText = $s->cur_user_text;
264 $this->mTimestamp = $s->cur_timestamp;
265 $this->mComment = $s->cur_comment;
266 $this->mMinorEdit = $s->cur_minor_edit;
267 }
268 }
269
270 function getTimestamp()
271 {
272 $this->loadLastEdit();
273 return $this->mTimestamp;
274 }
275
276 function getUser()
277 {
278 $this->loadLastEdit();
279 return $this->mUser;
280 }
281
282 function getUserText()
283 {
284 $this->loadLastEdit();
285 return $this->mUserText;
286 }
287
288 function getComment()
289 {
290 $this->loadLastEdit();
291 return $this->mComment;
292 }
293
294 function getMinorEdit()
295 {
296 $this->loadLastEdit();
297 return $this->mMinorEdit;
298 }
299
300 # This is the default action of the script: just view the page of
301 # the given title.
302
303 function view()
304 {
305 global $wgUser, $wgOut, $wgLang;
306 global $oldid, $diff, $printable; # From query
307 global $wgLinkCache, $IP, $wgEnableParserCache;
308
309 $fname = "Article::view";
310 wfProfileIn( $fname );
311
312 $wgOut->setArticleFlag( true );
313 $wgOut->setRobotpolicy( "index,follow" );
314
315 # If we got diff and oldid in the query, we want to see a
316 # diff page instead of the article.
317
318 if ( isset( $diff ) ) {
319 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
320 $de = new DifferenceEngine( $oldid, $diff );
321 $de->showDiffPage();
322 wfProfileOut( $fname );
323 return;
324 }
325
326 if ( !isset( $oldid ) and $this->checkTouched() ) {
327 if( $wgOut->checkLastModified( $this->mTouched ) ){
328 return;
329 } else if ( $this->tryFileCache() ) {
330 # tell wgOut that output is taken care of
331 $wgOut->disable();
332 $this->viewUpdates();
333 return;
334 }
335 }
336
337 $text = $this->getContent(); # May change mTitle
338 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
339 $wgOut->setHTMLTitle( $this->mTitle->getPrefixedText() .
340 " - " . wfMsg( "wikititlesuffix" ) );
341
342 # We're looking at an old revision
343
344 if ( $oldid ) {
345 $this->setOldSubtitle();
346 $wgOut->setRobotpolicy( "noindex,follow" );
347 }
348 if ( "" != $this->mRedirectedFrom ) {
349 $sk = $wgUser->getSkin();
350 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, "",
351 "redirect=no" );
352 $s = wfMsg( "redirectedfrom", $redir );
353 $wgOut->setSubtitle( $s );
354 }
355
356 $wgLinkCache->preFill( $this->mTitle );
357
358 if ( $printable == "yes" ) {
359 $wgOut->mParserOptions->setPrintable( true );
360 }
361
362 if( $wgEnableParserCache && intval($wgUser->getOption( "stubthreshold" )) == 0 ){
363 $wgOut->addWikiText( $text, true, $this );
364 } else {
365 $wgOut->addWikiText( $text );
366 }
367
368 $this->viewUpdates();
369 wfProfileOut( $fname );
370 }
371
372 # Theoretically we could defer these whole insert and update
373 # functions for after display, but that's taking a big leap
374 # of faith, and we want to be able to report database
375 # errors at some point.
376
377 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
378 {
379 global $wgOut, $wgUser, $wgLinkCache, $wgMwRedir;
380 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
381
382 $fname = "Article::insertNewArticle";
383
384 $this->mCountAdjustment = $this->isCountable( $text );
385
386 $ns = $this->mTitle->getNamespace();
387 $ttl = $this->mTitle->getDBkey();
388 $text = $this->preSaveTransform( $text );
389 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
390 else { $redir = 0; }
391
392 $now = wfTimestampNow();
393 $won = wfInvertTimestamp( $now );
394 wfSeedRandom();
395 $rand = number_format( mt_rand() / mt_getrandmax(), 12, ".", "" );
396 $isminor = ( $isminor && $wgUser->getID() ) ? 1 : 0;
397 $sql = "INSERT INTO cur (cur_namespace,cur_title,cur_text," .
398 "cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter," .
399 "cur_restrictions,cur_user_text,cur_is_redirect," .
400 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$ns},'" . wfStrencode( $ttl ) . "', '" .
401 wfStrencode( $text ) . "', '" .
402 wfStrencode( $summary ) . "', '" .
403 $wgUser->getID() . "', '{$now}', " .
404 $isminor . ", 0, '', '" .
405 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
406 $res = wfQuery( $sql, DB_WRITE, $fname );
407
408 $newid = wfInsertId();
409 $this->mTitle->resetArticleID( $newid );
410
411 Article::onArticleCreate( $this->mTitle );
412 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary );
413
414 if ($watchthis) {
415 if(!$this->mTitle->userIsWatching()) $this->watch();
416 } else {
417 if ( $this->mTitle->userIsWatching() ) {
418 $this->unwatch();
419 }
420 }
421
422 # The talk page isn't in the regular link tables, so we need to update manually:
423 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
424 $sql = "UPDATE cur set cur_touched='$now' WHERE cur_namespace=$talkns AND cur_title='" . wfStrencode( $ttl ) . "'";
425 wfQuery( $sql, DB_WRITE );
426
427 # standard deferred updates
428 $this->editUpdates( $text );
429
430 # Squid purging
431 if ( $wgUseSquid ) {
432 $urlArr = Array(
433 $this->mTitle->getInternalURL(),
434 $this->mTitle->getInternalURL('action=history')
435 );
436 wfPurgeSquidServers($urlArr);
437 /* this needs to be done after LinksUpdate */
438 $u = new SquidUpdate($this->mTitle);
439 array_push( $wgDeferredUpdateList, $u );
440 }
441
442 $this->showArticle( $text, wfMsg( "newarticle" ) );
443 }
444
445
446 /* Side effects: loads last edit */
447 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = ""){
448 $this->loadLastEdit();
449 $oldtext = $this->getContent();
450 if ($section != "") {
451 if($section=="new") {
452 if($summary) $subject="== {$summary} ==\n\n";
453 $text=$oldtext."\n\n".$subject.$text;
454 } else {
455 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
456 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
457 $secs[$section*2]=$text."\n\n"; // replace with edited
458 if($section) { $secs[$section*2-1]=""; } // erase old headline
459 $text=join("",$secs);
460 }
461 }
462 return $text;
463 }
464
465 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false )
466 {
467 global $wgOut, $wgUser, $wgLinkCache;
468 global $wgDBtransactions, $wgMwRedir;
469 global $wgUseSquid, $wgInternalServer;
470 $fname = "Article::updateArticle";
471
472 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
473 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
474 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ")[^\\n]+)/i", $text, $m ) ) {
475 $redir = 1;
476 $text = $m[1] . "\n"; # Remove all content but redirect
477 }
478 else { $redir = 0; }
479
480 $text = $this->preSaveTransform( $text );
481
482 # Update article, but only if changed.
483
484 if( $wgDBtransactions ) {
485 $sql = "BEGIN";
486 wfQuery( $sql, DB_WRITE );
487 }
488 $oldtext = $this->getContent( true );
489
490 if ( 0 != strcmp( $text, $oldtext ) ) {
491 $this->mCountAdjustment = $this->isCountable( $text )
492 - $this->isCountable( $oldtext );
493
494 $now = wfTimestampNow();
495 $won = wfInvertTimestamp( $now );
496 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
497 "',cur_comment='" . wfStrencode( $summary ) .
498 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
499 ",cur_timestamp='{$now}',cur_user_text='" .
500 wfStrencode( $wgUser->getName() ) .
501 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
502 "WHERE cur_id=" . $this->getID() .
503 " AND cur_timestamp='" . $this->getTimestamp() . "'";
504 $res = wfQuery( $sql, DB_WRITE, $fname );
505
506 if( wfAffectedRows() == 0 ) {
507 /* Belated edit conflict! Run away!! */
508 return false;
509 }
510
511 # This overwrites $oldtext if revision compression is on
512 $flags = Article::compressRevisionText( $oldtext );
513
514 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
515 "old_comment,old_user,old_user_text,old_timestamp," .
516 "old_minor_edit,inverse_timestamp,old_flags) VALUES (" .
517 $this->mTitle->getNamespace() . ", '" .
518 wfStrencode( $this->mTitle->getDBkey() ) . "', '" .
519 wfStrencode( $oldtext ) . "', '" .
520 wfStrencode( $this->getComment() ) . "', " .
521 $this->getUser() . ", '" .
522 wfStrencode( $this->getUserText() ) . "', '" .
523 $this->getTimestamp() . "', " . $me1 . ", '" .
524 wfInvertTimestamp( $this->getTimestamp() ) . "','$flags')";
525 $res = wfQuery( $sql, DB_WRITE, $fname );
526 $oldid = wfInsertID( $res );
527
528 $bot = (int)($wgUser->isBot() || $forceBot);
529 RecentChange::notifyEdit( $now, $this->mTitle, $me2, $wgUser, $summary,
530 $oldid, $this->getTimestamp(), $bot );
531 Article::onArticleEdit( $this->mTitle );
532 }
533
534 if( $wgDBtransactions ) {
535 $sql = "COMMIT";
536 wfQuery( $sql, DB_WRITE );
537 }
538
539 if ($watchthis) {
540 if (!$this->mTitle->userIsWatching()) $this->watch();
541 } else {
542 if ( $this->mTitle->userIsWatching() ) {
543 $this->unwatch();
544 }
545 }
546 # standard deferred updates
547 $this->editUpdates( $text );
548
549 # Squid updates
550
551 if ( $wgUseSquid ) {
552 $urlArr = Array(
553 $this->mTitle->getInternalURL(),
554 $this->mTitle->getInternalURL('action=history')
555 );
556 wfPurgeSquidServers($urlArr);
557 }
558
559 $this->showArticle( $text, wfMsg( "updated" ) );
560 return true;
561 }
562
563 # After we've either updated or inserted the article, update
564 # the link tables and redirect to the new page.
565
566 function showArticle( $text, $subtitle )
567 {
568 global $wgOut, $wgUser, $wgLinkCache;
569 global $wgMwRedir;
570
571 $wgLinkCache = new LinkCache();
572
573 # Get old version of link table to allow incremental link updates
574 $wgLinkCache->preFill( $this->mTitle );
575 $wgLinkCache->clear();
576
577 # Now update the link cache by parsing the text
578 $wgOut = new OutputPage();
579 $wgOut->addWikiText( $text );
580
581 if( $wgMwRedir->matchStart( $text ) )
582 $r = "redirect=no";
583 else
584 $r = "";
585 $wgOut->redirect( $this->mTitle->getFullURL( $r ) );
586 }
587
588 # Add this page to my watchlist
589
590 function watch( $add = true )
591 {
592 global $wgUser, $wgOut, $wgLang;
593 global $wgDeferredUpdateList;
594
595 if ( 0 == $wgUser->getID() ) {
596 $wgOut->errorpage( "watchnologin", "watchnologintext" );
597 return;
598 }
599 if ( wfReadOnly() ) {
600 $wgOut->readOnlyPage();
601 return;
602 }
603 if( $add )
604 $wgUser->addWatch( $this->mTitle );
605 else
606 $wgUser->removeWatch( $this->mTitle );
607
608 $wgOut->setPagetitle( wfMsg( $add ? "addedwatch" : "removedwatch" ) );
609 $wgOut->setRobotpolicy( "noindex,follow" );
610
611 $sk = $wgUser->getSkin() ;
612 $link = $sk->makeKnownLink ( $this->mTitle->getPrefixedText() ) ;
613
614 if($add)
615 $text = wfMsg( "addedwatchtext", $link );
616 else
617 $text = wfMsg( "removedwatchtext", $link );
618 $wgOut->addHTML( $text );
619
620 $up = new UserUpdate();
621 array_push( $wgDeferredUpdateList, $up );
622
623 $wgOut->returnToMain( false );
624 }
625
626 function unwatch()
627 {
628 $this->watch( false );
629 }
630
631 function protect( $limit = "sysop" )
632 {
633 global $wgUser, $wgOut;
634
635 if ( ! $wgUser->isSysop() ) {
636 $wgOut->sysopRequired();
637 return;
638 }
639 if ( wfReadOnly() ) {
640 $wgOut->readOnlyPage();
641 return;
642 }
643 $id = $this->mTitle->getArticleID();
644 if ( 0 == $id ) {
645 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
646 return;
647 }
648 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
649 "cur_restrictions='{$limit}' WHERE cur_id={$id}";
650 wfQuery( $sql, DB_WRITE, "Article::protect" );
651
652 $log = new LogPage( wfMsg( "protectlogpage" ), wfMsg( "protectlogtext" ) );
653 if ( $limit === "" ) {
654 $log->addEntry( wfMsg( "unprotectedarticle", $this->mTitle->getPrefixedText() ), "" );
655 } else {
656 $log->addEntry( wfMsg( "protectedarticle", $this->mTitle->getPrefixedText() ), "" );
657 }
658 $wgOut->redirect( $this->mTitle->getFullURL() );
659 }
660
661 function unprotect()
662 {
663 return $this->protect( "" );
664 }
665
666 function delete()
667 {
668 global $wgUser, $wgOut, $wgMessageCache;
669 global $wpConfirm, $wpReason, $image, $oldimage;
670
671 # This code desperately needs to be totally rewritten
672
673 if ( ( ! $wgUser->isSysop() ) ) {
674 $wgOut->sysopRequired();
675 return;
676 }
677 if ( wfReadOnly() ) {
678 $wgOut->readOnlyPage();
679 return;
680 }
681
682 # Can't delete cached MediaWiki namespace (i.e. vital messages)
683 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $wgMessageCache->isCacheable( $this->mTitle->getDBkey() ) ) {
684 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
685 return;
686 }
687
688 # Better double-check that it hasn't been deleted yet!
689 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
690 if ( ( "" == trim( $this->mTitle->getText() ) )
691 or ( $this->mTitle->getArticleId() == 0 ) ) {
692 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
693 return;
694 }
695
696 if ( $_POST["wpConfirm"] ) {
697 $this->doDelete();
698 return;
699 }
700
701 # determine whether this page has earlier revisions
702 # and insert a warning if it does
703 # we select the text because it might be useful below
704 $ns = $this->mTitle->getNamespace();
705 $title = $this->mTitle->getDBkey();
706 $etitle = wfStrencode( $title );
707 $sql = "SELECT old_text,old_flags FROM old WHERE old_namespace=$ns and old_title='$etitle' ORDER BY inverse_timestamp LIMIT 1";
708 $res = wfQuery( $sql, DB_READ, $fname );
709 if( ($old=wfFetchObject($res)) && !$wpConfirm ) {
710 $skin=$wgUser->getSkin();
711 $wgOut->addHTML("<B>".wfMsg("historywarning"));
712 $wgOut->addHTML( $skin->historyLink() ."</B><P>");
713 }
714
715 $sql="SELECT cur_text FROM cur WHERE cur_namespace=$ns and cur_title='$etitle'";
716 $res=wfQuery($sql, DB_READ, $fname);
717 if( ($s=wfFetchObject($res))) {
718
719 # if this is a mini-text, we can paste part of it into the deletion reason
720
721 #if this is empty, an earlier revision may contain "useful" text
722 if($s->cur_text!="") {
723 $text=$s->cur_text;
724 } else {
725 if($old) {
726 $text = Article::getRevisionText( $old );
727 $blanked=1;
728 }
729
730 }
731
732 $length=strlen($text);
733
734 # this should not happen, since it is not possible to store an empty, new
735 # page. Let's insert a standard text in case it does, though
736 if($length==0 && !$wpReason) { $wpReason=wfmsg("exblank");}
737
738
739 if($length < 500 && !$wpReason) {
740
741 # comment field=255, let's grep the first 150 to have some user
742 # space left
743 $text=substr($text,0,150);
744 # let's strip out newlines and HTML tags
745 $text=preg_replace("/\"/","'",$text);
746 $text=preg_replace("/\</","&lt;",$text);
747 $text=preg_replace("/\>/","&gt;",$text);
748 $text=preg_replace("/[\n\r]/","",$text);
749 if(!$blanked) {
750 $wpReason=wfMsg("excontent"). " '".$text;
751 } else {
752 $wpReason=wfMsg("exbeforeblank") . " '".$text;
753 }
754 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
755 $wpReason.="'";
756 }
757 }
758
759 return $this->confirmDelete();
760 }
761
762 function confirmDelete( $par = "" )
763 {
764 global $wgOut;
765 global $wpReason;
766
767 wfDebug( "Article::confirmDelete\n" );
768
769 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
770 $wgOut->setSubtitle( wfMsg( "deletesub", $sub ) );
771 $wgOut->setRobotpolicy( "noindex,nofollow" );
772 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
773
774 $formaction = $this->mTitle->escapeLocalURL( "action=delete" . $par );
775
776 $confirm = wfMsg( "confirm" );
777 $check = wfMsg( "confirmcheck" );
778 $delcom = wfMsg( "deletecomment" );
779
780 $wgOut->addHTML( "
781 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
782 <table border=0><tr><td align=right>
783 {$delcom}:</td><td align=left>
784 <input type=text size=60 name=\"wpReason\" value=\"" . htmlspecialchars( $wpReason ) . "\">
785 </td></tr><tr><td>&nbsp;</td></tr>
786 <tr><td align=right>
787 <input type=checkbox name=\"wpConfirm\" value='1' id=\"wpConfirm\">
788 </td><td><label for=\"wpConfirm\">{$check}</label></td>
789 </tr><tr><td>&nbsp;</td><td>
790 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
791 </td></tr></table></form>\n" );
792
793 $wgOut->returnToMain( false );
794 }
795
796 function doDelete()
797 {
798 global $wgOut, $wgUser, $wgLang;
799 global $wpReason;
800 $fname = "Article::doDelete";
801 wfDebug( "$fname\n" );
802
803 $this->doDeleteArticle( $this->mTitle );
804 $deleted = $this->mTitle->getPrefixedText();
805
806 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
807 $wgOut->setRobotpolicy( "noindex,nofollow" );
808
809 $sk = $wgUser->getSkin();
810 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
811 Namespace::getWikipedia() ) .
812 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
813
814 $text = wfMsg( "deletedtext", $deleted, $loglink );
815
816 $wgOut->addHTML( "<p>" . $text );
817 $wgOut->returnToMain( false );
818 }
819
820 function doDeleteArticle( $title )
821 {
822 global $wgUser, $wgOut, $wgLang, $wgRequest;
823 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
824
825 $fname = "Article::doDeleteArticle";
826 wfDebug( "$fname\n" );
827
828 $ns = $title->getNamespace();
829 $t = wfStrencode( $title->getDBkey() );
830 $id = $title->getArticleID();
831
832 if ( "" == $t ) {
833 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
834 return;
835 }
836
837 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
838 array_push( $wgDeferredUpdateList, $u );
839
840 # Squid purging
841 if ( $wgUseSquid ) {
842 $urlArr = Array(
843 $this->mTitle->getInternalURL(),
844 $this->mTitle->getInternalURL('action=history')
845 );
846 wfPurgeSquidServers($urlArr);
847
848 /* prepare the list of urls to purge */
849 $sql = "SELECT cur_namespace,cur_title FROM links,cur WHERE l_to={$id} and l_from=cur_id" ;
850 $res = wfQuery ( $sql, DB_READ ) ;
851 while ( $BL = wfFetchObject ( $res ) )
852 {
853 $tobj = Title::MakeTitle( $BL->cur_namespace, $BL->cur_title ) ;
854 $blurlArr[] = $tobj->getInternalURL();
855 }
856 wfFreeResult ( $res ) ;
857 $u = new SquidUpdate( $this->mTitle, $blurlArr );
858 array_push( $wgDeferredUpdateList, $u );
859
860 }
861
862
863
864 # Move article and history to the "archive" table
865 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
866 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
867 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
868 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
869 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
870 wfQuery( $sql, DB_WRITE, $fname );
871
872 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
873 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
874 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
875 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
876 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
877 wfQuery( $sql, DB_WRITE, $fname );
878
879 # Now that it's safely backed up, delete it
880
881 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
882 "cur_title='{$t}'";
883 wfQuery( $sql, DB_WRITE, $fname );
884
885 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
886 "old_title='{$t}'";
887 wfQuery( $sql, DB_WRITE, $fname );
888
889 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
890 "rc_title='{$t}'";
891 wfQuery( $sql, DB_WRITE, $fname );
892
893 # Finally, clean up the link tables
894
895 if ( 0 != $id ) {
896
897 $t = wfStrencode( $title->getPrefixedDBkey() );
898
899 Article::onArticleDelete( $title );
900
901 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
902 $res = wfQuery( $sql, DB_READ, $fname );
903
904 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
905 $now = wfTimestampNow();
906 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
907 $first = true;
908
909 while ( $s = wfFetchObject( $res ) ) {
910 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
911 $first = false;
912 $sql .= "({$s->l_from},'{$t}')";
913 $sql2 .= "{$s->l_from}";
914 }
915 $sql2 .= ")";
916 if ( ! $first ) {
917 wfQuery( $sql, DB_WRITE, $fname );
918 wfQuery( $sql2, DB_WRITE, $fname );
919 }
920 wfFreeResult( $res );
921
922 $sql = "DELETE FROM links WHERE l_to={$id}";
923 wfQuery( $sql, DB_WRITE, $fname );
924
925 $sql = "DELETE FROM links WHERE l_from={$id}";
926 wfQuery( $sql, DB_WRITE, $fname );
927
928 $sql = "DELETE FROM imagelinks WHERE il_from={$d}";
929 wfQuery( $sql, DB_WRITE, $fname );
930
931 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
932 wfQuery( $sql, DB_WRITE, $fname );
933 }
934
935 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
936 $art = $title->getPrefixedText();
937 $wpReason = $wgRequest->getText( "wpReason" );
938 $log->addEntry( wfMsg( "deletedarticle", $art ), $wpReason );
939
940 # Clear the cached article id so the interface doesn't act like we exist
941 $this->mTitle->resetArticleID( 0 );
942 $this->mTitle->mArticleID = 0;
943 }
944
945 function rollback()
946 {
947 global $wgUser, $wgLang, $wgOut, $wgRequest;
948
949 if ( ! $wgUser->isSysop() ) {
950 $wgOut->sysopRequired();
951 return;
952 }
953 if ( wfReadOnly() ) {
954 $wgOut->readOnlyPage( $this->getContent() );
955 return;
956 }
957
958 # Enhanced rollback, marks edits rc_bot=1
959 $bot = $wgRequest->getBool( 'bot' );
960
961 # Replace all this user's current edits with the next one down
962 $tt = wfStrencode( $this->mTitle->getDBKey() );
963 $n = $this->mTitle->getNamespace();
964
965 # Get the last editor
966 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
967 $res = wfQuery( $sql, DB_READ );
968 if( ($x = wfNumRows( $res )) != 1 ) {
969 # Something wrong
970 $wgOut->addHTML( wfMsg( "notanarticle" ) );
971 return;
972 }
973 $s = wfFetchObject( $res );
974 $ut = wfStrencode( $s->cur_user_text );
975 $uid = $s->cur_user;
976 $pid = $s->cur_id;
977
978 $from = str_replace( '_', ' ', $wgRequest->getVal( "from" ) );
979 if( $from != $s->cur_user_text ) {
980 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
981 $wgOut->addWikiText( wfMsg( "alreadyrolled",
982 htmlspecialchars( $this->mTitle->getPrefixedText()),
983 htmlspecialchars( $from ),
984 htmlspecialchars( $s->cur_user_text ) ) );
985 if($s->cur_comment != "") {
986 $wgOut->addHTML(
987 wfMsg("editcomment",
988 htmlspecialchars( $s->cur_comment ) ) );
989 }
990 return;
991 }
992
993 # Get the last edit not by this guy
994 $sql = "SELECT old_text,old_user,old_user_text,old_timestamp,old_flags
995 FROM old USE INDEX (name_title_timestamp)
996 WHERE old_namespace={$n} AND old_title='{$tt}'
997 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
998 ORDER BY inverse_timestamp LIMIT 1";
999 $res = wfQuery( $sql, DB_READ );
1000 if( wfNumRows( $res ) != 1 ) {
1001 # Something wrong
1002 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
1003 $wgOut->addHTML( wfMsg( "cantrollback" ) );
1004 return;
1005 }
1006 $s = wfFetchObject( $res );
1007
1008 if ( $bot ) {
1009 # Mark all reverted edits as bot
1010 $sql = "UPDATE recentchanges SET rc_bot=1 WHERE
1011 rc_cur_id=$pid AND rc_user=$uid AND rc_timestamp > '{$s->old_timestamp}'";
1012 wfQuery( $sql, DB_WRITE, $fname );
1013 }
1014
1015 # Save it!
1016 $newcomment = wfMsg( "revertpage", $s->old_user_text, $from );
1017 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1018 $wgOut->setRobotpolicy( "noindex,nofollow" );
1019 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
1020 $this->updateArticle( Article::getRevisionText( $s ), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1021 Article::onArticleEdit( $this->mTitle );
1022 $wgOut->returnToMain( false );
1023 }
1024
1025
1026 # Do standard deferred updates after page view
1027
1028 /* private */ function viewUpdates()
1029 {
1030 global $wgDeferredUpdateList;
1031 if ( 0 != $this->getID() ) {
1032 global $wgDisableCounters;
1033 if( !$wgDisableCounters ) {
1034 Article::incViewCount( $this->getID() );
1035 $u = new SiteStatsUpdate( 1, 0, 0 );
1036 array_push( $wgDeferredUpdateList, $u );
1037 }
1038 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
1039 $this->mTitle->getDBkey() );
1040 array_push( $wgDeferredUpdateList, $u );
1041 }
1042 }
1043
1044 # Do standard deferred updates after page edit.
1045 # Every 1000th edit, prune the recent changes table.
1046
1047 /* private */ function editUpdates( $text )
1048 {
1049 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1050 global $wgMessageCache;
1051
1052 wfSeedRandom();
1053 if ( 0 == mt_rand( 0, 999 ) ) {
1054 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1055 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1056 wfQuery( $sql, DB_WRITE );
1057 }
1058 $id = $this->getID();
1059 $title = $this->mTitle->getPrefixedDBkey();
1060 $shortTitle = $this->mTitle->getDBkey();
1061
1062 $adj = $this->mCountAdjustment;
1063
1064 if ( 0 != $id ) {
1065 $u = new LinksUpdate( $id, $title );
1066 array_push( $wgDeferredUpdateList, $u );
1067 $u = new SiteStatsUpdate( 0, 1, $adj );
1068 array_push( $wgDeferredUpdateList, $u );
1069 $u = new SearchUpdate( $id, $title, $text );
1070 array_push( $wgDeferredUpdateList, $u );
1071
1072 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle );
1073 array_push( $wgDeferredUpdateList, $u );
1074
1075 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1076 $wgMessageCache->replace( $shortTitle, $text );
1077 }
1078 }
1079 }
1080
1081 /* private */ function setOldSubtitle()
1082 {
1083 global $wgLang, $wgOut;
1084
1085 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1086 $r = wfMsg( "revisionasof", $td );
1087 $wgOut->setSubtitle( "({$r})" );
1088 }
1089
1090 # This function is called right before saving the wikitext,
1091 # so we can do things like signatures and links-in-context.
1092
1093 function preSaveTransform( $text )
1094 {
1095 global $wgParser, $wgUser;
1096 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
1097 }
1098
1099 /* Caching functions */
1100
1101 # checkLastModified returns true iff it has taken care of all
1102 # output to the client that is necessary for this request.
1103 # (that is, it has sent a cached version of the page)
1104 function tryFileCache() {
1105 static $called = false;
1106 if( $called ) {
1107 wfDebug( " tryFileCache() -- called twice!?\n" );
1108 return;
1109 }
1110 $called = true;
1111 if($this->isFileCacheable()) {
1112 $touched = $this->mTouched;
1113 if( $this->mTitle->getPrefixedDBkey() == wfMsg( "mainpage" ) ) {
1114 # Expire the main page quicker
1115 $expire = wfUnix2Timestamp( time() - 3600 );
1116 $touched = max( $expire, $touched );
1117 }
1118 $cache = new CacheManager( $this->mTitle );
1119 if($cache->isFileCacheGood( $touched )) {
1120 global $wgOut;
1121 wfDebug( " tryFileCache() - about to load\n" );
1122 $cache->loadFromFileCache();
1123 return true;
1124 } else {
1125 wfDebug( " tryFileCache() - starting buffer\n" );
1126 ob_start( array(&$cache, 'saveToFileCache' ) );
1127 }
1128 } else {
1129 wfDebug( " tryFileCache() - not cacheable\n" );
1130 }
1131 }
1132
1133 function isFileCacheable() {
1134 global $wgUser, $wgUseFileCache, $wgShowIPinHeader;
1135 global $action, $oldid, $diff, $redirect, $printable;
1136 return $wgUseFileCache
1137 and (!$wgShowIPinHeader)
1138 and ($this->getID() != 0)
1139 and ($wgUser->getId() == 0)
1140 and (!$wgUser->getNewtalk())
1141 and ($this->mTitle->getNamespace() != Namespace::getSpecial())
1142 and ($action == "view")
1143 and (!isset($oldid))
1144 and (!isset($diff))
1145 and (!isset($redirect))
1146 and (!isset($printable))
1147 and (!$this->mRedirectedFrom);
1148 }
1149
1150 function checkTouched() {
1151 $id = $this->getID();
1152 $sql = "SELECT cur_touched,cur_is_redirect FROM cur WHERE cur_id=$id";
1153 $res = wfQuery( $sql, DB_READ, "Article::checkTouched" );
1154 if( $s = wfFetchObject( $res ) ) {
1155 $this->mTouched = $s->cur_touched;
1156 return !$s->cur_is_redirect;
1157 } else {
1158 return false;
1159 }
1160 }
1161
1162 /* static */ function incViewCount( $id )
1163 {
1164 $id = intval( $id );
1165 global $wgHitcounterUpdateFreq;
1166
1167 if( $wgHitcounterUpdateFreq <= 1 ){ //
1168 wfQuery("UPDATE cur SET cur_counter = cur_counter + 1 " .
1169 "WHERE cur_id = $id", DB_WRITE);
1170 return;
1171 }
1172
1173 # Not important enough to warrant an error page in case of failure
1174 $oldignore = wfIgnoreSQLErrors( true );
1175
1176 wfQuery("INSERT INTO hitcounter (hc_id) VALUES ({$id})", DB_WRITE);
1177
1178 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
1179 if( (rand() % $checkfreq != 0) or (wfLastErrno() != 0) ){
1180 # Most of the time (or on SQL errors), skip row count check
1181 wfIgnoreSQLErrors( $oldignore );
1182 return;
1183 }
1184
1185 $res = wfQuery("SELECT COUNT(*) as n FROM hitcounter", DB_WRITE);
1186 $row = wfFetchObject( $res );
1187 $rown = intval( $row->n );
1188 if( $rown >= $wgHitcounterUpdateFreq ){
1189 wfProfileIn( "Article::incViewCount-collect" );
1190 $old_user_abort = ignore_user_abort( true );
1191
1192 wfQuery("LOCK TABLES hitcounter WRITE", DB_WRITE);
1193 wfQuery("CREATE TEMPORARY TABLE acchits TYPE=HEAP ".
1194 "SELECT hc_id,COUNT(*) AS hc_n FROM hitcounter ".
1195 "GROUP BY hc_id", DB_WRITE);
1196 wfQuery("DELETE FROM hitcounter", DB_WRITE);
1197 wfQuery("UNLOCK TABLES", DB_WRITE);
1198 wfQuery("UPDATE cur,acchits SET cur_counter=cur_counter + hc_n ".
1199 "WHERE cur_id = hc_id", DB_WRITE);
1200 wfQuery("DROP TABLE acchits", DB_WRITE);
1201
1202 ignore_user_abort( $old_user_abort );
1203 wfProfileOut( "Article::incViewCount-collect" );
1204 }
1205 wfIgnoreSQLErrors( $oldignore );
1206 }
1207
1208 # The onArticle*() functions are supposed to be a kind of hooks
1209 # which should be called whenever any of the specified actions
1210 # are done.
1211 #
1212 # This is a good place to put code to clear caches, for instance.
1213
1214 /* static */ function onArticleCreate($title_obj){
1215 global $wgEnablePersistentLC, $wgEnableParserCache;
1216 if ( $wgEnablePersistentLC ) {
1217 LinkCache::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1218 }
1219 if ( $wgEnableParserCache ) {
1220 OutputPage::parsercacheClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1221 }
1222 }
1223
1224 /* static */ function onArticleDelete($title_obj){
1225 global $wgEnablePersistentLC, $wgEnableParserCache;
1226 if ( $wgEnablePersistentLC ) {
1227 LinkCache::linksccClearLinksTo( $title_obj->getArticleID() );
1228 }
1229 if ( $wgEnableParserCache ) {
1230 OutputPage::parsercacheClearLinksTo( $title_obj->getArticleID() );
1231 }
1232 }
1233
1234 /* static */ function onArticleEdit($title_obj){
1235 global $wgEnablePersistentLC, $wgEnableParserCache;
1236 if ( $wgEnablePersistentLC ) {
1237 LinkCache::linksccClearPage( $title_obj->getArticleID() );
1238 }
1239 if ( $wgEnableParserCache ) {
1240 OutputPage::parsercacheClearPage( $title_obj->getArticleID(), $title_obj->getNamespace() );
1241 }
1242 }
1243 }
1244
1245 function wfReplaceSubstVar( $matches ) {
1246 return wfMsg( $matches[1] );
1247 }
1248
1249 ?>