5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Represents a title within MediaWiki.
25 * Optionally may contain an interwiki designation or namespace.
26 * @note This class can fetch various kinds of data from the database;
27 * however, it does so inefficiently.
29 * @internal documentation reviewed 15 Mar 2010
32 /** @name Static cache variables */
34 static private $titleCache = array();
38 * Title::newFromText maintains a cache to avoid expensive re-normalization of
39 * commonly used titles. On a batch operation this can become a memory leak
40 * if not bounded. After hitting this many titles reset the cache.
42 const CACHE_MAX
= 1000;
45 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
46 * to use the master DB
48 const GAID_FOR_UPDATE
= 1;
51 * @name Private member variables
52 * Please use the accessor functions instead.
57 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
58 var $mUrlform = ''; // /< URL-encoded form of the main part
59 var $mDbkeyform = ''; // /< Main part with underscores
60 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
61 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
62 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
63 var $mFragment; // /< Title fragment (i.e. the bit after the #)
64 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
65 var $mLatestID = false; // /< ID of most recent revision
66 var $mCounter = -1; // /< Number of times this page has been viewed (-1 means "not loaded")
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 if ( isset( $row->page_counter
) )
277 $this->mCounter
= (int)$row->page_counter
;
278 } else { // page not found
279 $this->mArticleID
= 0;
281 $this->mRedirect
= false;
282 $this->mLatestID
= 0;
288 * Create a new Title from a namespace index and a DB key.
289 * It's assumed that $ns and $title are *valid*, for instance when
290 * they came directly from the database or a special page name.
291 * For convenience, spaces are converted to underscores so that
292 * eg user_text fields can be used directly.
294 * @param $ns Int the namespace of the article
295 * @param $title String the unprefixed database key form
296 * @param $fragment String the link fragment (after the "#")
297 * @param $interwiki String the interwiki prefix
298 * @return Title the new object
300 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
302 $t->mInterwiki
= $interwiki;
303 $t->mFragment
= $fragment;
304 $t->mNamespace
= $ns = intval( $ns );
305 $t->mDbkeyform
= str_replace( ' ', '_', $title );
306 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
307 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
308 $t->mTextform
= str_replace( '_', ' ', $title );
313 * Create a new Title from a namespace index and a DB key.
314 * The parameters will be checked for validity, which is a bit slower
315 * than makeTitle() but safer for user-provided data.
317 * @param $ns Int the namespace of the article
318 * @param $title String database key form
319 * @param $fragment String the link fragment (after the "#")
320 * @param $interwiki String interwiki prefix
321 * @return Title the new object, or NULL on an error
323 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
325 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
326 if ( $t->secureAndSplit() ) {
334 * Create a new Title for the Main Page
336 * @return Title the new object
338 public static function newMainPage() {
339 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
340 // Don't give fatal errors if the message is broken
342 $title = Title
::newFromText( 'Main Page' );
348 * Extract a redirect destination from a string and return the
349 * Title, or null if the text doesn't contain a valid redirect
350 * This will only return the very next target, useful for
351 * the redirect table and other checks that don't need full recursion
353 * @param $text String: Text with possible redirect
354 * @return Title: The corresponding Title
356 public static function newFromRedirect( $text ) {
357 return self
::newFromRedirectInternal( $text );
361 * Extract a redirect destination from a string and return the
362 * Title, or null if the text doesn't contain a valid redirect
363 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
364 * in order to provide (hopefully) the Title of the final destination instead of another redirect
366 * @param $text String Text with possible redirect
369 public static function newFromRedirectRecurse( $text ) {
370 $titles = self
::newFromRedirectArray( $text );
371 return $titles ?
array_pop( $titles ) : null;
375 * Extract a redirect destination from a string and return an
376 * array of Titles, or null if the text doesn't contain a valid redirect
377 * The last element in the array is the final destination after all redirects
378 * have been resolved (up to $wgMaxRedirects times)
380 * @param $text String Text with possible redirect
381 * @return Array of Titles, with the destination last
383 public static function newFromRedirectArray( $text ) {
384 global $wgMaxRedirects;
385 $title = self
::newFromRedirectInternal( $text );
386 if ( is_null( $title ) ) {
389 // recursive check to follow double redirects
390 $recurse = $wgMaxRedirects;
391 $titles = array( $title );
392 while ( --$recurse > 0 ) {
393 if ( $title->isRedirect() ) {
394 $page = WikiPage
::factory( $title );
395 $newtitle = $page->getRedirectTarget();
399 // Redirects to some special pages are not permitted
400 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
401 // the new title passes the checks, so make that our current title so that further recursion can be checked
403 $titles[] = $newtitle;
412 * Really extract the redirect destination
413 * Do not call this function directly, use one of the newFromRedirect* functions above
415 * @param $text String Text with possible redirect
418 protected static function newFromRedirectInternal( $text ) {
419 global $wgMaxRedirects;
420 if ( $wgMaxRedirects < 1 ) {
421 //redirects are disabled, so quit early
424 $redir = MagicWord
::get( 'redirect' );
425 $text = trim( $text );
426 if ( $redir->matchStartAndRemove( $text ) ) {
427 // Extract the first link and see if it's usable
428 // Ensure that it really does come directly after #REDIRECT
429 // Some older redirects included a colon, so don't freak about that!
431 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
432 // Strip preceding colon used to "escape" categories, etc.
433 // and URL-decode links
434 if ( strpos( $m[1], '%' ) !== false ) {
435 // Match behavior of inline link parsing here;
436 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
438 $title = Title
::newFromText( $m[1] );
439 // If the title is a redirect to bad special pages or is invalid, return null
440 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
450 * Get the prefixed DB key associated with an ID
452 * @param $id Int the page_id of the article
453 * @return Title an object representing the article, or NULL if no such article was found
455 public static function nameOf( $id ) {
456 $dbr = wfGetDB( DB_SLAVE
);
458 $s = $dbr->selectRow(
460 array( 'page_namespace', 'page_title' ),
461 array( 'page_id' => $id ),
464 if ( $s === false ) {
468 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
473 * Get a regex character class describing the legal characters in a link
475 * @return String the list of characters, not delimited
477 public static function legalChars() {
478 global $wgLegalTitleChars;
479 return $wgLegalTitleChars;
483 * Get a string representation of a title suitable for
484 * including in a search index
486 * @param $ns Int a namespace index
487 * @param $title String text-form main part
488 * @return String a stripped-down title string ready for the search index
490 public static function indexTitle( $ns, $title ) {
493 $lc = SearchEngine
::legalSearchChars() . '&#;';
494 $t = $wgContLang->normalizeForSearch( $title );
495 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
496 $t = $wgContLang->lc( $t );
499 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
500 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
502 $t = preg_replace( "/\\s+/", ' ', $t );
504 if ( $ns == NS_FILE
) {
505 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
511 * Make a prefixed DB key from a DB key and a namespace index
513 * @param $ns Int numerical representation of the namespace
514 * @param $title String the DB key form the title
515 * @param $fragment String The link fragment (after the "#")
516 * @param $interwiki String The interwiki prefix
517 * @return String the prefixed form of the title
519 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
522 $namespace = $wgContLang->getNsText( $ns );
523 $name = $namespace == '' ?
$title : "$namespace:$title";
524 if ( strval( $interwiki ) != '' ) {
525 $name = "$interwiki:$name";
527 if ( strval( $fragment ) != '' ) {
528 $name .= '#' . $fragment;
534 * Escape a text fragment, say from a link, for a URL
536 * @param $fragment string containing a URL or link fragment (after the "#")
537 * @return String: escaped string
539 static function escapeFragmentForURL( $fragment ) {
540 # Note that we don't urlencode the fragment. urlencoded Unicode
541 # fragments appear not to work in IE (at least up to 7) or in at least
542 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
543 # to care if they aren't encoded.
544 return Sanitizer
::escapeId( $fragment, 'noninitial' );
548 * Determine whether the object refers to a page within
551 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
553 public function isLocal() {
554 if ( $this->mInterwiki
!= '' ) {
555 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
562 * Is this Title interwiki?
566 public function isExternal() {
567 return ( $this->mInterwiki
!= '' );
571 * Get the interwiki prefix (or null string)
573 * @return String Interwiki prefix
575 public function getInterwiki() {
576 return $this->mInterwiki
;
580 * Determine whether the object refers to a page within
581 * this project and is transcludable.
583 * @return Bool TRUE if this is transcludable
585 public function isTrans() {
586 if ( $this->mInterwiki
== '' ) {
590 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
594 * Returns the DB name of the distant wiki which owns the object.
596 * @return String the DB name
598 public function getTransWikiID() {
599 if ( $this->mInterwiki
== '' ) {
603 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
607 * Get the text form (spaces not underscores) of the main part
609 * @return String Main part of the title
611 public function getText() {
612 return $this->mTextform
;
616 * Get the URL-encoded form of the main part
618 * @return String Main part of the title, URL-encoded
620 public function getPartialURL() {
621 return $this->mUrlform
;
625 * Get the main part with underscores
627 * @return String: Main part of the title, with underscores
629 public function getDBkey() {
630 return $this->mDbkeyform
;
634 * Get the namespace index, i.e. one of the NS_xxxx constants.
636 * @return Integer: Namespace index
638 public function getNamespace() {
639 return $this->mNamespace
;
643 * Get the namespace text
645 * @return String: Namespace text
647 public function getNsText() {
650 if ( $this->mInterwiki
!= '' ) {
651 // This probably shouldn't even happen. ohh man, oh yuck.
652 // But for interwiki transclusion it sometimes does.
653 // Shit. Shit shit shit.
655 // Use the canonical namespaces if possible to try to
656 // resolve a foreign namespace.
657 if ( MWNamespace
::exists( $this->mNamespace
) ) {
658 return MWNamespace
::getCanonicalName( $this->mNamespace
);
662 // Strip off subpages
663 $pagename = $this->getText();
664 if ( strpos( $pagename, '/' ) !== false ) {
665 list( $username , ) = explode( '/', $pagename, 2 );
667 $username = $pagename;
670 if ( $wgContLang->needsGenderDistinction() &&
671 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
672 $gender = GenderCache
::singleton()->getGenderOf( $username, __METHOD__
);
673 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
676 return $wgContLang->getNsText( $this->mNamespace
);
680 * Get the DB key with the initial letter case as specified by the user
682 * @return String DB key
684 function getUserCaseDBKey() {
685 return $this->mUserCaseDBKey
;
689 * Get the namespace text of the subject (rather than talk) page
691 * @return String Namespace text
693 public function getSubjectNsText() {
695 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
699 * Get the namespace text of the talk page
701 * @return String Namespace text
703 public function getTalkNsText() {
705 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
709 * Could this title have a corresponding talk page?
711 * @return Bool TRUE or FALSE
713 public function canTalk() {
714 return( MWNamespace
::canTalk( $this->mNamespace
) );
718 * Get the Title fragment (i.e.\ the bit after the #) in text form
720 * @return String Title fragment
722 public function getFragment() { return $this->mFragment
; }
725 * Get the fragment in URL form, including the "#" character if there is one
726 * @return String Fragment in URL form
728 public function getFragmentForURL() {
729 if ( $this->mFragment
== '' ) {
732 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
737 * Get the default namespace index, for when there is no namespace
739 * @return Int Default namespace index
741 public function getDefaultNamespace() {
742 return $this->mDefaultNamespace
;
746 * Get title for search index
748 * @return String a stripped-down title string ready for the
751 public function getIndexTitle() {
752 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
756 * Get the prefixed database key form
758 * @return String the prefixed title, with underscores and
759 * any interwiki and namespace prefixes
761 public function getPrefixedDBkey() {
762 $s = $this->prefix( $this->mDbkeyform
);
763 $s = str_replace( ' ', '_', $s );
768 * Get the prefixed title with spaces.
769 * This is the form usually used for display
771 * @return String the prefixed title, with spaces
773 public function getPrefixedText() {
774 // @todo FIXME: Bad usage of empty() ?
775 if ( empty( $this->mPrefixedText
) ) {
776 $s = $this->prefix( $this->mTextform
);
777 $s = str_replace( '_', ' ', $s );
778 $this->mPrefixedText
= $s;
780 return $this->mPrefixedText
;
785 * Get the prefixed title with spaces, plus any fragment
786 * (part beginning with '#')
788 * @return String the prefixed title, with spaces and the fragment, including '#'
790 public function getFullText() {
791 $text = $this->getPrefixedText();
792 if ( $this->mFragment
!= '' ) {
793 $text .= '#' . $this->mFragment
;
799 * Get the base page name, i.e. the leftmost part before any slashes
801 * @return String Base name
803 public function getBaseText() {
804 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
805 return $this->getText();
808 $parts = explode( '/', $this->getText() );
809 # Don't discard the real title if there's no subpage involved
810 if ( count( $parts ) > 1 ) {
811 unset( $parts[count( $parts ) - 1] );
813 return implode( '/', $parts );
817 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
819 * @return String Subpage name
821 public function getSubpageText() {
822 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
823 return( $this->mTextform
);
825 $parts = explode( '/', $this->mTextform
);
826 return( $parts[count( $parts ) - 1] );
830 * Get the HTML-escaped displayable text form.
831 * Used for the title field in <a> tags.
833 * @return String the text, including any prefixes
835 public function getEscapedText() {
836 return htmlspecialchars( $this->getPrefixedText() );
840 * Get a URL-encoded form of the subpage text
842 * @return String URL-encoded subpage name
844 public function getSubpageUrlForm() {
845 $text = $this->getSubpageText();
846 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
851 * Get a URL-encoded title (not an actual URL) including interwiki
853 * @return String the URL-encoded form
855 public function getPrefixedURL() {
856 $s = $this->prefix( $this->mDbkeyform
);
857 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
862 * Get a real URL referring to this title, with interwiki link and
865 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
866 * links. Can be specified as an associative array as well, e.g.,
867 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
868 * @param $variant String language variant of url (for sr, zh..)
869 * @return String the URL
871 public function getFullURL( $query = '', $variant = false ) {
872 # Hand off all the decisions on urls to getLocalURL
873 $url = $this->getLocalURL( $query, $variant );
875 # Expand the url to make it a full url. Note that getLocalURL has the
876 # potential to output full urls for a variety of reasons, so we use
877 # wfExpandUrl instead of simply prepending $wgServer
878 $url = wfExpandUrl( $url, PROTO_RELATIVE
);
880 # Finally, add the fragment.
881 $url .= $this->getFragmentForURL();
883 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query, $variant ) );
888 * Get a URL with no fragment or server name. If this page is generated
889 * with action=render, $wgServer is prepended.
891 * @param $query Mixed: an optional query string; if not specified,
892 * $wgArticlePath will be used. Can be specified as an associative array
893 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
895 * @param $variant String language variant of url (for sr, zh..)
896 * @return String the URL
898 public function getLocalURL( $query = '', $variant = false ) {
899 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
900 global $wgVariantArticlePath;
902 if ( is_array( $query ) ) {
903 $query = wfArrayToCGI( $query );
906 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
908 $namespace = $this->getNsText();
909 if ( $namespace != '' ) {
910 # Can this actually happen? Interwikis shouldn't be parsed.
911 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
914 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
915 $url = wfAppendQuery( $url, $query );
917 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
918 if ( $query == '' ) {
919 if ( $variant != false && $this->getPageLanguage()->hasVariants() ) {
920 if ( !$wgVariantArticlePath ) {
921 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
923 $variantArticlePath = $wgVariantArticlePath;
925 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
926 $url = str_replace( '$1', $dbkey, $url );
928 $url = str_replace( '$1', $dbkey, $wgArticlePath );
929 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
932 global $wgActionPaths;
935 if ( !empty( $wgActionPaths ) &&
936 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
938 $action = urldecode( $matches[2] );
939 if ( isset( $wgActionPaths[$action] ) ) {
940 $query = $matches[1];
941 if ( isset( $matches[4] ) ) {
942 $query .= $matches[4];
944 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
945 if ( $query != '' ) {
946 $url = wfAppendQuery( $url, $query );
951 if ( $url === false ) {
952 if ( $query == '-' ) {
955 $url = "{$wgScript}?title={$dbkey}&{$query}";
959 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query, $variant ) );
961 // @todo FIXME: This causes breakage in various places when we
962 // actually expected a local URL and end up with dupe prefixes.
963 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
964 $url = $wgServer . $url;
967 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query, $variant ) );
972 * Get a URL that's the simplest URL that will be valid to link, locally,
973 * to the current Title. It includes the fragment, but does not include
974 * the server unless action=render is used (or the link is external). If
975 * there's a fragment but the prefixed text is empty, we just return a link
978 * The result obviously should not be URL-escaped, but does need to be
979 * HTML-escaped if it's being output in HTML.
981 * @param $query Array of Strings An associative array of key => value pairs for the
982 * query string. Keys and values will be escaped.
983 * @param $variant String language variant of URL (for sr, zh..). Ignored
984 * for external links. Default is "false" (same variant as current page,
985 * for anonymous users).
986 * @return String the URL
988 public function getLinkURL( $query = array(), $variant = false ) {
989 wfProfileIn( __METHOD__
);
990 if ( $this->isExternal() ) {
991 $ret = $this->getFullURL( $query );
992 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
993 $ret = $this->getFragmentForURL();
995 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
997 wfProfileOut( __METHOD__
);
1002 * Get an HTML-escaped version of the URL form, suitable for
1003 * using in a link, without a server name or fragment
1005 * @param $query String an optional query string
1006 * @return String the URL
1008 public function escapeLocalURL( $query = '' ) {
1009 return htmlspecialchars( $this->getLocalURL( $query ) );
1013 * Get an HTML-escaped version of the URL form, suitable for
1014 * using in a link, including the server name and fragment
1016 * @param $query String an optional query string
1017 * @return String the URL
1019 public function escapeFullURL( $query = '' ) {
1020 return htmlspecialchars( $this->getFullURL( $query ) );
1024 * Get the URL form for an internal link.
1025 * - Used in various Squid-related code, in case we have a different
1026 * internal hostname for the server from the exposed one.
1028 * This uses $wgInternalServer to qualify the path, or $wgServer
1029 * if $wgInternalServer is not set. If the server variable used is
1030 * protocol-relative, the URL will be expanded to http://
1032 * @param $query String an optional query string
1033 * @param $variant String language variant of url (for sr, zh..)
1034 * @return String the URL
1036 public function getInternalURL( $query = '', $variant = false ) {
1037 global $wgInternalServer, $wgServer;
1038 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1039 $url = wfExpandUrl( $server . $this->getLocalURL( $query, $variant ), PROTO_HTTP
);
1040 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query, $variant ) );
1045 * Get the URL for a canonical link, for use in things like IRC and
1046 * e-mail notifications. Uses $wgCanonicalServer and the
1047 * GetCanonicalURL hook.
1049 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1051 * @param $query string An optional query string
1052 * @param $variant string Language variant of URL (for sr, zh, ...)
1053 * @return string The URL
1056 public function getCanonicalURL( $query = '', $variant = false ) {
1057 $url = wfExpandUrl( $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1058 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query, $variant ) );
1063 * HTML-escaped version of getCanonicalURL()
1066 public function escapeCanonicalURL( $query = '', $variant = false ) {
1067 return htmlspecialchars( $this->getCanonicalURL( $query, $variant ) );
1071 * Get the edit URL for this Title
1073 * @return String the URL, or a null string if this is an
1076 public function getEditURL() {
1077 if ( $this->mInterwiki
!= '' ) {
1080 $s = $this->getLocalURL( 'action=edit' );
1086 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1088 * @param $action String Action to check (default: edit)
1091 public function isSemiProtected( $action = 'edit' ) {
1092 if ( $this->exists() ) {
1093 $restrictions = $this->getRestrictions( $action );
1094 if ( count( $restrictions ) > 0 ) {
1095 foreach ( $restrictions as $restriction ) {
1096 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1106 # If it doesn't exist, it can't be protected
1112 * Does the title correspond to a protected article?
1114 * @param $action String the action the page is protected from,
1115 * by default checks all actions.
1118 public function isProtected( $action = '' ) {
1119 global $wgRestrictionLevels;
1121 $restrictionTypes = $this->getRestrictionTypes();
1123 # Special pages have inherent protection
1124 if( $this->isSpecialPage() ) {
1128 # Check regular protection levels
1129 foreach ( $restrictionTypes as $type ) {
1130 if ( $action == $type ||
$action == '' ) {
1131 $r = $this->getRestrictions( $type );
1132 foreach ( $wgRestrictionLevels as $level ) {
1133 if ( in_array( $level, $r ) && $level != '' ) {
1144 * Determines if $user is unable to edit this page because it has been protected
1145 * by $wgNamespaceProtection.
1147 * @param $user User object to check permissions
1150 public function isNamespaceProtected( User
$user ) {
1151 global $wgNamespaceProtection;
1153 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
1154 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
1155 if ( $right != '' && !$user->isAllowed( $right ) ) {
1164 * Is this a conversion table for the LanguageConverter?
1168 public function isConversionTable() {
1170 $this->getNamespace() == NS_MEDIAWIKI
&&
1171 strpos( $this->getText(), 'Conversiontable' ) !== false
1181 * Is $wgUser watching this page?
1185 public function userIsWatching() {
1188 if ( is_null( $this->mWatched
) ) {
1189 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1190 $this->mWatched
= false;
1192 $this->mWatched
= $wgUser->isWatched( $this );
1195 return $this->mWatched
;
1199 * Can $wgUser read this page?
1201 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1203 * @todo fold these checks into userCan()
1205 public function userCanRead() {
1206 return $this->userCan( 'read' );
1210 * Can $wgUser perform $action on this page?
1211 * This skips potentially expensive cascading permission checks
1212 * as well as avoids expensive error formatting
1214 * Suitable for use for nonessential UI controls in common cases, but
1215 * _not_ for functional access control.
1217 * May provide false positives, but should never provide a false negative.
1219 * @param $action String action that permission needs to be checked for
1220 * @param $user User to check (since 1.19)
1223 public function quickUserCan( $action, $user = null ) {
1224 return $this->userCan( $action, $user, false );
1228 * Can $wgUser perform $action on this page?
1230 * @param $action String action that permission needs to be checked for
1231 * @param $user User to check (since 1.19)
1232 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1235 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1236 if ( !$user instanceof User
) {
1240 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1244 * Can $user perform $action on this page?
1246 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1248 * @param $action String action that permission needs to be checked for
1249 * @param $user User to check
1250 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries by
1251 * skipping checks for cascading protections and user blocks.
1252 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1253 * @return Array of arguments to wfMsg to explain permissions problems.
1255 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1256 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1258 // Remove the errors being ignored.
1259 foreach ( $errors as $index => $error ) {
1260 $error_key = is_array( $error ) ?
$error[0] : $error;
1262 if ( in_array( $error_key, $ignoreErrors ) ) {
1263 unset( $errors[$index] );
1271 * Permissions checks that fail most often, and which are easiest to test.
1273 * @param $action String the action to check
1274 * @param $user User user to check
1275 * @param $errors Array list of current errors
1276 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1277 * @param $short Boolean short circuit on first error
1279 * @return Array list of errors
1281 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1282 $ns = $this->getNamespace();
1284 if ( $action == 'create' ) {
1285 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk', $ns ) ) ||
1286 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage', $ns ) ) ) {
1287 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1289 } elseif ( $action == 'move' ) {
1290 if ( !$user->isAllowed( 'move-rootuserpages', $ns )
1291 && $ns == NS_USER
&& !$this->isSubpage() ) {
1292 // Show user page-specific message only if the user can move other pages
1293 $errors[] = array( 'cant-move-user-page' );
1296 // Check if user is allowed to move files if it's a file
1297 if ( $ns == NS_FILE
&& !$user->isAllowed( 'movefile', $ns ) ) {
1298 $errors[] = array( 'movenotallowedfile' );
1301 if ( !$user->isAllowed( 'move', $ns) ) {
1302 // User can't move anything
1304 $userCanMove = in_array( 'move', User
::getGroupPermissions(
1305 array( 'user' ), $ns ), true );
1306 $autoconfirmedCanMove = in_array( 'move', User
::getGroupPermissions(
1307 array( 'autoconfirmed' ), $ns ), true );
1309 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1310 // custom message if logged-in users without any special rights can move
1311 $errors[] = array( 'movenologintext' );
1313 $errors[] = array( 'movenotallowed' );
1316 } elseif ( $action == 'move-target' ) {
1317 if ( !$user->isAllowed( 'move', $ns ) ) {
1318 // User can't move anything
1319 $errors[] = array( 'movenotallowed' );
1320 } elseif ( !$user->isAllowed( 'move-rootuserpages', $ns )
1321 && $ns == NS_USER
&& !$this->isSubpage() ) {
1322 // Show user page-specific message only if the user can move other pages
1323 $errors[] = array( 'cant-move-to-user-page' );
1325 } elseif ( !$user->isAllowed( $action, $ns ) ) {
1326 $errors[] = $this->missingPermissionError( $action, $short );
1333 * Add the resulting error code to the errors array
1335 * @param $errors Array list of current errors
1336 * @param $result Mixed result of errors
1338 * @return Array list of errors
1340 private function resultToError( $errors, $result ) {
1341 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1342 // A single array representing an error
1343 $errors[] = $result;
1344 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1345 // A nested array representing multiple errors
1346 $errors = array_merge( $errors, $result );
1347 } elseif ( $result !== '' && is_string( $result ) ) {
1348 // A string representing a message-id
1349 $errors[] = array( $result );
1350 } elseif ( $result === false ) {
1351 // a generic "We don't want them to do that"
1352 $errors[] = array( 'badaccess-group0' );
1358 * Check various permission hooks
1360 * @param $action String the action to check
1361 * @param $user User user to check
1362 * @param $errors Array list of current errors
1363 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1364 * @param $short Boolean short circuit on first error
1366 * @return Array list of errors
1368 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1369 // Use getUserPermissionsErrors instead
1371 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1372 return $result ?
array() : array( array( 'badaccess-group0' ) );
1374 // Check getUserPermissionsErrors hook
1375 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1376 $errors = $this->resultToError( $errors, $result );
1378 // Check getUserPermissionsErrorsExpensive hook
1379 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1380 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1381 $errors = $this->resultToError( $errors, $result );
1388 * Check permissions on special pages & namespaces
1390 * @param $action String the action to check
1391 * @param $user User user to check
1392 * @param $errors Array list of current errors
1393 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1394 * @param $short Boolean short circuit on first error
1396 * @return Array list of errors
1398 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1399 # Only 'createaccount' and 'execute' can be performed on
1400 # special pages, which don't actually exist in the DB.
1401 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1402 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1403 $errors[] = array( 'ns-specialprotected' );
1406 # Check $wgNamespaceProtection for restricted namespaces
1407 if ( $this->isNamespaceProtected( $user ) ) {
1408 $ns = $this->mNamespace
== NS_MAIN ?
1409 wfMsg( 'nstab-main' ) : $this->getNsText();
1410 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1411 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1418 * Check CSS/JS sub-page permissions
1420 * @param $action String the action to check
1421 * @param $user User user to check
1422 * @param $errors Array list of current errors
1423 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1424 * @param $short Boolean short circuit on first error
1426 * @return Array list of errors
1428 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1429 # Protect css/js subpages of user pages
1430 # XXX: this might be better using restrictions
1431 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1432 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1433 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1434 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1435 $errors[] = array( 'customcssprotected' );
1436 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1437 $errors[] = array( 'customjsprotected' );
1445 * Check against page_restrictions table requirements on this
1446 * page. The user must possess all required rights for this
1449 * @param $action String the action to check
1450 * @param $user User user to check
1451 * @param $errors Array list of current errors
1452 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1453 * @param $short Boolean short circuit on first error
1455 * @return Array list of errors
1457 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1458 foreach ( $this->getRestrictions( $action ) as $right ) {
1459 // Backwards compatibility, rewrite sysop -> protect
1460 if ( $right == 'sysop' ) {
1463 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace
) ) {
1464 // Users with 'editprotected' permission can edit protected pages
1465 // without cascading option turned on.
1466 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected', $this->mNamespace
)
1467 ||
$this->mCascadeRestriction
)
1469 $errors[] = array( 'protectedpagetext', $right );
1478 * Check restrictions on cascading pages.
1480 * @param $action String the action to check
1481 * @param $user User to check
1482 * @param $errors Array list of current errors
1483 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1484 * @param $short Boolean short circuit on first error
1486 * @return Array list of errors
1488 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1489 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1490 # We /could/ use the protection level on the source page, but it's
1491 # fairly ugly as we have to establish a precedence hierarchy for pages
1492 # included by multiple cascade-protected pages. So just restrict
1493 # it to people with 'protect' permission, as they could remove the
1494 # protection anyway.
1495 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1496 # Cascading protection depends on more than this page...
1497 # Several cascading protected pages may include this page...
1498 # Check each cascading level
1499 # This is only for protection restrictions, not for all actions
1500 if ( isset( $restrictions[$action] ) ) {
1501 foreach ( $restrictions[$action] as $right ) {
1502 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1503 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace
) ) {
1505 foreach ( $cascadingSources as $page )
1506 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1507 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1517 * Check action permissions not already checked in checkQuickPermissions
1519 * @param $action String the action to check
1520 * @param $user User to check
1521 * @param $errors Array list of current errors
1522 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1523 * @param $short Boolean short circuit on first error
1525 * @return Array list of errors
1527 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1528 if ( $action == 'protect' ) {
1529 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1530 // If they can't edit, they shouldn't protect.
1531 $errors[] = array( 'protect-cantedit' );
1533 } elseif ( $action == 'create' ) {
1534 $title_protection = $this->getTitleProtection();
1535 if( $title_protection ) {
1536 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1537 $title_protection['pt_create_perm'] = 'protect'; // B/C
1539 if( $title_protection['pt_create_perm'] == '' ||
1540 !$user->isAllowed( $title_protection['pt_create_perm'],
1541 $this->mNamespace
) ) {
1542 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1545 } elseif ( $action == 'move' ) {
1546 // Check for immobile pages
1547 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1548 // Specific message for this case
1549 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1550 } elseif ( !$this->isMovable() ) {
1551 // Less specific message for rarer cases
1552 $errors[] = array( 'immobile-source-page' );
1554 } elseif ( $action == 'move-target' ) {
1555 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1556 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1557 } elseif ( !$this->isMovable() ) {
1558 $errors[] = array( 'immobile-target-page' );
1565 * Check that the user isn't blocked from editting.
1567 * @param $action String the action to check
1568 * @param $user User to check
1569 * @param $errors Array list of current errors
1570 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1571 * @param $short Boolean short circuit on first error
1573 * @return Array list of errors
1575 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1576 // Account creation blocks handled at userlogin.
1577 // Unblocking handled in SpecialUnblock
1578 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1582 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1584 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1585 $errors[] = array( 'confirmedittext' );
1588 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1589 // Don't block the user from editing their own talk page unless they've been
1590 // explicitly blocked from that too.
1591 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1592 $block = $user->mBlock
;
1594 // This is from OutputPage::blockedPage
1595 // Copied at r23888 by werdna
1597 $id = $user->blockedBy();
1598 $reason = $user->blockedFor();
1599 if ( $reason == '' ) {
1600 $reason = wfMsg( 'blockednoreason' );
1602 $ip = $user->getRequest()->getIP();
1604 if ( is_numeric( $id ) ) {
1605 $name = User
::whoIs( $id );
1610 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1611 $blockid = $block->getId();
1612 $blockExpiry = $user->mBlock
->mExpiry
;
1613 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1614 if ( $blockExpiry == 'infinity' ) {
1615 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1617 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1620 $intended = strval( $user->mBlock
->getTarget() );
1622 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1623 $blockid, $blockExpiry, $intended, $blockTimestamp );
1630 * Check that the user is allowed to read this page.
1632 * @param $action String the action to check
1633 * @param $user User to check
1634 * @param $errors Array list of current errors
1635 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1636 * @param $short Boolean short circuit on first error
1638 * @return Array list of errors
1640 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1641 static $useShortcut = null;
1643 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1644 if ( is_null( $useShortcut ) ) {
1645 global $wgGroupPermissions, $wgRevokePermissions;
1646 $useShortcut = true;
1647 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1648 # Not a public wiki, so no shortcut
1649 $useShortcut = false;
1650 } elseif ( !empty( $wgRevokePermissions ) ) {
1652 * Iterate through each group with permissions being revoked (key not included since we don't care
1653 * what the group name is), then check if the read permission is being revoked. If it is, then
1654 * we don't use the shortcut below since the user might not be able to read, even though anon
1655 * reading is allowed.
1657 foreach ( $wgRevokePermissions as $perms ) {
1658 if ( !empty( $perms['read'] ) ) {
1659 # We might be removing the read right from the user, so no shortcut
1660 $useShortcut = false;
1667 # Shortcut for public wikis, allows skipping quite a bit of code
1668 if ( $useShortcut ) {
1672 # If the user is allowed to read pages, he is allowed to read all pages
1673 if ( $user->isAllowed( 'read', $this->mNamespace
) ) {
1677 # Always grant access to the login page.
1678 # Even anons need to be able to log in.
1679 if ( $this->isSpecial( 'Userlogin' )
1680 ||
$this->isSpecial( 'ChangePassword' )
1681 ||
$this->isSpecial( 'PasswordReset' )
1686 # Time to check the whitelist
1687 global $wgWhitelistRead;
1689 # Only to these checks is there's something to check against
1690 if ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
1691 # Check for explicit whitelisting
1692 $name = $this->getPrefixedText();
1693 $dbName = $this->getPrefixedDBKey();
1695 // Check with and without underscores
1696 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
1700 # Old settings might have the title prefixed with
1701 # a colon for main-namespace pages
1702 if ( $this->getNamespace() == NS_MAIN
) {
1703 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1708 # If it's a special page, ditch the subpage bit and check again
1709 if ( $this->isSpecialPage() ) {
1710 $name = $this->getDBkey();
1711 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
1712 if ( $name !== false ) {
1713 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1714 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1721 $errors[] = $this->missingPermissionError( $action, $short );
1726 * Get a description array when the user doesn't have the right to perform
1727 * $action (i.e. when User::isAllowed() returns false)
1729 * @param $action String the action to check
1730 * @param $short Boolean short circuit on first error
1731 * @return Array list of errors
1733 private function missingPermissionError( $action, $short ) {
1734 // We avoid expensive display logic for quickUserCan's and such
1736 return array( 'badaccess-group0' );
1739 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1740 User
::getGroupsWithPermission( $action, $this->mNamespace
) );
1742 if ( count( $groups ) ) {
1746 $wgLang->commaList( $groups ),
1750 return array( 'badaccess-group0' );
1755 * Can $user perform $action on this page? This is an internal function,
1756 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1757 * checks on wfReadOnly() and blocks)
1759 * @param $action String action that permission needs to be checked for
1760 * @param $user User to check
1761 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1762 * @param $short Bool Set this to true to stop after the first permission error.
1763 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1765 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1766 wfProfileIn( __METHOD__
);
1768 # Read has special handling
1769 if ( $action == 'read' ) {
1771 'checkPermissionHooks',
1772 'checkReadPermissions',
1776 'checkQuickPermissions',
1777 'checkPermissionHooks',
1778 'checkSpecialsAndNSPermissions',
1779 'checkCSSandJSPermissions',
1780 'checkPageRestrictions',
1781 'checkCascadingSourcesRestrictions',
1782 'checkActionPermissions',
1788 while( count( $checks ) > 0 &&
1789 !( $short && count( $errors ) > 0 ) ) {
1790 $method = array_shift( $checks );
1791 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1794 wfProfileOut( __METHOD__
);
1799 * Is this title subject to title protection?
1800 * Title protection is the one applied against creation of such title.
1802 * @return Mixed An associative array representing any existent title
1803 * protection, or false if there's none.
1805 private function getTitleProtection() {
1806 // Can't protect pages in special namespaces
1807 if ( $this->getNamespace() < 0 ) {
1811 // Can't protect pages that exist.
1812 if ( $this->exists() ) {
1816 if ( !isset( $this->mTitleProtection
) ) {
1817 $dbr = wfGetDB( DB_SLAVE
);
1818 $res = $dbr->select( 'protected_titles', '*',
1819 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1822 // fetchRow returns false if there are no rows.
1823 $this->mTitleProtection
= $dbr->fetchRow( $res );
1825 return $this->mTitleProtection
;
1829 * Update the title protection status
1831 * @param $create_perm String Permission required for creation
1832 * @param $reason String Reason for protection
1833 * @param $expiry String Expiry timestamp
1834 * @return boolean true
1836 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1837 global $wgUser, $wgContLang;
1839 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1840 && $expiry == $this->mRestrictionsExpiry
['create'] ) {
1845 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1847 $dbw = wfGetDB( DB_MASTER
);
1849 $encodedExpiry = $dbw->encodeExpiry( $expiry );
1851 $expiry_description = '';
1852 if ( $encodedExpiry != $dbw->getInfinity() ) {
1853 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1854 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1856 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1859 # Update protection table
1860 if ( $create_perm != '' ) {
1861 $this->mTitleProtection
= array(
1862 'pt_namespace' => $namespace,
1863 'pt_title' => $title,
1864 'pt_create_perm' => $create_perm,
1865 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1866 'pt_expiry' => $encodedExpiry,
1867 'pt_user' => $wgUser->getId(),
1868 'pt_reason' => $reason,
1870 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1871 $this->mTitleProtection
, __METHOD__
);
1873 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1874 'pt_title' => $title ), __METHOD__
);
1875 $this->mTitleProtection
= false;
1878 # Update the protection log
1879 if ( $dbw->affectedRows() ) {
1880 $log = new LogPage( 'protect' );
1882 if ( $create_perm ) {
1883 $params = array( "[create=$create_perm] $expiry_description", '' );
1884 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1886 $log->addEntry( 'unprotect', $this, $reason );
1894 * Remove any title protection due to page existing
1896 public function deleteTitleProtection() {
1897 $dbw = wfGetDB( DB_MASTER
);
1901 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1904 $this->mTitleProtection
= false;
1908 * Would anybody with sufficient privileges be able to move this page?
1909 * Some pages just aren't movable.
1911 * @return Bool TRUE or FALSE
1913 public function isMovable() {
1914 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
1915 // Interwiki title or immovable namespace. Hooks don't get to override here
1920 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
1925 * Is this the mainpage?
1926 * @note Title::newFromText seams to be sufficiently optimized by the title
1927 * cache that we don't need to over-optimize by doing direct comparisons and
1928 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1929 * ends up reporting something differently than $title->isMainPage();
1934 public function isMainPage() {
1935 return $this->equals( Title
::newMainPage() );
1939 * Is this a talk page of some sort?
1943 public function isTalkPage() {
1944 return MWNamespace
::isTalk( $this->getNamespace() );
1948 * Is this a subpage?
1952 public function isSubpage() {
1953 return MWNamespace
::hasSubpages( $this->mNamespace
)
1954 ?
strpos( $this->getText(), '/' ) !== false
1959 * Returns true if the title is inside the specified namespace.
1961 * Please make use of this instead of comparing to getNamespace()
1962 * This function is much more resistant to changes we may make
1963 * to namespaces than code that makes direct comparisons.
1964 * @param $ns int The namespace
1968 public function inNamespace( $ns ) {
1969 return MWNamespace
::equals( $this->getNamespace(), $ns );
1973 * Returns true if the title is inside one of the specified namespaces.
1975 * @param ...$namespaces The namespaces to check for
1979 public function inNamespaces( /* ... */ ) {
1980 $namespaces = func_get_args();
1981 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1982 $namespaces = $namespaces[0];
1985 foreach ( $namespaces as $ns ) {
1986 if ( $this->inNamespace( $ns ) ) {
1995 * Returns true if the title has the same subject namespace as the
1996 * namespace specified.
1997 * For example this method will take NS_USER and return true if namespace
1998 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1999 * as their subject namespace.
2001 * This is MUCH simpler than individually testing for equivilance
2002 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
2005 public function hasSubjectNamespace( $ns ) {
2006 return MWNamespace
::subjectEquals( $this->getNamespace(), $ns );
2010 * Does this have subpages? (Warning, usually requires an extra DB query.)
2014 public function hasSubpages() {
2015 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
2020 # We dynamically add a member variable for the purpose of this method
2021 # alone to cache the result. There's no point in having it hanging
2022 # around uninitialized in every Title object; therefore we only add it
2023 # if needed and don't declare it statically.
2024 if ( isset( $this->mHasSubpages
) ) {
2025 return $this->mHasSubpages
;
2028 $subpages = $this->getSubpages( 1 );
2029 if ( $subpages instanceof TitleArray
) {
2030 return $this->mHasSubpages
= (bool)$subpages->count();
2032 return $this->mHasSubpages
= false;
2036 * Get all subpages of this page.
2038 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2039 * @return mixed TitleArray, or empty array if this page's namespace
2040 * doesn't allow subpages
2042 public function getSubpages( $limit = -1 ) {
2043 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
2047 $dbr = wfGetDB( DB_SLAVE
);
2048 $conds['page_namespace'] = $this->getNamespace();
2049 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2051 if ( $limit > -1 ) {
2052 $options['LIMIT'] = $limit;
2054 return $this->mSubpages
= TitleArray
::newFromResult(
2055 $dbr->select( 'page',
2056 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2065 * Does that page contain wikitext, or it is JS, CSS or whatever?
2069 public function isWikitextPage() {
2070 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
2071 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
2076 * Could this page contain custom CSS or JavaScript, based
2081 public function isCssOrJsPage() {
2082 $retval = $this->mNamespace
== NS_MEDIAWIKI
2083 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
2084 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
2089 * Is this a .css or .js subpage of a user page?
2092 public function isCssJsSubpage() {
2093 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
2097 * Is this a *valid* .css or .js subpage of a user page?
2100 * @deprecated since 1.17
2102 public function isValidCssJsSubpage() {
2103 return $this->isCssJsSubpage();
2107 * Trim down a .css or .js subpage title to get the corresponding skin name
2109 * @return string containing skin name from .css or .js subpage title
2111 public function getSkinFromCssJsSubpage() {
2112 $subpage = explode( '/', $this->mTextform
);
2113 $subpage = $subpage[ count( $subpage ) - 1 ];
2114 $lastdot = strrpos( $subpage, '.' );
2115 if ( $lastdot === false )
2116 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
2117 return substr( $subpage, 0, $lastdot );
2121 * Is this a .css subpage of a user page?
2125 public function isCssSubpage() {
2126 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
2130 * Is this a .js subpage of a user page?
2134 public function isJsSubpage() {
2135 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
2139 * Protect css subpages of user pages: can $wgUser edit
2142 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2145 public function userCanEditCssSubpage() {
2147 wfDeprecated( __METHOD__
);
2148 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2149 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2153 * Protect js subpages of user pages: can $wgUser edit
2156 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2159 public function userCanEditJsSubpage() {
2161 wfDeprecated( __METHOD__
);
2162 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2163 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2167 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2169 * @return Bool If the page is subject to cascading restrictions.
2171 public function isCascadeProtected() {
2172 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2173 return ( $sources > 0 );
2177 * Cascading protection: Get the source of any cascading restrictions on this page.
2179 * @param $getPages Bool Whether or not to retrieve the actual pages
2180 * that the restrictions have come from.
2181 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2182 * have come, false for none, or true if such restrictions exist, but $getPages
2183 * was not set. The restriction array is an array of each type, each of which
2184 * contains a array of unique groups.
2186 public function getCascadeProtectionSources( $getPages = true ) {
2188 $pagerestrictions = array();
2190 if ( isset( $this->mCascadeSources
) && $getPages ) {
2191 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2192 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2193 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2196 wfProfileIn( __METHOD__
);
2198 $dbr = wfGetDB( DB_SLAVE
);
2200 if ( $this->getNamespace() == NS_FILE
) {
2201 $tables = array( 'imagelinks', 'page_restrictions' );
2202 $where_clauses = array(
2203 'il_to' => $this->getDBkey(),
2208 $tables = array( 'templatelinks', 'page_restrictions' );
2209 $where_clauses = array(
2210 'tl_namespace' => $this->getNamespace(),
2211 'tl_title' => $this->getDBkey(),
2218 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2219 'pr_expiry', 'pr_type', 'pr_level' );
2220 $where_clauses[] = 'page_id=pr_page';
2223 $cols = array( 'pr_expiry' );
2226 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2228 $sources = $getPages ?
array() : false;
2229 $now = wfTimestampNow();
2230 $purgeExpired = false;
2232 foreach ( $res as $row ) {
2233 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2234 if ( $expiry > $now ) {
2236 $page_id = $row->pr_page
;
2237 $page_ns = $row->page_namespace
;
2238 $page_title = $row->page_title
;
2239 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2240 # Add groups needed for each restriction type if its not already there
2241 # Make sure this restriction type still exists
2243 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2244 $pagerestrictions[$row->pr_type
] = array();
2247 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2248 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2249 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2255 // Trigger lazy purge of expired restrictions from the db
2256 $purgeExpired = true;
2259 if ( $purgeExpired ) {
2260 Title
::purgeExpiredRestrictions();
2264 $this->mCascadeSources
= $sources;
2265 $this->mCascadingRestrictions
= $pagerestrictions;
2267 $this->mHasCascadingRestrictions
= $sources;
2270 wfProfileOut( __METHOD__
);
2271 return array( $sources, $pagerestrictions );
2275 * Returns cascading restrictions for the current article
2279 function areRestrictionsCascading() {
2280 if ( !$this->mRestrictionsLoaded
) {
2281 $this->loadRestrictions();
2284 return $this->mCascadeRestriction
;
2288 * Loads a string into mRestrictions array
2290 * @param $res Resource restrictions as an SQL result.
2291 * @param $oldFashionedRestrictions String comma-separated list of page
2292 * restrictions from page table (pre 1.10)
2294 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2297 foreach ( $res as $row ) {
2301 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2305 * Compiles list of active page restrictions from both page table (pre 1.10)
2306 * and page_restrictions table for this existing page.
2307 * Public for usage by LiquidThreads.
2309 * @param $rows array of db result objects
2310 * @param $oldFashionedRestrictions string comma-separated list of page
2311 * restrictions from page table (pre 1.10)
2313 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2315 $dbr = wfGetDB( DB_SLAVE
);
2317 $restrictionTypes = $this->getRestrictionTypes();
2319 foreach ( $restrictionTypes as $type ) {
2320 $this->mRestrictions
[$type] = array();
2321 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2324 $this->mCascadeRestriction
= false;
2326 # Backwards-compatibility: also load the restrictions from the page record (old format).
2328 if ( $oldFashionedRestrictions === null ) {
2329 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2330 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2333 if ( $oldFashionedRestrictions != '' ) {
2335 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2336 $temp = explode( '=', trim( $restrict ) );
2337 if ( count( $temp ) == 1 ) {
2338 // old old format should be treated as edit/move restriction
2339 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2340 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2342 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2346 $this->mOldRestrictions
= true;
2350 if ( count( $rows ) ) {
2351 # Current system - load second to make them override.
2352 $now = wfTimestampNow();
2353 $purgeExpired = false;
2355 # Cycle through all the restrictions.
2356 foreach ( $rows as $row ) {
2358 // Don't take care of restrictions types that aren't allowed
2359 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2362 // This code should be refactored, now that it's being used more generally,
2363 // But I don't really see any harm in leaving it in Block for now -werdna
2364 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2366 // Only apply the restrictions if they haven't expired!
2367 if ( !$expiry ||
$expiry > $now ) {
2368 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2369 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2371 $this->mCascadeRestriction |
= $row->pr_cascade
;
2373 // Trigger a lazy purge of expired restrictions
2374 $purgeExpired = true;
2378 if ( $purgeExpired ) {
2379 Title
::purgeExpiredRestrictions();
2383 $this->mRestrictionsLoaded
= true;
2387 * Load restrictions from the page_restrictions table
2389 * @param $oldFashionedRestrictions String comma-separated list of page
2390 * restrictions from page table (pre 1.10)
2392 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2394 if ( !$this->mRestrictionsLoaded
) {
2395 if ( $this->exists() ) {
2396 $dbr = wfGetDB( DB_SLAVE
);
2398 $res = $dbr->select(
2399 'page_restrictions',
2401 array( 'pr_page' => $this->getArticleId() ),
2405 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2407 $title_protection = $this->getTitleProtection();
2409 if ( $title_protection ) {
2410 $now = wfTimestampNow();
2411 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2413 if ( !$expiry ||
$expiry > $now ) {
2414 // Apply the restrictions
2415 $this->mRestrictionsExpiry
['create'] = $expiry;
2416 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2417 } else { // Get rid of the old restrictions
2418 Title
::purgeExpiredRestrictions();
2419 $this->mTitleProtection
= false;
2422 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2424 $this->mRestrictionsLoaded
= true;
2430 * Purge expired restrictions from the page_restrictions table
2432 static function purgeExpiredRestrictions() {
2433 $dbw = wfGetDB( DB_MASTER
);
2435 'page_restrictions',
2436 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2442 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2448 * Accessor/initialisation for mRestrictions
2450 * @param $action String action that permission needs to be checked for
2451 * @return Array of Strings the array of groups allowed to edit this article
2453 public function getRestrictions( $action ) {
2454 if ( !$this->mRestrictionsLoaded
) {
2455 $this->loadRestrictions();
2457 return isset( $this->mRestrictions
[$action] )
2458 ?
$this->mRestrictions
[$action]
2463 * Get the expiry time for the restriction against a given action
2465 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2466 * or not protected at all, or false if the action is not recognised.
2468 public function getRestrictionExpiry( $action ) {
2469 if ( !$this->mRestrictionsLoaded
) {
2470 $this->loadRestrictions();
2472 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2476 * Is there a version of this page in the deletion archive?
2478 * @return Int the number of archived revisions
2480 public function isDeleted() {
2481 if ( $this->getNamespace() < 0 ) {
2484 $dbr = wfGetDB( DB_SLAVE
);
2486 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2487 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2490 if ( $this->getNamespace() == NS_FILE
) {
2491 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2492 array( 'fa_name' => $this->getDBkey() ),
2501 * Is there a version of this page in the deletion archive?
2505 public function isDeletedQuick() {
2506 if ( $this->getNamespace() < 0 ) {
2509 $dbr = wfGetDB( DB_SLAVE
);
2510 $deleted = (bool)$dbr->selectField( 'archive', '1',
2511 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2514 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2515 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2516 array( 'fa_name' => $this->getDBkey() ),
2524 * Get the number of views of this page
2526 * @return int The view count for the page
2528 public function getCount() {
2529 if ( $this->mCounter
== -1 ) {
2530 if ( $this->exists() ) {
2531 $dbr = wfGetDB( DB_SLAVE
);
2532 $this->mCounter
= $dbr->selectField( 'page',
2534 array( 'page_id' => $this->getArticleID() ),
2538 $this->mCounter
= 0;
2542 return $this->mCounter
;
2546 * Get the article ID for this Title from the link cache,
2547 * adding it if necessary
2549 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2551 * @return Int the ID
2553 public function getArticleID( $flags = 0 ) {
2554 if ( $this->getNamespace() < 0 ) {
2555 return $this->mArticleID
= 0;
2557 $linkCache = LinkCache
::singleton();
2558 if ( $flags & self
::GAID_FOR_UPDATE
) {
2559 $oldUpdate = $linkCache->forUpdate( true );
2560 $linkCache->clearLink( $this );
2561 $this->mArticleID
= $linkCache->addLinkObj( $this );
2562 $linkCache->forUpdate( $oldUpdate );
2564 if ( -1 == $this->mArticleID
) {
2565 $this->mArticleID
= $linkCache->addLinkObj( $this );
2568 return $this->mArticleID
;
2572 * Is this an article that is a redirect page?
2573 * Uses link cache, adding it if necessary
2575 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2578 public function isRedirect( $flags = 0 ) {
2579 if ( !is_null( $this->mRedirect
) ) {
2580 return $this->mRedirect
;
2582 # Calling getArticleID() loads the field from cache as needed
2583 if ( !$this->getArticleID( $flags ) ) {
2584 return $this->mRedirect
= false;
2586 $linkCache = LinkCache
::singleton();
2587 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2589 return $this->mRedirect
;
2593 * What is the length of this page?
2594 * Uses link cache, adding it if necessary
2596 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2599 public function getLength( $flags = 0 ) {
2600 if ( $this->mLength
!= -1 ) {
2601 return $this->mLength
;
2603 # Calling getArticleID() loads the field from cache as needed
2604 if ( !$this->getArticleID( $flags ) ) {
2605 return $this->mLength
= 0;
2607 $linkCache = LinkCache
::singleton();
2608 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2610 return $this->mLength
;
2614 * What is the page_latest field for this page?
2616 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2617 * @return Int or 0 if the page doesn't exist
2619 public function getLatestRevID( $flags = 0 ) {
2620 if ( $this->mLatestID
!== false ) {
2621 return intval( $this->mLatestID
);
2623 # Calling getArticleID() loads the field from cache as needed
2624 if ( !$this->getArticleID( $flags ) ) {
2625 return $this->mLatestID
= 0;
2627 $linkCache = LinkCache
::singleton();
2628 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2630 return $this->mLatestID
;
2634 * This clears some fields in this object, and clears any associated
2635 * keys in the "bad links" section of the link cache.
2637 * - This is called from Article::doEdit() and Article::insertOn() to allow
2638 * loading of the new page_id. It's also called from
2639 * Article::doDeleteArticle()
2641 * @param $newid Int the new Article ID
2643 public function resetArticleID( $newid ) {
2644 $linkCache = LinkCache
::singleton();
2645 $linkCache->clearLink( $this );
2647 if ( $newid === false ) {
2648 $this->mArticleID
= -1;
2650 $this->mArticleID
= intval( $newid );
2652 $this->mRestrictionsLoaded
= false;
2653 $this->mRestrictions
= array();
2654 $this->mRedirect
= null;
2655 $this->mLength
= -1;
2656 $this->mLatestID
= false;
2657 $this->mCounter
= -1;
2661 * Updates page_touched for this page; called from LinksUpdate.php
2663 * @return Bool true if the update succeded
2665 public function invalidateCache() {
2666 if ( wfReadOnly() ) {
2669 $dbw = wfGetDB( DB_MASTER
);
2670 $success = $dbw->update(
2672 array( 'page_touched' => $dbw->timestamp() ),
2676 HTMLFileCache
::clearFileCache( $this );
2681 * Prefix some arbitrary text with the namespace or interwiki prefix
2684 * @param $name String the text
2685 * @return String the prefixed text
2688 private function prefix( $name ) {
2690 if ( $this->mInterwiki
!= '' ) {
2691 $p = $this->mInterwiki
. ':';
2694 if ( 0 != $this->mNamespace
) {
2695 $p .= $this->getNsText() . ':';
2701 * Returns a simple regex that will match on characters and sequences invalid in titles.
2702 * Note that this doesn't pick up many things that could be wrong with titles, but that
2703 * replacing this regex with something valid will make many titles valid.
2705 * @return String regex string
2707 static function getTitleInvalidRegex() {
2708 static $rxTc = false;
2710 # Matching titles will be held as illegal.
2712 # Any character not allowed is forbidden...
2713 '[^' . Title
::legalChars() . ']' .
2714 # URL percent encoding sequences interfere with the ability
2715 # to round-trip titles -- you can't link to them consistently.
2716 '|%[0-9A-Fa-f]{2}' .
2717 # XML/HTML character references produce similar issues.
2718 '|&[A-Za-z0-9\x80-\xff]+;' .
2720 '|&#x[0-9A-Fa-f]+;' .
2728 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2730 * @param $text String containing title to capitalize
2731 * @param $ns int namespace index, defaults to NS_MAIN
2732 * @return String containing capitalized title
2734 public static function capitalize( $text, $ns = NS_MAIN
) {
2737 if ( MWNamespace
::isCapitalized( $ns ) ) {
2738 return $wgContLang->ucfirst( $text );
2745 * Secure and split - main initialisation function for this object
2747 * Assumes that mDbkeyform has been set, and is urldecoded
2748 * and uses underscores, but not otherwise munged. This function
2749 * removes illegal characters, splits off the interwiki and
2750 * namespace prefixes, sets the other forms, and canonicalizes
2753 * @return Bool true on success
2755 private function secureAndSplit() {
2756 global $wgContLang, $wgLocalInterwiki;
2759 $this->mInterwiki
= $this->mFragment
= '';
2760 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2762 $dbkey = $this->mDbkeyform
;
2764 # Strip Unicode bidi override characters.
2765 # Sometimes they slip into cut-n-pasted page titles, where the
2766 # override chars get included in list displays.
2767 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2769 # Clean up whitespace
2770 # Note: use of the /u option on preg_replace here will cause
2771 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2772 # conveniently disabling them.
2773 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2774 $dbkey = trim( $dbkey, '_' );
2776 if ( $dbkey == '' ) {
2780 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2781 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2785 $this->mDbkeyform
= $dbkey;
2787 # Initial colon indicates main namespace rather than specified default
2788 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2789 if ( ':' == $dbkey[0] ) {
2790 $this->mNamespace
= NS_MAIN
;
2791 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2792 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2795 # Namespace or interwiki prefix
2797 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2800 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2802 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2803 # Ordinary namespace
2805 $this->mNamespace
= $ns;
2806 # For Talk:X pages, check if X has a "namespace" prefix
2807 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2808 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2809 # Disallow Talk:File:x type titles...
2811 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2812 # Disallow Talk:Interwiki:x type titles...
2816 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2817 if ( !$firstPass ) {
2818 # Can't make a local interwiki link to an interwiki link.
2819 # That's just crazy!
2825 $this->mInterwiki
= $wgContLang->lc( $p );
2827 # Redundant interwiki prefix to the local wiki
2828 if ( $wgLocalInterwiki !== false
2829 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
2831 if ( $dbkey == '' ) {
2832 # Can't have an empty self-link
2835 $this->mInterwiki
= '';
2837 # Do another namespace split...
2841 # If there's an initial colon after the interwiki, that also
2842 # resets the default namespace
2843 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2844 $this->mNamespace
= NS_MAIN
;
2845 $dbkey = substr( $dbkey, 1 );
2848 # If there's no recognized interwiki or namespace,
2849 # then let the colon expression be part of the title.
2854 # We already know that some pages won't be in the database!
2855 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2856 $this->mArticleID
= 0;
2858 $fragment = strstr( $dbkey, '#' );
2859 if ( false !== $fragment ) {
2860 $this->setFragment( $fragment );
2861 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2862 # remove whitespace again: prevents "Foo_bar_#"
2863 # becoming "Foo_bar_"
2864 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2867 # Reject illegal characters.
2868 $rxTc = self
::getTitleInvalidRegex();
2869 if ( preg_match( $rxTc, $dbkey ) ) {
2873 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2874 # reachable due to the way web browsers deal with 'relative' URLs.
2875 # Also, they conflict with subpage syntax. Forbid them explicitly.
2876 if ( strpos( $dbkey, '.' ) !== false &&
2877 ( $dbkey === '.' ||
$dbkey === '..' ||
2878 strpos( $dbkey, './' ) === 0 ||
2879 strpos( $dbkey, '../' ) === 0 ||
2880 strpos( $dbkey, '/./' ) !== false ||
2881 strpos( $dbkey, '/../' ) !== false ||
2882 substr( $dbkey, -2 ) == '/.' ||
2883 substr( $dbkey, -3 ) == '/..' ) )
2888 # Magic tilde sequences? Nu-uh!
2889 if ( strpos( $dbkey, '~~~' ) !== false ) {
2893 # Limit the size of titles to 255 bytes. This is typically the size of the
2894 # underlying database field. We make an exception for special pages, which
2895 # don't need to be stored in the database, and may edge over 255 bytes due
2896 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2897 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2898 strlen( $dbkey ) > 512 )
2903 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2904 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2905 # other site might be case-sensitive.
2906 $this->mUserCaseDBKey
= $dbkey;
2907 if ( $this->mInterwiki
== '' ) {
2908 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2911 # Can't make a link to a namespace alone... "empty" local links can only be
2912 # self-links with a fragment identifier.
2913 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
2917 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2918 // IP names are not allowed for accounts, and can only be referring to
2919 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2920 // there are numerous ways to present the same IP. Having sp:contribs scan
2921 // them all is silly and having some show the edits and others not is
2922 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2923 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
2924 ? IP
::sanitizeIP( $dbkey )
2927 // Any remaining initial :s are illegal.
2928 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
2933 $this->mDbkeyform
= $dbkey;
2934 $this->mUrlform
= wfUrlencode( $dbkey );
2936 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2942 * Set the fragment for this title. Removes the first character from the
2943 * specified fragment before setting, so it assumes you're passing it with
2946 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2947 * Still in active use privately.
2949 * @param $fragment String text
2951 public function setFragment( $fragment ) {
2952 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2956 * Get a Title object associated with the talk page of this article
2958 * @return Title the object for the talk page
2960 public function getTalkPage() {
2961 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2965 * Get a title object associated with the subject page of this
2968 * @return Title the object for the subject page
2970 public function getSubjectPage() {
2971 // Is this the same title?
2972 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2973 if ( $this->getNamespace() == $subjectNS ) {
2976 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2980 * Get an array of Title objects linking to this Title
2981 * Also stores the IDs in the link cache.
2983 * WARNING: do not use this function on arbitrary user-supplied titles!
2984 * On heavily-used templates it will max out the memory.
2986 * @param $options Array: may be FOR UPDATE
2987 * @param $table String: table name
2988 * @param $prefix String: fields prefix
2989 * @return Array of Title objects linking here
2991 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2992 $linkCache = LinkCache
::singleton();
2994 if ( count( $options ) > 0 ) {
2995 $db = wfGetDB( DB_MASTER
);
2997 $db = wfGetDB( DB_SLAVE
);
3001 array( 'page', $table ),
3002 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3004 "{$prefix}_from=page_id",
3005 "{$prefix}_namespace" => $this->getNamespace(),
3006 "{$prefix}_title" => $this->getDBkey() ),
3012 if ( $db->numRows( $res ) ) {
3013 foreach ( $res as $row ) {
3014 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
3016 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3017 $retVal[] = $titleObj;
3025 * Get an array of Title objects using this Title as a template
3026 * Also stores the IDs in the link cache.
3028 * WARNING: do not use this function on arbitrary user-supplied titles!
3029 * On heavily-used templates it will max out the memory.
3031 * @param $options Array: may be FOR UPDATE
3032 * @return Array of Title the Title objects linking here
3034 public function getTemplateLinksTo( $options = array() ) {
3035 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3039 * Get an array of Title objects referring to non-existent articles linked from this page
3041 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3042 * @return Array of Title the Title objects
3044 public function getBrokenLinksFrom() {
3045 if ( $this->getArticleId() == 0 ) {
3046 # All links from article ID 0 are false positives
3050 $dbr = wfGetDB( DB_SLAVE
);
3051 $res = $dbr->select(
3052 array( 'page', 'pagelinks' ),
3053 array( 'pl_namespace', 'pl_title' ),
3055 'pl_from' => $this->getArticleId(),
3056 'page_namespace IS NULL'
3058 __METHOD__
, array(),
3062 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3068 foreach ( $res as $row ) {
3069 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
3076 * Get a list of URLs to purge from the Squid cache when this
3079 * @return Array of String the URLs
3081 public function getSquidURLs() {
3085 $this->getInternalURL(),
3086 $this->getInternalURL( 'action=history' )
3089 // purge variant urls as well
3090 if ( $wgContLang->hasVariants() ) {
3091 $variants = $wgContLang->getVariants();
3092 foreach ( $variants as $vCode ) {
3093 $urls[] = $this->getInternalURL( '', $vCode );
3101 * Purge all applicable Squid URLs
3103 public function purgeSquid() {
3105 if ( $wgUseSquid ) {
3106 $urls = $this->getSquidURLs();
3107 $u = new SquidUpdate( $urls );
3113 * Move this page without authentication
3115 * @param $nt Title the new page Title
3116 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3118 public function moveNoAuth( &$nt ) {
3119 return $this->moveTo( $nt, false );
3123 * Check whether a given move operation would be valid.
3124 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3126 * @param $nt Title the new title
3127 * @param $auth Bool indicates whether $wgUser's permissions
3129 * @param $reason String is the log summary of the move, used for spam checking
3130 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3132 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3137 // Normally we'd add this to $errors, but we'll get
3138 // lots of syntax errors if $nt is not an object
3139 return array( array( 'badtitletext' ) );
3141 if ( $this->equals( $nt ) ) {
3142 $errors[] = array( 'selfmove' );
3144 if ( !$this->isMovable() ) {
3145 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3147 if ( $nt->getInterwiki() != '' ) {
3148 $errors[] = array( 'immobile-target-namespace-iw' );
3150 if ( !$nt->isMovable() ) {
3151 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3154 $oldid = $this->getArticleID();
3155 $newid = $nt->getArticleID();
3157 if ( strlen( $nt->getDBkey() ) < 1 ) {
3158 $errors[] = array( 'articleexists' );
3160 if ( ( $this->getDBkey() == '' ) ||
3162 ( $nt->getDBkey() == '' ) ) {
3163 $errors[] = array( 'badarticleerror' );
3166 // Image-specific checks
3167 if ( $this->getNamespace() == NS_FILE
) {
3168 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3171 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3172 $errors[] = array( 'nonfile-cannot-move-to-file' );
3176 $errors = wfMergeErrorArrays( $errors,
3177 $this->getUserPermissionsErrors( 'move', $wgUser ),
3178 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3179 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3180 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3183 $match = EditPage
::matchSummarySpamRegex( $reason );
3184 if ( $match !== false ) {
3185 // This is kind of lame, won't display nice
3186 $errors[] = array( 'spamprotectiontext' );
3190 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3191 $errors[] = array( 'hookaborted', $err );
3194 # The move is allowed only if (1) the target doesn't exist, or
3195 # (2) the target is a redirect to the source, and has no history
3196 # (so we can undo bad moves right after they're done).
3198 if ( 0 != $newid ) { # Target exists; check for validity
3199 if ( !$this->isValidMoveTarget( $nt ) ) {
3200 $errors[] = array( 'articleexists' );
3203 $tp = $nt->getTitleProtection();
3204 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3205 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3206 $errors[] = array( 'cantmove-titleprotected' );
3209 if ( empty( $errors ) ) {
3216 * Check if the requested move target is a valid file move target
3217 * @param Title $nt Target title
3218 * @return array List of errors
3220 protected function validateFileMoveOperation( $nt ) {
3225 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3227 $file = wfLocalFile( $this );
3228 if ( $file->exists() ) {
3229 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3230 $errors[] = array( 'imageinvalidfilename' );
3232 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3233 $errors[] = array( 'imagetypemismatch' );
3237 if ( $nt->getNamespace() != NS_FILE
) {
3238 $errors[] = array( 'imagenocrossnamespace' );
3239 // From here we want to do checks on a file object, so if we can't
3240 // create one, we must return.
3244 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3246 $destFile = wfLocalFile( $nt );
3247 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3248 $errors[] = array( 'file-exists-sharedrepo' );
3255 * Move a title to a new location
3257 * @param $nt Title the new title
3258 * @param $auth Bool indicates whether $wgUser's permissions
3260 * @param $reason String the reason for the move
3261 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3262 * Ignored if the user doesn't have the suppressredirect right.
3263 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3265 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3267 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3268 if ( is_array( $err ) ) {
3269 // Auto-block user's IP if the account was "hard" blocked
3270 $wgUser->spreadAnyEditBlock();
3274 // If it is a file, move it first.
3275 // It is done before all other moving stuff is done because it's hard to revert.
3276 $dbw = wfGetDB( DB_MASTER
);
3277 if ( $this->getNamespace() == NS_FILE
) {
3278 $file = wfLocalFile( $this );
3279 if ( $file->exists() ) {
3280 $status = $file->move( $nt );
3281 if ( !$status->isOk() ) {
3282 return $status->getErrorsArray();
3286 // Clear RepoGroup process cache
3287 RepoGroup
::singleton()->clearCache( $this );
3288 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3290 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3291 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3292 $protected = $this->isProtected();
3293 $pageCountChange = ( $createRedirect ?
1 : 0 ) - ( $nt->exists() ?
1 : 0 );
3295 // Do the actual move
3296 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3297 if ( is_array( $err ) ) {
3298 # @todo FIXME: What about the File we have already moved?
3303 $redirid = $this->getArticleID();
3305 // Refresh the sortkey for this row. Be careful to avoid resetting
3306 // cl_timestamp, which may disturb time-based lists on some sites.
3307 $prefixes = $dbw->select(
3309 array( 'cl_sortkey_prefix', 'cl_to' ),
3310 array( 'cl_from' => $pageid ),
3313 foreach ( $prefixes as $prefixRow ) {
3314 $prefix = $prefixRow->cl_sortkey_prefix
;
3315 $catTo = $prefixRow->cl_to
;
3316 $dbw->update( 'categorylinks',
3318 'cl_sortkey' => Collation
::singleton()->getSortKey(
3319 $nt->getCategorySortkey( $prefix ) ),
3320 'cl_timestamp=cl_timestamp' ),
3322 'cl_from' => $pageid,
3323 'cl_to' => $catTo ),
3329 # Protect the redirect title as the title used to be...
3330 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3332 'pr_page' => $redirid,
3333 'pr_type' => 'pr_type',
3334 'pr_level' => 'pr_level',
3335 'pr_cascade' => 'pr_cascade',
3336 'pr_user' => 'pr_user',
3337 'pr_expiry' => 'pr_expiry'
3339 array( 'pr_page' => $pageid ),
3343 # Update the protection log
3344 $log = new LogPage( 'protect' );
3345 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3347 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3349 // @todo FIXME: $params?
3350 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3354 $oldnamespace = $this->getNamespace() & ~
1;
3355 $newnamespace = $nt->getNamespace() & ~
1;
3356 $oldtitle = $this->getDBkey();
3357 $newtitle = $nt->getDBkey();
3359 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3360 WatchedItem
::duplicateEntries( $this, $nt );
3363 # Update search engine
3364 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3366 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3372 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3373 # No longer a content page
3374 # Not viewed, edited, removing
3375 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3376 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3377 # Now a content page
3378 # Not viewed, edited, adding
3379 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
3380 } elseif ( $pageCountChange ) {
3382 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3391 # Update message cache for interface messages
3392 if ( $this->getNamespace() == NS_MEDIAWIKI
) {
3393 # @bug 17860: old article can be deleted, if this the case,
3394 # delete it from message cache
3395 if ( $this->getArticleID() === 0 ) {
3396 MessageCache
::singleton()->replace( $this->getDBkey(), false );
3398 $rev = Revision
::newFromTitle( $this );
3399 MessageCache
::singleton()->replace( $this->getDBkey(), $rev->getText() );
3402 if ( $nt->getNamespace() == NS_MEDIAWIKI
) {
3403 $rev = Revision
::newFromTitle( $nt );
3404 MessageCache
::singleton()->replace( $nt->getDBkey(), $rev->getText() );
3407 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3412 * Move page to a title which is either a redirect to the
3413 * source page or nonexistent
3415 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3416 * @param $reason String The reason for the move
3417 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3418 * if the user doesn't have the suppressredirect right
3420 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3421 global $wgUser, $wgContLang;
3423 if ( $nt->exists() ) {
3424 $moveOverRedirect = true;
3425 $logType = 'move_redir';
3427 $moveOverRedirect = false;
3431 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3433 $logEntry = new ManualLogEntry( 'move', $logType );
3434 $logEntry->setPerformer( $wgUser );
3435 $logEntry->setTarget( $this );
3436 $logEntry->setComment( $reason );
3437 $logEntry->setParameters( array(
3438 '4::target' => $nt->getPrefixedText(),
3439 '5::noredir' => $redirectSuppressed ?
'1': '0',
3442 $formatter = LogFormatter
::newFromEntry( $logEntry );
3443 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3444 $comment = $formatter->getPlainActionText();
3446 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3448 # Truncate for whole multibyte characters.
3449 $comment = $wgContLang->truncate( $comment, 255 );
3451 $oldid = $this->getArticleID();
3452 $latest = $this->getLatestRevID();
3454 $dbw = wfGetDB( DB_MASTER
);
3456 if ( $moveOverRedirect ) {
3457 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3459 $newid = $nt->getArticleID();
3460 $newns = $nt->getNamespace();
3461 $newdbk = $nt->getDBkey();
3463 # Delete the old redirect. We don't save it to history since
3464 # by definition if we've got here it's rather uninteresting.
3465 # We have to remove it so that the next step doesn't trigger
3466 # a conflict on the unique namespace+title index...
3467 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3468 if ( !$dbw->cascadingDeletes() ) {
3469 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3471 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3472 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3473 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3474 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3475 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3476 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3477 $dbw->delete( 'iwlinks', array( 'iwl_from' => $newid ), __METHOD__
);
3478 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3479 $dbw->delete( 'page_props', array( 'pp_page' => $newid ), __METHOD__
);
3481 // If the target page was recently created, it may have an entry in recentchanges still
3482 $dbw->delete( 'recentchanges',
3483 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3488 # Save a null revision in the page's history notifying of the move
3489 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3490 if ( !is_object( $nullRevision ) ) {
3491 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3493 $nullRevId = $nullRevision->insertOn( $dbw );
3495 $now = wfTimestampNow();
3496 # Change the name of the target page:
3497 $dbw->update( 'page',
3499 'page_touched' => $dbw->timestamp( $now ),
3500 'page_namespace' => $nt->getNamespace(),
3501 'page_title' => $nt->getDBkey(),
3502 'page_latest' => $nullRevId,
3504 /* WHERE */ array( 'page_id' => $oldid ),
3507 $nt->resetArticleID( $oldid );
3509 $article = WikiPage
::factory( $nt );
3510 wfRunHooks( 'NewRevisionFromEditComplete',
3511 array( $article, $nullRevision, $latest, $wgUser ) );
3512 $article->setCachedLastEditTime( $now );
3514 # Recreate the redirect, this time in the other direction.
3515 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3516 $mwRedir = MagicWord
::get( 'redirect' );
3517 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3518 $redirectArticle = WikiPage
::factory( $this );
3519 $newid = $redirectArticle->insertOn( $dbw );
3520 if ( $newid ) { // sanity
3521 $redirectRevision = new Revision( array(
3523 'comment' => $comment,
3524 'text' => $redirectText ) );
3525 $redirectRevision->insertOn( $dbw );
3526 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3528 wfRunHooks( 'NewRevisionFromEditComplete',
3529 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3531 # Now, we record the link from the redirect to the new title.
3532 # It should have no other outgoing links...
3533 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3534 $dbw->insert( 'pagelinks',
3536 'pl_from' => $newid,
3537 'pl_namespace' => $nt->getNamespace(),
3538 'pl_title' => $nt->getDBkey() ),
3542 $this->resetArticleID( 0 );
3546 $logid = $logEntry->insert();
3547 $logEntry->publish( $logid );
3549 # Purge caches for old and new titles
3550 if ( $moveOverRedirect ) {
3551 # A simple purge is enough when moving over a redirect
3554 # Purge caches as per article creation, including any pages that link to this title
3555 Article
::onArticleCreate( $nt );
3557 $this->purgeSquid();
3561 * Move this page's subpages to be subpages of $nt
3563 * @param $nt Title Move target
3564 * @param $auth bool Whether $wgUser's permissions should be checked
3565 * @param $reason string The reason for the move
3566 * @param $createRedirect bool Whether to create redirects from the old subpages to
3567 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3568 * @return mixed array with old page titles as keys, and strings (new page titles) or
3569 * arrays (errors) as values, or an error array with numeric indices if no pages
3572 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3573 global $wgMaximumMovedPages;
3574 // Check permissions
3575 if ( !$this->userCan( 'move-subpages' ) ) {
3576 return array( 'cant-move-subpages' );
3578 // Do the source and target namespaces support subpages?
3579 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3580 return array( 'namespace-nosubpages',
3581 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3583 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3584 return array( 'namespace-nosubpages',
3585 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3588 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3591 foreach ( $subpages as $oldSubpage ) {
3593 if ( $count > $wgMaximumMovedPages ) {
3594 $retval[$oldSubpage->getPrefixedTitle()] =
3595 array( 'movepage-max-pages',
3596 $wgMaximumMovedPages );
3600 // We don't know whether this function was called before
3601 // or after moving the root page, so check both
3603 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3604 $oldSubpage->getArticleID() == $nt->getArticleId() )
3606 // When moving a page to a subpage of itself,
3607 // don't move it twice
3610 $newPageName = preg_replace(
3611 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3612 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3613 $oldSubpage->getDBkey() );
3614 if ( $oldSubpage->isTalkPage() ) {
3615 $newNs = $nt->getTalkPage()->getNamespace();
3617 $newNs = $nt->getSubjectPage()->getNamespace();
3619 # Bug 14385: we need makeTitleSafe because the new page names may
3620 # be longer than 255 characters.
3621 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3623 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3624 if ( $success === true ) {
3625 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3627 $retval[$oldSubpage->getPrefixedText()] = $success;
3634 * Checks if this page is just a one-rev redirect.
3635 * Adds lock, so don't use just for light purposes.
3639 public function isSingleRevRedirect() {
3640 $dbw = wfGetDB( DB_MASTER
);
3642 $row = $dbw->selectRow( 'page',
3643 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3646 array( 'FOR UPDATE' )
3648 # Cache some fields we may want
3649 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3650 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3651 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3652 if ( !$this->mRedirect
) {
3655 # Does the article have a history?
3656 $row = $dbw->selectField( array( 'page', 'revision' ),
3658 array( 'page_namespace' => $this->getNamespace(),
3659 'page_title' => $this->getDBkey(),
3661 'page_latest != rev_id'
3664 array( 'FOR UPDATE' )
3666 # Return true if there was no history
3667 return ( $row === false );
3671 * Checks if $this can be moved to a given Title
3672 * - Selects for update, so don't call it unless you mean business
3674 * @param $nt Title the new title to check
3677 public function isValidMoveTarget( $nt ) {
3678 # Is it an existing file?
3679 if ( $nt->getNamespace() == NS_FILE
) {
3680 $file = wfLocalFile( $nt );
3681 if ( $file->exists() ) {
3682 wfDebug( __METHOD__
. ": file exists\n" );
3686 # Is it a redirect with no history?
3687 if ( !$nt->isSingleRevRedirect() ) {
3688 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3691 # Get the article text
3692 $rev = Revision
::newFromTitle( $nt );
3693 if( !is_object( $rev ) ){
3696 $text = $rev->getText();
3697 # Does the redirect point to the source?
3698 # Or is it a broken self-redirect, usually caused by namespace collisions?
3700 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3701 $redirTitle = Title
::newFromText( $m[1] );
3702 if ( !is_object( $redirTitle ) ||
3703 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3704 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3705 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3710 wfDebug( __METHOD__
. ": failsafe\n" );
3717 * Can this title be added to a user's watchlist?
3719 * @return Bool TRUE or FALSE
3721 public function isWatchable() {
3722 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3726 * Get categories to which this Title belongs and return an array of
3727 * categories' names.
3729 * @return Array of parents in the form:
3730 * $parent => $currentarticle
3732 public function getParentCategories() {
3737 $titleKey = $this->getArticleId();
3739 if ( $titleKey === 0 ) {
3743 $dbr = wfGetDB( DB_SLAVE
);
3745 $res = $dbr->select( 'categorylinks', '*',
3747 'cl_from' => $titleKey,
3753 if ( $dbr->numRows( $res ) > 0 ) {
3754 foreach ( $res as $row ) {
3755 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3756 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3763 * Get a tree of parent categories
3765 * @param $children Array with the children in the keys, to check for circular refs
3766 * @return Array Tree of parent categories
3768 public function getParentCategoryTree( $children = array() ) {
3770 $parents = $this->getParentCategories();
3773 foreach ( $parents as $parent => $current ) {
3774 if ( array_key_exists( $parent, $children ) ) {
3775 # Circular reference
3776 $stack[$parent] = array();
3778 $nt = Title
::newFromText( $parent );
3780 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3790 * Get an associative array for selecting this title from
3793 * @return Array suitable for the $where parameter of DB::select()
3795 public function pageCond() {
3796 if ( $this->mArticleID
> 0 ) {
3797 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3798 return array( 'page_id' => $this->mArticleID
);
3800 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3805 * Get the revision ID of the previous revision
3807 * @param $revId Int Revision ID. Get the revision that was before this one.
3808 * @param $flags Int Title::GAID_FOR_UPDATE
3809 * @return Int|Bool Old revision ID, or FALSE if none exists
3811 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3812 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3813 return $db->selectField( 'revision', 'rev_id',
3815 'rev_page' => $this->getArticleId( $flags ),
3816 'rev_id < ' . intval( $revId )
3819 array( 'ORDER BY' => 'rev_id DESC' )
3824 * Get the revision ID of the next revision
3826 * @param $revId Int Revision ID. Get the revision that was after this one.
3827 * @param $flags Int Title::GAID_FOR_UPDATE
3828 * @return Int|Bool Next revision ID, or FALSE if none exists
3830 public function getNextRevisionID( $revId, $flags = 0 ) {
3831 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3832 return $db->selectField( 'revision', 'rev_id',
3834 'rev_page' => $this->getArticleId( $flags ),
3835 'rev_id > ' . intval( $revId )
3838 array( 'ORDER BY' => 'rev_id' )
3843 * Get the first revision of the page
3845 * @param $flags Int Title::GAID_FOR_UPDATE
3846 * @return Revision|Null if page doesn't exist
3848 public function getFirstRevision( $flags = 0 ) {
3849 $pageId = $this->getArticleId( $flags );
3851 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3852 $row = $db->selectRow( 'revision', '*',
3853 array( 'rev_page' => $pageId ),
3855 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3858 return new Revision( $row );
3865 * Get the oldest revision timestamp of this page
3867 * @param $flags Int Title::GAID_FOR_UPDATE
3868 * @return String: MW timestamp
3870 public function getEarliestRevTime( $flags = 0 ) {
3871 $rev = $this->getFirstRevision( $flags );
3872 return $rev ?
$rev->getTimestamp() : null;
3876 * Check if this is a new page
3880 public function isNewPage() {
3881 $dbr = wfGetDB( DB_SLAVE
);
3882 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3886 * Get the number of revisions between the given revision.
3887 * Used for diffs and other things that really need it.
3889 * @param $old int|Revision Old revision or rev ID (first before range)
3890 * @param $new int|Revision New revision or rev ID (first after range)
3891 * @return Int Number of revisions between these revisions.
3893 public function countRevisionsBetween( $old, $new ) {
3894 if ( !( $old instanceof Revision
) ) {
3895 $old = Revision
::newFromTitle( $this, (int)$old );
3897 if ( !( $new instanceof Revision
) ) {
3898 $new = Revision
::newFromTitle( $this, (int)$new );
3900 if ( !$old ||
!$new ) {
3901 return 0; // nothing to compare
3903 $dbr = wfGetDB( DB_SLAVE
);
3904 return (int)$dbr->selectField( 'revision', 'count(*)',
3906 'rev_page' => $this->getArticleId(),
3907 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3908 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3915 * Get the number of authors between the given revision IDs.
3916 * Used for diffs and other things that really need it.
3918 * @param $old int|Revision Old revision or rev ID (first before range)
3919 * @param $new int|Revision New revision or rev ID (first after range)
3920 * @param $limit Int Maximum number of authors
3921 * @return Int Number of revision authors between these revisions.
3923 public function countAuthorsBetween( $old, $new, $limit ) {
3924 if ( !( $old instanceof Revision
) ) {
3925 $old = Revision
::newFromTitle( $this, (int)$old );
3927 if ( !( $new instanceof Revision
) ) {
3928 $new = Revision
::newFromTitle( $this, (int)$new );
3930 if ( !$old ||
!$new ) {
3931 return 0; // nothing to compare
3933 $dbr = wfGetDB( DB_SLAVE
);
3934 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
3936 'rev_page' => $this->getArticleID(),
3937 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3938 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3940 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
3942 return (int)$dbr->numRows( $res );
3946 * Compare with another title.
3948 * @param $title Title
3951 public function equals( Title
$title ) {
3952 // Note: === is necessary for proper matching of number-like titles.
3953 return $this->getInterwiki() === $title->getInterwiki()
3954 && $this->getNamespace() == $title->getNamespace()
3955 && $this->getDBkey() === $title->getDBkey();
3959 * Check if this title is a subpage of another title
3961 * @param $title Title
3964 public function isSubpageOf( Title
$title ) {
3965 return $this->getInterwiki() === $title->getInterwiki()
3966 && $this->getNamespace() == $title->getNamespace()
3967 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
3971 * Callback for usort() to do title sorts by (namespace, title)
3976 * @return Integer: result of string comparison, or namespace comparison
3978 public static function compare( $a, $b ) {
3979 if ( $a->getNamespace() == $b->getNamespace() ) {
3980 return strcmp( $a->getText(), $b->getText() );
3982 return $a->getNamespace() - $b->getNamespace();
3987 * Return a string representation of this title
3989 * @return String representation of this title
3991 public function __toString() {
3992 return $this->getPrefixedText();
3996 * Check if page exists. For historical reasons, this function simply
3997 * checks for the existence of the title in the page table, and will
3998 * thus return false for interwiki links, special pages and the like.
3999 * If you want to know if a title can be meaningfully viewed, you should
4000 * probably call the isKnown() method instead.
4004 public function exists() {
4005 return $this->getArticleId() != 0;
4009 * Should links to this title be shown as potentially viewable (i.e. as
4010 * "bluelinks"), even if there's no record by this title in the page
4013 * This function is semi-deprecated for public use, as well as somewhat
4014 * misleadingly named. You probably just want to call isKnown(), which
4015 * calls this function internally.
4017 * (ISSUE: Most of these checks are cheap, but the file existence check
4018 * can potentially be quite expensive. Including it here fixes a lot of
4019 * existing code, but we might want to add an optional parameter to skip
4020 * it and any other expensive checks.)
4024 public function isAlwaysKnown() {
4025 if ( $this->mInterwiki
!= '' ) {
4026 return true; // any interwiki link might be viewable, for all we know
4028 switch( $this->mNamespace
) {
4031 // file exists, possibly in a foreign repo
4032 return (bool)wfFindFile( $this );
4034 // valid special page
4035 return SpecialPageFactory
::exists( $this->getDBkey() );
4037 // selflink, possibly with fragment
4038 return $this->mDbkeyform
== '';
4040 // known system message
4041 return $this->hasSourceText() !== false;
4048 * Does this title refer to a page that can (or might) be meaningfully
4049 * viewed? In particular, this function may be used to determine if
4050 * links to the title should be rendered as "bluelinks" (as opposed to
4051 * "redlinks" to non-existent pages).
4055 public function isKnown() {
4056 return $this->isAlwaysKnown() ||
$this->exists();
4060 * Does this page have source text?
4064 public function hasSourceText() {
4065 if ( $this->exists() ) {
4069 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
4070 // If the page doesn't exist but is a known system message, default
4071 // message content will be displayed, same for language subpages-
4072 // Use always content language to avoid loading hundreds of languages
4073 // to get the link color.
4075 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4076 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4077 return $message->exists();
4084 * Get the default message text or false if the message doesn't exist
4086 * @return String or false
4088 public function getDefaultMessageText() {
4091 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4095 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4096 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4098 if ( $message->exists() ) {
4099 return $message->plain();
4106 * Is this in a namespace that allows actual pages?
4109 * @internal note -- uses hardcoded namespace index instead of constants
4111 public function canExist() {
4112 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
4116 * Update page_touched timestamps and send squid purge messages for
4117 * pages linking to this title. May be sent to the job queue depending
4118 * on the number of links. Typically called on create and delete.
4120 public function touchLinks() {
4121 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4124 if ( $this->getNamespace() == NS_CATEGORY
) {
4125 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4131 * Get the last touched timestamp
4133 * @param $db DatabaseBase: optional db
4134 * @return String last-touched timestamp
4136 public function getTouched( $db = null ) {
4137 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4138 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4143 * Get the timestamp when this page was updated since the user last saw it.
4146 * @return String|Null
4148 public function getNotificationTimestamp( $user = null ) {
4149 global $wgUser, $wgShowUpdatedMarker;
4150 // Assume current user if none given
4154 // Check cache first
4155 $uid = $user->getId();
4156 // avoid isset here, as it'll return false for null entries
4157 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4158 return $this->mNotificationTimestamp
[$uid];
4160 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4161 return $this->mNotificationTimestamp
[$uid] = false;
4163 // Don't cache too much!
4164 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4165 $this->mNotificationTimestamp
= array();
4167 $dbr = wfGetDB( DB_SLAVE
);
4168 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4169 'wl_notificationtimestamp',
4170 array( 'wl_namespace' => $this->getNamespace(),
4171 'wl_title' => $this->getDBkey(),
4172 'wl_user' => $user->getId()
4176 return $this->mNotificationTimestamp
[$uid];
4180 * Generate strings used for xml 'id' names in monobook tabs
4182 * @param $prepend string defaults to 'nstab-'
4183 * @return String XML 'id' name
4185 public function getNamespaceKey( $prepend = 'nstab-' ) {
4187 // Gets the subject namespace if this title
4188 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4189 // Checks if cononical namespace name exists for namespace
4190 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4191 // Uses canonical namespace name
4192 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4194 // Uses text of namespace
4195 $namespaceKey = $this->getSubjectNsText();
4197 // Makes namespace key lowercase
4198 $namespaceKey = $wgContLang->lc( $namespaceKey );
4200 if ( $namespaceKey == '' ) {
4201 $namespaceKey = 'main';
4203 // Changes file to image for backwards compatibility
4204 if ( $namespaceKey == 'file' ) {
4205 $namespaceKey = 'image';
4207 return $prepend . $namespaceKey;
4211 * Returns true if this is a special page.
4215 public function isSpecialPage() {
4216 return $this->getNamespace() == NS_SPECIAL
;
4220 * Returns true if this title resolves to the named special page
4222 * @param $name String The special page name
4225 public function isSpecial( $name ) {
4226 if ( $this->isSpecialPage() ) {
4227 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
4228 if ( $name == $thisName ) {
4236 * If the Title refers to a special page alias which is not the local default, resolve
4237 * the alias, and localise the name as necessary. Otherwise, return $this
4241 public function fixSpecialName() {
4242 if ( $this->isSpecialPage() ) {
4243 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
4244 if ( $canonicalName ) {
4245 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
4246 if ( $localName != $this->mDbkeyform
) {
4247 return Title
::makeTitle( NS_SPECIAL
, $localName );
4255 * Is this Title in a namespace which contains content?
4256 * In other words, is this a content page, for the purposes of calculating
4261 public function isContentPage() {
4262 return MWNamespace
::isContent( $this->getNamespace() );
4266 * Get all extant redirects to this Title
4268 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4269 * @return Array of Title redirects to this title
4271 public function getRedirectsHere( $ns = null ) {
4274 $dbr = wfGetDB( DB_SLAVE
);
4276 'rd_namespace' => $this->getNamespace(),
4277 'rd_title' => $this->getDBkey(),
4280 if ( !is_null( $ns ) ) {
4281 $where['page_namespace'] = $ns;
4284 $res = $dbr->select(
4285 array( 'redirect', 'page' ),
4286 array( 'page_namespace', 'page_title' ),
4291 foreach ( $res as $row ) {
4292 $redirs[] = self
::newFromRow( $row );
4298 * Check if this Title is a valid redirect target
4302 public function isValidRedirectTarget() {
4303 global $wgInvalidRedirectTargets;
4305 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4306 if ( $this->isSpecial( 'Userlogout' ) ) {
4310 foreach ( $wgInvalidRedirectTargets as $target ) {
4311 if ( $this->isSpecial( $target ) ) {
4320 * Get a backlink cache object
4322 * @return BacklinkCache
4324 function getBacklinkCache() {
4325 if ( is_null( $this->mBacklinkCache
) ) {
4326 $this->mBacklinkCache
= new BacklinkCache( $this );
4328 return $this->mBacklinkCache
;
4332 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4336 public function canUseNoindex() {
4337 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4339 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4340 ?
$wgContentNamespaces
4341 : $wgExemptFromUserRobotsControl;
4343 return !in_array( $this->mNamespace
, $bannedNamespaces );
4348 * Returns restriction types for the current Title
4350 * @return array applicable restriction types
4352 public function getRestrictionTypes() {
4353 if ( $this->isSpecialPage() ) {
4357 $types = self
::getFilteredRestrictionTypes( $this->exists() );
4359 if ( $this->getNamespace() != NS_FILE
) {
4360 # Remove the upload restriction for non-file titles
4361 $types = array_diff( $types, array( 'upload' ) );
4364 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4366 wfDebug( __METHOD__
. ': applicable restrictions to [[' .
4367 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
4372 * Get a filtered list of all restriction types supported by this wiki.
4373 * @param bool $exists True to get all restriction types that apply to
4374 * titles that do exist, False for all restriction types that apply to
4375 * titles that do not exist
4378 public static function getFilteredRestrictionTypes( $exists = true ) {
4379 global $wgRestrictionTypes;
4380 $types = $wgRestrictionTypes;
4382 # Remove the create restriction for existing titles
4383 $types = array_diff( $types, array( 'create' ) );
4385 # Only the create and upload restrictions apply to non-existing titles
4386 $types = array_intersect( $types, array( 'create', 'upload' ) );
4392 * Returns the raw sort key to be used for categories, with the specified
4393 * prefix. This will be fed to Collation::getSortKey() to get a
4394 * binary sortkey that can be used for actual sorting.
4396 * @param $prefix string The prefix to be used, specified using
4397 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4401 public function getCategorySortkey( $prefix = '' ) {
4402 $unprefixed = $this->getText();
4404 // Anything that uses this hook should only depend
4405 // on the Title object passed in, and should probably
4406 // tell the users to run updateCollations.php --force
4407 // in order to re-sort existing category relations.
4408 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4409 if ( $prefix !== '' ) {
4410 # Separate with a line feed, so the unprefixed part is only used as
4411 # a tiebreaker when two pages have the exact same prefix.
4412 # In UCA, tab is the only character that can sort above LF
4413 # so we strip both of them from the original prefix.
4414 $prefix = strtr( $prefix, "\n\t", ' ' );
4415 return "$prefix\n$unprefixed";
4421 * Get the language in which the content of this page is written.
4422 * Defaults to $wgContLang, but in certain cases it can be e.g.
4423 * $wgLang (such as special pages, which are in the user language).
4426 * @return object Language
4428 public function getPageLanguage() {
4430 if ( $this->isSpecialPage() ) {
4431 // special pages are in the user language
4433 } elseif ( $this->isCssOrJsPage() ) {
4434 // css/js should always be LTR and is, in fact, English
4435 return wfGetLangObj( 'en' );
4436 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4437 // Parse mediawiki messages with correct target language
4438 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4439 return wfGetLangObj( $lang );
4442 // If nothing special, it should be in the wiki content language
4443 $pageLang = $wgContLang;
4444 // Hook at the end because we don't want to override the above stuff
4445 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4446 return wfGetLangObj( $pageLang );