Feature-Request #816659,#668443: No (next 50) link if there is no next page
[mediawiki.git] / includes / Article.php
blob3a7cdf47b4dd4597dbbed886c7a794ff83606306
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;
23 /* private */ var $mId, $mTable;
25 function Article( &$title ) {
26 $this->mTitle =& $title;
27 $this->clear();
30 /* private */ function clear()
32 $this->mContentLoaded = false;
33 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
34 $this->mRedirectedFrom = $this->mUserText =
35 $this->mTimestamp = $this->mComment = $this->mFileCache = "";
36 $this->mCountAdjustment = 0;
37 $this->mTouched = "19700101000000";
40 /* static */ function getRevisionText( $row, $prefix = "old_" ) {
41 # Deal with optional compression of archived pages.
42 # This can be done periodically via maintenance/compressOld.php, and
43 # as pages are saved if $wgCompressRevisions is set.
44 $text = $prefix . "text";
45 $flags = $prefix . "flags";
46 if( isset( $row->$flags ) && (false !== strpos( $row->$flags, "gzip" ) ) ) {
47 return gzinflate( $row->$text );
49 if( isset( $row->$text ) ) {
50 return $row->$text;
52 return false;
55 /* static */ function compressRevisionText( &$text ) {
56 global $wgCompressRevisions;
57 if( !$wgCompressRevisions ) {
58 return "";
60 if( !function_exists( "gzdeflate" ) ) {
61 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
62 return "";
64 $text = gzdeflate( $text );
65 return "gzip";
68 # Note that getContent/loadContent may follow redirects if
69 # not told otherwise, and so may cause a change to mTitle.
71 # Return the text of this revision
72 function getContent( $noredir = false )
74 global $action,$section,$count; # From query string
75 $fname = "Article::getContent";
76 wfProfileIn( $fname );
78 if ( 0 == $this->getID() ) {
79 if ( "edit" == $action ) {
80 wfProfileOut( $fname );
81 return ""; # was "newarticletext", now moved above the box)
83 wfProfileOut( $fname );
84 return wfMsg( "noarticletext" );
85 } else {
86 $this->loadContent( $noredir );
88 if(
89 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
90 ( $this->mTitle->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
91 preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$this->mTitle->getText()) &&
92 $action=="view"
95 wfProfileOut( $fname );
96 return $this->mContent . "\n" .wfMsg("anontalkpagetext"); }
97 else {
98 if($action=="edit") {
99 if($section!="") {
100 if($section=="new") {
101 wfProfileOut( $fname );
102 return "";
105 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
106 $this->mContent, -1,
107 PREG_SPLIT_DELIM_CAPTURE);
108 if($section==0) {
109 wfProfileOut( $fname );
110 return trim($secs[0]);
111 } else {
112 wfProfileOut( $fname );
113 return trim($secs[$section*2-1] . $secs[$section*2]);
117 wfProfileOut( $fname );
118 return $this->mContent;
123 # Load the revision (including cur_text) into this object
124 function loadContent( $noredir = false )
126 global $wgOut, $wgMwRedir;
127 global $oldid, $redirect; # From query
129 if ( $this->mContentLoaded ) return;
130 $fname = "Article::loadContent";
131 $success = true;
133 if ( ! $oldid ) { # Retrieve current version
134 $id = $this->getID();
135 if ( 0 == $id ) return;
137 $sql = "SELECT " .
138 "cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched " .
139 "FROM cur WHERE cur_id={$id}";
140 wfDebug( "$sql\n" );
141 $res = wfQuery( $sql, DB_READ, $fname );
142 if ( 0 == wfNumRows( $res ) ) {
143 return;
146 $s = wfFetchObject( $res );
147 # If we got a redirect, follow it (unless we've been told
148 # not to by either the function parameter or the query
149 if ( ( "no" != $redirect ) && ( false == $noredir ) &&
150 ( $wgMwRedir->matchStart( $s->cur_text ) ) ) {
151 if ( preg_match( "/\\[\\[([^\\]\\|]+)[\\]\\|]/",
152 $s->cur_text, $m ) ) {
153 $rt = Title::newFromText( $m[1] );
154 if( $rt ) {
155 # Gotta hand redirects to special pages differently:
156 # Fill the HTTP response "Location" header and ignore
157 # the rest of the page we're on.
159 if ( $rt->getInterwiki() != "" ) {
160 $wgOut->redirect( $rt->getFullURL() ) ;
161 return;
163 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
164 $wgOut->redirect( wfLocalUrl(
165 $rt->getPrefixedURL() ) );
166 return;
168 $rid = $rt->getArticleID();
169 if ( 0 != $rid ) {
170 $sql = "SELECT cur_text,cur_timestamp,cur_user," .
171 "cur_counter,cur_restrictions,cur_touched FROM cur WHERE cur_id={$rid}";
172 $res = wfQuery( $sql, DB_READ, $fname );
174 if ( 0 != wfNumRows( $res ) ) {
175 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
176 $this->mTitle = $rt;
177 $s = wfFetchObject( $res );
184 $this->mContent = $s->cur_text;
185 $this->mUser = $s->cur_user;
186 $this->mCounter = $s->cur_counter;
187 $this->mTimestamp = $s->cur_timestamp;
188 $this->mTouched = $s->cur_touched;
189 $this->mTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
190 $this->mTitle->mRestrictionsLoaded = true;
191 wfFreeResult( $res );
192 } else { # oldid set, retrieve historical version
193 $sql = "SELECT old_text,old_timestamp,old_user,old_flags FROM old " .
194 "WHERE old_id={$oldid}";
195 $res = wfQuery( $sql, DB_READ, $fname );
196 if ( 0 == wfNumRows( $res ) ) { return; }
198 $s = wfFetchObject( $res );
199 $this->mContent = Article::getRevisionText( $s );
200 $this->mUser = $s->old_user;
201 $this->mCounter = 0;
202 $this->mTimestamp = $s->old_timestamp;
203 wfFreeResult( $res );
206 # Return error message :P
207 # Horrible, confusing UI and data. I think this should return false on error -- TS
208 if ( !$success ) {
209 $t = $this->mTitle->getPrefixedText();
210 if ( isset( $oldid ) ) {
211 $oldid = IntVal( $oldid );
212 $t .= ",oldid={$oldid}";
214 if ( isset( $redirect ) ) {
215 $redirect = ($redirect == "no") ? "no" : "yes";
216 $t .= ",redirect={$redirect}";
218 $this->mContent = wfMsg( "missingarticle", $t );
221 $this->mContentLoaded = true;
224 function getID() {
225 if( $this->mTitle ) {
226 return $this->mTitle->getArticleID();
227 } else {
228 return 0;
232 function getCount()
234 if ( -1 == $this->mCounter ) {
235 $id = $this->getID();
236 $this->mCounter = wfGetSQL( "cur", "cur_counter", "cur_id={$id}" );
238 return $this->mCounter;
241 # Would the given text make this article a "good" article (i.e.,
242 # suitable for including in the article count)?
244 function isCountable( $text )
246 global $wgUseCommaCount, $wgMwRedir;
248 if ( 0 != $this->mTitle->getNamespace() ) { return 0; }
249 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
250 $token = ($wgUseCommaCount ? "," : "[[" );
251 if ( false === strstr( $text, $token ) ) { return 0; }
252 return 1;
255 # Loads everything from cur except cur_text
256 # This isn't necessary for all uses, so it's only done if needed.
258 /* private */ function loadLastEdit()
260 global $wgOut;
261 if ( -1 != $this->mUser ) return;
263 $sql = "SELECT cur_user,cur_user_text,cur_timestamp," .
264 "cur_comment,cur_minor_edit FROM cur WHERE " .
265 "cur_id=" . $this->getID();
266 $res = wfQuery( $sql, DB_READ, "Article::loadLastEdit" );
268 if ( wfNumRows( $res ) > 0 ) {
269 $s = wfFetchObject( $res );
270 $this->mUser = $s->cur_user;
271 $this->mUserText = $s->cur_user_text;
272 $this->mTimestamp = $s->cur_timestamp;
273 $this->mComment = $s->cur_comment;
274 $this->mMinorEdit = $s->cur_minor_edit;
278 function getTimestamp()
280 $this->loadLastEdit();
281 return $this->mTimestamp;
284 function getUser()
286 $this->loadLastEdit();
287 return $this->mUser;
290 function getUserText()
292 $this->loadLastEdit();
293 return $this->mUserText;
296 function getComment()
298 $this->loadLastEdit();
299 return $this->mComment;
302 function getMinorEdit()
304 $this->loadLastEdit();
305 return $this->mMinorEdit;
308 # This is the default action of the script: just view the page of
309 # the given title.
311 function view()
313 global $wgUser, $wgOut, $wgLang;
314 global $oldid, $diff; # From query
315 global $wgLinkCache, $IP;
316 $fname = "Article::view";
317 wfProfileIn( $fname );
319 $wgOut->setArticleFlag( true );
320 $wgOut->setRobotpolicy( "index,follow" );
322 # If we got diff and oldid in the query, we want to see a
323 # diff page instead of the article.
325 if ( isset( $diff ) ) {
326 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
327 $de = new DifferenceEngine( $oldid, $diff );
328 $de->showDiffPage();
329 wfProfileOut( $fname );
330 return;
333 if ( !isset( $oldid ) and $this->checkTouched() ) {
334 if( $wgOut->checkLastModified( $this->mTouched ) ){
335 return;
336 } else if ( $this->tryFileCache() ) {
337 # tell wgOut that output is taken care of
338 $wgOut->disable();
339 $this->viewUpdates();
340 return;
344 $text = $this->getContent(); # May change mTitle
345 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
346 $wgOut->setHTMLTitle( $this->mTitle->getPrefixedText() .
347 " - " . wfMsg( "wikititlesuffix" ) );
349 # We're looking at an old revision
351 if ( $oldid ) {
352 $this->setOldSubtitle();
353 $wgOut->setRobotpolicy( "noindex,follow" );
355 if ( "" != $this->mRedirectedFrom ) {
356 $sk = $wgUser->getSkin();
357 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, "",
358 "redirect=no" );
359 $s = wfMsg( "redirectedfrom", $redir );
360 $wgOut->setSubtitle( $s );
363 $wgLinkCache->preFill( $this->mTitle );
364 $wgOut->addWikiText( $text );
366 $this->viewUpdates();
367 wfProfileOut( $fname );
370 # Theoretically we could defer these whole insert and update
371 # functions for after display, but that's taking a big leap
372 # of faith, and we want to be able to report database
373 # errors at some point.
375 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
377 global $wgOut, $wgUser, $wgLinkCache, $wgMwRedir;
379 $fname = "Article::insertNewArticle";
381 $this->mCountAdjustment = $this->isCountable( $text );
383 $ns = $this->mTitle->getNamespace();
384 $ttl = $this->mTitle->getDBkey();
385 $text = $this->preSaveTransform( $text );
386 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
387 else { $redir = 0; }
389 $now = wfTimestampNow();
390 $won = wfInvertTimestamp( $now );
391 wfSeedRandom();
392 $rand = number_format( mt_rand() / mt_getrandmax(), 12, ".", "" );
393 $sql = "INSERT INTO cur (cur_namespace,cur_title,cur_text," .
394 "cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter," .
395 "cur_restrictions,cur_user_text,cur_is_redirect," .
396 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$ns},'" . wfStrencode( $ttl ) . "', '" .
397 wfStrencode( $text ) . "', '" .
398 wfStrencode( $summary ) . "', '" .
399 $wgUser->getID() . "', '{$now}', " .
400 ( $isminor ? 1 : 0 ) . ", 0, '', '" .
401 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
402 $res = wfQuery( $sql, DB_WRITE, $fname );
404 $newid = wfInsertId();
405 $this->mTitle->resetArticleID( $newid );
407 Article::onArticleCreate( $this->mTitle );
408 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary );
410 if ($watchthis) {
411 if(!$this->mTitle->userIsWatching()) $this->watch();
412 } else {
413 if ( $this->mTitle->userIsWatching() ) {
414 $this->unwatch();
418 # The talk page isn't in the regular link tables, so we need to update manually:
419 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
420 $sql = "UPDATE cur set cur_touched='$now' WHERE cur_namespace=$talkns AND cur_title='" . wfStrencode( $ttl ) . "'";
421 wfQuery( $sql, DB_WRITE );
423 $this->showArticle( $text, wfMsg( "newarticle" ) );
426 function updateArticle( $text, $summary, $minor, $watchthis, $section = "", $forceBot = false )
428 global $wgOut, $wgUser, $wgLinkCache;
429 global $wgDBtransactions, $wgMwRedir;
430 $fname = "Article::updateArticle";
432 $this->loadLastEdit();
434 // insert updated section into old text if we have only edited part
435 // of the article
436 if ($section != "") {
437 $oldtext=$this->getContent();
438 if($section=="new") {
439 if($summary) $subject="== {$summary} ==\n\n";
440 $text=$oldtext."\n\n".$subject.$text;
441 } else {
442 $secs=preg_split("/(^=+.*?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)/mi",
443 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
444 $secs[$section*2]=$text."\n\n"; // replace with edited
445 if($section) { $secs[$section*2-1]=""; } // erase old headline
446 $text=join("",$secs);
449 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
450 if ( $minor ) { $me2 = 1; } else { $me2 = 0; }
451 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ")[^\\n]+)/i", $text, $m ) ) {
452 $redir = 1;
453 $text = $m[1] . "\n"; # Remove all content but redirect
455 else { $redir = 0; }
457 $text = $this->preSaveTransform( $text );
459 # Update article, but only if changed.
461 if( $wgDBtransactions ) {
462 $sql = "BEGIN";
463 wfQuery( $sql, DB_WRITE );
465 $oldtext = $this->getContent( true );
467 if ( 0 != strcmp( $text, $oldtext ) ) {
468 $this->mCountAdjustment = $this->isCountable( $text )
469 - $this->isCountable( $oldtext );
471 $now = wfTimestampNow();
472 $won = wfInvertTimestamp( $now );
473 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
474 "',cur_comment='" . wfStrencode( $summary ) .
475 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
476 ",cur_timestamp='{$now}',cur_user_text='" .
477 wfStrencode( $wgUser->getName() ) .
478 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
479 "WHERE cur_id=" . $this->getID() .
480 " AND cur_timestamp='" . $this->getTimestamp() . "'";
481 $res = wfQuery( $sql, DB_WRITE, $fname );
483 if( wfAffectedRows() == 0 ) {
484 /* Belated edit conflict! Run away!! */
485 return false;
488 # This overwrites $oldtext if revision compression is on
489 $flags = Article::compressRevisionText( $oldtext );
491 $sql = "INSERT INTO old (old_namespace,old_title,old_text," .
492 "old_comment,old_user,old_user_text,old_timestamp," .
493 "old_minor_edit,inverse_timestamp,old_flags) VALUES (" .
494 $this->mTitle->getNamespace() . ", '" .
495 wfStrencode( $this->mTitle->getDBkey() ) . "', '" .
496 wfStrencode( $oldtext ) . "', '" .
497 wfStrencode( $this->getComment() ) . "', " .
498 $this->getUser() . ", '" .
499 wfStrencode( $this->getUserText() ) . "', '" .
500 $this->getTimestamp() . "', " . $me1 . ", '" .
501 wfInvertTimestamp( $this->getTimestamp() ) . "','$flags')";
502 $res = wfQuery( $sql, DB_WRITE, $fname );
503 $oldid = wfInsertID( $res );
505 $bot = (int)($wgUser->isBot() || $forceBot);
506 RecentChange::notifyEdit( $now, $this->mTitle, $me2, $wgUser, $summary,
507 $oldid, $this->getTimestamp() );
508 Article::onArticleEdit( $this->mTitle );
511 if( $wgDBtransactions ) {
512 $sql = "COMMIT";
513 wfQuery( $sql, DB_WRITE );
516 if ($watchthis) {
517 if (!$this->mTitle->userIsWatching()) $this->watch();
518 } else {
519 if ( $this->mTitle->userIsWatching() ) {
520 $this->unwatch();
524 $this->showArticle( $text, wfMsg( "updated" ) );
525 return true;
528 # After we've either updated or inserted the article, update
529 # the link tables and redirect to the new page.
531 function showArticle( $text, $subtitle )
533 global $wgOut, $wgUser, $wgLinkCache;
534 global $wgMwRedir;
536 $wgLinkCache = new LinkCache();
538 # Get old version of link table to allow incremental link updates
539 $wgLinkCache->preFill( $this->mTitle );
540 $wgLinkCache->clear();
542 # Now update the link cache by parsing the text
543 $wgOut = new OutputPage();
544 $wgOut->addWikiText( $text );
546 $this->editUpdates( $text );
547 if( $wgMwRedir->matchStart( $text ) )
548 $r = "redirect=no";
549 else
550 $r = "";
551 $wgOut->redirect( wfLocalUrl( $this->mTitle->getPrefixedURL(), $r ) );
554 # Add this page to my watchlist
556 function watch( $add = true )
558 global $wgUser, $wgOut, $wgLang;
559 global $wgDeferredUpdateList;
561 if ( 0 == $wgUser->getID() ) {
562 $wgOut->errorpage( "watchnologin", "watchnologintext" );
563 return;
565 if ( wfReadOnly() ) {
566 $wgOut->readOnlyPage();
567 return;
569 if( $add )
570 $wgUser->addWatch( $this->mTitle );
571 else
572 $wgUser->removeWatch( $this->mTitle );
574 $wgOut->setPagetitle( wfMsg( $add ? "addedwatch" : "removedwatch" ) );
575 $wgOut->setRobotpolicy( "noindex,follow" );
577 $sk = $wgUser->getSkin() ;
578 $link = $sk->makeKnownLink ( $this->mTitle->getPrefixedText() ) ;
580 if($add)
581 $text = wfMsg( "addedwatchtext", $link );
582 else
583 $text = wfMsg( "removedwatchtext", $link );
584 $wgOut->addHTML( $text );
586 $up = new UserUpdate();
587 array_push( $wgDeferredUpdateList, $up );
589 $wgOut->returnToMain( false );
592 function unwatch()
594 $this->watch( false );
597 function protect( $limit = "sysop" )
599 global $wgUser, $wgOut;
601 if ( ! $wgUser->isSysop() ) {
602 $wgOut->sysopRequired();
603 return;
605 if ( wfReadOnly() ) {
606 $wgOut->readOnlyPage();
607 return;
609 $id = $this->mTitle->getArticleID();
610 if ( 0 == $id ) {
611 $wgOut->fatalEror( wfMsg( "badarticleerror" ) );
612 return;
614 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
615 "cur_restrictions='{$limit}' WHERE cur_id={$id}";
616 wfQuery( $sql, DB_WRITE, "Article::protect" );
618 $log = new LogPage( wfMsg( "protectlogpage" ), wfMsg( "protectlogtext" ) );
619 if ( $limit === "" ) {
620 $log->addEntry( wfMsg( "unprotectedarticle", $this->mTitle->getPrefixedText() ), "" );
621 } else {
622 $log->addEntry( wfMsg( "protectedarticle", $this->mTitle->getPrefixedText() ), "" );
624 $wgOut->redirect( wfLocalUrl( $this->mTitle->getPrefixedURL() ) );
627 function unprotect()
629 return $this->protect( "" );
632 function delete()
634 global $wgUser, $wgOut, $wgMessageCache;
635 global $wpConfirm, $wpReason, $image, $oldimage;
637 # This code desperately needs to be totally rewritten
639 if ( ( ! $wgUser->isSysop() ) ) {
640 $wgOut->sysopRequired();
641 return;
643 if ( wfReadOnly() ) {
644 $wgOut->readOnlyPage();
645 return;
648 # Can't delete cached MediaWiki namespace (i.e. vital messages)
649 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI && $wgMessageCache->isCacheable( $this->mTitle->getDBkey() ) ) {
650 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
651 return;
654 # Better double-check that it hasn't been deleted yet!
655 $wgOut->setPagetitle( wfMsg( "confirmdelete" ) );
656 if ( ( "" == trim( $this->mTitle->getText() ) )
657 or ( $this->mTitle->getArticleId() == 0 ) ) {
658 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
659 return;
662 if ( $_POST["wpConfirm"] ) {
663 $this->doDelete();
664 return;
667 # determine whether this page has earlier revisions
668 # and insert a warning if it does
669 # we select the text because it might be useful below
670 $ns = $this->mTitle->getNamespace();
671 $title = $this->mTitle->getDBkey();
672 $etitle = wfStrencode( $title );
673 $sql = "SELECT old_text,old_flags FROM old WHERE old_namespace=$ns and old_title='$etitle' ORDER BY inverse_timestamp LIMIT 1";
674 $res = wfQuery( $sql, DB_READ, $fname );
675 if( ($old=wfFetchObject($res)) && !$wpConfirm ) {
676 $skin=$wgUser->getSkin();
677 $wgOut->addHTML("<B>".wfMsg("historywarning"));
678 $wgOut->addHTML( $skin->historyLink() ."</B><P>");
681 $sql="SELECT cur_text FROM cur WHERE cur_namespace=$ns and cur_title='$etitle'";
682 $res=wfQuery($sql, DB_READ, $fname);
683 if( ($s=wfFetchObject($res))) {
685 # if this is a mini-text, we can paste part of it into the deletion reason
687 #if this is empty, an earlier revision may contain "useful" text
688 if($s->cur_text!="") {
689 $text=$s->cur_text;
690 } else {
691 if($old) {
692 $text = Article::getRevisionText( $old );
693 $blanked=1;
698 $length=strlen($text);
700 # this should not happen, since it is not possible to store an empty, new
701 # page. Let's insert a standard text in case it does, though
702 if($length==0 && !$wpReason) { $wpReason=wfmsg("exblank");}
705 if($length < 500 && !$wpReason) {
707 # comment field=255, let's grep the first 150 to have some user
708 # space left
709 $text=substr($text,0,150);
710 # let's strip out newlines and HTML tags
711 $text=preg_replace("/\"/","'",$text);
712 $text=preg_replace("/\</","&lt;",$text);
713 $text=preg_replace("/\>/","&gt;",$text);
714 $text=preg_replace("/[\n\r]/","",$text);
715 if(!$blanked) {
716 $wpReason=wfMsg("excontent"). " '".$text;
717 } else {
718 $wpReason=wfMsg("exbeforeblank") . " '".$text;
720 if($length>150) { $wpReason .= "..."; } # we've only pasted part of the text
721 $wpReason.="'";
725 return $this->confirmDelete();
728 function confirmDelete( $par = "" )
730 global $wgOut;
731 global $wpReason;
733 wfDebug( "Article::confirmDelete\n" );
735 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
736 $wgOut->setSubtitle( wfMsg( "deletesub", $sub ) );
737 $wgOut->setRobotpolicy( "noindex,nofollow" );
738 $wgOut->addWikiText( wfMsg( "confirmdeletetext" ) );
740 $t = $this->mTitle->getPrefixedURL();
742 $formaction = wfEscapeHTML( wfLocalUrl( $t, "action=delete" . $par ) );
743 $confirm = wfMsg( "confirm" );
744 $check = wfMsg( "confirmcheck" );
745 $delcom = wfMsg( "deletecomment" );
747 $wgOut->addHTML( "
748 <form id=\"deleteconfirm\" method=\"post\" action=\"{$formaction}\">
749 <table border=0><tr><td align=right>
750 {$delcom}:</td><td align=left>
751 <input type=text size=60 name=\"wpReason\" value=\"" . htmlspecialchars( $wpReason ) . "\">
752 </td></tr><tr><td>&nbsp;</td></tr>
753 <tr><td align=right>
754 <input type=checkbox name=\"wpConfirm\" value='1' id=\"wpConfirm\">
755 </td><td><label for=\"wpConfirm\">{$check}</label></td>
756 </tr><tr><td>&nbsp;</td><td>
757 <input type=submit name=\"wpConfirmB\" value=\"{$confirm}\">
758 </td></tr></table></form>\n" );
760 $wgOut->returnToMain( false );
763 function doDelete()
765 global $wgOut, $wgUser, $wgLang;
766 global $wpReason;
767 $fname = "Article::doDelete";
768 wfDebug( "$fname\n" );
770 $this->doDeleteArticle( $this->mTitle );
771 $deleted = $this->mTitle->getPrefixedText();
773 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
774 $wgOut->setRobotpolicy( "noindex,nofollow" );
776 $sk = $wgUser->getSkin();
777 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
778 Namespace::getWikipedia() ) .
779 ":" . wfMsg( "dellogpage" ), wfMsg( "deletionlog" ) );
781 $text = wfMsg( "deletedtext", $deleted, $loglink );
783 $wgOut->addHTML( "<p>" . $text );
784 $wgOut->returnToMain( false );
787 function doDeleteArticle( $title )
789 global $wgUser, $wgOut, $wgLang, $wpReason, $wgDeferredUpdateList;
791 $fname = "Article::doDeleteArticle";
792 wfDebug( "$fname\n" );
794 $ns = $title->getNamespace();
795 $t = wfStrencode( $title->getDBkey() );
796 $id = $title->getArticleID();
798 if ( "" == $t ) {
799 $wgOut->fatalError( wfMsg( "cannotdelete" ) );
800 return;
803 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
804 array_push( $wgDeferredUpdateList, $u );
806 # Move article and history to the "archive" table
807 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
808 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
809 "ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment," .
810 "cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur " .
811 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
812 wfQuery( $sql, DB_WRITE, $fname );
814 $sql = "INSERT INTO archive (ar_namespace,ar_title,ar_text," .
815 "ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit," .
816 "ar_flags) SELECT old_namespace,old_title,old_text,old_comment," .
817 "old_user,old_user_text,old_timestamp,old_minor_edit,old_flags " .
818 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
819 wfQuery( $sql, DB_WRITE, $fname );
821 # Now that it's safely backed up, delete it
823 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
824 "cur_title='{$t}'";
825 wfQuery( $sql, DB_WRITE, $fname );
827 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
828 "old_title='{$t}'";
829 wfQuery( $sql, DB_WRITE, $fname );
831 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
832 "rc_title='{$t}'";
833 wfQuery( $sql, DB_WRITE, $fname );
835 # Finally, clean up the link tables
837 if ( 0 != $id ) {
839 $t = wfStrencode( $title->getPrefixedDBkey() );
841 Article::onArticleDelete( $title );
843 $sql = "SELECT l_from FROM links WHERE l_to={$id}";
844 $res = wfQuery( $sql, DB_READ, $fname );
846 $sql = "INSERT INTO brokenlinks (bl_from,bl_to) VALUES ";
847 $now = wfTimestampNow();
848 $sql2 = "UPDATE cur SET cur_touched='{$now}' WHERE cur_id IN (";
849 $first = true;
851 while ( $s = wfFetchObject( $res ) ) {
852 $nt = Title::newFromDBkey( $s->l_from );
853 $lid = $nt->getArticleID();
855 if ( ! $first ) { $sql .= ","; $sql2 .= ","; }
856 $first = false;
857 $sql .= "({$lid},'{$t}')";
858 $sql2 .= "{$lid}";
860 $sql2 .= ")";
861 if ( ! $first ) {
862 wfQuery( $sql, DB_WRITE, $fname );
863 wfQuery( $sql2, DB_WRITE, $fname );
865 wfFreeResult( $res );
867 $sql = "DELETE FROM links WHERE l_to={$id}";
868 wfQuery( $sql, DB_WRITE, $fname );
870 $sql = "DELETE FROM links WHERE l_from='{$t}'";
871 wfQuery( $sql, DB_WRITE, $fname );
873 $sql = "DELETE FROM imagelinks WHERE il_from='{$t}'";
874 wfQuery( $sql, DB_WRITE, $fname );
876 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
877 wfQuery( $sql, DB_WRITE, $fname );
880 $log = new LogPage( wfMsg( "dellogpage" ), wfMsg( "dellogpagetext" ) );
881 $art = $title->getPrefixedText();
882 $wpReason = wfCleanQueryVar( $wpReason );
883 $log->addEntry( wfMsg( "deletedarticle", $art ), $wpReason );
885 # Clear the cached article id so the interface doesn't act like we exist
886 $this->mTitle->resetArticleID( 0 );
887 $this->mTitle->mArticleID = 0;
890 function rollback()
892 global $wgUser, $wgLang, $wgOut, $from;
894 if ( ! $wgUser->isSysop() ) {
895 $wgOut->sysopRequired();
896 return;
898 if ( wfReadOnly() ) {
899 $wgOut->readOnlyPage( $this->getContent() );
900 return;
903 # Enhanced rollback, marks edits rc_bot=1
904 $bot = !!$_REQUEST['bot'];
906 # Replace all this user's current edits with the next one down
907 $tt = wfStrencode( $this->mTitle->getDBKey() );
908 $n = $this->mTitle->getNamespace();
910 # Get the last editor
911 $sql = "SELECT cur_id,cur_user,cur_user_text,cur_comment FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
912 $res = wfQuery( $sql, DB_READ );
913 if( ($x = wfNumRows( $res )) != 1 ) {
914 # Something wrong
915 $wgOut->addHTML( wfMsg( "notanarticle" ) );
916 return;
918 $s = wfFetchObject( $res );
919 $ut = wfStrencode( $s->cur_user_text );
920 $uid = $s->cur_user;
921 $pid = $s->cur_id;
923 $from = str_replace( '_', ' ', wfCleanQueryVar( $from ) );
924 if( $from != $s->cur_user_text ) {
925 $wgOut->setPageTitle(wfmsg("rollbackfailed"));
926 $wgOut->addWikiText( wfMsg( "alreadyrolled",
927 htmlspecialchars( $this->mTitle->getPrefixedText()),
928 htmlspecialchars( $from ),
929 htmlspecialchars( $s->cur_user_text ) ) );
930 if($s->cur_comment != "") {
931 $wgOut->addHTML(
932 wfMsg("editcomment",
933 htmlspecialchars( $s->cur_comment ) ) );
935 return;
938 # Get the last edit not by this guy
939 $sql = "SELECT old_text,old_user,old_user_text,old_timestamp,old_flags
940 FROM old USE INDEX (name_title_timestamp)
941 WHERE old_namespace={$n} AND old_title='{$tt}'
942 AND (old_user <> {$uid} OR old_user_text <> '{$ut}')
943 ORDER BY inverse_timestamp LIMIT 1";
944 $res = wfQuery( $sql, DB_READ );
945 if( wfNumRows( $res ) != 1 ) {
946 # Something wrong
947 $wgOut->setPageTitle(wfMsg("rollbackfailed"));
948 $wgOut->addHTML( wfMsg( "cantrollback" ) );
949 return;
951 $s = wfFetchObject( $res );
953 if ( $bot ) {
954 # Mark all reverted edits as bot
955 $sql = "UPDATE recentchanges SET rc_bot=1 WHERE
956 rc_cur_id=$pid AND rc_user=$uid AND rc_timestamp > '{$s->old_timestamp}'";
957 wfQuery( $sql, DB_WRITE, $fname );
960 # Save it!
961 $newcomment = wfMsg( "revertpage", $s->old_user_text, $from );
962 $wgOut->setPagetitle( wfMsg( "actioncomplete" ) );
963 $wgOut->setRobotpolicy( "noindex,nofollow" );
964 $wgOut->addHTML( "<h2>" . $newcomment . "</h2>\n<hr>\n" );
965 $this->updateArticle( Article::getRevisionText( $s ), $newcomment, 1, $this->mTitle->userIsWatching(), "", $bot );
967 Article::onArticleEdit( $this->mTitle );
968 $wgOut->returnToMain( false );
972 # Do standard deferred updates after page view
974 /* private */ function viewUpdates()
976 global $wgDeferredUpdateList;
977 if ( 0 != $this->getID() ) {
978 global $wgDisableCounters;
979 if( !$wgDisableCounters ) {
980 Article::incViewCount( $this->getID() );
981 $u = new SiteStatsUpdate( 1, 0, 0 );
982 array_push( $wgDeferredUpdateList, $u );
984 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
985 $this->mTitle->getDBkey() );
986 array_push( $wgDeferredUpdateList, $u );
990 # Do standard deferred updates after page edit.
991 # Every 1000th edit, prune the recent changes table.
993 /* private */ function editUpdates( $text )
995 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
996 global $wgMessageCache;
998 wfSeedRandom();
999 if ( 0 == mt_rand( 0, 999 ) ) {
1000 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1001 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1002 wfQuery( $sql, DB_WRITE );
1004 $id = $this->getID();
1005 $title = $this->mTitle->getPrefixedDBkey();
1006 $shortTitle = $this->mTitle->getDBkey();
1008 $adj = $this->mCountAdjustment;
1010 if ( 0 != $id ) {
1011 $u = new LinksUpdate( $id, $title );
1012 array_push( $wgDeferredUpdateList, $u );
1013 $u = new SiteStatsUpdate( 0, 1, $adj );
1014 array_push( $wgDeferredUpdateList, $u );
1015 $u = new SearchUpdate( $id, $title, $text );
1016 array_push( $wgDeferredUpdateList, $u );
1018 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle );
1019 array_push( $wgDeferredUpdateList, $u );
1021 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1022 $wgMessageCache->replace( $shortTitle, $text );
1027 /* private */ function setOldSubtitle()
1029 global $wgLang, $wgOut;
1031 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1032 $r = wfMsg( "revisionasof", $td );
1033 $wgOut->setSubtitle( "({$r})" );
1036 # This function is called right before saving the wikitext,
1037 # so we can do things like signatures and links-in-context.
1039 function preSaveTransform( $text )
1041 $s = "";
1042 while ( "" != $text ) {
1043 $p = preg_split( "/<\\s*nowiki\\s*>/i", $text, 2 );
1044 $s .= $this->pstPass2( $p[0] );
1046 if ( ( count( $p ) < 2 ) || ( "" == $p[1] ) ) { $text = ""; }
1047 else {
1048 $q = preg_split( "/<\\/\\s*nowiki\\s*>/i", $p[1], 2 );
1049 $s .= "<nowiki>{$q[0]}</nowiki>";
1050 $text = $q[1];
1053 return rtrim( $s );
1056 /* private */ function pstPass2( $text )
1058 global $wgUser, $wgLang, $wgLocaltimezone;
1060 # Signatures
1062 $n = $wgUser->getName();
1063 $k = $wgUser->getOption( "nickname" );
1064 if ( "" == $k ) { $k = $n; }
1065 if(isset($wgLocaltimezone)) {
1066 $oldtz = getenv("TZ"); putenv("TZ=$wgLocaltimezone");
1068 /* Note: this is an ugly timezone hack for the European wikis */
1069 $d = $wgLang->timeanddate( date( "YmdHis" ), false ) .
1070 " (" . date( "T" ) . ")";
1071 if(isset($wgLocaltimezone)) putenv("TZ=$oldtz");
1073 $text = preg_replace( "/~~~~/", "[[" . $wgLang->getNsText(
1074 Namespace::getUser() ) . ":$n|$k]] $d", $text );
1075 $text = preg_replace( "/~~~/", "[[" . $wgLang->getNsText(
1076 Namespace::getUser() ) . ":$n|$k]]", $text );
1078 # Context links: [[|name]] and [[name (context)|]]
1080 $tc = "[&;%\\-,.\\(\\)' _0-9A-Za-z\\/:\\x80-\\xff]";
1081 $np = "[&;%\\-,.' _0-9A-Za-z\\/:\\x80-\\xff]"; # No parens
1082 $namespacechar = '[ _0-9A-Za-z\x80-\xff]'; # Namespaces can use non-ascii!
1083 $conpat = "/^({$np}+) \\(({$tc}+)\\)$/";
1085 $p1 = "/\[\[({$np}+) \\(({$np}+)\\)\\|]]/"; # [[page (context)|]]
1086 $p2 = "/\[\[\\|({$tc}+)]]/"; # [[|page]]
1087 $p3 = "/\[\[($namespacechar+):({$np}+)\\|]]/"; # [[namespace:page|]]
1088 $p4 = "/\[\[($namespacechar+):({$np}+) \\(({$np}+)\\)\\|]]/";
1089 # [[ns:page (cont)|]]
1090 $context = "";
1091 $t = $this->mTitle->getText();
1092 if ( preg_match( $conpat, $t, $m ) ) {
1093 $context = $m[2];
1095 $text = preg_replace( $p4, "[[\\1:\\2 (\\3)|\\2]]", $text );
1096 $text = preg_replace( $p1, "[[\\1 (\\2)|\\1]]", $text );
1097 $text = preg_replace( $p3, "[[\\1:\\2|\\2]]", $text );
1099 if ( "" == $context ) {
1100 $text = preg_replace( $p2, "[[\\1]]", $text );
1101 } else {
1102 $text = preg_replace( $p2, "[[\\1 ({$context})|\\1]]", $text );
1105 # {{SUBST:xxx}} variables
1107 $mw =& MagicWord::get( MAG_SUBST );
1108 $text = $mw->substituteCallback( $text, "wfReplaceSubstVar" );
1110 /* Experimental:
1111 # Trim trailing whitespace
1112 # MAG_END (__END__) tag allows for trailing
1113 # whitespace to be deliberately included
1114 $text = rtrim( $text );
1115 $mw =& MagicWord::get( MAG_END );
1116 $mw->matchAndRemove( $text );
1118 return $text;
1121 /* Caching functions */
1123 # checkLastModified returns true iff it has taken care of all
1124 # output to the client that is necessary for this request.
1125 # (that is, it has sent a cached version of the page)
1126 function tryFileCache() {
1127 static $called = false;
1128 if( $called ) {
1129 wfDebug( " tryFileCache() -- called twice!?\n" );
1130 return;
1132 $called = true;
1133 if($this->isFileCacheable()) {
1134 $touched = $this->mTouched;
1135 if( $this->mTitle->getPrefixedDBkey() == wfMsg( "mainpage" ) ) {
1136 # Expire the main page quicker
1137 $expire = wfUnix2Timestamp( time() - 3600 );
1138 $touched = max( $expire, $touched );
1140 $cache = new CacheManager( $this->mTitle );
1141 if($cache->isFileCacheGood( $touched )) {
1142 global $wgOut;
1143 wfDebug( " tryFileCache() - about to load\n" );
1144 $cache->loadFromFileCache();
1145 return true;
1146 } else {
1147 wfDebug( " tryFileCache() - starting buffer\n" );
1148 ob_start( array(&$cache, 'saveToFileCache' ) );
1150 } else {
1151 wfDebug( " tryFileCache() - not cacheable\n" );
1155 function isFileCacheable() {
1156 global $wgUser, $wgUseFileCache, $wgShowIPinHeader;
1157 global $action, $oldid, $diff, $redirect, $printable;
1158 return $wgUseFileCache
1159 and (!$wgShowIPinHeader)
1160 and ($this->getID() != 0)
1161 and ($wgUser->getId() == 0)
1162 and (!$wgUser->getNewtalk())
1163 and ($this->mTitle->getNamespace() != Namespace::getSpecial())
1164 and ($action == "view")
1165 and (!isset($oldid))
1166 and (!isset($diff))
1167 and (!isset($redirect))
1168 and (!isset($printable))
1169 and (!$this->mRedirectedFrom);
1172 function checkTouched() {
1173 $id = $this->getID();
1174 $sql = "SELECT cur_touched,cur_is_redirect FROM cur WHERE cur_id=$id";
1175 $res = wfQuery( $sql, DB_READ, "Article::checkTouched" );
1176 if( $s = wfFetchObject( $res ) ) {
1177 $this->mTouched = $s->cur_touched;
1178 return !$s->cur_is_redirect;
1179 } else {
1180 return false;
1184 /* static */ function incViewCount( $id )
1186 $id = intval( $id );
1187 global $wgHitcounterUpdateFreq;
1189 if( $wgHitcounterUpdateFreq <= 1 ){ //
1190 wfQuery("UPDATE cur SET cur_counter = cur_counter + 1 " .
1191 "WHERE cur_id = $id", DB_WRITE);
1192 return;
1195 # Not important enough to warrant an error page in case of failure
1196 $oldignore = wfIgnoreSQLErrors( true );
1198 wfQuery("INSERT INTO hitcounter (hc_id) VALUES ({$id})", DB_WRITE);
1200 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
1201 if( (rand() % $checkfreq != 0) or (wfLastErrno() != 0) ){
1202 # Most of the time (or on SQL errors), skip row count check
1203 wfIgnoreSQLErrors( $oldignore );
1204 return;
1207 $res = wfQuery("SELECT COUNT(*) as n FROM hitcounter", DB_WRITE);
1208 $row = wfFetchObject( $res );
1209 $rown = intval( $row->n );
1210 if( $rown >= $wgHitcounterUpdateFreq ){
1211 wfProfileIn( "Article::incViewCount-collect" );
1212 $old_user_abort = ignore_user_abort( true );
1214 wfQuery("LOCK TABLES hitcounter WRITE", DB_WRITE);
1215 wfQuery("CREATE TEMPORARY TABLE acchits TYPE=HEAP ".
1216 "SELECT hc_id,COUNT(*) AS hc_n FROM hitcounter ".
1217 "GROUP BY hc_id", DB_WRITE);
1218 wfQuery("DELETE FROM hitcounter", DB_WRITE);
1219 wfQuery("UNLOCK TABLES", DB_WRITE);
1220 wfQuery("UPDATE cur,acchits SET cur_counter=cur_counter + hc_n ".
1221 "WHERE cur_id = hc_id", DB_WRITE);
1222 wfQuery("DROP TABLE acchits", DB_WRITE);
1224 ignore_user_abort( $old_user_abort );
1225 wfProfileOut( "Article::incViewCount-collect" );
1227 wfIgnoreSQLErrors( $oldignore );
1230 # The onArticle*() functions are supposed to be a kind of hooks
1231 # which should be called whenever any of the specified actions
1232 # are done.
1234 # This is a good place to put code to clear caches, for instance.
1236 /* static */ function onArticleCreate($title_obj){
1237 global $wgEnablePersistentLC, $wgEnableParserCache;
1238 if ( $wgEnablePersistentLC ) {
1239 LinkCache::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1241 if ( $wgEnableParserCache ) {
1242 OutputPage::parsercacheClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1246 /* static */ function onArticleDelete($title_obj){
1247 global $wgEnablePersistentLC, $wgEnableParserCache;
1248 if ( $wgEnablePersistentLC ) {
1249 LinkCache::linksccClearLinksTo( $title_obj->getArticleID() );
1251 if ( $wgEnableParserCache ) {
1252 OutputPage::parsercacheClearLinksTo( $title_obj->getArticleID() );
1256 /* static */ function onArticleEdit($title_obj){
1257 global $wgEnablePersistentLC, $wgEnableParserCache;
1258 if ( $wgEnablePersistentLC ) {
1259 LinkCache::linksccClearPage( $title_obj->getArticleID() );
1261 if ( $wgEnableParserCache ) {
1262 OutputPage::parsercacheClearPage( $title_obj->getArticleID() );
1267 function wfReplaceSubstVar( $matches ) {
1268 return wfMsg( $matches[1] );