5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Represents a title within MediaWiki.
25 * Optionally may contain an interwiki designation or namespace.
26 * @note This class can fetch various kinds of data from the database;
27 * however, it does so inefficiently.
29 * @internal documentation reviewed 15 Mar 2010
32 /** @name Static cache variables */
34 static private $titleCache = array();
38 * Title::newFromText maintains a cache to avoid expensive re-normalization of
39 * commonly used titles. On a batch operation this can become a memory leak
40 * if not bounded. After hitting this many titles reset the cache.
42 const CACHE_MAX
= 1000;
45 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
46 * to use the master DB
48 const GAID_FOR_UPDATE
= 1;
51 * @name Private member variables
52 * Please use the accessor functions instead.
57 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
58 var $mUrlform = ''; // /< URL-encoded form of the main part
59 var $mDbkeyform = ''; // /< Main part with underscores
60 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
61 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
62 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
63 var $mFragment; // /< Title fragment (i.e. the bit after the #)
64 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
65 var $mLatestID = false; // /< ID of most recent revision
66 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
67 var $mOldRestrictions = false;
68 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
69 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
70 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
71 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
72 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
73 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
74 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
75 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
76 # Don't change the following default, NS_MAIN is hardcoded in several
77 # places. See bug 696.
78 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
79 # Zero except in {{transclusion}} tags
80 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
81 var $mLength = -1; // /< The page length, 0 for special pages
82 var $mRedirect = null; // /< Is the article at this title a redirect?
83 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
84 var $mBacklinkCache = null; // /< Cache of links to this title
91 /*protected*/ function __construct() { }
94 * Create a new Title from a prefixed DB key
96 * @param $key String the database key, which has underscores
97 * instead of spaces, possibly including namespace and
99 * @return Title, or NULL on an error
101 public static function newFromDBkey( $key ) {
103 $t->mDbkeyform
= $key;
104 if ( $t->secureAndSplit() ) {
112 * Create a new Title from text, such as what one would find in a link. De-
113 * codes any HTML entities in the text.
115 * @param $text String the link text; spaces, prefixes, and an
116 * initial ':' indicating the main namespace are accepted.
117 * @param $defaultNamespace Int the namespace to use if none is speci-
118 * fied by a prefix. If you want to force a specific namespace even if
119 * $text might begin with a namespace prefix, use makeTitle() or
121 * @return Title, or null on an error.
123 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
124 if ( is_object( $text ) ) {
125 throw new MWException( 'Title::newFromText given an object' );
129 * Wiki pages often contain multiple links to the same page.
130 * Title normalization and parsing can become expensive on
131 * pages with many links, so we can save a little time by
134 * In theory these are value objects and won't get changed...
136 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
137 return Title
::$titleCache[$text];
140 # Convert things like é ā or 〗 into normalized (bug 14952) text
141 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
144 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
145 $t->mDefaultNamespace
= $defaultNamespace;
147 static $cachedcount = 0 ;
148 if ( $t->secureAndSplit() ) {
149 if ( $defaultNamespace == NS_MAIN
) {
150 if ( $cachedcount >= self
::CACHE_MAX
) {
151 # Avoid memory leaks on mass operations...
152 Title
::$titleCache = array();
156 Title
::$titleCache[$text] =& $t;
166 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
168 * Example of wrong and broken code:
169 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
171 * Example of right code:
172 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
174 * Create a new Title from URL-encoded text. Ensures that
175 * the given title's length does not exceed the maximum.
177 * @param $url String the title, as might be taken from a URL
178 * @return Title the new object, or NULL on an error
180 public static function newFromURL( $url ) {
181 global $wgLegalTitleChars;
184 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
185 # but some URLs used it as a space replacement and they still come
186 # from some external search tools.
187 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
188 $url = str_replace( '+', ' ', $url );
191 $t->mDbkeyform
= str_replace( ' ', '_', $url );
192 if ( $t->secureAndSplit() ) {
200 * Create a new Title from an article ID
202 * @param $id Int the page_id corresponding to the Title to create
203 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
204 * @return Title the new object, or NULL on an error
206 public static function newFromID( $id, $flags = 0 ) {
207 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
208 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
209 if ( $row !== false ) {
210 $title = Title
::newFromRow( $row );
218 * Make an array of titles from an array of IDs
220 * @param $ids Array of Int Array of IDs
221 * @return Array of Titles
223 public static function newFromIDs( $ids ) {
224 if ( !count( $ids ) ) {
227 $dbr = wfGetDB( DB_SLAVE
);
232 'page_namespace', 'page_title', 'page_id',
233 'page_len', 'page_is_redirect', 'page_latest',
235 array( 'page_id' => $ids ),
240 foreach ( $res as $row ) {
241 $titles[] = Title
::newFromRow( $row );
247 * Make a Title object from a DB row
249 * @param $row Object database row (needs at least page_title,page_namespace)
250 * @return Title corresponding Title
252 public static function newFromRow( $row ) {
253 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
254 $t->loadFromRow( $row );
259 * Load Title object fields from a DB row.
260 * If false is given, the title will be treated as non-existing.
262 * @param $row Object|false database row
265 public function loadFromRow( $row ) {
266 if ( $row ) { // page found
267 if ( isset( $row->page_id
) )
268 $this->mArticleID
= (int)$row->page_id
;
269 if ( isset( $row->page_len
) )
270 $this->mLength
= (int)$row->page_len
;
271 if ( isset( $row->page_is_redirect
) )
272 $this->mRedirect
= (bool)$row->page_is_redirect
;
273 if ( isset( $row->page_latest
) )
274 $this->mLatestID
= (int)$row->page_latest
;
275 } else { // page not found
276 $this->mArticleID
= 0;
278 $this->mRedirect
= false;
279 $this->mLatestID
= 0;
284 * Create a new Title from a namespace index and a DB key.
285 * It's assumed that $ns and $title are *valid*, for instance when
286 * they came directly from the database or a special page name.
287 * For convenience, spaces are converted to underscores so that
288 * eg user_text fields can be used directly.
290 * @param $ns Int the namespace of the article
291 * @param $title String the unprefixed database key form
292 * @param $fragment String the link fragment (after the "#")
293 * @param $interwiki String the interwiki prefix
294 * @return Title the new object
296 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
298 $t->mInterwiki
= $interwiki;
299 $t->mFragment
= $fragment;
300 $t->mNamespace
= $ns = intval( $ns );
301 $t->mDbkeyform
= str_replace( ' ', '_', $title );
302 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
303 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
304 $t->mTextform
= str_replace( '_', ' ', $title );
309 * Create a new Title from a namespace index and a DB key.
310 * The parameters will be checked for validity, which is a bit slower
311 * than makeTitle() but safer for user-provided data.
313 * @param $ns Int the namespace of the article
314 * @param $title String database key form
315 * @param $fragment String the link fragment (after the "#")
316 * @param $interwiki String interwiki prefix
317 * @return Title the new object, or NULL on an error
319 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
321 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
322 if ( $t->secureAndSplit() ) {
330 * Create a new Title for the Main Page
332 * @return Title the new object
334 public static function newMainPage() {
335 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
336 // Don't give fatal errors if the message is broken
338 $title = Title
::newFromText( 'Main Page' );
344 * Extract a redirect destination from a string and return the
345 * Title, or null if the text doesn't contain a valid redirect
346 * This will only return the very next target, useful for
347 * the redirect table and other checks that don't need full recursion
349 * @param $text String: Text with possible redirect
350 * @return Title: The corresponding Title
352 public static function newFromRedirect( $text ) {
353 return self
::newFromRedirectInternal( $text );
357 * Extract a redirect destination from a string and return the
358 * Title, or null if the text doesn't contain a valid redirect
359 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
360 * in order to provide (hopefully) the Title of the final destination instead of another redirect
362 * @param $text String Text with possible redirect
365 public static function newFromRedirectRecurse( $text ) {
366 $titles = self
::newFromRedirectArray( $text );
367 return $titles ?
array_pop( $titles ) : null;
371 * Extract a redirect destination from a string and return an
372 * array of Titles, or null if the text doesn't contain a valid redirect
373 * The last element in the array is the final destination after all redirects
374 * have been resolved (up to $wgMaxRedirects times)
376 * @param $text String Text with possible redirect
377 * @return Array of Titles, with the destination last
379 public static function newFromRedirectArray( $text ) {
380 global $wgMaxRedirects;
381 $title = self
::newFromRedirectInternal( $text );
382 if ( is_null( $title ) ) {
385 // recursive check to follow double redirects
386 $recurse = $wgMaxRedirects;
387 $titles = array( $title );
388 while ( --$recurse > 0 ) {
389 if ( $title->isRedirect() ) {
390 $page = WikiPage
::factory( $title );
391 $newtitle = $page->getRedirectTarget();
395 // Redirects to some special pages are not permitted
396 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
397 // the new title passes the checks, so make that our current title so that further recursion can be checked
399 $titles[] = $newtitle;
408 * Really extract the redirect destination
409 * Do not call this function directly, use one of the newFromRedirect* functions above
411 * @param $text String Text with possible redirect
414 protected static function newFromRedirectInternal( $text ) {
415 global $wgMaxRedirects;
416 if ( $wgMaxRedirects < 1 ) {
417 //redirects are disabled, so quit early
420 $redir = MagicWord
::get( 'redirect' );
421 $text = trim( $text );
422 if ( $redir->matchStartAndRemove( $text ) ) {
423 // Extract the first link and see if it's usable
424 // Ensure that it really does come directly after #REDIRECT
425 // Some older redirects included a colon, so don't freak about that!
427 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
428 // Strip preceding colon used to "escape" categories, etc.
429 // and URL-decode links
430 if ( strpos( $m[1], '%' ) !== false ) {
431 // Match behavior of inline link parsing here;
432 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
434 $title = Title
::newFromText( $m[1] );
435 // If the title is a redirect to bad special pages or is invalid, return null
436 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
445 # ----------------------------------------------------------------------------
447 # ----------------------------------------------------------------------------
450 * Get the prefixed DB key associated with an ID
452 * @param $id Int the page_id of the article
453 * @return Title an object representing the article, or NULL if no such article was found
455 public static function nameOf( $id ) {
456 $dbr = wfGetDB( DB_SLAVE
);
458 $s = $dbr->selectRow(
460 array( 'page_namespace', 'page_title' ),
461 array( 'page_id' => $id ),
464 if ( $s === false ) {
468 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
473 * Get a regex character class describing the legal characters in a link
475 * @return String the list of characters, not delimited
477 public static function legalChars() {
478 global $wgLegalTitleChars;
479 return $wgLegalTitleChars;
483 * Get a string representation of a title suitable for
484 * including in a search index
486 * @param $ns Int a namespace index
487 * @param $title String text-form main part
488 * @return String a stripped-down title string ready for the search index
490 public static function indexTitle( $ns, $title ) {
493 $lc = SearchEngine
::legalSearchChars() . '&#;';
494 $t = $wgContLang->normalizeForSearch( $title );
495 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
496 $t = $wgContLang->lc( $t );
499 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
500 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
502 $t = preg_replace( "/\\s+/", ' ', $t );
504 if ( $ns == NS_FILE
) {
505 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
511 * Make a prefixed DB key from a DB key and a namespace index
513 * @param $ns Int numerical representation of the namespace
514 * @param $title String the DB key form the title
515 * @param $fragment String The link fragment (after the "#")
516 * @param $interwiki String The interwiki prefix
517 * @return String the prefixed form of the title
519 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
522 $namespace = $wgContLang->getNsText( $ns );
523 $name = $namespace == '' ?
$title : "$namespace:$title";
524 if ( strval( $interwiki ) != '' ) {
525 $name = "$interwiki:$name";
527 if ( strval( $fragment ) != '' ) {
528 $name .= '#' . $fragment;
534 * Determine whether the object refers to a page within
537 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
539 public function isLocal() {
540 if ( $this->mInterwiki
!= '' ) {
541 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
548 * Determine whether the object refers to a page within
549 * this project and is transcludable.
551 * @return Bool TRUE if this is transcludable
553 public function isTrans() {
554 if ( $this->mInterwiki
== '' ) {
558 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
562 * Returns the DB name of the distant wiki which owns the object.
564 * @return String the DB name
566 public function getTransWikiID() {
567 if ( $this->mInterwiki
== '' ) {
571 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
575 * Escape a text fragment, say from a link, for a URL
577 * @param $fragment string containing a URL or link fragment (after the "#")
578 * @return String: escaped string
580 static function escapeFragmentForURL( $fragment ) {
581 # Note that we don't urlencode the fragment. urlencoded Unicode
582 # fragments appear not to work in IE (at least up to 7) or in at least
583 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
584 # to care if they aren't encoded.
585 return Sanitizer
::escapeId( $fragment, 'noninitial' );
588 # ----------------------------------------------------------------------------
590 # ----------------------------------------------------------------------------
592 /** Simple accessors */
594 * Get the text form (spaces not underscores) of the main part
596 * @return String Main part of the title
598 public function getText() { return $this->mTextform
; }
601 * Get the URL-encoded form of the main part
603 * @return String Main part of the title, URL-encoded
605 public function getPartialURL() { return $this->mUrlform
; }
608 * Get the main part with underscores
610 * @return String: Main part of the title, with underscores
612 public function getDBkey() { return $this->mDbkeyform
; }
615 * Get the namespace index, i.e. one of the NS_xxxx constants.
617 * @return Integer: Namespace index
619 public function getNamespace() { return $this->mNamespace
; }
622 * Get the namespace text
624 * @return String: Namespace text
626 public function getNsText() {
629 if ( $this->mInterwiki
!= '' ) {
630 // This probably shouldn't even happen. ohh man, oh yuck.
631 // But for interwiki transclusion it sometimes does.
632 // Shit. Shit shit shit.
634 // Use the canonical namespaces if possible to try to
635 // resolve a foreign namespace.
636 if ( MWNamespace
::exists( $this->mNamespace
) ) {
637 return MWNamespace
::getCanonicalName( $this->mNamespace
);
641 // Strip off subpages
642 $pagename = $this->getText();
643 if ( strpos( $pagename, '/' ) !== false ) {
644 list( $username , ) = explode( '/', $pagename, 2 );
646 $username = $pagename;
649 if ( $wgContLang->needsGenderDistinction() &&
650 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
651 $gender = GenderCache
::singleton()->getGenderOf( $username, __METHOD__
);
652 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
655 return $wgContLang->getNsText( $this->mNamespace
);
659 * Get the DB key with the initial letter case as specified by the user
661 * @return String DB key
663 function getUserCaseDBKey() {
664 return $this->mUserCaseDBKey
;
668 * Get the namespace text of the subject (rather than talk) page
670 * @return String Namespace text
672 public function getSubjectNsText() {
674 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
678 * Get the namespace text of the talk page
680 * @return String Namespace text
682 public function getTalkNsText() {
684 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
688 * Could this title have a corresponding talk page?
690 * @return Bool TRUE or FALSE
692 public function canTalk() {
693 return( MWNamespace
::canTalk( $this->mNamespace
) );
697 * Get the interwiki prefix (or null string)
699 * @return String Interwiki prefix
701 public function getInterwiki() { return $this->mInterwiki
; }
704 * Get the Title fragment (i.e.\ the bit after the #) in text form
706 * @return String Title fragment
708 public function getFragment() { return $this->mFragment
; }
711 * Get the fragment in URL form, including the "#" character if there is one
712 * @return String Fragment in URL form
714 public function getFragmentForURL() {
715 if ( $this->mFragment
== '' ) {
718 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
723 * Get the default namespace index, for when there is no namespace
725 * @return Int Default namespace index
727 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
730 * Get title for search index
732 * @return String a stripped-down title string ready for the
735 public function getIndexTitle() {
736 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
740 * Get the prefixed database key form
742 * @return String the prefixed title, with underscores and
743 * any interwiki and namespace prefixes
745 public function getPrefixedDBkey() {
746 $s = $this->prefix( $this->mDbkeyform
);
747 $s = str_replace( ' ', '_', $s );
752 * Get the prefixed title with spaces.
753 * This is the form usually used for display
755 * @return String the prefixed title, with spaces
757 public function getPrefixedText() {
758 // @todo FIXME: Bad usage of empty() ?
759 if ( empty( $this->mPrefixedText
) ) {
760 $s = $this->prefix( $this->mTextform
);
761 $s = str_replace( '_', ' ', $s );
762 $this->mPrefixedText
= $s;
764 return $this->mPrefixedText
;
769 * Get the prefixed title with spaces, plus any fragment
770 * (part beginning with '#')
772 * @return String the prefixed title, with spaces and the fragment, including '#'
774 public function getFullText() {
775 $text = $this->getPrefixedText();
776 if ( $this->mFragment
!= '' ) {
777 $text .= '#' . $this->mFragment
;
783 * Get the base page name, i.e. the leftmost part before any slashes
785 * @return String Base name
787 public function getBaseText() {
788 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
789 return $this->getText();
792 $parts = explode( '/', $this->getText() );
793 # Don't discard the real title if there's no subpage involved
794 if ( count( $parts ) > 1 ) {
795 unset( $parts[count( $parts ) - 1] );
797 return implode( '/', $parts );
801 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
803 * @return String Subpage name
805 public function getSubpageText() {
806 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
807 return( $this->mTextform
);
809 $parts = explode( '/', $this->mTextform
);
810 return( $parts[count( $parts ) - 1] );
814 * Get a URL-encoded form of the subpage text
816 * @return String URL-encoded subpage name
818 public function getSubpageUrlForm() {
819 $text = $this->getSubpageText();
820 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
825 * Get a URL-encoded title (not an actual URL) including interwiki
827 * @return String the URL-encoded form
829 public function getPrefixedURL() {
830 $s = $this->prefix( $this->mDbkeyform
);
831 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
836 * Get a real URL referring to this title, with interwiki link and
839 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
840 * links. Can be specified as an associative array as well, e.g.,
841 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
842 * @param $variant String language variant of url (for sr, zh..)
843 * @return String the URL
845 public function getFullURL( $query = '', $variant = false ) {
846 # Hand off all the decisions on urls to getLocalURL
847 $url = $this->getLocalURL( $query, $variant );
849 # Expand the url to make it a full url. Note that getLocalURL has the
850 # potential to output full urls for a variety of reasons, so we use
851 # wfExpandUrl instead of simply prepending $wgServer
852 $url = wfExpandUrl( $url, PROTO_RELATIVE
);
854 # Finally, add the fragment.
855 $url .= $this->getFragmentForURL();
857 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query, $variant ) );
862 * Get a URL with no fragment or server name. If this page is generated
863 * with action=render, $wgServer is prepended.
865 * @param $query Mixed: an optional query string; if not specified,
866 * $wgArticlePath will be used. Can be specified as an associative array
867 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
869 * @param $variant String language variant of url (for sr, zh..)
870 * @return String the URL
872 public function getLocalURL( $query = '', $variant = false ) {
873 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
874 global $wgVariantArticlePath;
876 if ( is_array( $query ) ) {
877 $query = wfArrayToCGI( $query );
880 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
882 $namespace = $this->getNsText();
883 if ( $namespace != '' ) {
884 # Can this actually happen? Interwikis shouldn't be parsed.
885 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
888 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
889 $url = wfAppendQuery( $url, $query );
891 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
892 if ( $query == '' ) {
893 if ( $variant != false && $this->getPageLanguage()->hasVariants() ) {
894 if ( !$wgVariantArticlePath ) {
895 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
897 $variantArticlePath = $wgVariantArticlePath;
899 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
900 $url = str_replace( '$1', $dbkey, $url );
902 $url = str_replace( '$1', $dbkey, $wgArticlePath );
903 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
906 global $wgActionPaths;
909 if ( !empty( $wgActionPaths ) &&
910 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
912 $action = urldecode( $matches[2] );
913 if ( isset( $wgActionPaths[$action] ) ) {
914 $query = $matches[1];
915 if ( isset( $matches[4] ) ) {
916 $query .= $matches[4];
918 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
919 if ( $query != '' ) {
920 $url = wfAppendQuery( $url, $query );
925 if ( $url === false ) {
926 if ( $query == '-' ) {
929 $url = "{$wgScript}?title={$dbkey}&{$query}";
933 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query, $variant ) );
935 // @todo FIXME: This causes breakage in various places when we
936 // actually expected a local URL and end up with dupe prefixes.
937 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
938 $url = $wgServer . $url;
941 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query, $variant ) );
946 * Get a URL that's the simplest URL that will be valid to link, locally,
947 * to the current Title. It includes the fragment, but does not include
948 * the server unless action=render is used (or the link is external). If
949 * there's a fragment but the prefixed text is empty, we just return a link
952 * The result obviously should not be URL-escaped, but does need to be
953 * HTML-escaped if it's being output in HTML.
955 * @param $query Array of Strings An associative array of key => value pairs for the
956 * query string. Keys and values will be escaped.
957 * @param $variant String language variant of URL (for sr, zh..). Ignored
958 * for external links. Default is "false" (same variant as current page,
959 * for anonymous users).
960 * @return String the URL
962 public function getLinkURL( $query = array(), $variant = false ) {
963 wfProfileIn( __METHOD__
);
964 if ( $this->isExternal() ) {
965 $ret = $this->getFullURL( $query );
966 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
967 $ret = $this->getFragmentForURL();
969 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
971 wfProfileOut( __METHOD__
);
976 * Get an HTML-escaped version of the URL form, suitable for
977 * using in a link, without a server name or fragment
979 * @param $query String an optional query string
980 * @return String the URL
982 public function escapeLocalURL( $query = '' ) {
983 return htmlspecialchars( $this->getLocalURL( $query ) );
987 * Get an HTML-escaped version of the URL form, suitable for
988 * using in a link, including the server name and fragment
990 * @param $query String an optional query string
991 * @return String the URL
993 public function escapeFullURL( $query = '' ) {
994 return htmlspecialchars( $this->getFullURL( $query ) );
998 * HTML-escaped version of getCanonicalURL()
1001 public function escapeCanonicalURL( $query = '', $variant = false ) {
1002 return htmlspecialchars( $this->getCanonicalURL( $query, $variant ) );
1006 * Get the URL form for an internal link.
1007 * - Used in various Squid-related code, in case we have a different
1008 * internal hostname for the server from the exposed one.
1010 * This uses $wgInternalServer to qualify the path, or $wgServer
1011 * if $wgInternalServer is not set. If the server variable used is
1012 * protocol-relative, the URL will be expanded to http://
1014 * @param $query String an optional query string
1015 * @param $variant String language variant of url (for sr, zh..)
1016 * @return String the URL
1018 public function getInternalURL( $query = '', $variant = false ) {
1019 global $wgInternalServer, $wgServer;
1020 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1021 $url = wfExpandUrl( $server . $this->getLocalURL( $query, $variant ), PROTO_HTTP
);
1022 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query, $variant ) );
1027 * Get the URL for a canonical link, for use in things like IRC and
1028 * e-mail notifications. Uses $wgCanonicalServer and the
1029 * GetCanonicalURL hook.
1031 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1033 * @param $query string An optional query string
1034 * @param $variant string Language variant of URL (for sr, zh, ...)
1035 * @return string The URL
1038 public function getCanonicalURL( $query = '', $variant = false ) {
1039 $url = wfExpandUrl( $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1040 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query, $variant ) );
1045 * Get the edit URL for this Title
1047 * @return String the URL, or a null string if this is an
1050 public function getEditURL() {
1051 if ( $this->mInterwiki
!= '' ) {
1054 $s = $this->getLocalURL( 'action=edit' );
1060 * Get the HTML-escaped displayable text form.
1061 * Used for the title field in <a> tags.
1063 * @return String the text, including any prefixes
1065 public function getEscapedText() {
1066 return htmlspecialchars( $this->getPrefixedText() );
1070 * Is this Title interwiki?
1074 public function isExternal() {
1075 return ( $this->mInterwiki
!= '' );
1079 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1081 * @param $action String Action to check (default: edit)
1084 public function isSemiProtected( $action = 'edit' ) {
1085 if ( $this->exists() ) {
1086 $restrictions = $this->getRestrictions( $action );
1087 if ( count( $restrictions ) > 0 ) {
1088 foreach ( $restrictions as $restriction ) {
1089 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1099 # If it doesn't exist, it can't be protected
1105 * Does the title correspond to a protected article?
1107 * @param $action String the action the page is protected from,
1108 * by default checks all actions.
1111 public function isProtected( $action = '' ) {
1112 global $wgRestrictionLevels;
1114 $restrictionTypes = $this->getRestrictionTypes();
1116 # Special pages have inherent protection
1117 if( $this->isSpecialPage() ) {
1121 # Check regular protection levels
1122 foreach ( $restrictionTypes as $type ) {
1123 if ( $action == $type ||
$action == '' ) {
1124 $r = $this->getRestrictions( $type );
1125 foreach ( $wgRestrictionLevels as $level ) {
1126 if ( in_array( $level, $r ) && $level != '' ) {
1137 * Determines if $user is unable to edit this page because it has been protected
1138 * by $wgNamespaceProtection.
1140 * @param $user User object to check permissions
1143 public function isNamespaceProtected( User
$user ) {
1144 global $wgNamespaceProtection;
1146 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
1147 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
1148 if ( $right != '' && !$user->isAllowed( $right ) ) {
1157 * Is this a conversion table for the LanguageConverter?
1161 public function isConversionTable() {
1163 $this->getNamespace() == NS_MEDIAWIKI
&&
1164 strpos( $this->getText(), 'Conversiontable' ) !== false
1174 * Is $wgUser watching this page?
1178 public function userIsWatching() {
1181 if ( is_null( $this->mWatched
) ) {
1182 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1183 $this->mWatched
= false;
1185 $this->mWatched
= $wgUser->isWatched( $this );
1188 return $this->mWatched
;
1192 * Can $wgUser read this page?
1194 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1196 * @todo fold these checks into userCan()
1198 public function userCanRead() {
1199 return $this->userCan( 'read' );
1203 * Can $wgUser perform $action on this page?
1204 * This skips potentially expensive cascading permission checks
1205 * as well as avoids expensive error formatting
1207 * Suitable for use for nonessential UI controls in common cases, but
1208 * _not_ for functional access control.
1210 * May provide false positives, but should never provide a false negative.
1212 * @param $action String action that permission needs to be checked for
1213 * @param $user User to check (since 1.19)
1216 public function quickUserCan( $action, $user = null ) {
1217 return $this->userCan( $action, $user, false );
1221 * Can $wgUser perform $action on this page?
1223 * @param $action String action that permission needs to be checked for
1224 * @param $user User to check (since 1.19)
1225 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1228 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1229 if ( !$user instanceof User
) {
1233 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1237 * Can $user perform $action on this page?
1239 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1241 * @param $action String action that permission needs to be checked for
1242 * @param $user User to check
1243 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries by
1244 * skipping checks for cascading protections and user blocks.
1245 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1246 * @return Array of arguments to wfMsg to explain permissions problems.
1248 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1249 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1251 // Remove the errors being ignored.
1252 foreach ( $errors as $index => $error ) {
1253 $error_key = is_array( $error ) ?
$error[0] : $error;
1255 if ( in_array( $error_key, $ignoreErrors ) ) {
1256 unset( $errors[$index] );
1264 * Permissions checks that fail most often, and which are easiest to test.
1266 * @param $action String the action to check
1267 * @param $user User user to check
1268 * @param $errors Array list of current errors
1269 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1270 * @param $short Boolean short circuit on first error
1272 * @return Array list of errors
1274 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1275 $ns = $this->getNamespace();
1277 if ( $action == 'create' ) {
1278 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk', $ns ) ) ||
1279 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage', $ns ) ) ) {
1280 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1282 } elseif ( $action == 'move' ) {
1283 if ( !$user->isAllowed( 'move-rootuserpages', $ns )
1284 && $ns == NS_USER
&& !$this->isSubpage() ) {
1285 // Show user page-specific message only if the user can move other pages
1286 $errors[] = array( 'cant-move-user-page' );
1289 // Check if user is allowed to move files if it's a file
1290 if ( $ns == NS_FILE
&& !$user->isAllowed( 'movefile', $ns ) ) {
1291 $errors[] = array( 'movenotallowedfile' );
1294 if ( !$user->isAllowed( 'move', $ns) ) {
1295 // User can't move anything
1297 $userCanMove = in_array( 'move', User
::getGroupPermissions(
1298 array( 'user' ), $ns ), true );
1299 $autoconfirmedCanMove = in_array( 'move', User
::getGroupPermissions(
1300 array( 'autoconfirmed' ), $ns ), true );
1302 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1303 // custom message if logged-in users without any special rights can move
1304 $errors[] = array( 'movenologintext' );
1306 $errors[] = array( 'movenotallowed' );
1309 } elseif ( $action == 'move-target' ) {
1310 if ( !$user->isAllowed( 'move', $ns ) ) {
1311 // User can't move anything
1312 $errors[] = array( 'movenotallowed' );
1313 } elseif ( !$user->isAllowed( 'move-rootuserpages', $ns )
1314 && $ns == NS_USER
&& !$this->isSubpage() ) {
1315 // Show user page-specific message only if the user can move other pages
1316 $errors[] = array( 'cant-move-to-user-page' );
1318 } elseif ( !$user->isAllowed( $action, $ns ) ) {
1319 $errors[] = $this->missingPermissionError( $action, $short );
1326 * Add the resulting error code to the errors array
1328 * @param $errors Array list of current errors
1329 * @param $result Mixed result of errors
1331 * @return Array list of errors
1333 private function resultToError( $errors, $result ) {
1334 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1335 // A single array representing an error
1336 $errors[] = $result;
1337 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1338 // A nested array representing multiple errors
1339 $errors = array_merge( $errors, $result );
1340 } elseif ( $result !== '' && is_string( $result ) ) {
1341 // A string representing a message-id
1342 $errors[] = array( $result );
1343 } elseif ( $result === false ) {
1344 // a generic "We don't want them to do that"
1345 $errors[] = array( 'badaccess-group0' );
1351 * Check various permission hooks
1353 * @param $action String the action to check
1354 * @param $user User user to check
1355 * @param $errors Array list of current errors
1356 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1357 * @param $short Boolean short circuit on first error
1359 * @return Array list of errors
1361 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1362 // Use getUserPermissionsErrors instead
1364 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1365 return $result ?
array() : array( array( 'badaccess-group0' ) );
1367 // Check getUserPermissionsErrors hook
1368 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1369 $errors = $this->resultToError( $errors, $result );
1371 // Check getUserPermissionsErrorsExpensive hook
1372 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1373 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1374 $errors = $this->resultToError( $errors, $result );
1381 * Check permissions on special pages & namespaces
1383 * @param $action String the action to check
1384 * @param $user User user to check
1385 * @param $errors Array list of current errors
1386 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1387 * @param $short Boolean short circuit on first error
1389 * @return Array list of errors
1391 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1392 # Only 'createaccount' and 'execute' can be performed on
1393 # special pages, which don't actually exist in the DB.
1394 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1395 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1396 $errors[] = array( 'ns-specialprotected' );
1399 # Check $wgNamespaceProtection for restricted namespaces
1400 if ( $this->isNamespaceProtected( $user ) ) {
1401 $ns = $this->mNamespace
== NS_MAIN ?
1402 wfMsg( 'nstab-main' ) : $this->getNsText();
1403 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1404 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1411 * Check CSS/JS sub-page permissions
1413 * @param $action String the action to check
1414 * @param $user User user to check
1415 * @param $errors Array list of current errors
1416 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1417 * @param $short Boolean short circuit on first error
1419 * @return Array list of errors
1421 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1422 # Protect css/js subpages of user pages
1423 # XXX: this might be better using restrictions
1424 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1425 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1426 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1427 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1428 $errors[] = array( 'customcssprotected' );
1429 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1430 $errors[] = array( 'customjsprotected' );
1438 * Check against page_restrictions table requirements on this
1439 * page. The user must possess all required rights for this
1442 * @param $action String the action to check
1443 * @param $user User user to check
1444 * @param $errors Array list of current errors
1445 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1446 * @param $short Boolean short circuit on first error
1448 * @return Array list of errors
1450 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1451 foreach ( $this->getRestrictions( $action ) as $right ) {
1452 // Backwards compatibility, rewrite sysop -> protect
1453 if ( $right == 'sysop' ) {
1456 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace
) ) {
1457 // Users with 'editprotected' permission can edit protected pages
1458 // without cascading option turned on.
1459 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected', $this->mNamespace
)
1460 ||
$this->mCascadeRestriction
)
1462 $errors[] = array( 'protectedpagetext', $right );
1471 * Check restrictions on cascading pages.
1473 * @param $action String the action to check
1474 * @param $user User to check
1475 * @param $errors Array list of current errors
1476 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1477 * @param $short Boolean short circuit on first error
1479 * @return Array list of errors
1481 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1482 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1483 # We /could/ use the protection level on the source page, but it's
1484 # fairly ugly as we have to establish a precedence hierarchy for pages
1485 # included by multiple cascade-protected pages. So just restrict
1486 # it to people with 'protect' permission, as they could remove the
1487 # protection anyway.
1488 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1489 # Cascading protection depends on more than this page...
1490 # Several cascading protected pages may include this page...
1491 # Check each cascading level
1492 # This is only for protection restrictions, not for all actions
1493 if ( isset( $restrictions[$action] ) ) {
1494 foreach ( $restrictions[$action] as $right ) {
1495 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1496 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace
) ) {
1498 foreach ( $cascadingSources as $page )
1499 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1500 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1510 * Check action permissions not already checked in checkQuickPermissions
1512 * @param $action String the action to check
1513 * @param $user User to check
1514 * @param $errors Array list of current errors
1515 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1516 * @param $short Boolean short circuit on first error
1518 * @return Array list of errors
1520 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1521 if ( $action == 'protect' ) {
1522 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1523 // If they can't edit, they shouldn't protect.
1524 $errors[] = array( 'protect-cantedit' );
1526 } elseif ( $action == 'create' ) {
1527 $title_protection = $this->getTitleProtection();
1528 if( $title_protection ) {
1529 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1530 $title_protection['pt_create_perm'] = 'protect'; // B/C
1532 if( $title_protection['pt_create_perm'] == '' ||
1533 !$user->isAllowed( $title_protection['pt_create_perm'],
1534 $this->mNamespace
) ) {
1535 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1538 } elseif ( $action == 'move' ) {
1539 // Check for immobile pages
1540 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1541 // Specific message for this case
1542 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1543 } elseif ( !$this->isMovable() ) {
1544 // Less specific message for rarer cases
1545 $errors[] = array( 'immobile-source-page' );
1547 } elseif ( $action == 'move-target' ) {
1548 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1549 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1550 } elseif ( !$this->isMovable() ) {
1551 $errors[] = array( 'immobile-target-page' );
1558 * Check that the user isn't blocked from editting.
1560 * @param $action String the action to check
1561 * @param $user User to check
1562 * @param $errors Array list of current errors
1563 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1564 * @param $short Boolean short circuit on first error
1566 * @return Array list of errors
1568 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1569 // Account creation blocks handled at userlogin.
1570 // Unblocking handled in SpecialUnblock
1571 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1575 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1577 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1578 $errors[] = array( 'confirmedittext' );
1581 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1582 // Don't block the user from editing their own talk page unless they've been
1583 // explicitly blocked from that too.
1584 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1585 $block = $user->mBlock
;
1587 // This is from OutputPage::blockedPage
1588 // Copied at r23888 by werdna
1590 $id = $user->blockedBy();
1591 $reason = $user->blockedFor();
1592 if ( $reason == '' ) {
1593 $reason = wfMsg( 'blockednoreason' );
1595 $ip = $user->getRequest()->getIP();
1597 if ( is_numeric( $id ) ) {
1598 $name = User
::whoIs( $id );
1603 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1604 $blockid = $block->getId();
1605 $blockExpiry = $user->mBlock
->mExpiry
;
1606 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1607 if ( $blockExpiry == 'infinity' ) {
1608 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1610 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1613 $intended = strval( $user->mBlock
->getTarget() );
1615 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1616 $blockid, $blockExpiry, $intended, $blockTimestamp );
1623 * Check that the user is allowed to read this page.
1625 * @param $action String the action to check
1626 * @param $user User to check
1627 * @param $errors Array list of current errors
1628 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1629 * @param $short Boolean short circuit on first error
1631 * @return Array list of errors
1633 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1634 static $useShortcut = null;
1636 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1637 if ( is_null( $useShortcut ) ) {
1638 global $wgGroupPermissions, $wgRevokePermissions;
1639 $useShortcut = true;
1640 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1641 # Not a public wiki, so no shortcut
1642 $useShortcut = false;
1643 } elseif ( !empty( $wgRevokePermissions ) ) {
1645 * Iterate through each group with permissions being revoked (key not included since we don't care
1646 * what the group name is), then check if the read permission is being revoked. If it is, then
1647 * we don't use the shortcut below since the user might not be able to read, even though anon
1648 * reading is allowed.
1650 foreach ( $wgRevokePermissions as $perms ) {
1651 if ( !empty( $perms['read'] ) ) {
1652 # We might be removing the read right from the user, so no shortcut
1653 $useShortcut = false;
1660 # Shortcut for public wikis, allows skipping quite a bit of code
1661 if ( $useShortcut ) {
1665 # If the user is allowed to read pages, he is allowed to read all pages
1666 if ( $user->isAllowed( 'read', $this->mNamespace
) ) {
1670 # Always grant access to the login page.
1671 # Even anons need to be able to log in.
1672 if ( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'ChangePassword' ) ) {
1676 # Time to check the whitelist
1677 global $wgWhitelistRead;
1679 # Only to these checks is there's something to check against
1680 if ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
1681 # Check for explicit whitelisting
1682 $name = $this->getPrefixedText();
1683 $dbName = $this->getPrefixedDBKey();
1685 // Check with and without underscores
1686 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
1690 # Old settings might have the title prefixed with
1691 # a colon for main-namespace pages
1692 if ( $this->getNamespace() == NS_MAIN
) {
1693 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1698 # If it's a special page, ditch the subpage bit and check again
1699 if ( $this->isSpecialPage() ) {
1700 $name = $this->getDBkey();
1701 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
1702 if ( $name !== false ) {
1703 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1704 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1711 $errors[] = $this->missingPermissionError( $action, $short );
1716 * Get a description array when the user doesn't have the right to perform
1717 * $action (i.e. when User::isAllowed() returns false)
1719 * @param $action String the action to check
1720 * @param $short Boolean short circuit on first error
1721 * @return Array list of errors
1723 private function missingPermissionError( $action, $short ) {
1724 // We avoid expensive display logic for quickUserCan's and such
1726 return array( 'badaccess-group0' );
1729 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1730 User
::getGroupsWithPermission( $action, $this->mNamespace
) );
1732 if ( count( $groups ) ) {
1736 $wgLang->commaList( $groups ),
1740 return array( 'badaccess-group0' );
1745 * Can $user perform $action on this page? This is an internal function,
1746 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1747 * checks on wfReadOnly() and blocks)
1749 * @param $action String action that permission needs to be checked for
1750 * @param $user User to check
1751 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1752 * @param $short Bool Set this to true to stop after the first permission error.
1753 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1755 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1756 wfProfileIn( __METHOD__
);
1758 # Read has special handling
1759 if ( $action == 'read' ) {
1761 'checkPermissionHooks',
1762 'checkReadPermissions',
1766 'checkQuickPermissions',
1767 'checkPermissionHooks',
1768 'checkSpecialsAndNSPermissions',
1769 'checkCSSandJSPermissions',
1770 'checkPageRestrictions',
1771 'checkCascadingSourcesRestrictions',
1772 'checkActionPermissions',
1778 while( count( $checks ) > 0 &&
1779 !( $short && count( $errors ) > 0 ) ) {
1780 $method = array_shift( $checks );
1781 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1784 wfProfileOut( __METHOD__
);
1789 * Is this title subject to title protection?
1790 * Title protection is the one applied against creation of such title.
1792 * @return Mixed An associative array representing any existent title
1793 * protection, or false if there's none.
1795 private function getTitleProtection() {
1796 // Can't protect pages in special namespaces
1797 if ( $this->getNamespace() < 0 ) {
1801 // Can't protect pages that exist.
1802 if ( $this->exists() ) {
1806 if ( !isset( $this->mTitleProtection
) ) {
1807 $dbr = wfGetDB( DB_SLAVE
);
1808 $res = $dbr->select( 'protected_titles', '*',
1809 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1812 // fetchRow returns false if there are no rows.
1813 $this->mTitleProtection
= $dbr->fetchRow( $res );
1815 return $this->mTitleProtection
;
1819 * Update the title protection status
1821 * @param $create_perm String Permission required for creation
1822 * @param $reason String Reason for protection
1823 * @param $expiry String Expiry timestamp
1824 * @return boolean true
1826 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1827 global $wgUser, $wgContLang;
1829 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1830 && $expiry == $this->mRestrictionsExpiry
['create'] ) {
1835 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1837 $dbw = wfGetDB( DB_MASTER
);
1839 $encodedExpiry = $dbw->encodeExpiry( $expiry );
1841 $expiry_description = '';
1842 if ( $encodedExpiry != $dbw->getInfinity() ) {
1843 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1844 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1846 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1849 # Update protection table
1850 if ( $create_perm != '' ) {
1851 $this->mTitleProtection
= array(
1852 'pt_namespace' => $namespace,
1853 'pt_title' => $title,
1854 'pt_create_perm' => $create_perm,
1855 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1856 'pt_expiry' => $encodedExpiry,
1857 'pt_user' => $wgUser->getId(),
1858 'pt_reason' => $reason,
1860 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1861 $this->mTitleProtection
, __METHOD__
);
1863 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1864 'pt_title' => $title ), __METHOD__
);
1865 $this->mTitleProtection
= false;
1868 # Update the protection log
1869 if ( $dbw->affectedRows() ) {
1870 $log = new LogPage( 'protect' );
1872 if ( $create_perm ) {
1873 $params = array( "[create=$create_perm] $expiry_description", '' );
1874 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1876 $log->addEntry( 'unprotect', $this, $reason );
1884 * Remove any title protection due to page existing
1886 public function deleteTitleProtection() {
1887 $dbw = wfGetDB( DB_MASTER
);
1891 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1894 $this->mTitleProtection
= false;
1898 * Would anybody with sufficient privileges be able to move this page?
1899 * Some pages just aren't movable.
1901 * @return Bool TRUE or FALSE
1903 public function isMovable() {
1904 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
1905 // Interwiki title or immovable namespace. Hooks don't get to override here
1910 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
1915 * Is this the mainpage?
1916 * @note Title::newFromText seams to be sufficiently optimized by the title
1917 * cache that we don't need to over-optimize by doing direct comparisons and
1918 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1919 * ends up reporting something differently than $title->isMainPage();
1924 public function isMainPage() {
1925 return $this->equals( Title
::newMainPage() );
1929 * Is this a talk page of some sort?
1933 public function isTalkPage() {
1934 return MWNamespace
::isTalk( $this->getNamespace() );
1938 * Is this a subpage?
1942 public function isSubpage() {
1943 return MWNamespace
::hasSubpages( $this->mNamespace
)
1944 ?
strpos( $this->getText(), '/' ) !== false
1949 * Returns true if the title is inside the specified namespace.
1951 * Please make use of this instead of comparing to getNamespace()
1952 * This function is much more resistant to changes we may make
1953 * to namespaces than code that makes direct comparisons.
1954 * @param $ns The namespace
1958 public function inNamespace( $ns ) {
1959 return MWNamespace
::equals( $this->getNamespace(), $ns );
1963 * Returns true if the title is inside one of the specified namespaces.
1965 * @param ...$namespaces The namespaces to check for
1969 public function inNamespaces( /* ... */ ) {
1970 $namespaces = func_get_args();
1971 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1972 $namespaces = $namespaces[0];
1975 foreach ( $namespaces as $ns ) {
1976 if ( $this->inNamespace( $ns ) ) {
1985 * Returns true if the title has the same subject namespace as the
1986 * namespace specified.
1987 * For example this method will take NS_USER and return true if namespace
1988 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1989 * as their subject namespace.
1991 * This is MUCH simpler than individually testing for equivilance
1992 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1995 public function hasSubjectNamespace( $ns ) {
1996 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
2000 * Does this have subpages? (Warning, usually requires an extra DB query.)
2004 public function hasSubpages() {
2005 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2010 # We dynamically add a member variable for the purpose of this method
2011 # alone to cache the result. There's no point in having it hanging
2012 # around uninitialized in every Title object; therefore we only add it
2013 # if needed and don't declare it statically.
2014 if ( isset( $this->mHasSubpages
) ) {
2015 return $this->mHasSubpages
;
2018 $subpages = $this->getSubpages( 1 );
2019 if ( $subpages instanceof TitleArray
) {
2020 return $this->mHasSubpages
= (bool)$subpages->count();
2022 return $this->mHasSubpages
= false;
2026 * Get all subpages of this page.
2028 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2029 * @return mixed TitleArray, or empty array if this page's namespace
2030 * doesn't allow subpages
2032 public function getSubpages( $limit = -1 ) {
2033 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2037 $dbr = wfGetDB( DB_SLAVE
);
2038 $conds['page_namespace'] = $this->getNamespace();
2039 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2041 if ( $limit > -1 ) {
2042 $options['LIMIT'] = $limit;
2044 return $this->mSubpages
= TitleArray
::newFromResult(
2045 $dbr->select( 'page',
2046 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2055 * Does that page contain wikitext, or it is JS, CSS or whatever?
2059 public function isWikitextPage() {
2060 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
2061 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
2066 * Could this page contain custom CSS or JavaScript, based
2071 public function isCssOrJsPage() {
2072 $retval = $this->mNamespace
== NS_MEDIAWIKI
2073 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
2074 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
2079 * Is this a .css or .js subpage of a user page?
2082 public function isCssJsSubpage() {
2083 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
2087 * Is this a *valid* .css or .js subpage of a user page?
2090 * @deprecated since 1.17
2092 public function isValidCssJsSubpage() {
2093 return $this->isCssJsSubpage();
2097 * Trim down a .css or .js subpage title to get the corresponding skin name
2099 * @return string containing skin name from .css or .js subpage title
2101 public function getSkinFromCssJsSubpage() {
2102 $subpage = explode( '/', $this->mTextform
);
2103 $subpage = $subpage[ count( $subpage ) - 1 ];
2104 $lastdot = strrpos( $subpage, '.' );
2105 if ( $lastdot === false )
2106 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
2107 return substr( $subpage, 0, $lastdot );
2111 * Is this a .css subpage of a user page?
2115 public function isCssSubpage() {
2116 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
2120 * Is this a .js subpage of a user page?
2124 public function isJsSubpage() {
2125 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
2129 * Protect css subpages of user pages: can $wgUser edit
2132 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2135 public function userCanEditCssSubpage() {
2137 wfDeprecated( __METHOD__
);
2138 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2139 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2143 * Protect js subpages of user pages: can $wgUser edit
2146 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2149 public function userCanEditJsSubpage() {
2151 wfDeprecated( __METHOD__
);
2152 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2153 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2157 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2159 * @return Bool If the page is subject to cascading restrictions.
2161 public function isCascadeProtected() {
2162 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2163 return ( $sources > 0 );
2167 * Cascading protection: Get the source of any cascading restrictions on this page.
2169 * @param $getPages Bool Whether or not to retrieve the actual pages
2170 * that the restrictions have come from.
2171 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2172 * have come, false for none, or true if such restrictions exist, but $getPages
2173 * was not set. The restriction array is an array of each type, each of which
2174 * contains a array of unique groups.
2176 public function getCascadeProtectionSources( $getPages = true ) {
2178 $pagerestrictions = array();
2180 if ( isset( $this->mCascadeSources
) && $getPages ) {
2181 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2182 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2183 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2186 wfProfileIn( __METHOD__
);
2188 $dbr = wfGetDB( DB_SLAVE
);
2190 if ( $this->getNamespace() == NS_FILE
) {
2191 $tables = array( 'imagelinks', 'page_restrictions' );
2192 $where_clauses = array(
2193 'il_to' => $this->getDBkey(),
2198 $tables = array( 'templatelinks', 'page_restrictions' );
2199 $where_clauses = array(
2200 'tl_namespace' => $this->getNamespace(),
2201 'tl_title' => $this->getDBkey(),
2208 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2209 'pr_expiry', 'pr_type', 'pr_level' );
2210 $where_clauses[] = 'page_id=pr_page';
2213 $cols = array( 'pr_expiry' );
2216 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2218 $sources = $getPages ?
array() : false;
2219 $now = wfTimestampNow();
2220 $purgeExpired = false;
2222 foreach ( $res as $row ) {
2223 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2224 if ( $expiry > $now ) {
2226 $page_id = $row->pr_page
;
2227 $page_ns = $row->page_namespace
;
2228 $page_title = $row->page_title
;
2229 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2230 # Add groups needed for each restriction type if its not already there
2231 # Make sure this restriction type still exists
2233 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2234 $pagerestrictions[$row->pr_type
] = array();
2237 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2238 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2239 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2245 // Trigger lazy purge of expired restrictions from the db
2246 $purgeExpired = true;
2249 if ( $purgeExpired ) {
2250 Title
::purgeExpiredRestrictions();
2254 $this->mCascadeSources
= $sources;
2255 $this->mCascadingRestrictions
= $pagerestrictions;
2257 $this->mHasCascadingRestrictions
= $sources;
2260 wfProfileOut( __METHOD__
);
2261 return array( $sources, $pagerestrictions );
2265 * Returns cascading restrictions for the current article
2269 function areRestrictionsCascading() {
2270 if ( !$this->mRestrictionsLoaded
) {
2271 $this->loadRestrictions();
2274 return $this->mCascadeRestriction
;
2278 * Loads a string into mRestrictions array
2280 * @param $res Resource restrictions as an SQL result.
2281 * @param $oldFashionedRestrictions String comma-separated list of page
2282 * restrictions from page table (pre 1.10)
2284 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2287 foreach ( $res as $row ) {
2291 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2295 * Compiles list of active page restrictions from both page table (pre 1.10)
2296 * and page_restrictions table for this existing page.
2297 * Public for usage by LiquidThreads.
2299 * @param $rows array of db result objects
2300 * @param $oldFashionedRestrictions string comma-separated list of page
2301 * restrictions from page table (pre 1.10)
2303 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2305 $dbr = wfGetDB( DB_SLAVE
);
2307 $restrictionTypes = $this->getRestrictionTypes();
2309 foreach ( $restrictionTypes as $type ) {
2310 $this->mRestrictions
[$type] = array();
2311 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2314 $this->mCascadeRestriction
= false;
2316 # Backwards-compatibility: also load the restrictions from the page record (old format).
2318 if ( $oldFashionedRestrictions === null ) {
2319 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2320 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2323 if ( $oldFashionedRestrictions != '' ) {
2325 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2326 $temp = explode( '=', trim( $restrict ) );
2327 if ( count( $temp ) == 1 ) {
2328 // old old format should be treated as edit/move restriction
2329 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2330 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2332 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2336 $this->mOldRestrictions
= true;
2340 if ( count( $rows ) ) {
2341 # Current system - load second to make them override.
2342 $now = wfTimestampNow();
2343 $purgeExpired = false;
2345 # Cycle through all the restrictions.
2346 foreach ( $rows as $row ) {
2348 // Don't take care of restrictions types that aren't allowed
2349 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2352 // This code should be refactored, now that it's being used more generally,
2353 // But I don't really see any harm in leaving it in Block for now -werdna
2354 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2356 // Only apply the restrictions if they haven't expired!
2357 if ( !$expiry ||
$expiry > $now ) {
2358 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2359 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2361 $this->mCascadeRestriction |
= $row->pr_cascade
;
2363 // Trigger a lazy purge of expired restrictions
2364 $purgeExpired = true;
2368 if ( $purgeExpired ) {
2369 Title
::purgeExpiredRestrictions();
2373 $this->mRestrictionsLoaded
= true;
2377 * Load restrictions from the page_restrictions table
2379 * @param $oldFashionedRestrictions String comma-separated list of page
2380 * restrictions from page table (pre 1.10)
2382 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2384 if ( !$this->mRestrictionsLoaded
) {
2385 if ( $this->exists() ) {
2386 $dbr = wfGetDB( DB_SLAVE
);
2388 $res = $dbr->select(
2389 'page_restrictions',
2391 array( 'pr_page' => $this->getArticleId() ),
2395 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2397 $title_protection = $this->getTitleProtection();
2399 if ( $title_protection ) {
2400 $now = wfTimestampNow();
2401 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2403 if ( !$expiry ||
$expiry > $now ) {
2404 // Apply the restrictions
2405 $this->mRestrictionsExpiry
['create'] = $expiry;
2406 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2407 } else { // Get rid of the old restrictions
2408 Title
::purgeExpiredRestrictions();
2409 $this->mTitleProtection
= false;
2412 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2414 $this->mRestrictionsLoaded
= true;
2420 * Purge expired restrictions from the page_restrictions table
2422 static function purgeExpiredRestrictions() {
2423 $dbw = wfGetDB( DB_MASTER
);
2425 'page_restrictions',
2426 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2432 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2438 * Accessor/initialisation for mRestrictions
2440 * @param $action String action that permission needs to be checked for
2441 * @return Array of Strings the array of groups allowed to edit this article
2443 public function getRestrictions( $action ) {
2444 if ( !$this->mRestrictionsLoaded
) {
2445 $this->loadRestrictions();
2447 return isset( $this->mRestrictions
[$action] )
2448 ?
$this->mRestrictions
[$action]
2453 * Get the expiry time for the restriction against a given action
2455 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2456 * or not protected at all, or false if the action is not recognised.
2458 public function getRestrictionExpiry( $action ) {
2459 if ( !$this->mRestrictionsLoaded
) {
2460 $this->loadRestrictions();
2462 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2466 * Is there a version of this page in the deletion archive?
2468 * @return Int the number of archived revisions
2470 public function isDeleted() {
2471 if ( $this->getNamespace() < 0 ) {
2474 $dbr = wfGetDB( DB_SLAVE
);
2476 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2477 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2480 if ( $this->getNamespace() == NS_FILE
) {
2481 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2482 array( 'fa_name' => $this->getDBkey() ),
2491 * Is there a version of this page in the deletion archive?
2495 public function isDeletedQuick() {
2496 if ( $this->getNamespace() < 0 ) {
2499 $dbr = wfGetDB( DB_SLAVE
);
2500 $deleted = (bool)$dbr->selectField( 'archive', '1',
2501 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2504 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2505 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2506 array( 'fa_name' => $this->getDBkey() ),
2514 * Get the article ID for this Title from the link cache,
2515 * adding it if necessary
2517 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2519 * @return Int the ID
2521 public function getArticleID( $flags = 0 ) {
2522 if ( $this->getNamespace() < 0 ) {
2523 return $this->mArticleID
= 0;
2525 $linkCache = LinkCache
::singleton();
2526 if ( $flags & self
::GAID_FOR_UPDATE
) {
2527 $oldUpdate = $linkCache->forUpdate( true );
2528 $linkCache->clearLink( $this );
2529 $this->mArticleID
= $linkCache->addLinkObj( $this );
2530 $linkCache->forUpdate( $oldUpdate );
2532 if ( -1 == $this->mArticleID
) {
2533 $this->mArticleID
= $linkCache->addLinkObj( $this );
2536 return $this->mArticleID
;
2540 * Is this an article that is a redirect page?
2541 * Uses link cache, adding it if necessary
2543 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2546 public function isRedirect( $flags = 0 ) {
2547 if ( !is_null( $this->mRedirect
) ) {
2548 return $this->mRedirect
;
2550 # Calling getArticleID() loads the field from cache as needed
2551 if ( !$this->getArticleID( $flags ) ) {
2552 return $this->mRedirect
= false;
2554 $linkCache = LinkCache
::singleton();
2555 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2557 return $this->mRedirect
;
2561 * What is the length of this page?
2562 * Uses link cache, adding it if necessary
2564 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2567 public function getLength( $flags = 0 ) {
2568 if ( $this->mLength
!= -1 ) {
2569 return $this->mLength
;
2571 # Calling getArticleID() loads the field from cache as needed
2572 if ( !$this->getArticleID( $flags ) ) {
2573 return $this->mLength
= 0;
2575 $linkCache = LinkCache
::singleton();
2576 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2578 return $this->mLength
;
2582 * What is the page_latest field for this page?
2584 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2585 * @return Int or 0 if the page doesn't exist
2587 public function getLatestRevID( $flags = 0 ) {
2588 if ( $this->mLatestID
!== false ) {
2589 return intval( $this->mLatestID
);
2591 # Calling getArticleID() loads the field from cache as needed
2592 if ( !$this->getArticleID( $flags ) ) {
2593 return $this->mLatestID
= 0;
2595 $linkCache = LinkCache
::singleton();
2596 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2598 return $this->mLatestID
;
2602 * This clears some fields in this object, and clears any associated
2603 * keys in the "bad links" section of the link cache.
2605 * - This is called from Article::doEdit() and Article::insertOn() to allow
2606 * loading of the new page_id. It's also called from
2607 * Article::doDeleteArticle()
2609 * @param $newid Int the new Article ID
2611 public function resetArticleID( $newid ) {
2612 $linkCache = LinkCache
::singleton();
2613 $linkCache->clearLink( $this );
2615 if ( $newid === false ) {
2616 $this->mArticleID
= -1;
2618 $this->mArticleID
= intval( $newid );
2620 $this->mRestrictionsLoaded
= false;
2621 $this->mRestrictions
= array();
2622 $this->mRedirect
= null;
2623 $this->mLength
= -1;
2624 $this->mLatestID
= false;
2628 * Updates page_touched for this page; called from LinksUpdate.php
2630 * @return Bool true if the update succeded
2632 public function invalidateCache() {
2633 if ( wfReadOnly() ) {
2636 $dbw = wfGetDB( DB_MASTER
);
2637 $success = $dbw->update(
2639 array( 'page_touched' => $dbw->timestamp() ),
2643 HTMLFileCache
::clearFileCache( $this );
2648 * Prefix some arbitrary text with the namespace or interwiki prefix
2651 * @param $name String the text
2652 * @return String the prefixed text
2655 private function prefix( $name ) {
2657 if ( $this->mInterwiki
!= '' ) {
2658 $p = $this->mInterwiki
. ':';
2661 if ( 0 != $this->mNamespace
) {
2662 $p .= $this->getNsText() . ':';
2668 * Returns a simple regex that will match on characters and sequences invalid in titles.
2669 * Note that this doesn't pick up many things that could be wrong with titles, but that
2670 * replacing this regex with something valid will make many titles valid.
2672 * @return String regex string
2674 static function getTitleInvalidRegex() {
2675 static $rxTc = false;
2677 # Matching titles will be held as illegal.
2679 # Any character not allowed is forbidden...
2680 '[^' . Title
::legalChars() . ']' .
2681 # URL percent encoding sequences interfere with the ability
2682 # to round-trip titles -- you can't link to them consistently.
2683 '|%[0-9A-Fa-f]{2}' .
2684 # XML/HTML character references produce similar issues.
2685 '|&[A-Za-z0-9\x80-\xff]+;' .
2687 '|&#x[0-9A-Fa-f]+;' .
2695 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2697 * @param $text String containing title to capitalize
2698 * @param $ns int namespace index, defaults to NS_MAIN
2699 * @return String containing capitalized title
2701 public static function capitalize( $text, $ns = NS_MAIN
) {
2704 if ( MWNamespace
::isCapitalized( $ns ) ) {
2705 return $wgContLang->ucfirst( $text );
2712 * Secure and split - main initialisation function for this object
2714 * Assumes that mDbkeyform has been set, and is urldecoded
2715 * and uses underscores, but not otherwise munged. This function
2716 * removes illegal characters, splits off the interwiki and
2717 * namespace prefixes, sets the other forms, and canonicalizes
2720 * @return Bool true on success
2722 private function secureAndSplit() {
2723 global $wgContLang, $wgLocalInterwiki;
2726 $this->mInterwiki
= $this->mFragment
= '';
2727 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2729 $dbkey = $this->mDbkeyform
;
2731 # Strip Unicode bidi override characters.
2732 # Sometimes they slip into cut-n-pasted page titles, where the
2733 # override chars get included in list displays.
2734 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2736 # Clean up whitespace
2737 # Note: use of the /u option on preg_replace here will cause
2738 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2739 # conveniently disabling them.
2740 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2741 $dbkey = trim( $dbkey, '_' );
2743 if ( $dbkey == '' ) {
2747 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2748 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2752 $this->mDbkeyform
= $dbkey;
2754 # Initial colon indicates main namespace rather than specified default
2755 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2756 if ( ':' == $dbkey[0] ) {
2757 $this->mNamespace
= NS_MAIN
;
2758 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2759 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2762 # Namespace or interwiki prefix
2764 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2767 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2769 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2770 # Ordinary namespace
2772 $this->mNamespace
= $ns;
2773 # For Talk:X pages, check if X has a "namespace" prefix
2774 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2775 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2776 # Disallow Talk:File:x type titles...
2778 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2779 # Disallow Talk:Interwiki:x type titles...
2783 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2784 if ( !$firstPass ) {
2785 # Can't make a local interwiki link to an interwiki link.
2786 # That's just crazy!
2792 $this->mInterwiki
= $wgContLang->lc( $p );
2794 # Redundant interwiki prefix to the local wiki
2795 if ( $wgLocalInterwiki !== false
2796 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
2798 if ( $dbkey == '' ) {
2799 # Can't have an empty self-link
2802 $this->mInterwiki
= '';
2804 # Do another namespace split...
2808 # If there's an initial colon after the interwiki, that also
2809 # resets the default namespace
2810 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2811 $this->mNamespace
= NS_MAIN
;
2812 $dbkey = substr( $dbkey, 1 );
2815 # If there's no recognized interwiki or namespace,
2816 # then let the colon expression be part of the title.
2821 # We already know that some pages won't be in the database!
2822 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2823 $this->mArticleID
= 0;
2825 $fragment = strstr( $dbkey, '#' );
2826 if ( false !== $fragment ) {
2827 $this->setFragment( $fragment );
2828 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2829 # remove whitespace again: prevents "Foo_bar_#"
2830 # becoming "Foo_bar_"
2831 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2834 # Reject illegal characters.
2835 $rxTc = self
::getTitleInvalidRegex();
2836 if ( preg_match( $rxTc, $dbkey ) ) {
2840 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2841 # reachable due to the way web browsers deal with 'relative' URLs.
2842 # Also, they conflict with subpage syntax. Forbid them explicitly.
2843 if ( strpos( $dbkey, '.' ) !== false &&
2844 ( $dbkey === '.' ||
$dbkey === '..' ||
2845 strpos( $dbkey, './' ) === 0 ||
2846 strpos( $dbkey, '../' ) === 0 ||
2847 strpos( $dbkey, '/./' ) !== false ||
2848 strpos( $dbkey, '/../' ) !== false ||
2849 substr( $dbkey, -2 ) == '/.' ||
2850 substr( $dbkey, -3 ) == '/..' ) )
2855 # Magic tilde sequences? Nu-uh!
2856 if ( strpos( $dbkey, '~~~' ) !== false ) {
2860 # Limit the size of titles to 255 bytes. This is typically the size of the
2861 # underlying database field. We make an exception for special pages, which
2862 # don't need to be stored in the database, and may edge over 255 bytes due
2863 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2864 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2865 strlen( $dbkey ) > 512 )
2870 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2871 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2872 # other site might be case-sensitive.
2873 $this->mUserCaseDBKey
= $dbkey;
2874 if ( $this->mInterwiki
== '' ) {
2875 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2878 # Can't make a link to a namespace alone... "empty" local links can only be
2879 # self-links with a fragment identifier.
2880 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
2884 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2885 // IP names are not allowed for accounts, and can only be referring to
2886 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2887 // there are numerous ways to present the same IP. Having sp:contribs scan
2888 // them all is silly and having some show the edits and others not is
2889 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2890 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
2891 ? IP
::sanitizeIP( $dbkey )
2894 // Any remaining initial :s are illegal.
2895 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
2900 $this->mDbkeyform
= $dbkey;
2901 $this->mUrlform
= wfUrlencode( $dbkey );
2903 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2909 * Set the fragment for this title. Removes the first character from the
2910 * specified fragment before setting, so it assumes you're passing it with
2913 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2914 * Still in active use privately.
2916 * @param $fragment String text
2918 public function setFragment( $fragment ) {
2919 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2923 * Get a Title object associated with the talk page of this article
2925 * @return Title the object for the talk page
2927 public function getTalkPage() {
2928 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2932 * Get a title object associated with the subject page of this
2935 * @return Title the object for the subject page
2937 public function getSubjectPage() {
2938 // Is this the same title?
2939 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2940 if ( $this->getNamespace() == $subjectNS ) {
2943 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2947 * Get an array of Title objects linking to this Title
2948 * Also stores the IDs in the link cache.
2950 * WARNING: do not use this function on arbitrary user-supplied titles!
2951 * On heavily-used templates it will max out the memory.
2953 * @param $options Array: may be FOR UPDATE
2954 * @param $table String: table name
2955 * @param $prefix String: fields prefix
2956 * @return Array of Title objects linking here
2958 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2959 $linkCache = LinkCache
::singleton();
2961 if ( count( $options ) > 0 ) {
2962 $db = wfGetDB( DB_MASTER
);
2964 $db = wfGetDB( DB_SLAVE
);
2968 array( 'page', $table ),
2969 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2971 "{$prefix}_from=page_id",
2972 "{$prefix}_namespace" => $this->getNamespace(),
2973 "{$prefix}_title" => $this->getDBkey() ),
2979 if ( $db->numRows( $res ) ) {
2980 foreach ( $res as $row ) {
2981 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
2983 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
2984 $retVal[] = $titleObj;
2992 * Get an array of Title objects using this Title as a template
2993 * Also stores the IDs in the link cache.
2995 * WARNING: do not use this function on arbitrary user-supplied titles!
2996 * On heavily-used templates it will max out the memory.
2998 * @param $options Array: may be FOR UPDATE
2999 * @return Array of Title the Title objects linking here
3001 public function getTemplateLinksTo( $options = array() ) {
3002 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3006 * Get an array of Title objects referring to non-existent articles linked from this page
3008 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3009 * @return Array of Title the Title objects
3011 public function getBrokenLinksFrom() {
3012 if ( $this->getArticleId() == 0 ) {
3013 # All links from article ID 0 are false positives
3017 $dbr = wfGetDB( DB_SLAVE
);
3018 $res = $dbr->select(
3019 array( 'page', 'pagelinks' ),
3020 array( 'pl_namespace', 'pl_title' ),
3022 'pl_from' => $this->getArticleId(),
3023 'page_namespace IS NULL'
3025 __METHOD__
, array(),
3029 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3035 foreach ( $res as $row ) {
3036 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3043 * Get a list of URLs to purge from the Squid cache when this
3046 * @return Array of String the URLs
3048 public function getSquidURLs() {
3052 $this->getInternalURL(),
3053 $this->getInternalURL( 'action=history' )
3056 // purge variant urls as well
3057 if ( $wgContLang->hasVariants() ) {
3058 $variants = $wgContLang->getVariants();
3059 foreach ( $variants as $vCode ) {
3060 $urls[] = $this->getInternalURL( '', $vCode );
3068 * Purge all applicable Squid URLs
3070 public function purgeSquid() {
3072 if ( $wgUseSquid ) {
3073 $urls = $this->getSquidURLs();
3074 $u = new SquidUpdate( $urls );
3080 * Move this page without authentication
3082 * @param $nt Title the new page Title
3083 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3085 public function moveNoAuth( &$nt ) {
3086 return $this->moveTo( $nt, false );
3090 * Check whether a given move operation would be valid.
3091 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3093 * @param $nt Title the new title
3094 * @param $auth Bool indicates whether $wgUser's permissions
3096 * @param $reason String is the log summary of the move, used for spam checking
3097 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3099 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3104 // Normally we'd add this to $errors, but we'll get
3105 // lots of syntax errors if $nt is not an object
3106 return array( array( 'badtitletext' ) );
3108 if ( $this->equals( $nt ) ) {
3109 $errors[] = array( 'selfmove' );
3111 if ( !$this->isMovable() ) {
3112 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3114 if ( $nt->getInterwiki() != '' ) {
3115 $errors[] = array( 'immobile-target-namespace-iw' );
3117 if ( !$nt->isMovable() ) {
3118 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3121 $oldid = $this->getArticleID();
3122 $newid = $nt->getArticleID();
3124 if ( strlen( $nt->getDBkey() ) < 1 ) {
3125 $errors[] = array( 'articleexists' );
3127 if ( ( $this->getDBkey() == '' ) ||
3129 ( $nt->getDBkey() == '' ) ) {
3130 $errors[] = array( 'badarticleerror' );
3133 // Image-specific checks
3134 if ( $this->getNamespace() == NS_FILE
) {
3135 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3138 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3139 $errors[] = array( 'nonfile-cannot-move-to-file' );
3143 $errors = wfMergeErrorArrays( $errors,
3144 $this->getUserPermissionsErrors( 'move', $wgUser ),
3145 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3146 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3147 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3150 $match = EditPage
::matchSummarySpamRegex( $reason );
3151 if ( $match !== false ) {
3152 // This is kind of lame, won't display nice
3153 $errors[] = array( 'spamprotectiontext' );
3157 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3158 $errors[] = array( 'hookaborted', $err );
3161 # The move is allowed only if (1) the target doesn't exist, or
3162 # (2) the target is a redirect to the source, and has no history
3163 # (so we can undo bad moves right after they're done).
3165 if ( 0 != $newid ) { # Target exists; check for validity
3166 if ( !$this->isValidMoveTarget( $nt ) ) {
3167 $errors[] = array( 'articleexists' );
3170 $tp = $nt->getTitleProtection();
3171 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3172 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3173 $errors[] = array( 'cantmove-titleprotected' );
3176 if ( empty( $errors ) ) {
3183 * Check if the requested move target is a valid file move target
3184 * @param Title $nt Target title
3185 * @return array List of errors
3187 protected function validateFileMoveOperation( $nt ) {
3192 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3194 $file = wfLocalFile( $this );
3195 if ( $file->exists() ) {
3196 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3197 $errors[] = array( 'imageinvalidfilename' );
3199 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3200 $errors[] = array( 'imagetypemismatch' );
3204 if ( $nt->getNamespace() != NS_FILE
) {
3205 $errors[] = array( 'imagenocrossnamespace' );
3206 // From here we want to do checks on a file object, so if we can't
3207 // create one, we must return.
3211 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3213 $destFile = wfLocalFile( $nt );
3214 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3215 $errors[] = array( 'file-exists-sharedrepo' );
3222 * Move a title to a new location
3224 * @param $nt Title the new title
3225 * @param $auth Bool indicates whether $wgUser's permissions
3227 * @param $reason String the reason for the move
3228 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3229 * Ignored if the user doesn't have the suppressredirect right.
3230 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3232 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3234 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3235 if ( is_array( $err ) ) {
3236 // Auto-block user's IP if the account was "hard" blocked
3237 $wgUser->spreadAnyEditBlock();
3241 // If it is a file, move it first.
3242 // It is done before all other moving stuff is done because it's hard to revert.
3243 $dbw = wfGetDB( DB_MASTER
);
3244 if ( $this->getNamespace() == NS_FILE
) {
3245 $file = wfLocalFile( $this );
3246 if ( $file->exists() ) {
3247 $status = $file->move( $nt );
3248 if ( !$status->isOk() ) {
3249 return $status->getErrorsArray();
3253 // Clear RepoGroup process cache
3254 RepoGroup
::singleton()->clearCache( $this );
3255 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3257 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3258 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3259 $protected = $this->isProtected();
3260 $pageCountChange = ( $createRedirect ?
1 : 0 ) - ( $nt->exists() ?
1 : 0 );
3262 // Do the actual move
3263 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3264 if ( is_array( $err ) ) {
3265 # @todo FIXME: What about the File we have already moved?
3270 $redirid = $this->getArticleID();
3272 // Refresh the sortkey for this row. Be careful to avoid resetting
3273 // cl_timestamp, which may disturb time-based lists on some sites.
3274 $prefixes = $dbw->select(
3276 array( 'cl_sortkey_prefix', 'cl_to' ),
3277 array( 'cl_from' => $pageid ),
3280 foreach ( $prefixes as $prefixRow ) {
3281 $prefix = $prefixRow->cl_sortkey_prefix
;
3282 $catTo = $prefixRow->cl_to
;
3283 $dbw->update( 'categorylinks',
3285 'cl_sortkey' => Collation
::singleton()->getSortKey(
3286 $nt->getCategorySortkey( $prefix ) ),
3287 'cl_timestamp=cl_timestamp' ),
3289 'cl_from' => $pageid,
3290 'cl_to' => $catTo ),
3296 # Protect the redirect title as the title used to be...
3297 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3299 'pr_page' => $redirid,
3300 'pr_type' => 'pr_type',
3301 'pr_level' => 'pr_level',
3302 'pr_cascade' => 'pr_cascade',
3303 'pr_user' => 'pr_user',
3304 'pr_expiry' => 'pr_expiry'
3306 array( 'pr_page' => $pageid ),
3310 # Update the protection log
3311 $log = new LogPage( 'protect' );
3312 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3314 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3316 // @todo FIXME: $params?
3317 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3321 $oldnamespace = $this->getNamespace() & ~
1;
3322 $newnamespace = $nt->getNamespace() & ~
1;
3323 $oldtitle = $this->getDBkey();
3324 $newtitle = $nt->getDBkey();
3326 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3327 WatchedItem
::duplicateEntries( $this, $nt );
3330 # Update search engine
3331 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3333 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3339 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3340 # No longer a content page
3341 # Not viewed, edited, removing
3342 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3343 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3344 # Now a content page
3345 # Not viewed, edited, adding
3346 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
3347 } elseif ( $pageCountChange ) {
3349 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3358 # Update message cache for interface messages
3359 if ( $this->getNamespace() == NS_MEDIAWIKI
) {
3360 # @bug 17860: old article can be deleted, if this the case,
3361 # delete it from message cache
3362 if ( $this->getArticleID() === 0 ) {
3363 MessageCache
::singleton()->replace( $this->getDBkey(), false );
3365 $rev = Revision
::newFromTitle( $this );
3366 MessageCache
::singleton()->replace( $this->getDBkey(), $rev->getText() );
3369 if ( $nt->getNamespace() == NS_MEDIAWIKI
) {
3370 $rev = Revision
::newFromTitle( $nt );
3371 MessageCache
::singleton()->replace( $nt->getDBkey(), $rev->getText() );
3374 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3379 * Move page to a title which is either a redirect to the
3380 * source page or nonexistent
3382 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3383 * @param $reason String The reason for the move
3384 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3385 * if the user doesn't have the suppressredirect right
3387 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3388 global $wgUser, $wgContLang;
3390 if ( $nt->exists() ) {
3391 $moveOverRedirect = true;
3392 $logType = 'move_redir';
3394 $moveOverRedirect = false;
3398 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3400 $logEntry = new ManualLogEntry( 'move', $logType );
3401 $logEntry->setPerformer( $wgUser );
3402 $logEntry->setTarget( $this );
3403 $logEntry->setComment( $reason );
3404 $logEntry->setParameters( array(
3405 '4::target' => $nt->getPrefixedText(),
3406 '5::noredir' => $redirectSuppressed ?
'1': '0',
3409 $formatter = LogFormatter
::newFromEntry( $logEntry );
3410 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3411 $comment = $formatter->getPlainActionText();
3413 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3415 # Truncate for whole multibyte characters.
3416 $comment = $wgContLang->truncate( $comment, 255 );
3418 $oldid = $this->getArticleID();
3419 $latest = $this->getLatestRevID();
3421 $dbw = wfGetDB( DB_MASTER
);
3423 if ( $moveOverRedirect ) {
3424 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3426 $newid = $nt->getArticleID();
3427 $newns = $nt->getNamespace();
3428 $newdbk = $nt->getDBkey();
3430 # Delete the old redirect. We don't save it to history since
3431 # by definition if we've got here it's rather uninteresting.
3432 # We have to remove it so that the next step doesn't trigger
3433 # a conflict on the unique namespace+title index...
3434 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3435 if ( !$dbw->cascadingDeletes() ) {
3436 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3438 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3439 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3440 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3441 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3442 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3443 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3444 $dbw->delete( 'iwlinks', array( 'iwl_from' => $newid ), __METHOD__
);
3445 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3446 $dbw->delete( 'page_props', array( 'pp_page' => $newid ), __METHOD__
);
3448 // If the target page was recently created, it may have an entry in recentchanges still
3449 $dbw->delete( 'recentchanges',
3450 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3455 # Save a null revision in the page's history notifying of the move
3456 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3457 if ( !is_object( $nullRevision ) ) {
3458 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3460 $nullRevId = $nullRevision->insertOn( $dbw );
3462 $now = wfTimestampNow();
3463 # Change the name of the target page:
3464 $dbw->update( 'page',
3466 'page_touched' => $dbw->timestamp( $now ),
3467 'page_namespace' => $nt->getNamespace(),
3468 'page_title' => $nt->getDBkey(),
3469 'page_latest' => $nullRevId,
3471 /* WHERE */ array( 'page_id' => $oldid ),
3474 $nt->resetArticleID( $oldid );
3476 $article = WikiPage
::factory( $nt );
3477 wfRunHooks( 'NewRevisionFromEditComplete',
3478 array( $article, $nullRevision, $latest, $wgUser ) );
3479 $article->setCachedLastEditTime( $now );
3481 # Recreate the redirect, this time in the other direction.
3482 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3483 $mwRedir = MagicWord
::get( 'redirect' );
3484 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3485 $redirectArticle = WikiPage
::factory( $this );
3486 $newid = $redirectArticle->insertOn( $dbw );
3487 if ( $newid ) { // sanity
3488 $redirectRevision = new Revision( array(
3490 'comment' => $comment,
3491 'text' => $redirectText ) );
3492 $redirectRevision->insertOn( $dbw );
3493 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3495 wfRunHooks( 'NewRevisionFromEditComplete',
3496 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3498 # Now, we record the link from the redirect to the new title.
3499 # It should have no other outgoing links...
3500 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3501 $dbw->insert( 'pagelinks',
3503 'pl_from' => $newid,
3504 'pl_namespace' => $nt->getNamespace(),
3505 'pl_title' => $nt->getDBkey() ),
3509 $this->resetArticleID( 0 );
3513 $logid = $logEntry->insert();
3514 $logEntry->publish( $logid );
3516 # Purge caches for old and new titles
3517 if ( $moveOverRedirect ) {
3518 # A simple purge is enough when moving over a redirect
3521 # Purge caches as per article creation, including any pages that link to this title
3522 Article
::onArticleCreate( $nt );
3524 $this->purgeSquid();
3528 * Move this page's subpages to be subpages of $nt
3530 * @param $nt Title Move target
3531 * @param $auth bool Whether $wgUser's permissions should be checked
3532 * @param $reason string The reason for the move
3533 * @param $createRedirect bool Whether to create redirects from the old subpages to
3534 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3535 * @return mixed array with old page titles as keys, and strings (new page titles) or
3536 * arrays (errors) as values, or an error array with numeric indices if no pages
3539 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3540 global $wgMaximumMovedPages;
3541 // Check permissions
3542 if ( !$this->userCan( 'move-subpages' ) ) {
3543 return array( 'cant-move-subpages' );
3545 // Do the source and target namespaces support subpages?
3546 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3547 return array( 'namespace-nosubpages',
3548 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3550 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3551 return array( 'namespace-nosubpages',
3552 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3555 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3558 foreach ( $subpages as $oldSubpage ) {
3560 if ( $count > $wgMaximumMovedPages ) {
3561 $retval[$oldSubpage->getPrefixedTitle()] =
3562 array( 'movepage-max-pages',
3563 $wgMaximumMovedPages );
3567 // We don't know whether this function was called before
3568 // or after moving the root page, so check both
3570 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3571 $oldSubpage->getArticleID() == $nt->getArticleId() )
3573 // When moving a page to a subpage of itself,
3574 // don't move it twice
3577 $newPageName = preg_replace(
3578 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3579 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3580 $oldSubpage->getDBkey() );
3581 if ( $oldSubpage->isTalkPage() ) {
3582 $newNs = $nt->getTalkPage()->getNamespace();
3584 $newNs = $nt->getSubjectPage()->getNamespace();
3586 # Bug 14385: we need makeTitleSafe because the new page names may
3587 # be longer than 255 characters.
3588 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3590 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3591 if ( $success === true ) {
3592 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3594 $retval[$oldSubpage->getPrefixedText()] = $success;
3601 * Checks if this page is just a one-rev redirect.
3602 * Adds lock, so don't use just for light purposes.
3606 public function isSingleRevRedirect() {
3607 $dbw = wfGetDB( DB_MASTER
);
3609 $row = $dbw->selectRow( 'page',
3610 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3613 array( 'FOR UPDATE' )
3615 # Cache some fields we may want
3616 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3617 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3618 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3619 if ( !$this->mRedirect
) {
3622 # Does the article have a history?
3623 $row = $dbw->selectField( array( 'page', 'revision' ),
3625 array( 'page_namespace' => $this->getNamespace(),
3626 'page_title' => $this->getDBkey(),
3628 'page_latest != rev_id'
3631 array( 'FOR UPDATE' )
3633 # Return true if there was no history
3634 return ( $row === false );
3638 * Checks if $this can be moved to a given Title
3639 * - Selects for update, so don't call it unless you mean business
3641 * @param $nt Title the new title to check
3644 public function isValidMoveTarget( $nt ) {
3645 # Is it an existing file?
3646 if ( $nt->getNamespace() == NS_FILE
) {
3647 $file = wfLocalFile( $nt );
3648 if ( $file->exists() ) {
3649 wfDebug( __METHOD__
. ": file exists\n" );
3653 # Is it a redirect with no history?
3654 if ( !$nt->isSingleRevRedirect() ) {
3655 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3658 # Get the article text
3659 $rev = Revision
::newFromTitle( $nt );
3660 if( !is_object( $rev ) ){
3663 $text = $rev->getText();
3664 # Does the redirect point to the source?
3665 # Or is it a broken self-redirect, usually caused by namespace collisions?
3667 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3668 $redirTitle = Title
::newFromText( $m[1] );
3669 if ( !is_object( $redirTitle ) ||
3670 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3671 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3672 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3677 wfDebug( __METHOD__
. ": failsafe\n" );
3684 * Can this title be added to a user's watchlist?
3686 * @return Bool TRUE or FALSE
3688 public function isWatchable() {
3689 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3693 * Get categories to which this Title belongs and return an array of
3694 * categories' names.
3696 * @return Array of parents in the form:
3697 * $parent => $currentarticle
3699 public function getParentCategories() {
3704 $titleKey = $this->getArticleId();
3706 if ( $titleKey === 0 ) {
3710 $dbr = wfGetDB( DB_SLAVE
);
3712 $res = $dbr->select( 'categorylinks', '*',
3714 'cl_from' => $titleKey,
3720 if ( $dbr->numRows( $res ) > 0 ) {
3721 foreach ( $res as $row ) {
3722 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3723 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3730 * Get a tree of parent categories
3732 * @param $children Array with the children in the keys, to check for circular refs
3733 * @return Array Tree of parent categories
3735 public function getParentCategoryTree( $children = array() ) {
3737 $parents = $this->getParentCategories();
3740 foreach ( $parents as $parent => $current ) {
3741 if ( array_key_exists( $parent, $children ) ) {
3742 # Circular reference
3743 $stack[$parent] = array();
3745 $nt = Title
::newFromText( $parent );
3747 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3757 * Get an associative array for selecting this title from
3760 * @return Array suitable for the $where parameter of DB::select()
3762 public function pageCond() {
3763 if ( $this->mArticleID
> 0 ) {
3764 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3765 return array( 'page_id' => $this->mArticleID
);
3767 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3772 * Get the revision ID of the previous revision
3774 * @param $revId Int Revision ID. Get the revision that was before this one.
3775 * @param $flags Int Title::GAID_FOR_UPDATE
3776 * @return Int|Bool Old revision ID, or FALSE if none exists
3778 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3779 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3780 return $db->selectField( 'revision', 'rev_id',
3782 'rev_page' => $this->getArticleId( $flags ),
3783 'rev_id < ' . intval( $revId )
3786 array( 'ORDER BY' => 'rev_id DESC' )
3791 * Get the revision ID of the next revision
3793 * @param $revId Int Revision ID. Get the revision that was after this one.
3794 * @param $flags Int Title::GAID_FOR_UPDATE
3795 * @return Int|Bool Next revision ID, or FALSE if none exists
3797 public function getNextRevisionID( $revId, $flags = 0 ) {
3798 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3799 return $db->selectField( 'revision', 'rev_id',
3801 'rev_page' => $this->getArticleId( $flags ),
3802 'rev_id > ' . intval( $revId )
3805 array( 'ORDER BY' => 'rev_id' )
3810 * Get the first revision of the page
3812 * @param $flags Int Title::GAID_FOR_UPDATE
3813 * @return Revision|Null if page doesn't exist
3815 public function getFirstRevision( $flags = 0 ) {
3816 $pageId = $this->getArticleId( $flags );
3818 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3819 $row = $db->selectRow( 'revision', '*',
3820 array( 'rev_page' => $pageId ),
3822 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3825 return new Revision( $row );
3832 * Get the oldest revision timestamp of this page
3834 * @param $flags Int Title::GAID_FOR_UPDATE
3835 * @return String: MW timestamp
3837 public function getEarliestRevTime( $flags = 0 ) {
3838 $rev = $this->getFirstRevision( $flags );
3839 return $rev ?
$rev->getTimestamp() : null;
3843 * Check if this is a new page
3847 public function isNewPage() {
3848 $dbr = wfGetDB( DB_SLAVE
);
3849 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3853 * Get the number of revisions between the given revision.
3854 * Used for diffs and other things that really need it.
3856 * @param $old int|Revision Old revision or rev ID (first before range)
3857 * @param $new int|Revision New revision or rev ID (first after range)
3858 * @return Int Number of revisions between these revisions.
3860 public function countRevisionsBetween( $old, $new ) {
3861 if ( !( $old instanceof Revision
) ) {
3862 $old = Revision
::newFromTitle( $this, (int)$old );
3864 if ( !( $new instanceof Revision
) ) {
3865 $new = Revision
::newFromTitle( $this, (int)$new );
3867 if ( !$old ||
!$new ) {
3868 return 0; // nothing to compare
3870 $dbr = wfGetDB( DB_SLAVE
);
3871 return (int)$dbr->selectField( 'revision', 'count(*)',
3873 'rev_page' => $this->getArticleId(),
3874 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3875 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3882 * Get the number of authors between the given revision IDs.
3883 * Used for diffs and other things that really need it.
3885 * @param $old int|Revision Old revision or rev ID (first before range)
3886 * @param $new int|Revision New revision or rev ID (first after range)
3887 * @param $limit Int Maximum number of authors
3888 * @return Int Number of revision authors between these revisions.
3890 public function countAuthorsBetween( $old, $new, $limit ) {
3891 if ( !( $old instanceof Revision
) ) {
3892 $old = Revision
::newFromTitle( $this, (int)$old );
3894 if ( !( $new instanceof Revision
) ) {
3895 $new = Revision
::newFromTitle( $this, (int)$new );
3897 if ( !$old ||
!$new ) {
3898 return 0; // nothing to compare
3900 $dbr = wfGetDB( DB_SLAVE
);
3901 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
3903 'rev_page' => $this->getArticleID(),
3904 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3905 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3907 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
3909 return (int)$dbr->numRows( $res );
3913 * Compare with another title.
3915 * @param $title Title
3918 public function equals( Title
$title ) {
3919 // Note: === is necessary for proper matching of number-like titles.
3920 return $this->getInterwiki() === $title->getInterwiki()
3921 && $this->getNamespace() == $title->getNamespace()
3922 && $this->getDBkey() === $title->getDBkey();
3926 * Check if this title is a subpage of another title
3928 * @param $title Title
3931 public function isSubpageOf( Title
$title ) {
3932 return $this->getInterwiki() === $title->getInterwiki()
3933 && $this->getNamespace() == $title->getNamespace()
3934 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
3938 * Callback for usort() to do title sorts by (namespace, title)
3943 * @return Integer: result of string comparison, or namespace comparison
3945 public static function compare( $a, $b ) {
3946 if ( $a->getNamespace() == $b->getNamespace() ) {
3947 return strcmp( $a->getText(), $b->getText() );
3949 return $a->getNamespace() - $b->getNamespace();
3954 * Return a string representation of this title
3956 * @return String representation of this title
3958 public function __toString() {
3959 return $this->getPrefixedText();
3963 * Check if page exists. For historical reasons, this function simply
3964 * checks for the existence of the title in the page table, and will
3965 * thus return false for interwiki links, special pages and the like.
3966 * If you want to know if a title can be meaningfully viewed, you should
3967 * probably call the isKnown() method instead.
3971 public function exists() {
3972 return $this->getArticleId() != 0;
3976 * Should links to this title be shown as potentially viewable (i.e. as
3977 * "bluelinks"), even if there's no record by this title in the page
3980 * This function is semi-deprecated for public use, as well as somewhat
3981 * misleadingly named. You probably just want to call isKnown(), which
3982 * calls this function internally.
3984 * (ISSUE: Most of these checks are cheap, but the file existence check
3985 * can potentially be quite expensive. Including it here fixes a lot of
3986 * existing code, but we might want to add an optional parameter to skip
3987 * it and any other expensive checks.)
3991 public function isAlwaysKnown() {
3992 if ( $this->mInterwiki
!= '' ) {
3993 return true; // any interwiki link might be viewable, for all we know
3995 switch( $this->mNamespace
) {
3998 // file exists, possibly in a foreign repo
3999 return (bool)wfFindFile( $this );
4001 // valid special page
4002 return SpecialPageFactory
::exists( $this->getDBkey() );
4004 // selflink, possibly with fragment
4005 return $this->mDbkeyform
== '';
4007 // known system message
4008 return $this->hasSourceText() !== false;
4015 * Does this title refer to a page that can (or might) be meaningfully
4016 * viewed? In particular, this function may be used to determine if
4017 * links to the title should be rendered as "bluelinks" (as opposed to
4018 * "redlinks" to non-existent pages).
4022 public function isKnown() {
4023 return $this->isAlwaysKnown() ||
$this->exists();
4027 * Does this page have source text?
4031 public function hasSourceText() {
4032 if ( $this->exists() ) {
4036 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4037 // If the page doesn't exist but is a known system message, default
4038 // message content will be displayed, same for language subpages-
4039 // Use always content language to avoid loading hundreds of languages
4040 // to get the link color.
4042 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4043 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4044 return $message->exists();
4051 * Get the default message text or false if the message doesn't exist
4053 * @return String or false
4055 public function getDefaultMessageText() {
4058 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4062 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4063 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4065 if ( $message->exists() ) {
4066 return $message->plain();
4073 * Is this in a namespace that allows actual pages?
4076 * @internal note -- uses hardcoded namespace index instead of constants
4078 public function canExist() {
4079 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
4083 * Update page_touched timestamps and send squid purge messages for
4084 * pages linking to this title. May be sent to the job queue depending
4085 * on the number of links. Typically called on create and delete.
4087 public function touchLinks() {
4088 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4091 if ( $this->getNamespace() == NS_CATEGORY
) {
4092 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4098 * Get the last touched timestamp
4100 * @param $db DatabaseBase: optional db
4101 * @return String last-touched timestamp
4103 public function getTouched( $db = null ) {
4104 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4105 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4110 * Get the timestamp when this page was updated since the user last saw it.
4113 * @return String|Null
4115 public function getNotificationTimestamp( $user = null ) {
4116 global $wgUser, $wgShowUpdatedMarker;
4117 // Assume current user if none given
4121 // Check cache first
4122 $uid = $user->getId();
4123 // avoid isset here, as it'll return false for null entries
4124 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4125 return $this->mNotificationTimestamp
[$uid];
4127 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4128 return $this->mNotificationTimestamp
[$uid] = false;
4130 // Don't cache too much!
4131 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4132 $this->mNotificationTimestamp
= array();
4134 $dbr = wfGetDB( DB_SLAVE
);
4135 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4136 'wl_notificationtimestamp',
4137 array( 'wl_namespace' => $this->getNamespace(),
4138 'wl_title' => $this->getDBkey(),
4139 'wl_user' => $user->getId()
4143 return $this->mNotificationTimestamp
[$uid];
4147 * Generate strings used for xml 'id' names in monobook tabs
4149 * @param $prepend string defaults to 'nstab-'
4150 * @return String XML 'id' name
4152 public function getNamespaceKey( $prepend = 'nstab-' ) {
4154 // Gets the subject namespace if this title
4155 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4156 // Checks if cononical namespace name exists for namespace
4157 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4158 // Uses canonical namespace name
4159 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4161 // Uses text of namespace
4162 $namespaceKey = $this->getSubjectNsText();
4164 // Makes namespace key lowercase
4165 $namespaceKey = $wgContLang->lc( $namespaceKey );
4167 if ( $namespaceKey == '' ) {
4168 $namespaceKey = 'main';
4170 // Changes file to image for backwards compatibility
4171 if ( $namespaceKey == 'file' ) {
4172 $namespaceKey = 'image';
4174 return $prepend . $namespaceKey;
4178 * Returns true if this is a special page.
4182 public function isSpecialPage() {
4183 return $this->getNamespace() == NS_SPECIAL
;
4187 * Returns true if this title resolves to the named special page
4189 * @param $name String The special page name
4192 public function isSpecial( $name ) {
4193 if ( $this->isSpecialPage() ) {
4194 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
4195 if ( $name == $thisName ) {
4203 * If the Title refers to a special page alias which is not the local default, resolve
4204 * the alias, and localise the name as necessary. Otherwise, return $this
4208 public function fixSpecialName() {
4209 if ( $this->isSpecialPage() ) {
4210 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
4211 if ( $canonicalName ) {
4212 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
4213 if ( $localName != $this->mDbkeyform
) {
4214 return Title
::makeTitle( NS_SPECIAL
, $localName );
4222 * Is this Title in a namespace which contains content?
4223 * In other words, is this a content page, for the purposes of calculating
4228 public function isContentPage() {
4229 return MWNamespace
::isContent( $this->getNamespace() );
4233 * Get all extant redirects to this Title
4235 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4236 * @return Array of Title redirects to this title
4238 public function getRedirectsHere( $ns = null ) {
4241 $dbr = wfGetDB( DB_SLAVE
);
4243 'rd_namespace' => $this->getNamespace(),
4244 'rd_title' => $this->getDBkey(),
4247 if ( !is_null( $ns ) ) {
4248 $where['page_namespace'] = $ns;
4251 $res = $dbr->select(
4252 array( 'redirect', 'page' ),
4253 array( 'page_namespace', 'page_title' ),
4258 foreach ( $res as $row ) {
4259 $redirs[] = self
::newFromRow( $row );
4265 * Check if this Title is a valid redirect target
4269 public function isValidRedirectTarget() {
4270 global $wgInvalidRedirectTargets;
4272 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4273 if ( $this->isSpecial( 'Userlogout' ) ) {
4277 foreach ( $wgInvalidRedirectTargets as $target ) {
4278 if ( $this->isSpecial( $target ) ) {
4287 * Get a backlink cache object
4289 * @return BacklinkCache
4291 function getBacklinkCache() {
4292 if ( is_null( $this->mBacklinkCache
) ) {
4293 $this->mBacklinkCache
= new BacklinkCache( $this );
4295 return $this->mBacklinkCache
;
4299 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4303 public function canUseNoindex() {
4304 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4306 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4307 ?
$wgContentNamespaces
4308 : $wgExemptFromUserRobotsControl;
4310 return !in_array( $this->mNamespace
, $bannedNamespaces );
4315 * Returns restriction types for the current Title
4317 * @return array applicable restriction types
4319 public function getRestrictionTypes() {
4320 if ( $this->isSpecialPage() ) {
4324 $types = self
::getFilteredRestrictionTypes( $this->exists() );
4326 if ( $this->getNamespace() != NS_FILE
) {
4327 # Remove the upload restriction for non-file titles
4328 $types = array_diff( $types, array( 'upload' ) );
4331 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4333 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
4334 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
4339 * Get a filtered list of all restriction types supported by this wiki.
4340 * @param bool $exists True to get all restriction types that apply to
4341 * titles that do exist, False for all restriction types that apply to
4342 * titles that do not exist
4345 public static function getFilteredRestrictionTypes( $exists = true ) {
4346 global $wgRestrictionTypes;
4347 $types = $wgRestrictionTypes;
4349 # Remove the create restriction for existing titles
4350 $types = array_diff( $types, array( 'create' ) );
4352 # Only the create and upload restrictions apply to non-existing titles
4353 $types = array_intersect( $types, array( 'create', 'upload' ) );
4359 * Returns the raw sort key to be used for categories, with the specified
4360 * prefix. This will be fed to Collation::getSortKey() to get a
4361 * binary sortkey that can be used for actual sorting.
4363 * @param $prefix string The prefix to be used, specified using
4364 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4368 public function getCategorySortkey( $prefix = '' ) {
4369 $unprefixed = $this->getText();
4371 // Anything that uses this hook should only depend
4372 // on the Title object passed in, and should probably
4373 // tell the users to run updateCollations.php --force
4374 // in order to re-sort existing category relations.
4375 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4376 if ( $prefix !== '' ) {
4377 # Separate with a line feed, so the unprefixed part is only used as
4378 # a tiebreaker when two pages have the exact same prefix.
4379 # In UCA, tab is the only character that can sort above LF
4380 # so we strip both of them from the original prefix.
4381 $prefix = strtr( $prefix, "\n\t", ' ' );
4382 return "$prefix\n$unprefixed";
4388 * Get the language in which the content of this page is written.
4389 * Defaults to $wgContLang, but in certain cases it can be e.g.
4390 * $wgLang (such as special pages, which are in the user language).
4393 * @return object Language
4395 public function getPageLanguage() {
4397 if ( $this->isSpecialPage() ) {
4398 // special pages are in the user language
4400 } elseif ( $this->isCssOrJsPage() ) {
4401 // css/js should always be LTR and is, in fact, English
4402 return wfGetLangObj( 'en' );
4403 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4404 // Parse mediawiki messages with correct target language
4405 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4406 return wfGetLangObj( $lang );
4409 // If nothing special, it should be in the wiki content language
4410 $pageLang = $wgContLang;
4411 // Hook at the end because we don't want to override the above stuff
4412 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4413 return wfGetLangObj( $pageLang );