8 * Need the CacheManager to be loaded
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
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.
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mGoodAdjustment, $mTotalAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
44 * Constructor and clear the article
45 * @param Title &$title
46 * @param integer $oldId Revision ID, null to fetch from request, zero for current
48 function Article( &$title, $oldId = null ) {
49 $this->mTitle
=& $title;
50 $this->mOldId
= $oldId;
55 * Tell the page view functions that this view was redirected
56 * from another page on the wiki.
59 function setRedirectedFrom( $from ) {
60 $this->mRedirectedFrom
= $from;
64 * @return mixed false, Title of in-wiki target, or string with URL
66 function followRedirect() {
67 $text = $this->getContent();
68 $rt = Title
::newFromRedirect( $text );
70 # process if title object is valid and not special:userlogout
72 if( $rt->getInterwiki() != '' ) {
73 if( $rt->isLocal() ) {
74 // Offsite wikis need an HTTP redirect.
76 // This can be hard to reverse and may produce loops,
77 // so they may be disabled in the site configuration.
79 $source = $this->mTitle
->getFullURL( 'redirect=no' );
80 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
83 if( $rt->getNamespace() == NS_SPECIAL
) {
84 // Gotta hand redirects to special pages differently:
85 // Fill the HTTP response "Location" header and ignore
86 // the rest of the page we're on.
88 // This can be hard to reverse, so they may be disabled.
90 if( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) {
93 return $rt->getFullURL();
100 // No or invalid redirect
105 * get the title object of the article
107 function getTitle() {
108 return $this->mTitle
;
116 $this->mDataLoaded
= false;
117 $this->mContentLoaded
= false;
119 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
120 $this->mRedirectedFrom
= null; # Title object if set
122 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
123 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
124 $this->mTouched
= '19700101000000';
125 $this->mForUpdate
= false;
126 $this->mIsRedirect
= false;
127 $this->mRevIdFetched
= 0;
128 $this->mRedirectUrl
= false;
129 $this->mLatest
= false;
133 * Note that getContent/loadContent do not follow redirects anymore.
134 * If you need to fetch redirectable content easily, try
135 * the shortcut in Article::followContent()
137 * @fixme There are still side-effects in this!
138 * In general, you should use the Revision class, not Article,
139 * to fetch text for purposes other than page views.
141 * @return Return the text of this revision
143 function getContent() {
144 global $wgRequest, $wgUser, $wgOut;
146 # Get variables from query string :P
147 $action = $wgRequest->getText( 'action', 'view' );
148 $section = $wgRequest->getText( 'section' );
149 $preload = $wgRequest->getText( 'preload' );
151 $fname = 'Article::getContent';
152 wfProfileIn( $fname );
154 if ( 0 == $this->getID() ) {
155 if ( 'edit' == $action ) {
156 wfProfileOut( $fname );
158 # If requested, preload some text.
159 $text=$this->getPreloadedText($preload);
161 # We used to put MediaWiki:Newarticletext here if
162 # $text was empty at this point.
163 # This is now shown above the edit box instead.
166 wfProfileOut( $fname );
167 $wgOut->setRobotpolicy( 'noindex,nofollow' );
169 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
170 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
172 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
175 return "<div class='noarticletext'>$ret</div>";
177 $this->loadContent();
178 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
179 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
180 $wgUser->isIP($this->mTitle
->getText()) &&
183 wfProfileOut( $fname );
184 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
186 if($action=='edit') {
188 if($section=='new') {
189 wfProfileOut( $fname );
190 $text=$this->getPreloadedText($preload);
194 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
195 # comments to be stripped as well)
196 $rv=$this->getSection($this->mContent
,$section);
197 wfProfileOut( $fname );
201 wfProfileOut( $fname );
202 return $this->mContent
;
208 * Get the contents of a page from its title and remove includeonly tags
210 * @param string The title of the page
211 * @return string The contents of the page
213 function getPreloadedText($preload) {
214 if ( $preload === '' )
217 $preloadTitle = Title
::newFromText( $preload );
218 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
219 $rev=Revision
::newFromTitle($preloadTitle);
220 if ( is_object( $rev ) ) {
221 $text = $rev->getText();
222 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
223 // its own mini-parser! -ævar
224 $text = preg_replace( '~</?includeonly>~', '', $text );
233 * This function returns the text of a section, specified by a number ($section).
234 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
235 * the first section before any such heading (section 0).
237 * If a section contains subsections, these are also returned.
239 * @param string $text text to look in
240 * @param integer $section section number
241 * @return string text of the requested section
243 function getSection($text,$section) {
245 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
246 # comments to be stripped as well)
248 $parser=new Parser();
249 $parser->mOutputType
=OT_WIKI
;
250 $parser->mOptions
= new ParserOptions();
251 $striptext=$parser->strip($text, $striparray, true);
253 # now that we can be sure that no pseudo-sections are in the source,
254 # split it up by section
257 '/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
259 PREG_SPLIT_DELIM_CAPTURE
);
263 $headline=$secs[$section*2-1];
264 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
267 # translate wiki heading into level
268 if(strpos($hlevel,'=')!==false) {
269 $hlevel=strlen($hlevel);
272 $rv=$headline. $secs[$section*2];
276 while(!empty($secs[$count*2-1]) && !$break) {
278 $subheadline=$secs[$count*2-1];
279 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
280 $subhlevel=$matches[1];
281 if(strpos($subhlevel,'=')!==false) {
282 $subhlevel=strlen($subhlevel);
284 if($subhlevel > $hlevel) {
285 $rv.=$subheadline.$secs[$count*2];
287 if($subhlevel <= $hlevel) {
294 # reinsert stripped tags
295 $rv=$parser->unstrip($rv,$striparray);
296 $rv=$parser->unstripNoWiki($rv,$striparray);
303 * @return int The oldid of the article that is to be shown, 0 for the
306 function getOldID() {
307 if ( is_null( $this->mOldId
) ) {
308 $this->mOldId
= $this->getOldIDFromRequest();
310 return $this->mOldId
;
314 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
316 * @return int The old id for the request
318 function getOldIDFromRequest() {
320 $this->mRedirectUrl
= false;
321 $oldid = $wgRequest->getVal( 'oldid' );
322 if ( isset( $oldid ) ) {
323 $oldid = intval( $oldid );
324 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
325 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
329 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
331 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
332 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
348 * Load the revision (including text) into this object
350 function loadContent() {
351 if ( $this->mContentLoaded
) return;
354 $oldid = $this->getOldID();
356 $fname = 'Article::loadContent';
358 # Pre-fill content with error message so that if something
359 # fails we'll have something telling us what we intended.
361 $t = $this->mTitle
->getPrefixedText();
363 $this->mOldId
= $oldid;
364 $this->fetchContent( $oldid );
369 * Fetch a page record with the given conditions
370 * @param Database $dbr
371 * @param array $conditions
374 function pageData( &$dbr, $conditions ) {
387 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
388 $row = $dbr->selectRow( 'page',
391 'Article::pageData' );
392 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
397 * @param Database $dbr
398 * @param Title $title
400 function pageDataFromTitle( &$dbr, $title ) {
401 return $this->pageData( $dbr, array(
402 'page_namespace' => $title->getNamespace(),
403 'page_title' => $title->getDBkey() ) );
407 * @param Database $dbr
410 function pageDataFromId( &$dbr, $id ) {
411 return $this->pageData( $dbr, array( 'page_id' => $id ) );
415 * Set the general counter, title etc data loaded from
418 * @param object $data
421 function loadPageData( $data = 'fromdb' ) {
422 if ( $data === 'fromdb' ) {
423 $dbr =& $this->getDB();
424 $data = $this->pageDataFromId( $dbr, $this->getId() );
427 $lc =& LinkCache
::singleton();
429 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
431 $this->mTitle
->mArticleID
= $data->page_id
;
432 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
433 $this->mTitle
->mRestrictionsLoaded
= true;
435 $this->mCounter
= $data->page_counter
;
436 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
437 $this->mIsRedirect
= $data->page_is_redirect
;
438 $this->mLatest
= $data->page_latest
;
440 $lc->addBadLinkObj( $this->mTitle
);
441 $this->mTitle
->mArticleID
= 0;
444 $this->mDataLoaded
= true;
448 * Get text of an article from database
449 * Does *NOT* follow redirects.
450 * @param int $oldid 0 for whatever the latest revision is
453 function fetchContent( $oldid = 0 ) {
454 if ( $this->mContentLoaded
) {
455 return $this->mContent
;
458 $dbr =& $this->getDB();
459 $fname = 'Article::fetchContent';
461 # Pre-fill content with error message so that if something
462 # fails we'll have something telling us what we intended.
463 $t = $this->mTitle
->getPrefixedText();
465 $t .= ',oldid='.$oldid;
467 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
470 $revision = Revision
::newFromId( $oldid );
471 if( is_null( $revision ) ) {
472 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
475 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
477 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
480 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
481 $this->loadPageData( $data );
483 if( !$this->mDataLoaded
) {
484 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
486 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
489 $this->loadPageData( $data );
491 $revision = Revision
::newFromId( $this->mLatest
);
492 if( is_null( $revision ) ) {
493 wfDebug( "$fname failed to retrieve current page, rev_id {$data->page_latest}\n" );
498 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
499 // We should instead work with the Revision object when we need it...
500 $this->mContent
= $revision->userCan( MW_REV_DELETED_TEXT
) ?
$revision->getRawText() : "";
501 //$this->mContent = $revision->getText();
503 $this->mUser
= $revision->getUser();
504 $this->mUserText
= $revision->getUserText();
505 $this->mComment
= $revision->getComment();
506 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
508 $this->mRevIdFetched
= $revision->getID();
509 $this->mContentLoaded
= true;
510 $this->mRevision
=& $revision;
512 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
514 return $this->mContent
;
518 * Read/write accessor to select FOR UPDATE
522 function forUpdate( $x = NULL ) {
523 return wfSetVar( $this->mForUpdate
, $x );
527 * Get the database which should be used for reads
532 $ret =& wfGetDB( DB_MASTER
);
537 * Get options for all SELECT statements
539 * @param array $options an optional options array which'll be appended to
541 * @return array Options
543 function getSelectOptions( $options = '' ) {
544 if ( $this->mForUpdate
) {
545 if ( is_array( $options ) ) {
546 $options[] = 'FOR UPDATE';
548 $options = 'FOR UPDATE';
555 * @return int Page ID
558 if( $this->mTitle
) {
559 return $this->mTitle
->getArticleID();
566 * @return bool Whether or not the page exists in the database
569 return $this->getId() != 0;
573 * @return int The view count for the page
575 function getCount() {
576 if ( -1 == $this->mCounter
) {
577 $id = $this->getID();
581 $dbr =& wfGetDB( DB_SLAVE
);
582 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
583 'Article::getCount', $this->getSelectOptions() );
586 return $this->mCounter
;
590 * Determine whether a page would be suitable for being counted as an
591 * article in the site_stats table based on the title & its content
593 * @param string $text Text to analyze
596 function isCountable( $text ) {
597 global $wgUseCommaCount;
599 $token = $wgUseCommaCount ?
',' : '[[';
601 $this->mTitle
->getNamespace() == NS_MAIN
602 && ! $this->isRedirect( $text )
603 && in_string( $token, $text );
607 * Tests if the article text represents a redirect
609 * @param string $text
612 function isRedirect( $text = false ) {
613 if ( $text === false ) {
614 $this->loadContent();
615 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
617 $titleObj = Title
::newFromRedirect( $text );
619 return $titleObj !== NULL;
623 * Returns true if the currently-referenced revision is the current edit
624 * to this page (and it exists).
627 function isCurrent() {
628 return $this->exists() &&
629 isset( $this->mRevision
) &&
630 $this->mRevision
->isCurrent();
634 * Loads everything except the text
635 * This isn't necessary for all uses, so it's only done if needed.
638 function loadLastEdit() {
639 if ( -1 != $this->mUser
)
642 # New or non-existent articles have no user information
643 $id = $this->getID();
644 if ( 0 == $id ) return;
646 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
647 if( !is_null( $this->mLastRevision
) ) {
648 $this->mUser
= $this->mLastRevision
->getUser();
649 $this->mUserText
= $this->mLastRevision
->getUserText();
650 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
651 $this->mComment
= $this->mLastRevision
->getComment();
652 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
653 $this->mRevIdFetched
= $this->mLastRevision
->getID();
657 function getTimestamp() {
658 // Check if the field has been filled by ParserCache::get()
659 if ( !$this->mTimestamp
) {
660 $this->loadLastEdit();
662 return wfTimestamp(TS_MW
, $this->mTimestamp
);
666 $this->loadLastEdit();
670 function getUserText() {
671 $this->loadLastEdit();
672 return $this->mUserText
;
675 function getComment() {
676 $this->loadLastEdit();
677 return $this->mComment
;
680 function getMinorEdit() {
681 $this->loadLastEdit();
682 return $this->mMinorEdit
;
685 function getRevIdFetched() {
686 $this->loadLastEdit();
687 return $this->mRevIdFetched
;
690 function getContributors($limit = 0, $offset = 0) {
691 $fname = 'Article::getContributors';
693 # XXX: this is expensive; cache this info somewhere.
695 $title = $this->mTitle
;
697 $dbr =& wfGetDB( DB_SLAVE
);
698 $revTable = $dbr->tableName( 'revision' );
699 $userTable = $dbr->tableName( 'user' );
700 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
701 $ns = $title->getNamespace();
702 $user = $this->getUser();
703 $pageId = $this->getId();
705 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
706 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
707 WHERE rev_page = $pageId
708 AND rev_user != $user
709 GROUP BY rev_user, rev_user_text, user_real_name
710 ORDER BY timestamp DESC";
712 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
713 $sql .= ' '. $this->getSelectOptions();
715 $res = $dbr->query($sql, $fname);
717 while ( $line = $dbr->fetchObject( $res ) ) {
718 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
721 $dbr->freeResult($res);
726 * This is the default action of the script: just view the page of
730 global $wgUser, $wgOut, $wgRequest, $wgContLang;
731 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
732 global $wgUseTrackbacks;
733 $sk = $wgUser->getSkin();
735 $fname = 'Article::view';
736 wfProfileIn( $fname );
737 $parserCache =& ParserCache
::singleton();
738 # Get variables from query string
739 $oldid = $this->getOldID();
741 # getOldID may want us to redirect somewhere else
742 if ( $this->mRedirectUrl
) {
743 $wgOut->redirect( $this->mRedirectUrl
);
744 wfProfileOut( $fname );
748 $diff = $wgRequest->getVal( 'diff' );
749 $rcid = $wgRequest->getVal( 'rcid' );
750 $rdfrom = $wgRequest->getVal( 'rdfrom' );
752 $wgOut->setArticleFlag( true );
753 $wgOut->setRobotpolicy( 'index,follow' );
754 # If we got diff and oldid in the query, we want to see a
755 # diff page instead of the article.
757 if ( !is_null( $diff ) ) {
758 require_once( 'DifferenceEngine.php' );
759 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
761 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
762 // DifferenceEngine directly fetched the revision:
763 $this->mRevIdFetched
= $de->mNewid
;
767 # Run view updates for current revision only
768 $this->viewUpdates();
770 wfProfileOut( $fname );
774 if ( empty( $oldid ) && $this->checkTouched() ) {
775 $wgOut->setETag($parserCache->getETag($this, $wgUser));
777 if( $wgOut->checkLastModified( $this->mTouched
) ){
778 wfProfileOut( $fname );
780 } else if ( $this->tryFileCache() ) {
781 # tell wgOut that output is taken care of
783 $this->viewUpdates();
784 wfProfileOut( $fname );
788 # Should the parser cache be used?
789 $pcache = $wgEnableParserCache &&
790 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
793 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
794 if ( $wgUser->getOption( 'stubthreshold' ) ) {
795 wfIncrStats( 'pcache_miss_stub' );
798 $wasRedirected = false;
799 if ( isset( $this->mRedirectedFrom
) ) {
800 // This is an internally redirected page view.
801 // We'll need a backlink to the source page for navigation.
802 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
803 $sk = $wgUser->getSkin();
804 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
805 $s = wfMsg( 'redirectedfrom', $redir );
806 $wgOut->setSubtitle( $s );
807 $wasRedirected = true;
809 } elseif ( !empty( $rdfrom ) ) {
810 // This is an externally redirected view, from some other wiki.
811 // If it was reported from a trusted site, supply a backlink.
812 global $wgRedirectSources;
813 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
814 $sk = $wgUser->getSkin();
815 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
816 $s = wfMsg( 'redirectedfrom', $redir );
817 $wgOut->setSubtitle( $s );
818 $wasRedirected = true;
824 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
828 if ( !$outputDone ) {
829 $text = $this->getContent();
830 if ( $text === false ) {
831 # Failed to load, replace text with error message
832 $t = $this->mTitle
->getPrefixedText();
834 $t .= ',oldid='.$oldid;
835 $text = wfMsg( 'missingarticle', $t );
837 $text = wfMsg( 'noarticletext', $t );
841 # Another whitelist check in case oldid is altering the title
842 if ( !$this->mTitle
->userCanRead() ) {
843 $wgOut->loginToUse();
848 # We're looking at an old revision
850 if ( !empty( $oldid ) ) {
851 $wgOut->setRobotpolicy( 'noindex,nofollow' );
852 if( is_null( $this->mRevision
) ) {
853 // FIXME: This would be a nice place to load the 'no such page' text.
855 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
856 if( $this->mRevision
->isDeleted( MW_REV_DELETED_TEXT
) ) {
857 if( !$this->mRevision
->userCan( MW_REV_DELETED_TEXT
) ) {
858 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
859 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
862 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
863 // and we are allowed to see...
872 * @fixme: this hook doesn't work most of the time, as it doesn't
873 * trigger when the parser cache is used.
875 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
876 $wgOut->setRevisionId( $this->getRevIdFetched() );
877 # wrap user css and user js in pre and don't parse
878 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
880 $this->mTitle
->getNamespace() == NS_USER
&&
881 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
883 $wgOut->addWikiText( wfMsg('clearyourcache'));
884 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
885 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
887 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
888 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
889 if( !$wasRedirected ) {
890 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
892 $targetUrl = $rt->escapeLocalURL();
893 $titleText = htmlspecialchars( $rt->getPrefixedText() );
894 $link = $sk->makeLinkObj( $rt );
896 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
897 '<span class="redirectText">'.$link.'</span>' );
899 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
900 $wgOut->addParserOutputNoText( $parseout );
901 } else if ( $pcache ) {
902 # Display content and save to parser cache
903 $wgOut->addPrimaryWikiText( $text, $this );
905 # Display content, don't attempt to save to parser cache
907 # Don't show section-edit links on old revisions... this way lies madness.
908 if( !$this->isCurrent() ) {
909 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
911 # Display content and don't save to parser cache
912 $wgOut->addPrimaryWikiText( $text, $this, false );
914 if( !$this->isCurrent() ) {
915 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
919 /* title may have been set from the cache */
920 $t = $wgOut->getPageTitle();
922 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
925 # If we have been passed an &rcid= parameter, we want to give the user a
926 # chance to mark this new article as patrolled.
927 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
929 "<div class='patrollink'>" .
930 wfMsg ( 'markaspatrolledlink',
931 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
938 if ($wgUseTrackbacks)
939 $this->addTrackbacks();
941 $this->viewUpdates();
942 wfProfileOut( $fname );
945 function addTrackbacks() {
946 global $wgOut, $wgUser;
948 $dbr =& wfGetDB(DB_SLAVE
);
950 /* FROM */ 'trackbacks',
951 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
952 /* WHERE */ array('tb_page' => $this->getID())
955 if (!$dbr->numrows($tbs))
959 while ($o = $dbr->fetchObject($tbs)) {
961 if ($wgUser->isSysop()) {
962 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
963 . $o->tb_id
. "&token=" . $wgUser->editToken());
964 $rmvtxt = wfMsg('trackbackremove', $delurl);
966 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
973 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
976 function deletetrackback() {
977 global $wgUser, $wgRequest, $wgOut, $wgTitle;
979 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
980 $wgOut->addWikitext(wfMsg('sessionfailure'));
984 if ((!$wgUser->isAllowed('delete'))) {
985 $wgOut->sysopRequired();
990 $wgOut->readOnlyPage();
994 $db =& wfGetDB(DB_MASTER
);
995 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
996 $wgTitle->invalidateCache();
997 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
1003 $wgOut->setArticleBodyOnly(true);
1008 * Handle action=purge
1011 global $wgUser, $wgRequest, $wgOut;
1013 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
1014 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1018 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1019 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
1020 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1021 $msg = str_replace( '$1',
1022 "<form method=\"post\" action=\"$action\">\n" .
1023 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1024 "</form>\n", $msg );
1026 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1027 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1028 $wgOut->addHTML( $msg );
1033 * Perform the actions of a page purging
1035 function doPurge() {
1037 // Invalidate the cache
1038 $this->mTitle
->invalidateCache();
1040 if ( $wgUseSquid ) {
1041 // Commit the transaction before the purge is sent
1042 $dbw = wfGetDB( DB_MASTER
);
1043 $dbw->immediateCommit();
1046 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1047 $update->doUpdate();
1053 * Insert a new empty page record for this article.
1054 * This *must* be followed up by creating a revision
1055 * and running $this->updateToLatest( $rev_id );
1056 * or else the record will be left in a funky state.
1057 * Best if all done inside a transaction.
1059 * @param Database $dbw
1060 * @param string $restrictions
1061 * @return int The newly created page_id key
1064 function insertOn( &$dbw, $restrictions = '' ) {
1065 $fname = 'Article::insertOn';
1066 wfProfileIn( $fname );
1068 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1069 $dbw->insert( 'page', array(
1070 'page_id' => $page_id,
1071 'page_namespace' => $this->mTitle
->getNamespace(),
1072 'page_title' => $this->mTitle
->getDBkey(),
1073 'page_counter' => 0,
1074 'page_restrictions' => $restrictions,
1075 'page_is_redirect' => 0, # Will set this shortly...
1077 'page_random' => wfRandom(),
1078 'page_touched' => $dbw->timestamp(),
1079 'page_latest' => 0, # Fill this in shortly...
1080 'page_len' => 0, # Fill this in shortly...
1082 $newid = $dbw->insertId();
1084 $this->mTitle
->resetArticleId( $newid );
1086 wfProfileOut( $fname );
1091 * Update the page record to point to a newly saved revision.
1093 * @param Database $dbw
1094 * @param Revision $revision For ID number, and text used to set
1095 length and redirect status fields
1096 * @param int $lastRevision If given, will not overwrite the page field
1097 * when different from the currently set value.
1098 * Giving 0 indicates the new page flag should
1100 * @return bool true on success, false on failure
1103 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1104 $fname = 'Article::updateToRevision';
1105 wfProfileIn( $fname );
1107 $conditions = array( 'page_id' => $this->getId() );
1108 if( !is_null( $lastRevision ) ) {
1109 # An extra check against threads stepping on each other
1110 $conditions['page_latest'] = $lastRevision;
1113 $text = $revision->getText();
1114 $dbw->update( 'page',
1116 'page_latest' => $revision->getId(),
1117 'page_touched' => $dbw->timestamp(),
1118 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1119 'page_is_redirect' => Article
::isRedirect( $text ) ?
1 : 0,
1120 'page_len' => strlen( $text ),
1125 wfProfileOut( $fname );
1126 return ( $dbw->affectedRows() != 0 );
1130 * If the given revision is newer than the currently set page_latest,
1131 * update the page record. Otherwise, do nothing.
1133 * @param Database $dbw
1134 * @param Revision $revision
1136 function updateIfNewerOn( &$dbw, $revision ) {
1137 $fname = 'Article::updateIfNewerOn';
1138 wfProfileIn( $fname );
1140 $row = $dbw->selectRow(
1141 array( 'revision', 'page' ),
1142 array( 'rev_id', 'rev_timestamp' ),
1144 'page_id' => $this->getId(),
1145 'page_latest=rev_id' ),
1148 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1149 wfProfileOut( $fname );
1152 $prev = $row->rev_id
;
1154 # No or missing previous revision; mark the page as new
1158 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1159 wfProfileOut( $fname );
1164 * Insert a new article into the database
1167 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1170 $fname = 'Article::insertNewArticle';
1171 wfProfileIn( $fname );
1173 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1174 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1175 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1176 wfProfileOut( $fname );
1180 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1181 $this->mTotalAdjustment
= 1;
1183 $ns = $this->mTitle
->getNamespace();
1184 $ttl = $this->mTitle
->getDBkey();
1186 # If this is a comment, add the summary as headline
1187 if($comment && $summary!="") {
1188 $text="== {$summary} ==\n\n".$text;
1190 $text = $this->preSaveTransform( $text );
1192 /* Silently ignore minoredit if not allowed */
1193 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1194 $now = wfTimestampNow();
1196 $dbw =& wfGetDB( DB_MASTER
);
1198 # Add the page record; stake our claim on this title!
1199 $newid = $this->insertOn( $dbw );
1201 # Save the revision text...
1202 $revision = new Revision( array(
1204 'comment' => $summary,
1205 'minor_edit' => $isminor,
1208 $revisionId = $revision->insertOn( $dbw );
1210 $this->mTitle
->resetArticleID( $newid );
1212 # Update the page record with revision data
1213 $this->updateRevisionOn( $dbw, $revision, 0 );
1215 Article
::onArticleCreate( $this->mTitle
);
1217 require_once( 'RecentChange.php' );
1218 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, 'default',
1219 '', strlen( $text ), $revisionId );
1220 # Mark as patrolled if the user can and has the option set
1221 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1222 RecentChange
::markPatrolled( $rcid );
1227 if(!$this->mTitle
->userIsWatching()) $this->doWatch();
1229 if ( $this->mTitle
->userIsWatching() ) {
1234 # The talk page isn't in the regular link tables, so we need to update manually:
1235 $talkns = $ns ^
1; # talk -> normal; normal -> talk
1236 $dbw->update( 'page',
1237 array( 'page_touched' => $dbw->timestamp($now) ),
1238 array( 'page_namespace' => $talkns,
1239 'page_title' => $ttl ),
1242 # standard deferred updates
1243 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1245 $oldid = 0; # new article
1246 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1248 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1250 $watchthis, NULL ) );
1251 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1253 $watchthis, NULL ) );
1254 wfProfileOut( $fname );
1257 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1258 $this->replaceSection( $section, $text, $summary, $edittime );
1262 * @return string Complete article text, or null if error
1264 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1265 $fname = 'Article::replaceSection';
1266 wfProfileIn( $fname );
1268 if ($section != '') {
1269 if( is_null( $edittime ) ) {
1270 $rev = Revision
::newFromTitle( $this->mTitle
);
1272 $dbw =& wfGetDB( DB_MASTER
);
1273 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1275 if( is_null( $rev ) ) {
1276 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1277 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1280 $oldtext = $rev->getText();
1282 if($section=='new') {
1283 if($summary) $subject="== {$summary} ==\n\n";
1284 $text=$oldtext."\n\n".$subject.$text;
1287 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1288 # comments to be stripped as well)
1289 $striparray=array();
1290 $parser=new Parser();
1291 $parser->mOutputType
=OT_WIKI
;
1292 $parser->mOptions
= new ParserOptions();
1293 $oldtext=$parser->strip($oldtext, $striparray, true);
1295 # now that we can be sure that no pseudo-sections are in the source,
1297 # Unfortunately we can't simply do a preg_replace because that might
1298 # replace the wrong section, so we have to use the section counter instead
1299 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1300 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1301 $secs[$section*2]=$text."\n\n"; // replace with edited
1303 # section 0 is top (intro) section
1306 # headline of old section - we need to go through this section
1307 # to determine if there are any subsections that now need to
1308 # be erased, as the mother section has been replaced with
1309 # the text of all subsections.
1310 $headline=$secs[$section*2-1];
1311 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1312 $hlevel=$matches[1];
1314 # determine headline level for wikimarkup headings
1315 if(strpos($hlevel,'=')!==false) {
1316 $hlevel=strlen($hlevel);
1319 $secs[$section*2-1]=''; // erase old headline
1322 while(!empty($secs[$count*2-1]) && !$break) {
1324 $subheadline=$secs[$count*2-1];
1326 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1327 $subhlevel=$matches[1];
1328 if(strpos($subhlevel,'=')!==false) {
1329 $subhlevel=strlen($subhlevel);
1331 if($subhlevel > $hlevel) {
1332 // erase old subsections
1333 $secs[$count*2-1]='';
1336 if($subhlevel <= $hlevel) {
1344 $text=join('',$secs);
1345 # reinsert the stuff that we stripped out earlier
1346 $text=$parser->unstrip($text,$striparray);
1347 $text=$parser->unstripNoWiki($text,$striparray);
1351 wfProfileOut( $fname );
1356 * Change an existing article. Puts the previous version back into the old table, updates RC
1357 * and all necessary caches, mostly via the deferred update array.
1359 * It is possible to call this function from a command-line script, but note that you should
1360 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1362 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1363 global $wgUser, $wgDBtransactions, $wgUseSquid;
1364 global $wgPostCommitUpdateList, $wgUseFileCache;
1366 $fname = 'Article::updateArticle';
1367 wfProfileIn( $fname );
1370 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1372 &$watchthis, &$sectionanchor ) ) ) {
1373 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1374 wfProfileOut( $fname );
1378 $isminor = $minor && $wgUser->isAllowed('minoredit');
1379 $redir = (int)$this->isRedirect( $text );
1381 $text = $this->preSaveTransform( $text );
1382 $dbw =& wfGetDB( DB_MASTER
);
1383 $now = wfTimestampNow();
1385 # Update article, but only if changed.
1387 # It's important that we either rollback or complete, otherwise an attacker could
1388 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1389 # could conceivably have the same effect, especially if cur is locked for long periods.
1390 if( !$wgDBtransactions ) {
1391 $userAbort = ignore_user_abort( true );
1394 $oldtext = $this->getContent();
1395 $oldsize = strlen( $oldtext );
1396 $newsize = strlen( $text );
1400 if ( 0 != strcmp( $text, $oldtext ) ) {
1401 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1402 - (int)$this->isCountable( $oldtext );
1403 $this->mTotalAdjustment
= 0;
1404 $now = wfTimestampNow();
1406 $lastRevision = $dbw->selectField(
1407 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1409 $revision = new Revision( array(
1410 'page' => $this->getId(),
1411 'comment' => $summary,
1412 'minor_edit' => $isminor,
1416 $dbw->immediateCommit();
1418 $revisionId = $revision->insertOn( $dbw );
1421 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1424 /* Belated edit conflict! Run away!! */
1428 # Update recentchanges and purge cache and whatnot
1429 require_once( 'RecentChange.php' );
1430 $bot = (int)($wgUser->isBot() ||
$forceBot);
1431 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1432 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1435 # Mark as patrolled if the user can do so and has it set in their options
1436 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1437 RecentChange
::markPatrolled( $rcid );
1442 // Update caches outside the main transaction
1443 Article
::onArticleEdit( $this->mTitle
);
1446 // Keep the same revision ID, but do some updates on it
1447 $revisionId = $this->getRevIdFetched();
1450 if( !$wgDBtransactions ) {
1451 ignore_user_abort( $userAbort );
1456 if (!$this->mTitle
->userIsWatching()) {
1457 $dbw->immediateCommit();
1463 if ( $this->mTitle
->userIsWatching() ) {
1464 $dbw->immediateCommit();
1470 # standard deferred updates
1471 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1475 # Invalidate caches of all articles using this article as a template
1477 # Template namespace
1478 # Purge all articles linking here
1479 $titles = $this->mTitle
->getTemplateLinksTo();
1480 Title
::touchArray( $titles );
1481 if ( $wgUseSquid ) {
1482 foreach ( $titles as $title ) {
1483 $urls[] = $title->getInternalURL();
1488 if ( $wgUseSquid ) {
1489 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1490 $u = new SquidUpdate( $urls );
1491 array_push( $wgPostCommitUpdateList, $u );
1495 if ( $wgUseFileCache ) {
1496 $cm = new CacheManager($this->mTitle
);
1497 @unlink
($cm->fileCacheName());
1500 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1502 wfRunHooks( 'ArticleSaveComplete',
1503 array( &$this, &$wgUser, $text,
1505 $watchthis, $sectionanchor ) );
1506 wfProfileOut( $fname );
1511 * After we've either updated or inserted the article, update
1512 * the link tables and redirect to the new page.
1514 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1517 $fname = 'Article::showArticle';
1518 wfProfileIn( $fname );
1520 # Output the redirect
1521 if( $this->isRedirect( $text ) )
1525 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1527 wfProfileOut( $fname );
1531 * Mark this particular edit as patrolled
1533 function markpatrolled() {
1534 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1535 $wgOut->setRobotpolicy( 'noindex,follow' );
1537 # Check RC patrol config. option
1538 if( !$wgUseRCPatrol ) {
1539 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1544 if( !$wgUser->isAllowed( 'patrol' ) ) {
1545 $wgOut->permissionRequired( 'patrol' );
1549 $rcid = $wgRequest->getVal( 'rcid' );
1550 if ( !is_null ( $rcid ) ) {
1551 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1552 require_once( 'RecentChange.php' );
1553 RecentChange
::markPatrolled( $rcid );
1554 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1555 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1556 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1558 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1559 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1562 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1567 * User-interface handler for the "watch" action
1572 global $wgUser, $wgOut;
1574 if ( $wgUser->isAnon() ) {
1575 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1578 if ( wfReadOnly() ) {
1579 $wgOut->readOnlyPage();
1583 if( $this->doWatch() ) {
1584 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1585 $wgOut->setRobotpolicy( 'noindex,follow' );
1587 $link = $this->mTitle
->getPrefixedText();
1588 $text = wfMsg( 'addedwatchtext', $link );
1589 $wgOut->addWikiText( $text );
1592 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1596 * Add this page to $wgUser's watchlist
1597 * @return bool true on successful watch operation
1599 function doWatch() {
1601 if( $wgUser->isAnon() ) {
1605 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1606 $wgUser->addWatch( $this->mTitle
);
1607 $wgUser->saveSettings();
1609 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1616 * User interface handler for the "unwatch" action.
1618 function unwatch() {
1620 global $wgUser, $wgOut;
1622 if ( $wgUser->isAnon() ) {
1623 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1626 if ( wfReadOnly() ) {
1627 $wgOut->readOnlyPage();
1631 if( $this->doUnwatch() ) {
1632 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1633 $wgOut->setRobotpolicy( 'noindex,follow' );
1635 $link = $this->mTitle
->getPrefixedText();
1636 $text = wfMsg( 'removedwatchtext', $link );
1637 $wgOut->addWikiText( $text );
1640 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1644 * Stop watching a page
1645 * @return bool true on successful unwatch
1647 function doUnwatch() {
1649 if( $wgUser->isAnon() ) {
1653 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1654 $wgUser->removeWatch( $this->mTitle
);
1655 $wgUser->saveSettings();
1657 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1664 * action=protect handler
1666 function protect() {
1667 require_once 'ProtectionForm.php';
1668 $form = new ProtectionForm( $this );
1673 * action=unprotect handler (alias)
1675 function unprotect() {
1680 * Update the article's restriction field, and leave a log entry.
1682 * @param array $limit set of restriction keys
1683 * @param string $reason
1684 * @return bool true on success
1686 function updateRestrictions( $limit = array(), $reason = '' ) {
1689 if ( !$wgUser->isAllowed( 'protect' ) ) {
1693 if( wfReadOnly() ) {
1697 $id = $this->mTitle
->getArticleID();
1702 $flat = Article
::flattenRestrictions( $limit );
1703 $protecting = ($flat != '');
1705 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser,
1706 $limit, $reason ) ) ) {
1708 $dbw =& wfGetDB( DB_MASTER
);
1709 $dbw->update( 'page',
1711 'page_touched' => $dbw->timestamp(),
1712 'page_restrictions' => $flat
1713 ), array( /* WHERE */
1715 ), 'Article::protect'
1718 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser,
1719 $limit, $reason ) );
1721 $log = new LogPage( 'protect' );
1723 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$flat]" ) );
1725 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1732 * Take an array of page restrictions and flatten it to a string
1733 * suitable for insertion into the page_restrictions field.
1734 * @param array $limit
1738 function flattenRestrictions( $limit ) {
1739 if( !is_array( $limit ) ) {
1740 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1743 foreach( $limit as $action => $restrictions ) {
1744 if( $restrictions != '' ) {
1745 $bits[] = "$action=$restrictions";
1748 return implode( ':', $bits );
1752 * UI entry point for page deletion
1755 global $wgUser, $wgOut, $wgRequest;
1756 $fname = 'Article::delete';
1757 $confirm = $wgRequest->wasPosted() &&
1758 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1759 $reason = $wgRequest->getText( 'wpReason' );
1761 # This code desperately needs to be totally rewritten
1764 if( $wgUser->isAllowed( 'delete' ) ) {
1765 if( $wgUser->isBlocked() ) {
1766 $wgOut->blockedPage();
1770 $wgOut->permissionRequired( 'delete' );
1774 if( wfReadOnly() ) {
1775 $wgOut->readOnlyPage();
1779 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1781 # Better double-check that it hasn't been deleted yet!
1782 $dbw =& wfGetDB( DB_MASTER
);
1783 $conds = $this->mTitle
->pageCond();
1784 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1785 if ( $latest === false ) {
1786 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1791 $this->doDelete( $reason );
1795 # determine whether this page has earlier revisions
1796 # and insert a warning if it does
1798 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1800 if( count( $authors ) > 1 && !$confirm ) {
1801 $skin=$wgUser->getSkin();
1802 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1803 $wgOut->addHTML( $skin->historyLink() .'</b>');
1806 # If a single user is responsible for all revisions, find out who they are
1807 if ( count( $authors ) == $maxRevisions ) {
1808 // Query bailed out, too many revisions to find out if they're all the same
1809 $authorOfAll = false;
1811 $authorOfAll = reset( $authors );
1812 foreach ( $authors as $author ) {
1813 if ( $authorOfAll != $author ) {
1814 $authorOfAll = false;
1819 # Fetch article text
1820 $rev = Revision
::newFromTitle( $this->mTitle
);
1822 if( !is_null( $rev ) ) {
1823 # if this is a mini-text, we can paste part of it into the deletion reason
1824 $text = $rev->getText();
1826 #if this is empty, an earlier revision may contain "useful" text
1829 $prev = $rev->getPrevious();
1831 $text = $prev->getText();
1836 $length = strlen( $text );
1838 # this should not happen, since it is not possible to store an empty, new
1839 # page. Let's insert a standard text in case it does, though
1840 if( $length == 0 && $reason === '' ) {
1841 $reason = wfMsgForContent( 'exblank' );
1844 if( $length < 500 && $reason === '' ) {
1845 # comment field=255, let's grep the first 150 to have some user
1848 $text = $wgContLang->truncate( $text, 150, '...' );
1850 # let's strip out newlines
1851 $text = preg_replace( "/[\n\r]/", '', $text );
1854 if( $authorOfAll === false ) {
1855 $reason = wfMsgForContent( 'excontent', $text );
1857 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1860 $reason = wfMsgForContent( 'exbeforeblank', $text );
1865 return $this->confirmDelete( '', $reason );
1869 * Get the last N authors
1870 * @param int $num Number of revisions to get
1871 * @param string $revLatest The latest rev_id, selected from the master (optional)
1872 * @return array Array of authors, duplicates not removed
1874 function getLastNAuthors( $num, $revLatest = 0 ) {
1875 $fname = 'Article::getLastNAuthors';
1876 wfProfileIn( $fname );
1878 // First try the slave
1879 // If that doesn't have the latest revision, try the master
1881 $db =& wfGetDB( DB_SLAVE
);
1883 $res = $db->select( array( 'page', 'revision' ),
1884 array( 'rev_id', 'rev_user_text' ),
1886 'page_namespace' => $this->mTitle
->getNamespace(),
1887 'page_title' => $this->mTitle
->getDBkey(),
1888 'rev_page = page_id'
1889 ), $fname, $this->getSelectOptions( array(
1890 'ORDER BY' => 'rev_timestamp DESC',
1895 wfProfileOut( $fname );
1898 $row = $db->fetchObject( $res );
1899 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1900 $db =& wfGetDB( DB_MASTER
);
1905 } while ( $continue );
1907 $authors = array( $row->rev_user_text
);
1908 while ( $row = $db->fetchObject( $res ) ) {
1909 $authors[] = $row->rev_user_text
;
1911 wfProfileOut( $fname );
1916 * Output deletion confirmation dialog
1918 function confirmDelete( $par, $reason ) {
1919 global $wgOut, $wgUser;
1921 wfDebug( "Article::confirmDelete\n" );
1923 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1924 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1925 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1926 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1928 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1930 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1931 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1932 $token = htmlspecialchars( $wgUser->editToken() );
1935 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1939 <label for='wpReason'>{$delcom}:</label>
1942 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1948 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1952 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1955 $wgOut->returnToMain( false );
1960 * Perform a deletion and output success or failure messages
1962 function doDelete( $reason ) {
1963 global $wgOut, $wgUser;
1964 $fname = 'Article::doDelete';
1965 wfDebug( $fname."\n" );
1967 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1968 if ( $this->doDeleteArticle( $reason ) ) {
1969 $deleted = $this->mTitle
->getPrefixedText();
1971 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1972 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1974 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1975 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1977 $wgOut->addWikiText( $text );
1978 $wgOut->returnToMain( false );
1979 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1981 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1987 * Back-end article deletion
1988 * Deletes the article with database consistency, writes logs, purges caches
1991 function doDeleteArticle( $reason ) {
1992 global $wgUseSquid, $wgDeferredUpdateList;
1993 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1995 $fname = 'Article::doDeleteArticle';
1996 wfDebug( $fname."\n" );
1998 $dbw =& wfGetDB( DB_MASTER
);
1999 $ns = $this->mTitle
->getNamespace();
2000 $t = $this->mTitle
->getDBkey();
2001 $id = $this->mTitle
->getArticleID();
2003 if ( $t == '' ||
$id == 0 ) {
2007 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2008 array_push( $wgDeferredUpdateList, $u );
2010 $linksTo = $this->mTitle
->getLinksTo();
2013 if ( $wgUseSquid ) {
2015 $this->mTitle
->getInternalURL(),
2016 $this->mTitle
->getInternalURL( 'history' )
2019 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
2020 array_push( $wgPostCommitUpdateList, $u );
2024 # Client and file cache invalidation
2025 Title
::touchArray( $linksTo );
2028 // For now, shunt the revision data into the archive table.
2029 // Text is *not* removed from the text table; bulk storage
2030 // is left intact to avoid breaking block-compression or
2031 // immutable storage schemes.
2033 // For backwards compatibility, note that some older archive
2034 // table entries will have ar_text and ar_flags fields still.
2036 // In the future, we may keep revisions and mark them with
2037 // the rev_deleted field, which is reserved for this purpose.
2038 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2040 'ar_namespace' => 'page_namespace',
2041 'ar_title' => 'page_title',
2042 'ar_comment' => 'rev_comment',
2043 'ar_user' => 'rev_user',
2044 'ar_user_text' => 'rev_user_text',
2045 'ar_timestamp' => 'rev_timestamp',
2046 'ar_minor_edit' => 'rev_minor_edit',
2047 'ar_rev_id' => 'rev_id',
2048 'ar_text_id' => 'rev_text_id',
2051 'page_id = rev_page'
2055 # Now that it's safely backed up, delete it
2056 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2057 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2059 if ($wgUseTrackbacks)
2060 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2062 # Clean up recentchanges entries...
2063 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2065 # Finally, clean up the link tables
2066 $t = $this->mTitle
->getPrefixedDBkey();
2068 Article
::onArticleDelete( $this->mTitle
);
2070 # Delete outgoing links
2071 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2072 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2073 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2074 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2075 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2078 $log = new LogPage( 'delete' );
2079 $log->addEntry( 'delete', $this->mTitle
, $reason );
2081 # Clear the cached article id so the interface doesn't act like we exist
2082 $this->mTitle
->resetArticleID( 0 );
2083 $this->mTitle
->mArticleID
= 0;
2088 * Revert a modification
2090 function rollback() {
2091 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2092 $fname = 'Article::rollback';
2094 if( $wgUser->isAllowed( 'rollback' ) ) {
2095 if( $wgUser->isBlocked() ) {
2096 $wgOut->blockedPage();
2100 $wgOut->permissionRequired( 'rollback' );
2104 if ( wfReadOnly() ) {
2105 $wgOut->readOnlyPage( $this->getContent() );
2108 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2109 array( $this->mTitle
->getPrefixedText(),
2110 $wgRequest->getVal( 'from' ) ) ) ) {
2111 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2112 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2115 $dbw =& wfGetDB( DB_MASTER
);
2117 # Enhanced rollback, marks edits rc_bot=1
2118 $bot = $wgRequest->getBool( 'bot' );
2120 # Replace all this user's current edits with the next one down
2121 $tt = $this->mTitle
->getDBKey();
2122 $n = $this->mTitle
->getNamespace();
2124 # Get the last editor, lock table exclusively
2126 $current = Revision
::newFromTitle( $this->mTitle
);
2127 if( is_null( $current ) ) {
2128 # Something wrong... no page?
2130 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2134 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2135 if( $from != $current->getUserText() ) {
2136 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2137 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2138 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2139 htmlspecialchars( $from ),
2140 htmlspecialchars( $current->getUserText() ) ) );
2141 if( $current->getComment() != '') {
2143 wfMsg( 'editcomment',
2144 htmlspecialchars( $current->getComment() ) ) );
2149 # Get the last edit not by this guy
2150 $user = intval( $current->getUser() );
2151 $user_text = $dbw->addQuotes( $current->getUserText() );
2152 $s = $dbw->selectRow( 'revision',
2153 array( 'rev_id', 'rev_timestamp' ),
2155 'rev_page' => $current->getPage(),
2156 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2159 'USE INDEX' => 'page_timestamp',
2160 'ORDER BY' => 'rev_timestamp DESC' )
2162 if( $s === false ) {
2165 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2166 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2172 # Mark all reverted edits as bot
2175 if ( $wgUseRCPatrol ) {
2176 # Mark all reverted edits as patrolled
2177 $set['rc_patrolled'] = 1;
2181 $dbw->update( 'recentchanges', $set,
2183 'rc_cur_id' => $current->getPage(),
2184 'rc_user_text' => $current->getUserText(),
2185 "rc_timestamp > '{$s->rev_timestamp}'",
2190 # Get the edit summary
2191 $target = Revision
::newFromId( $s->rev_id
);
2192 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2193 $newComment = $wgRequest->getText( 'summary', $newComment );
2196 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2197 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2198 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2200 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2201 Article
::onArticleEdit( $this->mTitle
);
2204 $wgOut->returnToMain( false );
2209 * Do standard deferred updates after page view
2212 function viewUpdates() {
2213 global $wgDeferredUpdateList;
2215 if ( 0 != $this->getID() ) {
2216 global $wgDisableCounters;
2217 if( !$wgDisableCounters ) {
2218 Article
::incViewCount( $this->getID() );
2219 $u = new SiteStatsUpdate( 1, 0, 0 );
2220 array_push( $wgDeferredUpdateList, $u );
2224 # Update newtalk / watchlist notification status
2226 $wgUser->clearNotification( $this->mTitle
);
2230 * Do standard deferred updates after page edit.
2231 * Every 1000th edit, prune the recent changes table.
2233 * @param string $text
2235 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2236 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2238 $fname = 'Article::editUpdates';
2239 wfProfileIn( $fname );
2242 $options = new ParserOptions
;
2243 $options->setTidy(true);
2244 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2246 # Save it to the parser cache
2247 $parserCache =& ParserCache
::singleton();
2248 $parserCache->save( $poutput, $this, $wgUser );
2250 # Update the links tables
2251 $u = new LinksUpdate( $this->mTitle
, $poutput );
2254 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2256 if ( 0 == mt_rand( 0, 999 ) ) {
2257 # Periodically flush old entries from the recentchanges table.
2260 $dbw =& wfGetDB( DB_MASTER
);
2261 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2262 $recentchanges = $dbw->tableName( 'recentchanges' );
2263 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2264 $dbw->query( $sql );
2268 $id = $this->getID();
2269 $title = $this->mTitle
->getPrefixedDBkey();
2270 $shortTitle = $this->mTitle
->getDBkey();
2273 wfProfileOut( $fname );
2277 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2278 array_push( $wgDeferredUpdateList, $u );
2279 $u = new SearchUpdate( $id, $title, $text );
2280 array_push( $wgDeferredUpdateList, $u );
2282 # If this is another user's talk page, update newtalk
2284 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
2285 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2286 $other = User
::newFromName( $shortTitle );
2287 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2288 // An anonymous user
2289 $other = new User();
2290 $other->setName( $shortTitle );
2293 $other->setNewtalk( true );
2298 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2299 $wgMessageCache->replace( $shortTitle, $text );
2302 wfProfileOut( $fname );
2306 * Generate the navigation links when browsing through an article revisions
2307 * It shows the information as:
2308 * Revision as of <date>; view current revision
2309 * <- Previous version | Next Version ->
2312 * @param string $oldid Revision ID of this article revision
2314 function setOldSubtitle( $oldid=0 ) {
2315 global $wgLang, $wgOut, $wgUser;
2317 $current = ( $oldid == $this->mLatest
);
2318 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2319 $sk = $wgUser->getSkin();
2321 ?
wfMsg( 'currentrevisionlink' )
2322 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2323 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2325 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2326 : wfMsg( 'previousrevision' );
2327 $nextlink = $current
2328 ?
wfMsg( 'nextrevision' )
2329 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2330 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2331 $wgOut->setSubtitle( $r );
2335 * This function is called right before saving the wikitext,
2336 * so we can do things like signatures and links-in-context.
2338 * @param string $text
2340 function preSaveTransform( $text ) {
2341 global $wgParser, $wgUser;
2342 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2345 /* Caching functions */
2348 * checkLastModified returns true if it has taken care of all
2349 * output to the client that is necessary for this request.
2350 * (that is, it has sent a cached version of the page)
2352 function tryFileCache() {
2353 static $called = false;
2355 wfDebug( " tryFileCache() -- called twice!?\n" );
2359 if($this->isFileCacheable()) {
2360 $touched = $this->mTouched
;
2361 $cache = new CacheManager( $this->mTitle
);
2362 if($cache->isFileCacheGood( $touched )) {
2363 wfDebug( " tryFileCache() - about to load\n" );
2364 $cache->loadFromFileCache();
2367 wfDebug( " tryFileCache() - starting buffer\n" );
2368 ob_start( array(&$cache, 'saveToFileCache' ) );
2371 wfDebug( " tryFileCache() - not cacheable\n" );
2376 * Check if the page can be cached
2379 function isFileCacheable() {
2380 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2381 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2383 return $wgUseFileCache
2384 and (!$wgShowIPinHeader)
2385 and ($this->getID() != 0)
2386 and ($wgUser->isAnon())
2387 and (!$wgUser->getNewtalk())
2388 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2389 and (empty( $action ) ||
$action == 'view')
2390 and (!isset($oldid))
2392 and (!isset($redirect))
2393 and (!isset($printable))
2394 and (!$this->mRedirectedFrom
);
2398 * Loads page_touched and returns a value indicating if it should be used
2401 function checkTouched() {
2402 $fname = 'Article::checkTouched';
2403 if( !$this->mDataLoaded
) {
2404 $this->loadPageData();
2406 return !$this->mIsRedirect
;
2410 * Get the page_touched field
2412 function getTouched() {
2413 # Ensure that page data has been loaded
2414 if( !$this->mDataLoaded
) {
2415 $this->loadPageData();
2417 return $this->mTouched
;
2421 * Get the page_latest field
2423 function getLatest() {
2424 if ( !$this->mDataLoaded
) {
2425 $this->loadPageData();
2427 return $this->mLatest
;
2431 * Edit an article without doing all that other stuff
2432 * The article must already exist; link tables etc
2433 * are not updated, caches are not flushed.
2435 * @param string $text text submitted
2436 * @param string $comment comment submitted
2437 * @param bool $minor whereas it's a minor modification
2439 function quickEdit( $text, $comment = '', $minor = 0 ) {
2440 $fname = 'Article::quickEdit';
2441 wfProfileIn( $fname );
2443 $dbw =& wfGetDB( DB_MASTER
);
2445 $revision = new Revision( array(
2446 'page' => $this->getId(),
2448 'comment' => $comment,
2449 'minor_edit' => $minor ?
1 : 0,
2451 $revisionId = $revision->insertOn( $dbw );
2452 $this->updateRevisionOn( $dbw, $revision );
2455 wfProfileOut( $fname );
2459 * Used to increment the view counter
2462 * @param integer $id article id
2464 function incViewCount( $id ) {
2465 $id = intval( $id );
2466 global $wgHitcounterUpdateFreq;
2468 $dbw =& wfGetDB( DB_MASTER
);
2469 $pageTable = $dbw->tableName( 'page' );
2470 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2471 $acchitsTable = $dbw->tableName( 'acchits' );
2473 if( $wgHitcounterUpdateFreq <= 1 ){ //
2474 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2478 # Not important enough to warrant an error page in case of failure
2479 $oldignore = $dbw->ignoreErrors( true );
2481 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2483 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2484 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2485 # Most of the time (or on SQL errors), skip row count check
2486 $dbw->ignoreErrors( $oldignore );
2490 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2491 $row = $dbw->fetchObject( $res );
2492 $rown = intval( $row->n
);
2493 if( $rown >= $wgHitcounterUpdateFreq ){
2494 wfProfileIn( 'Article::incViewCount-collect' );
2495 $old_user_abort = ignore_user_abort( true );
2497 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2498 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable ENGINE=HEAP ".
2499 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2501 $dbw->query("DELETE FROM $hitcounterTable");
2502 $dbw->query('UNLOCK TABLES');
2503 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2504 'WHERE page_id = hc_id');
2505 $dbw->query("DROP TABLE $acchitsTable");
2507 ignore_user_abort( $old_user_abort );
2508 wfProfileOut( 'Article::incViewCount-collect' );
2510 $dbw->ignoreErrors( $oldignore );
2514 * The onArticle*() functions are supposed to be a kind of hooks
2515 * which should be called whenever any of the specified actions
2518 * This is a good place to put code to clear caches, for instance.
2520 * This is called on page move and undelete, as well as edit
2522 * @param $title_obj a title object
2525 function onArticleCreate($title_obj) {
2526 global $wgUseSquid, $wgPostCommitUpdateList;
2528 $title_obj->touchLinks();
2529 $titles = $title_obj->getLinksTo();
2532 if ( $wgUseSquid ) {
2533 $urls = $title_obj->getSquidURLs();
2534 foreach ( $titles as $linkTitle ) {
2535 $urls[] = $linkTitle->getInternalURL();
2537 $u = new SquidUpdate( $urls );
2538 array_push( $wgPostCommitUpdateList, $u );
2542 function onArticleDelete( $title ) {
2543 global $wgMessageCache;
2545 $title->touchLinks();
2547 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2548 $wgMessageCache->replace( $title->getDBkey(), false );
2553 * Purge caches on page update etc
2555 function onArticleEdit( $title ) {
2556 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2560 // Template namespace? Purge all articles linking here.
2561 // FIXME: When a templatelinks table arrives, use it for all includes.
2562 if ( $title->getNamespace() == NS_TEMPLATE
) {
2563 $titles = $title->getLinksTo();
2564 Title
::touchArray( $titles );
2565 if ( $wgUseSquid ) {
2566 foreach ( $titles as $link ) {
2567 $urls[] = $link->getInternalURL();
2573 if ( $wgUseSquid ) {
2574 $urls = array_merge( $urls, $title->getSquidURLs() );
2575 $u = new SquidUpdate( $urls );
2576 array_push( $wgPostCommitUpdateList, $u );
2580 if ( $wgUseFileCache ) {
2581 $cm = new CacheManager( $title );
2582 @unlink
( $cm->fileCacheName() );
2589 * Info about this page
2590 * Called for ?action=info when $wgAllowPageInfo is on.
2595 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2596 $fname = 'Article::info';
2598 if ( !$wgAllowPageInfo ) {
2599 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2603 $page = $this->mTitle
->getSubjectPage();
2605 $wgOut->setPagetitle( $page->getPrefixedText() );
2606 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2608 # first, see if the page exists at all.
2609 $exists = $page->getArticleId() != 0;
2611 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2612 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2614 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2617 $dbr =& wfGetDB( DB_SLAVE
);
2619 'wl_title' => $page->getDBkey(),
2620 'wl_namespace' => $page->getNamespace() );
2621 $numwatchers = $dbr->selectField(
2626 $this->getSelectOptions() );
2628 $pageInfo = $this->pageCountInfo( $page );
2629 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2631 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2632 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2634 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2636 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2638 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2640 $wgOut->addHTML( '</ul>' );
2646 * Return the total number of edits and number of unique editors
2647 * on a given page. If page does not exist, returns false.
2649 * @param Title $title
2653 function pageCountInfo( $title ) {
2654 $id = $title->getArticleId();
2659 $dbr =& wfGetDB( DB_SLAVE
);
2661 $rev_clause = array( 'rev_page' => $id );
2662 $fname = 'Article::pageCountInfo';
2664 $edits = $dbr->selectField(
2669 $this->getSelectOptions() );
2671 $authors = $dbr->selectField(
2673 'COUNT(DISTINCT rev_user_text)',
2676 $this->getSelectOptions() );
2678 return array( 'edits' => $edits, 'authors' => $authors );
2682 * Return a list of templates used by this article.
2683 * Uses the templatelinks table
2685 * @return array Array of Title objects
2687 function getUsedTemplates() {
2689 $id = $this->mTitle
->getArticleID();
2694 $dbr =& wfGetDB( DB_SLAVE
);
2695 $res = $dbr->select( array( 'templatelinks' ),
2696 array( 'tl_namespace', 'tl_title' ),
2697 array( 'tl_from' => $id ),
2698 'Article:getUsedTemplates' );
2699 if ( false !== $res ) {
2700 if ( $dbr->numRows( $res ) ) {
2701 while ( $row = $dbr->fetchObject( $res ) ) {
2702 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2706 $dbr->freeResult( $res );