7 $wgArticleCurContentFields = false;
8 $wgArticleOldContentFields = false;
11 * Class representing a MediaWiki article and history.
13 * See design.txt for an overview.
14 * Note: edit user interface and cache support functions have been
15 * moved to separate EditPage and CacheManager classes.
25 var $mContentLoaded; //!<
29 var $mGoodAdjustment; //!<
34 var $mRedirectedFrom; //!<
35 var $mRedirectUrl; //!<
36 var $mRevIdFetched; //!<
41 var $mTotalAdjustment; //!<
48 * Constructor and clear the article
49 * @param $title Reference to a Title object.
50 * @param $oldId Integer revision ID, null to fetch from request, zero for current
52 function Article( &$title, $oldId = null ) {
53 $this->mTitle
=& $title;
54 $this->mOldId
= $oldId;
59 * Tell the page view functions that this view was redirected
60 * from another page on the wiki.
61 * @param $from Title object.
63 function setRedirectedFrom( $from ) {
64 $this->mRedirectedFrom
= $from;
68 * @return mixed false, Title of in-wiki target, or string with URL
70 function followRedirect() {
71 $text = $this->getContent();
72 $rt = Title
::newFromRedirect( $text );
74 # process if title object is valid and not special:userlogout
76 if( $rt->getInterwiki() != '' ) {
77 if( $rt->isLocal() ) {
78 // Offsite wikis need an HTTP redirect.
80 // This can be hard to reverse and may produce loops,
81 // so they may be disabled in the site configuration.
83 $source = $this->mTitle
->getFullURL( 'redirect=no' );
84 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
87 if( $rt->getNamespace() == NS_SPECIAL
) {
88 // Gotta hand redirects to special pages differently:
89 // Fill the HTTP response "Location" header and ignore
90 // the rest of the page we're on.
92 // This can be hard to reverse, so they may be disabled.
94 if( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) {
97 return $rt->getFullURL();
104 // No or invalid redirect
109 * get the title object of the article
111 function getTitle() {
112 return $this->mTitle
;
120 $this->mDataLoaded
= false;
121 $this->mContentLoaded
= false;
123 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
124 $this->mRedirectedFrom
= null; # Title object if set
126 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
127 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
128 $this->mTouched
= '19700101000000';
129 $this->mForUpdate
= false;
130 $this->mIsRedirect
= false;
131 $this->mRevIdFetched
= 0;
132 $this->mRedirectUrl
= false;
133 $this->mLatest
= false;
137 * Note that getContent/loadContent do not follow redirects anymore.
138 * If you need to fetch redirectable content easily, try
139 * the shortcut in Article::followContent()
141 * @todo There are still side-effects in this!
142 * In general, you should use the Revision class, not Article,
143 * to fetch text for purposes other than page views.
145 * @return Return the text of this revision
147 function getContent() {
148 global $wgRequest, $wgUser, $wgOut;
150 # Get variables from query string :P
151 $action = $wgRequest->getText( 'action', 'view' );
152 $section = $wgRequest->getText( 'section' );
153 $preload = $wgRequest->getText( 'preload' );
155 $fname = 'Article::getContent';
156 wfProfileIn( $fname );
158 if ( 0 == $this->getID() ) {
159 if ( 'edit' == $action ) {
160 wfProfileOut( $fname );
162 # If requested, preload some text.
163 $text=$this->getPreloadedText($preload);
165 # We used to put MediaWiki:Newarticletext here if
166 # $text was empty at this point.
167 # This is now shown above the edit box instead.
170 wfProfileOut( $fname );
171 $wgOut->setRobotpolicy( 'noindex,nofollow' );
173 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
174 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
176 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
179 return "<div class='noarticletext'>$ret</div>";
181 $this->loadContent();
182 if($action=='edit') {
184 if($section=='new') {
185 wfProfileOut( $fname );
186 $text=$this->getPreloadedText($preload);
190 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
191 # comments to be stripped as well)
192 $rv=$this->getSection($this->mContent
,$section);
193 wfProfileOut( $fname );
197 wfProfileOut( $fname );
198 return $this->mContent
;
203 * Get the contents of a page from its title and remove includeonly tags
205 * @param $preload String: the title of the page.
206 * @return string The contents of the page.
208 function getPreloadedText($preload) {
209 if ( $preload === '' )
212 $preloadTitle = Title
::newFromText( $preload );
213 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
214 $rev=Revision
::newFromTitle($preloadTitle);
215 if ( is_object( $rev ) ) {
216 $text = $rev->getText();
217 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
218 // its own mini-parser! -ævar
219 $text = preg_replace( '~</?includeonly>~', '', $text );
228 * This function returns the text of a section, specified by a number ($section).
229 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
230 * the first section before any such heading (section 0).
232 * If a section contains subsections, these are also returned.
234 * @param $text String: text to look in
235 * @param $section Integer: section number
236 * @return string text of the requested section
238 function getSection($text,$section) {
240 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
241 # comments to be stripped as well)
243 $parser=new Parser();
244 $parser->mOutputType
=OT_WIKI
;
245 $parser->mOptions
= new ParserOptions();
246 $striptext=$parser->strip($text, $striparray, true);
248 # now that we can be sure that no pseudo-sections are in the source,
249 # split it up by section
252 '/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
254 PREG_SPLIT_DELIM_CAPTURE
);
258 $headline=$secs[$section*2-1];
259 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
262 # translate wiki heading into level
263 if(strpos($hlevel,'=')!==false) {
264 $hlevel=strlen($hlevel);
267 $rv=$headline. $secs[$section*2];
271 while(!empty($secs[$count*2-1]) && !$break) {
273 $subheadline=$secs[$count*2-1];
274 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
275 $subhlevel=$matches[1];
276 if(strpos($subhlevel,'=')!==false) {
277 $subhlevel=strlen($subhlevel);
279 if($subhlevel > $hlevel) {
280 $rv.=$subheadline.$secs[$count*2];
282 if($subhlevel <= $hlevel) {
289 # reinsert stripped tags
290 $rv=$parser->unstrip($rv,$striparray);
291 $rv=$parser->unstripNoWiki($rv,$striparray);
298 * @return int The oldid of the article that is to be shown, 0 for the
301 function getOldID() {
302 if ( is_null( $this->mOldId
) ) {
303 $this->mOldId
= $this->getOldIDFromRequest();
305 return $this->mOldId
;
309 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
311 * @return int The old id for the request
313 function getOldIDFromRequest() {
315 $this->mRedirectUrl
= false;
316 $oldid = $wgRequest->getVal( 'oldid' );
317 if ( isset( $oldid ) ) {
318 $oldid = intval( $oldid );
319 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
320 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
324 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
326 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
327 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
344 * Load the revision (including text) into this object
346 function loadContent() {
347 if ( $this->mContentLoaded
) return;
350 $oldid = $this->getOldID();
352 # Pre-fill content with error message so that if something
353 # fails we'll have something telling us what we intended.
355 $t = $this->mTitle
->getPrefixedText();
357 $this->mOldId
= $oldid;
358 $this->fetchContent( $oldid );
363 * Fetch a page record with the given conditions
364 * @param Database $dbr
365 * @param array $conditions
368 function pageData( &$dbr, $conditions ) {
381 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
382 $row = $dbr->selectRow( 'page',
385 'Article::pageData' );
386 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
391 * @param Database $dbr
392 * @param Title $title
394 function pageDataFromTitle( &$dbr, $title ) {
395 return $this->pageData( $dbr, array(
396 'page_namespace' => $title->getNamespace(),
397 'page_title' => $title->getDBkey() ) );
401 * @param Database $dbr
404 function pageDataFromId( &$dbr, $id ) {
405 return $this->pageData( $dbr, array( 'page_id' => $id ) );
409 * Set the general counter, title etc data loaded from
412 * @param object $data
415 function loadPageData( $data = 'fromdb' ) {
416 if ( $data === 'fromdb' ) {
417 $dbr =& $this->getDB();
418 $data = $this->pageDataFromId( $dbr, $this->getId() );
421 $lc =& LinkCache
::singleton();
423 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
425 $this->mTitle
->mArticleID
= $data->page_id
;
426 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
427 $this->mTitle
->mRestrictionsLoaded
= true;
429 $this->mCounter
= $data->page_counter
;
430 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
431 $this->mIsRedirect
= $data->page_is_redirect
;
432 $this->mLatest
= $data->page_latest
;
434 if ( is_object( $this->mTitle
) ) {
435 $lc->addBadLinkObj( $this->mTitle
);
437 $this->mTitle
->mArticleID
= 0;
440 $this->mDataLoaded
= true;
444 * Get text of an article from database
445 * Does *NOT* follow redirects.
446 * @param int $oldid 0 for whatever the latest revision is
449 function fetchContent( $oldid = 0 ) {
450 if ( $this->mContentLoaded
) {
451 return $this->mContent
;
454 $dbr =& $this->getDB();
455 $fname = 'Article::fetchContent';
457 # Pre-fill content with error message so that if something
458 # fails we'll have something telling us what we intended.
459 $t = $this->mTitle
->getPrefixedText();
461 $t .= ',oldid='.$oldid;
463 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
466 $revision = Revision
::newFromId( $oldid );
467 if( is_null( $revision ) ) {
468 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
471 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
473 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
476 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
477 $this->loadPageData( $data );
479 if( !$this->mDataLoaded
) {
480 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
482 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
485 $this->loadPageData( $data );
487 $revision = Revision
::newFromId( $this->mLatest
);
488 if( is_null( $revision ) ) {
489 wfDebug( "$fname failed to retrieve current page, rev_id {$data->page_latest}\n" );
494 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
495 // We should instead work with the Revision object when we need it...
496 $this->mContent
= $revision->userCan( MW_REV_DELETED_TEXT
) ?
$revision->getRawText() : "";
497 //$this->mContent = $revision->getText();
499 $this->mUser
= $revision->getUser();
500 $this->mUserText
= $revision->getUserText();
501 $this->mComment
= $revision->getComment();
502 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
504 $this->mRevIdFetched
= $revision->getID();
505 $this->mContentLoaded
= true;
506 $this->mRevision
=& $revision;
508 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
510 return $this->mContent
;
514 * Read/write accessor to select FOR UPDATE
516 * @param $x Mixed: FIXME
518 function forUpdate( $x = NULL ) {
519 return wfSetVar( $this->mForUpdate
, $x );
523 * Get the database which should be used for reads
528 $ret =& wfGetDB( DB_MASTER
);
533 * Get options for all SELECT statements
535 * @param $options Array: an optional options array which'll be appended to
537 * @return Array: options
539 function getSelectOptions( $options = '' ) {
540 if ( $this->mForUpdate
) {
541 if ( is_array( $options ) ) {
542 $options[] = 'FOR UPDATE';
544 $options = 'FOR UPDATE';
551 * @return int Page ID
554 if( $this->mTitle
) {
555 return $this->mTitle
->getArticleID();
562 * @return bool Whether or not the page exists in the database
565 return $this->getId() != 0;
569 * @return int The view count for the page
571 function getCount() {
572 if ( -1 == $this->mCounter
) {
573 $id = $this->getID();
577 $dbr =& wfGetDB( DB_SLAVE
);
578 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
579 'Article::getCount', $this->getSelectOptions() );
582 return $this->mCounter
;
586 * Determine whether a page would be suitable for being counted as an
587 * article in the site_stats table based on the title & its content
589 * @param $text String: text to analyze
592 function isCountable( $text ) {
593 global $wgUseCommaCount;
595 $token = $wgUseCommaCount ?
',' : '[[';
597 $this->mTitle
->getNamespace() == NS_MAIN
598 && ! $this->isRedirect( $text )
599 && in_string( $token, $text );
603 * Tests if the article text represents a redirect
605 * @param $text String: FIXME
608 function isRedirect( $text = false ) {
609 if ( $text === false ) {
610 $this->loadContent();
611 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
613 $titleObj = Title
::newFromRedirect( $text );
615 return $titleObj !== NULL;
619 * Returns true if the currently-referenced revision is the current edit
620 * to this page (and it exists).
623 function isCurrent() {
624 return $this->exists() &&
625 isset( $this->mRevision
) &&
626 $this->mRevision
->isCurrent();
630 * Loads everything except the text
631 * This isn't necessary for all uses, so it's only done if needed.
634 function loadLastEdit() {
635 if ( -1 != $this->mUser
)
638 # New or non-existent articles have no user information
639 $id = $this->getID();
640 if ( 0 == $id ) return;
642 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
643 if( !is_null( $this->mLastRevision
) ) {
644 $this->mUser
= $this->mLastRevision
->getUser();
645 $this->mUserText
= $this->mLastRevision
->getUserText();
646 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
647 $this->mComment
= $this->mLastRevision
->getComment();
648 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
649 $this->mRevIdFetched
= $this->mLastRevision
->getID();
653 function getTimestamp() {
654 // Check if the field has been filled by ParserCache::get()
655 if ( !$this->mTimestamp
) {
656 $this->loadLastEdit();
658 return wfTimestamp(TS_MW
, $this->mTimestamp
);
662 $this->loadLastEdit();
666 function getUserText() {
667 $this->loadLastEdit();
668 return $this->mUserText
;
671 function getComment() {
672 $this->loadLastEdit();
673 return $this->mComment
;
676 function getMinorEdit() {
677 $this->loadLastEdit();
678 return $this->mMinorEdit
;
681 function getRevIdFetched() {
682 $this->loadLastEdit();
683 return $this->mRevIdFetched
;
687 * @todo Document, fixme $offset never used.
688 * @param $limit Integer: default 0.
689 * @param $offset Integer: default 0.
691 function getContributors($limit = 0, $offset = 0) {
692 $fname = 'Article::getContributors';
694 # XXX: this is expensive; cache this info somewhere.
696 $title = $this->mTitle
;
698 $dbr =& wfGetDB( DB_SLAVE
);
699 $revTable = $dbr->tableName( 'revision' );
700 $userTable = $dbr->tableName( 'user' );
701 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
702 $ns = $title->getNamespace();
703 $user = $this->getUser();
704 $pageId = $this->getId();
706 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
707 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
708 WHERE rev_page = $pageId
709 AND rev_user != $user
710 GROUP BY rev_user, rev_user_text, user_real_name
711 ORDER BY timestamp DESC";
713 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
714 $sql .= ' '. $this->getSelectOptions();
716 $res = $dbr->query($sql, $fname);
718 while ( $line = $dbr->fetchObject( $res ) ) {
719 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
722 $dbr->freeResult($res);
727 * This is the default action of the script: just view the page of
731 global $wgUser, $wgOut, $wgRequest, $wgContLang;
732 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
733 global $wgUseTrackbacks;
734 $sk = $wgUser->getSkin();
736 $fname = 'Article::view';
737 wfProfileIn( $fname );
738 $parserCache =& ParserCache
::singleton();
739 # Get variables from query string
740 $oldid = $this->getOldID();
742 # getOldID may want us to redirect somewhere else
743 if ( $this->mRedirectUrl
) {
744 $wgOut->redirect( $this->mRedirectUrl
);
745 wfProfileOut( $fname );
749 $diff = $wgRequest->getVal( 'diff' );
750 $rcid = $wgRequest->getVal( 'rcid' );
751 $rdfrom = $wgRequest->getVal( 'rdfrom' );
753 $wgOut->setArticleFlag( true );
754 $wgOut->setRobotpolicy( 'index,follow' );
755 # If we got diff and oldid in the query, we want to see a
756 # diff page instead of the article.
758 if ( !is_null( $diff ) ) {
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 # Don't overwrite the subtitle if this was an old revision
890 if( !$wasRedirected && $this->isCurrent() ) {
891 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
893 $targetUrl = $rt->escapeLocalURL();
894 #Â fixme unused $titleText :
895 $titleText = htmlspecialchars( $rt->getPrefixedText() );
896 $link = $sk->makeLinkObj( $rt );
898 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
899 '<span class="redirectText">'.$link.'</span>' );
901 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
902 $wgOut->addParserOutputNoText( $parseout );
903 } else if ( $pcache ) {
904 # Display content and save to parser cache
905 $wgOut->addPrimaryWikiText( $text, $this );
907 # Display content, don't attempt to save to parser cache
909 # Don't show section-edit links on old revisions... this way lies madness.
910 if( !$this->isCurrent() ) {
911 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
913 # Display content and don't save to parser cache
914 $wgOut->addPrimaryWikiText( $text, $this, false );
916 if( !$this->isCurrent() ) {
917 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
921 /* title may have been set from the cache */
922 $t = $wgOut->getPageTitle();
924 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
927 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
928 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
929 User
::isIP( $this->mTitle
->getText() ) ) {
930 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
933 # If we have been passed an &rcid= parameter, we want to give the user a
934 # chance to mark this new article as patrolled.
935 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
937 "<div class='patrollink'>" .
938 wfMsg ( 'markaspatrolledlink',
939 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
946 if ($wgUseTrackbacks)
947 $this->addTrackbacks();
949 $this->viewUpdates();
950 wfProfileOut( $fname );
953 function addTrackbacks() {
954 global $wgOut, $wgUser;
956 $dbr =& wfGetDB(DB_SLAVE
);
958 /* FROM */ 'trackbacks',
959 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
960 /* WHERE */ array('tb_page' => $this->getID())
963 if (!$dbr->numrows($tbs))
967 while ($o = $dbr->fetchObject($tbs)) {
969 if ($wgUser->isAllowed( 'trackback' )) {
970 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
971 . $o->tb_id
. "&token=" . $wgUser->editToken());
972 $rmvtxt = wfMsg('trackbackremove', $delurl);
974 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
981 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
984 function deletetrackback() {
985 global $wgUser, $wgRequest, $wgOut, $wgTitle;
987 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
988 $wgOut->addWikitext(wfMsg('sessionfailure'));
992 if ((!$wgUser->isAllowed('delete'))) {
993 $wgOut->sysopRequired();
998 $wgOut->readOnlyPage();
1002 $db =& wfGetDB(DB_MASTER
);
1003 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1004 $wgTitle->invalidateCache();
1005 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
1011 $wgOut->setArticleBodyOnly(true);
1016 * Handle action=purge
1019 global $wgUser, $wgRequest, $wgOut;
1021 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
1022 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1026 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1027 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
1028 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1029 $msg = str_replace( '$1',
1030 "<form method=\"post\" action=\"$action\">\n" .
1031 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1032 "</form>\n", $msg );
1034 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1035 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1036 $wgOut->addHTML( $msg );
1041 * Perform the actions of a page purging
1043 function doPurge() {
1045 // Invalidate the cache
1046 $this->mTitle
->invalidateCache();
1048 if ( $wgUseSquid ) {
1049 // Commit the transaction before the purge is sent
1050 $dbw = wfGetDB( DB_MASTER
);
1051 $dbw->immediateCommit();
1054 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1055 $update->doUpdate();
1061 * Insert a new empty page record for this article.
1062 * This *must* be followed up by creating a revision
1063 * and running $this->updateToLatest( $rev_id );
1064 * or else the record will be left in a funky state.
1065 * Best if all done inside a transaction.
1067 * @param Database $dbw
1068 * @param string $restrictions
1069 * @return int The newly created page_id key
1072 function insertOn( &$dbw, $restrictions = '' ) {
1073 $fname = 'Article::insertOn';
1074 wfProfileIn( $fname );
1076 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1077 $dbw->insert( 'page', array(
1078 'page_id' => $page_id,
1079 'page_namespace' => $this->mTitle
->getNamespace(),
1080 'page_title' => $this->mTitle
->getDBkey(),
1081 'page_counter' => 0,
1082 'page_restrictions' => $restrictions,
1083 'page_is_redirect' => 0, # Will set this shortly...
1085 'page_random' => wfRandom(),
1086 'page_touched' => $dbw->timestamp(),
1087 'page_latest' => 0, # Fill this in shortly...
1088 'page_len' => 0, # Fill this in shortly...
1090 $newid = $dbw->insertId();
1092 $this->mTitle
->resetArticleId( $newid );
1094 wfProfileOut( $fname );
1099 * Update the page record to point to a newly saved revision.
1101 * @param Database $dbw
1102 * @param Revision $revision For ID number, and text used to set
1103 length and redirect status fields
1104 * @param int $lastRevision If given, will not overwrite the page field
1105 * when different from the currently set value.
1106 * Giving 0 indicates the new page flag should
1108 * @return bool true on success, false on failure
1111 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1112 $fname = 'Article::updateToRevision';
1113 wfProfileIn( $fname );
1115 $conditions = array( 'page_id' => $this->getId() );
1116 if( !is_null( $lastRevision ) ) {
1117 # An extra check against threads stepping on each other
1118 $conditions['page_latest'] = $lastRevision;
1121 $text = $revision->getText();
1122 $dbw->update( 'page',
1124 'page_latest' => $revision->getId(),
1125 'page_touched' => $dbw->timestamp(),
1126 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1127 'page_is_redirect' => Article
::isRedirect( $text ) ?
1 : 0,
1128 'page_len' => strlen( $text ),
1133 wfProfileOut( $fname );
1134 return ( $dbw->affectedRows() != 0 );
1138 * If the given revision is newer than the currently set page_latest,
1139 * update the page record. Otherwise, do nothing.
1141 * @param Database $dbw
1142 * @param Revision $revision
1144 function updateIfNewerOn( &$dbw, $revision ) {
1145 $fname = 'Article::updateIfNewerOn';
1146 wfProfileIn( $fname );
1148 $row = $dbw->selectRow(
1149 array( 'revision', 'page' ),
1150 array( 'rev_id', 'rev_timestamp' ),
1152 'page_id' => $this->getId(),
1153 'page_latest=rev_id' ),
1156 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1157 wfProfileOut( $fname );
1160 $prev = $row->rev_id
;
1162 # No or missing previous revision; mark the page as new
1166 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1167 wfProfileOut( $fname );
1172 * Insert a new article into the database
1175 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1178 $fname = 'Article::insertNewArticle';
1179 wfProfileIn( $fname );
1181 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1182 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1183 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1184 wfProfileOut( $fname );
1188 $ns = $this->mTitle
->getNamespace();
1189 $ttl = $this->mTitle
->getDBkey();
1191 # If this is a comment, add the summary as headline
1192 if($comment && $summary!="") {
1193 $text="== {$summary} ==\n\n".$text;
1195 $text = $this->preSaveTransform( $text );
1198 # Set statistics members
1199 # We work out if it's countable after PST to avoid counter drift
1200 # when articles are created with {{subst:}}
1201 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1202 $this->mTotalAdjustment
= 1;
1204 /* Silently ignore minoredit if not allowed */
1205 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1206 $now = wfTimestampNow();
1208 $dbw =& wfGetDB( DB_MASTER
);
1210 # Add the page record; stake our claim on this title!
1211 $newid = $this->insertOn( $dbw );
1213 # Save the revision text...
1214 $revision = new Revision( array(
1216 'comment' => $summary,
1217 'minor_edit' => $isminor,
1220 $revisionId = $revision->insertOn( $dbw );
1222 $this->mTitle
->resetArticleID( $newid );
1224 # Update the page record with revision data
1225 $this->updateRevisionOn( $dbw, $revision, 0 );
1227 Article
::onArticleCreate( $this->mTitle
);
1229 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, 'default',
1230 '', strlen( $text ), $revisionId );
1231 # Mark as patrolled if the user can and has the option set
1232 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1233 RecentChange
::markPatrolled( $rcid );
1238 if(!$this->mTitle
->userIsWatching()) $this->doWatch();
1240 if ( $this->mTitle
->userIsWatching() ) {
1245 # The talk page isn't in the regular link tables, so we need to update manually:
1246 $talkns = $ns ^
1; # talk -> normal; normal -> talk
1247 $dbw->update( 'page',
1248 array( 'page_touched' => $dbw->timestamp($now) ),
1249 array( 'page_namespace' => $talkns,
1250 'page_title' => $ttl ),
1253 # standard deferred updates
1254 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1256 $oldid = 0; # new article
1257 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1259 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1261 $watchthis, NULL ) );
1262 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1264 $watchthis, NULL ) );
1265 wfProfileOut( $fname );
1269 * @return string Complete article text, or null if error
1271 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1272 $fname = 'Article::replaceSection';
1273 wfProfileIn( $fname );
1275 if ($section != '') {
1276 if( is_null( $edittime ) ) {
1277 $rev = Revision
::newFromTitle( $this->mTitle
);
1279 $dbw =& wfGetDB( DB_MASTER
);
1280 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1282 if( is_null( $rev ) ) {
1283 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1284 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1287 $oldtext = $rev->getText();
1289 if($section=='new') {
1290 if($summary) $subject="== {$summary} ==\n\n";
1291 $text=$oldtext."\n\n".$subject.$text;
1294 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1295 # comments to be stripped as well)
1296 $striparray=array();
1297 $parser=new Parser();
1298 $parser->mOutputType
=OT_WIKI
;
1299 $parser->mOptions
= new ParserOptions();
1300 $oldtext=$parser->strip($oldtext, $striparray, true);
1302 # now that we can be sure that no pseudo-sections are in the source,
1304 # Unfortunately we can't simply do a preg_replace because that might
1305 # replace the wrong section, so we have to use the section counter instead
1306 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1307 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1308 $secs[$section*2]=$text."\n\n"; // replace with edited
1310 # section 0 is top (intro) section
1313 # headline of old section - we need to go through this section
1314 # to determine if there are any subsections that now need to
1315 # be erased, as the mother section has been replaced with
1316 # the text of all subsections.
1317 $headline=$secs[$section*2-1];
1318 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1319 $hlevel=$matches[1];
1321 # determine headline level for wikimarkup headings
1322 if(strpos($hlevel,'=')!==false) {
1323 $hlevel=strlen($hlevel);
1326 $secs[$section*2-1]=''; // erase old headline
1329 while(!empty($secs[$count*2-1]) && !$break) {
1331 $subheadline=$secs[$count*2-1];
1333 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1334 $subhlevel=$matches[1];
1335 if(strpos($subhlevel,'=')!==false) {
1336 $subhlevel=strlen($subhlevel);
1338 if($subhlevel > $hlevel) {
1339 // erase old subsections
1340 $secs[$count*2-1]='';
1343 if($subhlevel <= $hlevel) {
1351 $text=join('',$secs);
1352 # reinsert the stuff that we stripped out earlier
1353 $text=$parser->unstrip($text,$striparray);
1354 $text=$parser->unstripNoWiki($text,$striparray);
1358 wfProfileOut( $fname );
1363 * Change an existing article. Puts the previous version back into the old table, updates RC
1364 * and all necessary caches, mostly via the deferred update array.
1366 * It is possible to call this function from a command-line script, but note that you should
1367 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1369 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1370 global $wgUser, $wgDBtransactions, $wgUseSquid;
1371 global $wgPostCommitUpdateList, $wgUseFileCache;
1373 $fname = 'Article::updateArticle';
1374 wfProfileIn( $fname );
1377 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1379 &$watchthis, &$sectionanchor ) ) ) {
1380 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1381 wfProfileOut( $fname );
1385 $isminor = $minor && $wgUser->isAllowed('minoredit');
1387 $text = $this->preSaveTransform( $text );
1388 $dbw =& wfGetDB( DB_MASTER
);
1389 $now = wfTimestampNow();
1391 # Update article, but only if changed.
1393 # It's important that we either rollback or complete, otherwise an attacker could
1394 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1395 # could conceivably have the same effect, especially if cur is locked for long periods.
1396 if( !$wgDBtransactions ) {
1397 $userAbort = ignore_user_abort( true );
1400 $oldtext = $this->getContent();
1401 $oldsize = strlen( $oldtext );
1402 $newsize = strlen( $text );
1406 if ( 0 != strcmp( $text, $oldtext ) ) {
1407 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1408 - (int)$this->isCountable( $oldtext );
1409 $this->mTotalAdjustment
= 0;
1410 $now = wfTimestampNow();
1412 $lastRevision = $dbw->selectField(
1413 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1415 $revision = new Revision( array(
1416 'page' => $this->getId(),
1417 'comment' => $summary,
1418 'minor_edit' => $isminor,
1422 $dbw->immediateCommit();
1424 $revisionId = $revision->insertOn( $dbw );
1427 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1430 /* Belated edit conflict! Run away!! */
1434 # Update recentchanges and purge cache and whatnot
1435 $bot = (int)($wgUser->isBot() ||
$forceBot);
1436 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1437 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1440 # Mark as patrolled if the user can do so and has it set in their options
1441 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1442 RecentChange
::markPatrolled( $rcid );
1447 // Update caches outside the main transaction
1448 Article
::onArticleEdit( $this->mTitle
);
1451 // Keep the same revision ID, but do some updates on it
1452 $revisionId = $this->getRevIdFetched();
1455 if( !$wgDBtransactions ) {
1456 ignore_user_abort( $userAbort );
1461 if (!$this->mTitle
->userIsWatching()) {
1462 $dbw->immediateCommit();
1468 if ( $this->mTitle
->userIsWatching() ) {
1469 $dbw->immediateCommit();
1475 # standard deferred updates
1476 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1480 # Invalidate caches of all articles using this article as a template
1482 # Template namespace
1483 # Purge all articles linking here
1484 $titles = $this->mTitle
->getTemplateLinksTo();
1485 Title
::touchArray( $titles );
1486 if ( $wgUseSquid ) {
1487 foreach ( $titles as $title ) {
1488 $urls[] = $title->getInternalURL();
1493 if ( $wgUseSquid ) {
1494 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1495 $u = new SquidUpdate( $urls );
1496 array_push( $wgPostCommitUpdateList, $u );
1500 if ( $wgUseFileCache ) {
1501 $cm = new CacheManager($this->mTitle
);
1502 @unlink
($cm->fileCacheName());
1505 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1507 wfRunHooks( 'ArticleSaveComplete',
1508 array( &$this, &$wgUser, $text,
1510 $watchthis, $sectionanchor ) );
1511 wfProfileOut( $fname );
1516 * After we've either updated or inserted the article, update
1517 * the link tables and redirect to the new page.
1518 * @todo FIXME some function arguments never used
1520 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1523 $fname = 'Article::showArticle';
1524 wfProfileIn( $fname );
1526 # Output the redirect
1527 if( $this->isRedirect( $text ) )
1531 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1533 wfProfileOut( $fname );
1537 * Mark this particular edit as patrolled
1539 function markpatrolled() {
1540 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1541 $wgOut->setRobotpolicy( 'noindex,follow' );
1543 # Check RC patrol config. option
1544 if( !$wgUseRCPatrol ) {
1545 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1550 if( !$wgUser->isAllowed( 'patrol' ) ) {
1551 $wgOut->permissionRequired( 'patrol' );
1555 $rcid = $wgRequest->getVal( 'rcid' );
1556 if ( !is_null ( $rcid ) ) {
1557 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1558 RecentChange
::markPatrolled( $rcid );
1559 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1560 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1561 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1563 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1564 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1567 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1572 * User-interface handler for the "watch" action
1577 global $wgUser, $wgOut;
1579 if ( $wgUser->isAnon() ) {
1580 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1583 if ( wfReadOnly() ) {
1584 $wgOut->readOnlyPage();
1588 if( $this->doWatch() ) {
1589 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1590 $wgOut->setRobotpolicy( 'noindex,follow' );
1592 $link = $this->mTitle
->getPrefixedText();
1593 $text = wfMsg( 'addedwatchtext', $link );
1594 $wgOut->addWikiText( $text );
1597 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1601 * Add this page to $wgUser's watchlist
1602 * @return bool true on successful watch operation
1604 function doWatch() {
1606 if( $wgUser->isAnon() ) {
1610 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1611 $wgUser->addWatch( $this->mTitle
);
1612 $wgUser->saveSettings();
1614 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1621 * User interface handler for the "unwatch" action.
1623 function unwatch() {
1625 global $wgUser, $wgOut;
1627 if ( $wgUser->isAnon() ) {
1628 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1631 if ( wfReadOnly() ) {
1632 $wgOut->readOnlyPage();
1636 if( $this->doUnwatch() ) {
1637 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1638 $wgOut->setRobotpolicy( 'noindex,follow' );
1640 $link = $this->mTitle
->getPrefixedText();
1641 $text = wfMsg( 'removedwatchtext', $link );
1642 $wgOut->addWikiText( $text );
1645 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1649 * Stop watching a page
1650 * @return bool true on successful unwatch
1652 function doUnwatch() {
1654 if( $wgUser->isAnon() ) {
1658 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1659 $wgUser->removeWatch( $this->mTitle
);
1660 $wgUser->saveSettings();
1662 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1669 * action=protect handler
1671 function protect() {
1672 $form = new ProtectionForm( $this );
1677 * action=unprotect handler (alias)
1679 function unprotect() {
1684 * Update the article's restriction field, and leave a log entry.
1686 * @param array $limit set of restriction keys
1687 * @param string $reason
1688 * @return bool true on success
1690 function updateRestrictions( $limit = array(), $reason = '' ) {
1691 global $wgUser, $wgRestrictionTypes, $wgContLang;
1693 $id = $this->mTitle
->getArticleID();
1694 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1698 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1699 # we expect a single selection, but the schema allows otherwise.
1701 foreach( $wgRestrictionTypes as $action )
1702 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1704 $current = Article
::flattenRestrictions( $current );
1705 $updated = Article
::flattenRestrictions( $limit );
1707 $changed = ( $current != $updated );
1708 $protect = ( $updated != '' );
1710 # If nothing's changed, do nothing
1712 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1714 $dbw =& wfGetDB( DB_MASTER
);
1716 # Prepare a null revision to be added to the history
1717 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ?
'protectedarticle' : 'unprotectedarticle', $this->mTitle
->getPrefixedText() ) );
1719 $comment .= ": $reason";
1721 $comment .= " [$updated]";
1722 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1723 $nullRevId = $nullRevision->insertOn( $dbw );
1725 # Update page record
1726 $dbw->update( 'page',
1728 'page_touched' => $dbw->timestamp(),
1729 'page_restrictions' => $updated,
1730 'page_latest' => $nullRevId
1731 ), array( /* WHERE */
1733 ), 'Article::protect'
1735 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1737 # Update the protection log
1738 $log = new LogPage( 'protect' );
1740 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$updated]" ) );
1742 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1746 } # End "changed" check
1752 * Take an array of page restrictions and flatten it to a string
1753 * suitable for insertion into the page_restrictions field.
1754 * @param array $limit
1758 function flattenRestrictions( $limit ) {
1759 if( !is_array( $limit ) ) {
1760 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1764 foreach( $limit as $action => $restrictions ) {
1765 if( $restrictions != '' ) {
1766 $bits[] = "$action=$restrictions";
1769 return implode( ':', $bits );
1773 * UI entry point for page deletion
1776 global $wgUser, $wgOut, $wgRequest;
1777 $fname = 'Article::delete';
1778 $confirm = $wgRequest->wasPosted() &&
1779 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1780 $reason = $wgRequest->getText( 'wpReason' );
1782 # This code desperately needs to be totally rewritten
1785 if( $wgUser->isAllowed( 'delete' ) ) {
1786 if( $wgUser->isBlocked() ) {
1787 $wgOut->blockedPage();
1791 $wgOut->permissionRequired( 'delete' );
1795 if( wfReadOnly() ) {
1796 $wgOut->readOnlyPage();
1800 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1802 # Better double-check that it hasn't been deleted yet!
1803 $dbw =& wfGetDB( DB_MASTER
);
1804 $conds = $this->mTitle
->pageCond();
1805 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1806 if ( $latest === false ) {
1807 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1812 $this->doDelete( $reason );
1816 # determine whether this page has earlier revisions
1817 # and insert a warning if it does
1819 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1821 if( count( $authors ) > 1 && !$confirm ) {
1822 $skin=$wgUser->getSkin();
1823 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1826 # If a single user is responsible for all revisions, find out who they are
1827 if ( count( $authors ) == $maxRevisions ) {
1828 // Query bailed out, too many revisions to find out if they're all the same
1829 $authorOfAll = false;
1831 $authorOfAll = reset( $authors );
1832 foreach ( $authors as $author ) {
1833 if ( $authorOfAll != $author ) {
1834 $authorOfAll = false;
1839 # Fetch article text
1840 $rev = Revision
::newFromTitle( $this->mTitle
);
1842 if( !is_null( $rev ) ) {
1843 # if this is a mini-text, we can paste part of it into the deletion reason
1844 $text = $rev->getText();
1846 #if this is empty, an earlier revision may contain "useful" text
1849 $prev = $rev->getPrevious();
1851 $text = $prev->getText();
1856 $length = strlen( $text );
1858 # this should not happen, since it is not possible to store an empty, new
1859 # page. Let's insert a standard text in case it does, though
1860 if( $length == 0 && $reason === '' ) {
1861 $reason = wfMsgForContent( 'exblank' );
1864 if( $length < 500 && $reason === '' ) {
1865 # comment field=255, let's grep the first 150 to have some user
1868 $text = $wgContLang->truncate( $text, 150, '...' );
1870 # let's strip out newlines
1871 $text = preg_replace( "/[\n\r]/", '', $text );
1874 if( $authorOfAll === false ) {
1875 $reason = wfMsgForContent( 'excontent', $text );
1877 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1880 $reason = wfMsgForContent( 'exbeforeblank', $text );
1885 return $this->confirmDelete( '', $reason );
1889 * Get the last N authors
1890 * @param int $num Number of revisions to get
1891 * @param string $revLatest The latest rev_id, selected from the master (optional)
1892 * @return array Array of authors, duplicates not removed
1894 function getLastNAuthors( $num, $revLatest = 0 ) {
1895 $fname = 'Article::getLastNAuthors';
1896 wfProfileIn( $fname );
1898 // First try the slave
1899 // If that doesn't have the latest revision, try the master
1901 $db =& wfGetDB( DB_SLAVE
);
1903 $res = $db->select( array( 'page', 'revision' ),
1904 array( 'rev_id', 'rev_user_text' ),
1906 'page_namespace' => $this->mTitle
->getNamespace(),
1907 'page_title' => $this->mTitle
->getDBkey(),
1908 'rev_page = page_id'
1909 ), $fname, $this->getSelectOptions( array(
1910 'ORDER BY' => 'rev_timestamp DESC',
1915 wfProfileOut( $fname );
1918 $row = $db->fetchObject( $res );
1919 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1920 $db =& wfGetDB( DB_MASTER
);
1925 } while ( $continue );
1927 $authors = array( $row->rev_user_text
);
1928 while ( $row = $db->fetchObject( $res ) ) {
1929 $authors[] = $row->rev_user_text
;
1931 wfProfileOut( $fname );
1936 * Output deletion confirmation dialog
1938 function confirmDelete( $par, $reason ) {
1939 global $wgOut, $wgUser;
1941 wfDebug( "Article::confirmDelete\n" );
1943 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1944 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1945 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1946 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1948 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1950 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1951 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1952 $token = htmlspecialchars( $wgUser->editToken() );
1955 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1959 <label for='wpReason'>{$delcom}:</label>
1962 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1968 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1972 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1975 $wgOut->returnToMain( false );
1980 * Perform a deletion and output success or failure messages
1982 function doDelete( $reason ) {
1983 global $wgOut, $wgUser;
1984 $fname = 'Article::doDelete';
1985 wfDebug( $fname."\n" );
1987 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1988 if ( $this->doDeleteArticle( $reason ) ) {
1989 $deleted = $this->mTitle
->getPrefixedText();
1991 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1992 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1994 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1995 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1997 $wgOut->addWikiText( $text );
1998 $wgOut->returnToMain( false );
1999 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2001 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
2007 * Back-end article deletion
2008 * Deletes the article with database consistency, writes logs, purges caches
2011 function doDeleteArticle( $reason ) {
2012 global $wgUseSquid, $wgDeferredUpdateList;
2013 global $wgPostCommitUpdateList, $wgUseTrackbacks;
2015 $fname = 'Article::doDeleteArticle';
2016 wfDebug( $fname."\n" );
2018 $dbw =& wfGetDB( DB_MASTER
);
2019 $ns = $this->mTitle
->getNamespace();
2020 $t = $this->mTitle
->getDBkey();
2021 $id = $this->mTitle
->getArticleID();
2023 if ( $t == '' ||
$id == 0 ) {
2027 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2028 array_push( $wgDeferredUpdateList, $u );
2030 $linksTo = $this->mTitle
->getLinksTo();
2033 if ( $wgUseSquid ) {
2035 $this->mTitle
->getInternalURL(),
2036 $this->mTitle
->getInternalURL( 'history' )
2039 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
2040 array_push( $wgPostCommitUpdateList, $u );
2044 # Client and file cache invalidation
2045 Title
::touchArray( $linksTo );
2048 // For now, shunt the revision data into the archive table.
2049 // Text is *not* removed from the text table; bulk storage
2050 // is left intact to avoid breaking block-compression or
2051 // immutable storage schemes.
2053 // For backwards compatibility, note that some older archive
2054 // table entries will have ar_text and ar_flags fields still.
2056 // In the future, we may keep revisions and mark them with
2057 // the rev_deleted field, which is reserved for this purpose.
2058 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2060 'ar_namespace' => 'page_namespace',
2061 'ar_title' => 'page_title',
2062 'ar_comment' => 'rev_comment',
2063 'ar_user' => 'rev_user',
2064 'ar_user_text' => 'rev_user_text',
2065 'ar_timestamp' => 'rev_timestamp',
2066 'ar_minor_edit' => 'rev_minor_edit',
2067 'ar_rev_id' => 'rev_id',
2068 'ar_text_id' => 'rev_text_id',
2071 'page_id = rev_page'
2075 # Now that it's safely backed up, delete it
2076 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2077 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2079 if ($wgUseTrackbacks)
2080 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2082 # Clean up recentchanges entries...
2083 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2085 # Finally, clean up the link tables
2086 $t = $this->mTitle
->getPrefixedDBkey();
2088 Article
::onArticleDelete( $this->mTitle
);
2090 # Delete outgoing links
2091 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2092 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2093 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2094 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2095 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2096 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2099 $log = new LogPage( 'delete' );
2100 $log->addEntry( 'delete', $this->mTitle
, $reason );
2102 # Clear the cached article id so the interface doesn't act like we exist
2103 $this->mTitle
->resetArticleID( 0 );
2104 $this->mTitle
->mArticleID
= 0;
2109 * Revert a modification
2111 function rollback() {
2112 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2113 $fname = 'Article::rollback';
2115 if( $wgUser->isAllowed( 'rollback' ) ) {
2116 if( $wgUser->isBlocked() ) {
2117 $wgOut->blockedPage();
2121 $wgOut->permissionRequired( 'rollback' );
2125 if ( wfReadOnly() ) {
2126 $wgOut->readOnlyPage( $this->getContent() );
2129 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2130 array( $this->mTitle
->getPrefixedText(),
2131 $wgRequest->getVal( 'from' ) ) ) ) {
2132 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2133 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2136 $dbw =& wfGetDB( DB_MASTER
);
2138 # Enhanced rollback, marks edits rc_bot=1
2139 $bot = $wgRequest->getBool( 'bot' );
2141 # Replace all this user's current edits with the next one down
2142 $tt = $this->mTitle
->getDBKey();
2143 $n = $this->mTitle
->getNamespace();
2145 # Get the last editor, lock table exclusively
2147 $current = Revision
::newFromTitle( $this->mTitle
);
2148 if( is_null( $current ) ) {
2149 # Something wrong... no page?
2151 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2155 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2156 if( $from != $current->getUserText() ) {
2157 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2158 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2159 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2160 htmlspecialchars( $from ),
2161 htmlspecialchars( $current->getUserText() ) ) );
2162 if( $current->getComment() != '') {
2164 wfMsg( 'editcomment',
2165 htmlspecialchars( $current->getComment() ) ) );
2170 # Get the last edit not by this guy
2171 $user = intval( $current->getUser() );
2172 $user_text = $dbw->addQuotes( $current->getUserText() );
2173 $s = $dbw->selectRow( 'revision',
2174 array( 'rev_id', 'rev_timestamp' ),
2176 'rev_page' => $current->getPage(),
2177 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2180 'USE INDEX' => 'page_timestamp',
2181 'ORDER BY' => 'rev_timestamp DESC' )
2183 if( $s === false ) {
2186 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2187 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2193 # Mark all reverted edits as bot
2196 if ( $wgUseRCPatrol ) {
2197 # Mark all reverted edits as patrolled
2198 $set['rc_patrolled'] = 1;
2202 $dbw->update( 'recentchanges', $set,
2204 'rc_cur_id' => $current->getPage(),
2205 'rc_user_text' => $current->getUserText(),
2206 "rc_timestamp > '{$s->rev_timestamp}'",
2211 # Get the edit summary
2212 $target = Revision
::newFromId( $s->rev_id
);
2213 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2214 $newComment = $wgRequest->getText( 'summary', $newComment );
2217 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2218 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2219 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2221 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2222 Article
::onArticleEdit( $this->mTitle
);
2225 $wgOut->returnToMain( false );
2230 * Do standard deferred updates after page view
2233 function viewUpdates() {
2234 global $wgDeferredUpdateList;
2236 if ( 0 != $this->getID() ) {
2237 global $wgDisableCounters;
2238 if( !$wgDisableCounters ) {
2239 Article
::incViewCount( $this->getID() );
2240 $u = new SiteStatsUpdate( 1, 0, 0 );
2241 array_push( $wgDeferredUpdateList, $u );
2245 # Update newtalk / watchlist notification status
2247 $wgUser->clearNotification( $this->mTitle
);
2251 * Do standard deferred updates after page edit.
2252 * Every 1000th edit, prune the recent changes table.
2254 * @param string $text
2256 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2257 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2259 $fname = 'Article::editUpdates';
2260 wfProfileIn( $fname );
2263 $options = new ParserOptions
;
2264 $options->setTidy(true);
2265 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2267 # Save it to the parser cache
2268 $parserCache =& ParserCache
::singleton();
2269 $parserCache->save( $poutput, $this, $wgUser );
2271 # Update the links tables
2272 $u = new LinksUpdate( $this->mTitle
, $poutput );
2275 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2277 if ( 0 == mt_rand( 0, 999 ) ) {
2278 # Periodically flush old entries from the recentchanges table.
2281 $dbw =& wfGetDB( DB_MASTER
);
2282 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2283 $recentchanges = $dbw->tableName( 'recentchanges' );
2284 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2285 $dbw->query( $sql );
2289 $id = $this->getID();
2290 $title = $this->mTitle
->getPrefixedDBkey();
2291 $shortTitle = $this->mTitle
->getDBkey();
2294 wfProfileOut( $fname );
2298 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2299 array_push( $wgDeferredUpdateList, $u );
2300 $u = new SearchUpdate( $id, $title, $text );
2301 array_push( $wgDeferredUpdateList, $u );
2303 # If this is another user's talk page, update newtalk
2305 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
2306 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2307 $other = User
::newFromName( $shortTitle );
2308 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2309 // An anonymous user
2310 $other = new User();
2311 $other->setName( $shortTitle );
2314 $other->setNewtalk( true );
2319 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2320 $wgMessageCache->replace( $shortTitle, $text );
2323 wfProfileOut( $fname );
2327 * Generate the navigation links when browsing through an article revisions
2328 * It shows the information as:
2329 * Revision as of \<date\>; view current revision
2330 * \<- Previous version | Next Version -\>
2333 * @param string $oldid Revision ID of this article revision
2335 function setOldSubtitle( $oldid=0 ) {
2336 global $wgLang, $wgOut, $wgUser;
2338 $current = ( $oldid == $this->mLatest
);
2339 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2340 $sk = $wgUser->getSkin();
2342 ?
wfMsg( 'currentrevisionlink' )
2343 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2344 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2346 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2347 : wfMsg( 'previousrevision' );
2348 $nextlink = $current
2349 ?
wfMsg( 'nextrevision' )
2350 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2351 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2352 $wgOut->setSubtitle( $r );
2356 * This function is called right before saving the wikitext,
2357 * so we can do things like signatures and links-in-context.
2359 * @param string $text
2361 function preSaveTransform( $text ) {
2362 global $wgParser, $wgUser;
2363 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2366 /* Caching functions */
2369 * checkLastModified returns true if it has taken care of all
2370 * output to the client that is necessary for this request.
2371 * (that is, it has sent a cached version of the page)
2373 function tryFileCache() {
2374 static $called = false;
2376 wfDebug( " tryFileCache() -- called twice!?\n" );
2380 if($this->isFileCacheable()) {
2381 $touched = $this->mTouched
;
2382 $cache = new CacheManager( $this->mTitle
);
2383 if($cache->isFileCacheGood( $touched )) {
2384 wfDebug( " tryFileCache() - about to load\n" );
2385 $cache->loadFromFileCache();
2388 wfDebug( " tryFileCache() - starting buffer\n" );
2389 ob_start( array(&$cache, 'saveToFileCache' ) );
2392 wfDebug( " tryFileCache() - not cacheable\n" );
2397 * Check if the page can be cached
2400 function isFileCacheable() {
2401 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2402 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2404 return $wgUseFileCache
2405 and (!$wgShowIPinHeader)
2406 and ($this->getID() != 0)
2407 and ($wgUser->isAnon())
2408 and (!$wgUser->getNewtalk())
2409 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2410 and (empty( $action ) ||
$action == 'view')
2411 and (!isset($oldid))
2413 and (!isset($redirect))
2414 and (!isset($printable))
2415 and (!$this->mRedirectedFrom
);
2419 * Loads page_touched and returns a value indicating if it should be used
2422 function checkTouched() {
2423 $fname = 'Article::checkTouched';
2424 if( !$this->mDataLoaded
) {
2425 $this->loadPageData();
2427 return !$this->mIsRedirect
;
2431 * Get the page_touched field
2433 function getTouched() {
2434 # Ensure that page data has been loaded
2435 if( !$this->mDataLoaded
) {
2436 $this->loadPageData();
2438 return $this->mTouched
;
2442 * Get the page_latest field
2444 function getLatest() {
2445 if ( !$this->mDataLoaded
) {
2446 $this->loadPageData();
2448 return $this->mLatest
;
2452 * Edit an article without doing all that other stuff
2453 * The article must already exist; link tables etc
2454 * are not updated, caches are not flushed.
2456 * @param string $text text submitted
2457 * @param string $comment comment submitted
2458 * @param bool $minor whereas it's a minor modification
2460 function quickEdit( $text, $comment = '', $minor = 0 ) {
2461 $fname = 'Article::quickEdit';
2462 wfProfileIn( $fname );
2464 $dbw =& wfGetDB( DB_MASTER
);
2466 $revision = new Revision( array(
2467 'page' => $this->getId(),
2469 'comment' => $comment,
2470 'minor_edit' => $minor ?
1 : 0,
2472 # fixme : $revisionId never used
2473 $revisionId = $revision->insertOn( $dbw );
2474 $this->updateRevisionOn( $dbw, $revision );
2477 wfProfileOut( $fname );
2481 * Used to increment the view counter
2484 * @param integer $id article id
2486 function incViewCount( $id ) {
2487 $id = intval( $id );
2488 global $wgHitcounterUpdateFreq, $wgDBtype;
2490 $dbw =& wfGetDB( DB_MASTER
);
2491 $pageTable = $dbw->tableName( 'page' );
2492 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2493 $acchitsTable = $dbw->tableName( 'acchits' );
2495 if( $wgHitcounterUpdateFreq <= 1 ){ //
2496 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2500 # Not important enough to warrant an error page in case of failure
2501 $oldignore = $dbw->ignoreErrors( true );
2503 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2505 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2506 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2507 # Most of the time (or on SQL errors), skip row count check
2508 $dbw->ignoreErrors( $oldignore );
2512 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2513 $row = $dbw->fetchObject( $res );
2514 $rown = intval( $row->n
);
2515 if( $rown >= $wgHitcounterUpdateFreq ){
2516 wfProfileIn( 'Article::incViewCount-collect' );
2517 $old_user_abort = ignore_user_abort( true );
2519 if ($wgDBtype == 'mysql')
2520 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2521 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2522 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2523 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2525 $dbw->query("DELETE FROM $hitcounterTable");
2526 if ($wgDBtype == 'mysql')
2527 $dbw->query('UNLOCK TABLES');
2528 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2529 'WHERE page_id = hc_id');
2530 $dbw->query("DROP TABLE $acchitsTable");
2532 ignore_user_abort( $old_user_abort );
2533 wfProfileOut( 'Article::incViewCount-collect' );
2535 $dbw->ignoreErrors( $oldignore );
2539 * The onArticle*() functions are supposed to be a kind of hooks
2540 * which should be called whenever any of the specified actions
2543 * This is a good place to put code to clear caches, for instance.
2545 * This is called on page move and undelete, as well as edit
2547 * @param $title_obj a title object
2550 function onArticleCreate($title_obj) {
2551 global $wgUseSquid, $wgPostCommitUpdateList;
2553 $title_obj->touchLinks();
2554 $titles = $title_obj->getLinksTo();
2557 if ( $wgUseSquid ) {
2558 $urls = $title_obj->getSquidURLs();
2559 foreach ( $titles as $linkTitle ) {
2560 $urls[] = $linkTitle->getInternalURL();
2562 $u = new SquidUpdate( $urls );
2563 array_push( $wgPostCommitUpdateList, $u );
2567 function onArticleDelete( $title ) {
2568 global $wgMessageCache;
2570 $title->touchLinks();
2572 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2573 $wgMessageCache->replace( $title->getDBkey(), false );
2578 * Purge caches on page update etc
2580 function onArticleEdit( $title ) {
2581 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2585 // Template namespace? Purge all articles linking here.
2586 // FIXME: When a templatelinks table arrives, use it for all includes.
2587 if ( $title->getNamespace() == NS_TEMPLATE
) {
2588 $titles = $title->getLinksTo();
2589 Title
::touchArray( $titles );
2590 if ( $wgUseSquid ) {
2591 foreach ( $titles as $link ) {
2592 $urls[] = $link->getInternalURL();
2598 if ( $wgUseSquid ) {
2599 $urls = array_merge( $urls, $title->getSquidURLs() );
2600 $u = new SquidUpdate( $urls );
2601 array_push( $wgPostCommitUpdateList, $u );
2605 if ( $wgUseFileCache ) {
2606 $cm = new CacheManager( $title );
2607 @unlink
( $cm->fileCacheName() );
2614 * Info about this page
2615 * Called for ?action=info when $wgAllowPageInfo is on.
2620 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2621 $fname = 'Article::info';
2623 if ( !$wgAllowPageInfo ) {
2624 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2628 $page = $this->mTitle
->getSubjectPage();
2630 $wgOut->setPagetitle( $page->getPrefixedText() );
2631 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2633 # first, see if the page exists at all.
2634 $exists = $page->getArticleId() != 0;
2636 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2637 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2639 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2642 $dbr =& wfGetDB( DB_SLAVE
);
2644 'wl_title' => $page->getDBkey(),
2645 'wl_namespace' => $page->getNamespace() );
2646 $numwatchers = $dbr->selectField(
2651 $this->getSelectOptions() );
2653 $pageInfo = $this->pageCountInfo( $page );
2654 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2656 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2657 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2659 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2661 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2663 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2665 $wgOut->addHTML( '</ul>' );
2671 * Return the total number of edits and number of unique editors
2672 * on a given page. If page does not exist, returns false.
2674 * @param Title $title
2678 function pageCountInfo( $title ) {
2679 $id = $title->getArticleId();
2684 $dbr =& wfGetDB( DB_SLAVE
);
2686 $rev_clause = array( 'rev_page' => $id );
2687 $fname = 'Article::pageCountInfo';
2689 $edits = $dbr->selectField(
2694 $this->getSelectOptions() );
2696 $authors = $dbr->selectField(
2698 'COUNT(DISTINCT rev_user_text)',
2701 $this->getSelectOptions() );
2703 return array( 'edits' => $edits, 'authors' => $authors );
2707 * Return a list of templates used by this article.
2708 * Uses the templatelinks table
2710 * @return array Array of Title objects
2712 function getUsedTemplates() {
2714 $id = $this->mTitle
->getArticleID();
2719 $dbr =& wfGetDB( DB_SLAVE
);
2720 $res = $dbr->select( array( 'templatelinks' ),
2721 array( 'tl_namespace', 'tl_title' ),
2722 array( 'tl_from' => $id ),
2723 'Article:getUsedTemplates' );
2724 if ( false !== $res ) {
2725 if ( $dbr->numRows( $res ) ) {
2726 while ( $row = $dbr->fetchObject( $res ) ) {
2727 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2731 $dbr->freeResult( $res );