5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
24 * Represents a title within MediaWiki.
25 * Optionally may contain an interwiki designation or namespace.
26 * @note This class can fetch various kinds of data from the database;
27 * however, it does so inefficiently.
29 * @internal documentation reviewed 15 Mar 2010
32 /** @name Static cache variables */
34 static private $titleCache = array();
38 * Title::newFromText maintains a cache to avoid expensive re-normalization of
39 * commonly used titles. On a batch operation this can become a memory leak
40 * if not bounded. After hitting this many titles reset the cache.
42 const CACHE_MAX
= 1000;
45 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
46 * to use the master DB
48 const GAID_FOR_UPDATE
= 1;
51 * @name Private member variables
52 * Please use the accessor functions instead.
57 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
58 var $mUrlform = ''; // /< URL-encoded form of the main part
59 var $mDbkeyform = ''; // /< Main part with underscores
60 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
61 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
62 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
63 var $mFragment; // /< Title fragment (i.e. the bit after the #)
64 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
65 var $mLatestID = false; // /< ID of most recent revision
66 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
67 var $mOldRestrictions = false;
68 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
69 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
70 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
71 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
72 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
73 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
74 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
75 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
76 # Don't change the following default, NS_MAIN is hardcoded in several
77 # places. See bug 696.
78 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
79 # Zero except in {{transclusion}} tags
80 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
81 var $mLength = -1; // /< The page length, 0 for special pages
82 var $mRedirect = null; // /< Is the article at this title a redirect?
83 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
84 var $mBacklinkCache = null; // /< Cache of links to this title
91 /*protected*/ function __construct() { }
94 * Create a new Title from a prefixed DB key
96 * @param $key String the database key, which has underscores
97 * instead of spaces, possibly including namespace and
99 * @return Title, or NULL on an error
101 public static function newFromDBkey( $key ) {
103 $t->mDbkeyform
= $key;
104 if ( $t->secureAndSplit() ) {
112 * Create a new Title from text, such as what one would find in a link. De-
113 * codes any HTML entities in the text.
115 * @param $text String the link text; spaces, prefixes, and an
116 * initial ':' indicating the main namespace are accepted.
117 * @param $defaultNamespace Int the namespace to use if none is speci-
118 * fied by a prefix. If you want to force a specific namespace even if
119 * $text might begin with a namespace prefix, use makeTitle() or
121 * @return Title, or null on an error.
123 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
124 if ( is_object( $text ) ) {
125 throw new MWException( 'Title::newFromText given an object' );
129 * Wiki pages often contain multiple links to the same page.
130 * Title normalization and parsing can become expensive on
131 * pages with many links, so we can save a little time by
134 * In theory these are value objects and won't get changed...
136 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
137 return Title
::$titleCache[$text];
140 # Convert things like é ā or 〗 into normalized (bug 14952) text
141 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
144 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
145 $t->mDefaultNamespace
= $defaultNamespace;
147 static $cachedcount = 0 ;
148 if ( $t->secureAndSplit() ) {
149 if ( $defaultNamespace == NS_MAIN
) {
150 if ( $cachedcount >= self
::CACHE_MAX
) {
151 # Avoid memory leaks on mass operations...
152 Title
::$titleCache = array();
156 Title
::$titleCache[$text] =& $t;
166 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
168 * Example of wrong and broken code:
169 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
171 * Example of right code:
172 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
174 * Create a new Title from URL-encoded text. Ensures that
175 * the given title's length does not exceed the maximum.
177 * @param $url String the title, as might be taken from a URL
178 * @return Title the new object, or NULL on an error
180 public static function newFromURL( $url ) {
181 global $wgLegalTitleChars;
184 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
185 # but some URLs used it as a space replacement and they still come
186 # from some external search tools.
187 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
188 $url = str_replace( '+', ' ', $url );
191 $t->mDbkeyform
= str_replace( ' ', '_', $url );
192 if ( $t->secureAndSplit() ) {
200 * Create a new Title from an article ID
202 * @param $id Int the page_id corresponding to the Title to create
203 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
204 * @return Title the new object, or NULL on an error
206 public static function newFromID( $id, $flags = 0 ) {
207 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
208 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
209 if ( $row !== false ) {
210 $title = Title
::newFromRow( $row );
218 * Make an array of titles from an array of IDs
220 * @param $ids Array of Int Array of IDs
221 * @return Array of Titles
223 public static function newFromIDs( $ids ) {
224 if ( !count( $ids ) ) {
227 $dbr = wfGetDB( DB_SLAVE
);
232 'page_namespace', 'page_title', 'page_id',
233 'page_len', 'page_is_redirect', 'page_latest',
235 array( 'page_id' => $ids ),
240 foreach ( $res as $row ) {
241 $titles[] = Title
::newFromRow( $row );
247 * Make a Title object from a DB row
249 * @param $row Object database row (needs at least page_title,page_namespace)
250 * @return Title corresponding Title
252 public static function newFromRow( $row ) {
253 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
254 $t->loadFromRow( $row );
259 * Load Title object fields from a DB row.
260 * If false is given, the title will be treated as non-existing.
262 * @param $row Object|false database row
265 public function loadFromRow( $row ) {
266 if ( $row ) { // page found
267 if ( isset( $row->page_id
) )
268 $this->mArticleID
= (int)$row->page_id
;
269 if ( isset( $row->page_len
) )
270 $this->mLength
= (int)$row->page_len
;
271 if ( isset( $row->page_is_redirect
) )
272 $this->mRedirect
= (bool)$row->page_is_redirect
;
273 if ( isset( $row->page_latest
) )
274 $this->mLatestID
= (int)$row->page_latest
;
275 } else { // page not found
276 $this->mArticleID
= 0;
278 $this->mRedirect
= false;
279 $this->mLatestID
= 0;
284 * Create a new Title from a namespace index and a DB key.
285 * It's assumed that $ns and $title are *valid*, for instance when
286 * they came directly from the database or a special page name.
287 * For convenience, spaces are converted to underscores so that
288 * eg user_text fields can be used directly.
290 * @param $ns Int the namespace of the article
291 * @param $title String the unprefixed database key form
292 * @param $fragment String the link fragment (after the "#")
293 * @param $interwiki String the interwiki prefix
294 * @return Title the new object
296 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
298 $t->mInterwiki
= $interwiki;
299 $t->mFragment
= $fragment;
300 $t->mNamespace
= $ns = intval( $ns );
301 $t->mDbkeyform
= str_replace( ' ', '_', $title );
302 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
303 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
304 $t->mTextform
= str_replace( '_', ' ', $title );
309 * Create a new Title from a namespace index and a DB key.
310 * The parameters will be checked for validity, which is a bit slower
311 * than makeTitle() but safer for user-provided data.
313 * @param $ns Int the namespace of the article
314 * @param $title String database key form
315 * @param $fragment String the link fragment (after the "#")
316 * @param $interwiki String interwiki prefix
317 * @return Title the new object, or NULL on an error
319 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
321 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
322 if ( $t->secureAndSplit() ) {
330 * Create a new Title for the Main Page
332 * @return Title the new object
334 public static function newMainPage() {
335 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
336 // Don't give fatal errors if the message is broken
338 $title = Title
::newFromText( 'Main Page' );
344 * Extract a redirect destination from a string and return the
345 * Title, or null if the text doesn't contain a valid redirect
346 * This will only return the very next target, useful for
347 * the redirect table and other checks that don't need full recursion
349 * @param $text String: Text with possible redirect
350 * @return Title: The corresponding Title
352 public static function newFromRedirect( $text ) {
353 return self
::newFromRedirectInternal( $text );
357 * Extract a redirect destination from a string and return the
358 * Title, or null if the text doesn't contain a valid redirect
359 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
360 * in order to provide (hopefully) the Title of the final destination instead of another redirect
362 * @param $text String Text with possible redirect
365 public static function newFromRedirectRecurse( $text ) {
366 $titles = self
::newFromRedirectArray( $text );
367 return $titles ?
array_pop( $titles ) : null;
371 * Extract a redirect destination from a string and return an
372 * array of Titles, or null if the text doesn't contain a valid redirect
373 * The last element in the array is the final destination after all redirects
374 * have been resolved (up to $wgMaxRedirects times)
376 * @param $text String Text with possible redirect
377 * @return Array of Titles, with the destination last
379 public static function newFromRedirectArray( $text ) {
380 global $wgMaxRedirects;
381 $title = self
::newFromRedirectInternal( $text );
382 if ( is_null( $title ) ) {
385 // recursive check to follow double redirects
386 $recurse = $wgMaxRedirects;
387 $titles = array( $title );
388 while ( --$recurse > 0 ) {
389 if ( $title->isRedirect() ) {
390 $page = WikiPage
::factory( $title );
391 $newtitle = $page->getRedirectTarget();
395 // Redirects to some special pages are not permitted
396 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
397 // the new title passes the checks, so make that our current title so that further recursion can be checked
399 $titles[] = $newtitle;
408 * Really extract the redirect destination
409 * Do not call this function directly, use one of the newFromRedirect* functions above
411 * @param $text String Text with possible redirect
414 protected static function newFromRedirectInternal( $text ) {
415 global $wgMaxRedirects;
416 if ( $wgMaxRedirects < 1 ) {
417 //redirects are disabled, so quit early
420 $redir = MagicWord
::get( 'redirect' );
421 $text = trim( $text );
422 if ( $redir->matchStartAndRemove( $text ) ) {
423 // Extract the first link and see if it's usable
424 // Ensure that it really does come directly after #REDIRECT
425 // Some older redirects included a colon, so don't freak about that!
427 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
428 // Strip preceding colon used to "escape" categories, etc.
429 // and URL-decode links
430 if ( strpos( $m[1], '%' ) !== false ) {
431 // Match behavior of inline link parsing here;
432 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
434 $title = Title
::newFromText( $m[1] );
435 // If the title is a redirect to bad special pages or is invalid, return null
436 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
445 # ----------------------------------------------------------------------------
447 # ----------------------------------------------------------------------------
450 * Get the prefixed DB key associated with an ID
452 * @param $id Int the page_id of the article
453 * @return Title an object representing the article, or NULL if no such article was found
455 public static function nameOf( $id ) {
456 $dbr = wfGetDB( DB_SLAVE
);
458 $s = $dbr->selectRow(
460 array( 'page_namespace', 'page_title' ),
461 array( 'page_id' => $id ),
464 if ( $s === false ) {
468 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
473 * Get a regex character class describing the legal characters in a link
475 * @return String the list of characters, not delimited
477 public static function legalChars() {
478 global $wgLegalTitleChars;
479 return $wgLegalTitleChars;
483 * Get a string representation of a title suitable for
484 * including in a search index
486 * @param $ns Int a namespace index
487 * @param $title String text-form main part
488 * @return String a stripped-down title string ready for the search index
490 public static function indexTitle( $ns, $title ) {
493 $lc = SearchEngine
::legalSearchChars() . '&#;';
494 $t = $wgContLang->normalizeForSearch( $title );
495 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
496 $t = $wgContLang->lc( $t );
499 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
500 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
502 $t = preg_replace( "/\\s+/", ' ', $t );
504 if ( $ns == NS_FILE
) {
505 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
511 * Make a prefixed DB key from a DB key and a namespace index
513 * @param $ns Int numerical representation of the namespace
514 * @param $title String the DB key form the title
515 * @param $fragment String The link fragment (after the "#")
516 * @param $interwiki String The interwiki prefix
517 * @return String the prefixed form of the title
519 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
522 $namespace = $wgContLang->getNsText( $ns );
523 $name = $namespace == '' ?
$title : "$namespace:$title";
524 if ( strval( $interwiki ) != '' ) {
525 $name = "$interwiki:$name";
527 if ( strval( $fragment ) != '' ) {
528 $name .= '#' . $fragment;
534 * Determine whether the object refers to a page within
537 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
539 public function isLocal() {
540 if ( $this->mInterwiki
!= '' ) {
541 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
548 * Determine whether the object refers to a page within
549 * this project and is transcludable.
551 * @return Bool TRUE if this is transcludable
553 public function isTrans() {
554 if ( $this->mInterwiki
== '' ) {
558 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
562 * Returns the DB name of the distant wiki which owns the object.
564 * @return String the DB name
566 public function getTransWikiID() {
567 if ( $this->mInterwiki
== '' ) {
571 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
575 * Escape a text fragment, say from a link, for a URL
577 * @param $fragment string containing a URL or link fragment (after the "#")
578 * @return String: escaped string
580 static function escapeFragmentForURL( $fragment ) {
581 # Note that we don't urlencode the fragment. urlencoded Unicode
582 # fragments appear not to work in IE (at least up to 7) or in at least
583 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
584 # to care if they aren't encoded.
585 return Sanitizer
::escapeId( $fragment, 'noninitial' );
588 # ----------------------------------------------------------------------------
590 # ----------------------------------------------------------------------------
592 /** Simple accessors */
594 * Get the text form (spaces not underscores) of the main part
596 * @return String Main part of the title
598 public function getText() { return $this->mTextform
; }
601 * Get the URL-encoded form of the main part
603 * @return String Main part of the title, URL-encoded
605 public function getPartialURL() { return $this->mUrlform
; }
608 * Get the main part with underscores
610 * @return String: Main part of the title, with underscores
612 public function getDBkey() { return $this->mDbkeyform
; }
615 * Get the namespace index, i.e. one of the NS_xxxx constants.
617 * @return Integer: Namespace index
619 public function getNamespace() { return $this->mNamespace
; }
622 * Get the namespace text
624 * @return String: Namespace text
626 public function getNsText() {
629 if ( $this->mInterwiki
!= '' ) {
630 // This probably shouldn't even happen. ohh man, oh yuck.
631 // But for interwiki transclusion it sometimes does.
632 // Shit. Shit shit shit.
634 // Use the canonical namespaces if possible to try to
635 // resolve a foreign namespace.
636 if ( MWNamespace
::exists( $this->mNamespace
) ) {
637 return MWNamespace
::getCanonicalName( $this->mNamespace
);
641 // Strip off subpages
642 $pagename = $this->getText();
643 if ( strpos( $pagename, '/' ) !== false ) {
644 list( $username , ) = explode( '/', $pagename, 2 );
646 $username = $pagename;
649 if ( $wgContLang->needsGenderDistinction() &&
650 MWNamespace
::hasGenderDistinction( $this->mNamespace
) ) {
651 $gender = GenderCache
::singleton()->getGenderOf( $username, __METHOD__
);
652 return $wgContLang->getGenderNsText( $this->mNamespace
, $gender );
655 return $wgContLang->getNsText( $this->mNamespace
);
659 * Get the DB key with the initial letter case as specified by the user
661 * @return String DB key
663 function getUserCaseDBKey() {
664 return $this->mUserCaseDBKey
;
668 * Get the namespace text of the subject (rather than talk) page
670 * @return String Namespace text
672 public function getSubjectNsText() {
674 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
678 * Get the namespace text of the talk page
680 * @return String Namespace text
682 public function getTalkNsText() {
684 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
688 * Could this title have a corresponding talk page?
690 * @return Bool TRUE or FALSE
692 public function canTalk() {
693 return( MWNamespace
::canTalk( $this->mNamespace
) );
697 * Get the interwiki prefix (or null string)
699 * @return String Interwiki prefix
701 public function getInterwiki() { return $this->mInterwiki
; }
704 * Get the Title fragment (i.e.\ the bit after the #) in text form
706 * @return String Title fragment
708 public function getFragment() { return $this->mFragment
; }
711 * Get the fragment in URL form, including the "#" character if there is one
712 * @return String Fragment in URL form
714 public function getFragmentForURL() {
715 if ( $this->mFragment
== '' ) {
718 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
723 * Get the default namespace index, for when there is no namespace
725 * @return Int Default namespace index
727 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
730 * Get title for search index
732 * @return String a stripped-down title string ready for the
735 public function getIndexTitle() {
736 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
740 * Get the prefixed database key form
742 * @return String the prefixed title, with underscores and
743 * any interwiki and namespace prefixes
745 public function getPrefixedDBkey() {
746 $s = $this->prefix( $this->mDbkeyform
);
747 $s = str_replace( ' ', '_', $s );
752 * Get the prefixed title with spaces.
753 * This is the form usually used for display
755 * @return String the prefixed title, with spaces
757 public function getPrefixedText() {
758 // @todo FIXME: Bad usage of empty() ?
759 if ( empty( $this->mPrefixedText
) ) {
760 $s = $this->prefix( $this->mTextform
);
761 $s = str_replace( '_', ' ', $s );
762 $this->mPrefixedText
= $s;
764 return $this->mPrefixedText
;
769 * Get the prefixed title with spaces, plus any fragment
770 * (part beginning with '#')
772 * @return String the prefixed title, with spaces and the fragment, including '#'
774 public function getFullText() {
775 $text = $this->getPrefixedText();
776 if ( $this->mFragment
!= '' ) {
777 $text .= '#' . $this->mFragment
;
783 * Get the base page name, i.e. the leftmost part before any slashes
785 * @return String Base name
787 public function getBaseText() {
788 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
789 return $this->getText();
792 $parts = explode( '/', $this->getText() );
793 # Don't discard the real title if there's no subpage involved
794 if ( count( $parts ) > 1 ) {
795 unset( $parts[count( $parts ) - 1] );
797 return implode( '/', $parts );
801 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
803 * @return String Subpage name
805 public function getSubpageText() {
806 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
807 return( $this->mTextform
);
809 $parts = explode( '/', $this->mTextform
);
810 return( $parts[count( $parts ) - 1] );
814 * Get a URL-encoded form of the subpage text
816 * @return String URL-encoded subpage name
818 public function getSubpageUrlForm() {
819 $text = $this->getSubpageText();
820 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
825 * Get a URL-encoded title (not an actual URL) including interwiki
827 * @return String the URL-encoded form
829 public function getPrefixedURL() {
830 $s = $this->prefix( $this->mDbkeyform
);
831 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
836 * Get a real URL referring to this title, with interwiki link and
839 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
840 * links. Can be specified as an associative array as well, e.g.,
841 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
842 * @param $variant String language variant of url (for sr, zh..)
843 * @return String the URL
845 public function getFullURL( $query = '', $variant = false ) {
846 # Hand off all the decisions on urls to getLocalURL
847 $url = $this->getLocalURL( $query, $variant );
849 # Expand the url to make it a full url. Note that getLocalURL has the
850 # potential to output full urls for a variety of reasons, so we use
851 # wfExpandUrl instead of simply prepending $wgServer
852 $url = wfExpandUrl( $url, PROTO_RELATIVE
);
854 # Finally, add the fragment.
855 $url .= $this->getFragmentForURL();
857 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query, $variant ) );
862 * Get a URL with no fragment or server name. If this page is generated
863 * with action=render, $wgServer is prepended.
865 * @param $query Mixed: an optional query string; if not specified,
866 * $wgArticlePath will be used. Can be specified as an associative array
867 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
869 * @param $variant String language variant of url (for sr, zh..)
870 * @return String the URL
872 public function getLocalURL( $query = '', $variant = false ) {
873 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
874 global $wgVariantArticlePath;
876 if ( is_array( $query ) ) {
877 $query = wfArrayToCGI( $query );
880 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
882 $namespace = $this->getNsText();
883 if ( $namespace != '' ) {
884 # Can this actually happen? Interwikis shouldn't be parsed.
885 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
888 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
889 $url = wfAppendQuery( $url, $query );
891 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
892 if ( $query == '' ) {
893 if ( $variant != false && $this->getPageLanguage()->hasVariants() ) {
894 if ( !$wgVariantArticlePath ) {
895 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
897 $variantArticlePath = $wgVariantArticlePath;
899 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
900 $url = str_replace( '$1', $dbkey, $url );
902 $url = str_replace( '$1', $dbkey, $wgArticlePath );
903 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
906 global $wgActionPaths;
909 if ( !empty( $wgActionPaths ) &&
910 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
912 $action = urldecode( $matches[2] );
913 if ( isset( $wgActionPaths[$action] ) ) {
914 $query = $matches[1];
915 if ( isset( $matches[4] ) ) {
916 $query .= $matches[4];
918 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
919 if ( $query != '' ) {
920 $url = wfAppendQuery( $url, $query );
925 if ( $url === false ) {
926 if ( $query == '-' ) {
929 $url = "{$wgScript}?title={$dbkey}&{$query}";
933 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query, $variant ) );
935 // @todo FIXME: This causes breakage in various places when we
936 // actually expected a local URL and end up with dupe prefixes.
937 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
938 $url = $wgServer . $url;
941 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query, $variant ) );
946 * Get a URL that's the simplest URL that will be valid to link, locally,
947 * to the current Title. It includes the fragment, but does not include
948 * the server unless action=render is used (or the link is external). If
949 * there's a fragment but the prefixed text is empty, we just return a link
952 * The result obviously should not be URL-escaped, but does need to be
953 * HTML-escaped if it's being output in HTML.
955 * @param $query Array of Strings An associative array of key => value pairs for the
956 * query string. Keys and values will be escaped.
957 * @param $variant String language variant of URL (for sr, zh..). Ignored
958 * for external links. Default is "false" (same variant as current page,
959 * for anonymous users).
960 * @return String the URL
962 public function getLinkUrl( $query = array(), $variant = false ) {
963 wfProfileIn( __METHOD__
);
964 if ( $this->isExternal() ) {
965 $ret = $this->getFullURL( $query );
966 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
967 $ret = $this->getFragmentForURL();
969 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
971 wfProfileOut( __METHOD__
);
976 * Get an HTML-escaped version of the URL form, suitable for
977 * using in a link, without a server name or fragment
979 * @param $query String an optional query string
980 * @return String the URL
982 public function escapeLocalURL( $query = '' ) {
983 return htmlspecialchars( $this->getLocalURL( $query ) );
987 * Get an HTML-escaped version of the URL form, suitable for
988 * using in a link, including the server name and fragment
990 * @param $query String an optional query string
991 * @return String the URL
993 public function escapeFullURL( $query = '' ) {
994 return htmlspecialchars( $this->getFullURL( $query ) );
998 * HTML-escaped version of getCanonicalURL()
1001 public function escapeCanonicalURL( $query = '', $variant = false ) {
1002 return htmlspecialchars( $this->getCanonicalURL( $query, $variant ) );
1006 * Get the URL form for an internal link.
1007 * - Used in various Squid-related code, in case we have a different
1008 * internal hostname for the server from the exposed one.
1010 * This uses $wgInternalServer to qualify the path, or $wgServer
1011 * if $wgInternalServer is not set. If the server variable used is
1012 * protocol-relative, the URL will be expanded to http://
1014 * @param $query String an optional query string
1015 * @param $variant String language variant of url (for sr, zh..)
1016 * @return String the URL
1018 public function getInternalURL( $query = '', $variant = false ) {
1019 global $wgInternalServer, $wgServer;
1020 $server = $wgInternalServer !== false ?
$wgInternalServer : $wgServer;
1021 $url = wfExpandUrl( $server . $this->getLocalURL( $query, $variant ), PROTO_HTTP
);
1022 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query, $variant ) );
1027 * Get the URL for a canonical link, for use in things like IRC and
1028 * e-mail notifications. Uses $wgCanonicalServer and the
1029 * GetCanonicalURL hook.
1031 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1033 * @param $query string An optional query string
1034 * @param $variant string Language variant of URL (for sr, zh, ...)
1035 * @return string The URL
1038 public function getCanonicalURL( $query = '', $variant = false ) {
1039 $url = wfExpandUrl( $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL(), PROTO_CANONICAL
);
1040 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query, $variant ) );
1045 * Get the edit URL for this Title
1047 * @return String the URL, or a null string if this is an
1050 public function getEditURL() {
1051 if ( $this->mInterwiki
!= '' ) {
1054 $s = $this->getLocalURL( 'action=edit' );
1060 * Get the HTML-escaped displayable text form.
1061 * Used for the title field in <a> tags.
1063 * @return String the text, including any prefixes
1065 public function getEscapedText() {
1066 return htmlspecialchars( $this->getPrefixedText() );
1070 * Is this Title interwiki?
1074 public function isExternal() {
1075 return ( $this->mInterwiki
!= '' );
1079 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1081 * @param $action String Action to check (default: edit)
1084 public function isSemiProtected( $action = 'edit' ) {
1085 if ( $this->exists() ) {
1086 $restrictions = $this->getRestrictions( $action );
1087 if ( count( $restrictions ) > 0 ) {
1088 foreach ( $restrictions as $restriction ) {
1089 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1099 # If it doesn't exist, it can't be protected
1105 * Does the title correspond to a protected article?
1107 * @param $action String the action the page is protected from,
1108 * by default checks all actions.
1111 public function isProtected( $action = '' ) {
1112 global $wgRestrictionLevels;
1114 $restrictionTypes = $this->getRestrictionTypes();
1116 # Special pages have inherent protection
1117 if( $this->isSpecialPage() ) {
1121 # Check regular protection levels
1122 foreach ( $restrictionTypes as $type ) {
1123 if ( $action == $type ||
$action == '' ) {
1124 $r = $this->getRestrictions( $type );
1125 foreach ( $wgRestrictionLevels as $level ) {
1126 if ( in_array( $level, $r ) && $level != '' ) {
1137 * Determines if $user is unable to edit this page because it has been protected
1138 * by $wgNamespaceProtection.
1140 * @param $user User object to check permissions
1143 public function isNamespaceProtected( User
$user ) {
1144 global $wgNamespaceProtection;
1146 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
1147 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
1148 if ( $right != '' && !$user->isAllowed( $right ) ) {
1157 * Is this a conversion table for the LanguageConverter?
1161 public function isConversionTable() {
1163 $this->getNamespace() == NS_MEDIAWIKI
&&
1164 strpos( $this->getText(), 'Conversiontable' ) !== false
1174 * Is $wgUser watching this page?
1178 public function userIsWatching() {
1181 if ( is_null( $this->mWatched
) ) {
1182 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1183 $this->mWatched
= false;
1185 $this->mWatched
= $wgUser->isWatched( $this );
1188 return $this->mWatched
;
1192 * Can $wgUser read this page?
1194 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1196 * @todo fold these checks into userCan()
1198 public function userCanRead() {
1199 return $this->userCan( 'read' );
1203 * Can $wgUser perform $action on this page?
1204 * This skips potentially expensive cascading permission checks
1205 * as well as avoids expensive error formatting
1207 * Suitable for use for nonessential UI controls in common cases, but
1208 * _not_ for functional access control.
1210 * May provide false positives, but should never provide a false negative.
1212 * @param $action String action that permission needs to be checked for
1213 * @param $user User to check (since 1.19)
1216 public function quickUserCan( $action, $user = null ) {
1217 return $this->userCan( $action, $user, false );
1221 * Can $wgUser perform $action on this page?
1223 * @param $action String action that permission needs to be checked for
1224 * @param $user User to check (since 1.19)
1225 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1228 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1229 if ( !$user instanceof User
) {
1233 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1237 * Can $user perform $action on this page?
1239 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1241 * @param $action String action that permission needs to be checked for
1242 * @param $user User to check
1243 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries by
1244 * skipping checks for cascading protections and user blocks.
1245 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1246 * @return Array of arguments to wfMsg to explain permissions problems.
1248 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1249 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1251 // Remove the errors being ignored.
1252 foreach ( $errors as $index => $error ) {
1253 $error_key = is_array( $error ) ?
$error[0] : $error;
1255 if ( in_array( $error_key, $ignoreErrors ) ) {
1256 unset( $errors[$index] );
1264 * Permissions checks that fail most often, and which are easiest to test.
1266 * @param $action String the action to check
1267 * @param $user User user to check
1268 * @param $errors Array list of current errors
1269 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1270 * @param $short Boolean short circuit on first error
1272 * @return Array list of errors
1274 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1275 $ns = $this->getNamespace();
1277 if ( $action == 'create' ) {
1278 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk', $ns ) ) ||
1279 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage', $ns ) ) ) {
1280 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1282 } elseif ( $action == 'move' ) {
1283 if ( !$user->isAllowed( 'move-rootuserpages', $ns )
1284 && $ns == NS_USER
&& !$this->isSubpage() ) {
1285 // Show user page-specific message only if the user can move other pages
1286 $errors[] = array( 'cant-move-user-page' );
1289 // Check if user is allowed to move files if it's a file
1290 if ( $ns == NS_FILE
&& !$user->isAllowed( 'movefile', $ns ) ) {
1291 $errors[] = array( 'movenotallowedfile' );
1294 if ( !$user->isAllowed( 'move', $ns) ) {
1295 // User can't move anything
1297 $userCanMove = in_array( 'move', User
::getGroupPermissions(
1298 array( 'user' ), $ns ), true );
1299 $autoconfirmedCanMove = in_array( 'move', User
::getGroupPermissions(
1300 array( 'autoconfirmed' ), $ns ), true );
1302 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1303 // custom message if logged-in users without any special rights can move
1304 $errors[] = array( 'movenologintext' );
1306 $errors[] = array( 'movenotallowed' );
1309 } elseif ( $action == 'move-target' ) {
1310 if ( !$user->isAllowed( 'move', $ns ) ) {
1311 // User can't move anything
1312 $errors[] = array( 'movenotallowed' );
1313 } elseif ( !$user->isAllowed( 'move-rootuserpages', $ns )
1314 && $ns == NS_USER
&& !$this->isSubpage() ) {
1315 // Show user page-specific message only if the user can move other pages
1316 $errors[] = array( 'cant-move-to-user-page' );
1318 } elseif ( !$user->isAllowed( $action, $ns ) ) {
1319 $errors[] = $this->missingPermissionError( $action, $short );
1326 * Add the resulting error code to the errors array
1328 * @param $errors Array list of current errors
1329 * @param $result Mixed result of errors
1331 * @return Array list of errors
1333 private function resultToError( $errors, $result ) {
1334 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1335 // A single array representing an error
1336 $errors[] = $result;
1337 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1338 // A nested array representing multiple errors
1339 $errors = array_merge( $errors, $result );
1340 } elseif ( $result !== '' && is_string( $result ) ) {
1341 // A string representing a message-id
1342 $errors[] = array( $result );
1343 } elseif ( $result === false ) {
1344 // a generic "We don't want them to do that"
1345 $errors[] = array( 'badaccess-group0' );
1351 * Check various permission hooks
1353 * @param $action String the action to check
1354 * @param $user User user to check
1355 * @param $errors Array list of current errors
1356 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1357 * @param $short Boolean short circuit on first error
1359 * @return Array list of errors
1361 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1362 // Use getUserPermissionsErrors instead
1364 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1365 return $result ?
array() : array( array( 'badaccess-group0' ) );
1367 // Check getUserPermissionsErrors hook
1368 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1369 $errors = $this->resultToError( $errors, $result );
1371 // Check getUserPermissionsErrorsExpensive hook
1372 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1373 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1374 $errors = $this->resultToError( $errors, $result );
1381 * Check permissions on special pages & namespaces
1383 * @param $action String the action to check
1384 * @param $user User user to check
1385 * @param $errors Array list of current errors
1386 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1387 * @param $short Boolean short circuit on first error
1389 * @return Array list of errors
1391 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1392 # Only 'createaccount' and 'execute' can be performed on
1393 # special pages, which don't actually exist in the DB.
1394 $specialOKActions = array( 'createaccount', 'execute', 'read' );
1395 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1396 $errors[] = array( 'ns-specialprotected' );
1399 # Check $wgNamespaceProtection for restricted namespaces
1400 if ( $this->isNamespaceProtected( $user ) ) {
1401 $ns = $this->mNamespace
== NS_MAIN ?
1402 wfMsg( 'nstab-main' ) : $this->getNsText();
1403 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1404 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1411 * Check CSS/JS sub-page permissions
1413 * @param $action String the action to check
1414 * @param $user User user to check
1415 * @param $errors Array list of current errors
1416 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1417 * @param $short Boolean short circuit on first error
1419 * @return Array list of errors
1421 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1422 # Protect css/js subpages of user pages
1423 # XXX: this might be better using restrictions
1424 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1425 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1426 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1427 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1428 $errors[] = array( 'customcssprotected' );
1429 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1430 $errors[] = array( 'customjsprotected' );
1438 * Check against page_restrictions table requirements on this
1439 * page. The user must possess all required rights for this
1442 * @param $action String the action to check
1443 * @param $user User user to check
1444 * @param $errors Array list of current errors
1445 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1446 * @param $short Boolean short circuit on first error
1448 * @return Array list of errors
1450 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1451 foreach ( $this->getRestrictions( $action ) as $right ) {
1452 // Backwards compatibility, rewrite sysop -> protect
1453 if ( $right == 'sysop' ) {
1456 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace
) ) {
1457 // Users with 'editprotected' permission can edit protected pages
1458 // without cascading option turned on.
1459 if ( $action != 'edit' ||
!$user->isAllowed( 'editprotected', $this->mNamespace
)
1460 ||
$this->mCascadeRestriction
)
1462 $errors[] = array( 'protectedpagetext', $right );
1471 * Check restrictions on cascading pages.
1473 * @param $action String the action to check
1474 * @param $user User to check
1475 * @param $errors Array list of current errors
1476 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1477 * @param $short Boolean short circuit on first error
1479 * @return Array list of errors
1481 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1482 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1483 # We /could/ use the protection level on the source page, but it's
1484 # fairly ugly as we have to establish a precedence hierarchy for pages
1485 # included by multiple cascade-protected pages. So just restrict
1486 # it to people with 'protect' permission, as they could remove the
1487 # protection anyway.
1488 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1489 # Cascading protection depends on more than this page...
1490 # Several cascading protected pages may include this page...
1491 # Check each cascading level
1492 # This is only for protection restrictions, not for all actions
1493 if ( isset( $restrictions[$action] ) ) {
1494 foreach ( $restrictions[$action] as $right ) {
1495 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1496 if ( $right != '' && !$user->isAllowed( $right, $this->mNamespace
) ) {
1498 foreach ( $cascadingSources as $page )
1499 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1500 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1510 * Check action permissions not already checked in checkQuickPermissions
1512 * @param $action String the action to check
1513 * @param $user User to check
1514 * @param $errors Array list of current errors
1515 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1516 * @param $short Boolean short circuit on first error
1518 * @return Array list of errors
1520 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1521 if ( $action == 'protect' ) {
1522 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1523 // If they can't edit, they shouldn't protect.
1524 $errors[] = array( 'protect-cantedit' );
1526 } elseif ( $action == 'create' ) {
1527 $title_protection = $this->getTitleProtection();
1528 if( $title_protection ) {
1529 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1530 $title_protection['pt_create_perm'] = 'protect'; // B/C
1532 if( $title_protection['pt_create_perm'] == '' ||
1533 !$user->isAllowed( $title_protection['pt_create_perm'],
1534 $this->mNamespace
) ) {
1535 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1538 } elseif ( $action == 'move' ) {
1539 // Check for immobile pages
1540 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1541 // Specific message for this case
1542 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1543 } elseif ( !$this->isMovable() ) {
1544 // Less specific message for rarer cases
1545 $errors[] = array( 'immobile-source-page' );
1547 } elseif ( $action == 'move-target' ) {
1548 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1549 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1550 } elseif ( !$this->isMovable() ) {
1551 $errors[] = array( 'immobile-target-page' );
1558 * Check that the user isn't blocked from editting.
1560 * @param $action String the action to check
1561 * @param $user User to check
1562 * @param $errors Array list of current errors
1563 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1564 * @param $short Boolean short circuit on first error
1566 * @return Array list of errors
1568 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1569 // Account creation blocks handled at userlogin.
1570 // Unblocking handled in SpecialUnblock
1571 if( !$doExpensiveQueries ||
in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
1575 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1577 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
1578 $errors[] = array( 'confirmedittext' );
1581 if ( ( $action == 'edit' ||
$action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
1582 // Don't block the user from editing their own talk page unless they've been
1583 // explicitly blocked from that too.
1584 } elseif( $user->isBlocked() && $user->mBlock
->prevents( $action ) !== false ) {
1585 $block = $user->mBlock
;
1587 // This is from OutputPage::blockedPage
1588 // Copied at r23888 by werdna
1590 $id = $user->blockedBy();
1591 $reason = $user->blockedFor();
1592 if ( $reason == '' ) {
1593 $reason = wfMsg( 'blockednoreason' );
1595 $ip = $user->getRequest()->getIP();
1597 if ( is_numeric( $id ) ) {
1598 $name = User
::whoIs( $id );
1603 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1604 $blockid = $block->getId();
1605 $blockExpiry = $user->mBlock
->mExpiry
;
1606 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1607 if ( $blockExpiry == 'infinity' ) {
1608 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1610 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1613 $intended = strval( $user->mBlock
->getTarget() );
1615 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1616 $blockid, $blockExpiry, $intended, $blockTimestamp );
1623 * Check that the user is allowed to read this page.
1625 * @param $action String the action to check
1626 * @param $user User to check
1627 * @param $errors Array list of current errors
1628 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1629 * @param $short Boolean short circuit on first error
1631 * @return Array list of errors
1633 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1634 static $useShortcut = null;
1636 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1637 if ( is_null( $useShortcut ) ) {
1638 global $wgGroupPermissions, $wgRevokePermissions;
1639 $useShortcut = true;
1640 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1641 # Not a public wiki, so no shortcut
1642 $useShortcut = false;
1643 } elseif ( !empty( $wgRevokePermissions ) ) {
1645 * Iterate through each group with permissions being revoked (key not included since we don't care
1646 * what the group name is), then check if the read permission is being revoked. If it is, then
1647 * we don't use the shortcut below since the user might not be able to read, even though anon
1648 * reading is allowed.
1650 foreach ( $wgRevokePermissions as $perms ) {
1651 if ( !empty( $perms['read'] ) ) {
1652 # We might be removing the read right from the user, so no shortcut
1653 $useShortcut = false;
1660 # Shortcut for public wikis, allows skipping quite a bit of code
1661 if ( $useShortcut ) {
1665 # If the user is allowed to read pages, he is allowed to read all pages
1666 if ( $user->isAllowed( 'read', $this->mNamespace
) ) {
1670 # Always grant access to the login page.
1671 # Even anons need to be able to log in.
1672 if ( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'ChangePassword' ) ) {
1676 # Time to check the whitelist
1677 global $wgWhitelistRead;
1679 # Only to these checks is there's something to check against
1680 if ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
1681 # Check for explicit whitelisting
1682 $name = $this->getPrefixedText();
1683 $dbName = $this->getPrefixedDBKey();
1685 // Check with and without underscores
1686 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) ) {
1690 # Old settings might have the title prefixed with
1691 # a colon for main-namespace pages
1692 if ( $this->getNamespace() == NS_MAIN
) {
1693 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1698 # If it's a special page, ditch the subpage bit and check again
1699 if ( $this->isSpecialPage() ) {
1700 $name = $this->getDBkey();
1701 list( $name, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $name );
1702 if ( $name !== false ) {
1703 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1704 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1711 $errors[] = $this->missingPermissionError( $action, $short );
1716 * Get a description array when the user doesn't have the right to perform
1717 * $action (i.e. when User::isAllowed() returns false)
1719 * @param $action String the action to check
1720 * @param $short Boolean short circuit on first error
1721 * @return Array list of errors
1723 private function missingPermissionError( $action, $short ) {
1724 // We avoid expensive display logic for quickUserCan's and such
1726 return array( 'badaccess-group0' );
1729 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1730 User
::getGroupsWithPermission( $action, $this->mNamespace
) );
1732 if ( count( $groups ) ) {
1736 $wgLang->commaList( $groups ),
1740 return array( 'badaccess-group0' );
1745 * Can $user perform $action on this page? This is an internal function,
1746 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1747 * checks on wfReadOnly() and blocks)
1749 * @param $action String action that permission needs to be checked for
1750 * @param $user User to check
1751 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1752 * @param $short Bool Set this to true to stop after the first permission error.
1753 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1755 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1756 wfProfileIn( __METHOD__
);
1758 # Read has special handling
1759 if ( $action == 'read' ) {
1761 'checkPermissionHooks',
1762 'checkReadPermissions',
1766 'checkQuickPermissions',
1767 'checkPermissionHooks',
1768 'checkSpecialsAndNSPermissions',
1769 'checkCSSandJSPermissions',
1770 'checkPageRestrictions',
1771 'checkCascadingSourcesRestrictions',
1772 'checkActionPermissions',
1778 while( count( $checks ) > 0 &&
1779 !( $short && count( $errors ) > 0 ) ) {
1780 $method = array_shift( $checks );
1781 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1784 wfProfileOut( __METHOD__
);
1789 * Is this title subject to title protection?
1790 * Title protection is the one applied against creation of such title.
1792 * @return Mixed An associative array representing any existent title
1793 * protection, or false if there's none.
1795 private function getTitleProtection() {
1796 // Can't protect pages in special namespaces
1797 if ( $this->getNamespace() < 0 ) {
1801 // Can't protect pages that exist.
1802 if ( $this->exists() ) {
1806 if ( !isset( $this->mTitleProtection
) ) {
1807 $dbr = wfGetDB( DB_SLAVE
);
1808 $res = $dbr->select( 'protected_titles', '*',
1809 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1812 // fetchRow returns false if there are no rows.
1813 $this->mTitleProtection
= $dbr->fetchRow( $res );
1815 return $this->mTitleProtection
;
1819 * Update the title protection status
1821 * @param $create_perm String Permission required for creation
1822 * @param $reason String Reason for protection
1823 * @param $expiry String Expiry timestamp
1824 * @return boolean true
1826 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1827 global $wgUser, $wgContLang;
1829 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1830 && $expiry == $this->mRestrictionsExpiry
['create'] ) {
1835 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1837 $dbw = wfGetDB( DB_MASTER
);
1839 $encodedExpiry = $dbw->encodeExpiry( $expiry );
1841 $expiry_description = '';
1842 if ( $encodedExpiry != $dbw->getInfinity() ) {
1843 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1844 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1846 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1849 # Update protection table
1850 if ( $create_perm != '' ) {
1851 $this->mTitleProtection
= array(
1852 'pt_namespace' => $namespace,
1853 'pt_title' => $title,
1854 'pt_create_perm' => $create_perm,
1855 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1856 'pt_expiry' => $encodedExpiry,
1857 'pt_user' => $wgUser->getId(),
1858 'pt_reason' => $reason,
1860 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1861 $this->mTitleProtection
, __METHOD__
);
1863 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1864 'pt_title' => $title ), __METHOD__
);
1865 $this->mTitleProtection
= false;
1868 # Update the protection log
1869 if ( $dbw->affectedRows() ) {
1870 $log = new LogPage( 'protect' );
1872 if ( $create_perm ) {
1873 $params = array( "[create=$create_perm] $expiry_description", '' );
1874 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1876 $log->addEntry( 'unprotect', $this, $reason );
1884 * Remove any title protection due to page existing
1886 public function deleteTitleProtection() {
1887 $dbw = wfGetDB( DB_MASTER
);
1891 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1894 $this->mTitleProtection
= false;
1898 * Would anybody with sufficient privileges be able to move this page?
1899 * Some pages just aren't movable.
1901 * @return Bool TRUE or FALSE
1903 public function isMovable() {
1904 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ||
$this->getInterwiki() != '' ) {
1905 // Interwiki title or immovable namespace. Hooks don't get to override here
1910 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
1915 * Is this the mainpage?
1916 * @note Title::newFromText seams to be sufficiently optimized by the title
1917 * cache that we don't need to over-optimize by doing direct comparisons and
1918 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1919 * ends up reporting something differently than $title->isMainPage();
1924 public function isMainPage() {
1925 return $this->equals( Title
::newMainPage() );
1929 * Is this a talk page of some sort?
1933 public function isTalkPage() {
1934 return MWNamespace
::isTalk( $this->getNamespace() );
1938 * Is this a subpage?
1942 public function isSubpage() {
1943 return MWNamespace
::hasSubpages( $this->mNamespace
)
1944 ?
strpos( $this->getText(), '/' ) !== false
1949 * Does this have subpages? (Warning, usually requires an extra DB query.)
1953 public function hasSubpages() {
1954 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1959 # We dynamically add a member variable for the purpose of this method
1960 # alone to cache the result. There's no point in having it hanging
1961 # around uninitialized in every Title object; therefore we only add it
1962 # if needed and don't declare it statically.
1963 if ( isset( $this->mHasSubpages
) ) {
1964 return $this->mHasSubpages
;
1967 $subpages = $this->getSubpages( 1 );
1968 if ( $subpages instanceof TitleArray
) {
1969 return $this->mHasSubpages
= (bool)$subpages->count();
1971 return $this->mHasSubpages
= false;
1975 * Get all subpages of this page.
1977 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
1978 * @return mixed TitleArray, or empty array if this page's namespace
1979 * doesn't allow subpages
1981 public function getSubpages( $limit = -1 ) {
1982 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
1986 $dbr = wfGetDB( DB_SLAVE
);
1987 $conds['page_namespace'] = $this->getNamespace();
1988 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1990 if ( $limit > -1 ) {
1991 $options['LIMIT'] = $limit;
1993 return $this->mSubpages
= TitleArray
::newFromResult(
1994 $dbr->select( 'page',
1995 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2004 * Does that page contain wikitext, or it is JS, CSS or whatever?
2008 public function isWikitextPage() {
2009 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
2010 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
2015 * Could this page contain custom CSS or JavaScript, based
2020 public function isCssOrJsPage() {
2021 $retval = $this->mNamespace
== NS_MEDIAWIKI
2022 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
2023 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
2028 * Is this a .css or .js subpage of a user page?
2031 public function isCssJsSubpage() {
2032 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
2036 * Is this a *valid* .css or .js subpage of a user page?
2039 * @deprecated since 1.17
2041 public function isValidCssJsSubpage() {
2042 return $this->isCssJsSubpage();
2046 * Trim down a .css or .js subpage title to get the corresponding skin name
2048 * @return string containing skin name from .css or .js subpage title
2050 public function getSkinFromCssJsSubpage() {
2051 $subpage = explode( '/', $this->mTextform
);
2052 $subpage = $subpage[ count( $subpage ) - 1 ];
2053 $lastdot = strrpos( $subpage, '.' );
2054 if ( $lastdot === false )
2055 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
2056 return substr( $subpage, 0, $lastdot );
2060 * Is this a .css subpage of a user page?
2064 public function isCssSubpage() {
2065 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
2069 * Is this a .js subpage of a user page?
2073 public function isJsSubpage() {
2074 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
2078 * Protect css subpages of user pages: can $wgUser edit
2081 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2084 public function userCanEditCssSubpage() {
2086 wfDeprecated( __METHOD__
);
2087 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2088 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2092 * Protect js subpages of user pages: can $wgUser edit
2095 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2098 public function userCanEditJsSubpage() {
2100 wfDeprecated( __METHOD__
);
2101 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2102 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
2106 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2108 * @return Bool If the page is subject to cascading restrictions.
2110 public function isCascadeProtected() {
2111 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2112 return ( $sources > 0 );
2116 * Cascading protection: Get the source of any cascading restrictions on this page.
2118 * @param $getPages Bool Whether or not to retrieve the actual pages
2119 * that the restrictions have come from.
2120 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2121 * have come, false for none, or true if such restrictions exist, but $getPages
2122 * was not set. The restriction array is an array of each type, each of which
2123 * contains a array of unique groups.
2125 public function getCascadeProtectionSources( $getPages = true ) {
2127 $pagerestrictions = array();
2129 if ( isset( $this->mCascadeSources
) && $getPages ) {
2130 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
2131 } elseif ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
2132 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
2135 wfProfileIn( __METHOD__
);
2137 $dbr = wfGetDB( DB_SLAVE
);
2139 if ( $this->getNamespace() == NS_FILE
) {
2140 $tables = array( 'imagelinks', 'page_restrictions' );
2141 $where_clauses = array(
2142 'il_to' => $this->getDBkey(),
2147 $tables = array( 'templatelinks', 'page_restrictions' );
2148 $where_clauses = array(
2149 'tl_namespace' => $this->getNamespace(),
2150 'tl_title' => $this->getDBkey(),
2157 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2158 'pr_expiry', 'pr_type', 'pr_level' );
2159 $where_clauses[] = 'page_id=pr_page';
2162 $cols = array( 'pr_expiry' );
2165 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2167 $sources = $getPages ?
array() : false;
2168 $now = wfTimestampNow();
2169 $purgeExpired = false;
2171 foreach ( $res as $row ) {
2172 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2173 if ( $expiry > $now ) {
2175 $page_id = $row->pr_page
;
2176 $page_ns = $row->page_namespace
;
2177 $page_title = $row->page_title
;
2178 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2179 # Add groups needed for each restriction type if its not already there
2180 # Make sure this restriction type still exists
2182 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2183 $pagerestrictions[$row->pr_type
] = array();
2186 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2187 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2188 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2194 // Trigger lazy purge of expired restrictions from the db
2195 $purgeExpired = true;
2198 if ( $purgeExpired ) {
2199 Title
::purgeExpiredRestrictions();
2203 $this->mCascadeSources
= $sources;
2204 $this->mCascadingRestrictions
= $pagerestrictions;
2206 $this->mHasCascadingRestrictions
= $sources;
2209 wfProfileOut( __METHOD__
);
2210 return array( $sources, $pagerestrictions );
2214 * Returns cascading restrictions for the current article
2218 function areRestrictionsCascading() {
2219 if ( !$this->mRestrictionsLoaded
) {
2220 $this->loadRestrictions();
2223 return $this->mCascadeRestriction
;
2227 * Loads a string into mRestrictions array
2229 * @param $res Resource restrictions as an SQL result.
2230 * @param $oldFashionedRestrictions String comma-separated list of page
2231 * restrictions from page table (pre 1.10)
2233 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2236 foreach ( $res as $row ) {
2240 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2244 * Compiles list of active page restrictions from both page table (pre 1.10)
2245 * and page_restrictions table for this existing page.
2246 * Public for usage by LiquidThreads.
2248 * @param $rows array of db result objects
2249 * @param $oldFashionedRestrictions string comma-separated list of page
2250 * restrictions from page table (pre 1.10)
2252 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2254 $dbr = wfGetDB( DB_SLAVE
);
2256 $restrictionTypes = $this->getRestrictionTypes();
2258 foreach ( $restrictionTypes as $type ) {
2259 $this->mRestrictions
[$type] = array();
2260 $this->mRestrictionsExpiry
[$type] = $wgContLang->formatExpiry( '', TS_MW
);
2263 $this->mCascadeRestriction
= false;
2265 # Backwards-compatibility: also load the restrictions from the page record (old format).
2267 if ( $oldFashionedRestrictions === null ) {
2268 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2269 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2272 if ( $oldFashionedRestrictions != '' ) {
2274 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2275 $temp = explode( '=', trim( $restrict ) );
2276 if ( count( $temp ) == 1 ) {
2277 // old old format should be treated as edit/move restriction
2278 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2279 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2281 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2285 $this->mOldRestrictions
= true;
2289 if ( count( $rows ) ) {
2290 # Current system - load second to make them override.
2291 $now = wfTimestampNow();
2292 $purgeExpired = false;
2294 # Cycle through all the restrictions.
2295 foreach ( $rows as $row ) {
2297 // Don't take care of restrictions types that aren't allowed
2298 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2301 // This code should be refactored, now that it's being used more generally,
2302 // But I don't really see any harm in leaving it in Block for now -werdna
2303 $expiry = $wgContLang->formatExpiry( $row->pr_expiry
, TS_MW
);
2305 // Only apply the restrictions if they haven't expired!
2306 if ( !$expiry ||
$expiry > $now ) {
2307 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2308 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2310 $this->mCascadeRestriction |
= $row->pr_cascade
;
2312 // Trigger a lazy purge of expired restrictions
2313 $purgeExpired = true;
2317 if ( $purgeExpired ) {
2318 Title
::purgeExpiredRestrictions();
2322 $this->mRestrictionsLoaded
= true;
2326 * Load restrictions from the page_restrictions table
2328 * @param $oldFashionedRestrictions String comma-separated list of page
2329 * restrictions from page table (pre 1.10)
2331 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2333 if ( !$this->mRestrictionsLoaded
) {
2334 if ( $this->exists() ) {
2335 $dbr = wfGetDB( DB_SLAVE
);
2337 $res = $dbr->select(
2338 'page_restrictions',
2340 array( 'pr_page' => $this->getArticleId() ),
2344 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2346 $title_protection = $this->getTitleProtection();
2348 if ( $title_protection ) {
2349 $now = wfTimestampNow();
2350 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW
);
2352 if ( !$expiry ||
$expiry > $now ) {
2353 // Apply the restrictions
2354 $this->mRestrictionsExpiry
['create'] = $expiry;
2355 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2356 } else { // Get rid of the old restrictions
2357 Title
::purgeExpiredRestrictions();
2358 $this->mTitleProtection
= false;
2361 $this->mRestrictionsExpiry
['create'] = $wgContLang->formatExpiry( '', TS_MW
);
2363 $this->mRestrictionsLoaded
= true;
2369 * Purge expired restrictions from the page_restrictions table
2371 static function purgeExpiredRestrictions() {
2372 $dbw = wfGetDB( DB_MASTER
);
2374 'page_restrictions',
2375 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2381 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2387 * Accessor/initialisation for mRestrictions
2389 * @param $action String action that permission needs to be checked for
2390 * @return Array of Strings the array of groups allowed to edit this article
2392 public function getRestrictions( $action ) {
2393 if ( !$this->mRestrictionsLoaded
) {
2394 $this->loadRestrictions();
2396 return isset( $this->mRestrictions
[$action] )
2397 ?
$this->mRestrictions
[$action]
2402 * Get the expiry time for the restriction against a given action
2404 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2405 * or not protected at all, or false if the action is not recognised.
2407 public function getRestrictionExpiry( $action ) {
2408 if ( !$this->mRestrictionsLoaded
) {
2409 $this->loadRestrictions();
2411 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2415 * Is there a version of this page in the deletion archive?
2417 * @return Int the number of archived revisions
2419 public function isDeleted() {
2420 if ( $this->getNamespace() < 0 ) {
2423 $dbr = wfGetDB( DB_SLAVE
);
2425 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2426 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2429 if ( $this->getNamespace() == NS_FILE
) {
2430 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2431 array( 'fa_name' => $this->getDBkey() ),
2440 * Is there a version of this page in the deletion archive?
2444 public function isDeletedQuick() {
2445 if ( $this->getNamespace() < 0 ) {
2448 $dbr = wfGetDB( DB_SLAVE
);
2449 $deleted = (bool)$dbr->selectField( 'archive', '1',
2450 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2453 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2454 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2455 array( 'fa_name' => $this->getDBkey() ),
2463 * Get the article ID for this Title from the link cache,
2464 * adding it if necessary
2466 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2468 * @return Int the ID
2470 public function getArticleID( $flags = 0 ) {
2471 if ( $this->getNamespace() < 0 ) {
2472 return $this->mArticleID
= 0;
2474 $linkCache = LinkCache
::singleton();
2475 if ( $flags & self
::GAID_FOR_UPDATE
) {
2476 $oldUpdate = $linkCache->forUpdate( true );
2477 $linkCache->clearLink( $this );
2478 $this->mArticleID
= $linkCache->addLinkObj( $this );
2479 $linkCache->forUpdate( $oldUpdate );
2481 if ( -1 == $this->mArticleID
) {
2482 $this->mArticleID
= $linkCache->addLinkObj( $this );
2485 return $this->mArticleID
;
2489 * Is this an article that is a redirect page?
2490 * Uses link cache, adding it if necessary
2492 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2495 public function isRedirect( $flags = 0 ) {
2496 if ( !is_null( $this->mRedirect
) ) {
2497 return $this->mRedirect
;
2499 # Calling getArticleID() loads the field from cache as needed
2500 if ( !$this->getArticleID( $flags ) ) {
2501 return $this->mRedirect
= false;
2503 $linkCache = LinkCache
::singleton();
2504 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2506 return $this->mRedirect
;
2510 * What is the length of this page?
2511 * Uses link cache, adding it if necessary
2513 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2516 public function getLength( $flags = 0 ) {
2517 if ( $this->mLength
!= -1 ) {
2518 return $this->mLength
;
2520 # Calling getArticleID() loads the field from cache as needed
2521 if ( !$this->getArticleID( $flags ) ) {
2522 return $this->mLength
= 0;
2524 $linkCache = LinkCache
::singleton();
2525 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2527 return $this->mLength
;
2531 * What is the page_latest field for this page?
2533 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2534 * @return Int or 0 if the page doesn't exist
2536 public function getLatestRevID( $flags = 0 ) {
2537 if ( $this->mLatestID
!== false ) {
2538 return intval( $this->mLatestID
);
2540 # Calling getArticleID() loads the field from cache as needed
2541 if ( !$this->getArticleID( $flags ) ) {
2542 return $this->mLatestID
= 0;
2544 $linkCache = LinkCache
::singleton();
2545 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2547 return $this->mLatestID
;
2551 * This clears some fields in this object, and clears any associated
2552 * keys in the "bad links" section of the link cache.
2554 * - This is called from Article::doEdit() and Article::insertOn() to allow
2555 * loading of the new page_id. It's also called from
2556 * Article::doDeleteArticle()
2558 * @param $newid Int the new Article ID
2560 public function resetArticleID( $newid ) {
2561 $linkCache = LinkCache
::singleton();
2562 $linkCache->clearLink( $this );
2564 if ( $newid === false ) {
2565 $this->mArticleID
= -1;
2567 $this->mArticleID
= intval( $newid );
2569 $this->mRestrictionsLoaded
= false;
2570 $this->mRestrictions
= array();
2571 $this->mRedirect
= null;
2572 $this->mLength
= -1;
2573 $this->mLatestID
= false;
2577 * Updates page_touched for this page; called from LinksUpdate.php
2579 * @return Bool true if the update succeded
2581 public function invalidateCache() {
2582 if ( wfReadOnly() ) {
2585 $dbw = wfGetDB( DB_MASTER
);
2586 $success = $dbw->update(
2588 array( 'page_touched' => $dbw->timestamp() ),
2592 HTMLFileCache
::clearFileCache( $this );
2597 * Prefix some arbitrary text with the namespace or interwiki prefix
2600 * @param $name String the text
2601 * @return String the prefixed text
2604 private function prefix( $name ) {
2606 if ( $this->mInterwiki
!= '' ) {
2607 $p = $this->mInterwiki
. ':';
2610 if ( 0 != $this->mNamespace
) {
2611 $p .= $this->getNsText() . ':';
2617 * Returns a simple regex that will match on characters and sequences invalid in titles.
2618 * Note that this doesn't pick up many things that could be wrong with titles, but that
2619 * replacing this regex with something valid will make many titles valid.
2621 * @return String regex string
2623 static function getTitleInvalidRegex() {
2624 static $rxTc = false;
2626 # Matching titles will be held as illegal.
2628 # Any character not allowed is forbidden...
2629 '[^' . Title
::legalChars() . ']' .
2630 # URL percent encoding sequences interfere with the ability
2631 # to round-trip titles -- you can't link to them consistently.
2632 '|%[0-9A-Fa-f]{2}' .
2633 # XML/HTML character references produce similar issues.
2634 '|&[A-Za-z0-9\x80-\xff]+;' .
2636 '|&#x[0-9A-Fa-f]+;' .
2644 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2646 * @param $text String containing title to capitalize
2647 * @param $ns int namespace index, defaults to NS_MAIN
2648 * @return String containing capitalized title
2650 public static function capitalize( $text, $ns = NS_MAIN
) {
2653 if ( MWNamespace
::isCapitalized( $ns ) ) {
2654 return $wgContLang->ucfirst( $text );
2661 * Secure and split - main initialisation function for this object
2663 * Assumes that mDbkeyform has been set, and is urldecoded
2664 * and uses underscores, but not otherwise munged. This function
2665 * removes illegal characters, splits off the interwiki and
2666 * namespace prefixes, sets the other forms, and canonicalizes
2669 * @return Bool true on success
2671 private function secureAndSplit() {
2672 global $wgContLang, $wgLocalInterwiki;
2675 $this->mInterwiki
= $this->mFragment
= '';
2676 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2678 $dbkey = $this->mDbkeyform
;
2680 # Strip Unicode bidi override characters.
2681 # Sometimes they slip into cut-n-pasted page titles, where the
2682 # override chars get included in list displays.
2683 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2685 # Clean up whitespace
2686 # Note: use of the /u option on preg_replace here will cause
2687 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2688 # conveniently disabling them.
2689 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2690 $dbkey = trim( $dbkey, '_' );
2692 if ( $dbkey == '' ) {
2696 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2697 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2701 $this->mDbkeyform
= $dbkey;
2703 # Initial colon indicates main namespace rather than specified default
2704 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2705 if ( ':' == $dbkey[0] ) {
2706 $this->mNamespace
= NS_MAIN
;
2707 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2708 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2711 # Namespace or interwiki prefix
2713 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2716 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2718 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2719 # Ordinary namespace
2721 $this->mNamespace
= $ns;
2722 # For Talk:X pages, check if X has a "namespace" prefix
2723 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2724 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2725 # Disallow Talk:File:x type titles...
2727 } elseif ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2728 # Disallow Talk:Interwiki:x type titles...
2732 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2733 if ( !$firstPass ) {
2734 # Can't make a local interwiki link to an interwiki link.
2735 # That's just crazy!
2741 $this->mInterwiki
= $wgContLang->lc( $p );
2743 # Redundant interwiki prefix to the local wiki
2744 if ( $wgLocalInterwiki !== false
2745 && 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) )
2747 if ( $dbkey == '' ) {
2748 # Can't have an empty self-link
2751 $this->mInterwiki
= '';
2753 # Do another namespace split...
2757 # If there's an initial colon after the interwiki, that also
2758 # resets the default namespace
2759 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2760 $this->mNamespace
= NS_MAIN
;
2761 $dbkey = substr( $dbkey, 1 );
2764 # If there's no recognized interwiki or namespace,
2765 # then let the colon expression be part of the title.
2770 # We already know that some pages won't be in the database!
2771 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2772 $this->mArticleID
= 0;
2774 $fragment = strstr( $dbkey, '#' );
2775 if ( false !== $fragment ) {
2776 $this->setFragment( $fragment );
2777 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2778 # remove whitespace again: prevents "Foo_bar_#"
2779 # becoming "Foo_bar_"
2780 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2783 # Reject illegal characters.
2784 $rxTc = self
::getTitleInvalidRegex();
2785 if ( preg_match( $rxTc, $dbkey ) ) {
2789 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2790 # reachable due to the way web browsers deal with 'relative' URLs.
2791 # Also, they conflict with subpage syntax. Forbid them explicitly.
2792 if ( strpos( $dbkey, '.' ) !== false &&
2793 ( $dbkey === '.' ||
$dbkey === '..' ||
2794 strpos( $dbkey, './' ) === 0 ||
2795 strpos( $dbkey, '../' ) === 0 ||
2796 strpos( $dbkey, '/./' ) !== false ||
2797 strpos( $dbkey, '/../' ) !== false ||
2798 substr( $dbkey, -2 ) == '/.' ||
2799 substr( $dbkey, -3 ) == '/..' ) )
2804 # Magic tilde sequences? Nu-uh!
2805 if ( strpos( $dbkey, '~~~' ) !== false ) {
2809 # Limit the size of titles to 255 bytes. This is typically the size of the
2810 # underlying database field. We make an exception for special pages, which
2811 # don't need to be stored in the database, and may edge over 255 bytes due
2812 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2813 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2814 strlen( $dbkey ) > 512 )
2819 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2820 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2821 # other site might be case-sensitive.
2822 $this->mUserCaseDBKey
= $dbkey;
2823 if ( $this->mInterwiki
== '' ) {
2824 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2827 # Can't make a link to a namespace alone... "empty" local links can only be
2828 # self-links with a fragment identifier.
2829 if ( $dbkey == '' && $this->mInterwiki
== '' && $this->mNamespace
!= NS_MAIN
) {
2833 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2834 // IP names are not allowed for accounts, and can only be referring to
2835 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2836 // there are numerous ways to present the same IP. Having sp:contribs scan
2837 // them all is silly and having some show the edits and others not is
2838 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2839 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
)
2840 ? IP
::sanitizeIP( $dbkey )
2843 // Any remaining initial :s are illegal.
2844 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
2849 $this->mDbkeyform
= $dbkey;
2850 $this->mUrlform
= wfUrlencode( $dbkey );
2852 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2858 * Set the fragment for this title. Removes the first character from the
2859 * specified fragment before setting, so it assumes you're passing it with
2862 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2863 * Still in active use privately.
2865 * @param $fragment String text
2867 public function setFragment( $fragment ) {
2868 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2872 * Get a Title object associated with the talk page of this article
2874 * @return Title the object for the talk page
2876 public function getTalkPage() {
2877 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2881 * Get a title object associated with the subject page of this
2884 * @return Title the object for the subject page
2886 public function getSubjectPage() {
2887 // Is this the same title?
2888 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2889 if ( $this->getNamespace() == $subjectNS ) {
2892 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2896 * Get an array of Title objects linking to this Title
2897 * Also stores the IDs in the link cache.
2899 * WARNING: do not use this function on arbitrary user-supplied titles!
2900 * On heavily-used templates it will max out the memory.
2902 * @param $options Array: may be FOR UPDATE
2903 * @param $table String: table name
2904 * @param $prefix String: fields prefix
2905 * @return Array of Title objects linking here
2907 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2908 $linkCache = LinkCache
::singleton();
2910 if ( count( $options ) > 0 ) {
2911 $db = wfGetDB( DB_MASTER
);
2913 $db = wfGetDB( DB_SLAVE
);
2917 array( 'page', $table ),
2918 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2920 "{$prefix}_from=page_id",
2921 "{$prefix}_namespace" => $this->getNamespace(),
2922 "{$prefix}_title" => $this->getDBkey() ),
2928 if ( $db->numRows( $res ) ) {
2929 foreach ( $res as $row ) {
2930 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
2932 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
2933 $retVal[] = $titleObj;
2941 * Get an array of Title objects using this Title as a template
2942 * Also stores the IDs in the link cache.
2944 * WARNING: do not use this function on arbitrary user-supplied titles!
2945 * On heavily-used templates it will max out the memory.
2947 * @param $options Array: may be FOR UPDATE
2948 * @return Array of Title the Title objects linking here
2950 public function getTemplateLinksTo( $options = array() ) {
2951 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2955 * Get an array of Title objects referring to non-existent articles linked from this page
2957 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2958 * @return Array of Title the Title objects
2960 public function getBrokenLinksFrom() {
2961 if ( $this->getArticleId() == 0 ) {
2962 # All links from article ID 0 are false positives
2966 $dbr = wfGetDB( DB_SLAVE
);
2967 $res = $dbr->select(
2968 array( 'page', 'pagelinks' ),
2969 array( 'pl_namespace', 'pl_title' ),
2971 'pl_from' => $this->getArticleId(),
2972 'page_namespace IS NULL'
2974 __METHOD__
, array(),
2978 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2984 foreach ( $res as $row ) {
2985 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2992 * Get a list of URLs to purge from the Squid cache when this
2995 * @return Array of String the URLs
2997 public function getSquidURLs() {
3001 $this->getInternalURL(),
3002 $this->getInternalURL( 'action=history' )
3005 // purge variant urls as well
3006 if ( $wgContLang->hasVariants() ) {
3007 $variants = $wgContLang->getVariants();
3008 foreach ( $variants as $vCode ) {
3009 $urls[] = $this->getInternalURL( '', $vCode );
3017 * Purge all applicable Squid URLs
3019 public function purgeSquid() {
3021 if ( $wgUseSquid ) {
3022 $urls = $this->getSquidURLs();
3023 $u = new SquidUpdate( $urls );
3029 * Move this page without authentication
3031 * @param $nt Title the new page Title
3032 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3034 public function moveNoAuth( &$nt ) {
3035 return $this->moveTo( $nt, false );
3039 * Check whether a given move operation would be valid.
3040 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3042 * @param $nt Title the new title
3043 * @param $auth Bool indicates whether $wgUser's permissions
3045 * @param $reason String is the log summary of the move, used for spam checking
3046 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3048 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3053 // Normally we'd add this to $errors, but we'll get
3054 // lots of syntax errors if $nt is not an object
3055 return array( array( 'badtitletext' ) );
3057 if ( $this->equals( $nt ) ) {
3058 $errors[] = array( 'selfmove' );
3060 if ( !$this->isMovable() ) {
3061 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3063 if ( $nt->getInterwiki() != '' ) {
3064 $errors[] = array( 'immobile-target-namespace-iw' );
3066 if ( !$nt->isMovable() ) {
3067 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3070 $oldid = $this->getArticleID();
3071 $newid = $nt->getArticleID();
3073 if ( strlen( $nt->getDBkey() ) < 1 ) {
3074 $errors[] = array( 'articleexists' );
3076 if ( ( $this->getDBkey() == '' ) ||
3078 ( $nt->getDBkey() == '' ) ) {
3079 $errors[] = array( 'badarticleerror' );
3082 // Image-specific checks
3083 if ( $this->getNamespace() == NS_FILE
) {
3084 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3087 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
3088 $errors[] = array( 'nonfile-cannot-move-to-file' );
3092 $errors = wfMergeErrorArrays( $errors,
3093 $this->getUserPermissionsErrors( 'move', $wgUser ),
3094 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3095 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3096 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3099 $match = EditPage
::matchSummarySpamRegex( $reason );
3100 if ( $match !== false ) {
3101 // This is kind of lame, won't display nice
3102 $errors[] = array( 'spamprotectiontext' );
3106 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3107 $errors[] = array( 'hookaborted', $err );
3110 # The move is allowed only if (1) the target doesn't exist, or
3111 # (2) the target is a redirect to the source, and has no history
3112 # (so we can undo bad moves right after they're done).
3114 if ( 0 != $newid ) { # Target exists; check for validity
3115 if ( !$this->isValidMoveTarget( $nt ) ) {
3116 $errors[] = array( 'articleexists' );
3119 $tp = $nt->getTitleProtection();
3120 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3121 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3122 $errors[] = array( 'cantmove-titleprotected' );
3125 if ( empty( $errors ) ) {
3132 * Check if the requested move target is a valid file move target
3133 * @param Title $nt Target title
3134 * @return array List of errors
3136 protected function validateFileMoveOperation( $nt ) {
3141 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3143 $file = wfLocalFile( $this );
3144 if ( $file->exists() ) {
3145 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3146 $errors[] = array( 'imageinvalidfilename' );
3148 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3149 $errors[] = array( 'imagetypemismatch' );
3153 if ( $nt->getNamespace() != NS_FILE
) {
3154 $errors[] = array( 'imagenocrossnamespace' );
3155 // From here we want to do checks on a file object, so if we can't
3156 // create one, we must return.
3160 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3162 $destFile = wfLocalFile( $nt );
3163 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3164 $errors[] = array( 'file-exists-sharedrepo' );
3171 * Move a title to a new location
3173 * @param $nt Title the new title
3174 * @param $auth Bool indicates whether $wgUser's permissions
3176 * @param $reason String the reason for the move
3177 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3178 * Ignored if the user doesn't have the suppressredirect right.
3179 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3181 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3183 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3184 if ( is_array( $err ) ) {
3185 // Auto-block user's IP if the account was "hard" blocked
3186 $wgUser->spreadAnyEditBlock();
3190 // If it is a file, move it first.
3191 // It is done before all other moving stuff is done because it's hard to revert.
3192 $dbw = wfGetDB( DB_MASTER
);
3193 if ( $this->getNamespace() == NS_FILE
) {
3194 $file = wfLocalFile( $this );
3195 if ( $file->exists() ) {
3196 $status = $file->move( $nt );
3197 if ( !$status->isOk() ) {
3198 return $status->getErrorsArray();
3202 // Clear RepoGroup process cache
3203 RepoGroup
::singleton()->clearCache( $this );
3204 RepoGroup
::singleton()->clearCache( $nt ); # clear false negative cache
3206 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3207 $pageid = $this->getArticleID( self
::GAID_FOR_UPDATE
);
3208 $protected = $this->isProtected();
3209 $pageCountChange = ( $createRedirect ?
1 : 0 ) - ( $nt->exists() ?
1 : 0 );
3211 // Do the actual move
3212 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3213 if ( is_array( $err ) ) {
3214 # @todo FIXME: What about the File we have already moved?
3219 $redirid = $this->getArticleID();
3221 // Refresh the sortkey for this row. Be careful to avoid resetting
3222 // cl_timestamp, which may disturb time-based lists on some sites.
3223 $prefixes = $dbw->select(
3225 array( 'cl_sortkey_prefix', 'cl_to' ),
3226 array( 'cl_from' => $pageid ),
3229 foreach ( $prefixes as $prefixRow ) {
3230 $prefix = $prefixRow->cl_sortkey_prefix
;
3231 $catTo = $prefixRow->cl_to
;
3232 $dbw->update( 'categorylinks',
3234 'cl_sortkey' => Collation
::singleton()->getSortKey(
3235 $nt->getCategorySortkey( $prefix ) ),
3236 'cl_timestamp=cl_timestamp' ),
3238 'cl_from' => $pageid,
3239 'cl_to' => $catTo ),
3245 # Protect the redirect title as the title used to be...
3246 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3248 'pr_page' => $redirid,
3249 'pr_type' => 'pr_type',
3250 'pr_level' => 'pr_level',
3251 'pr_cascade' => 'pr_cascade',
3252 'pr_user' => 'pr_user',
3253 'pr_expiry' => 'pr_expiry'
3255 array( 'pr_page' => $pageid ),
3259 # Update the protection log
3260 $log = new LogPage( 'protect' );
3261 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3263 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3265 // @todo FIXME: $params?
3266 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3270 $oldnamespace = $this->getNamespace() & ~
1;
3271 $newnamespace = $nt->getNamespace() & ~
1;
3272 $oldtitle = $this->getDBkey();
3273 $newtitle = $nt->getDBkey();
3275 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3276 WatchedItem
::duplicateEntries( $this, $nt );
3279 # Update search engine
3280 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3282 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3288 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3289 # No longer a content page
3290 # Not viewed, edited, removing
3291 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3292 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3293 # Now a content page
3294 # Not viewed, edited, adding
3295 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
3296 } elseif ( $pageCountChange ) {
3298 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3307 # Update message cache for interface messages
3308 if ( $this->getNamespace() == NS_MEDIAWIKI
) {
3309 # @bug 17860: old article can be deleted, if this the case,
3310 # delete it from message cache
3311 if ( $this->getArticleID() === 0 ) {
3312 MessageCache
::singleton()->replace( $this->getDBkey(), false );
3314 $rev = Revision
::newFromTitle( $this );
3315 MessageCache
::singleton()->replace( $this->getDBkey(), $rev->getText() );
3318 if ( $nt->getNamespace() == NS_MEDIAWIKI
) {
3319 $rev = Revision
::newFromTitle( $nt );
3320 MessageCache
::singleton()->replace( $nt->getDBkey(), $rev->getText() );
3323 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3328 * Move page to a title which is either a redirect to the
3329 * source page or nonexistent
3331 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3332 * @param $reason String The reason for the move
3333 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3334 * if the user doesn't have the suppressredirect right
3336 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3337 global $wgUser, $wgContLang;
3339 if ( $nt->exists() ) {
3340 $moveOverRedirect = true;
3341 $logType = 'move_redir';
3343 $moveOverRedirect = false;
3347 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3349 $logEntry = new ManualLogEntry( 'move', $logType );
3350 $logEntry->setPerformer( $wgUser );
3351 $logEntry->setTarget( $this );
3352 $logEntry->setComment( $reason );
3353 $logEntry->setParameters( array(
3354 '4::target' => $nt->getPrefixedText(),
3355 '5::noredir' => $redirectSuppressed ?
'1': '0',
3358 $formatter = LogFormatter
::newFromEntry( $logEntry );
3359 $formatter->setContext( RequestContext
::newExtraneousContext( $this ) );
3360 $comment = $formatter->getPlainActionText();
3362 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3364 # Truncate for whole multibyte characters.
3365 $comment = $wgContLang->truncate( $comment, 255 );
3367 $oldid = $this->getArticleID();
3368 $latest = $this->getLatestRevID();
3370 $dbw = wfGetDB( DB_MASTER
);
3372 if ( $moveOverRedirect ) {
3373 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3375 $newid = $nt->getArticleID();
3376 $newns = $nt->getNamespace();
3377 $newdbk = $nt->getDBkey();
3379 # Delete the old redirect. We don't save it to history since
3380 # by definition if we've got here it's rather uninteresting.
3381 # We have to remove it so that the next step doesn't trigger
3382 # a conflict on the unique namespace+title index...
3383 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3384 if ( !$dbw->cascadingDeletes() ) {
3385 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3386 global $wgUseTrackbacks;
3387 if ( $wgUseTrackbacks ) {
3388 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
3390 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3391 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3392 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3393 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3394 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3395 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3396 $dbw->delete( 'iwlinks', array( 'iwl_from' => $newid ), __METHOD__
);
3397 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3398 $dbw->delete( 'page_props', array( 'pp_page' => $newid ), __METHOD__
);
3400 // If the target page was recently created, it may have an entry in recentchanges still
3401 $dbw->delete( 'recentchanges',
3402 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3407 # Save a null revision in the page's history notifying of the move
3408 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3409 if ( !is_object( $nullRevision ) ) {
3410 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3412 $nullRevId = $nullRevision->insertOn( $dbw );
3414 $now = wfTimestampNow();
3415 # Change the name of the target page:
3416 $dbw->update( 'page',
3418 'page_touched' => $dbw->timestamp( $now ),
3419 'page_namespace' => $nt->getNamespace(),
3420 'page_title' => $nt->getDBkey(),
3421 'page_latest' => $nullRevId,
3423 /* WHERE */ array( 'page_id' => $oldid ),
3426 $nt->resetArticleID( $oldid );
3428 $article = WikiPage
::factory( $nt );
3429 wfRunHooks( 'NewRevisionFromEditComplete',
3430 array( $article, $nullRevision, $latest, $wgUser ) );
3431 $article->setCachedLastEditTime( $now );
3433 # Recreate the redirect, this time in the other direction.
3434 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3435 $mwRedir = MagicWord
::get( 'redirect' );
3436 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3437 $redirectArticle = WikiPage
::factory( $this );
3438 $newid = $redirectArticle->insertOn( $dbw );
3439 if ( $newid ) { // sanity
3440 $redirectRevision = new Revision( array(
3442 'comment' => $comment,
3443 'text' => $redirectText ) );
3444 $redirectRevision->insertOn( $dbw );
3445 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3447 wfRunHooks( 'NewRevisionFromEditComplete',
3448 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3450 # Now, we record the link from the redirect to the new title.
3451 # It should have no other outgoing links...
3452 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3453 $dbw->insert( 'pagelinks',
3455 'pl_from' => $newid,
3456 'pl_namespace' => $nt->getNamespace(),
3457 'pl_title' => $nt->getDBkey() ),
3461 $this->resetArticleID( 0 );
3465 $logid = $logEntry->insert();
3466 $logEntry->publish( $logid );
3468 # Purge caches for old and new titles
3469 if ( $moveOverRedirect ) {
3470 # A simple purge is enough when moving over a redirect
3473 # Purge caches as per article creation, including any pages that link to this title
3474 Article
::onArticleCreate( $nt );
3476 $this->purgeSquid();
3480 * Move this page's subpages to be subpages of $nt
3482 * @param $nt Title Move target
3483 * @param $auth bool Whether $wgUser's permissions should be checked
3484 * @param $reason string The reason for the move
3485 * @param $createRedirect bool Whether to create redirects from the old subpages to
3486 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3487 * @return mixed array with old page titles as keys, and strings (new page titles) or
3488 * arrays (errors) as values, or an error array with numeric indices if no pages
3491 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3492 global $wgMaximumMovedPages;
3493 // Check permissions
3494 if ( !$this->userCan( 'move-subpages' ) ) {
3495 return array( 'cant-move-subpages' );
3497 // Do the source and target namespaces support subpages?
3498 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3499 return array( 'namespace-nosubpages',
3500 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3502 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3503 return array( 'namespace-nosubpages',
3504 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3507 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3510 foreach ( $subpages as $oldSubpage ) {
3512 if ( $count > $wgMaximumMovedPages ) {
3513 $retval[$oldSubpage->getPrefixedTitle()] =
3514 array( 'movepage-max-pages',
3515 $wgMaximumMovedPages );
3519 // We don't know whether this function was called before
3520 // or after moving the root page, so check both
3522 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3523 $oldSubpage->getArticleID() == $nt->getArticleId() )
3525 // When moving a page to a subpage of itself,
3526 // don't move it twice
3529 $newPageName = preg_replace(
3530 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3531 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3532 $oldSubpage->getDBkey() );
3533 if ( $oldSubpage->isTalkPage() ) {
3534 $newNs = $nt->getTalkPage()->getNamespace();
3536 $newNs = $nt->getSubjectPage()->getNamespace();
3538 # Bug 14385: we need makeTitleSafe because the new page names may
3539 # be longer than 255 characters.
3540 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3542 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3543 if ( $success === true ) {
3544 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3546 $retval[$oldSubpage->getPrefixedText()] = $success;
3553 * Checks if this page is just a one-rev redirect.
3554 * Adds lock, so don't use just for light purposes.
3558 public function isSingleRevRedirect() {
3559 $dbw = wfGetDB( DB_MASTER
);
3561 $row = $dbw->selectRow( 'page',
3562 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3565 array( 'FOR UPDATE' )
3567 # Cache some fields we may want
3568 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3569 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3570 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3571 if ( !$this->mRedirect
) {
3574 # Does the article have a history?
3575 $row = $dbw->selectField( array( 'page', 'revision' ),
3577 array( 'page_namespace' => $this->getNamespace(),
3578 'page_title' => $this->getDBkey(),
3580 'page_latest != rev_id'
3583 array( 'FOR UPDATE' )
3585 # Return true if there was no history
3586 return ( $row === false );
3590 * Checks if $this can be moved to a given Title
3591 * - Selects for update, so don't call it unless you mean business
3593 * @param $nt Title the new title to check
3596 public function isValidMoveTarget( $nt ) {
3597 # Is it an existing file?
3598 if ( $nt->getNamespace() == NS_FILE
) {
3599 $file = wfLocalFile( $nt );
3600 if ( $file->exists() ) {
3601 wfDebug( __METHOD__
. ": file exists\n" );
3605 # Is it a redirect with no history?
3606 if ( !$nt->isSingleRevRedirect() ) {
3607 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3610 # Get the article text
3611 $rev = Revision
::newFromTitle( $nt );
3612 if( !is_object( $rev ) ){
3615 $text = $rev->getText();
3616 # Does the redirect point to the source?
3617 # Or is it a broken self-redirect, usually caused by namespace collisions?
3619 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3620 $redirTitle = Title
::newFromText( $m[1] );
3621 if ( !is_object( $redirTitle ) ||
3622 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3623 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3624 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3629 wfDebug( __METHOD__
. ": failsafe\n" );
3636 * Can this title be added to a user's watchlist?
3638 * @return Bool TRUE or FALSE
3640 public function isWatchable() {
3641 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3645 * Get categories to which this Title belongs and return an array of
3646 * categories' names.
3648 * @return Array of parents in the form:
3649 * $parent => $currentarticle
3651 public function getParentCategories() {
3656 $titleKey = $this->getArticleId();
3658 if ( $titleKey === 0 ) {
3662 $dbr = wfGetDB( DB_SLAVE
);
3664 $res = $dbr->select( 'categorylinks', '*',
3666 'cl_from' => $titleKey,
3672 if ( $dbr->numRows( $res ) > 0 ) {
3673 foreach ( $res as $row ) {
3674 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3675 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3682 * Get a tree of parent categories
3684 * @param $children Array with the children in the keys, to check for circular refs
3685 * @return Array Tree of parent categories
3687 public function getParentCategoryTree( $children = array() ) {
3689 $parents = $this->getParentCategories();
3692 foreach ( $parents as $parent => $current ) {
3693 if ( array_key_exists( $parent, $children ) ) {
3694 # Circular reference
3695 $stack[$parent] = array();
3697 $nt = Title
::newFromText( $parent );
3699 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3709 * Get an associative array for selecting this title from
3712 * @return Array suitable for the $where parameter of DB::select()
3714 public function pageCond() {
3715 if ( $this->mArticleID
> 0 ) {
3716 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3717 return array( 'page_id' => $this->mArticleID
);
3719 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3724 * Get the revision ID of the previous revision
3726 * @param $revId Int Revision ID. Get the revision that was before this one.
3727 * @param $flags Int Title::GAID_FOR_UPDATE
3728 * @return Int|Bool Old revision ID, or FALSE if none exists
3730 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3731 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3732 return $db->selectField( 'revision', 'rev_id',
3734 'rev_page' => $this->getArticleId( $flags ),
3735 'rev_id < ' . intval( $revId )
3738 array( 'ORDER BY' => 'rev_id DESC' )
3743 * Get the revision ID of the next revision
3745 * @param $revId Int Revision ID. Get the revision that was after this one.
3746 * @param $flags Int Title::GAID_FOR_UPDATE
3747 * @return Int|Bool Next revision ID, or FALSE if none exists
3749 public function getNextRevisionID( $revId, $flags = 0 ) {
3750 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3751 return $db->selectField( 'revision', 'rev_id',
3753 'rev_page' => $this->getArticleId( $flags ),
3754 'rev_id > ' . intval( $revId )
3757 array( 'ORDER BY' => 'rev_id' )
3762 * Get the first revision of the page
3764 * @param $flags Int Title::GAID_FOR_UPDATE
3765 * @return Revision|Null if page doesn't exist
3767 public function getFirstRevision( $flags = 0 ) {
3768 $pageId = $this->getArticleId( $flags );
3770 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3771 $row = $db->selectRow( 'revision', '*',
3772 array( 'rev_page' => $pageId ),
3774 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3777 return new Revision( $row );
3784 * Get the oldest revision timestamp of this page
3786 * @param $flags Int Title::GAID_FOR_UPDATE
3787 * @return String: MW timestamp
3789 public function getEarliestRevTime( $flags = 0 ) {
3790 $rev = $this->getFirstRevision( $flags );
3791 return $rev ?
$rev->getTimestamp() : null;
3795 * Check if this is a new page
3799 public function isNewPage() {
3800 $dbr = wfGetDB( DB_SLAVE
);
3801 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3805 * Get the number of revisions between the given revision.
3806 * Used for diffs and other things that really need it.
3808 * @param $old int|Revision Old revision or rev ID (first before range)
3809 * @param $new int|Revision New revision or rev ID (first after range)
3810 * @return Int Number of revisions between these revisions.
3812 public function countRevisionsBetween( $old, $new ) {
3813 if ( !( $old instanceof Revision
) ) {
3814 $old = Revision
::newFromTitle( $this, (int)$old );
3816 if ( !( $new instanceof Revision
) ) {
3817 $new = Revision
::newFromTitle( $this, (int)$new );
3819 if ( !$old ||
!$new ) {
3820 return 0; // nothing to compare
3822 $dbr = wfGetDB( DB_SLAVE
);
3823 return (int)$dbr->selectField( 'revision', 'count(*)',
3825 'rev_page' => $this->getArticleId(),
3826 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3827 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3834 * Get the number of authors between the given revision IDs.
3835 * Used for diffs and other things that really need it.
3837 * @param $old int|Revision Old revision or rev ID (first before range)
3838 * @param $new int|Revision New revision or rev ID (first after range)
3839 * @param $limit Int Maximum number of authors
3840 * @return Int Number of revision authors between these revisions.
3842 public function countAuthorsBetween( $old, $new, $limit ) {
3843 if ( !( $old instanceof Revision
) ) {
3844 $old = Revision
::newFromTitle( $this, (int)$old );
3846 if ( !( $new instanceof Revision
) ) {
3847 $new = Revision
::newFromTitle( $this, (int)$new );
3849 if ( !$old ||
!$new ) {
3850 return 0; // nothing to compare
3852 $dbr = wfGetDB( DB_SLAVE
);
3853 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
3855 'rev_page' => $this->getArticleID(),
3856 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3857 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3859 array( 'LIMIT' => $limit +
1 ) // add one so caller knows it was truncated
3861 return (int)$dbr->numRows( $res );
3865 * Compare with another title.
3867 * @param $title Title
3870 public function equals( Title
$title ) {
3871 // Note: === is necessary for proper matching of number-like titles.
3872 return $this->getInterwiki() === $title->getInterwiki()
3873 && $this->getNamespace() == $title->getNamespace()
3874 && $this->getDBkey() === $title->getDBkey();
3878 * Check if this title is a subpage of another title
3880 * @param $title Title
3883 public function isSubpageOf( Title
$title ) {
3884 return $this->getInterwiki() === $title->getInterwiki()
3885 && $this->getNamespace() == $title->getNamespace()
3886 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
3890 * Callback for usort() to do title sorts by (namespace, title)
3895 * @return Integer: result of string comparison, or namespace comparison
3897 public static function compare( $a, $b ) {
3898 if ( $a->getNamespace() == $b->getNamespace() ) {
3899 return strcmp( $a->getText(), $b->getText() );
3901 return $a->getNamespace() - $b->getNamespace();
3906 * Return a string representation of this title
3908 * @return String representation of this title
3910 public function __toString() {
3911 return $this->getPrefixedText();
3915 * Check if page exists. For historical reasons, this function simply
3916 * checks for the existence of the title in the page table, and will
3917 * thus return false for interwiki links, special pages and the like.
3918 * If you want to know if a title can be meaningfully viewed, you should
3919 * probably call the isKnown() method instead.
3923 public function exists() {
3924 return $this->getArticleId() != 0;
3928 * Should links to this title be shown as potentially viewable (i.e. as
3929 * "bluelinks"), even if there's no record by this title in the page
3932 * This function is semi-deprecated for public use, as well as somewhat
3933 * misleadingly named. You probably just want to call isKnown(), which
3934 * calls this function internally.
3936 * (ISSUE: Most of these checks are cheap, but the file existence check
3937 * can potentially be quite expensive. Including it here fixes a lot of
3938 * existing code, but we might want to add an optional parameter to skip
3939 * it and any other expensive checks.)
3943 public function isAlwaysKnown() {
3944 if ( $this->mInterwiki
!= '' ) {
3945 return true; // any interwiki link might be viewable, for all we know
3947 switch( $this->mNamespace
) {
3950 // file exists, possibly in a foreign repo
3951 return (bool)wfFindFile( $this );
3953 // valid special page
3954 return SpecialPageFactory
::exists( $this->getDBkey() );
3956 // selflink, possibly with fragment
3957 return $this->mDbkeyform
== '';
3959 // known system message
3960 return $this->hasSourceText() !== false;
3967 * Does this title refer to a page that can (or might) be meaningfully
3968 * viewed? In particular, this function may be used to determine if
3969 * links to the title should be rendered as "bluelinks" (as opposed to
3970 * "redlinks" to non-existent pages).
3974 public function isKnown() {
3975 return $this->isAlwaysKnown() ||
$this->exists();
3979 * Does this page have source text?
3983 public function hasSourceText() {
3984 if ( $this->exists() ) {
3988 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
3989 // If the page doesn't exist but is a known system message, default
3990 // message content will be displayed, same for language subpages-
3991 // Use always content language to avoid loading hundreds of languages
3992 // to get the link color.
3994 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
3995 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
3996 return $message->exists();
4003 * Get the default message text or false if the message doesn't exist
4005 * @return String or false
4007 public function getDefaultMessageText() {
4010 if ( $this->getNamespace() != NS_MEDIAWIKI
) { // Just in case
4014 list( $name, $lang ) = MessageCache
::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4015 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4017 if ( $message->exists() ) {
4018 return $message->plain();
4025 * Is this in a namespace that allows actual pages?
4028 * @internal note -- uses hardcoded namespace index instead of constants
4030 public function canExist() {
4031 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
4035 * Update page_touched timestamps and send squid purge messages for
4036 * pages linking to this title. May be sent to the job queue depending
4037 * on the number of links. Typically called on create and delete.
4039 public function touchLinks() {
4040 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4043 if ( $this->getNamespace() == NS_CATEGORY
) {
4044 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4050 * Get the last touched timestamp
4052 * @param $db DatabaseBase: optional db
4053 * @return String last-touched timestamp
4055 public function getTouched( $db = null ) {
4056 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
4057 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
4062 * Get the timestamp when this page was updated since the user last saw it.
4065 * @return String|Null
4067 public function getNotificationTimestamp( $user = null ) {
4068 global $wgUser, $wgShowUpdatedMarker;
4069 // Assume current user if none given
4073 // Check cache first
4074 $uid = $user->getId();
4075 // avoid isset here, as it'll return false for null entries
4076 if ( array_key_exists( $uid, $this->mNotificationTimestamp
) ) {
4077 return $this->mNotificationTimestamp
[$uid];
4079 if ( !$uid ||
!$wgShowUpdatedMarker ) {
4080 return $this->mNotificationTimestamp
[$uid] = false;
4082 // Don't cache too much!
4083 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
4084 $this->mNotificationTimestamp
= array();
4086 $dbr = wfGetDB( DB_SLAVE
);
4087 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
4088 'wl_notificationtimestamp',
4089 array( 'wl_namespace' => $this->getNamespace(),
4090 'wl_title' => $this->getDBkey(),
4091 'wl_user' => $user->getId()
4095 return $this->mNotificationTimestamp
[$uid];
4099 * Get the trackback URL for this page
4101 * @return String Trackback URL
4103 public function trackbackURL() {
4104 global $wgScriptPath, $wgServer, $wgScriptExtension;
4106 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
4107 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
4111 * Get the trackback RDF for this page
4113 * @return String Trackback RDF
4115 public function trackbackRDF() {
4116 $url = htmlspecialchars( $this->getFullURL() );
4117 $title = htmlspecialchars( $this->getText() );
4118 $tburl = $this->trackbackURL();
4120 // Autodiscovery RDF is placed in comments so HTML validator
4121 // won't barf. This is a rather icky workaround, but seems
4122 // frequently used by this kind of RDF thingy.
4124 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
4126 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
4127 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
4128 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
4131 dc:identifier=\"$url\"
4133 trackback:ping=\"$tburl\" />
4139 * Generate strings used for xml 'id' names in monobook tabs
4141 * @param $prepend string defaults to 'nstab-'
4142 * @return String XML 'id' name
4144 public function getNamespaceKey( $prepend = 'nstab-' ) {
4146 // Gets the subject namespace if this title
4147 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
4148 // Checks if cononical namespace name exists for namespace
4149 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
4150 // Uses canonical namespace name
4151 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
4153 // Uses text of namespace
4154 $namespaceKey = $this->getSubjectNsText();
4156 // Makes namespace key lowercase
4157 $namespaceKey = $wgContLang->lc( $namespaceKey );
4159 if ( $namespaceKey == '' ) {
4160 $namespaceKey = 'main';
4162 // Changes file to image for backwards compatibility
4163 if ( $namespaceKey == 'file' ) {
4164 $namespaceKey = 'image';
4166 return $prepend . $namespaceKey;
4170 * Returns true if this is a special page.
4174 public function isSpecialPage() {
4175 return $this->getNamespace() == NS_SPECIAL
;
4179 * Returns true if this title resolves to the named special page
4181 * @param $name String The special page name
4184 public function isSpecial( $name ) {
4185 if ( $this->isSpecialPage() ) {
4186 list( $thisName, /* $subpage */ ) = SpecialPageFactory
::resolveAlias( $this->getDBkey() );
4187 if ( $name == $thisName ) {
4195 * If the Title refers to a special page alias which is not the local default, resolve
4196 * the alias, and localise the name as necessary. Otherwise, return $this
4200 public function fixSpecialName() {
4201 if ( $this->isSpecialPage() ) {
4202 list( $canonicalName, $par ) = SpecialPageFactory
::resolveAlias( $this->mDbkeyform
);
4203 if ( $canonicalName ) {
4204 $localName = SpecialPageFactory
::getLocalNameFor( $canonicalName, $par );
4205 if ( $localName != $this->mDbkeyform
) {
4206 return Title
::makeTitle( NS_SPECIAL
, $localName );
4214 * Is this Title in a namespace which contains content?
4215 * In other words, is this a content page, for the purposes of calculating
4220 public function isContentPage() {
4221 return MWNamespace
::isContent( $this->getNamespace() );
4225 * Get all extant redirects to this Title
4227 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4228 * @return Array of Title redirects to this title
4230 public function getRedirectsHere( $ns = null ) {
4233 $dbr = wfGetDB( DB_SLAVE
);
4235 'rd_namespace' => $this->getNamespace(),
4236 'rd_title' => $this->getDBkey(),
4239 if ( !is_null( $ns ) ) {
4240 $where['page_namespace'] = $ns;
4243 $res = $dbr->select(
4244 array( 'redirect', 'page' ),
4245 array( 'page_namespace', 'page_title' ),
4250 foreach ( $res as $row ) {
4251 $redirs[] = self
::newFromRow( $row );
4257 * Check if this Title is a valid redirect target
4261 public function isValidRedirectTarget() {
4262 global $wgInvalidRedirectTargets;
4264 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4265 if ( $this->isSpecial( 'Userlogout' ) ) {
4269 foreach ( $wgInvalidRedirectTargets as $target ) {
4270 if ( $this->isSpecial( $target ) ) {
4279 * Get a backlink cache object
4281 * @return object BacklinkCache
4283 function getBacklinkCache() {
4284 if ( is_null( $this->mBacklinkCache
) ) {
4285 $this->mBacklinkCache
= new BacklinkCache( $this );
4287 return $this->mBacklinkCache
;
4291 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4295 public function canUseNoindex() {
4296 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4298 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4299 ?
$wgContentNamespaces
4300 : $wgExemptFromUserRobotsControl;
4302 return !in_array( $this->mNamespace
, $bannedNamespaces );
4307 * Returns restriction types for the current Title
4309 * @return array applicable restriction types
4311 public function getRestrictionTypes() {
4312 if ( $this->isSpecialPage() ) {
4316 $types = self
::getFilteredRestrictionTypes( $this->exists() );
4318 if ( $this->getNamespace() != NS_FILE
) {
4319 # Remove the upload restriction for non-file titles
4320 $types = array_diff( $types, array( 'upload' ) );
4323 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4325 wfDebug( __METHOD__
. ': applicable restriction types for ' .
4326 $this->getPrefixedText() . ' are ' . implode( ',', $types ) . "\n" );
4331 * Get a filtered list of all restriction types supported by this wiki.
4332 * @param bool $exists True to get all restriction types that apply to
4333 * titles that do exist, False for all restriction types that apply to
4334 * titles that do not exist
4337 public static function getFilteredRestrictionTypes( $exists = true ) {
4338 global $wgRestrictionTypes;
4339 $types = $wgRestrictionTypes;
4341 # Remove the create restriction for existing titles
4342 $types = array_diff( $types, array( 'create' ) );
4344 # Only the create and upload restrictions apply to non-existing titles
4345 $types = array_intersect( $types, array( 'create', 'upload' ) );
4351 * Returns the raw sort key to be used for categories, with the specified
4352 * prefix. This will be fed to Collation::getSortKey() to get a
4353 * binary sortkey that can be used for actual sorting.
4355 * @param $prefix string The prefix to be used, specified using
4356 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4360 public function getCategorySortkey( $prefix = '' ) {
4361 $unprefixed = $this->getText();
4363 // Anything that uses this hook should only depend
4364 // on the Title object passed in, and should probably
4365 // tell the users to run updateCollations.php --force
4366 // in order to re-sort existing category relations.
4367 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4368 if ( $prefix !== '' ) {
4369 # Separate with a line feed, so the unprefixed part is only used as
4370 # a tiebreaker when two pages have the exact same prefix.
4371 # In UCA, tab is the only character that can sort above LF
4372 # so we strip both of them from the original prefix.
4373 $prefix = strtr( $prefix, "\n\t", ' ' );
4374 return "$prefix\n$unprefixed";
4380 * Get the language in which the content of this page is written.
4381 * Defaults to $wgContLang, but in certain cases it can be e.g.
4382 * $wgLang (such as special pages, which are in the user language).
4385 * @return object Language
4387 public function getPageLanguage() {
4389 if ( $this->isSpecialPage() ) {
4390 // special pages are in the user language
4392 } elseif ( $this->isCssOrJsPage() ) {
4393 // css/js should always be LTR and is, in fact, English
4394 return wfGetLangObj( 'en' );
4395 } elseif ( $this->getNamespace() == NS_MEDIAWIKI
) {
4396 // Parse mediawiki messages with correct target language
4397 list( /* $unused */, $lang ) = MessageCache
::singleton()->figureMessage( $this->getText() );
4398 return wfGetLangObj( $lang );
4401 // If nothing special, it should be in the wiki content language
4402 $pageLang = $wgContLang;
4403 // Hook at the end because we don't want to override the above stuff
4404 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4405 return wfGetLangObj( $pageLang );