Link fix for "About protected pages"
[mediawiki.git] / includes / Article.php
blob269b1936514a52dc660d0a7ae3e1c2f55a2fcd20
1 <?
2 # Class representing a Wikipedia article and history.
3 # See design.doc for an overview.
5 # Note: edit user interface and cache support functions have been
6 # moved to separate EditPage and CacheManager classes.
8 include_once( "CacheManager.php" );
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;
17 function Article( &$title ) {
18 $this->mTitle =& $title;
19 $this->clear();
22 /* private */ function clear()
24 $this->mContentLoaded = false;
25 $this->mUser = $this->mCounter = -1; # Not loaded
26 $this->mRedirectedFrom = $this->mUserText =
27 $this->mTimestamp = $this->mComment = $this->mFileCache = "";
28 $this->mCountAdjustment = 0;
29 $this->mTouched = "19700101000000";
32 # Note that getContent/loadContent may follow redirects if
33 # not told otherwise, and so may cause a change to wgTitle.
35 function getContent( $noredir = false )
37 global $action,$section,$count; # From query string
38 wfProfileIn( "Article::getContent" );
40 if ( 0 == $this->getID() ) {
41 if ( "edit" == $action ) {
42 return ""; # was "newarticletext", now moved above the box)
44 wfProfileOut();
45 return wfMsg( "noarticletext" );
46 } else {
47 $this->loadContent( $noredir );
48 wfProfileOut();
50 if(
51 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
52 ( $this->mTitle->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
53 preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$this->mTitle->getText()) &&
54 $action=="view"
57 return $this->mContent . "\n" .wfMsg("anontalkpagetext"); }
58 else {
59 if($action=="edit") {
60 if($section!="") {
61 if($section=="new") { return ""; }
63 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
64 $this->mContent, -1,
65 PREG_SPLIT_DELIM_CAPTURE);
66 if($section==0) {
67 return trim($secs[0]);
68 } else {
69 return trim($secs[$section*2-1] . $secs[$section*2]);
73 return $this->mContent;
78 function loadContent( $noredir = false )
80 global $wgOut, $wgMwRedir;
81 global $oldid, $redirect; # From query
83 if ( $this->mContentLoaded ) return;
84 $fname = "Article::loadContent";
86 # Pre-fill content with error message so that if something
87 # fails we'll have something telling us what we intended.
89 $t = $this->mTitle->getPrefixedText();
90 if ( $oldid ) { $t .= ",oldid={$oldid}"; }
91 if ( $redirect ) { $t .= ",redirect={$redirect}"; }
92 $this->mContent = str_replace( "$1", $t, wfMsg( "missingarticle" ) );
94 if ( ! $oldid ) { # Retrieve current version
95 $id = $this->getID();
96 if ( 0 == $id ) return;
98 $sql = "SELECT " .
99 "cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched " .
100 "FROM cur WHERE cur_id={$id}";
101 $res = wfQuery( $sql, DB_READ, $fname );
102 if ( 0 == wfNumRows( $res ) ) { return; }
104 $s = wfFetchObject( $res );
106 # If we got a redirect, follow it (unless we've been told
107 # not to by either the function parameter or the query
108 if ( ( "no" != $redirect ) && ( false == $noredir ) &&
109 ( $wgMwRedir->matchStart( $s->cur_text ) ) ) {
110 if ( preg_match( "/\\[\\[([^\\]\\|]+)[\\]\\|]/",
111 $s->cur_text, $m ) ) {
112 $rt = Title::newFromText( $m[1] );
114 # Gotta hand redirects to special pages differently:
115 # Fill the HTTP response "Location" header and ignore
116 # the rest of the page we're on.
118 if ( $rt->getInterwiki() != "" ) {
119 $wgOut->redirect( $rt->getFullURL() ) ;
120 return;
122 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
123 $wgOut->redirect( wfLocalUrl(
124 $rt->getPrefixedURL() ) );
125 return;
127 $rid = $rt->getArticleID();
128 if ( 0 != $rid ) {
129 $sql = "SELECT cur_text,cur_timestamp,cur_user," .
130 "cur_counter,cur_touched FROM cur WHERE cur_id={$rid}";
131 $res = wfQuery( $sql, DB_READ, $fname );
133 if ( 0 != wfNumRows( $res ) ) {
134 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
135 $this->mTitle = $rt;
136 $s = wfFetchObject( $res );
141 $this->mContent = $s->cur_text;
142 $this->mUser = $s->cur_user;
143 $this->mCounter = $s->cur_counter;
144 $this->mTimestamp = $s->cur_timestamp;
145 $this->mTouched = $s->cur_touched;
146 $this->mTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
147 $this->mTitle->mRestrictionsLoaded = true;
148 wfFreeResult( $res );
149 } else { # oldid set, retrieve historical version
150 $sql = "SELECT old_text,old_timestamp,old_user FROM old " .
151 "WHERE old_id={$oldid}";
152 $res = wfQuery( $sql, DB_READ, $fname );
153 if ( 0 == wfNumRows( $res ) ) { return; }
155 $s = wfFetchObject( $res );
156 $this->mContent = $s->old_text;
157 $this->mUser = $s->old_user;
158 $this->mCounter = 0;
159 $this->mTimestamp = $s->old_timestamp;
160 wfFreeResult( $res );
162 $this->mContentLoaded = true;
165 function getID() { return $this->mTitle->getArticleID(); }
167 function getCount()
169 if ( -1 == $this->mCounter ) {
170 $id = $this->getID();
171 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
173 return $this->mCounter;
176 # Would the given text make this article a "good" article (i.e.,
177 # suitable for including in the article count)?
179 function isCountable( $text )
181 global $wgUseCommaCount, $wgMwRedir;
183 if ( 0 != $this->mTitle->getNamespace() ) { return 0; }
184 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
185 $token = ($wgUseCommaCount ? "," : "[[" );
186 if ( false === strstr( $text, $token ) ) { return 0; }
187 return 1;
190 # Load the field related to the last edit time of the article.
191 # This isn't necessary for all uses, so it's only done if needed.
193 /* private */ function loadLastEdit()
195 global $wgOut;
196 if ( -1 != $this->mUser ) return;
198 $sql = "SELECT cur_user,cur_user_text,cur_timestamp," .
199 "cur_comment,cur_minor_edit FROM cur WHERE " .
200 "cur_id=" . $this->getID();
201 $res = wfQuery( $sql, DB_READ, "Article::loadLastEdit" );
203 if ( wfNumRows( $res ) > 0 ) {
204 $s = wfFetchObject( $res );
205 $this->mUser = $s->cur_user;
206 $this->mUserText = $s->cur_user_text;
207 $this->mTimestamp = $s->cur_timestamp;
208 $this->mComment = $s->cur_comment;
209 $this->mMinorEdit = $s->cur_minor_edit;
213 function getTimestamp()
215 $this->loadLastEdit();
216 return $this->mTimestamp;
219 function getUser()
221 $this->loadLastEdit();
222 return $this->mUser;
225 function getUserText()
227 $this->loadLastEdit();
228 return $this->mUserText;
231 function getComment()
233 $this->loadLastEdit();
234 return $this->mComment;
237 function getMinorEdit()
239 $this->loadLastEdit();
240 return $this->mMinorEdit;
243 # This is the default action of the script: just view the page of
244 # the given title.
246 function view()
248 global $wgUser, $wgOut, $wgLang;
249 global $oldid, $diff; # From query
250 global $wgLinkCache;
251 wfProfileIn( "Article::view" );
253 $wgOut->setArticleFlag( true );
254 $wgOut->setRobotpolicy( "index,follow" );
256 # If we got diff and oldid in the query, we want to see a
257 # diff page instead of the article.
259 if ( isset( $diff ) ) {
260 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
261 $de = new DifferenceEngine( $oldid, $diff );
262 $de->showDiffPage();
263 wfProfileOut();
264 return;
266 $text = $this->getContent(); # May change wgTitle!
267 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
268 $wgOut->setHTMLTitle( $this->mTitle->getPrefixedText() .
269 " - " . wfMsg( "wikititlesuffix" ) );
271 # We're looking at an old revision
273 if ( $oldid ) {
274 $this->setOldSubtitle();
275 $wgOut->setRobotpolicy( "noindex,follow" );
277 if ( "" != $this->mRedirectedFrom ) {
278 $sk = $wgUser->getSkin();
279 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, "",
280 "redirect=no" );
281 $s = str_replace( "$1", $redir, wfMsg( "redirectedfrom" ) );
282 $wgOut->setSubtitle( $s );
284 $wgOut->checkLastModified( $this->mTouched );
285 $this->tryFileCache();
286 $wgLinkCache->preFill( $this->mTitle );
287 $wgOut->addWikiText( $text );
289 $this->viewUpdates();
290 wfProfileOut();
293 # Theoretically we could defer these whole insert and update
294 # functions for after display, but that's taking a big leap
295 # of faith, and we want to be able to report database
296 # errors at some point.
298 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
300 global $wgOut, $wgUser, $wgLinkCache, $wgMwRedir;
301 $fname = "Article::insertNewArticle";
303 $ns = $this->mTitle->getNamespace();
304 $ttl = $this->mTitle->getDBkey();
305 $text = $this->preSaveTransform( $text );
306 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
307 else { $redir = 0; }
309 $now = wfTimestampNow();
310 $won = wfInvertTimestamp( $now );
311 wfSeedRandom();
312 $rand = number_format( mt_rand() / mt_getrandmax(), 12, ".", "" );
313 $sql = "INSERT INTO cur (cur_namespace,cur_title,cur_text," .
314 "cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter," .
315 "cur_restrictions,cur_user_text,cur_is_redirect," .
316 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$ns},'" . wfStrencode( $ttl ) . "', '" .
317 wfStrencode( $text ) . "', '" .
318 wfStrencode( $summary ) . "', '" .
319 $wgUser->getID() . "', '{$now}', " .
320 ( $isminor ? 1 : 0 ) . ", 0, '', '" .
321 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
322 $res = wfQuery( $sql, DB_WRITE, $fname );
324 $newid = wfInsertId();
325 $this->mTitle->resetArticleID( $newid );
327 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
328 "rc_namespace,rc_title,rc_new,rc_minor,rc_cur_id,rc_user," .
329 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid,rc_bot) VALUES (" .
330 "'{$now}','{$now}',{$ns},'" . wfStrencode( $ttl ) . "',1," .
331 ( $isminor ? 1 : 0 ) . ",{$newid}," . $wgUser->getID() . ",'" .
332 wfStrencode( $wgUser->getName() ) . "','" .
333 wfStrencode( $summary ) . "',0,0," .
334 ( $wgUser->isBot() ? 1 : 0 ) . ")";
335 wfQuery( $sql, DB_WRITE, $fname );
336 if ($watchthis) {
337 if(!$this->mTitle->userIsWatching()) $this->watch();
338 } else {
339 if ( $this->mTitle->userIsWatching() ) {
340 $this->unwatch();
344 $this->showArticle( $text, wfMsg( "newarticle" ) );
347 function updateArticle( $text, $summary, $minor, $watchthis, $section="" )
349 global $wgOut, $wgUser, $wgLinkCache;
350 global $wgDBtransactions, $wgMwRedir;
351 $fname = "Article::updateArticle";
353 $this->loadLastEdit();
355 // insert updated section into old text if we have only edited part
356 // of the article
357 if ($section != "") {
358 $oldtext=$this->getContent();
359 if($section=="new") {
360 if($summary) $subject="== {$summary} ==\n\n";
361 $text=$oldtext."\n\n".$subject.$text;
362 } else {
363 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
364 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
365 $secs[$section*2]=$text."\n\n"; // replace with edited
366 if($section) { $secs[$section*2-1]=""; } // erase old headline
367 $text=join("",$secs);
370 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
371 if ( $minor ) { $me2 = 1; } else { $me2 = 0; }
372 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ")[^\\n]+)/i", $text, $m ) ) {
373 $redir = 1;
374 $text = $m[1] . "\n"; # Remove all content but redirect
376 else { $redir = 0; }
378 $text = $this->preSaveTransform( $text );
380 # Update article, but only if changed.
382 if( $wgDBtransactions ) {
383 $sql = "BEGIN";
384 wfQuery( $sql, DB_WRITE );
386 $oldtext = $this->getContent( true );
388 if ( 0 != strcmp( $text, $oldtext ) ) {
389 $this->mCountAdjustment = $this->isCountable( $text )
390 - $this->isCountable( $oldtext );
392 $now = wfTimestampNow();
393 $won = wfInvertTimestamp( $now );
394 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
395 "',cur_comment='" . wfStrencode( $summary ) .
396 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
397 ",cur_timestamp='{$now}',cur_user_text='" .
398 wfStrencode( $wgUser->getName() ) .
399 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
400 "WHERE cur_id=" . $this->getID() .
401 " AND cur_timestamp='" . $this->getTimestamp() . "'";
402 $res = wfQuery( $sql, DB_WRITE, $fname );
404 if( wfAffectedRows() == 0 ) {
405 /* Belated edit conflict! Run away!! */
406 return false;
409 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
410 "old_comment,old_user,old_user_text,old_timestamp," .
411 "old_minor_edit,inverse_timestamp) VALUES (" .
412 $this->mTitle->getNamespace() . ", '" .
413 wfStrencode( $this->mTitle->getDBkey() ) . "', '" .
414 wfStrencode( $oldtext ) . "', '" .
415 wfStrencode( $this->getComment() ) . "', " .
416 $this->getUser() . ", '" .
417 wfStrencode( $this->getUserText() ) . "', '" .
418 $this->getTimestamp() . "', " . $me1 . ", '" .
419 wfInvertTimestamp( $this->getTimestamp() ) . "')";
420 $res = wfQuery( $sql, DB_WRITE, $fname );
421 $oldid = wfInsertID( $res );
423 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
424 "rc_namespace,rc_title,rc_new,rc_minor,rc_bot,rc_cur_id,rc_user," .
425 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid) VALUES (" .
426 "'{$now}','{$now}'," . $this->mTitle->getNamespace() . ",'" .
427 wfStrencode( $this->mTitle->getDBkey() ) . "',0,{$me2}," .
428 ( $wgUser->isBot() ? 1 : 0 ) . "," .
429 $this->getID() . "," . $wgUser->getID() . ",'" .
430 wfStrencode( $wgUser->getName() ) . "','" .
431 wfStrencode( $summary ) . "',0,{$oldid})";
432 wfQuery( $sql, DB_WRITE, $fname );
434 $sql = "UPDATE recentchanges SET rc_this_oldid={$oldid} " .
435 "WHERE rc_namespace=" . $this->mTitle->getNamespace() . " AND " .
436 "rc_title='" . wfStrencode( $this->mTitle->getDBkey() ) . "' AND " .
437 "rc_timestamp='" . $this->getTimestamp() . "'";
438 wfQuery( $sql, DB_WRITE, $fname );
440 $sql = "UPDATE recentchanges SET rc_cur_time='{$now}' " .
441 "WHERE rc_cur_id=" . $this->getID();
442 wfQuery( $sql, DB_WRITE, $fname );
444 if( $wgDBtransactions ) {
445 $sql = "COMMIT";
446 wfQuery( $sql, DB_WRITE );
449 if ($watchthis) {
450 if (!$this->mTitle->userIsWatching()) $this->watch();
451 } else {
452 if ( $this->mTitle->userIsWatching() ) {
453 $this->unwatch();
457 $this->showArticle( $text, wfMsg( "updated" ) );
458 return true;
461 # After we've either updated or inserted the article, update
462 # the link tables and redirect to the new page.
464 function showArticle( $text, $subtitle )
466 global $wgOut, $wgUser, $wgLinkCache, $wgUseBetterLinksUpdate;
467 global $wgMwRedir;
469 $wgLinkCache = new LinkCache();
471 # Get old version of link table to allow incremental link updates
472 if ( $wgUseBetterLinksUpdate ) {
473 $wgLinkCache->preFill( $this->mTitle );
474 $wgLinkCache->clear();
477 # Now update the link cache by parsing the text
478 $wgOut = new OutputPage();
479 $wgOut->addWikiText( $text );
481 $this->editUpdates( $text );
482 if( $wgMwRedir->matchStart( $text ) )
483 $r = "redirect=no";
484 else
485 $r = "";
486 $wgOut->redirect( wfLocalUrl( $this->mTitle->getPrefixedURL(), $r ) );
489 # Add this page to my watchlist
491 function watch( $add = true )
493 global $wgUser, $wgOut, $wgLang;
494 global $wgDeferredUpdateList;
496 if ( 0 == $wgUser->getID() ) {
497 $wgOut->errorpage( "watchnologin", "watchnologintext" );
498 return;
500 if ( wfReadOnly() ) {
501 $wgOut->readOnlyPage();
502 return;
504 if( $add )
505 $wgUser->addWatch( $this->mTitle );
506 else
507 $wgUser->removeWatch( $this->mTitle );
509 $wgOut->setPagetitle( wfMsg( $add ? "addedwatch" : "removedwatch" ) );
510 $wgOut->setRobotpolicy( "noindex,follow" );
512 $sk = $wgUser->getSkin() ;
513 $link = $sk->makeKnownLink ( $this->mTitle->getPrefixedText() ) ;
515 if($add)
516 $text = wfMsg( "addedwatchtext", $link );
517 else
518 $text = wfMsg( "removedwatchtext", $link );
519 $wgOut->addHTML( $text );
521 $up = new UserUpdate();
522 array_push( $wgDeferredUpdateList, $up );
524 $wgOut->returnToMain( false );
527 function unwatch()
529 $this->watch( false );
532 # This shares a lot of issues (and code) with Recent Changes
534 function history()
536 global $wgUser, $wgOut, $wgLang, $offset, $limit;
538 # If page hasn't changed, client can cache this
540 $wgOut->checkLastModified( $this->getTimestamp() );
541 wfProfileIn( "Article::history" );
543 $wgOut->setPageTitle( $this->mTitle->getPRefixedText() );
544 $wgOut->setSubtitle( wfMsg( "revhistory" ) );
545 $wgOut->setArticleFlag( false );
546 $wgOut->setRobotpolicy( "noindex,nofollow" );
548 if( $this->mTitle->getArticleID() == 0 ) {
549 $wgOut->addHTML( wfMsg( "nohistory" ) );
550 wfProfileOut();
551 return;
554 $offset = (int)$offset;
555 $limit = (int)$limit;
556 if( $limit == 0 ) $limit = 50;
557 $namespace = $this->mTitle->getNamespace();
558 $title = $this->mTitle->getText();
559 $sql = "SELECT old_id,old_user," .
560 "old_comment,old_user_text,old_timestamp,old_minor_edit ".
561 "FROM old USE INDEX (name_title_timestamp) " .
562 "WHERE old_namespace={$namespace} AND " .
563 "old_title='" . wfStrencode( $this->mTitle->getDBkey() ) . "' " .
564 "ORDER BY inverse_timestamp LIMIT $offset, $limit";
565 $res = wfQuery( $sql, DB_READ, "Article::history" );
567 $revs = wfNumRows( $res );
568 if( $this->mTitle->getArticleID() == 0 ) {
569 $wgOut->addHTML( wfMsg( "nohistory" ) );
570 wfProfileOut();
571 return;
574 $sk = $wgUser->getSkin();
575 $numbar = wfViewPrevNext(
576 $offset, $limit,
577 $this->mTitle->getPrefixedText(),
578 "action=history" );
579 $s = $numbar;
580 $s .= $sk->beginHistoryList();
582 if($offset == 0 )
583 $s .= $sk->historyLine( $this->getTimestamp(), $this->getUser(),
584 $this->getUserText(), $namespace,
585 $title, 0, $this->getComment(),
586 ( $this->getMinorEdit() > 0 ) );
588 $revs = wfNumRows( $res );
589 while ( $line = wfFetchObject( $res ) ) {
590 $s .= $sk->historyLine( $line->old_timestamp, $line->old_user,
591 $line->old_user_text, $namespace,
592 $title, $line->old_id,
593 $line->old_comment, ( $line->old_minor_edit > 0 ) );
595 $s .= $sk->endHistoryList();
596 $s .= $numbar;
597 $wgOut->addHTML( $s );
598 wfProfileOut();
601 function protect( $limit = "sysop" )
603 global $wgUser, $wgOut;
605 if ( ! $wgUser->isSysop() ) {
606 $wgOut->sysopRequired();
607 return;
609 if ( wfReadOnly() ) {
610 $wgOut->readOnlyPage();
611 return;
613 $id = $this->mTitle->getArticleID();
614 if ( 0 == $id ) {
615 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
616 return;
618 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
619 "cur_restrictions='{$limit}' WHERE cur_id={$id}";
620 wfQuery( $sql, DB_WRITE, "Article::protect" );
622 $wgOut->redirect( wfLocalUrl( $this->mTitle->getPrefixedURL() ) );
625 function unprotect()
627 return $this->protect( "" );
630 function delete()
632 global $wgUser, $wgOut;
633 global $wpConfirm, $wpReason, $image, $oldimage;
635 # Anybody can delete old revisions of images; only sysops
636 # can delete articles and current images
638 if ( ( ! $oldimage ) && ( ! $wgUser->isSysop() ) ) {
639 $wgOut->sysopRequired();
640 return;
642 if ( wfReadOnly() ) {
643 $wgOut->readOnlyPage();
644 return;
647 # Better double-check that it hasn't been deleted yet!
648 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
649 if ( ( "" == trim( $this->mTitle->getText() ) )
650 or ( $this->mTitle->getArticleId() == 0 ) ) {
651 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
652 return;
655 # determine whether this page has earlier revisions
656 # and insert a warning if it does
657 # we select the text because it might be useful below
658 $sql="SELECT old_text FROM old WHERE old_namespace=0 and old_title='" . wfStrencode($this->mTitle->getPrefixedDBkey())."' ORDER BY inverse_timestamp LIMIT 1";
659 $res=wfQuery($sql, DB_READ, $fname);
660 if( ($old=wfFetchObject($res)) && !$wpConfirm ) {
661 $skin=$wgUser->getSkin();
662 $wgOut->addHTML("<B>".wfMsg("historywarning"));
663 $wgOut->addHTML( $skin->historyLink() ."</B><P>");
666 $sql="SELECT cur_text FROM cur WHERE cur_namespace=0 and cur_title='" . wfStrencode($this->mTitle->getPrefixedDBkey())."'";
667 $res=wfQuery($sql, DB_READ, $fname);
668 if( ($s=wfFetchObject($res))) {
670 # if this is a mini-text, we can paste part of it into the deletion reason
672 #if this is empty, an earlier revision may contain "useful" text
673 if($s->cur_text!="") {
674 $text=$s->cur_text;
675 } else {
676 if($old) {
677 $text=$old->old_text;
678 $blanked=1;
683 $length=strlen($text);
685 # this should not happen, since it is not possible to store an empty, new
686 # page. Let's insert a standard text in case it does, though
687 if($length==0 && !$wpReason) { $wpReason=wfmsg("exblank");}
690 if($length < 500 && !$wpReason) {
692 # comment field=255, let's grep the first 150 to have some user
693 # space left
694 $text=substr($text,0,150);
695 # let's strip out newlines and HTML tags
696 $text=preg_replace("/\"/","'",$text);
697 $text=preg_replace("/\</","&lt;",$text);
698 $text=preg_replace("/\>/","&gt;",$text);
699 $text=preg_replace("/[\n\r]/","",$text);
700 if(!$blanked) {
701 $wpReason=wfMsg("excontent"). " '".$text;
702 } else {
703 $wpReason=wfMsg("exbeforeblank") . " '".$text;
705 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
706 $wpReason.="'";
710 return $this->confirmDelete();
713 function confirmDelete( $par = "" )
715 global $wgOut;
717 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
718 $wgOut->setSubtitle( wfMsg( "deletesub", $sub ) );
719 $wgOut->setRobotpolicy( "noindex,nofollow" );
720 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
722 $t = $this->mTitle->getPrefixedURL();
724 $formaction = wfEscapeHTML( wfLocalUrl( $t, "action=delete" . $par ) );
725 $confirm = wfMsg( "confirm" );
726 $check = wfMsg( "confirmcheck" );
727 $delcom = wfMsg( "deletecomment" );
729 $wgOut->addHTML( "
730 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
731 <table border=0><tr><td align=right>
732 {$delcom}:</td><td align=left>
733 <input type=text size=60 name=\"wpReason\" value=\"{$wpReason}\">
734 </td></tr><tr><td>&nbsp;</td></tr>
735 <tr><td align=right>
736 <input type=checkbox name=\"wpConfirm\" value='1' id=\"wpConfirm\">
737 </td><td><label for=\"wpConfirm\">{$check}</label></td>
738 </tr><tr><td>&nbsp;</td><td>
739 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
740 </td></tr></table></form>\n" );
742 $wgOut->returnToMain( false );
745 function doDelete()
747 global $wgOut, $wgUser, $wgLang;
748 global $wpReason;
749 $fname = "Article::doDelete";
751 $this->doDeleteArticle( $this->mTitle );
752 $deleted = $this->mTitle->getPrefixedText();
754 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
755 $wgOut->setRobotpolicy( "noindex,nofollow" );
757 $sk = $wgUser->getSkin();
758 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
759 Namespace::getWikipedia() ) .
760 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
762 $text = str_replace( "$1" , $deleted, wfMsg( "deletedtext" ) );
763 $text = str_replace( "$2", $loglink, $text );
765 $wgOut->addHTML( "<p>" . $text );
766 $wgOut->returnToMain( false );
769 function doDeleteArticle( $title )
771 global $wgUser, $wgOut, $wgLang, $wpReason, $wgDeferredUpdateList;
773 $fname = "Article::doDeleteArticle";
774 $ns = $title->getNamespace();
775 $t = wfStrencode( $title->getDBkey() );
776 $id = $title->getArticleID();
778 if ( "" == $t ) {
779 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
780 return;
783 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
784 array_push( $wgDeferredUpdateList, $u );
786 # Move article and history to the "archive" table
787 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
788 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
789 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
790 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
791 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
792 wfQuery( $sql, DB_WRITE, $fname );
794 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
795 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
796 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
797 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
798 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
799 wfQuery( $sql, DB_WRITE, $fname );
801 # Now that it's safely backed up, delete it
803 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
804 "cur_title='{$t}'";
805 wfQuery( $sql, DB_WRITE, $fname );
807 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
808 "old_title='{$t}'";
809 wfQuery( $sql, DB_WRITE, $fname );
811 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
812 "rc_title='{$t}'";
813 wfQuery( $sql, DB_WRITE, $fname );
815 # Finally, clean up the link tables
817 if ( 0 != $id ) {
818 $t = wfStrencode( $title->getPrefixedDBkey() );
819 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
820 $res = wfQuery( $sql, DB_READ, $fname );
822 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
823 $now = wfTimestampNow();
824 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
825 $first = true;
827 while ( $s = wfFetchObject( $res ) ) {
828 $nt = Title::newFromDBkey( $s->l_from );
829 $lid = $nt->getArticleID();
831 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
832 $first = false;
833 $sql .= "({$lid},'{$t}')";
834 $sql2 .= "{$lid}";
836 $sql2 .= ")";
837 if ( ! $first ) {
838 wfQuery( $sql, DB_WRITE, $fname );
839 wfQuery( $sql2, DB_WRITE, $fname );
841 wfFreeResult( $res );
843 $sql = "DELETE FROM links WHERE l_to={$id}";
844 wfQuery( $sql, DB_WRITE, $fname );
846 $sql = "DELETE FROM links WHERE l_from='{$t}'";
847 wfQuery( $sql, DB_WRITE, $fname );
849 $sql = "DELETE FROM imagelinks WHERE il_from='{$t}'";
850 wfQuery( $sql, DB_WRITE, $fname );
852 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
853 wfQuery( $sql, DB_WRITE, $fname );
856 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
857 $art = $title->getPrefixedText();
858 $wpReason = wfCleanQueryVar( $wpReason );
859 $log->addEntry( str_replace( "$1", $art, wfMsg( "deletedarticle" ) ), $wpReason );
861 # Clear the cached article id so the interface doesn't act like we exist
862 $this->mTitle->resetArticleID( 0 );
863 $this->mTitle->mArticleID = 0;
866 function rollback()
868 global $wgUser, $wgLang, $wgOut, $from;
870 if ( ! $wgUser->isSysop() ) {
871 $wgOut->sysopRequired();
872 return;
875 # Replace all this user's current edits with the next one down
876 $tt = wfStrencode( $this->mTitle->getDBKey() );
877 $n = $this->mTitle->getNamespace();
879 # Get the last editor
880 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
881 $res = wfQuery( $sql, DB_READ );
882 if( ($x = wfNumRows( $res )) != 1 ) {
883 # Something wrong
884 $wgOut->addHTML( wfMsg( "notanarticle" ) );
885 return;
887 $s = wfFetchObject( $res );
888 $ut = wfStrencode( $s->cur_user_text );
889 $uid = $s->cur_user;
890 $pid = $s->cur_id;
892 $from = str_replace( '_', ' ', wfCleanQueryVar( $from ) );
893 if( $from != $s->cur_user_text ) {
894 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
895 $wgOut->addWikiText( wfMsg( "alreadyrolled",
896 htmlspecialchars( $this->mTitle->getPrefixedText()),
897 htmlspecialchars( $from ),
898 htmlspecialchars( $s->cur_user_text ) ) );
899 if($s->cur_comment != "") {
900 $wgOut->addHTML(
901 wfMsg("editcomment",
902 htmlspecialchars( $s->cur_comment ) ) );
904 return;
907 # Get the last edit not by this guy
908 $sql = "SELECT old_text,old_user,old_user_text
909 FROM old USE INDEX (name_title_timestamp)
910 WHERE old_namespace={$n} AND old_title='{$tt}'
911 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
912 ORDER BY inverse_timestamp LIMIT 1";
913 $res = wfQuery( $sql, DB_READ );
914 if( wfNumRows( $res ) != 1 ) {
915 # Something wrong
916 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
917 $wgOut->addHTML( wfMsg( "cantrollback" ) );
918 return;
920 $s = wfFetchObject( $res );
922 # Save it!
923 $newcomment = str_replace( "$1", $s->old_user_text, wfMsg( "revertpage" ) );
924 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
925 $wgOut->setRobotpolicy( "noindex,nofollow" );
926 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
927 $this->updateArticle( $s->old_text, $newcomment, 1, $this->mTitle->userIsWatching() );
929 $wgOut->returnToMain( false );
933 # Do standard deferred updates after page view
935 /* private */ function viewUpdates()
937 global $wgDeferredUpdateList;
939 if ( 0 != $this->getID() ) {
940 $u = new ViewCountUpdate( $this->getID() );
941 array_push( $wgDeferredUpdateList, $u );
942 $u = new SiteStatsUpdate( 1, 0, 0 );
943 array_push( $wgDeferredUpdateList, $u );
945 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
946 $this->mTitle->getDBkey() );
947 array_push( $wgDeferredUpdateList, $u );
951 # Do standard deferred updates after page edit.
952 # Every 1000th edit, prune the recent changes table.
954 /* private */ function editUpdates( $text )
956 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
958 wfSeedRandom();
959 if ( 0 == mt_rand( 0, 999 ) ) {
960 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
961 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
962 wfQuery( $sql, DB_WRITE );
964 $id = $this->getID();
965 $title = $this->mTitle->getPrefixedDBkey();
966 $adj = $this->mCountAdjustment;
968 if ( 0 != $id ) {
969 $u = new LinksUpdate( $id, $title );
970 array_push( $wgDeferredUpdateList, $u );
971 $u = new SiteStatsUpdate( 0, 1, $adj );
972 array_push( $wgDeferredUpdateList, $u );
973 $u = new SearchUpdate( $id, $title, $text );
974 array_push( $wgDeferredUpdateList, $u );
976 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(),
977 $this->mTitle->getDBkey() );
978 array_push( $wgDeferredUpdateList, $u );
980 if ( $this->getNamespace == NS_MEDIAWIKI ) {
981 $key = "$wgDBname:MediaWiki:title:" . $this->mTitle->getDBkey();
982 $wgMemc->delete( $key );
987 /* private */ function setOldSubtitle()
989 global $wgLang, $wgOut;
991 $td = $wgLang->timeanddate( $this->mTimestamp, true );
992 $r = str_replace( "$1", "{$td}", wfMsg( "revisionasof" ) );
993 $wgOut->setSubtitle( "({$r})" );
996 # This function is called right before saving the wikitext,
997 # so we can do things like signatures and links-in-context.
999 function preSaveTransform( $text )
1001 $s = "";
1002 while ( "" != $text ) {
1003 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
1004 $s .= $this->pstPass2( $p[0] );
1006 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
1007 else {
1008 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
1009 $s .= "<nowiki>{$q[0]}</nowiki>";
1010 $text = $q[1];
1013 return rtrim( $s );
1016 /* private */ function pstPass2( $text )
1018 global $wgUser, $wgLang, $wgLocaltimezone;
1020 # Signatures
1022 $n = $wgUser->getName();
1023 $k = $wgUser->getOption( "nickname" );
1024 if ( "" == $k ) { $k = $n; }
1025 if(isset($wgLocaltimezone)) {
1026 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1028 /* Note: this is an ugly timezone hack for the European wikis */
1029 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1030 " (" . date( "T" ) . ")";
1031 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1033 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1034 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1035 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1036 Namespace::getUser() ) . ":$n|$k]]", $text );
1038 # Context links: [[|name]] and [[name (context)|]]
1040 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1041 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1042 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1044 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1045 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1046 $p3 = "/\[\[([A-Za-z _]+):({$np}+)\\|]]/"; # [[namespace:page|]]
1047 $p4 = "/\[\[([A-Aa-z _]+):({$np}+) \\(({$np}+)\\)\\|]]/";
1048 # [[ns:page (cont)|]]
1049 $context = "";
1050 $t = $this->mTitle->getText();
1051 if ( preg_match( $conpat, $t, $m ) ) {
1052 $context = $m[2];
1054 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1055 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1056 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1058 if ( "" == $context ) {
1059 $text = preg_replace( $p2, "[[\\1]]", $text );
1060 } else {
1061 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1064 # {{SUBST:xxx}} variables
1066 $mw =& MagicWord::get( MAG_SUBST );
1067 $text = $mw->substituteCallback( $text, "replaceMsgVar" );
1069 return $text;
1072 /* Caching functions */
1074 function tryFileCache() {
1075 if($this->isFileCacheable()) {
1076 $touched = $this->mTouched;
1077 if( strpos( $this->mContent, "{{" ) !== false ) {
1078 # Expire pages with variable replacements in an hour
1079 $expire = wfUnix2Timestamp( time() - 3600 );
1080 $touched = max( $expire, $touched );
1082 $cache = new CacheManager( $this->mTitle );
1083 if($cache->isFileCacheGood( $touched )) {
1084 wfDebug( " tryFileCache() - about to load\n" );
1085 $cache->loadFromFileCache();
1086 exit;
1087 } else {
1088 wfDebug( " tryFileCache() - starting buffer\n" );
1089 if($cache->useGzip() && wfClientAcceptsGzip()) {
1090 /* For some reason, adding this header line over in
1091 CacheManager::saveToFileCache() fails on my test
1092 setup at home, though it works on the live install.
1093 Make double-sure... --brion */
1094 header( "Content-Encoding: gzip" );
1096 ob_start( array(&$cache, 'saveToFileCache' ) );
1098 } else {
1099 wfDebug( " tryFileCache() - not cacheable\n" );
1103 function isFileCacheable() {
1104 global $wgUser, $wgUseFileCache, $wgShowIPinHeader;
1105 global $action, $oldid, $diff, $redirect, $printable;
1106 return $wgUseFileCache
1107 and (!$wgShowIPinHeader)
1108 and ($this->getID() != 0)
1109 and ($wgUser->getId() == 0)
1110 and (!$wgUser->getNewtalk())
1111 and ($this->mTitle->getNamespace != Namespace::getSpecial())
1112 and ($action == "view")
1113 and (!isset($oldid))
1114 and (!isset($diff))
1115 and (!isset($redirect))
1116 and (!isset($printable))
1117 and (!$this->mRedirectedFrom);