7 if ( !class_exists( 'UtfNormal' ) ) {
8 require_once( dirname(__FILE__
) . '/normal/UtfNormal.php' );
11 define ( 'GAID_FOR_UPDATE', 1 );
15 * Constants for pr_cascade bitfield
17 define( 'CASCADE', 1 );
20 * Represents a title within MediaWiki.
21 * Optionally may contain an interwiki designation or namespace.
22 * @note This class can fetch various kinds of data from the database;
23 * however, it does so inefficiently.
26 /** @name Static cache variables */
28 static private $titleCache=array();
29 static private $interwikiCache=array();
33 * Title::newFromText maintains a cache to avoid expensive re-normalization of
34 * commonly used titles. On a batch operation this can become a memory leak
35 * if not bounded. After hitting this many titles reset the cache.
37 const CACHE_MAX
= 1000;
41 * @name Private member variables
42 * Please use the accessor functions instead.
47 var $mTextform = ''; ///< Text form (spaces not underscores) of the main part
48 var $mUrlform = ''; ///< URL-encoded form of the main part
49 var $mDbkeyform = ''; ///< Main part with underscores
50 var $mUserCaseDBKey; ///< DB key with the initial letter in the case specified by the user
51 var $mNamespace = NS_MAIN
; ///< Namespace index, i.e. one of the NS_xxxx constants
52 var $mInterwiki = ''; ///< Interwiki prefix (or null string)
53 var $mFragment; ///< Title fragment (i.e. the bit after the #)
54 var $mArticleID = -1; ///< Article ID, fetched from the link cache on demand
55 var $mLatestID = false; ///< ID of most recent revision
56 var $mRestrictions = array(); ///< Array of groups allowed to edit this article
57 var $mOldRestrictions = false;
58 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
59 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
60 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
61 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
62 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
63 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
64 # Don't change the following default, NS_MAIN is hardcoded in several
65 # places. See bug 696.
66 var $mDefaultNamespace = NS_MAIN
; ///< Namespace index when there is no namespace
67 # Zero except in {{transclusion}} tags
68 var $mWatched = null; ///< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
69 var $mLength = -1; ///< The page length, 0 for special pages
70 var $mRedirect = null; ///< Is the article at this title a redirect?
78 /* private */ function __construct() {}
81 * Create a new Title from a prefixed DB key
82 * @param $key \type{\string} The database key, which has underscores
83 * instead of spaces, possibly including namespace and
85 * @return \type{Title} the new object, or NULL on an error
87 public static function newFromDBkey( $key ) {
89 $t->mDbkeyform
= $key;
90 if( $t->secureAndSplit() )
97 * Create a new Title from text, such as what one would find in a link. De-
98 * codes any HTML entities in the text.
100 * @param $text string The link text; spaces, prefixes, and an
101 * initial ':' indicating the main namespace are accepted.
102 * @param $defaultNamespace int The namespace to use if none is speci-
104 * @return Title The new object, or null on an error.
106 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
107 if( is_object( $text ) ) {
108 throw new MWException( 'Title::newFromText given an object' );
112 * Wiki pages often contain multiple links to the same page.
113 * Title normalization and parsing can become expensive on
114 * pages with many links, so we can save a little time by
117 * In theory these are value objects and won't get changed...
119 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
120 return Title
::$titleCache[$text];
124 * Convert things like é ā or 〗 into real text...
126 $filteredText = Sanitizer
::decodeCharReferences( $text );
129 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
130 $t->mDefaultNamespace
= $defaultNamespace;
132 static $cachedcount = 0 ;
133 if( $t->secureAndSplit() ) {
134 if( $defaultNamespace == NS_MAIN
) {
135 if( $cachedcount >= self
::CACHE_MAX
) {
136 # Avoid memory leaks on mass operations...
137 Title
::$titleCache = array();
141 Title
::$titleCache[$text] =& $t;
151 * Create a new Title from URL-encoded text. Ensures that
152 * the given title's length does not exceed the maximum.
153 * @param $url \type{\string} the title, as might be taken from a URL
154 * @return \type{Title} the new object, or NULL on an error
156 public static function newFromURL( $url ) {
157 global $wgLegalTitleChars;
160 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
161 # but some URLs used it as a space replacement and they still come
162 # from some external search tools.
163 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
164 $url = str_replace( '+', ' ', $url );
167 $t->mDbkeyform
= str_replace( ' ', '_', $url );
168 if( $t->secureAndSplit() ) {
176 * Create a new Title from an article ID
178 * @todo This is inefficiently implemented, the page row is requested
179 * but not used for anything else
181 * @param $id \type{\int} the page_id corresponding to the Title to create
182 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
183 * @return \type{Title} the new object, or NULL on an error
185 public static function newFromID( $id, $flags = 0 ) {
186 $fname = 'Title::newFromID';
187 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
188 $row = $db->selectRow( 'page', array( 'page_namespace', 'page_title' ),
189 array( 'page_id' => $id ), $fname );
190 if ( $row !== false ) {
191 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
199 * Make an array of titles from an array of IDs
200 * @param $ids \type{\arrayof{\int}} Array of IDs
201 * @return \type{\arrayof{Title}} Array of Titles
203 public static function newFromIDs( $ids ) {
204 if ( !count( $ids ) ) {
207 $dbr = wfGetDB( DB_SLAVE
);
208 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
209 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
212 foreach( $res as $row ) {
213 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
219 * Make a Title object from a DB row
220 * @param $row \type{Row} (needs at least page_title,page_namespace)
221 * @return \type{Title} corresponding Title
223 public static function newFromRow( $row ) {
224 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
226 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
227 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
228 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: NULL;
229 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
235 * Create a new Title from a namespace index and a DB key.
236 * It's assumed that $ns and $title are *valid*, for instance when
237 * they came directly from the database or a special page name.
238 * For convenience, spaces are converted to underscores so that
239 * eg user_text fields can be used directly.
241 * @param $ns \type{\int} the namespace of the article
242 * @param $title \type{\string} the unprefixed database key form
243 * @param $fragment \type{\string} The link fragment (after the "#")
244 * @return \type{Title} the new object
246 public static function &makeTitle( $ns, $title, $fragment = '' ) {
249 $t->mFragment
= $fragment;
250 $t->mNamespace
= $ns = intval( $ns );
251 $t->mDbkeyform
= str_replace( ' ', '_', $title );
252 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
253 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
254 $t->mTextform
= str_replace( '_', ' ', $title );
259 * Create a new Title from a namespace index and a DB key.
260 * The parameters will be checked for validity, which is a bit slower
261 * than makeTitle() but safer for user-provided data.
263 * @param $ns \type{\int} the namespace of the article
264 * @param $title \type{\string} the database key form
265 * @param $fragment \type{\string} The link fragment (after the "#")
266 * @return \type{Title} the new object, or NULL on an error
268 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
270 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
271 if( $t->secureAndSplit() ) {
279 * Create a new Title for the Main Page
280 * @return \type{Title} the new object
282 public static function newMainPage() {
283 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
284 // Don't give fatal errors if the message is broken
286 $title = Title
::newFromText( 'Main Page' );
292 * Extract a redirect destination from a string and return the
293 * Title, or null if the text doesn't contain a valid redirect
295 * @param $text \type{String} Text with possible redirect
296 * @return \type{Title} The corresponding Title
298 public static function newFromRedirect( $text ) {
299 $redir = MagicWord
::get( 'redirect' );
301 if( $redir->matchStartAndRemove( $text ) ) {
302 // Extract the first link and see if it's usable
303 // Ensure that it really does come directly after #REDIRECT
304 // Some older redirects included a colon, so don't freak about that!
306 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
307 // Strip preceding colon used to "escape" categories, etc.
308 // and URL-decode links
309 if( strpos( $m[1], '%' ) !== false ) {
310 // Match behavior of inline link parsing here;
311 // don't interpret + as " " most of the time!
312 // It might be safe to just use rawurldecode instead, though.
313 $m[1] = urldecode( ltrim( $m[1], ':' ) );
315 $title = Title
::newFromText( $m[1] );
316 // Redirects to Special:Userlogout are not permitted
317 if( $title instanceof Title
&& !$title->isSpecial( 'Userlogout' ) )
324 #----------------------------------------------------------------------------
326 #----------------------------------------------------------------------------
329 * Get the prefixed DB key associated with an ID
330 * @param $id \type{\int} the page_id of the article
331 * @return \type{Title} an object representing the article, or NULL
332 * if no such article was found
334 public static function nameOf( $id ) {
335 $dbr = wfGetDB( DB_SLAVE
);
337 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), __METHOD__
);
338 if ( $s === false ) { return NULL; }
340 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
345 * Get a regex character class describing the legal characters in a link
346 * @return \type{\string} the list of characters, not delimited
348 public static function legalChars() {
349 global $wgLegalTitleChars;
350 return $wgLegalTitleChars;
354 * Get a string representation of a title suitable for
355 * including in a search index
357 * @param $ns \type{\int} a namespace index
358 * @param $title \type{\string} text-form main part
359 * @return \type{\string} a stripped-down title string ready for the
362 public static function indexTitle( $ns, $title ) {
365 $lc = SearchEngine
::legalSearchChars() . '&#;';
366 $t = $wgContLang->stripForSearch( $title );
367 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
368 $t = $wgContLang->lc( $t );
371 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
372 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
374 $t = preg_replace( "/\\s+/", ' ', $t );
376 if ( $ns == NS_IMAGE
) {
377 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
383 * Make a prefixed DB key from a DB key and a namespace index
384 * @param $ns \type{\int} numerical representation of the namespace
385 * @param $title \type{\string} the DB key form the title
386 * @param $fragment \type{\string} The link fragment (after the "#")
387 * @return \type{\string} the prefixed form of the title
389 public static function makeName( $ns, $title, $fragment = '' ) {
392 $namespace = $wgContLang->getNsText( $ns );
393 $name = $namespace == '' ?
$title : "$namespace:$title";
394 if ( strval( $fragment ) != '' ) {
395 $name .= '#' . $fragment;
401 * Returns the URL associated with an interwiki prefix
402 * @param $key \type{\string} the interwiki prefix (e.g. "MeatBall")
403 * @return \type{\string} the associated URL, containing "$1",
404 * which should be replaced by an article title
406 * @deprecated See Interwiki class
408 public function getInterwikiLink( $key ) {
409 return Interwiki
::fetch( $key )->getURL( );
413 * Determine whether the object refers to a page within
416 * @return \type{\bool} TRUE if this is an in-project interwiki link
417 * or a wikilink, FALSE otherwise
419 public function isLocal() {
420 if ( $this->mInterwiki
!= '' ) {
421 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
428 * Determine whether the object refers to a page within
429 * this project and is transcludable.
431 * @return \type{\bool} TRUE if this is transcludable
433 public function isTrans() {
434 if ($this->mInterwiki
== '')
437 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
441 * Escape a text fragment, say from a link, for a URL
443 static function escapeFragmentForURL( $fragment ) {
444 $fragment = str_replace( ' ', '_', $fragment );
445 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
446 $replaceArray = array(
450 return strtr( $fragment, $replaceArray );
453 #----------------------------------------------------------------------------
455 #----------------------------------------------------------------------------
457 /** Simple accessors */
459 * Get the text form (spaces not underscores) of the main part
460 * @return \type{\string} Main part of the title
462 public function getText() { return $this->mTextform
; }
464 * Get the URL-encoded form of the main part
465 * @return \type{\string} Main part of the title, URL-encoded
467 public function getPartialURL() { return $this->mUrlform
; }
469 * Get the main part with underscores
470 * @return \type{\string} Main part of the title, with underscores
472 public function getDBkey() { return $this->mDbkeyform
; }
474 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
475 * @return \type{\int} Namespace index
477 public function getNamespace() { return $this->mNamespace
; }
479 * Get the namespace text
480 * @return \type{\string} Namespace text
482 public function getNsText() {
483 global $wgContLang, $wgCanonicalNamespaceNames;
485 if ( '' != $this->mInterwiki
) {
486 // This probably shouldn't even happen. ohh man, oh yuck.
487 // But for interwiki transclusion it sometimes does.
488 // Shit. Shit shit shit.
490 // Use the canonical namespaces if possible to try to
491 // resolve a foreign namespace.
492 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
493 return $wgCanonicalNamespaceNames[$this->mNamespace
];
496 return $wgContLang->getNsText( $this->mNamespace
);
499 * Get the DB key with the initial letter case as specified by the user
500 * @return \type{\string} DB key
502 function getUserCaseDBKey() {
503 return $this->mUserCaseDBKey
;
506 * Get the namespace text of the subject (rather than talk) page
507 * @return \type{\string} Namespace text
509 public function getSubjectNsText() {
511 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
514 * Get the namespace text of the talk page
515 * @return \type{\string} Namespace text
517 public function getTalkNsText() {
519 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
522 * Could this title have a corresponding talk page?
523 * @return \type{\bool} TRUE or FALSE
525 public function canTalk() {
526 return( MWNamespace
::canTalk( $this->mNamespace
) );
529 * Get the interwiki prefix (or null string)
530 * @return \type{\string} Interwiki prefix
532 public function getInterwiki() { return $this->mInterwiki
; }
534 * Get the Title fragment (i.e.\ the bit after the #) in text form
535 * @return \type{\string} Title fragment
537 public function getFragment() { return $this->mFragment
; }
539 * Get the fragment in URL form, including the "#" character if there is one
540 * @return \type{\string} Fragment in URL form
542 public function getFragmentForURL() {
543 if ( $this->mFragment
== '' ) {
546 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
550 * Get the default namespace index, for when there is no namespace
551 * @return \type{\int} Default namespace index
553 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
556 * Get title for search index
557 * @return \type{\string} a stripped-down title string ready for the
560 public function getIndexTitle() {
561 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
565 * Get the prefixed database key form
566 * @return \type{\string} the prefixed title, with underscores and
567 * any interwiki and namespace prefixes
569 public function getPrefixedDBkey() {
570 $s = $this->prefix( $this->mDbkeyform
);
571 $s = str_replace( ' ', '_', $s );
576 * Get the prefixed title with spaces.
577 * This is the form usually used for display
578 * @return \type{\string} the prefixed title, with spaces
580 public function getPrefixedText() {
581 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
582 $s = $this->prefix( $this->mTextform
);
583 $s = str_replace( '_', ' ', $s );
584 $this->mPrefixedText
= $s;
586 return $this->mPrefixedText
;
590 * Get the prefixed title with spaces, plus any fragment
591 * (part beginning with '#')
592 * @return \type{\string} the prefixed title, with spaces and
593 * the fragment, including '#'
595 public function getFullText() {
596 $text = $this->getPrefixedText();
597 if( '' != $this->mFragment
) {
598 $text .= '#' . $this->mFragment
;
604 * Get the base name, i.e. the leftmost parts before the /
605 * @return \type{\string} Base name
607 public function getBaseText() {
608 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
609 return $this->getText();
612 $parts = explode( '/', $this->getText() );
613 # Don't discard the real title if there's no subpage involved
614 if( count( $parts ) > 1 )
615 unset( $parts[ count( $parts ) - 1 ] );
616 return implode( '/', $parts );
620 * Get the lowest-level subpage name, i.e. the rightmost part after /
621 * @return \type{\string} Subpage name
623 public function getSubpageText() {
624 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
625 return( $this->mTextform
);
627 $parts = explode( '/', $this->mTextform
);
628 return( $parts[ count( $parts ) - 1 ] );
632 * Get a URL-encoded form of the subpage text
633 * @return \type{\string} URL-encoded subpage name
635 public function getSubpageUrlForm() {
636 $text = $this->getSubpageText();
637 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
638 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
643 * Get a URL-encoded title (not an actual URL) including interwiki
644 * @return \type{\string} the URL-encoded form
646 public function getPrefixedURL() {
647 $s = $this->prefix( $this->mDbkeyform
);
648 $s = str_replace( ' ', '_', $s );
650 $s = wfUrlencode ( $s ) ;
652 # Cleaning up URL to make it look nice -- is this safe?
653 $s = str_replace( '%28', '(', $s );
654 $s = str_replace( '%29', ')', $s );
660 * Get a real URL referring to this title, with interwiki link and
663 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
664 * links. Can be specified as an associative array as well, e.g.,
665 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
666 * @param $variant \type{\string} language variant of url (for sr, zh..)
667 * @return \type{\string} the URL
669 public function getFullURL( $query = '', $variant = false ) {
670 global $wgContLang, $wgServer, $wgRequest;
672 if( is_array( $query ) ) {
673 $query = wfArrayToCGI( $query );
676 if ( '' == $this->mInterwiki
) {
677 $url = $this->getLocalUrl( $query, $variant );
679 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
680 // Correct fix would be to move the prepending elsewhere.
681 if ($wgRequest->getVal('action') != 'render') {
682 $url = $wgServer . $url;
685 $baseUrl = Interwiki
::fetch( $this->mInterwiki
)->getURL( );
687 $namespace = wfUrlencode( $this->getNsText() );
688 if ( '' != $namespace ) {
689 # Can this actually happen? Interwikis shouldn't be parsed.
690 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
693 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
694 $url = wfAppendQuery( $url, $query );
697 # Finally, add the fragment.
698 $url .= $this->getFragmentForURL();
700 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
705 * Get a URL with no fragment or server name. If this page is generated
706 * with action=render, $wgServer is prepended.
707 * @param mixed $query an optional query string; if not specified,
708 * $wgArticlePath will be used. Can be specified as an associative array
709 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
711 * @param $variant \type{\string} language variant of url (for sr, zh..)
712 * @return \type{\string} the URL
714 public function getLocalURL( $query = '', $variant = false ) {
715 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
716 global $wgVariantArticlePath, $wgContLang, $wgUser;
718 if( is_array( $query ) ) {
719 $query = wfArrayToCGI( $query );
722 // internal links should point to same variant as current page (only anonymous users)
723 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
724 $pref = $wgContLang->getPreferredVariant(false);
725 if($pref != $wgContLang->getCode())
729 if ( $this->isExternal() ) {
730 $url = $this->getFullURL();
732 // This is currently only used for edit section links in the
733 // context of interwiki transclusion. In theory we should
734 // append the query to the end of any existing query string,
735 // but interwiki transclusion is already broken in that case.
739 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
740 if ( $query == '' ) {
741 if( $variant != false && $wgContLang->hasVariants() ) {
742 if( $wgVariantArticlePath == false ) {
743 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
745 $variantArticlePath = $wgVariantArticlePath;
747 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
748 $url = str_replace( '$1', $dbkey, $url );
750 $url = str_replace( '$1', $dbkey, $wgArticlePath );
753 global $wgActionPaths;
756 if( !empty( $wgActionPaths ) &&
757 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
759 $action = urldecode( $matches[2] );
760 if( isset( $wgActionPaths[$action] ) ) {
761 $query = $matches[1];
762 if( isset( $matches[4] ) ) $query .= $matches[4];
763 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
764 if( $query != '' ) $url .= '?' . $query;
767 if ( $url === false ) {
768 if ( $query == '-' ) {
771 $url = "{$wgScript}?title={$dbkey}&{$query}";
775 // FIXME: this causes breakage in various places when we
776 // actually expected a local URL and end up with dupe prefixes.
777 if ($wgRequest->getVal('action') == 'render') {
778 $url = $wgServer . $url;
781 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
786 * Get a URL that's the simplest URL that will be valid to link, locally,
787 * to the current Title. It includes the fragment, but does not include
788 * the server unless action=render is used (or the link is external). If
789 * there's a fragment but the prefixed text is empty, we just return a link
792 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
793 * query string. Keys and values will be escaped.
794 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
795 * for external links. Default is "false" (same variant as current page,
796 * for anonymous users).
797 * @return \type{\string} the URL
799 public function getLinkUrl( $query = array(), $variant = false ) {
800 if( !is_array( $query ) ) {
801 throw new MWException( 'Title::getLinkUrl passed a non-array for '.
804 if( $this->isExternal() ) {
805 return $this->getFullURL( $query );
806 } elseif( $this->getPrefixedText() === ''
807 and $this->getFragment() !== '' ) {
808 return $this->getFragmentForURL();
810 return $this->getLocalURL( $query, $variant )
811 . $this->getFragmentForURL();
816 * Get an HTML-escaped version of the URL form, suitable for
817 * using in a link, without a server name or fragment
818 * @param $query \type{\string} an optional query string
819 * @return \type{\string} the URL
821 public function escapeLocalURL( $query = '' ) {
822 return htmlspecialchars( $this->getLocalURL( $query ) );
826 * Get an HTML-escaped version of the URL form, suitable for
827 * using in a link, including the server name and fragment
829 * @param $query \type{\string} an optional query string
830 * @return \type{\string} the URL
832 public function escapeFullURL( $query = '' ) {
833 return htmlspecialchars( $this->getFullURL( $query ) );
837 * Get the URL form for an internal link.
838 * - Used in various Squid-related code, in case we have a different
839 * internal hostname for the server from the exposed one.
841 * @param $query \type{\string} an optional query string
842 * @param $variant \type{\string} language variant of url (for sr, zh..)
843 * @return \type{\string} the URL
845 public function getInternalURL( $query = '', $variant = false ) {
846 global $wgInternalServer;
847 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
848 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
853 * Get the edit URL for this Title
854 * @return \type{\string} the URL, or a null string if this is an
857 public function getEditURL() {
858 if ( '' != $this->mInterwiki
) { return ''; }
859 $s = $this->getLocalURL( 'action=edit' );
865 * Get the HTML-escaped displayable text form.
866 * Used for the title field in <a> tags.
867 * @return \type{\string} the text, including any prefixes
869 public function getEscapedText() {
870 return htmlspecialchars( $this->getPrefixedText() );
874 * Is this Title interwiki?
875 * @return \type{\bool}
877 public function isExternal() { return ( '' != $this->mInterwiki
); }
880 * Is this page "semi-protected" - the *only* protection is autoconfirm?
882 * @param @action \type{\string} Action to check (default: edit)
883 * @return \type{\bool}
885 public function isSemiProtected( $action = 'edit' ) {
886 if( $this->exists() ) {
887 $restrictions = $this->getRestrictions( $action );
888 if( count( $restrictions ) > 0 ) {
889 foreach( $restrictions as $restriction ) {
890 if( strtolower( $restriction ) != 'autoconfirmed' )
899 # If it doesn't exist, it can't be protected
905 * Does the title correspond to a protected article?
906 * @param $what \type{\string} the action the page is protected from,
907 * by default checks move and edit
908 * @return \type{\bool}
910 public function isProtected( $action = '' ) {
911 global $wgRestrictionLevels, $wgRestrictionTypes;
913 # Special pages have inherent protection
914 if( $this->getNamespace() == NS_SPECIAL
)
917 # Check regular protection levels
918 foreach( $wgRestrictionTypes as $type ){
919 if( $action == $type ||
$action == '' ) {
920 $r = $this->getRestrictions( $type );
921 foreach( $wgRestrictionLevels as $level ) {
922 if( in_array( $level, $r ) && $level != '' ) {
933 * Is $wgUser watching this page?
934 * @return \type{\bool}
936 public function userIsWatching() {
939 if ( is_null( $this->mWatched
) ) {
940 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
941 $this->mWatched
= false;
943 $this->mWatched
= $wgUser->isWatched( $this );
946 return $this->mWatched
;
950 * Can $wgUser perform $action on this page?
951 * This skips potentially expensive cascading permission checks.
953 * Suitable for use for nonessential UI controls in common cases, but
954 * _not_ for functional access control.
956 * May provide false positives, but should never provide a false negative.
958 * @param $action \type{\string} action that permission needs to be checked for
959 * @return \type{\bool}
961 public function quickUserCan( $action ) {
962 return $this->userCan( $action, false );
966 * Determines if $wgUser is unable to edit this page because it has been protected
967 * by $wgNamespaceProtection.
969 * @return \type{\bool}
971 public function isNamespaceProtected() {
972 global $wgNamespaceProtection, $wgUser;
973 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
974 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
975 if( $right != '' && !$wgUser->isAllowed( $right ) )
983 * Can $wgUser perform $action on this page?
984 * @param $action \type{\string} action that permission needs to be checked for
985 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
986 * @return \type{\bool}
988 public function userCan( $action, $doExpensiveQueries = true ) {
990 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
994 * Can $user perform $action on this page?
996 * FIXME: This *does not* check throttles (User::pingLimiter()).
998 * @param $action \type{\string}action that permission needs to be checked for
999 * @param $user \type{User} user to check
1000 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1001 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1002 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1004 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1005 if( !StubObject
::isRealObject( $user ) ) {
1006 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1008 $wgUser->_unstub( '', 5 );
1011 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1015 global $wgEmailConfirmToEdit;
1017 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1018 $errors[] = array( 'confirmedittext' );
1021 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1022 if ( $user->isBlockedFrom( $this ) && $action != 'read' && $action != 'createaccount' ) {
1023 $block = $user->mBlock
;
1025 // This is from OutputPage::blockedPage
1026 // Copied at r23888 by werdna
1028 $id = $user->blockedBy();
1029 $reason = $user->blockedFor();
1030 if( $reason == '' ) {
1031 $reason = wfMsg( 'blockednoreason' );
1035 if ( is_numeric( $id ) ) {
1036 $name = User
::whoIs( $id );
1041 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1042 $blockid = $block->mId
;
1043 $blockExpiry = $user->mBlock
->mExpiry
;
1044 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1046 if ( $blockExpiry == 'infinity' ) {
1047 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1048 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1050 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1051 if ( strpos( $option, ':' ) == false )
1054 list ($show, $value) = explode( ":", $option );
1056 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1057 $blockExpiry = $show;
1062 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1065 $intended = $user->mBlock
->mAddress
;
1067 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1068 $blockid, $blockExpiry, $intended, $blockTimestamp );
1071 // Remove the errors being ignored.
1073 foreach( $errors as $index => $error ) {
1074 $error_key = is_array($error) ?
$error[0] : $error;
1076 if (in_array( $error_key, $ignoreErrors )) {
1077 unset($errors[$index]);
1085 * Can $user perform $action on this page? This is an internal function,
1086 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1087 * checks on wfReadOnly() and blocks)
1089 * @param $action \type{\string} action that permission needs to be checked for
1090 * @param $user \type{User} user to check
1091 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1092 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1094 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1095 wfProfileIn( __METHOD__
);
1099 // Use getUserPermissionsErrors instead
1100 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1101 wfProfileOut( __METHOD__
);
1102 return $result ?
array() : array( array( 'badaccess-group0' ) );
1105 if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1106 if ($result != array() && is_array($result) && !is_array($result[0]))
1107 $errors[] = $result; # A single array representing an error
1108 else if (is_array($result) && is_array($result[0]))
1109 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1110 else if ($result != '' && $result != null && $result !== true && $result !== false)
1111 $errors[] = array($result); # A string representing a message-id
1112 else if ($result === false )
1113 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1115 if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1116 if ($result != array() && is_array($result) && !is_array($result[0]))
1117 $errors[] = $result; # A single array representing an error
1118 else if (is_array($result) && is_array($result[0]))
1119 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1120 else if ($result != '' && $result != null && $result !== true && $result !== false)
1121 $errors[] = array($result); # A string representing a message-id
1122 else if ($result === false )
1123 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1126 $specialOKActions = array( 'createaccount', 'execute' );
1127 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1128 $errors[] = array('ns-specialprotected');
1131 if ( $this->isNamespaceProtected() ) {
1132 $ns = $this->getNamespace() == NS_MAIN
1133 ?
wfMsg( 'nstab-main' )
1134 : $this->getNsText();
1135 $errors[] = (NS_MEDIAWIKI
== $this->mNamespace
1136 ?
array('protectedinterface')
1137 : array( 'namespaceprotected', $ns ) );
1140 if( $this->mDbkeyform
== '_' ) {
1141 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1142 $errors[] = array('badaccess-group0');
1145 # protect css/js subpages of user pages
1146 # XXX: this might be better using restrictions
1147 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1148 if( $this->isCssJsSubpage()
1149 && !$user->isAllowed('editusercssjs')
1150 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) ) {
1151 $errors[] = array('customcssjsprotected');
1154 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1155 # We /could/ use the protection level on the source page, but it's fairly ugly
1156 # as we have to establish a precedence hierarchy for pages included by multiple
1157 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1158 # as they could remove the protection anyway.
1159 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1160 # Cascading protection depends on more than this page...
1161 # Several cascading protected pages may include this page...
1162 # Check each cascading level
1163 # This is only for protection restrictions, not for all actions
1164 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1165 foreach( $restrictions[$action] as $right ) {
1166 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1167 if( '' != $right && !$user->isAllowed( $right ) ) {
1169 foreach( $cascadingSources as $page )
1170 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1171 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1177 foreach( $this->getRestrictions($action) as $right ) {
1178 // Backwards compatibility, rewrite sysop -> protect
1179 if ( $right == 'sysop' ) {
1182 if( '' != $right && !$user->isAllowed( $right ) ) {
1183 //Users with 'editprotected' permission can edit protected pages
1184 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1185 //Users with 'editprotected' permission cannot edit protected pages
1186 //with cascading option turned on.
1187 if($this->mCascadeRestriction
) {
1188 $errors[] = array( 'protectedpagetext', $right );
1190 //Nothing, user can edit!
1193 $errors[] = array( 'protectedpagetext', $right );
1198 if ($action == 'protect') {
1199 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1200 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1204 if ($action == 'create') {
1205 $title_protection = $this->getTitleProtection();
1207 if (is_array($title_protection)) {
1208 extract($title_protection);
1210 if ($pt_create_perm == 'sysop')
1211 $pt_create_perm = 'protect';
1213 if ($pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm)) {
1214 $errors[] = array ( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1218 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1219 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1220 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1222 } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
1223 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1224 } elseif ( !$user->isAllowed( $action ) ) {
1226 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1227 User
::getGroupsWithPermission( $action ) );
1229 $return = array( 'badaccess-groups',
1231 implode( ', ', $groups ),
1232 count( $groups ) ) );
1235 $return = array( "badaccess-group0" );
1237 $errors[] = $return;
1240 wfProfileOut( __METHOD__
);
1245 * Is this title subject to title protection?
1246 * @return \type{\mixed} An associative array representing any existent title
1247 * protection, or false if there's none.
1249 private function getTitleProtection() {
1250 // Can't protect pages in special namespaces
1251 if ( $this->getNamespace() < 0 ) {
1255 $dbr = wfGetDB( DB_SLAVE
);
1256 $res = $dbr->select( 'protected_titles', '*',
1257 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1259 if ($row = $dbr->fetchRow( $res )) {
1267 * Update the title protection status
1268 * @param $create_perm \type{\string} Permission required for creation
1269 * @param $reason \type{\string} Reason for protection
1270 * @param $expiry \type{\string} Expiry timestamp
1272 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1273 global $wgUser,$wgContLang;
1275 if ($create_perm == implode(',',$this->getRestrictions('create'))
1276 && $expiry == $this->mRestrictionsExpiry
['create']) {
1281 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1283 $dbw = wfGetDB( DB_MASTER
);
1285 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1287 $expiry_description = '';
1288 if ( $encodedExpiry != 'infinity' ) {
1289 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1292 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1295 # Update protection table
1296 if ($create_perm != '' ) {
1297 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1298 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1299 , 'pt_create_perm' => $create_perm
1300 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1301 , 'pt_expiry' => $encodedExpiry
1302 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1304 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1305 'pt_title' => $title ), __METHOD__
);
1307 # Update the protection log
1308 $log = new LogPage( 'protect' );
1310 if( $create_perm ) {
1311 $params = array("[create=$create_perm] $expiry_description",'');
1312 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason ), $params );
1314 $log->addEntry( 'unprotect', $this, $reason );
1321 * Remove any title protection due to page existing
1323 public function deleteTitleProtection() {
1324 $dbw = wfGetDB( DB_MASTER
);
1326 $dbw->delete( 'protected_titles',
1327 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__
);
1331 * Can $wgUser edit this page?
1332 * @return \type{\bool} TRUE or FALSE
1333 * @deprecated use userCan('edit')
1335 public function userCanEdit( $doExpensiveQueries = true ) {
1336 return $this->userCan( 'edit', $doExpensiveQueries );
1340 * Can $wgUser create this page?
1341 * @return \type{\bool} TRUE or FALSE
1342 * @deprecated use userCan('create')
1344 public function userCanCreate( $doExpensiveQueries = true ) {
1345 return $this->userCan( 'create', $doExpensiveQueries );
1349 * Can $wgUser move this page?
1350 * @return \type{\bool} TRUE or FALSE
1351 * @deprecated use userCan('move')
1353 public function userCanMove( $doExpensiveQueries = true ) {
1354 return $this->userCan( 'move', $doExpensiveQueries );
1358 * Would anybody with sufficient privileges be able to move this page?
1359 * Some pages just aren't movable.
1361 * @return \type{\bool} TRUE or FALSE
1363 public function isMovable() {
1364 return MWNamespace
::isMovable( $this->getNamespace() )
1365 && $this->getInterwiki() == '';
1369 * Can $wgUser read this page?
1370 * @return \type{\bool} TRUE or FALSE
1371 * @todo fold these checks into userCan()
1373 public function userCanRead() {
1374 global $wgUser, $wgGroupPermissions;
1377 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1378 if ( $result !== null ) {
1382 # Shortcut for public wikis, allows skipping quite a bit of code
1383 if ($wgGroupPermissions['*']['read'])
1386 if( $wgUser->isAllowed( 'read' ) ) {
1389 global $wgWhitelistRead;
1392 * Always grant access to the login page.
1393 * Even anons need to be able to log in.
1395 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1400 * Bail out if there isn't whitelist
1402 if( !is_array($wgWhitelistRead) ) {
1407 * Check for explicit whitelisting
1409 $name = $this->getPrefixedText();
1410 $dbName = $this->getPrefixedDBKey();
1411 // Check with and without underscores
1412 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1416 * Old settings might have the title prefixed with
1417 * a colon for main-namespace pages
1419 if( $this->getNamespace() == NS_MAIN
) {
1420 if( in_array( ':' . $name, $wgWhitelistRead ) )
1425 * If it's a special page, ditch the subpage bit
1428 if( $this->getNamespace() == NS_SPECIAL
) {
1429 $name = $this->getDBkey();
1430 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1431 if ( $name === false ) {
1432 # Invalid special page, but we show standard login required message
1436 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1437 if( in_array( $pure, $wgWhitelistRead, true ) )
1446 * Is this a talk page of some sort?
1447 * @return \type{\bool} TRUE or FALSE
1449 public function isTalkPage() {
1450 return MWNamespace
::isTalk( $this->getNamespace() );
1454 * Is this a subpage?
1455 * @return \type{\bool} TRUE or FALSE
1457 public function isSubpage() {
1458 return MWNamespace
::hasSubpages( $this->mNamespace
)
1459 ?
strpos( $this->getText(), '/' ) !== false
1464 * Does this have subpages? (Warning, usually requires an extra DB query.)
1465 * @return \type{\bool} TRUE or FALSE
1467 public function hasSubpages() {
1468 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1473 # We dynamically add a member variable for the purpose of this method
1474 # alone to cache the result. There's no point in having it hanging
1475 # around uninitialized in every Title object; therefore we only add it
1476 # if needed and don't declare it statically.
1477 if( isset( $this->mHasSubpages
) ) {
1478 return $this->mHasSubpages
;
1481 $db = wfGetDB( DB_SLAVE
);
1482 return $this->mHasSubpages
= (bool)$db->selectField( 'page', '1',
1483 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1484 . $db->escapeLike( $this->mDbkeyform
) . "/%'",
1490 * Could this page contain custom CSS or JavaScript, based
1493 * @return \type{\bool} TRUE or FALSE
1495 public function isCssOrJsPage() {
1496 return $this->mNamespace
== NS_MEDIAWIKI
1497 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1501 * Is this a .css or .js subpage of a user page?
1502 * @return \type{\bool} TRUE or FALSE
1504 public function isCssJsSubpage() {
1505 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1508 * Is this a *valid* .css or .js subpage of a user page?
1509 * Check that the corresponding skin exists
1510 * @return \type{\bool} TRUE or FALSE
1512 public function isValidCssJsSubpage() {
1513 if ( $this->isCssJsSubpage() ) {
1514 $skinNames = Skin
::getSkinNames();
1515 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1521 * Trim down a .css or .js subpage title to get the corresponding skin name
1523 public function getSkinFromCssJsSubpage() {
1524 $subpage = explode( '/', $this->mTextform
);
1525 $subpage = $subpage[ count( $subpage ) - 1 ];
1526 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1529 * Is this a .css subpage of a user page?
1530 * @return \type{\bool} TRUE or FALSE
1532 public function isCssSubpage() {
1533 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1536 * Is this a .js subpage of a user page?
1537 * @return \type{\bool} TRUE or FALSE
1539 public function isJsSubpage() {
1540 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1543 * Protect css/js subpages of user pages: can $wgUser edit
1546 * @return \type{\bool} TRUE or FALSE
1547 * @todo XXX: this might be better using restrictions
1549 public function userCanEditCssJsSubpage() {
1551 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1555 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1557 * @return \type{\bool} If the page is subject to cascading restrictions.
1559 public function isCascadeProtected() {
1560 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1561 return ( $sources > 0 );
1565 * Cascading protection: Get the source of any cascading restrictions on this page.
1567 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1568 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1569 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1570 * The restriction array is an array of each type, each of which contains an array of unique groups.
1572 public function getCascadeProtectionSources( $get_pages = true ) {
1573 global $wgRestrictionTypes;
1575 # Define our dimension of restrictions types
1576 $pagerestrictions = array();
1577 foreach( $wgRestrictionTypes as $action )
1578 $pagerestrictions[$action] = array();
1580 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1581 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1582 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1583 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1586 wfProfileIn( __METHOD__
);
1588 $dbr = wfGetDb( DB_SLAVE
);
1590 if ( $this->getNamespace() == NS_IMAGE
) {
1591 $tables = array ('imagelinks', 'page_restrictions');
1592 $where_clauses = array(
1593 'il_to' => $this->getDBkey(),
1595 'pr_cascade' => 1 );
1597 $tables = array ('templatelinks', 'page_restrictions');
1598 $where_clauses = array(
1599 'tl_namespace' => $this->getNamespace(),
1600 'tl_title' => $this->getDBkey(),
1602 'pr_cascade' => 1 );
1606 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1607 $where_clauses[] = 'page_id=pr_page';
1610 $cols = array( 'pr_expiry' );
1613 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1615 $sources = $get_pages ?
array() : false;
1616 $now = wfTimestampNow();
1617 $purgeExpired = false;
1619 foreach( $res as $row ) {
1620 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1621 if( $expiry > $now ) {
1623 $page_id = $row->pr_page
;
1624 $page_ns = $row->page_namespace
;
1625 $page_title = $row->page_title
;
1626 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1627 # Add groups needed for each restriction type if its not already there
1628 # Make sure this restriction type still exists
1629 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1630 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1636 // Trigger lazy purge of expired restrictions from the db
1637 $purgeExpired = true;
1640 if( $purgeExpired ) {
1641 Title
::purgeExpiredRestrictions();
1644 wfProfileOut( __METHOD__
);
1647 $this->mCascadeSources
= $sources;
1648 $this->mCascadingRestrictions
= $pagerestrictions;
1650 $this->mHasCascadingRestrictions
= $sources;
1652 return array( $sources, $pagerestrictions );
1655 function areRestrictionsCascading() {
1656 if (!$this->mRestrictionsLoaded
) {
1657 $this->loadRestrictions();
1660 return $this->mCascadeRestriction
;
1664 * Loads a string into mRestrictions array
1665 * @param $res \type{Resource} restrictions as an SQL result.
1667 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1668 global $wgRestrictionTypes;
1669 $dbr = wfGetDB( DB_SLAVE
);
1671 foreach( $wgRestrictionTypes as $type ){
1672 $this->mRestrictions
[$type] = array();
1673 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry('');
1676 $this->mCascadeRestriction
= false;
1678 # Backwards-compatibility: also load the restrictions from the page record (old format).
1680 if ( $oldFashionedRestrictions === NULL ) {
1681 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1682 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1685 if ($oldFashionedRestrictions != '') {
1687 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1688 $temp = explode( '=', trim( $restrict ) );
1689 if(count($temp) == 1) {
1690 // old old format should be treated as edit/move restriction
1691 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1692 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1694 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1698 $this->mOldRestrictions
= true;
1702 if( $dbr->numRows( $res ) ) {
1703 # Current system - load second to make them override.
1704 $now = wfTimestampNow();
1705 $purgeExpired = false;
1707 foreach( $res as $row ) {
1708 # Cycle through all the restrictions.
1710 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1711 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1714 // This code should be refactored, now that it's being used more generally,
1715 // But I don't really see any harm in leaving it in Block for now -werdna
1716 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1718 // Only apply the restrictions if they haven't expired!
1719 if ( !$expiry ||
$expiry > $now ) {
1720 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
1721 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1723 $this->mCascadeRestriction |
= $row->pr_cascade
;
1725 // Trigger a lazy purge of expired restrictions
1726 $purgeExpired = true;
1730 if( $purgeExpired ) {
1731 Title
::purgeExpiredRestrictions();
1735 $this->mRestrictionsLoaded
= true;
1739 * Load restrictions from the page_restrictions table
1741 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1742 if( !$this->mRestrictionsLoaded
) {
1743 if ($this->exists()) {
1744 $dbr = wfGetDB( DB_SLAVE
);
1746 $res = $dbr->select( 'page_restrictions', '*',
1747 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1749 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1751 $title_protection = $this->getTitleProtection();
1753 if (is_array($title_protection)) {
1754 extract($title_protection);
1756 $now = wfTimestampNow();
1757 $expiry = Block
::decodeExpiry($pt_expiry);
1759 if (!$expiry ||
$expiry > $now) {
1760 // Apply the restrictions
1761 $this->mRestrictionsExpiry
['create'] = $expiry;
1762 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1763 } else { // Get rid of the old restrictions
1764 Title
::purgeExpiredRestrictions();
1767 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry('');
1769 $this->mRestrictionsLoaded
= true;
1775 * Purge expired restrictions from the page_restrictions table
1777 static function purgeExpiredRestrictions() {
1778 $dbw = wfGetDB( DB_MASTER
);
1779 $dbw->delete( 'page_restrictions',
1780 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1783 $dbw->delete( 'protected_titles',
1784 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1789 * Accessor/initialisation for mRestrictions
1791 * @param $action \type{\string} action that permission needs to be checked for
1792 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
1794 public function getRestrictions( $action ) {
1795 if( !$this->mRestrictionsLoaded
) {
1796 $this->loadRestrictions();
1798 return isset( $this->mRestrictions
[$action] )
1799 ?
$this->mRestrictions
[$action]
1804 * Get the expiry time for the restriction against a given action
1805 * @return 14-char timestamp, or 'infinity' if the page is protected forever
1806 * or not protected at all, or false if the action is not recognised.
1808 public function getRestrictionExpiry( $action ) {
1809 if( !$this->mRestrictionsLoaded
) {
1810 $this->loadRestrictions();
1812 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
1816 * Is there a version of this page in the deletion archive?
1817 * @return \type{\int} the number of archived revisions
1819 public function isDeleted() {
1820 $fname = 'Title::isDeleted';
1821 if ( $this->getNamespace() < 0 ) {
1824 $dbr = wfGetDB( DB_SLAVE
);
1825 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1826 'ar_title' => $this->getDBkey() ), $fname );
1827 if( $this->getNamespace() == NS_IMAGE
) {
1828 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1829 array( 'fa_name' => $this->getDBkey() ), $fname );
1836 * Get the article ID for this Title from the link cache,
1837 * adding it if necessary
1838 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
1840 * @return \type{\int} the ID
1842 public function getArticleID( $flags = 0 ) {
1843 $linkCache = LinkCache
::singleton();
1844 if( $flags & GAID_FOR_UPDATE
) {
1845 $oldUpdate = $linkCache->forUpdate( true );
1846 $linkCache->clearLink( $this );
1847 $this->mArticleID
= $linkCache->addLinkObj( $this );
1848 $linkCache->forUpdate( $oldUpdate );
1850 if( -1 == $this->mArticleID
) {
1851 $this->mArticleID
= $linkCache->addLinkObj( $this );
1854 return $this->mArticleID
;
1858 * Is this an article that is a redirect page?
1859 * Uses link cache, adding it if necessary
1860 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1861 * @return \type{\bool}
1863 public function isRedirect( $flags = 0 ) {
1864 if( !is_null($this->mRedirect
) )
1865 return $this->mRedirect
;
1866 # Zero for special pages.
1867 # Also, calling getArticleID() loads the field from cache!
1868 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1871 $linkCache = LinkCache
::singleton();
1872 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1874 return $this->mRedirect
;
1878 * What is the length of this page?
1879 * Uses link cache, adding it if necessary
1880 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1881 * @return \type{\bool}
1883 public function getLength( $flags = 0 ) {
1884 if( $this->mLength
!= -1 )
1885 return $this->mLength
;
1886 # Zero for special pages.
1887 # Also, calling getArticleID() loads the field from cache!
1888 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1891 $linkCache = LinkCache
::singleton();
1892 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1894 return $this->mLength
;
1898 * What is the page_latest field for this page?
1899 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1900 * @return \type{\int}
1902 public function getLatestRevID( $flags = 0 ) {
1903 if( $this->mLatestID
!== false )
1904 return $this->mLatestID
;
1906 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
1907 $this->mLatestID
= $db->selectField( 'page', 'page_latest',
1908 array( 'page_namespace' => $this->getNamespace(), 'page_title' => $this->getDBKey() ),
1910 return $this->mLatestID
;
1914 * This clears some fields in this object, and clears any associated
1915 * keys in the "bad links" section of the link cache.
1917 * - This is called from Article::insertNewArticle() to allow
1918 * loading of the new page_id. It's also called from
1919 * Article::doDeleteArticle()
1921 * @param $newid \type{\int} the new Article ID
1923 public function resetArticleID( $newid ) {
1924 $linkCache = LinkCache
::singleton();
1925 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1927 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1928 else { $this->mArticleID
= $newid; }
1929 $this->mRestrictionsLoaded
= false;
1930 $this->mRestrictions
= array();
1934 * Updates page_touched for this page; called from LinksUpdate.php
1935 * @return \type{\bool} true if the update succeded
1937 public function invalidateCache() {
1938 global $wgUseFileCache;
1940 if ( wfReadOnly() ) {
1944 $dbw = wfGetDB( DB_MASTER
);
1945 $success = $dbw->update( 'page',
1947 'page_touched' => $dbw->timestamp()
1948 ), array( /* WHERE */
1949 'page_namespace' => $this->getNamespace() ,
1950 'page_title' => $this->getDBkey()
1951 ), 'Title::invalidateCache'
1954 if ($wgUseFileCache) {
1955 $cache = new HTMLFileCache($this);
1956 @unlink
($cache->fileCacheName());
1963 * Prefix some arbitrary text with the namespace or interwiki prefix
1966 * @param $name \type{\string} the text
1967 * @return \type{\string} the prefixed text
1970 /* private */ function prefix( $name ) {
1972 if ( '' != $this->mInterwiki
) {
1973 $p = $this->mInterwiki
. ':';
1975 if ( 0 != $this->mNamespace
) {
1976 $p .= $this->getNsText() . ':';
1982 * Secure and split - main initialisation function for this object
1984 * Assumes that mDbkeyform has been set, and is urldecoded
1985 * and uses underscores, but not otherwise munged. This function
1986 * removes illegal characters, splits off the interwiki and
1987 * namespace prefixes, sets the other forms, and canonicalizes
1989 * @return \type{\bool} true on success
1991 private function secureAndSplit() {
1992 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1995 static $rxTc = false;
1997 # Matching titles will be held as illegal.
1999 # Any character not allowed is forbidden...
2000 '[^' . Title
::legalChars() . ']' .
2001 # URL percent encoding sequences interfere with the ability
2002 # to round-trip titles -- you can't link to them consistently.
2003 '|%[0-9A-Fa-f]{2}' .
2004 # XML/HTML character references produce similar issues.
2005 '|&[A-Za-z0-9\x80-\xff]+;' .
2007 '|&#x[0-9A-Fa-f]+;' .
2011 $this->mInterwiki
= $this->mFragment
= '';
2012 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2014 $dbkey = $this->mDbkeyform
;
2016 # Strip Unicode bidi override characters.
2017 # Sometimes they slip into cut-n-pasted page titles, where the
2018 # override chars get included in list displays.
2019 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2020 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2022 # Clean up whitespace
2024 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2025 $dbkey = trim( $dbkey, '_' );
2027 if ( '' == $dbkey ) {
2031 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2032 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2036 $this->mDbkeyform
= $dbkey;
2038 # Initial colon indicates main namespace rather than specified default
2039 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2040 if ( ':' == $dbkey{0} ) {
2041 $this->mNamespace
= NS_MAIN
;
2042 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2043 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2046 # Namespace or interwiki prefix
2050 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2052 if ( $ns = $wgContLang->getNsIndex( $p )) {
2053 # Ordinary namespace
2055 $this->mNamespace
= $ns;
2056 } elseif( Interwiki
::isValidInterwiki( $p ) ) {
2058 # Can't make a local interwiki link to an interwiki link.
2059 # That's just crazy!
2065 $this->mInterwiki
= $wgContLang->lc( $p );
2067 # Redundant interwiki prefix to the local wiki
2068 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2069 if( $dbkey == '' ) {
2070 # Can't have an empty self-link
2073 $this->mInterwiki
= '';
2075 # Do another namespace split...
2079 # If there's an initial colon after the interwiki, that also
2080 # resets the default namespace
2081 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2082 $this->mNamespace
= NS_MAIN
;
2083 $dbkey = substr( $dbkey, 1 );
2086 # If there's no recognized interwiki or namespace,
2087 # then let the colon expression be part of the title.
2092 # We already know that some pages won't be in the database!
2094 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2095 $this->mArticleID
= 0;
2097 $fragment = strstr( $dbkey, '#' );
2098 if ( false !== $fragment ) {
2099 $this->setFragment( $fragment );
2100 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2101 # remove whitespace again: prevents "Foo_bar_#"
2102 # becoming "Foo_bar_"
2103 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2106 # Reject illegal characters.
2108 if( preg_match( $rxTc, $dbkey ) ) {
2113 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2114 * reachable due to the way web browsers deal with 'relative' URLs.
2115 * Also, they conflict with subpage syntax. Forbid them explicitly.
2117 if ( strpos( $dbkey, '.' ) !== false &&
2118 ( $dbkey === '.' ||
$dbkey === '..' ||
2119 strpos( $dbkey, './' ) === 0 ||
2120 strpos( $dbkey, '../' ) === 0 ||
2121 strpos( $dbkey, '/./' ) !== false ||
2122 strpos( $dbkey, '/../' ) !== false ||
2123 substr( $dbkey, -2 ) == '/.' ||
2124 substr( $dbkey, -3 ) == '/..' ) )
2130 * Magic tilde sequences? Nu-uh!
2132 if( strpos( $dbkey, '~~~' ) !== false ) {
2137 * Limit the size of titles to 255 bytes.
2138 * This is typically the size of the underlying database field.
2139 * We make an exception for special pages, which don't need to be stored
2140 * in the database, and may edge over 255 bytes due to subpage syntax
2141 * for long titles, e.g. [[Special:Block/Long name]]
2143 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2144 strlen( $dbkey ) > 512 )
2150 * Normally, all wiki links are forced to have
2151 * an initial capital letter so [[foo]] and [[Foo]]
2152 * point to the same place.
2154 * Don't force it for interwikis, since the other
2155 * site might be case-sensitive.
2157 $this->mUserCaseDBKey
= $dbkey;
2158 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2159 $dbkey = $wgContLang->ucfirst( $dbkey );
2163 * Can't make a link to a namespace alone...
2164 * "empty" local links can only be self-links
2165 * with a fragment identifier.
2168 $this->mInterwiki
== '' &&
2169 $this->mNamespace
!= NS_MAIN
) {
2172 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2173 // IP names are not allowed for accounts, and can only be referring to
2174 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2175 // there are numerous ways to present the same IP. Having sp:contribs scan
2176 // them all is silly and having some show the edits and others not is
2177 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2178 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2179 IP
::sanitizeIP( $dbkey ) : $dbkey;
2180 // Any remaining initial :s are illegal.
2181 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2186 $this->mDbkeyform
= $dbkey;
2187 $this->mUrlform
= wfUrlencode( $dbkey );
2189 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2195 * Set the fragment for this title. Removes the first character from the
2196 * specified fragment before setting, so it assumes you're passing it with
2199 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2200 * Still in active use privately.
2202 * @param $fragment \type{\string} text
2204 public function setFragment( $fragment ) {
2205 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2209 * Get a Title object associated with the talk page of this article
2210 * @return \type{Title} the object for the talk page
2212 public function getTalkPage() {
2213 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2217 * Get a title object associated with the subject page of this
2220 * @return \type{Title} the object for the subject page
2222 public function getSubjectPage() {
2223 return Title
::makeTitle( MWNamespace
::getSubject( $this->getNamespace() ), $this->getDBkey() );
2227 * Get an array of Title objects linking to this Title
2228 * Also stores the IDs in the link cache.
2230 * WARNING: do not use this function on arbitrary user-supplied titles!
2231 * On heavily-used templates it will max out the memory.
2233 * @param $options \type{\string} may be FOR UPDATE
2234 * @return \type{\arrayof{Title}} the Title objects linking here
2236 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2237 $linkCache = LinkCache
::singleton();
2240 $db = wfGetDB( DB_MASTER
);
2242 $db = wfGetDB( DB_SLAVE
);
2245 $res = $db->select( array( 'page', $table ),
2246 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2248 "{$prefix}_from=page_id",
2249 "{$prefix}_namespace" => $this->getNamespace(),
2250 "{$prefix}_title" => $this->getDBkey() ),
2255 if ( $db->numRows( $res ) ) {
2256 foreach( $res as $row ) {
2257 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2258 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2259 $retVal[] = $titleObj;
2263 $db->freeResult( $res );
2268 * Get an array of Title objects using this Title as a template
2269 * Also stores the IDs in the link cache.
2271 * WARNING: do not use this function on arbitrary user-supplied titles!
2272 * On heavily-used templates it will max out the memory.
2274 * @param $options \type{\string} may be FOR UPDATE
2275 * @return \type{\arrayof{Title}} the Title objects linking here
2277 public function getTemplateLinksTo( $options = '' ) {
2278 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2282 * Get an array of Title objects referring to non-existent articles linked from this page
2284 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2285 * @param $options \type{\string} may be FOR UPDATE
2286 * @return \type{\arrayof{Title}} the Title objects
2288 public function getBrokenLinksFrom( $options = '' ) {
2289 if ( $this->getArticleId() == 0 ) {
2290 # All links from article ID 0 are false positives
2295 $db = wfGetDB( DB_MASTER
);
2297 $db = wfGetDB( DB_SLAVE
);
2300 $res = $db->safeQuery(
2301 "SELECT pl_namespace, pl_title
2304 ON pl_namespace=page_namespace
2305 AND pl_title=page_title
2307 AND page_namespace IS NULL
2309 $db->tableName( 'pagelinks' ),
2310 $db->tableName( 'page' ),
2311 $this->getArticleId(),
2315 if ( $db->numRows( $res ) ) {
2316 foreach( $res as $row ) {
2317 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2320 $db->freeResult( $res );
2326 * Get a list of URLs to purge from the Squid cache when this
2329 * @return \type{\arrayof{\string}} the URLs
2331 public function getSquidURLs() {
2335 $this->getInternalURL(),
2336 $this->getInternalURL( 'action=history' )
2339 // purge variant urls as well
2340 if($wgContLang->hasVariants()){
2341 $variants = $wgContLang->getVariants();
2342 foreach($variants as $vCode){
2343 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2344 $urls[] = $this->getInternalURL('',$vCode);
2352 * Purge all applicable Squid URLs
2354 public function purgeSquid() {
2356 if ( $wgUseSquid ) {
2357 $urls = $this->getSquidURLs();
2358 $u = new SquidUpdate( $urls );
2364 * Move this page without authentication
2365 * @param &$nt \type{Title} the new page Title
2367 public function moveNoAuth( &$nt ) {
2368 return $this->moveTo( $nt, false );
2372 * Check whether a given move operation would be valid.
2373 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2374 * @param &$nt \type{Title} the new title
2375 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2377 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2378 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2380 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2383 // Normally we'd add this to $errors, but we'll get
2384 // lots of syntax errors if $nt is not an object
2385 return array(array('badtitletext'));
2387 if( $this->equals( $nt ) ) {
2388 $errors[] = array('selfmove');
2390 if( !$this->isMovable() ||
!$nt->isMovable() ) {
2391 $errors[] = array('immobile_namespace');
2394 $oldid = $this->getArticleID();
2395 $newid = $nt->getArticleID();
2397 if ( strlen( $nt->getDBkey() ) < 1 ) {
2398 $errors[] = array('articleexists');
2400 if ( ( '' == $this->getDBkey() ) ||
2402 ( '' == $nt->getDBkey() ) ) {
2403 $errors[] = array('badarticleerror');
2406 // Image-specific checks
2407 if( $this->getNamespace() == NS_IMAGE
) {
2408 $file = wfLocalFile( $this );
2409 if( $file->exists() ) {
2410 if( $nt->getNamespace() != NS_IMAGE
) {
2411 $errors[] = array('imagenocrossnamespace');
2413 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2414 $errors[] = array('imageinvalidfilename');
2416 if( !File
::checkExtensionCompatibility( $file, $nt->getDbKey() ) ) {
2417 $errors[] = array('imagetypemismatch');
2424 $errors = wfArrayMerge($errors,
2425 $this->getUserPermissionsErrors('move', $wgUser),
2426 $this->getUserPermissionsErrors('edit', $wgUser),
2427 $nt->getUserPermissionsErrors('move', $wgUser),
2428 $nt->getUserPermissionsErrors('edit', $wgUser));
2431 $match = EditPage
::matchSpamRegex( $reason );
2432 if( $match !== false ) {
2433 // This is kind of lame, won't display nice
2434 $errors[] = array('spamprotectiontext');
2439 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2440 $errors[] = array('hookaborted', $err);
2443 # The move is allowed only if (1) the target doesn't exist, or
2444 # (2) the target is a redirect to the source, and has no history
2445 # (so we can undo bad moves right after they're done).
2447 if ( 0 != $newid ) { # Target exists; check for validity
2448 if ( ! $this->isValidMoveTarget( $nt ) ) {
2449 $errors[] = array('articleexists');
2452 $tp = $nt->getTitleProtection();
2453 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2454 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2455 $errors[] = array('cantmove-titleprotected');
2464 * Move a title to a new location
2465 * @param &$nt \type{Title} the new title
2466 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2468 * @param $reason \type{\string} The reason for the move
2469 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2470 * Ignored if the user doesn't have the suppressredirect right.
2471 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2473 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2474 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2475 if( is_array( $err ) ) {
2479 $pageid = $this->getArticleID();
2480 $protected = $this->isProtected();
2481 if( $nt->exists() ) {
2482 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2483 $pageCountChange = ($createRedirect ?
0 : -1);
2484 } else { # Target didn't exist, do normal move.
2485 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2486 $pageCountChange = ($createRedirect ?
1 : 0);
2489 if( is_array( $err ) ) {
2492 $redirid = $this->getArticleID();
2494 // Category memberships include a sort key which may be customized.
2495 // If it's left as the default (the page title), we need to update
2496 // the sort key to match the new title.
2498 // Be careful to avoid resetting cl_timestamp, which may disturb
2499 // time-based lists on some sites.
2501 // Warning -- if the sort key is *explicitly* set to the old title,
2502 // we can't actually distinguish it from a default here, and it'll
2503 // be set to the new title even though it really shouldn't.
2504 // It'll get corrected on the next edit, but resetting cl_timestamp.
2505 $dbw = wfGetDB( DB_MASTER
);
2506 $dbw->update( 'categorylinks',
2508 'cl_sortkey' => $nt->getPrefixedText(),
2509 'cl_timestamp=cl_timestamp' ),
2511 'cl_from' => $pageid,
2512 'cl_sortkey' => $this->getPrefixedText() ),
2516 # Protect the redirect title as the title used to be...
2517 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2519 'pr_page' => $redirid,
2520 'pr_type' => 'pr_type',
2521 'pr_level' => 'pr_level',
2522 'pr_cascade' => 'pr_cascade',
2523 'pr_user' => 'pr_user',
2524 'pr_expiry' => 'pr_expiry'
2526 array( 'pr_page' => $pageid ),
2530 # Update the protection log
2531 $log = new LogPage( 'protect' );
2532 $comment = wfMsgForContent('prot_1movedto2',$this->getPrefixedText(), $nt->getPrefixedText() );
2533 if( $reason ) $comment .= ': ' . $reason;
2534 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2538 $oldnamespace = $this->getNamespace() & ~
1;
2539 $newnamespace = $nt->getNamespace() & ~
1;
2540 $oldtitle = $this->getDBkey();
2541 $newtitle = $nt->getDBkey();
2543 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2544 WatchedItem
::duplicateEntries( $this, $nt );
2547 # Update search engine
2548 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2550 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2554 if( $this->isContentPage() && !$nt->isContentPage() ) {
2555 # No longer a content page
2556 # Not viewed, edited, removing
2557 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2558 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2559 # Now a content page
2560 # Not viewed, edited, adding
2561 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2562 } elseif( $pageCountChange ) {
2564 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2571 # Update message cache for interface messages
2572 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2573 global $wgMessageCache;
2574 $oldarticle = new Article( $this );
2575 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2576 $newarticle = new Article( $nt );
2577 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2581 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2586 * Move page to a title which is at present a redirect to the
2589 * @param &$nt \type{Title} the page to move to, which should currently
2591 * @param $reason \type{\string} The reason for the move
2592 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2593 * Ignored if the user doesn't have the suppressredirect right
2595 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2596 global $wgUseSquid, $wgUser;
2597 $fname = 'Title::moveOverExistingRedirect';
2598 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2601 $comment .= ": $reason";
2604 $now = wfTimestampNow();
2605 $newid = $nt->getArticleID();
2606 $oldid = $this->getArticleID();
2607 $latest = $this->getLatestRevID();
2609 $dbw = wfGetDB( DB_MASTER
);
2611 # Delete the old redirect. We don't save it to history since
2612 # by definition if we've got here it's rather uninteresting.
2613 # We have to remove it so that the next step doesn't trigger
2614 # a conflict on the unique namespace+title index...
2615 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2616 if ( !$dbw->cascadingDeletes() ) {
2617 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2618 global $wgUseTrackbacks;
2619 if ($wgUseTrackbacks)
2620 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2621 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2622 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2623 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2624 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2625 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2626 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2627 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2630 # Save a null revision in the page's history notifying of the move
2631 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2632 $nullRevId = $nullRevision->insertOn( $dbw );
2634 $article = new Article( $this );
2635 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2637 # Change the name of the target page:
2638 $dbw->update( 'page',
2640 'page_touched' => $dbw->timestamp($now),
2641 'page_namespace' => $nt->getNamespace(),
2642 'page_title' => $nt->getDBkey(),
2643 'page_latest' => $nullRevId,
2645 /* WHERE */ array( 'page_id' => $oldid ),
2648 $nt->resetArticleID( $oldid );
2650 # Recreate the redirect, this time in the other direction.
2651 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2652 $mwRedir = MagicWord
::get( 'redirect' );
2653 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2654 $redirectArticle = new Article( $this );
2655 $newid = $redirectArticle->insertOn( $dbw );
2656 $redirectRevision = new Revision( array(
2658 'comment' => $comment,
2659 'text' => $redirectText ) );
2660 $redirectRevision->insertOn( $dbw );
2661 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2663 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2665 # Now, we record the link from the redirect to the new title.
2666 # It should have no other outgoing links...
2667 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2668 $dbw->insert( 'pagelinks',
2670 'pl_from' => $newid,
2671 'pl_namespace' => $nt->getNamespace(),
2672 'pl_title' => $nt->getDBkey() ),
2675 $this->resetArticleID( 0 );
2678 # Move an image if this is a file
2679 if( $this->getNamespace() == NS_IMAGE
) {
2680 $file = wfLocalFile( $this );
2681 if( $file->exists() ) {
2682 $status = $file->move( $nt );
2683 if( !$status->isOk() ) {
2685 return $status->getErrorsArray();
2691 $log = new LogPage( 'move' );
2692 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2695 if ( $wgUseSquid ) {
2696 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2697 $u = new SquidUpdate( $urls );
2704 * Move page to non-existing title.
2705 * @param &$nt \type{Title} the new Title
2706 * @param $reason \type{\string} The reason for the move
2707 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2708 * Ignored if the user doesn't have the suppressredirect right
2710 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2711 global $wgUseSquid, $wgUser;
2712 $fname = 'MovePageForm::moveToNewTitle';
2713 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2715 $comment .= wfMsgExt( 'colon-separator',
2716 array( 'escapenoentities', 'content' ) );
2717 $comment .= $reason;
2720 $newid = $nt->getArticleID();
2721 $oldid = $this->getArticleID();
2722 $latest = $this->getLatestRevId();
2724 $dbw = wfGetDB( DB_MASTER
);
2725 $now = $dbw->timestamp();
2727 # Save a null revision in the page's history notifying of the move
2728 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2729 $nullRevId = $nullRevision->insertOn( $dbw );
2731 $article = new Article( $this );
2732 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2735 $dbw->update( 'page',
2737 'page_touched' => $now,
2738 'page_namespace' => $nt->getNamespace(),
2739 'page_title' => $nt->getDBkey(),
2740 'page_latest' => $nullRevId,
2742 /* WHERE */ array( 'page_id' => $oldid ),
2745 $nt->resetArticleID( $oldid );
2747 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2749 $mwRedir = MagicWord
::get( 'redirect' );
2750 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2751 $redirectArticle = new Article( $this );
2752 $newid = $redirectArticle->insertOn( $dbw );
2753 $redirectRevision = new Revision( array(
2755 'comment' => $comment,
2756 'text' => $redirectText ) );
2757 $redirectRevision->insertOn( $dbw );
2758 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2760 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2762 # Record the just-created redirect's linking to the page
2763 $dbw->insert( 'pagelinks',
2765 'pl_from' => $newid,
2766 'pl_namespace' => $nt->getNamespace(),
2767 'pl_title' => $nt->getDBkey() ),
2770 $this->resetArticleID( 0 );
2773 # Move an image if this is a file
2774 if( $this->getNamespace() == NS_IMAGE
) {
2775 $file = wfLocalFile( $this );
2776 if( $file->exists() ) {
2777 $status = $file->move( $nt );
2778 if( !$status->isOk() ) {
2780 return $status->getErrorsArray();
2786 $log = new LogPage( 'move' );
2787 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2789 # Purge caches as per article creation
2790 Article
::onArticleCreate( $nt );
2792 # Purge old title from squid
2793 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2794 $this->purgeSquid();
2799 * Checks if $this can be moved to a given Title
2800 * - Selects for update, so don't call it unless you mean business
2802 * @param &$nt \type{Title} the new title to check
2803 * @return \type{\bool} TRUE or FALSE
2805 public function isValidMoveTarget( $nt ) {
2807 $fname = 'Title::isValidMoveTarget';
2808 $dbw = wfGetDB( DB_MASTER
);
2810 # Is it an existsing file?
2811 if( $nt->getNamespace() == NS_IMAGE
) {
2812 $file = wfLocalFile( $nt );
2813 if( $file->exists() ) {
2814 wfDebug( __METHOD__
. ": file exists\n" );
2820 $id = $nt->getArticleID();
2821 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2822 array( 'page_is_redirect','old_text','old_flags' ),
2823 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2824 $fname, 'FOR UPDATE' );
2826 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2828 wfDebug( __METHOD__
. ": not a redirect\n" );
2831 $text = Revision
::getRevisionText( $obj );
2833 # Does the redirect point to the source?
2834 # Or is it a broken self-redirect, usually caused by namespace collisions?
2836 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2837 $redirTitle = Title
::newFromText( $m[1] );
2838 if( !is_object( $redirTitle ) ||
2839 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2840 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2841 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2846 wfDebug( __METHOD__
. ": failsafe\n" );
2850 # Does the article have a history?
2851 $row = $dbw->selectRow( array( 'page', 'revision'),
2853 array( 'page_namespace' => $nt->getNamespace(),
2854 'page_title' => $nt->getDBkey(),
2855 'page_id=rev_page AND page_latest != rev_id'
2856 ), $fname, 'FOR UPDATE'
2859 # Return true if there was no history
2860 return $row === false;
2864 * Can this title be added to a user's watchlist?
2866 * @return \type{\bool} TRUE or FALSE
2868 public function isWatchable() {
2869 return !$this->isExternal()
2870 && MWNamespace
::isWatchable( $this->getNamespace() );
2874 * Get categories to which this Title belongs and return an array of
2875 * categories' names.
2877 * @return \type{\array} array an array of parents in the form:
2878 * $parent => $currentarticle
2880 public function getParentCategories() {
2883 $titlekey = $this->getArticleId();
2884 $dbr = wfGetDB( DB_SLAVE
);
2885 $categorylinks = $dbr->tableName( 'categorylinks' );
2888 $sql = "SELECT * FROM $categorylinks"
2889 ." WHERE cl_from='$titlekey'"
2890 ." AND cl_from <> '0'"
2891 ." ORDER BY cl_sortkey";
2893 $res = $dbr->query( $sql );
2895 if( $dbr->numRows( $res ) > 0 ) {
2896 foreach( $res as $row )
2897 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2898 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
2899 $dbr->freeResult( $res );
2907 * Get a tree of parent categories
2908 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
2909 * @return \type{\array} Tree of parent categories
2911 public function getParentCategoryTree( $children = array() ) {
2913 $parents = $this->getParentCategories();
2916 foreach( $parents as $parent => $current ) {
2917 if ( array_key_exists( $parent, $children ) ) {
2918 # Circular reference
2919 $stack[$parent] = array();
2921 $nt = Title
::newFromText($parent);
2923 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2935 * Get an associative array for selecting this title from
2938 * @return \type{\array} Selection array
2940 public function pageCond() {
2941 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2945 * Get the revision ID of the previous revision
2947 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
2948 * @param $flags \type{\int} GAID_FOR_UPDATE
2949 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
2951 public function getPreviousRevisionID( $revId, $flags=0 ) {
2952 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
2953 return $db->selectField( 'revision', 'rev_id',
2955 'rev_page' => $this->getArticleId($flags),
2956 'rev_id < ' . intval( $revId )
2959 array( 'ORDER BY' => 'rev_id DESC' )
2964 * Get the revision ID of the next revision
2966 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
2967 * @param $flags \type{\int} GAID_FOR_UPDATE
2968 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
2970 public function getNextRevisionID( $revId, $flags=0 ) {
2971 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
2972 return $db->selectField( 'revision', 'rev_id',
2974 'rev_page' => $this->getArticleId($flags),
2975 'rev_id > ' . intval( $revId )
2978 array( 'ORDER BY' => 'rev_id' )
2983 * Get the number of revisions between the given revision IDs.
2984 * Used for diffs and other things that really need it.
2986 * @param $old \type{\int} Revision ID.
2987 * @param $new \type{\int} Revision ID.
2988 * @return \type{\int} Number of revisions between these IDs.
2990 public function countRevisionsBetween( $old, $new ) {
2991 $dbr = wfGetDB( DB_SLAVE
);
2992 return $dbr->selectField( 'revision', 'count(*)',
2993 'rev_page = ' . intval( $this->getArticleId() ) .
2994 ' AND rev_id > ' . intval( $old ) .
2995 ' AND rev_id < ' . intval( $new ),
2997 array( 'USE INDEX' => 'PRIMARY' ) );
3001 * Compare with another title.
3003 * @param \type{Title} $title
3004 * @return \type{\bool} TRUE or FALSE
3006 public function equals( Title
$title ) {
3007 // Note: === is necessary for proper matching of number-like titles.
3008 return $this->getInterwiki() === $title->getInterwiki()
3009 && $this->getNamespace() == $title->getNamespace()
3010 && $this->getDBkey() === $title->getDBkey();
3014 * Callback for usort() to do title sorts by (namespace, title)
3016 static function compare( $a, $b ) {
3017 if( $a->getNamespace() == $b->getNamespace() ) {
3018 return strcmp( $a->getText(), $b->getText() );
3020 return $a->getNamespace() - $b->getNamespace();
3025 * Return a string representation of this title
3027 * @return \type{\string} String representation of this title
3029 public function __toString() {
3030 return $this->getPrefixedText();
3034 * Check if page exists
3035 * @return \type{\bool} TRUE or FALSE
3037 public function exists() {
3038 return $this->getArticleId() != 0;
3042 * Do we know that this title definitely exists, or should we otherwise
3043 * consider that it exists?
3045 * @return \type{\bool} TRUE or FALSE
3047 public function isAlwaysKnown() {
3048 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3049 // the full l10n of that language to be loaded. That takes much memory and
3050 // isn't needed. So we strip the language part away.
3051 // Also, extension messages which are not loaded, are shown as red, because
3052 // we don't call MessageCache::loadAllMessages.
3053 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3054 return $this->isExternal()
3055 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
3056 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $basename ) );
3060 * Update page_touched timestamps and send squid purge messages for
3061 * pages linking to this title. May be sent to the job queue depending
3062 * on the number of links. Typically called on create and delete.
3064 public function touchLinks() {
3065 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3068 if ( $this->getNamespace() == NS_CATEGORY
) {
3069 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3075 * Get the last touched timestamp
3076 * @param Database $db, optional db
3077 * @return \type{\string} Last touched timestamp
3079 public function getTouched( $db = NULL ) {
3080 $db = isset($db) ?
$db : wfGetDB( DB_SLAVE
);
3081 $touched = $db->selectField( 'page', 'page_touched',
3083 'page_namespace' => $this->getNamespace(),
3084 'page_title' => $this->getDBkey()
3091 * Get the trackback URL for this page
3092 * @return \type{\string} Trackback URL
3094 public function trackbackURL() {
3095 global $wgScriptPath, $wgServer;
3097 return "$wgServer$wgScriptPath/trackback.php?article="
3098 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3102 * Get the trackback RDF for this page
3103 * @return \type{\string} Trackback RDF
3105 public function trackbackRDF() {
3106 $url = htmlspecialchars($this->getFullURL());
3107 $title = htmlspecialchars($this->getText());
3108 $tburl = $this->trackbackURL();
3110 // Autodiscovery RDF is placed in comments so HTML validator
3111 // won't barf. This is a rather icky workaround, but seems
3112 // frequently used by this kind of RDF thingy.
3114 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3116 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3117 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3118 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3121 dc:identifier=\"$url\"
3123 trackback:ping=\"$tburl\" />
3129 * Generate strings used for xml 'id' names in monobook tabs
3130 * @return \type{\string} XML 'id' name
3132 public function getNamespaceKey() {
3134 switch ($this->getNamespace()) {
3137 return 'nstab-main';
3140 return 'nstab-user';
3142 return 'nstab-media';
3144 return 'nstab-special';
3146 case NS_PROJECT_TALK
:
3147 return 'nstab-project';
3150 return 'nstab-image';
3152 case NS_MEDIAWIKI_TALK
:
3153 return 'nstab-mediawiki';
3155 case NS_TEMPLATE_TALK
:
3156 return 'nstab-template';
3159 return 'nstab-help';
3161 case NS_CATEGORY_TALK
:
3162 return 'nstab-category';
3164 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3169 * Returns true if this title resolves to the named special page
3170 * @param $name \type{\string} The special page name
3172 public function isSpecial( $name ) {
3173 if ( $this->getNamespace() == NS_SPECIAL
) {
3174 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3175 if ( $name == $thisName ) {
3183 * If the Title refers to a special page alias which is not the local default,
3184 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3186 public function fixSpecialName() {
3187 if ( $this->getNamespace() == NS_SPECIAL
) {
3188 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3189 if ( $canonicalName ) {
3190 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3191 if ( $localName != $this->mDbkeyform
) {
3192 return Title
::makeTitle( NS_SPECIAL
, $localName );
3200 * Is this Title in a namespace which contains content?
3201 * In other words, is this a content page, for the purposes of calculating
3204 * @return \type{\bool} TRUE or FALSE
3206 public function isContentPage() {
3207 return MWNamespace
::isContent( $this->getNamespace() );
3211 * Get all extant redirects to this Title
3213 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3214 * NULL to consider all namespaces
3215 * @return \type{\arrayof{Title}} Redirects to this title
3217 public function getRedirectsHere( $ns = null ) {
3220 $dbr = wfGetDB( DB_SLAVE
);
3222 'rd_namespace' => $this->getNamespace(),
3223 'rd_title' => $this->getDBkey(),
3226 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3228 $res = $dbr->select(
3229 array( 'redirect', 'page' ),
3230 array( 'page_namespace', 'page_title' ),
3236 foreach( $res as $row ) {
3237 $redirs[] = self
::newFromRow( $row );