8 * Need the CacheManager to be loaded
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
17 * Class representing a MediaWiki article and history.
19 * See design.txt for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mGoodAdjustment, $mTotalAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
44 * Constructor and clear the article
45 * @param Title &$title
46 * @param integer $oldId Revision ID, null to fetch from request, zero for current
48 function Article( &$title, $oldId = null ) {
49 $this->mTitle
=& $title;
50 $this->mOldId
= $oldId;
55 * Tell the page view functions that this view was redirected
56 * from another page on the wiki.
59 function setRedirectedFrom( $from ) {
60 $this->mRedirectedFrom
= $from;
64 * @return mixed false, Title of in-wiki target, or string with URL
66 function followRedirect() {
67 $text = $this->getContent();
68 $rt = Title
::newFromRedirect( $text );
70 # process if title object is valid and not special:userlogout
72 if( $rt->getInterwiki() != '' ) {
73 if( $rt->isLocal() ) {
74 // Offsite wikis need an HTTP redirect.
76 // This can be hard to reverse and may produce loops,
77 // so they may be disabled in the site configuration.
79 $source = $this->mTitle
->getFullURL( 'redirect=no' );
80 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
83 if( $rt->getNamespace() == NS_SPECIAL
) {
84 // Gotta hand redirects to special pages differently:
85 // Fill the HTTP response "Location" header and ignore
86 // the rest of the page we're on.
88 // This can be hard to reverse, so they may be disabled.
90 if( $rt->getNamespace() == NS_SPECIAL
&& $rt->getText() == 'Userlogout' ) {
93 return $rt->getFullURL();
100 // No or invalid redirect
105 * get the title object of the article
107 function getTitle() {
108 return $this->mTitle
;
116 $this->mDataLoaded
= false;
117 $this->mContentLoaded
= false;
119 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
120 $this->mRedirectedFrom
= null; # Title object if set
122 $this->mTimestamp
= $this->mComment
= $this->mFileCache
= '';
123 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
124 $this->mTouched
= '19700101000000';
125 $this->mForUpdate
= false;
126 $this->mIsRedirect
= false;
127 $this->mRevIdFetched
= 0;
128 $this->mRedirectUrl
= false;
129 $this->mLatest
= false;
133 * Note that getContent/loadContent do not follow redirects anymore.
134 * If you need to fetch redirectable content easily, try
135 * the shortcut in Article::followContent()
137 * @fixme There are still side-effects in this!
138 * In general, you should use the Revision class, not Article,
139 * to fetch text for purposes other than page views.
141 * @return Return the text of this revision
143 function getContent() {
144 global $wgRequest, $wgUser, $wgOut;
146 # Get variables from query string :P
147 $action = $wgRequest->getText( 'action', 'view' );
148 $section = $wgRequest->getText( 'section' );
149 $preload = $wgRequest->getText( 'preload' );
151 $fname = 'Article::getContent';
152 wfProfileIn( $fname );
154 if ( 0 == $this->getID() ) {
155 if ( 'edit' == $action ) {
156 wfProfileOut( $fname );
158 # If requested, preload some text.
159 $text=$this->getPreloadedText($preload);
161 # We used to put MediaWiki:Newarticletext here if
162 # $text was empty at this point.
163 # This is now shown above the edit box instead.
166 wfProfileOut( $fname );
167 $wgOut->setRobotpolicy( 'noindex,nofollow' );
169 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
170 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
172 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
175 return "<div class='noarticletext'>$ret</div>";
177 $this->loadContent();
178 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
179 if ( $this->mTitle
->getNamespace() == NS_USER_TALK
&&
180 $wgUser->isIP($this->mTitle
->getText()) &&
183 wfProfileOut( $fname );
184 return $this->mContent
. "\n" .wfMsg('anontalkpagetext');
186 if($action=='edit') {
188 if($section=='new') {
189 wfProfileOut( $fname );
190 $text=$this->getPreloadedText($preload);
194 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
195 # comments to be stripped as well)
196 $rv=$this->getSection($this->mContent
,$section);
197 wfProfileOut( $fname );
201 wfProfileOut( $fname );
202 return $this->mContent
;
208 * Get the contents of a page from its title and remove includeonly tags
210 * @param string The title of the page
211 * @return string The contents of the page
213 function getPreloadedText($preload) {
214 if ( $preload === '' )
217 $preloadTitle = Title
::newFromText( $preload );
218 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
219 $rev=Revision
::newFromTitle($preloadTitle);
220 if ( is_object( $rev ) ) {
221 $text = $rev->getText();
222 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
223 // its own mini-parser! -ævar
224 $text = preg_replace( '~</?includeonly>~', '', $text );
233 * This function returns the text of a section, specified by a number ($section).
234 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
235 * the first section before any such heading (section 0).
237 * If a section contains subsections, these are also returned.
239 * @param string $text text to look in
240 * @param integer $section section number
241 * @return string text of the requested section
243 function getSection($text,$section) {
245 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
246 # comments to be stripped as well)
248 $parser=new Parser();
249 $parser->mOutputType
=OT_WIKI
;
250 $parser->mOptions
= new ParserOptions();
251 $striptext=$parser->strip($text, $striparray, true);
253 # now that we can be sure that no pseudo-sections are in the source,
254 # split it up by section
257 '/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
259 PREG_SPLIT_DELIM_CAPTURE
);
263 $headline=$secs[$section*2-1];
264 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
267 # translate wiki heading into level
268 if(strpos($hlevel,'=')!==false) {
269 $hlevel=strlen($hlevel);
272 $rv=$headline. $secs[$section*2];
276 while(!empty($secs[$count*2-1]) && !$break) {
278 $subheadline=$secs[$count*2-1];
279 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
280 $subhlevel=$matches[1];
281 if(strpos($subhlevel,'=')!==false) {
282 $subhlevel=strlen($subhlevel);
284 if($subhlevel > $hlevel) {
285 $rv.=$subheadline.$secs[$count*2];
287 if($subhlevel <= $hlevel) {
294 # reinsert stripped tags
295 $rv=$parser->unstrip($rv,$striparray);
296 $rv=$parser->unstripNoWiki($rv,$striparray);
303 * @return int The oldid of the article that is to be shown, 0 for the
306 function getOldID() {
307 if ( is_null( $this->mOldId
) ) {
308 $this->mOldId
= $this->getOldIDFromRequest();
310 return $this->mOldId
;
314 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
316 * @return int The old id for the request
318 function getOldIDFromRequest() {
320 $this->mRedirectUrl
= false;
321 $oldid = $wgRequest->getVal( 'oldid' );
322 if ( isset( $oldid ) ) {
323 $oldid = intval( $oldid );
324 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
325 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
329 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
331 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
332 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
348 * Load the revision (including text) into this object
350 function loadContent() {
351 if ( $this->mContentLoaded
) return;
354 $oldid = $this->getOldID();
356 $fname = 'Article::loadContent';
358 # Pre-fill content with error message so that if something
359 # fails we'll have something telling us what we intended.
361 $t = $this->mTitle
->getPrefixedText();
363 $this->mOldId
= $oldid;
364 $this->fetchContent( $oldid );
369 * Fetch a page record with the given conditions
370 * @param Database $dbr
371 * @param array $conditions
374 function pageData( &$dbr, $conditions ) {
387 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
388 $row = $dbr->selectRow( 'page',
391 'Article::pageData' );
392 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
397 * @param Database $dbr
398 * @param Title $title
400 function pageDataFromTitle( &$dbr, $title ) {
401 return $this->pageData( $dbr, array(
402 'page_namespace' => $title->getNamespace(),
403 'page_title' => $title->getDBkey() ) );
407 * @param Database $dbr
410 function pageDataFromId( &$dbr, $id ) {
411 return $this->pageData( $dbr, array( 'page_id' => $id ) );
415 * Set the general counter, title etc data loaded from
418 * @param object $data
421 function loadPageData( $data = 'fromdb' ) {
422 if ( $data === 'fromdb' ) {
423 $dbr =& $this->getDB();
424 $data = $this->pageDataFromId( $dbr, $this->getId() );
427 $lc =& LinkCache
::singleton();
429 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
431 $this->mTitle
->mArticleID
= $data->page_id
;
432 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
433 $this->mTitle
->mRestrictionsLoaded
= true;
435 $this->mCounter
= $data->page_counter
;
436 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
437 $this->mIsRedirect
= $data->page_is_redirect
;
438 $this->mLatest
= $data->page_latest
;
440 $lc->addBadLinkObj( $this->mTitle
);
441 $this->mTitle
->mArticleID
= 0;
444 $this->mDataLoaded
= true;
448 * Get text of an article from database
449 * Does *NOT* follow redirects.
450 * @param int $oldid 0 for whatever the latest revision is
453 function fetchContent( $oldid = 0 ) {
454 if ( $this->mContentLoaded
) {
455 return $this->mContent
;
458 $dbr =& $this->getDB();
459 $fname = 'Article::fetchContent';
461 # Pre-fill content with error message so that if something
462 # fails we'll have something telling us what we intended.
463 $t = $this->mTitle
->getPrefixedText();
465 $t .= ',oldid='.$oldid;
467 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
470 $revision = Revision
::newFromId( $oldid );
471 if( is_null( $revision ) ) {
472 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
475 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
477 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
480 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
481 $this->loadPageData( $data );
483 if( !$this->mDataLoaded
) {
484 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
486 wfDebug( "$fname failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
489 $this->loadPageData( $data );
491 $revision = Revision
::newFromId( $this->mLatest
);
492 if( is_null( $revision ) ) {
493 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
498 $this->mContent
= $revision->getText();
500 $this->mUser
= $revision->getUser();
501 $this->mUserText
= $revision->getUserText();
502 $this->mComment
= $revision->getComment();
503 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
505 $this->mRevIdFetched
= $revision->getID();
506 $this->mContentLoaded
= true;
507 $this->mRevision
=& $revision;
509 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
511 return $this->mContent
;
515 * Read/write accessor to select FOR UPDATE
519 function forUpdate( $x = NULL ) {
520 return wfSetVar( $this->mForUpdate
, $x );
524 * Get the database which should be used for reads
529 $ret =& wfGetDB( DB_MASTER
);
534 * Get options for all SELECT statements
536 * @param array $options an optional options array which'll be appended to
538 * @return array Options
540 function getSelectOptions( $options = '' ) {
541 if ( $this->mForUpdate
) {
542 if ( is_array( $options ) ) {
543 $options[] = 'FOR UPDATE';
545 $options = 'FOR UPDATE';
552 * @return int Page ID
555 if( $this->mTitle
) {
556 return $this->mTitle
->getArticleID();
563 * @return bool Whether or not the page exists in the database
566 return $this->getId() != 0;
570 * @return int The view count for the page
572 function getCount() {
573 if ( -1 == $this->mCounter
) {
574 $id = $this->getID();
578 $dbr =& wfGetDB( DB_SLAVE
);
579 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
580 'Article::getCount', $this->getSelectOptions() );
583 return $this->mCounter
;
587 * Determine whether a page would be suitable for being counted as an
588 * article in the site_stats table based on the title & its content
590 * @param string $text Text to analyze
593 function isCountable( $text ) {
594 global $wgUseCommaCount;
596 $token = $wgUseCommaCount ?
',' : '[[';
598 $this->mTitle
->getNamespace() == NS_MAIN
599 && ! $this->isRedirect( $text )
600 && in_string( $token, $text );
604 * Tests if the article text represents a redirect
606 * @param string $text
609 function isRedirect( $text = false ) {
610 if ( $text === false ) {
611 $this->loadContent();
612 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
614 $titleObj = Title
::newFromRedirect( $text );
616 return $titleObj !== NULL;
620 * Returns true if the currently-referenced revision is the current edit
621 * to this page (and it exists).
624 function isCurrent() {
625 return $this->exists() &&
626 isset( $this->mRevision
) &&
627 $this->mRevision
->isCurrent();
631 * Loads everything except the text
632 * This isn't necessary for all uses, so it's only done if needed.
635 function loadLastEdit() {
636 if ( -1 != $this->mUser
)
639 # New or non-existent articles have no user information
640 $id = $this->getID();
641 if ( 0 == $id ) return;
643 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
644 if( !is_null( $this->mLastRevision
) ) {
645 $this->mUser
= $this->mLastRevision
->getUser();
646 $this->mUserText
= $this->mLastRevision
->getUserText();
647 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
648 $this->mComment
= $this->mLastRevision
->getComment();
649 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
650 $this->mRevIdFetched
= $this->mLastRevision
->getID();
654 function getTimestamp() {
655 // Check if the field has been filled by ParserCache::get()
656 if ( !$this->mTimestamp
) {
657 $this->loadLastEdit();
659 return wfTimestamp(TS_MW
, $this->mTimestamp
);
663 $this->loadLastEdit();
667 function getUserText() {
668 $this->loadLastEdit();
669 return $this->mUserText
;
672 function getComment() {
673 $this->loadLastEdit();
674 return $this->mComment
;
677 function getMinorEdit() {
678 $this->loadLastEdit();
679 return $this->mMinorEdit
;
682 function getRevIdFetched() {
683 $this->loadLastEdit();
684 return $this->mRevIdFetched
;
687 function getContributors($limit = 0, $offset = 0) {
688 $fname = 'Article::getContributors';
690 # XXX: this is expensive; cache this info somewhere.
692 $title = $this->mTitle
;
694 $dbr =& wfGetDB( DB_SLAVE
);
695 $revTable = $dbr->tableName( 'revision' );
696 $userTable = $dbr->tableName( 'user' );
697 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
698 $ns = $title->getNamespace();
699 $user = $this->getUser();
700 $pageId = $this->getId();
702 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
703 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
704 WHERE rev_page = $pageId
705 AND rev_user != $user
706 GROUP BY rev_user, rev_user_text, user_real_name
707 ORDER BY timestamp DESC";
709 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
710 $sql .= ' '. $this->getSelectOptions();
712 $res = $dbr->query($sql, $fname);
714 while ( $line = $dbr->fetchObject( $res ) ) {
715 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
718 $dbr->freeResult($res);
723 * This is the default action of the script: just view the page of
727 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgContLang;
728 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
729 global $wgUseTrackbacks;
730 $sk = $wgUser->getSkin();
732 $fname = 'Article::view';
733 wfProfileIn( $fname );
734 $parserCache =& ParserCache
::singleton();
735 # Get variables from query string
736 $oldid = $this->getOldID();
738 # getOldID may want us to redirect somewhere else
739 if ( $this->mRedirectUrl
) {
740 $wgOut->redirect( $this->mRedirectUrl
);
741 wfProfileOut( $fname );
745 $diff = $wgRequest->getVal( 'diff' );
746 $rcid = $wgRequest->getVal( 'rcid' );
747 $rdfrom = $wgRequest->getVal( 'rdfrom' );
749 $wgOut->setArticleFlag( true );
750 $wgOut->setRobotpolicy( 'index,follow' );
751 # If we got diff and oldid in the query, we want to see a
752 # diff page instead of the article.
754 if ( !is_null( $diff ) ) {
755 require_once( 'DifferenceEngine.php' );
756 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
758 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
759 // DifferenceEngine directly fetched the revision:
760 $this->mRevIdFetched
= $de->mNewid
;
764 # Run view updates for current revision only
765 $this->viewUpdates();
767 wfProfileOut( $fname );
771 if ( empty( $oldid ) && $this->checkTouched() ) {
772 $wgOut->setETag($parserCache->getETag($this, $wgUser));
774 if( $wgOut->checkLastModified( $this->mTouched
) ){
775 wfProfileOut( $fname );
777 } else if ( $this->tryFileCache() ) {
778 # tell wgOut that output is taken care of
780 $this->viewUpdates();
781 wfProfileOut( $fname );
785 # Should the parser cache be used?
786 $pcache = $wgEnableParserCache &&
787 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
790 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
791 if ( $wgUser->getOption( 'stubthreshold' ) ) {
792 wfIncrStats( 'pcache_miss_stub' );
795 $wasRedirected = false;
796 if ( isset( $this->mRedirectedFrom
) ) {
797 // This is an internally redirected page view.
798 // We'll need a backlink to the source page for navigation.
799 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
800 $sk = $wgUser->getSkin();
801 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
802 $s = wfMsg( 'redirectedfrom', $redir );
803 $wgOut->setSubtitle( $s );
804 $wasRedirected = true;
806 } elseif ( !empty( $rdfrom ) ) {
807 // This is an externally redirected view, from some other wiki.
808 // If it was reported from a trusted site, supply a backlink.
809 global $wgRedirectSources;
810 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
811 $sk = $wgUser->getSkin();
812 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
813 $s = wfMsg( 'redirectedfrom', $redir );
814 $wgOut->setSubtitle( $s );
815 $wasRedirected = true;
821 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
825 if ( !$outputDone ) {
826 $text = $this->getContent();
827 if ( $text === false ) {
828 # Failed to load, replace text with error message
829 $t = $this->mTitle
->getPrefixedText();
831 $t .= ',oldid='.$oldid;
832 $text = wfMsg( 'missingarticle', $t );
834 $text = wfMsg( 'noarticletext', $t );
838 # Another whitelist check in case oldid is altering the title
839 if ( !$this->mTitle
->userCanRead() ) {
840 $wgOut->loginToUse();
845 # We're looking at an old revision
847 if ( !empty( $oldid ) ) {
848 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
849 $wgOut->setRobotpolicy( 'noindex,follow' );
854 * @fixme: this hook doesn't work most of the time, as it doesn't
855 * trigger when the parser cache is used.
857 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
858 $wgOut->setRevisionId( $this->getRevIdFetched() );
859 # wrap user css and user js in pre and don't parse
860 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
862 $this->mTitle
->getNamespace() == NS_USER
&&
863 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
865 $wgOut->addWikiText( wfMsg('clearyourcache'));
866 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
867 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
869 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
870 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
871 if( !$wasRedirected ) {
872 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
874 $targetUrl = $rt->escapeLocalURL();
875 $titleText = htmlspecialchars( $rt->getPrefixedText() );
876 $link = $sk->makeLinkObj( $rt );
878 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
879 '<span class="redirectText">'.$link.'</span>' );
881 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
882 $wgOut->addParserOutputNoText( $parseout );
883 } else if ( $pcache ) {
884 # Display content and save to parser cache
885 $wgOut->addPrimaryWikiText( $text, $this );
887 # Display content, don't attempt to save to parser cache
889 # Don't show section-edit links on old revisions... this way lies madness.
890 if( !$this->isCurrent() ) {
891 $oldEditSectionSetting = $wgOut->mParserOptions
->setEditSection( false );
893 # Display content and don't save to parser cache
894 $wgOut->addPrimaryWikiText( $text, $this, false );
896 if( !$this->isCurrent() ) {
897 $wgOut->mParserOptions
->setEditSection( $oldEditSectionSetting );
901 /* title may have been set from the cache */
902 $t = $wgOut->getPageTitle();
904 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
907 # If we have been passed an &rcid= parameter, we want to give the user a
908 # chance to mark this new article as patrolled.
912 && $wgUser->isLoggedIn()
913 && ( $wgUser->isAllowed('patrol') ||
!$wgOnlySysopsCanPatrol ) )
916 "<div class='patrollink'>" .
917 wfMsg ( 'markaspatrolledlink',
918 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
925 if ($wgUseTrackbacks)
926 $this->addTrackbacks();
928 $this->viewUpdates();
929 wfProfileOut( $fname );
932 function addTrackbacks() {
933 global $wgOut, $wgUser;
935 $dbr =& wfGetDB(DB_SLAVE
);
937 /* FROM */ 'trackbacks',
938 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
939 /* WHERE */ array('tb_page' => $this->getID())
942 if (!$dbr->numrows($tbs))
946 while ($o = $dbr->fetchObject($tbs)) {
948 if ($wgUser->isSysop()) {
949 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
950 . $o->tb_id
. "&token=" . $wgUser->editToken());
951 $rmvtxt = wfMsg('trackbackremove', $delurl);
953 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
960 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
963 function deletetrackback() {
964 global $wgUser, $wgRequest, $wgOut, $wgTitle;
966 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
967 $wgOut->addWikitext(wfMsg('sessionfailure'));
971 if ((!$wgUser->isAllowed('delete'))) {
972 $wgOut->sysopRequired();
977 $wgOut->readOnlyPage();
981 $db =& wfGetDB(DB_MASTER
);
982 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
983 $wgTitle->invalidateCache();
984 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
990 $wgOut->setArticleBodyOnly(true);
995 * Handle action=purge
998 global $wgUser, $wgRequest, $wgOut;
1000 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
1001 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
1005 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
1006 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
1007 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
1008 $msg = str_replace( '$1',
1009 "<form method=\"post\" action=\"$action\">\n" .
1010 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
1011 "</form>\n", $msg );
1013 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
1014 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1015 $wgOut->addHTML( $msg );
1020 * Perform the actions of a page purging
1022 function doPurge() {
1024 // Invalidate the cache
1025 $this->mTitle
->invalidateCache();
1027 if ( $wgUseSquid ) {
1028 // Commit the transaction before the purge is sent
1029 $dbw = wfGetDB( DB_MASTER
);
1030 $dbw->immediateCommit();
1033 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
1034 $update->doUpdate();
1040 * Insert a new empty page record for this article.
1041 * This *must* be followed up by creating a revision
1042 * and running $this->updateToLatest( $rev_id );
1043 * or else the record will be left in a funky state.
1044 * Best if all done inside a transaction.
1046 * @param Database $dbw
1047 * @param string $restrictions
1048 * @return int The newly created page_id key
1051 function insertOn( &$dbw, $restrictions = '' ) {
1052 $fname = 'Article::insertOn';
1053 wfProfileIn( $fname );
1055 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1056 $dbw->insert( 'page', array(
1057 'page_id' => $page_id,
1058 'page_namespace' => $this->mTitle
->getNamespace(),
1059 'page_title' => $this->mTitle
->getDBkey(),
1060 'page_counter' => 0,
1061 'page_restrictions' => $restrictions,
1062 'page_is_redirect' => 0, # Will set this shortly...
1064 'page_random' => wfRandom(),
1065 'page_touched' => $dbw->timestamp(),
1066 'page_latest' => 0, # Fill this in shortly...
1067 'page_len' => 0, # Fill this in shortly...
1069 $newid = $dbw->insertId();
1071 $this->mTitle
->resetArticleId( $newid );
1073 wfProfileOut( $fname );
1078 * Update the page record to point to a newly saved revision.
1080 * @param Database $dbw
1081 * @param Revision $revision For ID number, and text used to set
1082 length and redirect status fields
1083 * @param int $lastRevision If given, will not overwrite the page field
1084 * when different from the currently set value.
1085 * Giving 0 indicates the new page flag should
1087 * @return bool true on success, false on failure
1090 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1091 $fname = 'Article::updateToRevision';
1092 wfProfileIn( $fname );
1094 $conditions = array( 'page_id' => $this->getId() );
1095 if( !is_null( $lastRevision ) ) {
1096 # An extra check against threads stepping on each other
1097 $conditions['page_latest'] = $lastRevision;
1100 $text = $revision->getText();
1101 $dbw->update( 'page',
1103 'page_latest' => $revision->getId(),
1104 'page_touched' => $dbw->timestamp(),
1105 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1106 'page_is_redirect' => Article
::isRedirect( $text ) ?
1 : 0,
1107 'page_len' => strlen( $text ),
1112 wfProfileOut( $fname );
1113 return ( $dbw->affectedRows() != 0 );
1117 * If the given revision is newer than the currently set page_latest,
1118 * update the page record. Otherwise, do nothing.
1120 * @param Database $dbw
1121 * @param Revision $revision
1123 function updateIfNewerOn( &$dbw, $revision ) {
1124 $fname = 'Article::updateIfNewerOn';
1125 wfProfileIn( $fname );
1127 $row = $dbw->selectRow(
1128 array( 'revision', 'page' ),
1129 array( 'rev_id', 'rev_timestamp' ),
1131 'page_id' => $this->getId(),
1132 'page_latest=rev_id' ),
1135 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1136 wfProfileOut( $fname );
1139 $prev = $row->rev_id
;
1141 # No or missing previous revision; mark the page as new
1145 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1146 wfProfileOut( $fname );
1151 * Insert a new article into the database
1154 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1157 $fname = 'Article::insertNewArticle';
1158 wfProfileIn( $fname );
1160 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1161 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1162 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1163 wfProfileOut( $fname );
1167 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1168 $this->mTotalAdjustment
= 1;
1170 $ns = $this->mTitle
->getNamespace();
1171 $ttl = $this->mTitle
->getDBkey();
1173 # If this is a comment, add the summary as headline
1174 if($comment && $summary!="") {
1175 $text="== {$summary} ==\n\n".$text;
1177 $text = $this->preSaveTransform( $text );
1179 /* Silently ignore minoredit if not allowed */
1180 $isminor = $isminor && $wgUser->isAllowed('minoredit');
1181 $now = wfTimestampNow();
1183 $dbw =& wfGetDB( DB_MASTER
);
1185 # Add the page record; stake our claim on this title!
1186 $newid = $this->insertOn( $dbw );
1188 # Save the revision text...
1189 $revision = new Revision( array(
1191 'comment' => $summary,
1192 'minor_edit' => $isminor,
1195 $revisionId = $revision->insertOn( $dbw );
1197 $this->mTitle
->resetArticleID( $newid );
1199 # Update the page record with revision data
1200 $this->updateRevisionOn( $dbw, $revision, 0 );
1202 Article
::onArticleCreate( $this->mTitle
);
1204 require_once( 'RecentChange.php' );
1205 RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, 'default',
1206 '', strlen( $text ), $revisionId );
1210 if(!$this->mTitle
->userIsWatching()) $this->doWatch();
1212 if ( $this->mTitle
->userIsWatching() ) {
1217 # The talk page isn't in the regular link tables, so we need to update manually:
1218 $talkns = $ns ^
1; # talk -> normal; normal -> talk
1219 $dbw->update( 'page',
1220 array( 'page_touched' => $dbw->timestamp($now) ),
1221 array( 'page_namespace' => $talkns,
1222 'page_title' => $ttl ),
1225 # standard deferred updates
1226 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1228 $oldid = 0; # new article
1229 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1231 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1233 $watchthis, NULL ) );
1234 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1236 $watchthis, NULL ) );
1237 wfProfileOut( $fname );
1240 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1241 $this->replaceSection( $section, $text, $summary, $edittime );
1245 * @return string Complete article text, or null if error
1247 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1248 $fname = 'Article::replaceSection';
1249 wfProfileIn( $fname );
1251 if ($section != '') {
1252 if( is_null( $edittime ) ) {
1253 $rev = Revision
::newFromTitle( $this->mTitle
);
1255 $dbw =& wfGetDB( DB_MASTER
);
1256 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1258 if( is_null( $rev ) ) {
1259 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1260 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1263 $oldtext = $rev->getText();
1265 if($section=='new') {
1266 if($summary) $subject="== {$summary} ==\n\n";
1267 $text=$oldtext."\n\n".$subject.$text;
1270 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1271 # comments to be stripped as well)
1272 $striparray=array();
1273 $parser=new Parser();
1274 $parser->mOutputType
=OT_WIKI
;
1275 $parser->mOptions
= new ParserOptions();
1276 $oldtext=$parser->strip($oldtext, $striparray, true);
1278 # now that we can be sure that no pseudo-sections are in the source,
1280 # Unfortunately we can't simply do a preg_replace because that might
1281 # replace the wrong section, so we have to use the section counter instead
1282 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?>.*?<\/h[1-6].*?>)(?!\S)/mi',
1283 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE
);
1284 $secs[$section*2]=$text."\n\n"; // replace with edited
1286 # section 0 is top (intro) section
1289 # headline of old section - we need to go through this section
1290 # to determine if there are any subsections that now need to
1291 # be erased, as the mother section has been replaced with
1292 # the text of all subsections.
1293 $headline=$secs[$section*2-1];
1294 preg_match( '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$headline,$matches);
1295 $hlevel=$matches[1];
1297 # determine headline level for wikimarkup headings
1298 if(strpos($hlevel,'=')!==false) {
1299 $hlevel=strlen($hlevel);
1302 $secs[$section*2-1]=''; // erase old headline
1305 while(!empty($secs[$count*2-1]) && !$break) {
1307 $subheadline=$secs[$count*2-1];
1309 '/^(=+).+?=+|^<h([1-6]).*?>.*?<\/h[1-6].*?>(?!\S)/mi',$subheadline,$matches);
1310 $subhlevel=$matches[1];
1311 if(strpos($subhlevel,'=')!==false) {
1312 $subhlevel=strlen($subhlevel);
1314 if($subhlevel > $hlevel) {
1315 // erase old subsections
1316 $secs[$count*2-1]='';
1319 if($subhlevel <= $hlevel) {
1327 $text=join('',$secs);
1328 # reinsert the stuff that we stripped out earlier
1329 $text=$parser->unstrip($text,$striparray);
1330 $text=$parser->unstripNoWiki($text,$striparray);
1334 wfProfileOut( $fname );
1339 * Change an existing article. Puts the previous version back into the old table, updates RC
1340 * and all necessary caches, mostly via the deferred update array.
1342 * It is possible to call this function from a command-line script, but note that you should
1343 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1345 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1346 global $wgUser, $wgDBtransactions, $wgUseSquid;
1347 global $wgPostCommitUpdateList, $wgUseFileCache;
1349 $fname = 'Article::updateArticle';
1350 wfProfileIn( $fname );
1353 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1355 &$watchthis, &$sectionanchor ) ) ) {
1356 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1357 wfProfileOut( $fname );
1361 $isminor = $minor && $wgUser->isAllowed('minoredit');
1362 $redir = (int)$this->isRedirect( $text );
1364 $text = $this->preSaveTransform( $text );
1365 $dbw =& wfGetDB( DB_MASTER
);
1366 $now = wfTimestampNow();
1368 # Update article, but only if changed.
1370 # It's important that we either rollback or complete, otherwise an attacker could
1371 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1372 # could conceivably have the same effect, especially if cur is locked for long periods.
1373 if( !$wgDBtransactions ) {
1374 $userAbort = ignore_user_abort( true );
1377 $oldtext = $this->getContent();
1378 $oldsize = strlen( $oldtext );
1379 $newsize = strlen( $text );
1383 if ( 0 != strcmp( $text, $oldtext ) ) {
1384 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1385 - (int)$this->isCountable( $oldtext );
1386 $this->mTotalAdjustment
= 0;
1387 $now = wfTimestampNow();
1389 $lastRevision = $dbw->selectField(
1390 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1392 $revision = new Revision( array(
1393 'page' => $this->getId(),
1394 'comment' => $summary,
1395 'minor_edit' => $isminor,
1399 $dbw->immediateCommit();
1401 $revisionId = $revision->insertOn( $dbw );
1404 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1407 /* Belated edit conflict! Run away!! */
1411 # Update recentchanges and purge cache and whatnot
1412 require_once( 'RecentChange.php' );
1413 $bot = (int)($wgUser->isBot() ||
$forceBot);
1414 RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1415 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1419 // Update caches outside the main transaction
1420 Article
::onArticleEdit( $this->mTitle
);
1423 // Keep the same revision ID, but do some updates on it
1424 $revisionId = $this->getRevIdFetched();
1427 if( !$wgDBtransactions ) {
1428 ignore_user_abort( $userAbort );
1433 if (!$this->mTitle
->userIsWatching()) {
1434 $dbw->immediateCommit();
1440 if ( $this->mTitle
->userIsWatching() ) {
1441 $dbw->immediateCommit();
1447 # standard deferred updates
1448 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1452 # Invalidate caches of all articles using this article as a template
1454 # Template namespace
1455 # Purge all articles linking here
1456 $titles = $this->mTitle
->getTemplateLinksTo();
1457 Title
::touchArray( $titles );
1458 if ( $wgUseSquid ) {
1459 foreach ( $titles as $title ) {
1460 $urls[] = $title->getInternalURL();
1465 if ( $wgUseSquid ) {
1466 $urls = array_merge( $urls, $this->mTitle
->getSquidURLs() );
1467 $u = new SquidUpdate( $urls );
1468 array_push( $wgPostCommitUpdateList, $u );
1472 if ( $wgUseFileCache ) {
1473 $cm = new CacheManager($this->mTitle
);
1474 @unlink
($cm->fileCacheName());
1477 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1479 wfRunHooks( 'ArticleSaveComplete',
1480 array( &$this, &$wgUser, $text,
1482 $watchthis, $sectionanchor ) );
1483 wfProfileOut( $fname );
1488 * After we've either updated or inserted the article, update
1489 * the link tables and redirect to the new page.
1491 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1494 $fname = 'Article::showArticle';
1495 wfProfileIn( $fname );
1497 # Output the redirect
1498 if( $this->isRedirect( $text ) )
1502 $wgOut->redirect( $this->mTitle
->getFullURL( $r ).$sectionanchor );
1504 wfProfileOut( $fname );
1508 * Mark this particular edit as patrolled
1510 function markpatrolled() {
1511 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1512 $wgOut->setRobotpolicy( 'noindex,follow' );
1514 # Check RC patrol config. option
1515 if( !$wgUseRCPatrol ) {
1516 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1521 if( $wgUser->isLoggedIn() ) {
1522 if( !$wgUser->isAllowed( 'patrol' ) ) {
1523 $wgOut->permissionRequired( 'patrol' );
1527 $wgOut->loginToUse();
1531 $rcid = $wgRequest->getVal( 'rcid' );
1532 if ( !is_null ( $rcid ) )
1534 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, $wgOnlySysopsCanPatrol ) ) ) {
1535 require_once( 'RecentChange.php' );
1536 RecentChange
::markPatrolled( $rcid );
1537 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, $wgOnlySysopsCanPatrol ) );
1538 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1539 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1541 $rcTitle = Title
::makeTitle( NS_SPECIAL
, 'Recentchanges' );
1542 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1546 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1551 * User-interface handler for the "watch" action
1556 global $wgUser, $wgOut;
1558 if ( $wgUser->isAnon() ) {
1559 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1562 if ( wfReadOnly() ) {
1563 $wgOut->readOnlyPage();
1567 if( $this->doWatch() ) {
1568 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1569 $wgOut->setRobotpolicy( 'noindex,follow' );
1571 $link = $this->mTitle
->getPrefixedText();
1572 $text = wfMsg( 'addedwatchtext', $link );
1573 $wgOut->addWikiText( $text );
1576 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1580 * Add this page to $wgUser's watchlist
1581 * @return bool true on successful watch operation
1583 function doWatch() {
1585 if( $wgUser->isAnon() ) {
1589 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1590 $wgUser->addWatch( $this->mTitle
);
1591 $wgUser->saveSettings();
1593 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1600 * User interface handler for the "unwatch" action.
1602 function unwatch() {
1604 global $wgUser, $wgOut;
1606 if ( $wgUser->isAnon() ) {
1607 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1610 if ( wfReadOnly() ) {
1611 $wgOut->readOnlyPage();
1615 if( $this->doUnwatch() ) {
1616 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1617 $wgOut->setRobotpolicy( 'noindex,follow' );
1619 $link = $this->mTitle
->getPrefixedText();
1620 $text = wfMsg( 'removedwatchtext', $link );
1621 $wgOut->addWikiText( $text );
1624 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1628 * Stop watching a page
1629 * @return bool true on successful unwatch
1631 function doUnwatch() {
1633 if( $wgUser->isAnon() ) {
1637 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1638 $wgUser->removeWatch( $this->mTitle
);
1639 $wgUser->saveSettings();
1641 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1648 * action=protect handler
1650 function protect() {
1651 require_once 'ProtectionForm.php';
1652 $form = new ProtectionForm( $this );
1657 * action=unprotect handler (alias)
1659 function unprotect() {
1664 * Update the article's restriction field, and leave a log entry.
1666 * @param array $limit set of restriction keys
1667 * @param string $reason
1668 * @return bool true on success
1670 function updateRestrictions( $limit = array(), $reason = '' ) {
1673 if ( !$wgUser->isAllowed( 'protect' ) ) {
1677 if( wfReadOnly() ) {
1681 $id = $this->mTitle
->getArticleID();
1686 $flat = Article
::flattenRestrictions( $limit );
1687 $protecting = ($flat != '');
1689 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser,
1690 $limit, $reason ) ) ) {
1692 $dbw =& wfGetDB( DB_MASTER
);
1693 $dbw->update( 'page',
1695 'page_touched' => $dbw->timestamp(),
1696 'page_restrictions' => $flat
1697 ), array( /* WHERE */
1699 ), 'Article::protect'
1702 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser,
1703 $limit, $reason ) );
1705 $log = new LogPage( 'protect' );
1707 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$flat]" ) );
1709 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1716 * Take an array of page restrictions and flatten it to a string
1717 * suitable for insertion into the page_restrictions field.
1718 * @param array $limit
1722 function flattenRestrictions( $limit ) {
1723 if( !is_array( $limit ) ) {
1724 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1727 foreach( $limit as $action => $restrictions ) {
1728 if( $restrictions != '' ) {
1729 $bits[] = "$action=$restrictions";
1732 return implode( ':', $bits );
1736 * UI entry point for page deletion
1739 global $wgUser, $wgOut, $wgRequest;
1740 $fname = 'Article::delete';
1741 $confirm = $wgRequest->wasPosted() &&
1742 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1743 $reason = $wgRequest->getText( 'wpReason' );
1745 # This code desperately needs to be totally rewritten
1748 if( $wgUser->isAllowed( 'delete' ) ) {
1749 if( $wgUser->isBlocked() ) {
1750 $wgOut->blockedPage();
1754 $wgOut->permissionRequired( 'delete' );
1758 if( wfReadOnly() ) {
1759 $wgOut->readOnlyPage();
1763 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1765 # Better double-check that it hasn't been deleted yet!
1766 $dbw =& wfGetDB( DB_MASTER
);
1767 $conds = $this->mTitle
->pageCond();
1768 $latest = $dbw->selectField( 'page', 'page_latest', $conds, $fname );
1769 if ( $latest === false ) {
1770 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1775 $this->doDelete( $reason );
1779 # determine whether this page has earlier revisions
1780 # and insert a warning if it does
1782 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1784 if( count( $authors ) > 1 && !$confirm ) {
1785 $skin=$wgUser->getSkin();
1786 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1787 $wgOut->addHTML( $skin->historyLink() .'</b>');
1790 # If a single user is responsible for all revisions, find out who they are
1791 if ( count( $authors ) == $maxRevisions ) {
1792 // Query bailed out, too many revisions to find out if they're all the same
1793 $authorOfAll = false;
1795 $authorOfAll = reset( $authors );
1796 foreach ( $authors as $author ) {
1797 if ( $authorOfAll != $author ) {
1798 $authorOfAll = false;
1803 # Fetch article text
1804 $rev = Revision
::newFromTitle( $this->mTitle
);
1806 if( !is_null( $rev ) ) {
1807 # if this is a mini-text, we can paste part of it into the deletion reason
1808 $text = $rev->getText();
1810 #if this is empty, an earlier revision may contain "useful" text
1813 $prev = $rev->getPrevious();
1815 $text = $prev->getText();
1820 $length = strlen( $text );
1822 # this should not happen, since it is not possible to store an empty, new
1823 # page. Let's insert a standard text in case it does, though
1824 if( $length == 0 && $reason === '' ) {
1825 $reason = wfMsgForContent( 'exblank' );
1828 if( $length < 500 && $reason === '' ) {
1829 # comment field=255, let's grep the first 150 to have some user
1832 $text = $wgContLang->truncate( $text, 150, '...' );
1834 # let's strip out newlines
1835 $text = preg_replace( "/[\n\r]/", '', $text );
1838 if( $authorOfAll === false ) {
1839 $reason = wfMsgForContent( 'excontent', $text );
1841 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1844 $reason = wfMsgForContent( 'exbeforeblank', $text );
1849 return $this->confirmDelete( '', $reason );
1853 * Get the last N authors
1854 * @param int $num Number of revisions to get
1855 * @param string $revLatest The latest rev_id, selected from the master (optional)
1856 * @return array Array of authors, duplicates not removed
1858 function getLastNAuthors( $num, $revLatest = 0 ) {
1859 $fname = 'Article::getLastNAuthors';
1860 wfProfileIn( $fname );
1862 // First try the slave
1863 // If that doesn't have the latest revision, try the master
1865 $db =& wfGetDB( DB_SLAVE
);
1867 $res = $db->select( array( 'page', 'revision' ),
1868 array( 'rev_id', 'rev_user_text' ),
1870 'page_namespace' => $this->mTitle
->getNamespace(),
1871 'page_title' => $this->mTitle
->getDBkey(),
1872 'rev_page = page_id'
1873 ), $fname, $this->getSelectOptions( array(
1874 'ORDER BY' => 'rev_timestamp DESC',
1879 wfProfileOut( $fname );
1882 $row = $db->fetchObject( $res );
1883 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1884 $db =& wfGetDB( DB_MASTER
);
1889 } while ( $continue );
1891 $authors = array( $row->rev_user_text
);
1892 while ( $row = $db->fetchObject( $res ) ) {
1893 $authors[] = $row->rev_user_text
;
1895 wfProfileOut( $fname );
1900 * Output deletion confirmation dialog
1902 function confirmDelete( $par, $reason ) {
1903 global $wgOut, $wgUser;
1905 wfDebug( "Article::confirmDelete\n" );
1907 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1908 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1909 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1910 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1912 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1914 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1915 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1916 $token = htmlspecialchars( $wgUser->editToken() );
1919 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1923 <label for='wpReason'>{$delcom}:</label>
1926 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1932 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1936 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1939 $wgOut->returnToMain( false );
1944 * Perform a deletion and output success or failure messages
1946 function doDelete( $reason ) {
1947 global $wgOut, $wgUser;
1948 $fname = 'Article::doDelete';
1949 wfDebug( $fname."\n" );
1951 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1952 if ( $this->doDeleteArticle( $reason ) ) {
1953 $deleted = $this->mTitle
->getPrefixedText();
1955 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1956 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1958 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1959 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1961 $wgOut->addWikiText( $text );
1962 $wgOut->returnToMain( false );
1963 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1965 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1971 * Back-end article deletion
1972 * Deletes the article with database consistency, writes logs, purges caches
1975 function doDeleteArticle( $reason ) {
1976 global $wgUseSquid, $wgDeferredUpdateList;
1977 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1979 $fname = 'Article::doDeleteArticle';
1980 wfDebug( $fname."\n" );
1982 $dbw =& wfGetDB( DB_MASTER
);
1983 $ns = $this->mTitle
->getNamespace();
1984 $t = $this->mTitle
->getDBkey();
1985 $id = $this->mTitle
->getArticleID();
1987 if ( $t == '' ||
$id == 0 ) {
1991 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
1992 array_push( $wgDeferredUpdateList, $u );
1994 $linksTo = $this->mTitle
->getLinksTo();
1997 if ( $wgUseSquid ) {
1999 $this->mTitle
->getInternalURL(),
2000 $this->mTitle
->getInternalURL( 'history' )
2003 $u = SquidUpdate
::newFromTitles( $linksTo, $urls );
2004 array_push( $wgPostCommitUpdateList, $u );
2008 # Client and file cache invalidation
2009 Title
::touchArray( $linksTo );
2012 // For now, shunt the revision data into the archive table.
2013 // Text is *not* removed from the text table; bulk storage
2014 // is left intact to avoid breaking block-compression or
2015 // immutable storage schemes.
2017 // For backwards compatibility, note that some older archive
2018 // table entries will have ar_text and ar_flags fields still.
2020 // In the future, we may keep revisions and mark them with
2021 // the rev_deleted field, which is reserved for this purpose.
2022 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
2024 'ar_namespace' => 'page_namespace',
2025 'ar_title' => 'page_title',
2026 'ar_comment' => 'rev_comment',
2027 'ar_user' => 'rev_user',
2028 'ar_user_text' => 'rev_user_text',
2029 'ar_timestamp' => 'rev_timestamp',
2030 'ar_minor_edit' => 'rev_minor_edit',
2031 'ar_rev_id' => 'rev_id',
2032 'ar_text_id' => 'rev_text_id',
2035 'page_id = rev_page'
2039 # Now that it's safely backed up, delete it
2040 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2041 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2043 if ($wgUseTrackbacks)
2044 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2046 # Clean up recentchanges entries...
2047 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2049 # Finally, clean up the link tables
2050 $t = $this->mTitle
->getPrefixedDBkey();
2052 Article
::onArticleDelete( $this->mTitle
);
2054 # Delete outgoing links
2055 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2056 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2057 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2058 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2059 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2062 $log = new LogPage( 'delete' );
2063 $log->addEntry( 'delete', $this->mTitle
, $reason );
2065 # Clear the cached article id so the interface doesn't act like we exist
2066 $this->mTitle
->resetArticleID( 0 );
2067 $this->mTitle
->mArticleID
= 0;
2072 * Revert a modification
2074 function rollback() {
2075 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2076 $fname = 'Article::rollback';
2078 if( $wgUser->isAllowed( 'rollback' ) ) {
2079 if( $wgUser->isBlocked() ) {
2080 $wgOut->blockedPage();
2084 $wgOut->permissionRequired( 'rollback' );
2088 if ( wfReadOnly() ) {
2089 $wgOut->readOnlyPage( $this->getContent() );
2092 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2093 array( $this->mTitle
->getPrefixedText(),
2094 $wgRequest->getVal( 'from' ) ) ) ) {
2095 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2096 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2099 $dbw =& wfGetDB( DB_MASTER
);
2101 # Enhanced rollback, marks edits rc_bot=1
2102 $bot = $wgRequest->getBool( 'bot' );
2104 # Replace all this user's current edits with the next one down
2105 $tt = $this->mTitle
->getDBKey();
2106 $n = $this->mTitle
->getNamespace();
2108 # Get the last editor, lock table exclusively
2110 $current = Revision
::newFromTitle( $this->mTitle
);
2111 if( is_null( $current ) ) {
2112 # Something wrong... no page?
2114 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2118 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2119 if( $from != $current->getUserText() ) {
2120 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2121 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2122 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2123 htmlspecialchars( $from ),
2124 htmlspecialchars( $current->getUserText() ) ) );
2125 if( $current->getComment() != '') {
2127 wfMsg( 'editcomment',
2128 htmlspecialchars( $current->getComment() ) ) );
2133 # Get the last edit not by this guy
2134 $user = intval( $current->getUser() );
2135 $user_text = $dbw->addQuotes( $current->getUserText() );
2136 $s = $dbw->selectRow( 'revision',
2137 array( 'rev_id', 'rev_timestamp' ),
2139 'rev_page' => $current->getPage(),
2140 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2143 'USE INDEX' => 'page_timestamp',
2144 'ORDER BY' => 'rev_timestamp DESC' )
2146 if( $s === false ) {
2149 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2150 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2156 # Mark all reverted edits as bot
2159 if ( $wgUseRCPatrol ) {
2160 # Mark all reverted edits as patrolled
2161 $set['rc_patrolled'] = 1;
2165 $dbw->update( 'recentchanges', $set,
2167 'rc_cur_id' => $current->getPage(),
2168 'rc_user_text' => $current->getUserText(),
2169 "rc_timestamp > '{$s->rev_timestamp}'",
2174 # Get the edit summary
2175 $target = Revision
::newFromId( $s->rev_id
);
2176 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2177 $newComment = $wgRequest->getText( 'summary', $newComment );
2180 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2181 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2182 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2184 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2185 Article
::onArticleEdit( $this->mTitle
);
2188 $wgOut->returnToMain( false );
2193 * Do standard deferred updates after page view
2196 function viewUpdates() {
2197 global $wgDeferredUpdateList;
2199 if ( 0 != $this->getID() ) {
2200 global $wgDisableCounters;
2201 if( !$wgDisableCounters ) {
2202 Article
::incViewCount( $this->getID() );
2203 $u = new SiteStatsUpdate( 1, 0, 0 );
2204 array_push( $wgDeferredUpdateList, $u );
2208 # Update newtalk / watchlist notification status
2210 $wgUser->clearNotification( $this->mTitle
);
2214 * Do standard deferred updates after page edit.
2215 * Every 1000th edit, prune the recent changes table.
2217 * @param string $text
2219 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2220 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2222 $fname = 'Article::editUpdates';
2223 wfProfileIn( $fname );
2226 $options = new ParserOptions
;
2227 $options->setTidy(true);
2228 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2230 # Save it to the parser cache
2231 $parserCache =& ParserCache
::singleton();
2232 $parserCache->save( $poutput, $this, $wgUser );
2234 # Update the links tables
2235 $u = new LinksUpdate( $this->mTitle
, $poutput );
2238 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2240 if ( 0 == mt_rand( 0, 999 ) ) {
2241 # Periodically flush old entries from the recentchanges table.
2244 $dbw =& wfGetDB( DB_MASTER
);
2245 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2246 $recentchanges = $dbw->tableName( 'recentchanges' );
2247 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2248 $dbw->query( $sql );
2252 $id = $this->getID();
2253 $title = $this->mTitle
->getPrefixedDBkey();
2254 $shortTitle = $this->mTitle
->getDBkey();
2257 wfProfileOut( $fname );
2261 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2262 array_push( $wgDeferredUpdateList, $u );
2263 $u = new SearchUpdate( $id, $title, $text );
2264 array_push( $wgDeferredUpdateList, $u );
2266 # If this is another user's talk page, update newtalk
2268 if ($this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getName()) {
2269 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2270 $other = User
::newFromName( $shortTitle );
2271 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2272 // An anonymous user
2273 $other = new User();
2274 $other->setName( $shortTitle );
2277 $other->setNewtalk( true );
2282 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2283 $wgMessageCache->replace( $shortTitle, $text );
2286 wfProfileOut( $fname );
2290 * Generate the navigation links when browsing through an article revisions
2291 * It shows the information as:
2292 * Revision as of <date>; view current revision
2293 * <- Previous version | Next Version ->
2296 * @param string $oldid Revision ID of this article revision
2298 function setOldSubtitle( $oldid=0 ) {
2299 global $wgLang, $wgOut, $wgUser;
2301 $current = ( $oldid == $this->mLatest
);
2302 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2303 $sk = $wgUser->getSkin();
2305 ?
wfMsg( 'currentrevisionlink' )
2306 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2307 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2309 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2310 : wfMsg( 'previousrevision' );
2311 $nextlink = $current
2312 ?
wfMsg( 'nextrevision' )
2313 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2314 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2315 $wgOut->setSubtitle( $r );
2319 * This function is called right before saving the wikitext,
2320 * so we can do things like signatures and links-in-context.
2322 * @param string $text
2324 function preSaveTransform( $text ) {
2325 global $wgParser, $wgUser;
2326 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2329 /* Caching functions */
2332 * checkLastModified returns true if it has taken care of all
2333 * output to the client that is necessary for this request.
2334 * (that is, it has sent a cached version of the page)
2336 function tryFileCache() {
2337 static $called = false;
2339 wfDebug( " tryFileCache() -- called twice!?\n" );
2343 if($this->isFileCacheable()) {
2344 $touched = $this->mTouched
;
2345 $cache = new CacheManager( $this->mTitle
);
2346 if($cache->isFileCacheGood( $touched )) {
2347 wfDebug( " tryFileCache() - about to load\n" );
2348 $cache->loadFromFileCache();
2351 wfDebug( " tryFileCache() - starting buffer\n" );
2352 ob_start( array(&$cache, 'saveToFileCache' ) );
2355 wfDebug( " tryFileCache() - not cacheable\n" );
2360 * Check if the page can be cached
2363 function isFileCacheable() {
2364 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2365 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2367 return $wgUseFileCache
2368 and (!$wgShowIPinHeader)
2369 and ($this->getID() != 0)
2370 and ($wgUser->isAnon())
2371 and (!$wgUser->getNewtalk())
2372 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2373 and (empty( $action ) ||
$action == 'view')
2374 and (!isset($oldid))
2376 and (!isset($redirect))
2377 and (!isset($printable))
2378 and (!$this->mRedirectedFrom
);
2382 * Loads page_touched and returns a value indicating if it should be used
2385 function checkTouched() {
2386 $fname = 'Article::checkTouched';
2387 if( !$this->mDataLoaded
) {
2388 $this->loadPageData();
2390 return !$this->mIsRedirect
;
2394 * Get the page_touched field
2396 function getTouched() {
2397 # Ensure that page data has been loaded
2398 if( !$this->mDataLoaded
) {
2399 $this->loadPageData();
2401 return $this->mTouched
;
2405 * Get the page_latest field
2407 function getLatest() {
2408 if ( !$this->mDataLoaded
) {
2409 $this->loadPageData();
2411 return $this->mLatest
;
2415 * Edit an article without doing all that other stuff
2416 * The article must already exist; link tables etc
2417 * are not updated, caches are not flushed.
2419 * @param string $text text submitted
2420 * @param string $comment comment submitted
2421 * @param bool $minor whereas it's a minor modification
2423 function quickEdit( $text, $comment = '', $minor = 0 ) {
2424 $fname = 'Article::quickEdit';
2425 wfProfileIn( $fname );
2427 $dbw =& wfGetDB( DB_MASTER
);
2429 $revision = new Revision( array(
2430 'page' => $this->getId(),
2432 'comment' => $comment,
2433 'minor_edit' => $minor ?
1 : 0,
2435 $revisionId = $revision->insertOn( $dbw );
2436 $this->updateRevisionOn( $dbw, $revision );
2439 wfProfileOut( $fname );
2443 * Used to increment the view counter
2446 * @param integer $id article id
2448 function incViewCount( $id ) {
2449 $id = intval( $id );
2450 global $wgHitcounterUpdateFreq;
2452 $dbw =& wfGetDB( DB_MASTER
);
2453 $pageTable = $dbw->tableName( 'page' );
2454 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2455 $acchitsTable = $dbw->tableName( 'acchits' );
2457 if( $wgHitcounterUpdateFreq <= 1 ){ //
2458 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2462 # Not important enough to warrant an error page in case of failure
2463 $oldignore = $dbw->ignoreErrors( true );
2465 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2467 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2468 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2469 # Most of the time (or on SQL errors), skip row count check
2470 $dbw->ignoreErrors( $oldignore );
2474 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2475 $row = $dbw->fetchObject( $res );
2476 $rown = intval( $row->n
);
2477 if( $rown >= $wgHitcounterUpdateFreq ){
2478 wfProfileIn( 'Article::incViewCount-collect' );
2479 $old_user_abort = ignore_user_abort( true );
2481 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2482 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable ENGINE=HEAP ".
2483 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2485 $dbw->query("DELETE FROM $hitcounterTable");
2486 $dbw->query('UNLOCK TABLES');
2487 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2488 'WHERE page_id = hc_id');
2489 $dbw->query("DROP TABLE $acchitsTable");
2491 ignore_user_abort( $old_user_abort );
2492 wfProfileOut( 'Article::incViewCount-collect' );
2494 $dbw->ignoreErrors( $oldignore );
2498 * The onArticle*() functions are supposed to be a kind of hooks
2499 * which should be called whenever any of the specified actions
2502 * This is a good place to put code to clear caches, for instance.
2504 * This is called on page move and undelete, as well as edit
2506 * @param $title_obj a title object
2509 function onArticleCreate($title_obj) {
2510 global $wgUseSquid, $wgPostCommitUpdateList;
2512 $title_obj->touchLinks();
2513 $titles = $title_obj->getLinksTo();
2516 if ( $wgUseSquid ) {
2517 $urls = $title_obj->getSquidURLs();
2518 foreach ( $titles as $linkTitle ) {
2519 $urls[] = $linkTitle->getInternalURL();
2521 $u = new SquidUpdate( $urls );
2522 array_push( $wgPostCommitUpdateList, $u );
2526 function onArticleDelete( $title ) {
2527 global $wgMessageCache;
2529 $title->touchLinks();
2531 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2532 $wgMessageCache->replace( $title->getDBkey(), false );
2537 * Purge caches on page update etc
2539 function onArticleEdit( $title ) {
2540 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2544 // Template namespace? Purge all articles linking here.
2545 // FIXME: When a templatelinks table arrives, use it for all includes.
2546 if ( $title->getNamespace() == NS_TEMPLATE
) {
2547 $titles = $title->getLinksTo();
2548 Title
::touchArray( $titles );
2549 if ( $wgUseSquid ) {
2550 foreach ( $titles as $link ) {
2551 $urls[] = $link->getInternalURL();
2557 if ( $wgUseSquid ) {
2558 $urls = array_merge( $urls, $title->getSquidURLs() );
2559 $u = new SquidUpdate( $urls );
2560 array_push( $wgPostCommitUpdateList, $u );
2564 if ( $wgUseFileCache ) {
2565 $cm = new CacheManager( $title );
2566 @unlink
( $cm->fileCacheName() );
2573 * Info about this page
2574 * Called for ?action=info when $wgAllowPageInfo is on.
2579 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2580 $fname = 'Article::info';
2582 if ( !$wgAllowPageInfo ) {
2583 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2587 $page = $this->mTitle
->getSubjectPage();
2589 $wgOut->setPagetitle( $page->getPrefixedText() );
2590 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2592 # first, see if the page exists at all.
2593 $exists = $page->getArticleId() != 0;
2595 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2596 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2598 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2601 $dbr =& wfGetDB( DB_SLAVE
);
2603 'wl_title' => $page->getDBkey(),
2604 'wl_namespace' => $page->getNamespace() );
2605 $numwatchers = $dbr->selectField(
2610 $this->getSelectOptions() );
2612 $pageInfo = $this->pageCountInfo( $page );
2613 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2615 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2616 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2618 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2620 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2622 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2624 $wgOut->addHTML( '</ul>' );
2630 * Return the total number of edits and number of unique editors
2631 * on a given page. If page does not exist, returns false.
2633 * @param Title $title
2637 function pageCountInfo( $title ) {
2638 $id = $title->getArticleId();
2643 $dbr =& wfGetDB( DB_SLAVE
);
2645 $rev_clause = array( 'rev_page' => $id );
2646 $fname = 'Article::pageCountInfo';
2648 $edits = $dbr->selectField(
2653 $this->getSelectOptions() );
2655 $authors = $dbr->selectField(
2657 'COUNT(DISTINCT rev_user_text)',
2660 $this->getSelectOptions() );
2662 return array( 'edits' => $edits, 'authors' => $authors );
2666 * Return a list of templates used by this article.
2667 * Uses the templatelinks table
2669 * @return array Array of Title objects
2671 function getUsedTemplates() {
2673 $id = $this->mTitle
->getArticleID();
2678 $dbr =& wfGetDB( DB_SLAVE
);
2679 $res = $dbr->select( array( 'templatelinks' ),
2680 array( 'tl_namespace', 'tl_title' ),
2681 array( 'tl_from' => $id ),
2682 'Article:getUsedTemplates' );
2683 if ( false !== $res ) {
2684 if ( $dbr->numRows( $res ) ) {
2685 while ( $row = $dbr->fetchObject( $res ) ) {
2686 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2690 $dbr->freeResult( $res );