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
79 /* private */ function __construct() {}
82 * Create a new Title from a prefixed DB key
83 * @param $key \type{\string} The database key, which has underscores
84 * instead of spaces, possibly including namespace and
86 * @return \type{Title} the new object, or NULL on an error
88 public static function newFromDBkey( $key ) {
90 $t->mDbkeyform
= $key;
91 if( $t->secureAndSplit() )
98 * Create a new Title from text, such as what one would find in a link. De-
99 * codes any HTML entities in the text.
101 * @param $text string The link text; spaces, prefixes, and an
102 * initial ':' indicating the main namespace are accepted.
103 * @param $defaultNamespace int The namespace to use if none is speci-
104 * fied by a prefix. If you want to force a specific namespace even if
105 * $text might begin with a namespace prefix, use makeTitle() or
107 * @return Title The new object, or null on an error.
109 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
110 if( is_object( $text ) ) {
111 throw new MWException( 'Title::newFromText given an object' );
115 * Wiki pages often contain multiple links to the same page.
116 * Title normalization and parsing can become expensive on
117 * pages with many links, so we can save a little time by
120 * In theory these are value objects and won't get changed...
122 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
123 return Title
::$titleCache[$text];
127 * Convert things like é ā or 〗 into real text...
129 $filteredText = Sanitizer
::decodeCharReferences( $text );
132 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
133 $t->mDefaultNamespace
= $defaultNamespace;
135 static $cachedcount = 0 ;
136 if( $t->secureAndSplit() ) {
137 if( $defaultNamespace == NS_MAIN
) {
138 if( $cachedcount >= self
::CACHE_MAX
) {
139 # Avoid memory leaks on mass operations...
140 Title
::$titleCache = array();
144 Title
::$titleCache[$text] =& $t;
154 * Create a new Title from URL-encoded text. Ensures that
155 * the given title's length does not exceed the maximum.
156 * @param $url \type{\string} the title, as might be taken from a URL
157 * @return \type{Title} the new object, or NULL on an error
159 public static function newFromURL( $url ) {
160 global $wgLegalTitleChars;
163 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
164 # but some URLs used it as a space replacement and they still come
165 # from some external search tools.
166 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
167 $url = str_replace( '+', ' ', $url );
170 $t->mDbkeyform
= str_replace( ' ', '_', $url );
171 if( $t->secureAndSplit() ) {
179 * Create a new Title from an article ID
181 * @todo This is inefficiently implemented, the page row is requested
182 * but not used for anything else
184 * @param $id \type{\int} the page_id corresponding to the Title to create
185 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
186 * @return \type{Title} the new object, or NULL on an error
188 public static function newFromID( $id, $flags = 0 ) {
189 $fname = 'Title::newFromID';
190 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
191 $row = $db->selectRow( 'page', array( 'page_namespace', 'page_title' ),
192 array( 'page_id' => $id ), $fname );
193 if ( $row !== false ) {
194 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
202 * Make an array of titles from an array of IDs
203 * @param $ids \type{\arrayof{\int}} Array of IDs
204 * @return \type{\arrayof{Title}} Array of Titles
206 public static function newFromIDs( $ids ) {
207 if ( !count( $ids ) ) {
210 $dbr = wfGetDB( DB_SLAVE
);
211 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
212 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
215 foreach( $res as $row ) {
216 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
222 * Make a Title object from a DB row
223 * @param $row \type{Row} (needs at least page_title,page_namespace)
224 * @return \type{Title} corresponding Title
226 public static function newFromRow( $row ) {
227 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
229 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
230 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
231 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: NULL;
232 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
238 * Create a new Title from a namespace index and a DB key.
239 * It's assumed that $ns and $title are *valid*, for instance when
240 * they came directly from the database or a special page name.
241 * For convenience, spaces are converted to underscores so that
242 * eg user_text fields can be used directly.
244 * @param $ns \type{\int} the namespace of the article
245 * @param $title \type{\string} the unprefixed database key form
246 * @param $fragment \type{\string} The link fragment (after the "#")
247 * @return \type{Title} the new object
249 public static function &makeTitle( $ns, $title, $fragment = '' ) {
252 $t->mFragment
= $fragment;
253 $t->mNamespace
= $ns = intval( $ns );
254 $t->mDbkeyform
= str_replace( ' ', '_', $title );
255 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
256 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
257 $t->mTextform
= str_replace( '_', ' ', $title );
262 * Create a new Title from a namespace index and a DB key.
263 * The parameters will be checked for validity, which is a bit slower
264 * than makeTitle() but safer for user-provided data.
266 * @param $ns \type{\int} the namespace of the article
267 * @param $title \type{\string} the database key form
268 * @param $fragment \type{\string} The link fragment (after the "#")
269 * @return \type{Title} the new object, or NULL on an error
271 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
273 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
274 if( $t->secureAndSplit() ) {
282 * Create a new Title for the Main Page
283 * @return \type{Title} the new object
285 public static function newMainPage() {
286 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
287 // Don't give fatal errors if the message is broken
289 $title = Title
::newFromText( 'Main Page' );
295 * Extract a redirect destination from a string and return the
296 * Title, or null if the text doesn't contain a valid redirect
298 * @param $text \type{String} Text with possible redirect
299 * @return \type{Title} The corresponding Title
301 public static function newFromRedirect( $text ) {
302 $redir = MagicWord
::get( 'redirect' );
304 if( $redir->matchStartAndRemove( $text ) ) {
305 // Extract the first link and see if it's usable
306 // Ensure that it really does come directly after #REDIRECT
307 // Some older redirects included a colon, so don't freak about that!
309 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
310 // Strip preceding colon used to "escape" categories, etc.
311 // and URL-decode links
312 if( strpos( $m[1], '%' ) !== false ) {
313 // Match behavior of inline link parsing here;
314 // don't interpret + as " " most of the time!
315 // It might be safe to just use rawurldecode instead, though.
316 $m[1] = urldecode( ltrim( $m[1], ':' ) );
318 $title = Title
::newFromText( $m[1] );
319 // Redirects to Special:Userlogout are not permitted
320 if( $title instanceof Title
&& !$title->isSpecial( 'Userlogout' ) )
327 #----------------------------------------------------------------------------
329 #----------------------------------------------------------------------------
332 * Get the prefixed DB key associated with an ID
333 * @param $id \type{\int} the page_id of the article
334 * @return \type{Title} an object representing the article, or NULL
335 * if no such article was found
337 public static function nameOf( $id ) {
338 $dbr = wfGetDB( DB_SLAVE
);
340 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), __METHOD__
);
341 if ( $s === false ) { return NULL; }
343 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
348 * Get a regex character class describing the legal characters in a link
349 * @return \type{\string} the list of characters, not delimited
351 public static function legalChars() {
352 global $wgLegalTitleChars;
353 return $wgLegalTitleChars;
357 * Get a string representation of a title suitable for
358 * including in a search index
360 * @param $ns \type{\int} a namespace index
361 * @param $title \type{\string} text-form main part
362 * @return \type{\string} a stripped-down title string ready for the
365 public static function indexTitle( $ns, $title ) {
368 $lc = SearchEngine
::legalSearchChars() . '&#;';
369 $t = $wgContLang->stripForSearch( $title );
370 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
371 $t = $wgContLang->lc( $t );
374 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
375 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
377 $t = preg_replace( "/\\s+/", ' ', $t );
379 if ( $ns == NS_IMAGE
) {
380 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
386 * Make a prefixed DB key from a DB key and a namespace index
387 * @param $ns \type{\int} numerical representation of the namespace
388 * @param $title \type{\string} the DB key form the title
389 * @param $fragment \type{\string} The link fragment (after the "#")
390 * @return \type{\string} the prefixed form of the title
392 public static function makeName( $ns, $title, $fragment = '' ) {
395 $namespace = $wgContLang->getNsText( $ns );
396 $name = $namespace == '' ?
$title : "$namespace:$title";
397 if ( strval( $fragment ) != '' ) {
398 $name .= '#' . $fragment;
404 * Returns the URL associated with an interwiki prefix
405 * @param $key \type{\string} the interwiki prefix (e.g. "MeatBall")
406 * @return \type{\string} the associated URL, containing "$1",
407 * which should be replaced by an article title
409 * @deprecated See Interwiki class
411 public function getInterwikiLink( $key ) {
412 return Interwiki
::fetch( $key )->getURL( );
416 * Determine whether the object refers to a page within
419 * @return \type{\bool} TRUE if this is an in-project interwiki link
420 * or a wikilink, FALSE otherwise
422 public function isLocal() {
423 if ( $this->mInterwiki
!= '' ) {
424 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
431 * Determine whether the object refers to a page within
432 * this project and is transcludable.
434 * @return \type{\bool} TRUE if this is transcludable
436 public function isTrans() {
437 if ($this->mInterwiki
== '')
440 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
444 * Escape a text fragment, say from a link, for a URL
446 static function escapeFragmentForURL( $fragment ) {
447 $fragment = str_replace( ' ', '_', $fragment );
448 $fragment = urlencode( Sanitizer
::decodeCharReferences( $fragment ) );
449 $replaceArray = array(
453 return strtr( $fragment, $replaceArray );
456 #----------------------------------------------------------------------------
458 #----------------------------------------------------------------------------
460 /** Simple accessors */
462 * Get the text form (spaces not underscores) of the main part
463 * @return \type{\string} Main part of the title
465 public function getText() { return $this->mTextform
; }
467 * Get the URL-encoded form of the main part
468 * @return \type{\string} Main part of the title, URL-encoded
470 public function getPartialURL() { return $this->mUrlform
; }
472 * Get the main part with underscores
473 * @return \type{\string} Main part of the title, with underscores
475 public function getDBkey() { return $this->mDbkeyform
; }
477 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
478 * @return \type{\int} Namespace index
480 public function getNamespace() { return $this->mNamespace
; }
482 * Get the namespace text
483 * @return \type{\string} Namespace text
485 public function getNsText() {
486 global $wgContLang, $wgCanonicalNamespaceNames;
488 if ( '' != $this->mInterwiki
) {
489 // This probably shouldn't even happen. ohh man, oh yuck.
490 // But for interwiki transclusion it sometimes does.
491 // Shit. Shit shit shit.
493 // Use the canonical namespaces if possible to try to
494 // resolve a foreign namespace.
495 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
496 return $wgCanonicalNamespaceNames[$this->mNamespace
];
499 return $wgContLang->getNsText( $this->mNamespace
);
502 * Get the DB key with the initial letter case as specified by the user
503 * @return \type{\string} DB key
505 function getUserCaseDBKey() {
506 return $this->mUserCaseDBKey
;
509 * Get the namespace text of the subject (rather than talk) page
510 * @return \type{\string} Namespace text
512 public function getSubjectNsText() {
514 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
517 * Get the namespace text of the talk page
518 * @return \type{\string} Namespace text
520 public function getTalkNsText() {
522 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
525 * Could this title have a corresponding talk page?
526 * @return \type{\bool} TRUE or FALSE
528 public function canTalk() {
529 return( MWNamespace
::canTalk( $this->mNamespace
) );
532 * Get the interwiki prefix (or null string)
533 * @return \type{\string} Interwiki prefix
535 public function getInterwiki() { return $this->mInterwiki
; }
537 * Get the Title fragment (i.e.\ the bit after the #) in text form
538 * @return \type{\string} Title fragment
540 public function getFragment() { return $this->mFragment
; }
542 * Get the fragment in URL form, including the "#" character if there is one
543 * @return \type{\string} Fragment in URL form
545 public function getFragmentForURL() {
546 if ( $this->mFragment
== '' ) {
549 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
553 * Get the default namespace index, for when there is no namespace
554 * @return \type{\int} Default namespace index
556 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
559 * Get title for search index
560 * @return \type{\string} a stripped-down title string ready for the
563 public function getIndexTitle() {
564 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
568 * Get the prefixed database key form
569 * @return \type{\string} the prefixed title, with underscores and
570 * any interwiki and namespace prefixes
572 public function getPrefixedDBkey() {
573 $s = $this->prefix( $this->mDbkeyform
);
574 $s = str_replace( ' ', '_', $s );
579 * Get the prefixed title with spaces.
580 * This is the form usually used for display
581 * @return \type{\string} the prefixed title, with spaces
583 public function getPrefixedText() {
584 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
585 $s = $this->prefix( $this->mTextform
);
586 $s = str_replace( '_', ' ', $s );
587 $this->mPrefixedText
= $s;
589 return $this->mPrefixedText
;
593 * Get the prefixed title with spaces, plus any fragment
594 * (part beginning with '#')
595 * @return \type{\string} the prefixed title, with spaces and
596 * the fragment, including '#'
598 public function getFullText() {
599 $text = $this->getPrefixedText();
600 if( '' != $this->mFragment
) {
601 $text .= '#' . $this->mFragment
;
607 * Get the base name, i.e. the leftmost parts before the /
608 * @return \type{\string} Base name
610 public function getBaseText() {
611 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
612 return $this->getText();
615 $parts = explode( '/', $this->getText() );
616 # Don't discard the real title if there's no subpage involved
617 if( count( $parts ) > 1 )
618 unset( $parts[ count( $parts ) - 1 ] );
619 return implode( '/', $parts );
623 * Get the lowest-level subpage name, i.e. the rightmost part after /
624 * @return \type{\string} Subpage name
626 public function getSubpageText() {
627 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
628 return( $this->mTextform
);
630 $parts = explode( '/', $this->mTextform
);
631 return( $parts[ count( $parts ) - 1 ] );
635 * Get a URL-encoded form of the subpage text
636 * @return \type{\string} URL-encoded subpage name
638 public function getSubpageUrlForm() {
639 $text = $this->getSubpageText();
640 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
641 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
646 * Get a URL-encoded title (not an actual URL) including interwiki
647 * @return \type{\string} the URL-encoded form
649 public function getPrefixedURL() {
650 $s = $this->prefix( $this->mDbkeyform
);
651 $s = str_replace( ' ', '_', $s );
653 $s = wfUrlencode ( $s ) ;
655 # Cleaning up URL to make it look nice -- is this safe?
656 $s = str_replace( '%28', '(', $s );
657 $s = str_replace( '%29', ')', $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 ($result != array() && is_array($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 != '' && $result != null && $result !== true && $result !== false)
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 ($result != array() && is_array($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 != '' && $result != null && $result !== true && $result !== false)
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"
1130 $specialOKActions = array( 'createaccount', 'execute' );
1131 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1132 $errors[] = array('ns-specialprotected');
1135 if ( $this->isNamespaceProtected() ) {
1136 $ns = $this->getNamespace() == NS_MAIN
1137 ?
wfMsg( 'nstab-main' )
1138 : $this->getNsText();
1139 $errors[] = (NS_MEDIAWIKI
== $this->mNamespace
1140 ?
array('protectedinterface')
1141 : array( 'namespaceprotected', $ns ) );
1144 if( $this->mDbkeyform
== '_' ) {
1145 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1146 $errors[] = array('badaccess-group0');
1149 # protect css/js subpages of user pages
1150 # XXX: this might be better using restrictions
1151 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1152 if( $this->isCssJsSubpage()
1153 && !$user->isAllowed('editusercssjs')
1154 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) ) {
1155 $errors[] = array('customcssjsprotected');
1158 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1159 # We /could/ use the protection level on the source page, but it's fairly ugly
1160 # as we have to establish a precedence hierarchy for pages included by multiple
1161 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1162 # as they could remove the protection anyway.
1163 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1164 # Cascading protection depends on more than this page...
1165 # Several cascading protected pages may include this page...
1166 # Check each cascading level
1167 # This is only for protection restrictions, not for all actions
1168 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1169 foreach( $restrictions[$action] as $right ) {
1170 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1171 if( '' != $right && !$user->isAllowed( $right ) ) {
1173 foreach( $cascadingSources as $page )
1174 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1175 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1181 foreach( $this->getRestrictions($action) as $right ) {
1182 // Backwards compatibility, rewrite sysop -> protect
1183 if ( $right == 'sysop' ) {
1186 if( '' != $right && !$user->isAllowed( $right ) ) {
1187 //Users with 'editprotected' permission can edit protected pages
1188 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1189 //Users with 'editprotected' permission cannot edit protected pages
1190 //with cascading option turned on.
1191 if($this->mCascadeRestriction
) {
1192 $errors[] = array( 'protectedpagetext', $right );
1194 //Nothing, user can edit!
1197 $errors[] = array( 'protectedpagetext', $right );
1202 if ($action == 'protect') {
1203 if ($this->getUserPermissionsErrors('edit', $user) != array()) {
1204 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1208 if ($action == 'create') {
1209 $title_protection = $this->getTitleProtection();
1211 if (is_array($title_protection)) {
1212 extract($title_protection);
1214 if ($pt_create_perm == 'sysop')
1215 $pt_create_perm = 'protect';
1217 if ($pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm)) {
1218 $errors[] = array ( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1222 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1223 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1224 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1227 } elseif ( $action == 'move' ) {
1228 if ( !$user->isAllowed( 'move' ) ) {
1229 // User can't move anything
1230 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1231 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1232 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1234 // Show user page-specific message only if the user can move other pages
1235 $errors[] = array( 'cant-move-user-page' );
1238 // Check for immobile pages
1239 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1240 // Specific message for this case
1241 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1242 } elseif ( !$this->isMovable() ) {
1243 // Less specific message for rarer cases
1244 $errors[] = array( 'immobile-page' );
1247 } elseif ( $action == 'move-target' ) {
1248 if ( !$user->isAllowed( 'move' ) ) {
1249 // User can't move anything
1250 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1251 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1252 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1254 // Show user page-specific message only if the user can move other pages
1255 $errors[] = array( 'cant-move-to-user-page' );
1257 if ( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1258 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1259 } elseif ( !$this->isMovable() ) {
1260 $errors[] = array( 'immobile-target-page' );
1263 } elseif ( !$user->isAllowed( $action ) ) {
1265 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1266 User
::getGroupsWithPermission( $action ) );
1268 $return = array( 'badaccess-groups',
1270 implode( ', ', $groups ),
1271 count( $groups ) ) );
1274 $return = array( "badaccess-group0" );
1276 $errors[] = $return;
1279 wfProfileOut( __METHOD__
);
1284 * Is this title subject to title protection?
1285 * @return \type{\mixed} An associative array representing any existent title
1286 * protection, or false if there's none.
1288 private function getTitleProtection() {
1289 // Can't protect pages in special namespaces
1290 if ( $this->getNamespace() < 0 ) {
1294 $dbr = wfGetDB( DB_SLAVE
);
1295 $res = $dbr->select( 'protected_titles', '*',
1296 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
1298 if ($row = $dbr->fetchRow( $res )) {
1306 * Update the title protection status
1307 * @param $create_perm \type{\string} Permission required for creation
1308 * @param $reason \type{\string} Reason for protection
1309 * @param $expiry \type{\string} Expiry timestamp
1311 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1312 global $wgUser,$wgContLang;
1314 if ($create_perm == implode(',',$this->getRestrictions('create'))
1315 && $expiry == $this->mRestrictionsExpiry
['create']) {
1320 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1322 $dbw = wfGetDB( DB_MASTER
);
1324 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1326 $expiry_description = '';
1327 if ( $encodedExpiry != 'infinity' ) {
1328 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
1331 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1334 # Update protection table
1335 if ($create_perm != '' ) {
1336 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1337 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1338 , 'pt_create_perm' => $create_perm
1339 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1340 , 'pt_expiry' => $encodedExpiry
1341 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1343 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1344 'pt_title' => $title ), __METHOD__
);
1346 # Update the protection log
1347 $log = new LogPage( 'protect' );
1349 if( $create_perm ) {
1350 $params = array("[create=$create_perm] $expiry_description",'');
1351 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason ), $params );
1353 $log->addEntry( 'unprotect', $this, $reason );
1360 * Remove any title protection due to page existing
1362 public function deleteTitleProtection() {
1363 $dbw = wfGetDB( DB_MASTER
);
1365 $dbw->delete( 'protected_titles',
1366 array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__
);
1370 * Can $wgUser edit this page?
1371 * @return \type{\bool} TRUE or FALSE
1372 * @deprecated use userCan('edit')
1374 public function userCanEdit( $doExpensiveQueries = true ) {
1375 return $this->userCan( 'edit', $doExpensiveQueries );
1379 * Can $wgUser create this page?
1380 * @return \type{\bool} TRUE or FALSE
1381 * @deprecated use userCan('create')
1383 public function userCanCreate( $doExpensiveQueries = true ) {
1384 return $this->userCan( 'create', $doExpensiveQueries );
1388 * Can $wgUser move this page?
1389 * @return \type{\bool} TRUE or FALSE
1390 * @deprecated use userCan('move')
1392 public function userCanMove( $doExpensiveQueries = true ) {
1393 return $this->userCan( 'move', $doExpensiveQueries );
1397 * Would anybody with sufficient privileges be able to move this page?
1398 * Some pages just aren't movable.
1400 * @return \type{\bool} TRUE or FALSE
1402 public function isMovable() {
1403 return MWNamespace
::isMovable( $this->getNamespace() )
1404 && $this->getInterwiki() == '';
1408 * Can $wgUser read this page?
1409 * @return \type{\bool} TRUE or FALSE
1410 * @todo fold these checks into userCan()
1412 public function userCanRead() {
1413 global $wgUser, $wgGroupPermissions;
1416 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1417 if ( $result !== null ) {
1421 # Shortcut for public wikis, allows skipping quite a bit of code
1422 if ($wgGroupPermissions['*']['read'])
1425 if( $wgUser->isAllowed( 'read' ) ) {
1428 global $wgWhitelistRead;
1431 * Always grant access to the login page.
1432 * Even anons need to be able to log in.
1434 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1439 * Bail out if there isn't whitelist
1441 if( !is_array($wgWhitelistRead) ) {
1446 * Check for explicit whitelisting
1448 $name = $this->getPrefixedText();
1449 $dbName = $this->getPrefixedDBKey();
1450 // Check with and without underscores
1451 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1455 * Old settings might have the title prefixed with
1456 * a colon for main-namespace pages
1458 if( $this->getNamespace() == NS_MAIN
) {
1459 if( in_array( ':' . $name, $wgWhitelistRead ) )
1464 * If it's a special page, ditch the subpage bit
1467 if( $this->getNamespace() == NS_SPECIAL
) {
1468 $name = $this->getDBkey();
1469 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1470 if ( $name === false ) {
1471 # Invalid special page, but we show standard login required message
1475 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1476 if( in_array( $pure, $wgWhitelistRead, true ) )
1485 * Is this a talk page of some sort?
1486 * @return \type{\bool} TRUE or FALSE
1488 public function isTalkPage() {
1489 return MWNamespace
::isTalk( $this->getNamespace() );
1493 * Is this a subpage?
1494 * @return \type{\bool} TRUE or FALSE
1496 public function isSubpage() {
1497 return MWNamespace
::hasSubpages( $this->mNamespace
)
1498 ?
strpos( $this->getText(), '/' ) !== false
1503 * Does this have subpages? (Warning, usually requires an extra DB query.)
1504 * @return \type{\bool} TRUE or FALSE
1506 public function hasSubpages() {
1507 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1512 # We dynamically add a member variable for the purpose of this method
1513 # alone to cache the result. There's no point in having it hanging
1514 # around uninitialized in every Title object; therefore we only add it
1515 # if needed and don't declare it statically.
1516 if( isset( $this->mHasSubpages
) ) {
1517 return $this->mHasSubpages
;
1520 $db = wfGetDB( DB_SLAVE
);
1521 return $this->mHasSubpages
= (bool)$db->selectField( 'page', '1',
1522 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1523 . $db->escapeLike( $this->mDbkeyform
) . "/%'",
1529 * Could this page contain custom CSS or JavaScript, based
1532 * @return \type{\bool} TRUE or FALSE
1534 public function isCssOrJsPage() {
1535 return $this->mNamespace
== NS_MEDIAWIKI
1536 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1540 * Is this a .css or .js subpage of a user page?
1541 * @return \type{\bool} TRUE or FALSE
1543 public function isCssJsSubpage() {
1544 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1547 * Is this a *valid* .css or .js subpage of a user page?
1548 * Check that the corresponding skin exists
1549 * @return \type{\bool} TRUE or FALSE
1551 public function isValidCssJsSubpage() {
1552 if ( $this->isCssJsSubpage() ) {
1553 $skinNames = Skin
::getSkinNames();
1554 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1560 * Trim down a .css or .js subpage title to get the corresponding skin name
1562 public function getSkinFromCssJsSubpage() {
1563 $subpage = explode( '/', $this->mTextform
);
1564 $subpage = $subpage[ count( $subpage ) - 1 ];
1565 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1568 * Is this a .css subpage of a user page?
1569 * @return \type{\bool} TRUE or FALSE
1571 public function isCssSubpage() {
1572 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1575 * Is this a .js subpage of a user page?
1576 * @return \type{\bool} TRUE or FALSE
1578 public function isJsSubpage() {
1579 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1582 * Protect css/js subpages of user pages: can $wgUser edit
1585 * @return \type{\bool} TRUE or FALSE
1586 * @todo XXX: this might be better using restrictions
1588 public function userCanEditCssJsSubpage() {
1590 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1594 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1596 * @return \type{\bool} If the page is subject to cascading restrictions.
1598 public function isCascadeProtected() {
1599 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1600 return ( $sources > 0 );
1604 * Cascading protection: Get the source of any cascading restrictions on this page.
1606 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1607 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1608 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1609 * The restriction array is an array of each type, each of which contains an array of unique groups.
1611 public function getCascadeProtectionSources( $get_pages = true ) {
1612 global $wgRestrictionTypes;
1614 # Define our dimension of restrictions types
1615 $pagerestrictions = array();
1616 foreach( $wgRestrictionTypes as $action )
1617 $pagerestrictions[$action] = array();
1619 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1620 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1621 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1622 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1625 wfProfileIn( __METHOD__
);
1627 $dbr = wfGetDB( DB_SLAVE
);
1629 if ( $this->getNamespace() == NS_IMAGE
) {
1630 $tables = array ('imagelinks', 'page_restrictions');
1631 $where_clauses = array(
1632 'il_to' => $this->getDBkey(),
1634 'pr_cascade' => 1 );
1636 $tables = array ('templatelinks', 'page_restrictions');
1637 $where_clauses = array(
1638 'tl_namespace' => $this->getNamespace(),
1639 'tl_title' => $this->getDBkey(),
1641 'pr_cascade' => 1 );
1645 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1646 $where_clauses[] = 'page_id=pr_page';
1649 $cols = array( 'pr_expiry' );
1652 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1654 $sources = $get_pages ?
array() : false;
1655 $now = wfTimestampNow();
1656 $purgeExpired = false;
1658 foreach( $res as $row ) {
1659 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1660 if( $expiry > $now ) {
1662 $page_id = $row->pr_page
;
1663 $page_ns = $row->page_namespace
;
1664 $page_title = $row->page_title
;
1665 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1666 # Add groups needed for each restriction type if its not already there
1667 # Make sure this restriction type still exists
1668 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1669 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1675 // Trigger lazy purge of expired restrictions from the db
1676 $purgeExpired = true;
1679 if( $purgeExpired ) {
1680 Title
::purgeExpiredRestrictions();
1683 wfProfileOut( __METHOD__
);
1686 $this->mCascadeSources
= $sources;
1687 $this->mCascadingRestrictions
= $pagerestrictions;
1689 $this->mHasCascadingRestrictions
= $sources;
1691 return array( $sources, $pagerestrictions );
1694 function areRestrictionsCascading() {
1695 if (!$this->mRestrictionsLoaded
) {
1696 $this->loadRestrictions();
1699 return $this->mCascadeRestriction
;
1703 * Loads a string into mRestrictions array
1704 * @param $res \type{Resource} restrictions as an SQL result.
1706 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1707 global $wgRestrictionTypes;
1708 $dbr = wfGetDB( DB_SLAVE
);
1710 foreach( $wgRestrictionTypes as $type ){
1711 $this->mRestrictions
[$type] = array();
1712 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry('');
1715 $this->mCascadeRestriction
= false;
1717 # Backwards-compatibility: also load the restrictions from the page record (old format).
1719 if ( $oldFashionedRestrictions === NULL ) {
1720 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1721 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1724 if ($oldFashionedRestrictions != '') {
1726 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1727 $temp = explode( '=', trim( $restrict ) );
1728 if(count($temp) == 1) {
1729 // old old format should be treated as edit/move restriction
1730 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1731 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1733 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1737 $this->mOldRestrictions
= true;
1741 if( $dbr->numRows( $res ) ) {
1742 # Current system - load second to make them override.
1743 $now = wfTimestampNow();
1744 $purgeExpired = false;
1746 foreach( $res as $row ) {
1747 # Cycle through all the restrictions.
1749 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1750 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1753 // This code should be refactored, now that it's being used more generally,
1754 // But I don't really see any harm in leaving it in Block for now -werdna
1755 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1757 // Only apply the restrictions if they haven't expired!
1758 if ( !$expiry ||
$expiry > $now ) {
1759 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
1760 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1762 $this->mCascadeRestriction |
= $row->pr_cascade
;
1764 // Trigger a lazy purge of expired restrictions
1765 $purgeExpired = true;
1769 if( $purgeExpired ) {
1770 Title
::purgeExpiredRestrictions();
1774 $this->mRestrictionsLoaded
= true;
1778 * Load restrictions from the page_restrictions table
1780 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1781 if( !$this->mRestrictionsLoaded
) {
1782 if ($this->exists()) {
1783 $dbr = wfGetDB( DB_SLAVE
);
1785 $res = $dbr->select( 'page_restrictions', '*',
1786 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1788 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1790 $title_protection = $this->getTitleProtection();
1792 if (is_array($title_protection)) {
1793 extract($title_protection);
1795 $now = wfTimestampNow();
1796 $expiry = Block
::decodeExpiry($pt_expiry);
1798 if (!$expiry ||
$expiry > $now) {
1799 // Apply the restrictions
1800 $this->mRestrictionsExpiry
['create'] = $expiry;
1801 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1802 } else { // Get rid of the old restrictions
1803 Title
::purgeExpiredRestrictions();
1806 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry('');
1808 $this->mRestrictionsLoaded
= true;
1814 * Purge expired restrictions from the page_restrictions table
1816 static function purgeExpiredRestrictions() {
1817 $dbw = wfGetDB( DB_MASTER
);
1818 $dbw->delete( 'page_restrictions',
1819 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1822 $dbw->delete( 'protected_titles',
1823 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1828 * Accessor/initialisation for mRestrictions
1830 * @param $action \type{\string} action that permission needs to be checked for
1831 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
1833 public function getRestrictions( $action ) {
1834 if( !$this->mRestrictionsLoaded
) {
1835 $this->loadRestrictions();
1837 return isset( $this->mRestrictions
[$action] )
1838 ?
$this->mRestrictions
[$action]
1843 * Get the expiry time for the restriction against a given action
1844 * @return 14-char timestamp, or 'infinity' if the page is protected forever
1845 * or not protected at all, or false if the action is not recognised.
1847 public function getRestrictionExpiry( $action ) {
1848 if( !$this->mRestrictionsLoaded
) {
1849 $this->loadRestrictions();
1851 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
1855 * Is there a version of this page in the deletion archive?
1856 * @return \type{\int} the number of archived revisions
1858 public function isDeleted() {
1859 $fname = 'Title::isDeleted';
1860 if ( $this->getNamespace() < 0 ) {
1863 $dbr = wfGetDB( DB_SLAVE
);
1864 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1865 'ar_title' => $this->getDBkey() ), $fname );
1866 if( $this->getNamespace() == NS_IMAGE
) {
1867 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1868 array( 'fa_name' => $this->getDBkey() ), $fname );
1875 * Get the article ID for this Title from the link cache,
1876 * adding it if necessary
1877 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
1879 * @return \type{\int} the ID
1881 public function getArticleID( $flags = 0 ) {
1882 $linkCache = LinkCache
::singleton();
1883 if( $flags & GAID_FOR_UPDATE
) {
1884 $oldUpdate = $linkCache->forUpdate( true );
1885 $linkCache->clearLink( $this );
1886 $this->mArticleID
= $linkCache->addLinkObj( $this );
1887 $linkCache->forUpdate( $oldUpdate );
1889 if( -1 == $this->mArticleID
) {
1890 $this->mArticleID
= $linkCache->addLinkObj( $this );
1893 return $this->mArticleID
;
1897 * Is this an article that is a redirect page?
1898 * Uses link cache, adding it if necessary
1899 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1900 * @return \type{\bool}
1902 public function isRedirect( $flags = 0 ) {
1903 if( !is_null($this->mRedirect
) )
1904 return $this->mRedirect
;
1905 # Zero for special pages.
1906 # Also, calling getArticleID() loads the field from cache!
1907 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1910 $linkCache = LinkCache
::singleton();
1911 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
1913 return $this->mRedirect
;
1917 * What is the length of this page?
1918 * Uses link cache, adding it if necessary
1919 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1920 * @return \type{\bool}
1922 public function getLength( $flags = 0 ) {
1923 if( $this->mLength
!= -1 )
1924 return $this->mLength
;
1925 # Zero for special pages.
1926 # Also, calling getArticleID() loads the field from cache!
1927 if( !$this->getArticleID($flags) ||
$this->getNamespace() == NS_SPECIAL
) {
1930 $linkCache = LinkCache
::singleton();
1931 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
1933 return $this->mLength
;
1937 * What is the page_latest field for this page?
1938 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1939 * @return \type{\int}
1941 public function getLatestRevID( $flags = 0 ) {
1942 if( $this->mLatestID
!== false )
1943 return $this->mLatestID
;
1945 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
1946 $this->mLatestID
= $db->selectField( 'page', 'page_latest',
1947 array( 'page_namespace' => $this->getNamespace(), 'page_title' => $this->getDBKey() ),
1949 return $this->mLatestID
;
1953 * This clears some fields in this object, and clears any associated
1954 * keys in the "bad links" section of the link cache.
1956 * - This is called from Article::insertNewArticle() to allow
1957 * loading of the new page_id. It's also called from
1958 * Article::doDeleteArticle()
1960 * @param $newid \type{\int} the new Article ID
1962 public function resetArticleID( $newid ) {
1963 $linkCache = LinkCache
::singleton();
1964 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1966 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1967 else { $this->mArticleID
= $newid; }
1968 $this->mRestrictionsLoaded
= false;
1969 $this->mRestrictions
= array();
1973 * Updates page_touched for this page; called from LinksUpdate.php
1974 * @return \type{\bool} true if the update succeded
1976 public function invalidateCache() {
1977 global $wgUseFileCache;
1979 if ( wfReadOnly() ) {
1983 $dbw = wfGetDB( DB_MASTER
);
1984 $success = $dbw->update( 'page',
1986 'page_touched' => $dbw->timestamp()
1987 ), array( /* WHERE */
1988 'page_namespace' => $this->getNamespace() ,
1989 'page_title' => $this->getDBkey()
1990 ), 'Title::invalidateCache'
1993 if ($wgUseFileCache) {
1994 $cache = new HTMLFileCache($this);
1995 @unlink
($cache->fileCacheName());
2002 * Prefix some arbitrary text with the namespace or interwiki prefix
2005 * @param $name \type{\string} the text
2006 * @return \type{\string} the prefixed text
2009 /* private */ function prefix( $name ) {
2011 if ( '' != $this->mInterwiki
) {
2012 $p = $this->mInterwiki
. ':';
2014 if ( 0 != $this->mNamespace
) {
2015 $p .= $this->getNsText() . ':';
2021 * Secure and split - main initialisation function for this object
2023 * Assumes that mDbkeyform has been set, and is urldecoded
2024 * and uses underscores, but not otherwise munged. This function
2025 * removes illegal characters, splits off the interwiki and
2026 * namespace prefixes, sets the other forms, and canonicalizes
2028 * @return \type{\bool} true on success
2030 private function secureAndSplit() {
2031 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2034 static $rxTc = false;
2036 # Matching titles will be held as illegal.
2038 # Any character not allowed is forbidden...
2039 '[^' . Title
::legalChars() . ']' .
2040 # URL percent encoding sequences interfere with the ability
2041 # to round-trip titles -- you can't link to them consistently.
2042 '|%[0-9A-Fa-f]{2}' .
2043 # XML/HTML character references produce similar issues.
2044 '|&[A-Za-z0-9\x80-\xff]+;' .
2046 '|&#x[0-9A-Fa-f]+;' .
2050 $this->mInterwiki
= $this->mFragment
= '';
2051 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2053 $dbkey = $this->mDbkeyform
;
2055 # Strip Unicode bidi override characters.
2056 # Sometimes they slip into cut-n-pasted page titles, where the
2057 # override chars get included in list displays.
2058 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
2059 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
2061 # Clean up whitespace
2063 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2064 $dbkey = trim( $dbkey, '_' );
2066 if ( '' == $dbkey ) {
2070 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2071 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2075 $this->mDbkeyform
= $dbkey;
2077 # Initial colon indicates main namespace rather than specified default
2078 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2079 if ( ':' == $dbkey{0} ) {
2080 $this->mNamespace
= NS_MAIN
;
2081 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2082 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2085 # Namespace or interwiki prefix
2089 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
2091 if ( $ns = $wgContLang->getNsIndex( $p )) {
2092 # Ordinary namespace
2094 $this->mNamespace
= $ns;
2095 } elseif( Interwiki
::isValidInterwiki( $p ) ) {
2097 # Can't make a local interwiki link to an interwiki link.
2098 # That's just crazy!
2104 $this->mInterwiki
= $wgContLang->lc( $p );
2106 # Redundant interwiki prefix to the local wiki
2107 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2108 if( $dbkey == '' ) {
2109 # Can't have an empty self-link
2112 $this->mInterwiki
= '';
2114 # Do another namespace split...
2118 # If there's an initial colon after the interwiki, that also
2119 # resets the default namespace
2120 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2121 $this->mNamespace
= NS_MAIN
;
2122 $dbkey = substr( $dbkey, 1 );
2125 # If there's no recognized interwiki or namespace,
2126 # then let the colon expression be part of the title.
2131 # We already know that some pages won't be in the database!
2133 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2134 $this->mArticleID
= 0;
2136 $fragment = strstr( $dbkey, '#' );
2137 if ( false !== $fragment ) {
2138 $this->setFragment( $fragment );
2139 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2140 # remove whitespace again: prevents "Foo_bar_#"
2141 # becoming "Foo_bar_"
2142 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2145 # Reject illegal characters.
2147 if( preg_match( $rxTc, $dbkey ) ) {
2152 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2153 * reachable due to the way web browsers deal with 'relative' URLs.
2154 * Also, they conflict with subpage syntax. Forbid them explicitly.
2156 if ( strpos( $dbkey, '.' ) !== false &&
2157 ( $dbkey === '.' ||
$dbkey === '..' ||
2158 strpos( $dbkey, './' ) === 0 ||
2159 strpos( $dbkey, '../' ) === 0 ||
2160 strpos( $dbkey, '/./' ) !== false ||
2161 strpos( $dbkey, '/../' ) !== false ||
2162 substr( $dbkey, -2 ) == '/.' ||
2163 substr( $dbkey, -3 ) == '/..' ) )
2169 * Magic tilde sequences? Nu-uh!
2171 if( strpos( $dbkey, '~~~' ) !== false ) {
2176 * Limit the size of titles to 255 bytes.
2177 * This is typically the size of the underlying database field.
2178 * We make an exception for special pages, which don't need to be stored
2179 * in the database, and may edge over 255 bytes due to subpage syntax
2180 * for long titles, e.g. [[Special:Block/Long name]]
2182 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2183 strlen( $dbkey ) > 512 )
2189 * Normally, all wiki links are forced to have
2190 * an initial capital letter so [[foo]] and [[Foo]]
2191 * point to the same place.
2193 * Don't force it for interwikis, since the other
2194 * site might be case-sensitive.
2196 $this->mUserCaseDBKey
= $dbkey;
2197 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2198 $dbkey = $wgContLang->ucfirst( $dbkey );
2202 * Can't make a link to a namespace alone...
2203 * "empty" local links can only be self-links
2204 * with a fragment identifier.
2207 $this->mInterwiki
== '' &&
2208 $this->mNamespace
!= NS_MAIN
) {
2211 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2212 // IP names are not allowed for accounts, and can only be referring to
2213 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2214 // there are numerous ways to present the same IP. Having sp:contribs scan
2215 // them all is silly and having some show the edits and others not is
2216 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2217 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2218 IP
::sanitizeIP( $dbkey ) : $dbkey;
2219 // Any remaining initial :s are illegal.
2220 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2225 $this->mDbkeyform
= $dbkey;
2226 $this->mUrlform
= wfUrlencode( $dbkey );
2228 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2234 * Set the fragment for this title. Removes the first character from the
2235 * specified fragment before setting, so it assumes you're passing it with
2238 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2239 * Still in active use privately.
2241 * @param $fragment \type{\string} text
2243 public function setFragment( $fragment ) {
2244 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2248 * Get a Title object associated with the talk page of this article
2249 * @return \type{Title} the object for the talk page
2251 public function getTalkPage() {
2252 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2256 * Get a title object associated with the subject page of this
2259 * @return \type{Title} the object for the subject page
2261 public function getSubjectPage() {
2262 // Is this the same title?
2263 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2264 if( $this->getNamespace() == $subjectNS ) {
2267 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2271 * Get an array of Title objects linking to this Title
2272 * Also stores the IDs in the link cache.
2274 * WARNING: do not use this function on arbitrary user-supplied titles!
2275 * On heavily-used templates it will max out the memory.
2277 * @param $options \type{\string} may be FOR UPDATE
2278 * @return \type{\arrayof{Title}} the Title objects linking here
2280 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2281 $linkCache = LinkCache
::singleton();
2284 $db = wfGetDB( DB_MASTER
);
2286 $db = wfGetDB( DB_SLAVE
);
2289 $res = $db->select( array( 'page', $table ),
2290 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2292 "{$prefix}_from=page_id",
2293 "{$prefix}_namespace" => $this->getNamespace(),
2294 "{$prefix}_title" => $this->getDBkey() ),
2299 if ( $db->numRows( $res ) ) {
2300 foreach( $res as $row ) {
2301 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2302 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2303 $retVal[] = $titleObj;
2307 $db->freeResult( $res );
2312 * Get an array of Title objects using this Title as a template
2313 * Also stores the IDs in the link cache.
2315 * WARNING: do not use this function on arbitrary user-supplied titles!
2316 * On heavily-used templates it will max out the memory.
2318 * @param $options \type{\string} may be FOR UPDATE
2319 * @return \type{\arrayof{Title}} the Title objects linking here
2321 public function getTemplateLinksTo( $options = '' ) {
2322 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2326 * Get an array of Title objects referring to non-existent articles linked from this page
2328 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2329 * @param $options \type{\string} may be FOR UPDATE
2330 * @return \type{\arrayof{Title}} the Title objects
2332 public function getBrokenLinksFrom( $options = '' ) {
2333 if ( $this->getArticleId() == 0 ) {
2334 # All links from article ID 0 are false positives
2339 $db = wfGetDB( DB_MASTER
);
2341 $db = wfGetDB( DB_SLAVE
);
2344 $res = $db->safeQuery(
2345 "SELECT pl_namespace, pl_title
2348 ON pl_namespace=page_namespace
2349 AND pl_title=page_title
2351 AND page_namespace IS NULL
2353 $db->tableName( 'pagelinks' ),
2354 $db->tableName( 'page' ),
2355 $this->getArticleId(),
2359 if ( $db->numRows( $res ) ) {
2360 foreach( $res as $row ) {
2361 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2364 $db->freeResult( $res );
2370 * Get a list of URLs to purge from the Squid cache when this
2373 * @return \type{\arrayof{\string}} the URLs
2375 public function getSquidURLs() {
2379 $this->getInternalURL(),
2380 $this->getInternalURL( 'action=history' )
2383 // purge variant urls as well
2384 if($wgContLang->hasVariants()){
2385 $variants = $wgContLang->getVariants();
2386 foreach($variants as $vCode){
2387 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2388 $urls[] = $this->getInternalURL('',$vCode);
2396 * Purge all applicable Squid URLs
2398 public function purgeSquid() {
2400 if ( $wgUseSquid ) {
2401 $urls = $this->getSquidURLs();
2402 $u = new SquidUpdate( $urls );
2408 * Move this page without authentication
2409 * @param &$nt \type{Title} the new page Title
2411 public function moveNoAuth( &$nt ) {
2412 return $this->moveTo( $nt, false );
2416 * Check whether a given move operation would be valid.
2417 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2418 * @param &$nt \type{Title} the new title
2419 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2421 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2422 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2424 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2429 // Normally we'd add this to $errors, but we'll get
2430 // lots of syntax errors if $nt is not an object
2431 return array(array('badtitletext'));
2433 if( $this->equals( $nt ) ) {
2434 $errors[] = array('selfmove');
2436 if( !$this->isMovable() ) {
2437 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2439 if ( !$nt->isMovable() ) {
2440 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2443 $oldid = $this->getArticleID();
2444 $newid = $nt->getArticleID();
2446 if ( strlen( $nt->getDBkey() ) < 1 ) {
2447 $errors[] = array('articleexists');
2449 if ( ( '' == $this->getDBkey() ) ||
2451 ( '' == $nt->getDBkey() ) ) {
2452 $errors[] = array('badarticleerror');
2455 // Image-specific checks
2456 if( $this->getNamespace() == NS_IMAGE
) {
2457 $file = wfLocalFile( $this );
2458 if( $file->exists() ) {
2459 if( $nt->getNamespace() != NS_IMAGE
) {
2460 $errors[] = array('imagenocrossnamespace');
2462 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2463 $errors[] = array('imageinvalidfilename');
2465 if( !File
::checkExtensionCompatibility( $file, $nt->getDBKey() ) ) {
2466 $errors[] = array('imagetypemismatch');
2472 $errors = wfMergeErrorArrays( $errors,
2473 $this->getUserPermissionsErrors('move', $wgUser),
2474 $this->getUserPermissionsErrors('edit', $wgUser),
2475 $nt->getUserPermissionsErrors('move-target', $wgUser),
2476 $nt->getUserPermissionsErrors('edit', $wgUser) );
2479 $match = EditPage
::matchSpamRegex( $reason );
2480 if( $match !== false ) {
2481 // This is kind of lame, won't display nice
2482 $errors[] = array('spamprotectiontext');
2486 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2487 $errors[] = array('hookaborted', $err);
2490 # The move is allowed only if (1) the target doesn't exist, or
2491 # (2) the target is a redirect to the source, and has no history
2492 # (so we can undo bad moves right after they're done).
2494 if ( 0 != $newid ) { # Target exists; check for validity
2495 if ( ! $this->isValidMoveTarget( $nt ) ) {
2496 $errors[] = array('articleexists');
2499 $tp = $nt->getTitleProtection();
2500 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2501 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2502 $errors[] = array('cantmove-titleprotected');
2511 * Move a title to a new location
2512 * @param &$nt \type{Title} the new title
2513 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2515 * @param $reason \type{\string} The reason for the move
2516 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2517 * Ignored if the user doesn't have the suppressredirect right.
2518 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2520 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2521 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2522 if( is_array( $err ) ) {
2526 $pageid = $this->getArticleID();
2527 $protected = $this->isProtected();
2528 if( $nt->exists() ) {
2529 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2530 $pageCountChange = ($createRedirect ?
0 : -1);
2531 } else { # Target didn't exist, do normal move.
2532 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2533 $pageCountChange = ($createRedirect ?
1 : 0);
2536 if( is_array( $err ) ) {
2539 $redirid = $this->getArticleID();
2541 // Category memberships include a sort key which may be customized.
2542 // If it's left as the default (the page title), we need to update
2543 // the sort key to match the new title.
2545 // Be careful to avoid resetting cl_timestamp, which may disturb
2546 // time-based lists on some sites.
2548 // Warning -- if the sort key is *explicitly* set to the old title,
2549 // we can't actually distinguish it from a default here, and it'll
2550 // be set to the new title even though it really shouldn't.
2551 // It'll get corrected on the next edit, but resetting cl_timestamp.
2552 $dbw = wfGetDB( DB_MASTER
);
2553 $dbw->update( 'categorylinks',
2555 'cl_sortkey' => $nt->getPrefixedText(),
2556 'cl_timestamp=cl_timestamp' ),
2558 'cl_from' => $pageid,
2559 'cl_sortkey' => $this->getPrefixedText() ),
2563 # Protect the redirect title as the title used to be...
2564 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2566 'pr_page' => $redirid,
2567 'pr_type' => 'pr_type',
2568 'pr_level' => 'pr_level',
2569 'pr_cascade' => 'pr_cascade',
2570 'pr_user' => 'pr_user',
2571 'pr_expiry' => 'pr_expiry'
2573 array( 'pr_page' => $pageid ),
2577 # Update the protection log
2578 $log = new LogPage( 'protect' );
2579 $comment = wfMsgForContent('prot_1movedto2',$this->getPrefixedText(), $nt->getPrefixedText() );
2580 if( $reason ) $comment .= ': ' . $reason;
2581 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2585 $oldnamespace = $this->getNamespace() & ~
1;
2586 $newnamespace = $nt->getNamespace() & ~
1;
2587 $oldtitle = $this->getDBkey();
2588 $newtitle = $nt->getDBkey();
2590 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2591 WatchedItem
::duplicateEntries( $this, $nt );
2594 # Update search engine
2595 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2597 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2601 if( $this->isContentPage() && !$nt->isContentPage() ) {
2602 # No longer a content page
2603 # Not viewed, edited, removing
2604 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2605 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2606 # Now a content page
2607 # Not viewed, edited, adding
2608 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2609 } elseif( $pageCountChange ) {
2611 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2618 # Update message cache for interface messages
2619 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2620 global $wgMessageCache;
2621 $oldarticle = new Article( $this );
2622 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2623 $newarticle = new Article( $nt );
2624 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2628 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2633 * Move page to a title which is at present a redirect to the
2636 * @param &$nt \type{Title} the page to move to, which should currently
2638 * @param $reason \type{\string} The reason for the move
2639 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2640 * Ignored if the user doesn't have the suppressredirect right
2642 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2643 global $wgUseSquid, $wgUser;
2644 $fname = 'Title::moveOverExistingRedirect';
2645 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2648 $comment .= ": $reason";
2651 $now = wfTimestampNow();
2652 $newid = $nt->getArticleID();
2653 $oldid = $this->getArticleID();
2654 $latest = $this->getLatestRevID();
2656 $dbw = wfGetDB( DB_MASTER
);
2658 # Delete the old redirect. We don't save it to history since
2659 # by definition if we've got here it's rather uninteresting.
2660 # We have to remove it so that the next step doesn't trigger
2661 # a conflict on the unique namespace+title index...
2662 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2663 if ( !$dbw->cascadingDeletes() ) {
2664 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2665 global $wgUseTrackbacks;
2666 if ($wgUseTrackbacks)
2667 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2668 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2669 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2670 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2671 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2672 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2673 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2674 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2677 # Save a null revision in the page's history notifying of the move
2678 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2679 $nullRevId = $nullRevision->insertOn( $dbw );
2681 $article = new Article( $this );
2682 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2684 # Change the name of the target page:
2685 $dbw->update( 'page',
2687 'page_touched' => $dbw->timestamp($now),
2688 'page_namespace' => $nt->getNamespace(),
2689 'page_title' => $nt->getDBkey(),
2690 'page_latest' => $nullRevId,
2692 /* WHERE */ array( 'page_id' => $oldid ),
2695 $nt->resetArticleID( $oldid );
2697 # Recreate the redirect, this time in the other direction.
2698 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2699 $mwRedir = MagicWord
::get( 'redirect' );
2700 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2701 $redirectArticle = new Article( $this );
2702 $newid = $redirectArticle->insertOn( $dbw );
2703 $redirectRevision = new Revision( array(
2705 'comment' => $comment,
2706 'text' => $redirectText ) );
2707 $redirectRevision->insertOn( $dbw );
2708 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2710 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2712 # Now, we record the link from the redirect to the new title.
2713 # It should have no other outgoing links...
2714 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2715 $dbw->insert( 'pagelinks',
2717 'pl_from' => $newid,
2718 'pl_namespace' => $nt->getNamespace(),
2719 'pl_title' => $nt->getDBkey() ),
2722 $this->resetArticleID( 0 );
2725 # Move an image if this is a file
2726 if( $this->getNamespace() == NS_IMAGE
) {
2727 $file = wfLocalFile( $this );
2728 if( $file->exists() ) {
2729 $status = $file->move( $nt );
2730 if( !$status->isOk() ) {
2732 return $status->getErrorsArray();
2738 $log = new LogPage( 'move' );
2739 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2742 if ( $wgUseSquid ) {
2743 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2744 $u = new SquidUpdate( $urls );
2751 * Move page to non-existing title.
2752 * @param &$nt \type{Title} the new Title
2753 * @param $reason \type{\string} The reason for the move
2754 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2755 * Ignored if the user doesn't have the suppressredirect right
2757 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2758 global $wgUseSquid, $wgUser;
2759 $fname = 'MovePageForm::moveToNewTitle';
2760 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2762 $comment .= wfMsgExt( 'colon-separator',
2763 array( 'escapenoentities', 'content' ) );
2764 $comment .= $reason;
2767 $newid = $nt->getArticleID();
2768 $oldid = $this->getArticleID();
2769 $latest = $this->getLatestRevId();
2771 $dbw = wfGetDB( DB_MASTER
);
2772 $now = $dbw->timestamp();
2774 # Save a null revision in the page's history notifying of the move
2775 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2776 $nullRevId = $nullRevision->insertOn( $dbw );
2778 $article = new Article( $this );
2779 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest) );
2782 $dbw->update( 'page',
2784 'page_touched' => $now,
2785 'page_namespace' => $nt->getNamespace(),
2786 'page_title' => $nt->getDBkey(),
2787 'page_latest' => $nullRevId,
2789 /* WHERE */ array( 'page_id' => $oldid ),
2792 $nt->resetArticleID( $oldid );
2794 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2796 $mwRedir = MagicWord
::get( 'redirect' );
2797 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2798 $redirectArticle = new Article( $this );
2799 $newid = $redirectArticle->insertOn( $dbw );
2800 $redirectRevision = new Revision( array(
2802 'comment' => $comment,
2803 'text' => $redirectText ) );
2804 $redirectRevision->insertOn( $dbw );
2805 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2807 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false) );
2809 # Record the just-created redirect's linking to the page
2810 $dbw->insert( 'pagelinks',
2812 'pl_from' => $newid,
2813 'pl_namespace' => $nt->getNamespace(),
2814 'pl_title' => $nt->getDBkey() ),
2817 $this->resetArticleID( 0 );
2820 # Move an image if this is a file
2821 if( $this->getNamespace() == NS_IMAGE
) {
2822 $file = wfLocalFile( $this );
2823 if( $file->exists() ) {
2824 $status = $file->move( $nt );
2825 if( !$status->isOk() ) {
2827 return $status->getErrorsArray();
2833 $log = new LogPage( 'move' );
2834 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2836 # Purge caches as per article creation
2837 Article
::onArticleCreate( $nt );
2839 # Purge old title from squid
2840 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2841 $this->purgeSquid();
2846 * Checks if this page is just a one-rev redirect.
2847 * Adds lock, so don't use just for light purposes.
2849 * @param $curId \type{int} page ID, optional
2850 * @return \type{\bool} TRUE or FALSE
2852 public function isSingleRevRedirect( $curId = 0 ) {
2853 $dbw = wfGetDB( DB_MASTER
);
2854 $curId = $curId ?
$curId : $this->getArticleId();
2860 $row = $dbw->selectRow( 'page',
2861 array( 'page_is_redirect', 'page_latest' ),
2862 array( 'page_id' => $curId ),
2866 # Cache some fields we may want
2867 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
2868 $this->mLatestID
= $row ?
intval($row->page_latest
) : false;
2869 if( $this->mRedirect
) {
2872 # Does the article have a history?
2873 $row = $dbw->selectField( array( 'page', 'revision'),
2875 array( 'page_namespace' => $this->getNamespace(),
2876 'page_title' => $this->getDBkey(),
2878 'page_latest != rev_id'
2883 # Return true if there was no history
2884 return ($row === false);
2888 * Checks if $this can be moved to a given Title
2889 * - Selects for update, so don't call it unless you mean business
2891 * @param &$nt \type{Title} the new title to check
2892 * @return \type{\bool} TRUE or FALSE
2894 public function isValidMoveTarget( $nt ) {
2895 $dbw = wfGetDB( DB_MASTER
);
2896 # Is it an existsing file?
2897 if( $nt->getNamespace() == NS_IMAGE
) {
2898 $file = wfLocalFile( $nt );
2899 if( $file->exists() ) {
2900 wfDebug( __METHOD__
. ": file exists\n" );
2904 # Is it a redirect with no history?
2905 if( !$nt->isSingleRevRedirect() ) {
2906 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
2909 # Get the article text
2910 $rev = Revision
::newFromTitle( $nt );
2911 $text = $rev->getText();
2912 # Does the redirect point to the source?
2913 # Or is it a broken self-redirect, usually caused by namespace collisions?
2915 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2916 $redirTitle = Title
::newFromText( $m[1] );
2917 if( !is_object( $redirTitle ) ||
2918 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2919 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2920 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2925 wfDebug( __METHOD__
. ": failsafe\n" );
2932 * Can this title be added to a user's watchlist?
2934 * @return \type{\bool} TRUE or FALSE
2936 public function isWatchable() {
2937 return !$this->isExternal()
2938 && MWNamespace
::isWatchable( $this->getNamespace() );
2942 * Get categories to which this Title belongs and return an array of
2943 * categories' names.
2945 * @return \type{\array} array an array of parents in the form:
2946 * $parent => $currentarticle
2948 public function getParentCategories() {
2951 $titlekey = $this->getArticleId();
2952 $dbr = wfGetDB( DB_SLAVE
);
2953 $categorylinks = $dbr->tableName( 'categorylinks' );
2956 $sql = "SELECT * FROM $categorylinks"
2957 ." WHERE cl_from='$titlekey'"
2958 ." AND cl_from <> '0'"
2959 ." ORDER BY cl_sortkey";
2961 $res = $dbr->query( $sql );
2963 if( $dbr->numRows( $res ) > 0 ) {
2964 foreach( $res as $row )
2965 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
2966 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
2967 $dbr->freeResult( $res );
2975 * Get a tree of parent categories
2976 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
2977 * @return \type{\array} Tree of parent categories
2979 public function getParentCategoryTree( $children = array() ) {
2981 $parents = $this->getParentCategories();
2984 foreach( $parents as $parent => $current ) {
2985 if ( array_key_exists( $parent, $children ) ) {
2986 # Circular reference
2987 $stack[$parent] = array();
2989 $nt = Title
::newFromText($parent);
2991 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
3003 * Get an associative array for selecting this title from
3006 * @return \type{\array} Selection array
3008 public function pageCond() {
3009 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3013 * Get the revision ID of the previous revision
3015 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3016 * @param $flags \type{\int} GAID_FOR_UPDATE
3017 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3019 public function getPreviousRevisionID( $revId, $flags=0 ) {
3020 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3021 return $db->selectField( 'revision', 'rev_id',
3023 'rev_page' => $this->getArticleId($flags),
3024 'rev_id < ' . intval( $revId )
3027 array( 'ORDER BY' => 'rev_id DESC' )
3032 * Get the revision ID of the next revision
3034 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3035 * @param $flags \type{\int} GAID_FOR_UPDATE
3036 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3038 public function getNextRevisionID( $revId, $flags=0 ) {
3039 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3040 return $db->selectField( 'revision', 'rev_id',
3042 'rev_page' => $this->getArticleId($flags),
3043 'rev_id > ' . intval( $revId )
3046 array( 'ORDER BY' => 'rev_id' )
3051 * Get the oldest revision timestamp of this page
3053 * @return string, MW timestamp
3055 public function getEarliestRevTime() {
3056 $dbr = wfGetDB( DB_SLAVE
);
3057 if( $this->exists() ) {
3058 $min = $dbr->selectField( 'revision',
3059 'MIN(rev_timestamp)',
3060 array( 'rev_page' => $this->getArticleId() ),
3062 return wfTimestampOrNull( TS_MW
, $min );
3068 * Get the number of revisions between the given revision IDs.
3069 * Used for diffs and other things that really need it.
3071 * @param $old \type{\int} Revision ID.
3072 * @param $new \type{\int} Revision ID.
3073 * @return \type{\int} Number of revisions between these IDs.
3075 public function countRevisionsBetween( $old, $new ) {
3076 $dbr = wfGetDB( DB_SLAVE
);
3077 return $dbr->selectField( 'revision', 'count(*)',
3078 'rev_page = ' . intval( $this->getArticleId() ) .
3079 ' AND rev_id > ' . intval( $old ) .
3080 ' AND rev_id < ' . intval( $new ),
3082 array( 'USE INDEX' => 'PRIMARY' ) );
3086 * Compare with another title.
3088 * @param \type{Title} $title
3089 * @return \type{\bool} TRUE or FALSE
3091 public function equals( Title
$title ) {
3092 // Note: === is necessary for proper matching of number-like titles.
3093 return $this->getInterwiki() === $title->getInterwiki()
3094 && $this->getNamespace() == $title->getNamespace()
3095 && $this->getDBkey() === $title->getDBkey();
3099 * Callback for usort() to do title sorts by (namespace, title)
3101 static function compare( $a, $b ) {
3102 if( $a->getNamespace() == $b->getNamespace() ) {
3103 return strcmp( $a->getText(), $b->getText() );
3105 return $a->getNamespace() - $b->getNamespace();
3110 * Return a string representation of this title
3112 * @return \type{\string} String representation of this title
3114 public function __toString() {
3115 return $this->getPrefixedText();
3119 * Check if page exists
3120 * @return \type{\bool} TRUE or FALSE
3122 public function exists() {
3123 return $this->getArticleId() != 0;
3127 * Do we know that this title definitely exists, or should we otherwise
3128 * consider that it exists?
3130 * @return \type{\bool} TRUE or FALSE
3132 public function isAlwaysKnown() {
3133 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3134 // the full l10n of that language to be loaded. That takes much memory and
3135 // isn't needed. So we strip the language part away.
3136 // Also, extension messages which are not loaded, are shown as red, because
3137 // we don't call MessageCache::loadAllMessages.
3138 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3139 return $this->isExternal()
3140 ||
( $this->mNamespace
== NS_MAIN
&& $this->mDbkeyform
== '' )
3141 ||
( $this->mNamespace
== NS_MEDIAWIKI
&& wfMsgWeirdKey( $basename ) );
3145 * Update page_touched timestamps and send squid purge messages for
3146 * pages linking to this title. May be sent to the job queue depending
3147 * on the number of links. Typically called on create and delete.
3149 public function touchLinks() {
3150 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3153 if ( $this->getNamespace() == NS_CATEGORY
) {
3154 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3160 * Get the last touched timestamp
3161 * @param Database $db, optional db
3162 * @return \type{\string} Last touched timestamp
3164 public function getTouched( $db = NULL ) {
3165 $db = isset($db) ?
$db : wfGetDB( DB_SLAVE
);
3166 $touched = $db->selectField( 'page', 'page_touched',
3168 'page_namespace' => $this->getNamespace(),
3169 'page_title' => $this->getDBkey()
3176 * Get the timestamp when this page was updated since the user last saw it.
3178 * @return mixed string/NULL
3180 public function getNotificationTimestamp( $user = NULL ) {
3181 global $wgUser, $wgShowUpdatedMarker;
3182 // Assume current user if none given
3183 if( !$user ) $user = $wgUser;
3184 // Check cache first
3185 $uid = $user->getId();
3186 if( isset($this->mNotificationTimestamp
[$uid]) ) {
3187 return $this->mNotificationTimestamp
[$uid];
3189 if( !$uid ||
!$wgShowUpdatedMarker ) {
3190 return $this->mNotificationTimestamp
[$uid] = false;
3192 // Don't cache too much!
3193 if( count($this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3194 $this->mNotificationTimestamp
= array();
3196 $dbr = wfGetDB( DB_SLAVE
);
3197 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3198 'wl_notificationtimestamp',
3199 array( 'wl_namespace' => $this->getNamespace(),
3200 'wl_title' => $this->getDBkey(),
3201 'wl_user' => $user->getId()
3205 return $this->mNotificationTimestamp
[$uid];
3209 * Get the trackback URL for this page
3210 * @return \type{\string} Trackback URL
3212 public function trackbackURL() {
3213 global $wgScriptPath, $wgServer;
3215 return "$wgServer$wgScriptPath/trackback.php?article="
3216 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3220 * Get the trackback RDF for this page
3221 * @return \type{\string} Trackback RDF
3223 public function trackbackRDF() {
3224 $url = htmlspecialchars($this->getFullURL());
3225 $title = htmlspecialchars($this->getText());
3226 $tburl = $this->trackbackURL();
3228 // Autodiscovery RDF is placed in comments so HTML validator
3229 // won't barf. This is a rather icky workaround, but seems
3230 // frequently used by this kind of RDF thingy.
3232 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3234 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3235 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3236 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3239 dc:identifier=\"$url\"
3241 trackback:ping=\"$tburl\" />
3247 * Generate strings used for xml 'id' names in monobook tabs
3248 * @return \type{\string} XML 'id' name
3250 public function getNamespaceKey() {
3252 switch ($this->getNamespace()) {
3255 return 'nstab-main';
3258 return 'nstab-user';
3260 return 'nstab-media';
3262 return 'nstab-special';
3264 case NS_PROJECT_TALK
:
3265 return 'nstab-project';
3268 return 'nstab-image';
3270 case NS_MEDIAWIKI_TALK
:
3271 return 'nstab-mediawiki';
3273 case NS_TEMPLATE_TALK
:
3274 return 'nstab-template';
3277 return 'nstab-help';
3279 case NS_CATEGORY_TALK
:
3280 return 'nstab-category';
3282 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3287 * Returns true if this title resolves to the named special page
3288 * @param $name \type{\string} The special page name
3290 public function isSpecial( $name ) {
3291 if ( $this->getNamespace() == NS_SPECIAL
) {
3292 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3293 if ( $name == $thisName ) {
3301 * If the Title refers to a special page alias which is not the local default,
3302 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3304 public function fixSpecialName() {
3305 if ( $this->getNamespace() == NS_SPECIAL
) {
3306 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3307 if ( $canonicalName ) {
3308 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3309 if ( $localName != $this->mDbkeyform
) {
3310 return Title
::makeTitle( NS_SPECIAL
, $localName );
3318 * Is this Title in a namespace which contains content?
3319 * In other words, is this a content page, for the purposes of calculating
3322 * @return \type{\bool} TRUE or FALSE
3324 public function isContentPage() {
3325 return MWNamespace
::isContent( $this->getNamespace() );
3329 * Get all extant redirects to this Title
3331 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3332 * NULL to consider all namespaces
3333 * @return \type{\arrayof{Title}} Redirects to this title
3335 public function getRedirectsHere( $ns = null ) {
3338 $dbr = wfGetDB( DB_SLAVE
);
3340 'rd_namespace' => $this->getNamespace(),
3341 'rd_title' => $this->getDBkey(),
3344 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3346 $res = $dbr->select(
3347 array( 'redirect', 'page' ),
3348 array( 'page_namespace', 'page_title' ),
3354 foreach( $res as $row ) {
3355 $redirs[] = self
::newFromRow( $row );