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.
31 var $mContentLoaded; //!<
35 var $mGoodAdjustment; //!<
40 var $mRedirectedFrom; //!<
41 var $mRedirectUrl; //!<
42 var $mRevIdFetched; //!<
47 var $mTotalAdjustment; //!<
54 * Constructor and clear the article
55 * @param $title Reference to a Title object.
56 * @param $oldId Integer revision ID, null to fetch from request, zero for current
58 function Article( &$title, $oldId = null ) {
59 $this->mTitle
=& $title;
60 $this->mOldId
= $oldId;
65 * Tell the page view functions that this view was redirected
66 * from another page on the wiki.
67 * @param $from Title object.
69 function setRedirectedFrom( $from ) {
70 $this->mRedirectedFrom
= $from;
74 * @return mixed false, Title of in-wiki target, or string with URL
76 function followRedirect() {
77 $text = $this->getContent();
78 $rt = Title
::newFromRedirect( $text );
80 # process if title object is valid and not special:userlogout
82 if( $rt->getInterwiki() != '' ) {
83 if( $rt->isLocal() ) {
84 // Offsite wikis need an HTTP redirect.
86 // This can be hard to reverse and may produce loops,
87 // so they may be disabled in the site configuration.
89 $source = $this->mTitle
->getFullURL( 'redirect=no' );
90 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
93 if( $rt->getNamespace() == NS_SPECIAL
) {
94 // Gotta hand redirects to special pages differently:
95 // Fill the HTTP response "Location" header and ignore
96 // the rest of the page we're on.
98 // This can be hard to reverse, so they may be disabled.
100 if( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) {
103 return $rt->getFullURL();
110 // No or invalid redirect
115 * get the title object of the article
117 function getTitle() {
118 return $this->mTitle
;
126 $this->mDataLoaded
= false;
127 $this->mContentLoaded
= false;
129 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
130 $this->mRedirectedFrom
= null; # Title object if set
132 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
133 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
134 $this->mTouched
= '19700101000000';
135 $this->mForUpdate
= false;
136 $this->mIsRedirect
= false;
137 $this->mRevIdFetched
= 0;
138 $this->mRedirectUrl
= false;
139 $this->mLatest
= false;
143 * Note that getContent/loadContent do not follow redirects anymore.
144 * If you need to fetch redirectable content easily, try
145 * the shortcut in Article::followContent()
147 * @todo There are still side-effects in this!
148 * In general, you should use the Revision class, not Article,
149 * to fetch text for purposes other than page views.
151 * @return Return the text of this revision
153 function getContent() {
154 global $wgRequest, $wgUser, $wgOut;
156 # Get variables from query string :P
157 $action = $wgRequest->getText( 'action', 'view' );
158 $section = $wgRequest->getText( 'section' );
159 $preload = $wgRequest->getText( 'preload' );
161 $fname = 'Article::getContent';
162 wfProfileIn( $fname );
164 if ( 0 == $this->getID() ) {
165 if ( 'edit' == $action ) {
166 wfProfileOut( $fname );
168 # If requested, preload some text.
169 $text=$this->getPreloadedText($preload);
171 # We used to put MediaWiki:Newarticletext here if
172 # $text was empty at this point.
173 # This is now shown above the edit box instead.
176 wfProfileOut( $fname );
177 $wgOut->setRobotpolicy( 'noindex,nofollow' );
179 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
180 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
182 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
185 return "<div class='noarticletext'>$ret</div>";
187 $this->loadContent();
188 if($action=='edit') {
190 if($section=='new') {
191 wfProfileOut( $fname );
192 $text=$this->getPreloadedText($preload);
196 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
197 # comments to be stripped as well)
198 $rv=$this->getSection($this->mContent
,$section);
199 wfProfileOut( $fname );
203 wfProfileOut( $fname );
204 return $this->mContent
;
209 * Get the contents of a page from its title and remove includeonly tags
211 * @param $preload String: the title of the page.
212 * @return string The contents of the page.
214 function getPreloadedText($preload) {
215 if ( $preload === '' )
218 $preloadTitle = Title
::newFromText( $preload );
219 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
220 $rev=Revision
::newFromTitle($preloadTitle);
221 if ( is_object( $rev ) ) {
222 $text = $rev->getText();
223 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
224 // its own mini-parser! -ævar
225 $text = preg_replace( '~</?includeonly>~', '', $text );
234 * This function returns the text of a section, specified by a number ($section).
235 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
236 * the first section before any such heading (section 0).
238 * If a section contains subsections, these are also returned.
240 * @param $text String: text to look in
241 * @param $section Integer: section number
242 * @return string text of the requested section
244 function getSection($text,$section) {
246 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
247 # comments to be stripped as well)
249 $parser=new Parser();
250 $parser->mOutputType
=OT_WIKI
;
251 $parser->mOptions
= new ParserOptions();
252 $striptext=$parser->strip($text, $striparray, true);
254 # now that we can be sure that no pseudo-sections are in the source,
255 # split it up by section
258 '/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
260 PREG_SPLIT_DELIM_CAPTURE
);
264 $headline=$secs[$section*2-1];
265 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
268 # translate wiki heading into level
269 if(strpos($hlevel,'=')!==false) {
270 $hlevel=strlen($hlevel);
273 $rv=$headline. $secs[$section*2];
277 while(!empty($secs[$count*2-1]) && !$break) {
279 $subheadline=$secs[$count*2-1];
280 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
281 $subhlevel=$matches[1];
282 if(strpos($subhlevel,'=')!==false) {
283 $subhlevel=strlen($subhlevel);
285 if($subhlevel > $hlevel) {
286 $rv.=$subheadline.$secs[$count*2];
288 if($subhlevel <= $hlevel) {
295 # reinsert stripped tags
296 $rv=$parser->unstrip($rv,$striparray);
297 $rv=$parser->unstripNoWiki($rv,$striparray);
304 * @return int The oldid of the article that is to be shown, 0 for the
307 function getOldID() {
308 if ( is_null( $this->mOldId
) ) {
309 $this->mOldId
= $this->getOldIDFromRequest();
311 return $this->mOldId
;
315 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
317 * @return int The old id for the request
319 function getOldIDFromRequest() {
321 $this->mRedirectUrl
= false;
322 $oldid = $wgRequest->getVal( 'oldid' );
323 if ( isset( $oldid ) ) {
324 $oldid = intval( $oldid );
325 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
326 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
330 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
332 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
333 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
350 * Load the revision (including text) into this object
352 function loadContent() {
353 if ( $this->mContentLoaded
) return;
356 $oldid = $this->getOldID();
358 # Pre-fill content with error message so that if something
359 # fails we'll have something telling us what we intended.
361 $t = $this->mTitle
->getPrefixedText();
363 $this->mOldId
= $oldid;
364 $this->fetchContent( $oldid );
369 * Fetch a page record with the given conditions
370 * @param Database $dbr
371 * @param array $conditions
374 function pageData( &$dbr, $conditions ) {
387 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
388 $row = $dbr->selectRow( 'page',
391 'Article::pageData' );
392 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
397 * @param Database $dbr
398 * @param Title $title
400 function pageDataFromTitle( &$dbr, $title ) {
401 return $this->pageData( $dbr, array(
402 'page_namespace' => $title->getNamespace(),
403 'page_title' => $title->getDBkey() ) );
407 * @param Database $dbr
410 function pageDataFromId( &$dbr, $id ) {
411 return $this->pageData( $dbr, array( 'page_id' => $id ) );
415 * Set the general counter, title etc data loaded from
418 * @param object $data
421 function loadPageData( $data = 'fromdb' ) {
422 if ( $data === 'fromdb' ) {
423 $dbr =& $this->getDB();
424 $data = $this->pageDataFromId( $dbr, $this->getId() );
427 $lc =& LinkCache
::singleton();
429 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
431 $this->mTitle
->mArticleID
= $data->page_id
;
432 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
433 $this->mTitle
->mRestrictionsLoaded
= true;
435 $this->mCounter
= $data->page_counter
;
436 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
437 $this->mIsRedirect
= $data->page_is_redirect
;
438 $this->mLatest
= $data->page_latest
;
440 if ( is_object( $this->mTitle
) ) {
441 $lc->addBadLinkObj( $this->mTitle
);
443 $this->mTitle
->mArticleID
= 0;
446 $this->mDataLoaded
= true;
450 * Get text of an article from database
451 * Does *NOT* follow redirects.
452 * @param int $oldid 0 for whatever the latest revision is
455 function fetchContent( $oldid = 0 ) {
456 if ( $this->mContentLoaded
) {
457 return $this->mContent
;
460 $dbr =& $this->getDB();
461 $fname = 'Article::fetchContent';
463 # Pre-fill content with error message so that if something
464 # fails we'll have something telling us what we intended.
465 $t = $this->mTitle
->getPrefixedText();
467 $t .= ',oldid='.$oldid;
469 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
472 $revision = Revision
::newFromId( $oldid );
473 if( is_null( $revision ) ) {
474 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
477 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
479 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
482 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
483 $this->loadPageData( $data );
485 if( !$this->mDataLoaded
) {
486 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
488 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
491 $this->loadPageData( $data );
493 $revision = Revision
::newFromId( $this->mLatest
);
494 if( is_null( $revision ) ) {
495 wfDebug( "$fname failed to retrieve current page, rev_id {$data->page_latest}\n" );
500 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
501 // We should instead work with the Revision object when we need it...
502 $this->mContent
= $revision->userCan( MW_REV_DELETED_TEXT
) ?
$revision->getRawText() : "";
503 //$this->mContent = $revision->getText();
505 $this->mUser
= $revision->getUser();
506 $this->mUserText
= $revision->getUserText();
507 $this->mComment
= $revision->getComment();
508 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
510 $this->mRevIdFetched
= $revision->getID();
511 $this->mContentLoaded
= true;
512 $this->mRevision
=& $revision;
514 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
516 return $this->mContent
;
520 * Read/write accessor to select FOR UPDATE
522 * @param $x Mixed: FIXME
524 function forUpdate( $x = NULL ) {
525 return wfSetVar( $this->mForUpdate
, $x );
529 * Get the database which should be used for reads
534 $ret =& wfGetDB( DB_MASTER
);
539 * Get options for all SELECT statements
541 * @param $options Array: an optional options array which'll be appended to
543 * @return Array: options
545 function getSelectOptions( $options = '' ) {
546 if ( $this->mForUpdate
) {
547 if ( is_array( $options ) ) {
548 $options[] = 'FOR UPDATE';
550 $options = 'FOR UPDATE';
557 * @return int Page ID
560 if( $this->mTitle
) {
561 return $this->mTitle
->getArticleID();
568 * @return bool Whether or not the page exists in the database
571 return $this->getId() != 0;
575 * @return int The view count for the page
577 function getCount() {
578 if ( -1 == $this->mCounter
) {
579 $id = $this->getID();
583 $dbr =& wfGetDB( DB_SLAVE
);
584 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
585 'Article::getCount', $this->getSelectOptions() );
588 return $this->mCounter
;
592 * Determine whether a page would be suitable for being counted as an
593 * article in the site_stats table based on the title & its content
595 * @param $text String: text to analyze
598 function isCountable( $text ) {
599 global $wgUseCommaCount;
601 $token = $wgUseCommaCount ?
',' : '[[';
603 $this->mTitle
->getNamespace() == NS_MAIN
604 && ! $this->isRedirect( $text )
605 && in_string( $token, $text );
609 * Tests if the article text represents a redirect
611 * @param $text String: FIXME
614 function isRedirect( $text = false ) {
615 if ( $text === false ) {
616 $this->loadContent();
617 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
619 $titleObj = Title
::newFromRedirect( $text );
621 return $titleObj !== NULL;
625 * Returns true if the currently-referenced revision is the current edit
626 * to this page (and it exists).
629 function isCurrent() {
630 return $this->exists() &&
631 isset( $this->mRevision
) &&
632 $this->mRevision
->isCurrent();
636 * Loads everything except the text
637 * This isn't necessary for all uses, so it's only done if needed.
640 function loadLastEdit() {
641 if ( -1 != $this->mUser
)
644 # New or non-existent articles have no user information
645 $id = $this->getID();
646 if ( 0 == $id ) return;
648 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
649 if( !is_null( $this->mLastRevision
) ) {
650 $this->mUser
= $this->mLastRevision
->getUser();
651 $this->mUserText
= $this->mLastRevision
->getUserText();
652 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
653 $this->mComment
= $this->mLastRevision
->getComment();
654 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
655 $this->mRevIdFetched
= $this->mLastRevision
->getID();
659 function getTimestamp() {
660 // Check if the field has been filled by ParserCache::get()
661 if ( !$this->mTimestamp
) {
662 $this->loadLastEdit();
664 return wfTimestamp(TS_MW
, $this->mTimestamp
);
668 $this->loadLastEdit();
672 function getUserText() {
673 $this->loadLastEdit();
674 return $this->mUserText
;
677 function getComment() {
678 $this->loadLastEdit();
679 return $this->mComment
;
682 function getMinorEdit() {
683 $this->loadLastEdit();
684 return $this->mMinorEdit
;
687 function getRevIdFetched() {
688 $this->loadLastEdit();
689 return $this->mRevIdFetched
;
693 * @todo Document, fixme $offset never used.
694 * @param $limit Integer: default 0.
695 * @param $offset Integer: default 0.
697 function getContributors($limit = 0, $offset = 0) {
698 $fname = 'Article::getContributors';
700 # XXX: this is expensive; cache this info somewhere.
702 $title = $this->mTitle
;
704 $dbr =& wfGetDB( DB_SLAVE
);
705 $revTable = $dbr->tableName( 'revision' );
706 $userTable = $dbr->tableName( 'user' );
707 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
708 $ns = $title->getNamespace();
709 $user = $this->getUser();
710 $pageId = $this->getId();
712 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
713 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
714 WHERE rev_page = $pageId
715 AND rev_user != $user
716 GROUP BY rev_user, rev_user_text, user_real_name
717 ORDER BY timestamp DESC";
719 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
720 $sql .= ' '. $this->getSelectOptions();
722 $res = $dbr->query($sql, $fname);
724 while ( $line = $dbr->fetchObject( $res ) ) {
725 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
728 $dbr->freeResult($res);
733 * This is the default action of the script: just view the page of
737 global $wgUser, $wgOut, $wgRequest, $wgContLang;
738 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
739 global $wgUseTrackbacks;
740 $sk = $wgUser->getSkin();
742 $fname = 'Article::view';
743 wfProfileIn( $fname );
744 $parserCache =& ParserCache
::singleton();
745 # Get variables from query string
746 $oldid = $this->getOldID();
748 # getOldID may want us to redirect somewhere else
749 if ( $this->mRedirectUrl
) {
750 $wgOut->redirect( $this->mRedirectUrl
);
751 wfProfileOut( $fname );
755 $diff = $wgRequest->getVal( 'diff' );
756 $rcid = $wgRequest->getVal( 'rcid' );
757 $rdfrom = $wgRequest->getVal( 'rdfrom' );
759 $wgOut->setArticleFlag( true );
760 $wgOut->setRobotpolicy( 'index,follow' );
761 # If we got diff and oldid in the query, we want to see a
762 # diff page instead of the article.
764 if ( !is_null( $diff ) ) {
765 require_once( 'DifferenceEngine.php' );
766 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
768 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
769 // DifferenceEngine directly fetched the revision:
770 $this->mRevIdFetched
= $de->mNewid
;
774 # Run view updates for current revision only
775 $this->viewUpdates();
777 wfProfileOut( $fname );
781 if ( empty( $oldid ) && $this->checkTouched() ) {
782 $wgOut->setETag($parserCache->getETag($this, $wgUser));
784 if( $wgOut->checkLastModified( $this->mTouched
) ){
785 wfProfileOut( $fname );
787 } else if ( $this->tryFileCache() ) {
788 # tell wgOut that output is taken care of
790 $this->viewUpdates();
791 wfProfileOut( $fname );
795 # Should the parser cache be used?
796 $pcache = $wgEnableParserCache &&
797 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
800 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
801 if ( $wgUser->getOption( 'stubthreshold' ) ) {
802 wfIncrStats( 'pcache_miss_stub' );
805 $wasRedirected = false;
806 if ( isset( $this->mRedirectedFrom
) ) {
807 // This is an internally redirected page view.
808 // We'll need a backlink to the source page for navigation.
809 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
810 $sk = $wgUser->getSkin();
811 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
812 $s = wfMsg( 'redirectedfrom', $redir );
813 $wgOut->setSubtitle( $s );
814 $wasRedirected = true;
816 } elseif ( !empty( $rdfrom ) ) {
817 // This is an externally redirected view, from some other wiki.
818 // If it was reported from a trusted site, supply a backlink.
819 global $wgRedirectSources;
820 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
821 $sk = $wgUser->getSkin();
822 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
823 $s = wfMsg( 'redirectedfrom', $redir );
824 $wgOut->setSubtitle( $s );
825 $wasRedirected = true;
831 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
835 if ( !$outputDone ) {
836 $text = $this->getContent();
837 if ( $text === false ) {
838 # Failed to load, replace text with error message
839 $t = $this->mTitle
->getPrefixedText();
841 $t .= ',oldid='.$oldid;
842 $text = wfMsg( 'missingarticle', $t );
844 $text = wfMsg( 'noarticletext', $t );
848 # Another whitelist check in case oldid is altering the title
849 if ( !$this->mTitle
->userCanRead() ) {
850 $wgOut->loginToUse();
855 # We're looking at an old revision
857 if ( !empty( $oldid ) ) {
858 $wgOut->setRobotpolicy( 'noindex,nofollow' );
859 if( is_null( $this->mRevision
) ) {
860 // FIXME: This would be a nice place to load the 'no such page' text.
862 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
863 if( $this->mRevision
->isDeleted( MW_REV_DELETED_TEXT
) ) {
864 if( !$this->mRevision
->userCan( MW_REV_DELETED_TEXT
) ) {
865 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
866 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
869 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
870 // and we are allowed to see...
879 * @fixme: this hook doesn't work most of the time, as it doesn't
880 * trigger when the parser cache is used.
882 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
883 $wgOut->setRevisionId( $this->getRevIdFetched() );
884 # wrap user css and user js in pre and don't parse
885 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
887 $this->mTitle
->getNamespace() == NS_USER
&&
888 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
890 $wgOut->addWikiText( wfMsg('clearyourcache'));
891 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
892 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
894 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
895 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
896 if( !$wasRedirected ) {
897 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
899 $targetUrl = $rt->escapeLocalURL();
900 #Â fixme unused $titleText :
901 $titleText = htmlspecialchars( $rt->getPrefixedText() );
902 $link = $sk->makeLinkObj( $rt );
904 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
905 '<span class="redirectText">'.$link.'</span>' );
907 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
908 $wgOut->addParserOutputNoText( $parseout );
909 } else if ( $pcache ) {
910 # Display content and save to parser cache
911 $wgOut->addPrimaryWikiText( $text, $this );
913 # Display content, don't attempt to save to parser cache
915 # Don't show section-edit links on old revisions... this way lies madness.
916 if( !$this->isCurrent() ) {
917 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
919 # Display content and don't save to parser cache
920 $wgOut->addPrimaryWikiText( $text, $this, false );
922 if( !$this->isCurrent() ) {
923 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
927 /* title may have been set from the cache */
928 $t = $wgOut->getPageTitle();
930 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
933 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
934 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
935 User
::isIP( $this->mTitle
->getText() ) ) {
936 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
939 # If we have been passed an &rcid= parameter, we want to give the user a
940 # chance to mark this new article as patrolled.
941 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
943 "<div class='patrollink'>" .
944 wfMsg ( 'markaspatrolledlink',
945 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
952 if ($wgUseTrackbacks)
953 $this->addTrackbacks();
955 $this->viewUpdates();
956 wfProfileOut( $fname );
959 function addTrackbacks() {
960 global $wgOut, $wgUser;
962 $dbr =& wfGetDB(DB_SLAVE
);
964 /* FROM */ 'trackbacks',
965 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
966 /* WHERE */ array('tb_page' => $this->getID())
969 if (!$dbr->numrows($tbs))
973 while ($o = $dbr->fetchObject($tbs)) {
975 if ($wgUser->isAllowed( 'trackback' )) {
976 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
977 . $o->tb_id
. "&token=" . $wgUser->editToken());
978 $rmvtxt = wfMsg('trackbackremove', $delurl);
980 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
987 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
990 function deletetrackback() {
991 global $wgUser, $wgRequest, $wgOut, $wgTitle;
993 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
994 $wgOut->addWikitext(wfMsg('sessionfailure'));
998 if ((!$wgUser->isAllowed('delete'))) {
999 $wgOut->sysopRequired();
1004 $wgOut->readOnlyPage();
1008 $db =& wfGetDB(DB_MASTER
);
1009 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
1010 $wgTitle->invalidateCache();
1011 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
1017 $wgOut->setArticleBodyOnly(true);
1022 * Handle action=purge
1025 global $wgUser, $wgRequest, $wgOut;
1027 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
1028 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1032 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1033 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
1034 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1035 $msg = str_replace( '$1',
1036 "<form method=\"post\" action=\"$action\">\n" .
1037 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1038 "</form>\n", $msg );
1040 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1041 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1042 $wgOut->addHTML( $msg );
1047 * Perform the actions of a page purging
1049 function doPurge() {
1051 // Invalidate the cache
1052 $this->mTitle
->invalidateCache();
1054 if ( $wgUseSquid ) {
1055 // Commit the transaction before the purge is sent
1056 $dbw = wfGetDB( DB_MASTER
);
1057 $dbw->immediateCommit();
1060 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1061 $update->doUpdate();
1067 * Insert a new empty page record for this article.
1068 * This *must* be followed up by creating a revision
1069 * and running $this->updateToLatest( $rev_id );
1070 * or else the record will be left in a funky state.
1071 * Best if all done inside a transaction.
1073 * @param Database $dbw
1074 * @param string $restrictions
1075 * @return int The newly created page_id key
1078 function insertOn( &$dbw, $restrictions = '' ) {
1079 $fname = 'Article::insertOn';
1080 wfProfileIn( $fname );
1082 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1083 $dbw->insert( 'page', array(
1084 'page_id' => $page_id,
1085 'page_namespace' => $this->mTitle
->getNamespace(),
1086 'page_title' => $this->mTitle
->getDBkey(),
1087 'page_counter' => 0,
1088 'page_restrictions' => $restrictions,
1089 'page_is_redirect' => 0, # Will set this shortly...
1091 'page_random' => wfRandom(),
1092 'page_touched' => $dbw->timestamp(),
1093 'page_latest' => 0, # Fill this in shortly...
1094 'page_len' => 0, # Fill this in shortly...
1096 $newid = $dbw->insertId();
1098 $this->mTitle
->resetArticleId( $newid );
1100 wfProfileOut( $fname );
1105 * Update the page record to point to a newly saved revision.
1107 * @param Database $dbw
1108 * @param Revision $revision For ID number, and text used to set
1109 length and redirect status fields
1110 * @param int $lastRevision If given, will not overwrite the page field
1111 * when different from the currently set value.
1112 * Giving 0 indicates the new page flag should
1114 * @return bool true on success, false on failure
1117 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1118 $fname = 'Article::updateToRevision';
1119 wfProfileIn( $fname );
1121 $conditions = array( 'page_id' => $this->getId() );
1122 if( !is_null( $lastRevision ) ) {
1123 # An extra check against threads stepping on each other
1124 $conditions['page_latest'] = $lastRevision;
1127 $text = $revision->getText();
1128 $dbw->update( 'page',
1130 'page_latest' => $revision->getId(),
1131 'page_touched' => $dbw->timestamp(),
1132 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1133 'page_is_redirect' => Article
::isRedirect( $text ) ?
1 : 0,
1134 'page_len' => strlen( $text ),
1139 wfProfileOut( $fname );
1140 return ( $dbw->affectedRows() != 0 );
1144 * If the given revision is newer than the currently set page_latest,
1145 * update the page record. Otherwise, do nothing.
1147 * @param Database $dbw
1148 * @param Revision $revision
1150 function updateIfNewerOn( &$dbw, $revision ) {
1151 $fname = 'Article::updateIfNewerOn';
1152 wfProfileIn( $fname );
1154 $row = $dbw->selectRow(
1155 array( 'revision', 'page' ),
1156 array( 'rev_id', 'rev_timestamp' ),
1158 'page_id' => $this->getId(),
1159 'page_latest=rev_id' ),
1162 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1163 wfProfileOut( $fname );
1166 $prev = $row->rev_id
;
1168 # No or missing previous revision; mark the page as new
1172 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1173 wfProfileOut( $fname );
1178 * Insert a new article into the database
1181 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1184 $fname = 'Article::insertNewArticle';
1185 wfProfileIn( $fname );
1187 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1188 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1189 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1190 wfProfileOut( $fname );
1194 $ns = $this->mTitle
->getNamespace();
1195 $ttl = $this->mTitle
->getDBkey();
1197 # If this is a comment, add the summary as headline
1198 if($comment && $summary!="") {
1199 $text="== {$summary} ==\n\n".$text;
1201 $text = $this->preSaveTransform( $text );
1204 # Set statistics members
1205 # We work out if it's countable after PST to avoid counter drift
1206 # when articles are created with {{subst:}}
1207 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1208 $this->mTotalAdjustment
= 1;
1210 /* Silently ignore minoredit if not allowed */
1211 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1212 $now = wfTimestampNow();
1214 $dbw =& wfGetDB( DB_MASTER
);
1216 # Add the page record; stake our claim on this title!
1217 $newid = $this->insertOn( $dbw );
1219 # Save the revision text...
1220 $revision = new Revision( array(
1222 'comment' => $summary,
1223 'minor_edit' => $isminor,
1226 $revisionId = $revision->insertOn( $dbw );
1228 $this->mTitle
->resetArticleID( $newid );
1230 # Update the page record with revision data
1231 $this->updateRevisionOn( $dbw, $revision, 0 );
1233 Article
::onArticleCreate( $this->mTitle
);
1235 require_once( 'RecentChange.php' );
1236 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, 'default',
1237 '', strlen( $text ), $revisionId );
1238 # Mark as patrolled if the user can and has the option set
1239 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1240 RecentChange
::markPatrolled( $rcid );
1245 if(!$this->mTitle
->userIsWatching()) $this->doWatch();
1247 if ( $this->mTitle
->userIsWatching() ) {
1252 # The talk page isn't in the regular link tables, so we need to update manually:
1253 $talkns = $ns ^
1; # talk -> normal; normal -> talk
1254 $dbw->update( 'page',
1255 array( 'page_touched' => $dbw->timestamp($now) ),
1256 array( 'page_namespace' => $talkns,
1257 'page_title' => $ttl ),
1260 # standard deferred updates
1261 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1263 $oldid = 0; # new article
1264 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1266 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1268 $watchthis, NULL ) );
1269 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1271 $watchthis, NULL ) );
1272 wfProfileOut( $fname );
1276 * @return string Complete article text, or null if error
1278 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1279 $fname = 'Article::replaceSection';
1280 wfProfileIn( $fname );
1282 if ($section != '') {
1283 if( is_null( $edittime ) ) {
1284 $rev = Revision
::newFromTitle( $this->mTitle
);
1286 $dbw =& wfGetDB( DB_MASTER
);
1287 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1289 if( is_null( $rev ) ) {
1290 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1291 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1294 $oldtext = $rev->getText();
1296 if($section=='new') {
1297 if($summary) $subject="== {$summary} ==\n\n";
1298 $text=$oldtext."\n\n".$subject.$text;
1301 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1302 # comments to be stripped as well)
1303 $striparray=array();
1304 $parser=new Parser();
1305 $parser->mOutputType
=OT_WIKI
;
1306 $parser->mOptions
= new ParserOptions();
1307 $oldtext=$parser->strip($oldtext, $striparray, true);
1309 # now that we can be sure that no pseudo-sections are in the source,
1311 # Unfortunately we can't simply do a preg_replace because that might
1312 # replace the wrong section, so we have to use the section counter instead
1313 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1314 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1315 $secs[$section*2]=$text."\n\n"; // replace with edited
1317 # section 0 is top (intro) section
1320 # headline of old section - we need to go through this section
1321 # to determine if there are any subsections that now need to
1322 # be erased, as the mother section has been replaced with
1323 # the text of all subsections.
1324 $headline=$secs[$section*2-1];
1325 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1326 $hlevel=$matches[1];
1328 # determine headline level for wikimarkup headings
1329 if(strpos($hlevel,'=')!==false) {
1330 $hlevel=strlen($hlevel);
1333 $secs[$section*2-1]=''; // erase old headline
1336 while(!empty($secs[$count*2-1]) && !$break) {
1338 $subheadline=$secs[$count*2-1];
1340 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1341 $subhlevel=$matches[1];
1342 if(strpos($subhlevel,'=')!==false) {
1343 $subhlevel=strlen($subhlevel);
1345 if($subhlevel > $hlevel) {
1346 // erase old subsections
1347 $secs[$count*2-1]='';
1350 if($subhlevel <= $hlevel) {
1358 $text=join('',$secs);
1359 # reinsert the stuff that we stripped out earlier
1360 $text=$parser->unstrip($text,$striparray);
1361 $text=$parser->unstripNoWiki($text,$striparray);
1365 wfProfileOut( $fname );
1370 * Change an existing article. Puts the previous version back into the old table, updates RC
1371 * and all necessary caches, mostly via the deferred update array.
1373 * It is possible to call this function from a command-line script, but note that you should
1374 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1376 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1377 global $wgUser, $wgDBtransactions, $wgUseSquid;
1378 global $wgPostCommitUpdateList, $wgUseFileCache;
1380 $fname = 'Article::updateArticle';
1381 wfProfileIn( $fname );
1384 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1386 &$watchthis, &$sectionanchor ) ) ) {
1387 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1388 wfProfileOut( $fname );
1392 $isminor = $minor && $wgUser->isAllowed('minoredit');
1394 $text = $this->preSaveTransform( $text );
1395 $dbw =& wfGetDB( DB_MASTER
);
1396 $now = wfTimestampNow();
1398 # Update article, but only if changed.
1400 # It's important that we either rollback or complete, otherwise an attacker could
1401 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1402 # could conceivably have the same effect, especially if cur is locked for long periods.
1403 if( !$wgDBtransactions ) {
1404 $userAbort = ignore_user_abort( true );
1407 $oldtext = $this->getContent();
1408 $oldsize = strlen( $oldtext );
1409 $newsize = strlen( $text );
1413 if ( 0 != strcmp( $text, $oldtext ) ) {
1414 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1415 - (int)$this->isCountable( $oldtext );
1416 $this->mTotalAdjustment
= 0;
1417 $now = wfTimestampNow();
1419 $lastRevision = $dbw->selectField(
1420 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1422 $revision = new Revision( array(
1423 'page' => $this->getId(),
1424 'comment' => $summary,
1425 'minor_edit' => $isminor,
1429 $dbw->immediateCommit();
1431 $revisionId = $revision->insertOn( $dbw );
1434 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1437 /* Belated edit conflict! Run away!! */
1441 # Update recentchanges and purge cache and whatnot
1442 require_once( 'RecentChange.php' );
1443 $bot = (int)($wgUser->isBot() ||
$forceBot);
1444 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1445 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1448 # Mark as patrolled if the user can do so and has it set in their options
1449 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1450 RecentChange
::markPatrolled( $rcid );
1455 // Update caches outside the main transaction
1456 Article
::onArticleEdit( $this->mTitle
);
1459 // Keep the same revision ID, but do some updates on it
1460 $revisionId = $this->getRevIdFetched();
1463 if( !$wgDBtransactions ) {
1464 ignore_user_abort( $userAbort );
1469 if (!$this->mTitle
->userIsWatching()) {
1470 $dbw->immediateCommit();
1476 if ( $this->mTitle
->userIsWatching() ) {
1477 $dbw->immediateCommit();
1483 # standard deferred updates
1484 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1488 # Invalidate caches of all articles using this article as a template
1490 # Template namespace
1491 # Purge all articles linking here
1492 $titles = $this->mTitle
->getTemplateLinksTo();
1493 Title
::touchArray( $titles );
1494 if ( $wgUseSquid ) {
1495 foreach ( $titles as $title ) {
1496 $urls[] = $title->getInternalURL();
1501 if ( $wgUseSquid ) {
1502 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1503 $u = new SquidUpdate( $urls );
1504 array_push( $wgPostCommitUpdateList, $u );
1508 if ( $wgUseFileCache ) {
1509 $cm = new CacheManager($this->mTitle
);
1510 @unlink
($cm->fileCacheName());
1513 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1515 wfRunHooks( 'ArticleSaveComplete',
1516 array( &$this, &$wgUser, $text,
1518 $watchthis, $sectionanchor ) );
1519 wfProfileOut( $fname );
1524 * After we've either updated or inserted the article, update
1525 * the link tables and redirect to the new page.
1526 * @todo FIXME some function arguments never used
1528 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1531 $fname = 'Article::showArticle';
1532 wfProfileIn( $fname );
1534 # Output the redirect
1535 if( $this->isRedirect( $text ) )
1539 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1541 wfProfileOut( $fname );
1545 * Mark this particular edit as patrolled
1547 function markpatrolled() {
1548 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1549 $wgOut->setRobotpolicy( 'noindex,follow' );
1551 # Check RC patrol config. option
1552 if( !$wgUseRCPatrol ) {
1553 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1558 if( !$wgUser->isAllowed( 'patrol' ) ) {
1559 $wgOut->permissionRequired( 'patrol' );
1563 $rcid = $wgRequest->getVal( 'rcid' );
1564 if ( !is_null ( $rcid ) ) {
1565 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1566 require_once( 'RecentChange.php' );
1567 RecentChange
::markPatrolled( $rcid );
1568 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1569 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1570 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1572 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1573 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1576 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1581 * User-interface handler for the "watch" action
1586 global $wgUser, $wgOut;
1588 if ( $wgUser->isAnon() ) {
1589 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1592 if ( wfReadOnly() ) {
1593 $wgOut->readOnlyPage();
1597 if( $this->doWatch() ) {
1598 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1599 $wgOut->setRobotpolicy( 'noindex,follow' );
1601 $link = $this->mTitle
->getPrefixedText();
1602 $text = wfMsg( 'addedwatchtext', $link );
1603 $wgOut->addWikiText( $text );
1606 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1610 * Add this page to $wgUser's watchlist
1611 * @return bool true on successful watch operation
1613 function doWatch() {
1615 if( $wgUser->isAnon() ) {
1619 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1620 $wgUser->addWatch( $this->mTitle
);
1621 $wgUser->saveSettings();
1623 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1630 * User interface handler for the "unwatch" action.
1632 function unwatch() {
1634 global $wgUser, $wgOut;
1636 if ( $wgUser->isAnon() ) {
1637 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1640 if ( wfReadOnly() ) {
1641 $wgOut->readOnlyPage();
1645 if( $this->doUnwatch() ) {
1646 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1647 $wgOut->setRobotpolicy( 'noindex,follow' );
1649 $link = $this->mTitle
->getPrefixedText();
1650 $text = wfMsg( 'removedwatchtext', $link );
1651 $wgOut->addWikiText( $text );
1654 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1658 * Stop watching a page
1659 * @return bool true on successful unwatch
1661 function doUnwatch() {
1663 if( $wgUser->isAnon() ) {
1667 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1668 $wgUser->removeWatch( $this->mTitle
);
1669 $wgUser->saveSettings();
1671 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1678 * action=protect handler
1680 function protect() {
1681 require_once 'ProtectionForm.php';
1682 $form = new ProtectionForm( $this );
1687 * action=unprotect handler (alias)
1689 function unprotect() {
1694 * Update the article's restriction field, and leave a log entry.
1696 * @param array $limit set of restriction keys
1697 * @param string $reason
1698 * @return bool true on success
1700 function updateRestrictions( $limit = array(), $reason = '' ) {
1701 global $wgUser, $wgRestrictionTypes, $wgContLang;
1703 $id = $this->mTitle
->getArticleID();
1704 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1708 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1709 # we expect a single selection, but the schema allows otherwise.
1711 foreach( $wgRestrictionTypes as $action )
1712 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1714 $current = Article
::flattenRestrictions( $current );
1715 $updated = Article
::flattenRestrictions( $limit );
1717 $changed = ( $current != $updated );
1718 $protect = ( $updated != '' );
1720 # If nothing's changed, do nothing
1722 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1724 $dbw =& wfGetDB( DB_MASTER
);
1726 # Prepare a null revision to be added to the history
1727 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ?
'protectedarticle' : 'unprotectedarticle', $this->mTitle
->getPrefixedText() ) );
1729 $comment .= ": $reason";
1731 $comment .= " [$updated]";
1732 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1733 $nullRevId = $nullRevision->insertOn( $dbw );
1735 # Update page record
1736 $dbw->update( 'page',
1738 'page_touched' => $dbw->timestamp(),
1739 'page_restrictions' => $updated,
1740 'page_latest' => $nullRevId
1741 ), array( /* WHERE */
1743 ), 'Article::protect'
1745 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1747 # Update the protection log
1748 $log = new LogPage( 'protect' );
1750 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$updated]" ) );
1752 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1756 } # End "changed" check
1762 * Take an array of page restrictions and flatten it to a string
1763 * suitable for insertion into the page_restrictions field.
1764 * @param array $limit
1768 function flattenRestrictions( $limit ) {
1769 if( !is_array( $limit ) ) {
1770 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1774 foreach( $limit as $action => $restrictions ) {
1775 if( $restrictions != '' ) {
1776 $bits[] = "$action=$restrictions";
1779 return implode( ':', $bits );
1783 * UI entry point for page deletion
1786 global $wgUser, $wgOut, $wgRequest;
1787 $fname = 'Article::delete';
1788 $confirm = $wgRequest->wasPosted() &&
1789 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1790 $reason = $wgRequest->getText( 'wpReason' );
1792 # This code desperately needs to be totally rewritten
1795 if( $wgUser->isAllowed( 'delete' ) ) {
1796 if( $wgUser->isBlocked() ) {
1797 $wgOut->blockedPage();
1801 $wgOut->permissionRequired( 'delete' );
1805 if( wfReadOnly() ) {
1806 $wgOut->readOnlyPage();
1810 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1812 # Better double-check that it hasn't been deleted yet!
1813 $dbw =& wfGetDB( DB_MASTER
);
1814 $conds = $this->mTitle
->pageCond();
1815 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1816 if ( $latest === false ) {
1817 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1822 $this->doDelete( $reason );
1826 # determine whether this page has earlier revisions
1827 # and insert a warning if it does
1829 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1831 if( count( $authors ) > 1 && !$confirm ) {
1832 $skin=$wgUser->getSkin();
1833 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1836 # If a single user is responsible for all revisions, find out who they are
1837 if ( count( $authors ) == $maxRevisions ) {
1838 // Query bailed out, too many revisions to find out if they're all the same
1839 $authorOfAll = false;
1841 $authorOfAll = reset( $authors );
1842 foreach ( $authors as $author ) {
1843 if ( $authorOfAll != $author ) {
1844 $authorOfAll = false;
1849 # Fetch article text
1850 $rev = Revision
::newFromTitle( $this->mTitle
);
1852 if( !is_null( $rev ) ) {
1853 # if this is a mini-text, we can paste part of it into the deletion reason
1854 $text = $rev->getText();
1856 #if this is empty, an earlier revision may contain "useful" text
1859 $prev = $rev->getPrevious();
1861 $text = $prev->getText();
1866 $length = strlen( $text );
1868 # this should not happen, since it is not possible to store an empty, new
1869 # page. Let's insert a standard text in case it does, though
1870 if( $length == 0 && $reason === '' ) {
1871 $reason = wfMsgForContent( 'exblank' );
1874 if( $length < 500 && $reason === '' ) {
1875 # comment field=255, let's grep the first 150 to have some user
1878 $text = $wgContLang->truncate( $text, 150, '...' );
1880 # let's strip out newlines
1881 $text = preg_replace( "/[\n\r]/", '', $text );
1884 if( $authorOfAll === false ) {
1885 $reason = wfMsgForContent( 'excontent', $text );
1887 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1890 $reason = wfMsgForContent( 'exbeforeblank', $text );
1895 return $this->confirmDelete( '', $reason );
1899 * Get the last N authors
1900 * @param int $num Number of revisions to get
1901 * @param string $revLatest The latest rev_id, selected from the master (optional)
1902 * @return array Array of authors, duplicates not removed
1904 function getLastNAuthors( $num, $revLatest = 0 ) {
1905 $fname = 'Article::getLastNAuthors';
1906 wfProfileIn( $fname );
1908 // First try the slave
1909 // If that doesn't have the latest revision, try the master
1911 $db =& wfGetDB( DB_SLAVE
);
1913 $res = $db->select( array( 'page', 'revision' ),
1914 array( 'rev_id', 'rev_user_text' ),
1916 'page_namespace' => $this->mTitle
->getNamespace(),
1917 'page_title' => $this->mTitle
->getDBkey(),
1918 'rev_page = page_id'
1919 ), $fname, $this->getSelectOptions( array(
1920 'ORDER BY' => 'rev_timestamp DESC',
1925 wfProfileOut( $fname );
1928 $row = $db->fetchObject( $res );
1929 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1930 $db =& wfGetDB( DB_MASTER
);
1935 } while ( $continue );
1937 $authors = array( $row->rev_user_text
);
1938 while ( $row = $db->fetchObject( $res ) ) {
1939 $authors[] = $row->rev_user_text
;
1941 wfProfileOut( $fname );
1946 * Output deletion confirmation dialog
1948 function confirmDelete( $par, $reason ) {
1949 global $wgOut, $wgUser;
1951 wfDebug( "Article::confirmDelete\n" );
1953 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1954 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1955 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1956 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1958 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1960 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1961 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1962 $token = htmlspecialchars( $wgUser->editToken() );
1965 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1969 <label for='wpReason'>{$delcom}:</label>
1972 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1978 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1982 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1985 $wgOut->returnToMain( false );
1990 * Perform a deletion and output success or failure messages
1992 function doDelete( $reason ) {
1993 global $wgOut, $wgUser;
1994 $fname = 'Article::doDelete';
1995 wfDebug( $fname."\n" );
1997 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1998 if ( $this->doDeleteArticle( $reason ) ) {
1999 $deleted = $this->mTitle
->getPrefixedText();
2001 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2002 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2004 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
2005 $text = wfMsg( 'deletedtext', $deleted, $loglink );
2007 $wgOut->addWikiText( $text );
2008 $wgOut->returnToMain( false );
2009 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
2011 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
2017 * Back-end article deletion
2018 * Deletes the article with database consistency, writes logs, purges caches
2021 function doDeleteArticle( $reason ) {
2022 global $wgUseSquid, $wgDeferredUpdateList;
2023 global $wgPostCommitUpdateList, $wgUseTrackbacks;
2025 $fname = 'Article::doDeleteArticle';
2026 wfDebug( $fname."\n" );
2028 $dbw =& wfGetDB( DB_MASTER
);
2029 $ns = $this->mTitle
->getNamespace();
2030 $t = $this->mTitle
->getDBkey();
2031 $id = $this->mTitle
->getArticleID();
2033 if ( $t == '' ||
$id == 0 ) {
2037 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
2038 array_push( $wgDeferredUpdateList, $u );
2040 $linksTo = $this->mTitle
->getLinksTo();
2043 if ( $wgUseSquid ) {
2045 $this->mTitle
->getInternalURL(),
2046 $this->mTitle
->getInternalURL( 'history' )
2049 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
2050 array_push( $wgPostCommitUpdateList, $u );
2054 # Client and file cache invalidation
2055 Title
::touchArray( $linksTo );
2058 // For now, shunt the revision data into the archive table.
2059 // Text is *not* removed from the text table; bulk storage
2060 // is left intact to avoid breaking block-compression or
2061 // immutable storage schemes.
2063 // For backwards compatibility, note that some older archive
2064 // table entries will have ar_text and ar_flags fields still.
2066 // In the future, we may keep revisions and mark them with
2067 // the rev_deleted field, which is reserved for this purpose.
2068 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2070 'ar_namespace' => 'page_namespace',
2071 'ar_title' => 'page_title',
2072 'ar_comment' => 'rev_comment',
2073 'ar_user' => 'rev_user',
2074 'ar_user_text' => 'rev_user_text',
2075 'ar_timestamp' => 'rev_timestamp',
2076 'ar_minor_edit' => 'rev_minor_edit',
2077 'ar_rev_id' => 'rev_id',
2078 'ar_text_id' => 'rev_text_id',
2081 'page_id = rev_page'
2085 # Now that it's safely backed up, delete it
2086 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2087 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2089 if ($wgUseTrackbacks)
2090 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2092 # Clean up recentchanges entries...
2093 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2095 # Finally, clean up the link tables
2096 $t = $this->mTitle
->getPrefixedDBkey();
2098 Article
::onArticleDelete( $this->mTitle
);
2100 # Delete outgoing links
2101 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2102 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2103 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2104 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2105 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2106 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2109 $log = new LogPage( 'delete' );
2110 $log->addEntry( 'delete', $this->mTitle
, $reason );
2112 # Clear the cached article id so the interface doesn't act like we exist
2113 $this->mTitle
->resetArticleID( 0 );
2114 $this->mTitle
->mArticleID
= 0;
2119 * Revert a modification
2121 function rollback() {
2122 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2123 $fname = 'Article::rollback';
2125 if( $wgUser->isAllowed( 'rollback' ) ) {
2126 if( $wgUser->isBlocked() ) {
2127 $wgOut->blockedPage();
2131 $wgOut->permissionRequired( 'rollback' );
2135 if ( wfReadOnly() ) {
2136 $wgOut->readOnlyPage( $this->getContent() );
2139 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2140 array( $this->mTitle
->getPrefixedText(),
2141 $wgRequest->getVal( 'from' ) ) ) ) {
2142 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2143 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2146 $dbw =& wfGetDB( DB_MASTER
);
2148 # Enhanced rollback, marks edits rc_bot=1
2149 $bot = $wgRequest->getBool( 'bot' );
2151 # Replace all this user's current edits with the next one down
2152 $tt = $this->mTitle
->getDBKey();
2153 $n = $this->mTitle
->getNamespace();
2155 # Get the last editor, lock table exclusively
2157 $current = Revision
::newFromTitle( $this->mTitle
);
2158 if( is_null( $current ) ) {
2159 # Something wrong... no page?
2161 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2165 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2166 if( $from != $current->getUserText() ) {
2167 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2168 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2169 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2170 htmlspecialchars( $from ),
2171 htmlspecialchars( $current->getUserText() ) ) );
2172 if( $current->getComment() != '') {
2174 wfMsg( 'editcomment',
2175 htmlspecialchars( $current->getComment() ) ) );
2180 # Get the last edit not by this guy
2181 $user = intval( $current->getUser() );
2182 $user_text = $dbw->addQuotes( $current->getUserText() );
2183 $s = $dbw->selectRow( 'revision',
2184 array( 'rev_id', 'rev_timestamp' ),
2186 'rev_page' => $current->getPage(),
2187 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2190 'USE INDEX' => 'page_timestamp',
2191 'ORDER BY' => 'rev_timestamp DESC' )
2193 if( $s === false ) {
2196 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2197 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2203 # Mark all reverted edits as bot
2206 if ( $wgUseRCPatrol ) {
2207 # Mark all reverted edits as patrolled
2208 $set['rc_patrolled'] = 1;
2212 $dbw->update( 'recentchanges', $set,
2214 'rc_cur_id' => $current->getPage(),
2215 'rc_user_text' => $current->getUserText(),
2216 "rc_timestamp > '{$s->rev_timestamp}'",
2221 # Get the edit summary
2222 $target = Revision
::newFromId( $s->rev_id
);
2223 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2224 $newComment = $wgRequest->getText( 'summary', $newComment );
2227 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2228 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2229 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2231 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2232 Article
::onArticleEdit( $this->mTitle
);
2235 $wgOut->returnToMain( false );
2240 * Do standard deferred updates after page view
2243 function viewUpdates() {
2244 global $wgDeferredUpdateList;
2246 if ( 0 != $this->getID() ) {
2247 global $wgDisableCounters;
2248 if( !$wgDisableCounters ) {
2249 Article
::incViewCount( $this->getID() );
2250 $u = new SiteStatsUpdate( 1, 0, 0 );
2251 array_push( $wgDeferredUpdateList, $u );
2255 # Update newtalk / watchlist notification status
2257 $wgUser->clearNotification( $this->mTitle
);
2261 * Do standard deferred updates after page edit.
2262 * Every 1000th edit, prune the recent changes table.
2264 * @param string $text
2266 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2267 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2269 $fname = 'Article::editUpdates';
2270 wfProfileIn( $fname );
2273 $options = new ParserOptions
;
2274 $options->setTidy(true);
2275 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2277 # Save it to the parser cache
2278 $parserCache =& ParserCache
::singleton();
2279 $parserCache->save( $poutput, $this, $wgUser );
2281 # Update the links tables
2282 $u = new LinksUpdate( $this->mTitle
, $poutput );
2285 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2287 if ( 0 == mt_rand( 0, 999 ) ) {
2288 # Periodically flush old entries from the recentchanges table.
2291 $dbw =& wfGetDB( DB_MASTER
);
2292 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2293 $recentchanges = $dbw->tableName( 'recentchanges' );
2294 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2295 $dbw->query( $sql );
2299 $id = $this->getID();
2300 $title = $this->mTitle
->getPrefixedDBkey();
2301 $shortTitle = $this->mTitle
->getDBkey();
2304 wfProfileOut( $fname );
2308 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2309 array_push( $wgDeferredUpdateList, $u );
2310 $u = new SearchUpdate( $id, $title, $text );
2311 array_push( $wgDeferredUpdateList, $u );
2313 # If this is another user's talk page, update newtalk
2315 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
2316 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2317 $other = User
::newFromName( $shortTitle );
2318 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2319 // An anonymous user
2320 $other = new User();
2321 $other->setName( $shortTitle );
2324 $other->setNewtalk( true );
2329 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2330 $wgMessageCache->replace( $shortTitle, $text );
2333 wfProfileOut( $fname );
2337 * Generate the navigation links when browsing through an article revisions
2338 * It shows the information as:
2339 * Revision as of \<date\>; view current revision
2340 * \<- Previous version | Next Version -\>
2343 * @param string $oldid Revision ID of this article revision
2345 function setOldSubtitle( $oldid=0 ) {
2346 global $wgLang, $wgOut, $wgUser;
2348 $current = ( $oldid == $this->mLatest
);
2349 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2350 $sk = $wgUser->getSkin();
2352 ?
wfMsg( 'currentrevisionlink' )
2353 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2354 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2356 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2357 : wfMsg( 'previousrevision' );
2358 $nextlink = $current
2359 ?
wfMsg( 'nextrevision' )
2360 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2361 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2362 $wgOut->setSubtitle( $r );
2366 * This function is called right before saving the wikitext,
2367 * so we can do things like signatures and links-in-context.
2369 * @param string $text
2371 function preSaveTransform( $text ) {
2372 global $wgParser, $wgUser;
2373 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2376 /* Caching functions */
2379 * checkLastModified returns true if it has taken care of all
2380 * output to the client that is necessary for this request.
2381 * (that is, it has sent a cached version of the page)
2383 function tryFileCache() {
2384 static $called = false;
2386 wfDebug( " tryFileCache() -- called twice!?\n" );
2390 if($this->isFileCacheable()) {
2391 $touched = $this->mTouched
;
2392 $cache = new CacheManager( $this->mTitle
);
2393 if($cache->isFileCacheGood( $touched )) {
2394 wfDebug( " tryFileCache() - about to load\n" );
2395 $cache->loadFromFileCache();
2398 wfDebug( " tryFileCache() - starting buffer\n" );
2399 ob_start( array(&$cache, 'saveToFileCache' ) );
2402 wfDebug( " tryFileCache() - not cacheable\n" );
2407 * Check if the page can be cached
2410 function isFileCacheable() {
2411 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2412 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2414 return $wgUseFileCache
2415 and (!$wgShowIPinHeader)
2416 and ($this->getID() != 0)
2417 and ($wgUser->isAnon())
2418 and (!$wgUser->getNewtalk())
2419 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2420 and (empty( $action ) ||
$action == 'view')
2421 and (!isset($oldid))
2423 and (!isset($redirect))
2424 and (!isset($printable))
2425 and (!$this->mRedirectedFrom
);
2429 * Loads page_touched and returns a value indicating if it should be used
2432 function checkTouched() {
2433 $fname = 'Article::checkTouched';
2434 if( !$this->mDataLoaded
) {
2435 $this->loadPageData();
2437 return !$this->mIsRedirect
;
2441 * Get the page_touched field
2443 function getTouched() {
2444 # Ensure that page data has been loaded
2445 if( !$this->mDataLoaded
) {
2446 $this->loadPageData();
2448 return $this->mTouched
;
2452 * Get the page_latest field
2454 function getLatest() {
2455 if ( !$this->mDataLoaded
) {
2456 $this->loadPageData();
2458 return $this->mLatest
;
2462 * Edit an article without doing all that other stuff
2463 * The article must already exist; link tables etc
2464 * are not updated, caches are not flushed.
2466 * @param string $text text submitted
2467 * @param string $comment comment submitted
2468 * @param bool $minor whereas it's a minor modification
2470 function quickEdit( $text, $comment = '', $minor = 0 ) {
2471 $fname = 'Article::quickEdit';
2472 wfProfileIn( $fname );
2474 $dbw =& wfGetDB( DB_MASTER
);
2476 $revision = new Revision( array(
2477 'page' => $this->getId(),
2479 'comment' => $comment,
2480 'minor_edit' => $minor ?
1 : 0,
2482 # fixme : $revisionId never used
2483 $revisionId = $revision->insertOn( $dbw );
2484 $this->updateRevisionOn( $dbw, $revision );
2487 wfProfileOut( $fname );
2491 * Used to increment the view counter
2494 * @param integer $id article id
2496 function incViewCount( $id ) {
2497 $id = intval( $id );
2498 global $wgHitcounterUpdateFreq, $wgDBtype;
2500 $dbw =& wfGetDB( DB_MASTER
);
2501 $pageTable = $dbw->tableName( 'page' );
2502 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2503 $acchitsTable = $dbw->tableName( 'acchits' );
2505 if( $wgHitcounterUpdateFreq <= 1 ){ //
2506 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2510 # Not important enough to warrant an error page in case of failure
2511 $oldignore = $dbw->ignoreErrors( true );
2513 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2515 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2516 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2517 # Most of the time (or on SQL errors), skip row count check
2518 $dbw->ignoreErrors( $oldignore );
2522 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2523 $row = $dbw->fetchObject( $res );
2524 $rown = intval( $row->n
);
2525 if( $rown >= $wgHitcounterUpdateFreq ){
2526 wfProfileIn( 'Article::incViewCount-collect' );
2527 $old_user_abort = ignore_user_abort( true );
2529 if ($wgDBtype == 'mysql')
2530 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2531 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2532 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype".
2533 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2535 $dbw->query("DELETE FROM $hitcounterTable");
2536 if ($wgDBtype == 'mysql')
2537 $dbw->query('UNLOCK TABLES');
2538 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2539 'WHERE page_id = hc_id');
2540 $dbw->query("DROP TABLE $acchitsTable");
2542 ignore_user_abort( $old_user_abort );
2543 wfProfileOut( 'Article::incViewCount-collect' );
2545 $dbw->ignoreErrors( $oldignore );
2549 * The onArticle*() functions are supposed to be a kind of hooks
2550 * which should be called whenever any of the specified actions
2553 * This is a good place to put code to clear caches, for instance.
2555 * This is called on page move and undelete, as well as edit
2557 * @param $title_obj a title object
2560 function onArticleCreate($title_obj) {
2561 global $wgUseSquid, $wgPostCommitUpdateList;
2563 $title_obj->touchLinks();
2564 $titles = $title_obj->getLinksTo();
2567 if ( $wgUseSquid ) {
2568 $urls = $title_obj->getSquidURLs();
2569 foreach ( $titles as $linkTitle ) {
2570 $urls[] = $linkTitle->getInternalURL();
2572 $u = new SquidUpdate( $urls );
2573 array_push( $wgPostCommitUpdateList, $u );
2577 function onArticleDelete( $title ) {
2578 global $wgMessageCache;
2580 $title->touchLinks();
2582 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2583 $wgMessageCache->replace( $title->getDBkey(), false );
2588 * Purge caches on page update etc
2590 function onArticleEdit( $title ) {
2591 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2595 // Template namespace? Purge all articles linking here.
2596 // FIXME: When a templatelinks table arrives, use it for all includes.
2597 if ( $title->getNamespace() == NS_TEMPLATE
) {
2598 $titles = $title->getLinksTo();
2599 Title
::touchArray( $titles );
2600 if ( $wgUseSquid ) {
2601 foreach ( $titles as $link ) {
2602 $urls[] = $link->getInternalURL();
2608 if ( $wgUseSquid ) {
2609 $urls = array_merge( $urls, $title->getSquidURLs() );
2610 $u = new SquidUpdate( $urls );
2611 array_push( $wgPostCommitUpdateList, $u );
2615 if ( $wgUseFileCache ) {
2616 $cm = new CacheManager( $title );
2617 @unlink
( $cm->fileCacheName() );
2624 * Info about this page
2625 * Called for ?action=info when $wgAllowPageInfo is on.
2630 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2631 $fname = 'Article::info';
2633 if ( !$wgAllowPageInfo ) {
2634 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2638 $page = $this->mTitle
->getSubjectPage();
2640 $wgOut->setPagetitle( $page->getPrefixedText() );
2641 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2643 # first, see if the page exists at all.
2644 $exists = $page->getArticleId() != 0;
2646 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2647 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2649 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2652 $dbr =& wfGetDB( DB_SLAVE
);
2654 'wl_title' => $page->getDBkey(),
2655 'wl_namespace' => $page->getNamespace() );
2656 $numwatchers = $dbr->selectField(
2661 $this->getSelectOptions() );
2663 $pageInfo = $this->pageCountInfo( $page );
2664 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2666 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2667 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2669 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2671 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2673 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2675 $wgOut->addHTML( '</ul>' );
2681 * Return the total number of edits and number of unique editors
2682 * on a given page. If page does not exist, returns false.
2684 * @param Title $title
2688 function pageCountInfo( $title ) {
2689 $id = $title->getArticleId();
2694 $dbr =& wfGetDB( DB_SLAVE
);
2696 $rev_clause = array( 'rev_page' => $id );
2697 $fname = 'Article::pageCountInfo';
2699 $edits = $dbr->selectField(
2704 $this->getSelectOptions() );
2706 $authors = $dbr->selectField(
2708 'COUNT(DISTINCT rev_user_text)',
2711 $this->getSelectOptions() );
2713 return array( 'edits' => $edits, 'authors' => $authors );
2717 * Return a list of templates used by this article.
2718 * Uses the templatelinks table
2720 * @return array Array of Title objects
2722 function getUsedTemplates() {
2724 $id = $this->mTitle
->getArticleID();
2729 $dbr =& wfGetDB( DB_SLAVE
);
2730 $res = $dbr->select( array( 'templatelinks' ),
2731 array( 'tl_namespace', 'tl_title' ),
2732 array( 'tl_from' => $id ),
2733 'Article:getUsedTemplates' );
2734 if ( false !== $res ) {
2735 if ( $dbr->numRows( $res ) ) {
2736 while ( $row = $dbr->fetchObject( $res ) ) {
2737 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2741 $dbr->freeResult( $res );