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() ) {
446 * Get the prefixed DB key associated with an ID
448 * @param $id Int the page_id of the article
449 * @return Title an object representing the article, or NULL if no such article was found
451 public static function nameOf( $id ) {
452 $dbr = wfGetDB( DB_SLAVE
);
454 $s = $dbr->selectRow(
456 array( 'page_namespace', 'page_title' ),
457 array( 'page_id' => $id ),
460 if ( $s === false ) {
464 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
469 * Get a regex character class describing the legal characters in a link
471 * @return String the list of characters, not delimited
473 public static function legalChars() {
474 global $wgLegalTitleChars;
475 return $wgLegalTitleChars;
479 * Get a string representation of a title suitable for
480 * including in a search index
482 * @param $ns Int a namespace index
483 * @param $title String text-form main part
484 * @return String a stripped-down title string ready for the search index
486 public static function indexTitle( $ns, $title ) {
489 $lc = SearchEngine
::legalSearchChars() . '&#;';
490 $t = $wgContLang->normalizeForSearch( $title );
491 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
492 $t = $wgContLang->lc( $t );
495 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
496 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
498 $t = preg_replace( "/\\s+/", ' ', $t );
500 if ( $ns == NS_FILE
) {
501 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
507 * Make a prefixed DB key from a DB key and a namespace index
509 * @param $ns Int numerical representation of the namespace
510 * @param $title String the DB key form the title
511 * @param $fragment String The link fragment (after the "#")
512 * @param $interwiki String The interwiki prefix
513 * @return String the prefixed form of the title
515 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
518 $namespace = $wgContLang->getNsText( $ns );
519 $name = $namespace == '' ?
$title : "$namespace:$title";
520 if ( strval( $interwiki ) != '' ) {
521 $name = "$interwiki:$name";
523 if ( strval( $fragment ) != '' ) {
524 $name .= '#' . $fragment;
530 * Escape a text fragment, say from a link, for a URL
532 * @param $fragment string containing a URL or link fragment (after the "#")
533 * @return String: escaped string
535 static function escapeFragmentForURL( $fragment ) {
536 # Note that we don't urlencode the fragment. urlencoded Unicode
537 # fragments appear not to work in IE (at least up to 7) or in at least
538 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
539 # to care if they aren't encoded.
540 return Sanitizer
::escapeId( $fragment, 'noninitial' );
544 * Determine whether the object refers to a page within
547 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
549 public function isLocal() {
550 if ( $this->mInterwiki
!= '' ) {
551 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
558 * Is this Title interwiki?
562 public function isExternal() {
563 return ( $this->mInterwiki
!= '' );
567 * Get the interwiki prefix (or null string)
569 * @return String Interwiki prefix
571 public function getInterwiki() {
572 return $this->mInterwiki
;
576 * Determine whether the object refers to a page within
577 * this project and is transcludable.
579 * @return Bool TRUE if this is transcludable
581 public function isTrans() {
582 if ( $this->mInterwiki
== '' ) {
586 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
590 * Returns the DB name of the distant wiki which owns the object.
592 * @return String the DB name
594 public function getTransWikiID() {
595 if ( $this->mInterwiki
== '' ) {
599 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
603 * Get the text form (spaces not underscores) of the main part
605 * @return String Main part of the title
607 public function getText() {
608 return $this->mTextform
;
612 * Get the URL-encoded form of the main part
614 * @return String Main part of the title, URL-encoded
616 public function getPartialURL() {
617 return $this->mUrlform
;
621 * Get the main part with underscores
623 * @return String: Main part of the title, with underscores
625 public function getDBkey() {
626 return $this->mDbkeyform
;
630 * Get the namespace index, i.e. one of the NS_xxxx constants.
632 * @return Integer: Namespace index
634 public function getNamespace() {
635 return $this->mNamespace
;
639 * Get the namespace text
641 * @return String: Namespace text
643 public function getNsText() {
646 if ( $this->mInterwiki
!= '' ) {
647 // This probably shouldn't even happen. ohh man, oh yuck.
648 // But for interwiki transclusion it sometimes does.
649 // Shit. Shit shit shit.
651 // Use the canonical namespaces if possible to try to
652 // resolve a foreign namespace.
653 if ( MWNamespace
::exists( $this->mNamespace
) ) {
654 return MWNamespace
::getCanonicalName( $this->mNamespace
);
658 // Strip off subpages
659 $pagename = $this->getText();
660 if ( strpos( $pagename, '/' ) !== false ) {
661 list( $username , ) = explode( '/', $pagename, 2 );
663 $username = $pagename;
666 if ( $wgContLang->needsGenderDistinction() &&
667 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
668 $gender = GenderCache
::singleton()->getGenderOf( $username, __METHOD__
);
669 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
672 return $wgContLang->getNsText( $this->mNamespace
);
676 * Get the DB key with the initial letter case as specified by the user
678 * @return String DB key
680 function getUserCaseDBKey() {
681 return $this->mUserCaseDBKey
;
685 * Get the namespace text of the subject (rather than talk) page
687 * @return String Namespace text
689 public function getSubjectNsText() {
691 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
695 * Get the namespace text of the talk page
697 * @return String Namespace text
699 public function getTalkNsText() {
701 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
705 * Could this title have a corresponding talk page?
707 * @return Bool TRUE or FALSE
709 public function canTalk() {
710 return( MWNamespace
::canTalk( $this->mNamespace
) );
714 * Get the Title fragment (i.e.\ the bit after the #) in text form
716 * @return String Title fragment
718 public function getFragment() { return $this->mFragment
; }
721 * Get the fragment in URL form, including the "#" character if there is one
722 * @return String Fragment in URL form
724 public function getFragmentForURL() {
725 if ( $this->mFragment
== '' ) {
728 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
733 * Get the default namespace index, for when there is no namespace
735 * @return Int Default namespace index
737 public function getDefaultNamespace() {
738 return $this->mDefaultNamespace
;
742 * Get title for search index
744 * @return String a stripped-down title string ready for the
747 public function getIndexTitle() {
748 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
752 * Get the prefixed database key form
754 * @return String the prefixed title, with underscores and
755 * any interwiki and namespace prefixes
757 public function getPrefixedDBkey() {
758 $s = $this->prefix( $this->mDbkeyform
);
759 $s = str_replace( ' ', '_', $s );
764 * Get the prefixed title with spaces.
765 * This is the form usually used for display
767 * @return String the prefixed title, with spaces
769 public function getPrefixedText() {
770 // @todo FIXME: Bad usage of empty() ?
771 if ( empty( $this->mPrefixedText
) ) {
772 $s = $this->prefix( $this->mTextform
);
773 $s = str_replace( '_', ' ', $s );
774 $this->mPrefixedText
= $s;
776 return $this->mPrefixedText
;
781 * Get the prefixed title with spaces, plus any fragment
782 * (part beginning with '#')
784 * @return String the prefixed title, with spaces and the fragment, including '#'
786 public function getFullText() {
787 $text = $this->getPrefixedText();
788 if ( $this->mFragment
!= '' ) {
789 $text .= '#' . $this->mFragment
;
795 * Get the base page name, i.e. the leftmost part before any slashes
797 * @return String Base name
799 public function getBaseText() {
800 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
801 return $this->getText();
804 $parts = explode( '/', $this->getText() );
805 # Don't discard the real title if there's no subpage involved
806 if ( count( $parts ) > 1 ) {
807 unset( $parts[count( $parts ) - 1] );
809 return implode( '/', $parts );
813 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
815 * @return String Subpage name
817 public function getSubpageText() {
818 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
819 return( $this->mTextform
);
821 $parts = explode( '/', $this->mTextform
);
822 return( $parts[count( $parts ) - 1] );
826 * Get the HTML-escaped displayable text form.
827 * Used for the title field in <a> tags.
829 * @return String the text, including any prefixes
831 public function getEscapedText() {
832 return htmlspecialchars( $this->getPrefixedText() );
836 * Get a URL-encoded form of the subpage text
838 * @return String URL-encoded subpage name
840 public function getSubpageUrlForm() {
841 $text = $this->getSubpageText();
842 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
847 * Get a URL-encoded title (not an actual URL) including interwiki
849 * @return String the URL-encoded form
851 public function getPrefixedURL() {
852 $s = $this->prefix( $this->mDbkeyform
);
853 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
858 * Get a real URL referring to this title, with interwiki link and
861 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
862 * links. Can be specified as an associative array as well, e.g.,
863 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
864 * @param $variant String language variant of url (for sr, zh..)
865 * @return String the URL
867 public function getFullURL( $query = '', $variant = false ) {
868 # Hand off all the decisions on urls to getLocalURL
869 $url = $this->getLocalURL( $query, $variant );
871 # Expand the url to make it a full url. Note that getLocalURL has the
872 # potential to output full urls for a variety of reasons, so we use
873 # wfExpandUrl instead of simply prepending $wgServer
874 $url = wfExpandUrl( $url, PROTO_RELATIVE
);
876 # Finally, add the fragment.
877 $url .= $this->getFragmentForURL();
879 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query, $variant ) );
884 * Get a URL with no fragment or server name. If this page is generated
885 * with action=render, $wgServer is prepended.
887 * @param $query Mixed: an optional query string; if not specified,
888 * $wgArticlePath will be used. Can be specified as an associative array
889 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
891 * @param $variant String language variant of url (for sr, zh..)
892 * @return String the URL
894 public function getLocalURL( $query = '', $variant = false ) {
895 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
896 global $wgVariantArticlePath;
898 if ( is_array( $query ) ) {
899 $query = wfArrayToCGI( $query );
902 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
904 $namespace = $this->getNsText();
905 if ( $namespace != '' ) {
906 # Can this actually happen? Interwikis shouldn't be parsed.
907 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
910 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
911 $url = wfAppendQuery( $url, $query );
913 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
914 if ( $query == '' ) {
915 if ( $variant != false && $this->getPageLanguage()->hasVariants() ) {
916 if ( !$wgVariantArticlePath ) {
917 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
919 $variantArticlePath = $wgVariantArticlePath;
921 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
922 $url = str_replace( '$1', $dbkey, $url );
924 $url = str_replace( '$1', $dbkey, $wgArticlePath );
925 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
928 global $wgActionPaths;
931 if ( !empty( $wgActionPaths ) &&
932 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
934 $action = urldecode( $matches[2] );
935 if ( isset( $wgActionPaths[$action] ) ) {
936 $query = $matches[1];
937 if ( isset( $matches[4] ) ) {
938 $query .= $matches[4];
940 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
941 if ( $query != '' ) {
942 $url = wfAppendQuery( $url, $query );
947 if ( $url === false ) {
948 if ( $query == '-' ) {
951 $url = "{$wgScript}?title={$dbkey}&{$query}";
955 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query, $variant ) );
957 // @todo FIXME: This causes breakage in various places when we
958 // actually expected a local URL and end up with dupe prefixes.
959 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
960 $url = $wgServer . $url;
963 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query, $variant ) );
968 * Get a URL that's the simplest URL that will be valid to link, locally,
969 * to the current Title. It includes the fragment, but does not include
970 * the server unless action=render is used (or the link is external). If
971 * there's a fragment but the prefixed text is empty, we just return a link
974 * The result obviously should not be URL-escaped, but does need to be
975 * HTML-escaped if it's being output in HTML.
977 * @param $query Array of Strings An associative array of key => value pairs for the
978 * query string. Keys and values will be escaped.
979 * @param $variant String language variant of URL (for sr, zh..). Ignored
980 * for external links. Default is "false" (same variant as current page,
981 * for anonymous users).
982 * @return String the URL
984 public function getLinkURL( $query = array(), $variant = false ) {
985 wfProfileIn( __METHOD__
);
986 if ( $this->isExternal() ) {
987 $ret = $this->getFullURL( $query );
988 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
989 $ret = $this->getFragmentForURL();
991 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
993 wfProfileOut( __METHOD__
);
998 * Get an HTML-escaped version of the URL form, suitable for
999 * using in a link, without a server name or fragment
1001 * @param $query String an optional query string
1002 * @return String the URL
1004 public function escapeLocalURL( $query = '' ) {
1005 return htmlspecialchars( $this->getLocalURL( $query ) );
1009 * Get an HTML-escaped version of the URL form, suitable for
1010 * using in a link, including the server name and fragment
1012 * @param $query String an optional query string
1013 * @return String the URL
1015 public function escapeFullURL( $query = '' ) {
1016 return htmlspecialchars( $this->getFullURL( $query ) );
1020 * Get the URL form for an internal link.
1021 * - Used in various Squid-related code, in case we have a different
1022 * internal hostname for the server from the exposed one.
1024 * This uses $wgInternalServer to qualify the path, or $wgServer
1025 * if $wgInternalServer is not set. If the server variable used is
1026 * protocol-relative, the URL will be expanded to http://
1028 * @param $query String an optional query string
1029 * @param $variant String language variant of url (for sr, zh..)
1030 * @return String the URL
1032 public function getInternalURL( $query = '', $variant = false ) {
1033 global $wgInternalServer, $wgServer;
1034 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1035 $url = wfExpandUrl( $server . $this->getLocalURL( $query, $variant ), PROTO_HTTP
);
1036 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query, $variant ) );
1041 * Get the URL for a canonical link, for use in things like IRC and
1042 * e-mail notifications. Uses $wgCanonicalServer and the
1043 * GetCanonicalURL hook.
1045 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1047 * @param $query string An optional query string
1048 * @param $variant string Language variant of URL (for sr, zh, ...)
1049 * @return string The URL
1052 public function getCanonicalURL( $query = '', $variant = false ) {
1053 $url = wfExpandUrl( $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1054 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query, $variant ) );
1059 * HTML-escaped version of getCanonicalURL()
1062 public function escapeCanonicalURL( $query = '', $variant = false ) {
1063 return htmlspecialchars( $this->getCanonicalURL( $query, $variant ) );
1067 * Get the edit URL for this Title
1069 * @return String the URL, or a null string if this is an
1072 public function getEditURL() {
1073 if ( $this->mInterwiki
!= '' ) {
1076 $s = $this->getLocalURL( 'action=edit' );
1082 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1084 * @param $action String Action to check (default: edit)
1087 public function isSemiProtected( $action = 'edit' ) {
1088 if ( $this->exists() ) {
1089 $restrictions = $this->getRestrictions( $action );
1090 if ( count( $restrictions ) > 0 ) {
1091 foreach ( $restrictions as $restriction ) {
1092 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1102 # If it doesn't exist, it can't be protected
1108 * Does the title correspond to a protected article?
1110 * @param $action String the action the page is protected from,
1111 * by default checks all actions.
1114 public function isProtected( $action = '' ) {
1115 global $wgRestrictionLevels;
1117 $restrictionTypes = $this->getRestrictionTypes();
1119 # Special pages have inherent protection
1120 if( $this->isSpecialPage() ) {
1124 # Check regular protection levels
1125 foreach ( $restrictionTypes as $type ) {
1126 if ( $action == $type ||
$action == '' ) {
1127 $r = $this->getRestrictions( $type );
1128 foreach ( $wgRestrictionLevels as $level ) {
1129 if ( in_array( $level, $r ) && $level != '' ) {
1140 * Determines if $user is unable to edit this page because it has been protected
1141 * by $wgNamespaceProtection.
1143 * @param $user User object to check permissions
1146 public function isNamespaceProtected( User
$user ) {
1147 global $wgNamespaceProtection;
1149 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
1150 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
1151 if ( $right != '' && !$user->isAllowed( $right ) ) {
1160 * Is this a conversion table for the LanguageConverter?
1164 public function isConversionTable() {
1166 $this->getNamespace() == NS_MEDIAWIKI
&&
1167 strpos( $this->getText(), 'Conversiontable' ) !== false
1177 * Is $wgUser watching this page?
1181 public function userIsWatching() {
1184 if ( is_null( $this->mWatched
) ) {
1185 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1186 $this->mWatched
= false;
1188 $this->mWatched
= $wgUser->isWatched( $this );
1191 return $this->mWatched
;
1195 * Can $wgUser read this page?
1197 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1199 * @todo fold these checks into userCan()
1201 public function userCanRead() {
1202 return $this->userCan( 'read' );
1206 * Can $wgUser perform $action on this page?
1207 * This skips potentially expensive cascading permission checks
1208 * as well as avoids expensive error formatting
1210 * Suitable for use for nonessential UI controls in common cases, but
1211 * _not_ for functional access control.
1213 * May provide false positives, but should never provide a false negative.
1215 * @param $action String action that permission needs to be checked for
1216 * @param $user User to check (since 1.19)
1219 public function quickUserCan( $action, $user = null ) {
1220 return $this->userCan( $action, $user, false );
1224 * Can $wgUser perform $action on this page?
1226 * @param $action String action that permission needs to be checked for
1227 * @param $user User to check (since 1.19)
1228 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1231 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1232 if ( !$user instanceof User
) {
1236 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1240 * Can $user perform $action on this page?
1242 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1244 * @param $action String action that permission needs to be checked for
1245 * @param $user User to check
1246 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries by
1247 * skipping checks for cascading protections and user blocks.
1248 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1249 * @return Array of arguments to wfMsg to explain permissions problems.
1251 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1252 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1254 // Remove the errors being ignored.
1255 foreach ( $errors as $index => $error ) {
1256 $error_key = is_array( $error ) ?
$error[0] : $error;
1258 if ( in_array( $error_key, $ignoreErrors ) ) {
1259 unset( $errors[$index] );
1267 * Permissions checks that fail most often, and which are easiest to test.
1269 * @param $action String the action to check
1270 * @param $user User user to check
1271 * @param $errors Array list of current errors
1272 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1273 * @param $short Boolean short circuit on first error
1275 * @return Array list of errors
1277 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1278 $ns = $this->getNamespace();
1280 if ( $action == 'create' ) {
1281 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk', $ns ) ) ||
1282 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage', $ns ) ) ) {
1283 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1285 } elseif ( $action == 'move' ) {
1286 if ( !$user->isAllowed( 'move-rootuserpages', $ns )
1287 && $ns == NS_USER
&& !$this->isSubpage() ) {
1288 // Show user page-specific message only if the user can move other pages
1289 $errors[] = array( 'cant-move-user-page' );
1292 // Check if user is allowed to move files if it's a file
1293 if ( $ns == NS_FILE
&& !$user->isAllowed( 'movefile', $ns ) ) {
1294 $errors[] = array( 'movenotallowedfile' );
1297 if ( !$user->isAllowed( 'move', $ns) ) {
1298 // User can't move anything
1300 $userCanMove = in_array( 'move', User
::getGroupPermissions(
1301 array( 'user' ), $ns ), true );
1302 $autoconfirmedCanMove = in_array( 'move', User
::getGroupPermissions(
1303 array( 'autoconfirmed' ), $ns ), true );
1305 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1306 // custom message if logged-in users without any special rights can move
1307 $errors[] = array( 'movenologintext' );
1309 $errors[] = array( 'movenotallowed' );
1312 } elseif ( $action == 'move-target' ) {
1313 if ( !$user->isAllowed( 'move', $ns ) ) {
1314 // User can't move anything
1315 $errors[] = array( 'movenotallowed' );
1316 } elseif ( !$user->isAllowed( 'move-rootuserpages', $ns )
1317 && $ns == NS_USER
&& !$this->isSubpage() ) {
1318 // Show user page-specific message only if the user can move other pages
1319 $errors[] = array( 'cant-move-to-user-page' );
1321 } elseif ( !$user->isAllowed( $action, $ns ) ) {
1322 $errors[] = $this->missingPermissionError( $action, $short );
1329 * Add the resulting error code to the errors array
1331 * @param $errors Array list of current errors
1332 * @param $result Mixed result of errors
1334 * @return Array list of errors
1336 private function resultToError( $errors, $result ) {
1337 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1338 // A single array representing an error
1339 $errors[] = $result;
1340 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1341 // A nested array representing multiple errors
1342 $errors = array_merge( $errors, $result );
1343 } elseif ( $result !== '' && is_string( $result ) ) {
1344 // A string representing a message-id
1345 $errors[] = array( $result );
1346 } elseif ( $result === false ) {
1347 // a generic "We don't want them to do that"
1348 $errors[] = array( 'badaccess-group0' );
1354 * Check various permission hooks
1356 * @param $action String the action to check
1357 * @param $user User user to check
1358 * @param $errors Array list of current errors
1359 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1360 * @param $short Boolean short circuit on first error
1362 * @return Array list of errors
1364 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1365 // Use getUserPermissionsErrors instead
1367 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1368 return $result ?
array() : array( array( 'badaccess-group0' ) );
1370 // Check getUserPermissionsErrors hook
1371 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1372 $errors = $this->resultToError( $errors, $result );
1374 // Check getUserPermissionsErrorsExpensive hook
1375 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1376 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1377 $errors = $this->resultToError( $errors, $result );
1384 * Check permissions on special pages & namespaces
1386 * @param $action String the action to check
1387 * @param $user User user to check
1388 * @param $errors Array list of current errors
1389 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1390 * @param $short Boolean short circuit on first error
1392 * @return Array list of errors
1394 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1395 # Only 'createaccount' and 'execute' can be performed on
1396 # special pages, which don't actually exist in the DB.
1397 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1398 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1399 $errors[] = array( 'ns-specialprotected' );
1402 # Check $wgNamespaceProtection for restricted namespaces
1403 if ( $this->isNamespaceProtected( $user ) ) {
1404 $ns = $this->mNamespace
== NS_MAIN ?
1405 wfMsg( 'nstab-main' ) : $this->getNsText();
1406 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1407 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1414 * Check CSS/JS sub-page permissions
1416 * @param $action String the action to check
1417 * @param $user User user to check
1418 * @param $errors Array list of current errors
1419 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1420 * @param $short Boolean short circuit on first error
1422 * @return Array list of errors
1424 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1425 # Protect css/js subpages of user pages
1426 # XXX: this might be better using restrictions
1427 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1428 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1429 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1430 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1431 $errors[] = array( 'customcssprotected' );
1432 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1433 $errors[] = array( 'customjsprotected' );
1441 * Check against page_restrictions table requirements on this
1442 * page. The user must possess all required rights for this
1445 * @param $action String the action to check
1446 * @param $user User user to check
1447 * @param $errors Array list of current errors
1448 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1449 * @param $short Boolean short circuit on first error
1451 * @return Array list of errors
1453 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1454 foreach ( $this->getRestrictions( $action ) as $right ) {
1455 // Backwards compatibility, rewrite sysop -> protect
1456 if ( $right == 'sysop' ) {
1459 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace
) ) {
1460 // Users with 'editprotected' permission can edit protected pages
1461 // without cascading option turned on.
1462 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected', $this->mNamespace
)
1463 ||
$this->mCascadeRestriction
)
1465 $errors[] = array( 'protectedpagetext', $right );
1474 * Check restrictions on cascading pages.
1476 * @param $action String the action to check
1477 * @param $user User to check
1478 * @param $errors Array list of current errors
1479 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1480 * @param $short Boolean short circuit on first error
1482 * @return Array list of errors
1484 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1485 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1486 # We /could/ use the protection level on the source page, but it's
1487 # fairly ugly as we have to establish a precedence hierarchy for pages
1488 # included by multiple cascade-protected pages. So just restrict
1489 # it to people with 'protect' permission, as they could remove the
1490 # protection anyway.
1491 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1492 # Cascading protection depends on more than this page...
1493 # Several cascading protected pages may include this page...
1494 # Check each cascading level
1495 # This is only for protection restrictions, not for all actions
1496 if ( isset( $restrictions[$action] ) ) {
1497 foreach ( $restrictions[$action] as $right ) {
1498 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1499 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace
) ) {
1501 foreach ( $cascadingSources as $page )
1502 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1503 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1513 * Check action permissions not already checked in checkQuickPermissions
1515 * @param $action String the action to check
1516 * @param $user User to check
1517 * @param $errors Array list of current errors
1518 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1519 * @param $short Boolean short circuit on first error
1521 * @return Array list of errors
1523 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1524 if ( $action == 'protect' ) {
1525 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1526 // If they can't edit, they shouldn't protect.
1527 $errors[] = array( 'protect-cantedit' );
1529 } elseif ( $action == 'create' ) {
1530 $title_protection = $this->getTitleProtection();
1531 if( $title_protection ) {
1532 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1533 $title_protection['pt_create_perm'] = 'protect'; // B/C
1535 if( $title_protection['pt_create_perm'] == '' ||
1536 !$user->isAllowed( $title_protection['pt_create_perm'],
1537 $this->mNamespace
) ) {
1538 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1541 } elseif ( $action == 'move' ) {
1542 // Check for immobile pages
1543 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1544 // Specific message for this case
1545 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1546 } elseif ( !$this->isMovable() ) {
1547 // Less specific message for rarer cases
1548 $errors[] = array( 'immobile-source-page' );
1550 } elseif ( $action == 'move-target' ) {
1551 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1552 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1553 } elseif ( !$this->isMovable() ) {
1554 $errors[] = array( 'immobile-target-page' );
1561 * Check that the user isn't blocked from editting.
1563 * @param $action String the action to check
1564 * @param $user User to check
1565 * @param $errors Array list of current errors
1566 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1567 * @param $short Boolean short circuit on first error
1569 * @return Array list of errors
1571 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1572 // Account creation blocks handled at userlogin.
1573 // Unblocking handled in SpecialUnblock
1574 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1578 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1580 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1581 $errors[] = array( 'confirmedittext' );
1584 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1585 // Don't block the user from editing their own talk page unless they've been
1586 // explicitly blocked from that too.
1587 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1588 $block = $user->mBlock
;
1590 // This is from OutputPage::blockedPage
1591 // Copied at r23888 by werdna
1593 $id = $user->blockedBy();
1594 $reason = $user->blockedFor();
1595 if ( $reason == '' ) {
1596 $reason = wfMsg( 'blockednoreason' );
1598 $ip = $user->getRequest()->getIP();
1600 if ( is_numeric( $id ) ) {
1601 $name = User
::whoIs( $id );
1606 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1607 $blockid = $block->getId();
1608 $blockExpiry = $user->mBlock
->mExpiry
;
1609 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1610 if ( $blockExpiry == 'infinity' ) {
1611 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1613 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1616 $intended = strval( $user->mBlock
->getTarget() );
1618 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1619 $blockid, $blockExpiry, $intended, $blockTimestamp );
1626 * Check that the user is allowed to read this page.
1628 * @param $action String the action to check
1629 * @param $user User to check
1630 * @param $errors Array list of current errors
1631 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1632 * @param $short Boolean short circuit on first error
1634 * @return Array list of errors
1636 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1637 static $useShortcut = null;
1639 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1640 if ( is_null( $useShortcut ) ) {
1641 global $wgGroupPermissions, $wgRevokePermissions;
1642 $useShortcut = true;
1643 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1644 # Not a public wiki, so no shortcut
1645 $useShortcut = false;
1646 } elseif ( !empty( $wgRevokePermissions ) ) {
1648 * Iterate through each group with permissions being revoked (key not included since we don't care
1649 * what the group name is), then check if the read permission is being revoked. If it is, then
1650 * we don't use the shortcut below since the user might not be able to read, even though anon
1651 * reading is allowed.
1653 foreach ( $wgRevokePermissions as $perms ) {
1654 if ( !empty( $perms['read'] ) ) {
1655 # We might be removing the read right from the user, so no shortcut
1656 $useShortcut = false;
1663 # Shortcut for public wikis, allows skipping quite a bit of code
1664 if ( $useShortcut ) {
1668 # If the user is allowed to read pages, he is allowed to read all pages
1669 if ( $user->isAllowed( 'read', $this->mNamespace
) ) {
1673 # Always grant access to the login page.
1674 # Even anons need to be able to log in.
1675 if ( $this->isSpecial( 'Userlogin' )
1676 ||
$this->isSpecial( 'ChangePassword' )
1677 ||
$this->isSpecial( 'PasswordReset' )
1682 # Time to check the whitelist
1683 global $wgWhitelistRead;
1685 # Only to these checks is there's something to check against
1686 if ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
1687 # Check for explicit whitelisting
1688 $name = $this->getPrefixedText();
1689 $dbName = $this->getPrefixedDBKey();
1691 // Check with and without underscores
1692 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
1696 # Old settings might have the title prefixed with
1697 # a colon for main-namespace pages
1698 if ( $this->getNamespace() == NS_MAIN
) {
1699 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1704 # If it's a special page, ditch the subpage bit and check again
1705 if ( $this->isSpecialPage() ) {
1706 $name = $this->getDBkey();
1707 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
1708 if ( $name !== false ) {
1709 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1710 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1717 $errors[] = $this->missingPermissionError( $action, $short );
1722 * Get a description array when the user doesn't have the right to perform
1723 * $action (i.e. when User::isAllowed() returns false)
1725 * @param $action String the action to check
1726 * @param $short Boolean short circuit on first error
1727 * @return Array list of errors
1729 private function missingPermissionError( $action, $short ) {
1730 // We avoid expensive display logic for quickUserCan's and such
1732 return array( 'badaccess-group0' );
1735 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1736 User
::getGroupsWithPermission( $action, $this->mNamespace
) );
1738 if ( count( $groups ) ) {
1742 $wgLang->commaList( $groups ),
1746 return array( 'badaccess-group0' );
1751 * Can $user perform $action on this page? This is an internal function,
1752 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1753 * checks on wfReadOnly() and blocks)
1755 * @param $action String action that permission needs to be checked for
1756 * @param $user User to check
1757 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1758 * @param $short Bool Set this to true to stop after the first permission error.
1759 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1761 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1762 wfProfileIn( __METHOD__
);
1764 # Read has special handling
1765 if ( $action == 'read' ) {
1767 'checkPermissionHooks',
1768 'checkReadPermissions',
1772 'checkQuickPermissions',
1773 'checkPermissionHooks',
1774 'checkSpecialsAndNSPermissions',
1775 'checkCSSandJSPermissions',
1776 'checkPageRestrictions',
1777 'checkCascadingSourcesRestrictions',
1778 'checkActionPermissions',
1784 while( count( $checks ) > 0 &&
1785 !( $short && count( $errors ) > 0 ) ) {
1786 $method = array_shift( $checks );
1787 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1790 wfProfileOut( __METHOD__
);
1795 * Is this title subject to title protection?
1796 * Title protection is the one applied against creation of such title.
1798 * @return Mixed An associative array representing any existent title
1799 * protection, or false if there's none.
1801 private function getTitleProtection() {
1802 // Can't protect pages in special namespaces
1803 if ( $this->getNamespace() < 0 ) {
1807 // Can't protect pages that exist.
1808 if ( $this->exists() ) {
1812 if ( !isset( $this->mTitleProtection
) ) {
1813 $dbr = wfGetDB( DB_SLAVE
);
1814 $res = $dbr->select( 'protected_titles', '*',
1815 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1818 // fetchRow returns false if there are no rows.
1819 $this->mTitleProtection
= $dbr->fetchRow( $res );
1821 return $this->mTitleProtection
;
1825 * Update the title protection status
1827 * @param $create_perm String Permission required for creation
1828 * @param $reason String Reason for protection
1829 * @param $expiry String Expiry timestamp
1830 * @return boolean true
1832 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1833 global $wgUser, $wgContLang;
1835 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1836 && $expiry == $this->mRestrictionsExpiry
['create'] ) {
1841 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1843 $dbw = wfGetDB( DB_MASTER
);
1845 $encodedExpiry = $dbw->encodeExpiry( $expiry );
1847 $expiry_description = '';
1848 if ( $encodedExpiry != $dbw->getInfinity() ) {
1849 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1850 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1852 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1855 # Update protection table
1856 if ( $create_perm != '' ) {
1857 $this->mTitleProtection
= array(
1858 'pt_namespace' => $namespace,
1859 'pt_title' => $title,
1860 'pt_create_perm' => $create_perm,
1861 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1862 'pt_expiry' => $encodedExpiry,
1863 'pt_user' => $wgUser->getId(),
1864 'pt_reason' => $reason,
1866 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1867 $this->mTitleProtection
, __METHOD__
);
1869 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1870 'pt_title' => $title ), __METHOD__
);
1871 $this->mTitleProtection
= false;
1874 # Update the protection log
1875 if ( $dbw->affectedRows() ) {
1876 $log = new LogPage( 'protect' );
1878 if ( $create_perm ) {
1879 $params = array( "[create=$create_perm] $expiry_description", '' );
1880 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1882 $log->addEntry( 'unprotect', $this, $reason );
1890 * Remove any title protection due to page existing
1892 public function deleteTitleProtection() {
1893 $dbw = wfGetDB( DB_MASTER
);
1897 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1900 $this->mTitleProtection
= false;
1904 * Would anybody with sufficient privileges be able to move this page?
1905 * Some pages just aren't movable.
1907 * @return Bool TRUE or FALSE
1909 public function isMovable() {
1910 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
1911 // Interwiki title or immovable namespace. Hooks don't get to override here
1916 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
1921 * Is this the mainpage?
1922 * @note Title::newFromText seams to be sufficiently optimized by the title
1923 * cache that we don't need to over-optimize by doing direct comparisons and
1924 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1925 * ends up reporting something differently than $title->isMainPage();
1930 public function isMainPage() {
1931 return $this->equals( Title
::newMainPage() );
1935 * Is this a talk page of some sort?
1939 public function isTalkPage() {
1940 return MWNamespace
::isTalk( $this->getNamespace() );
1944 * Is this a subpage?
1948 public function isSubpage() {
1949 return MWNamespace
::hasSubpages( $this->mNamespace
)
1950 ?
strpos( $this->getText(), '/' ) !== false
1955 * Returns true if the title is inside the specified namespace.
1957 * Please make use of this instead of comparing to getNamespace()
1958 * This function is much more resistant to changes we may make
1959 * to namespaces than code that makes direct comparisons.
1960 * @param $ns int The namespace
1964 public function inNamespace( $ns ) {
1965 return MWNamespace
::equals( $this->getNamespace(), $ns );
1969 * Returns true if the title is inside one of the specified namespaces.
1971 * @param ...$namespaces The namespaces to check for
1975 public function inNamespaces( /* ... */ ) {
1976 $namespaces = func_get_args();
1977 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1978 $namespaces = $namespaces[0];
1981 foreach ( $namespaces as $ns ) {
1982 if ( $this->inNamespace( $ns ) ) {
1991 * Returns true if the title has the same subject namespace as the
1992 * namespace specified.
1993 * For example this method will take NS_USER and return true if namespace
1994 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1995 * as their subject namespace.
1997 * This is MUCH simpler than individually testing for equivilance
1998 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
2001 public function hasSubjectNamespace( $ns ) {
2002 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
2006 * Does this have subpages? (Warning, usually requires an extra DB query.)
2010 public function hasSubpages() {
2011 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2016 # We dynamically add a member variable for the purpose of this method
2017 # alone to cache the result. There's no point in having it hanging
2018 # around uninitialized in every Title object; therefore we only add it
2019 # if needed and don't declare it statically.
2020 if ( isset( $this->mHasSubpages
) ) {
2021 return $this->mHasSubpages
;
2024 $subpages = $this->getSubpages( 1 );
2025 if ( $subpages instanceof TitleArray
) {
2026 return $this->mHasSubpages
= (bool)$subpages->count();
2028 return $this->mHasSubpages
= false;
2032 * Get all subpages of this page.
2034 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2035 * @return mixed TitleArray, or empty array if this page's namespace
2036 * doesn't allow subpages
2038 public function getSubpages( $limit = -1 ) {
2039 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2043 $dbr = wfGetDB( DB_SLAVE
);
2044 $conds['page_namespace'] = $this->getNamespace();
2045 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2047 if ( $limit > -1 ) {
2048 $options['LIMIT'] = $limit;
2050 return $this->mSubpages
= TitleArray
::newFromResult(
2051 $dbr->select( 'page',
2052 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2061 * Does that page contain wikitext, or it is JS, CSS or whatever?
2065 public function isWikitextPage() {
2066 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
2067 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
2072 * Could this page contain custom CSS or JavaScript, based
2077 public function isCssOrJsPage() {
2078 $retval = $this->mNamespace
== NS_MEDIAWIKI
2079 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
2080 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
2085 * Is this a .css or .js subpage of a user page?
2088 public function isCssJsSubpage() {
2089 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
2093 * Is this a *valid* .css or .js subpage of a user page?
2096 * @deprecated since 1.17
2098 public function isValidCssJsSubpage() {
2099 return $this->isCssJsSubpage();
2103 * Trim down a .css or .js subpage title to get the corresponding skin name
2105 * @return string containing skin name from .css or .js subpage title
2107 public function getSkinFromCssJsSubpage() {
2108 $subpage = explode( '/', $this->mTextform
);
2109 $subpage = $subpage[ count( $subpage ) - 1 ];
2110 $lastdot = strrpos( $subpage, '.' );
2111 if ( $lastdot === false )
2112 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
2113 return substr( $subpage, 0, $lastdot );
2117 * Is this a .css subpage of a user page?
2121 public function isCssSubpage() {
2122 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
2126 * Is this a .js subpage of a user page?
2130 public function isJsSubpage() {
2131 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
2135 * Protect css subpages of user pages: can $wgUser edit
2138 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2141 public function userCanEditCssSubpage() {
2143 wfDeprecated( __METHOD__
);
2144 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2145 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2149 * Protect js subpages of user pages: can $wgUser edit
2152 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2155 public function userCanEditJsSubpage() {
2157 wfDeprecated( __METHOD__
);
2158 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2159 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2163 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2165 * @return Bool If the page is subject to cascading restrictions.
2167 public function isCascadeProtected() {
2168 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2169 return ( $sources > 0 );
2173 * Cascading protection: Get the source of any cascading restrictions on this page.
2175 * @param $getPages Bool Whether or not to retrieve the actual pages
2176 * that the restrictions have come from.
2177 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2178 * have come, false for none, or true if such restrictions exist, but $getPages
2179 * was not set. The restriction array is an array of each type, each of which
2180 * contains a array of unique groups.
2182 public function getCascadeProtectionSources( $getPages = true ) {
2184 $pagerestrictions = array();
2186 if ( isset( $this->mCascadeSources
) && $getPages ) {
2187 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2188 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2189 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2192 wfProfileIn( __METHOD__
);
2194 $dbr = wfGetDB( DB_SLAVE
);
2196 if ( $this->getNamespace() == NS_FILE
) {
2197 $tables = array( 'imagelinks', 'page_restrictions' );
2198 $where_clauses = array(
2199 'il_to' => $this->getDBkey(),
2204 $tables = array( 'templatelinks', 'page_restrictions' );
2205 $where_clauses = array(
2206 'tl_namespace' => $this->getNamespace(),
2207 'tl_title' => $this->getDBkey(),
2214 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2215 'pr_expiry', 'pr_type', 'pr_level' );
2216 $where_clauses[] = 'page_id=pr_page';
2219 $cols = array( 'pr_expiry' );
2222 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2224 $sources = $getPages ?
array() : false;
2225 $now = wfTimestampNow();
2226 $purgeExpired = false;
2228 foreach ( $res as $row ) {
2229 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2230 if ( $expiry > $now ) {
2232 $page_id = $row->pr_page
;
2233 $page_ns = $row->page_namespace
;
2234 $page_title = $row->page_title
;
2235 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2236 # Add groups needed for each restriction type if its not already there
2237 # Make sure this restriction type still exists
2239 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2240 $pagerestrictions[$row->pr_type
] = array();
2243 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2244 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2245 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2251 // Trigger lazy purge of expired restrictions from the db
2252 $purgeExpired = true;
2255 if ( $purgeExpired ) {
2256 Title
::purgeExpiredRestrictions();
2260 $this->mCascadeSources
= $sources;
2261 $this->mCascadingRestrictions
= $pagerestrictions;
2263 $this->mHasCascadingRestrictions
= $sources;
2266 wfProfileOut( __METHOD__
);
2267 return array( $sources, $pagerestrictions );
2271 * Returns cascading restrictions for the current article
2275 function areRestrictionsCascading() {
2276 if ( !$this->mRestrictionsLoaded
) {
2277 $this->loadRestrictions();
2280 return $this->mCascadeRestriction
;
2284 * Loads a string into mRestrictions array
2286 * @param $res Resource restrictions as an SQL result.
2287 * @param $oldFashionedRestrictions String comma-separated list of page
2288 * restrictions from page table (pre 1.10)
2290 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2293 foreach ( $res as $row ) {
2297 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2301 * Compiles list of active page restrictions from both page table (pre 1.10)
2302 * and page_restrictions table for this existing page.
2303 * Public for usage by LiquidThreads.
2305 * @param $rows array of db result objects
2306 * @param $oldFashionedRestrictions string comma-separated list of page
2307 * restrictions from page table (pre 1.10)
2309 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2311 $dbr = wfGetDB( DB_SLAVE
);
2313 $restrictionTypes = $this->getRestrictionTypes();
2315 foreach ( $restrictionTypes as $type ) {
2316 $this->mRestrictions
[$type] = array();
2317 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2320 $this->mCascadeRestriction
= false;
2322 # Backwards-compatibility: also load the restrictions from the page record (old format).
2324 if ( $oldFashionedRestrictions === null ) {
2325 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2326 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2329 if ( $oldFashionedRestrictions != '' ) {
2331 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2332 $temp = explode( '=', trim( $restrict ) );
2333 if ( count( $temp ) == 1 ) {
2334 // old old format should be treated as edit/move restriction
2335 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2336 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2338 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2342 $this->mOldRestrictions
= true;
2346 if ( count( $rows ) ) {
2347 # Current system - load second to make them override.
2348 $now = wfTimestampNow();
2349 $purgeExpired = false;
2351 # Cycle through all the restrictions.
2352 foreach ( $rows as $row ) {
2354 // Don't take care of restrictions types that aren't allowed
2355 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2358 // This code should be refactored, now that it's being used more generally,
2359 // But I don't really see any harm in leaving it in Block for now -werdna
2360 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2362 // Only apply the restrictions if they haven't expired!
2363 if ( !$expiry ||
$expiry > $now ) {
2364 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2365 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2367 $this->mCascadeRestriction |
= $row->pr_cascade
;
2369 // Trigger a lazy purge of expired restrictions
2370 $purgeExpired = true;
2374 if ( $purgeExpired ) {
2375 Title
::purgeExpiredRestrictions();
2379 $this->mRestrictionsLoaded
= true;
2383 * Load restrictions from the page_restrictions table
2385 * @param $oldFashionedRestrictions String comma-separated list of page
2386 * restrictions from page table (pre 1.10)
2388 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2390 if ( !$this->mRestrictionsLoaded
) {
2391 if ( $this->exists() ) {
2392 $dbr = wfGetDB( DB_SLAVE
);
2394 $res = $dbr->select(
2395 'page_restrictions',
2397 array( 'pr_page' => $this->getArticleId() ),
2401 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2403 $title_protection = $this->getTitleProtection();
2405 if ( $title_protection ) {
2406 $now = wfTimestampNow();
2407 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2409 if ( !$expiry ||
$expiry > $now ) {
2410 // Apply the restrictions
2411 $this->mRestrictionsExpiry
['create'] = $expiry;
2412 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2413 } else { // Get rid of the old restrictions
2414 Title
::purgeExpiredRestrictions();
2415 $this->mTitleProtection
= false;
2418 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2420 $this->mRestrictionsLoaded
= true;
2426 * Purge expired restrictions from the page_restrictions table
2428 static function purgeExpiredRestrictions() {
2429 $dbw = wfGetDB( DB_MASTER
);
2431 'page_restrictions',
2432 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2438 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2444 * Accessor/initialisation for mRestrictions
2446 * @param $action String action that permission needs to be checked for
2447 * @return Array of Strings the array of groups allowed to edit this article
2449 public function getRestrictions( $action ) {
2450 if ( !$this->mRestrictionsLoaded
) {
2451 $this->loadRestrictions();
2453 return isset( $this->mRestrictions
[$action] )
2454 ?
$this->mRestrictions
[$action]
2459 * Get the expiry time for the restriction against a given action
2461 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2462 * or not protected at all, or false if the action is not recognised.
2464 public function getRestrictionExpiry( $action ) {
2465 if ( !$this->mRestrictionsLoaded
) {
2466 $this->loadRestrictions();
2468 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2472 * Is there a version of this page in the deletion archive?
2474 * @return Int the number of archived revisions
2476 public function isDeleted() {
2477 if ( $this->getNamespace() < 0 ) {
2480 $dbr = wfGetDB( DB_SLAVE
);
2482 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2483 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2486 if ( $this->getNamespace() == NS_FILE
) {
2487 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2488 array( 'fa_name' => $this->getDBkey() ),
2497 * Is there a version of this page in the deletion archive?
2501 public function isDeletedQuick() {
2502 if ( $this->getNamespace() < 0 ) {
2505 $dbr = wfGetDB( DB_SLAVE
);
2506 $deleted = (bool)$dbr->selectField( 'archive', '1',
2507 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2510 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2511 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2512 array( 'fa_name' => $this->getDBkey() ),
2520 * Get the article ID for this Title from the link cache,
2521 * adding it if necessary
2523 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2525 * @return Int the ID
2527 public function getArticleID( $flags = 0 ) {
2528 if ( $this->getNamespace() < 0 ) {
2529 return $this->mArticleID
= 0;
2531 $linkCache = LinkCache
::singleton();
2532 if ( $flags & self
::GAID_FOR_UPDATE
) {
2533 $oldUpdate = $linkCache->forUpdate( true );
2534 $linkCache->clearLink( $this );
2535 $this->mArticleID
= $linkCache->addLinkObj( $this );
2536 $linkCache->forUpdate( $oldUpdate );
2538 if ( -1 == $this->mArticleID
) {
2539 $this->mArticleID
= $linkCache->addLinkObj( $this );
2542 return $this->mArticleID
;
2546 * Is this an article that is a redirect page?
2547 * Uses link cache, adding it if necessary
2549 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2552 public function isRedirect( $flags = 0 ) {
2553 if ( !is_null( $this->mRedirect
) ) {
2554 return $this->mRedirect
;
2556 # Calling getArticleID() loads the field from cache as needed
2557 if ( !$this->getArticleID( $flags ) ) {
2558 return $this->mRedirect
= false;
2560 $linkCache = LinkCache
::singleton();
2561 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2563 return $this->mRedirect
;
2567 * What is the length of this page?
2568 * Uses link cache, adding it if necessary
2570 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2573 public function getLength( $flags = 0 ) {
2574 if ( $this->mLength
!= -1 ) {
2575 return $this->mLength
;
2577 # Calling getArticleID() loads the field from cache as needed
2578 if ( !$this->getArticleID( $flags ) ) {
2579 return $this->mLength
= 0;
2581 $linkCache = LinkCache
::singleton();
2582 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2584 return $this->mLength
;
2588 * What is the page_latest field for this page?
2590 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2591 * @return Int or 0 if the page doesn't exist
2593 public function getLatestRevID( $flags = 0 ) {
2594 if ( $this->mLatestID
!== false ) {
2595 return intval( $this->mLatestID
);
2597 # Calling getArticleID() loads the field from cache as needed
2598 if ( !$this->getArticleID( $flags ) ) {
2599 return $this->mLatestID
= 0;
2601 $linkCache = LinkCache
::singleton();
2602 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2604 return $this->mLatestID
;
2608 * This clears some fields in this object, and clears any associated
2609 * keys in the "bad links" section of the link cache.
2611 * - This is called from Article::doEdit() and Article::insertOn() to allow
2612 * loading of the new page_id. It's also called from
2613 * Article::doDeleteArticle()
2615 * @param $newid Int the new Article ID
2617 public function resetArticleID( $newid ) {
2618 $linkCache = LinkCache
::singleton();
2619 $linkCache->clearLink( $this );
2621 if ( $newid === false ) {
2622 $this->mArticleID
= -1;
2624 $this->mArticleID
= intval( $newid );
2626 $this->mRestrictionsLoaded
= false;
2627 $this->mRestrictions
= array();
2628 $this->mRedirect
= null;
2629 $this->mLength
= -1;
2630 $this->mLatestID
= false;
2634 * Updates page_touched for this page; called from LinksUpdate.php
2636 * @return Bool true if the update succeded
2638 public function invalidateCache() {
2639 if ( wfReadOnly() ) {
2642 $dbw = wfGetDB( DB_MASTER
);
2643 $success = $dbw->update(
2645 array( 'page_touched' => $dbw->timestamp() ),
2649 HTMLFileCache
::clearFileCache( $this );
2654 * Prefix some arbitrary text with the namespace or interwiki prefix
2657 * @param $name String the text
2658 * @return String the prefixed text
2661 private function prefix( $name ) {
2663 if ( $this->mInterwiki
!= '' ) {
2664 $p = $this->mInterwiki
. ':';
2667 if ( 0 != $this->mNamespace
) {
2668 $p .= $this->getNsText() . ':';
2674 * Returns a simple regex that will match on characters and sequences invalid in titles.
2675 * Note that this doesn't pick up many things that could be wrong with titles, but that
2676 * replacing this regex with something valid will make many titles valid.
2678 * @return String regex string
2680 static function getTitleInvalidRegex() {
2681 static $rxTc = false;
2683 # Matching titles will be held as illegal.
2685 # Any character not allowed is forbidden...
2686 '[^' . Title
::legalChars() . ']' .
2687 # URL percent encoding sequences interfere with the ability
2688 # to round-trip titles -- you can't link to them consistently.
2689 '|%[0-9A-Fa-f]{2}' .
2690 # XML/HTML character references produce similar issues.
2691 '|&[A-Za-z0-9\x80-\xff]+;' .
2693 '|&#x[0-9A-Fa-f]+;' .
2701 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2703 * @param $text String containing title to capitalize
2704 * @param $ns int namespace index, defaults to NS_MAIN
2705 * @return String containing capitalized title
2707 public static function capitalize( $text, $ns = NS_MAIN
) {
2710 if ( MWNamespace
::isCapitalized( $ns ) ) {
2711 return $wgContLang->ucfirst( $text );
2718 * Secure and split - main initialisation function for this object
2720 * Assumes that mDbkeyform has been set, and is urldecoded
2721 * and uses underscores, but not otherwise munged. This function
2722 * removes illegal characters, splits off the interwiki and
2723 * namespace prefixes, sets the other forms, and canonicalizes
2726 * @return Bool true on success
2728 private function secureAndSplit() {
2729 global $wgContLang, $wgLocalInterwiki;
2732 $this->mInterwiki
= $this->mFragment
= '';
2733 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2735 $dbkey = $this->mDbkeyform
;
2737 # Strip Unicode bidi override characters.
2738 # Sometimes they slip into cut-n-pasted page titles, where the
2739 # override chars get included in list displays.
2740 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2742 # Clean up whitespace
2743 # Note: use of the /u option on preg_replace here will cause
2744 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2745 # conveniently disabling them.
2746 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2747 $dbkey = trim( $dbkey, '_' );
2749 if ( $dbkey == '' ) {
2753 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2754 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2758 $this->mDbkeyform
= $dbkey;
2760 # Initial colon indicates main namespace rather than specified default
2761 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2762 if ( ':' == $dbkey[0] ) {
2763 $this->mNamespace
= NS_MAIN
;
2764 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2765 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2768 # Namespace or interwiki prefix
2770 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2773 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2775 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2776 # Ordinary namespace
2778 $this->mNamespace
= $ns;
2779 # For Talk:X pages, check if X has a "namespace" prefix
2780 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2781 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2782 # Disallow Talk:File:x type titles...
2784 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2785 # Disallow Talk:Interwiki:x type titles...
2789 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2790 if ( !$firstPass ) {
2791 # Can't make a local interwiki link to an interwiki link.
2792 # That's just crazy!
2798 $this->mInterwiki
= $wgContLang->lc( $p );
2800 # Redundant interwiki prefix to the local wiki
2801 if ( $wgLocalInterwiki !== false
2802 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
2804 if ( $dbkey == '' ) {
2805 # Can't have an empty self-link
2808 $this->mInterwiki
= '';
2810 # Do another namespace split...
2814 # If there's an initial colon after the interwiki, that also
2815 # resets the default namespace
2816 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2817 $this->mNamespace
= NS_MAIN
;
2818 $dbkey = substr( $dbkey, 1 );
2821 # If there's no recognized interwiki or namespace,
2822 # then let the colon expression be part of the title.
2827 # We already know that some pages won't be in the database!
2828 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2829 $this->mArticleID
= 0;
2831 $fragment = strstr( $dbkey, '#' );
2832 if ( false !== $fragment ) {
2833 $this->setFragment( $fragment );
2834 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2835 # remove whitespace again: prevents "Foo_bar_#"
2836 # becoming "Foo_bar_"
2837 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2840 # Reject illegal characters.
2841 $rxTc = self
::getTitleInvalidRegex();
2842 if ( preg_match( $rxTc, $dbkey ) ) {
2846 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2847 # reachable due to the way web browsers deal with 'relative' URLs.
2848 # Also, they conflict with subpage syntax. Forbid them explicitly.
2849 if ( strpos( $dbkey, '.' ) !== false &&
2850 ( $dbkey === '.' ||
$dbkey === '..' ||
2851 strpos( $dbkey, './' ) === 0 ||
2852 strpos( $dbkey, '../' ) === 0 ||
2853 strpos( $dbkey, '/./' ) !== false ||
2854 strpos( $dbkey, '/../' ) !== false ||
2855 substr( $dbkey, -2 ) == '/.' ||
2856 substr( $dbkey, -3 ) == '/..' ) )
2861 # Magic tilde sequences? Nu-uh!
2862 if ( strpos( $dbkey, '~~~' ) !== false ) {
2866 # Limit the size of titles to 255 bytes. This is typically the size of the
2867 # underlying database field. We make an exception for special pages, which
2868 # don't need to be stored in the database, and may edge over 255 bytes due
2869 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2870 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2871 strlen( $dbkey ) > 512 )
2876 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2877 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2878 # other site might be case-sensitive.
2879 $this->mUserCaseDBKey
= $dbkey;
2880 if ( $this->mInterwiki
== '' ) {
2881 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2884 # Can't make a link to a namespace alone... "empty" local links can only be
2885 # self-links with a fragment identifier.
2886 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
2890 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2891 // IP names are not allowed for accounts, and can only be referring to
2892 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2893 // there are numerous ways to present the same IP. Having sp:contribs scan
2894 // them all is silly and having some show the edits and others not is
2895 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2896 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
2897 ? IP
::sanitizeIP( $dbkey )
2900 // Any remaining initial :s are illegal.
2901 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
2906 $this->mDbkeyform
= $dbkey;
2907 $this->mUrlform
= wfUrlencode( $dbkey );
2909 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2915 * Set the fragment for this title. Removes the first character from the
2916 * specified fragment before setting, so it assumes you're passing it with
2919 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2920 * Still in active use privately.
2922 * @param $fragment String text
2924 public function setFragment( $fragment ) {
2925 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2929 * Get a Title object associated with the talk page of this article
2931 * @return Title the object for the talk page
2933 public function getTalkPage() {
2934 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2938 * Get a title object associated with the subject page of this
2941 * @return Title the object for the subject page
2943 public function getSubjectPage() {
2944 // Is this the same title?
2945 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2946 if ( $this->getNamespace() == $subjectNS ) {
2949 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2953 * Get an array of Title objects linking to this Title
2954 * Also stores the IDs in the link cache.
2956 * WARNING: do not use this function on arbitrary user-supplied titles!
2957 * On heavily-used templates it will max out the memory.
2959 * @param $options Array: may be FOR UPDATE
2960 * @param $table String: table name
2961 * @param $prefix String: fields prefix
2962 * @return Array of Title objects linking here
2964 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2965 $linkCache = LinkCache
::singleton();
2967 if ( count( $options ) > 0 ) {
2968 $db = wfGetDB( DB_MASTER
);
2970 $db = wfGetDB( DB_SLAVE
);
2974 array( 'page', $table ),
2975 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2977 "{$prefix}_from=page_id",
2978 "{$prefix}_namespace" => $this->getNamespace(),
2979 "{$prefix}_title" => $this->getDBkey() ),
2985 if ( $db->numRows( $res ) ) {
2986 foreach ( $res as $row ) {
2987 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
2989 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
2990 $retVal[] = $titleObj;
2998 * Get an array of Title objects using this Title as a template
2999 * Also stores the IDs in the link cache.
3001 * WARNING: do not use this function on arbitrary user-supplied titles!
3002 * On heavily-used templates it will max out the memory.
3004 * @param $options Array: may be FOR UPDATE
3005 * @return Array of Title the Title objects linking here
3007 public function getTemplateLinksTo( $options = array() ) {
3008 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3012 * Get an array of Title objects referring to non-existent articles linked from this page
3014 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3015 * @return Array of Title the Title objects
3017 public function getBrokenLinksFrom() {
3018 if ( $this->getArticleId() == 0 ) {
3019 # All links from article ID 0 are false positives
3023 $dbr = wfGetDB( DB_SLAVE
);
3024 $res = $dbr->select(
3025 array( 'page', 'pagelinks' ),
3026 array( 'pl_namespace', 'pl_title' ),
3028 'pl_from' => $this->getArticleId(),
3029 'page_namespace IS NULL'
3031 __METHOD__
, array(),
3035 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3041 foreach ( $res as $row ) {
3042 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3049 * Get a list of URLs to purge from the Squid cache when this
3052 * @return Array of String the URLs
3054 public function getSquidURLs() {
3058 $this->getInternalURL(),
3059 $this->getInternalURL( 'action=history' )
3062 // purge variant urls as well
3063 if ( $wgContLang->hasVariants() ) {
3064 $variants = $wgContLang->getVariants();
3065 foreach ( $variants as $vCode ) {
3066 $urls[] = $this->getInternalURL( '', $vCode );
3074 * Purge all applicable Squid URLs
3076 public function purgeSquid() {
3078 if ( $wgUseSquid ) {
3079 $urls = $this->getSquidURLs();
3080 $u = new SquidUpdate( $urls );
3086 * Move this page without authentication
3088 * @param $nt Title the new page Title
3089 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3091 public function moveNoAuth( &$nt ) {
3092 return $this->moveTo( $nt, false );
3096 * Check whether a given move operation would be valid.
3097 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3099 * @param $nt Title the new title
3100 * @param $auth Bool indicates whether $wgUser's permissions
3102 * @param $reason String is the log summary of the move, used for spam checking
3103 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3105 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3110 // Normally we'd add this to $errors, but we'll get
3111 // lots of syntax errors if $nt is not an object
3112 return array( array( 'badtitletext' ) );
3114 if ( $this->equals( $nt ) ) {
3115 $errors[] = array( 'selfmove' );
3117 if ( !$this->isMovable() ) {
3118 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3120 if ( $nt->getInterwiki() != '' ) {
3121 $errors[] = array( 'immobile-target-namespace-iw' );
3123 if ( !$nt->isMovable() ) {
3124 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3127 $oldid = $this->getArticleID();
3128 $newid = $nt->getArticleID();
3130 if ( strlen( $nt->getDBkey() ) < 1 ) {
3131 $errors[] = array( 'articleexists' );
3133 if ( ( $this->getDBkey() == '' ) ||
3135 ( $nt->getDBkey() == '' ) ) {
3136 $errors[] = array( 'badarticleerror' );
3139 // Image-specific checks
3140 if ( $this->getNamespace() == NS_FILE
) {
3141 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3144 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3145 $errors[] = array( 'nonfile-cannot-move-to-file' );
3149 $errors = wfMergeErrorArrays( $errors,
3150 $this->getUserPermissionsErrors( 'move', $wgUser ),
3151 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3152 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3153 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3156 $match = EditPage
::matchSummarySpamRegex( $reason );
3157 if ( $match !== false ) {
3158 // This is kind of lame, won't display nice
3159 $errors[] = array( 'spamprotectiontext' );
3163 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3164 $errors[] = array( 'hookaborted', $err );
3167 # The move is allowed only if (1) the target doesn't exist, or
3168 # (2) the target is a redirect to the source, and has no history
3169 # (so we can undo bad moves right after they're done).
3171 if ( 0 != $newid ) { # Target exists; check for validity
3172 if ( !$this->isValidMoveTarget( $nt ) ) {
3173 $errors[] = array( 'articleexists' );
3176 $tp = $nt->getTitleProtection();
3177 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3178 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3179 $errors[] = array( 'cantmove-titleprotected' );
3182 if ( empty( $errors ) ) {
3189 * Check if the requested move target is a valid file move target
3190 * @param Title $nt Target title
3191 * @return array List of errors
3193 protected function validateFileMoveOperation( $nt ) {
3198 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3200 $file = wfLocalFile( $this );
3201 if ( $file->exists() ) {
3202 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3203 $errors[] = array( 'imageinvalidfilename' );
3205 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3206 $errors[] = array( 'imagetypemismatch' );
3210 if ( $nt->getNamespace() != NS_FILE
) {
3211 $errors[] = array( 'imagenocrossnamespace' );
3212 // From here we want to do checks on a file object, so if we can't
3213 // create one, we must return.
3217 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3219 $destFile = wfLocalFile( $nt );
3220 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3221 $errors[] = array( 'file-exists-sharedrepo' );
3228 * Move a title to a new location
3230 * @param $nt Title the new title
3231 * @param $auth Bool indicates whether $wgUser's permissions
3233 * @param $reason String the reason for the move
3234 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3235 * Ignored if the user doesn't have the suppressredirect right.
3236 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3238 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3240 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3241 if ( is_array( $err ) ) {
3242 // Auto-block user's IP if the account was "hard" blocked
3243 $wgUser->spreadAnyEditBlock();
3247 // If it is a file, move it first.
3248 // It is done before all other moving stuff is done because it's hard to revert.
3249 $dbw = wfGetDB( DB_MASTER
);
3250 if ( $this->getNamespace() == NS_FILE
) {
3251 $file = wfLocalFile( $this );
3252 if ( $file->exists() ) {
3253 $status = $file->move( $nt );
3254 if ( !$status->isOk() ) {
3255 return $status->getErrorsArray();
3259 // Clear RepoGroup process cache
3260 RepoGroup
::singleton()->clearCache( $this );
3261 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3263 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3264 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3265 $protected = $this->isProtected();
3266 $pageCountChange = ( $createRedirect ?
1 : 0 ) - ( $nt->exists() ?
1 : 0 );
3268 // Do the actual move
3269 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3270 if ( is_array( $err ) ) {
3271 # @todo FIXME: What about the File we have already moved?
3276 $redirid = $this->getArticleID();
3278 // Refresh the sortkey for this row. Be careful to avoid resetting
3279 // cl_timestamp, which may disturb time-based lists on some sites.
3280 $prefixes = $dbw->select(
3282 array( 'cl_sortkey_prefix', 'cl_to' ),
3283 array( 'cl_from' => $pageid ),
3286 foreach ( $prefixes as $prefixRow ) {
3287 $prefix = $prefixRow->cl_sortkey_prefix
;
3288 $catTo = $prefixRow->cl_to
;
3289 $dbw->update( 'categorylinks',
3291 'cl_sortkey' => Collation
::singleton()->getSortKey(
3292 $nt->getCategorySortkey( $prefix ) ),
3293 'cl_timestamp=cl_timestamp' ),
3295 'cl_from' => $pageid,
3296 'cl_to' => $catTo ),
3302 # Protect the redirect title as the title used to be...
3303 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3305 'pr_page' => $redirid,
3306 'pr_type' => 'pr_type',
3307 'pr_level' => 'pr_level',
3308 'pr_cascade' => 'pr_cascade',
3309 'pr_user' => 'pr_user',
3310 'pr_expiry' => 'pr_expiry'
3312 array( 'pr_page' => $pageid ),
3316 # Update the protection log
3317 $log = new LogPage( 'protect' );
3318 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3320 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3322 // @todo FIXME: $params?
3323 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3327 $oldnamespace = $this->getNamespace() & ~
1;
3328 $newnamespace = $nt->getNamespace() & ~
1;
3329 $oldtitle = $this->getDBkey();
3330 $newtitle = $nt->getDBkey();
3332 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3333 WatchedItem
::duplicateEntries( $this, $nt );
3336 # Update search engine
3337 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3339 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3345 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3346 # No longer a content page
3347 # Not viewed, edited, removing
3348 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3349 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3350 # Now a content page
3351 # Not viewed, edited, adding
3352 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
3353 } elseif ( $pageCountChange ) {
3355 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3364 # Update message cache for interface messages
3365 if ( $this->getNamespace() == NS_MEDIAWIKI
) {
3366 # @bug 17860: old article can be deleted, if this the case,
3367 # delete it from message cache
3368 if ( $this->getArticleID() === 0 ) {
3369 MessageCache
::singleton()->replace( $this->getDBkey(), false );
3371 $rev = Revision
::newFromTitle( $this );
3372 MessageCache
::singleton()->replace( $this->getDBkey(), $rev->getText() );
3375 if ( $nt->getNamespace() == NS_MEDIAWIKI
) {
3376 $rev = Revision
::newFromTitle( $nt );
3377 MessageCache
::singleton()->replace( $nt->getDBkey(), $rev->getText() );
3380 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3385 * Move page to a title which is either a redirect to the
3386 * source page or nonexistent
3388 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3389 * @param $reason String The reason for the move
3390 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3391 * if the user doesn't have the suppressredirect right
3393 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3394 global $wgUser, $wgContLang;
3396 if ( $nt->exists() ) {
3397 $moveOverRedirect = true;
3398 $logType = 'move_redir';
3400 $moveOverRedirect = false;
3404 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3406 $logEntry = new ManualLogEntry( 'move', $logType );
3407 $logEntry->setPerformer( $wgUser );
3408 $logEntry->setTarget( $this );
3409 $logEntry->setComment( $reason );
3410 $logEntry->setParameters( array(
3411 '4::target' => $nt->getPrefixedText(),
3412 '5::noredir' => $redirectSuppressed ?
'1': '0',
3415 $formatter = LogFormatter
::newFromEntry( $logEntry );
3416 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3417 $comment = $formatter->getPlainActionText();
3419 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3421 # Truncate for whole multibyte characters.
3422 $comment = $wgContLang->truncate( $comment, 255 );
3424 $oldid = $this->getArticleID();
3425 $latest = $this->getLatestRevID();
3427 $dbw = wfGetDB( DB_MASTER
);
3429 if ( $moveOverRedirect ) {
3430 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3432 $newid = $nt->getArticleID();
3433 $newns = $nt->getNamespace();
3434 $newdbk = $nt->getDBkey();
3436 # Delete the old redirect. We don't save it to history since
3437 # by definition if we've got here it's rather uninteresting.
3438 # We have to remove it so that the next step doesn't trigger
3439 # a conflict on the unique namespace+title index...
3440 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3441 if ( !$dbw->cascadingDeletes() ) {
3442 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3444 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3445 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3446 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3447 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3448 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3449 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3450 $dbw->delete( 'iwlinks', array( 'iwl_from' => $newid ), __METHOD__
);
3451 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3452 $dbw->delete( 'page_props', array( 'pp_page' => $newid ), __METHOD__
);
3454 // If the target page was recently created, it may have an entry in recentchanges still
3455 $dbw->delete( 'recentchanges',
3456 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3461 # Save a null revision in the page's history notifying of the move
3462 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3463 if ( !is_object( $nullRevision ) ) {
3464 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3466 $nullRevId = $nullRevision->insertOn( $dbw );
3468 $now = wfTimestampNow();
3469 # Change the name of the target page:
3470 $dbw->update( 'page',
3472 'page_touched' => $dbw->timestamp( $now ),
3473 'page_namespace' => $nt->getNamespace(),
3474 'page_title' => $nt->getDBkey(),
3475 'page_latest' => $nullRevId,
3477 /* WHERE */ array( 'page_id' => $oldid ),
3480 $nt->resetArticleID( $oldid );
3482 $article = WikiPage
::factory( $nt );
3483 wfRunHooks( 'NewRevisionFromEditComplete',
3484 array( $article, $nullRevision, $latest, $wgUser ) );
3485 $article->setCachedLastEditTime( $now );
3487 # Recreate the redirect, this time in the other direction.
3488 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3489 $mwRedir = MagicWord
::get( 'redirect' );
3490 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3491 $redirectArticle = WikiPage
::factory( $this );
3492 $newid = $redirectArticle->insertOn( $dbw );
3493 if ( $newid ) { // sanity
3494 $redirectRevision = new Revision( array(
3496 'comment' => $comment,
3497 'text' => $redirectText ) );
3498 $redirectRevision->insertOn( $dbw );
3499 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3501 wfRunHooks( 'NewRevisionFromEditComplete',
3502 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3504 # Now, we record the link from the redirect to the new title.
3505 # It should have no other outgoing links...
3506 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3507 $dbw->insert( 'pagelinks',
3509 'pl_from' => $newid,
3510 'pl_namespace' => $nt->getNamespace(),
3511 'pl_title' => $nt->getDBkey() ),
3515 $this->resetArticleID( 0 );
3519 $logid = $logEntry->insert();
3520 $logEntry->publish( $logid );
3522 # Purge caches for old and new titles
3523 if ( $moveOverRedirect ) {
3524 # A simple purge is enough when moving over a redirect
3527 # Purge caches as per article creation, including any pages that link to this title
3528 Article
::onArticleCreate( $nt );
3530 $this->purgeSquid();
3534 * Move this page's subpages to be subpages of $nt
3536 * @param $nt Title Move target
3537 * @param $auth bool Whether $wgUser's permissions should be checked
3538 * @param $reason string The reason for the move
3539 * @param $createRedirect bool Whether to create redirects from the old subpages to
3540 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3541 * @return mixed array with old page titles as keys, and strings (new page titles) or
3542 * arrays (errors) as values, or an error array with numeric indices if no pages
3545 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3546 global $wgMaximumMovedPages;
3547 // Check permissions
3548 if ( !$this->userCan( 'move-subpages' ) ) {
3549 return array( 'cant-move-subpages' );
3551 // Do the source and target namespaces support subpages?
3552 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3553 return array( 'namespace-nosubpages',
3554 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3556 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3557 return array( 'namespace-nosubpages',
3558 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3561 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3564 foreach ( $subpages as $oldSubpage ) {
3566 if ( $count > $wgMaximumMovedPages ) {
3567 $retval[$oldSubpage->getPrefixedTitle()] =
3568 array( 'movepage-max-pages',
3569 $wgMaximumMovedPages );
3573 // We don't know whether this function was called before
3574 // or after moving the root page, so check both
3576 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3577 $oldSubpage->getArticleID() == $nt->getArticleId() )
3579 // When moving a page to a subpage of itself,
3580 // don't move it twice
3583 $newPageName = preg_replace(
3584 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3585 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3586 $oldSubpage->getDBkey() );
3587 if ( $oldSubpage->isTalkPage() ) {
3588 $newNs = $nt->getTalkPage()->getNamespace();
3590 $newNs = $nt->getSubjectPage()->getNamespace();
3592 # Bug 14385: we need makeTitleSafe because the new page names may
3593 # be longer than 255 characters.
3594 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3596 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3597 if ( $success === true ) {
3598 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3600 $retval[$oldSubpage->getPrefixedText()] = $success;
3607 * Checks if this page is just a one-rev redirect.
3608 * Adds lock, so don't use just for light purposes.
3612 public function isSingleRevRedirect() {
3613 $dbw = wfGetDB( DB_MASTER
);
3615 $row = $dbw->selectRow( 'page',
3616 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3619 array( 'FOR UPDATE' )
3621 # Cache some fields we may want
3622 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3623 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3624 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3625 if ( !$this->mRedirect
) {
3628 # Does the article have a history?
3629 $row = $dbw->selectField( array( 'page', 'revision' ),
3631 array( 'page_namespace' => $this->getNamespace(),
3632 'page_title' => $this->getDBkey(),
3634 'page_latest != rev_id'
3637 array( 'FOR UPDATE' )
3639 # Return true if there was no history
3640 return ( $row === false );
3644 * Checks if $this can be moved to a given Title
3645 * - Selects for update, so don't call it unless you mean business
3647 * @param $nt Title the new title to check
3650 public function isValidMoveTarget( $nt ) {
3651 # Is it an existing file?
3652 if ( $nt->getNamespace() == NS_FILE
) {
3653 $file = wfLocalFile( $nt );
3654 if ( $file->exists() ) {
3655 wfDebug( __METHOD__
. ": file exists\n" );
3659 # Is it a redirect with no history?
3660 if ( !$nt->isSingleRevRedirect() ) {
3661 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3664 # Get the article text
3665 $rev = Revision
::newFromTitle( $nt );
3666 if( !is_object( $rev ) ){
3669 $text = $rev->getText();
3670 # Does the redirect point to the source?
3671 # Or is it a broken self-redirect, usually caused by namespace collisions?
3673 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3674 $redirTitle = Title
::newFromText( $m[1] );
3675 if ( !is_object( $redirTitle ) ||
3676 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3677 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3678 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3683 wfDebug( __METHOD__
. ": failsafe\n" );
3690 * Can this title be added to a user's watchlist?
3692 * @return Bool TRUE or FALSE
3694 public function isWatchable() {
3695 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3699 * Get categories to which this Title belongs and return an array of
3700 * categories' names.
3702 * @return Array of parents in the form:
3703 * $parent => $currentarticle
3705 public function getParentCategories() {
3710 $titleKey = $this->getArticleId();
3712 if ( $titleKey === 0 ) {
3716 $dbr = wfGetDB( DB_SLAVE
);
3718 $res = $dbr->select( 'categorylinks', '*',
3720 'cl_from' => $titleKey,
3726 if ( $dbr->numRows( $res ) > 0 ) {
3727 foreach ( $res as $row ) {
3728 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3729 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3736 * Get a tree of parent categories
3738 * @param $children Array with the children in the keys, to check for circular refs
3739 * @return Array Tree of parent categories
3741 public function getParentCategoryTree( $children = array() ) {
3743 $parents = $this->getParentCategories();
3746 foreach ( $parents as $parent => $current ) {
3747 if ( array_key_exists( $parent, $children ) ) {
3748 # Circular reference
3749 $stack[$parent] = array();
3751 $nt = Title
::newFromText( $parent );
3753 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3763 * Get an associative array for selecting this title from
3766 * @return Array suitable for the $where parameter of DB::select()
3768 public function pageCond() {
3769 if ( $this->mArticleID
> 0 ) {
3770 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3771 return array( 'page_id' => $this->mArticleID
);
3773 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3778 * Get the revision ID of the previous revision
3780 * @param $revId Int Revision ID. Get the revision that was before this one.
3781 * @param $flags Int Title::GAID_FOR_UPDATE
3782 * @return Int|Bool Old revision ID, or FALSE if none exists
3784 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3785 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3786 return $db->selectField( 'revision', 'rev_id',
3788 'rev_page' => $this->getArticleId( $flags ),
3789 'rev_id < ' . intval( $revId )
3792 array( 'ORDER BY' => 'rev_id DESC' )
3797 * Get the revision ID of the next revision
3799 * @param $revId Int Revision ID. Get the revision that was after this one.
3800 * @param $flags Int Title::GAID_FOR_UPDATE
3801 * @return Int|Bool Next revision ID, or FALSE if none exists
3803 public function getNextRevisionID( $revId, $flags = 0 ) {
3804 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3805 return $db->selectField( 'revision', 'rev_id',
3807 'rev_page' => $this->getArticleId( $flags ),
3808 'rev_id > ' . intval( $revId )
3811 array( 'ORDER BY' => 'rev_id' )
3816 * Get the first revision of the page
3818 * @param $flags Int Title::GAID_FOR_UPDATE
3819 * @return Revision|Null if page doesn't exist
3821 public function getFirstRevision( $flags = 0 ) {
3822 $pageId = $this->getArticleId( $flags );
3824 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3825 $row = $db->selectRow( 'revision', '*',
3826 array( 'rev_page' => $pageId ),
3828 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3831 return new Revision( $row );
3838 * Get the oldest revision timestamp of this page
3840 * @param $flags Int Title::GAID_FOR_UPDATE
3841 * @return String: MW timestamp
3843 public function getEarliestRevTime( $flags = 0 ) {
3844 $rev = $this->getFirstRevision( $flags );
3845 return $rev ?
$rev->getTimestamp() : null;
3849 * Check if this is a new page
3853 public function isNewPage() {
3854 $dbr = wfGetDB( DB_SLAVE
);
3855 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3859 * Get the number of revisions between the given revision.
3860 * Used for diffs and other things that really need it.
3862 * @param $old int|Revision Old revision or rev ID (first before range)
3863 * @param $new int|Revision New revision or rev ID (first after range)
3864 * @return Int Number of revisions between these revisions.
3866 public function countRevisionsBetween( $old, $new ) {
3867 if ( !( $old instanceof Revision
) ) {
3868 $old = Revision
::newFromTitle( $this, (int)$old );
3870 if ( !( $new instanceof Revision
) ) {
3871 $new = Revision
::newFromTitle( $this, (int)$new );
3873 if ( !$old ||
!$new ) {
3874 return 0; // nothing to compare
3876 $dbr = wfGetDB( DB_SLAVE
);
3877 return (int)$dbr->selectField( 'revision', 'count(*)',
3879 'rev_page' => $this->getArticleId(),
3880 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3881 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3888 * Get the number of authors between the given revision IDs.
3889 * Used for diffs and other things that really need it.
3891 * @param $old int|Revision Old revision or rev ID (first before range)
3892 * @param $new int|Revision New revision or rev ID (first after range)
3893 * @param $limit Int Maximum number of authors
3894 * @return Int Number of revision authors between these revisions.
3896 public function countAuthorsBetween( $old, $new, $limit ) {
3897 if ( !( $old instanceof Revision
) ) {
3898 $old = Revision
::newFromTitle( $this, (int)$old );
3900 if ( !( $new instanceof Revision
) ) {
3901 $new = Revision
::newFromTitle( $this, (int)$new );
3903 if ( !$old ||
!$new ) {
3904 return 0; // nothing to compare
3906 $dbr = wfGetDB( DB_SLAVE
);
3907 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
3909 'rev_page' => $this->getArticleID(),
3910 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3911 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3913 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
3915 return (int)$dbr->numRows( $res );
3919 * Compare with another title.
3921 * @param $title Title
3924 public function equals( Title
$title ) {
3925 // Note: === is necessary for proper matching of number-like titles.
3926 return $this->getInterwiki() === $title->getInterwiki()
3927 && $this->getNamespace() == $title->getNamespace()
3928 && $this->getDBkey() === $title->getDBkey();
3932 * Check if this title is a subpage of another title
3934 * @param $title Title
3937 public function isSubpageOf( Title
$title ) {
3938 return $this->getInterwiki() === $title->getInterwiki()
3939 && $this->getNamespace() == $title->getNamespace()
3940 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
3944 * Callback for usort() to do title sorts by (namespace, title)
3949 * @return Integer: result of string comparison, or namespace comparison
3951 public static function compare( $a, $b ) {
3952 if ( $a->getNamespace() == $b->getNamespace() ) {
3953 return strcmp( $a->getText(), $b->getText() );
3955 return $a->getNamespace() - $b->getNamespace();
3960 * Return a string representation of this title
3962 * @return String representation of this title
3964 public function __toString() {
3965 return $this->getPrefixedText();
3969 * Check if page exists. For historical reasons, this function simply
3970 * checks for the existence of the title in the page table, and will
3971 * thus return false for interwiki links, special pages and the like.
3972 * If you want to know if a title can be meaningfully viewed, you should
3973 * probably call the isKnown() method instead.
3977 public function exists() {
3978 return $this->getArticleId() != 0;
3982 * Should links to this title be shown as potentially viewable (i.e. as
3983 * "bluelinks"), even if there's no record by this title in the page
3986 * This function is semi-deprecated for public use, as well as somewhat
3987 * misleadingly named. You probably just want to call isKnown(), which
3988 * calls this function internally.
3990 * (ISSUE: Most of these checks are cheap, but the file existence check
3991 * can potentially be quite expensive. Including it here fixes a lot of
3992 * existing code, but we might want to add an optional parameter to skip
3993 * it and any other expensive checks.)
3997 public function isAlwaysKnown() {
3998 if ( $this->mInterwiki
!= '' ) {
3999 return true; // any interwiki link might be viewable, for all we know
4001 switch( $this->mNamespace
) {
4004 // file exists, possibly in a foreign repo
4005 return (bool)wfFindFile( $this );
4007 // valid special page
4008 return SpecialPageFactory
::exists( $this->getDBkey() );
4010 // selflink, possibly with fragment
4011 return $this->mDbkeyform
== '';
4013 // known system message
4014 return $this->hasSourceText() !== false;
4021 * Does this title refer to a page that can (or might) be meaningfully
4022 * viewed? In particular, this function may be used to determine if
4023 * links to the title should be rendered as "bluelinks" (as opposed to
4024 * "redlinks" to non-existent pages).
4028 public function isKnown() {
4029 return $this->isAlwaysKnown() ||
$this->exists();
4033 * Does this page have source text?
4037 public function hasSourceText() {
4038 if ( $this->exists() ) {
4042 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4043 // If the page doesn't exist but is a known system message, default
4044 // message content will be displayed, same for language subpages-
4045 // Use always content language to avoid loading hundreds of languages
4046 // to get the link color.
4048 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4049 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4050 return $message->exists();
4057 * Get the default message text or false if the message doesn't exist
4059 * @return String or false
4061 public function getDefaultMessageText() {
4064 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4068 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4069 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4071 if ( $message->exists() ) {
4072 return $message->plain();
4079 * Is this in a namespace that allows actual pages?
4082 * @internal note -- uses hardcoded namespace index instead of constants
4084 public function canExist() {
4085 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
4089 * Update page_touched timestamps and send squid purge messages for
4090 * pages linking to this title. May be sent to the job queue depending
4091 * on the number of links. Typically called on create and delete.
4093 public function touchLinks() {
4094 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4097 if ( $this->getNamespace() == NS_CATEGORY
) {
4098 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4104 * Get the last touched timestamp
4106 * @param $db DatabaseBase: optional db
4107 * @return String last-touched timestamp
4109 public function getTouched( $db = null ) {
4110 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4111 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4116 * Get the timestamp when this page was updated since the user last saw it.
4119 * @return String|Null
4121 public function getNotificationTimestamp( $user = null ) {
4122 global $wgUser, $wgShowUpdatedMarker;
4123 // Assume current user if none given
4127 // Check cache first
4128 $uid = $user->getId();
4129 // avoid isset here, as it'll return false for null entries
4130 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4131 return $this->mNotificationTimestamp
[$uid];
4133 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4134 return $this->mNotificationTimestamp
[$uid] = false;
4136 // Don't cache too much!
4137 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4138 $this->mNotificationTimestamp
= array();
4140 $dbr = wfGetDB( DB_SLAVE
);
4141 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4142 'wl_notificationtimestamp',
4143 array( 'wl_namespace' => $this->getNamespace(),
4144 'wl_title' => $this->getDBkey(),
4145 'wl_user' => $user->getId()
4149 return $this->mNotificationTimestamp
[$uid];
4153 * Generate strings used for xml 'id' names in monobook tabs
4155 * @param $prepend string defaults to 'nstab-'
4156 * @return String XML 'id' name
4158 public function getNamespaceKey( $prepend = 'nstab-' ) {
4160 // Gets the subject namespace if this title
4161 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4162 // Checks if cononical namespace name exists for namespace
4163 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4164 // Uses canonical namespace name
4165 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4167 // Uses text of namespace
4168 $namespaceKey = $this->getSubjectNsText();
4170 // Makes namespace key lowercase
4171 $namespaceKey = $wgContLang->lc( $namespaceKey );
4173 if ( $namespaceKey == '' ) {
4174 $namespaceKey = 'main';
4176 // Changes file to image for backwards compatibility
4177 if ( $namespaceKey == 'file' ) {
4178 $namespaceKey = 'image';
4180 return $prepend . $namespaceKey;
4184 * Returns true if this is a special page.
4188 public function isSpecialPage() {
4189 return $this->getNamespace() == NS_SPECIAL
;
4193 * Returns true if this title resolves to the named special page
4195 * @param $name String The special page name
4198 public function isSpecial( $name ) {
4199 if ( $this->isSpecialPage() ) {
4200 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
4201 if ( $name == $thisName ) {
4209 * If the Title refers to a special page alias which is not the local default, resolve
4210 * the alias, and localise the name as necessary. Otherwise, return $this
4214 public function fixSpecialName() {
4215 if ( $this->isSpecialPage() ) {
4216 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
4217 if ( $canonicalName ) {
4218 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
4219 if ( $localName != $this->mDbkeyform
) {
4220 return Title
::makeTitle( NS_SPECIAL
, $localName );
4228 * Is this Title in a namespace which contains content?
4229 * In other words, is this a content page, for the purposes of calculating
4234 public function isContentPage() {
4235 return MWNamespace
::isContent( $this->getNamespace() );
4239 * Get all extant redirects to this Title
4241 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4242 * @return Array of Title redirects to this title
4244 public function getRedirectsHere( $ns = null ) {
4247 $dbr = wfGetDB( DB_SLAVE
);
4249 'rd_namespace' => $this->getNamespace(),
4250 'rd_title' => $this->getDBkey(),
4253 if ( !is_null( $ns ) ) {
4254 $where['page_namespace'] = $ns;
4257 $res = $dbr->select(
4258 array( 'redirect', 'page' ),
4259 array( 'page_namespace', 'page_title' ),
4264 foreach ( $res as $row ) {
4265 $redirs[] = self
::newFromRow( $row );
4271 * Check if this Title is a valid redirect target
4275 public function isValidRedirectTarget() {
4276 global $wgInvalidRedirectTargets;
4278 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4279 if ( $this->isSpecial( 'Userlogout' ) ) {
4283 foreach ( $wgInvalidRedirectTargets as $target ) {
4284 if ( $this->isSpecial( $target ) ) {
4293 * Get a backlink cache object
4295 * @return BacklinkCache
4297 function getBacklinkCache() {
4298 if ( is_null( $this->mBacklinkCache
) ) {
4299 $this->mBacklinkCache
= new BacklinkCache( $this );
4301 return $this->mBacklinkCache
;
4305 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4309 public function canUseNoindex() {
4310 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4312 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4313 ?
$wgContentNamespaces
4314 : $wgExemptFromUserRobotsControl;
4316 return !in_array( $this->mNamespace
, $bannedNamespaces );
4321 * Returns restriction types for the current Title
4323 * @return array applicable restriction types
4325 public function getRestrictionTypes() {
4326 if ( $this->isSpecialPage() ) {
4330 $types = self
::getFilteredRestrictionTypes( $this->exists() );
4332 if ( $this->getNamespace() != NS_FILE
) {
4333 # Remove the upload restriction for non-file titles
4334 $types = array_diff( $types, array( 'upload' ) );
4337 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4339 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
4340 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
4345 * Get a filtered list of all restriction types supported by this wiki.
4346 * @param bool $exists True to get all restriction types that apply to
4347 * titles that do exist, False for all restriction types that apply to
4348 * titles that do not exist
4351 public static function getFilteredRestrictionTypes( $exists = true ) {
4352 global $wgRestrictionTypes;
4353 $types = $wgRestrictionTypes;
4355 # Remove the create restriction for existing titles
4356 $types = array_diff( $types, array( 'create' ) );
4358 # Only the create and upload restrictions apply to non-existing titles
4359 $types = array_intersect( $types, array( 'create', 'upload' ) );
4365 * Returns the raw sort key to be used for categories, with the specified
4366 * prefix. This will be fed to Collation::getSortKey() to get a
4367 * binary sortkey that can be used for actual sorting.
4369 * @param $prefix string The prefix to be used, specified using
4370 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4374 public function getCategorySortkey( $prefix = '' ) {
4375 $unprefixed = $this->getText();
4377 // Anything that uses this hook should only depend
4378 // on the Title object passed in, and should probably
4379 // tell the users to run updateCollations.php --force
4380 // in order to re-sort existing category relations.
4381 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4382 if ( $prefix !== '' ) {
4383 # Separate with a line feed, so the unprefixed part is only used as
4384 # a tiebreaker when two pages have the exact same prefix.
4385 # In UCA, tab is the only character that can sort above LF
4386 # so we strip both of them from the original prefix.
4387 $prefix = strtr( $prefix, "\n\t", ' ' );
4388 return "$prefix\n$unprefixed";
4394 * Get the language in which the content of this page is written.
4395 * Defaults to $wgContLang, but in certain cases it can be e.g.
4396 * $wgLang (such as special pages, which are in the user language).
4399 * @return object Language
4401 public function getPageLanguage() {
4403 if ( $this->isSpecialPage() ) {
4404 // special pages are in the user language
4406 } elseif ( $this->isCssOrJsPage() ) {
4407 // css/js should always be LTR and is, in fact, English
4408 return wfGetLangObj( 'en' );
4409 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4410 // Parse mediawiki messages with correct target language
4411 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4412 return wfGetLangObj( $lang );
4415 // If nothing special, it should be in the wiki content language
4416 $pageLang = $wgContLang;
4417 // Hook at the end because we don't want to override the above stuff
4418 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4419 return wfGetLangObj( $pageLang );