3 * Representation a title within %MediaWiki.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
26 * Represents a title within MediaWiki.
27 * Optionally may contain an interwiki designation or namespace.
28 * @note This class can fetch various kinds of data from the database;
29 * however, it does so inefficiently.
31 * @internal documentation reviewed 15 Mar 2010
34 /** @name Static cache variables */
36 static private $titleCache = array();
40 * Title::newFromText maintains a cache to avoid expensive re-normalization of
41 * commonly used titles. On a batch operation this can become a memory leak
42 * if not bounded. After hitting this many titles reset the cache.
44 const CACHE_MAX
= 1000;
47 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
48 * to use the master DB
50 const GAID_FOR_UPDATE
= 1;
53 * @name Private member variables
54 * Please use the accessor functions instead.
59 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
60 var $mUrlform = ''; // /< URL-encoded form of the main part
61 var $mDbkeyform = ''; // /< Main part with underscores
62 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
63 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
64 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
65 var $mFragment; // /< Title fragment (i.e. the bit after the #)
66 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
67 var $mLatestID = false; // /< ID of most recent revision
68 var $mContentModel = false; // /< ID of the page's content model, i.e. one of the CONTENT_MODEL_XXX constants
69 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
70 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
71 var $mOldRestrictions = false;
72 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
73 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
74 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
75 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
76 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
77 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
78 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
79 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
80 # Don't change the following default, NS_MAIN is hardcoded in several
81 # places. See bug 696.
82 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
83 # Zero except in {{transclusion}} tags
84 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
85 var $mLength = -1; // /< The page length, 0 for special pages
86 var $mRedirect = null; // /< Is the article at this title a redirect?
87 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
88 var $mHasSubpage; // /< Whether a page has any subpages
94 /*protected*/ function __construct() { }
97 * Create a new Title from a prefixed DB key
99 * @param string $key the database key, which has underscores
100 * instead of spaces, possibly including namespace and
102 * @return Title, or NULL on an error
104 public static function newFromDBkey( $key ) {
106 $t->mDbkeyform
= $key;
107 if ( $t->secureAndSplit() ) {
115 * Create a new Title from text, such as what one would find in a link. De-
116 * codes any HTML entities in the text.
118 * @param string $text the link text; spaces, prefixes, and an
119 * initial ':' indicating the main namespace are accepted.
120 * @param int $defaultNamespace the namespace to use if none is specified
121 * by a prefix. If you want to force a specific namespace even if
122 * $text might begin with a namespace prefix, use makeTitle() or
124 * @throws MWException
125 * @return Title|null - Title or null on an error.
127 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
128 if ( is_object( $text ) ) {
129 throw new MWException( 'Title::newFromText given an object' );
133 * Wiki pages often contain multiple links to the same page.
134 * Title normalization and parsing can become expensive on
135 * pages with many links, so we can save a little time by
138 * In theory these are value objects and won't get changed...
140 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
141 return Title
::$titleCache[$text];
144 # Convert things like é ā or 〗 into normalized (bug 14952) text
145 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
148 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
149 $t->mDefaultNamespace
= $defaultNamespace;
151 static $cachedcount = 0;
152 if ( $t->secureAndSplit() ) {
153 if ( $defaultNamespace == NS_MAIN
) {
154 if ( $cachedcount >= self
::CACHE_MAX
) {
155 # Avoid memory leaks on mass operations...
156 Title
::$titleCache = array();
160 Title
::$titleCache[$text] =& $t;
170 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
172 * Example of wrong and broken code:
173 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
175 * Example of right code:
176 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
178 * Create a new Title from URL-encoded text. Ensures that
179 * the given title's length does not exceed the maximum.
181 * @param string $url the title, as might be taken from a URL
182 * @return Title the new object, or NULL on an error
184 public static function newFromURL( $url ) {
187 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
188 # but some URLs used it as a space replacement and they still come
189 # from some external search tools.
190 if ( strpos( self
::legalChars(), '+' ) === false ) {
191 $url = str_replace( '+', ' ', $url );
194 $t->mDbkeyform
= str_replace( ' ', '_', $url );
195 if ( $t->secureAndSplit() ) {
203 * Returns a list of fields that are to be selected for initializing Title objects or LinkCache entries.
204 * Uses $wgContentHandlerUseDB to determine whether to include page_content_model.
208 protected static function getSelectFields() {
209 global $wgContentHandlerUseDB;
212 'page_namespace', 'page_title', 'page_id',
213 'page_len', 'page_is_redirect', 'page_latest',
216 if ( $wgContentHandlerUseDB ) {
217 $fields[] = 'page_content_model';
224 * Create a new Title from an article ID
226 * @param int $id the page_id corresponding to the Title to create
227 * @param int $flags use Title::GAID_FOR_UPDATE to use master
228 * @return Title|null the new object, or NULL on an error
230 public static function newFromID( $id, $flags = 0 ) {
231 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
232 $row = $db->selectRow(
234 self
::getSelectFields(),
235 array( 'page_id' => $id ),
238 if ( $row !== false ) {
239 $title = Title
::newFromRow( $row );
247 * Make an array of titles from an array of IDs
249 * @param array $ids of Int Array of IDs
250 * @return Array of Titles
252 public static function newFromIDs( $ids ) {
253 if ( !count( $ids ) ) {
256 $dbr = wfGetDB( DB_SLAVE
);
260 self
::getSelectFields(),
261 array( 'page_id' => $ids ),
266 foreach ( $res as $row ) {
267 $titles[] = Title
::newFromRow( $row );
273 * Make a Title object from a DB row
275 * @param $row Object database row (needs at least page_title,page_namespace)
276 * @return Title corresponding Title
278 public static function newFromRow( $row ) {
279 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
280 $t->loadFromRow( $row );
285 * Load Title object fields from a DB row.
286 * If false is given, the title will be treated as non-existing.
288 * @param $row Object|bool database row
290 public function loadFromRow( $row ) {
291 if ( $row ) { // page found
292 if ( isset( $row->page_id
) ) {
293 $this->mArticleID
= (int)$row->page_id
;
295 if ( isset( $row->page_len
) ) {
296 $this->mLength
= (int)$row->page_len
;
298 if ( isset( $row->page_is_redirect
) ) {
299 $this->mRedirect
= (bool)$row->page_is_redirect
;
301 if ( isset( $row->page_latest
) ) {
302 $this->mLatestID
= (int)$row->page_latest
;
304 if ( isset( $row->page_content_model
) ) {
305 $this->mContentModel
= strval( $row->page_content_model
);
307 $this->mContentModel
= false; # initialized lazily in getContentModel()
309 } else { // page not found
310 $this->mArticleID
= 0;
312 $this->mRedirect
= false;
313 $this->mLatestID
= 0;
314 $this->mContentModel
= false; # initialized lazily in getContentModel()
319 * Create a new Title from a namespace index and a DB key.
320 * It's assumed that $ns and $title are *valid*, for instance when
321 * they came directly from the database or a special page name.
322 * For convenience, spaces are converted to underscores so that
323 * eg user_text fields can be used directly.
325 * @param int $ns the namespace of the article
326 * @param string $title the unprefixed database key form
327 * @param string $fragment the link fragment (after the "#")
328 * @param string $interwiki the interwiki prefix
329 * @return Title the new object
331 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
333 $t->mInterwiki
= $interwiki;
334 $t->mFragment
= $fragment;
335 $t->mNamespace
= $ns = intval( $ns );
336 $t->mDbkeyform
= str_replace( ' ', '_', $title );
337 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
338 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
339 $t->mTextform
= str_replace( '_', ' ', $title );
340 $t->mContentModel
= false; # initialized lazily in getContentModel()
345 * Create a new Title from a namespace index and a DB key.
346 * The parameters will be checked for validity, which is a bit slower
347 * than makeTitle() but safer for user-provided data.
349 * @param int $ns the namespace of the article
350 * @param string $title database key form
351 * @param string $fragment the link fragment (after the "#")
352 * @param string $interwiki interwiki prefix
353 * @return Title the new object, or NULL on an error
355 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
356 if ( !MWNamespace
::exists( $ns ) ) {
361 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
362 if ( $t->secureAndSplit() ) {
370 * Create a new Title for the Main Page
372 * @return Title the new object
374 public static function newMainPage() {
375 $title = Title
::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
376 // Don't give fatal errors if the message is broken
378 $title = Title
::newFromText( 'Main Page' );
384 * Extract a redirect destination from a string and return the
385 * Title, or null if the text doesn't contain a valid redirect
386 * This will only return the very next target, useful for
387 * the redirect table and other checks that don't need full recursion
389 * @param string $text Text with possible redirect
390 * @return Title: The corresponding Title
391 * @deprecated since 1.21, use Content::getRedirectTarget instead.
393 public static function newFromRedirect( $text ) {
394 ContentHandler
::deprecated( __METHOD__
, '1.21' );
396 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
397 return $content->getRedirectTarget();
401 * Extract a redirect destination from a string and return the
402 * Title, or null if the text doesn't contain a valid redirect
403 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
404 * in order to provide (hopefully) the Title of the final destination instead of another redirect
406 * @param string $text Text with possible redirect
408 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
410 public static function newFromRedirectRecurse( $text ) {
411 ContentHandler
::deprecated( __METHOD__
, '1.21' );
413 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
414 return $content->getUltimateRedirectTarget();
418 * Extract a redirect destination from a string and return an
419 * array of Titles, or null if the text doesn't contain a valid redirect
420 * The last element in the array is the final destination after all redirects
421 * have been resolved (up to $wgMaxRedirects times)
423 * @param string $text Text with possible redirect
424 * @return Array of Titles, with the destination last
425 * @deprecated since 1.21, use Content::getRedirectChain instead.
427 public static function newFromRedirectArray( $text ) {
428 ContentHandler
::deprecated( __METHOD__
, '1.21' );
430 $content = ContentHandler
::makeContent( $text, null, CONTENT_MODEL_WIKITEXT
);
431 return $content->getRedirectChain();
435 * Get the prefixed DB key associated with an ID
437 * @param int $id the page_id of the article
438 * @return Title an object representing the article, or NULL if no such article was found
440 public static function nameOf( $id ) {
441 $dbr = wfGetDB( DB_SLAVE
);
443 $s = $dbr->selectRow(
445 array( 'page_namespace', 'page_title' ),
446 array( 'page_id' => $id ),
449 if ( $s === false ) {
453 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
458 * Get a regex character class describing the legal characters in a link
460 * @return String the list of characters, not delimited
462 public static function legalChars() {
463 global $wgLegalTitleChars;
464 return $wgLegalTitleChars;
468 * Returns a simple regex that will match on characters and sequences invalid in titles.
469 * Note that this doesn't pick up many things that could be wrong with titles, but that
470 * replacing this regex with something valid will make many titles valid.
472 * @return String regex string
474 static function getTitleInvalidRegex() {
475 static $rxTc = false;
477 # Matching titles will be held as illegal.
479 # Any character not allowed is forbidden...
480 '[^' . self
::legalChars() . ']' .
481 # URL percent encoding sequences interfere with the ability
482 # to round-trip titles -- you can't link to them consistently.
484 # XML/HTML character references produce similar issues.
485 '|&[A-Za-z0-9\x80-\xff]+;' .
487 '|&#x[0-9A-Fa-f]+;' .
495 * Get a string representation of a title suitable for
496 * including in a search index
498 * @param int $ns a namespace index
499 * @param string $title text-form main part
500 * @return String a stripped-down title string ready for the search index
502 public static function indexTitle( $ns, $title ) {
505 $lc = SearchEngine
::legalSearchChars() . '&#;';
506 $t = $wgContLang->normalizeForSearch( $title );
507 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
508 $t = $wgContLang->lc( $t );
511 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
512 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
514 $t = preg_replace( "/\\s+/", ' ', $t );
516 if ( $ns == NS_FILE
) {
517 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
523 * Make a prefixed DB key from a DB key and a namespace index
525 * @param int $ns numerical representation of the namespace
526 * @param string $title the DB key form the title
527 * @param string $fragment The link fragment (after the "#")
528 * @param string $interwiki The interwiki prefix
529 * @return String the prefixed form of the title
531 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
534 $namespace = $wgContLang->getNsText( $ns );
535 $name = $namespace == '' ?
$title : "$namespace:$title";
536 if ( strval( $interwiki ) != '' ) {
537 $name = "$interwiki:$name";
539 if ( strval( $fragment ) != '' ) {
540 $name .= '#' . $fragment;
546 * Escape a text fragment, say from a link, for a URL
548 * @param string $fragment containing a URL or link fragment (after the "#")
549 * @return String: escaped string
551 static function escapeFragmentForURL( $fragment ) {
552 # Note that we don't urlencode the fragment. urlencoded Unicode
553 # fragments appear not to work in IE (at least up to 7) or in at least
554 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
555 # to care if they aren't encoded.
556 return Sanitizer
::escapeId( $fragment, 'noninitial' );
560 * Callback for usort() to do title sorts by (namespace, title)
565 * @return Integer: result of string comparison, or namespace comparison
567 public static function compare( $a, $b ) {
568 if ( $a->getNamespace() == $b->getNamespace() ) {
569 return strcmp( $a->getText(), $b->getText() );
571 return $a->getNamespace() - $b->getNamespace();
576 * Determine whether the object refers to a page within
579 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
581 public function isLocal() {
582 if ( $this->mInterwiki
!= '' ) {
583 $iw = Interwiki
::fetch( $this->mInterwiki
);
585 return $iw->isLocal();
592 * Is this Title interwiki?
596 public function isExternal() {
597 return ( $this->mInterwiki
!= '' );
601 * Get the interwiki prefix (or null string)
603 * @return String Interwiki prefix
605 public function getInterwiki() {
606 return $this->mInterwiki
;
610 * Determine whether the object refers to a page within
611 * this project and is transcludable.
613 * @return Bool TRUE if this is transcludable
615 public function isTrans() {
616 if ( $this->mInterwiki
== '' ) {
620 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
624 * Returns the DB name of the distant wiki which owns the object.
626 * @return String the DB name
628 public function getTransWikiID() {
629 if ( $this->mInterwiki
== '' ) {
633 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
637 * Get the text form (spaces not underscores) of the main part
639 * @return String Main part of the title
641 public function getText() {
642 return $this->mTextform
;
646 * Get the URL-encoded form of the main part
648 * @return String Main part of the title, URL-encoded
650 public function getPartialURL() {
651 return $this->mUrlform
;
655 * Get the main part with underscores
657 * @return String: Main part of the title, with underscores
659 public function getDBkey() {
660 return $this->mDbkeyform
;
664 * Get the DB key with the initial letter case as specified by the user
666 * @return String DB key
668 function getUserCaseDBKey() {
669 return $this->mUserCaseDBKey
;
673 * Get the namespace index, i.e. one of the NS_xxxx constants.
675 * @return Integer: Namespace index
677 public function getNamespace() {
678 return $this->mNamespace
;
682 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
684 * @throws MWException
685 * @return String: Content model id
687 public function getContentModel() {
688 if ( !$this->mContentModel
) {
689 $linkCache = LinkCache
::singleton();
690 $this->mContentModel
= $linkCache->getGoodLinkFieldObj( $this, 'model' );
693 if ( !$this->mContentModel
) {
694 $this->mContentModel
= ContentHandler
::getDefaultModelFor( $this );
697 if ( !$this->mContentModel
) {
698 throw new MWException( 'Failed to determine content model!' );
701 return $this->mContentModel
;
705 * Convenience method for checking a title's content model name
707 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
708 * @return Boolean true if $this->getContentModel() == $id
710 public function hasContentModel( $id ) {
711 return $this->getContentModel() == $id;
715 * Get the namespace text
717 * @return String: Namespace text
719 public function getNsText() {
722 if ( $this->mInterwiki
!= '' ) {
723 // This probably shouldn't even happen. ohh man, oh yuck.
724 // But for interwiki transclusion it sometimes does.
725 // Shit. Shit shit shit.
727 // Use the canonical namespaces if possible to try to
728 // resolve a foreign namespace.
729 if ( MWNamespace
::exists( $this->mNamespace
) ) {
730 return MWNamespace
::getCanonicalName( $this->mNamespace
);
734 if ( $wgContLang->needsGenderDistinction() &&
735 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
736 $gender = GenderCache
::singleton()->getGenderOf( $this->getText(), __METHOD__
);
737 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
740 return $wgContLang->getNsText( $this->mNamespace
);
744 * Get the namespace text of the subject (rather than talk) page
746 * @return String Namespace text
748 public function getSubjectNsText() {
750 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
754 * Get the namespace text of the talk page
756 * @return String Namespace text
758 public function getTalkNsText() {
760 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
764 * Could this title have a corresponding talk page?
766 * @return Bool TRUE or FALSE
768 public function canTalk() {
769 return( MWNamespace
::canTalk( $this->mNamespace
) );
773 * Is this in a namespace that allows actual pages?
776 * @internal note -- uses hardcoded namespace index instead of constants
778 public function canExist() {
779 return $this->mNamespace
>= NS_MAIN
;
783 * Can this title be added to a user's watchlist?
785 * @return Bool TRUE or FALSE
787 public function isWatchable() {
788 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
792 * Returns true if this is a special page.
796 public function isSpecialPage() {
797 return $this->getNamespace() == NS_SPECIAL
;
801 * Returns true if this title resolves to the named special page
803 * @param string $name The special page name
806 public function isSpecial( $name ) {
807 if ( $this->isSpecialPage() ) {
808 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
809 if ( $name == $thisName ) {
817 * If the Title refers to a special page alias which is not the local default, resolve
818 * the alias, and localise the name as necessary. Otherwise, return $this
822 public function fixSpecialName() {
823 if ( $this->isSpecialPage() ) {
824 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
825 if ( $canonicalName ) {
826 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
827 if ( $localName != $this->mDbkeyform
) {
828 return Title
::makeTitle( NS_SPECIAL
, $localName );
836 * Returns true if the title is inside the specified namespace.
838 * Please make use of this instead of comparing to getNamespace()
839 * This function is much more resistant to changes we may make
840 * to namespaces than code that makes direct comparisons.
841 * @param int $ns The namespace
845 public function inNamespace( $ns ) {
846 return MWNamespace
::equals( $this->getNamespace(), $ns );
850 * Returns true if the title is inside one of the specified namespaces.
852 * @param ...$namespaces The namespaces to check for
856 public function inNamespaces( /* ... */ ) {
857 $namespaces = func_get_args();
858 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
859 $namespaces = $namespaces[0];
862 foreach ( $namespaces as $ns ) {
863 if ( $this->inNamespace( $ns ) ) {
872 * Returns true if the title has the same subject namespace as the
873 * namespace specified.
874 * For example this method will take NS_USER and return true if namespace
875 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
876 * as their subject namespace.
878 * This is MUCH simpler than individually testing for equivalence
879 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
884 public function hasSubjectNamespace( $ns ) {
885 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
889 * Is this Title in a namespace which contains content?
890 * In other words, is this a content page, for the purposes of calculating
895 public function isContentPage() {
896 return MWNamespace
::isContent( $this->getNamespace() );
900 * Would anybody with sufficient privileges be able to move this page?
901 * Some pages just aren't movable.
903 * @return Bool TRUE or FALSE
905 public function isMovable() {
906 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
907 // Interwiki title or immovable namespace. Hooks don't get to override here
912 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
917 * Is this the mainpage?
918 * @note Title::newFromText seems to be sufficiently optimized by the title
919 * cache that we don't need to over-optimize by doing direct comparisons and
920 * accidentally creating new bugs where $title->equals( Title::newFromText() )
921 * ends up reporting something differently than $title->isMainPage();
926 public function isMainPage() {
927 return $this->equals( Title
::newMainPage() );
935 public function isSubpage() {
936 return MWNamespace
::hasSubpages( $this->mNamespace
)
937 ?
strpos( $this->getText(), '/' ) !== false
942 * Is this a conversion table for the LanguageConverter?
946 public function isConversionTable() {
947 //@todo: ConversionTable should become a separate content model.
949 return $this->getNamespace() == NS_MEDIAWIKI
&&
950 strpos( $this->getText(), 'Conversiontable/' ) === 0;
954 * Does that page contain wikitext, or it is JS, CSS or whatever?
958 public function isWikitextPage() {
959 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT
);
963 * Could this page contain custom CSS or JavaScript for the global UI.
964 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
965 * or CONTENT_MODEL_JAVASCRIPT.
967 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage() for that!
969 * Note that this method should not return true for pages that contain and show "inactive" CSS or JS.
973 public function isCssOrJsPage() {
974 $isCssOrJsPage = NS_MEDIAWIKI
== $this->mNamespace
975 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
976 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
978 #NOTE: this hook is also called in ContentHandler::getDefaultModel. It's called here again to make sure
979 # hook functions can force this method to return true even outside the mediawiki namespace.
981 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
983 return $isCssOrJsPage;
987 * Is this a .css or .js subpage of a user page?
990 public function isCssJsSubpage() {
991 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
992 && ( $this->hasContentModel( CONTENT_MODEL_CSS
)
993 ||
$this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) ) );
997 * Trim down a .css or .js subpage title to get the corresponding skin name
999 * @return string containing skin name from .css or .js subpage title
1001 public function getSkinFromCssJsSubpage() {
1002 $subpage = explode( '/', $this->mTextform
);
1003 $subpage = $subpage[count( $subpage ) - 1];
1004 $lastdot = strrpos( $subpage, '.' );
1005 if ( $lastdot === false ) {
1006 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1008 return substr( $subpage, 0, $lastdot );
1012 * Is this a .css subpage of a user page?
1016 public function isCssSubpage() {
1017 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1018 && $this->hasContentModel( CONTENT_MODEL_CSS
) );
1022 * Is this a .js subpage of a user page?
1026 public function isJsSubpage() {
1027 return ( NS_USER
== $this->mNamespace
&& $this->isSubpage()
1028 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT
) );
1032 * Is this a talk page of some sort?
1036 public function isTalkPage() {
1037 return MWNamespace
::isTalk( $this->getNamespace() );
1041 * Get a Title object associated with the talk page of this article
1043 * @return Title the object for the talk page
1045 public function getTalkPage() {
1046 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
1050 * Get a title object associated with the subject page of this
1053 * @return Title the object for the subject page
1055 public function getSubjectPage() {
1056 // Is this the same title?
1057 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
1058 if ( $this->getNamespace() == $subjectNS ) {
1061 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
1065 * Get the default namespace index, for when there is no namespace
1067 * @return Int Default namespace index
1069 public function getDefaultNamespace() {
1070 return $this->mDefaultNamespace
;
1074 * Get title for search index
1076 * @return String a stripped-down title string ready for the
1079 public function getIndexTitle() {
1080 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
1084 * Get the Title fragment (i.e.\ the bit after the #) in text form
1086 * @return String Title fragment
1088 public function getFragment() {
1089 return $this->mFragment
;
1093 * Get the fragment in URL form, including the "#" character if there is one
1094 * @return String Fragment in URL form
1096 public function getFragmentForURL() {
1097 if ( $this->mFragment
== '' ) {
1100 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
1105 * Set the fragment for this title. Removes the first character from the
1106 * specified fragment before setting, so it assumes you're passing it with
1109 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1110 * Still in active use privately.
1112 * @param string $fragment text
1114 public function setFragment( $fragment ) {
1115 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
1119 * Prefix some arbitrary text with the namespace or interwiki prefix
1122 * @param string $name the text
1123 * @return String the prefixed text
1126 private function prefix( $name ) {
1128 if ( $this->mInterwiki
!= '' ) {
1129 $p = $this->mInterwiki
. ':';
1132 if ( 0 != $this->mNamespace
) {
1133 $p .= $this->getNsText() . ':';
1139 * Get the prefixed database key form
1141 * @return String the prefixed title, with underscores and
1142 * any interwiki and namespace prefixes
1144 public function getPrefixedDBkey() {
1145 $s = $this->prefix( $this->mDbkeyform
);
1146 $s = str_replace( ' ', '_', $s );
1151 * Get the prefixed title with spaces.
1152 * This is the form usually used for display
1154 * @return String the prefixed title, with spaces
1156 public function getPrefixedText() {
1157 // @todo FIXME: Bad usage of empty() ?
1158 if ( empty( $this->mPrefixedText
) ) {
1159 $s = $this->prefix( $this->mTextform
);
1160 $s = str_replace( '_', ' ', $s );
1161 $this->mPrefixedText
= $s;
1163 return $this->mPrefixedText
;
1167 * Return a string representation of this title
1169 * @return String representation of this title
1171 public function __toString() {
1172 return $this->getPrefixedText();
1176 * Get the prefixed title with spaces, plus any fragment
1177 * (part beginning with '#')
1179 * @return String the prefixed title, with spaces and the fragment, including '#'
1181 public function getFullText() {
1182 $text = $this->getPrefixedText();
1183 if ( $this->mFragment
!= '' ) {
1184 $text .= '#' . $this->mFragment
;
1190 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1194 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1198 * @return String Root name
1201 public function getRootText() {
1202 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1203 return $this->getText();
1206 return strtok( $this->getText(), '/' );
1210 * Get the root page name title, i.e. the leftmost part before any slashes
1214 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1215 * # returns: Title{User:Foo}
1218 * @return Title Root title
1221 public function getRootTitle() {
1222 return Title
::makeTitle( $this->getNamespace(), $this->getRootText() );
1226 * Get the base page name without a namespace, i.e. the part before the subpage name
1230 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1231 * # returns: 'Foo/Bar'
1234 * @return String Base name
1236 public function getBaseText() {
1237 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1238 return $this->getText();
1241 $parts = explode( '/', $this->getText() );
1242 # Don't discard the real title if there's no subpage involved
1243 if ( count( $parts ) > 1 ) {
1244 unset( $parts[count( $parts ) - 1] );
1246 return implode( '/', $parts );
1250 * Get the base page name title, i.e. the part before the subpage name
1254 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1255 * # returns: Title{User:Foo/Bar}
1258 * @return Title Base title
1261 public function getBaseTitle() {
1262 return Title
::makeTitle( $this->getNamespace(), $this->getBaseText() );
1266 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1270 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1274 * @return String Subpage name
1276 public function getSubpageText() {
1277 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1278 return( $this->mTextform
);
1280 $parts = explode( '/', $this->mTextform
);
1281 return( $parts[count( $parts ) - 1] );
1285 * Get the title for a subpage of the current page
1289 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1290 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1293 * @param string $text The subpage name to add to the title
1294 * @return Title Subpage title
1297 public function getSubpage( $text ) {
1298 return Title
::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1302 * Get the HTML-escaped displayable text form.
1303 * Used for the title field in <a> tags.
1305 * @return String the text, including any prefixes
1306 * @deprecated since 1.19
1308 public function getEscapedText() {
1309 wfDeprecated( __METHOD__
, '1.19' );
1310 return htmlspecialchars( $this->getPrefixedText() );
1314 * Get a URL-encoded form of the subpage text
1316 * @return String URL-encoded subpage name
1318 public function getSubpageUrlForm() {
1319 $text = $this->getSubpageText();
1320 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1325 * Get a URL-encoded title (not an actual URL) including interwiki
1327 * @return String the URL-encoded form
1329 public function getPrefixedURL() {
1330 $s = $this->prefix( $this->mDbkeyform
);
1331 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1336 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1337 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1338 * second argument named variant. This was deprecated in favor
1339 * of passing an array of option with a "variant" key
1340 * Once $query2 is removed for good, this helper can be dropped
1341 * and the wfArrayToCgi moved to getLocalURL();
1343 * @since 1.19 (r105919)
1345 * @param $query2 bool
1348 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1349 if ( $query2 !== false ) {
1350 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1351 "method called with a second parameter is deprecated. Add your " .
1352 "parameter to an array passed as the first parameter.", "1.19" );
1354 if ( is_array( $query ) ) {
1355 $query = wfArrayToCgi( $query );
1358 if ( is_string( $query2 ) ) {
1359 // $query2 is a string, we will consider this to be
1360 // a deprecated $variant argument and add it to the query
1361 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1363 $query2 = wfArrayToCgi( $query2 );
1365 // If we have $query content add a & to it first
1369 // Now append the queries together
1376 * Get a real URL referring to this title, with interwiki link and
1379 * See getLocalURL for the arguments.
1381 * @see self::getLocalURL
1384 * @param $query2 bool
1385 * @param $proto Protocol type to use in URL
1386 * @return String the URL
1388 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1389 $query = self
::fixUrlQueryArgs( $query, $query2 );
1391 # Hand off all the decisions on urls to getLocalURL
1392 $url = $this->getLocalURL( $query );
1394 # Expand the url to make it a full url. Note that getLocalURL has the
1395 # potential to output full urls for a variety of reasons, so we use
1396 # wfExpandUrl instead of simply prepending $wgServer
1397 $url = wfExpandUrl( $url, $proto );
1399 # Finally, add the fragment.
1400 $url .= $this->getFragmentForURL();
1402 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1407 * Get a URL with no fragment or server name. If this page is generated
1408 * with action=render, $wgServer is prepended.
1410 * @param string|array $query an optional query string,
1411 * not used for interwiki links. Can be specified as an associative array as well,
1412 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1413 * Some query patterns will trigger various shorturl path replacements.
1414 * @param $query2 Mixed: An optional secondary query array. This one MUST
1415 * be an array. If a string is passed it will be interpreted as a deprecated
1416 * variant argument and urlencoded into a variant= argument.
1417 * This second query argument will be added to the $query
1418 * The second parameter is deprecated since 1.19. Pass it as a key,value
1419 * pair in the first parameter array instead.
1421 * @return String the URL
1423 public function getLocalURL( $query = '', $query2 = false ) {
1424 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1426 $query = self
::fixUrlQueryArgs( $query, $query2 );
1428 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
1430 $namespace = $this->getNsText();
1431 if ( $namespace != '' ) {
1432 # Can this actually happen? Interwikis shouldn't be parsed.
1433 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1436 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1437 $url = wfAppendQuery( $url, $query );
1439 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1440 if ( $query == '' ) {
1441 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1442 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1444 global $wgVariantArticlePath, $wgActionPaths;
1448 if ( !empty( $wgActionPaths ) &&
1449 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1451 $action = urldecode( $matches[2] );
1452 if ( isset( $wgActionPaths[$action] ) ) {
1453 $query = $matches[1];
1454 if ( isset( $matches[4] ) ) {
1455 $query .= $matches[4];
1457 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1458 if ( $query != '' ) {
1459 $url = wfAppendQuery( $url, $query );
1464 if ( $url === false &&
1465 $wgVariantArticlePath &&
1466 $this->getPageLanguage()->hasVariants() &&
1467 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1469 $variant = urldecode( $matches[1] );
1470 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1471 // Only do the variant replacement if the given variant is a valid
1472 // variant for the page's language.
1473 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1474 $url = str_replace( '$1', $dbkey, $url );
1478 if ( $url === false ) {
1479 if ( $query == '-' ) {
1482 $url = "{$wgScript}?title={$dbkey}&{$query}";
1486 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1488 // @todo FIXME: This causes breakage in various places when we
1489 // actually expected a local URL and end up with dupe prefixes.
1490 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1491 $url = $wgServer . $url;
1494 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1499 * Get a URL that's the simplest URL that will be valid to link, locally,
1500 * to the current Title. It includes the fragment, but does not include
1501 * the server unless action=render is used (or the link is external). If
1502 * there's a fragment but the prefixed text is empty, we just return a link
1505 * The result obviously should not be URL-escaped, but does need to be
1506 * HTML-escaped if it's being output in HTML.
1508 * See getLocalURL for the arguments.
1511 * @param $query2 bool
1512 * @param $proto Protocol to use; setting this will cause a full URL to be used
1513 * @see self::getLocalURL
1514 * @return String the URL
1516 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE
) {
1517 wfProfileIn( __METHOD__
);
1518 if ( $this->isExternal() ||
$proto !== PROTO_RELATIVE
) {
1519 $ret = $this->getFullURL( $query, $query2, $proto );
1520 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1521 $ret = $this->getFragmentForURL();
1523 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1525 wfProfileOut( __METHOD__
);
1530 * Get an HTML-escaped version of the URL form, suitable for
1531 * using in a link, without a server name or fragment
1533 * See getLocalURL for the arguments.
1535 * @see self::getLocalURL
1536 * @param $query string
1537 * @param $query2 bool|string
1538 * @return String the URL
1539 * @deprecated since 1.19
1541 public function escapeLocalURL( $query = '', $query2 = false ) {
1542 wfDeprecated( __METHOD__
, '1.19' );
1543 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1547 * Get an HTML-escaped version of the URL form, suitable for
1548 * using in a link, including the server name and fragment
1550 * See getLocalURL for the arguments.
1552 * @see self::getLocalURL
1553 * @return String the URL
1554 * @deprecated since 1.19
1556 public function escapeFullURL( $query = '', $query2 = false ) {
1557 wfDeprecated( __METHOD__
, '1.19' );
1558 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1562 * Get the URL form for an internal link.
1563 * - Used in various Squid-related code, in case we have a different
1564 * internal hostname for the server from the exposed one.
1566 * This uses $wgInternalServer to qualify the path, or $wgServer
1567 * if $wgInternalServer is not set. If the server variable used is
1568 * protocol-relative, the URL will be expanded to http://
1570 * See getLocalURL for the arguments.
1572 * @see self::getLocalURL
1573 * @return String the URL
1575 public function getInternalURL( $query = '', $query2 = false ) {
1576 global $wgInternalServer, $wgServer;
1577 $query = self
::fixUrlQueryArgs( $query, $query2 );
1578 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1579 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP
);
1580 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1585 * Get the URL for a canonical link, for use in things like IRC and
1586 * e-mail notifications. Uses $wgCanonicalServer and the
1587 * GetCanonicalURL hook.
1589 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1591 * See getLocalURL for the arguments.
1593 * @see self::getLocalURL
1594 * @return string The URL
1597 public function getCanonicalURL( $query = '', $query2 = false ) {
1598 $query = self
::fixUrlQueryArgs( $query, $query2 );
1599 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1600 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1605 * HTML-escaped version of getCanonicalURL()
1607 * See getLocalURL for the arguments.
1609 * @see self::getLocalURL
1612 * @deprecated since 1.19
1614 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1615 wfDeprecated( __METHOD__
, '1.19' );
1616 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1620 * Get the edit URL for this Title
1622 * @return String the URL, or a null string if this is an
1625 public function getEditURL() {
1626 if ( $this->mInterwiki
!= '' ) {
1629 $s = $this->getLocalURL( 'action=edit' );
1635 * Is $wgUser watching this page?
1637 * @deprecated in 1.20; use User::isWatched() instead.
1640 public function userIsWatching() {
1643 if ( is_null( $this->mWatched
) ) {
1644 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1645 $this->mWatched
= false;
1647 $this->mWatched
= $wgUser->isWatched( $this );
1650 return $this->mWatched
;
1654 * Can $wgUser read this page?
1656 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1658 * @todo fold these checks into userCan()
1660 public function userCanRead() {
1661 wfDeprecated( __METHOD__
, '1.19' );
1662 return $this->userCan( 'read' );
1666 * Can $user perform $action on this page?
1667 * This skips potentially expensive cascading permission checks
1668 * as well as avoids expensive error formatting
1670 * Suitable for use for nonessential UI controls in common cases, but
1671 * _not_ for functional access control.
1673 * May provide false positives, but should never provide a false negative.
1675 * @param string $action action that permission needs to be checked for
1676 * @param $user User to check (since 1.19); $wgUser will be used if not
1680 public function quickUserCan( $action, $user = null ) {
1681 return $this->userCan( $action, $user, false );
1685 * Can $user perform $action on this page?
1687 * @param string $action action that permission needs to be checked for
1688 * @param $user User to check (since 1.19); $wgUser will be used if not
1690 * @param bool $doExpensiveQueries Set this to false to avoid doing
1691 * unnecessary queries.
1694 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1695 if ( !$user instanceof User
) {
1699 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1703 * Can $user perform $action on this page?
1705 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1707 * @param string $action action that permission needs to be checked for
1708 * @param $user User to check
1709 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary
1710 * queries by skipping checks for cascading protections and user blocks.
1711 * @param array $ignoreErrors of Strings Set this to a list of message keys
1712 * whose corresponding errors may be ignored.
1713 * @return Array of arguments to wfMessage to explain permissions problems.
1715 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1716 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1718 // Remove the errors being ignored.
1719 foreach ( $errors as $index => $error ) {
1720 $error_key = is_array( $error ) ?
$error[0] : $error;
1722 if ( in_array( $error_key, $ignoreErrors ) ) {
1723 unset( $errors[$index] );
1731 * Permissions checks that fail most often, and which are easiest to test.
1733 * @param string $action the action to check
1734 * @param $user User user to check
1735 * @param array $errors list of current errors
1736 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1737 * @param $short Boolean short circuit on first error
1739 * @return Array list of errors
1741 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1742 if ( $action == 'create' ) {
1744 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1745 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1747 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1749 } elseif ( $action == 'move' ) {
1750 if ( !$user->isAllowed( 'move-rootuserpages' )
1751 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1752 // Show user page-specific message only if the user can move other pages
1753 $errors[] = array( 'cant-move-user-page' );
1756 // Check if user is allowed to move files if it's a file
1757 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1758 $errors[] = array( 'movenotallowedfile' );
1761 if ( !$user->isAllowed( 'move' ) ) {
1762 // User can't move anything
1763 $userCanMove = User
::groupHasPermission( 'user', 'move' );
1764 $autoconfirmedCanMove = User
::groupHasPermission( 'autoconfirmed', 'move' );
1765 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1766 // custom message if logged-in users without any special rights can move
1767 $errors[] = array( 'movenologintext' );
1769 $errors[] = array( 'movenotallowed' );
1772 } elseif ( $action == 'move-target' ) {
1773 if ( !$user->isAllowed( 'move' ) ) {
1774 // User can't move anything
1775 $errors[] = array( 'movenotallowed' );
1776 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1777 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1778 // Show user page-specific message only if the user can move other pages
1779 $errors[] = array( 'cant-move-to-user-page' );
1781 } elseif ( !$user->isAllowed( $action ) ) {
1782 $errors[] = $this->missingPermissionError( $action, $short );
1789 * Add the resulting error code to the errors array
1791 * @param array $errors list of current errors
1792 * @param $result Mixed result of errors
1794 * @return Array list of errors
1796 private function resultToError( $errors, $result ) {
1797 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1798 // A single array representing an error
1799 $errors[] = $result;
1800 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1801 // A nested array representing multiple errors
1802 $errors = array_merge( $errors, $result );
1803 } elseif ( $result !== '' && is_string( $result ) ) {
1804 // A string representing a message-id
1805 $errors[] = array( $result );
1806 } elseif ( $result === false ) {
1807 // a generic "We don't want them to do that"
1808 $errors[] = array( 'badaccess-group0' );
1814 * Check various permission hooks
1816 * @param string $action the action to check
1817 * @param $user User user to check
1818 * @param array $errors list of current errors
1819 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1820 * @param $short Boolean short circuit on first error
1822 * @return Array list of errors
1824 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1825 // Use getUserPermissionsErrors instead
1827 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1828 return $result ?
array() : array( array( 'badaccess-group0' ) );
1830 // Check getUserPermissionsErrors hook
1831 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1832 $errors = $this->resultToError( $errors, $result );
1834 // Check getUserPermissionsErrorsExpensive hook
1837 && !( $short && count( $errors ) > 0 )
1838 && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
1840 $errors = $this->resultToError( $errors, $result );
1847 * Check permissions on special pages & namespaces
1849 * @param string $action the action to check
1850 * @param $user User user to check
1851 * @param array $errors list of current errors
1852 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1853 * @param $short Boolean short circuit on first error
1855 * @return Array list of errors
1857 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1858 # Only 'createaccount' can be performed on special pages,
1859 # which don't actually exist in the DB.
1860 if ( NS_SPECIAL
== $this->mNamespace
&& $action !== 'createaccount' ) {
1861 $errors[] = array( 'ns-specialprotected' );
1864 # Check $wgNamespaceProtection for restricted namespaces
1865 if ( $this->isNamespaceProtected( $user ) ) {
1866 $ns = $this->mNamespace
== NS_MAIN ?
1867 wfMessage( 'nstab-main' )->text() : $this->getNsText();
1868 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1869 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1876 * Check CSS/JS sub-page permissions
1878 * @param string $action the action to check
1879 * @param $user User user to check
1880 * @param array $errors list of current errors
1881 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1882 * @param $short Boolean short circuit on first error
1884 * @return Array list of errors
1886 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1887 # Protect css/js subpages of user pages
1888 # XXX: this might be better using restrictions
1889 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1890 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1891 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1892 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1893 $errors[] = array( 'customcssprotected' );
1894 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1895 $errors[] = array( 'customjsprotected' );
1903 * Check against page_restrictions table requirements on this
1904 * page. The user must possess all required rights for this
1907 * @param string $action the action to check
1908 * @param $user User user to check
1909 * @param array $errors list of current errors
1910 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1911 * @param $short Boolean short circuit on first error
1913 * @return Array list of errors
1915 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1916 foreach ( $this->getRestrictions( $action ) as $right ) {
1917 // Backwards compatibility, rewrite sysop -> protect
1918 if ( $right == 'sysop' ) {
1921 if ( $right != '' && !$user->isAllowed( $right ) ) {
1922 // Users with 'editprotected' permission can edit protected pages
1923 // without cascading option turned on.
1924 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected' )
1925 ||
$this->mCascadeRestriction
)
1927 $errors[] = array( 'protectedpagetext', $right );
1936 * Check restrictions on cascading pages.
1938 * @param string $action the action to check
1939 * @param $user User to check
1940 * @param array $errors list of current errors
1941 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1942 * @param $short Boolean short circuit on first error
1944 * @return Array list of errors
1946 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1947 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1948 # We /could/ use the protection level on the source page, but it's
1949 # fairly ugly as we have to establish a precedence hierarchy for pages
1950 # included by multiple cascade-protected pages. So just restrict
1951 # it to people with 'protect' permission, as they could remove the
1952 # protection anyway.
1953 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1954 # Cascading protection depends on more than this page...
1955 # Several cascading protected pages may include this page...
1956 # Check each cascading level
1957 # This is only for protection restrictions, not for all actions
1958 if ( isset( $restrictions[$action] ) ) {
1959 foreach ( $restrictions[$action] as $right ) {
1960 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1961 if ( $right != '' && !$user->isAllowed( $right ) ) {
1963 foreach ( $cascadingSources as $page ) {
1964 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1966 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1976 * Check action permissions not already checked in checkQuickPermissions
1978 * @param string $action the action to check
1979 * @param $user User to check
1980 * @param array $errors list of current errors
1981 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1982 * @param $short Boolean short circuit on first error
1984 * @return Array list of errors
1986 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1987 global $wgDeleteRevisionsLimit, $wgLang;
1989 if ( $action == 'protect' ) {
1990 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1991 // If they can't edit, they shouldn't protect.
1992 $errors[] = array( 'protect-cantedit' );
1994 } elseif ( $action == 'create' ) {
1995 $title_protection = $this->getTitleProtection();
1996 if ( $title_protection ) {
1997 if ( $title_protection['pt_create_perm'] == 'sysop' ) {
1998 $title_protection['pt_create_perm'] = 'protect'; // B/C
2000 if ( $title_protection['pt_create_perm'] == '' ||
2001 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
2003 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
2006 } elseif ( $action == 'move' ) {
2007 // Check for immobile pages
2008 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2009 // Specific message for this case
2010 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2011 } elseif ( !$this->isMovable() ) {
2012 // Less specific message for rarer cases
2013 $errors[] = array( 'immobile-source-page' );
2015 } elseif ( $action == 'move-target' ) {
2016 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
2017 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2018 } elseif ( !$this->isMovable() ) {
2019 $errors[] = array( 'immobile-target-page' );
2021 } elseif ( $action == 'delete' ) {
2022 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
2023 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
2025 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2032 * Check that the user isn't blocked from editing.
2034 * @param string $action the action to check
2035 * @param $user User to check
2036 * @param array $errors list of current errors
2037 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2038 * @param $short Boolean short circuit on first error
2040 * @return Array list of errors
2042 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2043 // Account creation blocks handled at userlogin.
2044 // Unblocking handled in SpecialUnblock
2045 if ( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2049 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
2051 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2052 $errors[] = array( 'confirmedittext' );
2055 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2056 // Don't block the user from editing their own talk page unless they've been
2057 // explicitly blocked from that too.
2058 } elseif ( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
2059 $block = $user->getBlock();
2061 // This is from OutputPage::blockedPage
2062 // Copied at r23888 by werdna
2064 $id = $user->blockedBy();
2065 $reason = $user->blockedFor();
2066 if ( $reason == '' ) {
2067 $reason = wfMessage( 'blockednoreason' )->text();
2069 $ip = $user->getRequest()->getIP();
2071 if ( is_numeric( $id ) ) {
2072 $name = User
::whoIs( $id );
2077 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
2078 $blockid = $block->getId();
2079 $blockExpiry = $block->getExpiry();
2080 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $block->mTimestamp
), true );
2081 if ( $blockExpiry == 'infinity' ) {
2082 $blockExpiry = wfMessage( 'infiniteblock' )->text();
2084 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
2087 $intended = strval( $block->getTarget() );
2089 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
2090 $blockid, $blockExpiry, $intended, $blockTimestamp );
2097 * Check that the user is allowed to read this page.
2099 * @param string $action the action to check
2100 * @param $user User to check
2101 * @param array $errors list of current errors
2102 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2103 * @param $short Boolean short circuit on first error
2105 * @return Array list of errors
2107 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2108 global $wgWhitelistRead, $wgWhitelistReadRegexp, $wgRevokePermissions;
2109 static $useShortcut = null;
2111 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
2112 if ( is_null( $useShortcut ) ) {
2113 $useShortcut = true;
2114 if ( !User
::groupHasPermission( '*', 'read' ) ) {
2115 # Not a public wiki, so no shortcut
2116 $useShortcut = false;
2117 } elseif ( !empty( $wgRevokePermissions ) ) {
2119 * Iterate through each group with permissions being revoked (key not included since we don't care
2120 * what the group name is), then check if the read permission is being revoked. If it is, then
2121 * we don't use the shortcut below since the user might not be able to read, even though anon
2122 * reading is allowed.
2124 foreach ( $wgRevokePermissions as $perms ) {
2125 if ( !empty( $perms['read'] ) ) {
2126 # We might be removing the read right from the user, so no shortcut
2127 $useShortcut = false;
2134 $whitelisted = false;
2135 if ( $useShortcut ) {
2136 # Shortcut for public wikis, allows skipping quite a bit of code
2137 $whitelisted = true;
2138 } elseif ( $user->isAllowed( 'read' ) ) {
2139 # If the user is allowed to read pages, he is allowed to read all pages
2140 $whitelisted = true;
2141 } elseif ( $this->isSpecial( 'Userlogin' )
2142 ||
$this->isSpecial( 'ChangePassword' )
2143 ||
$this->isSpecial( 'PasswordReset' )
2145 # Always grant access to the login page.
2146 # Even anons need to be able to log in.
2147 $whitelisted = true;
2148 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2149 # Time to check the whitelist
2150 # Only do these checks is there's something to check against
2151 $name = $this->getPrefixedText();
2152 $dbName = $this->getPrefixedDBkey();
2154 // Check for explicit whitelisting with and without underscores
2155 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
2156 $whitelisted = true;
2157 } elseif ( $this->getNamespace() == NS_MAIN
) {
2158 # Old settings might have the title prefixed with
2159 # a colon for main-namespace pages
2160 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2161 $whitelisted = true;
2163 } elseif ( $this->isSpecialPage() ) {
2164 # If it's a special page, ditch the subpage bit and check again
2165 $name = $this->getDBkey();
2166 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
2168 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
2169 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2170 $whitelisted = true;
2176 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2177 $name = $this->getPrefixedText();
2178 // Check for regex whitelisting
2179 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2180 if ( preg_match( $listItem, $name ) ) {
2181 $whitelisted = true;
2187 if ( !$whitelisted ) {
2188 # If the title is not whitelisted, give extensions a chance to do so...
2189 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2190 if ( !$whitelisted ) {
2191 $errors[] = $this->missingPermissionError( $action, $short );
2199 * Get a description array when the user doesn't have the right to perform
2200 * $action (i.e. when User::isAllowed() returns false)
2202 * @param string $action the action to check
2203 * @param $short Boolean short circuit on first error
2204 * @return Array list of errors
2206 private function missingPermissionError( $action, $short ) {
2207 // We avoid expensive display logic for quickUserCan's and such
2209 return array( 'badaccess-group0' );
2212 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2213 User
::getGroupsWithPermission( $action ) );
2215 if ( count( $groups ) ) {
2219 $wgLang->commaList( $groups ),
2223 return array( 'badaccess-group0' );
2228 * Can $user perform $action on this page? This is an internal function,
2229 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2230 * checks on wfReadOnly() and blocks)
2232 * @param string $action action that permission needs to be checked for
2233 * @param $user User to check
2234 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
2235 * @param bool $short Set this to true to stop after the first permission error.
2236 * @return Array of arrays of the arguments to wfMessage to explain permissions problems.
2238 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2239 wfProfileIn( __METHOD__
);
2241 # Read has special handling
2242 if ( $action == 'read' ) {
2244 'checkPermissionHooks',
2245 'checkReadPermissions',
2249 'checkQuickPermissions',
2250 'checkPermissionHooks',
2251 'checkSpecialsAndNSPermissions',
2252 'checkCSSandJSPermissions',
2253 'checkPageRestrictions',
2254 'checkCascadingSourcesRestrictions',
2255 'checkActionPermissions',
2261 while ( count( $checks ) > 0 &&
2262 !( $short && count( $errors ) > 0 ) ) {
2263 $method = array_shift( $checks );
2264 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2267 wfProfileOut( __METHOD__
);
2272 * Protect css subpages of user pages: can $wgUser edit
2275 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2278 public function userCanEditCssSubpage() {
2280 wfDeprecated( __METHOD__
, '1.19' );
2281 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2282 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2286 * Protect js subpages of user pages: can $wgUser edit
2289 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2292 public function userCanEditJsSubpage() {
2294 wfDeprecated( __METHOD__
, '1.19' );
2296 ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2297 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
)
2302 * Get a filtered list of all restriction types supported by this wiki.
2303 * @param bool $exists True to get all restriction types that apply to
2304 * titles that do exist, False for all restriction types that apply to
2305 * titles that do not exist
2308 public static function getFilteredRestrictionTypes( $exists = true ) {
2309 global $wgRestrictionTypes;
2310 $types = $wgRestrictionTypes;
2312 # Remove the create restriction for existing titles
2313 $types = array_diff( $types, array( 'create' ) );
2315 # Only the create and upload restrictions apply to non-existing titles
2316 $types = array_intersect( $types, array( 'create', 'upload' ) );
2322 * Returns restriction types for the current Title
2324 * @return array applicable restriction types
2326 public function getRestrictionTypes() {
2327 if ( $this->isSpecialPage() ) {
2331 $types = self
::getFilteredRestrictionTypes( $this->exists() );
2333 if ( $this->getNamespace() != NS_FILE
) {
2334 # Remove the upload restriction for non-file titles
2335 $types = array_diff( $types, array( 'upload' ) );
2338 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2340 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
2341 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2347 * Is this title subject to title protection?
2348 * Title protection is the one applied against creation of such title.
2350 * @return Mixed An associative array representing any existent title
2351 * protection, or false if there's none.
2353 private function getTitleProtection() {
2354 // Can't protect pages in special namespaces
2355 if ( $this->getNamespace() < 0 ) {
2359 // Can't protect pages that exist.
2360 if ( $this->exists() ) {
2364 if ( !isset( $this->mTitleProtection
) ) {
2365 $dbr = wfGetDB( DB_SLAVE
);
2366 $res = $dbr->select(
2368 array( 'pt_user', 'pt_reason', 'pt_expiry', 'pt_create_perm' ),
2369 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2373 // fetchRow returns false if there are no rows.
2374 $this->mTitleProtection
= $dbr->fetchRow( $res );
2376 return $this->mTitleProtection
;
2380 * Update the title protection status
2382 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2383 * @param $create_perm String Permission required for creation
2384 * @param string $reason Reason for protection
2385 * @param string $expiry Expiry timestamp
2386 * @return boolean true
2388 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2389 wfDeprecated( __METHOD__
, '1.19' );
2393 $limit = array( 'create' => $create_perm );
2394 $expiry = array( 'create' => $expiry );
2396 $page = WikiPage
::factory( $this );
2398 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $wgUser );
2400 return $status->isOK();
2404 * Remove any title protection due to page existing
2406 public function deleteTitleProtection() {
2407 $dbw = wfGetDB( DB_MASTER
);
2411 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2414 $this->mTitleProtection
= false;
2418 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2420 * @param string $action Action to check (default: edit)
2423 public function isSemiProtected( $action = 'edit' ) {
2424 if ( $this->exists() ) {
2425 $restrictions = $this->getRestrictions( $action );
2426 if ( count( $restrictions ) > 0 ) {
2427 foreach ( $restrictions as $restriction ) {
2428 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2438 # If it doesn't exist, it can't be protected
2444 * Does the title correspond to a protected article?
2446 * @param string $action the action the page is protected from,
2447 * by default checks all actions.
2450 public function isProtected( $action = '' ) {
2451 global $wgRestrictionLevels;
2453 $restrictionTypes = $this->getRestrictionTypes();
2455 # Special pages have inherent protection
2456 if ( $this->isSpecialPage() ) {
2460 # Check regular protection levels
2461 foreach ( $restrictionTypes as $type ) {
2462 if ( $action == $type ||
$action == '' ) {
2463 $r = $this->getRestrictions( $type );
2464 foreach ( $wgRestrictionLevels as $level ) {
2465 if ( in_array( $level, $r ) && $level != '' ) {
2476 * Determines if $user is unable to edit this page because it has been protected
2477 * by $wgNamespaceProtection.
2479 * @param $user User object to check permissions
2482 public function isNamespaceProtected( User
$user ) {
2483 global $wgNamespaceProtection;
2485 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
2486 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
2487 if ( $right != '' && !$user->isAllowed( $right ) ) {
2496 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2498 * @return Bool If the page is subject to cascading restrictions.
2500 public function isCascadeProtected() {
2501 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2502 return ( $sources > 0 );
2506 * Cascading protection: Get the source of any cascading restrictions on this page.
2508 * @param bool $getPages Whether or not to retrieve the actual pages
2509 * that the restrictions have come from.
2510 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2511 * have come, false for none, or true if such restrictions exist, but $getPages
2512 * was not set. The restriction array is an array of each type, each of which
2513 * contains a array of unique groups.
2515 public function getCascadeProtectionSources( $getPages = true ) {
2517 $pagerestrictions = array();
2519 if ( isset( $this->mCascadeSources
) && $getPages ) {
2520 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2521 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2522 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2525 wfProfileIn( __METHOD__
);
2527 $dbr = wfGetDB( DB_SLAVE
);
2529 if ( $this->getNamespace() == NS_FILE
) {
2530 $tables = array( 'imagelinks', 'page_restrictions' );
2531 $where_clauses = array(
2532 'il_to' => $this->getDBkey(),
2537 $tables = array( 'templatelinks', 'page_restrictions' );
2538 $where_clauses = array(
2539 'tl_namespace' => $this->getNamespace(),
2540 'tl_title' => $this->getDBkey(),
2547 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2548 'pr_expiry', 'pr_type', 'pr_level' );
2549 $where_clauses[] = 'page_id=pr_page';
2552 $cols = array( 'pr_expiry' );
2555 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2557 $sources = $getPages ?
array() : false;
2558 $now = wfTimestampNow();
2559 $purgeExpired = false;
2561 foreach ( $res as $row ) {
2562 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2563 if ( $expiry > $now ) {
2565 $page_id = $row->pr_page
;
2566 $page_ns = $row->page_namespace
;
2567 $page_title = $row->page_title
;
2568 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2569 # Add groups needed for each restriction type if its not already there
2570 # Make sure this restriction type still exists
2572 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2573 $pagerestrictions[$row->pr_type
] = array();
2577 isset( $pagerestrictions[$row->pr_type
] )
2578 && !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] )
2580 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2586 // Trigger lazy purge of expired restrictions from the db
2587 $purgeExpired = true;
2590 if ( $purgeExpired ) {
2591 Title
::purgeExpiredRestrictions();
2595 $this->mCascadeSources
= $sources;
2596 $this->mCascadingRestrictions
= $pagerestrictions;
2598 $this->mHasCascadingRestrictions
= $sources;
2601 wfProfileOut( __METHOD__
);
2602 return array( $sources, $pagerestrictions );
2606 * Accessor/initialisation for mRestrictions
2608 * @param string $action action that permission needs to be checked for
2609 * @return Array of Strings the array of groups allowed to edit this article
2611 public function getRestrictions( $action ) {
2612 if ( !$this->mRestrictionsLoaded
) {
2613 $this->loadRestrictions();
2615 return isset( $this->mRestrictions
[$action] )
2616 ?
$this->mRestrictions
[$action]
2621 * Get the expiry time for the restriction against a given action
2624 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2625 * or not protected at all, or false if the action is not recognised.
2627 public function getRestrictionExpiry( $action ) {
2628 if ( !$this->mRestrictionsLoaded
) {
2629 $this->loadRestrictions();
2631 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2635 * Returns cascading restrictions for the current article
2639 function areRestrictionsCascading() {
2640 if ( !$this->mRestrictionsLoaded
) {
2641 $this->loadRestrictions();
2644 return $this->mCascadeRestriction
;
2648 * Loads a string into mRestrictions array
2650 * @param $res Resource restrictions as an SQL result.
2651 * @param string $oldFashionedRestrictions comma-separated list of page
2652 * restrictions from page table (pre 1.10)
2654 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2657 foreach ( $res as $row ) {
2661 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2665 * Compiles list of active page restrictions from both page table (pre 1.10)
2666 * and page_restrictions table for this existing page.
2667 * Public for usage by LiquidThreads.
2669 * @param array $rows of db result objects
2670 * @param string $oldFashionedRestrictions comma-separated list of page
2671 * restrictions from page table (pre 1.10)
2673 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2675 $dbr = wfGetDB( DB_SLAVE
);
2677 $restrictionTypes = $this->getRestrictionTypes();
2679 foreach ( $restrictionTypes as $type ) {
2680 $this->mRestrictions
[$type] = array();
2681 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2684 $this->mCascadeRestriction
= false;
2686 # Backwards-compatibility: also load the restrictions from the page record (old format).
2688 if ( $oldFashionedRestrictions === null ) {
2689 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2690 array( 'page_id' => $this->getArticleID() ), __METHOD__
);
2693 if ( $oldFashionedRestrictions != '' ) {
2695 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2696 $temp = explode( '=', trim( $restrict ) );
2697 if ( count( $temp ) == 1 ) {
2698 // old old format should be treated as edit/move restriction
2699 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2700 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2702 $restriction = trim( $temp[1] );
2703 if ( $restriction != '' ) { //some old entries are empty
2704 $this->mRestrictions
[$temp[0]] = explode( ',', $restriction );
2709 $this->mOldRestrictions
= true;
2713 if ( count( $rows ) ) {
2714 # Current system - load second to make them override.
2715 $now = wfTimestampNow();
2716 $purgeExpired = false;
2718 # Cycle through all the restrictions.
2719 foreach ( $rows as $row ) {
2721 // Don't take care of restrictions types that aren't allowed
2722 if ( !in_array( $row->pr_type
, $restrictionTypes ) ) {
2726 // This code should be refactored, now that it's being used more generally,
2727 // But I don't really see any harm in leaving it in Block for now -werdna
2728 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2730 // Only apply the restrictions if they haven't expired!
2731 if ( !$expiry ||
$expiry > $now ) {
2732 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2733 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2735 $this->mCascadeRestriction |
= $row->pr_cascade
;
2737 // Trigger a lazy purge of expired restrictions
2738 $purgeExpired = true;
2742 if ( $purgeExpired ) {
2743 Title
::purgeExpiredRestrictions();
2747 $this->mRestrictionsLoaded
= true;
2751 * Load restrictions from the page_restrictions table
2753 * @param string $oldFashionedRestrictions comma-separated list of page
2754 * restrictions from page table (pre 1.10)
2756 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2758 if ( !$this->mRestrictionsLoaded
) {
2759 if ( $this->exists() ) {
2760 $dbr = wfGetDB( DB_SLAVE
);
2762 $res = $dbr->select(
2763 'page_restrictions',
2764 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2765 array( 'pr_page' => $this->getArticleID() ),
2769 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2771 $title_protection = $this->getTitleProtection();
2773 if ( $title_protection ) {
2774 $now = wfTimestampNow();
2775 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2777 if ( !$expiry ||
$expiry > $now ) {
2778 // Apply the restrictions
2779 $this->mRestrictionsExpiry
['create'] = $expiry;
2780 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2781 } else { // Get rid of the old restrictions
2782 Title
::purgeExpiredRestrictions();
2783 $this->mTitleProtection
= false;
2786 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2788 $this->mRestrictionsLoaded
= true;
2794 * Flush the protection cache in this object and force reload from the database.
2795 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2797 public function flushRestrictions() {
2798 $this->mRestrictionsLoaded
= false;
2799 $this->mTitleProtection
= null;
2803 * Purge expired restrictions from the page_restrictions table
2805 static function purgeExpiredRestrictions() {
2806 if ( wfReadOnly() ) {
2810 $method = __METHOD__
;
2811 $dbw = wfGetDB( DB_MASTER
);
2812 $dbw->onTransactionIdle( function() use ( $dbw, $method ) {
2814 'page_restrictions',
2815 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2820 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2827 * Does this have subpages? (Warning, usually requires an extra DB query.)
2831 public function hasSubpages() {
2832 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2837 # We dynamically add a member variable for the purpose of this method
2838 # alone to cache the result. There's no point in having it hanging
2839 # around uninitialized in every Title object; therefore we only add it
2840 # if needed and don't declare it statically.
2841 if ( isset( $this->mHasSubpages
) ) {
2842 return $this->mHasSubpages
;
2845 $subpages = $this->getSubpages( 1 );
2846 if ( $subpages instanceof TitleArray
) {
2847 return $this->mHasSubpages
= (bool)$subpages->count();
2849 return $this->mHasSubpages
= false;
2853 * Get all subpages of this page.
2855 * @param int $limit maximum number of subpages to fetch; -1 for no limit
2856 * @return mixed TitleArray, or empty array if this page's namespace
2857 * doesn't allow subpages
2859 public function getSubpages( $limit = -1 ) {
2860 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2864 $dbr = wfGetDB( DB_SLAVE
);
2865 $conds['page_namespace'] = $this->getNamespace();
2866 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2868 if ( $limit > -1 ) {
2869 $options['LIMIT'] = $limit;
2871 return $this->mSubpages
= TitleArray
::newFromResult(
2872 $dbr->select( 'page',
2873 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2882 * Is there a version of this page in the deletion archive?
2884 * @return Int the number of archived revisions
2886 public function isDeleted() {
2887 if ( $this->getNamespace() < 0 ) {
2890 $dbr = wfGetDB( DB_SLAVE
);
2892 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2893 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2896 if ( $this->getNamespace() == NS_FILE
) {
2897 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2898 array( 'fa_name' => $this->getDBkey() ),
2907 * Is there a version of this page in the deletion archive?
2911 public function isDeletedQuick() {
2912 if ( $this->getNamespace() < 0 ) {
2915 $dbr = wfGetDB( DB_SLAVE
);
2916 $deleted = (bool)$dbr->selectField( 'archive', '1',
2917 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2920 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2921 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2922 array( 'fa_name' => $this->getDBkey() ),
2930 * Get the article ID for this Title from the link cache,
2931 * adding it if necessary
2933 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select
2935 * @return Int the ID
2937 public function getArticleID( $flags = 0 ) {
2938 if ( $this->getNamespace() < 0 ) {
2939 return $this->mArticleID
= 0;
2941 $linkCache = LinkCache
::singleton();
2942 if ( $flags & self
::GAID_FOR_UPDATE
) {
2943 $oldUpdate = $linkCache->forUpdate( true );
2944 $linkCache->clearLink( $this );
2945 $this->mArticleID
= $linkCache->addLinkObj( $this );
2946 $linkCache->forUpdate( $oldUpdate );
2948 if ( -1 == $this->mArticleID
) {
2949 $this->mArticleID
= $linkCache->addLinkObj( $this );
2952 return $this->mArticleID
;
2956 * Is this an article that is a redirect page?
2957 * Uses link cache, adding it if necessary
2959 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update
2962 public function isRedirect( $flags = 0 ) {
2963 if ( !is_null( $this->mRedirect
) ) {
2964 return $this->mRedirect
;
2966 # Calling getArticleID() loads the field from cache as needed
2967 if ( !$this->getArticleID( $flags ) ) {
2968 return $this->mRedirect
= false;
2971 $linkCache = LinkCache
::singleton();
2972 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2973 if ( $cached === null ) {
2974 // TODO: check the assumption that the cache actually knows about this title
2975 // and handle this, such as get the title from the database.
2976 // See https://bugzilla.wikimedia.org/show_bug.cgi?id=37209
2977 wfDebug( "LinkCache doesn't currently know about this title: " . $this->getPrefixedDBkey() );
2978 wfDebug( wfBacktrace() );
2981 $this->mRedirect
= (bool)$cached;
2983 return $this->mRedirect
;
2987 * What is the length of this page?
2988 * Uses link cache, adding it if necessary
2990 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update
2993 public function getLength( $flags = 0 ) {
2994 if ( $this->mLength
!= -1 ) {
2995 return $this->mLength
;
2997 # Calling getArticleID() loads the field from cache as needed
2998 if ( !$this->getArticleID( $flags ) ) {
2999 return $this->mLength
= 0;
3001 $linkCache = LinkCache
::singleton();
3002 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3003 if ( $cached === null ) { # check the assumption that the cache actually knows about this title
3004 # XXX: this does apparently happen, see https://bugzilla.wikimedia.org/show_bug.cgi?id=37209
3005 # as a stop gap, perhaps log this, but don't throw an exception?
3006 wfDebug( "LinkCache doesn't currently know about this title: " . $this->getPrefixedDBkey() );
3007 wfDebug( wfBacktrace() );
3010 $this->mLength
= intval( $cached );
3012 return $this->mLength
;
3016 * What is the page_latest field for this page?
3018 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update
3019 * @throws MWException
3020 * @return Int or 0 if the page doesn't exist
3022 public function getLatestRevID( $flags = 0 ) {
3023 if ( !( $flags & Title
::GAID_FOR_UPDATE
) && $this->mLatestID
!== false ) {
3024 return intval( $this->mLatestID
);
3026 # Calling getArticleID() loads the field from cache as needed
3027 if ( !$this->getArticleID( $flags ) ) {
3028 return $this->mLatestID
= 0;
3030 $linkCache = LinkCache
::singleton();
3031 $linkCache->addLinkObj( $this );
3032 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3033 if ( $cached === null ) { # check the assumption that the cache actually knows about this title
3034 # XXX: this does apparently happen, see https://bugzilla.wikimedia.org/show_bug.cgi?id=37209
3035 # as a stop gap, perhaps log this, but don't throw an exception?
3036 throw new MWException( "LinkCache doesn't currently know about this title: " . $this->getPrefixedDBkey() );
3039 $this->mLatestID
= intval( $cached );
3041 return $this->mLatestID
;
3045 * This clears some fields in this object, and clears any associated
3046 * keys in the "bad links" section of the link cache.
3048 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3049 * loading of the new page_id. It's also called from
3050 * WikiPage::doDeleteArticleReal()
3052 * @param int $newid the new Article ID
3054 public function resetArticleID( $newid ) {
3055 $linkCache = LinkCache
::singleton();
3056 $linkCache->clearLink( $this );
3058 if ( $newid === false ) {
3059 $this->mArticleID
= -1;
3061 $this->mArticleID
= intval( $newid );
3063 $this->mRestrictionsLoaded
= false;
3064 $this->mRestrictions
= array();
3065 $this->mRedirect
= null;
3066 $this->mLength
= -1;
3067 $this->mLatestID
= false;
3068 $this->mContentModel
= false;
3069 $this->mEstimateRevisions
= null;
3073 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3075 * @param string $text containing title to capitalize
3076 * @param int $ns namespace index, defaults to NS_MAIN
3077 * @return String containing capitalized title
3079 public static function capitalize( $text, $ns = NS_MAIN
) {
3082 if ( MWNamespace
::isCapitalized( $ns ) ) {
3083 return $wgContLang->ucfirst( $text );
3090 * Secure and split - main initialisation function for this object
3092 * Assumes that mDbkeyform has been set, and is urldecoded
3093 * and uses underscores, but not otherwise munged. This function
3094 * removes illegal characters, splits off the interwiki and
3095 * namespace prefixes, sets the other forms, and canonicalizes
3098 * @return Bool true on success
3100 private function secureAndSplit() {
3101 global $wgContLang, $wgLocalInterwiki;
3104 $this->mInterwiki
= $this->mFragment
= '';
3105 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
3107 $dbkey = $this->mDbkeyform
;
3109 # Strip Unicode bidi override characters.
3110 # Sometimes they slip into cut-n-pasted page titles, where the
3111 # override chars get included in list displays.
3112 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
3114 # Clean up whitespace
3115 # Note: use of the /u option on preg_replace here will cause
3116 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
3117 # conveniently disabling them.
3118 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
3119 $dbkey = trim( $dbkey, '_' );
3121 if ( $dbkey == '' ) {
3125 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
3126 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
3130 $this->mDbkeyform
= $dbkey;
3132 # Initial colon indicates main namespace rather than specified default
3133 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
3134 if ( ':' == $dbkey[0] ) {
3135 $this->mNamespace
= NS_MAIN
;
3136 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
3137 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
3140 # Namespace or interwiki prefix
3142 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
3145 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
3147 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
3148 # Ordinary namespace
3150 $this->mNamespace
= $ns;
3151 # For Talk:X pages, check if X has a "namespace" prefix
3152 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
3153 if ( $wgContLang->getNsIndex( $x[1] ) ) {
3154 # Disallow Talk:File:x type titles...
3156 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
3157 # Disallow Talk:Interwiki:x type titles...
3161 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
3162 if ( !$firstPass ) {
3163 # Can't make a local interwiki link to an interwiki link.
3164 # That's just crazy!
3170 $this->mInterwiki
= $wgContLang->lc( $p );
3172 # Redundant interwiki prefix to the local wiki
3173 if ( $wgLocalInterwiki !== false
3174 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
3176 if ( $dbkey == '' ) {
3177 # Can't have an empty self-link
3180 $this->mInterwiki
= '';
3182 # Do another namespace split...
3186 # If there's an initial colon after the interwiki, that also
3187 # resets the default namespace
3188 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3189 $this->mNamespace
= NS_MAIN
;
3190 $dbkey = substr( $dbkey, 1 );
3193 # If there's no recognized interwiki or namespace,
3194 # then let the colon expression be part of the title.
3199 # We already know that some pages won't be in the database!
3200 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
3201 $this->mArticleID
= 0;
3203 $fragment = strstr( $dbkey, '#' );
3204 if ( false !== $fragment ) {
3205 $this->setFragment( $fragment );
3206 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3207 # remove whitespace again: prevents "Foo_bar_#"
3208 # becoming "Foo_bar_"
3209 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3212 # Reject illegal characters.
3213 $rxTc = self
::getTitleInvalidRegex();
3214 if ( preg_match( $rxTc, $dbkey ) ) {
3218 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3219 # reachable due to the way web browsers deal with 'relative' URLs.
3220 # Also, they conflict with subpage syntax. Forbid them explicitly.
3222 strpos( $dbkey, '.' ) !== false &&
3224 $dbkey === '.' ||
$dbkey === '..' ||
3225 strpos( $dbkey, './' ) === 0 ||
3226 strpos( $dbkey, '../' ) === 0 ||
3227 strpos( $dbkey, '/./' ) !== false ||
3228 strpos( $dbkey, '/../' ) !== false ||
3229 substr( $dbkey, -2 ) == '/.' ||
3230 substr( $dbkey, -3 ) == '/..'
3236 # Magic tilde sequences? Nu-uh!
3237 if ( strpos( $dbkey, '~~~' ) !== false ) {
3241 # Limit the size of titles to 255 bytes. This is typically the size of the
3242 # underlying database field. We make an exception for special pages, which
3243 # don't need to be stored in the database, and may edge over 255 bytes due
3244 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3246 ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 )
3247 ||
strlen( $dbkey ) > 512
3252 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3253 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3254 # other site might be case-sensitive.
3255 $this->mUserCaseDBKey
= $dbkey;
3256 if ( $this->mInterwiki
== '' ) {
3257 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
3260 # Can't make a link to a namespace alone... "empty" local links can only be
3261 # self-links with a fragment identifier.
3262 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
3266 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3267 // IP names are not allowed for accounts, and can only be referring to
3268 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3269 // there are numerous ways to present the same IP. Having sp:contribs scan
3270 // them all is silly and having some show the edits and others not is
3271 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3272 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
3273 ? IP
::sanitizeIP( $dbkey )
3276 // Any remaining initial :s are illegal.
3277 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3282 $this->mDbkeyform
= $dbkey;
3283 $this->mUrlform
= wfUrlencode( $dbkey );
3285 $this->mTextform
= str_replace( '_', ' ', $dbkey );
3291 * Get an array of Title objects linking to this Title
3292 * Also stores the IDs in the link cache.
3294 * WARNING: do not use this function on arbitrary user-supplied titles!
3295 * On heavily-used templates it will max out the memory.
3297 * @param array $options may be FOR UPDATE
3298 * @param string $table table name
3299 * @param string $prefix fields prefix
3300 * @return Array of Title objects linking here
3302 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3303 if ( count( $options ) > 0 ) {
3304 $db = wfGetDB( DB_MASTER
);
3306 $db = wfGetDB( DB_SLAVE
);
3310 array( 'page', $table ),
3311 self
::getSelectFields(),
3313 "{$prefix}_from=page_id",
3314 "{$prefix}_namespace" => $this->getNamespace(),
3315 "{$prefix}_title" => $this->getDBkey() ),
3321 if ( $res->numRows() ) {
3322 $linkCache = LinkCache
::singleton();
3323 foreach ( $res as $row ) {
3324 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3326 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3327 $retVal[] = $titleObj;
3335 * Get an array of Title objects using this Title as a template
3336 * Also stores the IDs in the link cache.
3338 * WARNING: do not use this function on arbitrary user-supplied titles!
3339 * On heavily-used templates it will max out the memory.
3341 * @param array $options may be FOR UPDATE
3342 * @return Array of Title the Title objects linking here
3344 public function getTemplateLinksTo( $options = array() ) {
3345 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3349 * Get an array of Title objects linked from this Title
3350 * Also stores the IDs in the link cache.
3352 * WARNING: do not use this function on arbitrary user-supplied titles!
3353 * On heavily-used templates it will max out the memory.
3355 * @param array $options may be FOR UPDATE
3356 * @param string $table table name
3357 * @param string $prefix fields prefix
3358 * @return Array of Title objects linking here
3360 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3361 global $wgContentHandlerUseDB;
3363 $id = $this->getArticleID();
3365 # If the page doesn't exist; there can't be any link from this page
3370 if ( count( $options ) > 0 ) {
3371 $db = wfGetDB( DB_MASTER
);
3373 $db = wfGetDB( DB_SLAVE
);
3376 $namespaceFiled = "{$prefix}_namespace";
3377 $titleField = "{$prefix}_title";
3379 $fields = array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' );
3380 if ( $wgContentHandlerUseDB ) {
3381 $fields[] = 'page_content_model';
3385 array( $table, 'page' ),
3387 array( "{$prefix}_from" => $id ),
3390 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3394 if ( $res->numRows() ) {
3395 $linkCache = LinkCache
::singleton();
3396 foreach ( $res as $row ) {
3397 $titleObj = Title
::makeTitle( $row->$namespaceFiled, $row->$titleField );
3399 if ( $row->page_id
) {
3400 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3402 $linkCache->addBadLinkObj( $titleObj );
3404 $retVal[] = $titleObj;
3412 * Get an array of Title objects used on this Title as a template
3413 * Also stores the IDs in the link cache.
3415 * WARNING: do not use this function on arbitrary user-supplied titles!
3416 * On heavily-used templates it will max out the memory.
3418 * @param array $options may be FOR UPDATE
3419 * @return Array of Title the Title objects used here
3421 public function getTemplateLinksFrom( $options = array() ) {
3422 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3426 * Get an array of Title objects referring to non-existent articles linked from this page
3428 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3429 * @return Array of Title the Title objects
3431 public function getBrokenLinksFrom() {
3432 if ( $this->getArticleID() == 0 ) {
3433 # All links from article ID 0 are false positives
3437 $dbr = wfGetDB( DB_SLAVE
);
3438 $res = $dbr->select(
3439 array( 'page', 'pagelinks' ),
3440 array( 'pl_namespace', 'pl_title' ),
3442 'pl_from' => $this->getArticleID(),
3443 'page_namespace IS NULL'
3445 __METHOD__
, array(),
3449 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3455 foreach ( $res as $row ) {
3456 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3462 * Get a list of URLs to purge from the Squid cache when this
3465 * @return Array of String the URLs
3467 public function getSquidURLs() {
3469 $this->getInternalURL(),
3470 $this->getInternalURL( 'action=history' )
3473 $pageLang = $this->getPageLanguage();
3474 if ( $pageLang->hasVariants() ) {
3475 $variants = $pageLang->getVariants();
3476 foreach ( $variants as $vCode ) {
3477 $urls[] = $this->getInternalURL( '', $vCode );
3485 * Purge all applicable Squid URLs
3487 public function purgeSquid() {
3489 if ( $wgUseSquid ) {
3490 $urls = $this->getSquidURLs();
3491 $u = new SquidUpdate( $urls );
3497 * Move this page without authentication
3499 * @param $nt Title the new page Title
3500 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3502 public function moveNoAuth( &$nt ) {
3503 return $this->moveTo( $nt, false );
3507 * Check whether a given move operation would be valid.
3508 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3510 * @param $nt Title the new title
3511 * @param bool $auth indicates whether $wgUser's permissions
3513 * @param string $reason is the log summary of the move, used for spam checking
3514 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3516 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3517 global $wgUser, $wgContentHandlerUseDB;
3521 // Normally we'd add this to $errors, but we'll get
3522 // lots of syntax errors if $nt is not an object
3523 return array( array( 'badtitletext' ) );
3525 if ( $this->equals( $nt ) ) {
3526 $errors[] = array( 'selfmove' );
3528 if ( !$this->isMovable() ) {
3529 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3531 if ( $nt->getInterwiki() != '' ) {
3532 $errors[] = array( 'immobile-target-namespace-iw' );
3534 if ( !$nt->isMovable() ) {
3535 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3538 $oldid = $this->getArticleID();
3539 $newid = $nt->getArticleID();
3541 if ( strlen( $nt->getDBkey() ) < 1 ) {
3542 $errors[] = array( 'articleexists' );
3545 ( $this->getDBkey() == '' ) ||
3547 ( $nt->getDBkey() == '' )
3549 $errors[] = array( 'badarticleerror' );
3552 // Content model checks
3553 if ( !$wgContentHandlerUseDB &&
3554 $this->getContentModel() !== $nt->getContentModel() ) {
3555 // can't move a page if that would change the page's content model
3558 ContentHandler
::getLocalizedName( $this->getContentModel() ),
3559 ContentHandler
::getLocalizedName( $nt->getContentModel() )
3563 // Image-specific checks
3564 if ( $this->getNamespace() == NS_FILE
) {
3565 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3568 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3569 $errors[] = array( 'nonfile-cannot-move-to-file' );
3573 $errors = wfMergeErrorArrays( $errors,
3574 $this->getUserPermissionsErrors( 'move', $wgUser ),
3575 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3576 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3577 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3580 $match = EditPage
::matchSummarySpamRegex( $reason );
3581 if ( $match !== false ) {
3582 // This is kind of lame, won't display nice
3583 $errors[] = array( 'spamprotectiontext' );
3587 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3588 $errors[] = array( 'hookaborted', $err );
3591 # The move is allowed only if (1) the target doesn't exist, or
3592 # (2) the target is a redirect to the source, and has no history
3593 # (so we can undo bad moves right after they're done).
3595 if ( 0 != $newid ) { # Target exists; check for validity
3596 if ( !$this->isValidMoveTarget( $nt ) ) {
3597 $errors[] = array( 'articleexists' );
3600 $tp = $nt->getTitleProtection();
3601 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3602 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3603 $errors[] = array( 'cantmove-titleprotected' );
3606 if ( empty( $errors ) ) {
3613 * Check if the requested move target is a valid file move target
3614 * @param Title $nt Target title
3615 * @return array List of errors
3617 protected function validateFileMoveOperation( $nt ) {
3622 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3624 $file = wfLocalFile( $this );
3625 if ( $file->exists() ) {
3626 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3627 $errors[] = array( 'imageinvalidfilename' );
3629 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3630 $errors[] = array( 'imagetypemismatch' );
3634 if ( $nt->getNamespace() != NS_FILE
) {
3635 $errors[] = array( 'imagenocrossnamespace' );
3636 // From here we want to do checks on a file object, so if we can't
3637 // create one, we must return.
3641 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3643 $destFile = wfLocalFile( $nt );
3644 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3645 $errors[] = array( 'file-exists-sharedrepo' );
3652 * Move a title to a new location
3654 * @param $nt Title the new title
3655 * @param bool $auth indicates whether $wgUser's permissions
3657 * @param string $reason the reason for the move
3658 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3659 * Ignored if the user doesn't have the suppressredirect right.
3660 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3662 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3664 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3665 if ( is_array( $err ) ) {
3666 // Auto-block user's IP if the account was "hard" blocked
3667 $wgUser->spreadAnyEditBlock();
3670 // Check suppressredirect permission
3671 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3672 $createRedirect = true;
3675 // If it is a file, move it first.
3676 // It is done before all other moving stuff is done because it's hard to revert.
3677 $dbw = wfGetDB( DB_MASTER
);
3678 if ( $this->getNamespace() == NS_FILE
) {
3679 $file = wfLocalFile( $this );
3680 if ( $file->exists() ) {
3681 $status = $file->move( $nt );
3682 if ( !$status->isOk() ) {
3683 return $status->getErrorsArray();
3686 // Clear RepoGroup process cache
3687 RepoGroup
::singleton()->clearCache( $this );
3688 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3691 $dbw->begin( __METHOD__
); # If $file was a LocalFile, its transaction would have closed our own.
3692 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3693 $protected = $this->isProtected();
3695 // Do the actual move
3696 $this->moveToInternal( $nt, $reason, $createRedirect );
3698 // Refresh the sortkey for this row. Be careful to avoid resetting
3699 // cl_timestamp, which may disturb time-based lists on some sites.
3700 $prefixes = $dbw->select(
3702 array( 'cl_sortkey_prefix', 'cl_to' ),
3703 array( 'cl_from' => $pageid ),
3706 foreach ( $prefixes as $prefixRow ) {
3707 $prefix = $prefixRow->cl_sortkey_prefix
;
3708 $catTo = $prefixRow->cl_to
;
3709 $dbw->update( 'categorylinks',
3711 'cl_sortkey' => Collation
::singleton()->getSortKey(
3712 $nt->getCategorySortkey( $prefix ) ),
3713 'cl_timestamp=cl_timestamp' ),
3715 'cl_from' => $pageid,
3716 'cl_to' => $catTo ),
3721 $redirid = $this->getArticleID();
3724 # Protect the redirect title as the title used to be...
3725 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3727 'pr_page' => $redirid,
3728 'pr_type' => 'pr_type',
3729 'pr_level' => 'pr_level',
3730 'pr_cascade' => 'pr_cascade',
3731 'pr_user' => 'pr_user',
3732 'pr_expiry' => 'pr_expiry'
3734 array( 'pr_page' => $pageid ),
3738 # Update the protection log
3739 $log = new LogPage( 'protect' );
3740 $comment = wfMessage(
3742 $this->getPrefixedText(),
3743 $nt->getPrefixedText()
3744 )->inContentLanguage()->text();
3746 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3748 // @todo FIXME: $params?
3749 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3753 $oldnamespace = MWNamespace
::getSubject( $this->getNamespace() );
3754 $newnamespace = MWNamespace
::getSubject( $nt->getNamespace() );
3755 $oldtitle = $this->getDBkey();
3756 $newtitle = $nt->getDBkey();
3758 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3759 WatchedItem
::duplicateEntries( $this, $nt );
3762 $dbw->commit( __METHOD__
);
3764 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3769 * Move page to a title which is either a redirect to the
3770 * source page or nonexistent
3772 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3773 * @param string $reason The reason for the move
3774 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
3775 * if the user has the suppressredirect right
3776 * @throws MWException
3778 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3779 global $wgUser, $wgContLang;
3781 if ( $nt->exists() ) {
3782 $moveOverRedirect = true;
3783 $logType = 'move_redir';
3785 $moveOverRedirect = false;
3789 if ( $createRedirect ) {
3790 $contentHandler = ContentHandler
::getForTitle( $this );
3791 $redirectContent = $contentHandler->makeRedirectContent( $nt );
3793 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
3795 $redirectContent = null;
3798 $logEntry = new ManualLogEntry( 'move', $logType );
3799 $logEntry->setPerformer( $wgUser );
3800 $logEntry->setTarget( $this );
3801 $logEntry->setComment( $reason );
3802 $logEntry->setParameters( array(
3803 '4::target' => $nt->getPrefixedText(),
3804 '5::noredir' => $redirectContent ?
'0': '1',
3807 $formatter = LogFormatter
::newFromEntry( $logEntry );
3808 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3809 $comment = $formatter->getPlainActionText();
3811 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3813 # Truncate for whole multibyte characters.
3814 $comment = $wgContLang->truncate( $comment, 255 );
3816 $oldid = $this->getArticleID();
3818 $dbw = wfGetDB( DB_MASTER
);
3820 $newpage = WikiPage
::factory( $nt );
3822 if ( $moveOverRedirect ) {
3823 $newid = $nt->getArticleID();
3825 # Delete the old redirect. We don't save it to history since
3826 # by definition if we've got here it's rather uninteresting.
3827 # We have to remove it so that the next step doesn't trigger
3828 # a conflict on the unique namespace+title index...
3829 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3831 $newpage->doDeleteUpdates( $newid );
3834 # Save a null revision in the page's history notifying of the move
3835 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3836 if ( !is_object( $nullRevision ) ) {
3837 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3840 $nullRevision->insertOn( $dbw );
3842 # Change the name of the target page:
3843 $dbw->update( 'page',
3845 'page_namespace' => $nt->getNamespace(),
3846 'page_title' => $nt->getDBkey(),
3848 /* WHERE */ array( 'page_id' => $oldid ),
3852 $this->resetArticleID( 0 );
3853 $nt->resetArticleID( $oldid );
3854 $newpage->loadPageData( WikiPage
::READ_LOCKING
); // bug 46397
3856 $newpage->updateRevisionOn( $dbw, $nullRevision );
3858 wfRunHooks( 'NewRevisionFromEditComplete',
3859 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3861 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3863 if ( !$moveOverRedirect ) {
3864 WikiPage
::onArticleCreate( $nt );
3867 # Recreate the redirect, this time in the other direction.
3868 if ( !$redirectContent ) {
3869 WikiPage
::onArticleDelete( $this );
3871 $redirectArticle = WikiPage
::factory( $this );
3872 $redirectArticle->loadFromRow( false, WikiPage
::READ_LOCKING
); // bug 46397
3873 $newid = $redirectArticle->insertOn( $dbw );
3874 if ( $newid ) { // sanity
3875 $redirectRevision = new Revision( array(
3876 'title' => $this, // for determining the default content model
3878 'comment' => $comment,
3879 'content' => $redirectContent ) );
3880 $redirectRevision->insertOn( $dbw );
3881 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3883 wfRunHooks( 'NewRevisionFromEditComplete',
3884 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3886 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3891 $logid = $logEntry->insert();
3892 $logEntry->publish( $logid );
3896 * Move this page's subpages to be subpages of $nt
3898 * @param $nt Title Move target
3899 * @param bool $auth Whether $wgUser's permissions should be checked
3900 * @param string $reason The reason for the move
3901 * @param bool $createRedirect Whether to create redirects from the old subpages to
3902 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3903 * @return mixed array with old page titles as keys, and strings (new page titles) or
3904 * arrays (errors) as values, or an error array with numeric indices if no pages
3907 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3908 global $wgMaximumMovedPages;
3909 // Check permissions
3910 if ( !$this->userCan( 'move-subpages' ) ) {
3911 return array( 'cant-move-subpages' );
3913 // Do the source and target namespaces support subpages?
3914 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3915 return array( 'namespace-nosubpages',
3916 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3918 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3919 return array( 'namespace-nosubpages',
3920 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3923 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3926 foreach ( $subpages as $oldSubpage ) {
3928 if ( $count > $wgMaximumMovedPages ) {
3929 $retval[$oldSubpage->getPrefixedTitle()] =
3930 array( 'movepage-max-pages',
3931 $wgMaximumMovedPages );
3935 // We don't know whether this function was called before
3936 // or after moving the root page, so check both
3938 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3939 $oldSubpage->getArticleID() == $nt->getArticleID() )
3941 // When moving a page to a subpage of itself,
3942 // don't move it twice
3945 $newPageName = preg_replace(
3946 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3947 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3948 $oldSubpage->getDBkey() );
3949 if ( $oldSubpage->isTalkPage() ) {
3950 $newNs = $nt->getTalkPage()->getNamespace();
3952 $newNs = $nt->getSubjectPage()->getNamespace();
3954 # Bug 14385: we need makeTitleSafe because the new page names may
3955 # be longer than 255 characters.
3956 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3958 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3959 if ( $success === true ) {
3960 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3962 $retval[$oldSubpage->getPrefixedText()] = $success;
3969 * Checks if this page is just a one-rev redirect.
3970 * Adds lock, so don't use just for light purposes.
3974 public function isSingleRevRedirect() {
3975 global $wgContentHandlerUseDB;
3977 $dbw = wfGetDB( DB_MASTER
);
3980 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3981 if ( $wgContentHandlerUseDB ) {
3982 $fields[] = 'page_content_model';
3985 $row = $dbw->selectRow( 'page',
3989 array( 'FOR UPDATE' )
3991 # Cache some fields we may want
3992 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3993 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3994 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3995 $this->mContentModel
= $row && isset( $row->page_content_model
) ?
strval( $row->page_content_model
) : false;
3996 if ( !$this->mRedirect
) {
3999 # Does the article have a history?
4000 $row = $dbw->selectField( array( 'page', 'revision' ),
4002 array( 'page_namespace' => $this->getNamespace(),
4003 'page_title' => $this->getDBkey(),
4005 'page_latest != rev_id'
4008 array( 'FOR UPDATE' )
4010 # Return true if there was no history
4011 return ( $row === false );
4015 * Checks if $this can be moved to a given Title
4016 * - Selects for update, so don't call it unless you mean business
4018 * @param $nt Title the new title to check
4021 public function isValidMoveTarget( $nt ) {
4022 # Is it an existing file?
4023 if ( $nt->getNamespace() == NS_FILE
) {
4024 $file = wfLocalFile( $nt );
4025 if ( $file->exists() ) {
4026 wfDebug( __METHOD__
. ": file exists\n" );
4030 # Is it a redirect with no history?
4031 if ( !$nt->isSingleRevRedirect() ) {
4032 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
4035 # Get the article text
4036 $rev = Revision
::newFromTitle( $nt, false, Revision
::READ_LATEST
);
4037 if ( !is_object( $rev ) ) {
4040 $content = $rev->getContent();
4041 # Does the redirect point to the source?
4042 # Or is it a broken self-redirect, usually caused by namespace collisions?
4043 $redirTitle = $content ?
$content->getRedirectTarget() : null;
4045 if ( $redirTitle ) {
4046 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4047 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4048 wfDebug( __METHOD__
. ": redirect points to other page\n" );
4054 # Fail safe (not a redirect after all. strange.)
4055 wfDebug( __METHOD__
. ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4056 " is a redirect, but it doesn't contain a valid redirect.\n" );
4062 * Get categories to which this Title belongs and return an array of
4063 * categories' names.
4065 * @return Array of parents in the form:
4066 * $parent => $currentarticle
4068 public function getParentCategories() {
4073 $titleKey = $this->getArticleID();
4075 if ( $titleKey === 0 ) {
4079 $dbr = wfGetDB( DB_SLAVE
);
4081 $res = $dbr->select(
4084 array( 'cl_from' => $titleKey ),
4088 if ( $res->numRows() > 0 ) {
4089 foreach ( $res as $row ) {
4090 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4091 $data[$wgContLang->getNsText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
4098 * Get a tree of parent categories
4100 * @param array $children with the children in the keys, to check for circular refs
4101 * @return Array Tree of parent categories
4103 public function getParentCategoryTree( $children = array() ) {
4105 $parents = $this->getParentCategories();
4108 foreach ( $parents as $parent => $current ) {
4109 if ( array_key_exists( $parent, $children ) ) {
4110 # Circular reference
4111 $stack[$parent] = array();
4113 $nt = Title
::newFromText( $parent );
4115 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
4125 * Get an associative array for selecting this title from
4128 * @return Array suitable for the $where parameter of DB::select()
4130 public function pageCond() {
4131 if ( $this->mArticleID
> 0 ) {
4132 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4133 return array( 'page_id' => $this->mArticleID
);
4135 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
4140 * Get the revision ID of the previous revision
4142 * @param int $revId Revision ID. Get the revision that was before this one.
4143 * @param int $flags Title::GAID_FOR_UPDATE
4144 * @return Int|Bool Old revision ID, or FALSE if none exists
4146 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4147 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4148 $revId = $db->selectField( 'revision', 'rev_id',
4150 'rev_page' => $this->getArticleID( $flags ),
4151 'rev_id < ' . intval( $revId )
4154 array( 'ORDER BY' => 'rev_id DESC' )
4157 if ( $revId === false ) {
4160 return intval( $revId );
4165 * Get the revision ID of the next revision
4167 * @param int $revId Revision ID. Get the revision that was after this one.
4168 * @param int $flags Title::GAID_FOR_UPDATE
4169 * @return Int|Bool Next revision ID, or FALSE if none exists
4171 public function getNextRevisionID( $revId, $flags = 0 ) {
4172 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4173 $revId = $db->selectField( 'revision', 'rev_id',
4175 'rev_page' => $this->getArticleID( $flags ),
4176 'rev_id > ' . intval( $revId )
4179 array( 'ORDER BY' => 'rev_id' )
4182 if ( $revId === false ) {
4185 return intval( $revId );
4190 * Get the first revision of the page
4192 * @param int $flags Title::GAID_FOR_UPDATE
4193 * @return Revision|Null if page doesn't exist
4195 public function getFirstRevision( $flags = 0 ) {
4196 $pageId = $this->getArticleID( $flags );
4198 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
4199 $row = $db->selectRow( 'revision', Revision
::selectFields(),
4200 array( 'rev_page' => $pageId ),
4202 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4205 return new Revision( $row );
4212 * Get the oldest revision timestamp of this page
4214 * @param int $flags Title::GAID_FOR_UPDATE
4215 * @return String: MW timestamp
4217 public function getEarliestRevTime( $flags = 0 ) {
4218 $rev = $this->getFirstRevision( $flags );
4219 return $rev ?
$rev->getTimestamp() : null;
4223 * Check if this is a new page
4227 public function isNewPage() {
4228 $dbr = wfGetDB( DB_SLAVE
);
4229 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
4233 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4237 public function isBigDeletion() {
4238 global $wgDeleteRevisionsLimit;
4240 if ( !$wgDeleteRevisionsLimit ) {
4244 $revCount = $this->estimateRevisionCount();
4245 return $revCount > $wgDeleteRevisionsLimit;
4249 * Get the approximate revision count of this page.
4253 public function estimateRevisionCount() {
4254 if ( !$this->exists() ) {
4258 if ( $this->mEstimateRevisions
=== null ) {
4259 $dbr = wfGetDB( DB_SLAVE
);
4260 $this->mEstimateRevisions
= $dbr->estimateRowCount( 'revision', '*',
4261 array( 'rev_page' => $this->getArticleID() ), __METHOD__
);
4264 return $this->mEstimateRevisions
;
4268 * Get the number of revisions between the given revision.
4269 * Used for diffs and other things that really need it.
4271 * @param int|Revision $old Old revision or rev ID (first before range)
4272 * @param int|Revision $new New revision or rev ID (first after range)
4273 * @return Int Number of revisions between these revisions.
4275 public function countRevisionsBetween( $old, $new ) {
4276 if ( !( $old instanceof Revision
) ) {
4277 $old = Revision
::newFromTitle( $this, (int)$old );
4279 if ( !( $new instanceof Revision
) ) {
4280 $new = Revision
::newFromTitle( $this, (int)$new );
4282 if ( !$old ||
!$new ) {
4283 return 0; // nothing to compare
4285 $dbr = wfGetDB( DB_SLAVE
);
4286 return (int)$dbr->selectField( 'revision', 'count(*)',
4288 'rev_page' => $this->getArticleID(),
4289 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4290 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4297 * Get the number of authors between the given revisions or revision IDs.
4298 * Used for diffs and other things that really need it.
4300 * @param int|Revision $old Old revision or rev ID (first before range by default)
4301 * @param int|Revision $new New revision or rev ID (first after range by default)
4302 * @param int $limit Maximum number of authors
4303 * @param string|array $options (Optional): Single option, or an array of options:
4304 * 'include_old' Include $old in the range; $new is excluded.
4305 * 'include_new' Include $new in the range; $old is excluded.
4306 * 'include_both' Include both $old and $new in the range.
4307 * Unknown option values are ignored.
4308 * @return int Number of revision authors in the range; zero if not both revisions exist
4310 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4311 if ( !( $old instanceof Revision
) ) {
4312 $old = Revision
::newFromTitle( $this, (int)$old );
4314 if ( !( $new instanceof Revision
) ) {
4315 $new = Revision
::newFromTitle( $this, (int)$new );
4317 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4318 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4319 // in the sanity check below?
4320 if ( !$old ||
!$new ) {
4321 return 0; // nothing to compare
4325 $options = (array)$options;
4326 if ( in_array( 'include_old', $options ) ) {
4329 if ( in_array( 'include_new', $options ) ) {
4332 if ( in_array( 'include_both', $options ) ) {
4336 // No DB query needed if $old and $new are the same or successive revisions:
4337 if ( $old->getId() === $new->getId() ) {
4338 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4339 } elseif ( $old->getId() === $new->getParentId() ) {
4340 if ( $old_cmp === '>' ||
$new_cmp === '<' ) {
4341 return ( $old_cmp === '>' && $new_cmp === '<' ) ?
0 : 1;
4343 return ( $old->getRawUserText() === $new->getRawUserText() ) ?
1 : 2;
4345 $dbr = wfGetDB( DB_SLAVE
);
4346 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4348 'rev_page' => $this->getArticleID(),
4349 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4350 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4352 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
4354 return (int)$dbr->numRows( $res );
4358 * Compare with another title.
4360 * @param $title Title
4363 public function equals( Title
$title ) {
4364 // Note: === is necessary for proper matching of number-like titles.
4365 return $this->getInterwiki() === $title->getInterwiki()
4366 && $this->getNamespace() == $title->getNamespace()
4367 && $this->getDBkey() === $title->getDBkey();
4371 * Check if this title is a subpage of another title
4373 * @param $title Title
4376 public function isSubpageOf( Title
$title ) {
4377 return $this->getInterwiki() === $title->getInterwiki()
4378 && $this->getNamespace() == $title->getNamespace()
4379 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4383 * Check if page exists. For historical reasons, this function simply
4384 * checks for the existence of the title in the page table, and will
4385 * thus return false for interwiki links, special pages and the like.
4386 * If you want to know if a title can be meaningfully viewed, you should
4387 * probably call the isKnown() method instead.
4391 public function exists() {
4392 return $this->getArticleID() != 0;
4396 * Should links to this title be shown as potentially viewable (i.e. as
4397 * "bluelinks"), even if there's no record by this title in the page
4400 * This function is semi-deprecated for public use, as well as somewhat
4401 * misleadingly named. You probably just want to call isKnown(), which
4402 * calls this function internally.
4404 * (ISSUE: Most of these checks are cheap, but the file existence check
4405 * can potentially be quite expensive. Including it here fixes a lot of
4406 * existing code, but we might want to add an optional parameter to skip
4407 * it and any other expensive checks.)
4411 public function isAlwaysKnown() {
4415 * Allows overriding default behavior for determining if a page exists.
4416 * If $isKnown is kept as null, regular checks happen. If it's
4417 * a boolean, this value is returned by the isKnown method.
4421 * @param Title $title
4422 * @param boolean|null $isKnown
4424 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4426 if ( !is_null( $isKnown ) ) {
4430 if ( $this->mInterwiki
!= '' ) {
4431 return true; // any interwiki link might be viewable, for all we know
4434 switch( $this->mNamespace
) {
4437 // file exists, possibly in a foreign repo
4438 return (bool)wfFindFile( $this );
4440 // valid special page
4441 return SpecialPageFactory
::exists( $this->getDBkey() );
4443 // selflink, possibly with fragment
4444 return $this->mDbkeyform
== '';
4446 // known system message
4447 return $this->hasSourceText() !== false;
4454 * Does this title refer to a page that can (or might) be meaningfully
4455 * viewed? In particular, this function may be used to determine if
4456 * links to the title should be rendered as "bluelinks" (as opposed to
4457 * "redlinks" to non-existent pages).
4458 * Adding something else to this function will cause inconsistency
4459 * since LinkHolderArray calls isAlwaysKnown() and does its own
4460 * page existence check.
4464 public function isKnown() {
4465 return $this->isAlwaysKnown() ||
$this->exists();
4469 * Does this page have source text?
4473 public function hasSourceText() {
4474 if ( $this->exists() ) {
4478 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4479 // If the page doesn't exist but is a known system message, default
4480 // message content will be displayed, same for language subpages-
4481 // Use always content language to avoid loading hundreds of languages
4482 // to get the link color.
4484 list( $name, ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4485 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4486 return $message->exists();
4493 * Get the default message text or false if the message doesn't exist
4495 * @return String or false
4497 public function getDefaultMessageText() {
4500 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4504 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4505 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4507 if ( $message->exists() ) {
4508 return $message->plain();
4515 * Updates page_touched for this page; called from LinksUpdate.php
4517 * @return Bool true if the update succeeded
4519 public function invalidateCache() {
4522 if ( wfReadOnly() ) {
4526 $dbw = wfGetDB( DB_MASTER
);
4527 $conds = $this->pageCond();
4528 $dbw->onTransactionIdle( function() use ( $dbw, $conds ) {
4531 array( 'page_touched' => $dbw->timestamp() ),
4536 HTMLFileCache
::clearFileCache( $this );
4539 $revision = WikiPage
::factory( $this )->getRevision();
4540 if ( $revision !== null ) {
4541 $memcKey = wfMemcKey( 'infoaction', $this->getPrefixedText(), $revision->getId() );
4542 $success = $wgMemc->delete( $memcKey );
4551 * Update page_touched timestamps and send squid purge messages for
4552 * pages linking to this title. May be sent to the job queue depending
4553 * on the number of links. Typically called on create and delete.
4555 public function touchLinks() {
4556 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4559 if ( $this->getNamespace() == NS_CATEGORY
) {
4560 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4566 * Get the last touched timestamp
4568 * @param $db DatabaseBase: optional db
4569 * @return String last-touched timestamp
4571 public function getTouched( $db = null ) {
4572 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4573 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4578 * Get the timestamp when this page was updated since the user last saw it.
4581 * @return String|Null
4583 public function getNotificationTimestamp( $user = null ) {
4584 global $wgUser, $wgShowUpdatedMarker;
4585 // Assume current user if none given
4589 // Check cache first
4590 $uid = $user->getId();
4591 // avoid isset here, as it'll return false for null entries
4592 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4593 return $this->mNotificationTimestamp
[$uid];
4595 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4596 return $this->mNotificationTimestamp
[$uid] = false;
4598 // Don't cache too much!
4599 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4600 $this->mNotificationTimestamp
= array();
4602 $dbr = wfGetDB( DB_SLAVE
);
4603 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4604 'wl_notificationtimestamp',
4606 'wl_user' => $user->getId(),
4607 'wl_namespace' => $this->getNamespace(),
4608 'wl_title' => $this->getDBkey(),
4612 return $this->mNotificationTimestamp
[$uid];
4616 * Generate strings used for xml 'id' names in monobook tabs
4618 * @param string $prepend defaults to 'nstab-'
4619 * @return String XML 'id' name
4621 public function getNamespaceKey( $prepend = 'nstab-' ) {
4623 // Gets the subject namespace if this title
4624 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4625 // Checks if canonical namespace name exists for namespace
4626 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4627 // Uses canonical namespace name
4628 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4630 // Uses text of namespace
4631 $namespaceKey = $this->getSubjectNsText();
4633 // Makes namespace key lowercase
4634 $namespaceKey = $wgContLang->lc( $namespaceKey );
4636 if ( $namespaceKey == '' ) {
4637 $namespaceKey = 'main';
4639 // Changes file to image for backwards compatibility
4640 if ( $namespaceKey == 'file' ) {
4641 $namespaceKey = 'image';
4643 return $prepend . $namespaceKey;
4647 * Get all extant redirects to this Title
4649 * @param int|Null $ns Single namespace to consider; NULL to consider all namespaces
4650 * @return Array of Title redirects to this title
4652 public function getRedirectsHere( $ns = null ) {
4655 $dbr = wfGetDB( DB_SLAVE
);
4657 'rd_namespace' => $this->getNamespace(),
4658 'rd_title' => $this->getDBkey(),
4661 if ( $this->isExternal() ) {
4662 $where['rd_interwiki'] = $this->getInterwiki();
4664 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4666 if ( !is_null( $ns ) ) {
4667 $where['page_namespace'] = $ns;
4670 $res = $dbr->select(
4671 array( 'redirect', 'page' ),
4672 array( 'page_namespace', 'page_title' ),
4677 foreach ( $res as $row ) {
4678 $redirs[] = self
::newFromRow( $row );
4684 * Check if this Title is a valid redirect target
4688 public function isValidRedirectTarget() {
4689 global $wgInvalidRedirectTargets;
4691 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4692 if ( $this->isSpecial( 'Userlogout' ) ) {
4696 foreach ( $wgInvalidRedirectTargets as $target ) {
4697 if ( $this->isSpecial( $target ) ) {
4706 * Get a backlink cache object
4708 * @return BacklinkCache
4710 public function getBacklinkCache() {
4711 return BacklinkCache
::get( $this );
4715 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4719 public function canUseNoindex() {
4720 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4722 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4723 ?
$wgContentNamespaces
4724 : $wgExemptFromUserRobotsControl;
4726 return !in_array( $this->mNamespace
, $bannedNamespaces );
4731 * Returns the raw sort key to be used for categories, with the specified
4732 * prefix. This will be fed to Collation::getSortKey() to get a
4733 * binary sortkey that can be used for actual sorting.
4735 * @param string $prefix The prefix to be used, specified using
4736 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4740 public function getCategorySortkey( $prefix = '' ) {
4741 $unprefixed = $this->getText();
4743 // Anything that uses this hook should only depend
4744 // on the Title object passed in, and should probably
4745 // tell the users to run updateCollations.php --force
4746 // in order to re-sort existing category relations.
4747 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4748 if ( $prefix !== '' ) {
4749 # Separate with a line feed, so the unprefixed part is only used as
4750 # a tiebreaker when two pages have the exact same prefix.
4751 # In UCA, tab is the only character that can sort above LF
4752 # so we strip both of them from the original prefix.
4753 $prefix = strtr( $prefix, "\n\t", ' ' );
4754 return "$prefix\n$unprefixed";
4760 * Get the language in which the content of this page is written in
4761 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4762 * e.g. $wgLang (such as special pages, which are in the user language).
4767 public function getPageLanguage() {
4769 if ( $this->isSpecialPage() ) {
4770 // special pages are in the user language
4774 //TODO: use the LinkCache to cache this! Note that this may depend on user settings, so the cache should be only per-request.
4775 //NOTE: ContentHandler::getPageLanguage() may need to load the content to determine the page language!
4776 $contentHandler = ContentHandler
::getForTitle( $this );
4777 $pageLang = $contentHandler->getPageLanguage( $this );
4779 return wfGetLangObj( $pageLang );
4783 * Get the language in which the content of this page is written when
4784 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4785 * e.g. $wgLang (such as special pages, which are in the user language).
4790 public function getPageViewLanguage() {
4793 if ( $this->isSpecialPage() ) {
4794 // If the user chooses a variant, the content is actually
4795 // in a language whose code is the variant code.
4796 $variant = $wgLang->getPreferredVariant();
4797 if ( $wgLang->getCode() !== $variant ) {
4798 return Language
::factory( $variant );
4804 //NOTE: can't be cached persistently, depends on user settings
4805 //NOTE: ContentHandler::getPageViewLanguage() may need to load the content to determine the page language!
4806 $contentHandler = ContentHandler
::getForTitle( $this );
4807 $pageLang = $contentHandler->getPageViewLanguage( $this );
4812 * Get a list of rendered edit notices for this page.
4814 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4815 * they will already be wrapped in paragraphs.
4820 public function getEditNotices() {
4823 # Optional notices on a per-namespace and per-page basis
4824 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4825 $editnotice_ns_message = wfMessage( $editnotice_ns );
4826 if ( $editnotice_ns_message->exists() ) {
4827 $notices[$editnotice_ns] = $editnotice_ns_message->parseAsBlock();
4829 if ( MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
4830 $parts = explode( '/', $this->getDBkey() );
4831 $editnotice_base = $editnotice_ns;
4832 while ( count( $parts ) > 0 ) {
4833 $editnotice_base .= '-' . array_shift( $parts );
4834 $editnotice_base_msg = wfMessage( $editnotice_base );
4835 if ( $editnotice_base_msg->exists() ) {
4836 $notices[$editnotice_base] = $editnotice_base_msg->parseAsBlock();
4840 # Even if there are no subpages in namespace, we still don't want / in MW ns.
4841 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
4842 $editnoticeMsg = wfMessage( $editnoticeText );
4843 if ( $editnoticeMsg->exists() ) {
4844 $notices[$editnoticeText] = $editnoticeMsg->parseAsBlock();