Some changes to the link tables. They now all use a key on cur_id for the *_from...
[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 function updateArticle( $text, $summary, $minor, $watchthis, $section = "", $forceBot = false )
446 {
447 global $wgOut, $wgUser, $wgLinkCache;
448 global $wgDBtransactions, $wgMwRedir;
449 global $wgUseSquid, $wgInternalServer;
450 $fname = "Article::updateArticle";
451
452 $this->loadLastEdit();
453
454 // insert updated section into old text if we have only edited part
455 // of the article
456 if ($section != "") {
457 $oldtext=$this->getContent();
458 if($section=="new") {
459 if($summary) $subject="== {$summary} ==\n\n";
460 $text=$oldtext."\n\n".$subject.$text;
461 } else {
462 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
463 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
464 $secs[$section*2]=$text."\n\n"; // replace with edited
465 if($section) { $secs[$section*2-1]=""; } // erase old headline
466 $text=join("",$secs);
467 }
468 }
469 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
470 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
471 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ")[^\\n]+)/i", $text, $m ) ) {
472 $redir = 1;
473 $text = $m[1] . "\n"; # Remove all content but redirect
474 }
475 else { $redir = 0; }
476
477 $text = $this->preSaveTransform( $text );
478
479 # Update article, but only if changed.
480
481 if( $wgDBtransactions ) {
482 $sql = "BEGIN";
483 wfQuery( $sql, DB_WRITE );
484 }
485 $oldtext = $this->getContent( true );
486
487 if ( 0 != strcmp( $text, $oldtext ) ) {
488 $this->mCountAdjustment = $this->isCountable( $text )
489 - $this->isCountable( $oldtext );
490
491 $now = wfTimestampNow();
492 $won = wfInvertTimestamp( $now );
493 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
494 "',cur_comment='" . wfStrencode( $summary ) .
495 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
496 ",cur_timestamp='{$now}',cur_user_text='" .
497 wfStrencode( $wgUser->getName() ) .
498 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
499 "WHERE cur_id=" . $this->getID() .
500 " AND cur_timestamp='" . $this->getTimestamp() . "'";
501 $res = wfQuery( $sql, DB_WRITE, $fname );
502
503 if( wfAffectedRows() == 0 ) {
504 /* Belated edit conflict! Run away!! */
505 return false;
506 }
507
508 # This overwrites $oldtext if revision compression is on
509 $flags = Article::compressRevisionText( $oldtext );
510
511 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
512 "old_comment,old_user,old_user_text,old_timestamp," .
513 "old_minor_edit,inverse_timestamp,old_flags) VALUES (" .
514 $this->mTitle->getNamespace() . ", '" .
515 wfStrencode( $this->mTitle->getDBkey() ) . "', '" .
516 wfStrencode( $oldtext ) . "', '" .
517 wfStrencode( $this->getComment() ) . "', " .
518 $this->getUser() . ", '" .
519 wfStrencode( $this->getUserText() ) . "', '" .
520 $this->getTimestamp() . "', " . $me1 . ", '" .
521 wfInvertTimestamp( $this->getTimestamp() ) . "','$flags')";
522 $res = wfQuery( $sql, DB_WRITE, $fname );
523 $oldid = wfInsertID( $res );
524
525 $bot = (int)($wgUser->isBot() || $forceBot);
526 RecentChange::notifyEdit( $now, $this->mTitle, $me2, $wgUser, $summary,
527 $oldid, $this->getTimestamp(), $bot );
528 Article::onArticleEdit( $this->mTitle );
529 }
530
531 if( $wgDBtransactions ) {
532 $sql = "COMMIT";
533 wfQuery( $sql, DB_WRITE );
534 }
535
536 if ($watchthis) {
537 if (!$this->mTitle->userIsWatching()) $this->watch();
538 } else {
539 if ( $this->mTitle->userIsWatching() ) {
540 $this->unwatch();
541 }
542 }
543 # standard deferred updates
544 $this->editUpdates( $text );
545
546 # Squid updates
547
548 if ( $wgUseSquid ) {
549 $urlArr = Array(
550 $this->mTitle->getInternalURL(),
551 $this->mTitle->getInternalURL('action=history')
552 );
553 wfPurgeSquidServers($urlArr);
554 }
555
556 $this->showArticle( $text, wfMsg( "updated" ) );
557 return true;
558 }
559
560 # After we've either updated or inserted the article, update
561 # the link tables and redirect to the new page.
562
563 function showArticle( $text, $subtitle )
564 {
565 global $wgOut, $wgUser, $wgLinkCache;
566 global $wgMwRedir;
567
568 $wgLinkCache = new LinkCache();
569
570 # Get old version of link table to allow incremental link updates
571 $wgLinkCache->preFill( $this->mTitle );
572 $wgLinkCache->clear();
573
574 # Now update the link cache by parsing the text
575 $wgOut = new OutputPage();
576 $wgOut->addWikiText( $text );
577
578 if( $wgMwRedir->matchStart( $text ) )
579 $r = "redirect=no";
580 else
581 $r = "";
582 $wgOut->redirect( $this->mTitle->getFullURL( $r ) );
583 }
584
585 # Add this page to my watchlist
586
587 function watch( $add = true )
588 {
589 global $wgUser, $wgOut, $wgLang;
590 global $wgDeferredUpdateList;
591
592 if ( 0 == $wgUser->getID() ) {
593 $wgOut->errorpage( "watchnologin", "watchnologintext" );
594 return;
595 }
596 if ( wfReadOnly() ) {
597 $wgOut->readOnlyPage();
598 return;
599 }
600 if( $add )
601 $wgUser->addWatch( $this->mTitle );
602 else
603 $wgUser->removeWatch( $this->mTitle );
604
605 $wgOut->setPagetitle( wfMsg( $add ? "addedwatch" : "removedwatch" ) );
606 $wgOut->setRobotpolicy( "noindex,follow" );
607
608 $sk = $wgUser->getSkin() ;
609 $link = $sk->makeKnownLink ( $this->mTitle->getPrefixedText() ) ;
610
611 if($add)
612 $text = wfMsg( "addedwatchtext", $link );
613 else
614 $text = wfMsg( "removedwatchtext", $link );
615 $wgOut->addHTML( $text );
616
617 $up = new UserUpdate();
618 array_push( $wgDeferredUpdateList, $up );
619
620 $wgOut->returnToMain( false );
621 }
622
623 function unwatch()
624 {
625 $this->watch( false );
626 }
627
628 function protect( $limit = "sysop" )
629 {
630 global $wgUser, $wgOut;
631
632 if ( ! $wgUser->isSysop() ) {
633 $wgOut->sysopRequired();
634 return;
635 }
636 if ( wfReadOnly() ) {
637 $wgOut->readOnlyPage();
638 return;
639 }
640 $id = $this->mTitle->getArticleID();
641 if ( 0 == $id ) {
642 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
643 return;
644 }
645 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
646 "cur_restrictions='{$limit}' WHERE cur_id={$id}";
647 wfQuery( $sql, DB_WRITE, "Article::protect" );
648
649 $log = new LogPage( wfMsg( "protectlogpage" ), wfMsg( "protectlogtext" ) );
650 if ( $limit === "" ) {
651 $log->addEntry( wfMsg( "unprotectedarticle", $this->mTitle->getPrefixedText() ), "" );
652 } else {
653 $log->addEntry( wfMsg( "protectedarticle", $this->mTitle->getPrefixedText() ), "" );
654 }
655 $wgOut->redirect( $this->mTitle->getFullURL() );
656 }
657
658 function unprotect()
659 {
660 return $this->protect( "" );
661 }
662
663 function delete()
664 {
665 global $wgUser, $wgOut, $wgMessageCache;
666 global $wpConfirm, $wpReason, $image, $oldimage;
667
668 # This code desperately needs to be totally rewritten
669
670 if ( ( ! $wgUser->isSysop() ) ) {
671 $wgOut->sysopRequired();
672 return;
673 }
674 if ( wfReadOnly() ) {
675 $wgOut->readOnlyPage();
676 return;
677 }
678
679 # Can't delete cached MediaWiki namespace (i.e. vital messages)
680 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $wgMessageCache->isCacheable( $this->mTitle->getDBkey() ) ) {
681 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
682 return;
683 }
684
685 # Better double-check that it hasn't been deleted yet!
686 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
687 if ( ( "" == trim( $this->mTitle->getText() ) )
688 or ( $this->mTitle->getArticleId() == 0 ) ) {
689 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
690 return;
691 }
692
693 if ( $_POST["wpConfirm"] ) {
694 $this->doDelete();
695 return;
696 }
697
698 # determine whether this page has earlier revisions
699 # and insert a warning if it does
700 # we select the text because it might be useful below
701 $ns = $this->mTitle->getNamespace();
702 $title = $this->mTitle->getDBkey();
703 $etitle = wfStrencode( $title );
704 $sql = "SELECT old_text,old_flags FROM old WHERE old_namespace=$ns and old_title='$etitle' ORDER BY inverse_timestamp LIMIT 1";
705 $res = wfQuery( $sql, DB_READ, $fname );
706 if( ($old=wfFetchObject($res)) && !$wpConfirm ) {
707 $skin=$wgUser->getSkin();
708 $wgOut->addHTML("<B>".wfMsg("historywarning"));
709 $wgOut->addHTML( $skin->historyLink() ."</B><P>");
710 }
711
712 $sql="SELECT cur_text FROM cur WHERE cur_namespace=$ns and cur_title='$etitle'";
713 $res=wfQuery($sql, DB_READ, $fname);
714 if( ($s=wfFetchObject($res))) {
715
716 # if this is a mini-text, we can paste part of it into the deletion reason
717
718 #if this is empty, an earlier revision may contain "useful" text
719 if($s->cur_text!="") {
720 $text=$s->cur_text;
721 } else {
722 if($old) {
723 $text = Article::getRevisionText( $old );
724 $blanked=1;
725 }
726
727 }
728
729 $length=strlen($text);
730
731 # this should not happen, since it is not possible to store an empty, new
732 # page. Let's insert a standard text in case it does, though
733 if($length==0 && !$wpReason) { $wpReason=wfmsg("exblank");}
734
735
736 if($length < 500 && !$wpReason) {
737
738 # comment field=255, let's grep the first 150 to have some user
739 # space left
740 $text=substr($text,0,150);
741 # let's strip out newlines and HTML tags
742 $text=preg_replace("/\"/","'",$text);
743 $text=preg_replace("/\</","&lt;",$text);
744 $text=preg_replace("/\>/","&gt;",$text);
745 $text=preg_replace("/[\n\r]/","",$text);
746 if(!$blanked) {
747 $wpReason=wfMsg("excontent"). " '".$text;
748 } else {
749 $wpReason=wfMsg("exbeforeblank") . " '".$text;
750 }
751 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
752 $wpReason.="'";
753 }
754 }
755
756 return $this->confirmDelete();
757 }
758
759 function confirmDelete( $par = "" )
760 {
761 global $wgOut;
762 global $wpReason;
763
764 wfDebug( "Article::confirmDelete\n" );
765
766 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
767 $wgOut->setSubtitle( wfMsg( "deletesub", $sub ) );
768 $wgOut->setRobotpolicy( "noindex,nofollow" );
769 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
770
771 $formaction = $this->mTitle->escapeLocalURL( "action=delete" . $par );
772
773 $confirm = wfMsg( "confirm" );
774 $check = wfMsg( "confirmcheck" );
775 $delcom = wfMsg( "deletecomment" );
776
777 $wgOut->addHTML( "
778 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
779 <table border=0><tr><td align=right>
780 {$delcom}:</td><td align=left>
781 <input type=text size=60 name=\"wpReason\" value=\"" . htmlspecialchars( $wpReason ) . "\">
782 </td></tr><tr><td>&nbsp;</td></tr>
783 <tr><td align=right>
784 <input type=checkbox name=\"wpConfirm\" value='1' id=\"wpConfirm\">
785 </td><td><label for=\"wpConfirm\">{$check}</label></td>
786 </tr><tr><td>&nbsp;</td><td>
787 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
788 </td></tr></table></form>\n" );
789
790 $wgOut->returnToMain( false );
791 }
792
793 function doDelete()
794 {
795 global $wgOut, $wgUser, $wgLang;
796 global $wpReason;
797 $fname = "Article::doDelete";
798 wfDebug( "$fname\n" );
799
800 $this->doDeleteArticle( $this->mTitle );
801 $deleted = $this->mTitle->getPrefixedText();
802
803 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
804 $wgOut->setRobotpolicy( "noindex,nofollow" );
805
806 $sk = $wgUser->getSkin();
807 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
808 Namespace::getWikipedia() ) .
809 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
810
811 $text = wfMsg( "deletedtext", $deleted, $loglink );
812
813 $wgOut->addHTML( "<p>" . $text );
814 $wgOut->returnToMain( false );
815 }
816
817 function doDeleteArticle( $title )
818 {
819 global $wgUser, $wgOut, $wgLang, $wgRequest;
820 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
821
822 $fname = "Article::doDeleteArticle";
823 wfDebug( "$fname\n" );
824
825 $ns = $title->getNamespace();
826 $t = wfStrencode( $title->getDBkey() );
827 $id = $title->getArticleID();
828
829 if ( "" == $t ) {
830 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
831 return;
832 }
833
834 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
835 array_push( $wgDeferredUpdateList, $u );
836
837 # Squid purging
838 if ( $wgUseSquid ) {
839 $urlArr = Array(
840 $this->mTitle->getInternalURL(),
841 $this->mTitle->getInternalURL('action=history')
842 );
843 wfPurgeSquidServers($urlArr);
844
845 /* prepare the list of urls to purge */
846 $sql = "SELECT cur_namespace,cur_title FROM links,cur WHERE l_to={$id} and l_from=cur_id" ;
847 $res = wfQuery ( $sql, DB_READ ) ;
848 while ( $BL = wfFetchObject ( $res ) )
849 {
850 $tobj = Title::MakeTitle( $BL->cur_namespace, $BL->cur_title ) ;
851 $blurlArr[] = $tobj->getInternalURL();
852 }
853 wfFreeResult ( $res ) ;
854 $u = new SquidUpdate( $this->mTitle, $blurlArr );
855 array_push( $wgDeferredUpdateList, $u );
856
857 }
858
859
860
861 # Move article and history to the "archive" table
862 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
863 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
864 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
865 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
866 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
867 wfQuery( $sql, DB_WRITE, $fname );
868
869 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
870 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
871 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
872 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
873 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
874 wfQuery( $sql, DB_WRITE, $fname );
875
876 # Now that it's safely backed up, delete it
877
878 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
879 "cur_title='{$t}'";
880 wfQuery( $sql, DB_WRITE, $fname );
881
882 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
883 "old_title='{$t}'";
884 wfQuery( $sql, DB_WRITE, $fname );
885
886 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
887 "rc_title='{$t}'";
888 wfQuery( $sql, DB_WRITE, $fname );
889
890 # Finally, clean up the link tables
891
892 if ( 0 != $id ) {
893
894 $t = wfStrencode( $title->getPrefixedDBkey() );
895
896 Article::onArticleDelete( $title );
897
898 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
899 $res = wfQuery( $sql, DB_READ, $fname );
900
901 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
902 $now = wfTimestampNow();
903 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
904 $first = true;
905
906 while ( $s = wfFetchObject( $res ) ) {
907 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
908 $first = false;
909 $sql .= "({$s->l_from},'{$t}')";
910 $sql2 .= "{$s->l_from}";
911 }
912 $sql2 .= ")";
913 if ( ! $first ) {
914 wfQuery( $sql, DB_WRITE, $fname );
915 wfQuery( $sql2, DB_WRITE, $fname );
916 }
917 wfFreeResult( $res );
918
919 $sql = "DELETE FROM links WHERE l_to={$id}";
920 wfQuery( $sql, DB_WRITE, $fname );
921
922 $sql = "DELETE FROM links WHERE l_from={$id}";
923 wfQuery( $sql, DB_WRITE, $fname );
924
925 $sql = "DELETE FROM imagelinks WHERE il_from={$d}";
926 wfQuery( $sql, DB_WRITE, $fname );
927
928 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
929 wfQuery( $sql, DB_WRITE, $fname );
930 }
931
932 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
933 $art = $title->getPrefixedText();
934 $wpReason = $wgRequest->getText( "wpReason" );
935 $log->addEntry( wfMsg( "deletedarticle", $art ), $wpReason );
936
937 # Clear the cached article id so the interface doesn't act like we exist
938 $this->mTitle->resetArticleID( 0 );
939 $this->mTitle->mArticleID = 0;
940 }
941
942 function rollback()
943 {
944 global $wgUser, $wgLang, $wgOut, $wgRequest;
945
946 if ( ! $wgUser->isSysop() ) {
947 $wgOut->sysopRequired();
948 return;
949 }
950 if ( wfReadOnly() ) {
951 $wgOut->readOnlyPage( $this->getContent() );
952 return;
953 }
954
955 # Enhanced rollback, marks edits rc_bot=1
956 $bot = $wgRequest->getBool( 'bot' );
957
958 # Replace all this user's current edits with the next one down
959 $tt = wfStrencode( $this->mTitle->getDBKey() );
960 $n = $this->mTitle->getNamespace();
961
962 # Get the last editor
963 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
964 $res = wfQuery( $sql, DB_READ );
965 if( ($x = wfNumRows( $res )) != 1 ) {
966 # Something wrong
967 $wgOut->addHTML( wfMsg( "notanarticle" ) );
968 return;
969 }
970 $s = wfFetchObject( $res );
971 $ut = wfStrencode( $s->cur_user_text );
972 $uid = $s->cur_user;
973 $pid = $s->cur_id;
974
975 $from = str_replace( '_', ' ', $wgRequest->getVal( "from" ) );
976 if( $from != $s->cur_user_text ) {
977 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
978 $wgOut->addWikiText( wfMsg( "alreadyrolled",
979 htmlspecialchars( $this->mTitle->getPrefixedText()),
980 htmlspecialchars( $from ),
981 htmlspecialchars( $s->cur_user_text ) ) );
982 if($s->cur_comment != "") {
983 $wgOut->addHTML(
984 wfMsg("editcomment",
985 htmlspecialchars( $s->cur_comment ) ) );
986 }
987 return;
988 }
989
990 # Get the last edit not by this guy
991 $sql = "SELECT old_text,old_user,old_user_text,old_timestamp,old_flags
992 FROM old USE INDEX (name_title_timestamp)
993 WHERE old_namespace={$n} AND old_title='{$tt}'
994 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
995 ORDER BY inverse_timestamp LIMIT 1";
996 $res = wfQuery( $sql, DB_READ );
997 if( wfNumRows( $res ) != 1 ) {
998 # Something wrong
999 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
1000 $wgOut->addHTML( wfMsg( "cantrollback" ) );
1001 return;
1002 }
1003 $s = wfFetchObject( $res );
1004
1005 if ( $bot ) {
1006 # Mark all reverted edits as bot
1007 $sql = "UPDATE recentchanges SET rc_bot=1 WHERE
1008 rc_cur_id=$pid AND rc_user=$uid AND rc_timestamp > '{$s->old_timestamp}'";
1009 wfQuery( $sql, DB_WRITE, $fname );
1010 }
1011
1012 # Save it!
1013 $newcomment = wfMsg( "revertpage", $s->old_user_text, $from );
1014 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1015 $wgOut->setRobotpolicy( "noindex,nofollow" );
1016 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
1017 $this->updateArticle( Article::getRevisionText( $s ), $newcomment, 1, $this->mTitle->userIsWatching(), "", $bot );
1018
1019 Article::onArticleEdit( $this->mTitle );
1020 $wgOut->returnToMain( false );
1021 }
1022
1023
1024 # Do standard deferred updates after page view
1025
1026 /* private */ function viewUpdates()
1027 {
1028 global $wgDeferredUpdateList;
1029 if ( 0 != $this->getID() ) {
1030 global $wgDisableCounters;
1031 if( !$wgDisableCounters ) {
1032 Article::incViewCount( $this->getID() );
1033 $u = new SiteStatsUpdate( 1, 0, 0 );
1034 array_push( $wgDeferredUpdateList, $u );
1035 }
1036 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
1037 $this->mTitle->getDBkey() );
1038 array_push( $wgDeferredUpdateList, $u );
1039 }
1040 }
1041
1042 # Do standard deferred updates after page edit.
1043 # Every 1000th edit, prune the recent changes table.
1044
1045 /* private */ function editUpdates( $text )
1046 {
1047 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1048 global $wgMessageCache;
1049
1050 wfSeedRandom();
1051 if ( 0 == mt_rand( 0, 999 ) ) {
1052 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1053 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1054 wfQuery( $sql, DB_WRITE );
1055 }
1056 $id = $this->getID();
1057 $title = $this->mTitle->getPrefixedDBkey();
1058 $shortTitle = $this->mTitle->getDBkey();
1059
1060 $adj = $this->mCountAdjustment;
1061
1062 if ( 0 != $id ) {
1063 $u = new LinksUpdate( $id, $title );
1064 array_push( $wgDeferredUpdateList, $u );
1065 $u = new SiteStatsUpdate( 0, 1, $adj );
1066 array_push( $wgDeferredUpdateList, $u );
1067 $u = new SearchUpdate( $id, $title, $text );
1068 array_push( $wgDeferredUpdateList, $u );
1069
1070 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle );
1071 array_push( $wgDeferredUpdateList, $u );
1072
1073 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1074 $wgMessageCache->replace( $shortTitle, $text );
1075 }
1076 }
1077 }
1078
1079 /* private */ function setOldSubtitle()
1080 {
1081 global $wgLang, $wgOut;
1082
1083 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1084 $r = wfMsg( "revisionasof", $td );
1085 $wgOut->setSubtitle( "({$r})" );
1086 }
1087
1088 # This function is called right before saving the wikitext,
1089 # so we can do things like signatures and links-in-context.
1090
1091 function preSaveTransform( $text )
1092 {
1093 global $wgParser, $wgUser;
1094 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
1095 }
1096
1097 /* Caching functions */
1098
1099 # checkLastModified returns true iff it has taken care of all
1100 # output to the client that is necessary for this request.
1101 # (that is, it has sent a cached version of the page)
1102 function tryFileCache() {
1103 static $called = false;
1104 if( $called ) {
1105 wfDebug( " tryFileCache() -- called twice!?\n" );
1106 return;
1107 }
1108 $called = true;
1109 if($this->isFileCacheable()) {
1110 $touched = $this->mTouched;
1111 if( $this->mTitle->getPrefixedDBkey() == wfMsg( "mainpage" ) ) {
1112 # Expire the main page quicker
1113 $expire = wfUnix2Timestamp( time() - 3600 );
1114 $touched = max( $expire, $touched );
1115 }
1116 $cache = new CacheManager( $this->mTitle );
1117 if($cache->isFileCacheGood( $touched )) {
1118 global $wgOut;
1119 wfDebug( " tryFileCache() - about to load\n" );
1120 $cache->loadFromFileCache();
1121 return true;
1122 } else {
1123 wfDebug( " tryFileCache() - starting buffer\n" );
1124 ob_start( array(&$cache, 'saveToFileCache' ) );
1125 }
1126 } else {
1127 wfDebug( " tryFileCache() - not cacheable\n" );
1128 }
1129 }
1130
1131 function isFileCacheable() {
1132 global $wgUser, $wgUseFileCache, $wgShowIPinHeader;
1133 global $action, $oldid, $diff, $redirect, $printable;
1134 return $wgUseFileCache
1135 and (!$wgShowIPinHeader)
1136 and ($this->getID() != 0)
1137 and ($wgUser->getId() == 0)
1138 and (!$wgUser->getNewtalk())
1139 and ($this->mTitle->getNamespace() != Namespace::getSpecial())
1140 and ($action == "view")
1141 and (!isset($oldid))
1142 and (!isset($diff))
1143 and (!isset($redirect))
1144 and (!isset($printable))
1145 and (!$this->mRedirectedFrom);
1146 }
1147
1148 function checkTouched() {
1149 $id = $this->getID();
1150 $sql = "SELECT cur_touched,cur_is_redirect FROM cur WHERE cur_id=$id";
1151 $res = wfQuery( $sql, DB_READ, "Article::checkTouched" );
1152 if( $s = wfFetchObject( $res ) ) {
1153 $this->mTouched = $s->cur_touched;
1154 return !$s->cur_is_redirect;
1155 } else {
1156 return false;
1157 }
1158 }
1159
1160 /* static */ function incViewCount( $id )
1161 {
1162 $id = intval( $id );
1163 global $wgHitcounterUpdateFreq;
1164
1165 if( $wgHitcounterUpdateFreq <= 1 ){ //
1166 wfQuery("UPDATE cur SET cur_counter = cur_counter + 1 " .
1167 "WHERE cur_id = $id", DB_WRITE);
1168 return;
1169 }
1170
1171 # Not important enough to warrant an error page in case of failure
1172 $oldignore = wfIgnoreSQLErrors( true );
1173
1174 wfQuery("INSERT INTO hitcounter (hc_id) VALUES ({$id})", DB_WRITE);
1175
1176 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
1177 if( (rand() % $checkfreq != 0) or (wfLastErrno() != 0) ){
1178 # Most of the time (or on SQL errors), skip row count check
1179 wfIgnoreSQLErrors( $oldignore );
1180 return;
1181 }
1182
1183 $res = wfQuery("SELECT COUNT(*) as n FROM hitcounter", DB_WRITE);
1184 $row = wfFetchObject( $res );
1185 $rown = intval( $row->n );
1186 if( $rown >= $wgHitcounterUpdateFreq ){
1187 wfProfileIn( "Article::incViewCount-collect" );
1188 $old_user_abort = ignore_user_abort( true );
1189
1190 wfQuery("LOCK TABLES hitcounter WRITE", DB_WRITE);
1191 wfQuery("CREATE TEMPORARY TABLE acchits TYPE=HEAP ".
1192 "SELECT hc_id,COUNT(*) AS hc_n FROM hitcounter ".
1193 "GROUP BY hc_id", DB_WRITE);
1194 wfQuery("DELETE FROM hitcounter", DB_WRITE);
1195 wfQuery("UNLOCK TABLES", DB_WRITE);
1196 wfQuery("UPDATE cur,acchits SET cur_counter=cur_counter + hc_n ".
1197 "WHERE cur_id = hc_id", DB_WRITE);
1198 wfQuery("DROP TABLE acchits", DB_WRITE);
1199
1200 ignore_user_abort( $old_user_abort );
1201 wfProfileOut( "Article::incViewCount-collect" );
1202 }
1203 wfIgnoreSQLErrors( $oldignore );
1204 }
1205
1206 # The onArticle*() functions are supposed to be a kind of hooks
1207 # which should be called whenever any of the specified actions
1208 # are done.
1209 #
1210 # This is a good place to put code to clear caches, for instance.
1211
1212 /* static */ function onArticleCreate($title_obj){
1213 global $wgEnablePersistentLC, $wgEnableParserCache;
1214 if ( $wgEnablePersistentLC ) {
1215 LinkCache::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1216 }
1217 if ( $wgEnableParserCache ) {
1218 OutputPage::parsercacheClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1219 }
1220 }
1221
1222 /* static */ function onArticleDelete($title_obj){
1223 global $wgEnablePersistentLC, $wgEnableParserCache;
1224 if ( $wgEnablePersistentLC ) {
1225 LinkCache::linksccClearLinksTo( $title_obj->getArticleID() );
1226 }
1227 if ( $wgEnableParserCache ) {
1228 OutputPage::parsercacheClearLinksTo( $title_obj->getArticleID() );
1229 }
1230 }
1231
1232 /* static */ function onArticleEdit($title_obj){
1233 global $wgEnablePersistentLC, $wgEnableParserCache;
1234 if ( $wgEnablePersistentLC ) {
1235 LinkCache::linksccClearPage( $title_obj->getArticleID() );
1236 }
1237 if ( $wgEnableParserCache ) {
1238 OutputPage::parsercacheClearPage( $title_obj->getArticleID(), $title_obj->getNamespace() );
1239 }
1240 }
1241 }
1242
1243 function wfReplaceSubstVar( $matches ) {
1244 return wfMsg( $matches[1] );
1245 }
1246
1247 ?>