Some bug fixes, munge more charset stuff
[mediawiki.git] / includes / Article.php
blob95ef788b14ec7d32d4c8e40d54d926e99d2a8037
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 /* CHECK MERGE @@@
9 TEST THIS @@@
11 * s/\$wgTitle/\$this->mTitle/ performed, many replacements
12 * mTitle variable added to class
15 include_once( "CacheManager.php" );
17 class Article {
18 /* private */ var $mContent, $mContentLoaded;
19 /* private */ var $mUser, $mTimestamp, $mUserText;
20 /* private */ var $mCounter, $mComment, $mCountAdjustment;
21 /* private */ var $mMinorEdit, $mRedirectedFrom;
22 /* private */ var $mTouched, $mFileCache, $mTitle;
24 function Article( &$title ) {
25 $this->mTitle =& $title;
26 $this->clear();
29 /* private */ function clear()
31 $this->mContentLoaded = false;
32 $this->mUser = $this->mCounter = -1; # Not loaded
33 $this->mRedirectedFrom = $this->mUserText =
34 $this->mTimestamp = $this->mComment = $this->mFileCache = "";
35 $this->mCountAdjustment = 0;
36 $this->mTouched = "19700101000000";
39 # Note that getContent/loadContent may follow redirects if
40 # not told otherwise, and so may cause a change to mTitle.
42 function getContent( $noredir = false )
44 global $action,$section,$count; # From query string
45 $fname = "Article::getContent";
46 wfProfileIn( $fname );
48 if ( 0 == $this->getID() ) {
49 if ( "edit" == $action ) {
50 wfProfileOut( $fname );
51 return ""; # was "newarticletext", now moved above the box)
53 wfProfileOut( $fname );
54 return wfMsg( "noarticletext" );
55 } else {
56 $this->loadContent( $noredir );
58 if(
59 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
60 ( $this->mTitle->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
61 preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$this->mTitle->getText()) &&
62 $action=="view"
65 wfProfileOut( $fname );
66 return $this->mContent . "\n" .wfMsg("anontalkpagetext"); }
67 else {
68 if($action=="edit") {
69 if($section!="") {
70 if($section=="new") {
71 wfProfileOut( $fname );
72 return "";
75 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
76 $this->mContent, -1,
77 PREG_SPLIT_DELIM_CAPTURE);
78 if($section==0) {
79 wfProfileOut( $fname );
80 return trim($secs[0]);
81 } else {
82 wfProfileOut( $fname );
83 return trim($secs[$section*2-1] . $secs[$section*2]);
87 wfProfileOut( $fname );
88 return $this->mContent;
93 function loadContent( $noredir = false )
95 global $wgOut, $wgMwRedir;
96 global $oldid, $redirect; # From query
98 if ( $this->mContentLoaded ) return;
99 $fname = "Article::loadContent";
101 # Pre-fill content with error message so that if something
102 # fails we'll have something telling us what we intended.
104 $t = $this->mTitle->getPrefixedText();
105 if ( isset( $oldid ) ) {
106 $oldid = IntVal( $oldid );
107 $t .= ",oldid={$oldid}";
109 if ( isset( $redirect ) ) {
110 $redirect = ($redirect == "no") ? "no" : "yes";
111 $t .= ",redirect={$redirect}";
113 $this->mContent = wfMsg( "missingarticle", $t );
115 if ( ! $oldid ) { # Retrieve current version
116 $id = $this->getID();
117 if ( 0 == $id ) return;
119 $sql = "SELECT " .
120 "cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched " .
121 "FROM cur WHERE cur_id={$id}";
122 wfDebug( "$sql\n" );
123 $res = wfQuery( $sql, DB_READ, $fname );
124 if ( 0 == wfNumRows( $res ) ) {
125 return;
128 $s = wfFetchObject( $res );
129 # If we got a redirect, follow it (unless we've been told
130 # not to by either the function parameter or the query
131 if ( ( "no" != $redirect ) && ( false == $noredir ) &&
132 ( $wgMwRedir->matchStart( $s->cur_text ) ) ) {
133 if ( preg_match( "/\\[\\[([^\\]\\|]+)[\\]\\|]/",
134 $s->cur_text, $m ) ) {
135 $rt = Title::newFromText( $m[1] );
137 # Gotta hand redirects to special pages differently:
138 # Fill the HTTP response "Location" header and ignore
139 # the rest of the page we're on.
141 if ( $rt->getInterwiki() != "" ) {
142 $wgOut->redirect( $rt->getFullURL() ) ;
143 return;
145 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
146 $wgOut->redirect( wfLocalUrl(
147 $rt->getPrefixedURL() ) );
148 return;
150 $rid = $rt->getArticleID();
151 if ( 0 != $rid ) {
152 $sql = "SELECT cur_text,cur_timestamp,cur_user," .
153 "cur_counter,cur_restrictions,cur_touched FROM cur WHERE cur_id={$rid}";
154 $res = wfQuery( $sql, DB_READ, $fname );
156 if ( 0 != wfNumRows( $res ) ) {
157 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
158 $this->mTitle = $rt;
159 $s = wfFetchObject( $res );
165 $this->mContent = $s->cur_text;
166 $this->mUser = $s->cur_user;
167 $this->mCounter = $s->cur_counter;
168 $this->mTimestamp = $s->cur_timestamp;
169 $this->mTouched = $s->cur_touched;
170 $this->mTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
171 $this->mTitle->mRestrictionsLoaded = true;
172 wfFreeResult( $res );
173 } else { # oldid set, retrieve historical version
174 $sql = "SELECT old_text,old_timestamp,old_user FROM old " .
175 "WHERE old_id={$oldid}";
176 $res = wfQuery( $sql, DB_READ, $fname );
177 if ( 0 == wfNumRows( $res ) ) { return; }
179 $s = wfFetchObject( $res );
180 $this->mContent = $s->old_text;
181 $this->mUser = $s->old_user;
182 $this->mCounter = 0;
183 $this->mTimestamp = $s->old_timestamp;
184 wfFreeResult( $res );
186 $this->mContentLoaded = true;
189 function getID() {
190 if( $this->mTitle ) {
191 return $this->mTitle->getArticleID();
192 } else {
193 return 0;
197 function getCount()
199 if ( -1 == $this->mCounter ) {
200 $id = $this->getID();
201 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
203 return $this->mCounter;
206 # Would the given text make this article a "good" article (i.e.,
207 # suitable for including in the article count)?
209 function isCountable( $text )
211 global $wgUseCommaCount, $wgMwRedir;
213 if ( 0 != $this->mTitle->getNamespace() ) { return 0; }
214 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
215 $token = ($wgUseCommaCount ? "," : "[[" );
216 if ( false === strstr( $text, $token ) ) { return 0; }
217 return 1;
220 # Load the field related to the last edit time of the article.
221 # This isn't necessary for all uses, so it's only done if needed.
223 /* private */ function loadLastEdit()
225 global $wgOut;
226 if ( -1 != $this->mUser ) return;
228 $sql = "SELECT cur_user,cur_user_text,cur_timestamp," .
229 "cur_comment,cur_minor_edit FROM cur WHERE " .
230 "cur_id=" . $this->getID();
231 $res = wfQuery( $sql, DB_READ, "Article::loadLastEdit" );
233 if ( wfNumRows( $res ) > 0 ) {
234 $s = wfFetchObject( $res );
235 $this->mUser = $s->cur_user;
236 $this->mUserText = $s->cur_user_text;
237 $this->mTimestamp = $s->cur_timestamp;
238 $this->mComment = $s->cur_comment;
239 $this->mMinorEdit = $s->cur_minor_edit;
243 function getTimestamp()
245 $this->loadLastEdit();
246 return $this->mTimestamp;
249 function getUser()
251 $this->loadLastEdit();
252 return $this->mUser;
255 function getUserText()
257 $this->loadLastEdit();
258 return $this->mUserText;
261 function getComment()
263 $this->loadLastEdit();
264 return $this->mComment;
267 function getMinorEdit()
269 $this->loadLastEdit();
270 return $this->mMinorEdit;
273 # This is the default action of the script: just view the page of
274 # the given title.
276 function view()
278 global $wgUser, $wgOut, $wgLang;
279 global $oldid, $diff; # From query
280 global $wgLinkCache, $IP;
281 $fname = "Article::view";
282 wfProfileIn( $fname );
284 $wgOut->setArticleFlag( true );
285 $wgOut->setRobotpolicy( "index,follow" );
287 # If we got diff and oldid in the query, we want to see a
288 # diff page instead of the article.
290 if ( isset( $diff ) ) {
291 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
292 $de = new DifferenceEngine( $oldid, $diff );
293 $de->showDiffPage();
294 wfProfileOut( $fname );
295 return;
298 if ( !isset( $oldid ) ) {
299 if( $this->checkTouched() ) {
300 $wgOut->checkLastModified( $this->mTouched );
301 $this->tryFileCache();
305 $text = $this->getContent(); # May change mTitle
306 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
307 $wgOut->setHTMLTitle( $this->mTitle->getPrefixedText() .
308 " - " . wfMsg( "wikititlesuffix" ) );
310 # We're looking at an old revision
312 if ( $oldid ) {
313 $this->setOldSubtitle();
314 $wgOut->setRobotpolicy( "noindex,follow" );
316 if ( "" != $this->mRedirectedFrom ) {
317 $sk = $wgUser->getSkin();
318 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, "",
319 "redirect=no" );
320 $s = wfMsg( "redirectedfrom", $redir );
321 $wgOut->setSubtitle( $s );
323 $wgLinkCache->preFill( $this->mTitle );
324 $wgOut->addWikiText( $text );
326 $this->viewUpdates();
327 wfProfileOut( $fname );
330 # Theoretically we could defer these whole insert and update
331 # functions for after display, but that's taking a big leap
332 # of faith, and we want to be able to report database
333 # errors at some point.
335 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
337 global $wgOut, $wgUser, $wgLinkCache, $wgMwRedir;
338 global $wgEnablePersistentLC;
340 $fname = "Article::insertNewArticle";
342 $this->mCountAdjustment = $this->isCountable( $text );
344 $ns = $this->mTitle->getNamespace();
345 $ttl = $this->mTitle->getDBkey();
346 $text = $this->preSaveTransform( $text );
347 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
348 else { $redir = 0; }
350 $now = wfTimestampNow();
351 $won = wfInvertTimestamp( $now );
352 wfSeedRandom();
353 $rand = number_format( mt_rand() / mt_getrandmax(), 12, ".", "" );
354 $sql = "INSERT INTO cur (cur_namespace,cur_title,cur_text," .
355 "cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter," .
356 "cur_restrictions,cur_user_text,cur_is_redirect," .
357 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$ns},'" . wfStrencode( $ttl ) . "', '" .
358 wfStrencode( $text ) . "', '" .
359 wfStrencode( $summary ) . "', '" .
360 $wgUser->getID() . "', '{$now}', " .
361 ( $isminor ? 1 : 0 ) . ", 0, '', '" .
362 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
363 $res = wfQuery( $sql, DB_WRITE, $fname );
365 $newid = wfInsertId();
366 $this->mTitle->resetArticleID( $newid );
368 if ( $wgEnablePersistentLC ) {
369 // Purge related entries in links cache on new page, to heal broken links
370 $ptitle = wfStrencode( $ttl );
371 wfQuery("DELETE linkscc FROM linkscc,brokenlinks ".
372 "WHERE lcc_pageid=bl_from AND bl_to='{$ptitle}'", DB_WRITE);
375 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
376 "rc_namespace,rc_title,rc_new,rc_minor,rc_cur_id,rc_user," .
377 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid,rc_bot) VALUES (" .
378 "'{$now}','{$now}',{$ns},'" . wfStrencode( $ttl ) . "',1," .
379 ( $isminor ? 1 : 0 ) . ",{$newid}," . $wgUser->getID() . ",'" .
380 wfStrencode( $wgUser->getName() ) . "','" .
381 wfStrencode( $summary ) . "',0,0," .
382 ( $wgUser->isBot() ? 1 : 0 ) . ")";
383 wfQuery( $sql, DB_WRITE, $fname );
384 if ($watchthis) {
385 if(!$this->mTitle->userIsWatching()) $this->watch();
386 } else {
387 if ( $this->mTitle->userIsWatching() ) {
388 $this->unwatch();
392 # The talk page isn't in the regular link tables, so we need to update manually:
393 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
394 $sql = "UPDATE cur set cur_touched='$now' WHERE cur_namespace=$talkns AND cur_title='" . wfStrencode( $ttl ) . "'";
395 wfQuery( $sql, DB_WRITE );
397 $this->showArticle( $text, wfMsg( "newarticle" ) );
400 function updateArticle( $text, $summary, $minor, $watchthis, $section = "")
402 global $wgOut, $wgUser, $wgLinkCache;
403 global $wgDBtransactions, $wgMwRedir;
404 $fname = "Article::updateArticle";
406 $this->loadLastEdit();
408 // insert updated section into old text if we have only edited part
409 // of the article
410 if ($section != "") {
411 $oldtext=$this->getContent();
412 if($section=="new") {
413 if($summary) $subject="== {$summary} ==\n\n";
414 $text=$oldtext."\n\n".$subject.$text;
415 } else {
416 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
417 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
418 $secs[$section*2]=$text."\n\n"; // replace with edited
419 if($section) { $secs[$section*2-1]=""; } // erase old headline
420 $text=join("",$secs);
423 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
424 if ( $minor ) { $me2 = 1; } else { $me2 = 0; }
425 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ")[^\\n]+)/i", $text, $m ) ) {
426 $redir = 1;
427 $text = $m[1] . "\n"; # Remove all content but redirect
429 else { $redir = 0; }
431 $text = $this->preSaveTransform( $text );
433 # Update article, but only if changed.
435 if( $wgDBtransactions ) {
436 $sql = "BEGIN";
437 wfQuery( $sql, DB_WRITE );
439 $oldtext = $this->getContent( true );
441 if ( 0 != strcmp( $text, $oldtext ) ) {
442 $this->mCountAdjustment = $this->isCountable( $text )
443 - $this->isCountable( $oldtext );
445 $now = wfTimestampNow();
446 $won = wfInvertTimestamp( $now );
447 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
448 "',cur_comment='" . wfStrencode( $summary ) .
449 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
450 ",cur_timestamp='{$now}',cur_user_text='" .
451 wfStrencode( $wgUser->getName() ) .
452 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
453 "WHERE cur_id=" . $this->getID() .
454 " AND cur_timestamp='" . $this->getTimestamp() . "'";
455 $res = wfQuery( $sql, DB_WRITE, $fname );
457 if( wfAffectedRows() == 0 ) {
458 /* Belated edit conflict! Run away!! */
459 return false;
462 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
463 "old_comment,old_user,old_user_text,old_timestamp," .
464 "old_minor_edit,inverse_timestamp) VALUES (" .
465 $this->mTitle->getNamespace() . ", '" .
466 wfStrencode( $this->mTitle->getDBkey() ) . "', '" .
467 wfStrencode( $oldtext ) . "', '" .
468 wfStrencode( $this->getComment() ) . "', " .
469 $this->getUser() . ", '" .
470 wfStrencode( $this->getUserText() ) . "', '" .
471 $this->getTimestamp() . "', " . $me1 . ", '" .
472 wfInvertTimestamp( $this->getTimestamp() ) . "')";
473 $res = wfQuery( $sql, DB_WRITE, $fname );
474 $oldid = wfInsertID( $res );
476 $sql = "INSERT INTO recentchanges (rc_timestamp,rc_cur_time," .
477 "rc_namespace,rc_title,rc_new,rc_minor,rc_bot,rc_cur_id,rc_user," .
478 "rc_user_text,rc_comment,rc_this_oldid,rc_last_oldid) VALUES (" .
479 "'{$now}','{$now}'," . $this->mTitle->getNamespace() . ",'" .
480 wfStrencode( $this->mTitle->getDBkey() ) . "',0,{$me2}," .
481 ( $wgUser->isBot() ? 1 : 0 ) . "," .
482 $this->getID() . "," . $wgUser->getID() . ",'" .
483 wfStrencode( $wgUser->getName() ) . "','" .
484 wfStrencode( $summary ) . "',0,{$oldid})";
485 wfQuery( $sql, DB_WRITE, $fname );
487 $sql = "UPDATE recentchanges SET rc_this_oldid={$oldid} " .
488 "WHERE rc_namespace=" . $this->mTitle->getNamespace() . " AND " .
489 "rc_title='" . wfStrencode( $this->mTitle->getDBkey() ) . "' AND " .
490 "rc_timestamp='" . $this->getTimestamp() . "'";
491 wfQuery( $sql, DB_WRITE, $fname );
493 $sql = "UPDATE recentchanges SET rc_cur_time='{$now}' " .
494 "WHERE rc_cur_id=" . $this->getID();
495 wfQuery( $sql, DB_WRITE, $fname );
497 global $wgEnablePersistentLC;
498 if ( $wgEnablePersistentLC ) {
499 // Purge link cache for this page
500 $pageid=$this->getID();
501 wfQuery("DELETE FROM linkscc WHERE lcc_pageid='{$pageid}'", DB_WRITE);
505 if( $wgDBtransactions ) {
506 $sql = "COMMIT";
507 wfQuery( $sql, DB_WRITE );
510 if ($watchthis) {
511 if (!$this->mTitle->userIsWatching()) $this->watch();
512 } else {
513 if ( $this->mTitle->userIsWatching() ) {
514 $this->unwatch();
518 $this->showArticle( $text, wfMsg( "updated" ) );
519 return true;
522 # After we've either updated or inserted the article, update
523 # the link tables and redirect to the new page.
525 function showArticle( $text, $subtitle )
527 global $wgOut, $wgUser, $wgLinkCache, $wgUseBetterLinksUpdate;
528 global $wgMwRedir;
530 $wgLinkCache = new LinkCache();
532 # Get old version of link table to allow incremental link updates
533 if ( $wgUseBetterLinksUpdate ) {
534 $wgLinkCache->preFill( $this->mTitle );
535 $wgLinkCache->clear();
538 # Now update the link cache by parsing the text
539 $wgOut = new OutputPage();
540 $wgOut->addWikiText( $text );
542 $this->editUpdates( $text );
543 if( $wgMwRedir->matchStart( $text ) )
544 $r = "redirect=no";
545 else
546 $r = "";
547 $wgOut->redirect( wfLocalUrl( $this->mTitle->getPrefixedURL(), $r ) );
550 # Add this page to my watchlist
552 function watch( $add = true )
554 global $wgUser, $wgOut, $wgLang;
555 global $wgDeferredUpdateList;
557 if ( 0 == $wgUser->getID() ) {
558 $wgOut->errorpage( "watchnologin", "watchnologintext" );
559 return;
561 if ( wfReadOnly() ) {
562 $wgOut->readOnlyPage();
563 return;
565 if( $add )
566 $wgUser->addWatch( $this->mTitle );
567 else
568 $wgUser->removeWatch( $this->mTitle );
570 $wgOut->setPagetitle( wfMsg( $add ? "addedwatch" : "removedwatch" ) );
571 $wgOut->setRobotpolicy( "noindex,follow" );
573 $sk = $wgUser->getSkin() ;
574 $link = $sk->makeKnownLink ( $this->mTitle->getPrefixedText() ) ;
576 if($add)
577 $text = wfMsg( "addedwatchtext", $link );
578 else
579 $text = wfMsg( "removedwatchtext", $link );
580 $wgOut->addHTML( $text );
582 $up = new UserUpdate();
583 array_push( $wgDeferredUpdateList, $up );
585 $wgOut->returnToMain( false );
588 function unwatch()
590 $this->watch( false );
593 # This shares a lot of issues (and code) with Recent Changes
595 function history()
597 global $wgUser, $wgOut, $wgLang, $offset, $limit;
599 # If page hasn't changed, client can cache this
601 $wgOut->checkLastModified( $this->getTimestamp() );
602 $fname = "Article::history";
603 wfProfileIn( $fname );
605 $wgOut->setPageTitle( $this->mTitle->getPRefixedText() );
606 $wgOut->setSubtitle( wfMsg( "revhistory" ) );
607 $wgOut->setArticleFlag( false );
608 $wgOut->setRobotpolicy( "noindex,nofollow" );
610 if( $this->mTitle->getArticleID() == 0 ) {
611 $wgOut->addHTML( wfMsg( "nohistory" ) );
612 wfProfileOut( $fname );
613 return;
616 $offset = (int)$offset;
617 $limit = (int)$limit;
618 if( $limit == 0 ) $limit = 50;
619 $namespace = $this->mTitle->getNamespace();
620 $title = $this->mTitle->getText();
621 $sql = "SELECT old_id,old_user," .
622 "old_comment,old_user_text,old_timestamp,old_minor_edit ".
623 "FROM old USE INDEX (name_title_timestamp) " .
624 "WHERE old_namespace={$namespace} AND " .
625 "old_title='" . wfStrencode( $this->mTitle->getDBkey() ) . "' " .
626 "ORDER BY inverse_timestamp LIMIT $offset, $limit";
627 $res = wfQuery( $sql, DB_READ, "Article::history" );
629 $revs = wfNumRows( $res );
630 if( $this->mTitle->getArticleID() == 0 ) {
631 $wgOut->addHTML( wfMsg( "nohistory" ) );
632 wfProfileOut( $fname );
633 return;
636 $sk = $wgUser->getSkin();
637 $numbar = wfViewPrevNext(
638 $offset, $limit,
639 $this->mTitle->getPrefixedText(),
640 "action=history" );
641 $s = $numbar;
642 $s .= $sk->beginHistoryList();
644 if($offset == 0 )
645 $s .= $sk->historyLine( $this->getTimestamp(), $this->getUser(),
646 $this->getUserText(), $namespace,
647 $title, 0, $this->getComment(),
648 ( $this->getMinorEdit() > 0 ) );
650 $revs = wfNumRows( $res );
651 while ( $line = wfFetchObject( $res ) ) {
652 $s .= $sk->historyLine( $line->old_timestamp, $line->old_user,
653 $line->old_user_text, $namespace,
654 $title, $line->old_id,
655 $line->old_comment, ( $line->old_minor_edit > 0 ) );
657 $s .= $sk->endHistoryList();
658 $s .= $numbar;
659 $wgOut->addHTML( $s );
660 wfProfileOut( $fname );
663 function protect( $limit = "sysop" )
665 global $wgUser, $wgOut;
667 if ( ! $wgUser->isSysop() ) {
668 $wgOut->sysopRequired();
669 return;
671 if ( wfReadOnly() ) {
672 $wgOut->readOnlyPage();
673 return;
675 $id = $this->mTitle->getArticleID();
676 if ( 0 == $id ) {
677 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
678 return;
680 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
681 "cur_restrictions='{$limit}' WHERE cur_id={$id}";
682 wfQuery( $sql, DB_WRITE, "Article::protect" );
684 $log = new LogPage( wfMsg( "protectlogpage" ), wfMsg( "protectlogtext" ) );
685 if ( $limit === "" ) {
686 $log->addEntry( wfMsg( "unprotectedarticle", $this->mTitle->getPrefixedText() ), "" );
687 } else {
688 $log->addEntry( wfMsg( "protectedarticle", $this->mTitle->getPrefixedText() ), "" );
690 $wgOut->redirect( wfLocalUrl( $this->mTitle->getPrefixedURL() ) );
693 function unprotect()
695 return $this->protect( "" );
698 function delete()
700 global $wgUser, $wgOut;
701 global $wpConfirm, $wpReason, $image, $oldimage;
703 # This code desperately needs to be totally rewritten
705 if ( ( ! $wgUser->isSysop() ) ) {
706 $wgOut->sysopRequired();
707 return;
709 if ( wfReadOnly() ) {
710 $wgOut->readOnlyPage();
711 return;
714 # Better double-check that it hasn't been deleted yet!
715 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
716 if ( ( "" == trim( $this->mTitle->getText() ) )
717 or ( $this->mTitle->getArticleId() == 0 ) ) {
718 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
719 return;
722 if ( $_POST["wpConfirm"] ) {
723 $this->doDelete();
724 return;
727 # determine whether this page has earlier revisions
728 # and insert a warning if it does
729 # we select the text because it might be useful below
730 $ns = $this->mTitle->getNamespace();
731 $title = $this->mTitle->getDBkey();
732 $etitle = wfStrencode( $title );
733 $sql = "SELECT old_text FROM old WHERE old_namespace=$ns and old_title='$etitle' ORDER BY inverse_timestamp LIMIT 1";
734 $res = wfQuery( $sql, DB_READ, $fname );
735 if( ($old=wfFetchObject($res)) && !$wpConfirm ) {
736 $skin=$wgUser->getSkin();
737 $wgOut->addHTML("<B>".wfMsg("historywarning"));
738 $wgOut->addHTML( $skin->historyLink() ."</B><P>");
741 $sql="SELECT cur_text FROM cur WHERE cur_namespace=$ns and cur_title='$etitle'";
742 $res=wfQuery($sql, DB_READ, $fname);
743 if( ($s=wfFetchObject($res))) {
745 # if this is a mini-text, we can paste part of it into the deletion reason
747 #if this is empty, an earlier revision may contain "useful" text
748 if($s->cur_text!="") {
749 $text=$s->cur_text;
750 } else {
751 if($old) {
752 $text=$old->old_text;
753 $blanked=1;
758 $length=strlen($text);
760 # this should not happen, since it is not possible to store an empty, new
761 # page. Let's insert a standard text in case it does, though
762 if($length==0 && !$wpReason) { $wpReason=wfmsg("exblank");}
765 if($length < 500 && !$wpReason) {
767 # comment field=255, let's grep the first 150 to have some user
768 # space left
769 $text=substr($text,0,150);
770 # let's strip out newlines and HTML tags
771 $text=preg_replace("/\"/","'",$text);
772 $text=preg_replace("/\</","&lt;",$text);
773 $text=preg_replace("/\>/","&gt;",$text);
774 $text=preg_replace("/[\n\r]/","",$text);
775 if(!$blanked) {
776 $wpReason=wfMsg("excontent"). " '".$text;
777 } else {
778 $wpReason=wfMsg("exbeforeblank") . " '".$text;
780 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
781 $wpReason.="'";
785 return $this->confirmDelete();
788 function confirmDelete( $par = "" )
790 global $wgOut;
791 global $wpReason;
793 wfDebug( "Article::confirmDelete\n" );
795 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
796 $wgOut->setSubtitle( wfMsg( "deletesub", $sub ) );
797 $wgOut->setRobotpolicy( "noindex,nofollow" );
798 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
800 $t = $this->mTitle->getPrefixedURL();
802 $formaction = wfEscapeHTML( wfLocalUrl( $t, "action=delete" . $par ) );
803 $confirm = wfMsg( "confirm" );
804 $check = wfMsg( "confirmcheck" );
805 $delcom = wfMsg( "deletecomment" );
807 $wgOut->addHTML( "
808 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
809 <table border=0><tr><td align=right>
810 {$delcom}:</td><td align=left>
811 <input type=text size=60 name=\"wpReason\" value=\"" . htmlspecialchars( $wpReason ) . "\">
812 </td></tr><tr><td>&nbsp;</td></tr>
813 <tr><td align=right>
814 <input type=checkbox name=\"wpConfirm\" value='1' id=\"wpConfirm\">
815 </td><td><label for=\"wpConfirm\">{$check}</label></td>
816 </tr><tr><td>&nbsp;</td><td>
817 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
818 </td></tr></table></form>\n" );
820 $wgOut->returnToMain( false );
823 function doDelete()
825 global $wgOut, $wgUser, $wgLang;
826 global $wpReason;
827 $fname = "Article::doDelete";
828 wfDebug( "$fname\n" );
830 $this->doDeleteArticle( $this->mTitle );
831 $deleted = $this->mTitle->getPrefixedText();
833 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
834 $wgOut->setRobotpolicy( "noindex,nofollow" );
836 $sk = $wgUser->getSkin();
837 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
838 Namespace::getWikipedia() ) .
839 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
841 $text = wfMsg( "deletedtext", $deleted, $loglink );
843 $wgOut->addHTML( "<p>" . $text );
844 $wgOut->returnToMain( false );
847 function doDeleteArticle( $title )
849 global $wgUser, $wgOut, $wgLang, $wpReason, $wgDeferredUpdateList,
850 $wgEnablePersistentLC;
852 $fname = "Article::doDeleteArticle";
853 wfDebug( "$fname\n" );
855 $ns = $title->getNamespace();
856 $t = wfStrencode( $title->getDBkey() );
857 $id = $title->getArticleID();
859 if ( "" == $t ) {
860 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
861 return;
864 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
865 array_push( $wgDeferredUpdateList, $u );
867 # Move article and history to the "archive" table
868 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
869 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
870 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
871 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
872 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
873 wfQuery( $sql, DB_WRITE, $fname );
875 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
876 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
877 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
878 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
879 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
880 wfQuery( $sql, DB_WRITE, $fname );
882 # Now that it's safely backed up, delete it
884 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
885 "cur_title='{$t}'";
886 wfQuery( $sql, DB_WRITE, $fname );
888 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
889 "old_title='{$t}'";
890 wfQuery( $sql, DB_WRITE, $fname );
892 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
893 "rc_title='{$t}'";
894 wfQuery( $sql, DB_WRITE, $fname );
896 # Finally, clean up the link tables
898 if ( 0 != $id ) {
900 $t = wfStrencode( $title->getPrefixedDBkey() );
902 if ( $wgEnablePersistentLC ) {
903 // Purge related entries in links cache on delete,
904 wfQuery("DELETE linkscc FROM linkscc,links ".
905 "WHERE lcc_title=links.l_from AND l_to={$id}", DB_WRITE);
906 wfQuery("DELETE FROM linkscc WHERE lcc_title='{$t}'", DB_WRITE);
909 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
910 $res = wfQuery( $sql, DB_READ, $fname );
912 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
913 $now = wfTimestampNow();
914 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
915 $first = true;
917 while ( $s = wfFetchObject( $res ) ) {
918 $nt = Title::newFromDBkey( $s->l_from );
919 $lid = $nt->getArticleID();
921 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
922 $first = false;
923 $sql .= "({$lid},'{$t}')";
924 $sql2 .= "{$lid}";
926 $sql2 .= ")";
927 if ( ! $first ) {
928 wfQuery( $sql, DB_WRITE, $fname );
929 wfQuery( $sql2, DB_WRITE, $fname );
931 wfFreeResult( $res );
933 $sql = "DELETE FROM links WHERE l_to={$id}";
934 wfQuery( $sql, DB_WRITE, $fname );
936 $sql = "DELETE FROM links WHERE l_from='{$t}'";
937 wfQuery( $sql, DB_WRITE, $fname );
939 $sql = "DELETE FROM imagelinks WHERE il_from='{$t}'";
940 wfQuery( $sql, DB_WRITE, $fname );
942 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
943 wfQuery( $sql, DB_WRITE, $fname );
946 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
947 $art = $title->getPrefixedText();
948 $wpReason = wfCleanQueryVar( $wpReason );
949 $log->addEntry( wfMsg( "deletedarticle", $art ), $wpReason );
951 # Clear the cached article id so the interface doesn't act like we exist
952 $this->mTitle->resetArticleID( 0 );
953 $this->mTitle->mArticleID = 0;
956 function rollback()
958 global $wgUser, $wgLang, $wgOut, $from;
960 if ( ! $wgUser->isSysop() ) {
961 $wgOut->sysopRequired();
962 return;
965 # Replace all this user's current edits with the next one down
966 $tt = wfStrencode( $this->mTitle->getDBKey() );
967 $n = $this->mTitle->getNamespace();
969 # Get the last editor
970 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
971 $res = wfQuery( $sql, DB_READ );
972 if( ($x = wfNumRows( $res )) != 1 ) {
973 # Something wrong
974 $wgOut->addHTML( wfMsg( "notanarticle" ) );
975 return;
977 $s = wfFetchObject( $res );
978 $ut = wfStrencode( $s->cur_user_text );
979 $uid = $s->cur_user;
980 $pid = $s->cur_id;
982 $from = str_replace( '_', ' ', wfCleanQueryVar( $from ) );
983 if( $from != $s->cur_user_text ) {
984 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
985 $wgOut->addWikiText( wfMsg( "alreadyrolled",
986 htmlspecialchars( $this->mTitle->getPrefixedText()),
987 htmlspecialchars( $from ),
988 htmlspecialchars( $s->cur_user_text ) ) );
989 if($s->cur_comment != "") {
990 $wgOut->addHTML(
991 wfMsg("editcomment",
992 htmlspecialchars( $s->cur_comment ) ) );
994 return;
997 # Get the last edit not by this guy
998 $sql = "SELECT old_text,old_user,old_user_text
999 FROM old USE INDEX (name_title_timestamp)
1000 WHERE old_namespace={$n} AND old_title='{$tt}'
1001 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
1002 ORDER BY inverse_timestamp LIMIT 1";
1003 $res = wfQuery( $sql, DB_READ );
1004 if( wfNumRows( $res ) != 1 ) {
1005 # Something wrong
1006 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
1007 $wgOut->addHTML( wfMsg( "cantrollback" ) );
1008 return;
1010 $s = wfFetchObject( $res );
1012 # Save it!
1013 $newcomment = wfMsg( "revertpage", $s->old_user_text );
1014 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
1015 $wgOut->setRobotpolicy( "noindex,nofollow" );
1016 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
1017 $this->updateArticle( $s->old_text, $newcomment, 1, $this->mTitle->userIsWatching() );
1019 global $wgEnablePersistentLC;
1020 if ( $wgEnablePersistentLC ) {
1021 wfQuery("DELETE FROM linkscc WHERE lcc_pageid='{$pid}'", DB_WRITE);
1024 $wgOut->returnToMain( false );
1028 # Do standard deferred updates after page view
1030 /* private */ function viewUpdates()
1032 global $wgDeferredUpdateList;
1034 if ( 0 != $this->getID() ) {
1035 global $wgDisableCounters;
1036 if( !$wgDisableCounters ) {
1037 $u = new ViewCountUpdate( $this->getID() );
1038 array_push( $wgDeferredUpdateList, $u );
1039 $u = new SiteStatsUpdate( 1, 0, 0 );
1040 array_push( $wgDeferredUpdateList, $u );
1042 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
1043 $this->mTitle->getDBkey() );
1044 array_push( $wgDeferredUpdateList, $u );
1048 # Do standard deferred updates after page edit.
1049 # Every 1000th edit, prune the recent changes table.
1051 /* private */ function editUpdates( $text )
1053 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1055 wfSeedRandom();
1056 if ( 0 == mt_rand( 0, 999 ) ) {
1057 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1058 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1059 wfQuery( $sql, DB_WRITE );
1061 $id = $this->getID();
1062 $title = $this->mTitle->getPrefixedDBkey();
1063 $adj = $this->mCountAdjustment;
1065 if ( 0 != $id ) {
1066 $u = new LinksUpdate( $id, $title );
1067 array_push( $wgDeferredUpdateList, $u );
1068 $u = new SiteStatsUpdate( 0, 1, $adj );
1069 array_push( $wgDeferredUpdateList, $u );
1070 $u = new SearchUpdate( $id, $title, $text );
1071 array_push( $wgDeferredUpdateList, $u );
1073 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(),
1074 $this->mTitle->getDBkey() );
1075 array_push( $wgDeferredUpdateList, $u );
1077 if ( $this->getNamespace == NS_MEDIAWIKI ) {
1078 $messageCache = $wgMemc->get( "$wgDBname:messages" );
1079 if (!$messageCache) {
1080 $messageCache = wfLoadAllMessages();
1082 $messageCache[$title] = $text;
1083 $wgMemc->set( "$wgDBname:messages" );
1088 /* private */ function setOldSubtitle()
1090 global $wgLang, $wgOut;
1092 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1093 $r = wfMsg( "revisionasof", $td );
1094 $wgOut->setSubtitle( "({$r})" );
1097 # This function is called right before saving the wikitext,
1098 # so we can do things like signatures and links-in-context.
1100 function preSaveTransform( $text )
1102 $s = "";
1103 while ( "" != $text ) {
1104 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
1105 $s .= $this->pstPass2( $p[0] );
1107 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
1108 else {
1109 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
1110 $s .= "<nowiki>{$q[0]}</nowiki>";
1111 $text = $q[1];
1114 return rtrim( $s );
1117 /* private */ function pstPass2( $text )
1119 global $wgUser, $wgLang, $wgLocaltimezone;
1121 # Signatures
1123 $n = $wgUser->getName();
1124 $k = $wgUser->getOption( "nickname" );
1125 if ( "" == $k ) { $k = $n; }
1126 if(isset($wgLocaltimezone)) {
1127 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1129 /* Note: this is an ugly timezone hack for the European wikis */
1130 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1131 " (" . date( "T" ) . ")";
1132 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1134 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1135 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1136 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1137 Namespace::getUser() ) . ":$n|$k]]", $text );
1139 # Context links: [[|name]] and [[name (context)|]]
1141 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1142 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1143 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
1144 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1146 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1147 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1148 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
1149 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
1150 # [[ns:page (cont)|]]
1151 $context = "";
1152 $t = $this->mTitle->getText();
1153 if ( preg_match( $conpat, $t, $m ) ) {
1154 $context = $m[2];
1156 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1157 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1158 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1160 if ( "" == $context ) {
1161 $text = preg_replace( $p2, "[[\\1]]", $text );
1162 } else {
1163 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1166 # {{SUBST:xxx}} variables
1168 $mw =& MagicWord::get( MAG_SUBST );
1169 $text = $mw->substituteCallback( $text, "wfReplaceSubstVar" );
1171 return $text;
1174 /* Caching functions */
1176 function tryFileCache() {
1177 static $called = false;
1178 if( $called ) {
1179 wfDebug( " tryFileCache() -- called twice!?\n" );
1180 return;
1182 $called = true;
1183 if($this->isFileCacheable()) {
1184 $touched = $this->mTouched;
1185 if( strpos( $this->mContent, "{{" ) !== false ) {
1186 # Expire pages with variable replacements in an hour
1187 $expire = wfUnix2Timestamp( time() - 3600 );
1188 $touched = max( $expire, $touched );
1190 $cache = new CacheManager( $this->mTitle );
1191 if($cache->isFileCacheGood( $touched )) {
1192 global $wgOut;
1193 wfDebug( " tryFileCache() - about to load\n" );
1194 $cache->loadFromFileCache();
1195 $wgOut->reportTime(); # For profiling
1196 exit;
1197 } else {
1198 wfDebug( " tryFileCache() - starting buffer\n" );
1199 if($cache->useGzip() && wfClientAcceptsGzip()) {
1200 /* For some reason, adding this header line over in
1201 CacheManager::saveToFileCache() fails on my test
1202 setup at home, though it works on the live install.
1203 Make double-sure... --brion */
1204 header( "Content-Encoding: gzip" );
1206 ob_start( array(&$cache, 'saveToFileCache' ) );
1208 } else {
1209 wfDebug( " tryFileCache() - not cacheable\n" );
1213 function isFileCacheable() {
1214 global $wgUser, $wgUseFileCache, $wgShowIPinHeader;
1215 global $action, $oldid, $diff, $redirect, $printable;
1216 return $wgUseFileCache
1217 and (!$wgShowIPinHeader)
1218 and ($this->getID() != 0)
1219 and ($wgUser->getId() == 0)
1220 and (!$wgUser->getNewtalk())
1221 and ($this->mTitle->getNamespace != Namespace::getSpecial())
1222 and ($action == "view")
1223 and (!isset($oldid))
1224 and (!isset($diff))
1225 and (!isset($redirect))
1226 and (!isset($printable))
1227 and (!$this->mRedirectedFrom);
1230 function checkTouched() {
1231 $id = $this->getID();
1232 $sql = "SELECT cur_touched,cur_is_redirect FROM cur WHERE cur_id=$id";
1233 $res = wfQuery( $sql, DB_READ, "Article::checkTouched" );
1234 if( $s = wfFetchObject( $res ) ) {
1235 $this->mTouched = $s->cur_touched;
1236 return !$s->cur_is_redirect;
1237 } else {
1238 return false;
1243 function wfReplaceSubstVar( $matches ) {
1244 return wfMsg( $matches[1] );