fixed error handling broken since 1.96
[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
125 # Pre-fill content with error message so that if something
126 # fails we'll have something telling us what we intended.
127
128 $t = $this->mTitle->getPrefixedText();
129 if ( isset( $oldid ) ) {
130 $oldid = IntVal( $oldid );
131 $t .= ",oldid={$oldid}";
132 }
133 if ( isset( $redirect ) ) {
134 $redirect = ($redirect == "no") ? "no" : "yes";
135 $t .= ",redirect={$redirect}";
136 }
137 $this->mContent = wfMsg( "missingarticle", $t );
138
139 if ( ! $oldid ) { # Retrieve current version
140 $id = $this->getID();
141 if ( 0 == $id ) return;
142
143 $sql = "SELECT " .
144 "cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched " .
145 "FROM cur WHERE cur_id={$id}";
146 wfDebug( "$sql\n" );
147 $res = wfQuery( $sql, DB_READ, $fname );
148 if ( 0 == wfNumRows( $res ) ) {
149 return;
150 }
151
152 $s = wfFetchObject( $res );
153 # If we got a redirect, follow it (unless we've been told
154 # not to by either the function parameter or the query
155 if ( ( "no" != $redirect ) && ( false == $noredir ) &&
156 ( $wgMwRedir->matchStart( $s->cur_text ) ) ) {
157 if ( preg_match( "/\\[\\[([^\\]\\|]+)[\\]\\|]/",
158 $s->cur_text, $m ) ) {
159 $rt = Title::newFromText( $m[1] );
160 if( $rt ) {
161 # Gotta hand redirects to special pages differently:
162 # Fill the HTTP response "Location" header and ignore
163 # the rest of the page we're on.
164
165 if ( $rt->getInterwiki() != "" ) {
166 $wgOut->redirect( $rt->getFullURL() ) ;
167 return;
168 }
169 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
170 $wgOut->redirect( $rt->getFullURL() );
171 return;
172 }
173 $rid = $rt->getArticleID();
174 if ( 0 != $rid ) {
175 $sql = "SELECT cur_text,cur_timestamp,cur_user," .
176 "cur_counter,cur_restrictions,cur_touched FROM cur WHERE cur_id={$rid}";
177 $res = wfQuery( $sql, DB_READ, $fname );
178
179 if ( 0 != wfNumRows( $res ) ) {
180 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
181 $this->mTitle = $rt;
182 $s = wfFetchObject( $res );
183 }
184 }
185 }
186 }
187 }
188
189 $this->mContent = $s->cur_text;
190 $this->mUser = $s->cur_user;
191 $this->mCounter = $s->cur_counter;
192 $this->mTimestamp = $s->cur_timestamp;
193 $this->mTouched = $s->cur_touched;
194 $this->mTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
195 $this->mTitle->mRestrictionsLoaded = true;
196 wfFreeResult( $res );
197 } else { # oldid set, retrieve historical version
198 $sql = "SELECT old_text,old_timestamp,old_user,old_flags FROM old " .
199 "WHERE old_id={$oldid}";
200 $res = wfQuery( $sql, DB_READ, $fname );
201 if ( 0 == wfNumRows( $res ) ) { return; }
202
203 $s = wfFetchObject( $res );
204 $this->mContent = Article::getRevisionText( $s );
205 $this->mUser = $s->old_user;
206 $this->mCounter = 0;
207 $this->mTimestamp = $s->old_timestamp;
208 wfFreeResult( $res );
209 }
210 $this->mContentLoaded = true;
211 }
212
213 function getID() {
214 if( $this->mTitle ) {
215 return $this->mTitle->getArticleID();
216 } else {
217 return 0;
218 }
219 }
220
221 function getCount()
222 {
223 if ( -1 == $this->mCounter ) {
224 $id = $this->getID();
225 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
226 }
227 return $this->mCounter;
228 }
229
230 # Would the given text make this article a "good" article (i.e.,
231 # suitable for including in the article count)?
232
233 function isCountable( $text )
234 {
235 global $wgUseCommaCount, $wgMwRedir;
236
237 if ( 0 != $this->mTitle->getNamespace() ) { return 0; }
238 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
239 $token = ($wgUseCommaCount ? "," : "[[" );
240 if ( false === strstr( $text, $token ) ) { return 0; }
241 return 1;
242 }
243
244 # Loads everything from cur except cur_text
245 # This isn't necessary for all uses, so it's only done if needed.
246
247 /* private */ function loadLastEdit()
248 {
249 global $wgOut;
250 if ( -1 != $this->mUser ) return;
251
252 $sql = "SELECT cur_user,cur_user_text,cur_timestamp," .
253 "cur_comment,cur_minor_edit FROM cur WHERE " .
254 "cur_id=" . $this->getID();
255 $res = wfQuery( $sql, DB_READ, "Article::loadLastEdit" );
256
257 if ( wfNumRows( $res ) > 0 ) {
258 $s = wfFetchObject( $res );
259 $this->mUser = $s->cur_user;
260 $this->mUserText = $s->cur_user_text;
261 $this->mTimestamp = $s->cur_timestamp;
262 $this->mComment = $s->cur_comment;
263 $this->mMinorEdit = $s->cur_minor_edit;
264 }
265 }
266
267 function getTimestamp()
268 {
269 $this->loadLastEdit();
270 return $this->mTimestamp;
271 }
272
273 function getUser()
274 {
275 $this->loadLastEdit();
276 return $this->mUser;
277 }
278
279 function getUserText()
280 {
281 $this->loadLastEdit();
282 return $this->mUserText;
283 }
284
285 function getComment()
286 {
287 $this->loadLastEdit();
288 return $this->mComment;
289 }
290
291 function getMinorEdit()
292 {
293 $this->loadLastEdit();
294 return $this->mMinorEdit;
295 }
296
297 # This is the default action of the script: just view the page of
298 # the given title.
299
300 function view()
301 {
302 global $wgUser, $wgOut, $wgLang;
303 global $oldid, $diff, $printable; # From query
304 global $wgLinkCache, $IP, $wgEnableParserCache;
305
306 $fname = "Article::view";
307 wfProfileIn( $fname );
308
309 $wgOut->setArticleFlag( true );
310 $wgOut->setRobotpolicy( "index,follow" );
311
312 # If we got diff and oldid in the query, we want to see a
313 # diff page instead of the article.
314
315 if ( isset( $diff ) ) {
316 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
317 $de = new DifferenceEngine( $oldid, $diff );
318 $de->showDiffPage();
319 wfProfileOut( $fname );
320 return;
321 }
322
323 if ( !isset( $oldid ) and $this->checkTouched() ) {
324 if( $wgOut->checkLastModified( $this->mTouched ) ){
325 return;
326 } else if ( $this->tryFileCache() ) {
327 # tell wgOut that output is taken care of
328 $wgOut->disable();
329 $this->viewUpdates();
330 return;
331 }
332 }
333
334 $text = $this->getContent(); # May change mTitle
335 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
336 $wgOut->setHTMLTitle( $this->mTitle->getPrefixedText() .
337 " - " . wfMsg( "wikititlesuffix" ) );
338
339 # We're looking at an old revision
340
341 if ( $oldid ) {
342 $this->setOldSubtitle();
343 $wgOut->setRobotpolicy( "noindex,follow" );
344 }
345 if ( "" != $this->mRedirectedFrom ) {
346 $sk = $wgUser->getSkin();
347 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, "",
348 "redirect=no" );
349 $s = wfMsg( "redirectedfrom", $redir );
350 $wgOut->setSubtitle( $s );
351 }
352
353 $wgLinkCache->preFill( $this->mTitle );
354
355 if ( $printable == "yes" ) {
356 $wgOut->mParserOptions->setPrintable( true );
357 }
358
359 if( $wgEnableParserCache && intval($wgUser->getOption( "stubthreshold" )) == 0 ){
360 $wgOut->addWikiText( $text, true, $this );
361 } else {
362 $wgOut->addWikiText( $text );
363 }
364
365 # Add link titles as META keywords
366 $wgOut->addMetaTags() ;
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 $this->showArticle( $text, wfMsg( "newarticle" ) );
431 }
432
433
434 /* Side effects: loads last edit */
435 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = ""){
436 $this->loadLastEdit();
437 $oldtext = $this->getContent();
438 if ($section != "") {
439 if($section=="new") {
440 if($summary) $subject="== {$summary} ==\n\n";
441 $text=$oldtext."\n\n".$subject.$text;
442 } else {
443 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
444 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
445 $secs[$section*2]=$text."\n\n"; // replace with edited
446 if($section) { $secs[$section*2-1]=""; } // erase old headline
447 $text=join("",$secs);
448 }
449 }
450 return $text;
451 }
452
453 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false )
454 {
455 global $wgOut, $wgUser, $wgLinkCache;
456 global $wgDBtransactions, $wgMwRedir;
457 global $wgUseSquid, $wgInternalServer;
458 $fname = "Article::updateArticle";
459
460 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
461 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
462 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ")[^\\n]+)/i", $text, $m ) ) {
463 $redir = 1;
464 $text = $m[1] . "\n"; # Remove all content but redirect
465 }
466 else { $redir = 0; }
467
468 $text = $this->preSaveTransform( $text );
469
470 # Update article, but only if changed.
471
472 if( $wgDBtransactions ) {
473 $sql = "BEGIN";
474 wfQuery( $sql, DB_WRITE );
475 }
476 $oldtext = $this->getContent( true );
477
478 if ( 0 != strcmp( $text, $oldtext ) ) {
479 $this->mCountAdjustment = $this->isCountable( $text )
480 - $this->isCountable( $oldtext );
481
482 $now = wfTimestampNow();
483 $won = wfInvertTimestamp( $now );
484 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
485 "',cur_comment='" . wfStrencode( $summary ) .
486 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
487 ",cur_timestamp='{$now}',cur_user_text='" .
488 wfStrencode( $wgUser->getName() ) .
489 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
490 "WHERE cur_id=" . $this->getID() .
491 " AND cur_timestamp='" . $this->getTimestamp() . "'";
492 $res = wfQuery( $sql, DB_WRITE, $fname );
493
494 if( wfAffectedRows() == 0 ) {
495 /* Belated edit conflict! Run away!! */
496 return false;
497 }
498
499 # This overwrites $oldtext if revision compression is on
500 $flags = Article::compressRevisionText( $oldtext );
501
502 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
503 "old_comment,old_user,old_user_text,old_timestamp," .
504 "old_minor_edit,inverse_timestamp,old_flags) VALUES (" .
505 $this->mTitle->getNamespace() . ", '" .
506 wfStrencode( $this->mTitle->getDBkey() ) . "', '" .
507 wfStrencode( $oldtext ) . "', '" .
508 wfStrencode( $this->getComment() ) . "', " .
509 $this->getUser() . ", '" .
510 wfStrencode( $this->getUserText() ) . "', '" .
511 $this->getTimestamp() . "', " . $me1 . ", '" .
512 wfInvertTimestamp( $this->getTimestamp() ) . "','$flags')";
513 $res = wfQuery( $sql, DB_WRITE, $fname );
514 $oldid = wfInsertID( $res );
515
516 $bot = (int)($wgUser->isBot() || $forceBot);
517 RecentChange::notifyEdit( $now, $this->mTitle, $me2, $wgUser, $summary,
518 $oldid, $this->getTimestamp(), $bot );
519 Article::onArticleEdit( $this->mTitle );
520 }
521
522 if( $wgDBtransactions ) {
523 $sql = "COMMIT";
524 wfQuery( $sql, DB_WRITE );
525 }
526
527 if ($watchthis) {
528 if (!$this->mTitle->userIsWatching()) $this->watch();
529 } else {
530 if ( $this->mTitle->userIsWatching() ) {
531 $this->unwatch();
532 }
533 }
534 # standard deferred updates
535 $this->editUpdates( $text );
536
537
538 $urls = array();
539 # Template namespace
540 # Purge all articles linking here
541 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
542 $titles = $this->mTitle->getLinksTo();
543 Title::touchArray( $titles );
544 if ( $wgUseSquid ) {
545 foreach ( $titles as $title ) {
546 $urls[] = $title->getInternalURL();
547 }
548 }
549 }
550
551 # Squid updates
552 if ( $wgUseSquid ) {
553 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
554 $u = new SquidUpdate( $urls );
555 $u->doUpdate();
556 }
557
558 $this->showArticle( $text, wfMsg( "updated" ) );
559 return true;
560 }
561
562 # After we've either updated or inserted the article, update
563 # the link tables and redirect to the new page.
564
565 function showArticle( $text, $subtitle )
566 {
567 global $wgOut, $wgUser, $wgLinkCache;
568 global $wgMwRedir;
569
570 $wgLinkCache = new LinkCache();
571
572 # Get old version of link table to allow incremental link updates
573 $wgLinkCache->preFill( $this->mTitle );
574 $wgLinkCache->clear();
575
576 # Now update the link cache by parsing the text
577 $wgOut = new OutputPage();
578 $wgOut->addWikiText( $text );
579
580 if( $wgMwRedir->matchStart( $text ) )
581 $r = "redirect=no";
582 else
583 $r = "";
584 $wgOut->redirect( $this->mTitle->getFullURL( $r ) );
585 }
586
587 # Add this page to my watchlist
588
589 function watch( $add = true )
590 {
591 global $wgUser, $wgOut, $wgLang;
592 global $wgDeferredUpdateList;
593
594 if ( 0 == $wgUser->getID() ) {
595 $wgOut->errorpage( "watchnologin", "watchnologintext" );
596 return;
597 }
598 if ( wfReadOnly() ) {
599 $wgOut->readOnlyPage();
600 return;
601 }
602 if( $add )
603 $wgUser->addWatch( $this->mTitle );
604 else
605 $wgUser->removeWatch( $this->mTitle );
606
607 $wgOut->setPagetitle( wfMsg( $add ? "addedwatch" : "removedwatch" ) );
608 $wgOut->setRobotpolicy( "noindex,follow" );
609
610 $sk = $wgUser->getSkin() ;
611 $link = $sk->makeKnownLink ( $this->mTitle->getPrefixedText() ) ;
612
613 if($add)
614 $text = wfMsg( "addedwatchtext", $link );
615 else
616 $text = wfMsg( "removedwatchtext", $link );
617 $wgOut->addHTML( $text );
618
619 $up = new UserUpdate();
620 array_push( $wgDeferredUpdateList, $up );
621
622 $wgOut->returnToMain( false );
623 }
624
625 function unwatch()
626 {
627 $this->watch( false );
628 }
629
630 function protect( $limit = "sysop" )
631 {
632 global $wgUser, $wgOut;
633
634 if ( ! $wgUser->isSysop() ) {
635 $wgOut->sysopRequired();
636 return;
637 }
638 if ( wfReadOnly() ) {
639 $wgOut->readOnlyPage();
640 return;
641 }
642 $id = $this->mTitle->getArticleID();
643 if ( 0 == $id ) {
644 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
645 return;
646 }
647 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
648 "cur_restrictions='{$limit}' WHERE cur_id={$id}";
649 wfQuery( $sql, DB_WRITE, "Article::protect" );
650
651 $log = new LogPage( wfMsg( "protectlogpage" ), wfMsg( "protectlogtext" ) );
652 if ( $limit === "" ) {
653 $log->addEntry( wfMsg( "unprotectedarticle", $this->mTitle->getPrefixedText() ), "" );
654 } else {
655 $log->addEntry( wfMsg( "protectedarticle", $this->mTitle->getPrefixedText() ), "" );
656 }
657 $wgOut->redirect( $this->mTitle->getFullURL() );
658 }
659
660 function unprotect()
661 {
662 return $this->protect( "" );
663 }
664
665 function delete()
666 {
667 global $wgUser, $wgOut, $wgMessageCache;
668 global $wpConfirm, $wpReason, $image, $oldimage;
669 $fname = "Article::delete";
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 MediaWiki namespace
683 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
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 $blanked = false;
723 if($s->cur_text!="") {
724 $text=$s->cur_text;
725 } else {
726 if($old) {
727 $text = Article::getRevisionText( $old );
728 $blanked = true;
729 }
730
731 }
732
733 $length=strlen($text);
734
735 # this should not happen, since it is not possible to store an empty, new
736 # page. Let's insert a standard text in case it does, though
737 if($length==0 && !$wpReason) { $wpReason=wfmsg("exblank");}
738
739
740 if($length < 500 && !$wpReason) {
741
742 # comment field=255, let's grep the first 150 to have some user
743 # space left
744 $text=substr($text,0,150);
745 # let's strip out newlines and HTML tags
746 $text=preg_replace("/\"/","'",$text);
747 $text=preg_replace("/\</","&lt;",$text);
748 $text=preg_replace("/\>/","&gt;",$text);
749 $text=preg_replace("/[\n\r]/","",$text);
750 if(!$blanked) {
751 $wpReason=wfMsg("excontent"). " '".$text;
752 } else {
753 $wpReason=wfMsg("exbeforeblank") . " '".$text;
754 }
755 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
756 $wpReason.="'";
757 }
758 }
759
760 return $this->confirmDelete();
761 }
762
763 function confirmDelete( $par = "" )
764 {
765 global $wgOut;
766 global $wpReason;
767
768 wfDebug( "Article::confirmDelete\n" );
769
770 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
771 $wgOut->setSubtitle( wfMsg( "deletesub", $sub ) );
772 $wgOut->setRobotpolicy( "noindex,nofollow" );
773 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
774
775 $formaction = $this->mTitle->escapeLocalURL( "action=delete" . $par );
776
777 $confirm = wfMsg( "confirm" );
778 $check = wfMsg( "confirmcheck" );
779 $delcom = wfMsg( "deletecomment" );
780
781 $wgOut->addHTML( "
782 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
783 <table border=0><tr><td align=right>
784 {$delcom}:</td><td align=left>
785 <input type=text size=60 name=\"wpReason\" value=\"" . htmlspecialchars( $wpReason ) . "\">
786 </td></tr><tr><td>&nbsp;</td></tr>
787 <tr><td align=right>
788 <input type=checkbox name=\"wpConfirm\" value='1' id=\"wpConfirm\">
789 </td><td><label for=\"wpConfirm\">{$check}</label></td>
790 </tr><tr><td>&nbsp;</td><td>
791 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
792 </td></tr></table></form>\n" );
793
794 $wgOut->returnToMain( false );
795 }
796
797 function doDelete()
798 {
799 global $wgOut, $wgUser, $wgLang;
800 global $wpReason;
801 $fname = "Article::doDelete";
802 wfDebug( "$fname\n" );
803
804 if ( $this->doDeleteArticle() ) {
805 $deleted = $this->mTitle->getPrefixedText();
806
807 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
808 $wgOut->setRobotpolicy( "noindex,nofollow" );
809
810 $sk = $wgUser->getSkin();
811 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
812 Namespace::getWikipedia() ) .
813 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
814
815 $text = wfMsg( "deletedtext", $deleted, $loglink );
816
817 $wgOut->addHTML( "<p>" . $text );
818 $wgOut->returnToMain( false );
819 } else {
820 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
821 }
822 }
823
824 # Delete the article, returns success
825 function doDeleteArticle()
826 {
827 global $wgUser, $wgLang, $wgRequest;
828 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
829
830 $fname = "Article::doDeleteArticle";
831 wfDebug( "$fname\n" );
832
833 $ns = $this->mTitle->getNamespace();
834 $t = wfStrencode( $this->mTitle->getDBkey() );
835 $id = $this->mTitle->getArticleID();
836
837 if ( "" == $t || $id == 0 ) {
838 return false;
839 }
840
841 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
842 array_push( $wgDeferredUpdateList, $u );
843
844 $linksTo = $this->mTitle->getLinksTo();
845
846 # Squid purging
847 if ( $wgUseSquid ) {
848 $urls = array(
849 $this->mTitle->getInternalURL(),
850 $this->mTitle->getInternalURL( "history" )
851 );
852 foreach ( $linksTo as $linkTo ) {
853 $urls[] = $linkTo->getInternalURL();
854 }
855
856 $u = new SquidUpdate( $urls );
857 array_push( $wgDeferredUpdateList, $u );
858
859 }
860
861 # Client and file cache invalidation
862 Title::touchArray( $linksTo );
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 $t = wfStrencode( $this->mTitle->getPrefixedDBkey() );
895
896 Article::onArticleDelete( $this->mTitle );
897
898 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
899 $first = true;
900
901 foreach ( $linksTo as $titleObj ) {
902 if ( ! $first ) { $sql .= ","; }
903 $first = false;
904 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
905 $linkID = $titleObj->getArticleID();
906 $sql .= "({$linkID},'{$t}')";
907 }
908 if ( ! $first ) {
909 wfQuery( $sql, DB_WRITE, $fname );
910 }
911
912 $sql = "DELETE FROM links WHERE l_to={$id}";
913 wfQuery( $sql, DB_WRITE, $fname );
914
915 $sql = "DELETE FROM links WHERE l_from={$id}";
916 wfQuery( $sql, DB_WRITE, $fname );
917
918 $sql = "DELETE FROM imagelinks WHERE il_from={$id}";
919 wfQuery( $sql, DB_WRITE, $fname );
920
921 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
922 wfQuery( $sql, DB_WRITE, $fname );
923
924 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
925 $art = $this->mTitle->getPrefixedText();
926 $wpReason = $wgRequest->getText( "wpReason" );
927 $log->addEntry( wfMsg( "deletedarticle", $art ), $wpReason );
928
929 # Clear the cached article id so the interface doesn't act like we exist
930 $this->mTitle->resetArticleID( 0 );
931 $this->mTitle->mArticleID = 0;
932 return true;
933 }
934
935 function rollback()
936 {
937 global $wgUser, $wgLang, $wgOut, $wgRequest;
938
939 if ( ! $wgUser->isSysop() ) {
940 $wgOut->sysopRequired();
941 return;
942 }
943 if ( wfReadOnly() ) {
944 $wgOut->readOnlyPage( $this->getContent() );
945 return;
946 }
947
948 # Enhanced rollback, marks edits rc_bot=1
949 $bot = $wgRequest->getBool( 'bot' );
950
951 # Replace all this user's current edits with the next one down
952 $tt = wfStrencode( $this->mTitle->getDBKey() );
953 $n = $this->mTitle->getNamespace();
954
955 # Get the last editor
956 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
957 $res = wfQuery( $sql, DB_READ );
958 if( ($x = wfNumRows( $res )) != 1 ) {
959 # Something wrong
960 $wgOut->addHTML( wfMsg( "notanarticle" ) );
961 return;
962 }
963 $s = wfFetchObject( $res );
964 $ut = wfStrencode( $s->cur_user_text );
965 $uid = $s->cur_user;
966 $pid = $s->cur_id;
967
968 $from = str_replace( '_', ' ', $wgRequest->getVal( "from" ) );
969 if( $from != $s->cur_user_text ) {
970 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
971 $wgOut->addWikiText( wfMsg( "alreadyrolled",
972 htmlspecialchars( $this->mTitle->getPrefixedText()),
973 htmlspecialchars( $from ),
974 htmlspecialchars( $s->cur_user_text ) ) );
975 if($s->cur_comment != "") {
976 $wgOut->addHTML(
977 wfMsg("editcomment",
978 htmlspecialchars( $s->cur_comment ) ) );
979 }
980 return;
981 }
982
983 # Get the last edit not by this guy
984 $sql = "SELECT old_text,old_user,old_user_text,old_timestamp,old_flags
985 FROM old USE INDEX (name_title_timestamp)
986 WHERE old_namespace={$n} AND old_title='{$tt}'
987 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
988 ORDER BY inverse_timestamp LIMIT 1";
989 $res = wfQuery( $sql, DB_READ );
990 if( wfNumRows( $res ) != 1 ) {
991 # Something wrong
992 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
993 $wgOut->addHTML( wfMsg( "cantrollback" ) );
994 return;
995 }
996 $s = wfFetchObject( $res );
997
998 if ( $bot ) {
999 # Mark all reverted edits as bot
1000 $sql = "UPDATE recentchanges SET rc_bot=1 WHERE
1001 rc_cur_id=$pid AND rc_user=$uid AND rc_timestamp > '{$s->old_timestamp}'";
1002 wfQuery( $sql, DB_WRITE, $fname );
1003 }
1004
1005 # Save it!
1006 $newcomment = wfMsg( "revertpage", $s->old_user_text, $from );
1007 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1008 $wgOut->setRobotpolicy( "noindex,nofollow" );
1009 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
1010 $this->updateArticle( Article::getRevisionText( $s ), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1011 Article::onArticleEdit( $this->mTitle );
1012 $wgOut->returnToMain( false );
1013 }
1014
1015
1016 # Do standard deferred updates after page view
1017
1018 /* private */ function viewUpdates()
1019 {
1020 global $wgDeferredUpdateList;
1021 if ( 0 != $this->getID() ) {
1022 global $wgDisableCounters;
1023 if( !$wgDisableCounters ) {
1024 Article::incViewCount( $this->getID() );
1025 $u = new SiteStatsUpdate( 1, 0, 0 );
1026 array_push( $wgDeferredUpdateList, $u );
1027 }
1028 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
1029 $this->mTitle->getDBkey() );
1030 array_push( $wgDeferredUpdateList, $u );
1031 }
1032 }
1033
1034 # Do standard deferred updates after page edit.
1035 # Every 1000th edit, prune the recent changes table.
1036
1037 /* private */ function editUpdates( $text )
1038 {
1039 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1040 global $wgMessageCache;
1041
1042 wfSeedRandom();
1043 if ( 0 == mt_rand( 0, 999 ) ) {
1044 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1045 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1046 wfQuery( $sql, DB_WRITE );
1047 }
1048 $id = $this->getID();
1049 $title = $this->mTitle->getPrefixedDBkey();
1050 $shortTitle = $this->mTitle->getDBkey();
1051
1052 $adj = $this->mCountAdjustment;
1053
1054 if ( 0 != $id ) {
1055 $u = new LinksUpdate( $id, $title );
1056 array_push( $wgDeferredUpdateList, $u );
1057 $u = new SiteStatsUpdate( 0, 1, $adj );
1058 array_push( $wgDeferredUpdateList, $u );
1059 $u = new SearchUpdate( $id, $title, $text );
1060 array_push( $wgDeferredUpdateList, $u );
1061
1062 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle );
1063 array_push( $wgDeferredUpdateList, $u );
1064
1065 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1066 $wgMessageCache->replace( $shortTitle, $text );
1067 }
1068 }
1069 }
1070
1071 /* private */ function setOldSubtitle()
1072 {
1073 global $wgLang, $wgOut;
1074
1075 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1076 $r = wfMsg( "revisionasof", $td );
1077 $wgOut->setSubtitle( "({$r})" );
1078 }
1079
1080 # This function is called right before saving the wikitext,
1081 # so we can do things like signatures and links-in-context.
1082
1083 function preSaveTransform( $text )
1084 {
1085 global $wgParser, $wgUser;
1086 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
1087 }
1088
1089 /* Caching functions */
1090
1091 # checkLastModified returns true if it has taken care of all
1092 # output to the client that is necessary for this request.
1093 # (that is, it has sent a cached version of the page)
1094 function tryFileCache() {
1095 static $called = false;
1096 if( $called ) {
1097 wfDebug( " tryFileCache() -- called twice!?\n" );
1098 return;
1099 }
1100 $called = true;
1101 if($this->isFileCacheable()) {
1102 $touched = $this->mTouched;
1103 if( $this->mTitle->getPrefixedDBkey() == wfMsg( "mainpage" ) ) {
1104 # Expire the main page quicker
1105 $expire = wfUnix2Timestamp( time() - 3600 );
1106 $touched = max( $expire, $touched );
1107 }
1108 $cache = new CacheManager( $this->mTitle );
1109 if($cache->isFileCacheGood( $touched )) {
1110 global $wgOut;
1111 wfDebug( " tryFileCache() - about to load\n" );
1112 $cache->loadFromFileCache();
1113 return true;
1114 } else {
1115 wfDebug( " tryFileCache() - starting buffer\n" );
1116 ob_start( array(&$cache, 'saveToFileCache' ) );
1117 }
1118 } else {
1119 wfDebug( " tryFileCache() - not cacheable\n" );
1120 }
1121 }
1122
1123 function isFileCacheable() {
1124 global $wgUser, $wgUseFileCache, $wgShowIPinHeader;
1125 global $action, $oldid, $diff, $redirect, $printable;
1126 return $wgUseFileCache
1127 and (!$wgShowIPinHeader)
1128 and ($this->getID() != 0)
1129 and ($wgUser->getId() == 0)
1130 and (!$wgUser->getNewtalk())
1131 and ($this->mTitle->getNamespace() != Namespace::getSpecial())
1132 and ($action == "view")
1133 and (!isset($oldid))
1134 and (!isset($diff))
1135 and (!isset($redirect))
1136 and (!isset($printable))
1137 and (!$this->mRedirectedFrom);
1138 }
1139
1140 function checkTouched() {
1141 $id = $this->getID();
1142 $sql = "SELECT cur_touched,cur_is_redirect FROM cur WHERE cur_id=$id";
1143 $res = wfQuery( $sql, DB_READ, "Article::checkTouched" );
1144 if( $s = wfFetchObject( $res ) ) {
1145 $this->mTouched = $s->cur_touched;
1146 return !$s->cur_is_redirect;
1147 } else {
1148 return false;
1149 }
1150 }
1151
1152 /* static */ function incViewCount( $id )
1153 {
1154 $id = intval( $id );
1155 global $wgHitcounterUpdateFreq;
1156
1157 if( $wgHitcounterUpdateFreq <= 1 ){ //
1158 wfQuery("UPDATE cur SET cur_counter = cur_counter + 1 " .
1159 "WHERE cur_id = $id", DB_WRITE);
1160 return;
1161 }
1162
1163 # Not important enough to warrant an error page in case of failure
1164 $oldignore = wfIgnoreSQLErrors( true );
1165
1166 wfQuery("INSERT INTO hitcounter (hc_id) VALUES ({$id})", DB_WRITE);
1167
1168 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
1169 if( (rand() % $checkfreq != 0) or (wfLastErrno() != 0) ){
1170 # Most of the time (or on SQL errors), skip row count check
1171 wfIgnoreSQLErrors( $oldignore );
1172 return;
1173 }
1174
1175 $res = wfQuery("SELECT COUNT(*) as n FROM hitcounter", DB_WRITE);
1176 $row = wfFetchObject( $res );
1177 $rown = intval( $row->n );
1178 if( $rown >= $wgHitcounterUpdateFreq ){
1179 wfProfileIn( "Article::incViewCount-collect" );
1180 $old_user_abort = ignore_user_abort( true );
1181
1182 wfQuery("LOCK TABLES hitcounter WRITE", DB_WRITE);
1183 wfQuery("CREATE TEMPORARY TABLE acchits TYPE=HEAP ".
1184 "SELECT hc_id,COUNT(*) AS hc_n FROM hitcounter ".
1185 "GROUP BY hc_id", DB_WRITE);
1186 wfQuery("DELETE FROM hitcounter", DB_WRITE);
1187 wfQuery("UNLOCK TABLES", DB_WRITE);
1188 wfQuery("UPDATE cur,acchits SET cur_counter=cur_counter + hc_n ".
1189 "WHERE cur_id = hc_id", DB_WRITE);
1190 wfQuery("DROP TABLE acchits", DB_WRITE);
1191
1192 ignore_user_abort( $old_user_abort );
1193 wfProfileOut( "Article::incViewCount-collect" );
1194 }
1195 wfIgnoreSQLErrors( $oldignore );
1196 }
1197
1198 # The onArticle*() functions are supposed to be a kind of hooks
1199 # which should be called whenever any of the specified actions
1200 # are done.
1201 #
1202 # This is a good place to put code to clear caches, for instance.
1203
1204 # This is called on page move and undelete, as well as edit
1205 /* static */ function onArticleCreate($title_obj){
1206 global $wgEnablePersistentLC, $wgEnableParserCache, $wgUseSquid, $wgDeferredUpdateList;
1207
1208 $titles = $title_obj->getBrokenLinksTo();
1209
1210 # Purge squid
1211 if ( $wgUseSquid ) {
1212 $urls = $title_obj->getSquidURLs();
1213 foreach ( $titles as $linkTitle ) {
1214 $urls[] = $linkTitle->getInternalURL();
1215 }
1216 $u = new SquidUpdate( $urls );
1217 array_push( $wgDeferredUpdateList, $u );
1218 }
1219
1220 # Clear persistent link cache
1221 if ( $wgEnablePersistentLC ) {
1222 LinkCache::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1223 }
1224
1225 # Clear parser cache (not really used)
1226 if ( $wgEnableParserCache ) {
1227 OutputPage::parsercacheClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1228 }
1229 }
1230
1231 /* static */ function onArticleDelete($title_obj){
1232 global $wgEnablePersistentLC, $wgEnableParserCache;
1233 if ( $wgEnablePersistentLC ) {
1234 LinkCache::linksccClearLinksTo( $title_obj->getArticleID() );
1235 }
1236 if ( $wgEnableParserCache ) {
1237 OutputPage::parsercacheClearLinksTo( $title_obj->getArticleID() );
1238 }
1239 }
1240
1241 /* static */ function onArticleEdit($title_obj){
1242 global $wgEnablePersistentLC, $wgEnableParserCache;
1243 if ( $wgEnablePersistentLC ) {
1244 LinkCache::linksccClearPage( $title_obj->getArticleID() );
1245 }
1246 if ( $wgEnableParserCache ) {
1247 OutputPage::parsercacheClearPage( $title_obj->getArticleID(), $title_obj->getNamespace() );
1248 }
1249 }
1250 }
1251
1252 ?>