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 if($action=='edit') {
180 if($section=='new') {
181 wfProfileOut( $fname );
182 $text=$this->getPreloadedText($preload);
186 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
187 # comments to be stripped as well)
188 $rv=$this->getSection($this->mContent
,$section);
189 wfProfileOut( $fname );
193 wfProfileOut( $fname );
194 return $this->mContent
;
199 * Get the contents of a page from its title and remove includeonly tags
201 * @param string The title of the page
202 * @return string The contents of the page
204 function getPreloadedText($preload) {
205 if ( $preload === '' )
208 $preloadTitle = Title
::newFromText( $preload );
209 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
210 $rev=Revision
::newFromTitle($preloadTitle);
211 if ( is_object( $rev ) ) {
212 $text = $rev->getText();
213 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
214 // its own mini-parser! -ævar
215 $text = preg_replace( '~</?includeonly>~', '', $text );
224 * This function returns the text of a section, specified by a number ($section).
225 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
226 * the first section before any such heading (section 0).
228 * If a section contains subsections, these are also returned.
230 * @param string $text text to look in
231 * @param integer $section section number
232 * @return string text of the requested section
234 function getSection($text,$section) {
236 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
237 # comments to be stripped as well)
239 $parser=new Parser();
240 $parser->mOutputType
=OT_WIKI
;
241 $parser->mOptions
= new ParserOptions();
242 $striptext=$parser->strip($text, $striparray, true);
244 # now that we can be sure that no pseudo-sections are in the source,
245 # split it up by section
248 '/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
250 PREG_SPLIT_DELIM_CAPTURE
);
254 $headline=$secs[$section*2-1];
255 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
258 # translate wiki heading into level
259 if(strpos($hlevel,'=')!==false) {
260 $hlevel=strlen($hlevel);
263 $rv=$headline. $secs[$section*2];
267 while(!empty($secs[$count*2-1]) && !$break) {
269 $subheadline=$secs[$count*2-1];
270 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
271 $subhlevel=$matches[1];
272 if(strpos($subhlevel,'=')!==false) {
273 $subhlevel=strlen($subhlevel);
275 if($subhlevel > $hlevel) {
276 $rv.=$subheadline.$secs[$count*2];
278 if($subhlevel <= $hlevel) {
285 # reinsert stripped tags
286 $rv=$parser->unstrip($rv,$striparray);
287 $rv=$parser->unstripNoWiki($rv,$striparray);
294 * @return int The oldid of the article that is to be shown, 0 for the
297 function getOldID() {
298 if ( is_null( $this->mOldId
) ) {
299 $this->mOldId
= $this->getOldIDFromRequest();
301 return $this->mOldId
;
305 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
307 * @return int The old id for the request
309 function getOldIDFromRequest() {
311 $this->mRedirectUrl
= false;
312 $oldid = $wgRequest->getVal( 'oldid' );
313 if ( isset( $oldid ) ) {
314 $oldid = intval( $oldid );
315 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
316 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
320 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
322 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
323 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
339 * Load the revision (including text) into this object
341 function loadContent() {
342 if ( $this->mContentLoaded
) return;
345 $oldid = $this->getOldID();
347 $fname = 'Article::loadContent';
349 # Pre-fill content with error message so that if something
350 # fails we'll have something telling us what we intended.
352 $t = $this->mTitle
->getPrefixedText();
354 $this->mOldId
= $oldid;
355 $this->fetchContent( $oldid );
360 * Fetch a page record with the given conditions
361 * @param Database $dbr
362 * @param array $conditions
365 function pageData( &$dbr, $conditions ) {
378 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
379 $row = $dbr->selectRow( 'page',
382 'Article::pageData' );
383 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
388 * @param Database $dbr
389 * @param Title $title
391 function pageDataFromTitle( &$dbr, $title ) {
392 return $this->pageData( $dbr, array(
393 'page_namespace' => $title->getNamespace(),
394 'page_title' => $title->getDBkey() ) );
398 * @param Database $dbr
401 function pageDataFromId( &$dbr, $id ) {
402 return $this->pageData( $dbr, array( 'page_id' => $id ) );
406 * Set the general counter, title etc data loaded from
409 * @param object $data
412 function loadPageData( $data = 'fromdb' ) {
413 if ( $data === 'fromdb' ) {
414 $dbr =& $this->getDB();
415 $data = $this->pageDataFromId( $dbr, $this->getId() );
418 $lc =& LinkCache
::singleton();
420 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
422 $this->mTitle
->mArticleID
= $data->page_id
;
423 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
424 $this->mTitle
->mRestrictionsLoaded
= true;
426 $this->mCounter
= $data->page_counter
;
427 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
428 $this->mIsRedirect
= $data->page_is_redirect
;
429 $this->mLatest
= $data->page_latest
;
431 if ( is_object( $this->mTitle
) ) {
432 $lc->addBadLinkObj( $this->mTitle
);
434 $this->mTitle
->mArticleID
= 0;
437 $this->mDataLoaded
= true;
441 * Get text of an article from database
442 * Does *NOT* follow redirects.
443 * @param int $oldid 0 for whatever the latest revision is
446 function fetchContent( $oldid = 0 ) {
447 if ( $this->mContentLoaded
) {
448 return $this->mContent
;
451 $dbr =& $this->getDB();
452 $fname = 'Article::fetchContent';
454 # Pre-fill content with error message so that if something
455 # fails we'll have something telling us what we intended.
456 $t = $this->mTitle
->getPrefixedText();
458 $t .= ',oldid='.$oldid;
460 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
463 $revision = Revision
::newFromId( $oldid );
464 if( is_null( $revision ) ) {
465 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
468 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
470 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
473 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
474 $this->loadPageData( $data );
476 if( !$this->mDataLoaded
) {
477 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
479 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
482 $this->loadPageData( $data );
484 $revision = Revision
::newFromId( $this->mLatest
);
485 if( is_null( $revision ) ) {
486 wfDebug( "$fname failed to retrieve current page, rev_id {$data->page_latest}\n" );
491 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
492 // We should instead work with the Revision object when we need it...
493 $this->mContent
= $revision->userCan( MW_REV_DELETED_TEXT
) ?
$revision->getRawText() : "";
494 //$this->mContent = $revision->getText();
496 $this->mUser
= $revision->getUser();
497 $this->mUserText
= $revision->getUserText();
498 $this->mComment
= $revision->getComment();
499 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
501 $this->mRevIdFetched
= $revision->getID();
502 $this->mContentLoaded
= true;
503 $this->mRevision
=& $revision;
505 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
507 return $this->mContent
;
511 * Read/write accessor to select FOR UPDATE
515 function forUpdate( $x = NULL ) {
516 return wfSetVar( $this->mForUpdate
, $x );
520 * Get the database which should be used for reads
525 $ret =& wfGetDB( DB_MASTER
);
530 * Get options for all SELECT statements
532 * @param array $options an optional options array which'll be appended to
534 * @return array Options
536 function getSelectOptions( $options = '' ) {
537 if ( $this->mForUpdate
) {
538 if ( is_array( $options ) ) {
539 $options[] = 'FOR UPDATE';
541 $options = 'FOR UPDATE';
548 * @return int Page ID
551 if( $this->mTitle
) {
552 return $this->mTitle
->getArticleID();
559 * @return bool Whether or not the page exists in the database
562 return $this->getId() != 0;
566 * @return int The view count for the page
568 function getCount() {
569 if ( -1 == $this->mCounter
) {
570 $id = $this->getID();
574 $dbr =& wfGetDB( DB_SLAVE
);
575 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
576 'Article::getCount', $this->getSelectOptions() );
579 return $this->mCounter
;
583 * Determine whether a page would be suitable for being counted as an
584 * article in the site_stats table based on the title & its content
586 * @param string $text Text to analyze
589 function isCountable( $text ) {
590 global $wgUseCommaCount;
592 $token = $wgUseCommaCount ?
',' : '[[';
594 $this->mTitle
->getNamespace() == NS_MAIN
595 && ! $this->isRedirect( $text )
596 && in_string( $token, $text );
600 * Tests if the article text represents a redirect
602 * @param string $text
605 function isRedirect( $text = false ) {
606 if ( $text === false ) {
607 $this->loadContent();
608 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
610 $titleObj = Title
::newFromRedirect( $text );
612 return $titleObj !== NULL;
616 * Returns true if the currently-referenced revision is the current edit
617 * to this page (and it exists).
620 function isCurrent() {
621 return $this->exists() &&
622 isset( $this->mRevision
) &&
623 $this->mRevision
->isCurrent();
627 * Loads everything except the text
628 * This isn't necessary for all uses, so it's only done if needed.
631 function loadLastEdit() {
632 if ( -1 != $this->mUser
)
635 # New or non-existent articles have no user information
636 $id = $this->getID();
637 if ( 0 == $id ) return;
639 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
640 if( !is_null( $this->mLastRevision
) ) {
641 $this->mUser
= $this->mLastRevision
->getUser();
642 $this->mUserText
= $this->mLastRevision
->getUserText();
643 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
644 $this->mComment
= $this->mLastRevision
->getComment();
645 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
646 $this->mRevIdFetched
= $this->mLastRevision
->getID();
650 function getTimestamp() {
651 // Check if the field has been filled by ParserCache::get()
652 if ( !$this->mTimestamp
) {
653 $this->loadLastEdit();
655 return wfTimestamp(TS_MW
, $this->mTimestamp
);
659 $this->loadLastEdit();
663 function getUserText() {
664 $this->loadLastEdit();
665 return $this->mUserText
;
668 function getComment() {
669 $this->loadLastEdit();
670 return $this->mComment
;
673 function getMinorEdit() {
674 $this->loadLastEdit();
675 return $this->mMinorEdit
;
678 function getRevIdFetched() {
679 $this->loadLastEdit();
680 return $this->mRevIdFetched
;
683 function getContributors($limit = 0, $offset = 0) {
684 $fname = 'Article::getContributors';
686 # XXX: this is expensive; cache this info somewhere.
688 $title = $this->mTitle
;
690 $dbr =& wfGetDB( DB_SLAVE
);
691 $revTable = $dbr->tableName( 'revision' );
692 $userTable = $dbr->tableName( 'user' );
693 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
694 $ns = $title->getNamespace();
695 $user = $this->getUser();
696 $pageId = $this->getId();
698 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
699 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
700 WHERE rev_page = $pageId
701 AND rev_user != $user
702 GROUP BY rev_user, rev_user_text, user_real_name
703 ORDER BY timestamp DESC";
705 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
706 $sql .= ' '. $this->getSelectOptions();
708 $res = $dbr->query($sql, $fname);
710 while ( $line = $dbr->fetchObject( $res ) ) {
711 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
714 $dbr->freeResult($res);
719 * This is the default action of the script: just view the page of
723 global $wgUser, $wgOut, $wgRequest, $wgContLang;
724 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
725 global $wgUseTrackbacks;
726 $sk = $wgUser->getSkin();
728 $fname = 'Article::view';
729 wfProfileIn( $fname );
730 $parserCache =& ParserCache
::singleton();
731 # Get variables from query string
732 $oldid = $this->getOldID();
734 # getOldID may want us to redirect somewhere else
735 if ( $this->mRedirectUrl
) {
736 $wgOut->redirect( $this->mRedirectUrl
);
737 wfProfileOut( $fname );
741 $diff = $wgRequest->getVal( 'diff' );
742 $rcid = $wgRequest->getVal( 'rcid' );
743 $rdfrom = $wgRequest->getVal( 'rdfrom' );
745 $wgOut->setArticleFlag( true );
746 $wgOut->setRobotpolicy( 'index,follow' );
747 # If we got diff and oldid in the query, we want to see a
748 # diff page instead of the article.
750 if ( !is_null( $diff ) ) {
751 require_once( 'DifferenceEngine.php' );
752 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
754 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
755 // DifferenceEngine directly fetched the revision:
756 $this->mRevIdFetched
= $de->mNewid
;
760 # Run view updates for current revision only
761 $this->viewUpdates();
763 wfProfileOut( $fname );
767 if ( empty( $oldid ) && $this->checkTouched() ) {
768 $wgOut->setETag($parserCache->getETag($this, $wgUser));
770 if( $wgOut->checkLastModified( $this->mTouched
) ){
771 wfProfileOut( $fname );
773 } else if ( $this->tryFileCache() ) {
774 # tell wgOut that output is taken care of
776 $this->viewUpdates();
777 wfProfileOut( $fname );
781 # Should the parser cache be used?
782 $pcache = $wgEnableParserCache &&
783 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
786 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
787 if ( $wgUser->getOption( 'stubthreshold' ) ) {
788 wfIncrStats( 'pcache_miss_stub' );
791 $wasRedirected = false;
792 if ( isset( $this->mRedirectedFrom
) ) {
793 // This is an internally redirected page view.
794 // We'll need a backlink to the source page for navigation.
795 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
796 $sk = $wgUser->getSkin();
797 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
798 $s = wfMsg( 'redirectedfrom', $redir );
799 $wgOut->setSubtitle( $s );
800 $wasRedirected = true;
802 } elseif ( !empty( $rdfrom ) ) {
803 // This is an externally redirected view, from some other wiki.
804 // If it was reported from a trusted site, supply a backlink.
805 global $wgRedirectSources;
806 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
807 $sk = $wgUser->getSkin();
808 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
809 $s = wfMsg( 'redirectedfrom', $redir );
810 $wgOut->setSubtitle( $s );
811 $wasRedirected = true;
817 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
821 if ( !$outputDone ) {
822 $text = $this->getContent();
823 if ( $text === false ) {
824 # Failed to load, replace text with error message
825 $t = $this->mTitle
->getPrefixedText();
827 $t .= ',oldid='.$oldid;
828 $text = wfMsg( 'missingarticle', $t );
830 $text = wfMsg( 'noarticletext', $t );
834 # Another whitelist check in case oldid is altering the title
835 if ( !$this->mTitle
->userCanRead() ) {
836 $wgOut->loginToUse();
841 # We're looking at an old revision
843 if ( !empty( $oldid ) ) {
844 $wgOut->setRobotpolicy( 'noindex,nofollow' );
845 if( is_null( $this->mRevision
) ) {
846 // FIXME: This would be a nice place to load the 'no such page' text.
848 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
849 if( $this->mRevision
->isDeleted( MW_REV_DELETED_TEXT
) ) {
850 if( !$this->mRevision
->userCan( MW_REV_DELETED_TEXT
) ) {
851 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
852 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
855 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
856 // and we are allowed to see...
865 * @fixme: this hook doesn't work most of the time, as it doesn't
866 * trigger when the parser cache is used.
868 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
869 $wgOut->setRevisionId( $this->getRevIdFetched() );
870 # wrap user css and user js in pre and don't parse
871 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
873 $this->mTitle
->getNamespace() == NS_USER
&&
874 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
876 $wgOut->addWikiText( wfMsg('clearyourcache'));
877 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
878 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
880 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
881 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
882 if( !$wasRedirected ) {
883 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
885 $targetUrl = $rt->escapeLocalURL();
886 $titleText = htmlspecialchars( $rt->getPrefixedText() );
887 $link = $sk->makeLinkObj( $rt );
889 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
890 '<span class="redirectText">'.$link.'</span>' );
892 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
893 $wgOut->addParserOutputNoText( $parseout );
894 } else if ( $pcache ) {
895 # Display content and save to parser cache
896 $wgOut->addPrimaryWikiText( $text, $this );
898 # Display content, don't attempt to save to parser cache
900 # Don't show section-edit links on old revisions... this way lies madness.
901 if( !$this->isCurrent() ) {
902 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
904 # Display content and don't save to parser cache
905 $wgOut->addPrimaryWikiText( $text, $this, false );
907 if( !$this->isCurrent() ) {
908 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
912 /* title may have been set from the cache */
913 $t = $wgOut->getPageTitle();
915 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
918 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
919 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
920 User
::isIP( $this->mTitle
->getText() ) ) {
921 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
924 # If we have been passed an &rcid= parameter, we want to give the user a
925 # chance to mark this new article as patrolled.
926 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
928 "<div class='patrollink'>" .
929 wfMsg ( 'markaspatrolledlink',
930 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
937 if ($wgUseTrackbacks)
938 $this->addTrackbacks();
940 $this->viewUpdates();
941 wfProfileOut( $fname );
944 function addTrackbacks() {
945 global $wgOut, $wgUser;
947 $dbr =& wfGetDB(DB_SLAVE
);
949 /* FROM */ 'trackbacks',
950 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
951 /* WHERE */ array('tb_page' => $this->getID())
954 if (!$dbr->numrows($tbs))
958 while ($o = $dbr->fetchObject($tbs)) {
960 if ($wgUser->isSysop()) {
961 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
962 . $o->tb_id
. "&token=" . $wgUser->editToken());
963 $rmvtxt = wfMsg('trackbackremove', $delurl);
965 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
972 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
975 function deletetrackback() {
976 global $wgUser, $wgRequest, $wgOut, $wgTitle;
978 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
979 $wgOut->addWikitext(wfMsg('sessionfailure'));
983 if ((!$wgUser->isAllowed('delete'))) {
984 $wgOut->sysopRequired();
989 $wgOut->readOnlyPage();
993 $db =& wfGetDB(DB_MASTER
);
994 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
995 $wgTitle->invalidateCache();
996 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
1002 $wgOut->setArticleBodyOnly(true);
1007 * Handle action=purge
1010 global $wgUser, $wgRequest, $wgOut;
1012 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
1013 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1017 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1018 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
1019 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1020 $msg = str_replace( '$1',
1021 "<form method=\"post\" action=\"$action\">\n" .
1022 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1023 "</form>\n", $msg );
1025 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1026 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1027 $wgOut->addHTML( $msg );
1032 * Perform the actions of a page purging
1034 function doPurge() {
1036 // Invalidate the cache
1037 $this->mTitle
->invalidateCache();
1039 if ( $wgUseSquid ) {
1040 // Commit the transaction before the purge is sent
1041 $dbw = wfGetDB( DB_MASTER
);
1042 $dbw->immediateCommit();
1045 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1046 $update->doUpdate();
1052 * Insert a new empty page record for this article.
1053 * This *must* be followed up by creating a revision
1054 * and running $this->updateToLatest( $rev_id );
1055 * or else the record will be left in a funky state.
1056 * Best if all done inside a transaction.
1058 * @param Database $dbw
1059 * @param string $restrictions
1060 * @return int The newly created page_id key
1063 function insertOn( &$dbw, $restrictions = '' ) {
1064 $fname = 'Article::insertOn';
1065 wfProfileIn( $fname );
1067 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1068 $dbw->insert( 'page', array(
1069 'page_id' => $page_id,
1070 'page_namespace' => $this->mTitle
->getNamespace(),
1071 'page_title' => $this->mTitle
->getDBkey(),
1072 'page_counter' => 0,
1073 'page_restrictions' => $restrictions,
1074 'page_is_redirect' => 0, # Will set this shortly...
1076 'page_random' => wfRandom(),
1077 'page_touched' => $dbw->timestamp(),
1078 'page_latest' => 0, # Fill this in shortly...
1079 'page_len' => 0, # Fill this in shortly...
1081 $newid = $dbw->insertId();
1083 $this->mTitle
->resetArticleId( $newid );
1085 wfProfileOut( $fname );
1090 * Update the page record to point to a newly saved revision.
1092 * @param Database $dbw
1093 * @param Revision $revision For ID number, and text used to set
1094 length and redirect status fields
1095 * @param int $lastRevision If given, will not overwrite the page field
1096 * when different from the currently set value.
1097 * Giving 0 indicates the new page flag should
1099 * @return bool true on success, false on failure
1102 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1103 $fname = 'Article::updateToRevision';
1104 wfProfileIn( $fname );
1106 $conditions = array( 'page_id' => $this->getId() );
1107 if( !is_null( $lastRevision ) ) {
1108 # An extra check against threads stepping on each other
1109 $conditions['page_latest'] = $lastRevision;
1112 $text = $revision->getText();
1113 $dbw->update( 'page',
1115 'page_latest' => $revision->getId(),
1116 'page_touched' => $dbw->timestamp(),
1117 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1118 'page_is_redirect' => Article
::isRedirect( $text ) ?
1 : 0,
1119 'page_len' => strlen( $text ),
1124 wfProfileOut( $fname );
1125 return ( $dbw->affectedRows() != 0 );
1129 * If the given revision is newer than the currently set page_latest,
1130 * update the page record. Otherwise, do nothing.
1132 * @param Database $dbw
1133 * @param Revision $revision
1135 function updateIfNewerOn( &$dbw, $revision ) {
1136 $fname = 'Article::updateIfNewerOn';
1137 wfProfileIn( $fname );
1139 $row = $dbw->selectRow(
1140 array( 'revision', 'page' ),
1141 array( 'rev_id', 'rev_timestamp' ),
1143 'page_id' => $this->getId(),
1144 'page_latest=rev_id' ),
1147 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1148 wfProfileOut( $fname );
1151 $prev = $row->rev_id
;
1153 # No or missing previous revision; mark the page as new
1157 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1158 wfProfileOut( $fname );
1163 * Insert a new article into the database
1166 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1169 $fname = 'Article::insertNewArticle';
1170 wfProfileIn( $fname );
1172 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1173 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1174 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1175 wfProfileOut( $fname );
1179 $ns = $this->mTitle
->getNamespace();
1180 $ttl = $this->mTitle
->getDBkey();
1182 # If this is a comment, add the summary as headline
1183 if($comment && $summary!="") {
1184 $text="== {$summary} ==\n\n".$text;
1186 $text = $this->preSaveTransform( $text );
1189 # Set statistics members
1190 # We work out if it's countable after PST to avoid counter drift
1191 # when articles are created with {{subst:}}
1192 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1193 $this->mTotalAdjustment
= 1;
1195 /* Silently ignore minoredit if not allowed */
1196 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1197 $now = wfTimestampNow();
1199 $dbw =& wfGetDB( DB_MASTER
);
1201 # Add the page record; stake our claim on this title!
1202 $newid = $this->insertOn( $dbw );
1204 # Save the revision text...
1205 $revision = new Revision( array(
1207 'comment' => $summary,
1208 'minor_edit' => $isminor,
1211 $revisionId = $revision->insertOn( $dbw );
1213 $this->mTitle
->resetArticleID( $newid );
1215 # Update the page record with revision data
1216 $this->updateRevisionOn( $dbw, $revision, 0 );
1218 Article
::onArticleCreate( $this->mTitle
);
1220 require_once( 'RecentChange.php' );
1221 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, 'default',
1222 '', strlen( $text ), $revisionId );
1223 # Mark as patrolled if the user can and has the option set
1224 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1225 RecentChange
::markPatrolled( $rcid );
1230 if(!$this->mTitle
->userIsWatching()) $this->doWatch();
1232 if ( $this->mTitle
->userIsWatching() ) {
1237 # The talk page isn't in the regular link tables, so we need to update manually:
1238 $talkns = $ns ^
1; # talk -> normal; normal -> talk
1239 $dbw->update( 'page',
1240 array( 'page_touched' => $dbw->timestamp($now) ),
1241 array( 'page_namespace' => $talkns,
1242 'page_title' => $ttl ),
1245 # standard deferred updates
1246 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1248 $oldid = 0; # new article
1249 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1251 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1253 $watchthis, NULL ) );
1254 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1256 $watchthis, NULL ) );
1257 wfProfileOut( $fname );
1260 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1261 $this->replaceSection( $section, $text, $summary, $edittime );
1265 * @return string Complete article text, or null if error
1267 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1268 $fname = 'Article::replaceSection';
1269 wfProfileIn( $fname );
1271 if ($section != '') {
1272 if( is_null( $edittime ) ) {
1273 $rev = Revision
::newFromTitle( $this->mTitle
);
1275 $dbw =& wfGetDB( DB_MASTER
);
1276 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1278 if( is_null( $rev ) ) {
1279 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1280 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1283 $oldtext = $rev->getText();
1285 if($section=='new') {
1286 if($summary) $subject="== {$summary} ==\n\n";
1287 $text=$oldtext."\n\n".$subject.$text;
1290 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1291 # comments to be stripped as well)
1292 $striparray=array();
1293 $parser=new Parser();
1294 $parser->mOutputType
=OT_WIKI
;
1295 $parser->mOptions
= new ParserOptions();
1296 $oldtext=$parser->strip($oldtext, $striparray, true);
1298 # now that we can be sure that no pseudo-sections are in the source,
1300 # Unfortunately we can't simply do a preg_replace because that might
1301 # replace the wrong section, so we have to use the section counter instead
1302 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1303 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1304 $secs[$section*2]=$text."\n\n"; // replace with edited
1306 # section 0 is top (intro) section
1309 # headline of old section - we need to go through this section
1310 # to determine if there are any subsections that now need to
1311 # be erased, as the mother section has been replaced with
1312 # the text of all subsections.
1313 $headline=$secs[$section*2-1];
1314 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1315 $hlevel=$matches[1];
1317 # determine headline level for wikimarkup headings
1318 if(strpos($hlevel,'=')!==false) {
1319 $hlevel=strlen($hlevel);
1322 $secs[$section*2-1]=''; // erase old headline
1325 while(!empty($secs[$count*2-1]) && !$break) {
1327 $subheadline=$secs[$count*2-1];
1329 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1330 $subhlevel=$matches[1];
1331 if(strpos($subhlevel,'=')!==false) {
1332 $subhlevel=strlen($subhlevel);
1334 if($subhlevel > $hlevel) {
1335 // erase old subsections
1336 $secs[$count*2-1]='';
1339 if($subhlevel <= $hlevel) {
1347 $text=join('',$secs);
1348 # reinsert the stuff that we stripped out earlier
1349 $text=$parser->unstrip($text,$striparray);
1350 $text=$parser->unstripNoWiki($text,$striparray);
1354 wfProfileOut( $fname );
1359 * Change an existing article. Puts the previous version back into the old table, updates RC
1360 * and all necessary caches, mostly via the deferred update array.
1362 * It is possible to call this function from a command-line script, but note that you should
1363 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1365 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1366 global $wgUser, $wgDBtransactions, $wgUseSquid;
1367 global $wgPostCommitUpdateList, $wgUseFileCache;
1369 $fname = 'Article::updateArticle';
1370 wfProfileIn( $fname );
1373 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1375 &$watchthis, &$sectionanchor ) ) ) {
1376 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1377 wfProfileOut( $fname );
1381 $isminor = $minor && $wgUser->isAllowed('minoredit');
1382 $redir = (int)$this->isRedirect( $text );
1384 $text = $this->preSaveTransform( $text );
1385 $dbw =& wfGetDB( DB_MASTER
);
1386 $now = wfTimestampNow();
1388 # Update article, but only if changed.
1390 # It's important that we either rollback or complete, otherwise an attacker could
1391 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1392 # could conceivably have the same effect, especially if cur is locked for long periods.
1393 if( !$wgDBtransactions ) {
1394 $userAbort = ignore_user_abort( true );
1397 $oldtext = $this->getContent();
1398 $oldsize = strlen( $oldtext );
1399 $newsize = strlen( $text );
1403 if ( 0 != strcmp( $text, $oldtext ) ) {
1404 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1405 - (int)$this->isCountable( $oldtext );
1406 $this->mTotalAdjustment
= 0;
1407 $now = wfTimestampNow();
1409 $lastRevision = $dbw->selectField(
1410 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1412 $revision = new Revision( array(
1413 'page' => $this->getId(),
1414 'comment' => $summary,
1415 'minor_edit' => $isminor,
1419 $dbw->immediateCommit();
1421 $revisionId = $revision->insertOn( $dbw );
1424 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1427 /* Belated edit conflict! Run away!! */
1431 # Update recentchanges and purge cache and whatnot
1432 require_once( 'RecentChange.php' );
1433 $bot = (int)($wgUser->isBot() ||
$forceBot);
1434 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1435 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1438 # Mark as patrolled if the user can do so and has it set in their options
1439 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1440 RecentChange
::markPatrolled( $rcid );
1445 // Update caches outside the main transaction
1446 Article
::onArticleEdit( $this->mTitle
);
1449 // Keep the same revision ID, but do some updates on it
1450 $revisionId = $this->getRevIdFetched();
1453 if( !$wgDBtransactions ) {
1454 ignore_user_abort( $userAbort );
1459 if (!$this->mTitle
->userIsWatching()) {
1460 $dbw->immediateCommit();
1466 if ( $this->mTitle
->userIsWatching() ) {
1467 $dbw->immediateCommit();
1473 # standard deferred updates
1474 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1478 # Invalidate caches of all articles using this article as a template
1480 # Template namespace
1481 # Purge all articles linking here
1482 $titles = $this->mTitle
->getTemplateLinksTo();
1483 Title
::touchArray( $titles );
1484 if ( $wgUseSquid ) {
1485 foreach ( $titles as $title ) {
1486 $urls[] = $title->getInternalURL();
1491 if ( $wgUseSquid ) {
1492 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1493 $u = new SquidUpdate( $urls );
1494 array_push( $wgPostCommitUpdateList, $u );
1498 if ( $wgUseFileCache ) {
1499 $cm = new CacheManager($this->mTitle
);
1500 @unlink
($cm->fileCacheName());
1503 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1505 wfRunHooks( 'ArticleSaveComplete',
1506 array( &$this, &$wgUser, $text,
1508 $watchthis, $sectionanchor ) );
1509 wfProfileOut( $fname );
1514 * After we've either updated or inserted the article, update
1515 * the link tables and redirect to the new page.
1517 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1520 $fname = 'Article::showArticle';
1521 wfProfileIn( $fname );
1523 # Output the redirect
1524 if( $this->isRedirect( $text ) )
1528 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1530 wfProfileOut( $fname );
1534 * Mark this particular edit as patrolled
1536 function markpatrolled() {
1537 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1538 $wgOut->setRobotpolicy( 'noindex,follow' );
1540 # Check RC patrol config. option
1541 if( !$wgUseRCPatrol ) {
1542 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1547 if( !$wgUser->isAllowed( 'patrol' ) ) {
1548 $wgOut->permissionRequired( 'patrol' );
1552 $rcid = $wgRequest->getVal( 'rcid' );
1553 if ( !is_null ( $rcid ) ) {
1554 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1555 require_once( 'RecentChange.php' );
1556 RecentChange
::markPatrolled( $rcid );
1557 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1558 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1559 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1561 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1562 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1565 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1570 * User-interface handler for the "watch" action
1575 global $wgUser, $wgOut;
1577 if ( $wgUser->isAnon() ) {
1578 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1581 if ( wfReadOnly() ) {
1582 $wgOut->readOnlyPage();
1586 if( $this->doWatch() ) {
1587 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1588 $wgOut->setRobotpolicy( 'noindex,follow' );
1590 $link = $this->mTitle
->getPrefixedText();
1591 $text = wfMsg( 'addedwatchtext', $link );
1592 $wgOut->addWikiText( $text );
1595 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1599 * Add this page to $wgUser's watchlist
1600 * @return bool true on successful watch operation
1602 function doWatch() {
1604 if( $wgUser->isAnon() ) {
1608 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1609 $wgUser->addWatch( $this->mTitle
);
1610 $wgUser->saveSettings();
1612 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1619 * User interface handler for the "unwatch" action.
1621 function unwatch() {
1623 global $wgUser, $wgOut;
1625 if ( $wgUser->isAnon() ) {
1626 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1629 if ( wfReadOnly() ) {
1630 $wgOut->readOnlyPage();
1634 if( $this->doUnwatch() ) {
1635 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1636 $wgOut->setRobotpolicy( 'noindex,follow' );
1638 $link = $this->mTitle
->getPrefixedText();
1639 $text = wfMsg( 'removedwatchtext', $link );
1640 $wgOut->addWikiText( $text );
1643 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1647 * Stop watching a page
1648 * @return bool true on successful unwatch
1650 function doUnwatch() {
1652 if( $wgUser->isAnon() ) {
1656 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1657 $wgUser->removeWatch( $this->mTitle
);
1658 $wgUser->saveSettings();
1660 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1667 * action=protect handler
1669 function protect() {
1670 require_once 'ProtectionForm.php';
1671 $form = new ProtectionForm( $this );
1676 * action=unprotect handler (alias)
1678 function unprotect() {
1683 * Update the article's restriction field, and leave a log entry.
1685 * @param array $limit set of restriction keys
1686 * @param string $reason
1687 * @return bool true on success
1689 function updateRestrictions( $limit = array(), $reason = '' ) {
1690 global $wgUser, $wgRestrictionTypes, $wgContLang;
1692 $id = $this->mTitle
->getArticleID();
1693 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1697 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1698 # we expect a single selection, but the schema allows otherwise.
1700 foreach( $wgRestrictionTypes as $action )
1701 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1703 $current = Article
::flattenRestrictions( $current );
1704 $updated = Article
::flattenRestrictions( $limit );
1706 $changed = ( $current != $updated );
1707 $protect = ( $updated != '' );
1709 # If nothing's changed, do nothing
1711 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1713 $dbw =& wfGetDB( DB_MASTER
);
1715 # Prepare a null revision to be added to the history
1716 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ?
'protectedarticle' : 'unprotectedarticle', $this->mTitle
->getPrefixedText() ) );
1718 $comment .= ": $reason";
1720 $comment .= " [$updated]";
1721 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1722 $nullRevId = $nullRevision->insertOn( $dbw );
1724 # Update page record
1725 $dbw->update( 'page',
1727 'page_touched' => $dbw->timestamp(),
1728 'page_restrictions' => $updated,
1729 'page_latest' => $nullRevId
1730 ), array( /* WHERE */
1732 ), 'Article::protect'
1734 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1736 # Update the protection log
1737 $log = new LogPage( 'protect' );
1739 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$updated]" ) );
1741 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1745 } # End "changed" check
1751 * Take an array of page restrictions and flatten it to a string
1752 * suitable for insertion into the page_restrictions field.
1753 * @param array $limit
1757 function flattenRestrictions( $limit ) {
1758 if( !is_array( $limit ) ) {
1759 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1763 foreach( $limit as $action => $restrictions ) {
1764 if( $restrictions != '' ) {
1765 $bits[] = "$action=$restrictions";
1768 return implode( ':', $bits );
1772 * UI entry point for page deletion
1775 global $wgUser, $wgOut, $wgRequest;
1776 $fname = 'Article::delete';
1777 $confirm = $wgRequest->wasPosted() &&
1778 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1779 $reason = $wgRequest->getText( 'wpReason' );
1781 # This code desperately needs to be totally rewritten
1784 if( $wgUser->isAllowed( 'delete' ) ) {
1785 if( $wgUser->isBlocked() ) {
1786 $wgOut->blockedPage();
1790 $wgOut->permissionRequired( 'delete' );
1794 if( wfReadOnly() ) {
1795 $wgOut->readOnlyPage();
1799 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1801 # Better double-check that it hasn't been deleted yet!
1802 $dbw =& wfGetDB( DB_MASTER
);
1803 $conds = $this->mTitle
->pageCond();
1804 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1805 if ( $latest === false ) {
1806 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1811 $this->doDelete( $reason );
1815 # determine whether this page has earlier revisions
1816 # and insert a warning if it does
1818 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1820 if( count( $authors ) > 1 && !$confirm ) {
1821 $skin=$wgUser->getSkin();
1822 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1825 # If a single user is responsible for all revisions, find out who they are
1826 if ( count( $authors ) == $maxRevisions ) {
1827 // Query bailed out, too many revisions to find out if they're all the same
1828 $authorOfAll = false;
1830 $authorOfAll = reset( $authors );
1831 foreach ( $authors as $author ) {
1832 if ( $authorOfAll != $author ) {
1833 $authorOfAll = false;
1838 # Fetch article text
1839 $rev = Revision
::newFromTitle( $this->mTitle
);
1841 if( !is_null( $rev ) ) {
1842 # if this is a mini-text, we can paste part of it into the deletion reason
1843 $text = $rev->getText();
1845 #if this is empty, an earlier revision may contain "useful" text
1848 $prev = $rev->getPrevious();
1850 $text = $prev->getText();
1855 $length = strlen( $text );
1857 # this should not happen, since it is not possible to store an empty, new
1858 # page. Let's insert a standard text in case it does, though
1859 if( $length == 0 && $reason === '' ) {
1860 $reason = wfMsgForContent( 'exblank' );
1863 if( $length < 500 && $reason === '' ) {
1864 # comment field=255, let's grep the first 150 to have some user
1867 $text = $wgContLang->truncate( $text, 150, '...' );
1869 # let's strip out newlines
1870 $text = preg_replace( "/[\n\r]/", '', $text );
1873 if( $authorOfAll === false ) {
1874 $reason = wfMsgForContent( 'excontent', $text );
1876 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1879 $reason = wfMsgForContent( 'exbeforeblank', $text );
1884 return $this->confirmDelete( '', $reason );
1888 * Get the last N authors
1889 * @param int $num Number of revisions to get
1890 * @param string $revLatest The latest rev_id, selected from the master (optional)
1891 * @return array Array of authors, duplicates not removed
1893 function getLastNAuthors( $num, $revLatest = 0 ) {
1894 $fname = 'Article::getLastNAuthors';
1895 wfProfileIn( $fname );
1897 // First try the slave
1898 // If that doesn't have the latest revision, try the master
1900 $db =& wfGetDB( DB_SLAVE
);
1902 $res = $db->select( array( 'page', 'revision' ),
1903 array( 'rev_id', 'rev_user_text' ),
1905 'page_namespace' => $this->mTitle
->getNamespace(),
1906 'page_title' => $this->mTitle
->getDBkey(),
1907 'rev_page = page_id'
1908 ), $fname, $this->getSelectOptions( array(
1909 'ORDER BY' => 'rev_timestamp DESC',
1914 wfProfileOut( $fname );
1917 $row = $db->fetchObject( $res );
1918 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1919 $db =& wfGetDB( DB_MASTER
);
1924 } while ( $continue );
1926 $authors = array( $row->rev_user_text
);
1927 while ( $row = $db->fetchObject( $res ) ) {
1928 $authors[] = $row->rev_user_text
;
1930 wfProfileOut( $fname );
1935 * Output deletion confirmation dialog
1937 function confirmDelete( $par, $reason ) {
1938 global $wgOut, $wgUser;
1940 wfDebug( "Article::confirmDelete\n" );
1942 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1943 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1944 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1945 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1947 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1949 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1950 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1951 $token = htmlspecialchars( $wgUser->editToken() );
1954 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1958 <label for='wpReason'>{$delcom}:</label>
1961 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1967 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1971 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1974 $wgOut->returnToMain( false );
1979 * Perform a deletion and output success or failure messages
1981 function doDelete( $reason ) {
1982 global $wgOut, $wgUser;
1983 $fname = 'Article::doDelete';
1984 wfDebug( $fname."\n" );
1986 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1987 if ( $this->doDeleteArticle( $reason ) ) {
1988 $deleted = $this->mTitle
->getPrefixedText();
1990 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1991 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1993 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1994 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1996 $wgOut->addWikiText( $text );
1997 $wgOut->returnToMain( false );
1998 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2000 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
2006 * Back-end article deletion
2007 * Deletes the article with database consistency, writes logs, purges caches
2010 function doDeleteArticle( $reason ) {
2011 global $wgUseSquid, $wgDeferredUpdateList;
2012 global $wgPostCommitUpdateList, $wgUseTrackbacks;
2014 $fname = 'Article::doDeleteArticle';
2015 wfDebug( $fname."\n" );
2017 $dbw =& wfGetDB( DB_MASTER
);
2018 $ns = $this->mTitle
->getNamespace();
2019 $t = $this->mTitle
->getDBkey();
2020 $id = $this->mTitle
->getArticleID();
2022 if ( $t == '' ||
$id == 0 ) {
2026 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2027 array_push( $wgDeferredUpdateList, $u );
2029 $linksTo = $this->mTitle
->getLinksTo();
2032 if ( $wgUseSquid ) {
2034 $this->mTitle
->getInternalURL(),
2035 $this->mTitle
->getInternalURL( 'history' )
2038 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
2039 array_push( $wgPostCommitUpdateList, $u );
2043 # Client and file cache invalidation
2044 Title
::touchArray( $linksTo );
2047 // For now, shunt the revision data into the archive table.
2048 // Text is *not* removed from the text table; bulk storage
2049 // is left intact to avoid breaking block-compression or
2050 // immutable storage schemes.
2052 // For backwards compatibility, note that some older archive
2053 // table entries will have ar_text and ar_flags fields still.
2055 // In the future, we may keep revisions and mark them with
2056 // the rev_deleted field, which is reserved for this purpose.
2057 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2059 'ar_namespace' => 'page_namespace',
2060 'ar_title' => 'page_title',
2061 'ar_comment' => 'rev_comment',
2062 'ar_user' => 'rev_user',
2063 'ar_user_text' => 'rev_user_text',
2064 'ar_timestamp' => 'rev_timestamp',
2065 'ar_minor_edit' => 'rev_minor_edit',
2066 'ar_rev_id' => 'rev_id',
2067 'ar_text_id' => 'rev_text_id',
2070 'page_id = rev_page'
2074 # Now that it's safely backed up, delete it
2075 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2076 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2078 if ($wgUseTrackbacks)
2079 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2081 # Clean up recentchanges entries...
2082 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2084 # Finally, clean up the link tables
2085 $t = $this->mTitle
->getPrefixedDBkey();
2087 Article
::onArticleDelete( $this->mTitle
);
2089 # Delete outgoing links
2090 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2091 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2092 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2093 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2094 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2095 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2098 $log = new LogPage( 'delete' );
2099 $log->addEntry( 'delete', $this->mTitle
, $reason );
2101 # Clear the cached article id so the interface doesn't act like we exist
2102 $this->mTitle
->resetArticleID( 0 );
2103 $this->mTitle
->mArticleID
= 0;
2108 * Revert a modification
2110 function rollback() {
2111 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2112 $fname = 'Article::rollback';
2114 if( $wgUser->isAllowed( 'rollback' ) ) {
2115 if( $wgUser->isBlocked() ) {
2116 $wgOut->blockedPage();
2120 $wgOut->permissionRequired( 'rollback' );
2124 if ( wfReadOnly() ) {
2125 $wgOut->readOnlyPage( $this->getContent() );
2128 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2129 array( $this->mTitle
->getPrefixedText(),
2130 $wgRequest->getVal( 'from' ) ) ) ) {
2131 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2132 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2135 $dbw =& wfGetDB( DB_MASTER
);
2137 # Enhanced rollback, marks edits rc_bot=1
2138 $bot = $wgRequest->getBool( 'bot' );
2140 # Replace all this user's current edits with the next one down
2141 $tt = $this->mTitle
->getDBKey();
2142 $n = $this->mTitle
->getNamespace();
2144 # Get the last editor, lock table exclusively
2146 $current = Revision
::newFromTitle( $this->mTitle
);
2147 if( is_null( $current ) ) {
2148 # Something wrong... no page?
2150 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2154 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2155 if( $from != $current->getUserText() ) {
2156 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2157 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2158 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2159 htmlspecialchars( $from ),
2160 htmlspecialchars( $current->getUserText() ) ) );
2161 if( $current->getComment() != '') {
2163 wfMsg( 'editcomment',
2164 htmlspecialchars( $current->getComment() ) ) );
2169 # Get the last edit not by this guy
2170 $user = intval( $current->getUser() );
2171 $user_text = $dbw->addQuotes( $current->getUserText() );
2172 $s = $dbw->selectRow( 'revision',
2173 array( 'rev_id', 'rev_timestamp' ),
2175 'rev_page' => $current->getPage(),
2176 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2179 'USE INDEX' => 'page_timestamp',
2180 'ORDER BY' => 'rev_timestamp DESC' )
2182 if( $s === false ) {
2185 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2186 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2192 # Mark all reverted edits as bot
2195 if ( $wgUseRCPatrol ) {
2196 # Mark all reverted edits as patrolled
2197 $set['rc_patrolled'] = 1;
2201 $dbw->update( 'recentchanges', $set,
2203 'rc_cur_id' => $current->getPage(),
2204 'rc_user_text' => $current->getUserText(),
2205 "rc_timestamp > '{$s->rev_timestamp}'",
2210 # Get the edit summary
2211 $target = Revision
::newFromId( $s->rev_id
);
2212 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2213 $newComment = $wgRequest->getText( 'summary', $newComment );
2216 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2217 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2218 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2220 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2221 Article
::onArticleEdit( $this->mTitle
);
2224 $wgOut->returnToMain( false );
2229 * Do standard deferred updates after page view
2232 function viewUpdates() {
2233 global $wgDeferredUpdateList;
2235 if ( 0 != $this->getID() ) {
2236 global $wgDisableCounters;
2237 if( !$wgDisableCounters ) {
2238 Article
::incViewCount( $this->getID() );
2239 $u = new SiteStatsUpdate( 1, 0, 0 );
2240 array_push( $wgDeferredUpdateList, $u );
2244 # Update newtalk / watchlist notification status
2246 $wgUser->clearNotification( $this->mTitle
);
2250 * Do standard deferred updates after page edit.
2251 * Every 1000th edit, prune the recent changes table.
2253 * @param string $text
2255 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2256 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2258 $fname = 'Article::editUpdates';
2259 wfProfileIn( $fname );
2262 $options = new ParserOptions
;
2263 $options->setTidy(true);
2264 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2266 # Save it to the parser cache
2267 $parserCache =& ParserCache
::singleton();
2268 $parserCache->save( $poutput, $this, $wgUser );
2270 # Update the links tables
2271 $u = new LinksUpdate( $this->mTitle
, $poutput );
2274 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2276 if ( 0 == mt_rand( 0, 999 ) ) {
2277 # Periodically flush old entries from the recentchanges table.
2280 $dbw =& wfGetDB( DB_MASTER
);
2281 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2282 $recentchanges = $dbw->tableName( 'recentchanges' );
2283 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2284 $dbw->query( $sql );
2288 $id = $this->getID();
2289 $title = $this->mTitle
->getPrefixedDBkey();
2290 $shortTitle = $this->mTitle
->getDBkey();
2293 wfProfileOut( $fname );
2297 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2298 array_push( $wgDeferredUpdateList, $u );
2299 $u = new SearchUpdate( $id, $title, $text );
2300 array_push( $wgDeferredUpdateList, $u );
2302 # If this is another user's talk page, update newtalk
2304 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
2305 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2306 $other = User
::newFromName( $shortTitle );
2307 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2308 // An anonymous user
2309 $other = new User();
2310 $other->setName( $shortTitle );
2313 $other->setNewtalk( true );
2318 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2319 $wgMessageCache->replace( $shortTitle, $text );
2322 wfProfileOut( $fname );
2326 * Generate the navigation links when browsing through an article revisions
2327 * It shows the information as:
2328 * Revision as of <date>; view current revision
2329 * <- Previous version | Next Version ->
2332 * @param string $oldid Revision ID of this article revision
2334 function setOldSubtitle( $oldid=0 ) {
2335 global $wgLang, $wgOut, $wgUser;
2337 $current = ( $oldid == $this->mLatest
);
2338 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2339 $sk = $wgUser->getSkin();
2341 ?
wfMsg( 'currentrevisionlink' )
2342 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2343 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2345 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2346 : wfMsg( 'previousrevision' );
2347 $nextlink = $current
2348 ?
wfMsg( 'nextrevision' )
2349 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2350 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2351 $wgOut->setSubtitle( $r );
2355 * This function is called right before saving the wikitext,
2356 * so we can do things like signatures and links-in-context.
2358 * @param string $text
2360 function preSaveTransform( $text ) {
2361 global $wgParser, $wgUser;
2362 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2365 /* Caching functions */
2368 * checkLastModified returns true if it has taken care of all
2369 * output to the client that is necessary for this request.
2370 * (that is, it has sent a cached version of the page)
2372 function tryFileCache() {
2373 static $called = false;
2375 wfDebug( " tryFileCache() -- called twice!?\n" );
2379 if($this->isFileCacheable()) {
2380 $touched = $this->mTouched
;
2381 $cache = new CacheManager( $this->mTitle
);
2382 if($cache->isFileCacheGood( $touched )) {
2383 wfDebug( " tryFileCache() - about to load\n" );
2384 $cache->loadFromFileCache();
2387 wfDebug( " tryFileCache() - starting buffer\n" );
2388 ob_start( array(&$cache, 'saveToFileCache' ) );
2391 wfDebug( " tryFileCache() - not cacheable\n" );
2396 * Check if the page can be cached
2399 function isFileCacheable() {
2400 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2401 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2403 return $wgUseFileCache
2404 and (!$wgShowIPinHeader)
2405 and ($this->getID() != 0)
2406 and ($wgUser->isAnon())
2407 and (!$wgUser->getNewtalk())
2408 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2409 and (empty( $action ) ||
$action == 'view')
2410 and (!isset($oldid))
2412 and (!isset($redirect))
2413 and (!isset($printable))
2414 and (!$this->mRedirectedFrom
);
2418 * Loads page_touched and returns a value indicating if it should be used
2421 function checkTouched() {
2422 $fname = 'Article::checkTouched';
2423 if( !$this->mDataLoaded
) {
2424 $this->loadPageData();
2426 return !$this->mIsRedirect
;
2430 * Get the page_touched field
2432 function getTouched() {
2433 # Ensure that page data has been loaded
2434 if( !$this->mDataLoaded
) {
2435 $this->loadPageData();
2437 return $this->mTouched
;
2441 * Get the page_latest field
2443 function getLatest() {
2444 if ( !$this->mDataLoaded
) {
2445 $this->loadPageData();
2447 return $this->mLatest
;
2451 * Edit an article without doing all that other stuff
2452 * The article must already exist; link tables etc
2453 * are not updated, caches are not flushed.
2455 * @param string $text text submitted
2456 * @param string $comment comment submitted
2457 * @param bool $minor whereas it's a minor modification
2459 function quickEdit( $text, $comment = '', $minor = 0 ) {
2460 $fname = 'Article::quickEdit';
2461 wfProfileIn( $fname );
2463 $dbw =& wfGetDB( DB_MASTER
);
2465 $revision = new Revision( array(
2466 'page' => $this->getId(),
2468 'comment' => $comment,
2469 'minor_edit' => $minor ?
1 : 0,
2471 $revisionId = $revision->insertOn( $dbw );
2472 $this->updateRevisionOn( $dbw, $revision );
2475 wfProfileOut( $fname );
2479 * Used to increment the view counter
2482 * @param integer $id article id
2484 function incViewCount( $id ) {
2485 $id = intval( $id );
2486 global $wgHitcounterUpdateFreq, $wgDBtype;
2488 $dbw =& wfGetDB( DB_MASTER
);
2489 $pageTable = $dbw->tableName( 'page' );
2490 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2491 $acchitsTable = $dbw->tableName( 'acchits' );
2493 if( $wgHitcounterUpdateFreq <= 1 ){ //
2494 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2498 # Not important enough to warrant an error page in case of failure
2499 $oldignore = $dbw->ignoreErrors( true );
2501 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2503 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2504 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2505 # Most of the time (or on SQL errors), skip row count check
2506 $dbw->ignoreErrors( $oldignore );
2510 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2511 $row = $dbw->fetchObject( $res );
2512 $rown = intval( $row->n
);
2513 if( $rown >= $wgHitcounterUpdateFreq ){
2514 wfProfileIn( 'Article::incViewCount-collect' );
2515 $old_user_abort = ignore_user_abort( true );
2517 if ($wgDBtype == 'mysql')
2518 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2519 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2520 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2521 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2523 $dbw->query("DELETE FROM $hitcounterTable");
2524 if ($wgDBtype == 'mysql')
2525 $dbw->query('UNLOCK TABLES');
2526 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2527 'WHERE page_id = hc_id');
2528 $dbw->query("DROP TABLE $acchitsTable");
2530 ignore_user_abort( $old_user_abort );
2531 wfProfileOut( 'Article::incViewCount-collect' );
2533 $dbw->ignoreErrors( $oldignore );
2537 * The onArticle*() functions are supposed to be a kind of hooks
2538 * which should be called whenever any of the specified actions
2541 * This is a good place to put code to clear caches, for instance.
2543 * This is called on page move and undelete, as well as edit
2545 * @param $title_obj a title object
2548 function onArticleCreate($title_obj) {
2549 global $wgUseSquid, $wgPostCommitUpdateList;
2551 $title_obj->touchLinks();
2552 $titles = $title_obj->getLinksTo();
2555 if ( $wgUseSquid ) {
2556 $urls = $title_obj->getSquidURLs();
2557 foreach ( $titles as $linkTitle ) {
2558 $urls[] = $linkTitle->getInternalURL();
2560 $u = new SquidUpdate( $urls );
2561 array_push( $wgPostCommitUpdateList, $u );
2565 function onArticleDelete( $title ) {
2566 global $wgMessageCache;
2568 $title->touchLinks();
2570 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2571 $wgMessageCache->replace( $title->getDBkey(), false );
2576 * Purge caches on page update etc
2578 function onArticleEdit( $title ) {
2579 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2583 // Template namespace? Purge all articles linking here.
2584 // FIXME: When a templatelinks table arrives, use it for all includes.
2585 if ( $title->getNamespace() == NS_TEMPLATE
) {
2586 $titles = $title->getLinksTo();
2587 Title
::touchArray( $titles );
2588 if ( $wgUseSquid ) {
2589 foreach ( $titles as $link ) {
2590 $urls[] = $link->getInternalURL();
2596 if ( $wgUseSquid ) {
2597 $urls = array_merge( $urls, $title->getSquidURLs() );
2598 $u = new SquidUpdate( $urls );
2599 array_push( $wgPostCommitUpdateList, $u );
2603 if ( $wgUseFileCache ) {
2604 $cm = new CacheManager( $title );
2605 @unlink
( $cm->fileCacheName() );
2612 * Info about this page
2613 * Called for ?action=info when $wgAllowPageInfo is on.
2618 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2619 $fname = 'Article::info';
2621 if ( !$wgAllowPageInfo ) {
2622 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2626 $page = $this->mTitle
->getSubjectPage();
2628 $wgOut->setPagetitle( $page->getPrefixedText() );
2629 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2631 # first, see if the page exists at all.
2632 $exists = $page->getArticleId() != 0;
2634 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2635 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2637 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2640 $dbr =& wfGetDB( DB_SLAVE
);
2642 'wl_title' => $page->getDBkey(),
2643 'wl_namespace' => $page->getNamespace() );
2644 $numwatchers = $dbr->selectField(
2649 $this->getSelectOptions() );
2651 $pageInfo = $this->pageCountInfo( $page );
2652 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2654 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2655 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2657 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2659 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2661 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2663 $wgOut->addHTML( '</ul>' );
2669 * Return the total number of edits and number of unique editors
2670 * on a given page. If page does not exist, returns false.
2672 * @param Title $title
2676 function pageCountInfo( $title ) {
2677 $id = $title->getArticleId();
2682 $dbr =& wfGetDB( DB_SLAVE
);
2684 $rev_clause = array( 'rev_page' => $id );
2685 $fname = 'Article::pageCountInfo';
2687 $edits = $dbr->selectField(
2692 $this->getSelectOptions() );
2694 $authors = $dbr->selectField(
2696 'COUNT(DISTINCT rev_user_text)',
2699 $this->getSelectOptions() );
2701 return array( 'edits' => $edits, 'authors' => $authors );
2705 * Return a list of templates used by this article.
2706 * Uses the templatelinks table
2708 * @return array Array of Title objects
2710 function getUsedTemplates() {
2712 $id = $this->mTitle
->getArticleID();
2717 $dbr =& wfGetDB( DB_SLAVE
);
2718 $res = $dbr->select( array( 'templatelinks' ),
2719 array( 'tl_namespace', 'tl_title' ),
2720 array( 'tl_from' => $id ),
2721 'Article:getUsedTemplates' );
2722 if ( false !== $res ) {
2723 if ( $dbr->numRows( $res ) ) {
2724 while ( $row = $dbr->fetchObject( $res ) ) {
2725 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2729 $dbr->freeResult( $res );