+ if ( $nsText === false ) {
+ // See T165149. Awkward, but better than erroneously linking to the main namespace.
+ $nsText = $wgContLang->getNsText( NS_SPECIAL ) . ":Badtitle/NS{$this->mNamespace}";
+ }
+
+ $p .= $nsText . ':';
+ }
+ return $p . $name;
+ }
+
+ /**
+ * Get the prefixed database key form
+ *
+ * @return string The prefixed title, with underscores and
+ * any interwiki and namespace prefixes
+ */
+ public function getPrefixedDBkey() {
+ $s = $this->prefix( $this->mDbkeyform );
+ $s = strtr( $s, ' ', '_' );
+ return $s;
+ }
+
+ /**
+ * Get the prefixed title with spaces.
+ * This is the form usually used for display
+ *
+ * @return string The prefixed title, with spaces
+ */
+ public function getPrefixedText() {
+ if ( $this->mPrefixedText === null ) {
+ $s = $this->prefix( $this->mTextform );
+ $s = strtr( $s, '_', ' ' );
+ $this->mPrefixedText = $s;
+ }
+ return $this->mPrefixedText;
+ }
+
+ /**
+ * Return a string representation of this title
+ *
+ * @return string Representation of this title
+ */
+ public function __toString() {
+ return $this->getPrefixedText();
+ }
+
+ /**
+ * Get the prefixed title with spaces, plus any fragment
+ * (part beginning with '#')
+ *
+ * @return string The prefixed title, with spaces and the fragment, including '#'
+ */
+ public function getFullText() {
+ $text = $this->getPrefixedText();
+ if ( $this->hasFragment() ) {
+ $text .= '#' . $this->getFragment();
+ }
+ return $text;
+ }
+
+ /**
+ * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
+ *
+ * @par Example:
+ * @code
+ * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
+ * # returns: 'Foo'
+ * @endcode
+ *
+ * @return string Root name
+ * @since 1.20
+ */
+ public function getRootText() {
+ if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
+ return $this->getText();
+ }
+
+ return strtok( $this->getText(), '/' );
+ }
+
+ /**
+ * Get the root page name title, i.e. the leftmost part before any slashes
+ *
+ * @par Example:
+ * @code
+ * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
+ * # returns: Title{User:Foo}
+ * @endcode
+ *
+ * @return Title Root title
+ * @since 1.20
+ */
+ public function getRootTitle() {
+ return self::makeTitle( $this->getNamespace(), $this->getRootText() );
+ }
+
+ /**
+ * Get the base page name without a namespace, i.e. the part before the subpage name
+ *
+ * @par Example:
+ * @code
+ * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
+ * # returns: 'Foo/Bar'
+ * @endcode
+ *
+ * @return string Base name
+ */
+ public function getBaseText() {
+ if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
+ return $this->getText();
+ }
+
+ $parts = explode( '/', $this->getText() );
+ # Don't discard the real title if there's no subpage involved
+ if ( count( $parts ) > 1 ) {
+ unset( $parts[count( $parts ) - 1] );
+ }
+ return implode( '/', $parts );
+ }
+
+ /**
+ * Get the base page name title, i.e. the part before the subpage name
+ *
+ * @par Example:
+ * @code
+ * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
+ * # returns: Title{User:Foo/Bar}
+ * @endcode
+ *
+ * @return Title Base title
+ * @since 1.20
+ */
+ public function getBaseTitle() {
+ return self::makeTitle( $this->getNamespace(), $this->getBaseText() );
+ }
+
+ /**
+ * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
+ *
+ * @par Example:
+ * @code
+ * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
+ * # returns: "Baz"
+ * @endcode
+ *
+ * @return string Subpage name
+ */
+ public function getSubpageText() {
+ if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
+ return $this->mTextform;
+ }
+ $parts = explode( '/', $this->mTextform );
+ return $parts[count( $parts ) - 1];
+ }
+
+ /**
+ * Get the title for a subpage of the current page
+ *
+ * @par Example:
+ * @code
+ * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
+ * # returns: Title{User:Foo/Bar/Baz/Asdf}
+ * @endcode
+ *
+ * @param string $text The subpage name to add to the title
+ * @return Title Subpage title
+ * @since 1.20
+ */
+ public function getSubpage( $text ) {
+ return self::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
+ }
+
+ /**
+ * Get a URL-encoded form of the subpage text
+ *
+ * @return string URL-encoded subpage name
+ */
+ public function getSubpageUrlForm() {
+ $text = $this->getSubpageText();
+ $text = wfUrlencode( strtr( $text, ' ', '_' ) );
+ return $text;
+ }
+
+ /**
+ * Get a URL-encoded title (not an actual URL) including interwiki
+ *
+ * @return string The URL-encoded form
+ */
+ public function getPrefixedURL() {
+ $s = $this->prefix( $this->mDbkeyform );
+ $s = wfUrlencode( strtr( $s, ' ', '_' ) );
+ return $s;
+ }
+
+ /**
+ * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
+ * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
+ * second argument named variant. This was deprecated in favor
+ * of passing an array of option with a "variant" key
+ * Once $query2 is removed for good, this helper can be dropped
+ * and the wfArrayToCgi moved to getLocalURL();
+ *
+ * @since 1.19 (r105919)
+ * @param array|string $query
+ * @param string|string[]|bool $query2
+ * @return string
+ */
+ private static function fixUrlQueryArgs( $query, $query2 = false ) {
+ if ( $query2 !== false ) {
+ wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
+ "method called with a second parameter is deprecated. Add your " .
+ "parameter to an array passed as the first parameter.", "1.19" );
+ }
+ if ( is_array( $query ) ) {
+ $query = wfArrayToCgi( $query );
+ }
+ if ( $query2 ) {
+ if ( is_string( $query2 ) ) {
+ // $query2 is a string, we will consider this to be
+ // a deprecated $variant argument and add it to the query
+ $query2 = wfArrayToCgi( [ 'variant' => $query2 ] );
+ } else {
+ $query2 = wfArrayToCgi( $query2 );
+ }
+ // If we have $query content add a & to it first
+ if ( $query ) {
+ $query .= '&';
+ }
+ // Now append the queries together
+ $query .= $query2;
+ }
+ return $query;
+ }
+
+ /**
+ * Get a real URL referring to this title, with interwiki link and
+ * fragment
+ *
+ * @see self::getLocalURL for the arguments.
+ * @see wfExpandUrl
+ * @param string|string[] $query
+ * @param string|string[]|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 );
+
+ # Hand off all the decisions on urls to getLocalURL
+ $url = $this->getLocalURL( $query );
+
+ # Expand the url to make it a full url. Note that getLocalURL has the
+ # potential to output full urls for a variety of reasons, so we use
+ # wfExpandUrl instead of simply prepending $wgServer
+ $url = wfExpandUrl( $url, $proto );
+
+ # Finally, add the fragment.
+ $url .= $this->getFragmentForURL();
+ // Avoid PHP 7.1 warning from passing $this by reference
+ $titleRef = $this;
+ Hooks::run( 'GetFullURL', [ &$titleRef, &$url, $query ] );
+ return $url;
+ }
+
+ /**
+ * Get a url appropriate for making redirects based on an untrusted url arg
+ *
+ * This is basically the same as getFullUrl(), but in the case of external
+ * interwikis, we send the user to a landing page, to prevent possible
+ * phishing attacks and the like.
+ *
+ * @note Uses current protocol by default, since technically relative urls
+ * aren't allowed in redirects per HTTP spec, so this is not suitable for
+ * places where the url gets cached, as might pollute between
+ * https and non-https users.
+ * @see self::getLocalURL for the arguments.
+ * @param array|string $query
+ * @param string $proto Protocol type to use in URL
+ * @return string A url suitable to use in an HTTP location header.
+ */
+ public function getFullUrlForRedirect( $query = '', $proto = PROTO_CURRENT ) {
+ $target = $this;
+ if ( $this->isExternal() ) {
+ $target = SpecialPage::getTitleFor(
+ 'GoToInterwiki',
+ $this->getPrefixedDBKey()
+ );
+ }
+ return $target->getFullUrl( $query, false, $proto );
+ }
+
+ /**
+ * 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|string[] $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 string|string[]|bool $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 String of the URL.
+ */
+ public function getLocalURL( $query = '', $query2 = false ) {
+ global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
+
+ $query = self::fixUrlQueryArgs( $query, $query2 );
+
+ $interwiki = self::getInterwikiLookup()->fetch( $this->mInterwiki );
+ if ( $interwiki ) {
+ $namespace = $this->getNsText();
+ if ( $namespace != '' ) {
+ # Can this actually happen? Interwikis shouldn't be parsed.
+ # Yes! It can in interwiki transclusion. But... it probably shouldn't.
+ $namespace .= ':';
+ }
+ $url = $interwiki->getURL( $namespace . $this->getDBkey() );
+ $url = wfAppendQuery( $url, $query );
+ } else {
+ $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
+ if ( $query == '' ) {
+ $url = str_replace( '$1', $dbkey, $wgArticlePath );
+ // Avoid PHP 7.1 warning from passing $this by reference
+ $titleRef = $this;
+ Hooks::run( 'GetLocalURL::Article', [ &$titleRef, &$url ] );
+ } else {
+ global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
+ $url = false;
+ $matches = [];
+
+ if ( !empty( $wgActionPaths )
+ && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
+ ) {
+ $action = urldecode( $matches[2] );
+ if ( isset( $wgActionPaths[$action] ) ) {
+ $query = $matches[1];
+ if ( isset( $matches[4] ) ) {
+ $query .= $matches[4];
+ }
+ $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
+ if ( $query != '' ) {
+ $url = wfAppendQuery( $url, $query );
+ }
+ }
+ }
+
+ if ( $url === false
+ && $wgVariantArticlePath
+ && preg_match( '/^variant=([^&]*)$/', $query, $matches )
+ && $this->getPageLanguage()->equals( $wgContLang )
+ && $this->getPageLanguage()->hasVariants()
+ ) {
+ $variant = urldecode( $matches[1] );
+ if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
+ // Only do the variant replacement if the given variant is a valid
+ // variant for the page's language.
+ $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
+ $url = str_replace( '$1', $dbkey, $url );
+ }
+ }
+
+ if ( $url === false ) {
+ if ( $query == '-' ) {
+ $query = '';
+ }
+ $url = "{$wgScript}?title={$dbkey}&{$query}";
+ }
+ }
+ // Avoid PHP 7.1 warning from passing $this by reference
+ $titleRef = $this;
+ Hooks::run( 'GetLocalURL::Internal', [ &$titleRef, &$url, $query ] );
+
+ // @todo FIXME: This causes breakage in various places when we
+ // actually expected a local URL and end up with dupe prefixes.
+ if ( $wgRequest->getVal( 'action' ) == 'render' ) {
+ $url = $wgServer . $url;
+ }
+ }
+ // Avoid PHP 7.1 warning from passing $this by reference
+ $titleRef = $this;
+ Hooks::run( 'GetLocalURL', [ &$titleRef, &$url, $query ] );
+ return $url;
+ }
+
+ /**
+ * Get a URL that's the simplest URL that will be valid to link, locally,
+ * to the current Title. It includes the fragment, but does not include
+ * the server unless action=render is used (or the link is external). If
+ * there's a fragment but the prefixed text is empty, we just return a link
+ * to the fragment.
+ *
+ * The result obviously should not be URL-escaped, but does need to be
+ * HTML-escaped if it's being output in HTML.
+ *
+ * @param string|string[] $query
+ * @param bool $query2
+ * @param string|int|bool $proto A PROTO_* constant on how the URL should be expanded,
+ * or false (default) for no expansion
+ * @see self::getLocalURL for the arguments.
+ * @return string The URL
+ */
+ public function getLinkURL( $query = '', $query2 = false, $proto = false ) {
+ if ( $this->isExternal() || $proto !== false ) {
+ $ret = $this->getFullURL( $query, $query2, $proto );
+ } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
+ $ret = $this->getFragmentForURL();
+ } else {
+ $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
+ }
+ return $ret;
+ }
+
+ /**
+ * Get the URL form for an internal link.
+ * - Used in various CDN-related code, in case we have a different
+ * internal hostname for the server from the exposed one.
+ *
+ * This uses $wgInternalServer to qualify the path, or $wgServer
+ * if $wgInternalServer is not set. If the server variable used is
+ * protocol-relative, the URL will be expanded to http://
+ *
+ * @see self::getLocalURL for the arguments.
+ * @param string $query
+ * @param string|bool $query2
+ * @return string The URL
+ */
+ public function getInternalURL( $query = '', $query2 = false ) {
+ global $wgInternalServer, $wgServer;
+ $query = self::fixUrlQueryArgs( $query, $query2 );
+ $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
+ $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
+ // Avoid PHP 7.1 warning from passing $this by reference
+ $titleRef = $this;
+ Hooks::run( 'GetInternalURL', [ &$titleRef, &$url, $query ] );
+ return $url;
+ }
+
+ /**
+ * Get the URL for a canonical link, for use in things like IRC and
+ * e-mail notifications. Uses $wgCanonicalServer and the
+ * GetCanonicalURL hook.
+ *
+ * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
+ *
+ * @see self::getLocalURL for the arguments.
+ * @param string $query
+ * @param string|bool $query2
+ * @return string The URL
+ * @since 1.18
+ */
+ public function getCanonicalURL( $query = '', $query2 = false ) {
+ $query = self::fixUrlQueryArgs( $query, $query2 );
+ $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
+ // Avoid PHP 7.1 warning from passing $this by reference
+ $titleRef = $this;
+ Hooks::run( 'GetCanonicalURL', [ &$titleRef, &$url, $query ] );
+ return $url;
+ }
+
+ /**
+ * Get the edit URL for this Title
+ *
+ * @return string The URL, or a null string if this is an interwiki link
+ */
+ public function getEditURL() {
+ if ( $this->isExternal() ) {
+ return '';
+ }
+ $s = $this->getLocalURL( 'action=edit' );
+
+ return $s;
+ }
+
+ /**
+ * Can $user perform $action on this page?
+ * This skips potentially expensive cascading permission checks
+ * as well as avoids expensive error formatting
+ *
+ * Suitable for use for nonessential UI controls in common cases, but
+ * _not_ for functional access control.
+ *
+ * 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 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 );
+ }
+
+ /**
+ * Can $user perform $action on this page?
+ *
+ * @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 string $rigor Same format as Title::getUserPermissionsErrors()
+ * @return bool
+ */
+ public function userCan( $action, $user = null, $rigor = 'secure' ) {
+ if ( !$user instanceof User ) {
+ global $wgUser;
+ $user = $wgUser;
+ }
+
+ return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $rigor, true ) );
+ }
+
+ /**
+ * Can $user perform $action on this page?
+ *
+ * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
+ *
+ * @param string $action Action that permission needs to be checked for
+ * @param User $user User to check
+ * @param string $rigor One of (quick,full,secure)
+ * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
+ * - full : does cheap and expensive checks possibly from a replica DB
+ * - secure : does cheap and expensive checks, using the master as needed
+ * @param array $ignoreErrors Array of Strings Set this to a list of message keys
+ * whose corresponding errors may be ignored.
+ * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
+ */
+ public function getUserPermissionsErrors(
+ $action, $user, $rigor = 'secure', $ignoreErrors = []
+ ) {
+ $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $rigor );
+
+ // Remove the errors being ignored.
+ foreach ( $errors as $index => $error ) {
+ $errKey = is_array( $error ) ? $error[0] : $error;
+
+ if ( in_array( $errKey, $ignoreErrors ) ) {
+ unset( $errors[$index] );
+ }
+ if ( $errKey instanceof MessageSpecifier && in_array( $errKey->getKey(), $ignoreErrors ) ) {
+ unset( $errors[$index] );
+ }
+ }
+
+ return $errors;
+ }
+
+ /**
+ * 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 string $rigor Same format as Title::getUserPermissionsErrors()
+ * @param bool $short Short circuit on first error
+ *
+ * @return array List of errors
+ */
+ private function checkQuickPermissions( $action, $user, $errors, $rigor, $short ) {
+ if ( !Hooks::run( 'TitleQuickPermissions',
+ [ $this, $user, $action, &$errors, ( $rigor !== 'quick' ), $short ] )
+ ) {
+ return $errors;
+ }
+
+ if ( $action == 'create' ) {
+ if (
+ ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
+ ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
+ ) {
+ $errors[] = $user->isAnon() ? [ 'nocreatetext' ] : [ 'nocreate-loggedin' ];
+ }
+ } elseif ( $action == 'move' ) {
+ if ( !$user->isAllowed( 'move-rootuserpages' )
+ && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
+ // Show user page-specific message only if the user can move other pages
+ $errors[] = [ 'cant-move-user-page' ];
+ }
+
+ // Check if user is allowed to move files if it's a file
+ if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
+ $errors[] = [ '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[] = [ 'cant-move-category-page' ];
+ }
+
+ if ( !$user->isAllowed( 'move' ) ) {
+ // User can't move anything
+ $userCanMove = User::groupHasPermission( 'user', 'move' );
+ $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
+ if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
+ // custom message if logged-in users without any special rights can move
+ $errors[] = [ 'movenologintext' ];
+ } else {
+ $errors[] = [ 'movenotallowed' ];
+ }
+ }
+ } elseif ( $action == 'move-target' ) {
+ if ( !$user->isAllowed( 'move' ) ) {
+ // User can't move anything
+ $errors[] = [ 'movenotallowed' ];
+ } elseif ( !$user->isAllowed( 'move-rootuserpages' )
+ && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
+ // Show user page-specific message only if the user can move other pages
+ $errors[] = [ '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[] = [ 'cant-move-to-category-page' ];
+ }
+ } elseif ( !$user->isAllowed( $action ) ) {
+ $errors[] = $this->missingPermissionError( $action, $short );
+ }
+
+ return $errors;
+ }
+
+ /**
+ * Add the resulting error code to the errors array
+ *
+ * @param array $errors List of current errors
+ * @param array $result Result of errors
+ *
+ * @return array List of errors
+ */
+ private function resultToError( $errors, $result ) {
+ if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
+ // A single array representing an error
+ $errors[] = $result;
+ } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
+ // A nested array representing multiple errors
+ $errors = array_merge( $errors, $result );
+ } elseif ( $result !== '' && is_string( $result ) ) {
+ // A string representing a message-id
+ $errors[] = [ $result ];
+ } elseif ( $result instanceof MessageSpecifier ) {
+ // A message specifier representing an error
+ $errors[] = [ $result ];
+ } elseif ( $result === false ) {
+ // a generic "We don't want them to do that"
+ $errors[] = [ 'badaccess-group0' ];
+ }
+ return $errors;
+ }
+
+ /**
+ * 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 string $rigor Same format as Title::getUserPermissionsErrors()
+ * @param bool $short Short circuit on first error
+ *
+ * @return array List of errors
+ */
+ private function checkPermissionHooks( $action, $user, $errors, $rigor, $short ) {
+ // Use getUserPermissionsErrors instead
+ $result = '';
+ // Avoid PHP 7.1 warning from passing $this by reference
+ $titleRef = $this;
+ if ( !Hooks::run( 'userCan', [ &$titleRef, &$user, $action, &$result ] ) ) {
+ return $result ? [] : [ [ 'badaccess-group0' ] ];
+ }
+ // Check getUserPermissionsErrors hook
+ // Avoid PHP 7.1 warning from passing $this by reference
+ $titleRef = $this;
+ if ( !Hooks::run( 'getUserPermissionsErrors', [ &$titleRef, &$user, $action, &$result ] ) ) {
+ $errors = $this->resultToError( $errors, $result );
+ }
+ // Check getUserPermissionsErrorsExpensive hook
+ if (
+ $rigor !== 'quick'
+ && !( $short && count( $errors ) > 0 )
+ && !Hooks::run( 'getUserPermissionsErrorsExpensive', [ &$titleRef, &$user, $action, &$result ] )
+ ) {
+ $errors = $this->resultToError( $errors, $result );
+ }
+
+ return $errors;
+ }
+
+ /**
+ * 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 string $rigor Same format as Title::getUserPermissionsErrors()
+ * @param bool $short Short circuit on first error
+ *
+ * @return array List of errors
+ */
+ private function checkSpecialsAndNSPermissions( $action, $user, $errors, $rigor, $short ) {
+ # Only 'createaccount' can be performed on special pages,
+ # which don't actually exist in the DB.
+ if ( $this->isSpecialPage() && $action !== 'createaccount' ) {
+ $errors[] = [ 'ns-specialprotected' ];
+ }
+
+ # Check $wgNamespaceProtection for restricted namespaces
+ if ( $this->isNamespaceProtected( $user ) ) {
+ $ns = $this->mNamespace == NS_MAIN ?
+ wfMessage( 'nstab-main' )->text() : $this->getNsText();
+ $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
+ [ 'protectedinterface', $action ] : [ 'namespaceprotected', $ns, $action ];
+ }
+
+ return $errors;
+ }
+
+ /**
+ * 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 string $rigor Same format as Title::getUserPermissionsErrors()
+ * @param bool $short Short circuit on first error
+ *
+ * @return array List of errors
+ */
+ private function checkCSSandJSPermissions( $action, $user, $errors, $rigor, $short ) {
+ # Protect css/js subpages of user pages
+ # XXX: this might be better using restrictions
+ if ( $action != 'patrol' ) {
+ if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
+ if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
+ $errors[] = [ 'mycustomcssprotected', $action ];
+ } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
+ $errors[] = [ 'mycustomjsprotected', $action ];
+ }
+ } else {
+ if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
+ $errors[] = [ 'customcssprotected', $action ];
+ } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
+ $errors[] = [ 'customjsprotected', $action ];
+ }
+ }
+ }
+
+ return $errors;
+ }
+
+ /**
+ * Check against page_restrictions table requirements on this
+ * 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 string $rigor Same format as Title::getUserPermissionsErrors()
+ * @param bool $short Short circuit on first error
+ *
+ * @return array List of errors
+ */
+ private function checkPageRestrictions( $action, $user, $errors, $rigor, $short ) {
+ foreach ( $this->getRestrictions( $action ) as $right ) {
+ // Backwards compatibility, rewrite sysop -> editprotected
+ if ( $right == 'sysop' ) {
+ $right = 'editprotected';
+ }
+ // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
+ if ( $right == 'autoconfirmed' ) {
+ $right = 'editsemiprotected';
+ }
+ if ( $right == '' ) {
+ continue;
+ }
+ if ( !$user->isAllowed( $right ) ) {
+ $errors[] = [ 'protectedpagetext', $right, $action ];
+ } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
+ $errors[] = [ 'protectedpagetext', 'protect', $action ];
+ }
+ }
+
+ return $errors;
+ }
+
+ /**
+ * Check restrictions on cascading pages.
+ *
+ * @param string $action The action to check
+ * @param User $user User to check
+ * @param array $errors List of current errors
+ * @param string $rigor Same format as Title::getUserPermissionsErrors()
+ * @param bool $short Short circuit on first error
+ *
+ * @return array List of errors
+ */
+ private function checkCascadingSourcesRestrictions( $action, $user, $errors, $rigor, $short ) {
+ if ( $rigor !== 'quick' && !$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
+ # included by multiple cascade-protected pages. So just restrict
+ # it to people with 'protect' permission, as they could remove the
+ # protection anyway.
+ list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
+ # Cascading protection depends on more than this page...
+ # Several cascading protected pages may include this page...
+ # Check each cascading level
+ # This is only for protection restrictions, not for all actions
+ if ( isset( $restrictions[$action] ) ) {
+ foreach ( $restrictions[$action] as $right ) {
+ // Backwards compatibility, rewrite sysop -> editprotected
+ if ( $right == 'sysop' ) {
+ $right = 'editprotected';
+ }
+ // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
+ if ( $right == 'autoconfirmed' ) {
+ $right = 'editsemiprotected';
+ }
+ if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
+ $pages = '';
+ foreach ( $cascadingSources as $page ) {
+ $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
+ }
+ $errors[] = [ 'cascadeprotected', count( $cascadingSources ), $pages, $action ];
+ }
+ }
+ }
+ }
+
+ return $errors;
+ }
+
+ /**
+ * Check action permissions not already checked in checkQuickPermissions
+ *
+ * @param string $action The action to check
+ * @param User $user User to check
+ * @param array $errors List of current errors
+ * @param string $rigor Same format as Title::getUserPermissionsErrors()
+ * @param bool $short Short circuit on first error
+ *
+ * @return array List of errors
+ */
+ private function checkActionPermissions( $action, $user, $errors, $rigor, $short ) {
+ global $wgDeleteRevisionsLimit, $wgLang;
+
+ if ( $action == 'protect' ) {
+ if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
+ // If they can't edit, they shouldn't protect.
+ $errors[] = [ 'protect-cantedit' ];
+ }
+ } elseif ( $action == 'create' ) {
+ $title_protection = $this->getTitleProtection();
+ if ( $title_protection ) {
+ if ( $title_protection['permission'] == ''
+ || !$user->isAllowed( $title_protection['permission'] )
+ ) {
+ $errors[] = [
+ 'titleprotected',
+ User::whoIs( $title_protection['user'] ),
+ $title_protection['reason']
+ ];
+ }
+ }
+ } elseif ( $action == 'move' ) {
+ // Check for immobile pages
+ if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
+ // Specific message for this case
+ $errors[] = [ 'immobile-source-namespace', $this->getNsText() ];
+ } elseif ( !$this->isMovable() ) {
+ // Less specific message for rarer cases
+ $errors[] = [ 'immobile-source-page' ];
+ }
+ } elseif ( $action == 'move-target' ) {
+ if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
+ $errors[] = [ 'immobile-target-namespace', $this->getNsText() ];
+ } elseif ( !$this->isMovable() ) {
+ $errors[] = [ 'immobile-target-page' ];
+ }
+ } elseif ( $action == 'delete' ) {
+ $tempErrors = $this->checkPageRestrictions( 'edit', $user, [], $rigor, true );
+ if ( !$tempErrors ) {
+ $tempErrors = $this->checkCascadingSourcesRestrictions( 'edit',
+ $user, $tempErrors, $rigor, true );
+ }
+ if ( $tempErrors ) {
+ // If protection keeps them from editing, they shouldn't be able to delete.
+ $errors[] = [ 'deleteprotected' ];
+ }
+ if ( $rigor !== 'quick' && $wgDeleteRevisionsLimit
+ && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
+ ) {
+ $errors[] = [ 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) ];
+ }
+ } elseif ( $action === 'undelete' ) {
+ if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $rigor, true ) ) ) {
+ // Undeleting implies editing
+ $errors[] = [ 'undelete-cantedit' ];
+ }
+ if ( !$this->exists()
+ && count( $this->getUserPermissionsErrorsInternal( 'create', $user, $rigor, true ) )
+ ) {
+ // Undeleting where nothing currently exists implies creating
+ $errors[] = [ 'undelete-cantcreate' ];
+ }
+ }
+ return $errors;
+ }
+
+ /**
+ * Check that the user isn't blocked from editing.
+ *
+ * @param string $action The action to check
+ * @param User $user User to check
+ * @param array $errors List of current errors
+ * @param string $rigor Same format as Title::getUserPermissionsErrors()
+ * @param bool $short Short circuit on first error
+ *
+ * @return array List of errors
+ */
+ private function checkUserBlock( $action, $user, $errors, $rigor, $short ) {
+ global $wgEmailConfirmToEdit, $wgBlockDisablesLogin;
+ // Account creation blocks handled at userlogin.
+ // Unblocking handled in SpecialUnblock
+ if ( $rigor === 'quick' || in_array( $action, [ 'createaccount', 'unblock' ] ) ) {
+ return $errors;
+ }
+
+ // Optimize for a very common case
+ if ( $action === 'read' && !$wgBlockDisablesLogin ) {
+ return $errors;
+ }
+
+ if ( $wgEmailConfirmToEdit
+ && !$user->isEmailConfirmed()
+ && $action === 'edit'
+ ) {
+ $errors[] = [ 'confirmedittext' ];
+ }
+
+ $useSlave = ( $rigor !== 'secure' );
+ if ( ( $action == 'edit' || $action == 'create' )
+ && !$user->isBlockedFrom( $this, $useSlave )
+ ) {
+ // Don't block the user from editing their own talk page unless they've been
+ // explicitly blocked from that too.
+ } elseif ( $user->isBlocked() && $user->getBlock()->prevents( $action ) !== false ) {
+ // @todo FIXME: Pass the relevant context into this function.
+ $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
+ }
+
+ return $errors;
+ }
+
+ /**
+ * Check that the user is allowed to read this page.
+ *
+ * @param string $action The action to check
+ * @param User $user User to check
+ * @param array $errors List of current errors
+ * @param string $rigor Same format as Title::getUserPermissionsErrors()
+ * @param bool $short Short circuit on first error
+ *
+ * @return array List of errors
+ */
+ private function checkReadPermissions( $action, $user, $errors, $rigor, $short ) {
+ global $wgWhitelistRead, $wgWhitelistReadRegexp;
+
+ $whitelisted = false;
+ if ( User::isEveryoneAllowed( 'read' ) ) {
+ # Shortcut for public wikis, allows skipping quite a bit of code
+ $whitelisted = true;
+ } elseif ( $user->isAllowed( 'read' ) ) {
+ # If the user is allowed to read pages, he is allowed to read all pages
+ $whitelisted = true;
+ } elseif ( $this->isSpecial( 'Userlogin' )
+ || $this->isSpecial( 'PasswordReset' )
+ || $this->isSpecial( 'Userlogout' )
+ ) {
+ # Always grant access to the login page.
+ # Even anons need to be able to log in.
+ $whitelisted = true;
+ } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
+ # Time to check the whitelist
+ # Only do these checks is there's something to check against
+ $name = $this->getPrefixedText();
+ $dbName = $this->getPrefixedDBkey();
+
+ // Check for explicit whitelisting with and without underscores
+ if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
+ $whitelisted = true;
+ } elseif ( $this->getNamespace() == NS_MAIN ) {
+ # Old settings might have the title prefixed with
+ # a colon for main-namespace pages
+ if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
+ $whitelisted = true;
+ }
+ } elseif ( $this->isSpecialPage() ) {
+ # If it's a special page, ditch the subpage bit and check again
+ $name = $this->getDBkey();
+ list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
+ if ( $name ) {
+ $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
+ if ( in_array( $pure, $wgWhitelistRead, true ) ) {
+ $whitelisted = true;
+ }
+ }
+ }
+ }
+
+ if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
+ $name = $this->getPrefixedText();
+ // Check for regex whitelisting
+ foreach ( $wgWhitelistReadRegexp as $listItem ) {
+ if ( preg_match( $listItem, $name ) ) {
+ $whitelisted = true;
+ break;
+ }
+ }
+ }
+
+ if ( !$whitelisted ) {
+ # If the title is not whitelisted, give extensions a chance to do so...
+ Hooks::run( 'TitleReadWhitelist', [ $this, $user, &$whitelisted ] );
+ if ( !$whitelisted ) {
+ $errors[] = $this->missingPermissionError( $action, $short );
+ }
+ }
+
+ return $errors;
+ }
+
+ /**
+ * 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 bool $short Short circuit on first error
+ * @return array Array containing an error message key and any parameters
+ */
+ private function missingPermissionError( $action, $short ) {
+ // We avoid expensive display logic for quickUserCan's and such
+ if ( $short ) {
+ return [ 'badaccess-group0' ];
+ }
+
+ return User::newFatalPermissionDeniedStatus( $action )->getErrorsArray()[0];
+ }
+
+ /**
+ * Can $user perform $action on this page? This is an internal function,
+ * with multiple levels of checks depending on performance needs; see $rigor below.
+ * It does not check wfReadOnly().
+ *
+ * @param string $action Action that permission needs to be checked for
+ * @param User $user User to check
+ * @param string $rigor One of (quick,full,secure)
+ * - quick : does cheap permission checks from replica DBs (usable for GUI creation)
+ * - full : does cheap and expensive checks possibly from a replica DB
+ * - secure : does cheap and expensive checks, using the master as needed
+ * @param bool $short Set this to true to stop after the first permission error.
+ * @return array Array of arrays of the arguments to wfMessage to explain permissions problems.
+ */
+ protected function getUserPermissionsErrorsInternal(
+ $action, $user, $rigor = 'secure', $short = false
+ ) {
+ if ( $rigor === true ) {
+ $rigor = 'secure'; // b/c
+ } elseif ( $rigor === false ) {
+ $rigor = 'quick'; // b/c
+ } elseif ( !in_array( $rigor, [ 'quick', 'full', 'secure' ] ) ) {
+ throw new Exception( "Invalid rigor parameter '$rigor'." );
+ }
+
+ # Read has special handling
+ if ( $action == 'read' ) {
+ $checks = [
+ 'checkPermissionHooks',
+ 'checkReadPermissions',
+ 'checkUserBlock', // for wgBlockDisablesLogin
+ ];
+ # 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 = [
+ 'checkQuickPermissions',
+ 'checkPermissionHooks',
+ 'checkPageRestrictions',
+ 'checkCascadingSourcesRestrictions',
+ 'checkActionPermissions',
+ 'checkUserBlock'
+ ];
+ } else {
+ $checks = [
+ 'checkQuickPermissions',
+ 'checkPermissionHooks',
+ 'checkSpecialsAndNSPermissions',
+ 'checkCSSandJSPermissions',
+ 'checkPageRestrictions',
+ 'checkCascadingSourcesRestrictions',
+ 'checkActionPermissions',
+ 'checkUserBlock'
+ ];
+ }
+
+ $errors = [];
+ while ( count( $checks ) > 0 &&
+ !( $short && count( $errors ) > 0 ) ) {
+ $method = array_shift( $checks );
+ $errors = $this->$method( $action, $user, $errors, $rigor, $short );
+ }
+
+ return $errors;
+ }
+
+ /**
+ * Get a filtered list of all restriction types supported by this wiki.
+ * @param bool $exists True to get all restriction types that apply to
+ * titles that do exist, False for all restriction types that apply to
+ * titles that do not exist
+ * @return array
+ */
+ public static function getFilteredRestrictionTypes( $exists = true ) {
+ global $wgRestrictionTypes;
+ $types = $wgRestrictionTypes;
+ if ( $exists ) {
+ # Remove the create restriction for existing titles
+ $types = array_diff( $types, [ 'create' ] );
+ } else {
+ # Only the create and upload restrictions apply to non-existing titles
+ $types = array_intersect( $types, [ 'create', 'upload' ] );
+ }
+ return $types;
+ }
+
+ /**
+ * Returns restriction types for the current Title
+ *
+ * @return array Applicable restriction types
+ */
+ public function getRestrictionTypes() {
+ if ( $this->isSpecialPage() ) {
+ return [];
+ }
+
+ $types = self::getFilteredRestrictionTypes( $this->exists() );
+
+ if ( $this->getNamespace() != NS_FILE ) {
+ # Remove the upload restriction for non-file titles
+ $types = array_diff( $types, [ 'upload' ] );
+ }
+
+ Hooks::run( 'TitleGetRestrictionTypes', [ $this, &$types ] );
+
+ wfDebug( __METHOD__ . ': applicable restrictions to [[' .
+ $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
+
+ return $types;
+ }
+
+ /**
+ * Is this title subject to title protection?
+ * Title protection is the one applied against creation of such title.
+ *
+ * @return array|bool An associative array representing any existent title
+ * protection, or false if there's none.
+ */
+ public function getTitleProtection() {
+ $protection = $this->getTitleProtectionInternal();
+ if ( $protection ) {
+ if ( $protection['permission'] == 'sysop' ) {
+ $protection['permission'] = 'editprotected'; // B/C
+ }
+ if ( $protection['permission'] == 'autoconfirmed' ) {
+ $protection['permission'] = 'editsemiprotected'; // B/C
+ }
+ }
+ return $protection;
+ }
+
+ /**
+ * Fetch title protection settings
+ *
+ * To work correctly, $this->loadRestrictions() needs to have access to the
+ * actual protections in the database without munging 'sysop' =>
+ * 'editprotected' and 'autoconfirmed' => 'editsemiprotected'. Other
+ * callers probably want $this->getTitleProtection() instead.
+ *
+ * @return array|bool
+ */
+ protected function getTitleProtectionInternal() {
+ // Can't protect pages in special namespaces
+ if ( $this->getNamespace() < 0 ) {
+ return false;
+ }
+
+ // Can't protect pages that exist.
+ if ( $this->exists() ) {
+ return false;
+ }
+
+ if ( $this->mTitleProtection === null ) {
+ $dbr = wfGetDB( DB_REPLICA );
+ $commentStore = new CommentStore( 'pt_reason' );
+ $commentQuery = $commentStore->getJoin();
+ $res = $dbr->select(
+ [ 'protected_titles' ] + $commentQuery['tables'],
+ [
+ 'user' => 'pt_user',
+ 'expiry' => 'pt_expiry',
+ 'permission' => 'pt_create_perm'
+ ] + $commentQuery['fields'],
+ [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
+ __METHOD__,
+ [],
+ $commentQuery['joins']
+ );
+
+ // fetchRow returns false if there are no rows.
+ $row = $dbr->fetchRow( $res );
+ if ( $row ) {
+ $this->mTitleProtection = [
+ 'user' => $row['user'],
+ 'expiry' => $dbr->decodeExpiry( $row['expiry'] ),
+ 'permission' => $row['permission'],
+ 'reason' => $commentStore->getComment( $row )->text,
+ ];
+ } else {
+ $this->mTitleProtection = false;
+ }
+ }
+ return $this->mTitleProtection;
+ }
+
+ /**
+ * Remove any title protection due to page existing
+ */
+ public function deleteTitleProtection() {
+ $dbw = wfGetDB( DB_MASTER );
+
+ $dbw->delete(
+ 'protected_titles',
+ [ 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ],
+ __METHOD__
+ );
+ $this->mTitleProtection = false;
+ }
+
+ /**
+ * Is this page "semi-protected" - the *only* protection levels are listed
+ * in $wgSemiprotectedRestrictionLevels?
+ *
+ * @param string $action Action to check (default: edit)
+ * @return bool
+ */
+ public function isSemiProtected( $action = 'edit' ) {
+ global $wgSemiprotectedRestrictionLevels;
+
+ $restrictions = $this->getRestrictions( $action );
+ $semi = $wgSemiprotectedRestrictionLevels;
+ if ( !$restrictions || !$semi ) {
+ // Not protected, or all protection is full protection
+ return false;
+ }
+
+ // Remap autoconfirmed to editsemiprotected for BC
+ foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
+ $semi[$key] = 'editsemiprotected';
+ }
+ foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
+ $restrictions[$key] = 'editsemiprotected';
+ }
+
+ return !array_diff( $restrictions, $semi );
+ }
+
+ /**
+ * Does the title correspond to a protected article?
+ *
+ * @param string $action The action the page is protected from,
+ * by default checks all actions.
+ * @return bool
+ */
+ public function isProtected( $action = '' ) {
+ global $wgRestrictionLevels;
+
+ $restrictionTypes = $this->getRestrictionTypes();
+
+ # Special pages have inherent protection
+ if ( $this->isSpecialPage() ) {
+ return true;
+ }
+
+ # Check regular protection levels
+ foreach ( $restrictionTypes as $type ) {
+ if ( $action == $type || $action == '' ) {
+ $r = $this->getRestrictions( $type );
+ foreach ( $wgRestrictionLevels as $level ) {
+ if ( in_array( $level, $r ) && $level != '' ) {
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Determines if $user is unable to edit this page because it has been protected
+ * by $wgNamespaceProtection.
+ *
+ * @param User $user User object to check permissions
+ * @return bool
+ */
+ public function isNamespaceProtected( User $user ) {
+ global $wgNamespaceProtection;
+
+ if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
+ foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
+ if ( $right != '' && !$user->isAllowed( $right ) ) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
+ *
+ * @return bool If the page is subject to cascading restrictions.
+ */
+ public function isCascadeProtected() {
+ list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
+ return ( $sources > 0 );
+ }
+
+ /**
+ * 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 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 ) {
+ $pagerestrictions = [];
+
+ if ( $this->mCascadeSources !== null && $getPages ) {
+ return [ $this->mCascadeSources, $this->mCascadingRestrictions ];
+ } elseif ( $this->mHasCascadingRestrictions !== null && !$getPages ) {
+ return [ $this->mHasCascadingRestrictions, $pagerestrictions ];
+ }
+
+ $dbr = wfGetDB( DB_REPLICA );
+
+ if ( $this->getNamespace() == NS_FILE ) {
+ $tables = [ 'imagelinks', 'page_restrictions' ];
+ $where_clauses = [
+ 'il_to' => $this->getDBkey(),
+ 'il_from=pr_page',
+ 'pr_cascade' => 1
+ ];
+ } else {
+ $tables = [ 'templatelinks', 'page_restrictions' ];
+ $where_clauses = [
+ 'tl_namespace' => $this->getNamespace(),
+ 'tl_title' => $this->getDBkey(),
+ 'tl_from=pr_page',
+ 'pr_cascade' => 1
+ ];
+ }
+
+ if ( $getPages ) {
+ $cols = [ 'pr_page', 'page_namespace', 'page_title',
+ 'pr_expiry', 'pr_type', 'pr_level' ];
+ $where_clauses[] = 'page_id=pr_page';
+ $tables[] = 'page';
+ } else {
+ $cols = [ 'pr_expiry' ];
+ }
+
+ $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
+
+ $sources = $getPages ? [] : false;
+ $now = wfTimestampNow();
+
+ foreach ( $res as $row ) {
+ $expiry = $dbr->decodeExpiry( $row->pr_expiry );
+ if ( $expiry > $now ) {
+ if ( $getPages ) {
+ $page_id = $row->pr_page;
+ $page_ns = $row->page_namespace;
+ $page_title = $row->page_title;
+ $sources[$page_id] = self::makeTitle( $page_ns, $page_title );
+ # Add groups needed for each restriction type if its not already there
+ # Make sure this restriction type still exists
+
+ if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
+ $pagerestrictions[$row->pr_type] = [];
+ }
+
+ if (
+ isset( $pagerestrictions[$row->pr_type] )
+ && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
+ ) {
+ $pagerestrictions[$row->pr_type][] = $row->pr_level;
+ }
+ } else {
+ $sources = true;
+ }
+ }
+ }
+
+ if ( $getPages ) {
+ $this->mCascadeSources = $sources;
+ $this->mCascadingRestrictions = $pagerestrictions;
+ } else {
+ $this->mHasCascadingRestrictions = $sources;
+ }
+
+ return [ $sources, $pagerestrictions ];
+ }
+
+ /**
+ * 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 Restriction levels needed to take the action. All levels are
+ * required. Note that restriction levels are normally user rights, but 'sysop'
+ * and 'autoconfirmed' are also allowed for backwards compatibility. These should
+ * be mapped to 'editprotected' and 'editsemiprotected' respectively.
+ */
+ public function getRestrictions( $action ) {
+ if ( !$this->mRestrictionsLoaded ) {
+ $this->loadRestrictions();
+ }
+ return isset( $this->mRestrictions[$action] )
+ ? $this->mRestrictions[$action]
+ : [];
+ }
+
+ /**
+ * 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 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 ) {
+ if ( !$this->mRestrictionsLoaded ) {
+ $this->loadRestrictions();
+ }
+ return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
+ }
+
+ /**
+ * Returns cascading restrictions for the current article
+ *
+ * @return bool
+ */
+ function areRestrictionsCascading() {
+ if ( !$this->mRestrictionsLoaded ) {
+ $this->loadRestrictions();
+ }
+
+ return $this->mCascadeRestriction;
+ }
+
+ /**
+ * Compiles list of active page restrictions from both page table (pre 1.10)
+ * and page_restrictions table for this existing page.
+ * Public for usage by LiquidThreads.
+ *
+ * @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 ) {
+ $dbr = wfGetDB( DB_REPLICA );
+
+ $restrictionTypes = $this->getRestrictionTypes();
+
+ foreach ( $restrictionTypes as $type ) {
+ $this->mRestrictions[$type] = [];
+ $this->mRestrictionsExpiry[$type] = 'infinity';
+ }
+
+ $this->mCascadeRestriction = false;
+
+ # Backwards-compatibility: also load the restrictions from the page record (old format).
+ if ( $oldFashionedRestrictions !== null ) {
+ $this->mOldRestrictions = $oldFashionedRestrictions;
+ }
+
+ if ( $this->mOldRestrictions === false ) {
+ $this->mOldRestrictions = $dbr->selectField( 'page', 'page_restrictions',
+ [ 'page_id' => $this->getArticleID() ], __METHOD__ );
+ }
+
+ if ( $this->mOldRestrictions != '' ) {
+ foreach ( explode( ':', trim( $this->mOldRestrictions ) ) as $restrict ) {
+ $temp = explode( '=', trim( $restrict ) );
+ if ( count( $temp ) == 1 ) {
+ // old old format should be treated as edit/move restriction
+ $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
+ $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );