diff options
author | Pierre Schmitz <pierre@archlinux.de> | 2014-12-27 15:41:37 +0100 |
---|---|---|
committer | Pierre Schmitz <pierre@archlinux.de> | 2014-12-31 11:43:28 +0100 |
commit | c1f9b1f7b1b77776192048005dcc66dcf3df2bfb (patch) | |
tree | 2b38796e738dd74cb42ecd9bfd151803108386bc /includes/Title.php | |
parent | b88ab0086858470dd1f644e64cb4e4f62bb2be9b (diff) |
Update to MediaWiki 1.24.1
Diffstat (limited to 'includes/Title.php')
-rw-r--r-- | includes/Title.php | 1932 |
1 files changed, 925 insertions, 1007 deletions
diff --git a/includes/Title.php b/includes/Title.php index 21872e45..74d78ba5 100644 --- a/includes/Title.php +++ b/includes/Title.php @@ -1,6 +1,6 @@ <?php /** - * Representation a title within %MediaWiki. + * Representation of a title within %MediaWiki. * * See title.txt * @@ -27,14 +27,14 @@ * Optionally may contain an interwiki designation or namespace. * @note This class can fetch various kinds of data from the database; * however, it does so inefficiently. + * @note Consider using a TitleValue object instead. TitleValue is more lightweight + * and does not rely on global state or the database. * * @internal documentation reviewed 15 Mar 2010 */ class Title { - /** @name Static cache variables */ - // @{ - static private $titleCache = array(); - // @} + /** @var MapCacheLRU */ + static private $titleCache = null; /** * Title::newFromText maintains a cache to avoid expensive re-normalization of @@ -56,50 +56,173 @@ class Title { */ // @{ - var $mTextform = ''; // /< Text form (spaces not underscores) of the main part - var $mUrlform = ''; // /< URL-encoded form of the main part - var $mDbkeyform = ''; // /< Main part with underscores - var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user - var $mNamespace = NS_MAIN; // /< Namespace index, i.e. one of the NS_xxxx constants - var $mInterwiki = ''; // /< Interwiki prefix (or null string) - var $mFragment; // /< Title fragment (i.e. the bit after the #) - var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand - var $mLatestID = false; // /< ID of most recent revision - var $mContentModel = false; // /< ID of the page's content model, i.e. one of the CONTENT_MODEL_XXX constants - private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded - var $mRestrictions = array(); // /< Array of groups allowed to edit this article - var $mOldRestrictions = false; - var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images? - var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources - var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire? - var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page? - var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page? - var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand - var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand - var $mTitleProtection; ///< Cached value for getTitleProtection (create protection) - # Don't change the following default, NS_MAIN is hardcoded in several - # places. See bug 696. - var $mDefaultNamespace = NS_MAIN; // /< Namespace index when there is no namespace - # Zero except in {{transclusion}} tags - var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching() - var $mLength = -1; // /< The page length, 0 for special pages - var $mRedirect = null; // /< Is the article at this title a redirect? - var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false - var $mHasSubpage; // /< Whether a page has any subpages + /** @var string Text form (spaces not underscores) of the main part */ + public $mTextform = ''; + + /** @var string URL-encoded form of the main part */ + public $mUrlform = ''; + + /** @var string Main part with underscores */ + public $mDbkeyform = ''; + + /** @var string Database key with the initial letter in the case specified by the user */ + protected $mUserCaseDBKey; + + /** @var int Namespace index, i.e. one of the NS_xxxx constants */ + public $mNamespace = NS_MAIN; + + /** @var string Interwiki prefix */ + public $mInterwiki = ''; + + /** @var bool Was this Title created from a string with a local interwiki prefix? */ + private $mLocalInterwiki = false; + + /** @var string Title fragment (i.e. the bit after the #) */ + public $mFragment = ''; + + /** @var int Article ID, fetched from the link cache on demand */ + public $mArticleID = -1; + + /** @var bool|int ID of most recent revision */ + protected $mLatestID = false; + + /** + * @var bool|string ID of the page's content model, i.e. one of the + * CONTENT_MODEL_XXX constants + */ + public $mContentModel = false; + + /** @var int Estimated number of revisions; null of not loaded */ + private $mEstimateRevisions; + + /** @var array Array of groups allowed to edit this article */ + public $mRestrictions = array(); + + /** @var bool */ + protected $mOldRestrictions = false; + + /** @var bool Cascade restrictions on this page to included templates and images? */ + public $mCascadeRestriction; + + /** Caching the results of getCascadeProtectionSources */ + public $mCascadingRestrictions; + + /** @var array When do the restrictions on this page expire? */ + protected $mRestrictionsExpiry = array(); + + /** @var bool Are cascading restrictions in effect on this page? */ + protected $mHasCascadingRestrictions; + + /** @var array Where are the cascading restrictions coming from on this page? */ + public $mCascadeSources; + + /** @var bool Boolean for initialisation on demand */ + public $mRestrictionsLoaded = false; + + /** @var string Text form including namespace/interwiki, initialised on demand */ + protected $mPrefixedText = null; + + /** @var mixed Cached value for getTitleProtection (create protection) */ + public $mTitleProtection; + + /** + * @var int Namespace index when there is no namespace. Don't change the + * following default, NS_MAIN is hardcoded in several places. See bug 696. + * Zero except in {{transclusion}} tags. + */ + public $mDefaultNamespace = NS_MAIN; + + /** + * @var bool Is $wgUser watching this page? null if unfilled, accessed + * through userIsWatching() + */ + protected $mWatched = null; + + /** @var int The page length, 0 for special pages */ + protected $mLength = -1; + + /** @var null Is the article at this title a redirect? */ + public $mRedirect = null; + + /** @var array Associative array of user ID -> timestamp/false */ + private $mNotificationTimestamp = array(); + + /** @var bool Whether a page has any subpages */ + private $mHasSubpages; + + /** @var bool The (string) language code of the page's language and content code. */ + private $mPageLanguage = false; + + /** @var string The page language code from the database */ + private $mDbPageLanguage = null; + + /** @var TitleValue A corresponding TitleValue object */ + private $mTitleValue = null; + + /** @var bool Would deleting this page be a big deletion? */ + private $mIsBigDeletion = null; // @} /** - * Constructor + * B/C kludge: provide a TitleParser for use by Title. + * Ideally, Title would have no methods that need this. + * Avoid usage of this singleton by using TitleValue + * and the associated services when possible. + * + * @return TitleParser */ - /*protected*/ function __construct() { } + private static function getTitleParser() { + global $wgContLang, $wgLocalInterwikis; + + static $titleCodec = null; + static $titleCodecFingerprint = null; + + // $wgContLang and $wgLocalInterwikis may change (especially while testing), + // make sure we are using the right one. To detect changes over the course + // of a request, we remember a fingerprint of the config used to create the + // codec singleton, and re-create it if the fingerprint doesn't match. + $fingerprint = spl_object_hash( $wgContLang ) . '|' . join( '+', $wgLocalInterwikis ); + + if ( $fingerprint !== $titleCodecFingerprint ) { + $titleCodec = null; + } + + if ( !$titleCodec ) { + $titleCodec = new MediaWikiTitleCodec( + $wgContLang, + GenderCache::singleton(), + $wgLocalInterwikis + ); + $titleCodecFingerprint = $fingerprint; + } + + return $titleCodec; + } + + /** + * B/C kludge: provide a TitleParser for use by Title. + * Ideally, Title would have no methods that need this. + * Avoid usage of this singleton by using TitleValue + * and the associated services when possible. + * + * @return TitleFormatter + */ + private static function getTitleFormatter() { + //NOTE: we know that getTitleParser() returns a MediaWikiTitleCodec, + // which implements TitleFormatter. + return self::getTitleParser(); + } + + function __construct() { + } /** * Create a new Title from a prefixed DB key * - * @param string $key the database key, which has underscores + * @param string $key The database key, which has underscores * instead of spaces, possibly including namespace and * interwiki prefixes - * @return Title, or NULL on an error + * @return Title|null Title, or null on an error */ public static function newFromDBkey( $key ) { $t = new Title(); @@ -112,23 +235,39 @@ class Title { } /** + * Create a new Title from a TitleValue + * + * @param TitleValue $titleValue Assumed to be safe. + * + * @return Title + */ + public static function newFromTitleValue( TitleValue $titleValue ) { + return self::makeTitle( + $titleValue->getNamespace(), + $titleValue->getText(), + $titleValue->getFragment() ); + } + + /** * Create a new Title from text, such as what one would find in a link. De- * codes any HTML entities in the text. * - * @param string $text the link text; spaces, prefixes, and an + * @param string $text The link text; spaces, prefixes, and an * initial ':' indicating the main namespace are accepted. - * @param int $defaultNamespace the namespace to use if none is specified + * @param int $defaultNamespace The namespace to use if none is specified * by a prefix. If you want to force a specific namespace even if * $text might begin with a namespace prefix, use makeTitle() or * makeTitleSafe(). * @throws MWException - * @return Title|null - Title or null on an error. + * @return Title|null Title or null on an error. */ public static function newFromText( $text, $defaultNamespace = NS_MAIN ) { if ( is_object( $text ) ) { throw new MWException( 'Title::newFromText given an object' ); } + $cache = self::getTitleCache(); + /** * Wiki pages often contain multiple links to the same page. * Title normalization and parsing can become expensive on @@ -137,8 +276,8 @@ class Title { * * In theory these are value objects and won't get changed... */ - if ( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) { - return Title::$titleCache[$text]; + if ( $defaultNamespace == NS_MAIN && $cache->has( $text ) ) { + return $cache->get( $text ); } # Convert things like é ā or 〗 into normalized (bug 14952) text @@ -146,23 +285,15 @@ class Title { $t = new Title(); $t->mDbkeyform = str_replace( ' ', '_', $filteredText ); - $t->mDefaultNamespace = $defaultNamespace; + $t->mDefaultNamespace = intval( $defaultNamespace ); - static $cachedcount = 0; if ( $t->secureAndSplit() ) { if ( $defaultNamespace == NS_MAIN ) { - if ( $cachedcount >= self::CACHE_MAX ) { - # Avoid memory leaks on mass operations... - Title::$titleCache = array(); - $cachedcount = 0; - } - $cachedcount++; - Title::$titleCache[$text] =& $t; + $cache->set( $text, $t ); } return $t; } else { - $ret = null; - return $ret; + return null; } } @@ -178,8 +309,8 @@ class Title { * Create a new Title from URL-encoded text. Ensures that * the given title's length does not exceed the maximum. * - * @param string $url the title, as might be taken from a URL - * @return Title the new object, or NULL on an error + * @param string $url The title, as might be taken from a URL + * @return Title|null The new object, or null on an error */ public static function newFromURL( $url ) { $t = new Title(); @@ -200,8 +331,19 @@ class Title { } /** - * Returns a list of fields that are to be selected for initializing Title objects or LinkCache entries. - * Uses $wgContentHandlerUseDB to determine whether to include page_content_model. + * @return MapCacheLRU + */ + private static function getTitleCache() { + if ( self::$titleCache == null ) { + self::$titleCache = new MapCacheLRU( self::CACHE_MAX ); + } + return self::$titleCache; + } + + /** + * Returns a list of fields that are to be selected for initializing Title + * objects or LinkCache entries. Uses $wgContentHandlerUseDB to determine + * whether to include page_content_model. * * @return array */ @@ -223,9 +365,9 @@ class Title { /** * Create a new Title from an article ID * - * @param int $id the page_id corresponding to the Title to create - * @param int $flags use Title::GAID_FOR_UPDATE to use master - * @return Title|null the new object, or NULL on an error + * @param int $id The page_id corresponding to the Title to create + * @param int $flags Use Title::GAID_FOR_UPDATE to use master + * @return Title|null The new object, or null on an error */ public static function newFromID( $id, $flags = 0 ) { $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE ); @@ -246,8 +388,8 @@ class Title { /** * Make an array of titles from an array of IDs * - * @param array $ids of Int Array of IDs - * @return Array of Titles + * @param int[] $ids Array of IDs + * @return Title[] Array of Titles */ public static function newFromIDs( $ids ) { if ( !count( $ids ) ) { @@ -272,8 +414,8 @@ class Title { /** * Make a Title object from a DB row * - * @param $row Object database row (needs at least page_title,page_namespace) - * @return Title corresponding Title + * @param stdClass $row Object database row (needs at least page_title,page_namespace) + * @return Title Corresponding Title */ public static function newFromRow( $row ) { $t = self::makeTitle( $row->page_namespace, $row->page_title ); @@ -285,7 +427,7 @@ class Title { * Load Title object fields from a DB row. * If false is given, the title will be treated as non-existing. * - * @param $row Object|bool database row + * @param stdClass|bool $row Database row */ public function loadFromRow( $row ) { if ( $row ) { // page found @@ -306,6 +448,9 @@ class Title { } else { $this->mContentModel = false; # initialized lazily in getContentModel() } + if ( isset( $row->page_lang ) ) { + $this->mDbPageLanguage = (string)$row->page_lang; + } } else { // page not found $this->mArticleID = 0; $this->mLength = 0; @@ -322,11 +467,11 @@ class Title { * For convenience, spaces are converted to underscores so that * eg user_text fields can be used directly. * - * @param int $ns the namespace of the article - * @param string $title the unprefixed database key form - * @param string $fragment the link fragment (after the "#") - * @param string $interwiki the interwiki prefix - * @return Title the new object + * @param int $ns The namespace of the article + * @param string $title The unprefixed database key form + * @param string $fragment The link fragment (after the "#") + * @param string $interwiki The interwiki prefix + * @return Title The new object */ public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) { $t = new Title(); @@ -346,11 +491,11 @@ class Title { * The parameters will be checked for validity, which is a bit slower * than makeTitle() but safer for user-provided data. * - * @param int $ns the namespace of the article - * @param string $title database key form - * @param string $fragment the link fragment (after the "#") - * @param string $interwiki interwiki prefix - * @return Title the new object, or NULL on an error + * @param int $ns The namespace of the article + * @param string $title Database key form + * @param string $fragment The link fragment (after the "#") + * @param string $interwiki Interwiki prefix + * @return Title The new object, or null on an error */ public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) { if ( !MWNamespace::exists( $ns ) ) { @@ -369,7 +514,7 @@ class Title { /** * Create a new Title for the Main Page * - * @return Title the new object + * @return Title The new object */ public static function newMainPage() { $title = Title::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() ); @@ -387,7 +532,7 @@ class Title { * the redirect table and other checks that don't need full recursion * * @param string $text Text with possible redirect - * @return Title: The corresponding Title + * @return Title The corresponding Title * @deprecated since 1.21, use Content::getRedirectTarget instead. */ public static function newFromRedirect( $text ) { @@ -421,7 +566,7 @@ class Title { * have been resolved (up to $wgMaxRedirects times) * * @param string $text Text with possible redirect - * @return Array of Titles, with the destination last + * @return Title[] Array of Titles, with the destination last * @deprecated since 1.21, use Content::getRedirectChain instead. */ public static function newFromRedirectArray( $text ) { @@ -434,8 +579,8 @@ class Title { /** * Get the prefixed DB key associated with an ID * - * @param int $id the page_id of the article - * @return Title an object representing the article, or NULL if no such article was found + * @param int $id The page_id of the article + * @return Title|null An object representing the article, or null if no such article was found */ public static function nameOf( $id ) { $dbr = wfGetDB( DB_SLAVE ); @@ -457,7 +602,7 @@ class Title { /** * Get a regex character class describing the legal characters in a link * - * @return String the list of characters, not delimited + * @return string The list of characters, not delimited */ public static function legalChars() { global $wgLegalTitleChars; @@ -469,7 +614,9 @@ class Title { * Note that this doesn't pick up many things that could be wrong with titles, but that * replacing this regex with something valid will make many titles valid. * - * @return String regex string + * @todo move this into MediaWikiTitleCodec + * + * @return string Regex string */ static function getTitleInvalidRegex() { static $rxTc = false; @@ -594,41 +741,13 @@ class Title { } /** - * Get a string representation of a title suitable for - * including in a search index - * - * @param int $ns a namespace index - * @param string $title text-form main part - * @return String a stripped-down title string ready for the search index - */ - public static function indexTitle( $ns, $title ) { - global $wgContLang; - - $lc = SearchEngine::legalSearchChars() . '&#;'; - $t = $wgContLang->normalizeForSearch( $title ); - $t = preg_replace( "/[^{$lc}]+/", ' ', $t ); - $t = $wgContLang->lc( $t ); - - # Handle 's, s' - $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t ); - $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t ); - - $t = preg_replace( "/\\s+/", ' ', $t ); - - if ( $ns == NS_FILE ) { - $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t ); - } - return trim( $t ); - } - - /** * Make a prefixed DB key from a DB key and a namespace index * - * @param int $ns numerical representation of the namespace - * @param string $title the DB key form the title + * @param int $ns Numerical representation of the namespace + * @param string $title The DB key form the title * @param string $fragment The link fragment (after the "#") * @param string $interwiki The interwiki prefix - * @return String the prefixed form of the title + * @return string The prefixed form of the title */ public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) { global $wgContLang; @@ -647,8 +766,8 @@ class Title { /** * Escape a text fragment, say from a link, for a URL * - * @param string $fragment containing a URL or link fragment (after the "#") - * @return String: escaped string + * @param string $fragment Containing a URL or link fragment (after the "#") + * @return string Escaped string */ static function escapeFragmentForURL( $fragment ) { # Note that we don't urlencode the fragment. urlencoded Unicode @@ -661,10 +780,10 @@ class Title { /** * Callback for usort() to do title sorts by (namespace, title) * - * @param $a Title - * @param $b Title + * @param Title $a + * @param Title $b * - * @return Integer: result of string comparison, or namespace comparison + * @return int Result of string comparison, or namespace comparison */ public static function compare( $a, $b ) { if ( $a->getNamespace() == $b->getNamespace() ) { @@ -678,10 +797,10 @@ class Title { * Determine whether the object refers to a page within * this project. * - * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise + * @return bool True if this is an in-project interwiki link or a wikilink, false otherwise */ public function isLocal() { - if ( $this->mInterwiki != '' ) { + if ( $this->isExternal() ) { $iw = Interwiki::fetch( $this->mInterwiki ); if ( $iw ) { return $iw->isLocal(); @@ -693,29 +812,40 @@ class Title { /** * Is this Title interwiki? * - * @return Bool + * @return bool */ public function isExternal() { - return ( $this->mInterwiki != '' ); + return $this->mInterwiki !== ''; } /** - * Get the interwiki prefix (or null string) + * Get the interwiki prefix * - * @return String Interwiki prefix + * Use Title::isExternal to check if a interwiki is set + * + * @return string Interwiki prefix */ public function getInterwiki() { return $this->mInterwiki; } /** + * Was this a local interwiki link? + * + * @return bool + */ + public function wasLocalInterwiki() { + return $this->mLocalInterwiki; + } + + /** * Determine whether the object refers to a page within * this project and is transcludable. * - * @return Bool TRUE if this is transcludable + * @return bool True if this is transcludable */ public function isTrans() { - if ( $this->mInterwiki == '' ) { + if ( !$this->isExternal() ) { return false; } @@ -725,10 +855,10 @@ class Title { /** * Returns the DB name of the distant wiki which owns the object. * - * @return String the DB name + * @return string The DB name */ public function getTransWikiID() { - if ( $this->mInterwiki == '' ) { + if ( !$this->isExternal() ) { return false; } @@ -736,9 +866,34 @@ class Title { } /** + * Get a TitleValue object representing this Title. + * + * @note Not all valid Titles have a corresponding valid TitleValue + * (e.g. TitleValues cannot represent page-local links that have a + * fragment but no title text). + * + * @return TitleValue|null + */ + public function getTitleValue() { + if ( $this->mTitleValue === null ) { + try { + $this->mTitleValue = new TitleValue( + $this->getNamespace(), + $this->getDBkey(), + $this->getFragment() ); + } catch ( InvalidArgumentException $ex ) { + wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' . + $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" ); + } + } + + return $this->mTitleValue; + } + + /** * Get the text form (spaces not underscores) of the main part * - * @return String Main part of the title + * @return string Main part of the title */ public function getText() { return $this->mTextform; @@ -747,7 +902,7 @@ class Title { /** * Get the URL-encoded form of the main part * - * @return String Main part of the title, URL-encoded + * @return string Main part of the title, URL-encoded */ public function getPartialURL() { return $this->mUrlform; @@ -756,7 +911,7 @@ class Title { /** * Get the main part with underscores * - * @return String: Main part of the title, with underscores + * @return string Main part of the title, with underscores */ public function getDBkey() { return $this->mDbkeyform; @@ -765,16 +920,21 @@ class Title { /** * Get the DB key with the initial letter case as specified by the user * - * @return String DB key + * @return string DB key */ function getUserCaseDBKey() { - return $this->mUserCaseDBKey; + if ( !is_null( $this->mUserCaseDBKey ) ) { + return $this->mUserCaseDBKey; + } else { + // If created via makeTitle(), $this->mUserCaseDBKey is not set. + return $this->mDbkeyform; + } } /** * Get the namespace index, i.e. one of the NS_xxxx constants. * - * @return Integer: Namespace index + * @return int Namespace index */ public function getNamespace() { return $this->mNamespace; @@ -784,10 +944,12 @@ class Title { * Get the page's content model id, see the CONTENT_MODEL_XXX constants. * * @throws MWException - * @return String: Content model id + * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update + * @return string Content model id */ - public function getContentModel() { - if ( !$this->mContentModel ) { + public function getContentModel( $flags = 0 ) { + # Calling getArticleID() loads the field from cache as needed + if ( !$this->mContentModel && $this->getArticleID( $flags ) ) { $linkCache = LinkCache::singleton(); $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' ); } @@ -807,7 +969,7 @@ class Title { * Convenience method for checking a title's content model name * * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants). - * @return Boolean true if $this->getContentModel() == $id + * @return bool True if $this->getContentModel() == $id */ public function hasContentModel( $id ) { return $this->getContentModel() == $id; @@ -816,12 +978,10 @@ class Title { /** * Get the namespace text * - * @return String: Namespace text + * @return string Namespace text */ public function getNsText() { - global $wgContLang; - - if ( $this->mInterwiki != '' ) { + if ( $this->isExternal() ) { // This probably shouldn't even happen. ohh man, oh yuck. // But for interwiki transclusion it sometimes does. // Shit. Shit shit shit. @@ -833,19 +993,19 @@ class Title { } } - if ( $wgContLang->needsGenderDistinction() && - MWNamespace::hasGenderDistinction( $this->mNamespace ) ) { - $gender = GenderCache::singleton()->getGenderOf( $this->getText(), __METHOD__ ); - return $wgContLang->getGenderNsText( $this->mNamespace, $gender ); + try { + $formatter = self::getTitleFormatter(); + return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform ); + } catch ( InvalidArgumentException $ex ) { + wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" ); + return false; } - - return $wgContLang->getNsText( $this->mNamespace ); } /** * Get the namespace text of the subject (rather than talk) page * - * @return String Namespace text + * @return string Namespace text */ public function getSubjectNsText() { global $wgContLang; @@ -855,7 +1015,7 @@ class Title { /** * Get the namespace text of the talk page * - * @return String Namespace text + * @return string Namespace text */ public function getTalkNsText() { global $wgContLang; @@ -865,7 +1025,7 @@ class Title { /** * Could this title have a corresponding talk page? * - * @return Bool TRUE or FALSE + * @return bool */ public function canTalk() { return MWNamespace::canTalk( $this->mNamespace ); @@ -874,7 +1034,7 @@ class Title { /** * Is this in a namespace that allows actual pages? * - * @return Bool + * @return bool * @internal note -- uses hardcoded namespace index instead of constants */ public function canExist() { @@ -884,7 +1044,7 @@ class Title { /** * Can this title be added to a user's watchlist? * - * @return Bool TRUE or FALSE + * @return bool */ public function isWatchable() { return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() ); @@ -893,7 +1053,7 @@ class Title { /** * Returns true if this is a special page. * - * @return boolean + * @return bool */ public function isSpecialPage() { return $this->getNamespace() == NS_SPECIAL; @@ -903,7 +1063,7 @@ class Title { * Returns true if this title resolves to the named special page * * @param string $name The special page name - * @return boolean + * @return bool */ public function isSpecial( $name ) { if ( $this->isSpecialPage() ) { @@ -951,7 +1111,7 @@ class Title { /** * Returns true if the title is inside one of the specified namespaces. * - * @param ...$namespaces The namespaces to check for + * @param int $namespaces,... The namespaces to check for * @return bool * @since 1.19 */ @@ -980,7 +1140,7 @@ class Title { * This is MUCH simpler than individually testing for equivalence * against both NS_USER and NS_USER_TALK, and is also forward compatible. * @since 1.19 - * @param $ns int + * @param int $ns * @return bool */ public function hasSubjectNamespace( $ns ) { @@ -992,7 +1152,7 @@ class Title { * In other words, is this a content page, for the purposes of calculating * statistics, etc? * - * @return Boolean + * @return bool */ public function isContentPage() { return MWNamespace::isContent( $this->getNamespace() ); @@ -1002,10 +1162,10 @@ class Title { * Would anybody with sufficient privileges be able to move this page? * Some pages just aren't movable. * - * @return Bool TRUE or FALSE + * @return bool */ public function isMovable() { - if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->getInterwiki() != '' ) { + if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->isExternal() ) { // Interwiki title or immovable namespace. Hooks don't get to override here return false; } @@ -1023,7 +1183,7 @@ class Title { * ends up reporting something differently than $title->isMainPage(); * * @since 1.18 - * @return Bool + * @return bool */ public function isMainPage() { return $this->equals( Title::newMainPage() ); @@ -1032,7 +1192,7 @@ class Title { /** * Is this a subpage? * - * @return Bool + * @return bool */ public function isSubpage() { return MWNamespace::hasSubpages( $this->mNamespace ) @@ -1043,7 +1203,7 @@ class Title { /** * Is this a conversion table for the LanguageConverter? * - * @return Bool + * @return bool */ public function isConversionTable() { // @todo ConversionTable should become a separate content model. @@ -1055,7 +1215,7 @@ class Title { /** * Does that page contain wikitext, or it is JS, CSS or whatever? * - * @return Bool + * @return bool */ public function isWikitextPage() { return $this->hasContentModel( CONTENT_MODEL_WIKITEXT ); @@ -1066,19 +1226,22 @@ class Title { * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS * or CONTENT_MODEL_JAVASCRIPT. * - * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage() for that! + * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage() + * for that! * - * Note that this method should not return true for pages that contain and show "inactive" CSS or JS. + * Note that this method should not return true for pages that contain and + * show "inactive" CSS or JS. * - * @return Bool + * @return bool */ public function isCssOrJsPage() { $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace && ( $this->hasContentModel( CONTENT_MODEL_CSS ) || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ); - #NOTE: this hook is also called in ContentHandler::getDefaultModel. It's called here again to make sure - # hook functions can force this method to return true even outside the mediawiki namespace. + # @note This hook is also called in ContentHandler::getDefaultModel. + # It's called here again to make sure hook functions can force this + # method to return true even outside the mediawiki namespace. wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) ); @@ -1087,7 +1250,7 @@ class Title { /** * Is this a .css or .js subpage of a user page? - * @return Bool + * @return bool */ public function isCssJsSubpage() { return ( NS_USER == $this->mNamespace && $this->isSubpage() @@ -1098,7 +1261,7 @@ class Title { /** * Trim down a .css or .js subpage title to get the corresponding skin name * - * @return string containing skin name from .css or .js subpage title + * @return string Containing skin name from .css or .js subpage title */ public function getSkinFromCssJsSubpage() { $subpage = explode( '/', $this->mTextform ); @@ -1113,7 +1276,7 @@ class Title { /** * Is this a .css subpage of a user page? * - * @return Bool + * @return bool */ public function isCssSubpage() { return ( NS_USER == $this->mNamespace && $this->isSubpage() @@ -1123,7 +1286,7 @@ class Title { /** * Is this a .js subpage of a user page? * - * @return Bool + * @return bool */ public function isJsSubpage() { return ( NS_USER == $this->mNamespace && $this->isSubpage() @@ -1133,7 +1296,7 @@ class Title { /** * Is this a talk page of some sort? * - * @return Bool + * @return bool */ public function isTalkPage() { return MWNamespace::isTalk( $this->getNamespace() ); @@ -1142,7 +1305,7 @@ class Title { /** * Get a Title object associated with the talk page of this article * - * @return Title the object for the talk page + * @return Title The object for the talk page */ public function getTalkPage() { return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() ); @@ -1152,7 +1315,7 @@ class Title { * Get a title object associated with the subject page of this * talk page * - * @return Title the object for the subject page + * @return Title The object for the subject page */ public function getSubjectPage() { // Is this the same title? @@ -1166,40 +1329,42 @@ class Title { /** * Get the default namespace index, for when there is no namespace * - * @return Int Default namespace index + * @return int Default namespace index */ public function getDefaultNamespace() { return $this->mDefaultNamespace; } /** - * Get title for search index + * Get the Title fragment (i.e.\ the bit after the #) in text form * - * @return String a stripped-down title string ready for the - * search index + * Use Title::hasFragment to check for a fragment + * + * @return string Title fragment */ - public function getIndexTitle() { - return Title::indexTitle( $this->mNamespace, $this->mTextform ); + public function getFragment() { + return $this->mFragment; } /** - * Get the Title fragment (i.e.\ the bit after the #) in text form + * Check if a Title fragment is set * - * @return String Title fragment + * @return bool + * @since 1.23 */ - public function getFragment() { - return $this->mFragment; + public function hasFragment() { + return $this->mFragment !== ''; } /** * Get the fragment in URL form, including the "#" character if there is one - * @return String Fragment in URL form + * @return string Fragment in URL form */ public function getFragmentForURL() { - if ( $this->mFragment == '' ) { + if ( !$this->hasFragment() ) { return ''; } else { - return '#' . Title::escapeFragmentForURL( $this->mFragment ); + return '#' . Title::escapeFragmentForURL( $this->getFragment() ); } } @@ -1211,7 +1376,7 @@ class Title { * Deprecated for public use, use Title::makeTitle() with fragment parameter. * Still in active use privately. * - * @param string $fragment text + * @param string $fragment Text */ public function setFragment( $fragment ) { $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) ); @@ -1221,13 +1386,12 @@ class Title { * Prefix some arbitrary text with the namespace or interwiki prefix * of this object * - * @param string $name the text - * @return String the prefixed text - * @private + * @param string $name The text + * @return string The prefixed text */ private function prefix( $name ) { $p = ''; - if ( $this->mInterwiki != '' ) { + if ( $this->isExternal() ) { $p = $this->mInterwiki . ':'; } @@ -1240,7 +1404,7 @@ class Title { /** * Get the prefixed database key form * - * @return String the prefixed title, with underscores and + * @return string The prefixed title, with underscores and * any interwiki and namespace prefixes */ public function getPrefixedDBkey() { @@ -1253,11 +1417,10 @@ class Title { * Get the prefixed title with spaces. * This is the form usually used for display * - * @return String the prefixed title, with spaces + * @return string The prefixed title, with spaces */ public function getPrefixedText() { - // @todo FIXME: Bad usage of empty() ? - if ( empty( $this->mPrefixedText ) ) { + if ( $this->mPrefixedText === null ) { $s = $this->prefix( $this->mTextform ); $s = str_replace( '_', ' ', $s ); $this->mPrefixedText = $s; @@ -1268,7 +1431,7 @@ class Title { /** * Return a string representation of this title * - * @return String representation of this title + * @return string Representation of this title */ public function __toString() { return $this->getPrefixedText(); @@ -1278,12 +1441,12 @@ class Title { * Get the prefixed title with spaces, plus any fragment * (part beginning with '#') * - * @return String the prefixed title, with spaces and the fragment, including '#' + * @return string The prefixed title, with spaces and the fragment, including '#' */ public function getFullText() { $text = $this->getPrefixedText(); - if ( $this->mFragment != '' ) { - $text .= '#' . $this->mFragment; + if ( $this->hasFragment() ) { + $text .= '#' . $this->getFragment(); } return $text; } @@ -1297,7 +1460,7 @@ class Title { * # returns: 'Foo' * @endcode * - * @return String Root name + * @return string Root name * @since 1.20 */ public function getRootText() { @@ -1333,7 +1496,7 @@ class Title { * # returns: 'Foo/Bar' * @endcode * - * @return String Base name + * @return string Base name */ public function getBaseText() { if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) { @@ -1373,7 +1536,7 @@ class Title { * # returns: "Baz" * @endcode * - * @return String Subpage name + * @return string Subpage name */ public function getSubpageText() { if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) { @@ -1401,21 +1564,9 @@ class Title { } /** - * Get the HTML-escaped displayable text form. - * Used for the title field in <a> tags. - * - * @return String the text, including any prefixes - * @deprecated since 1.19 - */ - public function getEscapedText() { - wfDeprecated( __METHOD__, '1.19' ); - return htmlspecialchars( $this->getPrefixedText() ); - } - - /** * Get a URL-encoded form of the subpage text * - * @return String URL-encoded subpage name + * @return string URL-encoded subpage name */ public function getSubpageUrlForm() { $text = $this->getSubpageText(); @@ -1426,7 +1577,7 @@ class Title { /** * Get a URL-encoded title (not an actual URL) including interwiki * - * @return String the URL-encoded form + * @return string The URL-encoded form */ public function getPrefixedURL() { $s = $this->prefix( $this->mDbkeyform ); @@ -1443,9 +1594,9 @@ class Title { * and the wfArrayToCgi moved to getLocalURL(); * * @since 1.19 (r105919) - * @param $query - * @param $query2 bool - * @return String + * @param array|string $query + * @param bool $query2 + * @return string */ private static function fixUrlQueryArgs( $query, $query2 = false ) { if ( $query2 !== false ) { @@ -1478,14 +1629,12 @@ class Title { * Get a real URL referring to this title, with interwiki link and * fragment * - * See getLocalURL for the arguments. - * - * @see self::getLocalURL + * @see self::getLocalURL for the arguments. * @see wfExpandUrl - * @param $query - * @param $query2 bool - * @param $proto Protocol type to use in URL - * @return String the URL + * @param array|string $query + * @param bool $query2 + * @param string $proto Protocol type to use in URL + * @return string The URL */ public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) { $query = self::fixUrlQueryArgs( $query, $query2 ); @@ -1506,21 +1655,27 @@ class Title { } /** - * Get a URL with no fragment or server name. If this page is generated - * with action=render, $wgServer is prepended. + * Get a URL with no fragment or server name (relative URL) from a Title object. + * If this page is generated with action=render, however, + * $wgServer is prepended to make an absolute URL. + * + * @see self::getFullURL to always get an absolute URL. + * @see self::getLinkURL to always get a URL that's the simplest URL that will be + * valid to link, locally, to the current Title. + * @see self::newFromText to produce a Title object. * - * @param string|array $query an optional query string, + * @param string|array $query An optional query string, * not used for interwiki links. Can be specified as an associative array as well, * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped). * Some query patterns will trigger various shorturl path replacements. - * @param $query2 Mixed: An optional secondary query array. This one MUST + * @param array $query2 An optional secondary query array. This one MUST * be an array. If a string is passed it will be interpreted as a deprecated * variant argument and urlencoded into a variant= argument. * This second query argument will be added to the $query * The second parameter is deprecated since 1.19. Pass it as a key,value * pair in the first parameter array instead. * - * @return String the URL + * @return string String of the URL. */ public function getLocalURL( $query = '', $query2 = false ) { global $wgArticlePath, $wgScript, $wgServer, $wgRequest; @@ -1547,9 +1702,9 @@ class Title { $url = false; $matches = array(); - if ( !empty( $wgActionPaths ) && - preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) - { + if ( !empty( $wgActionPaths ) + && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) + ) { $action = urldecode( $matches[2] ); if ( isset( $wgActionPaths[$action] ) ) { $query = $matches[1]; @@ -1563,12 +1718,12 @@ class Title { } } - if ( $url === false && - $wgVariantArticlePath && - $wgContLang->getCode() === $this->getPageLanguage()->getCode() && - $this->getPageLanguage()->hasVariants() && - preg_match( '/^variant=([^&]*)$/', $query, $matches ) ) - { + if ( $url === false + && $wgVariantArticlePath + && $wgContLang->getCode() === $this->getPageLanguage()->getCode() + && $this->getPageLanguage()->hasVariants() + && preg_match( '/^variant=([^&]*)$/', $query, $matches ) + ) { $variant = urldecode( $matches[1] ); if ( $this->getPageLanguage()->hasVariant( $variant ) ) { // Only do the variant replacement if the given variant is a valid @@ -1608,19 +1763,17 @@ class Title { * The result obviously should not be URL-escaped, but does need to be * HTML-escaped if it's being output in HTML. * - * See getLocalURL for the arguments. - * - * @param $query - * @param $query2 bool - * @param $proto Protocol to use; setting this will cause a full URL to be used - * @see self::getLocalURL - * @return String the URL + * @param array $query + * @param bool $query2 + * @param string $proto Protocol to use; setting this will cause a full URL to be used + * @see self::getLocalURL for the arguments. + * @return string The URL */ public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) { wfProfileIn( __METHOD__ ); if ( $this->isExternal() || $proto !== PROTO_RELATIVE ) { $ret = $this->getFullURL( $query, $query2, $proto ); - } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) { + } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) { $ret = $this->getFragmentForURL(); } else { $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL(); @@ -1630,38 +1783,6 @@ class Title { } /** - * Get an HTML-escaped version of the URL form, suitable for - * using in a link, without a server name or fragment - * - * See getLocalURL for the arguments. - * - * @see self::getLocalURL - * @param $query string - * @param $query2 bool|string - * @return String the URL - * @deprecated since 1.19 - */ - public function escapeLocalURL( $query = '', $query2 = false ) { - wfDeprecated( __METHOD__, '1.19' ); - return htmlspecialchars( $this->getLocalURL( $query, $query2 ) ); - } - - /** - * Get an HTML-escaped version of the URL form, suitable for - * using in a link, including the server name and fragment - * - * See getLocalURL for the arguments. - * - * @see self::getLocalURL - * @return String the URL - * @deprecated since 1.19 - */ - public function escapeFullURL( $query = '', $query2 = false ) { - wfDeprecated( __METHOD__, '1.19' ); - return htmlspecialchars( $this->getFullURL( $query, $query2 ) ); - } - - /** * Get the URL form for an internal link. * - Used in various Squid-related code, in case we have a different * internal hostname for the server from the exposed one. @@ -1670,10 +1791,8 @@ class Title { * if $wgInternalServer is not set. If the server variable used is * protocol-relative, the URL will be expanded to http:// * - * See getLocalURL for the arguments. - * - * @see self::getLocalURL - * @return String the URL + * @see self::getLocalURL for the arguments. + * @return string The URL */ public function getInternalURL( $query = '', $query2 = false ) { global $wgInternalServer, $wgServer; @@ -1691,9 +1810,7 @@ class Title { * * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment * - * See getLocalURL for the arguments. - * - * @see self::getLocalURL + * @see self::getLocalURL for the arguments. * @return string The URL * @since 1.18 */ @@ -1705,28 +1822,12 @@ class Title { } /** - * HTML-escaped version of getCanonicalURL() - * - * See getLocalURL for the arguments. - * - * @see self::getLocalURL - * @since 1.18 - * @return string - * @deprecated since 1.19 - */ - public function escapeCanonicalURL( $query = '', $query2 = false ) { - wfDeprecated( __METHOD__, '1.19' ); - return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) ); - } - - /** * Get the edit URL for this Title * - * @return String the URL, or a null string if this is an - * interwiki link + * @return string The URL, or a null string if this is an interwiki link */ public function getEditURL() { - if ( $this->mInterwiki != '' ) { + if ( $this->isExternal() ) { return ''; } $s = $this->getLocalURL( 'action=edit' ); @@ -1737,8 +1838,8 @@ class Title { /** * Is $wgUser watching this page? * - * @deprecated in 1.20; use User::isWatched() instead. - * @return Bool + * @deprecated since 1.20; use User::isWatched() instead. + * @return bool */ public function userIsWatching() { global $wgUser; @@ -1754,18 +1855,6 @@ class Title { } /** - * Can $wgUser read this page? - * - * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead - * @return Bool - * @todo fold these checks into userCan() - */ - public function userCanRead() { - wfDeprecated( __METHOD__, '1.19' ); - return $this->userCan( 'read' ); - } - - /** * Can $user perform $action on this page? * This skips potentially expensive cascading permission checks * as well as avoids expensive error formatting @@ -1775,10 +1864,9 @@ class Title { * * May provide false positives, but should never provide a false negative. * - * @param string $action action that permission needs to be checked for - * @param $user User to check (since 1.19); $wgUser will be used if not - * provided. - * @return Bool + * @param string $action Action that permission needs to be checked for + * @param User $user User to check (since 1.19); $wgUser will be used if not provided. + * @return bool */ public function quickUserCan( $action, $user = null ) { return $this->userCan( $action, $user, false ); @@ -1787,19 +1875,21 @@ class Title { /** * Can $user perform $action on this page? * - * @param string $action action that permission needs to be checked for - * @param $user User to check (since 1.19); $wgUser will be used if not + * @param string $action Action that permission needs to be checked for + * @param User $user User to check (since 1.19); $wgUser will be used if not * provided. * @param bool $doExpensiveQueries Set this to false to avoid doing * unnecessary queries. - * @return Bool + * @return bool */ public function userCan( $action, $user = null, $doExpensiveQueries = true ) { if ( !$user instanceof User ) { global $wgUser; $user = $wgUser; } - return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) ); + + return !count( $this->getUserPermissionsErrorsInternal( + $action, $user, $doExpensiveQueries, true ) ); } /** @@ -1807,15 +1897,17 @@ class Title { * * @todo FIXME: This *does not* check throttles (User::pingLimiter()). * - * @param string $action action that permission needs to be checked for - * @param $user User to check + * @param string $action Action that permission needs to be checked for + * @param User $user User to check * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary * queries by skipping checks for cascading protections and user blocks. - * @param array $ignoreErrors of Strings Set this to a list of message keys + * @param array $ignoreErrors Array of Strings Set this to a list of message keys * whose corresponding errors may be ignored. - * @return Array of arguments to wfMessage to explain permissions problems. + * @return array Array of arguments to wfMessage to explain permissions problems. */ - public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) { + public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, + $ignoreErrors = array() + ) { $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries ); // Remove the errors being ignored. @@ -1833,16 +1925,20 @@ class Title { /** * Permissions checks that fail most often, and which are easiest to test. * - * @param string $action the action to check - * @param $user User user to check - * @param array $errors list of current errors - * @param $doExpensiveQueries Boolean whether or not to perform expensive queries - * @param $short Boolean short circuit on first error + * @param string $action The action to check + * @param User $user User to check + * @param array $errors List of current errors + * @param bool $doExpensiveQueries Whether or not to perform expensive queries + * @param bool $short Short circuit on first error * - * @return Array list of errors + * @return array List of errors */ - private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) { - if ( !wfRunHooks( 'TitleQuickPermissions', array( $this, $user, $action, &$errors, $doExpensiveQueries, $short ) ) ) { + private function checkQuickPermissions( $action, $user, $errors, + $doExpensiveQueries, $short + ) { + if ( !wfRunHooks( 'TitleQuickPermissions', + array( $this, $user, $action, &$errors, $doExpensiveQueries, $short ) ) + ) { return $errors; } @@ -1865,6 +1961,11 @@ class Title { $errors[] = array( 'movenotallowedfile' ); } + // Check if user is allowed to move category pages if it's a category page + if ( $this->mNamespace == NS_CATEGORY && !$user->isAllowed( 'move-categorypages' ) ) { + $errors[] = array( 'cant-move-category-page' ); + } + if ( !$user->isAllowed( 'move' ) ) { // User can't move anything $userCanMove = User::groupHasPermission( 'user', 'move' ); @@ -1884,6 +1985,10 @@ class Title { && $this->mNamespace == NS_USER && !$this->isSubpage() ) { // Show user page-specific message only if the user can move other pages $errors[] = array( 'cant-move-to-user-page' ); + } elseif ( !$user->isAllowed( 'move-categorypages' ) + && $this->mNamespace == NS_CATEGORY ) { + // Show category page-specific message only if the user can move other pages + $errors[] = array( 'cant-move-to-category-page' ); } } elseif ( !$user->isAllowed( $action ) ) { $errors[] = $this->missingPermissionError( $action, $short ); @@ -1895,10 +2000,10 @@ class Title { /** * Add the resulting error code to the errors array * - * @param array $errors list of current errors - * @param $result Mixed result of errors + * @param array $errors List of current errors + * @param array $result Result of errors * - * @return Array list of errors + * @return array List of errors */ private function resultToError( $errors, $result ) { if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) { @@ -1920,13 +2025,13 @@ class Title { /** * Check various permission hooks * - * @param string $action the action to check - * @param $user User user to check - * @param array $errors list of current errors - * @param $doExpensiveQueries Boolean whether or not to perform expensive queries - * @param $short Boolean short circuit on first error + * @param string $action The action to check + * @param User $user User to check + * @param array $errors List of current errors + * @param bool $doExpensiveQueries Whether or not to perform expensive queries + * @param bool $short Short circuit on first error * - * @return Array list of errors + * @return array List of errors */ private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) { // Use getUserPermissionsErrors instead @@ -1953,15 +2058,17 @@ class Title { /** * Check permissions on special pages & namespaces * - * @param string $action the action to check - * @param $user User user to check - * @param array $errors list of current errors - * @param $doExpensiveQueries Boolean whether or not to perform expensive queries - * @param $short Boolean short circuit on first error + * @param string $action The action to check + * @param User $user User to check + * @param array $errors List of current errors + * @param bool $doExpensiveQueries Whether or not to perform expensive queries + * @param bool $short Short circuit on first error * - * @return Array list of errors + * @return array List of errors */ - private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) { + private function checkSpecialsAndNSPermissions( $action, $user, $errors, + $doExpensiveQueries, $short + ) { # Only 'createaccount' can be performed on special pages, # which don't actually exist in the DB. if ( NS_SPECIAL == $this->mNamespace && $action !== 'createaccount' ) { @@ -1973,7 +2080,7 @@ class Title { $ns = $this->mNamespace == NS_MAIN ? wfMessage( 'nstab-main' )->text() : $this->getNsText(); $errors[] = $this->mNamespace == NS_MEDIAWIKI ? - array( 'protectedinterface' ) : array( 'namespaceprotected', $ns ); + array( 'protectedinterface', $action ) : array( 'namespaceprotected', $ns, $action ); } return $errors; @@ -1982,13 +2089,13 @@ class Title { /** * Check CSS/JS sub-page permissions * - * @param string $action the action to check - * @param $user User user to check - * @param array $errors list of current errors - * @param $doExpensiveQueries Boolean whether or not to perform expensive queries - * @param $short Boolean short circuit on first error + * @param string $action The action to check + * @param User $user User to check + * @param array $errors List of current errors + * @param bool $doExpensiveQueries Whether or not to perform expensive queries + * @param bool $short Short circuit on first error * - * @return Array list of errors + * @return array List of errors */ private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) { # Protect css/js subpages of user pages @@ -1997,15 +2104,15 @@ class Title { if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) { if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) { if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) { - $errors[] = array( 'mycustomcssprotected' ); + $errors[] = array( 'mycustomcssprotected', $action ); } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) { - $errors[] = array( 'mycustomjsprotected' ); + $errors[] = array( 'mycustomjsprotected', $action ); } } else { if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) { - $errors[] = array( 'customcssprotected' ); + $errors[] = array( 'customcssprotected', $action ); } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) { - $errors[] = array( 'customjsprotected' ); + $errors[] = array( 'customjsprotected', $action ); } } } @@ -2018,13 +2125,13 @@ class Title { * page. The user must possess all required rights for this * action. * - * @param string $action the action to check - * @param $user User user to check - * @param array $errors list of current errors - * @param $doExpensiveQueries Boolean whether or not to perform expensive queries - * @param $short Boolean short circuit on first error + * @param string $action The action to check + * @param User $user User to check + * @param array $errors List of current errors + * @param bool $doExpensiveQueries Whether or not to perform expensive queries + * @param bool $short Short circuit on first error * - * @return Array list of errors + * @return array List of errors */ private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) { foreach ( $this->getRestrictions( $action ) as $right ) { @@ -2040,9 +2147,9 @@ class Title { continue; } if ( !$user->isAllowed( $right ) ) { - $errors[] = array( 'protectedpagetext', $right ); + $errors[] = array( 'protectedpagetext', $right, $action ); } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) { - $errors[] = array( 'protectedpagetext', 'protect' ); + $errors[] = array( 'protectedpagetext', 'protect', $action ); } } @@ -2052,15 +2159,17 @@ class Title { /** * Check restrictions on cascading pages. * - * @param string $action the action to check - * @param $user User to check - * @param array $errors list of current errors - * @param $doExpensiveQueries Boolean whether or not to perform expensive queries - * @param $short Boolean short circuit on first error + * @param string $action The action to check + * @param User $user User to check + * @param array $errors List of current errors + * @param bool $doExpensiveQueries Whether or not to perform expensive queries + * @param bool $short Short circuit on first error * - * @return Array list of errors + * @return array List of errors */ - private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) { + private function checkCascadingSourcesRestrictions( $action, $user, $errors, + $doExpensiveQueries, $short + ) { if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) { # We /could/ use the protection level on the source page, but it's # fairly ugly as we have to establish a precedence hierarchy for pages @@ -2087,7 +2196,7 @@ class Title { foreach ( $cascadingSources as $page ) { $pages .= '* [[:' . $page->getPrefixedText() . "]]\n"; } - $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages ); + $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages, $action ); } } } @@ -2099,19 +2208,23 @@ class Title { /** * Check action permissions not already checked in checkQuickPermissions * - * @param string $action the action to check - * @param $user User to check - * @param array $errors list of current errors - * @param $doExpensiveQueries Boolean whether or not to perform expensive queries - * @param $short Boolean short circuit on first error + * @param string $action The action to check + * @param User $user User to check + * @param array $errors List of current errors + * @param bool $doExpensiveQueries Whether or not to perform expensive queries + * @param bool $short Short circuit on first error * - * @return Array list of errors + * @return array List of errors */ - private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) { + private function checkActionPermissions( $action, $user, $errors, + $doExpensiveQueries, $short + ) { global $wgDeleteRevisionsLimit, $wgLang; if ( $action == 'protect' ) { - if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) { + if ( count( $this->getUserPermissionsErrorsInternal( 'edit', + $user, $doExpensiveQueries, true ) ) + ) { // If they can't edit, they shouldn't protect. $errors[] = array( 'protect-cantedit' ); } @@ -2124,10 +2237,14 @@ class Title { if ( $title_protection['pt_create_perm'] == 'autoconfirmed' ) { $title_protection['pt_create_perm'] = 'editsemiprotected'; // B/C } - if ( $title_protection['pt_create_perm'] == '' || - !$user->isAllowed( $title_protection['pt_create_perm'] ) ) - { - $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] ); + if ( $title_protection['pt_create_perm'] == '' + || !$user->isAllowed( $title_protection['pt_create_perm'] ) + ) { + $errors[] = array( + 'titleprotected', + User::whoIs( $title_protection['pt_user'] ), + $title_protection['pt_reason'] + ); } } } elseif ( $action == 'move' ) { @@ -2146,9 +2263,19 @@ class Title { $errors[] = array( 'immobile-target-page' ); } } elseif ( $action == 'delete' ) { + $tempErrors = $this->checkPageRestrictions( 'edit', + $user, array(), $doExpensiveQueries, true ); + if ( !$tempErrors ) { + $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit', + $user, $tempErrors, $doExpensiveQueries, true ); + } + if ( $tempErrors ) { + // If protection keeps them from editing, they shouldn't be able to delete. + $errors[] = array( 'deleteprotected' ); + } if ( $doExpensiveQueries && $wgDeleteRevisionsLimit - && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() ) - { + && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() + ) { $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ); } } @@ -2158,13 +2285,13 @@ class Title { /** * Check that the user isn't blocked from editing. * - * @param string $action the action to check - * @param $user User to check - * @param array $errors list of current errors - * @param $doExpensiveQueries Boolean whether or not to perform expensive queries - * @param $short Boolean short circuit on first error + * @param string $action The action to check + * @param User $user User to check + * @param array $errors List of current errors + * @param bool $doExpensiveQueries Whether or not to perform expensive queries + * @param bool $short Short circuit on first error * - * @return Array list of errors + * @return array List of errors */ private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) { // Account creation blocks handled at userlogin. @@ -2193,13 +2320,13 @@ class Title { /** * Check that the user is allowed to read this page. * - * @param string $action the action to check - * @param $user User to check - * @param array $errors list of current errors - * @param $doExpensiveQueries Boolean whether or not to perform expensive queries - * @param $short Boolean short circuit on first error + * @param string $action The action to check + * @param User $user User to check + * @param array $errors List of current errors + * @param bool $doExpensiveQueries Whether or not to perform expensive queries + * @param bool $short Short circuit on first error * - * @return Array list of errors + * @return array List of errors */ private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) { global $wgWhitelistRead, $wgWhitelistReadRegexp; @@ -2272,9 +2399,9 @@ class Title { * Get a description array when the user doesn't have the right to perform * $action (i.e. when User::isAllowed() returns false) * - * @param string $action the action to check - * @param $short Boolean short circuit on first error - * @return Array list of errors + * @param string $action The action to check + * @param bool $short Short circuit on first error + * @return array List of errors */ private function missingPermissionError( $action, $short ) { // We avoid expensive display logic for quickUserCan's and such @@ -2302,13 +2429,15 @@ class Title { * which checks ONLY that previously checked by userCan (i.e. it leaves out * checks on wfReadOnly() and blocks) * - * @param string $action action that permission needs to be checked for - * @param $user User to check + * @param string $action Action that permission needs to be checked for + * @param User $user User to check * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries. * @param bool $short Set this to true to stop after the first permission error. - * @return Array of arrays of the arguments to wfMessage to explain permissions problems. + * @return array Array of arrays of the arguments to wfMessage to explain permissions problems. */ - protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) { + protected function getUserPermissionsErrorsInternal( $action, $user, + $doExpensiveQueries = true, $short = false + ) { wfProfileIn( __METHOD__ ); # Read has special handling @@ -2317,6 +2446,19 @@ class Title { 'checkPermissionHooks', 'checkReadPermissions', ); + # Don't call checkSpecialsAndNSPermissions or checkCSSandJSPermissions + # here as it will lead to duplicate error messages. This is okay to do + # since anywhere that checks for create will also check for edit, and + # those checks are called for edit. + } elseif ( $action == 'create' ) { + $checks = array( + 'checkQuickPermissions', + 'checkPermissionHooks', + 'checkPageRestrictions', + 'checkCascadingSourcesRestrictions', + 'checkActionPermissions', + 'checkUserBlock' + ); } else { $checks = array( 'checkQuickPermissions', @@ -2364,7 +2506,7 @@ class Title { /** * Returns restriction types for the current Title * - * @return array applicable restriction types + * @return array Applicable restriction types */ public function getRestrictionTypes() { if ( $this->isSpecialPage() ) { @@ -2390,7 +2532,7 @@ class Title { * Is this title subject to title protection? * Title protection is the one applied against creation of such title. * - * @return Mixed An associative array representing any existent title + * @return array|bool An associative array representing any existent title * protection, or false if there's none. */ private function getTitleProtection() { @@ -2404,7 +2546,7 @@ class Title { return false; } - if ( !isset( $this->mTitleProtection ) ) { + if ( $this->mTitleProtection === null ) { $dbr = wfGetDB( DB_SLAVE ); $res = $dbr->select( 'protected_titles', @@ -2420,30 +2562,6 @@ class Title { } /** - * Update the title protection status - * - * @deprecated in 1.19; use WikiPage::doUpdateRestrictions() instead. - * @param $create_perm String Permission required for creation - * @param string $reason Reason for protection - * @param string $expiry Expiry timestamp - * @return boolean true - */ - public function updateTitleProtection( $create_perm, $reason, $expiry ) { - wfDeprecated( __METHOD__, '1.19' ); - - global $wgUser; - - $limit = array( 'create' => $create_perm ); - $expiry = array( 'create' => $expiry ); - - $page = WikiPage::factory( $this ); - $cascade = false; - $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $wgUser ); - - return $status->isOK(); - } - - /** * Remove any title protection due to page existing */ public function deleteTitleProtection() { @@ -2462,7 +2580,7 @@ class Title { * in $wgSemiprotectedRestrictionLevels? * * @param string $action Action to check (default: edit) - * @return Bool + * @return bool */ public function isSemiProtected( $action = 'edit' ) { global $wgSemiprotectedRestrictionLevels; @@ -2488,9 +2606,9 @@ class Title { /** * Does the title correspond to a protected article? * - * @param string $action the action the page is protected from, + * @param string $action The action the page is protected from, * by default checks all actions. - * @return Bool + * @return bool */ public function isProtected( $action = '' ) { global $wgRestrictionLevels; @@ -2521,8 +2639,8 @@ class Title { * Determines if $user is unable to edit this page because it has been protected * by $wgNamespaceProtection. * - * @param $user User object to check permissions - * @return Bool + * @param User $user User object to check permissions + * @return bool */ public function isNamespaceProtected( User $user ) { global $wgNamespaceProtection; @@ -2540,7 +2658,7 @@ class Title { /** * Cascading protection: Return true if cascading restrictions apply to this page, false if not. * - * @return Bool If the page is subject to cascading restrictions. + * @return bool If the page is subject to cascading restrictions. */ public function isCascadeProtected() { list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false ); @@ -2548,22 +2666,38 @@ class Title { } /** + * Determines whether cascading protection sources have already been loaded from + * the database. + * + * @param bool $getPages True to check if the pages are loaded, or false to check + * if the status is loaded. + * @return bool Whether or not the specified information has been loaded + * @since 1.23 + */ + public function areCascadeProtectionSourcesLoaded( $getPages = true ) { + return $getPages ? $this->mCascadeSources !== null : $this->mHasCascadingRestrictions !== null; + } + + /** * Cascading protection: Get the source of any cascading restrictions on this page. * * @param bool $getPages Whether or not to retrieve the actual pages - * that the restrictions have come from. - * @return Mixed Array of Title objects of the pages from which cascading restrictions - * have come, false for none, or true if such restrictions exist, but $getPages - * was not set. The restriction array is an array of each type, each of which - * contains a array of unique groups. + * that the restrictions have come from and the actual restrictions + * themselves. + * @return array Two elements: First is an array of Title objects of the + * pages from which cascading restrictions have come, false for + * none, or true if such restrictions exist but $getPages was not + * set. Second is an array like that returned by + * Title::getAllRestrictions(), or an empty array if $getPages is + * false. */ public function getCascadeProtectionSources( $getPages = true ) { global $wgContLang; $pagerestrictions = array(); - if ( isset( $this->mCascadeSources ) && $getPages ) { + if ( $this->mCascadeSources !== null && $getPages ) { return array( $this->mCascadeSources, $this->mCascadingRestrictions ); - } elseif ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) { + } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) { return array( $this->mHasCascadingRestrictions, $pagerestrictions ); } @@ -2648,10 +2782,22 @@ class Title { } /** + * Accessor for mRestrictionsLoaded + * + * @return bool Whether or not the page's restrictions have already been + * loaded from the database + * @since 1.23 + */ + public function areRestrictionsLoaded() { + return $this->mRestrictionsLoaded; + } + + /** * Accessor/initialisation for mRestrictions * - * @param string $action action that permission needs to be checked for - * @return Array of Strings the array of groups allowed to edit this article + * @param string $action Action that permission needs to be checked for + * @return array Restriction levels needed to take the action. All levels + * are required. */ public function getRestrictions( $action ) { if ( !$this->mRestrictionsLoaded ) { @@ -2663,10 +2809,24 @@ class Title { } /** + * Accessor/initialisation for mRestrictions + * + * @return array Keys are actions, values are arrays as returned by + * Title::getRestrictions() + * @since 1.23 + */ + public function getAllRestrictions() { + if ( !$this->mRestrictionsLoaded ) { + $this->loadRestrictions(); + } + return $this->mRestrictions; + } + + /** * Get the expiry time for the restriction against a given action * - * @param $action - * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever + * @param string $action + * @return string|bool 14-char timestamp, or 'infinity' if the page is protected forever * or not protected at all, or false if the action is not recognised. */ public function getRestrictionExpiry( $action ) { @@ -2679,7 +2839,7 @@ class Title { /** * Returns cascading restrictions for the current article * - * @return Boolean + * @return bool */ function areRestrictionsCascading() { if ( !$this->mRestrictionsLoaded ) { @@ -2692,8 +2852,8 @@ class Title { /** * Loads a string into mRestrictions array * - * @param $res Resource restrictions as an SQL result. - * @param string $oldFashionedRestrictions comma-separated list of page + * @param ResultWrapper $res Resource restrictions as an SQL result. + * @param string $oldFashionedRestrictions Comma-separated list of page * restrictions from page table (pre 1.10) */ private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) { @@ -2711,9 +2871,9 @@ class Title { * and page_restrictions table for this existing page. * Public for usage by LiquidThreads. * - * @param array $rows of db result objects - * @param string $oldFashionedRestrictions comma-separated list of page - * restrictions from page table (pre 1.10) + * @param array $rows Array of db result objects + * @param string $oldFashionedRestrictions Comma-separated list of page + * restrictions from page table (pre 1.10) */ public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) { global $wgContLang; @@ -2795,8 +2955,8 @@ class Title { /** * Load restrictions from the page_restrictions table * - * @param string $oldFashionedRestrictions comma-separated list of page - * restrictions from page table (pre 1.10) + * @param string $oldFashionedRestrictions Comma-separated list of page + * restrictions from page table (pre 1.10) */ public function loadRestrictions( $oldFashionedRestrictions = null ) { global $wgContLang; @@ -2854,7 +3014,7 @@ class Title { $method = __METHOD__; $dbw = wfGetDB( DB_MASTER ); - $dbw->onTransactionIdle( function() use ( $dbw, $method ) { + $dbw->onTransactionIdle( function () use ( $dbw, $method ) { $dbw->delete( 'page_restrictions', array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), @@ -2871,7 +3031,7 @@ class Title { /** * Does this have subpages? (Warning, usually requires an extra DB query.) * - * @return Bool + * @return bool */ public function hasSubpages() { if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) { @@ -2883,22 +3043,22 @@ class Title { # alone to cache the result. There's no point in having it hanging # around uninitialized in every Title object; therefore we only add it # if needed and don't declare it statically. - if ( isset( $this->mHasSubpages ) ) { - return $this->mHasSubpages; + if ( $this->mHasSubpages === null ) { + $this->mHasSubpages = false; + $subpages = $this->getSubpages( 1 ); + if ( $subpages instanceof TitleArray ) { + $this->mHasSubpages = (bool)$subpages->count(); + } } - $subpages = $this->getSubpages( 1 ); - if ( $subpages instanceof TitleArray ) { - return $this->mHasSubpages = (bool)$subpages->count(); - } - return $this->mHasSubpages = false; + return $this->mHasSubpages; } /** * Get all subpages of this page. * - * @param int $limit maximum number of subpages to fetch; -1 for no limit - * @return mixed TitleArray, or empty array if this page's namespace + * @param int $limit Maximum number of subpages to fetch; -1 for no limit + * @return TitleArray|array TitleArray, or empty array if this page's namespace * doesn't allow subpages */ public function getSubpages( $limit = -1 ) { @@ -2913,7 +3073,7 @@ class Title { if ( $limit > -1 ) { $options['LIMIT'] = $limit; } - return $this->mSubpages = TitleArray::newFromResult( + $this->mSubpages = TitleArray::newFromResult( $dbr->select( 'page', array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ), $conds, @@ -2921,12 +3081,13 @@ class Title { $options ) ); + return $this->mSubpages; } /** * Is there a version of this page in the deletion archive? * - * @return Int the number of archived revisions + * @return int The number of archived revisions */ public function isDeleted() { if ( $this->getNamespace() < 0 ) { @@ -2951,7 +3112,7 @@ class Title { /** * Is there a version of this page in the deletion archive? * - * @return Boolean + * @return bool */ public function isDeletedQuick() { if ( $this->getNamespace() < 0 ) { @@ -2975,13 +3136,14 @@ class Title { * Get the article ID for this Title from the link cache, * adding it if necessary * - * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select + * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select * for update - * @return Int the ID + * @return int The ID */ public function getArticleID( $flags = 0 ) { if ( $this->getNamespace() < 0 ) { - return $this->mArticleID = 0; + $this->mArticleID = 0; + return $this->mArticleID; } $linkCache = LinkCache::singleton(); if ( $flags & self::GAID_FOR_UPDATE ) { @@ -3001,8 +3163,8 @@ class Title { * Is this an article that is a redirect page? * Uses link cache, adding it if necessary * - * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update - * @return Bool + * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update + * @return bool */ public function isRedirect( $flags = 0 ) { if ( !is_null( $this->mRedirect ) ) { @@ -3010,7 +3172,8 @@ class Title { } # Calling getArticleID() loads the field from cache as needed if ( !$this->getArticleID( $flags ) ) { - return $this->mRedirect = false; + $this->mRedirect = false; + return $this->mRedirect; } $linkCache = LinkCache::singleton(); @@ -3022,7 +3185,8 @@ class Title { # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is # set, then LinkCache will definitely be up to date here, since getArticleID() forces # LinkCache to refresh its data from the master. - return $this->mRedirect = false; + $this->mRedirect = false; + return $this->mRedirect; } $this->mRedirect = (bool)$cached; @@ -3034,8 +3198,8 @@ class Title { * What is the length of this page? * Uses link cache, adding it if necessary * - * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update - * @return Int + * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update + * @return int */ public function getLength( $flags = 0 ) { if ( $this->mLength != -1 ) { @@ -3043,13 +3207,15 @@ class Title { } # Calling getArticleID() loads the field from cache as needed if ( !$this->getArticleID( $flags ) ) { - return $this->mLength = 0; + $this->mLength = 0; + return $this->mLength; } $linkCache = LinkCache::singleton(); $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' ); if ( $cached === null ) { # Trust LinkCache's state over our own, as for isRedirect() - return $this->mLength = 0; + $this->mLength = 0; + return $this->mLength; } $this->mLength = intval( $cached ); @@ -3060,8 +3226,8 @@ class Title { /** * What is the page_latest field for this page? * - * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update - * @return Int or 0 if the page doesn't exist + * @param int $flags A bit field; may be Title::GAID_FOR_UPDATE to select for update + * @return int Int or 0 if the page doesn't exist */ public function getLatestRevID( $flags = 0 ) { if ( !( $flags & Title::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) { @@ -3069,14 +3235,16 @@ class Title { } # Calling getArticleID() loads the field from cache as needed if ( !$this->getArticleID( $flags ) ) { - return $this->mLatestID = 0; + $this->mLatestID = 0; + return $this->mLatestID; } $linkCache = LinkCache::singleton(); $linkCache->addLinkObj( $this ); $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' ); if ( $cached === null ) { # Trust LinkCache's state over our own, as for isRedirect() - return $this->mLatestID = 0; + $this->mLatestID = 0; + return $this->mLatestID; } $this->mLatestID = intval( $cached ); @@ -3092,7 +3260,7 @@ class Title { * loading of the new page_id. It's also called from * WikiPage::doDeleteArticleReal() * - * @param int $newid the new Article ID + * @param int $newid The new Article ID */ public function resetArticleID( $newid ) { $linkCache = LinkCache::singleton(); @@ -3110,14 +3278,17 @@ class Title { $this->mLatestID = false; $this->mContentModel = false; $this->mEstimateRevisions = null; + $this->mPageLanguage = false; + $this->mDbPageLanguage = null; + $this->mIsBigDeletion = null; } /** * Capitalize a text string for a title if it belongs to a namespace that capitalizes * - * @param string $text containing title to capitalize - * @param int $ns namespace index, defaults to NS_MAIN - * @return String containing capitalized title + * @param string $text Containing title to capitalize + * @param int $ns Namespace index, defaults to NS_MAIN + * @return string Containing capitalized title */ public static function capitalize( $text, $ns = NS_MAIN ) { global $wgContLang; @@ -3138,195 +3309,41 @@ class Title { * namespace prefixes, sets the other forms, and canonicalizes * everything. * - * @return Bool true on success + * @return bool True on success */ private function secureAndSplit() { - global $wgContLang, $wgLocalInterwiki; - # Initialisation - $this->mInterwiki = $this->mFragment = ''; + $this->mInterwiki = ''; + $this->mFragment = ''; $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN $dbkey = $this->mDbkeyform; - # Strip Unicode bidi override characters. - # Sometimes they slip into cut-n-pasted page titles, where the - # override chars get included in list displays. - $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey ); - - # Clean up whitespace - # Note: use of the /u option on preg_replace here will cause - # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x, - # conveniently disabling them. - $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey ); - $dbkey = trim( $dbkey, '_' ); - - if ( $dbkey == '' ) { - return false; - } - - if ( strpos( $dbkey, UTF8_REPLACEMENT ) !== false ) { - # Contained illegal UTF-8 sequences or forbidden Unicode chars. + try { + // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share + // the parsing code with Title, while avoiding massive refactoring. + // @todo: get rid of secureAndSplit, refactor parsing code. + $titleParser = self::getTitleParser(); + $parts = $titleParser->splitTitleString( $dbkey, $this->getDefaultNamespace() ); + } catch ( MalformedTitleException $ex ) { return false; } - $this->mDbkeyform = $dbkey; - - # Initial colon indicates main namespace rather than specified default - # but should not create invalid {ns,title} pairs such as {0,Project:Foo} - if ( ':' == $dbkey[0] ) { - $this->mNamespace = NS_MAIN; - $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing - $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace - } - - # Namespace or interwiki prefix - $firstPass = true; - $prefixRegexp = "/^(.+?)_*:_*(.*)$/S"; - do { - $m = array(); - if ( preg_match( $prefixRegexp, $dbkey, $m ) ) { - $p = $m[1]; - if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) { - # Ordinary namespace - $dbkey = $m[2]; - $this->mNamespace = $ns; - # For Talk:X pages, check if X has a "namespace" prefix - if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) { - if ( $wgContLang->getNsIndex( $x[1] ) ) { - # Disallow Talk:File:x type titles... - return false; - } elseif ( Interwiki::isValidInterwiki( $x[1] ) ) { - # Disallow Talk:Interwiki:x type titles... - return false; - } - } - } elseif ( Interwiki::isValidInterwiki( $p ) ) { - if ( !$firstPass ) { - # Can't make a local interwiki link to an interwiki link. - # That's just crazy! - return false; - } + # Fill fields + $this->setFragment( '#' . $parts['fragment'] ); + $this->mInterwiki = $parts['interwiki']; + $this->mLocalInterwiki = $parts['local_interwiki']; + $this->mNamespace = $parts['namespace']; + $this->mUserCaseDBKey = $parts['user_case_dbkey']; - # Interwiki link - $dbkey = $m[2]; - $this->mInterwiki = $wgContLang->lc( $p ); - - # Redundant interwiki prefix to the local wiki - if ( $wgLocalInterwiki !== false - && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) - { - if ( $dbkey == '' ) { - # Can't have an empty self-link - return false; - } - $this->mInterwiki = ''; - $firstPass = false; - # Do another namespace split... - continue; - } - - # If there's an initial colon after the interwiki, that also - # resets the default namespace - if ( $dbkey !== '' && $dbkey[0] == ':' ) { - $this->mNamespace = NS_MAIN; - $dbkey = substr( $dbkey, 1 ); - } - } - # If there's no recognized interwiki or namespace, - # then let the colon expression be part of the title. - } - break; - } while ( true ); + $this->mDbkeyform = $parts['dbkey']; + $this->mUrlform = wfUrlencode( $this->mDbkeyform ); + $this->mTextform = str_replace( '_', ' ', $this->mDbkeyform ); # We already know that some pages won't be in the database! - if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) { + if ( $this->isExternal() || $this->mNamespace == NS_SPECIAL ) { $this->mArticleID = 0; } - $fragment = strstr( $dbkey, '#' ); - if ( false !== $fragment ) { - $this->setFragment( $fragment ); - $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) ); - # remove whitespace again: prevents "Foo_bar_#" - # becoming "Foo_bar_" - $dbkey = preg_replace( '/_*$/', '', $dbkey ); - } - - # Reject illegal characters. - $rxTc = self::getTitleInvalidRegex(); - if ( preg_match( $rxTc, $dbkey ) ) { - return false; - } - - # Pages with "/./" or "/../" appearing in the URLs will often be un- - # reachable due to the way web browsers deal with 'relative' URLs. - # Also, they conflict with subpage syntax. Forbid them explicitly. - if ( - strpos( $dbkey, '.' ) !== false && - ( - $dbkey === '.' || $dbkey === '..' || - strpos( $dbkey, './' ) === 0 || - strpos( $dbkey, '../' ) === 0 || - strpos( $dbkey, '/./' ) !== false || - strpos( $dbkey, '/../' ) !== false || - substr( $dbkey, -2 ) == '/.' || - substr( $dbkey, -3 ) == '/..' - ) - ) { - return false; - } - - # Magic tilde sequences? Nu-uh! - if ( strpos( $dbkey, '~~~' ) !== false ) { - return false; - } - - # Limit the size of titles to 255 bytes. This is typically the size of the - # underlying database field. We make an exception for special pages, which - # don't need to be stored in the database, and may edge over 255 bytes due - # to subpage syntax for long titles, e.g. [[Special:Block/Long name]] - if ( - ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) - || strlen( $dbkey ) > 512 - ) { - return false; - } - - # Normally, all wiki links are forced to have an initial capital letter so [[foo]] - # and [[Foo]] point to the same place. Don't force it for interwikis, since the - # other site might be case-sensitive. - $this->mUserCaseDBKey = $dbkey; - if ( $this->mInterwiki == '' ) { - $dbkey = self::capitalize( $dbkey, $this->mNamespace ); - } - - # Can't make a link to a namespace alone... "empty" local links can only be - # self-links with a fragment identifier. - # TODO: Why do we exclude NS_MAIN (bug 54044) - if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) { - return false; - } - - // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles. - // IP names are not allowed for accounts, and can only be referring to - // edits from the IP. Given '::' abbreviations and caps/lowercaps, - // there are numerous ways to present the same IP. Having sp:contribs scan - // them all is silly and having some show the edits and others not is - // inconsistent. Same for talk/userpages. Keep them normalized instead. - $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK ) - ? IP::sanitizeIP( $dbkey ) - : $dbkey; - - // Any remaining initial :s are illegal. - if ( $dbkey !== '' && ':' == $dbkey[0] ) { - return false; - } - - # Fill fields - $this->mDbkeyform = $dbkey; - $this->mUrlform = wfUrlencode( $dbkey ); - - $this->mTextform = str_replace( '_', ' ', $dbkey ); return true; } @@ -3338,10 +3355,10 @@ class Title { * WARNING: do not use this function on arbitrary user-supplied titles! * On heavily-used templates it will max out the memory. * - * @param array $options may be FOR UPDATE - * @param string $table table name - * @param string $prefix fields prefix - * @return Array of Title objects linking here + * @param array $options May be FOR UPDATE + * @param string $table Table name + * @param string $prefix Fields prefix + * @return Title[] Array of Title objects linking here */ public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) { if ( count( $options ) > 0 ) { @@ -3382,8 +3399,8 @@ class Title { * WARNING: do not use this function on arbitrary user-supplied titles! * On heavily-used templates it will max out the memory. * - * @param array $options may be FOR UPDATE - * @return Array of Title the Title objects linking here + * @param array $options May be FOR UPDATE + * @return Title[] Array of Title the Title objects linking here */ public function getTemplateLinksTo( $options = array() ) { return $this->getLinksTo( $options, 'templatelinks', 'tl' ); @@ -3396,10 +3413,10 @@ class Title { * WARNING: do not use this function on arbitrary user-supplied titles! * On heavily-used templates it will max out the memory. * - * @param array $options may be FOR UPDATE - * @param string $table table name - * @param string $prefix fields prefix - * @return Array of Title objects linking here + * @param array $options May be FOR UPDATE + * @param string $table Table name + * @param string $prefix Fields prefix + * @return array Array of Title objects linking here */ public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) { global $wgContentHandlerUseDB; @@ -3420,7 +3437,15 @@ class Title { $namespaceFiled = "{$prefix}_namespace"; $titleField = "{$prefix}_title"; - $fields = array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ); + $fields = array( + $namespaceFiled, + $titleField, + 'page_id', + 'page_len', + 'page_is_redirect', + 'page_latest' + ); + if ( $wgContentHandlerUseDB ) { $fields[] = 'page_content_model'; } @@ -3431,7 +3456,10 @@ class Title { array( "{$prefix}_from" => $id ), __METHOD__, $options, - array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) ) + array( 'page' => array( + 'LEFT JOIN', + array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) + ) ) ); $retVal = array(); @@ -3459,18 +3487,20 @@ class Title { * WARNING: do not use this function on arbitrary user-supplied titles! * On heavily-used templates it will max out the memory. * - * @param array $options may be FOR UPDATE - * @return Array of Title the Title objects used here + * @param array $options May be FOR UPDATE + * @return Title[] Array of Title the Title objects used here */ public function getTemplateLinksFrom( $options = array() ) { return $this->getLinksFrom( $options, 'templatelinks', 'tl' ); } /** - * Get an array of Title objects referring to non-existent articles linked from this page + * Get an array of Title objects referring to non-existent articles linked + * from this page. * - * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case) - * @return Array of Title the Title objects + * @todo check if needed (used only in SpecialBrokenRedirects.php, and + * should use redirect table in this case). + * @return Title[] Array of Title the Title objects */ public function getBrokenLinksFrom() { if ( $this->getArticleID() == 0 ) { @@ -3506,7 +3536,7 @@ class Title { * Get a list of URLs to purge from the Squid cache when this * page changes * - * @return Array of String the URLs + * @return string[] Array of String the URLs */ public function getSquidURLs() { $urls = array( @@ -3522,6 +3552,13 @@ class Title { } } + // If we are looking at a css/js user subpage, purge the action=raw. + if ( $this->isJsSubpage() ) { + $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' ); + } elseif ( $this->isCssSubpage() ) { + $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' ); + } + wfRunHooks( 'TitleSquidURLs', array( $this, &$urls ) ); return $urls; } @@ -3541,8 +3578,8 @@ class Title { /** * Move this page without authentication * - * @param $nt Title the new page Title - * @return Mixed true on success, getUserPermissionsErrors()-like array on failure + * @param Title $nt The new page Title + * @return array|bool True on success, getUserPermissionsErrors()-like array on failure */ public function moveNoAuth( &$nt ) { return $this->moveTo( $nt, false ); @@ -3552,11 +3589,12 @@ class Title { * Check whether a given move operation would be valid. * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise * - * @param $nt Title the new title - * @param bool $auth indicates whether $wgUser's permissions + * @todo move this into MovePage + * @param Title $nt The new title + * @param bool $auth Indicates whether $wgUser's permissions * should be checked - * @param string $reason is the log summary of the move, used for spam checking - * @return Mixed True on success, getUserPermissionsErrors()-like array on failure + * @param string $reason Is the log summary of the move, used for spam checking + * @return array|bool True on success, getUserPermissionsErrors()-like array on failure */ public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) { global $wgUser, $wgContentHandlerUseDB; @@ -3573,7 +3611,7 @@ class Title { if ( !$this->isMovable() ) { $errors[] = array( 'immobile-source-namespace', $this->getNsText() ); } - if ( $nt->getInterwiki() != '' ) { + if ( $nt->isExternal() ) { $errors[] = array( 'immobile-target-namespace-iw' ); } if ( !$nt->isMovable() ) { @@ -3702,13 +3740,14 @@ class Title { /** * Move a title to a new location * - * @param $nt Title the new title - * @param bool $auth indicates whether $wgUser's permissions + * @todo Deprecate this in favor of MovePage + * @param Title $nt The new title + * @param bool $auth Indicates whether $wgUser's permissions * should be checked - * @param string $reason the reason for the move + * @param string $reason The reason for the move * @param bool $createRedirect Whether to create a redirect from the old title to the new title. * Ignored if the user doesn't have the suppressredirect right. - * @return Mixed true on success, getUserPermissionsErrors()-like array on failure + * @return array|bool True on success, getUserPermissionsErrors()-like array on failure */ public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) { global $wgUser; @@ -3725,240 +3764,24 @@ class Title { wfRunHooks( 'TitleMove', array( $this, $nt, $wgUser ) ); - // If it is a file, move it first. - // It is done before all other moving stuff is done because it's hard to revert. - $dbw = wfGetDB( DB_MASTER ); - if ( $this->getNamespace() == NS_FILE ) { - $file = wfLocalFile( $this ); - if ( $file->exists() ) { - $status = $file->move( $nt ); - if ( !$status->isOk() ) { - return $status->getErrorsArray(); - } - } - // Clear RepoGroup process cache - RepoGroup::singleton()->clearCache( $this ); - RepoGroup::singleton()->clearCache( $nt ); # clear false negative cache - } - - $dbw->begin( __METHOD__ ); # If $file was a LocalFile, its transaction would have closed our own. - $pageid = $this->getArticleID( self::GAID_FOR_UPDATE ); - $protected = $this->isProtected(); - - // Do the actual move - $this->moveToInternal( $nt, $reason, $createRedirect ); - - // Refresh the sortkey for this row. Be careful to avoid resetting - // cl_timestamp, which may disturb time-based lists on some sites. - $prefixes = $dbw->select( - 'categorylinks', - array( 'cl_sortkey_prefix', 'cl_to' ), - array( 'cl_from' => $pageid ), - __METHOD__ - ); - foreach ( $prefixes as $prefixRow ) { - $prefix = $prefixRow->cl_sortkey_prefix; - $catTo = $prefixRow->cl_to; - $dbw->update( 'categorylinks', - array( - 'cl_sortkey' => Collation::singleton()->getSortKey( - $nt->getCategorySortkey( $prefix ) ), - 'cl_timestamp=cl_timestamp' ), - array( - 'cl_from' => $pageid, - 'cl_to' => $catTo ), - __METHOD__ - ); - } - - $redirid = $this->getArticleID(); - - if ( $protected ) { - # Protect the redirect title as the title used to be... - $dbw->insertSelect( 'page_restrictions', 'page_restrictions', - array( - 'pr_page' => $redirid, - 'pr_type' => 'pr_type', - 'pr_level' => 'pr_level', - 'pr_cascade' => 'pr_cascade', - 'pr_user' => 'pr_user', - 'pr_expiry' => 'pr_expiry' - ), - array( 'pr_page' => $pageid ), - __METHOD__, - array( 'IGNORE' ) - ); - # Update the protection log - $log = new LogPage( 'protect' ); - $comment = wfMessage( - 'prot_1movedto2', - $this->getPrefixedText(), - $nt->getPrefixedText() - )->inContentLanguage()->text(); - if ( $reason ) { - $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason; - } - // @todo FIXME: $params? - $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ), $wgUser ); - } - - # Update watchlists - $oldnamespace = MWNamespace::getSubject( $this->getNamespace() ); - $newnamespace = MWNamespace::getSubject( $nt->getNamespace() ); - $oldtitle = $this->getDBkey(); - $newtitle = $nt->getDBkey(); - - if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) { - WatchedItem::duplicateEntries( $this, $nt ); - } - - $dbw->commit( __METHOD__ ); - - wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) ); - return true; - } - - /** - * Move page to a title which is either a redirect to the - * source page or nonexistent - * - * @param $nt Title the page to move to, which should be a redirect or nonexistent - * @param string $reason The reason for the move - * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check - * if the user has the suppressredirect right - * @throws MWException - */ - private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) { - global $wgUser, $wgContLang; - - if ( $nt->exists() ) { - $moveOverRedirect = true; - $logType = 'move_redir'; - } else { - $moveOverRedirect = false; - $logType = 'move'; - } - - if ( $createRedirect ) { - $contentHandler = ContentHandler::getForTitle( $this ); - $redirectContent = $contentHandler->makeRedirectContent( $nt, - wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() ); - - // NOTE: If this page's content model does not support redirects, $redirectContent will be null. + $mp = new MovePage( $this, $nt ); + $status = $mp->move( $wgUser, $reason, $createRedirect ); + if ( $status->isOK() ) { + return true; } else { - $redirectContent = null; - } - - $logEntry = new ManualLogEntry( 'move', $logType ); - $logEntry->setPerformer( $wgUser ); - $logEntry->setTarget( $this ); - $logEntry->setComment( $reason ); - $logEntry->setParameters( array( - '4::target' => $nt->getPrefixedText(), - '5::noredir' => $redirectContent ? '0': '1', - ) ); - - $formatter = LogFormatter::newFromEntry( $logEntry ); - $formatter->setContext( RequestContext::newExtraneousContext( $this ) ); - $comment = $formatter->getPlainActionText(); - if ( $reason ) { - $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason; - } - # Truncate for whole multibyte characters. - $comment = $wgContLang->truncate( $comment, 255 ); - - $oldid = $this->getArticleID(); - - $dbw = wfGetDB( DB_MASTER ); - - $newpage = WikiPage::factory( $nt ); - - if ( $moveOverRedirect ) { - $newid = $nt->getArticleID(); - - # Delete the old redirect. We don't save it to history since - # by definition if we've got here it's rather uninteresting. - # We have to remove it so that the next step doesn't trigger - # a conflict on the unique namespace+title index... - $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ ); - - $newpage->doDeleteUpdates( $newid ); - } - - # Save a null revision in the page's history notifying of the move - $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true ); - if ( !is_object( $nullRevision ) ) { - throw new MWException( 'No valid null revision produced in ' . __METHOD__ ); - } - - $nullRevision->insertOn( $dbw ); - - # Change the name of the target page: - $dbw->update( 'page', - /* SET */ array( - 'page_namespace' => $nt->getNamespace(), - 'page_title' => $nt->getDBkey(), - ), - /* WHERE */ array( 'page_id' => $oldid ), - __METHOD__ - ); - - // clean up the old title before reset article id - bug 45348 - if ( !$redirectContent ) { - WikiPage::onArticleDelete( $this ); - } - - $this->resetArticleID( 0 ); // 0 == non existing - $nt->resetArticleID( $oldid ); - $newpage->loadPageData( WikiPage::READ_LOCKING ); // bug 46397 - - $newpage->updateRevisionOn( $dbw, $nullRevision ); - - wfRunHooks( 'NewRevisionFromEditComplete', - array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) ); - - $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) ); - - if ( !$moveOverRedirect ) { - WikiPage::onArticleCreate( $nt ); + return $status->getErrorsArray(); } - - # Recreate the redirect, this time in the other direction. - if ( $redirectContent ) { - $redirectArticle = WikiPage::factory( $this ); - $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // bug 46397 - $newid = $redirectArticle->insertOn( $dbw ); - if ( $newid ) { // sanity - $this->resetArticleID( $newid ); - $redirectRevision = new Revision( array( - 'title' => $this, // for determining the default content model - 'page' => $newid, - 'comment' => $comment, - 'content' => $redirectContent ) ); - $redirectRevision->insertOn( $dbw ); - $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 ); - - wfRunHooks( 'NewRevisionFromEditComplete', - array( $redirectArticle, $redirectRevision, false, $wgUser ) ); - - $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) ); - } - } - - # Log the move - $logid = $logEntry->insert(); - $logEntry->publish( $logid ); } /** * Move this page's subpages to be subpages of $nt * - * @param $nt Title Move target + * @param Title $nt Move target * @param bool $auth Whether $wgUser's permissions should be checked * @param string $reason The reason for the move * @param bool $createRedirect Whether to create redirects from the old subpages to * the new ones Ignored if the user doesn't have the 'suppressredirect' right - * @return mixed array with old page titles as keys, and strings (new page titles) or + * @return array Array with old page titles as keys, and strings (new page titles) or * arrays (errors) as values, or an error array with numeric indices if no pages * were moved */ @@ -3984,7 +3807,7 @@ class Title { foreach ( $subpages as $oldSubpage ) { $count++; if ( $count > $wgMaximumMovedPages ) { - $retval[$oldSubpage->getPrefixedTitle()] = + $retval[$oldSubpage->getPrefixedText()] = array( 'movepage-max-pages', $wgMaximumMovedPages ); break; @@ -3993,9 +3816,9 @@ class Title { // We don't know whether this function was called before // or after moving the root page, so check both // $this and $nt - if ( $oldSubpage->getArticleID() == $this->getArticleID() || - $oldSubpage->getArticleID() == $nt->getArticleID() ) - { + if ( $oldSubpage->getArticleID() == $this->getArticleID() + || $oldSubpage->getArticleID() == $nt->getArticleID() + ) { // When moving a page to a subpage of itself, // don't move it twice continue; @@ -4027,7 +3850,7 @@ class Title { * Checks if this page is just a one-rev redirect. * Adds lock, so don't use just for light purposes. * - * @return Bool + * @return bool */ public function isSingleRevRedirect() { global $wgContentHandlerUseDB; @@ -4050,7 +3873,10 @@ class Title { $this->mArticleID = $row ? intval( $row->page_id ) : 0; $this->mRedirect = $row ? (bool)$row->page_is_redirect : false; $this->mLatestID = $row ? intval( $row->page_latest ) : false; - $this->mContentModel = $row && isset( $row->page_content_model ) ? strval( $row->page_content_model ) : false; + $this->mContentModel = $row && isset( $row->page_content_model ) + ? strval( $row->page_content_model ) + : false; + if ( !$this->mRedirect ) { return false; } @@ -4073,8 +3899,8 @@ class Title { * Checks if $this can be moved to a given Title * - Selects for update, so don't call it unless you mean business * - * @param $nt Title the new title to check - * @return Bool + * @param Title $nt The new title to check + * @return bool */ public function isValidMoveTarget( $nt ) { # Is it an existing file? @@ -4120,7 +3946,7 @@ class Title { * Get categories to which this Title belongs and return an array of * categories' names. * - * @return Array of parents in the form: + * @return array Array of parents in the form: * $parent => $currentarticle */ public function getParentCategories() { @@ -4155,8 +3981,8 @@ class Title { /** * Get a tree of parent categories * - * @param array $children with the children in the keys, to check for circular refs - * @return Array Tree of parent categories + * @param array $children Array with the children in the keys, to check for circular refs + * @return array Tree of parent categories */ public function getParentCategoryTree( $children = array() ) { $stack = array(); @@ -4183,7 +4009,7 @@ class Title { * Get an associative array for selecting this title from * the "page" table * - * @return Array suitable for the $where parameter of DB::select() + * @return array Array suitable for the $where parameter of DB::select() */ public function pageCond() { if ( $this->mArticleID > 0 ) { @@ -4199,7 +4025,7 @@ class Title { * * @param int $revId Revision ID. Get the revision that was before this one. * @param int $flags Title::GAID_FOR_UPDATE - * @return Int|Bool Old revision ID, or FALSE if none exists + * @return int|bool Old revision ID, or false if none exists */ public function getPreviousRevisionID( $revId, $flags = 0 ) { $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE ); @@ -4224,7 +4050,7 @@ class Title { * * @param int $revId Revision ID. Get the revision that was after this one. * @param int $flags Title::GAID_FOR_UPDATE - * @return Int|Bool Next revision ID, or FALSE if none exists + * @return int|bool Next revision ID, or false if none exists */ public function getNextRevisionID( $revId, $flags = 0 ) { $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE ); @@ -4248,7 +4074,7 @@ class Title { * Get the first revision of the page * * @param int $flags Title::GAID_FOR_UPDATE - * @return Revision|Null if page doesn't exist + * @return Revision|null If page doesn't exist */ public function getFirstRevision( $flags = 0 ) { $pageId = $this->getArticleID( $flags ); @@ -4270,7 +4096,7 @@ class Title { * Get the oldest revision timestamp of this page * * @param int $flags Title::GAID_FOR_UPDATE - * @return String: MW timestamp + * @return string MW timestamp */ public function getEarliestRevTime( $flags = 0 ) { $rev = $this->getFirstRevision( $flags ); @@ -4299,12 +4125,32 @@ class Title { return false; } - $revCount = $this->estimateRevisionCount(); - return $revCount > $wgDeleteRevisionsLimit; + if ( $this->mIsBigDeletion === null ) { + $dbr = wfGetDB( DB_SLAVE ); + + $innerQuery = $dbr->selectSQLText( + 'revision', + '1', + array( 'rev_page' => $this->getArticleID() ), + __METHOD__, + array( 'LIMIT' => $wgDeleteRevisionsLimit + 1 ) + ); + + $revCount = $dbr->query( + 'SELECT COUNT(*) FROM (' . $innerQuery . ') AS innerQuery', + __METHOD__ + ); + $revCount = $revCount->fetchRow(); + $revCount = $revCount['COUNT(*)']; + + $this->mIsBigDeletion = $revCount > $wgDeleteRevisionsLimit; + } + + return $this->mIsBigDeletion; } /** - * Get the approximate revision count of this page. + * Get the approximate revision count of this page. * * @return int */ @@ -4328,9 +4174,10 @@ class Title { * * @param int|Revision $old Old revision or rev ID (first before range) * @param int|Revision $new New revision or rev ID (first after range) - * @return Int Number of revisions between these revisions. + * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations + * @return int Number of revisions between these revisions. */ - public function countRevisionsBetween( $old, $new ) { + public function countRevisionsBetween( $old, $new, $max = null ) { if ( !( $old instanceof Revision ) ) { $old = Revision::newFromTitle( $this, (int)$old ); } @@ -4341,20 +4188,29 @@ class Title { return 0; // nothing to compare } $dbr = wfGetDB( DB_SLAVE ); - return (int)$dbr->selectField( 'revision', 'count(*)', - array( - 'rev_page' => $this->getArticleID(), - 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ), - 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) ) - ), - __METHOD__ + $conds = array( + 'rev_page' => $this->getArticleID(), + 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ), + 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) ) ); + if ( $max !== null ) { + $res = $dbr->select( 'revision', '1', + $conds, + __METHOD__, + array( 'LIMIT' => $max + 1 ) // extra to detect truncation + ); + return $res->numRows(); + } else { + return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ ); + } } /** - * Get the number of authors between the given revisions or revision IDs. + * Get the authors between the given revisions or revision IDs. * Used for diffs and other things that really need it. * + * @since 1.23 + * * @param int|Revision $old Old revision or rev ID (first before range by default) * @param int|Revision $new New revision or rev ID (first after range by default) * @param int $limit Maximum number of authors @@ -4363,9 +4219,9 @@ class Title { * 'include_new' Include $new in the range; $old is excluded. * 'include_both' Include both $old and $new in the range. * Unknown option values are ignored. - * @return int Number of revision authors in the range; zero if not both revisions exist + * @return array|null Names of revision authors in the range; null if not both revisions exist */ - public function countAuthorsBetween( $old, $new, $limit, $options = array() ) { + public function getAuthorsBetween( $old, $new, $limit, $options = array() ) { if ( !( $old instanceof Revision ) ) { $old = Revision::newFromTitle( $this, (int)$old ); } @@ -4376,8 +4232,9 @@ class Title { // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID() // in the sanity check below? if ( !$old || !$new ) { - return 0; // nothing to compare + return null; // nothing to compare } + $authors = array(); $old_cmp = '>'; $new_cmp = '<'; $options = (array)$options; @@ -4393,12 +4250,19 @@ class Title { } // No DB query needed if $old and $new are the same or successive revisions: if ( $old->getId() === $new->getId() ) { - return ( $old_cmp === '>' && $new_cmp === '<' ) ? 0 : 1; + return ( $old_cmp === '>' && $new_cmp === '<' ) ? array() : array( $old->getRawUserText() ); } elseif ( $old->getId() === $new->getParentId() ) { - if ( $old_cmp === '>' || $new_cmp === '<' ) { - return ( $old_cmp === '>' && $new_cmp === '<' ) ? 0 : 1; + if ( $old_cmp === '>=' && $new_cmp === '<=' ) { + $authors[] = $old->getRawUserText(); + if ( $old->getRawUserText() != $new->getRawUserText() ) { + $authors[] = $new->getRawUserText(); + } + } elseif ( $old_cmp === '>=' ) { + $authors[] = $old->getRawUserText(); + } elseif ( $new_cmp === '<=' ) { + $authors[] = $new->getRawUserText(); } - return ( $old->getRawUserText() === $new->getRawUserText() ) ? 1 : 2; + return $authors; } $dbr = wfGetDB( DB_SLAVE ); $res = $dbr->select( 'revision', 'DISTINCT rev_user_text', @@ -4409,14 +4273,36 @@ class Title { ), __METHOD__, array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated ); - return (int)$dbr->numRows( $res ); + foreach ( $res as $row ) { + $authors[] = $row->rev_user_text; + } + return $authors; + } + + /** + * Get the number of authors between the given revisions or revision IDs. + * Used for diffs and other things that really need it. + * + * @param int|Revision $old Old revision or rev ID (first before range by default) + * @param int|Revision $new New revision or rev ID (first after range by default) + * @param int $limit Maximum number of authors + * @param string|array $options (Optional): Single option, or an array of options: + * 'include_old' Include $old in the range; $new is excluded. + * 'include_new' Include $new in the range; $old is excluded. + * 'include_both' Include both $old and $new in the range. + * Unknown option values are ignored. + * @return int Number of revision authors in the range; zero if not both revisions exist + */ + public function countAuthorsBetween( $old, $new, $limit, $options = array() ) { + $authors = $this->getAuthorsBetween( $old, $new, $limit, $options ); + return $authors ? count( $authors ) : 0; } /** * Compare with another title. * - * @param $title Title - * @return Bool + * @param Title $title + * @return bool */ public function equals( Title $title ) { // Note: === is necessary for proper matching of number-like titles. @@ -4428,8 +4314,8 @@ class Title { /** * Check if this title is a subpage of another title * - * @param $title Title - * @return Bool + * @param Title $title + * @return bool */ public function isSubpageOf( Title $title ) { return $this->getInterwiki() === $title->getInterwiki() @@ -4444,10 +4330,12 @@ class Title { * If you want to know if a title can be meaningfully viewed, you should * probably call the isKnown() method instead. * - * @return Bool + * @return bool */ public function exists() { - return $this->getArticleID() != 0; + $exists = $this->getArticleID() != 0; + wfRunHooks( 'TitleExists', array( $this, &$exists ) ); + return $exists; } /** @@ -4464,7 +4352,7 @@ class Title { * existing code, but we might want to add an optional parameter to skip * it and any other expensive checks.) * - * @return Bool + * @return bool */ public function isAlwaysKnown() { $isKnown = null; @@ -4477,7 +4365,7 @@ class Title { * @since 1.20 * * @param Title $title - * @param boolean|null $isKnown + * @param bool|null $isKnown */ wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) ); @@ -4485,7 +4373,7 @@ class Title { return $isKnown; } - if ( $this->mInterwiki != '' ) { + if ( $this->isExternal() ) { return true; // any interwiki link might be viewable, for all we know } @@ -4517,7 +4405,7 @@ class Title { * since LinkHolderArray calls isAlwaysKnown() and does its own * page existence check. * - * @return Bool + * @return bool */ public function isKnown() { return $this->isAlwaysKnown() || $this->exists(); @@ -4526,7 +4414,7 @@ class Title { /** * Does this page have source text? * - * @return Boolean + * @return bool */ public function hasSourceText() { if ( $this->exists() ) { @@ -4539,7 +4427,9 @@ class Title { // Use always content language to avoid loading hundreds of languages // to get the link color. global $wgContLang; - list( $name, ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) ); + list( $name, ) = MessageCache::singleton()->figureMessage( + $wgContLang->lcfirst( $this->getText() ) + ); $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false ); return $message->exists(); } @@ -4550,7 +4440,7 @@ class Title { /** * Get the default message text or false if the message doesn't exist * - * @return String or false + * @return string|bool */ public function getDefaultMessageText() { global $wgContLang; @@ -4559,7 +4449,9 @@ class Title { return false; } - list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) ); + list( $name, $lang ) = MessageCache::singleton()->figureMessage( + $wgContLang->lcfirst( $this->getText() ) + ); $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false ); if ( $message->exists() ) { @@ -4572,17 +4464,21 @@ class Title { /** * Updates page_touched for this page; called from LinksUpdate.php * - * @return Bool true if the update succeeded + * @return bool True if the update succeeded */ public function invalidateCache() { if ( wfReadOnly() ) { return false; } + if ( $this->mArticleID === 0 ) { + return true; // avoid gap locking if we know it's not there + } + $method = __METHOD__; $dbw = wfGetDB( DB_MASTER ); $conds = $this->pageCond(); - $dbw->onTransactionIdle( function() use ( $dbw, $conds, $method ) { + $dbw->onTransactionIdle( function () use ( $dbw, $conds, $method ) { $dbw->update( 'page', array( 'page_touched' => $dbw->timestamp() ), @@ -4612,11 +4508,13 @@ class Title { /** * Get the last touched timestamp * - * @param $db DatabaseBase: optional db - * @return String last-touched timestamp + * @param DatabaseBase $db Optional db + * @return string Last-touched timestamp */ public function getTouched( $db = null ) { - $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE ); + if ( $db === null ) { + $db = wfGetDB( DB_SLAVE ); + } $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ ); return $touched; } @@ -4624,8 +4522,8 @@ class Title { /** * Get the timestamp when this page was updated since the user last saw it. * - * @param $user User - * @return String|Null + * @param User $user + * @return string|null */ public function getNotificationTimestamp( $user = null ) { global $wgUser, $wgShowUpdatedMarker; @@ -4640,7 +4538,8 @@ class Title { return $this->mNotificationTimestamp[$uid]; } if ( !$uid || !$wgShowUpdatedMarker || !$user->isAllowed( 'viewmywatchlist' ) ) { - return $this->mNotificationTimestamp[$uid] = false; + $this->mNotificationTimestamp[$uid] = false; + return $this->mNotificationTimestamp[$uid]; } // Don't cache too much! if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) { @@ -4662,8 +4561,8 @@ class Title { /** * Generate strings used for xml 'id' names in monobook tabs * - * @param string $prepend defaults to 'nstab-' - * @return String XML 'id' name + * @param string $prepend Defaults to 'nstab-' + * @return string XML 'id' name */ public function getNamespaceKey( $prepend = 'nstab-' ) { global $wgContLang; @@ -4693,8 +4592,8 @@ class Title { /** * Get all extant redirects to this Title * - * @param int|Null $ns Single namespace to consider; NULL to consider all namespaces - * @return Array of Title redirects to this title + * @param int|null $ns Single namespace to consider; null to consider all namespaces + * @return Title[] Array of Title redirects to this title */ public function getRedirectsHere( $ns = null ) { $redirs = array(); @@ -4730,7 +4629,7 @@ class Title { /** * Check if this Title is a valid redirect target * - * @return Bool + * @return bool */ public function isValidRedirectTarget() { global $wgInvalidRedirectTargets; @@ -4761,7 +4660,7 @@ class Title { /** * Whether the magic words __INDEX__ and __NOINDEX__ function for this page. * - * @return Boolean + * @return bool */ public function canUseNoindex() { global $wgContentNamespaces, $wgExemptFromUserRobotsControl; @@ -4812,18 +4711,36 @@ class Title { * @return Language */ public function getPageLanguage() { - global $wgLang; + global $wgLang, $wgLanguageCode; + wfProfileIn( __METHOD__ ); if ( $this->isSpecialPage() ) { // special pages are in the user language + wfProfileOut( __METHOD__ ); return $wgLang; } - //TODO: use the LinkCache to cache this! Note that this may depend on user settings, so the cache should be only per-request. - //NOTE: ContentHandler::getPageLanguage() may need to load the content to determine the page language! - $contentHandler = ContentHandler::getForTitle( $this ); - $pageLang = $contentHandler->getPageLanguage( $this ); + // Checking if DB language is set + if ( $this->mDbPageLanguage ) { + wfProfileOut( __METHOD__ ); + return wfGetLangObj( $this->mDbPageLanguage ); + } - return wfGetLangObj( $pageLang ); + if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) { + // Note that this may depend on user settings, so the cache should + // be only per-request. + // NOTE: ContentHandler::getPageLanguage() may need to load the + // content to determine the page language! + // Checking $wgLanguageCode hasn't changed for the benefit of unit + // tests. + $contentHandler = ContentHandler::getForTitle( $this ); + $langObj = wfGetLangObj( $contentHandler->getPageLanguage( $this ) ); + $this->mPageLanguage = array( $langObj->getCode(), $wgLanguageCode ); + } else { + $langObj = wfGetLangObj( $this->mPageLanguage[0] ); + } + + wfProfileOut( __METHOD__ ); + return $langObj; } /** @@ -4848,8 +4765,9 @@ class Title { return $wgLang; } - //NOTE: can't be cached persistently, depends on user settings - //NOTE: ContentHandler::getPageViewLanguage() may need to load the content to determine the page language! + // @note Can't be cached persistently, depends on user settings. + // @note ContentHandler::getPageViewLanguage() may need to load the + // content to determine the page language! $contentHandler = ContentHandler::getForTitle( $this ); $pageLang = $contentHandler->getPageViewLanguage( $this ); return $pageLang; @@ -4862,8 +4780,8 @@ class Title { * they will already be wrapped in paragraphs. * * @since 1.21 - * @param int oldid Revision ID that's being edited - * @return Array + * @param int $oldid Revision ID that's being edited + * @return array */ public function getEditNotices( $oldid = 0 ) { $notices = array(); |