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;
52 * @name Private member variables
53 * Please use the accessor functions instead.
58 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
59 var $mUrlform = ''; // /< URL-encoded form of the main part
60 var $mDbkeyform = ''; // /< Main part with underscores
61 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
62 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
63 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
64 var $mFragment; // /< Title fragment (i.e. the bit after the #)
65 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
66 var $mLatestID = false; // /< ID of most recent revision
67 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
68 var $mOldRestrictions = false;
69 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
70 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
71 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
72 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
73 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
74 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
75 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
76 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
77 # Don't change the following default, NS_MAIN is hardcoded in several
78 # places. See bug 696.
79 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
80 # Zero except in {{transclusion}} tags
81 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
82 var $mLength = -1; // /< The page length, 0 for special pages
83 var $mRedirect = null; // /< Is the article at this title a redirect?
84 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
85 var $mBacklinkCache = null; // /< Cache of links to this title
92 /*protected*/ function __construct() { }
95 * Create a new Title from a prefixed DB key
97 * @param $key String the database key, which has underscores
98 * instead of spaces, possibly including namespace and
100 * @return Title, or NULL on an error
102 public static function newFromDBkey( $key ) {
104 $t->mDbkeyform
= $key;
105 if ( $t->secureAndSplit() ) {
113 * Create a new Title from text, such as what one would find in a link. De-
114 * codes any HTML entities in the text.
116 * @param $text String the link text; spaces, prefixes, and an
117 * initial ':' indicating the main namespace are accepted.
118 * @param $defaultNamespace Int the namespace to use if none is speci-
119 * fied by a prefix. If you want to force a specific namespace even if
120 * $text might begin with a namespace prefix, use makeTitle() or
122 * @return Title, or null on an error.
124 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
125 if ( is_object( $text ) ) {
126 throw new MWException( 'Title::newFromText given an object' );
130 * Wiki pages often contain multiple links to the same page.
131 * Title normalization and parsing can become expensive on
132 * pages with many links, so we can save a little time by
135 * In theory these are value objects and won't get changed...
137 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
138 return Title
::$titleCache[$text];
141 # Convert things like é ā or 〗 into normalized (bug 14952) text
142 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
145 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
146 $t->mDefaultNamespace
= $defaultNamespace;
148 static $cachedcount = 0 ;
149 if ( $t->secureAndSplit() ) {
150 if ( $defaultNamespace == NS_MAIN
) {
151 if ( $cachedcount >= self
::CACHE_MAX
) {
152 # Avoid memory leaks on mass operations...
153 Title
::$titleCache = array();
157 Title
::$titleCache[$text] =& $t;
167 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
169 * Example of wrong and broken code:
170 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
172 * Example of right code:
173 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
175 * Create a new Title from URL-encoded text. Ensures that
176 * the given title's length does not exceed the maximum.
178 * @param $url String the title, as might be taken from a URL
179 * @return Title the new object, or NULL on an error
181 public static function newFromURL( $url ) {
182 global $wgLegalTitleChars;
185 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
186 # but some URLs used it as a space replacement and they still come
187 # from some external search tools.
188 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
189 $url = str_replace( '+', ' ', $url );
192 $t->mDbkeyform
= str_replace( ' ', '_', $url );
193 if ( $t->secureAndSplit() ) {
201 * Create a new Title from an article ID
203 * @param $id Int the page_id corresponding to the Title to create
204 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
205 * @return Title the new object, or NULL on an error
207 public static function newFromID( $id, $flags = 0 ) {
208 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
209 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
210 if ( $row !== false ) {
211 $title = Title
::newFromRow( $row );
219 * Make an array of titles from an array of IDs
221 * @param $ids Array of Int Array of IDs
222 * @return Array of Titles
224 public static function newFromIDs( $ids ) {
225 if ( !count( $ids ) ) {
228 $dbr = wfGetDB( DB_SLAVE
);
233 'page_namespace', 'page_title', 'page_id',
234 'page_len', 'page_is_redirect', 'page_latest',
236 array( 'page_id' => $ids ),
241 foreach ( $res as $row ) {
242 $titles[] = Title
::newFromRow( $row );
248 * Make a Title object from a DB row
250 * @param $row Object database row (needs at least page_title,page_namespace)
251 * @return Title corresponding Title
253 public static function newFromRow( $row ) {
254 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
255 $t->loadFromRow( $row );
260 * Load Title object fields from a DB row.
261 * If false is given, the title will be treated as non-existing.
263 * @param $row Object|false database row
266 public function loadFromRow( $row ) {
267 if ( $row ) { // page found
268 if ( isset( $row->page_id
) )
269 $this->mArticleID
= (int)$row->page_id
;
270 if ( isset( $row->page_len
) )
271 $this->mLength
= (int)$row->page_len
;
272 if ( isset( $row->page_is_redirect
) )
273 $this->mRedirect
= (bool)$row->page_is_redirect
;
274 if ( isset( $row->page_latest
) )
275 $this->mLatestID
= (int)$row->page_latest
;
276 } else { // page not found
277 $this->mArticleID
= 0;
279 $this->mRedirect
= false;
280 $this->mLatestID
= 0;
285 * Create a new Title from a namespace index and a DB key.
286 * It's assumed that $ns and $title are *valid*, for instance when
287 * they came directly from the database or a special page name.
288 * For convenience, spaces are converted to underscores so that
289 * eg user_text fields can be used directly.
291 * @param $ns Int the namespace of the article
292 * @param $title String the unprefixed database key form
293 * @param $fragment String the link fragment (after the "#")
294 * @param $interwiki String the interwiki prefix
295 * @return Title the new object
297 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
299 $t->mInterwiki
= $interwiki;
300 $t->mFragment
= $fragment;
301 $t->mNamespace
= $ns = intval( $ns );
302 $t->mDbkeyform
= str_replace( ' ', '_', $title );
303 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
304 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
305 $t->mTextform
= str_replace( '_', ' ', $title );
310 * Create a new Title from a namespace index and a DB key.
311 * The parameters will be checked for validity, which is a bit slower
312 * than makeTitle() but safer for user-provided data.
314 * @param $ns Int the namespace of the article
315 * @param $title String database key form
316 * @param $fragment String the link fragment (after the "#")
317 * @param $interwiki String interwiki prefix
318 * @return Title the new object, or NULL on an error
320 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
322 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
323 if ( $t->secureAndSplit() ) {
331 * Create a new Title for the Main Page
333 * @return Title the new object
335 public static function newMainPage() {
336 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
337 // Don't give fatal errors if the message is broken
339 $title = Title
::newFromText( 'Main Page' );
345 * Extract a redirect destination from a string and return the
346 * Title, or null if the text doesn't contain a valid redirect
347 * This will only return the very next target, useful for
348 * the redirect table and other checks that don't need full recursion
350 * @param $text String: Text with possible redirect
351 * @return Title: The corresponding Title
353 public static function newFromRedirect( $text ) {
354 return self
::newFromRedirectInternal( $text );
358 * Extract a redirect destination from a string and return the
359 * Title, or null if the text doesn't contain a valid redirect
360 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
361 * in order to provide (hopefully) the Title of the final destination instead of another redirect
363 * @param $text String Text with possible redirect
366 public static function newFromRedirectRecurse( $text ) {
367 $titles = self
::newFromRedirectArray( $text );
368 return $titles ?
array_pop( $titles ) : null;
372 * Extract a redirect destination from a string and return an
373 * array of Titles, or null if the text doesn't contain a valid redirect
374 * The last element in the array is the final destination after all redirects
375 * have been resolved (up to $wgMaxRedirects times)
377 * @param $text String Text with possible redirect
378 * @return Array of Titles, with the destination last
380 public static function newFromRedirectArray( $text ) {
381 global $wgMaxRedirects;
382 $title = self
::newFromRedirectInternal( $text );
383 if ( is_null( $title ) ) {
386 // recursive check to follow double redirects
387 $recurse = $wgMaxRedirects;
388 $titles = array( $title );
389 while ( --$recurse > 0 ) {
390 if ( $title->isRedirect() ) {
391 $article = new Article( $title, 0 );
392 $newtitle = $article->getRedirectTarget();
396 // Redirects to some special pages are not permitted
397 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
398 // the new title passes the checks, so make that our current title so that further recursion can be checked
400 $titles[] = $newtitle;
409 * Really extract the redirect destination
410 * Do not call this function directly, use one of the newFromRedirect* functions above
412 * @param $text String Text with possible redirect
415 protected static function newFromRedirectInternal( $text ) {
416 global $wgMaxRedirects;
417 if ( $wgMaxRedirects < 1 ) {
418 //redirects are disabled, so quit early
421 $redir = MagicWord
::get( 'redirect' );
422 $text = trim( $text );
423 if ( $redir->matchStartAndRemove( $text ) ) {
424 // Extract the first link and see if it's usable
425 // Ensure that it really does come directly after #REDIRECT
426 // Some older redirects included a colon, so don't freak about that!
428 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
429 // Strip preceding colon used to "escape" categories, etc.
430 // and URL-decode links
431 if ( strpos( $m[1], '%' ) !== false ) {
432 // Match behavior of inline link parsing here;
433 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
435 $title = Title
::newFromText( $m[1] );
436 // If the title is a redirect to bad special pages or is invalid, return null
437 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
446 # ----------------------------------------------------------------------------
448 # ----------------------------------------------------------------------------
451 * Get the prefixed DB key associated with an ID
453 * @param $id Int the page_id of the article
454 * @return Title an object representing the article, or NULL if no such article was found
456 public static function nameOf( $id ) {
457 $dbr = wfGetDB( DB_SLAVE
);
459 $s = $dbr->selectRow(
461 array( 'page_namespace', 'page_title' ),
462 array( 'page_id' => $id ),
465 if ( $s === false ) {
469 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
474 * Get a regex character class describing the legal characters in a link
476 * @return String the list of characters, not delimited
478 public static function legalChars() {
479 global $wgLegalTitleChars;
480 return $wgLegalTitleChars;
484 * Get a string representation of a title suitable for
485 * including in a search index
487 * @param $ns Int a namespace index
488 * @param $title String text-form main part
489 * @return String a stripped-down title string ready for the search index
491 public static function indexTitle( $ns, $title ) {
494 $lc = SearchEngine
::legalSearchChars() . '&#;';
495 $t = $wgContLang->normalizeForSearch( $title );
496 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
497 $t = $wgContLang->lc( $t );
500 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
501 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
503 $t = preg_replace( "/\\s+/", ' ', $t );
505 if ( $ns == NS_FILE
) {
506 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
512 * Make a prefixed DB key from a DB key and a namespace index
514 * @param $ns Int numerical representation of the namespace
515 * @param $title String the DB key form the title
516 * @param $fragment String The link fragment (after the "#")
517 * @param $interwiki String The interwiki prefix
518 * @return String the prefixed form of the title
520 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
523 $namespace = $wgContLang->getNsText( $ns );
524 $name = $namespace == '' ?
$title : "$namespace:$title";
525 if ( strval( $interwiki ) != '' ) {
526 $name = "$interwiki:$name";
528 if ( strval( $fragment ) != '' ) {
529 $name .= '#' . $fragment;
535 * Determine whether the object refers to a page within
538 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
540 public function isLocal() {
541 if ( $this->mInterwiki
!= '' ) {
542 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
549 * Determine whether the object refers to a page within
550 * this project and is transcludable.
552 * @return Bool TRUE if this is transcludable
554 public function isTrans() {
555 if ( $this->mInterwiki
== '' ) {
559 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
563 * Returns the DB name of the distant wiki which owns the object.
565 * @return String the DB name
567 public function getTransWikiID() {
568 if ( $this->mInterwiki
== '' ) {
572 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
576 * Escape a text fragment, say from a link, for a URL
578 * @param $fragment string containing a URL or link fragment (after the "#")
579 * @return String: escaped string
581 static function escapeFragmentForURL( $fragment ) {
582 # Note that we don't urlencode the fragment. urlencoded Unicode
583 # fragments appear not to work in IE (at least up to 7) or in at least
584 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
585 # to care if they aren't encoded.
586 return Sanitizer
::escapeId( $fragment, 'noninitial' );
589 # ----------------------------------------------------------------------------
591 # ----------------------------------------------------------------------------
593 /** Simple accessors */
595 * Get the text form (spaces not underscores) of the main part
597 * @return String Main part of the title
599 public function getText() { return $this->mTextform
; }
602 * Get the URL-encoded form of the main part
604 * @return String Main part of the title, URL-encoded
606 public function getPartialURL() { return $this->mUrlform
; }
609 * Get the main part with underscores
611 * @return String: Main part of the title, with underscores
613 public function getDBkey() { return $this->mDbkeyform
; }
616 * Get the namespace index, i.e. one of the NS_xxxx constants.
618 * @return Integer: Namespace index
620 public function getNamespace() { return $this->mNamespace
; }
623 * Get the namespace text
625 * @return String: Namespace text
627 public function getNsText() {
630 if ( $this->mInterwiki
!= '' ) {
631 // This probably shouldn't even happen. ohh man, oh yuck.
632 // But for interwiki transclusion it sometimes does.
633 // Shit. Shit shit shit.
635 // Use the canonical namespaces if possible to try to
636 // resolve a foreign namespace.
637 if ( MWNamespace
::exists( $this->mNamespace
) ) {
638 return MWNamespace
::getCanonicalName( $this->mNamespace
);
642 // Strip off subpages
643 $pagename = $this->getText();
644 if ( strpos( $pagename, '/' ) !== false ) {
645 list( $username , ) = explode( '/', $pagename, 2 );
647 $username = $pagename;
650 if ( $wgContLang->needsGenderDistinction() &&
651 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
652 $gender = GenderCache
::singleton()->getGenderOf( $username, __METHOD__
);
653 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
656 return $wgContLang->getNsText( $this->mNamespace
);
660 * Get the DB key with the initial letter case as specified by the user
662 * @return String DB key
664 function getUserCaseDBKey() {
665 return $this->mUserCaseDBKey
;
669 * Get the namespace text of the subject (rather than talk) page
671 * @return String Namespace text
673 public function getSubjectNsText() {
675 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
679 * Get the namespace text of the talk page
681 * @return String Namespace text
683 public function getTalkNsText() {
685 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
689 * Could this title have a corresponding talk page?
691 * @return Bool TRUE or FALSE
693 public function canTalk() {
694 return( MWNamespace
::canTalk( $this->mNamespace
) );
698 * Get the interwiki prefix (or null string)
700 * @return String Interwiki prefix
702 public function getInterwiki() { return $this->mInterwiki
; }
705 * Get the Title fragment (i.e.\ the bit after the #) in text form
707 * @return String Title fragment
709 public function getFragment() { return $this->mFragment
; }
712 * Get the fragment in URL form, including the "#" character if there is one
713 * @return String Fragment in URL form
715 public function getFragmentForURL() {
716 if ( $this->mFragment
== '' ) {
719 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
724 * Get the default namespace index, for when there is no namespace
726 * @return Int Default namespace index
728 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
731 * Get title for search index
733 * @return String a stripped-down title string ready for the
736 public function getIndexTitle() {
737 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
741 * Get the prefixed database key form
743 * @return String the prefixed title, with underscores and
744 * any interwiki and namespace prefixes
746 public function getPrefixedDBkey() {
747 $s = $this->prefix( $this->mDbkeyform
);
748 $s = str_replace( ' ', '_', $s );
753 * Get the prefixed title with spaces.
754 * This is the form usually used for display
756 * @return String the prefixed title, with spaces
758 public function getPrefixedText() {
759 // @todo FIXME: Bad usage of empty() ?
760 if ( empty( $this->mPrefixedText
) ) {
761 $s = $this->prefix( $this->mTextform
);
762 $s = str_replace( '_', ' ', $s );
763 $this->mPrefixedText
= $s;
765 return $this->mPrefixedText
;
769 * Return the prefixed title with spaces _without_ the interwiki prefix
771 * @return \type{\string} the title, prefixed by the namespace but not by the interwiki prefix, with spaces
773 public function getSemiPrefixedText() {
774 if ( !isset( $this->mSemiPrefixedText
) ){
775 $s = ( $this->mNamespace
=== NS_MAIN ?
'' : $this->getNsText() . ':' ) . $this->mTextform
;
776 $s = str_replace( '_', ' ', $s );
777 $this->mSemiPrefixedText
= $s;
779 return $this->mSemiPrefixedText
;
783 * Get the prefixed title with spaces, plus any fragment
784 * (part beginning with '#')
786 * @return String the prefixed title, with spaces and the fragment, including '#'
788 public function getFullText() {
789 $text = $this->getPrefixedText();
790 if ( $this->mFragment
!= '' ) {
791 $text .= '#' . $this->mFragment
;
797 * Get the base page name, i.e. the leftmost part before any slashes
799 * @return String Base name
801 public function getBaseText() {
802 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
803 return $this->getText();
806 $parts = explode( '/', $this->getText() );
807 # Don't discard the real title if there's no subpage involved
808 if ( count( $parts ) > 1 ) {
809 unset( $parts[count( $parts ) - 1] );
811 return implode( '/', $parts );
815 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
817 * @return String Subpage name
819 public function getSubpageText() {
820 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
821 return( $this->mTextform
);
823 $parts = explode( '/', $this->mTextform
);
824 return( $parts[count( $parts ) - 1] );
828 * Get a URL-encoded form of the subpage text
830 * @return String URL-encoded subpage name
832 public function getSubpageUrlForm() {
833 $text = $this->getSubpageText();
834 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
839 * Get a URL-encoded title (not an actual URL) including interwiki
841 * @return String the URL-encoded form
843 public function getPrefixedURL() {
844 $s = $this->prefix( $this->mDbkeyform
);
845 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
850 * Get a real URL referring to this title, with interwiki link and
853 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
854 * links. Can be specified as an associative array as well, e.g.,
855 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
856 * @param $variant String language variant of url (for sr, zh..)
857 * @return String the URL
859 public function getFullURL( $query = '', $variant = false ) {
860 # Hand off all the decisions on urls to getLocalURL
861 $url = $this->getLocalURL( $query, $variant );
863 # Expand the url to make it a full url. Note that getLocalURL has the
864 # potential to output full urls for a variety of reasons, so we use
865 # wfExpandUrl instead of simply prepending $wgServer
866 $url = wfExpandUrl( $url, PROTO_RELATIVE
);
868 # Finally, add the fragment.
869 $url .= $this->getFragmentForURL();
871 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query, $variant ) );
876 * Get a URL with no fragment or server name. If this page is generated
877 * with action=render, $wgServer is prepended.
879 * @param $query Mixed: an optional query string; if not specified,
880 * $wgArticlePath will be used. Can be specified as an associative array
881 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
883 * @param $variant String language variant of url (for sr, zh..)
884 * @return String the URL
886 public function getLocalURL( $query = '', $variant = false ) {
887 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
888 global $wgVariantArticlePath, $wgContLang;
890 if ( is_array( $query ) ) {
891 $query = wfArrayToCGI( $query );
894 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
896 $namespace = $this->getNsText();
897 if ( $namespace != '' ) {
898 # Can this actually happen? Interwikis shouldn't be parsed.
899 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
902 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
903 $url = wfAppendQuery( $url, $query );
905 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
906 if ( $query == '' ) {
907 if ( $variant != false && $wgContLang->hasVariants() ) {
908 if ( !$wgVariantArticlePath ) {
909 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
911 $variantArticlePath = $wgVariantArticlePath;
913 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
914 $url = str_replace( '$1', $dbkey, $url );
916 $url = str_replace( '$1', $dbkey, $wgArticlePath );
917 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
920 global $wgActionPaths;
923 if ( !empty( $wgActionPaths ) &&
924 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
926 $action = urldecode( $matches[2] );
927 if ( isset( $wgActionPaths[$action] ) ) {
928 $query = $matches[1];
929 if ( isset( $matches[4] ) ) {
930 $query .= $matches[4];
932 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
933 if ( $query != '' ) {
934 $url = wfAppendQuery( $url, $query );
939 if ( $url === false ) {
940 if ( $query == '-' ) {
943 $url = "{$wgScript}?title={$dbkey}&{$query}";
947 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query, $variant ) );
949 // @todo FIXME: This causes breakage in various places when we
950 // actually expected a local URL and end up with dupe prefixes.
951 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
952 $url = $wgServer . $url;
955 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query, $variant ) );
960 * Get a URL that's the simplest URL that will be valid to link, locally,
961 * to the current Title. It includes the fragment, but does not include
962 * the server unless action=render is used (or the link is external). If
963 * there's a fragment but the prefixed text is empty, we just return a link
966 * The result obviously should not be URL-escaped, but does need to be
967 * HTML-escaped if it's being output in HTML.
969 * @param $query Array of Strings An associative array of key => value pairs for the
970 * query string. Keys and values will be escaped.
971 * @param $variant String language variant of URL (for sr, zh..). Ignored
972 * for external links. Default is "false" (same variant as current page,
973 * for anonymous users).
974 * @return String the URL
976 public function getLinkUrl( $query = array(), $variant = false ) {
977 wfProfileIn( __METHOD__
);
978 if ( $this->isExternal() ) {
979 $ret = $this->getFullURL( $query );
980 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
981 $ret = $this->getFragmentForURL();
983 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
985 wfProfileOut( __METHOD__
);
990 * Get an HTML-escaped version of the URL form, suitable for
991 * using in a link, without a server name or fragment
993 * @param $query String an optional query string
994 * @return String the URL
996 public function escapeLocalURL( $query = '' ) {
997 return htmlspecialchars( $this->getLocalURL( $query ) );
1001 * Get an HTML-escaped version of the URL form, suitable for
1002 * using in a link, including the server name and fragment
1004 * @param $query String an optional query string
1005 * @return String the URL
1007 public function escapeFullURL( $query = '' ) {
1008 return htmlspecialchars( $this->getFullURL( $query ) );
1012 * HTML-escaped version of getCanonicalURL()
1014 public function escapeCanonicalURL( $query = '', $variant = false ) {
1015 return htmlspecialchars( $this->getCanonicalURL( $query, $variant ) );
1019 * Get the URL form for an internal link.
1020 * - Used in various Squid-related code, in case we have a different
1021 * internal hostname for the server from the exposed one.
1023 * This uses $wgInternalServer to qualify the path, or $wgServer
1024 * if $wgInternalServer is not set. If the server variable used is
1025 * protocol-relative, the URL will be expanded to http://
1027 * @param $query String an optional query string
1028 * @param $variant String language variant of url (for sr, zh..)
1029 * @return String the URL
1031 public function getInternalURL( $query = '', $variant = false ) {
1032 if ( $this->isExternal( ) ) {
1035 global $wgInternalServer, $wgServer;
1036 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1038 $url = wfExpandUrl( $server . $this->getLocalURL( $query, $variant ), PROTO_HTTP
);
1039 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query, $variant ) );
1044 * Get the URL for a canonical link, for use in things like IRC and
1045 * e-mail notifications. Uses $wgCanonicalServer and the
1046 * GetCanonicalURL hook.
1048 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1050 * @param $query string An optional query string
1051 * @param $variant string Language variant of URL (for sr, zh, ...)
1052 * @return string The URL
1054 public function getCanonicalURL( $query = '', $variant = false ) {
1055 $url = wfExpandUrl( $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1056 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query, $variant ) );
1061 * Get the edit URL for this Title
1063 * @return String the URL, or a null string if this is an
1066 public function getEditURL() {
1067 if ( $this->mInterwiki
!= '' ) {
1070 $s = $this->getLocalURL( 'action=edit' );
1076 * Get the HTML-escaped displayable text form.
1077 * Used for the title field in <a> tags.
1079 * @return String the text, including any prefixes
1081 public function getEscapedText() {
1082 return htmlspecialchars( $this->getPrefixedText() );
1086 * Is this Title interwiki?
1090 public function isExternal() {
1091 return ( $this->mInterwiki
!= '' );
1095 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1097 * @param $action String Action to check (default: edit)
1100 public function isSemiProtected( $action = 'edit' ) {
1101 if ( $this->exists() ) {
1102 $restrictions = $this->getRestrictions( $action );
1103 if ( count( $restrictions ) > 0 ) {
1104 foreach ( $restrictions as $restriction ) {
1105 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1115 # If it doesn't exist, it can't be protected
1121 * Does the title correspond to a protected article?
1123 * @param $action String the action the page is protected from,
1124 * by default checks all actions.
1127 public function isProtected( $action = '' ) {
1128 global $wgRestrictionLevels;
1130 $restrictionTypes = $this->getRestrictionTypes();
1132 # Special pages have inherent protection
1133 if( $this->getNamespace() == NS_SPECIAL
) {
1137 # Check regular protection levels
1138 foreach ( $restrictionTypes as $type ) {
1139 if ( $action == $type ||
$action == '' ) {
1140 $r = $this->getRestrictions( $type );
1141 foreach ( $wgRestrictionLevels as $level ) {
1142 if ( in_array( $level, $r ) && $level != '' ) {
1153 * Is this a conversion table for the LanguageConverter?
1157 public function isConversionTable() {
1159 $this->getNamespace() == NS_MEDIAWIKI
&&
1160 strpos( $this->getText(), 'Conversiontable' ) !== false
1170 * Is $wgUser watching this page?
1174 public function userIsWatching() {
1177 if ( is_null( $this->mWatched
) ) {
1178 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1179 $this->mWatched
= false;
1181 $this->mWatched
= $wgUser->isWatched( $this );
1184 return $this->mWatched
;
1188 * Can $wgUser perform $action on this page?
1189 * This skips potentially expensive cascading permission checks
1190 * as well as avoids expensive error formatting
1192 * Suitable for use for nonessential UI controls in common cases, but
1193 * _not_ for functional access control.
1195 * May provide false positives, but should never provide a false negative.
1197 * @param $action String action that permission needs to be checked for
1200 public function quickUserCan( $action ) {
1201 return $this->userCan( $action, false );
1205 * Determines if $user is unable to edit this page because it has been protected
1206 * by $wgNamespaceProtection.
1208 * @param $user User object to check permissions
1211 public function isNamespaceProtected( User
$user ) {
1212 global $wgNamespaceProtection;
1214 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
1215 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
1216 if ( $right != '' && !$user->isAllowed( $right ) ) {
1225 * Can $wgUser perform $action on this page?
1227 * @param $action String action that permission needs to be checked for
1228 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1231 public function userCan( $action, $doExpensiveQueries = true ) {
1233 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1237 * Can $user perform $action on this page?
1239 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1241 * @param $action String action that permission needs to be checked for
1242 * @param $user User to check
1243 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries by
1244 * skipping checks for cascading protections and user blocks.
1245 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1246 * @return Array of arguments to wfMsg to explain permissions problems.
1248 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1249 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1251 // Remove the errors being ignored.
1252 foreach ( $errors as $index => $error ) {
1253 $error_key = is_array( $error ) ?
$error[0] : $error;
1255 if ( in_array( $error_key, $ignoreErrors ) ) {
1256 unset( $errors[$index] );
1264 * Permissions checks that fail most often, and which are easiest to test.
1266 * @param $action String the action to check
1267 * @param $user User user to check
1268 * @param $errors Array list of current errors
1269 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1270 * @param $short Boolean short circuit on first error
1272 * @return Array list of errors
1274 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1275 $ns = $this->getNamespace();
1277 if ( $action == 'create' ) {
1278 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk', $ns ) ) ||
1279 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage', $ns ) ) ) {
1280 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1282 } elseif ( $action == 'move' ) {
1283 if ( !$user->isAllowed( 'move-rootuserpages', $ns )
1284 && $ns == NS_USER
&& !$this->isSubpage() ) {
1285 // Show user page-specific message only if the user can move other pages
1286 $errors[] = array( 'cant-move-user-page' );
1289 // Check if user is allowed to move files if it's a file
1290 if ( $ns == NS_FILE
&& !$user->isAllowed( 'movefile', $ns ) ) {
1291 $errors[] = array( 'movenotallowedfile' );
1294 if ( !$user->isAllowed( 'move', $ns) ) {
1295 // User can't move anything
1297 $userCanMove = in_array( 'move', User
::getGroupPermissions(
1298 array( 'user' ), $ns ), true );
1299 $autoconfirmedCanMove = in_array( 'move', User
::getGroupPermissions(
1300 array( 'autoconfirmed' ), $ns ), true );
1302 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1303 // custom message if logged-in users without any special rights can move
1304 $errors[] = array( 'movenologintext' );
1306 $errors[] = array( 'movenotallowed' );
1309 } elseif ( $action == 'move-target' ) {
1310 if ( !$user->isAllowed( 'move', $ns ) ) {
1311 // User can't move anything
1312 $errors[] = array( 'movenotallowed' );
1313 } elseif ( !$user->isAllowed( 'move-rootuserpages', $ns )
1314 && $ns == NS_USER
&& !$this->isSubpage() ) {
1315 // Show user page-specific message only if the user can move other pages
1316 $errors[] = array( 'cant-move-to-user-page' );
1318 } elseif ( !$user->isAllowed( $action, $ns ) ) {
1319 // We avoid expensive display logic for quickUserCan's and such
1322 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1323 User
::getGroupsWithPermission( $action, $ns ) );
1330 $wgLang->commaList( $groups ),
1334 $return = array( 'badaccess-group0' );
1336 $errors[] = $return;
1343 * Add the resulting error code to the errors array
1345 * @param $errors Array list of current errors
1346 * @param $result Mixed result of errors
1348 * @return Array list of errors
1350 private function resultToError( $errors, $result ) {
1351 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1352 // A single array representing an error
1353 $errors[] = $result;
1354 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1355 // A nested array representing multiple errors
1356 $errors = array_merge( $errors, $result );
1357 } elseif ( $result !== '' && is_string( $result ) ) {
1358 // A string representing a message-id
1359 $errors[] = array( $result );
1360 } elseif ( $result === false ) {
1361 // a generic "We don't want them to do that"
1362 $errors[] = array( 'badaccess-group0' );
1368 * Check various permission hooks
1370 * @param $action String the action to check
1371 * @param $user User user to check
1372 * @param $errors Array list of current errors
1373 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1374 * @param $short Boolean short circuit on first error
1376 * @return Array list of errors
1378 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1379 // Use getUserPermissionsErrors instead
1381 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1382 return $result ?
array() : array( array( 'badaccess-group0' ) );
1384 // Check getUserPermissionsErrors hook
1385 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1386 $errors = $this->resultToError( $errors, $result );
1388 // Check getUserPermissionsErrorsExpensive hook
1389 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1390 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1391 $errors = $this->resultToError( $errors, $result );
1398 * Check permissions on special pages & namespaces
1400 * @param $action String the action to check
1401 * @param $user User user to check
1402 * @param $errors Array list of current errors
1403 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1404 * @param $short Boolean short circuit on first error
1406 * @return Array list of errors
1408 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1409 # Only 'createaccount' and 'execute' can be performed on
1410 # special pages, which don't actually exist in the DB.
1411 $specialOKActions = array( 'createaccount', 'execute' );
1412 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1413 $errors[] = array( 'ns-specialprotected' );
1416 # Check $wgNamespaceProtection for restricted namespaces
1417 if ( $this->isNamespaceProtected( $user ) ) {
1418 $ns = $this->mNamespace
== NS_MAIN ?
1419 wfMsg( 'nstab-main' ) : $this->getNsText();
1420 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1421 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1428 * Check CSS/JS sub-page permissions
1430 * @param $action String the action to check
1431 * @param $user User user to check
1432 * @param $errors Array list of current errors
1433 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1434 * @param $short Boolean short circuit on first error
1436 * @return Array list of errors
1438 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1439 # Protect css/js subpages of user pages
1440 # XXX: this might be better using restrictions
1441 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1442 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1443 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1444 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1445 $errors[] = array( 'customcssprotected' );
1446 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1447 $errors[] = array( 'customjsprotected' );
1455 * Check against page_restrictions table requirements on this
1456 * page. The user must possess all required rights for this
1459 * @param $action String the action to check
1460 * @param $user User user to check
1461 * @param $errors Array list of current errors
1462 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1463 * @param $short Boolean short circuit on first error
1465 * @return Array list of errors
1467 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1468 foreach ( $this->getRestrictions( $action ) as $right ) {
1469 // Backwards compatibility, rewrite sysop -> protect
1470 if ( $right == 'sysop' ) {
1473 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace
) ) {
1474 // Users with 'editprotected' permission can edit protected pages
1475 if ( $action == 'edit' && $user->isAllowed( 'editprotected', $this->mNamespace
) ) {
1476 // Users with 'editprotected' permission cannot edit protected pages
1477 // with cascading option turned on.
1478 if ( $this->mCascadeRestriction
) {
1479 $errors[] = array( 'protectedpagetext', $right );
1482 $errors[] = array( 'protectedpagetext', $right );
1491 * Check restrictions on cascading pages.
1493 * @param $action String the action to check
1494 * @param $user User to check
1495 * @param $errors Array list of current errors
1496 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1497 * @param $short Boolean short circuit on first error
1499 * @return Array list of errors
1501 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1502 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1503 # We /could/ use the protection level on the source page, but it's
1504 # fairly ugly as we have to establish a precedence hierarchy for pages
1505 # included by multiple cascade-protected pages. So just restrict
1506 # it to people with 'protect' permission, as they could remove the
1507 # protection anyway.
1508 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1509 # Cascading protection depends on more than this page...
1510 # Several cascading protected pages may include this page...
1511 # Check each cascading level
1512 # This is only for protection restrictions, not for all actions
1513 if ( isset( $restrictions[$action] ) ) {
1514 foreach ( $restrictions[$action] as $right ) {
1515 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1516 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace
) ) {
1518 foreach ( $cascadingSources as $page )
1519 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1520 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1530 * Check action permissions not already checked in checkQuickPermissions
1532 * @param $action String the action to check
1533 * @param $user User to check
1534 * @param $errors Array list of current errors
1535 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1536 * @param $short Boolean short circuit on first error
1538 * @return Array list of errors
1540 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1541 if ( $action == 'protect' ) {
1542 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1543 // If they can't edit, they shouldn't protect.
1544 $errors[] = array( 'protect-cantedit' );
1546 } elseif ( $action == 'create' ) {
1547 $title_protection = $this->getTitleProtection();
1548 if( $title_protection ) {
1549 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1550 $title_protection['pt_create_perm'] = 'protect'; // B/C
1552 if( $title_protection['pt_create_perm'] == '' ||
1553 !$user->isAllowed( $title_protection['pt_create_perm'],
1554 $this->mNamespace
) ) {
1555 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1558 } elseif ( $action == 'move' ) {
1559 // Check for immobile pages
1560 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1561 // Specific message for this case
1562 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1563 } elseif ( !$this->isMovable() ) {
1564 // Less specific message for rarer cases
1565 $errors[] = array( 'immobile-source-page' );
1567 } elseif ( $action == 'move-target' ) {
1568 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1569 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1570 } elseif ( !$this->isMovable() ) {
1571 $errors[] = array( 'immobile-target-page' );
1578 * Check that the user isn't blocked from editting.
1580 * @param $action String the action to check
1581 * @param $user User to check
1582 * @param $errors Array list of current errors
1583 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1584 * @param $short Boolean short circuit on first error
1586 * @return Array list of errors
1588 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1589 if( !$doExpensiveQueries ) {
1593 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1595 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1596 $errors[] = array( 'confirmedittext' );
1599 if ( in_array( $action, array( 'read', 'createaccount', 'unblock' ) ) ){
1600 // Edit blocks should not affect reading.
1601 // Account creation blocks handled at userlogin.
1602 // Unblocking handled in SpecialUnblock
1603 } elseif( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ){
1604 // Don't block the user from editing their own talk page unless they've been
1605 // explicitly blocked from that too.
1606 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1607 $block = $user->mBlock
;
1609 // This is from OutputPage::blockedPage
1610 // Copied at r23888 by werdna
1612 $id = $user->blockedBy();
1613 $reason = $user->blockedFor();
1614 if ( $reason == '' ) {
1615 $reason = wfMsg( 'blockednoreason' );
1617 $ip = $user->getRequest()->getIP();
1619 if ( is_numeric( $id ) ) {
1620 $name = User
::whoIs( $id );
1625 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1626 $blockid = $block->getId();
1627 $blockExpiry = $user->mBlock
->mExpiry
;
1628 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1629 if ( $blockExpiry == 'infinity' ) {
1630 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1632 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1635 $intended = strval( $user->mBlock
->getTarget() );
1637 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1638 $blockid, $blockExpiry, $intended, $blockTimestamp );
1645 * Can $user perform $action on this page? This is an internal function,
1646 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1647 * checks on wfReadOnly() and blocks)
1649 * @param $action String action that permission needs to be checked for
1650 * @param $user User to check
1651 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1652 * @param $short Bool Set this to true to stop after the first permission error.
1653 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1655 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1656 wfProfileIn( __METHOD__
);
1660 'checkQuickPermissions',
1661 'checkPermissionHooks',
1662 'checkSpecialsAndNSPermissions',
1663 'checkCSSandJSPermissions',
1664 'checkPageRestrictions',
1665 'checkCascadingSourcesRestrictions',
1666 'checkActionPermissions',
1670 while( count( $checks ) > 0 &&
1671 !( $short && count( $errors ) > 0 ) ) {
1672 $method = array_shift( $checks );
1673 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1676 wfProfileOut( __METHOD__
);
1681 * Is this title subject to title protection?
1682 * Title protection is the one applied against creation of such title.
1684 * @return Mixed An associative array representing any existent title
1685 * protection, or false if there's none.
1687 private function getTitleProtection() {
1688 // Can't protect pages in special namespaces
1689 if ( $this->getNamespace() < 0 ) {
1693 // Can't protect pages that exist.
1694 if ( $this->exists() ) {
1698 if ( !isset( $this->mTitleProtection
) ) {
1699 $dbr = wfGetDB( DB_SLAVE
);
1700 $res = $dbr->select( 'protected_titles', '*',
1701 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1704 // fetchRow returns false if there are no rows.
1705 $this->mTitleProtection
= $dbr->fetchRow( $res );
1707 return $this->mTitleProtection
;
1711 * Update the title protection status
1713 * @param $create_perm String Permission required for creation
1714 * @param $reason String Reason for protection
1715 * @param $expiry String Expiry timestamp
1716 * @return boolean true
1718 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1719 global $wgUser, $wgContLang;
1721 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1722 && $expiry == $this->mRestrictionsExpiry
['create'] ) {
1727 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1729 $dbw = wfGetDB( DB_MASTER
);
1731 $encodedExpiry = $dbw->encodeExpiry( $expiry );
1733 $expiry_description = '';
1734 if ( $encodedExpiry != $dbw->getInfinity() ) {
1735 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1736 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1738 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1741 # Update protection table
1742 if ( $create_perm != '' ) {
1743 $this->mTitleProtection
= array(
1744 'pt_namespace' => $namespace,
1745 'pt_title' => $title,
1746 'pt_create_perm' => $create_perm,
1747 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1748 'pt_expiry' => $encodedExpiry,
1749 'pt_user' => $wgUser->getId(),
1750 'pt_reason' => $reason,
1752 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1753 $this->mTitleProtection
, __METHOD__
);
1755 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1756 'pt_title' => $title ), __METHOD__
);
1757 $this->mTitleProtection
= false;
1760 # Update the protection log
1761 if ( $dbw->affectedRows() ) {
1762 $log = new LogPage( 'protect' );
1764 if ( $create_perm ) {
1765 $params = array( "[create=$create_perm] $expiry_description", '' );
1766 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1768 $log->addEntry( 'unprotect', $this, $reason );
1776 * Remove any title protection due to page existing
1778 public function deleteTitleProtection() {
1779 $dbw = wfGetDB( DB_MASTER
);
1783 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1786 $this->mTitleProtection
= false;
1790 * Would anybody with sufficient privileges be able to move this page?
1791 * Some pages just aren't movable.
1793 * @return Bool TRUE or FALSE
1795 public function isMovable() {
1796 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
1797 // Interwiki title or immovable namespace. Hooks don't get to override here
1802 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
1807 * Can $wgUser read this page?
1810 * @todo fold these checks into userCan()
1812 public function userCanRead() {
1813 global $wgUser, $wgGroupPermissions;
1815 static $useShortcut = null;
1817 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1818 if ( is_null( $useShortcut ) ) {
1819 global $wgRevokePermissions;
1820 $useShortcut = true;
1821 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1822 # Not a public wiki, so no shortcut
1823 $useShortcut = false;
1824 } elseif ( !empty( $wgRevokePermissions ) ) {
1826 * Iterate through each group with permissions being revoked (key not included since we don't care
1827 * what the group name is), then check if the read permission is being revoked. If it is, then
1828 * we don't use the shortcut below since the user might not be able to read, even though anon
1829 * reading is allowed.
1831 foreach ( $wgRevokePermissions as $perms ) {
1832 if ( !empty( $perms['read'] ) ) {
1833 # We might be removing the read right from the user, so no shortcut
1834 $useShortcut = false;
1842 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1843 if ( $result !== null ) {
1847 # Shortcut for public wikis, allows skipping quite a bit of code
1848 if ( $useShortcut ) {
1852 if ( $wgUser->isAllowed( 'read' ) ) {
1855 global $wgWhitelistRead;
1857 # Always grant access to the login page.
1858 # Even anons need to be able to log in.
1859 if ( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'ChangePassword' ) ) {
1863 # Bail out if there isn't whitelist
1864 if ( !is_array( $wgWhitelistRead ) ) {
1868 # Check for explicit whitelisting
1869 $name = $this->getPrefixedText();
1870 $dbName = $this->getPrefixedDBKey();
1871 // Check with and without underscores
1872 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) )
1875 # Old settings might have the title prefixed with
1876 # a colon for main-namespace pages
1877 if ( $this->getNamespace() == NS_MAIN
) {
1878 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1883 # If it's a special page, ditch the subpage bit and check again
1884 if ( $this->getNamespace() == NS_SPECIAL
) {
1885 $name = $this->getDBkey();
1886 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
1887 if ( $name === false ) {
1888 # Invalid special page, but we show standard login required message
1892 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1893 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1903 * Is this the mainpage?
1904 * @note Title::newFromText seams to be sufficiently optimized by the title
1905 * cache that we don't need to over-optimize by doing direct comparisons and
1906 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1907 * ends up reporting something differently than $title->isMainPage();
1912 public function isMainPage() {
1913 return $this->equals( Title
::newMainPage() );
1917 * Is this a talk page of some sort?
1921 public function isTalkPage() {
1922 return MWNamespace
::isTalk( $this->getNamespace() );
1926 * Is this a subpage?
1930 public function isSubpage() {
1931 return MWNamespace
::hasSubpages( $this->mNamespace
)
1932 ?
strpos( $this->getText(), '/' ) !== false
1937 * Does this have subpages? (Warning, usually requires an extra DB query.)
1941 public function hasSubpages() {
1942 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1947 # We dynamically add a member variable for the purpose of this method
1948 # alone to cache the result. There's no point in having it hanging
1949 # around uninitialized in every Title object; therefore we only add it
1950 # if needed and don't declare it statically.
1951 if ( isset( $this->mHasSubpages
) ) {
1952 return $this->mHasSubpages
;
1955 $subpages = $this->getSubpages( 1 );
1956 if ( $subpages instanceof TitleArray
) {
1957 return $this->mHasSubpages
= (bool)$subpages->count();
1959 return $this->mHasSubpages
= false;
1963 * Get all subpages of this page.
1965 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
1966 * @return mixed TitleArray, or empty array if this page's namespace
1967 * doesn't allow subpages
1969 public function getSubpages( $limit = -1 ) {
1970 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
1974 $dbr = wfGetDB( DB_SLAVE
);
1975 $conds['page_namespace'] = $this->getNamespace();
1976 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1978 if ( $limit > -1 ) {
1979 $options['LIMIT'] = $limit;
1981 return $this->mSubpages
= TitleArray
::newFromResult(
1982 $dbr->select( 'page',
1983 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1992 * Does that page contain wikitext, or it is JS, CSS or whatever?
1996 public function isWikitextPage() {
1997 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
1998 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
2003 * Could this page contain custom CSS or JavaScript, based
2008 public function isCssOrJsPage() {
2009 $retval = $this->mNamespace
== NS_MEDIAWIKI
2010 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
2011 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
2016 * Is this a .css or .js subpage of a user page?
2019 public function isCssJsSubpage() {
2020 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
2024 * Is this a *valid* .css or .js subpage of a user page?
2027 * @deprecated since 1.17
2029 public function isValidCssJsSubpage() {
2030 return $this->isCssJsSubpage();
2034 * Trim down a .css or .js subpage title to get the corresponding skin name
2036 * @return string containing skin name from .css or .js subpage title
2038 public function getSkinFromCssJsSubpage() {
2039 $subpage = explode( '/', $this->mTextform
);
2040 $subpage = $subpage[ count( $subpage ) - 1 ];
2041 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
2045 * Is this a .css subpage of a user page?
2049 public function isCssSubpage() {
2050 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
2054 * Is this a .js subpage of a user page?
2058 public function isJsSubpage() {
2059 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
2063 * Protect css subpages of user pages: can $wgUser edit
2066 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2069 public function userCanEditCssSubpage() {
2071 wfDeprecated( __METHOD__
);
2072 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2073 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2077 * Protect js subpages of user pages: can $wgUser edit
2080 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2083 public function userCanEditJsSubpage() {
2085 wfDeprecated( __METHOD__
);
2086 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2087 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2091 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2093 * @return Bool If the page is subject to cascading restrictions.
2095 public function isCascadeProtected() {
2096 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2097 return ( $sources > 0 );
2101 * Cascading protection: Get the source of any cascading restrictions on this page.
2103 * @param $getPages Bool Whether or not to retrieve the actual pages
2104 * that the restrictions have come from.
2105 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2106 * have come, false for none, or true if such restrictions exist, but $getPages
2107 * was not set. The restriction array is an array of each type, each of which
2108 * contains a array of unique groups.
2110 public function getCascadeProtectionSources( $getPages = true ) {
2112 $pagerestrictions = array();
2114 if ( isset( $this->mCascadeSources
) && $getPages ) {
2115 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2116 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2117 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2120 wfProfileIn( __METHOD__
);
2122 $dbr = wfGetDB( DB_SLAVE
);
2124 if ( $this->getNamespace() == NS_FILE
) {
2125 $tables = array( 'imagelinks', 'page_restrictions' );
2126 $where_clauses = array(
2127 'il_to' => $this->getDBkey(),
2132 $tables = array( 'templatelinks', 'page_restrictions' );
2133 $where_clauses = array(
2134 'tl_namespace' => $this->getNamespace(),
2135 'tl_title' => $this->getDBkey(),
2142 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2143 'pr_expiry', 'pr_type', 'pr_level' );
2144 $where_clauses[] = 'page_id=pr_page';
2147 $cols = array( 'pr_expiry' );
2150 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2152 $sources = $getPages ?
array() : false;
2153 $now = wfTimestampNow();
2154 $purgeExpired = false;
2156 foreach ( $res as $row ) {
2157 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2158 if ( $expiry > $now ) {
2160 $page_id = $row->pr_page
;
2161 $page_ns = $row->page_namespace
;
2162 $page_title = $row->page_title
;
2163 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2164 # Add groups needed for each restriction type if its not already there
2165 # Make sure this restriction type still exists
2167 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2168 $pagerestrictions[$row->pr_type
] = array();
2171 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2172 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2173 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2179 // Trigger lazy purge of expired restrictions from the db
2180 $purgeExpired = true;
2183 if ( $purgeExpired ) {
2184 Title
::purgeExpiredRestrictions();
2188 $this->mCascadeSources
= $sources;
2189 $this->mCascadingRestrictions
= $pagerestrictions;
2191 $this->mHasCascadingRestrictions
= $sources;
2194 wfProfileOut( __METHOD__
);
2195 return array( $sources, $pagerestrictions );
2199 * Returns cascading restrictions for the current article
2203 function areRestrictionsCascading() {
2204 if ( !$this->mRestrictionsLoaded
) {
2205 $this->loadRestrictions();
2208 return $this->mCascadeRestriction
;
2212 * Loads a string into mRestrictions array
2214 * @param $res Resource restrictions as an SQL result.
2215 * @param $oldFashionedRestrictions String comma-separated list of page
2216 * restrictions from page table (pre 1.10)
2218 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2221 foreach ( $res as $row ) {
2225 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2229 * Compiles list of active page restrictions from both page table (pre 1.10)
2230 * and page_restrictions table for this existing page.
2231 * Public for usage by LiquidThreads.
2233 * @param $rows array of db result objects
2234 * @param $oldFashionedRestrictions string comma-separated list of page
2235 * restrictions from page table (pre 1.10)
2237 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2239 $dbr = wfGetDB( DB_SLAVE
);
2241 $restrictionTypes = $this->getRestrictionTypes();
2243 foreach ( $restrictionTypes as $type ) {
2244 $this->mRestrictions
[$type] = array();
2245 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2248 $this->mCascadeRestriction
= false;
2250 # Backwards-compatibility: also load the restrictions from the page record (old format).
2252 if ( $oldFashionedRestrictions === null ) {
2253 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2254 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2257 if ( $oldFashionedRestrictions != '' ) {
2259 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2260 $temp = explode( '=', trim( $restrict ) );
2261 if ( count( $temp ) == 1 ) {
2262 // old old format should be treated as edit/move restriction
2263 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2264 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2266 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2270 $this->mOldRestrictions
= true;
2274 if ( count( $rows ) ) {
2275 # Current system - load second to make them override.
2276 $now = wfTimestampNow();
2277 $purgeExpired = false;
2279 # Cycle through all the restrictions.
2280 foreach ( $rows as $row ) {
2282 // Don't take care of restrictions types that aren't allowed
2283 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2286 // This code should be refactored, now that it's being used more generally,
2287 // But I don't really see any harm in leaving it in Block for now -werdna
2288 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2290 // Only apply the restrictions if they haven't expired!
2291 if ( !$expiry ||
$expiry > $now ) {
2292 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2293 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2295 $this->mCascadeRestriction |
= $row->pr_cascade
;
2297 // Trigger a lazy purge of expired restrictions
2298 $purgeExpired = true;
2302 if ( $purgeExpired ) {
2303 Title
::purgeExpiredRestrictions();
2307 $this->mRestrictionsLoaded
= true;
2311 * Load restrictions from the page_restrictions table
2313 * @param $oldFashionedRestrictions String comma-separated list of page
2314 * restrictions from page table (pre 1.10)
2316 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2318 if ( !$this->mRestrictionsLoaded
) {
2319 if ( $this->exists() ) {
2320 $dbr = wfGetDB( DB_SLAVE
);
2322 $res = $dbr->select(
2323 'page_restrictions',
2325 array( 'pr_page' => $this->getArticleId() ),
2329 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2331 $title_protection = $this->getTitleProtection();
2333 if ( $title_protection ) {
2334 $now = wfTimestampNow();
2335 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2337 if ( !$expiry ||
$expiry > $now ) {
2338 // Apply the restrictions
2339 $this->mRestrictionsExpiry
['create'] = $expiry;
2340 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2341 } else { // Get rid of the old restrictions
2342 Title
::purgeExpiredRestrictions();
2343 $this->mTitleProtection
= false;
2346 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2348 $this->mRestrictionsLoaded
= true;
2354 * Purge expired restrictions from the page_restrictions table
2356 static function purgeExpiredRestrictions() {
2357 $dbw = wfGetDB( DB_MASTER
);
2359 'page_restrictions',
2360 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2366 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2372 * Accessor/initialisation for mRestrictions
2374 * @param $action String action that permission needs to be checked for
2375 * @return Array of Strings the array of groups allowed to edit this article
2377 public function getRestrictions( $action ) {
2378 if ( !$this->mRestrictionsLoaded
) {
2379 $this->loadRestrictions();
2381 return isset( $this->mRestrictions
[$action] )
2382 ?
$this->mRestrictions
[$action]
2387 * Get the expiry time for the restriction against a given action
2389 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2390 * or not protected at all, or false if the action is not recognised.
2392 public function getRestrictionExpiry( $action ) {
2393 if ( !$this->mRestrictionsLoaded
) {
2394 $this->loadRestrictions();
2396 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2400 * Is there a version of this page in the deletion archive?
2402 * @return Int the number of archived revisions
2404 public function isDeleted() {
2405 if ( $this->getNamespace() < 0 ) {
2408 $dbr = wfGetDB( DB_SLAVE
);
2410 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2411 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2414 if ( $this->getNamespace() == NS_FILE
) {
2415 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2416 array( 'fa_name' => $this->getDBkey() ),
2425 * Is there a version of this page in the deletion archive?
2429 public function isDeletedQuick() {
2430 if ( $this->getNamespace() < 0 ) {
2433 $dbr = wfGetDB( DB_SLAVE
);
2434 $deleted = (bool)$dbr->selectField( 'archive', '1',
2435 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2438 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2439 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2440 array( 'fa_name' => $this->getDBkey() ),
2448 * Get the article ID for this Title from the link cache,
2449 * adding it if necessary
2451 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2453 * @return Int the ID
2455 public function getArticleID( $flags = 0 ) {
2456 if ( $this->getNamespace() < 0 ) {
2457 return $this->mArticleID
= 0;
2459 $linkCache = LinkCache
::singleton();
2460 if ( $flags & self
::GAID_FOR_UPDATE
) {
2461 $oldUpdate = $linkCache->forUpdate( true );
2462 $linkCache->clearLink( $this );
2463 $this->mArticleID
= $linkCache->addLinkObj( $this );
2464 $linkCache->forUpdate( $oldUpdate );
2466 if ( -1 == $this->mArticleID
) {
2467 $this->mArticleID
= $linkCache->addLinkObj( $this );
2470 return $this->mArticleID
;
2474 * Is this an article that is a redirect page?
2475 * Uses link cache, adding it if necessary
2477 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2480 public function isRedirect( $flags = 0 ) {
2481 if ( !is_null( $this->mRedirect
) ) {
2482 return $this->mRedirect
;
2484 # Calling getArticleID() loads the field from cache as needed
2485 if ( !$this->getArticleID( $flags ) ) {
2486 return $this->mRedirect
= false;
2488 $linkCache = LinkCache
::singleton();
2489 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2491 return $this->mRedirect
;
2495 * What is the length of this page?
2496 * Uses link cache, adding it if necessary
2498 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2501 public function getLength( $flags = 0 ) {
2502 if ( $this->mLength
!= -1 ) {
2503 return $this->mLength
;
2505 # Calling getArticleID() loads the field from cache as needed
2506 if ( !$this->getArticleID( $flags ) ) {
2507 return $this->mLength
= 0;
2509 $linkCache = LinkCache
::singleton();
2510 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2512 return $this->mLength
;
2516 * What is the page_latest field for this page?
2518 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2519 * @return Int or 0 if the page doesn't exist
2521 public function getLatestRevID( $flags = 0 ) {
2522 if ( $this->mLatestID
!== false ) {
2523 return intval( $this->mLatestID
);
2525 # Calling getArticleID() loads the field from cache as needed
2526 if ( !$this->getArticleID( $flags ) ) {
2527 return $this->mLatestID
= 0;
2529 $linkCache = LinkCache
::singleton();
2530 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2532 return $this->mLatestID
;
2536 * This clears some fields in this object, and clears any associated
2537 * keys in the "bad links" section of the link cache.
2539 * - This is called from Article::doEdit() and Article::insertOn() to allow
2540 * loading of the new page_id. It's also called from
2541 * Article::doDeleteArticle()
2543 * @param $newid Int the new Article ID
2545 public function resetArticleID( $newid ) {
2546 $linkCache = LinkCache
::singleton();
2547 $linkCache->clearLink( $this );
2549 if ( $newid === false ) {
2550 $this->mArticleID
= -1;
2552 $this->mArticleID
= intval( $newid );
2554 $this->mRestrictionsLoaded
= false;
2555 $this->mRestrictions
= array();
2556 $this->mRedirect
= null;
2557 $this->mLength
= -1;
2558 $this->mLatestID
= false;
2562 * Updates page_touched for this page; called from LinksUpdate.php
2564 * @return Bool true if the update succeded
2566 public function invalidateCache() {
2567 if ( wfReadOnly() ) {
2570 $dbw = wfGetDB( DB_MASTER
);
2571 $success = $dbw->update(
2573 array( 'page_touched' => $dbw->timestamp() ),
2577 HTMLFileCache
::clearFileCache( $this );
2582 * Prefix some arbitrary text with the namespace or interwiki prefix
2585 * @param $name String the text
2586 * @return String the prefixed text
2589 private function prefix( $name ) {
2591 if ( $this->mInterwiki
!= '' ) {
2592 $p = $this->mInterwiki
. ':';
2595 if ( 0 != $this->mNamespace
) {
2596 $p .= $this->getNsText() . ':';
2602 * Returns a simple regex that will match on characters and sequences invalid in titles.
2603 * Note that this doesn't pick up many things that could be wrong with titles, but that
2604 * replacing this regex with something valid will make many titles valid.
2606 * @return String regex string
2608 static function getTitleInvalidRegex() {
2609 static $rxTc = false;
2611 # Matching titles will be held as illegal.
2613 # Any character not allowed is forbidden...
2614 '[^' . Title
::legalChars() . ']' .
2615 # URL percent encoding sequences interfere with the ability
2616 # to round-trip titles -- you can't link to them consistently.
2617 '|%[0-9A-Fa-f]{2}' .
2618 # XML/HTML character references produce similar issues.
2619 '|&[A-Za-z0-9\x80-\xff]+;' .
2621 '|&#x[0-9A-Fa-f]+;' .
2629 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2631 * @param $text String containing title to capitalize
2632 * @param $ns int namespace index, defaults to NS_MAIN
2633 * @return String containing capitalized title
2635 public static function capitalize( $text, $ns = NS_MAIN
) {
2638 if ( MWNamespace
::isCapitalized( $ns ) ) {
2639 return $wgContLang->ucfirst( $text );
2646 * Secure and split - main initialisation function for this object
2648 * Assumes that mDbkeyform has been set, and is urldecoded
2649 * and uses underscores, but not otherwise munged. This function
2650 * removes illegal characters, splits off the interwiki and
2651 * namespace prefixes, sets the other forms, and canonicalizes
2654 * @return Bool true on success
2656 private function secureAndSplit() {
2657 global $wgContLang, $wgLocalInterwiki;
2660 $this->mInterwiki
= $this->mFragment
= '';
2661 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2663 $dbkey = $this->mDbkeyform
;
2665 # Strip Unicode bidi override characters.
2666 # Sometimes they slip into cut-n-pasted page titles, where the
2667 # override chars get included in list displays.
2668 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2670 # Clean up whitespace
2671 # Note: use of the /u option on preg_replace here will cause
2672 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2673 # conveniently disabling them.
2674 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2675 $dbkey = trim( $dbkey, '_' );
2677 if ( $dbkey == '' ) {
2681 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2682 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2686 $this->mDbkeyform
= $dbkey;
2688 # Initial colon indicates main namespace rather than specified default
2689 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2690 if ( ':' == $dbkey[0] ) {
2691 $this->mNamespace
= NS_MAIN
;
2692 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2693 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2696 # Namespace or interwiki prefix
2698 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2701 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2703 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2704 # Ordinary namespace
2706 $this->mNamespace
= $ns;
2707 # For Talk:X pages, check if X has a "namespace" prefix
2708 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2709 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2710 # Disallow Talk:File:x type titles...
2712 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2713 # Disallow Talk:Interwiki:x type titles...
2717 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2718 if ( !$firstPass ) {
2719 # Can't make a local interwiki link to an interwiki link.
2720 # That's just crazy!
2726 $this->mInterwiki
= $wgContLang->lc( $p );
2728 # Redundant interwiki prefix to the local wiki
2729 if ( $wgLocalInterwiki !== false
2730 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
2732 if ( $dbkey == '' ) {
2733 # Can't have an empty self-link
2736 $this->mInterwiki
= '';
2738 # Do another namespace split...
2742 # If there's an initial colon after the interwiki, that also
2743 # resets the default namespace
2744 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2745 $this->mNamespace
= NS_MAIN
;
2746 $dbkey = substr( $dbkey, 1 );
2749 # If there's no recognized interwiki or namespace,
2750 # then let the colon expression be part of the title.
2755 # We already know that some pages won't be in the database!
2756 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2757 $this->mArticleID
= 0;
2759 $fragment = strstr( $dbkey, '#' );
2760 if ( false !== $fragment ) {
2761 $this->setFragment( $fragment );
2762 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2763 # remove whitespace again: prevents "Foo_bar_#"
2764 # becoming "Foo_bar_"
2765 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2768 # Reject illegal characters.
2769 $rxTc = self
::getTitleInvalidRegex();
2770 if ( preg_match( $rxTc, $dbkey ) ) {
2774 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2775 # reachable due to the way web browsers deal with 'relative' URLs.
2776 # Also, they conflict with subpage syntax. Forbid them explicitly.
2777 if ( strpos( $dbkey, '.' ) !== false &&
2778 ( $dbkey === '.' ||
$dbkey === '..' ||
2779 strpos( $dbkey, './' ) === 0 ||
2780 strpos( $dbkey, '../' ) === 0 ||
2781 strpos( $dbkey, '/./' ) !== false ||
2782 strpos( $dbkey, '/../' ) !== false ||
2783 substr( $dbkey, -2 ) == '/.' ||
2784 substr( $dbkey, -3 ) == '/..' ) )
2789 # Magic tilde sequences? Nu-uh!
2790 if ( strpos( $dbkey, '~~~' ) !== false ) {
2794 # Limit the size of titles to 255 bytes. This is typically the size of the
2795 # underlying database field. We make an exception for special pages, which
2796 # don't need to be stored in the database, and may edge over 255 bytes due
2797 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2798 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2799 strlen( $dbkey ) > 512 )
2804 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2805 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2806 # other site might be case-sensitive.
2807 $this->mUserCaseDBKey
= $dbkey;
2808 if ( $this->mInterwiki
== '' ) {
2809 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2812 # Can't make a link to a namespace alone... "empty" local links can only be
2813 # self-links with a fragment identifier.
2814 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
2818 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2819 // IP names are not allowed for accounts, and can only be referring to
2820 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2821 // there are numerous ways to present the same IP. Having sp:contribs scan
2822 // them all is silly and having some show the edits and others not is
2823 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2824 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
2825 ? IP
::sanitizeIP( $dbkey )
2828 // Any remaining initial :s are illegal.
2829 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2834 $this->mDbkeyform
= $dbkey;
2835 $this->mUrlform
= wfUrlencode( $dbkey );
2837 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2843 * Set the fragment for this title. Removes the first character from the
2844 * specified fragment before setting, so it assumes you're passing it with
2847 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2848 * Still in active use privately.
2850 * @param $fragment String text
2852 public function setFragment( $fragment ) {
2853 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2856 public function setInterwiki( $interwiki ) {
2857 $this->mInterwiki
= $interwiki;
2861 * Get a Title object associated with the talk page of this article
2863 * @return Title the object for the talk page
2865 public function getTalkPage() {
2866 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2870 * Get a title object associated with the subject page of this
2873 * @return Title the object for the subject page
2875 public function getSubjectPage() {
2876 // Is this the same title?
2877 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2878 if ( $this->getNamespace() == $subjectNS ) {
2881 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2885 * Get an array of Title objects linking to this Title
2886 * Also stores the IDs in the link cache.
2888 * WARNING: do not use this function on arbitrary user-supplied titles!
2889 * On heavily-used templates it will max out the memory.
2891 * @param $options Array: may be FOR UPDATE
2892 * @param $table String: table name
2893 * @param $prefix String: fields prefix
2894 * @return Array of Title objects linking here
2896 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2897 $linkCache = LinkCache
::singleton();
2899 if ( count( $options ) > 0 ) {
2900 $db = wfGetDB( DB_MASTER
);
2902 $db = wfGetDB( DB_SLAVE
);
2906 array( 'page', $table ),
2907 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2909 "{$prefix}_from=page_id",
2910 "{$prefix}_namespace" => $this->getNamespace(),
2911 "{$prefix}_title" => $this->getDBkey() ),
2917 if ( $db->numRows( $res ) ) {
2918 foreach ( $res as $row ) {
2919 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
2921 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
2922 $retVal[] = $titleObj;
2930 * Get an array of Title objects using this Title as a template
2931 * Also stores the IDs in the link cache.
2933 * WARNING: do not use this function on arbitrary user-supplied titles!
2934 * On heavily-used templates it will max out the memory.
2936 * @param $options Array: may be FOR UPDATE
2937 * @return Array of Title the Title objects linking here
2939 public function getTemplateLinksTo( $options = array() ) {
2940 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2944 * Get an array of Title objects referring to non-existent articles linked from this page
2946 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2947 * @return Array of Title the Title objects
2949 public function getBrokenLinksFrom() {
2950 if ( $this->getArticleId() == 0 ) {
2951 # All links from article ID 0 are false positives
2955 $dbr = wfGetDB( DB_SLAVE
);
2956 $res = $dbr->select(
2957 array( 'page', 'pagelinks' ),
2958 array( 'pl_namespace', 'pl_title' ),
2960 'pl_from' => $this->getArticleId(),
2961 'page_namespace IS NULL'
2963 __METHOD__
, array(),
2967 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2973 foreach ( $res as $row ) {
2974 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2981 * Get a list of URLs to purge from the Squid cache when this
2984 * @return Array of String the URLs
2986 public function getSquidURLs() {
2990 $this->getInternalURL(),
2991 $this->getInternalURL( 'action=history' )
2994 // purge variant urls as well
2995 if ( $wgContLang->hasVariants() ) {
2996 $variants = $wgContLang->getVariants();
2997 foreach ( $variants as $vCode ) {
2998 $urls[] = $this->getInternalURL( '', $vCode );
3006 * Purge all applicable Squid URLs
3008 public function purgeSquid() {
3010 if ( $wgUseSquid ) {
3011 $urls = $this->getSquidURLs();
3012 $u = new SquidUpdate( $urls );
3018 * Move this page without authentication
3020 * @param $nt Title the new page Title
3021 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3023 public function moveNoAuth( &$nt ) {
3024 return $this->moveTo( $nt, false );
3028 * Check whether a given move operation would be valid.
3029 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3031 * @param $nt Title the new title
3032 * @param $auth Bool indicates whether $wgUser's permissions
3034 * @param $reason String is the log summary of the move, used for spam checking
3035 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3037 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3042 // Normally we'd add this to $errors, but we'll get
3043 // lots of syntax errors if $nt is not an object
3044 return array( array( 'badtitletext' ) );
3046 if ( $this->equals( $nt ) ) {
3047 $errors[] = array( 'selfmove' );
3049 if ( !$this->isMovable() ) {
3050 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3052 if ( $nt->getInterwiki() != '' ) {
3053 $errors[] = array( 'immobile-target-namespace-iw' );
3055 if ( !$nt->isMovable() ) {
3056 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3059 $oldid = $this->getArticleID();
3060 $newid = $nt->getArticleID();
3062 if ( strlen( $nt->getDBkey() ) < 1 ) {
3063 $errors[] = array( 'articleexists' );
3065 if ( ( $this->getDBkey() == '' ) ||
3067 ( $nt->getDBkey() == '' ) ) {
3068 $errors[] = array( 'badarticleerror' );
3071 // Image-specific checks
3072 if ( $this->getNamespace() == NS_FILE
) {
3073 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3076 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3077 $errors[] = array( 'nonfile-cannot-move-to-file' );
3081 $errors = wfMergeErrorArrays( $errors,
3082 $this->getUserPermissionsErrors( 'move', $wgUser ),
3083 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3084 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3085 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3088 $match = EditPage
::matchSummarySpamRegex( $reason );
3089 if ( $match !== false ) {
3090 // This is kind of lame, won't display nice
3091 $errors[] = array( 'spamprotectiontext' );
3095 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3096 $errors[] = array( 'hookaborted', $err );
3099 # The move is allowed only if (1) the target doesn't exist, or
3100 # (2) the target is a redirect to the source, and has no history
3101 # (so we can undo bad moves right after they're done).
3103 if ( 0 != $newid ) { # Target exists; check for validity
3104 if ( !$this->isValidMoveTarget( $nt ) ) {
3105 $errors[] = array( 'articleexists' );
3108 $tp = $nt->getTitleProtection();
3109 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3110 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3111 $errors[] = array( 'cantmove-titleprotected' );
3114 if ( empty( $errors ) ) {
3121 * Check if the requested move target is a valid file move target
3122 * @param Title $nt Target title
3123 * @return array List of errors
3125 protected function validateFileMoveOperation( $nt ) {
3130 if ( $nt->getNamespace() != NS_FILE
) {
3131 $errors[] = array( 'imagenocrossnamespace' );
3134 $file = wfLocalFile( $this );
3135 if ( $file->exists() ) {
3136 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3137 $errors[] = array( 'imageinvalidfilename' );
3139 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3140 $errors[] = array( 'imagetypemismatch' );
3144 $destFile = wfLocalFile( $nt );
3145 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3146 $errors[] = array( 'file-exists-sharedrepo' );
3153 * Move a title to a new location
3155 * @param $nt Title the new title
3156 * @param $auth Bool indicates whether $wgUser's permissions
3158 * @param $reason String the reason for the move
3159 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3160 * Ignored if the user doesn't have the suppressredirect right.
3161 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3163 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3164 global $wgEnableInterwikiTemplatesTracking, $wgGlobalDatabase;
3166 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3167 if ( is_array( $err ) ) {
3171 // If it is a file, move it first.
3172 // It is done before all other moving stuff is done because it's hard to revert.
3173 $dbw = wfGetDB( DB_MASTER
);
3174 if ( $this->getNamespace() == NS_FILE
) {
3175 $file = wfLocalFile( $this );
3176 if ( $file->exists() ) {
3177 $status = $file->move( $nt );
3178 if ( !$status->isOk() ) {
3179 return $status->getErrorsArray();
3183 // Clear RepoGroup process cache
3184 RepoGroup
::singleton()->clearCache( $this );
3185 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3187 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3188 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3189 $protected = $this->isProtected();
3190 $pageCountChange = ( $createRedirect ?
1 : 0 ) - ( $nt->exists() ?
1 : 0 );
3192 // Do the actual move
3193 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
3194 if ( is_array( $err ) ) {
3195 # @todo FIXME: What about the File we have already moved?
3200 $redirid = $this->getArticleID();
3202 // Refresh the sortkey for this row. Be careful to avoid resetting
3203 // cl_timestamp, which may disturb time-based lists on some sites.
3204 $prefixes = $dbw->select(
3206 array( 'cl_sortkey_prefix', 'cl_to' ),
3207 array( 'cl_from' => $pageid ),
3210 foreach ( $prefixes as $prefixRow ) {
3211 $prefix = $prefixRow->cl_sortkey_prefix
;
3212 $catTo = $prefixRow->cl_to
;
3213 $dbw->update( 'categorylinks',
3215 'cl_sortkey' => Collation
::singleton()->getSortKey(
3216 $nt->getCategorySortkey( $prefix ) ),
3217 'cl_timestamp=cl_timestamp' ),
3219 'cl_from' => $pageid,
3220 'cl_to' => $catTo ),
3225 if ( $wgEnableInterwikiTemplatesTracking && $wgGlobalDatabase ) {
3226 $dbw2 = wfGetDB( DB_MASTER
, array(), $wgGlobalDatabase );
3227 $dbw2->update( 'globaltemplatelinks',
3228 array( 'gtl_from_namespace' => $nt->getNamespace(),
3229 'gtl_from_title' => $nt->getText() ),
3230 array ( 'gtl_from_page' => $pageid ),
3235 # Protect the redirect title as the title used to be...
3236 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3238 'pr_page' => $redirid,
3239 'pr_type' => 'pr_type',
3240 'pr_level' => 'pr_level',
3241 'pr_cascade' => 'pr_cascade',
3242 'pr_user' => 'pr_user',
3243 'pr_expiry' => 'pr_expiry'
3245 array( 'pr_page' => $pageid ),
3249 # Update the protection log
3250 $log = new LogPage( 'protect' );
3251 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3253 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3255 // @todo FIXME: $params?
3256 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3260 $oldnamespace = $this->getNamespace() & ~
1;
3261 $newnamespace = $nt->getNamespace() & ~
1;
3262 $oldtitle = $this->getDBkey();
3263 $newtitle = $nt->getDBkey();
3265 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3266 WatchedItem
::duplicateEntries( $this, $nt );
3269 # Update search engine
3270 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3272 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3278 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3279 # No longer a content page
3280 # Not viewed, edited, removing
3281 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3282 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3283 # Now a content page
3284 # Not viewed, edited, adding
3285 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
3286 } elseif ( $pageCountChange ) {
3288 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3297 # Update message cache for interface messages
3298 if ( $this->getNamespace() == NS_MEDIAWIKI
) {
3299 # @bug 17860: old article can be deleted, if this the case,
3300 # delete it from message cache
3301 if ( $this->getArticleID() === 0 ) {
3302 MessageCache
::singleton()->replace( $this->getDBkey(), false );
3304 $oldarticle = new Article( $this );
3305 MessageCache
::singleton()->replace( $this->getDBkey(), $oldarticle->getContent() );
3308 if ( $nt->getNamespace() == NS_MEDIAWIKI
) {
3309 $newarticle = new Article( $nt );
3310 MessageCache
::singleton()->replace( $nt->getDBkey(), $newarticle->getContent() );
3314 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3319 * Move page to a title which is either a redirect to the
3320 * source page or nonexistent
3322 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3323 * @param $reason String The reason for the move
3324 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3325 * if the user doesn't have the suppressredirect right
3327 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
3328 global $wgUser, $wgContLang, $wgEnableInterwikiTemplatesTracking, $wgGlobalDatabase;
3330 if ( $nt->exists() ) {
3331 $moveOverRedirect = true;
3332 $logType = 'move_redir';
3334 $moveOverRedirect = false;
3338 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3340 $logEntry = new ManualLogEntry( 'move', $logType );
3341 $logEntry->setPerformer( $wgUser );
3342 $logEntry->setTarget( $this );
3343 $logEntry->setComment( $reason );
3344 $logEntry->setParameters( array(
3345 '4::target' => $nt->getPrefixedText(),
3346 '5::noredir' => $redirectSuppressed ?
'1': '0',
3349 $formatter = LogFormatter
::newFromEntry( $logEntry );
3350 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3351 $comment = $formatter->getPlainActionText();
3353 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3355 # Truncate for whole multibyte characters.
3356 $comment = $wgContLang->truncate( $comment, 255 );
3358 $oldid = $this->getArticleID();
3359 $latest = $this->getLatestRevID();
3361 $dbw = wfGetDB( DB_MASTER
);
3363 if ( $moveOverRedirect ) {
3364 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3366 $newid = $nt->getArticleID();
3367 $newns = $nt->getNamespace();
3368 $newdbk = $nt->getDBkey();
3370 # Delete the old redirect. We don't save it to history since
3371 # by definition if we've got here it's rather uninteresting.
3372 # We have to remove it so that the next step doesn't trigger
3373 # a conflict on the unique namespace+title index...
3374 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3375 if ( !$dbw->cascadingDeletes() ) {
3376 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3377 global $wgUseTrackbacks;
3378 if ( $wgUseTrackbacks ) {
3379 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
3381 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3382 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3383 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3384 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3385 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3386 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3387 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3388 $dbw->delete( 'page_props', array( 'pp_page' => $newid ), __METHOD__
);
3390 // If the target page was recently created, it may have an entry in recentchanges still
3391 $dbw->delete( 'recentchanges',
3392 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3396 if ( $wgEnableInterwikiTemplatesTracking && $wgGlobalDatabase ) {
3397 $dbw2 = wfGetDB( DB_MASTER
, array(), $wgGlobalDatabase );
3398 $dbw2->delete( 'globaltemplatelinks',
3399 array( 'gtl_from_wiki' => wfGetID(),
3400 'gtl_from_page' => $newid ),
3405 # Save a null revision in the page's history notifying of the move
3406 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3407 if ( !is_object( $nullRevision ) ) {
3408 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3410 $nullRevId = $nullRevision->insertOn( $dbw );
3412 $now = wfTimestampNow();
3413 # Change the name of the target page:
3414 $dbw->update( 'page',
3416 'page_touched' => $dbw->timestamp( $now ),
3417 'page_namespace' => $nt->getNamespace(),
3418 'page_title' => $nt->getDBkey(),
3419 'page_latest' => $nullRevId,
3421 /* WHERE */ array( 'page_id' => $oldid ),
3424 $nt->resetArticleID( $oldid );
3426 $article = new Article( $nt );
3427 wfRunHooks( 'NewRevisionFromEditComplete',
3428 array( $article, $nullRevision, $latest, $wgUser ) );
3429 $article->setCachedLastEditTime( $now );
3431 # Recreate the redirect, this time in the other direction.
3432 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3433 $mwRedir = MagicWord
::get( 'redirect' );
3434 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3435 $redirectArticle = new Article( $this );
3436 $newid = $redirectArticle->insertOn( $dbw );
3437 if ( $newid ) { // sanity
3438 $redirectRevision = new Revision( array(
3440 'comment' => $comment,
3441 'text' => $redirectText ) );
3442 $redirectRevision->insertOn( $dbw );
3443 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3445 wfRunHooks( 'NewRevisionFromEditComplete',
3446 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3448 # Now, we record the link from the redirect to the new title.
3449 # It should have no other outgoing links...
3450 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3451 $dbw->insert( 'pagelinks',
3453 'pl_from' => $newid,
3454 'pl_namespace' => $nt->getNamespace(),
3455 'pl_title' => $nt->getDBkey() ),
3459 $this->resetArticleID( 0 );
3463 $logid = $logEntry->insert();
3464 $logEntry->publish( $logid );
3466 # Purge caches for old and new titles
3467 if ( $moveOverRedirect ) {
3468 # A simple purge is enough when moving over a redirect
3471 # Purge caches as per article creation, including any pages that link to this title
3472 Article
::onArticleCreate( $nt );
3474 $this->purgeSquid();
3478 * Move this page's subpages to be subpages of $nt
3480 * @param $nt Title Move target
3481 * @param $auth bool Whether $wgUser's permissions should be checked
3482 * @param $reason string The reason for the move
3483 * @param $createRedirect bool Whether to create redirects from the old subpages to
3484 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3485 * @return mixed array with old page titles as keys, and strings (new page titles) or
3486 * arrays (errors) as values, or an error array with numeric indices if no pages
3489 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3490 global $wgMaximumMovedPages;
3491 // Check permissions
3492 if ( !$this->userCan( 'move-subpages' ) ) {
3493 return array( 'cant-move-subpages' );
3495 // Do the source and target namespaces support subpages?
3496 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3497 return array( 'namespace-nosubpages',
3498 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3500 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3501 return array( 'namespace-nosubpages',
3502 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3505 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3508 foreach ( $subpages as $oldSubpage ) {
3510 if ( $count > $wgMaximumMovedPages ) {
3511 $retval[$oldSubpage->getPrefixedTitle()] =
3512 array( 'movepage-max-pages',
3513 $wgMaximumMovedPages );
3517 // We don't know whether this function was called before
3518 // or after moving the root page, so check both
3520 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3521 $oldSubpage->getArticleID() == $nt->getArticleId() )
3523 // When moving a page to a subpage of itself,
3524 // don't move it twice
3527 $newPageName = preg_replace(
3528 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3529 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3530 $oldSubpage->getDBkey() );
3531 if ( $oldSubpage->isTalkPage() ) {
3532 $newNs = $nt->getTalkPage()->getNamespace();
3534 $newNs = $nt->getSubjectPage()->getNamespace();
3536 # Bug 14385: we need makeTitleSafe because the new page names may
3537 # be longer than 255 characters.
3538 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3540 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3541 if ( $success === true ) {
3542 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3544 $retval[$oldSubpage->getPrefixedText()] = $success;
3551 * Checks if this page is just a one-rev redirect.
3552 * Adds lock, so don't use just for light purposes.
3556 public function isSingleRevRedirect() {
3557 $dbw = wfGetDB( DB_MASTER
);
3559 $row = $dbw->selectRow( 'page',
3560 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3563 array( 'FOR UPDATE' )
3565 # Cache some fields we may want
3566 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3567 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3568 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3569 if ( !$this->mRedirect
) {
3572 # Does the article have a history?
3573 $row = $dbw->selectField( array( 'page', 'revision' ),
3575 array( 'page_namespace' => $this->getNamespace(),
3576 'page_title' => $this->getDBkey(),
3578 'page_latest != rev_id'
3581 array( 'FOR UPDATE' )
3583 # Return true if there was no history
3584 return ( $row === false );
3588 * Checks if $this can be moved to a given Title
3589 * - Selects for update, so don't call it unless you mean business
3591 * @param $nt Title the new title to check
3594 public function isValidMoveTarget( $nt ) {
3595 # Is it an existing file?
3596 if ( $nt->getNamespace() == NS_FILE
) {
3597 $file = wfLocalFile( $nt );
3598 if ( $file->exists() ) {
3599 wfDebug( __METHOD__
. ": file exists\n" );
3603 # Is it a redirect with no history?
3604 if ( !$nt->isSingleRevRedirect() ) {
3605 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3608 # Get the article text
3609 $rev = Revision
::newFromTitle( $nt );
3610 $text = $rev->getText();
3611 # Does the redirect point to the source?
3612 # Or is it a broken self-redirect, usually caused by namespace collisions?
3614 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3615 $redirTitle = Title
::newFromText( $m[1] );
3616 if ( !is_object( $redirTitle ) ||
3617 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3618 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3619 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3624 wfDebug( __METHOD__
. ": failsafe\n" );
3631 * Can this title be added to a user's watchlist?
3633 * @return Bool TRUE or FALSE
3635 public function isWatchable() {
3636 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3640 * Get categories to which this Title belongs and return an array of
3641 * categories' names.
3643 * @return Array of parents in the form:
3644 * $parent => $currentarticle
3646 public function getParentCategories() {
3651 $titleKey = $this->getArticleId();
3653 if ( $titleKey === 0 ) {
3657 $dbr = wfGetDB( DB_SLAVE
);
3659 $res = $dbr->select( 'categorylinks', '*',
3661 'cl_from' => $titleKey,
3667 if ( $dbr->numRows( $res ) > 0 ) {
3668 foreach ( $res as $row ) {
3669 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3670 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3677 * Get a tree of parent categories
3679 * @param $children Array with the children in the keys, to check for circular refs
3680 * @return Array Tree of parent categories
3682 public function getParentCategoryTree( $children = array() ) {
3684 $parents = $this->getParentCategories();
3687 foreach ( $parents as $parent => $current ) {
3688 if ( array_key_exists( $parent, $children ) ) {
3689 # Circular reference
3690 $stack[$parent] = array();
3692 $nt = Title
::newFromText( $parent );
3694 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3704 * Get an associative array for selecting this title from
3707 * @return Array suitable for the $where parameter of DB::select()
3709 public function pageCond() {
3710 if ( $this->mArticleID
> 0 ) {
3711 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3712 return array( 'page_id' => $this->mArticleID
);
3714 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3719 * Get the revision ID of the previous revision
3721 * @param $revId Int Revision ID. Get the revision that was before this one.
3722 * @param $flags Int Title::GAID_FOR_UPDATE
3723 * @return Int|Bool Old revision ID, or FALSE if none exists
3725 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3726 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3727 return $db->selectField( 'revision', 'rev_id',
3729 'rev_page' => $this->getArticleId( $flags ),
3730 'rev_id < ' . intval( $revId )
3733 array( 'ORDER BY' => 'rev_id DESC' )
3738 * Get the revision ID of the next revision
3740 * @param $revId Int Revision ID. Get the revision that was after this one.
3741 * @param $flags Int Title::GAID_FOR_UPDATE
3742 * @return Int|Bool Next revision ID, or FALSE if none exists
3744 public function getNextRevisionID( $revId, $flags = 0 ) {
3745 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3746 return $db->selectField( 'revision', 'rev_id',
3748 'rev_page' => $this->getArticleId( $flags ),
3749 'rev_id > ' . intval( $revId )
3752 array( 'ORDER BY' => 'rev_id' )
3757 * Get the first revision of the page
3759 * @param $flags Int Title::GAID_FOR_UPDATE
3760 * @return Revision|Null if page doesn't exist
3762 public function getFirstRevision( $flags = 0 ) {
3763 $pageId = $this->getArticleId( $flags );
3765 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3766 $row = $db->selectRow( 'revision', '*',
3767 array( 'rev_page' => $pageId ),
3769 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3772 return new Revision( $row );
3779 * Get the oldest revision timestamp of this page
3781 * @param $flags Int Title::GAID_FOR_UPDATE
3782 * @return String: MW timestamp
3784 public function getEarliestRevTime( $flags = 0 ) {
3785 $rev = $this->getFirstRevision( $flags );
3786 return $rev ?
$rev->getTimestamp() : null;
3790 * Check if this is a new page
3794 public function isNewPage() {
3795 $dbr = wfGetDB( DB_SLAVE
);
3796 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3800 * Get the number of revisions between the given revision.
3801 * Used for diffs and other things that really need it.
3803 * @param $old int|Revision Old revision or rev ID (first before range)
3804 * @param $new int|Revision New revision or rev ID (first after range)
3805 * @return Int Number of revisions between these revisions.
3807 public function countRevisionsBetween( $old, $new ) {
3808 if ( !( $old instanceof Revision
) ) {
3809 $old = Revision
::newFromTitle( $this, (int)$old );
3811 if ( !( $new instanceof Revision
) ) {
3812 $new = Revision
::newFromTitle( $this, (int)$new );
3814 if ( !$old ||
!$new ) {
3815 return 0; // nothing to compare
3817 $dbr = wfGetDB( DB_SLAVE
);
3818 return (int)$dbr->selectField( 'revision', 'count(*)',
3820 'rev_page' => $this->getArticleId(),
3821 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3822 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3829 * Get the number of authors between the given revision IDs.
3830 * Used for diffs and other things that really need it.
3832 * @param $old int|Revision Old revision or rev ID (first before range)
3833 * @param $new int|Revision New revision or rev ID (first after range)
3834 * @param $limit Int Maximum number of authors
3835 * @return Int Number of revision authors between these revisions.
3837 public function countAuthorsBetween( $old, $new, $limit ) {
3838 if ( !( $old instanceof Revision
) ) {
3839 $old = Revision
::newFromTitle( $this, (int)$old );
3841 if ( !( $new instanceof Revision
) ) {
3842 $new = Revision
::newFromTitle( $this, (int)$new );
3844 if ( !$old ||
!$new ) {
3845 return 0; // nothing to compare
3847 $dbr = wfGetDB( DB_SLAVE
);
3848 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
3850 'rev_page' => $this->getArticleID(),
3851 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3852 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3854 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
3856 return (int)$dbr->numRows( $res );
3860 * Compare with another title.
3862 * @param $title Title
3865 public function equals( Title
$title ) {
3866 // Note: === is necessary for proper matching of number-like titles.
3867 return $this->getInterwiki() === $title->getInterwiki()
3868 && $this->getNamespace() == $title->getNamespace()
3869 && $this->getDBkey() === $title->getDBkey();
3873 * Check if this title is a subpage of another title
3875 * @param $title Title
3878 public function isSubpageOf( Title
$title ) {
3879 return $this->getInterwiki() === $title->getInterwiki()
3880 && $this->getNamespace() == $title->getNamespace()
3881 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
3885 * Callback for usort() to do title sorts by (namespace, title)
3890 * @return Integer: result of string comparison, or namespace comparison
3892 public static function compare( $a, $b ) {
3893 if ( $a->getNamespace() == $b->getNamespace() ) {
3894 return strcmp( $a->getText(), $b->getText() );
3896 return $a->getNamespace() - $b->getNamespace();
3901 * Return a string representation of this title
3903 * @return String representation of this title
3905 public function __toString() {
3906 return $this->getPrefixedText();
3910 * Check if page exists. For historical reasons, this function simply
3911 * checks for the existence of the title in the page table, and will
3912 * thus return false for interwiki links, special pages and the like.
3913 * If you want to know if a title can be meaningfully viewed, you should
3914 * probably call the isKnown() method instead.
3918 public function exists() {
3919 return $this->getArticleId() != 0;
3923 * Should links to this title be shown as potentially viewable (i.e. as
3924 * "bluelinks"), even if there's no record by this title in the page
3927 * This function is semi-deprecated for public use, as well as somewhat
3928 * misleadingly named. You probably just want to call isKnown(), which
3929 * calls this function internally.
3931 * (ISSUE: Most of these checks are cheap, but the file existence check
3932 * can potentially be quite expensive. Including it here fixes a lot of
3933 * existing code, but we might want to add an optional parameter to skip
3934 * it and any other expensive checks.)
3938 public function isAlwaysKnown() {
3939 if ( $this->mInterwiki
!= '' ) {
3940 return true; // any interwiki link might be viewable, for all we know
3942 switch( $this->mNamespace
) {
3945 // file exists, possibly in a foreign repo
3946 return (bool)wfFindFile( $this );
3948 // valid special page
3949 return SpecialPageFactory
::exists( $this->getDBkey() );
3951 // selflink, possibly with fragment
3952 return $this->mDbkeyform
== '';
3954 // known system message
3955 return $this->getDefaultMessageText() !== false;
3962 * Does this title refer to a page that can (or might) be meaningfully
3963 * viewed? In particular, this function may be used to determine if
3964 * links to the title should be rendered as "bluelinks" (as opposed to
3965 * "redlinks" to non-existent pages).
3969 public function isKnown() {
3970 return $this->isAlwaysKnown() ||
$this->exists();
3974 * Does this page have source text?
3978 public function hasSourceText() {
3979 if ( $this->exists() ) {
3983 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
3984 // If the page doesn't exist but is a known system message, default
3985 // message content will be displayed, same for language subpages
3986 return $this->getDefaultMessageText() !== false;
3993 * Get the default message text or false if the message doesn't exist
3995 * @return String or false
3997 public function getDefaultMessageText() {
4000 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4004 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4005 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4007 if ( $message->exists() ) {
4008 return $message->plain();
4015 * Is this in a namespace that allows actual pages?
4018 * @internal note -- uses hardcoded namespace index instead of constants
4020 public function canExist() {
4021 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
4025 * Update page_touched timestamps and send squid purge messages for
4026 * pages linking to this title. May be sent to the job queue depending
4027 * on the number of links. Typically called on create and delete.
4029 public function touchLinks() {
4030 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4033 if ( $this->getNamespace() == NS_CATEGORY
) {
4034 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4040 * Get the last touched timestamp
4042 * @param $db DatabaseBase: optional db
4043 * @return String last-touched timestamp
4045 public function getTouched( $db = null ) {
4046 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4047 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4052 * Get the timestamp when this page was updated since the user last saw it.
4055 * @return String|Null
4057 public function getNotificationTimestamp( $user = null ) {
4058 global $wgUser, $wgShowUpdatedMarker;
4059 // Assume current user if none given
4063 // Check cache first
4064 $uid = $user->getId();
4065 // avoid isset here, as it'll return false for null entries
4066 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4067 return $this->mNotificationTimestamp
[$uid];
4069 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4070 return $this->mNotificationTimestamp
[$uid] = false;
4072 // Don't cache too much!
4073 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4074 $this->mNotificationTimestamp
= array();
4076 $dbr = wfGetDB( DB_SLAVE
);
4077 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4078 'wl_notificationtimestamp',
4079 array( 'wl_namespace' => $this->getNamespace(),
4080 'wl_title' => $this->getDBkey(),
4081 'wl_user' => $user->getId()
4085 return $this->mNotificationTimestamp
[$uid];
4089 * Get the trackback URL for this page
4091 * @return String Trackback URL
4093 public function trackbackURL() {
4094 global $wgScriptPath, $wgServer, $wgScriptExtension;
4096 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
4097 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
4101 * Get the trackback RDF for this page
4103 * @return String Trackback RDF
4105 public function trackbackRDF() {
4106 $url = htmlspecialchars( $this->getFullURL() );
4107 $title = htmlspecialchars( $this->getText() );
4108 $tburl = $this->trackbackURL();
4110 // Autodiscovery RDF is placed in comments so HTML validator
4111 // won't barf. This is a rather icky workaround, but seems
4112 // frequently used by this kind of RDF thingy.
4114 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
4116 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
4117 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
4118 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
4121 dc:identifier=\"$url\"
4123 trackback:ping=\"$tburl\" />
4129 * Generate strings used for xml 'id' names in monobook tabs
4131 * @param $prepend string defaults to 'nstab-'
4132 * @return String XML 'id' name
4134 public function getNamespaceKey( $prepend = 'nstab-' ) {
4136 // Gets the subject namespace if this title
4137 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4138 // Checks if cononical namespace name exists for namespace
4139 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4140 // Uses canonical namespace name
4141 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4143 // Uses text of namespace
4144 $namespaceKey = $this->getSubjectNsText();
4146 // Makes namespace key lowercase
4147 $namespaceKey = $wgContLang->lc( $namespaceKey );
4149 if ( $namespaceKey == '' ) {
4150 $namespaceKey = 'main';
4152 // Changes file to image for backwards compatibility
4153 if ( $namespaceKey == 'file' ) {
4154 $namespaceKey = 'image';
4156 return $prepend . $namespaceKey;
4160 * Returns true if this is a special page.
4164 public function isSpecialPage() {
4165 return $this->getNamespace() == NS_SPECIAL
;
4169 * Returns true if this title resolves to the named special page
4171 * @param $name String The special page name
4174 public function isSpecial( $name ) {
4175 if ( $this->getNamespace() == NS_SPECIAL
) {
4176 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
4177 if ( $name == $thisName ) {
4185 * If the Title refers to a special page alias which is not the local default, resolve
4186 * the alias, and localise the name as necessary. Otherwise, return $this
4190 public function fixSpecialName() {
4191 if ( $this->getNamespace() == NS_SPECIAL
) {
4192 list( $canonicalName, /*...*/ ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
4193 if ( $canonicalName ) {
4194 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName );
4195 if ( $localName != $this->mDbkeyform
) {
4196 return Title
::makeTitle( NS_SPECIAL
, $localName );
4204 * Is this Title in a namespace which contains content?
4205 * In other words, is this a content page, for the purposes of calculating
4210 public function isContentPage() {
4211 return MWNamespace
::isContent( $this->getNamespace() );
4215 * Get all extant redirects to this Title
4217 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4218 * @return Array of Title redirects to this title
4220 public function getRedirectsHere( $ns = null ) {
4223 $dbr = wfGetDB( DB_SLAVE
);
4225 'rd_namespace' => $this->getNamespace(),
4226 'rd_title' => $this->getDBkey(),
4229 if ( !is_null( $ns ) ) {
4230 $where['page_namespace'] = $ns;
4233 $res = $dbr->select(
4234 array( 'redirect', 'page' ),
4235 array( 'page_namespace', 'page_title' ),
4240 foreach ( $res as $row ) {
4241 $redirs[] = self
::newFromRow( $row );
4247 * Check if this Title is a valid redirect target
4251 public function isValidRedirectTarget() {
4252 global $wgInvalidRedirectTargets;
4254 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4255 if ( $this->isSpecial( 'Userlogout' ) ) {
4259 foreach ( $wgInvalidRedirectTargets as $target ) {
4260 if ( $this->isSpecial( $target ) ) {
4269 * Get a backlink cache object
4271 * @return object BacklinkCache
4273 function getBacklinkCache() {
4274 if ( is_null( $this->mBacklinkCache
) ) {
4275 $this->mBacklinkCache
= new BacklinkCache( $this );
4277 return $this->mBacklinkCache
;
4281 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4285 public function canUseNoindex() {
4286 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4288 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4289 ?
$wgContentNamespaces
4290 : $wgExemptFromUserRobotsControl;
4292 return !in_array( $this->mNamespace
, $bannedNamespaces );
4297 * Returns restriction types for the current Title
4299 * @return array applicable restriction types
4301 public function getRestrictionTypes() {
4302 if ( $this->getNamespace() == NS_SPECIAL
) {
4306 $types = self
::getFilteredRestrictionTypes( $this->exists() );
4308 if ( $this->getNamespace() != NS_FILE
) {
4309 # Remove the upload restriction for non-file titles
4310 $types = array_diff( $types, array( 'upload' ) );
4313 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4315 wfDebug( __METHOD__
. ': applicable restriction types for ' .
4316 $this->getPrefixedText() . ' are ' . implode( ',', $types ) . "\n" );
4321 * Get a filtered list of all restriction types supported by this wiki.
4322 * @param bool $exists True to get all restriction types that apply to
4323 * titles that do exist, False for all restriction types that apply to
4324 * titles that do not exist
4327 public static function getFilteredRestrictionTypes( $exists = true ) {
4328 global $wgRestrictionTypes;
4329 $types = $wgRestrictionTypes;
4331 # Remove the create restriction for existing titles
4332 $types = array_diff( $types, array( 'create' ) );
4334 # Only the create and upload restrictions apply to non-existing titles
4335 $types = array_intersect( $types, array( 'create', 'upload' ) );
4341 * Returns the raw sort key to be used for categories, with the specified
4342 * prefix. This will be fed to Collation::getSortKey() to get a
4343 * binary sortkey that can be used for actual sorting.
4345 * @param $prefix string The prefix to be used, specified using
4346 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4350 public function getCategorySortkey( $prefix = '' ) {
4351 $unprefixed = $this->getText();
4353 // Anything that uses this hook should only depend
4354 // on the Title object passed in, and should probably
4355 // tell the users to run updateCollations.php --force
4356 // in order to re-sort existing category relations.
4357 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4358 if ( $prefix !== '' ) {
4359 # Separate with a line feed, so the unprefixed part is only used as
4360 # a tiebreaker when two pages have the exact same prefix.
4361 # In UCA, tab is the only character that can sort above LF
4362 # so we strip both of them from the original prefix.
4363 $prefix = strtr( $prefix, "\n\t", ' ' );
4364 return "$prefix\n$unprefixed";
4370 * Get the language in which the content of this page is written.
4371 * Defaults to $wgContLang, but in certain cases it can be e.g.
4372 * $wgLang (such as special pages, which are in the user language).
4375 * @return object Language
4377 public function getPageLanguage() {
4379 if ( $this->getNamespace() == NS_SPECIAL
) {
4380 // special pages are in the user language
4382 } elseif ( $this->isCssOrJsPage() ) {
4383 // css/js should always be LTR and is, in fact, English
4384 return wfGetLangObj( 'en' );
4385 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4386 // Parse mediawiki messages with correct target language
4387 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4388 return wfGetLangObj( $lang );
4391 // If nothing special, it should be in the wiki content language
4392 $pageLang = $wgContLang;
4393 // Hook at the end because we don't want to override the above stuff
4394 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4395 return wfGetLangObj( $pageLang );