mTitle =& $title;
$this->mOldId = $oldId;
$this->clear();
}
/**
* Tell the page view functions that this view was redirected
* from another page on the wiki.
* @param $from Title object.
*/
function setRedirectedFrom( $from ) {
$this->mRedirectedFrom = $from;
}
/**
* @return mixed false, Title of in-wiki target, or string with URL
*/
function followRedirect() {
$text = $this->getContent();
$rt = Title::newFromRedirect( $text );
# process if title object is valid and not special:userlogout
if( $rt ) {
if( $rt->getInterwiki() != '' ) {
if( $rt->isLocal() ) {
// Offsite wikis need an HTTP redirect.
//
// This can be hard to reverse and may produce loops,
// so they may be disabled in the site configuration.
$source = $this->mTitle->getFullURL( 'redirect=no' );
return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
}
} else {
if( $rt->getNamespace() == NS_SPECIAL ) {
// Gotta handle redirects to special pages differently:
// Fill the HTTP response "Location" header and ignore
// the rest of the page we're on.
//
// This can be hard to reverse, so they may be disabled.
if( $rt->isSpecial( 'Userlogout' ) ) {
// rolleyes
} else {
return $rt->getFullURL();
}
}
return $rt;
}
}
// No or invalid redirect
return false;
}
/**
* get the title object of the article
*/
function getTitle() {
return $this->mTitle;
}
/**
* Clear the object
* @private
*/
function clear() {
$this->mDataLoaded = false;
$this->mContentLoaded = false;
$this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
$this->mRedirectedFrom = null; # Title object if set
$this->mUserText =
$this->mTimestamp = $this->mComment = '';
$this->mGoodAdjustment = $this->mTotalAdjustment = 0;
$this->mTouched = '19700101000000';
$this->mForUpdate = false;
$this->mIsRedirect = false;
$this->mRevIdFetched = 0;
$this->mRedirectUrl = false;
$this->mLatest = false;
$this->mPreparedEdit = false;
}
/**
* Note that getContent/loadContent do not follow redirects anymore.
* If you need to fetch redirectable content easily, try
* the shortcut in Article::followContent()
* FIXME
* @todo There are still side-effects in this!
* In general, you should use the Revision class, not Article,
* to fetch text for purposes other than page views.
*
* @return Return the text of this revision
*/
function getContent() {
global $wgUser, $wgOut;
wfProfileIn( __METHOD__ );
if ( 0 == $this->getID() ) {
wfProfileOut( __METHOD__ );
$wgOut->setRobotpolicy( 'noindex,nofollow' );
if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
$ret = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
} else {
$ret = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
}
return "
$ret
";
} else {
$this->loadContent();
wfProfileOut( __METHOD__ );
return $this->mContent;
}
}
/**
* This function returns the text of a section, specified by a number ($section).
* A section is text under a heading like == Heading == or \
Heading\
, or
* the first section before any such heading (section 0).
*
* If a section contains subsections, these are also returned.
*
* @param $text String: text to look in
* @param $section Integer: section number
* @return string text of the requested section
* @deprecated
*/
function getSection($text,$section) {
global $wgParser;
return $wgParser->getSection( $text, $section );
}
/**
* @return int The oldid of the article that is to be shown, 0 for the
* current revision
*/
function getOldID() {
if ( is_null( $this->mOldId ) ) {
$this->mOldId = $this->getOldIDFromRequest();
}
return $this->mOldId;
}
/**
* Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
*
* @return int The old id for the request
*/
function getOldIDFromRequest() {
global $wgRequest;
$this->mRedirectUrl = false;
$oldid = $wgRequest->getVal( 'oldid' );
if ( isset( $oldid ) ) {
$oldid = intval( $oldid );
if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
$nextid = $this->mTitle->getNextRevisionID( $oldid );
if ( $nextid ) {
$oldid = $nextid;
} else {
$this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
}
} elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
$previd = $this->mTitle->getPreviousRevisionID( $oldid );
if ( $previd ) {
$oldid = $previd;
} else {
# TODO
}
}
# unused:
# $lastid = $oldid;
}
if ( !$oldid ) {
$oldid = 0;
}
return $oldid;
}
/**
* Load the revision (including text) into this object
*/
function loadContent() {
if ( $this->mContentLoaded ) return;
# Query variables :P
$oldid = $this->getOldID();
# Pre-fill content with error message so that if something
# fails we'll have something telling us what we intended.
$this->mOldId = $oldid;
$this->fetchContent( $oldid );
}
/**
* Fetch a page record with the given conditions
* @param Database $dbr
* @param array $conditions
* @private
*/
function pageData( $dbr, $conditions ) {
$fields = array(
'page_id',
'page_namespace',
'page_title',
'page_restrictions',
'page_counter',
'page_is_redirect',
'page_is_new',
'page_random',
'page_touched',
'page_latest',
'page_len',
);
wfRunHooks( 'ArticlePageDataBefore', array( &$this, &$fields ) );
$row = $dbr->selectRow(
'page',
$fields,
$conditions,
__METHOD__
);
wfRunHooks( 'ArticlePageDataAfter', array( &$this, &$row ) );
return $row ;
}
/**
* @param Database $dbr
* @param Title $title
*/
function pageDataFromTitle( $dbr, $title ) {
return $this->pageData( $dbr, array(
'page_namespace' => $title->getNamespace(),
'page_title' => $title->getDBkey() ) );
}
/**
* @param Database $dbr
* @param int $id
*/
function pageDataFromId( $dbr, $id ) {
return $this->pageData( $dbr, array( 'page_id' => $id ) );
}
/**
* Set the general counter, title etc data loaded from
* some source.
*
* @param object $data
* @private
*/
function loadPageData( $data = 'fromdb' ) {
if ( $data === 'fromdb' ) {
$dbr = $this->getDB();
$data = $this->pageDataFromId( $dbr, $this->getId() );
}
$lc =& LinkCache::singleton();
if ( $data ) {
$lc->addGoodLinkObj( $data->page_id, $this->mTitle );
$this->mTitle->mArticleID = $data->page_id;
# Old-fashioned restrictions.
$this->mTitle->loadRestrictions( $data->page_restrictions );
$this->mCounter = $data->page_counter;
$this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
$this->mIsRedirect = $data->page_is_redirect;
$this->mLatest = $data->page_latest;
} else {
if ( is_object( $this->mTitle ) ) {
$lc->addBadLinkObj( $this->mTitle );
}
$this->mTitle->mArticleID = 0;
}
$this->mDataLoaded = true;
}
/**
* Get text of an article from database
* Does *NOT* follow redirects.
* @param int $oldid 0 for whatever the latest revision is
* @return string
*/
function fetchContent( $oldid = 0 ) {
if ( $this->mContentLoaded ) {
return $this->mContent;
}
$dbr = $this->getDB();
# Pre-fill content with error message so that if something
# fails we'll have something telling us what we intended.
$t = $this->mTitle->getPrefixedText();
if( $oldid ) {
$t .= ',oldid='.$oldid;
}
$this->mContent = wfMsg( 'missingarticle', $t ) ;
if( $oldid ) {
$revision = Revision::newFromId( $oldid );
if( is_null( $revision ) ) {
wfDebug( __METHOD__." failed to retrieve specified revision, id $oldid\n" );
return false;
}
$data = $this->pageDataFromId( $dbr, $revision->getPage() );
if( !$data ) {
wfDebug( __METHOD__." failed to get page data linked to revision id $oldid\n" );
return false;
}
$this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
$this->loadPageData( $data );
} else {
if( !$this->mDataLoaded ) {
$data = $this->pageDataFromTitle( $dbr, $this->mTitle );
if( !$data ) {
wfDebug( __METHOD__." failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
return false;
}
$this->loadPageData( $data );
}
$revision = Revision::newFromId( $this->mLatest );
if( is_null( $revision ) ) {
wfDebug( __METHOD__." failed to retrieve current page, rev_id {$data->page_latest}\n" );
return false;
}
}
// FIXME: Horrible, horrible! This content-loading interface just plain sucks.
// We should instead work with the Revision object when we need it...
$this->mContent = $revision->userCan( Revision::DELETED_TEXT ) ? $revision->getRawText() : "";
//$this->mContent = $revision->getText();
$this->mUser = $revision->getUser();
$this->mUserText = $revision->getUserText();
$this->mComment = $revision->getComment();
$this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
$this->mRevIdFetched = $revision->getID();
$this->mContentLoaded = true;
$this->mRevision =& $revision;
wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
return $this->mContent;
}
/**
* Read/write accessor to select FOR UPDATE
*
* @param $x Mixed: FIXME
*/
function forUpdate( $x = NULL ) {
return wfSetVar( $this->mForUpdate, $x );
}
/**
* Get the database which should be used for reads
*
* @return Database
*/
function getDB() {
return wfGetDB( DB_MASTER );
}
/**
* Get options for all SELECT statements
*
* @param $options Array: an optional options array which'll be appended to
* the default
* @return Array: options
*/
function getSelectOptions( $options = '' ) {
if ( $this->mForUpdate ) {
if ( is_array( $options ) ) {
$options[] = 'FOR UPDATE';
} else {
$options = 'FOR UPDATE';
}
}
return $options;
}
/**
* @return int Page ID
*/
function getID() {
if( $this->mTitle ) {
return $this->mTitle->getArticleID();
} else {
return 0;
}
}
/**
* @return bool Whether or not the page exists in the database
*/
function exists() {
return $this->getId() != 0;
}
/**
* @return int The view count for the page
*/
function getCount() {
if ( -1 == $this->mCounter ) {
$id = $this->getID();
if ( $id == 0 ) {
$this->mCounter = 0;
} else {
$dbr = wfGetDB( DB_SLAVE );
$this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
'Article::getCount', $this->getSelectOptions() );
}
}
return $this->mCounter;
}
/**
* Determine whether a page would be suitable for being counted as an
* article in the site_stats table based on the title & its content
*
* @param $text String: text to analyze
* @return bool
*/
function isCountable( $text ) {
global $wgUseCommaCount;
$token = $wgUseCommaCount ? ',' : '[[';
return
$this->mTitle->isContentPage()
&& !$this->isRedirect( $text )
&& in_string( $token, $text );
}
/**
* Tests if the article text represents a redirect
*
* @param $text String: FIXME
* @return bool
*/
function isRedirect( $text = false ) {
if ( $text === false ) {
$this->loadContent();
$titleObj = Title::newFromRedirect( $this->fetchContent() );
} else {
$titleObj = Title::newFromRedirect( $text );
}
return $titleObj !== NULL;
}
/**
* Returns true if the currently-referenced revision is the current edit
* to this page (and it exists).
* @return bool
*/
function isCurrent() {
# If no oldid, this is the current version.
if ($this->getOldID() == 0)
return true;
return $this->exists() &&
isset( $this->mRevision ) &&
$this->mRevision->isCurrent();
}
/**
* Loads everything except the text
* This isn't necessary for all uses, so it's only done if needed.
* @private
*/
function loadLastEdit() {
if ( -1 != $this->mUser )
return;
# New or non-existent articles have no user information
$id = $this->getID();
if ( 0 == $id ) return;
$this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
if( !is_null( $this->mLastRevision ) ) {
$this->mUser = $this->mLastRevision->getUser();
$this->mUserText = $this->mLastRevision->getUserText();
$this->mTimestamp = $this->mLastRevision->getTimestamp();
$this->mComment = $this->mLastRevision->getComment();
$this->mMinorEdit = $this->mLastRevision->isMinor();
$this->mRevIdFetched = $this->mLastRevision->getID();
}
}
function getTimestamp() {
// Check if the field has been filled by ParserCache::get()
if ( !$this->mTimestamp ) {
$this->loadLastEdit();
}
return wfTimestamp(TS_MW, $this->mTimestamp);
}
function getUser() {
$this->loadLastEdit();
return $this->mUser;
}
function getUserText() {
$this->loadLastEdit();
return $this->mUserText;
}
function getComment() {
$this->loadLastEdit();
return $this->mComment;
}
function getMinorEdit() {
$this->loadLastEdit();
return $this->mMinorEdit;
}
function getRevIdFetched() {
$this->loadLastEdit();
return $this->mRevIdFetched;
}
/**
* @todo Document, fixme $offset never used.
* @param $limit Integer: default 0.
* @param $offset Integer: default 0.
*/
function getContributors($limit = 0, $offset = 0) {
# XXX: this is expensive; cache this info somewhere.
$contribs = array();
$dbr = wfGetDB( DB_SLAVE );
$revTable = $dbr->tableName( 'revision' );
$userTable = $dbr->tableName( 'user' );
$user = $this->getUser();
$pageId = $this->getId();
$sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
WHERE rev_page = $pageId
AND rev_user != $user
GROUP BY rev_user, rev_user_text, user_real_name
ORDER BY timestamp DESC";
if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
$sql .= ' '. $this->getSelectOptions();
$res = $dbr->query($sql, __METHOD__);
while ( $line = $dbr->fetchObject( $res ) ) {
$contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
}
$dbr->freeResult($res);
return $contribs;
}
/**
* This is the default action of the script: just view the page of
* the given title.
*/
function view() {
global $wgUser, $wgOut, $wgRequest, $wgContLang;
global $wgEnableParserCache, $wgStylePath, $wgParser;
global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
$sk = $wgUser->getSkin();
wfProfileIn( __METHOD__ );
$parserCache =& ParserCache::singleton();
$ns = $this->mTitle->getNamespace(); # shortcut
# Get variables from query string
$oldid = $this->getOldID();
# getOldID may want us to redirect somewhere else
if ( $this->mRedirectUrl ) {
$wgOut->redirect( $this->mRedirectUrl );
wfProfileOut( __METHOD__ );
return;
}
$diff = $wgRequest->getVal( 'diff' );
$rcid = $wgRequest->getVal( 'rcid' );
$rdfrom = $wgRequest->getVal( 'rdfrom' );
$diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
$purge = $wgRequest->getVal( 'action' ) == 'purge';
$wgOut->setArticleFlag( true );
# Discourage indexing of printable versions, but encourage following
if( $wgOut->isPrintable() ) {
$policy = 'noindex,follow';
} elseif ( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
$policy = $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()];
} elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
# Honour customised robot policies for this namespace
$policy = $wgNamespaceRobotPolicies[$ns];
} else {
# Default to encourage indexing and following links
$policy = 'index,follow';
}
$wgOut->setRobotPolicy( $policy );
# If we got diff and oldid in the query, we want to see a
# diff page instead of the article.
if ( !is_null( $diff ) ) {
$wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
$de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge );
// DifferenceEngine directly fetched the revision:
$this->mRevIdFetched = $de->mNewid;
$de->showDiffPage( $diffOnly );
// Needed to get the page's current revision
$this->loadPageData();
if( $diff == 0 || $diff == $this->mLatest ) {
# Run view updates for current revision only
$this->viewUpdates();
}
wfProfileOut( __METHOD__ );
return;
}
if ( empty( $oldid ) && $this->checkTouched() ) {
$wgOut->setETag($parserCache->getETag($this, $wgUser));
if( $wgOut->checkLastModified( $this->mTouched ) ){
wfProfileOut( __METHOD__ );
return;
} else if ( $this->tryFileCache() ) {
# tell wgOut that output is taken care of
$wgOut->disable();
$this->viewUpdates();
wfProfileOut( __METHOD__ );
return;
}
}
# Should the parser cache be used?
$pcache = $wgEnableParserCache
&& intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
&& $this->exists()
&& empty( $oldid )
&& !$this->mTitle->isCssOrJsPage()
&& !$this->mTitle->isCssJsSubpage();
wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
if ( $wgUser->getOption( 'stubthreshold' ) ) {
wfIncrStats( 'pcache_miss_stub' );
}
$wasRedirected = false;
if ( isset( $this->mRedirectedFrom ) ) {
// This is an internally redirected page view.
// We'll need a backlink to the source page for navigation.
if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
$sk = $wgUser->getSkin();
$redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
$s = wfMsg( 'redirectedfrom', $redir );
$wgOut->setSubtitle( $s );
// Set the fragment if one was specified in the redirect
if ( strval( $this->mTitle->getFragment() ) != '' ) {
$fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
$wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
}
$wasRedirected = true;
}
} elseif ( !empty( $rdfrom ) ) {
// This is an externally redirected view, from some other wiki.
// If it was reported from a trusted site, supply a backlink.
global $wgRedirectSources;
if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
$sk = $wgUser->getSkin();
$redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
$s = wfMsg( 'redirectedfrom', $redir );
$wgOut->setSubtitle( $s );
$wasRedirected = true;
}
}
$outputDone = false;
wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
if ( $pcache ) {
if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
// Ensure that UI elements requiring revision ID have
// the correct version information.
$wgOut->setRevisionId( $this->mLatest );
$outputDone = true;
}
}
if ( !$outputDone ) {
$text = $this->getContent();
if ( $text === false ) {
# Failed to load, replace text with error message
$t = $this->mTitle->getPrefixedText();
if( $oldid ) {
$t .= ',oldid='.$oldid;
$text = wfMsg( 'missingarticle', $t );
} else {
$text = wfMsg( 'noarticletext', $t );
}
}
# Another whitelist check in case oldid is altering the title
if ( !$this->mTitle->userCanRead() ) {
$wgOut->loginToUse();
$wgOut->output();
exit;
}
# We're looking at an old revision
if ( !empty( $oldid ) ) {
$wgOut->setRobotpolicy( 'noindex,nofollow' );
if( is_null( $this->mRevision ) ) {
// FIXME: This would be a nice place to load the 'no such page' text.
} else {
$this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
if( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
$wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
$wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
return;
} else {
$wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
// and we are allowed to see...
}
}
}
}
}
if( !$outputDone ) {
$wgOut->setRevisionId( $this->getRevIdFetched() );
// Pages containing custom CSS or JavaScript get special treatment
if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
$wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
// Give hooks a chance to customise the output
if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
// Wrap the whole lot in a
\n\t\t\t";
$wgOut->setSubtitle( $r );
}
/**
* This function is called right before saving the wikitext,
* so we can do things like signatures and links-in-context.
*
* @param string $text
*/
function preSaveTransform( $text ) {
global $wgParser, $wgUser;
return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
}
/* Caching functions */
/**
* checkLastModified returns true if it has taken care of all
* output to the client that is necessary for this request.
* (that is, it has sent a cached version of the page)
*/
function tryFileCache() {
static $called = false;
if( $called ) {
wfDebug( "Article::tryFileCache(): called twice!?\n" );
return;
}
$called = true;
if($this->isFileCacheable()) {
$touched = $this->mTouched;
$cache = new HTMLFileCache( $this->mTitle );
if($cache->isFileCacheGood( $touched )) {
wfDebug( "Article::tryFileCache(): about to load file\n" );
$cache->loadFromFileCache();
return true;
} else {
wfDebug( "Article::tryFileCache(): starting buffer\n" );
ob_start( array(&$cache, 'saveToFileCache' ) );
}
} else {
wfDebug( "Article::tryFileCache(): not cacheable\n" );
}
}
/**
* Check if the page can be cached
* @return bool
*/
function isFileCacheable() {
global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
$action = $wgRequest->getVal( 'action' );
$oldid = $wgRequest->getVal( 'oldid' );
$diff = $wgRequest->getVal( 'diff' );
$redirect = $wgRequest->getVal( 'redirect' );
$printable = $wgRequest->getVal( 'printable' );
$page = $wgRequest->getVal( 'page' );
//check for non-standard user language; this covers uselang,
//and extensions for auto-detecting user language.
$ulang = $wgLang->getCode();
$clang = $wgContLang->getCode();
$cacheable = $wgUseFileCache
&& (!$wgShowIPinHeader)
&& ($this->getID() != 0)
&& ($wgUser->isAnon())
&& (!$wgUser->getNewtalk())
&& ($this->mTitle->getNamespace() != NS_SPECIAL )
&& (empty( $action ) || $action == 'view')
&& (!isset($oldid))
&& (!isset($diff))
&& (!isset($redirect))
&& (!isset($printable))
&& !isset($page)
&& (!$this->mRedirectedFrom)
&& ($ulang === $clang);
if ( $cacheable ) {
//extension may have reason to disable file caching on some pages.
$cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
}
return $cacheable;
}
/**
* Loads page_touched and returns a value indicating if it should be used
*
*/
function checkTouched() {
if( !$this->mDataLoaded ) {
$this->loadPageData();
}
return !$this->mIsRedirect;
}
/**
* Get the page_touched field
*/
function getTouched() {
# Ensure that page data has been loaded
if( !$this->mDataLoaded ) {
$this->loadPageData();
}
return $this->mTouched;
}
/**
* Get the page_latest field
*/
function getLatest() {
if ( !$this->mDataLoaded ) {
$this->loadPageData();
}
return $this->mLatest;
}
/**
* Edit an article without doing all that other stuff
* The article must already exist; link tables etc
* are not updated, caches are not flushed.
*
* @param string $text text submitted
* @param string $comment comment submitted
* @param bool $minor whereas it's a minor modification
*/
function quickEdit( $text, $comment = '', $minor = 0 ) {
wfProfileIn( __METHOD__ );
$dbw = wfGetDB( DB_MASTER );
$dbw->begin();
$revision = new Revision( array(
'page' => $this->getId(),
'text' => $text,
'comment' => $comment,
'minor_edit' => $minor ? 1 : 0,
) );
$revision->insertOn( $dbw );
$this->updateRevisionOn( $dbw, $revision );
$dbw->commit();
wfProfileOut( __METHOD__ );
}
/**
* Used to increment the view counter
*
* @static
* @param integer $id article id
*/
function incViewCount( $id ) {
$id = intval( $id );
global $wgHitcounterUpdateFreq, $wgDBtype;
$dbw = wfGetDB( DB_MASTER );
$pageTable = $dbw->tableName( 'page' );
$hitcounterTable = $dbw->tableName( 'hitcounter' );
$acchitsTable = $dbw->tableName( 'acchits' );
if( $wgHitcounterUpdateFreq <= 1 ) {
$dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
return;
}
# Not important enough to warrant an error page in case of failure
$oldignore = $dbw->ignoreErrors( true );
$dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
$checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
# Most of the time (or on SQL errors), skip row count check
$dbw->ignoreErrors( $oldignore );
return;
}
$res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
$row = $dbw->fetchObject( $res );
$rown = intval( $row->n );
if( $rown >= $wgHitcounterUpdateFreq ){
wfProfileIn( 'Article::incViewCount-collect' );
$old_user_abort = ignore_user_abort( true );
if ($wgDBtype == 'mysql')
$dbw->query("LOCK TABLES $hitcounterTable WRITE");
$tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
$dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
"SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
'GROUP BY hc_id');
$dbw->query("DELETE FROM $hitcounterTable");
if ($wgDBtype == 'mysql') {
$dbw->query('UNLOCK TABLES');
$dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
'WHERE page_id = hc_id');
}
else {
$dbw->query("UPDATE $pageTable SET page_counter=page_counter + hc_n ".
"FROM $acchitsTable WHERE page_id = hc_id");
}
$dbw->query("DROP TABLE $acchitsTable");
ignore_user_abort( $old_user_abort );
wfProfileOut( 'Article::incViewCount-collect' );
}
$dbw->ignoreErrors( $oldignore );
}
/**#@+
* The onArticle*() functions are supposed to be a kind of hooks
* which should be called whenever any of the specified actions
* are done.
*
* This is a good place to put code to clear caches, for instance.
*
* This is called on page move and undelete, as well as edit
* @static
* @param $title_obj a title object
*/
static function onArticleCreate($title) {
# The talk page isn't in the regular link tables, so we need to update manually:
if ( $title->isTalkPage() ) {
$other = $title->getSubjectPage();
} else {
$other = $title->getTalkPage();
}
$other->invalidateCache();
$other->purgeSquid();
$title->touchLinks();
$title->purgeSquid();
$title->deleteTitleProtection();
}
static function onArticleDelete( $title ) {
global $wgUseFileCache, $wgMessageCache;
$title->touchLinks();
$title->purgeSquid();
# File cache
if ( $wgUseFileCache ) {
$cm = new HTMLFileCache( $title );
@unlink( $cm->fileCacheName() );
}
if( $title->getNamespace() == NS_MEDIAWIKI) {
$wgMessageCache->replace( $title->getDBkey(), false );
}
}
/**
* Purge caches on page update etc
*/
static function onArticleEdit( $title ) {
global $wgDeferredUpdateList, $wgUseFileCache;
// Invalidate caches of articles which include this page
$update = new HTMLCacheUpdate( $title, 'templatelinks' );
$wgDeferredUpdateList[] = $update;
# Purge squid for this page only
$title->purgeSquid();
# Clear file cache
if ( $wgUseFileCache ) {
$cm = new HTMLFileCache( $title );
@unlink( $cm->fileCacheName() );
}
}
/**#@-*/
/**
* Info about this page
* Called for ?action=info when $wgAllowPageInfo is on.
*
* @public
*/
function info() {
global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
if ( !$wgAllowPageInfo ) {
$wgOut->showErrorPage( 'nosuchaction', 'nosuchactiontext' );
return;
}
$page = $this->mTitle->getSubjectPage();
$wgOut->setPagetitle( $page->getPrefixedText() );
$wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
$wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
if( !$this->mTitle->exists() ) {
$wgOut->addHtml( '
' );
if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
// This doesn't quite make sense; the user is asking for
// information about the _page_, not the message... -- RC
$wgOut->addHtml( htmlspecialchars( wfMsgWeirdKey( $this->mTitle->getText() ) ) );
} else {
$msg = $wgUser->isLoggedIn()
? 'noarticletext'
: 'noarticletextanon';
$wgOut->addHtml( wfMsgExt( $msg, 'parse' ) );
}
$wgOut->addHtml( '
' );
}
}
/**
* Return the total number of edits and number of unique editors
* on a given page. If page does not exist, returns false.
*
* @param Title $title
* @return array
* @private
*/
function pageCountInfo( $title ) {
$id = $title->getArticleId();
if( $id == 0 ) {
return false;
}
$dbr = wfGetDB( DB_SLAVE );
$rev_clause = array( 'rev_page' => $id );
$edits = $dbr->selectField(
'revision',
'COUNT(rev_page)',
$rev_clause,
__METHOD__,
$this->getSelectOptions() );
$authors = $dbr->selectField(
'revision',
'COUNT(DISTINCT rev_user_text)',
$rev_clause,
__METHOD__,
$this->getSelectOptions() );
return array( 'edits' => $edits, 'authors' => $authors );
}
/**
* Return a list of templates used by this article.
* Uses the templatelinks table
*
* @return array Array of Title objects
*/
function getUsedTemplates() {
$result = array();
$id = $this->mTitle->getArticleID();
if( $id == 0 ) {
return array();
}
$dbr = wfGetDB( DB_SLAVE );
$res = $dbr->select( array( 'templatelinks' ),
array( 'tl_namespace', 'tl_title' ),
array( 'tl_from' => $id ),
'Article:getUsedTemplates' );
if ( false !== $res ) {
if ( $dbr->numRows( $res ) ) {
while ( $row = $dbr->fetchObject( $res ) ) {
$result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
}
}
}
$dbr->freeResult( $res );
return $result;
}
/**
* Return an auto-generated summary if the text provided is a redirect.
*
* @param string $text The wikitext to check
* @return string '' or an appropriate summary
*/
public static function getRedirectAutosummary( $text ) {
$rt = Title::newFromRedirect( $text );
if( is_object( $rt ) )
return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
else
return '';
}
/**
* Return an auto-generated summary if the new text is much shorter than
* the old text.
*
* @param string $oldtext The previous text of the page
* @param string $text The submitted text of the page
* @return string An appropriate autosummary, or an empty string.
*/
public static function getBlankingAutosummary( $oldtext, $text ) {
if ($oldtext!='' && $text=='') {
return wfMsgForContent('autosumm-blank');
} elseif (strlen($oldtext) > 10 * strlen($text) && strlen($text) < 500) {
#Removing more than 90% of the article
global $wgContLang;
$truncatedtext = $wgContLang->truncate($text, max(0, 200 - strlen(wfMsgForContent('autosumm-replace'))), '...');
return wfMsgForContent('autosumm-replace', $truncatedtext);
} else {
return '';
}
}
/**
* Return an applicable autosummary if one exists for the given edit.
* @param string $oldtext The previous text of the page.
* @param string $newtext The submitted text of the page.
* @param bitmask $flags A bitmask of flags submitted for the edit.
* @return string An appropriate autosummary, or an empty string.
*/
public static function getAutosummary( $oldtext, $newtext, $flags ) {
# This code is UGLY UGLY UGLY.
# Somebody PLEASE come up with a more elegant way to do it.
#Redirect autosummaries
$summary = self::getRedirectAutosummary( $newtext );
if ($summary)
return $summary;
#Blanking autosummaries
if (!($flags & EDIT_NEW))
$summary = self::getBlankingAutosummary( $oldtext, $newtext );
if ($summary)
return $summary;
#New page autosummaries
if ($flags & EDIT_NEW && strlen($newtext)) {
#If they're making a new article, give its text, truncated, in the summary.
global $wgContLang;
$truncatedtext = $wgContLang->truncate(
str_replace("\n", ' ', $newtext),
max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
'...' );
$summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
}
if ($summary)
return $summary;
return $summary;
}
/**
* Add the primary page-view wikitext to the output buffer
* Saves the text into the parser cache if possible.
* Updates templatelinks if it is out of date.
*
* @param string $text
* @param bool $cache
*/
public function outputWikiText( $text, $cache = true ) {
global $wgParser, $wgUser, $wgOut;
$popts = $wgOut->parserOptions();
$popts->setTidy(true);
$popts->enableLimitReport();
$parserOutput = $wgParser->parse( $text, $this->mTitle,
$popts, true, true, $this->getRevIdFetched() );
$popts->setTidy(false);
$popts->enableLimitReport( false );
if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
$parserCache =& ParserCache::singleton();
$parserCache->save( $parserOutput, $this, $wgUser );
}
if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
// templatelinks table may have become out of sync,
// especially if using variable-based transclusions.
// For paranoia, check if things have changed and if
// so apply updates to the database. This will ensure
// that cascaded protections apply as soon as the changes
// are visible.
# Get templates from templatelinks
$id = $this->mTitle->getArticleID();
$tlTemplates = array();
$dbr = wfGetDB( DB_SLAVE );
$res = $dbr->select( array( 'templatelinks' ),
array( 'tl_namespace', 'tl_title' ),
array( 'tl_from' => $id ),
'Article:getUsedTemplates' );
global $wgContLang;
if ( false !== $res ) {
if ( $dbr->numRows( $res ) ) {
while ( $row = $dbr->fetchObject( $res ) ) {
$tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
}
}
}
# Get templates from parser output.
$poTemplates_allns = $parserOutput->getTemplates();
$poTemplates = array ();
foreach ( $poTemplates_allns as $ns_templates ) {
$poTemplates = array_merge( $poTemplates, $ns_templates );
}
# Get the diff
$templates_diff = array_diff( $poTemplates, $tlTemplates );
if ( count( $templates_diff ) > 0 ) {
# Whee, link updates time.
$u = new LinksUpdate( $this->mTitle, $parserOutput );
$dbw = wfGetDb( DB_MASTER );
$dbw->begin();
$u->doUpdate();
$dbw->commit();
}
}
$wgOut->addParserOutput( $parserOutput );
}
}