8 * Class representing a MediaWiki article and history.
10 * See design.txt for an overview.
11 * Note: edit user interface and cache support functions have been
12 * moved to separate EditPage and HTMLFileCache classes.
22 var $mContentLoaded; //!<
25 var $mGoodAdjustment; //!<
29 var $mRedirectedFrom; //!<
30 var $mRedirectUrl; //!<
31 var $mRevIdFetched; //!<
35 var $mTotalAdjustment; //!<
42 * Constructor and clear the article
43 * @param $title Reference to a Title object.
44 * @param $oldId Integer revision ID, null to fetch from request, zero for current
46 function Article( &$title, $oldId = null ) {
47 $this->mTitle
=& $title;
48 $this->mOldId
= $oldId;
53 * Tell the page view functions that this view was redirected
54 * from another page on the wiki.
55 * @param $from Title object.
57 function setRedirectedFrom( $from ) {
58 $this->mRedirectedFrom
= $from;
62 * @return mixed false, Title of in-wiki target, or string with URL
64 function followRedirect() {
65 $text = $this->getContent();
66 $rt = Title
::newFromRedirect( $text );
68 # process if title object is valid and not special:userlogout
70 if( $rt->getInterwiki() != '' ) {
71 if( $rt->isLocal() ) {
72 // Offsite wikis need an HTTP redirect.
74 // This can be hard to reverse and may produce loops,
75 // so they may be disabled in the site configuration.
77 $source = $this->mTitle
->getFullURL( 'redirect=no' );
78 return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
81 if( $rt->getNamespace() == NS_SPECIAL
) {
82 // Gotta hand redirects to special pages differently:
83 // Fill the HTTP response "Location" header and ignore
84 // the rest of the page we're on.
86 // This can be hard to reverse, so they may be disabled.
88 if( $rt->isSpecial( 'Userlogout' ) ) {
91 return $rt->getFullURL();
98 // No or invalid redirect
103 * get the title object of the article
105 function getTitle() {
106 return $this->mTitle
;
114 $this->mDataLoaded
= false;
115 $this->mContentLoaded
= false;
117 $this->mCurID
= $this->mUser
= $this->mCounter
= -1; # Not loaded
118 $this->mRedirectedFrom
= null; # Title object if set
120 $this->mTimestamp
= $this->mComment
= '';
121 $this->mGoodAdjustment
= $this->mTotalAdjustment
= 0;
122 $this->mTouched
= '19700101000000';
123 $this->mForUpdate
= false;
124 $this->mIsRedirect
= false;
125 $this->mRevIdFetched
= 0;
126 $this->mRedirectUrl
= false;
127 $this->mLatest
= false;
131 * Note that getContent/loadContent do not follow redirects anymore.
132 * If you need to fetch redirectable content easily, try
133 * the shortcut in Article::followContent()
135 * @todo There are still side-effects in this!
136 * In general, you should use the Revision class, not Article,
137 * to fetch text for purposes other than page views.
139 * @return Return the text of this revision
141 function getContent() {
142 global $wgRequest, $wgUser, $wgOut;
144 wfProfileIn( __METHOD__
);
146 if ( 0 == $this->getID() ) {
147 wfProfileOut( __METHOD__
);
148 $wgOut->setRobotpolicy( 'noindex,nofollow' );
150 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
151 $ret = wfMsgWeirdKey ( $this->mTitle
->getText() ) ;
153 $ret = wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' );
156 return "<div class='noarticletext'>$ret</div>";
158 $this->loadContent();
159 wfProfileOut( __METHOD__
);
160 return $this->mContent
;
165 * This function returns the text of a section, specified by a number ($section).
166 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
167 * the first section before any such heading (section 0).
169 * If a section contains subsections, these are also returned.
171 * @param $text String: text to look in
172 * @param $section Integer: section number
173 * @return string text of the requested section
176 function getSection($text,$section) {
178 return $wgParser->getSection( $text, $section );
182 * @return int The oldid of the article that is to be shown, 0 for the
185 function getOldID() {
186 if ( is_null( $this->mOldId
) ) {
187 $this->mOldId
= $this->getOldIDFromRequest();
189 return $this->mOldId
;
193 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
195 * @return int The old id for the request
197 function getOldIDFromRequest() {
199 $this->mRedirectUrl
= false;
200 $oldid = $wgRequest->getVal( 'oldid' );
201 if ( isset( $oldid ) ) {
202 $oldid = intval( $oldid );
203 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
204 $nextid = $this->mTitle
->getNextRevisionID( $oldid );
208 $this->mRedirectUrl
= $this->mTitle
->getFullURL( 'redirect=no' );
210 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
211 $previd = $this->mTitle
->getPreviousRevisionID( $oldid );
229 * Load the revision (including text) into this object
231 function loadContent() {
232 if ( $this->mContentLoaded
) return;
235 $oldid = $this->getOldID();
237 # Pre-fill content with error message so that if something
238 # fails we'll have something telling us what we intended.
240 $t = $this->mTitle
->getPrefixedText();
242 $this->mOldId
= $oldid;
243 $this->fetchContent( $oldid );
248 * Fetch a page record with the given conditions
249 * @param Database $dbr
250 * @param array $conditions
253 function pageData( &$dbr, $conditions ) {
266 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
267 $row = $dbr->selectRow( 'page',
270 'Article::pageData' );
271 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
276 * @param Database $dbr
277 * @param Title $title
279 function pageDataFromTitle( &$dbr, $title ) {
280 return $this->pageData( $dbr, array(
281 'page_namespace' => $title->getNamespace(),
282 'page_title' => $title->getDBkey() ) );
286 * @param Database $dbr
289 function pageDataFromId( &$dbr, $id ) {
290 return $this->pageData( $dbr, array( 'page_id' => $id ) );
294 * Set the general counter, title etc data loaded from
297 * @param object $data
300 function loadPageData( $data = 'fromdb' ) {
301 if ( $data === 'fromdb' ) {
302 $dbr =& $this->getDB();
303 $data = $this->pageDataFromId( $dbr, $this->getId() );
306 $lc =& LinkCache
::singleton();
308 $lc->addGoodLinkObj( $data->page_id
, $this->mTitle
);
310 $this->mTitle
->mArticleID
= $data->page_id
;
311 $this->mTitle
->loadRestrictions( $data->page_restrictions
);
312 $this->mTitle
->mRestrictionsLoaded
= true;
314 $this->mCounter
= $data->page_counter
;
315 $this->mTouched
= wfTimestamp( TS_MW
, $data->page_touched
);
316 $this->mIsRedirect
= $data->page_is_redirect
;
317 $this->mLatest
= $data->page_latest
;
319 if ( is_object( $this->mTitle
) ) {
320 $lc->addBadLinkObj( $this->mTitle
);
322 $this->mTitle
->mArticleID
= 0;
325 $this->mDataLoaded
= true;
329 * Get text of an article from database
330 * Does *NOT* follow redirects.
331 * @param int $oldid 0 for whatever the latest revision is
334 function fetchContent( $oldid = 0 ) {
335 if ( $this->mContentLoaded
) {
336 return $this->mContent
;
339 $dbr =& $this->getDB();
341 # Pre-fill content with error message so that if something
342 # fails we'll have something telling us what we intended.
343 $t = $this->mTitle
->getPrefixedText();
345 $t .= ',oldid='.$oldid;
347 $this->mContent
= wfMsg( 'missingarticle', $t ) ;
350 $revision = Revision
::newFromId( $oldid );
351 if( is_null( $revision ) ) {
352 wfDebug( __METHOD__
." failed to retrieve specified revision, id $oldid\n" );
355 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
357 wfDebug( __METHOD__
." failed to get page data linked to revision id $oldid\n" );
360 $this->mTitle
= Title
::makeTitle( $data->page_namespace
, $data->page_title
);
361 $this->loadPageData( $data );
363 if( !$this->mDataLoaded
) {
364 $data = $this->pageDataFromTitle( $dbr, $this->mTitle
);
366 wfDebug( __METHOD__
." failed to find page data for title " . $this->mTitle
->getPrefixedText() . "\n" );
369 $this->loadPageData( $data );
371 $revision = Revision
::newFromId( $this->mLatest
);
372 if( is_null( $revision ) ) {
373 wfDebug( __METHOD__
." failed to retrieve current page, rev_id {$data->page_latest}\n" );
378 // FIXME: Horrible, horrible! This content-loading interface just plain sucks.
379 // We should instead work with the Revision object when we need it...
380 $this->mContent
= $revision->userCan( Revision
::DELETED_TEXT
) ?
$revision->getRawText() : "";
381 //$this->mContent = $revision->getText();
383 $this->mUser
= $revision->getUser();
384 $this->mUserText
= $revision->getUserText();
385 $this->mComment
= $revision->getComment();
386 $this->mTimestamp
= wfTimestamp( TS_MW
, $revision->getTimestamp() );
388 $this->mRevIdFetched
= $revision->getID();
389 $this->mContentLoaded
= true;
390 $this->mRevision
=& $revision;
392 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent
) ) ;
394 return $this->mContent
;
398 * Read/write accessor to select FOR UPDATE
400 * @param $x Mixed: FIXME
402 function forUpdate( $x = NULL ) {
403 return wfSetVar( $this->mForUpdate
, $x );
407 * Get the database which should be used for reads
412 $ret =& wfGetDB( DB_MASTER
);
417 * Get options for all SELECT statements
419 * @param $options Array: an optional options array which'll be appended to
421 * @return Array: options
423 function getSelectOptions( $options = '' ) {
424 if ( $this->mForUpdate
) {
425 if ( is_array( $options ) ) {
426 $options[] = 'FOR UPDATE';
428 $options = 'FOR UPDATE';
435 * @return int Page ID
438 if( $this->mTitle
) {
439 return $this->mTitle
->getArticleID();
446 * @return bool Whether or not the page exists in the database
449 return $this->getId() != 0;
453 * @return int The view count for the page
455 function getCount() {
456 if ( -1 == $this->mCounter
) {
457 $id = $this->getID();
461 $dbr =& wfGetDB( DB_SLAVE
);
462 $this->mCounter
= $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
463 'Article::getCount', $this->getSelectOptions() );
466 return $this->mCounter
;
470 * Determine whether a page would be suitable for being counted as an
471 * article in the site_stats table based on the title & its content
473 * @param $text String: text to analyze
476 function isCountable( $text ) {
477 global $wgUseCommaCount, $wgContentNamespaces;
479 $token = $wgUseCommaCount ?
',' : '[[';
481 array_search( $this->mTitle
->getNamespace(), $wgContentNamespaces ) !== false
482 && ! $this->isRedirect( $text )
483 && in_string( $token, $text );
487 * Tests if the article text represents a redirect
489 * @param $text String: FIXME
492 function isRedirect( $text = false ) {
493 if ( $text === false ) {
494 $this->loadContent();
495 $titleObj = Title
::newFromRedirect( $this->fetchContent() );
497 $titleObj = Title
::newFromRedirect( $text );
499 return $titleObj !== NULL;
503 * Returns true if the currently-referenced revision is the current edit
504 * to this page (and it exists).
507 function isCurrent() {
508 return $this->exists() &&
509 isset( $this->mRevision
) &&
510 $this->mRevision
->isCurrent();
514 * Loads everything except the text
515 * This isn't necessary for all uses, so it's only done if needed.
518 function loadLastEdit() {
519 if ( -1 != $this->mUser
)
522 # New or non-existent articles have no user information
523 $id = $this->getID();
524 if ( 0 == $id ) return;
526 $this->mLastRevision
= Revision
::loadFromPageId( $this->getDB(), $id );
527 if( !is_null( $this->mLastRevision
) ) {
528 $this->mUser
= $this->mLastRevision
->getUser();
529 $this->mUserText
= $this->mLastRevision
->getUserText();
530 $this->mTimestamp
= $this->mLastRevision
->getTimestamp();
531 $this->mComment
= $this->mLastRevision
->getComment();
532 $this->mMinorEdit
= $this->mLastRevision
->isMinor();
533 $this->mRevIdFetched
= $this->mLastRevision
->getID();
537 function getTimestamp() {
538 // Check if the field has been filled by ParserCache::get()
539 if ( !$this->mTimestamp
) {
540 $this->loadLastEdit();
542 return wfTimestamp(TS_MW
, $this->mTimestamp
);
546 $this->loadLastEdit();
550 function getUserText() {
551 $this->loadLastEdit();
552 return $this->mUserText
;
555 function getComment() {
556 $this->loadLastEdit();
557 return $this->mComment
;
560 function getMinorEdit() {
561 $this->loadLastEdit();
562 return $this->mMinorEdit
;
565 function getRevIdFetched() {
566 $this->loadLastEdit();
567 return $this->mRevIdFetched
;
571 * @todo Document, fixme $offset never used.
572 * @param $limit Integer: default 0.
573 * @param $offset Integer: default 0.
575 function getContributors($limit = 0, $offset = 0) {
576 # XXX: this is expensive; cache this info somewhere.
578 $title = $this->mTitle
;
580 $dbr =& wfGetDB( DB_SLAVE
);
581 $revTable = $dbr->tableName( 'revision' );
582 $userTable = $dbr->tableName( 'user' );
583 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
584 $ns = $title->getNamespace();
585 $user = $this->getUser();
586 $pageId = $this->getId();
588 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
589 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
590 WHERE rev_page = $pageId
591 AND rev_user != $user
592 GROUP BY rev_user, rev_user_text, user_real_name
593 ORDER BY timestamp DESC";
595 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
596 $sql .= ' '. $this->getSelectOptions();
598 $res = $dbr->query($sql, __METHOD__
);
600 while ( $line = $dbr->fetchObject( $res ) ) {
601 $contribs[] = array($line->rev_user
, $line->rev_user_text
, $line->user_real_name
);
604 $dbr->freeResult($res);
609 * This is the default action of the script: just view the page of
613 global $wgUser, $wgOut, $wgRequest, $wgContLang;
614 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
615 global $wgUseTrackbacks, $wgNamespaceRobotPolicies;
616 $sk = $wgUser->getSkin();
618 wfProfileIn( __METHOD__
);
620 $parserCache =& ParserCache
::singleton();
621 $ns = $this->mTitle
->getNamespace(); # shortcut
623 # Get variables from query string
624 $oldid = $this->getOldID();
626 # getOldID may want us to redirect somewhere else
627 if ( $this->mRedirectUrl
) {
628 $wgOut->redirect( $this->mRedirectUrl
);
629 wfProfileOut( __METHOD__
);
633 $diff = $wgRequest->getVal( 'diff' );
634 $rcid = $wgRequest->getVal( 'rcid' );
635 $rdfrom = $wgRequest->getVal( 'rdfrom' );
637 $wgOut->setArticleFlag( true );
638 if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
639 $policy = $wgNamespaceRobotPolicies[$ns];
641 $policy = 'index,follow';
643 $wgOut->setRobotpolicy( $policy );
645 # If we got diff and oldid in the query, we want to see a
646 # diff page instead of the article.
648 if ( !is_null( $diff ) ) {
649 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
651 $de = new DifferenceEngine( $this->mTitle
, $oldid, $diff, $rcid );
652 // DifferenceEngine directly fetched the revision:
653 $this->mRevIdFetched
= $de->mNewid
;
656 // Needed to get the page's current revision
657 $this->loadPageData();
658 if( $diff == 0 ||
$diff == $this->mLatest
) {
659 # Run view updates for current revision only
660 $this->viewUpdates();
662 wfProfileOut( __METHOD__
);
666 if ( empty( $oldid ) && $this->checkTouched() ) {
667 $wgOut->setETag($parserCache->getETag($this, $wgUser));
669 if( $wgOut->checkLastModified( $this->mTouched
) ){
670 wfProfileOut( __METHOD__
);
672 } else if ( $this->tryFileCache() ) {
673 # tell wgOut that output is taken care of
675 $this->viewUpdates();
676 wfProfileOut( __METHOD__
);
681 # Should the parser cache be used?
682 $pcache = $wgEnableParserCache &&
683 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
686 wfDebug( 'Article::view using parser cache: ' . ($pcache ?
'yes' : 'no' ) . "\n" );
687 if ( $wgUser->getOption( 'stubthreshold' ) ) {
688 wfIncrStats( 'pcache_miss_stub' );
691 $wasRedirected = false;
692 if ( isset( $this->mRedirectedFrom
) ) {
693 // This is an internally redirected page view.
694 // We'll need a backlink to the source page for navigation.
695 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
696 $sk = $wgUser->getSkin();
697 $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom
, '', 'redirect=no' );
698 $s = wfMsg( 'redirectedfrom', $redir );
699 $wgOut->setSubtitle( $s );
700 $wasRedirected = true;
702 } elseif ( !empty( $rdfrom ) ) {
703 // This is an externally redirected view, from some other wiki.
704 // If it was reported from a trusted site, supply a backlink.
705 global $wgRedirectSources;
706 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
707 $sk = $wgUser->getSkin();
708 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
709 $s = wfMsg( 'redirectedfrom', $redir );
710 $wgOut->setSubtitle( $s );
711 $wasRedirected = true;
717 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
718 wfRunHooks( 'ArticleViewHeader', array( &$this ) );
722 if ( !$outputDone ) {
723 $text = $this->getContent();
724 if ( $text === false ) {
725 # Failed to load, replace text with error message
726 $t = $this->mTitle
->getPrefixedText();
728 $t .= ',oldid='.$oldid;
729 $text = wfMsg( 'missingarticle', $t );
731 $text = wfMsg( 'noarticletext', $t );
735 # Another whitelist check in case oldid is altering the title
736 if ( !$this->mTitle
->userCanRead() ) {
737 $wgOut->loginToUse();
742 # We're looking at an old revision
744 if ( !empty( $oldid ) ) {
745 $wgOut->setRobotpolicy( 'noindex,nofollow' );
746 if( is_null( $this->mRevision
) ) {
747 // FIXME: This would be a nice place to load the 'no such page' text.
749 $this->setOldSubtitle( isset($this->mOldId
) ?
$this->mOldId
: $oldid );
750 if( $this->mRevision
->isDeleted( Revision
::DELETED_TEXT
) ) {
751 if( !$this->mRevision
->userCan( Revision
::DELETED_TEXT
) ) {
752 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
753 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
756 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
757 // and we are allowed to see...
766 * @fixme: this hook doesn't work most of the time, as it doesn't
767 * trigger when the parser cache is used.
769 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
770 $wgOut->setRevisionId( $this->getRevIdFetched() );
771 # wrap user css and user js in pre and don't parse
772 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
775 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle
->getDBkey())
777 $wgOut->addWikiText( wfMsg('clearyourcache'));
778 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent
)."\n</pre>" );
779 } else if ( $rt = Title
::newFromRedirect( $text ) ) {
781 $imageDir = $wgContLang->isRTL() ?
'rtl' : 'ltr';
782 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
783 # Don't overwrite the subtitle if this was an old revision
784 if( !$wasRedirected && $this->isCurrent() ) {
785 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
787 $targetUrl = $rt->escapeLocalURL();
788 #Â fixme unused $titleText :
789 $titleText = htmlspecialchars( $rt->getPrefixedText() );
790 $link = $sk->makeLinkObj( $rt );
792 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
793 '<span class="redirectText">'.$link.'</span>' );
795 $parseout = $wgParser->parse($text, $this->mTitle
, ParserOptions
::newFromUser($wgUser));
796 $wgOut->addParserOutputNoText( $parseout );
797 } else if ( $pcache ) {
798 # Display content and save to parser cache
799 $wgOut->addPrimaryWikiText( $text, $this );
801 # Display content, don't attempt to save to parser cache
802 # Don't show section-edit links on old revisions... this way lies madness.
803 if( !$this->isCurrent() ) {
804 $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
806 # Display content and don't save to parser cache
807 $wgOut->addPrimaryWikiText( $text, $this, false );
809 if( !$this->isCurrent() ) {
810 $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
814 /* title may have been set from the cache */
815 $t = $wgOut->getPageTitle();
817 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
820 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
821 if( $ns == NS_USER_TALK
&&
822 User
::isIP( $this->mTitle
->getText() ) ) {
823 $wgOut->addWikiText( wfMsg('anontalkpagetext') );
826 # If we have been passed an &rcid= parameter, we want to give the user a
827 # chance to mark this new article as patrolled.
828 if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
830 "<div class='patrollink'>" .
831 wfMsg ( 'markaspatrolledlink',
832 $sk->makeKnownLinkObj( $this->mTitle
, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
839 if ($wgUseTrackbacks)
840 $this->addTrackbacks();
842 $this->viewUpdates();
843 wfProfileOut( __METHOD__
);
846 function addTrackbacks() {
847 global $wgOut, $wgUser;
849 $dbr =& wfGetDB(DB_SLAVE
);
851 /* FROM */ 'trackbacks',
852 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
853 /* WHERE */ array('tb_page' => $this->getID())
856 if (!$dbr->numrows($tbs))
860 while ($o = $dbr->fetchObject($tbs)) {
862 if ($wgUser->isAllowed( 'trackback' )) {
863 $delurl = $this->mTitle
->getFullURL("action=deletetrackback&tbid="
864 . $o->tb_id
. "&token=" . $wgUser->editToken());
865 $rmvtxt = wfMsg('trackbackremove', $delurl);
867 $tbtext .= wfMsg(strlen($o->tb_ex
) ?
'trackbackexcerpt' : 'trackback',
874 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
877 function deletetrackback() {
878 global $wgUser, $wgRequest, $wgOut, $wgTitle;
880 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
881 $wgOut->addWikitext(wfMsg('sessionfailure'));
885 if ((!$wgUser->isAllowed('delete'))) {
886 $wgOut->permissionRequired( 'delete' );
891 $wgOut->readOnlyPage();
895 $db =& wfGetDB(DB_MASTER
);
896 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
897 $wgTitle->invalidateCache();
898 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
904 $wgOut->setArticleBodyOnly(true);
909 * Handle action=purge
912 global $wgUser, $wgRequest, $wgOut;
914 if ( $wgUser->isLoggedIn() ||
$wgRequest->wasPosted() ) {
915 if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
919 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
920 $action = $this->mTitle
->escapeLocalURL( 'action=purge' );
921 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
922 $msg = str_replace( '$1',
923 "<form method=\"post\" action=\"$action\">\n" .
924 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
927 $wgOut->setPageTitle( $this->mTitle
->getPrefixedText() );
928 $wgOut->setRobotpolicy( 'noindex,nofollow' );
929 $wgOut->addHTML( $msg );
934 * Perform the actions of a page purging
938 // Invalidate the cache
939 $this->mTitle
->invalidateCache();
942 // Commit the transaction before the purge is sent
943 $dbw = wfGetDB( DB_MASTER
);
944 $dbw->immediateCommit();
947 $update = SquidUpdate
::newSimplePurge( $this->mTitle
);
954 * Insert a new empty page record for this article.
955 * This *must* be followed up by creating a revision
956 * and running $this->updateToLatest( $rev_id );
957 * or else the record will be left in a funky state.
958 * Best if all done inside a transaction.
960 * @param Database $dbw
961 * @param string $restrictions
962 * @return int The newly created page_id key
965 function insertOn( &$dbw, $restrictions = '' ) {
966 wfProfileIn( __METHOD__
);
968 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
969 $dbw->insert( 'page', array(
970 'page_id' => $page_id,
971 'page_namespace' => $this->mTitle
->getNamespace(),
972 'page_title' => $this->mTitle
->getDBkey(),
974 'page_restrictions' => $restrictions,
975 'page_is_redirect' => 0, # Will set this shortly...
977 'page_random' => wfRandom(),
978 'page_touched' => $dbw->timestamp(),
979 'page_latest' => 0, # Fill this in shortly...
980 'page_len' => 0, # Fill this in shortly...
982 $newid = $dbw->insertId();
984 $this->mTitle
->resetArticleId( $newid );
986 wfProfileOut( __METHOD__
);
991 * Update the page record to point to a newly saved revision.
993 * @param Database $dbw
994 * @param Revision $revision For ID number, and text used to set
995 length and redirect status fields
996 * @param int $lastRevision If given, will not overwrite the page field
997 * when different from the currently set value.
998 * Giving 0 indicates the new page flag should
1000 * @param bool $lastRevIsRedirect If given, will optimize adding and
1001 * removing rows in redirect table.
1002 * @return bool true on success, false on failure
1005 function updateRevisionOn( &$dbw, $revision, $lastRevision = null, $lastRevIsRedirect = null ) {
1006 wfProfileIn( __METHOD__
);
1008 $text = $revision->getText();
1009 $rt = Title
::newFromRedirect( $text );
1011 $conditions = array( 'page_id' => $this->getId() );
1012 if( !is_null( $lastRevision ) ) {
1013 # An extra check against threads stepping on each other
1014 $conditions['page_latest'] = $lastRevision;
1017 $dbw->update( 'page',
1019 'page_latest' => $revision->getId(),
1020 'page_touched' => $dbw->timestamp(),
1021 'page_is_new' => ($lastRevision === 0) ?
1 : 0,
1022 'page_is_redirect' => $rt !== NULL ?
1 : 0,
1023 'page_len' => strlen( $text ),
1028 $result = $dbw->affectedRows() != 0;
1031 // FIXME: Should the result from updateRedirectOn() be returned instead?
1032 $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
1035 wfProfileOut( __METHOD__
);
1040 * Add row to the redirect table if this is a redirect, remove otherwise.
1042 * @param Database $dbw
1043 * @param $redirectTitle a title object pointing to the redirect target,
1044 * or NULL if this is not a redirect
1045 * @param bool $lastRevIsRedirect If given, will optimize adding and
1046 * removing rows in redirect table.
1047 * @return bool true on success, false on failure
1050 function updateRedirectOn( &$dbw, $redirectTitle, $lastRevIsRedirect = null ) {
1052 // Always update redirects (target link might have changed)
1053 // Update/Insert if we don't know if the last revision was a redirect or not
1054 // Delete if changing from redirect to non-redirect
1055 $isRedirect = !is_null($redirectTitle);
1056 if ($isRedirect ||
is_null($lastRevIsRedirect) ||
$lastRevIsRedirect !== $isRedirect) {
1058 wfProfileIn( __METHOD__
);
1062 // This title is a redirect, Add/Update row in the redirect table
1063 $set = array( /* SET */
1064 'rd_namespace' => $redirectTitle->getNamespace(),
1065 'rd_title' => $redirectTitle->getDBkey(),
1066 'rd_from' => $this->getId(),
1069 $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__
);
1071 // This is not a redirect, remove row from redirect table
1072 $where = array( 'rd_from' => $this->getId() );
1073 $dbw->delete( 'redirect', $where, __METHOD__
);
1076 wfProfileOut( __METHOD__
);
1077 return ( $dbw->affectedRows() != 0 );
1084 * If the given revision is newer than the currently set page_latest,
1085 * update the page record. Otherwise, do nothing.
1087 * @param Database $dbw
1088 * @param Revision $revision
1090 function updateIfNewerOn( &$dbw, $revision ) {
1091 wfProfileIn( __METHOD__
);
1093 $row = $dbw->selectRow(
1094 array( 'revision', 'page' ),
1095 array( 'rev_id', 'rev_timestamp', 'page_is_redirect' ),
1097 'page_id' => $this->getId(),
1098 'page_latest=rev_id' ),
1101 if( wfTimestamp(TS_MW
, $row->rev_timestamp
) >= $revision->getTimestamp() ) {
1102 wfProfileOut( __METHOD__
);
1105 $prev = $row->rev_id
;
1106 $lastRevIsRedirect = (bool)$row->page_is_redirect
;
1108 # No or missing previous revision; mark the page as new
1110 $lastRevIsRedirect = null;
1113 $ret = $this->updateRevisionOn( $dbw, $revision, $prev, $lastRevIsRedirect );
1114 wfProfileOut( __METHOD__
);
1119 * @return string Complete article text, or null if error
1121 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1122 wfProfileIn( __METHOD__
);
1124 if( $section == '' ) {
1125 // Whole-page edit; let the text through unmolested.
1127 if( is_null( $edittime ) ) {
1128 $rev = Revision
::newFromTitle( $this->mTitle
);
1130 $dbw =& wfGetDB( DB_MASTER
);
1131 $rev = Revision
::loadFromTimestamp( $dbw, $this->mTitle
, $edittime );
1133 if( is_null( $rev ) ) {
1134 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1135 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1138 $oldtext = $rev->getText();
1140 if($section=='new') {
1141 if($summary) $subject="== {$summary} ==\n\n";
1142 $text=$oldtext."\n\n".$subject.$text;
1145 $text = $wgParser->replaceSection( $oldtext, $section, $text );
1149 wfProfileOut( __METHOD__
);
1154 * @deprecated use Article::doEdit()
1156 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1157 $flags = EDIT_NEW | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1158 ( $isminor ? EDIT_MINOR
: 0 ) |
1159 ( $suppressRC ? EDIT_SUPPRESS_RC
: 0 );
1161 # If this is a comment, add the summary as headline
1162 if ( $comment && $summary != "" ) {
1163 $text = "== {$summary} ==\n\n".$text;
1166 $this->doEdit( $text, $summary, $flags );
1168 $dbw =& wfGetDB( DB_MASTER
);
1170 if (!$this->mTitle
->userIsWatching()) {
1176 if ( $this->mTitle
->userIsWatching() ) {
1182 $this->doRedirect( $this->isRedirect( $text ) );
1186 * @deprecated use Article::doEdit()
1188 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1189 $flags = EDIT_UPDATE | EDIT_DEFER_UPDATES | EDIT_AUTOSUMMARY |
1190 ( $minor ? EDIT_MINOR
: 0 ) |
1191 ( $forceBot ? EDIT_FORCE_BOT
: 0 );
1193 $good = $this->doEdit( $text, $summary, $flags );
1195 $dbw =& wfGetDB( DB_MASTER
);
1197 if (!$this->mTitle
->userIsWatching()) {
1203 if ( $this->mTitle
->userIsWatching() ) {
1210 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1218 * Change an existing article or create a new article. Updates RC and all necessary caches,
1219 * optionally via the deferred update array.
1221 * $wgUser must be set before calling this function.
1223 * @param string $text New text
1224 * @param string $summary Edit summary
1225 * @param integer $flags bitfield:
1227 * Article is known or assumed to be non-existent, create a new one
1229 * Article is known or assumed to be pre-existing, update it
1231 * Mark this edit minor, if the user is allowed to do so
1233 * Do not log the change in recentchanges
1235 * Mark the edit a "bot" edit regardless of user rights
1236 * EDIT_DEFER_UPDATES
1237 * Defer some of the updates until the end of index.php
1239 * Fill in blank summaries with generated text where possible
1241 * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
1242 * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
1243 * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
1244 * to be thrown from the Database. These two conditions are also possible with auto-detection due
1245 * to MediaWiki's performance-optimised locking strategy.
1247 * @return bool success
1249 function doEdit( $text, $summary, $flags = 0 ) {
1250 global $wgUser, $wgDBtransactions;
1252 wfProfileIn( __METHOD__
);
1255 if ( !($flags & EDIT_NEW
) && !($flags & EDIT_UPDATE
) ) {
1256 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
1258 $flags |
= EDIT_UPDATE
;
1264 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1265 &$summary, $flags & EDIT_MINOR
,
1266 null, null, &$flags ) ) )
1268 wfDebug( __METHOD__
. ": ArticleSave hook aborted save!\n" );
1269 wfProfileOut( __METHOD__
);
1273 # Silently ignore EDIT_MINOR if not allowed
1274 $isminor = ( $flags & EDIT_MINOR
) && $wgUser->isAllowed('minoredit');
1275 $bot = $wgUser->isAllowed( 'bot' ) ||
( $flags & EDIT_FORCE_BOT
);
1277 # If no edit comment was given when creating a new page, and what's being
1278 # created is a redirect, be smart and fill in a neat auto-comment
1279 if ( $flags & EDIT_AUTOSUMMARY
&& $summary == '' ) {
1280 $rt = Title
::newFromRedirect( $text );
1281 if( is_object( $rt ) )
1282 $summary = wfMsgForContent( 'autoredircomment', $rt->getPrefixedText() );
1285 $text = $this->preSaveTransform( $text );
1287 $dbw =& wfGetDB( DB_MASTER
);
1288 $now = wfTimestampNow();
1290 if ( $flags & EDIT_UPDATE
) {
1291 # Update article, but only if changed.
1293 # Make sure the revision is either completely inserted or not inserted at all
1294 if( !$wgDBtransactions ) {
1295 $userAbort = ignore_user_abort( true );
1298 $oldtext = $this->getContent();
1299 $oldsize = strlen( $oldtext );
1300 $newsize = strlen( $text );
1304 if ( 0 != strcmp( $text, $oldtext ) ) {
1305 $this->mGoodAdjustment
= (int)$this->isCountable( $text )
1306 - (int)$this->isCountable( $oldtext );
1307 $this->mTotalAdjustment
= 0;
1309 $lastRevision = $dbw->selectField(
1310 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1312 if ( !$lastRevision ) {
1313 # Article gone missing
1314 wfDebug( __METHOD__
.": EDIT_UPDATE specified but article doesn't exist\n" );
1315 wfProfileOut( __METHOD__
);
1319 if ($flags & EDIT_AUTOSUMMARY
&& $summary == '') {
1320 #If they're blanking an article, note it in the summary.
1321 if ($oldtext!='' && $text=='') {
1322 $summary = wfMsgForContent('autosumm-blank');
1323 } elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) { #Removing more than 90% of the article
1325 $truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
1326 $summary = wfMsgForContent('autosumm-replace', $truncatedtext);
1330 $revision = new Revision( array(
1331 'page' => $this->getId(),
1332 'comment' => $summary,
1333 'minor_edit' => $isminor,
1338 $revisionId = $revision->insertOn( $dbw );
1341 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1344 /* Belated edit conflict! Run away!! */
1348 # Update recentchanges
1349 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1350 $rcid = RecentChange
::notifyEdit( $now, $this->mTitle
, $isminor, $wgUser, $summary,
1351 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1354 # Mark as patrolled if the user can do so and has it set in their options
1355 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1356 RecentChange
::markPatrolled( $rcid );
1362 // Keep the same revision ID, but do some updates on it
1363 $revisionId = $this->getRevIdFetched();
1364 // Update page_touched, this is usually implicit in the page update
1365 // Other cache updates are done in onArticleEdit()
1366 $this->mTitle
->invalidateCache();
1369 if( !$wgDBtransactions ) {
1370 ignore_user_abort( $userAbort );
1374 # Invalidate cache of this article and all pages using this article
1375 # as a template. Partly deferred.
1376 Article
::onArticleEdit( $this->mTitle
);
1378 # Update links tables, site stats, etc.
1379 $changed = ( strcmp( $oldtext, $text ) != 0 );
1380 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
1383 # Create new article
1385 # Set statistics members
1386 # We work out if it's countable after PST to avoid counter drift
1387 # when articles are created with {{subst:}}
1388 $this->mGoodAdjustment
= (int)$this->isCountable( $text );
1389 $this->mTotalAdjustment
= 1;
1393 # Add the page record; stake our claim on this title!
1394 # This will fail with a database query exception if the article already exists
1395 $newid = $this->insertOn( $dbw );
1397 # Save the revision text...
1398 $revision = new Revision( array(
1400 'comment' => $summary,
1401 'minor_edit' => $isminor,
1404 $revisionId = $revision->insertOn( $dbw );
1406 $this->mTitle
->resetArticleID( $newid );
1408 # Update the page record with revision data
1409 $this->updateRevisionOn( $dbw, $revision, 0 );
1411 if( !( $flags & EDIT_SUPPRESS_RC
) ) {
1412 $rcid = RecentChange
::notifyNew( $now, $this->mTitle
, $isminor, $wgUser, $summary, $bot,
1413 '', strlen( $text ), $revisionId );
1414 # Mark as patrolled if the user can and has the option set
1415 if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
1416 RecentChange
::markPatrolled( $rcid );
1421 # Update links, etc.
1422 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, true );
1425 Article
::onArticleCreate( $this->mTitle
);
1427 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1428 $summary, $flags & EDIT_MINOR
,
1429 null, null, &$flags ) );
1432 if ( $good && !( $flags & EDIT_DEFER_UPDATES
) ) {
1436 wfRunHooks( 'ArticleSaveComplete',
1437 array( &$this, &$wgUser, $text,
1438 $summary, $flags & EDIT_MINOR
,
1439 null, null, &$flags ) );
1441 wfProfileOut( __METHOD__
);
1446 * @deprecated wrapper for doRedirect
1448 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1449 $this->doRedirect( $this->isRedirect( $text ), $sectionanchor );
1453 * Output a redirect back to the article.
1454 * This is typically used after an edit.
1456 * @param boolean $noRedir Add redirect=no
1457 * @param string $sectionAnchor section to redirect to, including "#"
1459 function doRedirect( $noRedir = false, $sectionAnchor = '' ) {
1462 $query = 'redirect=no';
1466 $wgOut->redirect( $this->mTitle
->getFullURL( $query ) . $sectionAnchor );
1470 * Mark this particular edit as patrolled
1472 function markpatrolled() {
1473 global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
1474 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1476 # Check RC patrol config. option
1477 if( !$wgUseRCPatrol ) {
1478 $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1483 if( !$wgUser->isAllowed( 'patrol' ) ) {
1484 $wgOut->permissionRequired( 'patrol' );
1488 $rcid = $wgRequest->getVal( 'rcid' );
1489 if ( !is_null ( $rcid ) ) {
1490 if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
1491 RecentChange
::markPatrolled( $rcid );
1492 wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
1493 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1494 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1496 $rcTitle = SpecialPage
::getTitleFor( 'Recentchanges' );
1497 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1500 $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1505 * User-interface handler for the "watch" action
1510 global $wgUser, $wgOut;
1512 if ( $wgUser->isAnon() ) {
1513 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1516 if ( wfReadOnly() ) {
1517 $wgOut->readOnlyPage();
1521 if( $this->doWatch() ) {
1522 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1523 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1525 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1526 $text = wfMsg( 'addedwatchtext', $link );
1527 $wgOut->addWikiText( $text );
1530 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1534 * Add this page to $wgUser's watchlist
1535 * @return bool true on successful watch operation
1537 function doWatch() {
1539 if( $wgUser->isAnon() ) {
1543 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1544 $wgUser->addWatch( $this->mTitle
);
1546 return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1553 * User interface handler for the "unwatch" action.
1555 function unwatch() {
1557 global $wgUser, $wgOut;
1559 if ( $wgUser->isAnon() ) {
1560 $wgOut->showErrorPage( 'watchnologin', 'watchnologintext' );
1563 if ( wfReadOnly() ) {
1564 $wgOut->readOnlyPage();
1568 if( $this->doUnwatch() ) {
1569 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1570 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1572 $link = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1573 $text = wfMsg( 'removedwatchtext', $link );
1574 $wgOut->addWikiText( $text );
1577 $wgOut->returnToMain( true, $this->mTitle
->getPrefixedText() );
1581 * Stop watching a page
1582 * @return bool true on successful unwatch
1584 function doUnwatch() {
1586 if( $wgUser->isAnon() ) {
1590 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1591 $wgUser->removeWatch( $this->mTitle
);
1593 return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1600 * action=protect handler
1602 function protect() {
1603 $form = new ProtectionForm( $this );
1608 * action=unprotect handler (alias)
1610 function unprotect() {
1615 * Update the article's restriction field, and leave a log entry.
1617 * @param array $limit set of restriction keys
1618 * @param string $reason
1619 * @return bool true on success
1621 function updateRestrictions( $limit = array(), $reason = '' ) {
1622 global $wgUser, $wgRestrictionTypes, $wgContLang;
1624 $id = $this->mTitle
->getArticleID();
1625 if( !$wgUser->isAllowed( 'protect' ) ||
wfReadOnly() ||
$id == 0 ) {
1629 # FIXME: Same limitations as described in ProtectionForm.php (line 37);
1630 # we expect a single selection, but the schema allows otherwise.
1632 foreach( $wgRestrictionTypes as $action )
1633 $current[$action] = implode( '', $this->mTitle
->getRestrictions( $action ) );
1635 $current = Article
::flattenRestrictions( $current );
1636 $updated = Article
::flattenRestrictions( $limit );
1638 $changed = ( $current != $updated );
1639 $protect = ( $updated != '' );
1641 # If nothing's changed, do nothing
1643 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
1645 $dbw =& wfGetDB( DB_MASTER
);
1647 # Prepare a null revision to be added to the history
1648 $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ?
'protectedarticle' : 'unprotectedarticle', $this->mTitle
->getPrefixedText() ) );
1650 $comment .= ": $reason";
1652 $comment .= " [$updated]";
1653 $nullRevision = Revision
::newNullRevision( $dbw, $id, $comment, true );
1654 $nullRevId = $nullRevision->insertOn( $dbw );
1656 # Update page record
1657 $dbw->update( 'page',
1659 'page_touched' => $dbw->timestamp(),
1660 'page_restrictions' => $updated,
1661 'page_latest' => $nullRevId
1662 ), array( /* WHERE */
1664 ), 'Article::protect'
1666 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
1668 # Update the protection log
1669 $log = new LogPage( 'protect' );
1671 $log->addEntry( 'protect', $this->mTitle
, trim( $reason . " [$updated]" ) );
1673 $log->addEntry( 'unprotect', $this->mTitle
, $reason );
1677 } # End "changed" check
1683 * Take an array of page restrictions and flatten it to a string
1684 * suitable for insertion into the page_restrictions field.
1685 * @param array $limit
1689 function flattenRestrictions( $limit ) {
1690 if( !is_array( $limit ) ) {
1691 throw new MWException( 'Article::flattenRestrictions given non-array restriction set' );
1695 foreach( $limit as $action => $restrictions ) {
1696 if( $restrictions != '' ) {
1697 $bits[] = "$action=$restrictions";
1700 return implode( ':', $bits );
1704 * UI entry point for page deletion
1707 global $wgUser, $wgOut, $wgRequest;
1708 $confirm = $wgRequest->wasPosted() &&
1709 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1710 $reason = $wgRequest->getText( 'wpReason' );
1712 # This code desperately needs to be totally rewritten
1715 if( $wgUser->isAllowed( 'delete' ) ) {
1716 if( $wgUser->isBlocked( !$confirm ) ) {
1717 $wgOut->blockedPage();
1721 $wgOut->permissionRequired( 'delete' );
1725 if( wfReadOnly() ) {
1726 $wgOut->readOnlyPage();
1730 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1732 # Better double-check that it hasn't been deleted yet!
1733 $dbw =& wfGetDB( DB_MASTER
);
1734 $conds = $this->mTitle
->pageCond();
1735 $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__
);
1736 if ( $latest === false ) {
1737 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1742 $this->doDelete( $reason );
1746 # determine whether this page has earlier revisions
1747 # and insert a warning if it does
1749 $authors = $this->getLastNAuthors( $maxRevisions, $latest );
1751 if( count( $authors ) > 1 && !$confirm ) {
1752 $skin=$wgUser->getSkin();
1753 $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
1756 # If a single user is responsible for all revisions, find out who they are
1757 if ( count( $authors ) == $maxRevisions ) {
1758 // Query bailed out, too many revisions to find out if they're all the same
1759 $authorOfAll = false;
1761 $authorOfAll = reset( $authors );
1762 foreach ( $authors as $author ) {
1763 if ( $authorOfAll != $author ) {
1764 $authorOfAll = false;
1769 # Fetch article text
1770 $rev = Revision
::newFromTitle( $this->mTitle
);
1772 if( !is_null( $rev ) ) {
1773 # if this is a mini-text, we can paste part of it into the deletion reason
1774 $text = $rev->getText();
1776 #if this is empty, an earlier revision may contain "useful" text
1779 $prev = $rev->getPrevious();
1781 $text = $prev->getText();
1786 $length = strlen( $text );
1788 # this should not happen, since it is not possible to store an empty, new
1789 # page. Let's insert a standard text in case it does, though
1790 if( $length == 0 && $reason === '' ) {
1791 $reason = wfMsgForContent( 'exblank' );
1794 if( $length < 500 && $reason === '' ) {
1795 # comment field=255, let's grep the first 150 to have some user
1798 $text = $wgContLang->truncate( $text, 150, '...' );
1800 # let's strip out newlines
1801 $text = preg_replace( "/[\n\r]/", '', $text );
1804 if( $authorOfAll === false ) {
1805 $reason = wfMsgForContent( 'excontent', $text );
1807 $reason = wfMsgForContent( 'excontentauthor', $text, $authorOfAll );
1810 $reason = wfMsgForContent( 'exbeforeblank', $text );
1815 return $this->confirmDelete( '', $reason );
1819 * Get the last N authors
1820 * @param int $num Number of revisions to get
1821 * @param string $revLatest The latest rev_id, selected from the master (optional)
1822 * @return array Array of authors, duplicates not removed
1824 function getLastNAuthors( $num, $revLatest = 0 ) {
1825 wfProfileIn( __METHOD__
);
1827 // First try the slave
1828 // If that doesn't have the latest revision, try the master
1830 $db =& wfGetDB( DB_SLAVE
);
1832 $res = $db->select( array( 'page', 'revision' ),
1833 array( 'rev_id', 'rev_user_text' ),
1835 'page_namespace' => $this->mTitle
->getNamespace(),
1836 'page_title' => $this->mTitle
->getDBkey(),
1837 'rev_page = page_id'
1838 ), __METHOD__
, $this->getSelectOptions( array(
1839 'ORDER BY' => 'rev_timestamp DESC',
1844 wfProfileOut( __METHOD__
);
1847 $row = $db->fetchObject( $res );
1848 if ( $continue == 2 && $revLatest && $row->rev_id
!= $revLatest ) {
1849 $db =& wfGetDB( DB_MASTER
);
1854 } while ( $continue );
1856 $authors = array( $row->rev_user_text
);
1857 while ( $row = $db->fetchObject( $res ) ) {
1858 $authors[] = $row->rev_user_text
;
1860 wfProfileOut( __METHOD__
);
1865 * Output deletion confirmation dialog
1867 function confirmDelete( $par, $reason ) {
1868 global $wgOut, $wgUser;
1870 wfDebug( "Article::confirmDelete\n" );
1872 $sub = htmlspecialchars( $this->mTitle
->getPrefixedText() );
1873 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1874 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1875 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1877 $formaction = $this->mTitle
->escapeLocalURL( 'action=delete' . $par );
1879 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1880 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1881 $token = htmlspecialchars( $wgUser->editToken() );
1884 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1888 <label for='wpReason'>{$delcom}:</label>
1891 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1897 <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" />
1901 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1904 $wgOut->returnToMain( false );
1909 * Perform a deletion and output success or failure messages
1911 function doDelete( $reason ) {
1912 global $wgOut, $wgUser;
1913 wfDebug( __METHOD__
."\n" );
1915 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1916 if ( $this->doDeleteArticle( $reason ) ) {
1917 $deleted = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
1919 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1920 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1922 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1923 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1925 $wgOut->addWikiText( $text );
1926 $wgOut->returnToMain( false );
1927 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1929 $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
1935 * Back-end article deletion
1936 * Deletes the article with database consistency, writes logs, purges caches
1939 function doDeleteArticle( $reason ) {
1940 global $wgUseSquid, $wgDeferredUpdateList;
1941 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1943 wfDebug( __METHOD__
."\n" );
1945 $dbw =& wfGetDB( DB_MASTER
);
1946 $ns = $this->mTitle
->getNamespace();
1947 $t = $this->mTitle
->getDBkey();
1948 $id = $this->mTitle
->getArticleID();
1950 if ( $t == '' ||
$id == 0 ) {
1954 $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
1955 array_push( $wgDeferredUpdateList, $u );
1957 // For now, shunt the revision data into the archive table.
1958 // Text is *not* removed from the text table; bulk storage
1959 // is left intact to avoid breaking block-compression or
1960 // immutable storage schemes.
1962 // For backwards compatibility, note that some older archive
1963 // table entries will have ar_text and ar_flags fields still.
1965 // In the future, we may keep revisions and mark them with
1966 // the rev_deleted field, which is reserved for this purpose.
1967 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1969 'ar_namespace' => 'page_namespace',
1970 'ar_title' => 'page_title',
1971 'ar_comment' => 'rev_comment',
1972 'ar_user' => 'rev_user',
1973 'ar_user_text' => 'rev_user_text',
1974 'ar_timestamp' => 'rev_timestamp',
1975 'ar_minor_edit' => 'rev_minor_edit',
1976 'ar_rev_id' => 'rev_id',
1977 'ar_text_id' => 'rev_text_id',
1980 'page_id = rev_page'
1984 # Now that it's safely backed up, delete it
1985 $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__
);
1987 # If using cascading deletes, we can skip some explicit deletes
1988 if ( !$dbw->cascadingDeletes() ) {
1990 $dbw->delete( 'revision', array( 'rev_page' => $id ), __METHOD__
);
1992 if ($wgUseTrackbacks)
1993 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), __METHOD__
);
1995 # Delete outgoing links
1996 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1997 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1998 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1999 $dbw->delete( 'templatelinks', array( 'tl_from' => $id ) );
2000 $dbw->delete( 'externallinks', array( 'el_from' => $id ) );
2001 $dbw->delete( 'langlinks', array( 'll_from' => $id ) );
2002 $dbw->delete( 'redirect', array( 'rd_from' => $id ) );
2005 # If using cleanup triggers, we can skip some manual deletes
2006 if ( !$dbw->cleanupTriggers() ) {
2008 # Clean up recentchanges entries...
2009 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), __METHOD__
);
2013 Article
::onArticleDelete( $this->mTitle
);
2016 $log = new LogPage( 'delete' );
2017 $log->addEntry( 'delete', $this->mTitle
, $reason );
2019 # Clear the cached article id so the interface doesn't act like we exist
2020 $this->mTitle
->resetArticleID( 0 );
2021 $this->mTitle
->mArticleID
= 0;
2026 * Revert a modification
2028 function rollback() {
2029 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
2031 if( $wgUser->isAllowed( 'rollback' ) ) {
2032 if( $wgUser->isBlocked() ) {
2033 $wgOut->blockedPage();
2037 $wgOut->permissionRequired( 'rollback' );
2041 if ( wfReadOnly() ) {
2042 $wgOut->readOnlyPage( $this->getContent() );
2045 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2046 array( $this->mTitle
->getPrefixedText(),
2047 $wgRequest->getVal( 'from' ) ) ) ) {
2048 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2049 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2052 $dbw =& wfGetDB( DB_MASTER
);
2054 # Enhanced rollback, marks edits rc_bot=1
2055 $bot = $wgRequest->getBool( 'bot' );
2057 # Replace all this user's current edits with the next one down
2058 $tt = $this->mTitle
->getDBKey();
2059 $n = $this->mTitle
->getNamespace();
2061 # Get the last editor
2062 $current = Revision
::newFromTitle( $this->mTitle
);
2063 if( is_null( $current ) ) {
2064 # Something wrong... no page?
2065 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2069 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2070 if( $from != $current->getUserText() ) {
2071 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2072 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2073 htmlspecialchars( $this->mTitle
->getPrefixedText()),
2074 htmlspecialchars( $from ),
2075 htmlspecialchars( $current->getUserText() ) ) );
2076 if( $current->getComment() != '') {
2078 wfMsg( 'editcomment',
2079 htmlspecialchars( $current->getComment() ) ) );
2084 # Get the last edit not by this guy
2085 $user = intval( $current->getUser() );
2086 $user_text = $dbw->addQuotes( $current->getUserText() );
2087 $s = $dbw->selectRow( 'revision',
2088 array( 'rev_id', 'rev_timestamp' ),
2090 'rev_page' => $current->getPage(),
2091 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2094 'USE INDEX' => 'page_timestamp',
2095 'ORDER BY' => 'rev_timestamp DESC' )
2097 if( $s === false ) {
2099 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2100 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2106 # Mark all reverted edits as bot
2109 if ( $wgUseRCPatrol ) {
2110 # Mark all reverted edits as patrolled
2111 $set['rc_patrolled'] = 1;
2115 $dbw->update( 'recentchanges', $set,
2117 'rc_cur_id' => $current->getPage(),
2118 'rc_user_text' => $current->getUserText(),
2119 "rc_timestamp > '{$s->rev_timestamp}'",
2124 # Get the edit summary
2125 $target = Revision
::newFromId( $s->rev_id
);
2126 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2127 $newComment = $wgRequest->getText( 'summary', $newComment );
2130 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2131 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2132 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2134 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle
->userIsWatching(), $bot );
2136 $wgOut->returnToMain( false );
2141 * Do standard deferred updates after page view
2144 function viewUpdates() {
2145 global $wgDeferredUpdateList;
2147 if ( 0 != $this->getID() ) {
2148 global $wgDisableCounters;
2149 if( !$wgDisableCounters ) {
2150 Article
::incViewCount( $this->getID() );
2151 $u = new SiteStatsUpdate( 1, 0, 0 );
2152 array_push( $wgDeferredUpdateList, $u );
2156 # Update newtalk / watchlist notification status
2158 $wgUser->clearNotification( $this->mTitle
);
2162 * Do standard deferred updates after page edit.
2163 * Update links tables, site stats, search index and message cache.
2164 * Every 1000th edit, prune the recent changes table.
2167 * @param $text New text of the article
2168 * @param $summary Edit summary
2169 * @param $minoredit Minor edit
2170 * @param $timestamp_of_pagechange Timestamp associated with the page change
2171 * @param $newid rev_id value of the new revision
2172 * @param $changed Whether or not the content actually changed
2174 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid, $changed = true ) {
2175 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser;
2177 wfProfileIn( __METHOD__
);
2180 $options = new ParserOptions
;
2181 $options->setTidy(true);
2182 $poutput = $wgParser->parse( $text, $this->mTitle
, $options, true, true, $newid );
2184 # Save it to the parser cache
2185 $parserCache =& ParserCache
::singleton();
2186 $parserCache->save( $poutput, $this, $wgUser );
2188 # Update the links tables
2189 $u = new LinksUpdate( $this->mTitle
, $poutput );
2192 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2194 if ( 0 == mt_rand( 0, 999 ) ) {
2195 # Periodically flush old entries from the recentchanges table.
2198 $dbw =& wfGetDB( DB_MASTER
);
2199 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2200 $recentchanges = $dbw->tableName( 'recentchanges' );
2201 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2202 $dbw->query( $sql );
2206 $id = $this->getID();
2207 $title = $this->mTitle
->getPrefixedDBkey();
2208 $shortTitle = $this->mTitle
->getDBkey();
2211 wfProfileOut( __METHOD__
);
2215 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment
, $this->mTotalAdjustment
);
2216 array_push( $wgDeferredUpdateList, $u );
2217 $u = new SearchUpdate( $id, $title, $text );
2218 array_push( $wgDeferredUpdateList, $u );
2220 # If this is another user's talk page, update newtalk
2221 # Don't do this if $changed = false otherwise some idiot can null-edit a
2222 # load of user talk pages and piss people off, nor if it's a minor edit
2223 # by a properly-flagged bot.
2224 if( $this->mTitle
->getNamespace() == NS_USER_TALK
&& $shortTitle != $wgUser->getTitleKey() && $changed
2225 && !($minoredit && $wgUser->isAllowed('nominornewtalk') ) ) {
2226 if (wfRunHooks('ArticleEditUpdateNewTalk', array(&$this)) ) {
2227 $other = User
::newFromName( $shortTitle );
2228 if( is_null( $other ) && User
::isIP( $shortTitle ) ) {
2229 // An anonymous user
2230 $other = new User();
2231 $other->setName( $shortTitle );
2234 $other->setNewtalk( true );
2239 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2240 $wgMessageCache->replace( $shortTitle, $text );
2243 wfProfileOut( __METHOD__
);
2247 * Perform article updates on a special page creation.
2249 * @param Revision $rev
2251 * @fixme This is a shitty interface function. Kill it and replace the
2252 * other shitty functions like editUpdates and such so it's not needed
2255 function createUpdates( $rev ) {
2256 $this->mGoodAdjustment
= $this->isCountable( $rev->getText() );
2257 $this->mTotalAdjustment
= 1;
2258 $this->editUpdates( $rev->getText(), $rev->getComment(),
2259 $rev->isMinor(), wfTimestamp(), $rev->getId(), true );
2263 * Generate the navigation links when browsing through an article revisions
2264 * It shows the information as:
2265 * Revision as of \<date\>; view current revision
2266 * \<- Previous version | Next Version -\>
2269 * @param string $oldid Revision ID of this article revision
2271 function setOldSubtitle( $oldid=0 ) {
2272 global $wgLang, $wgOut, $wgUser;
2274 if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
2278 $revision = Revision
::newFromId( $oldid );
2280 $current = ( $oldid == $this->mLatest
);
2281 $td = $wgLang->timeanddate( $this->mTimestamp
, true );
2282 $sk = $wgUser->getSkin();
2284 ?
wfMsg( 'currentrevisionlink' )
2285 : $lnk = $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'currentrevisionlink' ) );
2288 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
2289 $prev = $this->mTitle
->getPreviousRevisionID( $oldid ) ;
2291 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
2292 : wfMsg( 'previousrevision' );
2294 ?
$sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
2296 $nextlink = $current
2297 ?
wfMsg( 'nextrevision' )
2298 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2299 $nextdiff = $current
2301 : $sk->makeKnownLinkObj( $this->mTitle
, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
2303 $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
2304 . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
2306 $r = wfMsg( 'old-revision-navigation', $td, $lnk, $prevlink, $nextlink, $userlinks, $prevdiff, $nextdiff, $curdiff );
2307 $wgOut->setSubtitle( $r );
2311 * This function is called right before saving the wikitext,
2312 * so we can do things like signatures and links-in-context.
2314 * @param string $text
2316 function preSaveTransform( $text ) {
2317 global $wgParser, $wgUser;
2318 return $wgParser->preSaveTransform( $text, $this->mTitle
, $wgUser, ParserOptions
::newFromUser( $wgUser ) );
2321 /* Caching functions */
2324 * checkLastModified returns true if it has taken care of all
2325 * output to the client that is necessary for this request.
2326 * (that is, it has sent a cached version of the page)
2328 function tryFileCache() {
2329 static $called = false;
2331 wfDebug( "Article::tryFileCache(): called twice!?\n" );
2335 if($this->isFileCacheable()) {
2336 $touched = $this->mTouched
;
2337 $cache = new HTMLFileCache( $this->mTitle
);
2338 if($cache->isFileCacheGood( $touched )) {
2339 wfDebug( "Article::tryFileCache(): about to load file\n" );
2340 $cache->loadFromFileCache();
2343 wfDebug( "Article::tryFileCache(): starting buffer\n" );
2344 ob_start( array(&$cache, 'saveToFileCache' ) );
2347 wfDebug( "Article::tryFileCache(): not cacheable\n" );
2352 * Check if the page can be cached
2355 function isFileCacheable() {
2356 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2357 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2359 return $wgUseFileCache
2360 and (!$wgShowIPinHeader)
2361 and ($this->getID() != 0)
2362 and ($wgUser->isAnon())
2363 and (!$wgUser->getNewtalk())
2364 and ($this->mTitle
->getNamespace() != NS_SPECIAL
)
2365 and (empty( $action ) ||
$action == 'view')
2366 and (!isset($oldid))
2368 and (!isset($redirect))
2369 and (!isset($printable))
2370 and (!$this->mRedirectedFrom
);
2374 * Loads page_touched and returns a value indicating if it should be used
2377 function checkTouched() {
2378 if( !$this->mDataLoaded
) {
2379 $this->loadPageData();
2381 return !$this->mIsRedirect
;
2385 * Get the page_touched field
2387 function getTouched() {
2388 # Ensure that page data has been loaded
2389 if( !$this->mDataLoaded
) {
2390 $this->loadPageData();
2392 return $this->mTouched
;
2396 * Get the page_latest field
2398 function getLatest() {
2399 if ( !$this->mDataLoaded
) {
2400 $this->loadPageData();
2402 return $this->mLatest
;
2406 * Edit an article without doing all that other stuff
2407 * The article must already exist; link tables etc
2408 * are not updated, caches are not flushed.
2410 * @param string $text text submitted
2411 * @param string $comment comment submitted
2412 * @param bool $minor whereas it's a minor modification
2414 function quickEdit( $text, $comment = '', $minor = 0 ) {
2415 wfProfileIn( __METHOD__
);
2417 $dbw =& wfGetDB( DB_MASTER
);
2419 $revision = new Revision( array(
2420 'page' => $this->getId(),
2422 'comment' => $comment,
2423 'minor_edit' => $minor ?
1 : 0,
2425 # fixme : $revisionId never used
2426 $revisionId = $revision->insertOn( $dbw );
2427 $this->updateRevisionOn( $dbw, $revision );
2430 wfProfileOut( __METHOD__
);
2434 * Used to increment the view counter
2437 * @param integer $id article id
2439 function incViewCount( $id ) {
2440 $id = intval( $id );
2441 global $wgHitcounterUpdateFreq, $wgDBtype;
2443 $dbw =& wfGetDB( DB_MASTER
);
2444 $pageTable = $dbw->tableName( 'page' );
2445 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2446 $acchitsTable = $dbw->tableName( 'acchits' );
2448 if( $wgHitcounterUpdateFreq <= 1 ){ //
2449 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2453 # Not important enough to warrant an error page in case of failure
2454 $oldignore = $dbw->ignoreErrors( true );
2456 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2458 $checkfreq = intval( $wgHitcounterUpdateFreq/25 +
1 );
2459 if( (rand() %
$checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2460 # Most of the time (or on SQL errors), skip row count check
2461 $dbw->ignoreErrors( $oldignore );
2465 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2466 $row = $dbw->fetchObject( $res );
2467 $rown = intval( $row->n
);
2468 if( $rown >= $wgHitcounterUpdateFreq ){
2469 wfProfileIn( 'Article::incViewCount-collect' );
2470 $old_user_abort = ignore_user_abort( true );
2472 if ($wgDBtype == 'mysql')
2473 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2474 $tabletype = $wgDBtype == 'mysql' ?
"ENGINE=HEAP " : '';
2475 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS".
2476 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2478 $dbw->query("DELETE FROM $hitcounterTable");
2479 if ($wgDBtype == 'mysql')
2480 $dbw->query('UNLOCK TABLES');
2481 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2482 'WHERE page_id = hc_id');
2483 $dbw->query("DROP TABLE $acchitsTable");
2485 ignore_user_abort( $old_user_abort );
2486 wfProfileOut( 'Article::incViewCount-collect' );
2488 $dbw->ignoreErrors( $oldignore );
2492 * The onArticle*() functions are supposed to be a kind of hooks
2493 * which should be called whenever any of the specified actions
2496 * This is a good place to put code to clear caches, for instance.
2498 * This is called on page move and undelete, as well as edit
2500 * @param $title_obj a title object
2503 static function onArticleCreate($title) {
2504 # The talk page isn't in the regular link tables, so we need to update manually:
2505 if ( $title->isTalkPage() ) {
2506 $other = $title->getSubjectPage();
2508 $other = $title->getTalkPage();
2510 $other->invalidateCache();
2511 $other->purgeSquid();
2513 $title->touchLinks();
2514 $title->purgeSquid();
2517 static function onArticleDelete( $title ) {
2518 global $wgUseFileCache, $wgMessageCache;
2520 $title->touchLinks();
2521 $title->purgeSquid();
2524 if ( $wgUseFileCache ) {
2525 $cm = new HTMLFileCache( $title );
2526 @unlink
( $cm->fileCacheName() );
2529 if( $title->getNamespace() == NS_MEDIAWIKI
) {
2530 $wgMessageCache->replace( $title->getDBkey(), false );
2535 * Purge caches on page update etc
2537 static function onArticleEdit( $title ) {
2538 global $wgDeferredUpdateList, $wgUseFileCache;
2542 // Invalidate caches of articles which include this page
2543 $update = new HTMLCacheUpdate( $title, 'templatelinks' );
2544 $wgDeferredUpdateList[] = $update;
2546 # Purge squid for this page only
2547 $title->purgeSquid();
2550 if ( $wgUseFileCache ) {
2551 $cm = new HTMLFileCache( $title );
2552 @unlink
( $cm->fileCacheName() );
2559 * Info about this page
2560 * Called for ?action=info when $wgAllowPageInfo is on.
2565 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2567 if ( !$wgAllowPageInfo ) {
2568 $wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
2572 $page = $this->mTitle
->getSubjectPage();
2574 $wgOut->setPagetitle( $page->getPrefixedText() );
2575 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2577 # first, see if the page exists at all.
2578 $exists = $page->getArticleId() != 0;
2580 if ( $this->mTitle
->getNamespace() == NS_MEDIAWIKI
) {
2581 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle
->getText() ) );
2583 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ?
'noarticletext' : 'noarticletextanon' ) );
2586 $dbr =& wfGetDB( DB_SLAVE
);
2588 'wl_title' => $page->getDBkey(),
2589 'wl_namespace' => $page->getNamespace() );
2590 $numwatchers = $dbr->selectField(
2595 $this->getSelectOptions() );
2597 $pageInfo = $this->pageCountInfo( $page );
2598 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2600 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2601 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2603 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2605 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2607 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2609 $wgOut->addHTML( '</ul>' );
2615 * Return the total number of edits and number of unique editors
2616 * on a given page. If page does not exist, returns false.
2618 * @param Title $title
2622 function pageCountInfo( $title ) {
2623 $id = $title->getArticleId();
2628 $dbr =& wfGetDB( DB_SLAVE
);
2630 $rev_clause = array( 'rev_page' => $id );
2632 $edits = $dbr->selectField(
2637 $this->getSelectOptions() );
2639 $authors = $dbr->selectField(
2641 'COUNT(DISTINCT rev_user_text)',
2644 $this->getSelectOptions() );
2646 return array( 'edits' => $edits, 'authors' => $authors );
2650 * Return a list of templates used by this article.
2651 * Uses the templatelinks table
2653 * @return array Array of Title objects
2655 function getUsedTemplates() {
2657 $id = $this->mTitle
->getArticleID();
2662 $dbr =& wfGetDB( DB_SLAVE
);
2663 $res = $dbr->select( array( 'templatelinks' ),
2664 array( 'tl_namespace', 'tl_title' ),
2665 array( 'tl_from' => $id ),
2666 'Article:getUsedTemplates' );
2667 if ( false !== $res ) {
2668 if ( $dbr->numRows( $res ) ) {
2669 while ( $row = $dbr->fetchObject( $res ) ) {
2670 $result[] = Title
::makeTitle( $row->tl_namespace
, $row->tl_title
);
2674 $dbr->freeResult( $res );