* Removed $wgBlockExpiryOptions, obsoleted by msg:ipboptions
[mediawiki.git] / includes / Article.php
blobcd22c09cdb60d3eb8283052589bf7cfc4711740a
1 <?php
2 /**
3 * File for articles
4 * @package MediaWiki
5 */
7 /**
8 * Need the CacheManager to be loaded
9 */
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
16 /**
17 * Class representing a MediaWiki article and history.
19 * See design.txt for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
23 * @package MediaWiki
25 class Article {
26 /**#@+
27 * @access private
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mGoodAdjustment, $mTotalAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
34 var $mId, $mTable;
35 var $mForUpdate;
36 var $mOldId;
37 var $mRevIdFetched;
38 /**#@-*/
40 /**
41 * Constructor and clear the article
42 * @param mixed &$title
44 function Article( &$title ) {
45 $this->mTitle =& $title;
46 $this->clear();
49 /**
50 * get the title object of the article
51 * @public
53 function getTitle() {
54 return $this->mTitle;
57 /**
58 * Clear the object
59 * @private
61 function clear() {
62 $this->mDataLoaded = false;
63 $this->mContentLoaded = false;
65 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
66 $this->mRedirectedFrom = $this->mUserText =
67 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
68 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
69 $this->mTouched = '19700101000000';
70 $this->mForUpdate = false;
71 $this->mIsRedirect = false;
72 $this->mRevIdFetched = 0;
75 /**
76 * Note that getContent/loadContent may follow redirects if
77 * not told otherwise, and so may cause a change to mTitle.
79 * @param $noredir
80 * @return Return the text of this revision
82 function getContent( $noredir ) {
83 global $wgRequest, $wgUser;
85 # Get variables from query string :P
86 $action = $wgRequest->getText( 'action', 'view' );
87 $section = $wgRequest->getText( 'section' );
89 $fname = 'Article::getContent';
90 wfProfileIn( $fname );
92 if ( 0 == $this->getID() ) {
93 if ( 'edit' == $action ) {
94 wfProfileOut( $fname );
95 return ''; # was "newarticletext", now moved above the box)
97 wfProfileOut( $fname );
98 return wfMsg( 'noarticletext' );
99 } else {
100 $this->loadContent( $noredir );
101 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
102 if ( $this->mTitle->getNamespace() == NS_USER_TALK &&
103 $wgUser->isIP($this->mTitle->getText()) &&
104 $action=='view'
106 wfProfileOut( $fname );
107 return $this->mContent . "\n" .wfMsg('anontalkpagetext');
108 } else {
109 if($action=='edit') {
110 if($section!='') {
111 if($section=='new') {
112 wfProfileOut( $fname );
113 return '';
116 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
117 # comments to be stripped as well)
118 $rv=$this->getSection($this->mContent,$section);
119 wfProfileOut( $fname );
120 return $rv;
123 wfProfileOut( $fname );
124 return $this->mContent;
130 * This function returns the text of a section, specified by a number ($section).
131 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
132 * the first section before any such heading (section 0).
134 * If a section contains subsections, these are also returned.
136 * @param string $text text to look in
137 * @param integer $section section number
138 * @return string text of the requested section
140 function getSection($text,$section) {
142 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
143 # comments to be stripped as well)
144 $striparray=array();
145 $parser=new Parser();
146 $parser->mOutputType=OT_WIKI;
147 $striptext=$parser->strip($text, $striparray, true);
149 # now that we can be sure that no pseudo-sections are in the source,
150 # split it up by section
151 $secs =
152 preg_split(
153 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
154 $striptext, -1,
155 PREG_SPLIT_DELIM_CAPTURE);
156 if($section==0) {
157 $rv=$secs[0];
158 } else {
159 $headline=$secs[$section*2-1];
160 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
161 $hlevel=$matches[1];
163 # translate wiki heading into level
164 if(strpos($hlevel,'=')!==false) {
165 $hlevel=strlen($hlevel);
168 $rv=$headline. $secs[$section*2];
169 $count=$section+1;
171 $break=false;
172 while(!empty($secs[$count*2-1]) && !$break) {
174 $subheadline=$secs[$count*2-1];
175 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
176 $subhlevel=$matches[1];
177 if(strpos($subhlevel,'=')!==false) {
178 $subhlevel=strlen($subhlevel);
180 if($subhlevel > $hlevel) {
181 $rv.=$subheadline.$secs[$count*2];
183 if($subhlevel <= $hlevel) {
184 $break=true;
186 $count++;
190 # reinsert stripped tags
191 $rv=$parser->unstrip($rv,$striparray);
192 $rv=$parser->unstripNoWiki($rv,$striparray);
193 $rv=trim($rv);
194 return $rv;
199 * Return an array of the columns of the "cur"-table
201 function getContentFields() {
202 return $wgArticleContentFields = array(
203 'old_text','old_flags',
204 'rev_timestamp','rev_user', 'rev_user_text', 'rev_comment','page_counter',
205 'page_namespace', 'page_title', 'page_restrictions','page_touched','page_is_redirect' );
209 * Return the oldid of the article that is to be shown.
210 * For requests with a "direction", this is not the oldid of the
211 * query
213 function getOldID() {
214 global $wgRequest, $wgOut;
215 static $lastid;
217 if ( isset( $lastid ) ) {
218 return $lastid;
220 # Query variables :P
221 $oldid = $wgRequest->getVal( 'oldid' );
222 if ( isset( $oldid ) ) {
223 $oldid = IntVal( $oldid );
224 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
225 $nextid = $this->mTitle->getNextRevisionID( $oldid );
226 if ( $nextid ) {
227 $oldid = $nextid;
228 } else {
229 $wgOut->redirect( $this->mTitle->getFullURL( 'redirect=no' ) );
231 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
232 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
233 if ( $previd ) {
234 $oldid = $previd;
235 } else {
236 # TODO
239 $lastid = $oldid;
241 return @$oldid; # "@" to be able to return "unset" without PHP complaining
246 * Load the revision (including cur_text) into this object
248 function loadContent( $noredir = false ) {
249 global $wgOut, $wgRequest;
251 if ( $this->mContentLoaded ) return;
253 # Query variables :P
254 $oldid = $this->getOldID();
255 $redirect = $wgRequest->getVal( 'redirect' );
257 $fname = 'Article::loadContent';
259 # Pre-fill content with error message so that if something
260 # fails we'll have something telling us what we intended.
262 $t = $this->mTitle->getPrefixedText();
264 $noredir = $noredir || ($wgRequest->getVal( 'redirect' ) == 'no')
265 || $wgRequest->getCheck( 'rdfrom' );
266 $this->mOldId = $oldid;
267 $this->fetchContent( $oldid, $noredir, true );
272 * Fetch a page record with the given conditions
273 * @param Database $dbr
274 * @param array $conditions
275 * @access private
277 function pageData( &$dbr, $conditions ) {
278 return $dbr->selectRow( 'page',
279 array(
280 'page_id',
281 'page_namespace',
282 'page_title',
283 'page_restrictions',
284 'page_counter',
285 'page_is_redirect',
286 'page_is_new',
287 'page_random',
288 'page_touched',
289 'page_latest',
290 'page_len' ),
291 $conditions,
292 'Article::pageData' );
295 function pageDataFromTitle( &$dbr, $title ) {
296 return $this->pageData( $dbr, array(
297 'page_namespace' => $title->getNamespace(),
298 'page_title' => $title->getDBkey() ) );
301 function pageDataFromId( &$dbr, $id ) {
302 return $this->pageData( $dbr, array(
303 'page_id' => IntVal( $id ) ) );
307 * Set the general counter, title etc data loaded from
308 * some source.
310 * @param object $data
311 * @access private
313 function loadPageData( $data ) {
314 $this->mTitle->loadRestrictions( $data->page_restrictions );
315 $this->mTitle->mRestrictionsLoaded = true;
317 $this->mCounter = $data->page_counter;
318 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
319 $this->mIsRedirect = $data->page_is_redirect;
320 $this->mLatest = $data->page_latest;
322 $this->mDataLoaded = true;
326 * Get text of an article from database
327 * @param int $oldid 0 for whatever the latest revision is
328 * @param bool $noredir Set to true to avoid following redirects
329 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
330 * @return string
332 function fetchContent( $oldid = 0, $noredir = false, $globalTitle = false ) {
333 if ( $this->mContentLoaded ) {
334 return $this->mContent;
336 $dbr =& $this->getDB();
337 $fname = 'Article::fetchContent';
339 # Pre-fill content with error message so that if something
340 # fails we'll have something telling us what we intended.
341 $t = $this->mTitle->getPrefixedText();
342 if( $oldid ) {
343 $t .= ',oldid='.$oldid;
345 if( isset( $redirect ) ) {
346 $redirect = ($redirect == 'no') ? 'no' : 'yes';
347 $t .= ',redirect='.$redirect;
349 $this->mContent = wfMsg( 'missingarticle', $t );
351 if( $oldid ) {
352 $revision = Revision::newFromId( $oldid );
353 if( is_null( $revision ) ) {
354 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
355 return false;
357 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
358 if( !$data ) {
359 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
360 return false;
362 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
363 $this->loadPageData( $data );
364 } else {
365 if( !$this->mDataLoaded ) {
366 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
367 if( !$data ) {
368 wfDebug( "$fname failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
369 return false;
371 $this->loadPageData( $data );
373 $revision = Revision::newFromId( $this->mLatest );
374 if( is_null( $revision ) ) {
375 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
376 return false;
380 # If we got a redirect, follow it (unless we've been told
381 # not to by either the function parameter or the query
382 if ( !$oldid && !$noredir ) {
383 $rt = Title::newFromRedirect( $revision->getText() );
384 # process if title object is valid and not special:userlogout
385 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) ) {
386 # Gotta hand redirects to special pages differently:
387 # Fill the HTTP response "Location" header and ignore
388 # the rest of the page we're on.
389 global $wgDisableHardRedirects;
390 if( $globalTitle && !$wgDisableHardRedirects ) {
391 global $wgOut;
392 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
393 $source = $this->mTitle->getFullURL( 'redirect=no' );
394 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
395 return false;
397 if ( $rt->getNamespace() == NS_SPECIAL ) {
398 $wgOut->redirect( $rt->getFullURL() );
399 return false;
402 $redirData = $this->pageDataFromTitle( $dbr, $rt );
403 if( $redirData ) {
404 $redirRev = Revision::newFromId( $redirData->page_latest );
405 if( !is_null( $redirRev ) ) {
406 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
407 $this->mTitle = $rt;
408 $data = $redirData;
409 $this->loadPageData( $data );
410 $revision = $redirRev;
416 # if the title's different from expected, update...
417 if( $globalTitle ) {
418 global $wgTitle;
419 if( !$this->mTitle->equals( $wgTitle ) ) {
420 $wgTitle = $this->mTitle;
424 # Back to the business at hand...
425 $this->mContent = $revision->getText();
427 $this->mUser = $revision->getUser();
428 $this->mUserText = $revision->getUserText();
429 $this->mComment = $revision->getComment();
430 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
432 $this->mRevIdFetched = $revision->getID();
433 $this->mContentLoaded = true;
435 return $this->mContent;
439 * Gets the article text without using so many damn globals
440 * Returns false on error
442 * @param integer $oldid
444 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
445 return $this->fetchContent( $oldid, $noredir, false );
449 * Read/write accessor to select FOR UPDATE
451 function forUpdate( $x = NULL ) {
452 return wfSetVar( $this->mForUpdate, $x );
456 * Get the database which should be used for reads
458 function &getDB() {
459 #if ( $this->mForUpdate ) {
460 return wfGetDB( DB_MASTER );
461 #} else {
462 # return wfGetDB( DB_SLAVE );
467 * Get options for all SELECT statements
468 * Can pass an option array, to which the class-wide options will be appended
470 function getSelectOptions( $options = '' ) {
471 if ( $this->mForUpdate ) {
472 if ( is_array( $options ) ) {
473 $options[] = 'FOR UPDATE';
474 } else {
475 $options = 'FOR UPDATE';
478 return $options;
482 * Return the Article ID
484 function getID() {
485 if( $this->mTitle ) {
486 return $this->mTitle->getArticleID();
487 } else {
488 return 0;
493 * Get the view count for this article
495 function getCount() {
496 if ( -1 == $this->mCounter ) {
497 $id = $this->getID();
498 $dbr =& $this->getDB();
499 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
500 'Article::getCount', $this->getSelectOptions() );
502 return $this->mCounter;
506 * Would the given text make this article a "good" article (i.e.,
507 * suitable for including in the article count)?
508 * @param string $text Text to analyze
509 * @return integer 1 if it can be counted else 0
511 function isCountable( $text ) {
512 global $wgUseCommaCount;
514 if ( NS_MAIN != $this->mTitle->getNamespace() ) { return 0; }
515 if ( $this->isRedirect( $text ) ) { return 0; }
516 $token = ($wgUseCommaCount ? ',' : '[[' );
517 if ( false === strstr( $text, $token ) ) { return 0; }
518 return 1;
521 /**
522 * Tests if the article text represents a redirect
524 function isRedirect( $text = false ) {
525 if ( $text === false ) {
526 $this->loadContent();
527 $titleObj = Title::newFromRedirect( $this->fetchRevisionText() );
528 } else {
529 $titleObj = Title::newFromRedirect( $text );
531 return $titleObj !== NULL;
535 * Loads everything except the text
536 * This isn't necessary for all uses, so it's only done if needed.
537 * @private
539 function loadLastEdit() {
540 global $wgOut;
542 if ( -1 != $this->mUser )
543 return;
545 # New or non-existent articles have no user information
546 $id = $this->getID();
547 if ( 0 == $id ) return;
549 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
550 if( !is_null( $this->mLastRevision ) ) {
551 $this->mUser = $this->mLastRevision->getUser();
552 $this->mUserText = $this->mLastRevision->getUserText();
553 $this->mTimestamp = $this->mLastRevision->getTimestamp();
554 $this->mComment = $this->mLastRevision->getComment();
555 $this->mMinorEdit = $this->mLastRevision->isMinor();
559 function getTimestamp() {
560 $this->loadLastEdit();
561 return $this->mTimestamp;
564 function getUser() {
565 $this->loadLastEdit();
566 return $this->mUser;
569 function getUserText() {
570 $this->loadLastEdit();
571 return $this->mUserText;
574 function getComment() {
575 $this->loadLastEdit();
576 return $this->mComment;
579 function getMinorEdit() {
580 $this->loadLastEdit();
581 return $this->mMinorEdit;
584 function getRevIdFetched() {
585 $this->loadLastEdit();
586 return $this->mRevIdFetched;
589 function getContributors($limit = 0, $offset = 0) {
590 $fname = 'Article::getContributors';
592 # XXX: this is expensive; cache this info somewhere.
594 $title = $this->mTitle;
595 $contribs = array();
596 $dbr =& $this->getDB();
597 $revTable = $dbr->tableName( 'revision' );
598 $userTable = $dbr->tableName( 'user' );
599 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
600 $ns = $title->getNamespace();
601 $user = $this->getUser();
602 $pageId = $this->getId();
604 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
605 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
606 WHERE rev_page = $pageId
607 AND rev_user != $user
608 GROUP BY rev_user, rev_user_text, user_real_name
609 ORDER BY timestamp DESC";
611 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
612 $sql .= ' '. $this->getSelectOptions();
614 $res = $dbr->query($sql, $fname);
616 while ( $line = $dbr->fetchObject( $res ) ) {
617 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
620 $dbr->freeResult($res);
621 return $contribs;
625 * This is the default action of the script: just view the page of
626 * the given title.
628 function view() {
629 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
630 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
631 global $wgEnotif, $wgParser;
632 $sk = $wgUser->getSkin();
634 $fname = 'Article::view';
635 wfProfileIn( $fname );
636 # Get variables from query string
637 $oldid = $this->getOldID();
638 $diff = $wgRequest->getVal( 'diff' );
639 $rcid = $wgRequest->getVal( 'rcid' );
640 $rdfrom = $wgRequest->getVal( 'rdfrom' );
642 $wgOut->setArticleFlag( true );
643 $wgOut->setRobotpolicy( 'index,follow' );
644 # If we got diff and oldid in the query, we want to see a
645 # diff page instead of the article.
647 if ( !is_null( $diff ) ) {
648 require_once( 'DifferenceEngine.php' );
649 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
651 $de = new DifferenceEngine( $oldid, $diff, $rcid );
652 // DifferenceEngine directly fetched the revision:
653 $this->mRevIdFetched = $de->mNewid;
654 $de->showDiffPage();
656 if( $diff == 0 ) {
657 # Run view updates for current revision only
658 $this->viewUpdates();
660 wfProfileOut( $fname );
661 return;
663 if ( empty( $oldid ) && $this->checkTouched() ) {
664 if( $wgOut->checkLastModified( $this->mTouched ) ){
665 wfProfileOut( $fname );
666 return;
667 } else if ( $this->tryFileCache() ) {
668 # tell wgOut that output is taken care of
669 $wgOut->disable();
670 $this->viewUpdates();
671 wfProfileOut( $fname );
672 return;
675 # Should the parser cache be used?
676 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) && $this->getID() ) {
677 $pcache = true;
678 } else {
679 $pcache = false;
682 $outputDone = false;
683 if ( $pcache ) {
684 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
685 $outputDone = true;
688 if ( !$outputDone ) {
689 $text = $this->getContent( false ); # May change mTitle by following a redirect
691 # Another whitelist check in case oldid or redirects are altering the title
692 if ( !$this->mTitle->userCanRead() ) {
693 $wgOut->loginToUse();
694 $wgOut->output();
695 exit;
699 # We're looking at an old revision
701 if ( !empty( $oldid ) ) {
702 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
703 $wgOut->setRobotpolicy( 'noindex,follow' );
705 if ( '' != $this->mRedirectedFrom ) {
706 $sk = $wgUser->getSkin();
707 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '',
708 'redirect=no' );
709 $s = wfMsg( 'redirectedfrom', $redir );
710 $wgOut->setSubtitle( $s );
712 # Can't cache redirects
713 $pcache = false;
714 } elseif ( !empty( $rdfrom ) ) {
715 global $wgRedirectSources;
716 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
717 $sk = $wgUser->getSkin();
718 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
719 $s = wfMsg( 'redirectedfrom', $redir );
720 $wgOut->setSubtitle( $s );
724 # wrap user css and user js in pre and don't parse
725 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
726 if (
727 $this->mTitle->getNamespace() == NS_USER &&
728 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
730 $wgOut->addWikiText( wfMsg('clearyourcache'));
731 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
732 } else if ( $rt = Title::newFromRedirect( $text ) ) {
733 # Display redirect
734 $imageUrl = $wgStylePath.'/common/images/redirect.png';
735 $targetUrl = $rt->escapeLocalURL();
736 $titleText = htmlspecialchars( $rt->getPrefixedText() );
737 $link = $sk->makeLinkObj( $rt );
739 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
740 '<span class="redirectText">'.$link.'</span>' );
742 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
743 $catlinks = $parseout->getCategoryLinks();
744 $wgOut->addCategoryLinks($catlinks);
745 $skin = $wgUser->getSkin();
746 } else if ( $pcache ) {
747 # Display content and save to parser cache
748 $wgOut->addPrimaryWikiText( $text, $this );
749 } else {
750 # Display content, don't attempt to save to parser cache
751 $wgOut->addWikiText( $text );
754 /* title may have been set from the cache */
755 $t = $wgOut->getPageTitle();
756 if( empty( $t ) ) {
757 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
760 # If we have been passed an &rcid= parameter, we want to give the user a
761 # chance to mark this new article as patrolled.
762 if ( $wgUseRCPatrol
763 && !is_null($rcid)
764 && $rcid != 0
765 && $wgUser->isLoggedIn()
766 && ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
768 $wgOut->addHTML(
769 "<div class='patrollink'>" .
770 wfMsg ( 'markaspatrolledlink',
771 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
773 '</div>'
777 # Put link titles into the link cache
778 $wgOut->transformBuffer();
780 # Add link titles as META keywords
781 $wgOut->addMetaTags() ;
783 $this->viewUpdates();
784 wfProfileOut( $fname );
788 * Insert a new empty page record for this article.
789 * This *must* be followed up by creating a revision
790 * and running $this->updateToLatest( $rev_id );
791 * or else the record will be left in a funky state.
792 * Best if all done inside a transaction.
794 * @param Database $dbw
795 * @param string $restrictions
796 * @return int The newly created page_id key
797 * @access private
799 function insertOn( &$dbw, $restrictions = '' ) {
800 $fname = 'Article::insertOn';
801 wfProfileIn( $fname );
803 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
804 $dbw->insert( 'page', array(
805 'page_id' => $page_id,
806 'page_namespace' => $this->mTitle->getNamespace(),
807 'page_title' => $this->mTitle->getDBkey(),
808 'page_counter' => 0,
809 'page_restrictions' => $restrictions,
810 'page_is_redirect' => 0, # Will set this shortly...
811 'page_is_new' => 1,
812 'page_random' => wfRandom(),
813 'page_touched' => $dbw->timestamp(),
814 'page_latest' => 0, # Fill this in shortly...
815 ), $fname );
816 $newid = $dbw->insertId();
818 $this->mTitle->resetArticleId( $newid );
820 wfProfileOut( $fname );
821 return $newid;
825 * Update the page record to point to a newly saved revision.
827 * @param Database $dbw
828 * @param Revision $revision -- for ID number, and text used to set
829 length and redirect status fields
830 * @param int $lastRevision -- if given, will not overwrite the page field
831 * when different from the currently set value.
832 * Giving 0 indicates the new page flag should
833 * be set on.
834 * @return bool true on success, false on failure
835 * @access private
837 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
838 $fname = 'Article::updateToRevision';
839 wfProfileIn( $fname );
841 $conditions = array( 'page_id' => $this->getId() );
842 if( !is_null( $lastRevision ) ) {
843 # An extra check against threads stepping on each other
844 $conditions['page_latest'] = $lastRevision;
846 $text = $revision->getText();
847 $dbw->update( 'page',
848 array( /* SET */
849 'page_latest' => $revision->getId(),
850 'page_touched' => $dbw->timestamp(),
851 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
852 'page_is_redirect' => Article::isRedirect( $text ),
853 'page_len' => strlen( $text ),
855 $conditions,
856 $fname );
858 wfProfileOut( $fname );
859 return ( $dbw->affectedRows() != 0 );
863 * If the given revision is newer than the currently set page_latest,
864 * update the page record. Otherwise, do nothing.
866 * @param Database $dbw
867 * @param Revision $revision
869 function updateIfNewerOn( &$dbw, $revision ) {
870 $fname = 'Article::updateIfNewerOn';
871 wfProfileIn( $fname );
873 $row = $dbw->selectRow(
874 array( 'revision', 'page' ),
875 array( 'rev_id', 'rev_timestamp' ),
876 array(
877 'page_id' => $this->getId(),
878 'page_latest=rev_id' ),
879 $fname );
880 if( $row ) {
881 if( $row->rev_timestamp >= $revision->getTimestamp() ) {
882 wfProfileOut( $fname );
883 return false;
885 $prev = $row->rev_id;
886 } else {
887 # No or missing previous revision; mark the page as new
888 $prev = 0;
891 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
892 wfProfileOut( $fname );
893 return $ret;
897 * Theoretically we could defer these whole insert and update
898 * functions for after display, but that's taking a big leap
899 * of faith, and we want to be able to report database
900 * errors at some point.
901 * @private
903 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false ) {
904 global $wgOut, $wgUser;
905 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
907 $fname = 'Article::insertNewArticle';
909 $this->mGoodAdjustment = $this->isCountable( $text );
910 $this->mTotalAdjustment = 1;
912 $ns = $this->mTitle->getNamespace();
913 $ttl = $this->mTitle->getDBkey();
914 $text = $this->preSaveTransform( $text );
915 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ? 1 : 0;
916 $now = wfTimestampNow();
918 $dbw =& wfGetDB( DB_MASTER );
920 # Add the page record; stake our claim on this title!
921 $newid = $this->insertOn( $dbw );
923 # Save the revision text...
924 $revision = new Revision( array(
925 'page' => $newid,
926 'comment' => $summary,
927 'minor_edit' => $isminor,
928 'text' => $text
929 ) );
930 $revisionId = $revision->insertOn( $dbw );
932 $this->mTitle->resetArticleID( $newid );
934 # Update the page record with revision data
935 $this->updateRevisionOn( $dbw, $revision, 0 );
937 Article::onArticleCreate( $this->mTitle );
938 if(!$suppressRC) {
939 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary );
942 if ($watchthis) {
943 if(!$this->mTitle->userIsWatching()) $this->watch();
944 } else {
945 if ( $this->mTitle->userIsWatching() ) {
946 $this->unwatch();
950 # The talk page isn't in the regular link tables, so we need to update manually:
951 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
952 $dbw->update( 'page',
953 array( 'page_touched' => $dbw->timestamp($now) ),
954 array( 'page_namespace' => $talkns,
955 'page_title' => $ttl ),
956 $fname );
958 # standard deferred updates
959 $this->editUpdates( $text, $summary, $isminor, $now );
961 $oldid = 0; # new article
962 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
966 * Fetch and uncompress the text for a given revision.
967 * Can ask by rev_id number or timestamp (set $field)
968 * FIXME: This function is broken. Eliminate all uses and remove.
969 * Use Revision class in place.
971 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
972 $fname = 'Article::fetchRevisionText';
973 $dbw =& wfGetDB( DB_MASTER );
974 if( $revId ) {
975 $rev = $dbw->addQuotes( $revId );
976 } else {
977 $rev = 'page_latest';
979 $result = $dbw->query(
980 sprintf( "SELECT old_text, old_flags
981 FROM %s,%s,%s
982 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
983 AND %s=%s",
984 $dbw->tableName( 'page' ),
985 $dbw->tableName( 'revision' ),
986 $dbw->tableName( 'text' ),
987 IntVal( $this->mTitle->getArticleId() ),
988 $field,
989 $rev ),
990 $fname );
991 $obj = $dbw->fetchObject( $result );
992 $dbw->freeResult( $result );
993 $oldtext = Revision::getRevisionText( $obj );
994 return $oldtext;
997 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
998 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
999 if ($section != '') {
1000 if( is_null( $edittime ) ) {
1001 $rev = Revision::newFromTitle( $this->mTitle );
1002 } else {
1003 $dbw =& wfGetDB( DB_MASTER );
1004 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1006 $oldtext = $rev->getText();
1008 if($section=='new') {
1009 if($summary) $subject="== {$summary} ==\n\n";
1010 $text=$oldtext."\n\n".$subject.$text;
1011 } else {
1013 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1014 # comments to be stripped as well)
1015 $striparray=array();
1016 $parser=new Parser();
1017 $parser->mOutputType=OT_WIKI;
1018 $oldtext=$parser->strip($oldtext, $striparray, true);
1020 # now that we can be sure that no pseudo-sections are in the source,
1021 # split it up
1022 # Unfortunately we can't simply do a preg_replace because that might
1023 # replace the wrong section, so we have to use the section counter instead
1024 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1025 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1026 $secs[$section*2]=$text."\n\n"; // replace with edited
1028 # section 0 is top (intro) section
1029 if($section!=0) {
1031 # headline of old section - we need to go through this section
1032 # to determine if there are any subsections that now need to
1033 # be erased, as the mother section has been replaced with
1034 # the text of all subsections.
1035 $headline=$secs[$section*2-1];
1036 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1037 $hlevel=$matches[1];
1039 # determine headline level for wikimarkup headings
1040 if(strpos($hlevel,'=')!==false) {
1041 $hlevel=strlen($hlevel);
1044 $secs[$section*2-1]=''; // erase old headline
1045 $count=$section+1;
1046 $break=false;
1047 while(!empty($secs[$count*2-1]) && !$break) {
1049 $subheadline=$secs[$count*2-1];
1050 preg_match(
1051 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1052 $subhlevel=$matches[1];
1053 if(strpos($subhlevel,'=')!==false) {
1054 $subhlevel=strlen($subhlevel);
1056 if($subhlevel > $hlevel) {
1057 // erase old subsections
1058 $secs[$count*2-1]='';
1059 $secs[$count*2]='';
1061 if($subhlevel <= $hlevel) {
1062 $break=true;
1064 $count++;
1069 $text=join('',$secs);
1070 # reinsert the stuff that we stripped out earlier
1071 $text=$parser->unstrip($text,$striparray);
1072 $text=$parser->unstripNoWiki($text,$striparray);
1076 return $text;
1080 * Change an existing article. Puts the previous version back into the old table, updates RC
1081 * and all necessary caches, mostly via the deferred update array.
1083 * It is possible to call this function from a command-line script, but note that you should
1084 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1086 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1087 global $wgOut, $wgUser;
1088 global $wgDBtransactions, $wgMwRedir;
1089 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
1091 $fname = 'Article::updateArticle';
1092 $good = true;
1094 $isminor = ( $minor && $wgUser->isLoggedIn() );
1095 if ( $this->isRedirect( $text ) ) {
1096 # Remove all content but redirect
1097 # This could be done by reconstructing the redirect from a title given by
1098 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1099 # wants to see
1100 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1101 $redir = 1;
1102 $text = $m[1] . "\n";
1105 else { $redir = 0; }
1107 $text = $this->preSaveTransform( $text );
1108 $dbw =& wfGetDB( DB_MASTER );
1109 $now = wfTimestampNow();
1111 # Update article, but only if changed.
1113 # It's important that we either rollback or complete, otherwise an attacker could
1114 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1115 # could conceivably have the same effect, especially if cur is locked for long periods.
1116 if( !$wgDBtransactions ) {
1117 $userAbort = ignore_user_abort( true );
1120 $oldtext = $this->getContent( true );
1121 $lastRevision = 0;
1123 if ( 0 != strcmp( $text, $oldtext ) ) {
1124 $this->mGoodAdjustment = $this->isCountable( $text )
1125 - $this->isCountable( $oldtext );
1126 $this->mTotalAdjustment = 0;
1127 $now = wfTimestampNow();
1129 $lastRevision = $dbw->selectField(
1130 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1132 $revision = new Revision( array(
1133 'page' => $this->getId(),
1134 'comment' => $summary,
1135 'minor_edit' => $isminor,
1136 'text' => $text
1137 ) );
1138 $revisionId = $revision->insertOn( $dbw );
1140 # Update page
1141 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1143 if( !$ok ) {
1144 /* Belated edit conflict! Run away!! */
1145 $good = false;
1146 } else {
1147 # Update recentchanges and purge cache and whatnot
1148 $bot = (int)($wgUser->isBot() || $forceBot);
1149 RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1150 $lastRevision, $this->getTimestamp(), $bot );
1151 Article::onArticleEdit( $this->mTitle );
1155 if( !$wgDBtransactions ) {
1156 ignore_user_abort( $userAbort );
1159 if ( $good ) {
1160 if ($watchthis) {
1161 if (!$this->mTitle->userIsWatching()) $this->watch();
1162 } else {
1163 if ( $this->mTitle->userIsWatching() ) {
1164 $this->unwatch();
1167 # standard deferred updates
1168 $this->editUpdates( $text, $summary, $minor, $now );
1171 $urls = array();
1172 # Template namespace
1173 # Purge all articles linking here
1174 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
1175 $titles = $this->mTitle->getLinksTo();
1176 Title::touchArray( $titles );
1177 if ( $wgUseSquid ) {
1178 foreach ( $titles as $title ) {
1179 $urls[] = $title->getInternalURL();
1184 # Squid updates
1185 if ( $wgUseSquid ) {
1186 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1187 $u = new SquidUpdate( $urls );
1188 array_push( $wgPostCommitUpdateList, $u );
1191 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1193 return $good;
1197 * After we've either updated or inserted the article, update
1198 * the link tables and redirect to the new page.
1200 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1201 global $wgUseDumbLinkUpdate, $wgAntiLockFlags, $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1202 global $wgUseEnotif;
1204 $wgLinkCache = new LinkCache();
1206 if ( !$wgUseDumbLinkUpdate ) {
1207 # Preload links to reduce lock time
1208 if ( $wgAntiLockFlags & ALF_PRELOAD_LINKS ) {
1209 $wgLinkCache->preFill( $this->mTitle );
1210 $wgLinkCache->clear();
1214 # Parse the text and replace links with placeholders
1215 $wgOut = new OutputPage();
1217 # Pass the current title along in case we're creating a wiki page
1218 # which is different than the currently displayed one (e.g. image
1219 # pages created on file uploads); otherwise, link updates will
1220 # go wrong.
1221 $wgOut->addWikiTextWithTitle( $text, $this->mTitle );
1223 if ( !$wgUseDumbLinkUpdate ) {
1224 # Move the current links back to the second register
1225 $wgLinkCache->swapRegisters();
1227 # Get old version of link table to allow incremental link updates
1228 # Lock this data now since it is needed for an update
1229 $wgLinkCache->forUpdate( true );
1230 $wgLinkCache->preFill( $this->mTitle );
1232 # Swap this old version back into its rightful place
1233 $wgLinkCache->swapRegisters();
1236 if( $this->isRedirect( $text ) )
1237 $r = 'redirect=no';
1238 else
1239 $r = '';
1240 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1242 if ( $wgUseEnotif ) {
1243 # this would be better as an extension hook
1244 include_once( "UserMailer.php" );
1245 $wgEnotif = new EmailNotification ();
1246 $wgEnotif->notifyOnPageChange( $this->mTitle, $now, $summary, $me2, $oldid );
1251 * Mark this particular edit as patrolled
1253 function markpatrolled() {
1254 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1255 $wgOut->setRobotpolicy( 'noindex,follow' );
1257 if ( !$wgUseRCPatrol )
1259 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1260 return;
1262 if ( $wgUser->isAnon() )
1264 $wgOut->loginToUse();
1265 return;
1267 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1269 $wgOut->sysopRequired();
1270 return;
1272 $rcid = $wgRequest->getVal( 'rcid' );
1273 if ( !is_null ( $rcid ) )
1275 RecentChange::markPatrolled( $rcid );
1276 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1277 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1279 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1280 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1282 else
1284 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1289 * Validate function
1291 function validate() {
1292 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1294 if ( !$wgUseValidation ) # Are we using article validation at all?
1296 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1297 return ;
1300 $wgOut->setRobotpolicy( 'noindex,follow' );
1301 $revision = $wgRequest->getVal( 'revision' );
1303 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1305 $v = new Validation ;
1306 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1307 $t = $v->showList ( $this ) ;
1308 else if ( $wgRequest->getVal ( "mode" , "" ) == "details" )
1309 $t = $v->showDetails ( $this , $wgRequest->getVal( 'revision' ) ) ;
1310 else
1311 $t = $v->validatePageForm ( $this , $revision ) ;
1313 $wgOut->addHTML ( $t ) ;
1317 * Add this page to $wgUser's watchlist
1320 function watch() {
1322 global $wgUser, $wgOut;
1324 if ( $wgUser->isAnon() ) {
1325 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1326 return;
1328 if ( wfReadOnly() ) {
1329 $wgOut->readOnlyPage();
1330 return;
1333 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1335 $wgUser->addWatch( $this->mTitle );
1336 $wgUser->saveSettings();
1338 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1340 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1341 $wgOut->setRobotpolicy( 'noindex,follow' );
1343 $link = $this->mTitle->getPrefixedText();
1344 $text = wfMsg( 'addedwatchtext', $link );
1345 $wgOut->addWikiText( $text );
1348 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1352 * Stop watching a page
1355 function unwatch() {
1357 global $wgUser, $wgOut;
1359 if ( $wgUser->isAnon() ) {
1360 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1361 return;
1363 if ( wfReadOnly() ) {
1364 $wgOut->readOnlyPage();
1365 return;
1368 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1370 $wgUser->removeWatch( $this->mTitle );
1371 $wgUser->saveSettings();
1373 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1375 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1376 $wgOut->setRobotpolicy( 'noindex,follow' );
1378 $link = $this->mTitle->getPrefixedText();
1379 $text = wfMsg( 'removedwatchtext', $link );
1380 $wgOut->addWikiText( $text );
1383 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1387 * protect a page
1389 function protect( $limit = 'sysop' ) {
1390 global $wgUser, $wgOut, $wgRequest;
1392 if ( ! $wgUser->isAllowed('protect') ) {
1393 $wgOut->sysopRequired();
1394 return;
1396 if ( wfReadOnly() ) {
1397 $wgOut->readOnlyPage();
1398 return;
1400 $id = $this->mTitle->getArticleID();
1401 if ( 0 == $id ) {
1402 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1403 return;
1406 $confirm = $wgRequest->wasPosted() &&
1407 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1408 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1409 $reason = $wgRequest->getText( 'wpReasonProtect' );
1411 if ( $confirm ) {
1412 $dbw =& wfGetDB( DB_MASTER );
1413 $dbw->update( 'page',
1414 array( /* SET */
1415 'page_touched' => $dbw->timestamp(),
1416 'page_restrictions' => (string)$limit
1417 ), array( /* WHERE */
1418 'page_id' => $id
1419 ), 'Article::protect'
1422 $restrictions = "move=" . $limit;
1423 if( !$moveonly ) {
1424 $restrictions .= ":edit=" . $limit;
1426 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1428 $dbw =& wfGetDB( DB_MASTER );
1429 $dbw->update( 'page',
1430 array( /* SET */
1431 'page_touched' => $dbw->timestamp(),
1432 'page_restrictions' => $restrictions
1433 ), array( /* WHERE */
1434 'page_id' => $id
1435 ), 'Article::protect'
1438 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1440 $log = new LogPage( 'protect' );
1441 if ( $limit === '' ) {
1442 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1443 } else {
1444 $log->addEntry( 'protect', $this->mTitle, $reason );
1446 $wgOut->redirect( $this->mTitle->getFullURL() );
1448 return;
1449 } else {
1450 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1451 return $this->confirmProtect( '', $reason, $limit );
1456 * Output protection confirmation dialog
1458 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1459 global $wgOut, $wgUser;
1461 wfDebug( "Article::confirmProtect\n" );
1463 $sub = $this->mTitle->getPrefixedText();
1464 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1466 $check = '';
1467 $protcom = '';
1468 $moveonly = '';
1470 if ( $limit === '' ) {
1471 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1472 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1473 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1474 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1475 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1476 } else {
1477 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1478 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1479 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1480 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1481 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1482 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1485 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1486 $token = htmlspecialchars( $wgUser->editToken() );
1488 $wgOut->addHTML( "
1489 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1490 <table border='0'>
1491 <tr>
1492 <td align='right'>
1493 <label for='wpReasonProtect'>{$protcom}:</label>
1494 </td>
1495 <td align='left'>
1496 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1497 </td>
1498 </tr>" );
1499 if($moveonly != '') {
1500 $wgOut->AddHTML( "
1501 <tr>
1502 <td align='right'>
1503 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1504 </td>
1505 <td align='left'>
1506 <label for='wpMoveOnly'>{$moveonly}</label>
1507 </td>
1508 </tr> " );
1510 $wgOut->addHTML( "
1511 <tr>
1512 <td>&nbsp;</td>
1513 <td>
1514 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1515 </td>
1516 </tr>
1517 </table>
1518 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1519 </form>" );
1521 $wgOut->returnToMain( false );
1525 * Unprotect the pages
1527 function unprotect() {
1528 return $this->protect( '' );
1532 * UI entry point for page deletion
1534 function delete() {
1535 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1536 $fname = 'Article::delete';
1537 $confirm = $wgRequest->wasPosted() &&
1538 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1539 $reason = $wgRequest->getText( 'wpReason' );
1541 # This code desperately needs to be totally rewritten
1543 # Check permissions
1544 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1545 $wgOut->sysopRequired();
1546 return;
1548 if( wfReadOnly() ) {
1549 $wgOut->readOnlyPage();
1550 return;
1553 # Better double-check that it hasn't been deleted yet!
1554 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1555 if( !$this->mTitle->exists() ) {
1556 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1557 return;
1560 if( $confirm ) {
1561 $this->doDelete( $reason );
1562 return;
1565 # determine whether this page has earlier revisions
1566 # and insert a warning if it does
1567 # we select the text because it might be useful below
1568 $dbr =& $this->getDB();
1569 $ns = $this->mTitle->getNamespace();
1570 $title = $this->mTitle->getDBkey();
1571 $revisions = $dbr->select( array( 'page', 'revision' ),
1572 array( 'rev_id', 'rev_user_text' ),
1573 array(
1574 'page_namespace' => $ns,
1575 'page_title' => $title,
1576 'rev_page = page_id'
1577 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1580 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1581 $skin=$wgUser->getSkin();
1582 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1583 $wgOut->addHTML( $skin->historyLink() .'</b>');
1586 # Fetch cur_text
1587 $rev =& Revision::newFromTitle( $this->mTitle );
1589 # Fetch name(s) of contributors
1590 $rev_name = '';
1591 $all_same_user = true;
1592 while( $row = $dbr->fetchObject( $revisions ) ) {
1593 if( $rev_name != '' && $rev_name != $row->rev_user_text ) {
1594 $all_same_user = false;
1595 } else {
1596 $rev_name = $row->rev_user_text;
1600 if( !is_null( $rev ) ) {
1601 # if this is a mini-text, we can paste part of it into the deletion reason
1602 $text = $rev->getText();
1604 #if this is empty, an earlier revision may contain "useful" text
1605 $blanked = false;
1606 if( $text == '' ) {
1607 $prev = $rev->getPrevious();
1608 if( $prev ) {
1609 $text = $prev->getText();
1610 $blanked = true;
1614 $length = strlen( $text );
1616 # this should not happen, since it is not possible to store an empty, new
1617 # page. Let's insert a standard text in case it does, though
1618 if( $length == 0 && $reason === '' ) {
1619 $reason = wfMsg( 'exblank' );
1622 if( $length < 500 && $reason === '' ) {
1623 # comment field=255, let's grep the first 150 to have some user
1624 # space left
1625 global $wgContLang;
1626 $text = $wgContLang->truncate( $text, 150, '...' );
1628 # let's strip out newlines
1629 $text = preg_replace( "/[\n\r]/", '', $text );
1631 if( !$blanked ) {
1632 if( !$all_same_user ) {
1633 $reason = wfMsg( 'excontent', $text );
1634 } else {
1635 $reason = wfMsg( 'excontentauthor', $text, $rev_name );
1637 } else {
1638 $reason = wfMsg( 'exbeforeblank', $text );
1643 return $this->confirmDelete( '', $reason );
1647 * Output deletion confirmation dialog
1649 function confirmDelete( $par, $reason ) {
1650 global $wgOut, $wgUser;
1652 wfDebug( "Article::confirmDelete\n" );
1654 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1655 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1656 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1657 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1659 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1661 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1662 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1663 $token = htmlspecialchars( $wgUser->editToken() );
1665 $wgOut->addHTML( "
1666 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1667 <table border='0'>
1668 <tr>
1669 <td align='right'>
1670 <label for='wpReason'>{$delcom}:</label>
1671 </td>
1672 <td align='left'>
1673 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1674 </td>
1675 </tr>
1676 <tr>
1677 <td>&nbsp;</td>
1678 <td>
1679 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1680 </td>
1681 </tr>
1682 </table>
1683 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1684 </form>\n" );
1686 $wgOut->returnToMain( false );
1691 * Perform a deletion and output success or failure messages
1693 function doDelete( $reason ) {
1694 global $wgOut, $wgUser, $wgContLang;
1695 $fname = 'Article::doDelete';
1696 wfDebug( $fname."\n" );
1698 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1699 if ( $this->doDeleteArticle( $reason ) ) {
1700 $deleted = $this->mTitle->getPrefixedText();
1702 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1703 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1705 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1706 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1708 $wgOut->addWikiText( $text );
1709 $wgOut->returnToMain( false );
1710 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1711 } else {
1712 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1718 * Back-end article deletion
1719 * Deletes the article with database consistency, writes logs, purges caches
1720 * Returns success
1722 function doDeleteArticle( $reason ) {
1723 global $wgUser;
1724 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1726 $fname = 'Article::doDeleteArticle';
1727 wfDebug( $fname."\n" );
1729 $dbw =& wfGetDB( DB_MASTER );
1730 $ns = $this->mTitle->getNamespace();
1731 $t = $this->mTitle->getDBkey();
1732 $id = $this->mTitle->getArticleID();
1734 if ( $t == '' || $id == 0 ) {
1735 return false;
1738 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1739 array_push( $wgDeferredUpdateList, $u );
1741 $linksTo = $this->mTitle->getLinksTo();
1743 # Squid purging
1744 if ( $wgUseSquid ) {
1745 $urls = array(
1746 $this->mTitle->getInternalURL(),
1747 $this->mTitle->getInternalURL( 'history' )
1750 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1751 array_push( $wgPostCommitUpdateList, $u );
1755 # Client and file cache invalidation
1756 Title::touchArray( $linksTo );
1759 // For now, shunt the revision data into the archive table.
1760 // Text is *not* removed from the text table; bulk storage
1761 // is left intact to avoid breaking block-compression or
1762 // immutable storage schemes.
1764 // For backwards compatibility, note that some older archive
1765 // table entries will have ar_text and ar_flags fields still.
1767 // In the future, we may keep revisions and mark them with
1768 // the rev_deleted field, which is reserved for this purpose.
1769 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1770 array(
1771 'ar_namespace' => 'page_namespace',
1772 'ar_title' => 'page_title',
1773 'ar_comment' => 'rev_comment',
1774 'ar_user' => 'rev_user',
1775 'ar_user_text' => 'rev_user_text',
1776 'ar_timestamp' => 'rev_timestamp',
1777 'ar_minor_edit' => 'rev_minor_edit',
1778 'ar_rev_id' => 'rev_id',
1779 'ar_text_id' => 'rev_text_id',
1780 ), array(
1781 'page_id' => $id,
1782 'page_id = rev_page'
1783 ), $fname
1786 # Now that it's safely backed up, delete it
1787 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1788 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1790 # Clean up recentchanges entries...
1791 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1793 # Finally, clean up the link tables
1794 $t = $this->mTitle->getPrefixedDBkey();
1796 Article::onArticleDelete( $this->mTitle );
1798 # Delete outgoing links
1799 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1800 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1801 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1803 # Log the deletion
1804 $log = new LogPage( 'delete' );
1805 $log->addEntry( 'delete', $this->mTitle, $reason );
1807 # Clear the cached article id so the interface doesn't act like we exist
1808 $this->mTitle->resetArticleID( 0 );
1809 $this->mTitle->mArticleID = 0;
1810 return true;
1814 * Revert a modification
1816 function rollback() {
1817 global $wgUser, $wgOut, $wgRequest;
1818 $fname = 'Article::rollback';
1820 if ( ! $wgUser->isAllowed('rollback') ) {
1821 $wgOut->sysopRequired();
1822 return;
1824 if ( wfReadOnly() ) {
1825 $wgOut->readOnlyPage( $this->getContent( true ) );
1826 return;
1828 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1829 array( $this->mTitle->getPrefixedText(),
1830 $wgRequest->getVal( 'from' ) ) ) ) {
1831 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1832 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1833 return;
1835 $dbw =& wfGetDB( DB_MASTER );
1837 # Enhanced rollback, marks edits rc_bot=1
1838 $bot = $wgRequest->getBool( 'bot' );
1840 # Replace all this user's current edits with the next one down
1841 $tt = $this->mTitle->getDBKey();
1842 $n = $this->mTitle->getNamespace();
1844 # Get the last editor, lock table exclusively
1845 $dbw->begin();
1846 $current = Revision::newFromTitle( $this->mTitle );
1847 if( is_null( $current ) ) {
1848 # Something wrong... no page?
1849 $dbw->rollback();
1850 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1851 return;
1854 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1855 if( $from != $current->getUserText() ) {
1856 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1857 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1858 htmlspecialchars( $this->mTitle->getPrefixedText()),
1859 htmlspecialchars( $from ),
1860 htmlspecialchars( $current->getUserText() ) ) );
1861 if( $current->getComment() != '') {
1862 $wgOut->addHTML(
1863 wfMsg( 'editcomment',
1864 htmlspecialchars( $current->getComment() ) ) );
1866 return;
1869 # Get the last edit not by this guy
1870 $user = IntVal( $current->getUser() );
1871 $user_text = $dbw->addQuotes( $current->getUserText() );
1872 $s = $dbw->selectRow( 'revision',
1873 array( 'rev_id', 'rev_timestamp' ),
1874 array(
1875 'rev_page' => $current->getPage(),
1876 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1877 ), $fname,
1878 array(
1879 'USE INDEX' => 'page_timestamp',
1880 'ORDER BY' => 'rev_timestamp DESC' )
1882 if( $s === false ) {
1883 # Something wrong
1884 $dbw->rollback();
1885 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1886 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1887 return;
1890 if ( $bot ) {
1891 # Mark all reverted edits as bot
1892 $dbw->update( 'recentchanges',
1893 array( /* SET */
1894 'rc_bot' => 1
1895 ), array( /* WHERE */
1896 'rc_cur_id' => $current->getPage(),
1897 'rc_user_text' => $current->getUserText(),
1898 "rc_timestamp > '{$s->rev_timestamp}'",
1899 ), $fname
1903 # Save it!
1904 $target = Revision::newFromId( $s->rev_id );
1905 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1907 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1908 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1909 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1911 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1912 Article::onArticleEdit( $this->mTitle );
1914 $dbw->commit();
1915 $wgOut->returnToMain( false );
1920 * Do standard deferred updates after page view
1921 * @private
1923 function viewUpdates() {
1924 global $wgDeferredUpdateList, $wgUseEnotif;
1926 if ( 0 != $this->getID() ) {
1927 global $wgDisableCounters;
1928 if( !$wgDisableCounters ) {
1929 Article::incViewCount( $this->getID() );
1930 $u = new SiteStatsUpdate( 1, 0, 0 );
1931 array_push( $wgDeferredUpdateList, $u );
1935 # Update newtalk status if user is reading their own
1936 # talk page
1938 global $wgUser;
1939 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
1940 $this->mTitle->getText() == $wgUser->getName())
1942 if ( $wgUseEnotif ) {
1943 require_once( 'UserTalkUpdate.php' );
1944 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(), $this->mTitle->getDBkey(), false, false, false );
1945 } else {
1946 $wgUser->setNewtalk(0);
1947 $wgUser->saveNewtalk();
1949 } elseif ( $wgUseEnotif ) {
1950 $wgUser->clearNotification( $this->mTitle );
1956 * Do standard deferred updates after page edit.
1957 * Every 1000th edit, prune the recent changes table.
1958 * @private
1959 * @param string $text
1961 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1962 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1963 global $wgMessageCache, $wgUser, $wgUseEnotif;
1965 wfSeedRandom();
1966 if ( 0 == mt_rand( 0, 999 ) ) {
1967 # Periodically flush old entries from the recentchanges table.
1968 global $wgRCMaxAge;
1969 $dbw =& wfGetDB( DB_MASTER );
1970 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1971 $recentchanges = $dbw->tableName( 'recentchanges' );
1972 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1973 $dbw->query( $sql );
1975 $id = $this->getID();
1976 $title = $this->mTitle->getPrefixedDBkey();
1977 $shortTitle = $this->mTitle->getDBkey();
1979 if ( 0 != $id ) {
1980 $u = new LinksUpdate( $id, $title );
1981 array_push( $wgDeferredUpdateList, $u );
1982 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
1983 array_push( $wgDeferredUpdateList, $u );
1984 $u = new SearchUpdate( $id, $title, $text );
1985 array_push( $wgDeferredUpdateList, $u );
1987 # If this is another user's talk page, update newtalk
1989 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
1990 if ( $wgUseEnotif ) {
1991 require_once( 'UserTalkUpdate.php' );
1992 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle, $summary,
1993 $minoredit, $timestamp_of_pagechange);
1994 } else {
1995 $other = User::newFromName($shortTitle);
1996 $other->setNewtalk(1);
1997 $other->saveNewtalk();
2001 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2002 $wgMessageCache->replace( $shortTitle, $text );
2008 * @todo document this function
2009 * @private
2010 * @param string $oldid Revision ID of this article revision
2012 function setOldSubtitle( $oldid=0 ) {
2013 global $wgLang, $wgOut, $wgUser;
2015 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2016 $sk = $wgUser->getSkin();
2017 $lnk = $sk->makeKnownLinkObj ( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2018 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2019 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2020 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2021 $wgOut->setSubtitle( $r );
2025 * This function is called right before saving the wikitext,
2026 * so we can do things like signatures and links-in-context.
2028 * @param string $text
2030 function preSaveTransform( $text ) {
2031 global $wgParser, $wgUser;
2032 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2035 /* Caching functions */
2038 * checkLastModified returns true if it has taken care of all
2039 * output to the client that is necessary for this request.
2040 * (that is, it has sent a cached version of the page)
2042 function tryFileCache() {
2043 static $called = false;
2044 if( $called ) {
2045 wfDebug( " tryFileCache() -- called twice!?\n" );
2046 return;
2048 $called = true;
2049 if($this->isFileCacheable()) {
2050 $touched = $this->mTouched;
2051 $cache = new CacheManager( $this->mTitle );
2052 if($cache->isFileCacheGood( $touched )) {
2053 global $wgOut;
2054 wfDebug( " tryFileCache() - about to load\n" );
2055 $cache->loadFromFileCache();
2056 return true;
2057 } else {
2058 wfDebug( " tryFileCache() - starting buffer\n" );
2059 ob_start( array(&$cache, 'saveToFileCache' ) );
2061 } else {
2062 wfDebug( " tryFileCache() - not cacheable\n" );
2067 * Check if the page can be cached
2068 * @return bool
2070 function isFileCacheable() {
2071 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2072 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2074 return $wgUseFileCache
2075 and (!$wgShowIPinHeader)
2076 and ($this->getID() != 0)
2077 and ($wgUser->isAnon())
2078 and (!$wgUser->getNewtalk())
2079 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2080 and (empty( $action ) || $action == 'view')
2081 and (!isset($oldid))
2082 and (!isset($diff))
2083 and (!isset($redirect))
2084 and (!isset($printable))
2085 and (!$this->mRedirectedFrom);
2089 * Loads cur_touched and returns a value indicating if it should be used
2092 function checkTouched() {
2093 $fname = 'Article::checkTouched';
2094 if( !$this->mDataLoaded ) {
2095 $dbr =& $this->getDB();
2096 $data = $this->pageDataFromId( $dbr, $this->getId() );
2097 if( $data ) {
2098 $this->loadPageData( $data );
2101 return !$this->mIsRedirect;
2105 * Edit an article without doing all that other stuff
2106 * The article must already exist; link tables etc
2107 * are not updated, caches are not flushed.
2109 * @param string $text text submitted
2110 * @param string $comment comment submitted
2111 * @param bool $minor whereas it's a minor modification
2113 function quickEdit( $text, $comment = '', $minor = 0 ) {
2114 $fname = 'Article::quickEdit';
2115 wfProfileIn( $fname );
2117 $dbw =& wfGetDB( DB_MASTER );
2118 $dbw->begin();
2119 $revision = new Revision( array(
2120 'page' => $this->getId(),
2121 'text' => $text,
2122 'comment' => $comment,
2123 'minor_edit' => $minor ? 1 : 0,
2124 ) );
2125 $revisionId = $revision->insertOn( $dbw );
2126 $this->updateRevisionOn( $dbw, $revision );
2127 $dbw->commit();
2129 wfProfileOut( $fname );
2133 * Used to increment the view counter
2135 * @static
2136 * @param integer $id article id
2138 function incViewCount( $id ) {
2139 $id = intval( $id );
2140 global $wgHitcounterUpdateFreq;
2142 $dbw =& wfGetDB( DB_MASTER );
2143 $pageTable = $dbw->tableName( 'page' );
2144 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2145 $acchitsTable = $dbw->tableName( 'acchits' );
2147 if( $wgHitcounterUpdateFreq <= 1 ){ //
2148 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2149 return;
2152 # Not important enough to warrant an error page in case of failure
2153 $oldignore = $dbw->ignoreErrors( true );
2155 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2157 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2158 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2159 # Most of the time (or on SQL errors), skip row count check
2160 $dbw->ignoreErrors( $oldignore );
2161 return;
2164 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2165 $row = $dbw->fetchObject( $res );
2166 $rown = intval( $row->n );
2167 if( $rown >= $wgHitcounterUpdateFreq ){
2168 wfProfileIn( 'Article::incViewCount-collect' );
2169 $old_user_abort = ignore_user_abort( true );
2171 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2172 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2173 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2174 'GROUP BY hc_id');
2175 $dbw->query("DELETE FROM $hitcounterTable");
2176 $dbw->query('UNLOCK TABLES');
2177 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2178 'WHERE page_id = hc_id');
2179 $dbw->query("DROP TABLE $acchitsTable");
2181 ignore_user_abort( $old_user_abort );
2182 wfProfileOut( 'Article::incViewCount-collect' );
2184 $dbw->ignoreErrors( $oldignore );
2187 /**#@+
2188 * The onArticle*() functions are supposed to be a kind of hooks
2189 * which should be called whenever any of the specified actions
2190 * are done.
2192 * This is a good place to put code to clear caches, for instance.
2194 * This is called on page move and undelete, as well as edit
2195 * @static
2196 * @param $title_obj a title object
2199 function onArticleCreate($title_obj) {
2200 global $wgUseSquid, $wgPostCommitUpdateList;
2202 $title_obj->touchLinks();
2203 $titles = $title_obj->getLinksTo();
2205 # Purge squid
2206 if ( $wgUseSquid ) {
2207 $urls = $title_obj->getSquidURLs();
2208 foreach ( $titles as $linkTitle ) {
2209 $urls[] = $linkTitle->getInternalURL();
2211 $u = new SquidUpdate( $urls );
2212 array_push( $wgPostCommitUpdateList, $u );
2216 function onArticleDelete($title_obj) {
2217 $title_obj->touchLinks();
2220 function onArticleEdit($title_obj) {
2221 // This would be an appropriate place to purge caches.
2222 // Why's this not in here now?
2225 /**#@-*/
2228 * Info about this page
2229 * Called for ?action=info when $wgAllowPageInfo is on.
2231 * @access public
2233 function info() {
2234 global $wgLang, $wgOut, $wgAllowPageInfo;
2235 $fname = 'Article::info';
2237 if ( !$wgAllowPageInfo ) {
2238 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2239 return;
2242 $page = $this->mTitle->getSubjectPage();
2244 $wgOut->setPagetitle( $page->getPrefixedText() );
2245 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2247 # first, see if the page exists at all.
2248 $exists = $page->getArticleId() != 0;
2249 if( !$exists ) {
2250 $wgOut->addHTML( wfMsg('noarticletext') );
2251 } else {
2252 $dbr =& $this->getDB( DB_SLAVE );
2253 $wl_clause = array(
2254 'wl_title' => $page->getDBkey(),
2255 'wl_namespace' => $page->getNamespace() );
2256 $numwatchers = $dbr->selectField(
2257 'watchlist',
2258 'COUNT(*)',
2259 $wl_clause,
2260 $fname,
2261 $this->getSelectOptions() );
2263 $pageInfo = $this->pageCountInfo( $page );
2264 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2266 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2267 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2268 if( $talkInfo ) {
2269 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2271 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2272 if( $talkInfo ) {
2273 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2275 $wgOut->addHTML( '</ul>' );
2281 * Return the total number of edits and number of unique editors
2282 * on a given page. If page does not exist, returns false.
2284 * @param Title $title
2285 * @return array
2286 * @access private
2288 function pageCountInfo( $title ) {
2289 $id = $title->getArticleId();
2290 if( $id == 0 ) {
2291 return false;
2294 $dbr =& $this->getDB( DB_SLAVE );
2296 $rev_clause = array( 'rev_page' => $id );
2297 $fname = 'Article::pageCountInfo';
2299 $edits = $dbr->selectField(
2300 'revision',
2301 'COUNT(rev_page)',
2302 $rev_clause,
2303 $fname,
2304 $this->getSelectOptions() );
2306 $authors = $dbr->selectField(
2307 'revision',
2308 'COUNT(DISTINCT rev_user_text)',
2309 $rev_clause,
2310 $fname,
2311 $this->getSelectOptions() );
2313 return array( 'edits' => $edits, 'authors' => $authors );
2317 * Return a list of templates used by this article.
2318 * Uses the links table to find the templates
2320 * @return array
2322 function getUsedTemplates() {
2323 $result = array();
2324 $id = $this->mTitle->getArticleID();
2326 $db =& wfGetDB( DB_SLAVE );
2327 $res = $db->select( array( 'pagelinks' ),
2328 array( 'pl_title' ),
2329 array(
2330 'pl_from' => $id,
2331 'pl_namespace' => NS_TEMPLATE ),
2332 'Article:getUsedTemplates' );
2333 if ( false !== $res ) {
2334 if ( $db->numRows( $res ) ) {
2335 while ( $row = $db->fetchObject( $res ) ) {
2336 $result[] = $row->pl_title;
2340 $db->freeResult( $res );
2341 return $result;