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?
71 var $mNotificationTimestamp = array(); ///< Associative array of user ID -> timestamp/false
72 var $mTouched = null; // <last cache date>
80 /* private */ function __construct() {}
83 * Create a new Title from a prefixed DB key
84 * @param $key \type{\string} The database key, which has underscores
85 * instead of spaces, possibly including namespace and
87 * @return \type{Title} the new object, or NULL on an error
89 public static function newFromDBkey( $key ) {
91 $t->mDbkeyform
= $key;
92 if( $t->secureAndSplit() )
99 * Create a new Title from text, such as what one would find in a link. De-
100 * codes any HTML entities in the text.
102 * @param $text string The link text; spaces, prefixes, and an
103 * initial ':' indicating the main namespace are accepted.
104 * @param $defaultNamespace int The namespace to use if none is speci-
105 * fied by a prefix. If you want to force a specific namespace even if
106 * $text might begin with a namespace prefix, use makeTitle() or
108 * @return Title The new object, or null on an error.
110 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
111 if( is_object( $text ) ) {
112 throw new MWException( 'Title::newFromText given an object' );
116 * Wiki pages often contain multiple links to the same page.
117 * Title normalization and parsing can become expensive on
118 * pages with many links, so we can save a little time by
121 * In theory these are value objects and won't get changed...
123 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
124 return Title
::$titleCache[$text];
128 * Convert things like é ā or 〗 into real text...
130 $filteredText = Sanitizer
::decodeCharReferences( $text );
133 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
134 $t->mDefaultNamespace
= $defaultNamespace;
136 static $cachedcount = 0 ;
137 if( $t->secureAndSplit() ) {
138 if( $defaultNamespace == NS_MAIN
) {
139 if( $cachedcount >= self
::CACHE_MAX
) {
140 # Avoid memory leaks on mass operations...
141 Title
::$titleCache = array();
145 Title
::$titleCache[$text] =& $t;
155 * Create a new Title from URL-encoded text. Ensures that
156 * the given title's length does not exceed the maximum.
157 * @param $url \type{\string} the title, as might be taken from a URL
158 * @return \type{Title} the new object, or NULL on an error
160 public static function newFromURL( $url ) {
161 global $wgLegalTitleChars;
164 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
165 # but some URLs used it as a space replacement and they still come
166 # from some external search tools.
167 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
168 $url = str_replace( '+', ' ', $url );
171 $t->mDbkeyform
= str_replace( ' ', '_', $url );
172 if( $t->secureAndSplit() ) {
180 * Create a new Title from an article ID
182 * @todo This is inefficiently implemented, the page row is requested
183 * but not used for anything else
185 * @param $id \type{\int} the page_id corresponding to the Title to create
186 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
187 * @return \type{Title} the new object, or NULL on an error
189 public static function newFromID( $id, $flags = 0 ) {
190 $fname = 'Title::newFromID';
191 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
192 $row = $db->selectRow( 'page', array( 'page_namespace', 'page_title' ),
193 array( 'page_id' => $id ), $fname );
194 if ( $row !== false ) {
195 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
203 * Make an array of titles from an array of IDs
204 * @param $ids \type{\arrayof{\int}} Array of IDs
205 * @return \type{\arrayof{Title}} Array of Titles
207 public static function newFromIDs( $ids ) {
208 if ( !count( $ids ) ) {
211 $dbr = wfGetDB( DB_SLAVE
);
212 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
213 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
216 foreach( $res as $row ) {
217 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
223 * Make a Title object from a DB row
224 * @param $row \type{Row} (needs at least page_title,page_namespace)
225 * @return \type{Title} corresponding Title
227 public static function newFromRow( $row ) {
228 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
230 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
231 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
232 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: NULL;
233 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
239 * Create a new Title from a namespace index and a DB key.
240 * It's assumed that $ns and $title are *valid*, for instance when
241 * they came directly from the database or a special page name.
242 * For convenience, spaces are converted to underscores so that
243 * eg user_text fields can be used directly.
245 * @param $ns \type{\int} the namespace of the article
246 * @param $title \type{\string} the unprefixed database key form
247 * @param $fragment \type{\string} The link fragment (after the "#")
248 * @return \type{Title} the new object
250 public static function &makeTitle( $ns, $title, $fragment = '' ) {
253 $t->mFragment
= $fragment;
254 $t->mNamespace
= $ns = intval( $ns );
255 $t->mDbkeyform
= str_replace( ' ', '_', $title );
256 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
257 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
258 $t->mTextform
= str_replace( '_', ' ', $title );
263 * Create a new Title from a namespace index and a DB key.
264 * The parameters will be checked for validity, which is a bit slower
265 * than makeTitle() but safer for user-provided data.
267 * @param $ns \type{\int} the namespace of the article
268 * @param $title \type{\string} the database key form
269 * @param $fragment \type{\string} The link fragment (after the "#")
270 * @return \type{Title} the new object, or NULL on an error
272 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
274 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
275 if( $t->secureAndSplit() ) {
283 * Create a new Title for the Main Page
284 * @return \type{Title} the new object
286 public static function newMainPage() {
287 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
288 // Don't give fatal errors if the message is broken
290 $title = Title
::newFromText( 'Main Page' );
296 * Extract a redirect destination from a string and return the
297 * Title, or null if the text doesn't contain a valid redirect
299 * @param $text \type{String} Text with possible redirect
300 * @return \type{Title} The corresponding Title
302 public static function newFromRedirect( $text ) {
303 $redir = MagicWord
::get( 'redirect' );
305 if( $redir->matchStartAndRemove( $text ) ) {
306 // Extract the first link and see if it's usable
307 // Ensure that it really does come directly after #REDIRECT
308 // Some older redirects included a colon, so don't freak about that!
310 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
311 // Strip preceding colon used to "escape" categories, etc.
312 // and URL-decode links
313 if( strpos( $m[1], '%' ) !== false ) {
314 // Match behavior of inline link parsing here;
315 // don't interpret + as " " most of the time!
316 // It might be safe to just use rawurldecode instead, though.
317 $m[1] = urldecode( ltrim( $m[1], ':' ) );
319 $title = Title
::newFromText( $m[1] );
320 // Redirects to some special pages are not permitted
321 if( $title instanceof Title
322 && !$title->isSpecial( 'Userlogout' )
323 && !$title->isSpecial( 'Filepath' ) )
332 #----------------------------------------------------------------------------
334 #----------------------------------------------------------------------------
337 * Get the prefixed DB key associated with an ID
338 * @param $id \type{\int} the page_id of the article
339 * @return \type{Title} an object representing the article, or NULL
340 * if no such article was found
342 public static function nameOf( $id ) {
343 $dbr = wfGetDB( DB_SLAVE
);
345 $s = $dbr->selectRow( 'page',
346 array( 'page_namespace','page_title' ),
347 array( 'page_id' => $id ),
349 if ( $s === false ) { return NULL; }
351 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
356 * Get a regex character class describing the legal characters in a link
357 * @return \type{\string} the list of characters, not delimited
359 public static function legalChars() {
360 global $wgLegalTitleChars;
361 return $wgLegalTitleChars;
365 * Get a string representation of a title suitable for
366 * including in a search index
368 * @param $ns \type{\int} a namespace index
369 * @param $title \type{\string} text-form main part
370 * @return \type{\string} a stripped-down title string ready for the
373 public static function indexTitle( $ns, $title ) {
376 $lc = SearchEngine
::legalSearchChars() . '&#;';
377 $t = $wgContLang->stripForSearch( $title );
378 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
379 $t = $wgContLang->lc( $t );
382 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
383 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
385 $t = preg_replace( "/\\s+/", ' ', $t );
387 if ( $ns == NS_FILE
) {
388 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
394 * Make a prefixed DB key from a DB key and a namespace index
395 * @param $ns \type{\int} numerical representation of the namespace
396 * @param $title \type{\string} the DB key form the title
397 * @param $fragment \type{\string} The link fragment (after the "#")
398 * @return \type{\string} the prefixed form of the title
400 public static function makeName( $ns, $title, $fragment = '' ) {
403 $namespace = $wgContLang->getNsText( $ns );
404 $name = $namespace == '' ?
$title : "$namespace:$title";
405 if ( strval( $fragment ) != '' ) {
406 $name .= '#' . $fragment;
412 * Returns the URL associated with an interwiki prefix
413 * @param $key \type{\string} the interwiki prefix (e.g. "MeatBall")
414 * @return \type{\string} the associated URL, containing "$1",
415 * which should be replaced by an article title
417 * @deprecated See Interwiki class
419 public function getInterwikiLink( $key ) {
420 return Interwiki
::fetch( $key )->getURL( );
424 * Determine whether the object refers to a page within
427 * @return \type{\bool} TRUE if this is an in-project interwiki link
428 * or a wikilink, FALSE otherwise
430 public function isLocal() {
431 if ( $this->mInterwiki
!= '' ) {
432 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
439 * Determine whether the object refers to a page within
440 * this project and is transcludable.
442 * @return \type{\bool} TRUE if this is transcludable
444 public function isTrans() {
445 if ($this->mInterwiki
== '')
448 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
452 * Escape a text fragment, say from a link, for a URL
454 static function escapeFragmentForURL( $fragment ) {
455 $fragment = str_replace( ' ', '_', $fragment );
456 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
457 $replaceArray = array(
461 return strtr( $fragment, $replaceArray );
464 #----------------------------------------------------------------------------
466 #----------------------------------------------------------------------------
468 /** Simple accessors */
470 * Get the text form (spaces not underscores) of the main part
471 * @return \type{\string} Main part of the title
473 public function getText() { return $this->mTextform
; }
475 * Get the URL-encoded form of the main part
476 * @return \type{\string} Main part of the title, URL-encoded
478 public function getPartialURL() { return $this->mUrlform
; }
480 * Get the main part with underscores
481 * @return \type{\string} Main part of the title, with underscores
483 public function getDBkey() { return $this->mDbkeyform
; }
485 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
486 * @return \type{\int} Namespace index
488 public function getNamespace() { return $this->mNamespace
; }
490 * Get the namespace text
491 * @return \type{\string} Namespace text
493 public function getNsText() {
494 global $wgContLang, $wgCanonicalNamespaceNames;
496 if ( '' != $this->mInterwiki
) {
497 // This probably shouldn't even happen. ohh man, oh yuck.
498 // But for interwiki transclusion it sometimes does.
499 // Shit. Shit shit shit.
501 // Use the canonical namespaces if possible to try to
502 // resolve a foreign namespace.
503 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
504 return $wgCanonicalNamespaceNames[$this->mNamespace
];
507 return $wgContLang->getNsText( $this->mNamespace
);
510 * Get the DB key with the initial letter case as specified by the user
511 * @return \type{\string} DB key
513 function getUserCaseDBKey() {
514 return $this->mUserCaseDBKey
;
517 * Get the namespace text of the subject (rather than talk) page
518 * @return \type{\string} Namespace text
520 public function getSubjectNsText() {
522 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
525 * Get the namespace text of the talk page
526 * @return \type{\string} Namespace text
528 public function getTalkNsText() {
530 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
533 * Could this title have a corresponding talk page?
534 * @return \type{\bool} TRUE or FALSE
536 public function canTalk() {
537 return( MWNamespace
::canTalk( $this->mNamespace
) );
540 * Get the interwiki prefix (or null string)
541 * @return \type{\string} Interwiki prefix
543 public function getInterwiki() { return $this->mInterwiki
; }
545 * Get the Title fragment (i.e.\ the bit after the #) in text form
546 * @return \type{\string} Title fragment
548 public function getFragment() { return $this->mFragment
; }
550 * Get the fragment in URL form, including the "#" character if there is one
551 * @return \type{\string} Fragment in URL form
553 public function getFragmentForURL() {
554 if ( $this->mFragment
== '' ) {
557 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
561 * Get the default namespace index, for when there is no namespace
562 * @return \type{\int} Default namespace index
564 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
567 * Get title for search index
568 * @return \type{\string} a stripped-down title string ready for the
571 public function getIndexTitle() {
572 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
576 * Get the prefixed database key form
577 * @return \type{\string} the prefixed title, with underscores and
578 * any interwiki and namespace prefixes
580 public function getPrefixedDBkey() {
581 $s = $this->prefix( $this->mDbkeyform
);
582 $s = str_replace( ' ', '_', $s );
587 * Get the prefixed title with spaces.
588 * This is the form usually used for display
589 * @return \type{\string} the prefixed title, with spaces
591 public function getPrefixedText() {
592 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
593 $s = $this->prefix( $this->mTextform
);
594 $s = str_replace( '_', ' ', $s );
595 $this->mPrefixedText
= $s;
597 return $this->mPrefixedText
;
601 * Get the prefixed title with spaces, plus any fragment
602 * (part beginning with '#')
603 * @return \type{\string} the prefixed title, with spaces and
604 * the fragment, including '#'
606 public function getFullText() {
607 $text = $this->getPrefixedText();
608 if( '' != $this->mFragment
) {
609 $text .= '#' . $this->mFragment
;
615 * Get the base name, i.e. the leftmost parts before the /
616 * @return \type{\string} Base name
618 public function getBaseText() {
619 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
620 return $this->getText();
623 $parts = explode( '/', $this->getText() );
624 # Don't discard the real title if there's no subpage involved
625 if( count( $parts ) > 1 )
626 unset( $parts[ count( $parts ) - 1 ] );
627 return implode( '/', $parts );
631 * Get the lowest-level subpage name, i.e. the rightmost part after /
632 * @return \type{\string} Subpage name
634 public function getSubpageText() {
635 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
636 return( $this->mTextform
);
638 $parts = explode( '/', $this->mTextform
);
639 return( $parts[ count( $parts ) - 1 ] );
643 * Get a URL-encoded form of the subpage text
644 * @return \type{\string} URL-encoded subpage name
646 public function getSubpageUrlForm() {
647 $text = $this->getSubpageText();
648 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
653 * Get a URL-encoded title (not an actual URL) including interwiki
654 * @return \type{\string} the URL-encoded form
656 public function getPrefixedURL() {
657 $s = $this->prefix( $this->mDbkeyform
);
658 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
663 * Get a real URL referring to this title, with interwiki link and
666 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
667 * links. Can be specified as an associative array as well, e.g.,
668 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
669 * @param $variant \type{\string} language variant of url (for sr, zh..)
670 * @return \type{\string} the URL
672 public function getFullURL( $query = '', $variant = false ) {
673 global $wgContLang, $wgServer, $wgRequest;
675 if( is_array( $query ) ) {
676 $query = wfArrayToCGI( $query );
679 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
681 $url = $this->getLocalUrl( $query, $variant );
683 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
684 // Correct fix would be to move the prepending elsewhere.
685 if ($wgRequest->getVal('action') != 'render') {
686 $url = $wgServer . $url;
689 $baseUrl = $interwiki->getURL( );
691 $namespace = wfUrlencode( $this->getNsText() );
692 if ( '' != $namespace ) {
693 # Can this actually happen? Interwikis shouldn't be parsed.
694 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
697 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
698 $url = wfAppendQuery( $url, $query );
701 # Finally, add the fragment.
702 $url .= $this->getFragmentForURL();
704 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
709 * Get a URL with no fragment or server name. If this page is generated
710 * with action=render, $wgServer is prepended.
711 * @param mixed $query an optional query string; if not specified,
712 * $wgArticlePath will be used. Can be specified as an associative array
713 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
715 * @param $variant \type{\string} language variant of url (for sr, zh..)
716 * @return \type{\string} the URL
718 public function getLocalURL( $query = '', $variant = false ) {
719 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
720 global $wgVariantArticlePath, $wgContLang, $wgUser;
722 if( is_array( $query ) ) {
723 $query = wfArrayToCGI( $query );
726 // internal links should point to same variant as current page (only anonymous users)
727 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
728 $pref = $wgContLang->getPreferredVariant(false);
729 if($pref != $wgContLang->getCode())
733 if ( $this->isExternal() ) {
734 $url = $this->getFullURL();
736 // This is currently only used for edit section links in the
737 // context of interwiki transclusion. In theory we should
738 // append the query to the end of any existing query string,
739 // but interwiki transclusion is already broken in that case.
743 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
744 if ( $query == '' ) {
745 if( $variant != false && $wgContLang->hasVariants() ) {
746 if( $wgVariantArticlePath == false ) {
747 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
749 $variantArticlePath = $wgVariantArticlePath;
751 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
752 $url = str_replace( '$1', $dbkey, $url );
754 $url = str_replace( '$1', $dbkey, $wgArticlePath );
757 global $wgActionPaths;
760 if( !empty( $wgActionPaths ) &&
761 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
763 $action = urldecode( $matches[2] );
764 if( isset( $wgActionPaths[$action] ) ) {
765 $query = $matches[1];
766 if( isset( $matches[4] ) ) $query .= $matches[4];
767 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
768 if( $query != '' ) $url .= '?' . $query;
771 if ( $url === false ) {
772 if ( $query == '-' ) {
775 $url = "{$wgScript}?title={$dbkey}&{$query}";
779 // FIXME: this causes breakage in various places when we
780 // actually expected a local URL and end up with dupe prefixes.
781 if ($wgRequest->getVal('action') == 'render') {
782 $url = $wgServer . $url;
785 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
790 * Get a URL that's the simplest URL that will be valid to link, locally,
791 * to the current Title. It includes the fragment, but does not include
792 * the server unless action=render is used (or the link is external). If
793 * there's a fragment but the prefixed text is empty, we just return a link
796 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
797 * query string. Keys and values will be escaped.
798 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
799 * for external links. Default is "false" (same variant as current page,
800 * for anonymous users).
801 * @return \type{\string} the URL
803 public function getLinkUrl( $query = array(), $variant = false ) {
804 if( !is_array( $query ) ) {
805 throw new MWException( 'Title::getLinkUrl passed a non-array for '.
808 if( $this->isExternal() ) {
809 return $this->getFullURL( $query );
810 } elseif( $this->getPrefixedText() === ''
811 and $this->getFragment() !== '' ) {
812 return $this->getFragmentForURL();
814 return $this->getLocalURL( $query, $variant )
815 . $this->getFragmentForURL();
820 * Get an HTML-escaped version of the URL form, suitable for
821 * using in a link, without a server name or fragment
822 * @param $query \type{\string} an optional query string
823 * @return \type{\string} the URL
825 public function escapeLocalURL( $query = '' ) {
826 return htmlspecialchars( $this->getLocalURL( $query ) );
830 * Get an HTML-escaped version of the URL form, suitable for
831 * using in a link, including the server name and fragment
833 * @param $query \type{\string} an optional query string
834 * @return \type{\string} the URL
836 public function escapeFullURL( $query = '' ) {
837 return htmlspecialchars( $this->getFullURL( $query ) );
841 * Get the URL form for an internal link.
842 * - Used in various Squid-related code, in case we have a different
843 * internal hostname for the server from the exposed one.
845 * @param $query \type{\string} an optional query string
846 * @param $variant \type{\string} language variant of url (for sr, zh..)
847 * @return \type{\string} the URL
849 public function getInternalURL( $query = '', $variant = false ) {
850 global $wgInternalServer;
851 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
852 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
857 * Get the edit URL for this Title
858 * @return \type{\string} the URL, or a null string if this is an
861 public function getEditURL() {
862 if ( '' != $this->mInterwiki
) { return ''; }
863 $s = $this->getLocalURL( 'action=edit' );
869 * Get the HTML-escaped displayable text form.
870 * Used for the title field in <a> tags.
871 * @return \type{\string} the text, including any prefixes
873 public function getEscapedText() {
874 return htmlspecialchars( $this->getPrefixedText() );
878 * Is this Title interwiki?
879 * @return \type{\bool}
881 public function isExternal() { return ( '' != $this->mInterwiki
); }
884 * Is this page "semi-protected" - the *only* protection is autoconfirm?
886 * @param @action \type{\string} Action to check (default: edit)
887 * @return \type{\bool}
889 public function isSemiProtected( $action = 'edit' ) {
890 if( $this->exists() ) {
891 $restrictions = $this->getRestrictions( $action );
892 if( count( $restrictions ) > 0 ) {
893 foreach( $restrictions as $restriction ) {
894 if( strtolower( $restriction ) != 'autoconfirmed' )
903 # If it doesn't exist, it can't be protected
909 * Does the title correspond to a protected article?
910 * @param $what \type{\string} the action the page is protected from,
911 * by default checks move and edit
912 * @return \type{\bool}
914 public function isProtected( $action = '' ) {
915 global $wgRestrictionLevels, $wgRestrictionTypes;
917 # Special pages have inherent protection
918 if( $this->getNamespace() == NS_SPECIAL
)
921 # Check regular protection levels
922 foreach( $wgRestrictionTypes as $type ){
923 if( $action == $type ||
$action == '' ) {
924 $r = $this->getRestrictions( $type );
925 foreach( $wgRestrictionLevels as $level ) {
926 if( in_array( $level, $r ) && $level != '' ) {
937 * Is $wgUser watching this page?
938 * @return \type{\bool}
940 public function userIsWatching() {
943 if ( is_null( $this->mWatched
) ) {
944 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
945 $this->mWatched
= false;
947 $this->mWatched
= $wgUser->isWatched( $this );
950 return $this->mWatched
;
954 * Can $wgUser perform $action on this page?
955 * This skips potentially expensive cascading permission checks.
957 * Suitable for use for nonessential UI controls in common cases, but
958 * _not_ for functional access control.
960 * May provide false positives, but should never provide a false negative.
962 * @param $action \type{\string} action that permission needs to be checked for
963 * @return \type{\bool}
965 public function quickUserCan( $action ) {
966 return $this->userCan( $action, false );
970 * Determines if $wgUser is unable to edit this page because it has been protected
971 * by $wgNamespaceProtection.
973 * @return \type{\bool}
975 public function isNamespaceProtected() {
976 global $wgNamespaceProtection, $wgUser;
977 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
978 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
979 if( $right != '' && !$wgUser->isAllowed( $right ) )
987 * Can $wgUser perform $action on this page?
988 * @param $action \type{\string} action that permission needs to be checked for
989 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
990 * @return \type{\bool}
992 public function userCan( $action, $doExpensiveQueries = true ) {
994 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
998 * Can $user perform $action on this page?
1000 * FIXME: This *does not* check throttles (User::pingLimiter()).
1002 * @param $action \type{\string}action that permission needs to be checked for
1003 * @param $user \type{User} user to check
1004 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1005 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1006 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1008 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1009 if( !StubObject
::isRealObject( $user ) ) {
1010 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1012 $wgUser->_unstub( '', 5 );
1015 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1019 global $wgEmailConfirmToEdit;
1021 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1022 $errors[] = array( 'confirmedittext' );
1025 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1026 if ( $user->isBlockedFrom( $this ) && $action != 'read' && $action != 'createaccount' ) {
1027 $block = $user->mBlock
;
1029 // This is from OutputPage::blockedPage
1030 // Copied at r23888 by werdna
1032 $id = $user->blockedBy();
1033 $reason = $user->blockedFor();
1034 if( $reason == '' ) {
1035 $reason = wfMsg( 'blockednoreason' );
1039 if ( is_numeric( $id ) ) {
1040 $name = User
::whoIs( $id );
1045 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1046 $blockid = $block->mId
;
1047 $blockExpiry = $user->mBlock
->mExpiry
;
1048 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1050 if ( $blockExpiry == 'infinity' ) {
1051 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1052 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1054 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1055 if ( strpos( $option, ':' ) == false )
1058 list ($show, $value) = explode( ":", $option );
1060 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1061 $blockExpiry = $show;
1066 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1069 $intended = $user->mBlock
->mAddress
;
1071 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1072 $blockid, $blockExpiry, $intended, $blockTimestamp );
1075 // Remove the errors being ignored.
1077 foreach( $errors as $index => $error ) {
1078 $error_key = is_array($error) ?
$error[0] : $error;
1080 if (in_array( $error_key, $ignoreErrors )) {
1081 unset($errors[$index]);
1089 * Can $user perform $action on this page? This is an internal function,
1090 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1091 * checks on wfReadOnly() and blocks)
1093 * @param $action \type{\string} action that permission needs to be checked for
1094 * @param $user \type{User} user to check
1095 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1096 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1098 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
1099 wfProfileIn( __METHOD__
);
1103 // Use getUserPermissionsErrors instead
1104 if( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1105 wfProfileOut( __METHOD__
);
1106 return $result ?
array() : array( array( 'badaccess-group0' ) );
1109 if( !wfRunHooks( 'getUserPermissionsErrors', array(&$this,&$user,$action,&$result) ) ) {
1110 if( is_array($result) && count($result) && !is_array($result[0]) )
1111 $errors[] = $result; # A single array representing an error
1112 else if( is_array($result) && is_array($result[0]) )
1113 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1114 else if( $result !== '' && is_string($result) )
1115 $errors[] = array($result); # A string representing a message-id
1116 else if( $result === false )
1117 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1119 if( $doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array(&$this,&$user,$action,&$result) ) ) {
1120 if( is_array($result) && count($result) && !is_array($result[0]) )
1121 $errors[] = $result; # A single array representing an error
1122 else if( is_array($result) && is_array($result[0]) )
1123 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1124 else if( $result !== '' && is_string($result) )
1125 $errors[] = array($result); # A string representing a message-id
1126 else if( $result === false )
1127 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1131 $specialOKActions = array( 'createaccount', 'execute' );
1132 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1133 $errors[] = array('ns-specialprotected');
1136 if( $this->isNamespaceProtected() ) {
1137 $ns = $this->getNamespace() == NS_MAIN ?
1138 wfMsg( 'nstab-main' ) : $this->getNsText();
1139 $errors[] = NS_MEDIAWIKI
== $this->mNamespace ?
1140 array('protectedinterface') : array( 'namespaceprotected', $ns );
1143 # protect css/js subpages of user pages
1144 # XXX: this might be better using restrictions
1145 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1146 if( $this->isCssJsSubpage() && !$user->isAllowed('editusercssjs')
1147 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1149 $errors[] = array('customcssjsprotected');
1152 if( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1153 # We /could/ use the protection level on the source page, but it's fairly ugly
1154 # as we have to establish a precedence hierarchy for pages included by multiple
1155 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1156 # as they could remove the protection anyway.
1157 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1158 # Cascading protection depends on more than this page...
1159 # Several cascading protected pages may include this page...
1160 # Check each cascading level
1161 # This is only for protection restrictions, not for all actions
1162 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1163 foreach( $restrictions[$action] as $right ) {
1164 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1165 if( '' != $right && !$user->isAllowed( $right ) ) {
1167 foreach( $cascadingSources as $page )
1168 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1169 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1175 foreach( $this->getRestrictions($action) as $right ) {
1176 // Backwards compatibility, rewrite sysop -> protect
1177 if( $right == 'sysop' ) {
1180 if( '' != $right && !$user->isAllowed( $right ) ) {
1181 // Users with 'editprotected' permission can edit protected pages
1182 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1183 // Users with 'editprotected' permission cannot edit protected pages
1184 // with cascading option turned on.
1185 if( $this->mCascadeRestriction
) {
1186 $errors[] = array( 'protectedpagetext', $right );
1188 // Nothing, user can edit!
1191 $errors[] = array( 'protectedpagetext', $right );
1196 if( $action == 'protect' ) {
1197 if( $this->getUserPermissionsErrors('edit', $user) != array() ) {
1198 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1202 if( $action == 'create' ) {
1203 $title_protection = $this->getTitleProtection();
1204 if( is_array($title_protection) ) {
1205 extract($title_protection); // is this extract() really needed?
1207 if( $pt_create_perm == 'sysop' ) {
1208 $pt_create_perm = 'protect'; // B/C
1210 if( $pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm) ) {
1211 $errors[] = array( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1215 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1216 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) )
1218 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1220 } elseif( $action == 'move' ) {
1221 if( !$user->isAllowed( 'move' ) ) {
1222 // User can't move anything
1223 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1224 } elseif( !$user->isAllowed( 'move-rootuserpages' )
1225 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1227 // Show user page-specific message only if the user can move other pages
1228 $errors[] = array( 'cant-move-user-page' );
1230 // Check for immobile pages
1231 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1232 // Specific message for this case
1233 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1234 } elseif( !$this->isMovable() ) {
1235 // Less specific message for rarer cases
1236 $errors[] = array( 'immobile-page' );
1238 } elseif( $action == 'move-target' ) {
1239 if( !$user->isAllowed( 'move' ) ) {
1240 // User can't move anything
1241 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1242 } elseif( !$user->isAllowed( 'move-rootuserpages' )
1243 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1245 // Show user page-specific message only if the user can move other pages
1246 $errors[] = array( 'cant-move-to-user-page' );
1248 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1249 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1250 } elseif( !$this->isMovable() ) {
1251 $errors[] = array( 'immobile-target-page' );
1253 } elseif( !$user->isAllowed( $action ) ) {
1255 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1256 User
::getGroupsWithPermission( $action ) );
1258 $return = array( 'badaccess-groups',
1259 array( implode( ', ', $groups ), count( $groups ) ) );
1261 $return = array( "badaccess-group0" );
1263 $errors[] = $return;
1266 wfProfileOut( __METHOD__
);
1271 * Is this title subject to title protection?
1272 * @return \type{\mixed} An associative array representing any existent title
1273 * protection, or false if there's none.
1275 private function getTitleProtection() {
1276 // Can't protect pages in special namespaces
1277 if ( $this->getNamespace() < 0 ) {
1281 $dbr = wfGetDB( DB_SLAVE
);
1282 $res = $dbr->select( 'protected_titles', '*',
1283 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1286 if ($row = $dbr->fetchRow( $res )) {
1294 * Update the title protection status
1295 * @param $create_perm \type{\string} Permission required for creation
1296 * @param $reason \type{\string} Reason for protection
1297 * @param $expiry \type{\string} Expiry timestamp
1299 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1300 global $wgUser,$wgContLang;
1302 if ($create_perm == implode(',',$this->getRestrictions('create'))
1303 && $expiry == $this->mRestrictionsExpiry
['create']) {
1308 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1310 $dbw = wfGetDB( DB_MASTER
);
1312 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1314 $expiry_description = '';
1315 if ( $encodedExpiry != 'infinity' ) {
1316 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1319 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1322 # Update protection table
1323 if ($create_perm != '' ) {
1324 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1325 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1326 , 'pt_create_perm' => $create_perm
1327 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1328 , 'pt_expiry' => $encodedExpiry
1329 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1331 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1332 'pt_title' => $title ), __METHOD__
);
1334 # Update the protection log
1335 $log = new LogPage( 'protect' );
1337 if( $create_perm ) {
1338 $params = array("[create=$create_perm] $expiry_description",'');
1339 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason ), $params );
1341 $log->addEntry( 'unprotect', $this, $reason );
1348 * Remove any title protection due to page existing
1350 public function deleteTitleProtection() {
1351 $dbw = wfGetDB( DB_MASTER
);
1353 $dbw->delete( 'protected_titles',
1354 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1359 * Can $wgUser edit this page?
1360 * @return \type{\bool} TRUE or FALSE
1361 * @deprecated use userCan('edit')
1363 public function userCanEdit( $doExpensiveQueries = true ) {
1364 return $this->userCan( 'edit', $doExpensiveQueries );
1368 * Can $wgUser create this page?
1369 * @return \type{\bool} TRUE or FALSE
1370 * @deprecated use userCan('create')
1372 public function userCanCreate( $doExpensiveQueries = true ) {
1373 return $this->userCan( 'create', $doExpensiveQueries );
1377 * Can $wgUser move this page?
1378 * @return \type{\bool} TRUE or FALSE
1379 * @deprecated use userCan('move')
1381 public function userCanMove( $doExpensiveQueries = true ) {
1382 return $this->userCan( 'move', $doExpensiveQueries );
1386 * Would anybody with sufficient privileges be able to move this page?
1387 * Some pages just aren't movable.
1389 * @return \type{\bool} TRUE or FALSE
1391 public function isMovable() {
1392 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1396 * Can $wgUser read this page?
1397 * @return \type{\bool} TRUE or FALSE
1398 * @todo fold these checks into userCan()
1400 public function userCanRead() {
1401 global $wgUser, $wgGroupPermissions;
1404 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1405 if ( $result !== null ) {
1409 # Shortcut for public wikis, allows skipping quite a bit of code
1410 if ($wgGroupPermissions['*']['read'])
1413 if( $wgUser->isAllowed( 'read' ) ) {
1416 global $wgWhitelistRead;
1419 * Always grant access to the login page.
1420 * Even anons need to be able to log in.
1422 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1427 * Bail out if there isn't whitelist
1429 if( !is_array($wgWhitelistRead) ) {
1434 * Check for explicit whitelisting
1436 $name = $this->getPrefixedText();
1437 $dbName = $this->getPrefixedDBKey();
1438 // Check with and without underscores
1439 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1443 * Old settings might have the title prefixed with
1444 * a colon for main-namespace pages
1446 if( $this->getNamespace() == NS_MAIN
) {
1447 if( in_array( ':' . $name, $wgWhitelistRead ) )
1452 * If it's a special page, ditch the subpage bit
1455 if( $this->getNamespace() == NS_SPECIAL
) {
1456 $name = $this->getDBkey();
1457 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1458 if ( $name === false ) {
1459 # Invalid special page, but we show standard login required message
1463 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1464 if( in_array( $pure, $wgWhitelistRead, true ) )
1473 * Is this a talk page of some sort?
1474 * @return \type{\bool} TRUE or FALSE
1476 public function isTalkPage() {
1477 return MWNamespace
::isTalk( $this->getNamespace() );
1481 * Is this a subpage?
1482 * @return \type{\bool} TRUE or FALSE
1484 public function isSubpage() {
1485 return MWNamespace
::hasSubpages( $this->mNamespace
)
1486 ?
strpos( $this->getText(), '/' ) !== false
1491 * Does this have subpages? (Warning, usually requires an extra DB query.)
1492 * @return \type{\bool} TRUE or FALSE
1494 public function hasSubpages() {
1495 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1500 # We dynamically add a member variable for the purpose of this method
1501 # alone to cache the result. There's no point in having it hanging
1502 # around uninitialized in every Title object; therefore we only add it
1503 # if needed and don't declare it statically.
1504 if( isset( $this->mHasSubpages
) ) {
1505 return $this->mHasSubpages
;
1508 $db = wfGetDB( DB_SLAVE
);
1509 return $this->mHasSubpages
= (bool)$db->selectField( 'page', '1',
1510 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1511 . $db->escapeLike( $this->mDbkeyform
) . "/%'",
1517 * Could this page contain custom CSS or JavaScript, based
1520 * @return \type{\bool} TRUE or FALSE
1522 public function isCssOrJsPage() {
1523 return $this->mNamespace
== NS_MEDIAWIKI
1524 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1528 * Is this a .css or .js subpage of a user page?
1529 * @return \type{\bool} TRUE or FALSE
1531 public function isCssJsSubpage() {
1532 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1535 * Is this a *valid* .css or .js subpage of a user page?
1536 * Check that the corresponding skin exists
1537 * @return \type{\bool} TRUE or FALSE
1539 public function isValidCssJsSubpage() {
1540 if ( $this->isCssJsSubpage() ) {
1541 $skinNames = Skin
::getSkinNames();
1542 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1548 * Trim down a .css or .js subpage title to get the corresponding skin name
1550 public function getSkinFromCssJsSubpage() {
1551 $subpage = explode( '/', $this->mTextform
);
1552 $subpage = $subpage[ count( $subpage ) - 1 ];
1553 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1556 * Is this a .css subpage of a user page?
1557 * @return \type{\bool} TRUE or FALSE
1559 public function isCssSubpage() {
1560 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1563 * Is this a .js subpage of a user page?
1564 * @return \type{\bool} TRUE or FALSE
1566 public function isJsSubpage() {
1567 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1570 * Protect css/js subpages of user pages: can $wgUser edit
1573 * @return \type{\bool} TRUE or FALSE
1574 * @todo XXX: this might be better using restrictions
1576 public function userCanEditCssJsSubpage() {
1578 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1582 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1584 * @return \type{\bool} If the page is subject to cascading restrictions.
1586 public function isCascadeProtected() {
1587 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1588 return ( $sources > 0 );
1592 * Cascading protection: Get the source of any cascading restrictions on this page.
1594 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1595 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1596 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1597 * The restriction array is an array of each type, each of which contains an array of unique groups.
1599 public function getCascadeProtectionSources( $get_pages = true ) {
1600 global $wgRestrictionTypes;
1602 # Define our dimension of restrictions types
1603 $pagerestrictions = array();
1604 foreach( $wgRestrictionTypes as $action )
1605 $pagerestrictions[$action] = array();
1607 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1608 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1609 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1610 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1613 wfProfileIn( __METHOD__
);
1615 $dbr = wfGetDB( DB_SLAVE
);
1617 if ( $this->getNamespace() == NS_FILE
) {
1618 $tables = array ('imagelinks', 'page_restrictions');
1619 $where_clauses = array(
1620 'il_to' => $this->getDBkey(),
1622 'pr_cascade' => 1 );
1624 $tables = array ('templatelinks', 'page_restrictions');
1625 $where_clauses = array(
1626 'tl_namespace' => $this->getNamespace(),
1627 'tl_title' => $this->getDBkey(),
1629 'pr_cascade' => 1 );
1633 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1634 $where_clauses[] = 'page_id=pr_page';
1637 $cols = array( 'pr_expiry' );
1640 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1642 $sources = $get_pages ?
array() : false;
1643 $now = wfTimestampNow();
1644 $purgeExpired = false;
1646 foreach( $res as $row ) {
1647 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1648 if( $expiry > $now ) {
1650 $page_id = $row->pr_page
;
1651 $page_ns = $row->page_namespace
;
1652 $page_title = $row->page_title
;
1653 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1654 # Add groups needed for each restriction type if its not already there
1655 # Make sure this restriction type still exists
1656 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1657 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1663 // Trigger lazy purge of expired restrictions from the db
1664 $purgeExpired = true;
1667 if( $purgeExpired ) {
1668 Title
::purgeExpiredRestrictions();
1671 wfProfileOut( __METHOD__
);
1674 $this->mCascadeSources
= $sources;
1675 $this->mCascadingRestrictions
= $pagerestrictions;
1677 $this->mHasCascadingRestrictions
= $sources;
1679 return array( $sources, $pagerestrictions );
1682 function areRestrictionsCascading() {
1683 if (!$this->mRestrictionsLoaded
) {
1684 $this->loadRestrictions();
1687 return $this->mCascadeRestriction
;
1691 * Loads a string into mRestrictions array
1692 * @param $res \type{Resource} restrictions as an SQL result.
1694 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1695 global $wgRestrictionTypes;
1696 $dbr = wfGetDB( DB_SLAVE
);
1698 foreach( $wgRestrictionTypes as $type ){
1699 $this->mRestrictions
[$type] = array();
1700 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry('');
1703 $this->mCascadeRestriction
= false;
1705 # Backwards-compatibility: also load the restrictions from the page record (old format).
1707 if ( $oldFashionedRestrictions === NULL ) {
1708 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1709 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1712 if ($oldFashionedRestrictions != '') {
1714 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1715 $temp = explode( '=', trim( $restrict ) );
1716 if(count($temp) == 1) {
1717 // old old format should be treated as edit/move restriction
1718 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1719 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1721 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1725 $this->mOldRestrictions
= true;
1729 if( $dbr->numRows( $res ) ) {
1730 # Current system - load second to make them override.
1731 $now = wfTimestampNow();
1732 $purgeExpired = false;
1734 foreach( $res as $row ) {
1735 # Cycle through all the restrictions.
1737 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1738 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1741 // This code should be refactored, now that it's being used more generally,
1742 // But I don't really see any harm in leaving it in Block for now -werdna
1743 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1745 // Only apply the restrictions if they haven't expired!
1746 if ( !$expiry ||
$expiry > $now ) {
1747 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
1748 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1750 $this->mCascadeRestriction |
= $row->pr_cascade
;
1752 // Trigger a lazy purge of expired restrictions
1753 $purgeExpired = true;
1757 if( $purgeExpired ) {
1758 Title
::purgeExpiredRestrictions();
1762 $this->mRestrictionsLoaded
= true;
1766 * Load restrictions from the page_restrictions table
1768 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1769 if( !$this->mRestrictionsLoaded
) {
1770 if ($this->exists()) {
1771 $dbr = wfGetDB( DB_SLAVE
);
1773 $res = $dbr->select( 'page_restrictions', '*',
1774 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1776 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1778 $title_protection = $this->getTitleProtection();
1780 if (is_array($title_protection)) {
1781 extract($title_protection);
1783 $now = wfTimestampNow();
1784 $expiry = Block
::decodeExpiry($pt_expiry);
1786 if (!$expiry ||
$expiry > $now) {
1787 // Apply the restrictions
1788 $this->mRestrictionsExpiry
['create'] = $expiry;
1789 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1790 } else { // Get rid of the old restrictions
1791 Title
::purgeExpiredRestrictions();
1794 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry('');
1796 $this->mRestrictionsLoaded
= true;
1802 * Purge expired restrictions from the page_restrictions table
1804 static function purgeExpiredRestrictions() {
1805 $dbw = wfGetDB( DB_MASTER
);
1806 $dbw->delete( 'page_restrictions',
1807 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1810 $dbw->delete( 'protected_titles',
1811 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1816 * Accessor/initialisation for mRestrictions
1818 * @param $action \type{\string} action that permission needs to be checked for
1819 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
1821 public function getRestrictions( $action ) {
1822 if( !$this->mRestrictionsLoaded
) {
1823 $this->loadRestrictions();
1825 return isset( $this->mRestrictions
[$action] )
1826 ?
$this->mRestrictions
[$action]
1831 * Get the expiry time for the restriction against a given action
1832 * @return 14-char timestamp, or 'infinity' if the page is protected forever
1833 * or not protected at all, or false if the action is not recognised.
1835 public function getRestrictionExpiry( $action ) {
1836 if( !$this->mRestrictionsLoaded
) {
1837 $this->loadRestrictions();
1839 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
1843 * Is there a version of this page in the deletion archive?
1844 * @return \type{\int} the number of archived revisions
1846 public function isDeleted() {
1847 $fname = 'Title::isDeleted';
1848 if ( $this->getNamespace() < 0 ) {
1851 $dbr = wfGetDB( DB_SLAVE
);
1852 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1853 'ar_title' => $this->getDBkey() ), $fname );
1854 if( $this->getNamespace() == NS_FILE
) {
1855 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1856 array( 'fa_name' => $this->getDBkey() ), $fname );
1863 * Get the article ID for this Title from the link cache,
1864 * adding it if necessary
1865 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
1867 * @return \type{\int} the ID
1869 public function getArticleID( $flags = 0 ) {
1870 if( $this->getNamespace() < 0 ) {
1871 return $this->mArticleID
= 0;
1873 $linkCache = LinkCache
::singleton();
1874 if( $flags & GAID_FOR_UPDATE
) {
1875 $oldUpdate = $linkCache->forUpdate( true );
1876 $linkCache->clearLink( $this );
1877 $this->mArticleID
= $linkCache->addLinkObj( $this );
1878 $linkCache->forUpdate( $oldUpdate );
1880 if( -1 == $this->mArticleID
) {
1881 $this->mArticleID
= $linkCache->addLinkObj( $this );
1884 return $this->mArticleID
;
1888 * Is this an article that is a redirect page?
1889 * Uses link cache, adding it if necessary
1890 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1891 * @return \type{\bool}
1893 public function isRedirect( $flags = 0 ) {
1894 if( !is_null($this->mRedirect
) )
1895 return $this->mRedirect
;
1896 # Calling getArticleID() loads the field from cache as needed
1897 if( !$this->getArticleID($flags) ) {
1898 return $this->mRedirect
= false;
1900 $linkCache = LinkCache
::singleton();
1901 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1903 return $this->mRedirect
;
1907 * What is the length of this page?
1908 * Uses link cache, adding it if necessary
1909 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1910 * @return \type{\bool}
1912 public function getLength( $flags = 0 ) {
1913 if( $this->mLength
!= -1 )
1914 return $this->mLength
;
1915 # Calling getArticleID() loads the field from cache as needed
1916 if( !$this->getArticleID($flags) ) {
1917 return $this->mLength
= 0;
1919 $linkCache = LinkCache
::singleton();
1920 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1922 return $this->mLength
;
1926 * What is the page_latest field for this page?
1927 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1928 * @return \type{\int}
1930 public function getLatestRevID( $flags = 0 ) {
1931 if( $this->mLatestID
!== false )
1932 return $this->mLatestID
;
1934 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
1935 $this->mLatestID
= $db->selectField( 'page', 'page_latest', $this->pageCond(), __METHOD__
);
1936 return $this->mLatestID
;
1940 * This clears some fields in this object, and clears any associated
1941 * keys in the "bad links" section of the link cache.
1943 * - This is called from Article::insertNewArticle() to allow
1944 * loading of the new page_id. It's also called from
1945 * Article::doDeleteArticle()
1947 * @param $newid \type{\int} the new Article ID
1949 public function resetArticleID( $newid ) {
1950 $linkCache = LinkCache
::singleton();
1951 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1953 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1954 else { $this->mArticleID
= $newid; }
1955 $this->mRestrictionsLoaded
= false;
1956 $this->mRestrictions
= array();
1960 * Updates page_touched for this page; called from LinksUpdate.php
1961 * @return \type{\bool} true if the update succeded
1963 public function invalidateCache() {
1964 global $wgUseFileCache;
1965 if( wfReadOnly() ) {
1968 $dbw = wfGetDB( DB_MASTER
);
1969 $success = $dbw->update( 'page',
1970 array( 'page_touched' => $dbw->timestamp() ),
1974 if( $wgUseFileCache) {
1975 $cache = new HTMLFileCache( $this );
1976 @unlink
( $cache->fileCacheName() );
1982 * Prefix some arbitrary text with the namespace or interwiki prefix
1985 * @param $name \type{\string} the text
1986 * @return \type{\string} the prefixed text
1989 /* private */ function prefix( $name ) {
1991 if ( '' != $this->mInterwiki
) {
1992 $p = $this->mInterwiki
. ':';
1994 if ( 0 != $this->mNamespace
) {
1995 $p .= $this->getNsText() . ':';
2001 * Secure and split - main initialisation function for this object
2003 * Assumes that mDbkeyform has been set, and is urldecoded
2004 * and uses underscores, but not otherwise munged. This function
2005 * removes illegal characters, splits off the interwiki and
2006 * namespace prefixes, sets the other forms, and canonicalizes
2008 * @return \type{\bool} true on success
2010 private function secureAndSplit() {
2011 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2014 static $rxTc = false;
2016 # Matching titles will be held as illegal.
2018 # Any character not allowed is forbidden...
2019 '[^' . Title
::legalChars() . ']' .
2020 # URL percent encoding sequences interfere with the ability
2021 # to round-trip titles -- you can't link to them consistently.
2022 '|%[0-9A-Fa-f]{2}' .
2023 # XML/HTML character references produce similar issues.
2024 '|&[A-Za-z0-9\x80-\xff]+;' .
2026 '|&#x[0-9A-Fa-f]+;' .
2030 $this->mInterwiki
= $this->mFragment
= '';
2031 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2033 $dbkey = $this->mDbkeyform
;
2035 # Strip Unicode bidi override characters.
2036 # Sometimes they slip into cut-n-pasted page titles, where the
2037 # override chars get included in list displays.
2038 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2040 # Clean up whitespace
2042 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2043 $dbkey = trim( $dbkey, '_' );
2045 if ( '' == $dbkey ) {
2049 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2050 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2054 $this->mDbkeyform
= $dbkey;
2056 # Initial colon indicates main namespace rather than specified default
2057 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2058 if ( ':' == $dbkey{0} ) {
2059 $this->mNamespace
= NS_MAIN
;
2060 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2061 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2064 # Namespace or interwiki prefix
2068 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2070 if ( $ns = $wgContLang->getNsIndex( $p )) {
2071 # Ordinary namespace
2073 $this->mNamespace
= $ns;
2074 } elseif( Interwiki
::isValidInterwiki( $p ) ) {
2076 # Can't make a local interwiki link to an interwiki link.
2077 # That's just crazy!
2083 $this->mInterwiki
= $wgContLang->lc( $p );
2085 # Redundant interwiki prefix to the local wiki
2086 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2087 if( $dbkey == '' ) {
2088 # Can't have an empty self-link
2091 $this->mInterwiki
= '';
2093 # Do another namespace split...
2097 # If there's an initial colon after the interwiki, that also
2098 # resets the default namespace
2099 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2100 $this->mNamespace
= NS_MAIN
;
2101 $dbkey = substr( $dbkey, 1 );
2104 # If there's no recognized interwiki or namespace,
2105 # then let the colon expression be part of the title.
2110 # We already know that some pages won't be in the database!
2112 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2113 $this->mArticleID
= 0;
2115 $fragment = strstr( $dbkey, '#' );
2116 if ( false !== $fragment ) {
2117 $this->setFragment( $fragment );
2118 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2119 # remove whitespace again: prevents "Foo_bar_#"
2120 # becoming "Foo_bar_"
2121 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2124 # Reject illegal characters.
2126 if( preg_match( $rxTc, $dbkey ) ) {
2131 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2132 * reachable due to the way web browsers deal with 'relative' URLs.
2133 * Also, they conflict with subpage syntax. Forbid them explicitly.
2135 if ( strpos( $dbkey, '.' ) !== false &&
2136 ( $dbkey === '.' ||
$dbkey === '..' ||
2137 strpos( $dbkey, './' ) === 0 ||
2138 strpos( $dbkey, '../' ) === 0 ||
2139 strpos( $dbkey, '/./' ) !== false ||
2140 strpos( $dbkey, '/../' ) !== false ||
2141 substr( $dbkey, -2 ) == '/.' ||
2142 substr( $dbkey, -3 ) == '/..' ) )
2148 * Magic tilde sequences? Nu-uh!
2150 if( strpos( $dbkey, '~~~' ) !== false ) {
2155 * Limit the size of titles to 255 bytes.
2156 * This is typically the size of the underlying database field.
2157 * We make an exception for special pages, which don't need to be stored
2158 * in the database, and may edge over 255 bytes due to subpage syntax
2159 * for long titles, e.g. [[Special:Block/Long name]]
2161 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2162 strlen( $dbkey ) > 512 )
2168 * Normally, all wiki links are forced to have
2169 * an initial capital letter so [[foo]] and [[Foo]]
2170 * point to the same place.
2172 * Don't force it for interwikis, since the other
2173 * site might be case-sensitive.
2175 $this->mUserCaseDBKey
= $dbkey;
2176 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2177 $dbkey = $wgContLang->ucfirst( $dbkey );
2181 * Can't make a link to a namespace alone...
2182 * "empty" local links can only be self-links
2183 * with a fragment identifier.
2186 $this->mInterwiki
== '' &&
2187 $this->mNamespace
!= NS_MAIN
) {
2190 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2191 // IP names are not allowed for accounts, and can only be referring to
2192 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2193 // there are numerous ways to present the same IP. Having sp:contribs scan
2194 // them all is silly and having some show the edits and others not is
2195 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2196 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2197 IP
::sanitizeIP( $dbkey ) : $dbkey;
2198 // Any remaining initial :s are illegal.
2199 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2204 $this->mDbkeyform
= $dbkey;
2205 $this->mUrlform
= wfUrlencode( $dbkey );
2207 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2213 * Set the fragment for this title. Removes the first character from the
2214 * specified fragment before setting, so it assumes you're passing it with
2217 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2218 * Still in active use privately.
2220 * @param $fragment \type{\string} text
2222 public function setFragment( $fragment ) {
2223 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2227 * Get a Title object associated with the talk page of this article
2228 * @return \type{Title} the object for the talk page
2230 public function getTalkPage() {
2231 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2235 * Get a title object associated with the subject page of this
2238 * @return \type{Title} the object for the subject page
2240 public function getSubjectPage() {
2241 // Is this the same title?
2242 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2243 if( $this->getNamespace() == $subjectNS ) {
2246 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2250 * Get an array of Title objects linking to this Title
2251 * Also stores the IDs in the link cache.
2253 * WARNING: do not use this function on arbitrary user-supplied titles!
2254 * On heavily-used templates it will max out the memory.
2256 * @param $options \type{\string} may be FOR UPDATE
2257 * @return \type{\arrayof{Title}} the Title objects linking here
2259 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2260 $linkCache = LinkCache
::singleton();
2263 $db = wfGetDB( DB_MASTER
);
2265 $db = wfGetDB( DB_SLAVE
);
2268 $res = $db->select( array( 'page', $table ),
2269 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2271 "{$prefix}_from=page_id",
2272 "{$prefix}_namespace" => $this->getNamespace(),
2273 "{$prefix}_title" => $this->getDBkey() ),
2278 if ( $db->numRows( $res ) ) {
2279 foreach( $res as $row ) {
2280 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2281 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2282 $retVal[] = $titleObj;
2286 $db->freeResult( $res );
2291 * Get an array of Title objects using this Title as a template
2292 * Also stores the IDs in the link cache.
2294 * WARNING: do not use this function on arbitrary user-supplied titles!
2295 * On heavily-used templates it will max out the memory.
2297 * @param $options \type{\string} may be FOR UPDATE
2298 * @return \type{\arrayof{Title}} the Title objects linking here
2300 public function getTemplateLinksTo( $options = '' ) {
2301 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2305 * Get an array of Title objects referring to non-existent articles linked from this page
2307 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2308 * @param $options \type{\string} may be FOR UPDATE
2309 * @return \type{\arrayof{Title}} the Title objects
2311 public function getBrokenLinksFrom( $options = '' ) {
2312 if ( $this->getArticleId() == 0 ) {
2313 # All links from article ID 0 are false positives
2318 $db = wfGetDB( DB_MASTER
);
2320 $db = wfGetDB( DB_SLAVE
);
2323 $res = $db->safeQuery(
2324 "SELECT pl_namespace, pl_title
2327 ON pl_namespace=page_namespace
2328 AND pl_title=page_title
2330 AND page_namespace IS NULL
2332 $db->tableName( 'pagelinks' ),
2333 $db->tableName( 'page' ),
2334 $this->getArticleId(),
2338 if ( $db->numRows( $res ) ) {
2339 foreach( $res as $row ) {
2340 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2343 $db->freeResult( $res );
2349 * Get a list of URLs to purge from the Squid cache when this
2352 * @return \type{\arrayof{\string}} the URLs
2354 public function getSquidURLs() {
2358 $this->getInternalURL(),
2359 $this->getInternalURL( 'action=history' )
2362 // purge variant urls as well
2363 if($wgContLang->hasVariants()){
2364 $variants = $wgContLang->getVariants();
2365 foreach($variants as $vCode){
2366 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2367 $urls[] = $this->getInternalURL('',$vCode);
2375 * Purge all applicable Squid URLs
2377 public function purgeSquid() {
2379 if ( $wgUseSquid ) {
2380 $urls = $this->getSquidURLs();
2381 $u = new SquidUpdate( $urls );
2387 * Move this page without authentication
2388 * @param &$nt \type{Title} the new page Title
2390 public function moveNoAuth( &$nt ) {
2391 return $this->moveTo( $nt, false );
2395 * Check whether a given move operation would be valid.
2396 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2397 * @param &$nt \type{Title} the new title
2398 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2400 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2401 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2403 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2408 // Normally we'd add this to $errors, but we'll get
2409 // lots of syntax errors if $nt is not an object
2410 return array(array('badtitletext'));
2412 if( $this->equals( $nt ) ) {
2413 $errors[] = array('selfmove');
2415 if( !$this->isMovable() ) {
2416 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2418 if ( !$nt->isMovable() ) {
2419 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2422 $oldid = $this->getArticleID();
2423 $newid = $nt->getArticleID();
2425 if ( strlen( $nt->getDBkey() ) < 1 ) {
2426 $errors[] = array('articleexists');
2428 if ( ( '' == $this->getDBkey() ) ||
2430 ( '' == $nt->getDBkey() ) ) {
2431 $errors[] = array('badarticleerror');
2434 // Image-specific checks
2435 if( $this->getNamespace() == NS_FILE
) {
2436 $file = wfLocalFile( $this );
2437 if( $file->exists() ) {
2438 if( $nt->getNamespace() != NS_FILE
) {
2439 $errors[] = array('imagenocrossnamespace');
2441 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2442 $errors[] = array('imageinvalidfilename');
2444 if( !File
::checkExtensionCompatibility( $file, $nt->getDBKey() ) ) {
2445 $errors[] = array('imagetypemismatch');
2451 $errors = wfMergeErrorArrays( $errors,
2452 $this->getUserPermissionsErrors('move', $wgUser),
2453 $this->getUserPermissionsErrors('edit', $wgUser),
2454 $nt->getUserPermissionsErrors('move-target', $wgUser),
2455 $nt->getUserPermissionsErrors('edit', $wgUser) );
2458 $match = EditPage
::matchSpamRegex( $reason );
2459 if( $match !== false ) {
2460 // This is kind of lame, won't display nice
2461 $errors[] = array('spamprotectiontext');
2465 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2466 $errors[] = array('hookaborted', $err);
2469 # The move is allowed only if (1) the target doesn't exist, or
2470 # (2) the target is a redirect to the source, and has no history
2471 # (so we can undo bad moves right after they're done).
2473 if ( 0 != $newid ) { # Target exists; check for validity
2474 if ( ! $this->isValidMoveTarget( $nt ) ) {
2475 $errors[] = array('articleexists');
2478 $tp = $nt->getTitleProtection();
2479 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2480 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2481 $errors[] = array('cantmove-titleprotected');
2490 * Move a title to a new location
2491 * @param &$nt \type{Title} the new title
2492 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2494 * @param $reason \type{\string} The reason for the move
2495 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2496 * Ignored if the user doesn't have the suppressredirect right.
2497 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2499 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2500 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2501 if( is_array( $err ) ) {
2505 $pageid = $this->getArticleID();
2506 $protected = $this->isProtected();
2507 if( $nt->exists() ) {
2508 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2509 $pageCountChange = ($createRedirect ?
0 : -1);
2510 } else { # Target didn't exist, do normal move.
2511 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2512 $pageCountChange = ($createRedirect ?
1 : 0);
2515 if( is_array( $err ) ) {
2518 $redirid = $this->getArticleID();
2520 // Category memberships include a sort key which may be customized.
2521 // If it's left as the default (the page title), we need to update
2522 // the sort key to match the new title.
2524 // Be careful to avoid resetting cl_timestamp, which may disturb
2525 // time-based lists on some sites.
2527 // Warning -- if the sort key is *explicitly* set to the old title,
2528 // we can't actually distinguish it from a default here, and it'll
2529 // be set to the new title even though it really shouldn't.
2530 // It'll get corrected on the next edit, but resetting cl_timestamp.
2531 $dbw = wfGetDB( DB_MASTER
);
2532 $dbw->update( 'categorylinks',
2534 'cl_sortkey' => $nt->getPrefixedText(),
2535 'cl_timestamp=cl_timestamp' ),
2537 'cl_from' => $pageid,
2538 'cl_sortkey' => $this->getPrefixedText() ),
2542 # Protect the redirect title as the title used to be...
2543 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2545 'pr_page' => $redirid,
2546 'pr_type' => 'pr_type',
2547 'pr_level' => 'pr_level',
2548 'pr_cascade' => 'pr_cascade',
2549 'pr_user' => 'pr_user',
2550 'pr_expiry' => 'pr_expiry'
2552 array( 'pr_page' => $pageid ),
2556 # Update the protection log
2557 $log = new LogPage( 'protect' );
2558 $comment = wfMsgForContent('prot_1movedto2',$this->getPrefixedText(), $nt->getPrefixedText() );
2559 if( $reason ) $comment .= ': ' . $reason;
2560 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2564 $oldnamespace = $this->getNamespace() & ~
1;
2565 $newnamespace = $nt->getNamespace() & ~
1;
2566 $oldtitle = $this->getDBkey();
2567 $newtitle = $nt->getDBkey();
2569 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2570 WatchedItem
::duplicateEntries( $this, $nt );
2573 # Update search engine
2574 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2576 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2580 if( $this->isContentPage() && !$nt->isContentPage() ) {
2581 # No longer a content page
2582 # Not viewed, edited, removing
2583 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2584 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2585 # Now a content page
2586 # Not viewed, edited, adding
2587 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2588 } elseif( $pageCountChange ) {
2590 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2597 # Update message cache for interface messages
2598 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2599 global $wgMessageCache;
2600 $oldarticle = new Article( $this );
2601 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2602 $newarticle = new Article( $nt );
2603 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2607 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2612 * Move page to a title which is at present a redirect to the
2615 * @param &$nt \type{Title} the page to move to, which should currently
2617 * @param $reason \type{\string} The reason for the move
2618 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2619 * Ignored if the user doesn't have the suppressredirect right
2621 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2622 global $wgUseSquid, $wgUser;
2623 $fname = 'Title::moveOverExistingRedirect';
2624 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2627 $comment .= ": $reason";
2630 $now = wfTimestampNow();
2631 $newid = $nt->getArticleID();
2632 $oldid = $this->getArticleID();
2633 $latest = $this->getLatestRevID();
2635 $dbw = wfGetDB( DB_MASTER
);
2637 # Delete the old redirect. We don't save it to history since
2638 # by definition if we've got here it's rather uninteresting.
2639 # We have to remove it so that the next step doesn't trigger
2640 # a conflict on the unique namespace+title index...
2641 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2642 if ( !$dbw->cascadingDeletes() ) {
2643 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2644 global $wgUseTrackbacks;
2645 if ($wgUseTrackbacks)
2646 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2647 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2648 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2649 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2650 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2651 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2652 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2653 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2656 # Save a null revision in the page's history notifying of the move
2657 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2658 $nullRevId = $nullRevision->insertOn( $dbw );
2660 $article = new Article( $this );
2661 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
2663 # Change the name of the target page:
2664 $dbw->update( 'page',
2666 'page_touched' => $dbw->timestamp($now),
2667 'page_namespace' => $nt->getNamespace(),
2668 'page_title' => $nt->getDBkey(),
2669 'page_latest' => $nullRevId,
2671 /* WHERE */ array( 'page_id' => $oldid ),
2674 $nt->resetArticleID( $oldid );
2676 # Recreate the redirect, this time in the other direction.
2677 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2678 $mwRedir = MagicWord
::get( 'redirect' );
2679 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2680 $redirectArticle = new Article( $this );
2681 $newid = $redirectArticle->insertOn( $dbw );
2682 $redirectRevision = new Revision( array(
2684 'comment' => $comment,
2685 'text' => $redirectText ) );
2686 $redirectRevision->insertOn( $dbw );
2687 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2689 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
2691 # Now, we record the link from the redirect to the new title.
2692 # It should have no other outgoing links...
2693 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2694 $dbw->insert( 'pagelinks',
2696 'pl_from' => $newid,
2697 'pl_namespace' => $nt->getNamespace(),
2698 'pl_title' => $nt->getDBkey() ),
2701 $this->resetArticleID( 0 );
2704 # Move an image if this is a file
2705 if( $this->getNamespace() == NS_FILE
) {
2706 $file = wfLocalFile( $this );
2707 if( $file->exists() ) {
2708 $status = $file->move( $nt );
2709 if( !$status->isOk() ) {
2711 return $status->getErrorsArray();
2717 $log = new LogPage( 'move' );
2718 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2721 if ( $wgUseSquid ) {
2722 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2723 $u = new SquidUpdate( $urls );
2730 * Move page to non-existing title.
2731 * @param &$nt \type{Title} the new Title
2732 * @param $reason \type{\string} The reason for the move
2733 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2734 * Ignored if the user doesn't have the suppressredirect right
2736 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2737 global $wgUseSquid, $wgUser;
2738 $fname = 'MovePageForm::moveToNewTitle';
2739 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2741 $comment .= wfMsgExt( 'colon-separator',
2742 array( 'escapenoentities', 'content' ) );
2743 $comment .= $reason;
2746 $newid = $nt->getArticleID();
2747 $oldid = $this->getArticleID();
2748 $latest = $this->getLatestRevId();
2750 $dbw = wfGetDB( DB_MASTER
);
2751 $now = $dbw->timestamp();
2753 # Save a null revision in the page's history notifying of the move
2754 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2755 $nullRevId = $nullRevision->insertOn( $dbw );
2757 $article = new Article( $this );
2758 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
2761 $dbw->update( 'page',
2763 'page_touched' => $now,
2764 'page_namespace' => $nt->getNamespace(),
2765 'page_title' => $nt->getDBkey(),
2766 'page_latest' => $nullRevId,
2768 /* WHERE */ array( 'page_id' => $oldid ),
2771 $nt->resetArticleID( $oldid );
2773 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2775 $mwRedir = MagicWord
::get( 'redirect' );
2776 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2777 $redirectArticle = new Article( $this );
2778 $newid = $redirectArticle->insertOn( $dbw );
2779 $redirectRevision = new Revision( array(
2781 'comment' => $comment,
2782 'text' => $redirectText ) );
2783 $redirectRevision->insertOn( $dbw );
2784 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2786 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
2788 # Record the just-created redirect's linking to the page
2789 $dbw->insert( 'pagelinks',
2791 'pl_from' => $newid,
2792 'pl_namespace' => $nt->getNamespace(),
2793 'pl_title' => $nt->getDBkey() ),
2796 $this->resetArticleID( 0 );
2799 # Move an image if this is a file
2800 if( $this->getNamespace() == NS_FILE
) {
2801 $file = wfLocalFile( $this );
2802 if( $file->exists() ) {
2803 $status = $file->move( $nt );
2804 if( !$status->isOk() ) {
2806 return $status->getErrorsArray();
2812 $log = new LogPage( 'move' );
2813 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2815 # Purge caches as per article creation
2816 Article
::onArticleCreate( $nt );
2818 # Purge old title from squid
2819 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2820 $this->purgeSquid();
2825 * Checks if this page is just a one-rev redirect.
2826 * Adds lock, so don't use just for light purposes.
2828 * @return \type{\bool} TRUE or FALSE
2830 public function isSingleRevRedirect() {
2831 $dbw = wfGetDB( DB_MASTER
);
2833 $row = $dbw->selectRow( 'page',
2834 array( 'page_is_redirect', 'page_latest', 'page_id' ),
2839 # Cache some fields we may want
2840 $this->mArticleID
= $row ?
intval($row->page_id
) : 0;
2841 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
2842 $this->mLatestID
= $row ?
intval($row->page_latest
) : false;
2843 if( !$this->mRedirect
) {
2846 # Does the article have a history?
2847 $row = $dbw->selectField( array( 'page', 'revision'),
2849 array( 'page_namespace' => $this->getNamespace(),
2850 'page_title' => $this->getDBkey(),
2852 'page_latest != rev_id'
2857 # Return true if there was no history
2858 return ($row === false);
2862 * Checks if $this can be moved to a given Title
2863 * - Selects for update, so don't call it unless you mean business
2865 * @param &$nt \type{Title} the new title to check
2866 * @return \type{\bool} TRUE or FALSE
2868 public function isValidMoveTarget( $nt ) {
2869 $dbw = wfGetDB( DB_MASTER
);
2870 # Is it an existsing file?
2871 if( $nt->getNamespace() == NS_FILE
) {
2872 $file = wfLocalFile( $nt );
2873 if( $file->exists() ) {
2874 wfDebug( __METHOD__
. ": file exists\n" );
2878 # Is it a redirect with no history?
2879 if( !$nt->isSingleRevRedirect() ) {
2880 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
2883 # Get the article text
2884 $rev = Revision
::newFromTitle( $nt );
2885 $text = $rev->getText();
2886 # Does the redirect point to the source?
2887 # Or is it a broken self-redirect, usually caused by namespace collisions?
2889 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2890 $redirTitle = Title
::newFromText( $m[1] );
2891 if( !is_object( $redirTitle ) ||
2892 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2893 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2894 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2899 wfDebug( __METHOD__
. ": failsafe\n" );
2906 * Can this title be added to a user's watchlist?
2908 * @return \type{\bool} TRUE or FALSE
2910 public function isWatchable() {
2911 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
2915 * Get categories to which this Title belongs and return an array of
2916 * categories' names.
2918 * @return \type{\array} array an array of parents in the form:
2919 * $parent => $currentarticle
2921 public function getParentCategories() {
2924 $titlekey = $this->getArticleId();
2925 $dbr = wfGetDB( DB_SLAVE
);
2926 $categorylinks = $dbr->tableName( 'categorylinks' );
2929 $sql = "SELECT * FROM $categorylinks"
2930 ." WHERE cl_from='$titlekey'"
2931 ." AND cl_from <> '0'"
2932 ." ORDER BY cl_sortkey";
2934 $res = $dbr->query( $sql );
2936 if( $dbr->numRows( $res ) > 0 ) {
2937 foreach( $res as $row )
2938 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2939 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
2940 $dbr->freeResult( $res );
2948 * Get a tree of parent categories
2949 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
2950 * @return \type{\array} Tree of parent categories
2952 public function getParentCategoryTree( $children = array() ) {
2954 $parents = $this->getParentCategories();
2957 foreach( $parents as $parent => $current ) {
2958 if ( array_key_exists( $parent, $children ) ) {
2959 # Circular reference
2960 $stack[$parent] = array();
2962 $nt = Title
::newFromText($parent);
2964 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2976 * Get an associative array for selecting this title from
2979 * @return \type{\array} Selection array
2981 public function pageCond() {
2982 if( $this->mArticleID
> 0 ) {
2983 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
2984 return array( 'page_id' => $this->mArticleID
);
2986 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2991 * Get the revision ID of the previous revision
2993 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
2994 * @param $flags \type{\int} GAID_FOR_UPDATE
2995 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
2997 public function getPreviousRevisionID( $revId, $flags=0 ) {
2998 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
2999 return $db->selectField( 'revision', 'rev_id',
3001 'rev_page' => $this->getArticleId($flags),
3002 'rev_id < ' . intval( $revId )
3005 array( 'ORDER BY' => 'rev_id DESC' )
3010 * Get the revision ID of the next revision
3012 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3013 * @param $flags \type{\int} GAID_FOR_UPDATE
3014 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3016 public function getNextRevisionID( $revId, $flags=0 ) {
3017 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3018 return $db->selectField( 'revision', 'rev_id',
3020 'rev_page' => $this->getArticleId($flags),
3021 'rev_id > ' . intval( $revId )
3024 array( 'ORDER BY' => 'rev_id' )
3029 * Get the oldest revision timestamp of this page
3031 * @return string, MW timestamp
3033 public function getEarliestRevTime() {
3034 $dbr = wfGetDB( DB_SLAVE
);
3035 if( $this->exists() ) {
3036 $min = $dbr->selectField( 'revision',
3037 'MIN(rev_timestamp)',
3038 array( 'rev_page' => $this->getArticleId() ),
3040 return wfTimestampOrNull( TS_MW
, $min );
3046 * Get the number of revisions between the given revision IDs.
3047 * Used for diffs and other things that really need it.
3049 * @param $old \type{\int} Revision ID.
3050 * @param $new \type{\int} Revision ID.
3051 * @return \type{\int} Number of revisions between these IDs.
3053 public function countRevisionsBetween( $old, $new ) {
3054 $dbr = wfGetDB( DB_SLAVE
);
3055 return $dbr->selectField( 'revision', 'count(*)',
3056 'rev_page = ' . intval( $this->getArticleId() ) .
3057 ' AND rev_id > ' . intval( $old ) .
3058 ' AND rev_id < ' . intval( $new ),
3060 array( 'USE INDEX' => 'PRIMARY' ) );
3064 * Compare with another title.
3066 * @param \type{Title} $title
3067 * @return \type{\bool} TRUE or FALSE
3069 public function equals( Title
$title ) {
3070 // Note: === is necessary for proper matching of number-like titles.
3071 return $this->getInterwiki() === $title->getInterwiki()
3072 && $this->getNamespace() == $title->getNamespace()
3073 && $this->getDBkey() === $title->getDBkey();
3077 * Callback for usort() to do title sorts by (namespace, title)
3079 static function compare( $a, $b ) {
3080 if( $a->getNamespace() == $b->getNamespace() ) {
3081 return strcmp( $a->getText(), $b->getText() );
3083 return $a->getNamespace() - $b->getNamespace();
3088 * Return a string representation of this title
3090 * @return \type{\string} String representation of this title
3092 public function __toString() {
3093 return $this->getPrefixedText();
3097 * Check if page exists
3098 * @return \type{\bool} TRUE or FALSE
3100 public function exists() {
3101 return $this->getArticleId() != 0;
3105 * Do we know that this title definitely exists, or should we otherwise
3106 * consider that it exists?
3108 * @return \type{\bool} TRUE or FALSE
3110 public function isAlwaysKnown() {
3111 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3112 // the full l10n of that language to be loaded. That takes much memory and
3113 // isn't needed. So we strip the language part away.
3114 // Also, extension messages which are not loaded, are shown as red, because
3115 // we don't call MessageCache::loadAllMessages.
3116 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3117 return $this->isExternal()
3118 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
3119 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $basename ) );
3123 * Update page_touched timestamps and send squid purge messages for
3124 * pages linking to this title. May be sent to the job queue depending
3125 * on the number of links. Typically called on create and delete.
3127 public function touchLinks() {
3128 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3131 if ( $this->getNamespace() == NS_CATEGORY
) {
3132 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3138 * Get the last touched timestamp
3139 * @return \type{\string} Last touched timestamp
3141 public function getTouched() {
3142 if( !is_null($this->mTouched
) ) {
3143 return wfTimestamp( TS_MW
, $this->mTouched
);
3145 $dbr = wfGetDB( DB_SLAVE
);
3146 $this->mTouched
= $dbr->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3147 return $this->mTouched
;
3151 * Get the timestamp when this page was updated since the user last saw it.
3153 * @return mixed string/NULL
3155 public function getNotificationTimestamp( $user = NULL ) {
3156 global $wgUser, $wgShowUpdatedMarker;
3157 // Assume current user if none given
3158 if( !$user ) $user = $wgUser;
3159 // Check cache first
3160 $uid = $user->getId();
3161 if( isset($this->mNotificationTimestamp
[$uid]) ) {
3162 return $this->mNotificationTimestamp
[$uid];
3164 if( !$uid ||
!$wgShowUpdatedMarker ) {
3165 return $this->mNotificationTimestamp
[$uid] = false;
3167 // Don't cache too much!
3168 if( count($this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3169 $this->mNotificationTimestamp
= array();
3171 $dbr = wfGetDB( DB_SLAVE
);
3172 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3173 'wl_notificationtimestamp',
3174 array( 'wl_namespace' => $this->getNamespace(),
3175 'wl_title' => $this->getDBkey(),
3176 'wl_user' => $user->getId()
3180 return $this->mNotificationTimestamp
[$uid];
3184 * Get the trackback URL for this page
3185 * @return \type{\string} Trackback URL
3187 public function trackbackURL() {
3188 global $wgScriptPath, $wgServer;
3190 return "$wgServer$wgScriptPath/trackback.php?article="
3191 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3195 * Get the trackback RDF for this page
3196 * @return \type{\string} Trackback RDF
3198 public function trackbackRDF() {
3199 $url = htmlspecialchars($this->getFullURL());
3200 $title = htmlspecialchars($this->getText());
3201 $tburl = $this->trackbackURL();
3203 // Autodiscovery RDF is placed in comments so HTML validator
3204 // won't barf. This is a rather icky workaround, but seems
3205 // frequently used by this kind of RDF thingy.
3207 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3209 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3210 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3211 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3214 dc:identifier=\"$url\"
3216 trackback:ping=\"$tburl\" />
3222 * Generate strings used for xml 'id' names in monobook tabs
3223 * @return \type{\string} XML 'id' name
3225 public function getNamespaceKey() {
3227 switch ($this->getNamespace()) {
3230 return 'nstab-main';
3233 return 'nstab-user';
3235 return 'nstab-media';
3237 return 'nstab-special';
3239 case NS_PROJECT_TALK
:
3240 return 'nstab-project';
3243 return 'nstab-image';
3245 case NS_MEDIAWIKI_TALK
:
3246 return 'nstab-mediawiki';
3248 case NS_TEMPLATE_TALK
:
3249 return 'nstab-template';
3252 return 'nstab-help';
3254 case NS_CATEGORY_TALK
:
3255 return 'nstab-category';
3257 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3262 * Returns true if this title resolves to the named special page
3263 * @param $name \type{\string} The special page name
3265 public function isSpecial( $name ) {
3266 if ( $this->getNamespace() == NS_SPECIAL
) {
3267 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3268 if ( $name == $thisName ) {
3276 * If the Title refers to a special page alias which is not the local default,
3277 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3279 public function fixSpecialName() {
3280 if ( $this->getNamespace() == NS_SPECIAL
) {
3281 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3282 if ( $canonicalName ) {
3283 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3284 if ( $localName != $this->mDbkeyform
) {
3285 return Title
::makeTitle( NS_SPECIAL
, $localName );
3293 * Is this Title in a namespace which contains content?
3294 * In other words, is this a content page, for the purposes of calculating
3297 * @return \type{\bool} TRUE or FALSE
3299 public function isContentPage() {
3300 return MWNamespace
::isContent( $this->getNamespace() );
3304 * Get all extant redirects to this Title
3306 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3307 * NULL to consider all namespaces
3308 * @return \type{\arrayof{Title}} Redirects to this title
3310 public function getRedirectsHere( $ns = null ) {
3313 $dbr = wfGetDB( DB_SLAVE
);
3315 'rd_namespace' => $this->getNamespace(),
3316 'rd_title' => $this->getDBkey(),
3319 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3321 $res = $dbr->select(
3322 array( 'redirect', 'page' ),
3323 array( 'page_namespace', 'page_title' ),
3329 foreach( $res as $row ) {
3330 $redirs[] = self
::newFromRow( $row );