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 if ( is_object( $this->mTitle
) ) {
441 $lc->addBadLinkObj( $this->mTitle
);
443 $this->mTitle
->mArticleID
= 0;
446 $this->mDataLoaded
= true;
450 * Get text of an article from database
451 * Does *NOT* follow redirects.
452 * @param int $oldid 0 for whatever the latest revision is
455 function fetchContent( $oldid = 0 ) {
456 if ( $this->mContentLoaded
) {
457 return $this->mContent
;
460 $dbr =& $this->getDB();
461 $fname = 'Article::fetchContent';
463 # Pre-fill content with error message so that if something
464 # fails we'll have something telling us what we intended.
465 $t = $this->mTitle
->getPrefixedText();
467 $t .= ',oldid='.$oldid;
469 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
472 $revision = Revision
::newFromId( $oldid );
473 if( is_null( $revision ) ) {
474 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
477 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
479 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
482 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
483 $this->loadPageData( $data );
485 if( !$this->mDataLoaded
) {
486 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
488 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
491 $this->loadPageData( $data );
493 $revision = Revision
::newFromId( $this->mLatest
);
494 if( is_null( $revision ) ) {
495 wfDebug( "$fname failed to retrieve current page, rev_id {$data->page_latest}\n" );
500 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
501 // We should instead work with the Revision object when we need it...
502 $this->mContent
= $revision->userCan( MW_REV_DELETED_TEXT
) ?
$revision->getRawText() : "";
503 //$this->mContent = $revision->getText();
505 $this->mUser
= $revision->getUser();
506 $this->mUserText
= $revision->getUserText();
507 $this->mComment
= $revision->getComment();
508 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
510 $this->mRevIdFetched
= $revision->getID();
511 $this->mContentLoaded
= true;
512 $this->mRevision
=& $revision;
514 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
516 return $this->mContent
;
520 * Read/write accessor to select FOR UPDATE
524 function forUpdate( $x = NULL ) {
525 return wfSetVar( $this->mForUpdate
, $x );
529 * Get the database which should be used for reads
534 $ret =& wfGetDB( DB_MASTER
);
539 * Get options for all SELECT statements
541 * @param array $options an optional options array which'll be appended to
543 * @return array Options
545 function getSelectOptions( $options = '' ) {
546 if ( $this->mForUpdate
) {
547 if ( is_array( $options ) ) {
548 $options[] = 'FOR UPDATE';
550 $options = 'FOR UPDATE';
557 * @return int Page ID
560 if( $this->mTitle
) {
561 return $this->mTitle
->getArticleID();
568 * @return bool Whether or not the page exists in the database
571 return $this->getId() != 0;
575 * @return int The view count for the page
577 function getCount() {
578 if ( -1 == $this->mCounter
) {
579 $id = $this->getID();
583 $dbr =& wfGetDB( DB_SLAVE
);
584 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
585 'Article::getCount', $this->getSelectOptions() );
588 return $this->mCounter
;
592 * Determine whether a page would be suitable for being counted as an
593 * article in the site_stats table based on the title & its content
595 * @param string $text Text to analyze
598 function isCountable( $text ) {
599 global $wgUseCommaCount;
601 $token = $wgUseCommaCount ?
',' : '[[';
603 $this->mTitle
->getNamespace() == NS_MAIN
604 && ! $this->isRedirect( $text )
605 && in_string( $token, $text );
609 * Tests if the article text represents a redirect
611 * @param string $text
614 function isRedirect( $text = false ) {
615 if ( $text === false ) {
616 $this->loadContent();
617 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
619 $titleObj = Title
::newFromRedirect( $text );
621 return $titleObj !== NULL;
625 * Returns true if the currently-referenced revision is the current edit
626 * to this page (and it exists).
629 function isCurrent() {
630 return $this->exists() &&
631 isset( $this->mRevision
) &&
632 $this->mRevision
->isCurrent();
636 * Loads everything except the text
637 * This isn't necessary for all uses, so it's only done if needed.
640 function loadLastEdit() {
641 if ( -1 != $this->mUser
)
644 # New or non-existent articles have no user information
645 $id = $this->getID();
646 if ( 0 == $id ) return;
648 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
649 if( !is_null( $this->mLastRevision
) ) {
650 $this->mUser
= $this->mLastRevision
->getUser();
651 $this->mUserText
= $this->mLastRevision
->getUserText();
652 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
653 $this->mComment
= $this->mLastRevision
->getComment();
654 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
655 $this->mRevIdFetched
= $this->mLastRevision
->getID();
659 function getTimestamp() {
660 // Check if the field has been filled by ParserCache::get()
661 if ( !$this->mTimestamp
) {
662 $this->loadLastEdit();
664 return wfTimestamp(TS_MW
, $this->mTimestamp
);
668 $this->loadLastEdit();
672 function getUserText() {
673 $this->loadLastEdit();
674 return $this->mUserText
;
677 function getComment() {
678 $this->loadLastEdit();
679 return $this->mComment
;
682 function getMinorEdit() {
683 $this->loadLastEdit();
684 return $this->mMinorEdit
;
687 function getRevIdFetched() {
688 $this->loadLastEdit();
689 return $this->mRevIdFetched
;
692 function getContributors($limit = 0, $offset = 0) {
693 $fname = 'Article::getContributors';
695 # XXX: this is expensive; cache this info somewhere.
697 $title = $this->mTitle
;
699 $dbr =& wfGetDB( DB_SLAVE
);
700 $revTable = $dbr->tableName( 'revision' );
701 $userTable = $dbr->tableName( 'user' );
702 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
703 $ns = $title->getNamespace();
704 $user = $this->getUser();
705 $pageId = $this->getId();
707 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
708 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
709 WHERE rev_page = $pageId
710 AND rev_user != $user
711 GROUP BY rev_user, rev_user_text, user_real_name
712 ORDER BY timestamp DESC";
714 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
715 $sql .= ' '. $this->getSelectOptions();
717 $res = $dbr->query($sql, $fname);
719 while ( $line = $dbr->fetchObject( $res ) ) {
720 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
723 $dbr->freeResult($res);
728 * This is the default action of the script: just view the page of
732 global $wgUser, $wgOut, $wgRequest, $wgContLang;
733 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
734 global $wgUseTrackbacks;
735 $sk = $wgUser->getSkin();
737 $fname = 'Article::view';
738 wfProfileIn( $fname );
739 $parserCache =& ParserCache
::singleton();
740 # Get variables from query string
741 $oldid = $this->getOldID();
743 # getOldID may want us to redirect somewhere else
744 if ( $this->mRedirectUrl
) {
745 $wgOut->redirect( $this->mRedirectUrl
);
746 wfProfileOut( $fname );
750 $diff = $wgRequest->getVal( 'diff' );
751 $rcid = $wgRequest->getVal( 'rcid' );
752 $rdfrom = $wgRequest->getVal( 'rdfrom' );
754 $wgOut->setArticleFlag( true );
755 $wgOut->setRobotpolicy( 'index,follow' );
756 # If we got diff and oldid in the query, we want to see a
757 # diff page instead of the article.
759 if ( !is_null( $diff ) ) {
760 require_once( 'DifferenceEngine.php' );
761 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
763 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
764 // DifferenceEngine directly fetched the revision:
765 $this->mRevIdFetched
= $de->mNewid
;
769 # Run view updates for current revision only
770 $this->viewUpdates();
772 wfProfileOut( $fname );
776 if ( empty( $oldid ) && $this->checkTouched() ) {
777 $wgOut->setETag($parserCache->getETag($this, $wgUser));
779 if( $wgOut->checkLastModified( $this->mTouched
) ){
780 wfProfileOut( $fname );
782 } else if ( $this->tryFileCache() ) {
783 # tell wgOut that output is taken care of
785 $this->viewUpdates();
786 wfProfileOut( $fname );
790 # Should the parser cache be used?
791 $pcache = $wgEnableParserCache &&
792 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
795 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
796 if ( $wgUser->getOption( 'stubthreshold' ) ) {
797 wfIncrStats( 'pcache_miss_stub' );
800 $wasRedirected = false;
801 if ( isset( $this->mRedirectedFrom
) ) {
802 // This is an internally redirected page view.
803 // We'll need a backlink to the source page for navigation.
804 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
805 $sk = $wgUser->getSkin();
806 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
807 $s = wfMsg( 'redirectedfrom', $redir );
808 $wgOut->setSubtitle( $s );
809 $wasRedirected = true;
811 } elseif ( !empty( $rdfrom ) ) {
812 // This is an externally redirected view, from some other wiki.
813 // If it was reported from a trusted site, supply a backlink.
814 global $wgRedirectSources;
815 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
816 $sk = $wgUser->getSkin();
817 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
818 $s = wfMsg( 'redirectedfrom', $redir );
819 $wgOut->setSubtitle( $s );
820 $wasRedirected = true;
826 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
830 if ( !$outputDone ) {
831 $text = $this->getContent();
832 if ( $text === false ) {
833 # Failed to load, replace text with error message
834 $t = $this->mTitle
->getPrefixedText();
836 $t .= ',oldid='.$oldid;
837 $text = wfMsg( 'missingarticle', $t );
839 $text = wfMsg( 'noarticletext', $t );
843 # Another whitelist check in case oldid is altering the title
844 if ( !$this->mTitle
->userCanRead() ) {
845 $wgOut->loginToUse();
850 # We're looking at an old revision
852 if ( !empty( $oldid ) ) {
853 $wgOut->setRobotpolicy( 'noindex,nofollow' );
854 if( is_null( $this->mRevision
) ) {
855 // FIXME: This would be a nice place to load the 'no such page' text.
857 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
858 if( $this->mRevision
->isDeleted( MW_REV_DELETED_TEXT
) ) {
859 if( !$this->mRevision
->userCan( MW_REV_DELETED_TEXT
) ) {
860 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
861 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
864 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
865 // and we are allowed to see...
874 * @fixme: this hook doesn't work most of the time, as it doesn't
875 * trigger when the parser cache is used.
877 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
878 $wgOut->setRevisionId( $this->getRevIdFetched() );
879 # wrap user css and user js in pre and don't parse
880 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
882 $this->mTitle
->getNamespace() == NS_USER
&&
883 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
885 $wgOut->addWikiText( wfMsg('clearyourcache'));
886 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
887 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
889 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
890 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
891 if( !$wasRedirected ) {
892 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
894 $targetUrl = $rt->escapeLocalURL();
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 # If we have been passed an &rcid= parameter, we want to give the user a
928 # chance to mark this new article as patrolled.
929 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
931 "<div class='patrollink'>" .
932 wfMsg ( 'markaspatrolledlink',
933 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
940 if ($wgUseTrackbacks)
941 $this->addTrackbacks();
943 $this->viewUpdates();
944 wfProfileOut( $fname );
947 function addTrackbacks() {
948 global $wgOut, $wgUser;
950 $dbr =& wfGetDB(DB_SLAVE
);
952 /* FROM */ 'trackbacks',
953 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
954 /* WHERE */ array('tb_page' => $this->getID())
957 if (!$dbr->numrows($tbs))
961 while ($o = $dbr->fetchObject($tbs)) {
963 if ($wgUser->isSysop()) {
964 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
965 . $o->tb_id
. "&token=" . $wgUser->editToken());
966 $rmvtxt = wfMsg('trackbackremove', $delurl);
968 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
975 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
978 function deletetrackback() {
979 global $wgUser, $wgRequest, $wgOut, $wgTitle;
981 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
982 $wgOut->addWikitext(wfMsg('sessionfailure'));
986 if ((!$wgUser->isAllowed('delete'))) {
987 $wgOut->sysopRequired();
992 $wgOut->readOnlyPage();
996 $db =& wfGetDB(DB_MASTER
);
997 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
998 $wgTitle->invalidateCache();
999 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
1005 $wgOut->setArticleBodyOnly(true);
1010 * Handle action=purge
1013 global $wgUser, $wgRequest, $wgOut;
1015 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
1016 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1020 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1021 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
1022 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1023 $msg = str_replace( '$1',
1024 "<form method=\"post\" action=\"$action\">\n" .
1025 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1026 "</form>\n", $msg );
1028 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1029 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1030 $wgOut->addHTML( $msg );
1035 * Perform the actions of a page purging
1037 function doPurge() {
1039 // Invalidate the cache
1040 $this->mTitle
->invalidateCache();
1042 if ( $wgUseSquid ) {
1043 // Commit the transaction before the purge is sent
1044 $dbw = wfGetDB( DB_MASTER
);
1045 $dbw->immediateCommit();
1048 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1049 $update->doUpdate();
1055 * Insert a new empty page record for this article.
1056 * This *must* be followed up by creating a revision
1057 * and running $this->updateToLatest( $rev_id );
1058 * or else the record will be left in a funky state.
1059 * Best if all done inside a transaction.
1061 * @param Database $dbw
1062 * @param string $restrictions
1063 * @return int The newly created page_id key
1066 function insertOn( &$dbw, $restrictions = '' ) {
1067 $fname = 'Article::insertOn';
1068 wfProfileIn( $fname );
1070 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1071 $dbw->insert( 'page', array(
1072 'page_id' => $page_id,
1073 'page_namespace' => $this->mTitle
->getNamespace(),
1074 'page_title' => $this->mTitle
->getDBkey(),
1075 'page_counter' => 0,
1076 'page_restrictions' => $restrictions,
1077 'page_is_redirect' => 0, # Will set this shortly...
1079 'page_random' => wfRandom(),
1080 'page_touched' => $dbw->timestamp(),
1081 'page_latest' => 0, # Fill this in shortly...
1082 'page_len' => 0, # Fill this in shortly...
1084 $newid = $dbw->insertId();
1086 $this->mTitle
->resetArticleId( $newid );
1088 wfProfileOut( $fname );
1093 * Update the page record to point to a newly saved revision.
1095 * @param Database $dbw
1096 * @param Revision $revision For ID number, and text used to set
1097 length and redirect status fields
1098 * @param int $lastRevision If given, will not overwrite the page field
1099 * when different from the currently set value.
1100 * Giving 0 indicates the new page flag should
1102 * @return bool true on success, false on failure
1105 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1106 $fname = 'Article::updateToRevision';
1107 wfProfileIn( $fname );
1109 $conditions = array( 'page_id' => $this->getId() );
1110 if( !is_null( $lastRevision ) ) {
1111 # An extra check against threads stepping on each other
1112 $conditions['page_latest'] = $lastRevision;
1115 $text = $revision->getText();
1116 $dbw->update( 'page',
1118 'page_latest' => $revision->getId(),
1119 'page_touched' => $dbw->timestamp(),
1120 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1121 'page_is_redirect' => Article
::isRedirect( $text ) ?
1 : 0,
1122 'page_len' => strlen( $text ),
1127 wfProfileOut( $fname );
1128 return ( $dbw->affectedRows() != 0 );
1132 * If the given revision is newer than the currently set page_latest,
1133 * update the page record. Otherwise, do nothing.
1135 * @param Database $dbw
1136 * @param Revision $revision
1138 function updateIfNewerOn( &$dbw, $revision ) {
1139 $fname = 'Article::updateIfNewerOn';
1140 wfProfileIn( $fname );
1142 $row = $dbw->selectRow(
1143 array( 'revision', 'page' ),
1144 array( 'rev_id', 'rev_timestamp' ),
1146 'page_id' => $this->getId(),
1147 'page_latest=rev_id' ),
1150 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1151 wfProfileOut( $fname );
1154 $prev = $row->rev_id
;
1156 # No or missing previous revision; mark the page as new
1160 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1161 wfProfileOut( $fname );
1166 * Insert a new article into the database
1169 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1172 $fname = 'Article::insertNewArticle';
1173 wfProfileIn( $fname );
1175 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1176 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1177 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1178 wfProfileOut( $fname );
1182 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1183 $this->mTotalAdjustment
= 1;
1185 $ns = $this->mTitle
->getNamespace();
1186 $ttl = $this->mTitle
->getDBkey();
1188 # If this is a comment, add the summary as headline
1189 if($comment && $summary!="") {
1190 $text="== {$summary} ==\n\n".$text;
1192 $text = $this->preSaveTransform( $text );
1194 /* Silently ignore minoredit if not allowed */
1195 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1196 $now = wfTimestampNow();
1198 $dbw =& wfGetDB( DB_MASTER
);
1200 # Add the page record; stake our claim on this title!
1201 $newid = $this->insertOn( $dbw );
1203 # Save the revision text...
1204 $revision = new Revision( array(
1206 'comment' => $summary,
1207 'minor_edit' => $isminor,
1210 $revisionId = $revision->insertOn( $dbw );
1212 $this->mTitle
->resetArticleID( $newid );
1214 # Update the page record with revision data
1215 $this->updateRevisionOn( $dbw, $revision, 0 );
1217 Article
::onArticleCreate( $this->mTitle
);
1219 require_once( 'RecentChange.php' );
1220 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, 'default',
1221 '', strlen( $text ), $revisionId );
1222 # Mark as patrolled if the user can and has the option set
1223 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1224 RecentChange
::markPatrolled( $rcid );
1229 if(!$this->mTitle
->userIsWatching()) $this->doWatch();
1231 if ( $this->mTitle
->userIsWatching() ) {
1236 # The talk page isn't in the regular link tables, so we need to update manually:
1237 $talkns = $ns ^
1; # talk -> normal; normal -> talk
1238 $dbw->update( 'page',
1239 array( 'page_touched' => $dbw->timestamp($now) ),
1240 array( 'page_namespace' => $talkns,
1241 'page_title' => $ttl ),
1244 # standard deferred updates
1245 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1247 $oldid = 0; # new article
1248 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1250 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1252 $watchthis, NULL ) );
1253 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1255 $watchthis, NULL ) );
1256 wfProfileOut( $fname );
1259 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1260 $this->replaceSection( $section, $text, $summary, $edittime );
1264 * @return string Complete article text, or null if error
1266 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1267 $fname = 'Article::replaceSection';
1268 wfProfileIn( $fname );
1270 if ($section != '') {
1271 if( is_null( $edittime ) ) {
1272 $rev = Revision
::newFromTitle( $this->mTitle
);
1274 $dbw =& wfGetDB( DB_MASTER
);
1275 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1277 if( is_null( $rev ) ) {
1278 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1279 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1282 $oldtext = $rev->getText();
1284 if($section=='new') {
1285 if($summary) $subject="== {$summary} ==\n\n";
1286 $text=$oldtext."\n\n".$subject.$text;
1289 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1290 # comments to be stripped as well)
1291 $striparray=array();
1292 $parser=new Parser();
1293 $parser->mOutputType
=OT_WIKI
;
1294 $parser->mOptions
= new ParserOptions();
1295 $oldtext=$parser->strip($oldtext, $striparray, true);
1297 # now that we can be sure that no pseudo-sections are in the source,
1299 # Unfortunately we can't simply do a preg_replace because that might
1300 # replace the wrong section, so we have to use the section counter instead
1301 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1302 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1303 $secs[$section*2]=$text."\n\n"; // replace with edited
1305 # section 0 is top (intro) section
1308 # headline of old section - we need to go through this section
1309 # to determine if there are any subsections that now need to
1310 # be erased, as the mother section has been replaced with
1311 # the text of all subsections.
1312 $headline=$secs[$section*2-1];
1313 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1314 $hlevel=$matches[1];
1316 # determine headline level for wikimarkup headings
1317 if(strpos($hlevel,'=')!==false) {
1318 $hlevel=strlen($hlevel);
1321 $secs[$section*2-1]=''; // erase old headline
1324 while(!empty($secs[$count*2-1]) && !$break) {
1326 $subheadline=$secs[$count*2-1];
1328 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1329 $subhlevel=$matches[1];
1330 if(strpos($subhlevel,'=')!==false) {
1331 $subhlevel=strlen($subhlevel);
1333 if($subhlevel > $hlevel) {
1334 // erase old subsections
1335 $secs[$count*2-1]='';
1338 if($subhlevel <= $hlevel) {
1346 $text=join('',$secs);
1347 # reinsert the stuff that we stripped out earlier
1348 $text=$parser->unstrip($text,$striparray);
1349 $text=$parser->unstripNoWiki($text,$striparray);
1353 wfProfileOut( $fname );
1358 * Change an existing article. Puts the previous version back into the old table, updates RC
1359 * and all necessary caches, mostly via the deferred update array.
1361 * It is possible to call this function from a command-line script, but note that you should
1362 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1364 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1365 global $wgUser, $wgDBtransactions, $wgUseSquid;
1366 global $wgPostCommitUpdateList, $wgUseFileCache;
1368 $fname = 'Article::updateArticle';
1369 wfProfileIn( $fname );
1372 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1374 &$watchthis, &$sectionanchor ) ) ) {
1375 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1376 wfProfileOut( $fname );
1380 $isminor = $minor && $wgUser->isAllowed('minoredit');
1381 $redir = (int)$this->isRedirect( $text );
1383 $text = $this->preSaveTransform( $text );
1384 $dbw =& wfGetDB( DB_MASTER
);
1385 $now = wfTimestampNow();
1387 # Update article, but only if changed.
1389 # It's important that we either rollback or complete, otherwise an attacker could
1390 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1391 # could conceivably have the same effect, especially if cur is locked for long periods.
1392 if( !$wgDBtransactions ) {
1393 $userAbort = ignore_user_abort( true );
1396 $oldtext = $this->getContent();
1397 $oldsize = strlen( $oldtext );
1398 $newsize = strlen( $text );
1402 if ( 0 != strcmp( $text, $oldtext ) ) {
1403 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1404 - (int)$this->isCountable( $oldtext );
1405 $this->mTotalAdjustment
= 0;
1406 $now = wfTimestampNow();
1408 $lastRevision = $dbw->selectField(
1409 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1411 $revision = new Revision( array(
1412 'page' => $this->getId(),
1413 'comment' => $summary,
1414 'minor_edit' => $isminor,
1418 $dbw->immediateCommit();
1420 $revisionId = $revision->insertOn( $dbw );
1423 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1426 /* Belated edit conflict! Run away!! */
1430 # Update recentchanges and purge cache and whatnot
1431 require_once( 'RecentChange.php' );
1432 $bot = (int)($wgUser->isBot() ||
$forceBot);
1433 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1434 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1437 # Mark as patrolled if the user can do so and has it set in their options
1438 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1439 RecentChange
::markPatrolled( $rcid );
1444 // Update caches outside the main transaction
1445 Article
::onArticleEdit( $this->mTitle
);
1448 // Keep the same revision ID, but do some updates on it
1449 $revisionId = $this->getRevIdFetched();
1452 if( !$wgDBtransactions ) {
1453 ignore_user_abort( $userAbort );
1458 if (!$this->mTitle
->userIsWatching()) {
1459 $dbw->immediateCommit();
1465 if ( $this->mTitle
->userIsWatching() ) {
1466 $dbw->immediateCommit();
1472 # standard deferred updates
1473 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1477 # Invalidate caches of all articles using this article as a template
1479 # Template namespace
1480 # Purge all articles linking here
1481 $titles = $this->mTitle
->getTemplateLinksTo();
1482 Title
::touchArray( $titles );
1483 if ( $wgUseSquid ) {
1484 foreach ( $titles as $title ) {
1485 $urls[] = $title->getInternalURL();
1490 if ( $wgUseSquid ) {
1491 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1492 $u = new SquidUpdate( $urls );
1493 array_push( $wgPostCommitUpdateList, $u );
1497 if ( $wgUseFileCache ) {
1498 $cm = new CacheManager($this->mTitle
);
1499 @unlink
($cm->fileCacheName());
1502 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1504 wfRunHooks( 'ArticleSaveComplete',
1505 array( &$this, &$wgUser, $text,
1507 $watchthis, $sectionanchor ) );
1508 wfProfileOut( $fname );
1513 * After we've either updated or inserted the article, update
1514 * the link tables and redirect to the new page.
1516 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1519 $fname = 'Article::showArticle';
1520 wfProfileIn( $fname );
1522 # Output the redirect
1523 if( $this->isRedirect( $text ) )
1527 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1529 wfProfileOut( $fname );
1533 * Mark this particular edit as patrolled
1535 function markpatrolled() {
1536 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1537 $wgOut->setRobotpolicy( 'noindex,follow' );
1539 # Check RC patrol config. option
1540 if( !$wgUseRCPatrol ) {
1541 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1546 if( !$wgUser->isAllowed( 'patrol' ) ) {
1547 $wgOut->permissionRequired( 'patrol' );
1551 $rcid = $wgRequest->getVal( 'rcid' );
1552 if ( !is_null ( $rcid ) ) {
1553 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1554 require_once( 'RecentChange.php' );
1555 RecentChange
::markPatrolled( $rcid );
1556 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1557 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1558 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1560 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1561 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1564 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1569 * User-interface handler for the "watch" action
1574 global $wgUser, $wgOut;
1576 if ( $wgUser->isAnon() ) {
1577 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1580 if ( wfReadOnly() ) {
1581 $wgOut->readOnlyPage();
1585 if( $this->doWatch() ) {
1586 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1587 $wgOut->setRobotpolicy( 'noindex,follow' );
1589 $link = $this->mTitle
->getPrefixedText();
1590 $text = wfMsg( 'addedwatchtext', $link );
1591 $wgOut->addWikiText( $text );
1594 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1598 * Add this page to $wgUser's watchlist
1599 * @return bool true on successful watch operation
1601 function doWatch() {
1603 if( $wgUser->isAnon() ) {
1607 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1608 $wgUser->addWatch( $this->mTitle
);
1609 $wgUser->saveSettings();
1611 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1618 * User interface handler for the "unwatch" action.
1620 function unwatch() {
1622 global $wgUser, $wgOut;
1624 if ( $wgUser->isAnon() ) {
1625 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1628 if ( wfReadOnly() ) {
1629 $wgOut->readOnlyPage();
1633 if( $this->doUnwatch() ) {
1634 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1635 $wgOut->setRobotpolicy( 'noindex,follow' );
1637 $link = $this->mTitle
->getPrefixedText();
1638 $text = wfMsg( 'removedwatchtext', $link );
1639 $wgOut->addWikiText( $text );
1642 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1646 * Stop watching a page
1647 * @return bool true on successful unwatch
1649 function doUnwatch() {
1651 if( $wgUser->isAnon() ) {
1655 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1656 $wgUser->removeWatch( $this->mTitle
);
1657 $wgUser->saveSettings();
1659 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1666 * action=protect handler
1668 function protect() {
1669 require_once 'ProtectionForm.php';
1670 $form = new ProtectionForm( $this );
1675 * action=unprotect handler (alias)
1677 function unprotect() {
1682 * Update the article's restriction field, and leave a log entry.
1684 * @param array $limit set of restriction keys
1685 * @param string $reason
1686 * @return bool true on success
1688 function updateRestrictions( $limit = array(), $reason = '' ) {
1691 if ( !$wgUser->isAllowed( 'protect' ) ) {
1695 if( wfReadOnly() ) {
1699 $id = $this->mTitle
->getArticleID();
1704 $flat = Article
::flattenRestrictions( $limit );
1705 $protecting = ($flat != '');
1707 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser,
1708 $limit, $reason ) ) ) {
1710 $dbw =& wfGetDB( DB_MASTER
);
1711 $dbw->update( 'page',
1713 'page_touched' => $dbw->timestamp(),
1714 'page_restrictions' => $flat
1715 ), array( /* WHERE */
1717 ), 'Article::protect'
1720 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser,
1721 $limit, $reason ) );
1723 $log = new LogPage( 'protect' );
1725 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$flat]" ) );
1727 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1734 * Take an array of page restrictions and flatten it to a string
1735 * suitable for insertion into the page_restrictions field.
1736 * @param array $limit
1740 function flattenRestrictions( $limit ) {
1741 if( !is_array( $limit ) ) {
1742 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1745 foreach( $limit as $action => $restrictions ) {
1746 if( $restrictions != '' ) {
1747 $bits[] = "$action=$restrictions";
1750 return implode( ':', $bits );
1754 * UI entry point for page deletion
1757 global $wgUser, $wgOut, $wgRequest;
1758 $fname = 'Article::delete';
1759 $confirm = $wgRequest->wasPosted() &&
1760 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1761 $reason = $wgRequest->getText( 'wpReason' );
1763 # This code desperately needs to be totally rewritten
1766 if( $wgUser->isAllowed( 'delete' ) ) {
1767 if( $wgUser->isBlocked() ) {
1768 $wgOut->blockedPage();
1772 $wgOut->permissionRequired( 'delete' );
1776 if( wfReadOnly() ) {
1777 $wgOut->readOnlyPage();
1781 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1783 # Better double-check that it hasn't been deleted yet!
1784 $dbw =& wfGetDB( DB_MASTER
);
1785 $conds = $this->mTitle
->pageCond();
1786 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1787 if ( $latest === false ) {
1788 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1793 $this->doDelete( $reason );
1797 # determine whether this page has earlier revisions
1798 # and insert a warning if it does
1800 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1802 if( count( $authors ) > 1 && !$confirm ) {
1803 $skin=$wgUser->getSkin();
1804 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1805 $wgOut->addHTML( $skin->historyLink() .'</b>');
1808 # If a single user is responsible for all revisions, find out who they are
1809 if ( count( $authors ) == $maxRevisions ) {
1810 // Query bailed out, too many revisions to find out if they're all the same
1811 $authorOfAll = false;
1813 $authorOfAll = reset( $authors );
1814 foreach ( $authors as $author ) {
1815 if ( $authorOfAll != $author ) {
1816 $authorOfAll = false;
1821 # Fetch article text
1822 $rev = Revision
::newFromTitle( $this->mTitle
);
1824 if( !is_null( $rev ) ) {
1825 # if this is a mini-text, we can paste part of it into the deletion reason
1826 $text = $rev->getText();
1828 #if this is empty, an earlier revision may contain "useful" text
1831 $prev = $rev->getPrevious();
1833 $text = $prev->getText();
1838 $length = strlen( $text );
1840 # this should not happen, since it is not possible to store an empty, new
1841 # page. Let's insert a standard text in case it does, though
1842 if( $length == 0 && $reason === '' ) {
1843 $reason = wfMsgForContent( 'exblank' );
1846 if( $length < 500 && $reason === '' ) {
1847 # comment field=255, let's grep the first 150 to have some user
1850 $text = $wgContLang->truncate( $text, 150, '...' );
1852 # let's strip out newlines
1853 $text = preg_replace( "/[\n\r]/", '', $text );
1856 if( $authorOfAll === false ) {
1857 $reason = wfMsgForContent( 'excontent', $text );
1859 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1862 $reason = wfMsgForContent( 'exbeforeblank', $text );
1867 return $this->confirmDelete( '', $reason );
1871 * Get the last N authors
1872 * @param int $num Number of revisions to get
1873 * @param string $revLatest The latest rev_id, selected from the master (optional)
1874 * @return array Array of authors, duplicates not removed
1876 function getLastNAuthors( $num, $revLatest = 0 ) {
1877 $fname = 'Article::getLastNAuthors';
1878 wfProfileIn( $fname );
1880 // First try the slave
1881 // If that doesn't have the latest revision, try the master
1883 $db =& wfGetDB( DB_SLAVE
);
1885 $res = $db->select( array( 'page', 'revision' ),
1886 array( 'rev_id', 'rev_user_text' ),
1888 'page_namespace' => $this->mTitle
->getNamespace(),
1889 'page_title' => $this->mTitle
->getDBkey(),
1890 'rev_page = page_id'
1891 ), $fname, $this->getSelectOptions( array(
1892 'ORDER BY' => 'rev_timestamp DESC',
1897 wfProfileOut( $fname );
1900 $row = $db->fetchObject( $res );
1901 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1902 $db =& wfGetDB( DB_MASTER
);
1907 } while ( $continue );
1909 $authors = array( $row->rev_user_text
);
1910 while ( $row = $db->fetchObject( $res ) ) {
1911 $authors[] = $row->rev_user_text
;
1913 wfProfileOut( $fname );
1918 * Output deletion confirmation dialog
1920 function confirmDelete( $par, $reason ) {
1921 global $wgOut, $wgUser;
1923 wfDebug( "Article::confirmDelete\n" );
1925 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1926 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1927 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1928 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1930 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1932 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1933 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1934 $token = htmlspecialchars( $wgUser->editToken() );
1937 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1941 <label for='wpReason'>{$delcom}:</label>
1944 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1950 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1954 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1957 $wgOut->returnToMain( false );
1962 * Perform a deletion and output success or failure messages
1964 function doDelete( $reason ) {
1965 global $wgOut, $wgUser;
1966 $fname = 'Article::doDelete';
1967 wfDebug( $fname."\n" );
1969 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1970 if ( $this->doDeleteArticle( $reason ) ) {
1971 $deleted = $this->mTitle
->getPrefixedText();
1973 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1974 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1976 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1977 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1979 $wgOut->addWikiText( $text );
1980 $wgOut->returnToMain( false );
1981 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1983 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1989 * Back-end article deletion
1990 * Deletes the article with database consistency, writes logs, purges caches
1993 function doDeleteArticle( $reason ) {
1994 global $wgUseSquid, $wgDeferredUpdateList;
1995 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1997 $fname = 'Article::doDeleteArticle';
1998 wfDebug( $fname."\n" );
2000 $dbw =& wfGetDB( DB_MASTER
);
2001 $ns = $this->mTitle
->getNamespace();
2002 $t = $this->mTitle
->getDBkey();
2003 $id = $this->mTitle
->getArticleID();
2005 if ( $t == '' ||
$id == 0 ) {
2009 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2010 array_push( $wgDeferredUpdateList, $u );
2012 $linksTo = $this->mTitle
->getLinksTo();
2015 if ( $wgUseSquid ) {
2017 $this->mTitle
->getInternalURL(),
2018 $this->mTitle
->getInternalURL( 'history' )
2021 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
2022 array_push( $wgPostCommitUpdateList, $u );
2026 # Client and file cache invalidation
2027 Title
::touchArray( $linksTo );
2030 // For now, shunt the revision data into the archive table.
2031 // Text is *not* removed from the text table; bulk storage
2032 // is left intact to avoid breaking block-compression or
2033 // immutable storage schemes.
2035 // For backwards compatibility, note that some older archive
2036 // table entries will have ar_text and ar_flags fields still.
2038 // In the future, we may keep revisions and mark them with
2039 // the rev_deleted field, which is reserved for this purpose.
2040 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2042 'ar_namespace' => 'page_namespace',
2043 'ar_title' => 'page_title',
2044 'ar_comment' => 'rev_comment',
2045 'ar_user' => 'rev_user',
2046 'ar_user_text' => 'rev_user_text',
2047 'ar_timestamp' => 'rev_timestamp',
2048 'ar_minor_edit' => 'rev_minor_edit',
2049 'ar_rev_id' => 'rev_id',
2050 'ar_text_id' => 'rev_text_id',
2053 'page_id = rev_page'
2057 # Now that it's safely backed up, delete it
2058 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2059 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2061 if ($wgUseTrackbacks)
2062 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2064 # Clean up recentchanges entries...
2065 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2067 # Finally, clean up the link tables
2068 $t = $this->mTitle
->getPrefixedDBkey();
2070 Article
::onArticleDelete( $this->mTitle
);
2072 # Delete outgoing links
2073 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2074 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2075 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2076 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2077 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2080 $log = new LogPage( 'delete' );
2081 $log->addEntry( 'delete', $this->mTitle
, $reason );
2083 # Clear the cached article id so the interface doesn't act like we exist
2084 $this->mTitle
->resetArticleID( 0 );
2085 $this->mTitle
->mArticleID
= 0;
2090 * Revert a modification
2092 function rollback() {
2093 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2094 $fname = 'Article::rollback';
2096 if( $wgUser->isAllowed( 'rollback' ) ) {
2097 if( $wgUser->isBlocked() ) {
2098 $wgOut->blockedPage();
2102 $wgOut->permissionRequired( 'rollback' );
2106 if ( wfReadOnly() ) {
2107 $wgOut->readOnlyPage( $this->getContent() );
2110 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2111 array( $this->mTitle
->getPrefixedText(),
2112 $wgRequest->getVal( 'from' ) ) ) ) {
2113 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2114 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2117 $dbw =& wfGetDB( DB_MASTER
);
2119 # Enhanced rollback, marks edits rc_bot=1
2120 $bot = $wgRequest->getBool( 'bot' );
2122 # Replace all this user's current edits with the next one down
2123 $tt = $this->mTitle
->getDBKey();
2124 $n = $this->mTitle
->getNamespace();
2126 # Get the last editor, lock table exclusively
2128 $current = Revision
::newFromTitle( $this->mTitle
);
2129 if( is_null( $current ) ) {
2130 # Something wrong... no page?
2132 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2136 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2137 if( $from != $current->getUserText() ) {
2138 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2139 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2140 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2141 htmlspecialchars( $from ),
2142 htmlspecialchars( $current->getUserText() ) ) );
2143 if( $current->getComment() != '') {
2145 wfMsg( 'editcomment',
2146 htmlspecialchars( $current->getComment() ) ) );
2151 # Get the last edit not by this guy
2152 $user = intval( $current->getUser() );
2153 $user_text = $dbw->addQuotes( $current->getUserText() );
2154 $s = $dbw->selectRow( 'revision',
2155 array( 'rev_id', 'rev_timestamp' ),
2157 'rev_page' => $current->getPage(),
2158 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2161 'USE INDEX' => 'page_timestamp',
2162 'ORDER BY' => 'rev_timestamp DESC' )
2164 if( $s === false ) {
2167 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2168 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2174 # Mark all reverted edits as bot
2177 if ( $wgUseRCPatrol ) {
2178 # Mark all reverted edits as patrolled
2179 $set['rc_patrolled'] = 1;
2183 $dbw->update( 'recentchanges', $set,
2185 'rc_cur_id' => $current->getPage(),
2186 'rc_user_text' => $current->getUserText(),
2187 "rc_timestamp > '{$s->rev_timestamp}'",
2192 # Get the edit summary
2193 $target = Revision
::newFromId( $s->rev_id
);
2194 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2195 $newComment = $wgRequest->getText( 'summary', $newComment );
2198 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2199 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2200 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2202 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2203 Article
::onArticleEdit( $this->mTitle
);
2206 $wgOut->returnToMain( false );
2211 * Do standard deferred updates after page view
2214 function viewUpdates() {
2215 global $wgDeferredUpdateList;
2217 if ( 0 != $this->getID() ) {
2218 global $wgDisableCounters;
2219 if( !$wgDisableCounters ) {
2220 Article
::incViewCount( $this->getID() );
2221 $u = new SiteStatsUpdate( 1, 0, 0 );
2222 array_push( $wgDeferredUpdateList, $u );
2226 # Update newtalk / watchlist notification status
2228 $wgUser->clearNotification( $this->mTitle
);
2232 * Do standard deferred updates after page edit.
2233 * Every 1000th edit, prune the recent changes table.
2235 * @param string $text
2237 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2238 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2240 $fname = 'Article::editUpdates';
2241 wfProfileIn( $fname );
2244 $options = new ParserOptions
;
2245 $options->setTidy(true);
2246 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2248 # Save it to the parser cache
2249 $parserCache =& ParserCache
::singleton();
2250 $parserCache->save( $poutput, $this, $wgUser );
2252 # Update the links tables
2253 $u = new LinksUpdate( $this->mTitle
, $poutput );
2256 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2258 if ( 0 == mt_rand( 0, 999 ) ) {
2259 # Periodically flush old entries from the recentchanges table.
2262 $dbw =& wfGetDB( DB_MASTER
);
2263 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2264 $recentchanges = $dbw->tableName( 'recentchanges' );
2265 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2266 $dbw->query( $sql );
2270 $id = $this->getID();
2271 $title = $this->mTitle
->getPrefixedDBkey();
2272 $shortTitle = $this->mTitle
->getDBkey();
2275 wfProfileOut( $fname );
2279 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2280 array_push( $wgDeferredUpdateList, $u );
2281 $u = new SearchUpdate( $id, $title, $text );
2282 array_push( $wgDeferredUpdateList, $u );
2284 # If this is another user's talk page, update newtalk
2286 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
2287 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2288 $other = User
::newFromName( $shortTitle );
2289 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2290 // An anonymous user
2291 $other = new User();
2292 $other->setName( $shortTitle );
2295 $other->setNewtalk( true );
2300 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2301 $wgMessageCache->replace( $shortTitle, $text );
2304 wfProfileOut( $fname );
2308 * Generate the navigation links when browsing through an article revisions
2309 * It shows the information as:
2310 * Revision as of <date>; view current revision
2311 * <- Previous version | Next Version ->
2314 * @param string $oldid Revision ID of this article revision
2316 function setOldSubtitle( $oldid=0 ) {
2317 global $wgLang, $wgOut, $wgUser;
2319 $current = ( $oldid == $this->mLatest
);
2320 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2321 $sk = $wgUser->getSkin();
2323 ?
wfMsg( 'currentrevisionlink' )
2324 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2325 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2327 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2328 : wfMsg( 'previousrevision' );
2329 $nextlink = $current
2330 ?
wfMsg( 'nextrevision' )
2331 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2332 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2333 $wgOut->setSubtitle( $r );
2337 * This function is called right before saving the wikitext,
2338 * so we can do things like signatures and links-in-context.
2340 * @param string $text
2342 function preSaveTransform( $text ) {
2343 global $wgParser, $wgUser;
2344 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2347 /* Caching functions */
2350 * checkLastModified returns true if it has taken care of all
2351 * output to the client that is necessary for this request.
2352 * (that is, it has sent a cached version of the page)
2354 function tryFileCache() {
2355 static $called = false;
2357 wfDebug( " tryFileCache() -- called twice!?\n" );
2361 if($this->isFileCacheable()) {
2362 $touched = $this->mTouched
;
2363 $cache = new CacheManager( $this->mTitle
);
2364 if($cache->isFileCacheGood( $touched )) {
2365 wfDebug( " tryFileCache() - about to load\n" );
2366 $cache->loadFromFileCache();
2369 wfDebug( " tryFileCache() - starting buffer\n" );
2370 ob_start( array(&$cache, 'saveToFileCache' ) );
2373 wfDebug( " tryFileCache() - not cacheable\n" );
2378 * Check if the page can be cached
2381 function isFileCacheable() {
2382 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2383 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2385 return $wgUseFileCache
2386 and (!$wgShowIPinHeader)
2387 and ($this->getID() != 0)
2388 and ($wgUser->isAnon())
2389 and (!$wgUser->getNewtalk())
2390 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2391 and (empty( $action ) ||
$action == 'view')
2392 and (!isset($oldid))
2394 and (!isset($redirect))
2395 and (!isset($printable))
2396 and (!$this->mRedirectedFrom
);
2400 * Loads page_touched and returns a value indicating if it should be used
2403 function checkTouched() {
2404 $fname = 'Article::checkTouched';
2405 if( !$this->mDataLoaded
) {
2406 $this->loadPageData();
2408 return !$this->mIsRedirect
;
2412 * Get the page_touched field
2414 function getTouched() {
2415 # Ensure that page data has been loaded
2416 if( !$this->mDataLoaded
) {
2417 $this->loadPageData();
2419 return $this->mTouched
;
2423 * Get the page_latest field
2425 function getLatest() {
2426 if ( !$this->mDataLoaded
) {
2427 $this->loadPageData();
2429 return $this->mLatest
;
2433 * Edit an article without doing all that other stuff
2434 * The article must already exist; link tables etc
2435 * are not updated, caches are not flushed.
2437 * @param string $text text submitted
2438 * @param string $comment comment submitted
2439 * @param bool $minor whereas it's a minor modification
2441 function quickEdit( $text, $comment = '', $minor = 0 ) {
2442 $fname = 'Article::quickEdit';
2443 wfProfileIn( $fname );
2445 $dbw =& wfGetDB( DB_MASTER
);
2447 $revision = new Revision( array(
2448 'page' => $this->getId(),
2450 'comment' => $comment,
2451 'minor_edit' => $minor ?
1 : 0,
2453 $revisionId = $revision->insertOn( $dbw );
2454 $this->updateRevisionOn( $dbw, $revision );
2457 wfProfileOut( $fname );
2461 * Used to increment the view counter
2464 * @param integer $id article id
2466 function incViewCount( $id ) {
2467 $id = intval( $id );
2468 global $wgHitcounterUpdateFreq;
2470 $dbw =& wfGetDB( DB_MASTER
);
2471 $pageTable = $dbw->tableName( 'page' );
2472 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2473 $acchitsTable = $dbw->tableName( 'acchits' );
2475 if( $wgHitcounterUpdateFreq <= 1 ){ //
2476 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2480 # Not important enough to warrant an error page in case of failure
2481 $oldignore = $dbw->ignoreErrors( true );
2483 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2485 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2486 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2487 # Most of the time (or on SQL errors), skip row count check
2488 $dbw->ignoreErrors( $oldignore );
2492 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2493 $row = $dbw->fetchObject( $res );
2494 $rown = intval( $row->n
);
2495 if( $rown >= $wgHitcounterUpdateFreq ){
2496 wfProfileIn( 'Article::incViewCount-collect' );
2497 $old_user_abort = ignore_user_abort( true );
2499 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2500 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable ENGINE=HEAP ".
2501 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2503 $dbw->query("DELETE FROM $hitcounterTable");
2504 $dbw->query('UNLOCK TABLES');
2505 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2506 'WHERE page_id = hc_id');
2507 $dbw->query("DROP TABLE $acchitsTable");
2509 ignore_user_abort( $old_user_abort );
2510 wfProfileOut( 'Article::incViewCount-collect' );
2512 $dbw->ignoreErrors( $oldignore );
2516 * The onArticle*() functions are supposed to be a kind of hooks
2517 * which should be called whenever any of the specified actions
2520 * This is a good place to put code to clear caches, for instance.
2522 * This is called on page move and undelete, as well as edit
2524 * @param $title_obj a title object
2527 function onArticleCreate($title_obj) {
2528 global $wgUseSquid, $wgPostCommitUpdateList;
2530 $title_obj->touchLinks();
2531 $titles = $title_obj->getLinksTo();
2534 if ( $wgUseSquid ) {
2535 $urls = $title_obj->getSquidURLs();
2536 foreach ( $titles as $linkTitle ) {
2537 $urls[] = $linkTitle->getInternalURL();
2539 $u = new SquidUpdate( $urls );
2540 array_push( $wgPostCommitUpdateList, $u );
2544 function onArticleDelete( $title ) {
2545 global $wgMessageCache;
2547 $title->touchLinks();
2549 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2550 $wgMessageCache->replace( $title->getDBkey(), false );
2555 * Purge caches on page update etc
2557 function onArticleEdit( $title ) {
2558 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2562 // Template namespace? Purge all articles linking here.
2563 // FIXME: When a templatelinks table arrives, use it for all includes.
2564 if ( $title->getNamespace() == NS_TEMPLATE
) {
2565 $titles = $title->getLinksTo();
2566 Title
::touchArray( $titles );
2567 if ( $wgUseSquid ) {
2568 foreach ( $titles as $link ) {
2569 $urls[] = $link->getInternalURL();
2575 if ( $wgUseSquid ) {
2576 $urls = array_merge( $urls, $title->getSquidURLs() );
2577 $u = new SquidUpdate( $urls );
2578 array_push( $wgPostCommitUpdateList, $u );
2582 if ( $wgUseFileCache ) {
2583 $cm = new CacheManager( $title );
2584 @unlink
( $cm->fileCacheName() );
2591 * Info about this page
2592 * Called for ?action=info when $wgAllowPageInfo is on.
2597 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2598 $fname = 'Article::info';
2600 if ( !$wgAllowPageInfo ) {
2601 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2605 $page = $this->mTitle
->getSubjectPage();
2607 $wgOut->setPagetitle( $page->getPrefixedText() );
2608 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2610 # first, see if the page exists at all.
2611 $exists = $page->getArticleId() != 0;
2613 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2614 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2616 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2619 $dbr =& wfGetDB( DB_SLAVE
);
2621 'wl_title' => $page->getDBkey(),
2622 'wl_namespace' => $page->getNamespace() );
2623 $numwatchers = $dbr->selectField(
2628 $this->getSelectOptions() );
2630 $pageInfo = $this->pageCountInfo( $page );
2631 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2633 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2634 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2636 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2638 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2640 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2642 $wgOut->addHTML( '</ul>' );
2648 * Return the total number of edits and number of unique editors
2649 * on a given page. If page does not exist, returns false.
2651 * @param Title $title
2655 function pageCountInfo( $title ) {
2656 $id = $title->getArticleId();
2661 $dbr =& wfGetDB( DB_SLAVE
);
2663 $rev_clause = array( 'rev_page' => $id );
2664 $fname = 'Article::pageCountInfo';
2666 $edits = $dbr->selectField(
2671 $this->getSelectOptions() );
2673 $authors = $dbr->selectField(
2675 'COUNT(DISTINCT rev_user_text)',
2678 $this->getSelectOptions() );
2680 return array( 'edits' => $edits, 'authors' => $authors );
2684 * Return a list of templates used by this article.
2685 * Uses the templatelinks table
2687 * @return array Array of Title objects
2689 function getUsedTemplates() {
2691 $id = $this->mTitle
->getArticleID();
2696 $dbr =& wfGetDB( DB_SLAVE
);
2697 $res = $dbr->select( array( 'templatelinks' ),
2698 array( 'tl_namespace', 'tl_title' ),
2699 array( 'tl_from' => $id ),
2700 'Article:getUsedTemplates' );
2701 if ( false !== $res ) {
2702 if ( $dbr->numRows( $res ) ) {
2703 while ( $row = $dbr->fetchObject( $res ) ) {
2704 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2708 $dbr->freeResult( $res );