Fixed silly bug that I just introduced. "0" == false
[mediawiki.git] / includes / Article.php
blob326cda56a4f48aed25a48428b9a6ec1d30be1e1d
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 $fname = "Article::getContent";
39 wfProfileIn( $fname );
41 if ( 0 == $this->getID() ) {
42 if ( "edit" == $action ) {
43 wfProfileOut( $fname );
44 return ""; # was "newarticletext", now moved above the box)
46 wfProfileOut( $fname );
47 return wfMsg( "noarticletext" );
48 } else {
49 $this->loadContent( $noredir );
51 if(
52 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
53 ( $this->mTitle->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
54 preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$this->mTitle->getText()) &&
55 $action=="view"
58 wfProfileOut( $fname );
59 return $this->mContent . "\n" .wfMsg("anontalkpagetext"); }
60 else {
61 if($action=="edit") {
62 if($section!="") {
63 if($section=="new") {
64 wfProfileOut( $fname );
65 return "";
68 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
69 $this->mContent, -1,
70 PREG_SPLIT_DELIM_CAPTURE);
71 if($section==0) {
72 wfProfileOut( $fname );
73 return trim($secs[0]);
74 } else {
75 wfProfileOut( $fname );
76 return trim($secs[$section*2-1] . $secs[$section*2]);
80 wfProfileOut( $fname );
81 return $this->mContent;
86 function loadContent( $noredir = false )
88 global $wgOut, $wgMwRedir;
89 global $oldid, $redirect; # From query
91 if ( $this->mContentLoaded ) return;
92 $fname = "Article::loadContent";
94 # Pre-fill content with error message so that if something
95 # fails we'll have something telling us what we intended.
97 $t = $this->mTitle->getPrefixedText();
98 if ( $oldid ) { $t .= ",oldid={$oldid}"; }
99 if ( $redirect ) { $t .= ",redirect={$redirect}"; }
100 $this->mContent = str_replace( "$1", $t, wfMsg( "missingarticle" ) );
102 if ( ! $oldid ) { # Retrieve current version
103 $id = $this->getID();
104 if ( 0 == $id ) return;
106 $sql = "SELECT " .
107 "cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched " .
108 "FROM cur WHERE cur_id={$id}";
109 $res = wfQuery( $sql, DB_READ, $fname );
110 if ( 0 == wfNumRows( $res ) ) { return; }
112 $s = wfFetchObject( $res );
114 # If we got a redirect, follow it (unless we've been told
115 # not to by either the function parameter or the query
116 if ( ( "no" != $redirect ) && ( false == $noredir ) &&
117 ( $wgMwRedir->matchStart( $s->cur_text ) ) ) {
118 if ( preg_match( "/\\[\\[([^\\]\\|]+)[\\]\\|]/",
119 $s->cur_text, $m ) ) {
120 $rt = Title::newFromText( $m[1] );
122 # Gotta hand redirects to special pages differently:
123 # Fill the HTTP response "Location" header and ignore
124 # the rest of the page we're on.
126 if ( $rt->getInterwiki() != "" ) {
127 $wgOut->redirect( $rt->getFullURL() ) ;
128 return;
130 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
131 $wgOut->redirect( wfLocalUrl(
132 $rt->getPrefixedURL() ) );
133 return;
135 $rid = $rt->getArticleID();
136 if ( 0 != $rid ) {
137 $sql = "SELECT cur_text,cur_timestamp,cur_user," .
138 "cur_counter,cur_touched FROM cur WHERE cur_id={$rid}";
139 $res = wfQuery( $sql, DB_READ, $fname );
141 if ( 0 != wfNumRows( $res ) ) {
142 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
143 $this->mTitle = $rt;
144 $s = wfFetchObject( $res );
149 $this->mContent = $s->cur_text;
150 $this->mUser = $s->cur_user;
151 $this->mCounter = $s->cur_counter;
152 $this->mTimestamp = $s->cur_timestamp;
153 $this->mTouched = $s->cur_touched;
154 $this->mTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
155 $this->mTitle->mRestrictionsLoaded = true;
156 wfFreeResult( $res );
157 } else { # oldid set, retrieve historical version
158 $sql = "SELECT old_text,old_timestamp,old_user FROM old " .
159 "WHERE old_id={$oldid}";
160 $res = wfQuery( $sql, DB_READ, $fname );
161 if ( 0 == wfNumRows( $res ) ) { return; }
163 $s = wfFetchObject( $res );
164 $this->mContent = $s->old_text;
165 $this->mUser = $s->old_user;
166 $this->mCounter = 0;
167 $this->mTimestamp = $s->old_timestamp;
168 wfFreeResult( $res );
170 $this->mContentLoaded = true;
173 function getID() { return $this->mTitle->getArticleID(); }
175 function getCount()
177 if ( -1 == $this->mCounter ) {
178 $id = $this->getID();
179 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
181 return $this->mCounter;
184 # Would the given text make this article a "good" article (i.e.,
185 # suitable for including in the article count)?
187 function isCountable( $text )
189 global $wgUseCommaCount, $wgMwRedir;
191 if ( 0 != $this->mTitle->getNamespace() ) { return 0; }
192 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
193 $token = ($wgUseCommaCount ? "," : "[[" );
194 if ( false === strstr( $text, $token ) ) { return 0; }
195 return 1;
198 # Load the field related to the last edit time of the article.
199 # This isn't necessary for all uses, so it's only done if needed.
201 /* private */ function loadLastEdit()
203 global $wgOut;
204 if ( -1 != $this->mUser ) return;
206 $sql = "SELECT cur_user,cur_user_text,cur_timestamp," .
207 "cur_comment,cur_minor_edit FROM cur WHERE " .
208 "cur_id=" . $this->getID();
209 $res = wfQuery( $sql, DB_READ, "Article::loadLastEdit" );
211 if ( wfNumRows( $res ) > 0 ) {
212 $s = wfFetchObject( $res );
213 $this->mUser = $s->cur_user;
214 $this->mUserText = $s->cur_user_text;
215 $this->mTimestamp = $s->cur_timestamp;
216 $this->mComment = $s->cur_comment;
217 $this->mMinorEdit = $s->cur_minor_edit;
221 function getTimestamp()
223 $this->loadLastEdit();
224 return $this->mTimestamp;
227 function getUser()
229 $this->loadLastEdit();
230 return $this->mUser;
233 function getUserText()
235 $this->loadLastEdit();
236 return $this->mUserText;
239 function getComment()
241 $this->loadLastEdit();
242 return $this->mComment;
245 function getMinorEdit()
247 $this->loadLastEdit();
248 return $this->mMinorEdit;
251 # This is the default action of the script: just view the page of
252 # the given title.
254 function view()
256 global $wgUser, $wgOut, $wgLang;
257 global $oldid, $diff; # From query
258 global $wgLinkCache;
259 $fname = "Article::view";
260 wfProfileIn( $fname );
262 $wgOut->setArticleFlag( true );
263 $wgOut->setRobotpolicy( "index,follow" );
265 # If we got diff and oldid in the query, we want to see a
266 # diff page instead of the article.
268 if ( isset( $diff ) ) {
269 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
270 $de = new DifferenceEngine( $oldid, $diff );
271 $de->showDiffPage();
272 wfProfileOut( $fname );
273 return;
275 $text = $this->getContent(); # May change wgTitle!
276 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
277 $wgOut->setHTMLTitle( $this->mTitle->getPrefixedText() .
278 " - " . wfMsg( "wikititlesuffix" ) );
280 # We're looking at an old revision
282 if ( $oldid ) {
283 $this->setOldSubtitle();
284 $wgOut->setRobotpolicy( "noindex,follow" );
286 if ( "" != $this->mRedirectedFrom ) {
287 $sk = $wgUser->getSkin();
288 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, "",
289 "redirect=no" );
290 $s = str_replace( "$1", $redir, wfMsg( "redirectedfrom" ) );
291 $wgOut->setSubtitle( $s );
293 $wgOut->checkLastModified( $this->mTouched );
294 $this->tryFileCache();
295 $wgLinkCache->preFill( $this->mTitle );
296 $wgOut->addWikiText( $text );
298 $this->viewUpdates();
299 wfProfileOut( $fname );
302 # Theoretically we could defer these whole insert and update
303 # functions for after display, but that's taking a big leap
304 # of faith, and we want to be able to report database
305 # errors at some point.
307 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
309 global $wgOut, $wgUser, $wgLinkCache, $wgMwRedir;
310 $fname = "Article::insertNewArticle";
312 $ns = $this->mTitle->getNamespace();
313 $ttl = $this->mTitle->getDBkey();
314 $text = $this->preSaveTransform( $text );
315 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
316 else { $redir = 0; }
318 $now = wfTimestampNow();
319 $won = wfInvertTimestamp( $now );
320 wfSeedRandom();
321 $rand = number_format( mt_rand() / mt_getrandmax(), 12, ".", "" );
322 $sql = "INSERT INTO cur (cur_namespace,cur_title,cur_text," .
323 "cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter," .
324 "cur_restrictions,cur_user_text,cur_is_redirect," .
325 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$ns},'" . wfStrencode( $ttl ) . "', '" .
326 wfStrencode( $text ) . "', '" .
327 wfStrencode( $summary ) . "', '" .
328 $wgUser->getID() . "', '{$now}', " .
329 ( $isminor ? 1 : 0 ) . ", 0, '', '" .
330 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
331 $res = wfQuery( $sql, DB_WRITE, $fname );
333 $newid = wfInsertId();
334 $this->mTitle->resetArticleID( $newid );
336 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
337 "rc_namespace,rc_title,rc_new,rc_minor,rc_cur_id,rc_user," .
338 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid,rc_bot) VALUES (" .
339 "'{$now}','{$now}',{$ns},'" . wfStrencode( $ttl ) . "',1," .
340 ( $isminor ? 1 : 0 ) . ",{$newid}," . $wgUser->getID() . ",'" .
341 wfStrencode( $wgUser->getName() ) . "','" .
342 wfStrencode( $summary ) . "',0,0," .
343 ( $wgUser->isBot() ? 1 : 0 ) . ")";
344 wfQuery( $sql, DB_WRITE, $fname );
345 if ($watchthis) {
346 if(!$this->mTitle->userIsWatching()) $this->watch();
347 } else {
348 if ( $this->mTitle->userIsWatching() ) {
349 $this->unwatch();
353 $this->showArticle( $text, wfMsg( "newarticle" ) );
356 function updateArticle( $text, $summary, $minor, $watchthis, $section="" )
358 global $wgOut, $wgUser, $wgLinkCache;
359 global $wgDBtransactions, $wgMwRedir;
360 $fname = "Article::updateArticle";
362 $this->loadLastEdit();
364 // insert updated section into old text if we have only edited part
365 // of the article
366 if ($section != "") {
367 $oldtext=$this->getContent();
368 if($section=="new") {
369 if($summary) $subject="== {$summary} ==\n\n";
370 $text=$oldtext."\n\n".$subject.$text;
371 } else {
372 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
373 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
374 $secs[$section*2]=$text."\n\n"; // replace with edited
375 if($section) { $secs[$section*2-1]=""; } // erase old headline
376 $text=join("",$secs);
379 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
380 if ( $minor ) { $me2 = 1; } else { $me2 = 0; }
381 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ")[^\\n]+)/i", $text, $m ) ) {
382 $redir = 1;
383 $text = $m[1] . "\n"; # Remove all content but redirect
385 else { $redir = 0; }
387 $text = $this->preSaveTransform( $text );
389 # Update article, but only if changed.
391 if( $wgDBtransactions ) {
392 $sql = "BEGIN";
393 wfQuery( $sql, DB_WRITE );
395 $oldtext = $this->getContent( true );
397 if ( 0 != strcmp( $text, $oldtext ) ) {
398 $this->mCountAdjustment = $this->isCountable( $text )
399 - $this->isCountable( $oldtext );
401 $now = wfTimestampNow();
402 $won = wfInvertTimestamp( $now );
403 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
404 "',cur_comment='" . wfStrencode( $summary ) .
405 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
406 ",cur_timestamp='{$now}',cur_user_text='" .
407 wfStrencode( $wgUser->getName() ) .
408 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
409 "WHERE cur_id=" . $this->getID() .
410 " AND cur_timestamp='" . $this->getTimestamp() . "'";
411 $res = wfQuery( $sql, DB_WRITE, $fname );
413 if( wfAffectedRows() == 0 ) {
414 /* Belated edit conflict! Run away!! */
415 return false;
418 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
419 "old_comment,old_user,old_user_text,old_timestamp," .
420 "old_minor_edit,inverse_timestamp) VALUES (" .
421 $this->mTitle->getNamespace() . ", '" .
422 wfStrencode( $this->mTitle->getDBkey() ) . "', '" .
423 wfStrencode( $oldtext ) . "', '" .
424 wfStrencode( $this->getComment() ) . "', " .
425 $this->getUser() . ", '" .
426 wfStrencode( $this->getUserText() ) . "', '" .
427 $this->getTimestamp() . "', " . $me1 . ", '" .
428 wfInvertTimestamp( $this->getTimestamp() ) . "')";
429 $res = wfQuery( $sql, DB_WRITE, $fname );
430 $oldid = wfInsertID( $res );
432 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
433 "rc_namespace,rc_title,rc_new,rc_minor,rc_bot,rc_cur_id,rc_user," .
434 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid) VALUES (" .
435 "'{$now}','{$now}'," . $this->mTitle->getNamespace() . ",'" .
436 wfStrencode( $this->mTitle->getDBkey() ) . "',0,{$me2}," .
437 ( $wgUser->isBot() ? 1 : 0 ) . "," .
438 $this->getID() . "," . $wgUser->getID() . ",'" .
439 wfStrencode( $wgUser->getName() ) . "','" .
440 wfStrencode( $summary ) . "',0,{$oldid})";
441 wfQuery( $sql, DB_WRITE, $fname );
443 $sql = "UPDATE recentchanges SET rc_this_oldid={$oldid} " .
444 "WHERE rc_namespace=" . $this->mTitle->getNamespace() . " AND " .
445 "rc_title='" . wfStrencode( $this->mTitle->getDBkey() ) . "' AND " .
446 "rc_timestamp='" . $this->getTimestamp() . "'";
447 wfQuery( $sql, DB_WRITE, $fname );
449 $sql = "UPDATE recentchanges SET rc_cur_time='{$now}' " .
450 "WHERE rc_cur_id=" . $this->getID();
451 wfQuery( $sql, DB_WRITE, $fname );
453 if( $wgDBtransactions ) {
454 $sql = "COMMIT";
455 wfQuery( $sql, DB_WRITE );
458 if ($watchthis) {
459 if (!$this->mTitle->userIsWatching()) $this->watch();
460 } else {
461 if ( $this->mTitle->userIsWatching() ) {
462 $this->unwatch();
466 $this->showArticle( $text, wfMsg( "updated" ) );
467 return true;
470 # After we've either updated or inserted the article, update
471 # the link tables and redirect to the new page.
473 function showArticle( $text, $subtitle )
475 global $wgOut, $wgUser, $wgLinkCache, $wgUseBetterLinksUpdate;
476 global $wgMwRedir;
478 $wgLinkCache = new LinkCache();
480 # Get old version of link table to allow incremental link updates
481 if ( $wgUseBetterLinksUpdate ) {
482 $wgLinkCache->preFill( $this->mTitle );
483 $wgLinkCache->clear();
486 # Now update the link cache by parsing the text
487 $wgOut = new OutputPage();
488 $wgOut->addWikiText( $text );
490 $this->editUpdates( $text );
491 if( $wgMwRedir->matchStart( $text ) )
492 $r = "redirect=no";
493 else
494 $r = "";
495 $wgOut->redirect( wfLocalUrl( $this->mTitle->getPrefixedURL(), $r ) );
498 # Add this page to my watchlist
500 function watch( $add = true )
502 global $wgUser, $wgOut, $wgLang;
503 global $wgDeferredUpdateList;
505 if ( 0 == $wgUser->getID() ) {
506 $wgOut->errorpage( "watchnologin", "watchnologintext" );
507 return;
509 if ( wfReadOnly() ) {
510 $wgOut->readOnlyPage();
511 return;
513 if( $add )
514 $wgUser->addWatch( $this->mTitle );
515 else
516 $wgUser->removeWatch( $this->mTitle );
518 $wgOut->setPagetitle( wfMsg( $add ? "addedwatch" : "removedwatch" ) );
519 $wgOut->setRobotpolicy( "noindex,follow" );
521 $sk = $wgUser->getSkin() ;
522 $link = $sk->makeKnownLink ( $this->mTitle->getPrefixedText() ) ;
524 if($add)
525 $text = wfMsg( "addedwatchtext", $link );
526 else
527 $text = wfMsg( "removedwatchtext", $link );
528 $wgOut->addHTML( $text );
530 $up = new UserUpdate();
531 array_push( $wgDeferredUpdateList, $up );
533 $wgOut->returnToMain( false );
536 function unwatch()
538 $this->watch( false );
541 # This shares a lot of issues (and code) with Recent Changes
543 function history()
545 global $wgUser, $wgOut, $wgLang, $offset, $limit;
547 # If page hasn't changed, client can cache this
549 $wgOut->checkLastModified( $this->getTimestamp() );
550 $fname = "Article::history";
551 wfProfileIn( $fname );
553 $wgOut->setPageTitle( $this->mTitle->getPRefixedText() );
554 $wgOut->setSubtitle( wfMsg( "revhistory" ) );
555 $wgOut->setArticleFlag( false );
556 $wgOut->setRobotpolicy( "noindex,nofollow" );
558 if( $this->mTitle->getArticleID() == 0 ) {
559 $wgOut->addHTML( wfMsg( "nohistory" ) );
560 wfProfileOut( $fname );
561 return;
564 $offset = (int)$offset;
565 $limit = (int)$limit;
566 if( $limit == 0 ) $limit = 50;
567 $namespace = $this->mTitle->getNamespace();
568 $title = $this->mTitle->getText();
569 $sql = "SELECT old_id,old_user," .
570 "old_comment,old_user_text,old_timestamp,old_minor_edit ".
571 "FROM old USE INDEX (name_title_timestamp) " .
572 "WHERE old_namespace={$namespace} AND " .
573 "old_title='" . wfStrencode( $this->mTitle->getDBkey() ) . "' " .
574 "ORDER BY inverse_timestamp LIMIT $offset, $limit";
575 $res = wfQuery( $sql, DB_READ, "Article::history" );
577 $revs = wfNumRows( $res );
578 if( $this->mTitle->getArticleID() == 0 ) {
579 $wgOut->addHTML( wfMsg( "nohistory" ) );
580 wfProfileOut( $fname );
581 return;
584 $sk = $wgUser->getSkin();
585 $numbar = wfViewPrevNext(
586 $offset, $limit,
587 $this->mTitle->getPrefixedText(),
588 "action=history" );
589 $s = $numbar;
590 $s .= $sk->beginHistoryList();
592 if($offset == 0 )
593 $s .= $sk->historyLine( $this->getTimestamp(), $this->getUser(),
594 $this->getUserText(), $namespace,
595 $title, 0, $this->getComment(),
596 ( $this->getMinorEdit() > 0 ) );
598 $revs = wfNumRows( $res );
599 while ( $line = wfFetchObject( $res ) ) {
600 $s .= $sk->historyLine( $line->old_timestamp, $line->old_user,
601 $line->old_user_text, $namespace,
602 $title, $line->old_id,
603 $line->old_comment, ( $line->old_minor_edit > 0 ) );
605 $s .= $sk->endHistoryList();
606 $s .= $numbar;
607 $wgOut->addHTML( $s );
608 wfProfileOut( $fname );
611 function protect( $limit = "sysop" )
613 global $wgUser, $wgOut;
615 if ( ! $wgUser->isSysop() ) {
616 $wgOut->sysopRequired();
617 return;
619 if ( wfReadOnly() ) {
620 $wgOut->readOnlyPage();
621 return;
623 $id = $this->mTitle->getArticleID();
624 if ( 0 == $id ) {
625 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
626 return;
628 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
629 "cur_restrictions='{$limit}' WHERE cur_id={$id}";
630 wfQuery( $sql, DB_WRITE, "Article::protect" );
632 $wgOut->redirect( wfLocalUrl( $this->mTitle->getPrefixedURL() ) );
635 function unprotect()
637 return $this->protect( "" );
640 function delete()
642 global $wgUser, $wgOut;
643 global $wpConfirm, $wpReason, $image, $oldimage;
645 # Anybody can delete old revisions of images; only sysops
646 # can delete articles and current images
648 if ( ( ! $oldimage ) && ( ! $wgUser->isSysop() ) ) {
649 $wgOut->sysopRequired();
650 return;
652 if ( wfReadOnly() ) {
653 $wgOut->readOnlyPage();
654 return;
657 # Better double-check that it hasn't been deleted yet!
658 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
659 if ( ( "" == trim( $this->mTitle->getText() ) )
660 or ( $this->mTitle->getArticleId() == 0 ) ) {
661 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
662 return;
665 # determine whether this page has earlier revisions
666 # and insert a warning if it does
667 # we select the text because it might be useful below
668 $sql="SELECT old_text FROM old WHERE old_namespace=0 and old_title='" . wfStrencode($this->mTitle->getPrefixedDBkey())."' ORDER BY inverse_timestamp LIMIT 1";
669 $res=wfQuery($sql, DB_READ, $fname);
670 if( ($old=wfFetchObject($res)) && !$wpConfirm ) {
671 $skin=$wgUser->getSkin();
672 $wgOut->addHTML("<B>".wfMsg("historywarning"));
673 $wgOut->addHTML( $skin->historyLink() ."</B><P>");
676 $sql="SELECT cur_text FROM cur WHERE cur_namespace=0 and cur_title='" . wfStrencode($this->mTitle->getPrefixedDBkey())."'";
677 $res=wfQuery($sql, DB_READ, $fname);
678 if( ($s=wfFetchObject($res))) {
680 # if this is a mini-text, we can paste part of it into the deletion reason
682 #if this is empty, an earlier revision may contain "useful" text
683 if($s->cur_text!="") {
684 $text=$s->cur_text;
685 } else {
686 if($old) {
687 $text=$old->old_text;
688 $blanked=1;
693 $length=strlen($text);
695 # this should not happen, since it is not possible to store an empty, new
696 # page. Let's insert a standard text in case it does, though
697 if($length==0 && !$wpReason) { $wpReason=wfmsg("exblank");}
700 if($length < 500 && !$wpReason) {
702 # comment field=255, let's grep the first 150 to have some user
703 # space left
704 $text=substr($text,0,150);
705 # let's strip out newlines and HTML tags
706 $text=preg_replace("/\"/","'",$text);
707 $text=preg_replace("/\</","&lt;",$text);
708 $text=preg_replace("/\>/","&gt;",$text);
709 $text=preg_replace("/[\n\r]/","",$text);
710 if(!$blanked) {
711 $wpReason=wfMsg("excontent"). " '".$text;
712 } else {
713 $wpReason=wfMsg("exbeforeblank") . " '".$text;
715 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
716 $wpReason.="'";
720 return $this->confirmDelete();
723 function confirmDelete( $par = "" )
725 global $wgOut;
727 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
728 $wgOut->setSubtitle( wfMsg( "deletesub", $sub ) );
729 $wgOut->setRobotpolicy( "noindex,nofollow" );
730 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
732 $t = $this->mTitle->getPrefixedURL();
734 $formaction = wfEscapeHTML( wfLocalUrl( $t, "action=delete" . $par ) );
735 $confirm = wfMsg( "confirm" );
736 $check = wfMsg( "confirmcheck" );
737 $delcom = wfMsg( "deletecomment" );
739 $wgOut->addHTML( "
740 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
741 <table border=0><tr><td align=right>
742 {$delcom}:</td><td align=left>
743 <input type=text size=60 name=\"wpReason\" value=\"{$wpReason}\">
744 </td></tr><tr><td>&nbsp;</td></tr>
745 <tr><td align=right>
746 <input type=checkbox name=\"wpConfirm\" value='1' id=\"wpConfirm\">
747 </td><td><label for=\"wpConfirm\">{$check}</label></td>
748 </tr><tr><td>&nbsp;</td><td>
749 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
750 </td></tr></table></form>\n" );
752 $wgOut->returnToMain( false );
755 function doDelete()
757 global $wgOut, $wgUser, $wgLang;
758 global $wpReason;
759 $fname = "Article::doDelete";
761 $this->doDeleteArticle( $this->mTitle );
762 $deleted = $this->mTitle->getPrefixedText();
764 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
765 $wgOut->setRobotpolicy( "noindex,nofollow" );
767 $sk = $wgUser->getSkin();
768 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
769 Namespace::getWikipedia() ) .
770 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
772 $text = str_replace( "$1" , $deleted, wfMsg( "deletedtext" ) );
773 $text = str_replace( "$2", $loglink, $text );
775 $wgOut->addHTML( "<p>" . $text );
776 $wgOut->returnToMain( false );
779 function doDeleteArticle( $title )
781 global $wgUser, $wgOut, $wgLang, $wpReason, $wgDeferredUpdateList;
783 $fname = "Article::doDeleteArticle";
784 $ns = $title->getNamespace();
785 $t = wfStrencode( $title->getDBkey() );
786 $id = $title->getArticleID();
788 if ( "" == $t ) {
789 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
790 return;
793 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
794 array_push( $wgDeferredUpdateList, $u );
796 # Move article and history to the "archive" table
797 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
798 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
799 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
800 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
801 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
802 wfQuery( $sql, DB_WRITE, $fname );
804 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
805 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
806 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
807 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
808 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
809 wfQuery( $sql, DB_WRITE, $fname );
811 # Now that it's safely backed up, delete it
813 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
814 "cur_title='{$t}'";
815 wfQuery( $sql, DB_WRITE, $fname );
817 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
818 "old_title='{$t}'";
819 wfQuery( $sql, DB_WRITE, $fname );
821 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
822 "rc_title='{$t}'";
823 wfQuery( $sql, DB_WRITE, $fname );
825 # Finally, clean up the link tables
827 if ( 0 != $id ) {
828 $t = wfStrencode( $title->getPrefixedDBkey() );
829 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
830 $res = wfQuery( $sql, DB_READ, $fname );
832 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
833 $now = wfTimestampNow();
834 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
835 $first = true;
837 while ( $s = wfFetchObject( $res ) ) {
838 $nt = Title::newFromDBkey( $s->l_from );
839 $lid = $nt->getArticleID();
841 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
842 $first = false;
843 $sql .= "({$lid},'{$t}')";
844 $sql2 .= "{$lid}";
846 $sql2 .= ")";
847 if ( ! $first ) {
848 wfQuery( $sql, DB_WRITE, $fname );
849 wfQuery( $sql2, DB_WRITE, $fname );
851 wfFreeResult( $res );
853 $sql = "DELETE FROM links WHERE l_to={$id}";
854 wfQuery( $sql, DB_WRITE, $fname );
856 $sql = "DELETE FROM links WHERE l_from='{$t}'";
857 wfQuery( $sql, DB_WRITE, $fname );
859 $sql = "DELETE FROM imagelinks WHERE il_from='{$t}'";
860 wfQuery( $sql, DB_WRITE, $fname );
862 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
863 wfQuery( $sql, DB_WRITE, $fname );
866 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
867 $art = $title->getPrefixedText();
868 $wpReason = wfCleanQueryVar( $wpReason );
869 $log->addEntry( str_replace( "$1", $art, wfMsg( "deletedarticle" ) ), $wpReason );
871 # Clear the cached article id so the interface doesn't act like we exist
872 $this->mTitle->resetArticleID( 0 );
873 $this->mTitle->mArticleID = 0;
876 function rollback()
878 global $wgUser, $wgLang, $wgOut, $from;
880 if ( ! $wgUser->isSysop() ) {
881 $wgOut->sysopRequired();
882 return;
885 # Replace all this user's current edits with the next one down
886 $tt = wfStrencode( $this->mTitle->getDBKey() );
887 $n = $this->mTitle->getNamespace();
889 # Get the last editor
890 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
891 $res = wfQuery( $sql, DB_READ );
892 if( ($x = wfNumRows( $res )) != 1 ) {
893 # Something wrong
894 $wgOut->addHTML( wfMsg( "notanarticle" ) );
895 return;
897 $s = wfFetchObject( $res );
898 $ut = wfStrencode( $s->cur_user_text );
899 $uid = $s->cur_user;
900 $pid = $s->cur_id;
902 $from = str_replace( '_', ' ', wfCleanQueryVar( $from ) );
903 if( $from != $s->cur_user_text ) {
904 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
905 $wgOut->addWikiText( wfMsg( "alreadyrolled",
906 htmlspecialchars( $this->mTitle->getPrefixedText()),
907 htmlspecialchars( $from ),
908 htmlspecialchars( $s->cur_user_text ) ) );
909 if($s->cur_comment != "") {
910 $wgOut->addHTML(
911 wfMsg("editcomment",
912 htmlspecialchars( $s->cur_comment ) ) );
914 return;
917 # Get the last edit not by this guy
918 $sql = "SELECT old_text,old_user,old_user_text
919 FROM old USE INDEX (name_title_timestamp)
920 WHERE old_namespace={$n} AND old_title='{$tt}'
921 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
922 ORDER BY inverse_timestamp LIMIT 1";
923 $res = wfQuery( $sql, DB_READ );
924 if( wfNumRows( $res ) != 1 ) {
925 # Something wrong
926 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
927 $wgOut->addHTML( wfMsg( "cantrollback" ) );
928 return;
930 $s = wfFetchObject( $res );
932 # Save it!
933 $newcomment = str_replace( "$1", $s->old_user_text, wfMsg( "revertpage" ) );
934 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
935 $wgOut->setRobotpolicy( "noindex,nofollow" );
936 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
937 $this->updateArticle( $s->old_text, $newcomment, 1, $this->mTitle->userIsWatching() );
939 $wgOut->returnToMain( false );
943 # Do standard deferred updates after page view
945 /* private */ function viewUpdates()
947 global $wgDeferredUpdateList;
949 if ( 0 != $this->getID() ) {
950 $u = new ViewCountUpdate( $this->getID() );
951 array_push( $wgDeferredUpdateList, $u );
952 $u = new SiteStatsUpdate( 1, 0, 0 );
953 array_push( $wgDeferredUpdateList, $u );
955 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
956 $this->mTitle->getDBkey() );
957 array_push( $wgDeferredUpdateList, $u );
961 # Do standard deferred updates after page edit.
962 # Every 1000th edit, prune the recent changes table.
964 /* private */ function editUpdates( $text )
966 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
968 wfSeedRandom();
969 if ( 0 == mt_rand( 0, 999 ) ) {
970 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
971 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
972 wfQuery( $sql, DB_WRITE );
974 $id = $this->getID();
975 $title = $this->mTitle->getPrefixedDBkey();
976 $adj = $this->mCountAdjustment;
978 if ( 0 != $id ) {
979 $u = new LinksUpdate( $id, $title );
980 array_push( $wgDeferredUpdateList, $u );
981 $u = new SiteStatsUpdate( 0, 1, $adj );
982 array_push( $wgDeferredUpdateList, $u );
983 $u = new SearchUpdate( $id, $title, $text );
984 array_push( $wgDeferredUpdateList, $u );
986 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(),
987 $this->mTitle->getDBkey() );
988 array_push( $wgDeferredUpdateList, $u );
990 if ( $this->getNamespace == NS_MEDIAWIKI ) {
991 $wgMemc->delete( "$wgDBname:messages" );
996 /* private */ function setOldSubtitle()
998 global $wgLang, $wgOut;
1000 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1001 $r = str_replace( "$1", "{$td}", wfMsg( "revisionasof" ) );
1002 $wgOut->setSubtitle( "({$r})" );
1005 # This function is called right before saving the wikitext,
1006 # so we can do things like signatures and links-in-context.
1008 function preSaveTransform( $text )
1010 $s = "";
1011 while ( "" != $text ) {
1012 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
1013 $s .= $this->pstPass2( $p[0] );
1015 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
1016 else {
1017 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
1018 $s .= "<nowiki>{$q[0]}</nowiki>";
1019 $text = $q[1];
1022 return rtrim( $s );
1025 /* private */ function pstPass2( $text )
1027 global $wgUser, $wgLang, $wgLocaltimezone;
1029 # Signatures
1031 $n = $wgUser->getName();
1032 $k = $wgUser->getOption( "nickname" );
1033 if ( "" == $k ) { $k = $n; }
1034 if(isset($wgLocaltimezone)) {
1035 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1037 /* Note: this is an ugly timezone hack for the European wikis */
1038 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1039 " (" . date( "T" ) . ")";
1040 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1042 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1043 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1044 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1045 Namespace::getUser() ) . ":$n|$k]]", $text );
1047 # Context links: [[|name]] and [[name (context)|]]
1049 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1050 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1051 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1053 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1054 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1055 $p3 = "/\[\[([A-Za-z _]+):({$np}+)\\|]]/"; # [[namespace:page|]]
1056 $p4 = "/\[\[([A-Aa-z _]+):({$np}+) \\(({$np}+)\\)\\|]]/";
1057 # [[ns:page (cont)|]]
1058 $context = "";
1059 $t = $this->mTitle->getText();
1060 if ( preg_match( $conpat, $t, $m ) ) {
1061 $context = $m[2];
1063 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1064 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1065 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1067 if ( "" == $context ) {
1068 $text = preg_replace( $p2, "[[\\1]]", $text );
1069 } else {
1070 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1073 # {{SUBST:xxx}} variables
1075 $mw =& MagicWord::get( MAG_SUBST );
1076 $text = $mw->substituteCallback( $text, "replaceMsgVar" );
1078 return $text;
1081 /* Caching functions */
1083 function tryFileCache() {
1084 if($this->isFileCacheable()) {
1085 $touched = $this->mTouched;
1086 if( strpos( $this->mContent, "{{" ) !== false ) {
1087 # Expire pages with variable replacements in an hour
1088 $expire = wfUnix2Timestamp( time() - 3600 );
1089 $touched = max( $expire, $touched );
1091 $cache = new CacheManager( $this->mTitle );
1092 if($cache->isFileCacheGood( $touched )) {
1093 wfDebug( " tryFileCache() - about to load\n" );
1094 $cache->loadFromFileCache();
1095 exit;
1096 } else {
1097 wfDebug( " tryFileCache() - starting buffer\n" );
1098 if($cache->useGzip() && wfClientAcceptsGzip()) {
1099 /* For some reason, adding this header line over in
1100 CacheManager::saveToFileCache() fails on my test
1101 setup at home, though it works on the live install.
1102 Make double-sure... --brion */
1103 header( "Content-Encoding: gzip" );
1105 ob_start( array(&$cache, 'saveToFileCache' ) );
1107 } else {
1108 wfDebug( " tryFileCache() - not cacheable\n" );
1112 function isFileCacheable() {
1113 global $wgUser, $wgUseFileCache, $wgShowIPinHeader;
1114 global $action, $oldid, $diff, $redirect, $printable;
1115 return $wgUseFileCache
1116 and (!$wgShowIPinHeader)
1117 and ($this->getID() != 0)
1118 and ($wgUser->getId() == 0)
1119 and (!$wgUser->getNewtalk())
1120 and ($this->mTitle->getNamespace != Namespace::getSpecial())
1121 and ($action == "view")
1122 and (!isset($oldid))
1123 and (!isset($diff))
1124 and (!isset($redirect))
1125 and (!isset($printable))
1126 and (!$this->mRedirectedFrom);