8 * Need the CacheManager to be loaded
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
17 * Class representing a MediaWiki article and history.
19 * See design.txt for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mGoodAdjustment, $mTotalAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
44 * Constructor and clear the article
45 * @param Title &$title
46 * @param integer $oldId Revision ID, null to fetch from request, zero for current
48 function Article( &$title, $oldId = null ) {
49 $this->mTitle
=& $title;
50 $this->mOldId
= $oldId;
55 * Tell the page view functions that this view was redirected
56 * from another page on the wiki.
59 function setRedirectedFrom( $from ) {
60 $this->mRedirectedFrom
= $from;
64 * @return mixed false, Title of in-wiki target, or string with URL
66 function followRedirect() {
67 $text = $this->getContent();
68 $rt = Title
::newFromRedirect( $text );
70 # process if title object is valid and not special:userlogout
72 if( $rt->getInterwiki() != '' ) {
73 if( $rt->isLocal() ) {
74 // Offsite wikis need an HTTP redirect.
76 // This can be hard to reverse and may produce loops,
77 // so they may be disabled in the site configuration.
79 $source = $this->mTitle
->getFullURL( 'redirect=no' );
80 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
83 if( $rt->getNamespace() == NS_SPECIAL
) {
84 // Gotta hand redirects to special pages differently:
85 // Fill the HTTP response "Location" header and ignore
86 // the rest of the page we're on.
88 // This can be hard to reverse, so they may be disabled.
90 if( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) {
93 return $rt->getFullURL();
100 // No or invalid redirect
105 * get the title object of the article
107 function getTitle() {
108 return $this->mTitle
;
116 $this->mDataLoaded
= false;
117 $this->mContentLoaded
= false;
119 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
120 $this->mRedirectedFrom
= null; # Title object if set
122 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
123 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
124 $this->mTouched
= '19700101000000';
125 $this->mForUpdate
= false;
126 $this->mIsRedirect
= false;
127 $this->mRevIdFetched
= 0;
128 $this->mRedirectUrl
= false;
129 $this->mLatest
= false;
133 * Note that getContent/loadContent do not follow redirects anymore.
134 * If you need to fetch redirectable content easily, try
135 * the shortcut in Article::followContent()
137 * @fixme There are still side-effects in this!
138 * In general, you should use the Revision class, not Article,
139 * to fetch text for purposes other than page views.
141 * @return Return the text of this revision
143 function getContent() {
144 global $wgRequest, $wgUser, $wgOut;
146 # Get variables from query string :P
147 $action = $wgRequest->getText( 'action', 'view' );
148 $section = $wgRequest->getText( 'section' );
149 $preload = $wgRequest->getText( 'preload' );
151 $fname = 'Article::getContent';
152 wfProfileIn( $fname );
154 if ( 0 == $this->getID() ) {
155 if ( 'edit' == $action ) {
156 wfProfileOut( $fname );
158 # If requested, preload some text.
159 $text=$this->getPreloadedText($preload);
161 # We used to put MediaWiki:Newarticletext here if
162 # $text was empty at this point.
163 # This is now shown above the edit box instead.
166 wfProfileOut( $fname );
167 $wgOut->setRobotpolicy( 'noindex,nofollow' );
169 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
170 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
172 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
175 return "<div class='noarticletext'>$ret</div>";
177 $this->loadContent();
178 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
179 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
180 $wgUser->isIP($this->mTitle
->getText()) &&
183 wfProfileOut( $fname );
184 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
186 if($action=='edit') {
188 if($section=='new') {
189 wfProfileOut( $fname );
190 $text=$this->getPreloadedText($preload);
194 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
195 # comments to be stripped as well)
196 $rv=$this->getSection($this->mContent
,$section);
197 wfProfileOut( $fname );
201 wfProfileOut( $fname );
202 return $this->mContent
;
208 * Get the contents of a page from its title and remove includeonly tags
210 * @param string The title of the page
211 * @return string The contents of the page
213 function getPreloadedText($preload) {
214 if ( $preload === '' )
217 $preloadTitle = Title
::newFromText( $preload );
218 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
219 $rev=Revision
::newFromTitle($preloadTitle);
220 if ( is_object( $rev ) ) {
221 $text = $rev->getText();
222 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
223 // its own mini-parser! -ævar
224 $text = preg_replace( '~</?includeonly>~', '', $text );
233 * This function returns the text of a section, specified by a number ($section).
234 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
235 * the first section before any such heading (section 0).
237 * If a section contains subsections, these are also returned.
239 * @param string $text text to look in
240 * @param integer $section section number
241 * @return string text of the requested section
243 function getSection($text,$section) {
245 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
246 # comments to be stripped as well)
248 $parser=new Parser();
249 $parser->mOutputType
=OT_WIKI
;
250 $parser->mOptions
= new ParserOptions();
251 $striptext=$parser->strip($text, $striparray, true);
253 # now that we can be sure that no pseudo-sections are in the source,
254 # split it up by section
257 '/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
259 PREG_SPLIT_DELIM_CAPTURE
);
263 $headline=$secs[$section*2-1];
264 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
267 # translate wiki heading into level
268 if(strpos($hlevel,'=')!==false) {
269 $hlevel=strlen($hlevel);
272 $rv=$headline. $secs[$section*2];
276 while(!empty($secs[$count*2-1]) && !$break) {
278 $subheadline=$secs[$count*2-1];
279 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
280 $subhlevel=$matches[1];
281 if(strpos($subhlevel,'=')!==false) {
282 $subhlevel=strlen($subhlevel);
284 if($subhlevel > $hlevel) {
285 $rv.=$subheadline.$secs[$count*2];
287 if($subhlevel <= $hlevel) {
294 # reinsert stripped tags
295 $rv=$parser->unstrip($rv,$striparray);
296 $rv=$parser->unstripNoWiki($rv,$striparray);
303 * @return int The oldid of the article that is to be shown, 0 for the
306 function getOldID() {
307 if ( is_null( $this->mOldId
) ) {
308 $this->mOldId
= $this->getOldIDFromRequest();
310 return $this->mOldId
;
314 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
316 * @return int The old id for the request
318 function getOldIDFromRequest() {
320 $this->mRedirectUrl
= false;
321 $oldid = $wgRequest->getVal( 'oldid' );
322 if ( isset( $oldid ) ) {
323 $oldid = intval( $oldid );
324 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
325 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
329 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
331 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
332 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
348 * Load the revision (including text) into this object
350 function loadContent() {
351 if ( $this->mContentLoaded
) return;
354 $oldid = $this->getOldID();
356 $fname = 'Article::loadContent';
358 # Pre-fill content with error message so that if something
359 # fails we'll have something telling us what we intended.
361 $t = $this->mTitle
->getPrefixedText();
363 $this->mOldId
= $oldid;
364 $this->fetchContent( $oldid );
369 * Fetch a page record with the given conditions
370 * @param Database $dbr
371 * @param array $conditions
374 function pageData( &$dbr, $conditions ) {
387 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
388 $row = $dbr->selectRow( 'page',
391 'Article::pageData' );
392 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
397 * @param Database $dbr
398 * @param Title $title
400 function pageDataFromTitle( &$dbr, $title ) {
401 return $this->pageData( $dbr, array(
402 'page_namespace' => $title->getNamespace(),
403 'page_title' => $title->getDBkey() ) );
407 * @param Database $dbr
410 function pageDataFromId( &$dbr, $id ) {
411 return $this->pageData( $dbr, array( 'page_id' => $id ) );
415 * Set the general counter, title etc data loaded from
418 * @param object $data
421 function loadPageData( $data = 'fromdb' ) {
422 if ( $data === 'fromdb' ) {
423 $dbr =& $this->getDB();
424 $data = $this->pageDataFromId( $dbr, $this->getId() );
427 $lc =& LinkCache
::singleton();
429 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
431 $this->mTitle
->mArticleID
= $data->page_id
;
432 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
433 $this->mTitle
->mRestrictionsLoaded
= true;
435 $this->mCounter
= $data->page_counter
;
436 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
437 $this->mIsRedirect
= $data->page_is_redirect
;
438 $this->mLatest
= $data->page_latest
;
440 $lc->addBadLinkObj( $this->mTitle
);
441 $this->mTitle
->mArticleID
= 0;
444 $this->mDataLoaded
= true;
448 * Get text of an article from database
449 * Does *NOT* follow redirects.
450 * @param int $oldid 0 for whatever the latest revision is
453 function fetchContent( $oldid = 0 ) {
454 if ( $this->mContentLoaded
) {
455 return $this->mContent
;
458 $dbr =& $this->getDB();
459 $fname = 'Article::fetchContent';
461 # Pre-fill content with error message so that if something
462 # fails we'll have something telling us what we intended.
463 $t = $this->mTitle
->getPrefixedText();
465 $t .= ',oldid='.$oldid;
467 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
470 $revision = Revision
::newFromId( $oldid );
471 if( is_null( $revision ) ) {
472 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
475 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
477 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
480 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
481 $this->loadPageData( $data );
483 if( !$this->mDataLoaded
) {
484 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
486 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
489 $this->loadPageData( $data );
491 $revision = Revision
::newFromId( $this->mLatest
);
492 if( is_null( $revision ) ) {
493 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
498 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
499 // We should instead work with the Revision object when we need it...
500 $this->mContent
= $revision->userCan( MW_REV_DELETED_TEXT
) ?
$revision->getRawText() : "";
501 //$this->mContent = $revision->getText();
503 $this->mUser
= $revision->getUser();
504 $this->mUserText
= $revision->getUserText();
505 $this->mComment
= $revision->getComment();
506 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
508 $this->mRevIdFetched
= $revision->getID();
509 $this->mContentLoaded
= true;
510 $this->mRevision
=& $revision;
512 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
514 return $this->mContent
;
518 * Read/write accessor to select FOR UPDATE
522 function forUpdate( $x = NULL ) {
523 return wfSetVar( $this->mForUpdate
, $x );
527 * Get the database which should be used for reads
532 $ret =& wfGetDB( DB_MASTER
);
537 * Get options for all SELECT statements
539 * @param array $options an optional options array which'll be appended to
541 * @return array Options
543 function getSelectOptions( $options = '' ) {
544 if ( $this->mForUpdate
) {
545 if ( is_array( $options ) ) {
546 $options[] = 'FOR UPDATE';
548 $options = 'FOR UPDATE';
555 * @return int Page ID
558 if( $this->mTitle
) {
559 return $this->mTitle
->getArticleID();
566 * @return bool Whether or not the page exists in the database
569 return $this->getId() != 0;
573 * @return int The view count for the page
575 function getCount() {
576 if ( -1 == $this->mCounter
) {
577 $id = $this->getID();
581 $dbr =& wfGetDB( DB_SLAVE
);
582 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
583 'Article::getCount', $this->getSelectOptions() );
586 return $this->mCounter
;
590 * Determine whether a page would be suitable for being counted as an
591 * article in the site_stats table based on the title & its content
593 * @param string $text Text to analyze
596 function isCountable( $text ) {
597 global $wgUseCommaCount;
599 $token = $wgUseCommaCount ?
',' : '[[';
601 $this->mTitle
->getNamespace() == NS_MAIN
602 && ! $this->isRedirect( $text )
603 && in_string( $token, $text );
607 * Tests if the article text represents a redirect
609 * @param string $text
612 function isRedirect( $text = false ) {
613 if ( $text === false ) {
614 $this->loadContent();
615 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
617 $titleObj = Title
::newFromRedirect( $text );
619 return $titleObj !== NULL;
623 * Returns true if the currently-referenced revision is the current edit
624 * to this page (and it exists).
627 function isCurrent() {
628 return $this->exists() &&
629 isset( $this->mRevision
) &&
630 $this->mRevision
->isCurrent();
634 * Loads everything except the text
635 * This isn't necessary for all uses, so it's only done if needed.
638 function loadLastEdit() {
639 if ( -1 != $this->mUser
)
642 # New or non-existent articles have no user information
643 $id = $this->getID();
644 if ( 0 == $id ) return;
646 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
647 if( !is_null( $this->mLastRevision
) ) {
648 $this->mUser
= $this->mLastRevision
->getUser();
649 $this->mUserText
= $this->mLastRevision
->getUserText();
650 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
651 $this->mComment
= $this->mLastRevision
->getComment();
652 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
653 $this->mRevIdFetched
= $this->mLastRevision
->getID();
657 function getTimestamp() {
658 // Check if the field has been filled by ParserCache::get()
659 if ( !$this->mTimestamp
) {
660 $this->loadLastEdit();
662 return wfTimestamp(TS_MW
, $this->mTimestamp
);
666 $this->loadLastEdit();
670 function getUserText() {
671 $this->loadLastEdit();
672 return $this->mUserText
;
675 function getComment() {
676 $this->loadLastEdit();
677 return $this->mComment
;
680 function getMinorEdit() {
681 $this->loadLastEdit();
682 return $this->mMinorEdit
;
685 function getRevIdFetched() {
686 $this->loadLastEdit();
687 return $this->mRevIdFetched
;
690 function getContributors($limit = 0, $offset = 0) {
691 $fname = 'Article::getContributors';
693 # XXX: this is expensive; cache this info somewhere.
695 $title = $this->mTitle
;
697 $dbr =& wfGetDB( DB_SLAVE
);
698 $revTable = $dbr->tableName( 'revision' );
699 $userTable = $dbr->tableName( 'user' );
700 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
701 $ns = $title->getNamespace();
702 $user = $this->getUser();
703 $pageId = $this->getId();
705 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
706 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
707 WHERE rev_page = $pageId
708 AND rev_user != $user
709 GROUP BY rev_user, rev_user_text, user_real_name
710 ORDER BY timestamp DESC";
712 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
713 $sql .= ' '. $this->getSelectOptions();
715 $res = $dbr->query($sql, $fname);
717 while ( $line = $dbr->fetchObject( $res ) ) {
718 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
721 $dbr->freeResult($res);
726 * This is the default action of the script: just view the page of
730 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgContLang;
731 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
732 global $wgUseTrackbacks;
733 $sk = $wgUser->getSkin();
735 $fname = 'Article::view';
736 wfProfileIn( $fname );
737 $parserCache =& ParserCache
::singleton();
738 # Get variables from query string
739 $oldid = $this->getOldID();
741 # getOldID may want us to redirect somewhere else
742 if ( $this->mRedirectUrl
) {
743 $wgOut->redirect( $this->mRedirectUrl
);
744 wfProfileOut( $fname );
748 $diff = $wgRequest->getVal( 'diff' );
749 $rcid = $wgRequest->getVal( 'rcid' );
750 $rdfrom = $wgRequest->getVal( 'rdfrom' );
752 $wgOut->setArticleFlag( true );
753 $wgOut->setRobotpolicy( 'index,follow' );
754 # If we got diff and oldid in the query, we want to see a
755 # diff page instead of the article.
757 if ( !is_null( $diff ) ) {
758 require_once( 'DifferenceEngine.php' );
759 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
761 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
762 // DifferenceEngine directly fetched the revision:
763 $this->mRevIdFetched
= $de->mNewid
;
767 # Run view updates for current revision only
768 $this->viewUpdates();
770 wfProfileOut( $fname );
774 if ( empty( $oldid ) && $this->checkTouched() ) {
775 $wgOut->setETag($parserCache->getETag($this, $wgUser));
777 if( $wgOut->checkLastModified( $this->mTouched
) ){
778 wfProfileOut( $fname );
780 } else if ( $this->tryFileCache() ) {
781 # tell wgOut that output is taken care of
783 $this->viewUpdates();
784 wfProfileOut( $fname );
788 # Should the parser cache be used?
789 $pcache = $wgEnableParserCache &&
790 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
793 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
794 if ( $wgUser->getOption( 'stubthreshold' ) ) {
795 wfIncrStats( 'pcache_miss_stub' );
798 $wasRedirected = false;
799 if ( isset( $this->mRedirectedFrom
) ) {
800 // This is an internally redirected page view.
801 // We'll need a backlink to the source page for navigation.
802 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
803 $sk = $wgUser->getSkin();
804 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
805 $s = wfMsg( 'redirectedfrom', $redir );
806 $wgOut->setSubtitle( $s );
807 $wasRedirected = true;
809 } elseif ( !empty( $rdfrom ) ) {
810 // This is an externally redirected view, from some other wiki.
811 // If it was reported from a trusted site, supply a backlink.
812 global $wgRedirectSources;
813 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
814 $sk = $wgUser->getSkin();
815 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
816 $s = wfMsg( 'redirectedfrom', $redir );
817 $wgOut->setSubtitle( $s );
818 $wasRedirected = true;
824 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
828 if ( !$outputDone ) {
829 $text = $this->getContent();
830 if ( $text === false ) {
831 # Failed to load, replace text with error message
832 $t = $this->mTitle
->getPrefixedText();
834 $t .= ',oldid='.$oldid;
835 $text = wfMsg( 'missingarticle', $t );
837 $text = wfMsg( 'noarticletext', $t );
841 # Another whitelist check in case oldid is altering the title
842 if ( !$this->mTitle
->userCanRead() ) {
843 $wgOut->loginToUse();
848 # We're looking at an old revision
850 if ( !empty( $oldid ) ) {
851 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
852 $wgOut->setRobotpolicy( 'noindex,nofollow' );
853 if( $this->mRevision
->isDeleted( MW_REV_DELETED_TEXT
) ) {
854 if( !$this->mRevision
->userCan( MW_REV_DELETED_TEXT
) ) {
855 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
856 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
859 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
860 // and we are allowed to see...
868 * @fixme: this hook doesn't work most of the time, as it doesn't
869 * trigger when the parser cache is used.
871 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
872 $wgOut->setRevisionId( $this->getRevIdFetched() );
873 # wrap user css and user js in pre and don't parse
874 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
876 $this->mTitle
->getNamespace() == NS_USER
&&
877 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
879 $wgOut->addWikiText( wfMsg('clearyourcache'));
880 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
881 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
883 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
884 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
885 if( !$wasRedirected ) {
886 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
888 $targetUrl = $rt->escapeLocalURL();
889 $titleText = htmlspecialchars( $rt->getPrefixedText() );
890 $link = $sk->makeLinkObj( $rt );
892 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
893 '<span class="redirectText">'.$link.'</span>' );
895 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
896 $wgOut->addParserOutputNoText( $parseout );
897 } else if ( $pcache ) {
898 # Display content and save to parser cache
899 $wgOut->addPrimaryWikiText( $text, $this );
901 # Display content, don't attempt to save to parser cache
903 # Don't show section-edit links on old revisions... this way lies madness.
904 if( !$this->isCurrent() ) {
905 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
907 # Display content and don't save to parser cache
908 $wgOut->addPrimaryWikiText( $text, $this, false );
910 if( !$this->isCurrent() ) {
911 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
915 /* title may have been set from the cache */
916 $t = $wgOut->getPageTitle();
918 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
921 # If we have been passed an &rcid= parameter, we want to give the user a
922 # chance to mark this new article as patrolled.
926 && $wgUser->isLoggedIn()
927 && ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
930 "<div class='patrollink'>" .
931 wfMsg ( 'markaspatrolledlink',
932 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
939 if ($wgUseTrackbacks)
940 $this->addTrackbacks();
942 $this->viewUpdates();
943 wfProfileOut( $fname );
946 function addTrackbacks() {
947 global $wgOut, $wgUser;
949 $dbr =& wfGetDB(DB_SLAVE
);
951 /* FROM */ 'trackbacks',
952 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
953 /* WHERE */ array('tb_page' => $this->getID())
956 if (!$dbr->numrows($tbs))
960 while ($o = $dbr->fetchObject($tbs)) {
962 if ($wgUser->isSysop()) {
963 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
964 . $o->tb_id
. "&token=" . $wgUser->editToken());
965 $rmvtxt = wfMsg('trackbackremove', $delurl);
967 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
974 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
977 function deletetrackback() {
978 global $wgUser, $wgRequest, $wgOut, $wgTitle;
980 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
981 $wgOut->addWikitext(wfMsg('sessionfailure'));
985 if ((!$wgUser->isAllowed('delete'))) {
986 $wgOut->sysopRequired();
991 $wgOut->readOnlyPage();
995 $db =& wfGetDB(DB_MASTER
);
996 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
997 $wgTitle->invalidateCache();
998 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
1004 $wgOut->setArticleBodyOnly(true);
1009 * Handle action=purge
1012 global $wgUser, $wgRequest, $wgOut;
1014 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
1015 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1019 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1020 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
1021 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1022 $msg = str_replace( '$1',
1023 "<form method=\"post\" action=\"$action\">\n" .
1024 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1025 "</form>\n", $msg );
1027 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1028 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1029 $wgOut->addHTML( $msg );
1034 * Perform the actions of a page purging
1036 function doPurge() {
1038 // Invalidate the cache
1039 $this->mTitle
->invalidateCache();
1041 if ( $wgUseSquid ) {
1042 // Commit the transaction before the purge is sent
1043 $dbw = wfGetDB( DB_MASTER
);
1044 $dbw->immediateCommit();
1047 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1048 $update->doUpdate();
1054 * Insert a new empty page record for this article.
1055 * This *must* be followed up by creating a revision
1056 * and running $this->updateToLatest( $rev_id );
1057 * or else the record will be left in a funky state.
1058 * Best if all done inside a transaction.
1060 * @param Database $dbw
1061 * @param string $restrictions
1062 * @return int The newly created page_id key
1065 function insertOn( &$dbw, $restrictions = '' ) {
1066 $fname = 'Article::insertOn';
1067 wfProfileIn( $fname );
1069 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1070 $dbw->insert( 'page', array(
1071 'page_id' => $page_id,
1072 'page_namespace' => $this->mTitle
->getNamespace(),
1073 'page_title' => $this->mTitle
->getDBkey(),
1074 'page_counter' => 0,
1075 'page_restrictions' => $restrictions,
1076 'page_is_redirect' => 0, # Will set this shortly...
1078 'page_random' => wfRandom(),
1079 'page_touched' => $dbw->timestamp(),
1080 'page_latest' => 0, # Fill this in shortly...
1081 'page_len' => 0, # Fill this in shortly...
1083 $newid = $dbw->insertId();
1085 $this->mTitle
->resetArticleId( $newid );
1087 wfProfileOut( $fname );
1092 * Update the page record to point to a newly saved revision.
1094 * @param Database $dbw
1095 * @param Revision $revision For ID number, and text used to set
1096 length and redirect status fields
1097 * @param int $lastRevision If given, will not overwrite the page field
1098 * when different from the currently set value.
1099 * Giving 0 indicates the new page flag should
1101 * @return bool true on success, false on failure
1104 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1105 $fname = 'Article::updateToRevision';
1106 wfProfileIn( $fname );
1108 $conditions = array( 'page_id' => $this->getId() );
1109 if( !is_null( $lastRevision ) ) {
1110 # An extra check against threads stepping on each other
1111 $conditions['page_latest'] = $lastRevision;
1114 $text = $revision->getText();
1115 $dbw->update( 'page',
1117 'page_latest' => $revision->getId(),
1118 'page_touched' => $dbw->timestamp(),
1119 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1120 'page_is_redirect' => Article
::isRedirect( $text ) ?
1 : 0,
1121 'page_len' => strlen( $text ),
1126 wfProfileOut( $fname );
1127 return ( $dbw->affectedRows() != 0 );
1131 * If the given revision is newer than the currently set page_latest,
1132 * update the page record. Otherwise, do nothing.
1134 * @param Database $dbw
1135 * @param Revision $revision
1137 function updateIfNewerOn( &$dbw, $revision ) {
1138 $fname = 'Article::updateIfNewerOn';
1139 wfProfileIn( $fname );
1141 $row = $dbw->selectRow(
1142 array( 'revision', 'page' ),
1143 array( 'rev_id', 'rev_timestamp' ),
1145 'page_id' => $this->getId(),
1146 'page_latest=rev_id' ),
1149 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1150 wfProfileOut( $fname );
1153 $prev = $row->rev_id
;
1155 # No or missing previous revision; mark the page as new
1159 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1160 wfProfileOut( $fname );
1165 * Insert a new article into the database
1168 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1171 $fname = 'Article::insertNewArticle';
1172 wfProfileIn( $fname );
1174 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1175 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1176 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1177 wfProfileOut( $fname );
1181 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1182 $this->mTotalAdjustment
= 1;
1184 $ns = $this->mTitle
->getNamespace();
1185 $ttl = $this->mTitle
->getDBkey();
1187 # If this is a comment, add the summary as headline
1188 if($comment && $summary!="") {
1189 $text="== {$summary} ==\n\n".$text;
1191 $text = $this->preSaveTransform( $text );
1193 /* Silently ignore minoredit if not allowed */
1194 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1195 $now = wfTimestampNow();
1197 $dbw =& wfGetDB( DB_MASTER
);
1199 # Add the page record; stake our claim on this title!
1200 $newid = $this->insertOn( $dbw );
1202 # Save the revision text...
1203 $revision = new Revision( array(
1205 'comment' => $summary,
1206 'minor_edit' => $isminor,
1209 $revisionId = $revision->insertOn( $dbw );
1211 $this->mTitle
->resetArticleID( $newid );
1213 # Update the page record with revision data
1214 $this->updateRevisionOn( $dbw, $revision, 0 );
1216 Article
::onArticleCreate( $this->mTitle
);
1218 require_once( 'RecentChange.php' );
1219 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, 'default',
1220 '', strlen( $text ), $revisionId );
1224 if(!$this->mTitle
->userIsWatching()) $this->doWatch();
1226 if ( $this->mTitle
->userIsWatching() ) {
1231 # The talk page isn't in the regular link tables, so we need to update manually:
1232 $talkns = $ns ^
1; # talk -> normal; normal -> talk
1233 $dbw->update( 'page',
1234 array( 'page_touched' => $dbw->timestamp($now) ),
1235 array( 'page_namespace' => $talkns,
1236 'page_title' => $ttl ),
1239 # standard deferred updates
1240 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1242 $oldid = 0; # new article
1243 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1245 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1247 $watchthis, NULL ) );
1248 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1250 $watchthis, NULL ) );
1251 wfProfileOut( $fname );
1254 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1255 $this->replaceSection( $section, $text, $summary, $edittime );
1259 * @return string Complete article text, or null if error
1261 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1262 $fname = 'Article::replaceSection';
1263 wfProfileIn( $fname );
1265 if ($section != '') {
1266 if( is_null( $edittime ) ) {
1267 $rev = Revision
::newFromTitle( $this->mTitle
);
1269 $dbw =& wfGetDB( DB_MASTER
);
1270 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1272 if( is_null( $rev ) ) {
1273 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1274 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1277 $oldtext = $rev->getText();
1279 if($section=='new') {
1280 if($summary) $subject="== {$summary} ==\n\n";
1281 $text=$oldtext."\n\n".$subject.$text;
1284 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1285 # comments to be stripped as well)
1286 $striparray=array();
1287 $parser=new Parser();
1288 $parser->mOutputType
=OT_WIKI
;
1289 $parser->mOptions
= new ParserOptions();
1290 $oldtext=$parser->strip($oldtext, $striparray, true);
1292 # now that we can be sure that no pseudo-sections are in the source,
1294 # Unfortunately we can't simply do a preg_replace because that might
1295 # replace the wrong section, so we have to use the section counter instead
1296 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1297 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1298 $secs[$section*2]=$text."\n\n"; // replace with edited
1300 # section 0 is top (intro) section
1303 # headline of old section - we need to go through this section
1304 # to determine if there are any subsections that now need to
1305 # be erased, as the mother section has been replaced with
1306 # the text of all subsections.
1307 $headline=$secs[$section*2-1];
1308 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1309 $hlevel=$matches[1];
1311 # determine headline level for wikimarkup headings
1312 if(strpos($hlevel,'=')!==false) {
1313 $hlevel=strlen($hlevel);
1316 $secs[$section*2-1]=''; // erase old headline
1319 while(!empty($secs[$count*2-1]) && !$break) {
1321 $subheadline=$secs[$count*2-1];
1323 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1324 $subhlevel=$matches[1];
1325 if(strpos($subhlevel,'=')!==false) {
1326 $subhlevel=strlen($subhlevel);
1328 if($subhlevel > $hlevel) {
1329 // erase old subsections
1330 $secs[$count*2-1]='';
1333 if($subhlevel <= $hlevel) {
1341 $text=join('',$secs);
1342 # reinsert the stuff that we stripped out earlier
1343 $text=$parser->unstrip($text,$striparray);
1344 $text=$parser->unstripNoWiki($text,$striparray);
1348 wfProfileOut( $fname );
1353 * Change an existing article. Puts the previous version back into the old table, updates RC
1354 * and all necessary caches, mostly via the deferred update array.
1356 * It is possible to call this function from a command-line script, but note that you should
1357 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1359 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1360 global $wgUser, $wgDBtransactions, $wgUseSquid;
1361 global $wgPostCommitUpdateList, $wgUseFileCache;
1363 $fname = 'Article::updateArticle';
1364 wfProfileIn( $fname );
1367 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1369 &$watchthis, &$sectionanchor ) ) ) {
1370 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1371 wfProfileOut( $fname );
1375 $isminor = $minor && $wgUser->isAllowed('minoredit');
1376 $redir = (int)$this->isRedirect( $text );
1378 $text = $this->preSaveTransform( $text );
1379 $dbw =& wfGetDB( DB_MASTER
);
1380 $now = wfTimestampNow();
1382 # Update article, but only if changed.
1384 # It's important that we either rollback or complete, otherwise an attacker could
1385 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1386 # could conceivably have the same effect, especially if cur is locked for long periods.
1387 if( !$wgDBtransactions ) {
1388 $userAbort = ignore_user_abort( true );
1391 $oldtext = $this->getContent();
1392 $oldsize = strlen( $oldtext );
1393 $newsize = strlen( $text );
1397 if ( 0 != strcmp( $text, $oldtext ) ) {
1398 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1399 - (int)$this->isCountable( $oldtext );
1400 $this->mTotalAdjustment
= 0;
1401 $now = wfTimestampNow();
1403 $lastRevision = $dbw->selectField(
1404 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1406 $revision = new Revision( array(
1407 'page' => $this->getId(),
1408 'comment' => $summary,
1409 'minor_edit' => $isminor,
1413 $dbw->immediateCommit();
1415 $revisionId = $revision->insertOn( $dbw );
1418 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1421 /* Belated edit conflict! Run away!! */
1425 # Update recentchanges and purge cache and whatnot
1426 require_once( 'RecentChange.php' );
1427 $bot = (int)($wgUser->isBot() ||
$forceBot);
1428 RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1429 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1433 // Update caches outside the main transaction
1434 Article
::onArticleEdit( $this->mTitle
);
1437 // Keep the same revision ID, but do some updates on it
1438 $revisionId = $this->getRevIdFetched();
1441 if( !$wgDBtransactions ) {
1442 ignore_user_abort( $userAbort );
1447 if (!$this->mTitle
->userIsWatching()) {
1448 $dbw->immediateCommit();
1454 if ( $this->mTitle
->userIsWatching() ) {
1455 $dbw->immediateCommit();
1461 # standard deferred updates
1462 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1466 # Invalidate caches of all articles using this article as a template
1468 # Template namespace
1469 # Purge all articles linking here
1470 $titles = $this->mTitle
->getTemplateLinksTo();
1471 Title
::touchArray( $titles );
1472 if ( $wgUseSquid ) {
1473 foreach ( $titles as $title ) {
1474 $urls[] = $title->getInternalURL();
1479 if ( $wgUseSquid ) {
1480 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1481 $u = new SquidUpdate( $urls );
1482 array_push( $wgPostCommitUpdateList, $u );
1486 if ( $wgUseFileCache ) {
1487 $cm = new CacheManager($this->mTitle
);
1488 @unlink
($cm->fileCacheName());
1491 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1493 wfRunHooks( 'ArticleSaveComplete',
1494 array( &$this, &$wgUser, $text,
1496 $watchthis, $sectionanchor ) );
1497 wfProfileOut( $fname );
1502 * After we've either updated or inserted the article, update
1503 * the link tables and redirect to the new page.
1505 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1508 $fname = 'Article::showArticle';
1509 wfProfileIn( $fname );
1511 # Output the redirect
1512 if( $this->isRedirect( $text ) )
1516 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1518 wfProfileOut( $fname );
1522 * Mark this particular edit as patrolled
1524 function markpatrolled() {
1525 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1526 $wgOut->setRobotpolicy( 'noindex,follow' );
1528 # Check RC patrol config. option
1529 if( !$wgUseRCPatrol ) {
1530 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1535 if( $wgUser->isLoggedIn() ) {
1536 if( !$wgUser->isAllowed( 'patrol' ) ) {
1537 $wgOut->permissionRequired( 'patrol' );
1541 $wgOut->loginToUse();
1545 $rcid = $wgRequest->getVal( 'rcid' );
1546 if ( !is_null ( $rcid ) )
1548 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, $wgOnlySysopsCanPatrol ) ) ) {
1549 require_once( 'RecentChange.php' );
1550 RecentChange
::markPatrolled( $rcid );
1551 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, $wgOnlySysopsCanPatrol ) );
1552 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1553 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1555 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1556 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1560 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1565 * User-interface handler for the "watch" action
1570 global $wgUser, $wgOut;
1572 if ( $wgUser->isAnon() ) {
1573 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1576 if ( wfReadOnly() ) {
1577 $wgOut->readOnlyPage();
1581 if( $this->doWatch() ) {
1582 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1583 $wgOut->setRobotpolicy( 'noindex,follow' );
1585 $link = $this->mTitle
->getPrefixedText();
1586 $text = wfMsg( 'addedwatchtext', $link );
1587 $wgOut->addWikiText( $text );
1590 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1594 * Add this page to $wgUser's watchlist
1595 * @return bool true on successful watch operation
1597 function doWatch() {
1599 if( $wgUser->isAnon() ) {
1603 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1604 $wgUser->addWatch( $this->mTitle
);
1605 $wgUser->saveSettings();
1607 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1614 * User interface handler for the "unwatch" action.
1616 function unwatch() {
1618 global $wgUser, $wgOut;
1620 if ( $wgUser->isAnon() ) {
1621 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1624 if ( wfReadOnly() ) {
1625 $wgOut->readOnlyPage();
1629 if( $this->doUnwatch() ) {
1630 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1631 $wgOut->setRobotpolicy( 'noindex,follow' );
1633 $link = $this->mTitle
->getPrefixedText();
1634 $text = wfMsg( 'removedwatchtext', $link );
1635 $wgOut->addWikiText( $text );
1638 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1642 * Stop watching a page
1643 * @return bool true on successful unwatch
1645 function doUnwatch() {
1647 if( $wgUser->isAnon() ) {
1651 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1652 $wgUser->removeWatch( $this->mTitle
);
1653 $wgUser->saveSettings();
1655 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1662 * action=protect handler
1664 function protect() {
1665 require_once 'ProtectionForm.php';
1666 $form = new ProtectionForm( $this );
1671 * action=unprotect handler (alias)
1673 function unprotect() {
1678 * Update the article's restriction field, and leave a log entry.
1680 * @param array $limit set of restriction keys
1681 * @param string $reason
1682 * @return bool true on success
1684 function updateRestrictions( $limit = array(), $reason = '' ) {
1687 if ( !$wgUser->isAllowed( 'protect' ) ) {
1691 if( wfReadOnly() ) {
1695 $id = $this->mTitle
->getArticleID();
1700 $flat = Article
::flattenRestrictions( $limit );
1701 $protecting = ($flat != '');
1703 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser,
1704 $limit, $reason ) ) ) {
1706 $dbw =& wfGetDB( DB_MASTER
);
1707 $dbw->update( 'page',
1709 'page_touched' => $dbw->timestamp(),
1710 'page_restrictions' => $flat
1711 ), array( /* WHERE */
1713 ), 'Article::protect'
1716 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser,
1717 $limit, $reason ) );
1719 $log = new LogPage( 'protect' );
1721 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$flat]" ) );
1723 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1730 * Take an array of page restrictions and flatten it to a string
1731 * suitable for insertion into the page_restrictions field.
1732 * @param array $limit
1736 function flattenRestrictions( $limit ) {
1737 if( !is_array( $limit ) ) {
1738 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1741 foreach( $limit as $action => $restrictions ) {
1742 if( $restrictions != '' ) {
1743 $bits[] = "$action=$restrictions";
1746 return implode( ':', $bits );
1750 * UI entry point for page deletion
1753 global $wgUser, $wgOut, $wgRequest;
1754 $fname = 'Article::delete';
1755 $confirm = $wgRequest->wasPosted() &&
1756 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1757 $reason = $wgRequest->getText( 'wpReason' );
1759 # This code desperately needs to be totally rewritten
1762 if( $wgUser->isAllowed( 'delete' ) ) {
1763 if( $wgUser->isBlocked() ) {
1764 $wgOut->blockedPage();
1768 $wgOut->permissionRequired( 'delete' );
1772 if( wfReadOnly() ) {
1773 $wgOut->readOnlyPage();
1777 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1779 # Better double-check that it hasn't been deleted yet!
1780 $dbw =& wfGetDB( DB_MASTER
);
1781 $conds = $this->mTitle
->pageCond();
1782 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1783 if ( $latest === false ) {
1784 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1789 $this->doDelete( $reason );
1793 # determine whether this page has earlier revisions
1794 # and insert a warning if it does
1796 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1798 if( count( $authors ) > 1 && !$confirm ) {
1799 $skin=$wgUser->getSkin();
1800 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1801 $wgOut->addHTML( $skin->historyLink() .'</b>');
1804 # If a single user is responsible for all revisions, find out who they are
1805 if ( count( $authors ) == $maxRevisions ) {
1806 // Query bailed out, too many revisions to find out if they're all the same
1807 $authorOfAll = false;
1809 $authorOfAll = reset( $authors );
1810 foreach ( $authors as $author ) {
1811 if ( $authorOfAll != $author ) {
1812 $authorOfAll = false;
1817 # Fetch article text
1818 $rev = Revision
::newFromTitle( $this->mTitle
);
1820 if( !is_null( $rev ) ) {
1821 # if this is a mini-text, we can paste part of it into the deletion reason
1822 $text = $rev->getText();
1824 #if this is empty, an earlier revision may contain "useful" text
1827 $prev = $rev->getPrevious();
1829 $text = $prev->getText();
1834 $length = strlen( $text );
1836 # this should not happen, since it is not possible to store an empty, new
1837 # page. Let's insert a standard text in case it does, though
1838 if( $length == 0 && $reason === '' ) {
1839 $reason = wfMsgForContent( 'exblank' );
1842 if( $length < 500 && $reason === '' ) {
1843 # comment field=255, let's grep the first 150 to have some user
1846 $text = $wgContLang->truncate( $text, 150, '...' );
1848 # let's strip out newlines
1849 $text = preg_replace( "/[\n\r]/", '', $text );
1852 if( $authorOfAll === false ) {
1853 $reason = wfMsgForContent( 'excontent', $text );
1855 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1858 $reason = wfMsgForContent( 'exbeforeblank', $text );
1863 return $this->confirmDelete( '', $reason );
1867 * Get the last N authors
1868 * @param int $num Number of revisions to get
1869 * @param string $revLatest The latest rev_id, selected from the master (optional)
1870 * @return array Array of authors, duplicates not removed
1872 function getLastNAuthors( $num, $revLatest = 0 ) {
1873 $fname = 'Article::getLastNAuthors';
1874 wfProfileIn( $fname );
1876 // First try the slave
1877 // If that doesn't have the latest revision, try the master
1879 $db =& wfGetDB( DB_SLAVE
);
1881 $res = $db->select( array( 'page', 'revision' ),
1882 array( 'rev_id', 'rev_user_text' ),
1884 'page_namespace' => $this->mTitle
->getNamespace(),
1885 'page_title' => $this->mTitle
->getDBkey(),
1886 'rev_page = page_id'
1887 ), $fname, $this->getSelectOptions( array(
1888 'ORDER BY' => 'rev_timestamp DESC',
1893 wfProfileOut( $fname );
1896 $row = $db->fetchObject( $res );
1897 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1898 $db =& wfGetDB( DB_MASTER
);
1903 } while ( $continue );
1905 $authors = array( $row->rev_user_text
);
1906 while ( $row = $db->fetchObject( $res ) ) {
1907 $authors[] = $row->rev_user_text
;
1909 wfProfileOut( $fname );
1914 * Output deletion confirmation dialog
1916 function confirmDelete( $par, $reason ) {
1917 global $wgOut, $wgUser;
1919 wfDebug( "Article::confirmDelete\n" );
1921 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1922 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1923 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1924 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1926 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1928 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1929 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1930 $token = htmlspecialchars( $wgUser->editToken() );
1933 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1937 <label for='wpReason'>{$delcom}:</label>
1940 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1946 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1950 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1953 $wgOut->returnToMain( false );
1958 * Perform a deletion and output success or failure messages
1960 function doDelete( $reason ) {
1961 global $wgOut, $wgUser;
1962 $fname = 'Article::doDelete';
1963 wfDebug( $fname."\n" );
1965 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1966 if ( $this->doDeleteArticle( $reason ) ) {
1967 $deleted = $this->mTitle
->getPrefixedText();
1969 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1970 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1972 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1973 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1975 $wgOut->addWikiText( $text );
1976 $wgOut->returnToMain( false );
1977 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1979 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1985 * Back-end article deletion
1986 * Deletes the article with database consistency, writes logs, purges caches
1989 function doDeleteArticle( $reason ) {
1990 global $wgUseSquid, $wgDeferredUpdateList;
1991 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1993 $fname = 'Article::doDeleteArticle';
1994 wfDebug( $fname."\n" );
1996 $dbw =& wfGetDB( DB_MASTER
);
1997 $ns = $this->mTitle
->getNamespace();
1998 $t = $this->mTitle
->getDBkey();
1999 $id = $this->mTitle
->getArticleID();
2001 if ( $t == '' ||
$id == 0 ) {
2005 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2006 array_push( $wgDeferredUpdateList, $u );
2008 $linksTo = $this->mTitle
->getLinksTo();
2011 if ( $wgUseSquid ) {
2013 $this->mTitle
->getInternalURL(),
2014 $this->mTitle
->getInternalURL( 'history' )
2017 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
2018 array_push( $wgPostCommitUpdateList, $u );
2022 # Client and file cache invalidation
2023 Title
::touchArray( $linksTo );
2026 // For now, shunt the revision data into the archive table.
2027 // Text is *not* removed from the text table; bulk storage
2028 // is left intact to avoid breaking block-compression or
2029 // immutable storage schemes.
2031 // For backwards compatibility, note that some older archive
2032 // table entries will have ar_text and ar_flags fields still.
2034 // In the future, we may keep revisions and mark them with
2035 // the rev_deleted field, which is reserved for this purpose.
2036 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2038 'ar_namespace' => 'page_namespace',
2039 'ar_title' => 'page_title',
2040 'ar_comment' => 'rev_comment',
2041 'ar_user' => 'rev_user',
2042 'ar_user_text' => 'rev_user_text',
2043 'ar_timestamp' => 'rev_timestamp',
2044 'ar_minor_edit' => 'rev_minor_edit',
2045 'ar_rev_id' => 'rev_id',
2046 'ar_text_id' => 'rev_text_id',
2049 'page_id = rev_page'
2053 # Now that it's safely backed up, delete it
2054 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2055 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2057 if ($wgUseTrackbacks)
2058 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2060 # Clean up recentchanges entries...
2061 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2063 # Finally, clean up the link tables
2064 $t = $this->mTitle
->getPrefixedDBkey();
2066 Article
::onArticleDelete( $this->mTitle
);
2068 # Delete outgoing links
2069 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2070 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2071 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2072 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2073 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2076 $log = new LogPage( 'delete' );
2077 $log->addEntry( 'delete', $this->mTitle
, $reason );
2079 # Clear the cached article id so the interface doesn't act like we exist
2080 $this->mTitle
->resetArticleID( 0 );
2081 $this->mTitle
->mArticleID
= 0;
2086 * Revert a modification
2088 function rollback() {
2089 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2090 $fname = 'Article::rollback';
2092 if( $wgUser->isAllowed( 'rollback' ) ) {
2093 if( $wgUser->isBlocked() ) {
2094 $wgOut->blockedPage();
2098 $wgOut->permissionRequired( 'rollback' );
2102 if ( wfReadOnly() ) {
2103 $wgOut->readOnlyPage( $this->getContent() );
2106 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2107 array( $this->mTitle
->getPrefixedText(),
2108 $wgRequest->getVal( 'from' ) ) ) ) {
2109 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2110 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2113 $dbw =& wfGetDB( DB_MASTER
);
2115 # Enhanced rollback, marks edits rc_bot=1
2116 $bot = $wgRequest->getBool( 'bot' );
2118 # Replace all this user's current edits with the next one down
2119 $tt = $this->mTitle
->getDBKey();
2120 $n = $this->mTitle
->getNamespace();
2122 # Get the last editor, lock table exclusively
2124 $current = Revision
::newFromTitle( $this->mTitle
);
2125 if( is_null( $current ) ) {
2126 # Something wrong... no page?
2128 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2132 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2133 if( $from != $current->getUserText() ) {
2134 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2135 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2136 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2137 htmlspecialchars( $from ),
2138 htmlspecialchars( $current->getUserText() ) ) );
2139 if( $current->getComment() != '') {
2141 wfMsg( 'editcomment',
2142 htmlspecialchars( $current->getComment() ) ) );
2147 # Get the last edit not by this guy
2148 $user = intval( $current->getUser() );
2149 $user_text = $dbw->addQuotes( $current->getUserText() );
2150 $s = $dbw->selectRow( 'revision',
2151 array( 'rev_id', 'rev_timestamp' ),
2153 'rev_page' => $current->getPage(),
2154 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2157 'USE INDEX' => 'page_timestamp',
2158 'ORDER BY' => 'rev_timestamp DESC' )
2160 if( $s === false ) {
2163 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2164 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2170 # Mark all reverted edits as bot
2173 if ( $wgUseRCPatrol ) {
2174 # Mark all reverted edits as patrolled
2175 $set['rc_patrolled'] = 1;
2179 $dbw->update( 'recentchanges', $set,
2181 'rc_cur_id' => $current->getPage(),
2182 'rc_user_text' => $current->getUserText(),
2183 "rc_timestamp > '{$s->rev_timestamp}'",
2188 # Get the edit summary
2189 $target = Revision
::newFromId( $s->rev_id
);
2190 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2191 $newComment = $wgRequest->getText( 'summary', $newComment );
2194 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2195 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2196 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2198 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2199 Article
::onArticleEdit( $this->mTitle
);
2202 $wgOut->returnToMain( false );
2207 * Do standard deferred updates after page view
2210 function viewUpdates() {
2211 global $wgDeferredUpdateList;
2213 if ( 0 != $this->getID() ) {
2214 global $wgDisableCounters;
2215 if( !$wgDisableCounters ) {
2216 Article
::incViewCount( $this->getID() );
2217 $u = new SiteStatsUpdate( 1, 0, 0 );
2218 array_push( $wgDeferredUpdateList, $u );
2222 # Update newtalk / watchlist notification status
2224 $wgUser->clearNotification( $this->mTitle
);
2228 * Do standard deferred updates after page edit.
2229 * Every 1000th edit, prune the recent changes table.
2231 * @param string $text
2233 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2234 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2236 $fname = 'Article::editUpdates';
2237 wfProfileIn( $fname );
2240 $options = new ParserOptions
;
2241 $options->setTidy(true);
2242 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2244 # Save it to the parser cache
2245 $parserCache =& ParserCache
::singleton();
2246 $parserCache->save( $poutput, $this, $wgUser );
2248 # Update the links tables
2249 $u = new LinksUpdate( $this->mTitle
, $poutput );
2252 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2254 if ( 0 == mt_rand( 0, 999 ) ) {
2255 # Periodically flush old entries from the recentchanges table.
2258 $dbw =& wfGetDB( DB_MASTER
);
2259 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2260 $recentchanges = $dbw->tableName( 'recentchanges' );
2261 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2262 $dbw->query( $sql );
2266 $id = $this->getID();
2267 $title = $this->mTitle
->getPrefixedDBkey();
2268 $shortTitle = $this->mTitle
->getDBkey();
2271 wfProfileOut( $fname );
2275 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2276 array_push( $wgDeferredUpdateList, $u );
2277 $u = new SearchUpdate( $id, $title, $text );
2278 array_push( $wgDeferredUpdateList, $u );
2280 # If this is another user's talk page, update newtalk
2282 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
2283 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2284 $other = User
::newFromName( $shortTitle );
2285 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2286 // An anonymous user
2287 $other = new User();
2288 $other->setName( $shortTitle );
2291 $other->setNewtalk( true );
2296 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2297 $wgMessageCache->replace( $shortTitle, $text );
2300 wfProfileOut( $fname );
2304 * Generate the navigation links when browsing through an article revisions
2305 * It shows the information as:
2306 * Revision as of <date>; view current revision
2307 * <- Previous version | Next Version ->
2310 * @param string $oldid Revision ID of this article revision
2312 function setOldSubtitle( $oldid=0 ) {
2313 global $wgLang, $wgOut, $wgUser;
2315 $current = ( $oldid == $this->mLatest
);
2316 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2317 $sk = $wgUser->getSkin();
2319 ?
wfMsg( 'currentrevisionlink' )
2320 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2321 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2323 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2324 : wfMsg( 'previousrevision' );
2325 $nextlink = $current
2326 ?
wfMsg( 'nextrevision' )
2327 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2328 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2329 $wgOut->setSubtitle( $r );
2333 * This function is called right before saving the wikitext,
2334 * so we can do things like signatures and links-in-context.
2336 * @param string $text
2338 function preSaveTransform( $text ) {
2339 global $wgParser, $wgUser;
2340 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2343 /* Caching functions */
2346 * checkLastModified returns true if it has taken care of all
2347 * output to the client that is necessary for this request.
2348 * (that is, it has sent a cached version of the page)
2350 function tryFileCache() {
2351 static $called = false;
2353 wfDebug( " tryFileCache() -- called twice!?\n" );
2357 if($this->isFileCacheable()) {
2358 $touched = $this->mTouched
;
2359 $cache = new CacheManager( $this->mTitle
);
2360 if($cache->isFileCacheGood( $touched )) {
2361 wfDebug( " tryFileCache() - about to load\n" );
2362 $cache->loadFromFileCache();
2365 wfDebug( " tryFileCache() - starting buffer\n" );
2366 ob_start( array(&$cache, 'saveToFileCache' ) );
2369 wfDebug( " tryFileCache() - not cacheable\n" );
2374 * Check if the page can be cached
2377 function isFileCacheable() {
2378 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2379 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2381 return $wgUseFileCache
2382 and (!$wgShowIPinHeader)
2383 and ($this->getID() != 0)
2384 and ($wgUser->isAnon())
2385 and (!$wgUser->getNewtalk())
2386 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2387 and (empty( $action ) ||
$action == 'view')
2388 and (!isset($oldid))
2390 and (!isset($redirect))
2391 and (!isset($printable))
2392 and (!$this->mRedirectedFrom
);
2396 * Loads page_touched and returns a value indicating if it should be used
2399 function checkTouched() {
2400 $fname = 'Article::checkTouched';
2401 if( !$this->mDataLoaded
) {
2402 $this->loadPageData();
2404 return !$this->mIsRedirect
;
2408 * Get the page_touched field
2410 function getTouched() {
2411 # Ensure that page data has been loaded
2412 if( !$this->mDataLoaded
) {
2413 $this->loadPageData();
2415 return $this->mTouched
;
2419 * Get the page_latest field
2421 function getLatest() {
2422 if ( !$this->mDataLoaded
) {
2423 $this->loadPageData();
2425 return $this->mLatest
;
2429 * Edit an article without doing all that other stuff
2430 * The article must already exist; link tables etc
2431 * are not updated, caches are not flushed.
2433 * @param string $text text submitted
2434 * @param string $comment comment submitted
2435 * @param bool $minor whereas it's a minor modification
2437 function quickEdit( $text, $comment = '', $minor = 0 ) {
2438 $fname = 'Article::quickEdit';
2439 wfProfileIn( $fname );
2441 $dbw =& wfGetDB( DB_MASTER
);
2443 $revision = new Revision( array(
2444 'page' => $this->getId(),
2446 'comment' => $comment,
2447 'minor_edit' => $minor ?
1 : 0,
2449 $revisionId = $revision->insertOn( $dbw );
2450 $this->updateRevisionOn( $dbw, $revision );
2453 wfProfileOut( $fname );
2457 * Used to increment the view counter
2460 * @param integer $id article id
2462 function incViewCount( $id ) {
2463 $id = intval( $id );
2464 global $wgHitcounterUpdateFreq;
2466 $dbw =& wfGetDB( DB_MASTER
);
2467 $pageTable = $dbw->tableName( 'page' );
2468 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2469 $acchitsTable = $dbw->tableName( 'acchits' );
2471 if( $wgHitcounterUpdateFreq <= 1 ){ //
2472 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2476 # Not important enough to warrant an error page in case of failure
2477 $oldignore = $dbw->ignoreErrors( true );
2479 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2481 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2482 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2483 # Most of the time (or on SQL errors), skip row count check
2484 $dbw->ignoreErrors( $oldignore );
2488 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2489 $row = $dbw->fetchObject( $res );
2490 $rown = intval( $row->n
);
2491 if( $rown >= $wgHitcounterUpdateFreq ){
2492 wfProfileIn( 'Article::incViewCount-collect' );
2493 $old_user_abort = ignore_user_abort( true );
2495 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2496 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable ENGINE=HEAP ".
2497 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2499 $dbw->query("DELETE FROM $hitcounterTable");
2500 $dbw->query('UNLOCK TABLES');
2501 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2502 'WHERE page_id = hc_id');
2503 $dbw->query("DROP TABLE $acchitsTable");
2505 ignore_user_abort( $old_user_abort );
2506 wfProfileOut( 'Article::incViewCount-collect' );
2508 $dbw->ignoreErrors( $oldignore );
2512 * The onArticle*() functions are supposed to be a kind of hooks
2513 * which should be called whenever any of the specified actions
2516 * This is a good place to put code to clear caches, for instance.
2518 * This is called on page move and undelete, as well as edit
2520 * @param $title_obj a title object
2523 function onArticleCreate($title_obj) {
2524 global $wgUseSquid, $wgPostCommitUpdateList;
2526 $title_obj->touchLinks();
2527 $titles = $title_obj->getLinksTo();
2530 if ( $wgUseSquid ) {
2531 $urls = $title_obj->getSquidURLs();
2532 foreach ( $titles as $linkTitle ) {
2533 $urls[] = $linkTitle->getInternalURL();
2535 $u = new SquidUpdate( $urls );
2536 array_push( $wgPostCommitUpdateList, $u );
2540 function onArticleDelete( $title ) {
2541 global $wgMessageCache;
2543 $title->touchLinks();
2545 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2546 $wgMessageCache->replace( $title->getDBkey(), false );
2551 * Purge caches on page update etc
2553 function onArticleEdit( $title ) {
2554 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2558 // Template namespace? Purge all articles linking here.
2559 // FIXME: When a templatelinks table arrives, use it for all includes.
2560 if ( $title->getNamespace() == NS_TEMPLATE
) {
2561 $titles = $title->getLinksTo();
2562 Title
::touchArray( $titles );
2563 if ( $wgUseSquid ) {
2564 foreach ( $titles as $link ) {
2565 $urls[] = $link->getInternalURL();
2571 if ( $wgUseSquid ) {
2572 $urls = array_merge( $urls, $title->getSquidURLs() );
2573 $u = new SquidUpdate( $urls );
2574 array_push( $wgPostCommitUpdateList, $u );
2578 if ( $wgUseFileCache ) {
2579 $cm = new CacheManager( $title );
2580 @unlink
( $cm->fileCacheName() );
2587 * Info about this page
2588 * Called for ?action=info when $wgAllowPageInfo is on.
2593 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2594 $fname = 'Article::info';
2596 if ( !$wgAllowPageInfo ) {
2597 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2601 $page = $this->mTitle
->getSubjectPage();
2603 $wgOut->setPagetitle( $page->getPrefixedText() );
2604 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2606 # first, see if the page exists at all.
2607 $exists = $page->getArticleId() != 0;
2609 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2610 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2612 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2615 $dbr =& wfGetDB( DB_SLAVE
);
2617 'wl_title' => $page->getDBkey(),
2618 'wl_namespace' => $page->getNamespace() );
2619 $numwatchers = $dbr->selectField(
2624 $this->getSelectOptions() );
2626 $pageInfo = $this->pageCountInfo( $page );
2627 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2629 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2630 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2632 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2634 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2636 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2638 $wgOut->addHTML( '</ul>' );
2644 * Return the total number of edits and number of unique editors
2645 * on a given page. If page does not exist, returns false.
2647 * @param Title $title
2651 function pageCountInfo( $title ) {
2652 $id = $title->getArticleId();
2657 $dbr =& wfGetDB( DB_SLAVE
);
2659 $rev_clause = array( 'rev_page' => $id );
2660 $fname = 'Article::pageCountInfo';
2662 $edits = $dbr->selectField(
2667 $this->getSelectOptions() );
2669 $authors = $dbr->selectField(
2671 'COUNT(DISTINCT rev_user_text)',
2674 $this->getSelectOptions() );
2676 return array( 'edits' => $edits, 'authors' => $authors );
2680 * Return a list of templates used by this article.
2681 * Uses the templatelinks table
2683 * @return array Array of Title objects
2685 function getUsedTemplates() {
2687 $id = $this->mTitle
->getArticleID();
2692 $dbr =& wfGetDB( DB_SLAVE
);
2693 $res = $dbr->select( array( 'templatelinks' ),
2694 array( 'tl_namespace', 'tl_title' ),
2695 array( 'tl_from' => $id ),
2696 'Article:getUsedTemplates' );
2697 if ( false !== $res ) {
2698 if ( $dbr->numRows( $res ) ) {
2699 while ( $row = $dbr->fetchObject( $res ) ) {
2700 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2704 $dbr->freeResult( $res );