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
297 * This will only return the very next target, useful for
298 * the redirect table and other checks that don't need full recursion
300 * @param $text \type{\string} Text with possible redirect
301 * @return \type{Title} The corresponding Title
303 public static function newFromRedirect( $text ) {
304 return self
::newFromRedirectInternal( $text );
308 * Extract a redirect destination from a string and return the
309 * Title, or null if the text doesn't contain a valid redirect
310 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
311 * in order to provide (hopefully) the Title of the final destination instead of another redirect
313 * @param $text \type{\string} Text with possible redirect
314 * @return \type{Title} The corresponding Title
316 public static function newFromRedirectRecurse( $text ) {
317 $titles = self
::newFromRedirectArray( $text );
318 return $titles ?
array_pop( $titles ) : null;
322 * Extract a redirect destination from a string and return an
323 * array of Titles, or null if the text doesn't contain a valid redirect
324 * The last element in the array is the final destination after all redirects
325 * have been resolved (up to $wgMaxRedirects times)
327 * @param $text \type{\string} Text with possible redirect
328 * @return \type{\array} Array of Titles, with the destination last
330 public static function newFromRedirectArray( $text ) {
331 global $wgMaxRedirects;
332 // are redirects disabled?
333 if( $wgMaxRedirects < 1 )
335 $title = self
::newFromRedirectInternal( $text );
336 if( is_null( $title ) )
338 // recursive check to follow double redirects
339 $recurse = $wgMaxRedirects;
340 $titles = array( $title );
341 while( --$recurse >= 0 ) {
342 if( $title->isRedirect() ) {
343 $article = new Article( $title, 0 );
344 $newtitle = $article->getRedirectTarget();
348 // Redirects to some special pages are not permitted
349 if( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
350 // the new title passes the checks, so make that our current title so that further recursion can be checked
352 $titles[] = $newtitle;
361 * Really extract the redirect destination
362 * Do not call this function directly, use one of the newFromRedirect* functions above
364 * @param $text \type{\string} Text with possible redirect
365 * @return \type{Title} The corresponding Title
367 protected static function newFromRedirectInternal( $text ) {
368 $redir = MagicWord
::get( 'redirect' );
370 if( $redir->matchStartAndRemove( $text ) ) {
371 // Extract the first link and see if it's usable
372 // Ensure that it really does come directly after #REDIRECT
373 // Some older redirects included a colon, so don't freak about that!
375 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
376 // Strip preceding colon used to "escape" categories, etc.
377 // and URL-decode links
378 if( strpos( $m[1], '%' ) !== false ) {
379 // Match behavior of inline link parsing here;
380 // don't interpret + as " " most of the time!
381 // It might be safe to just use rawurldecode instead, though.
382 $m[1] = urldecode( ltrim( $m[1], ':' ) );
384 $title = Title
::newFromText( $m[1] );
385 // If the title is a redirect to bad special pages or is invalid, return null
386 if( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
395 #----------------------------------------------------------------------------
397 #----------------------------------------------------------------------------
400 * Get the prefixed DB key associated with an ID
401 * @param $id \type{\int} the page_id of the article
402 * @return \type{Title} an object representing the article, or NULL
403 * if no such article was found
405 public static function nameOf( $id ) {
406 $dbr = wfGetDB( DB_SLAVE
);
408 $s = $dbr->selectRow( 'page',
409 array( 'page_namespace','page_title' ),
410 array( 'page_id' => $id ),
412 if ( $s === false ) { return NULL; }
414 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
419 * Get a regex character class describing the legal characters in a link
420 * @return \type{\string} the list of characters, not delimited
422 public static function legalChars() {
423 global $wgLegalTitleChars;
424 return $wgLegalTitleChars;
428 * Get a string representation of a title suitable for
429 * including in a search index
431 * @param $ns \type{\int} a namespace index
432 * @param $title \type{\string} text-form main part
433 * @return \type{\string} a stripped-down title string ready for the
436 public static function indexTitle( $ns, $title ) {
439 $lc = SearchEngine
::legalSearchChars() . '&#;';
440 $t = $wgContLang->stripForSearch( $title );
441 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
442 $t = $wgContLang->lc( $t );
445 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
446 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
448 $t = preg_replace( "/\\s+/", ' ', $t );
450 if ( $ns == NS_FILE
) {
451 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
457 * Make a prefixed DB key from a DB key and a namespace index
458 * @param $ns \type{\int} numerical representation of the namespace
459 * @param $title \type{\string} the DB key form the title
460 * @param $fragment \type{\string} The link fragment (after the "#")
461 * @return \type{\string} the prefixed form of the title
463 public static function makeName( $ns, $title, $fragment = '' ) {
466 $namespace = $wgContLang->getNsText( $ns );
467 $name = $namespace == '' ?
$title : "$namespace:$title";
468 if ( strval( $fragment ) != '' ) {
469 $name .= '#' . $fragment;
475 * Returns the URL associated with an interwiki prefix
476 * @param $key \type{\string} the interwiki prefix (e.g. "MeatBall")
477 * @return \type{\string} the associated URL, containing "$1",
478 * which should be replaced by an article title
480 * @deprecated See Interwiki class
482 public function getInterwikiLink( $key ) {
483 return Interwiki
::fetch( $key )->getURL( );
487 * Determine whether the object refers to a page within
490 * @return \type{\bool} TRUE if this is an in-project interwiki link
491 * or a wikilink, FALSE otherwise
493 public function isLocal() {
494 if ( $this->mInterwiki
!= '' ) {
495 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
502 * Determine whether the object refers to a page within
503 * this project and is transcludable.
505 * @return \type{\bool} TRUE if this is transcludable
507 public function isTrans() {
508 if ($this->mInterwiki
== '')
511 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
515 * Escape a text fragment, say from a link, for a URL
517 static function escapeFragmentForURL( $fragment ) {
518 global $wgEnforceHtmlIds;
519 # Note that we don't urlencode the fragment. urlencoded Unicode
520 # fragments appear not to work in IE (at least up to 7) or in at least
521 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
522 # to care if they aren't encoded.
523 return Sanitizer
::escapeId( $fragment,
524 $wgEnforceHtmlIds ?
'noninitial' : 'xml' );
527 #----------------------------------------------------------------------------
529 #----------------------------------------------------------------------------
531 /** Simple accessors */
533 * Get the text form (spaces not underscores) of the main part
534 * @return \type{\string} Main part of the title
536 public function getText() { return $this->mTextform
; }
538 * Get the URL-encoded form of the main part
539 * @return \type{\string} Main part of the title, URL-encoded
541 public function getPartialURL() { return $this->mUrlform
; }
543 * Get the main part with underscores
544 * @return \type{\string} Main part of the title, with underscores
546 public function getDBkey() { return $this->mDbkeyform
; }
548 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
549 * @return \type{\int} Namespace index
551 public function getNamespace() { return $this->mNamespace
; }
553 * Get the namespace text
554 * @return \type{\string} Namespace text
556 public function getNsText() {
557 global $wgContLang, $wgCanonicalNamespaceNames;
559 if ( '' != $this->mInterwiki
) {
560 // This probably shouldn't even happen. ohh man, oh yuck.
561 // But for interwiki transclusion it sometimes does.
562 // Shit. Shit shit shit.
564 // Use the canonical namespaces if possible to try to
565 // resolve a foreign namespace.
566 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
567 return $wgCanonicalNamespaceNames[$this->mNamespace
];
570 return $wgContLang->getNsText( $this->mNamespace
);
573 * Get the DB key with the initial letter case as specified by the user
574 * @return \type{\string} DB key
576 function getUserCaseDBKey() {
577 return $this->mUserCaseDBKey
;
580 * Get the namespace text of the subject (rather than talk) page
581 * @return \type{\string} Namespace text
583 public function getSubjectNsText() {
585 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
588 * Get the namespace text of the talk page
589 * @return \type{\string} Namespace text
591 public function getTalkNsText() {
593 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
596 * Could this title have a corresponding talk page?
597 * @return \type{\bool} TRUE or FALSE
599 public function canTalk() {
600 return( MWNamespace
::canTalk( $this->mNamespace
) );
603 * Get the interwiki prefix (or null string)
604 * @return \type{\string} Interwiki prefix
606 public function getInterwiki() { return $this->mInterwiki
; }
608 * Get the Title fragment (i.e.\ the bit after the #) in text form
609 * @return \type{\string} Title fragment
611 public function getFragment() { return $this->mFragment
; }
613 * Get the fragment in URL form, including the "#" character if there is one
614 * @return \type{\string} Fragment in URL form
616 public function getFragmentForURL() {
617 if ( $this->mFragment
== '' ) {
620 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
624 * Get the default namespace index, for when there is no namespace
625 * @return \type{\int} Default namespace index
627 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
630 * Get title for search index
631 * @return \type{\string} a stripped-down title string ready for the
634 public function getIndexTitle() {
635 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
639 * Get the prefixed database key form
640 * @return \type{\string} the prefixed title, with underscores and
641 * any interwiki and namespace prefixes
643 public function getPrefixedDBkey() {
644 $s = $this->prefix( $this->mDbkeyform
);
645 $s = str_replace( ' ', '_', $s );
650 * Get the prefixed title with spaces.
651 * This is the form usually used for display
652 * @return \type{\string} the prefixed title, with spaces
654 public function getPrefixedText() {
655 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
656 $s = $this->prefix( $this->mTextform
);
657 $s = str_replace( '_', ' ', $s );
658 $this->mPrefixedText
= $s;
660 return $this->mPrefixedText
;
664 * Get the prefixed title with spaces, plus any fragment
665 * (part beginning with '#')
666 * @return \type{\string} the prefixed title, with spaces and
667 * the fragment, including '#'
669 public function getFullText() {
670 $text = $this->getPrefixedText();
671 if( '' != $this->mFragment
) {
672 $text .= '#' . $this->mFragment
;
678 * Get the base name, i.e. the leftmost parts before the /
679 * @return \type{\string} Base name
681 public function getBaseText() {
682 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
683 return $this->getText();
686 $parts = explode( '/', $this->getText() );
687 # Don't discard the real title if there's no subpage involved
688 if( count( $parts ) > 1 )
689 unset( $parts[ count( $parts ) - 1 ] );
690 return implode( '/', $parts );
694 * Get the lowest-level subpage name, i.e. the rightmost part after /
695 * @return \type{\string} Subpage name
697 public function getSubpageText() {
698 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
699 return( $this->mTextform
);
701 $parts = explode( '/', $this->mTextform
);
702 return( $parts[ count( $parts ) - 1 ] );
706 * Get a URL-encoded form of the subpage text
707 * @return \type{\string} URL-encoded subpage name
709 public function getSubpageUrlForm() {
710 $text = $this->getSubpageText();
711 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
716 * Get a URL-encoded title (not an actual URL) including interwiki
717 * @return \type{\string} the URL-encoded form
719 public function getPrefixedURL() {
720 $s = $this->prefix( $this->mDbkeyform
);
721 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
726 * Get a real URL referring to this title, with interwiki link and
729 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
730 * links. Can be specified as an associative array as well, e.g.,
731 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
732 * @param $variant \type{\string} language variant of url (for sr, zh..)
733 * @return \type{\string} the URL
735 public function getFullURL( $query = '', $variant = false ) {
736 global $wgContLang, $wgServer, $wgRequest;
738 if( is_array( $query ) ) {
739 $query = wfArrayToCGI( $query );
742 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
744 $url = $this->getLocalUrl( $query, $variant );
746 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
747 // Correct fix would be to move the prepending elsewhere.
748 if ($wgRequest->getVal('action') != 'render') {
749 $url = $wgServer . $url;
752 $baseUrl = $interwiki->getURL( );
754 $namespace = wfUrlencode( $this->getNsText() );
755 if ( '' != $namespace ) {
756 # Can this actually happen? Interwikis shouldn't be parsed.
757 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
760 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
761 $url = wfAppendQuery( $url, $query );
764 # Finally, add the fragment.
765 $url .= $this->getFragmentForURL();
767 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
772 * Get a URL with no fragment or server name. If this page is generated
773 * with action=render, $wgServer is prepended.
774 * @param mixed $query an optional query string; if not specified,
775 * $wgArticlePath will be used. Can be specified as an associative array
776 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
778 * @param $variant \type{\string} language variant of url (for sr, zh..)
779 * @return \type{\string} the URL
781 public function getLocalURL( $query = '', $variant = false ) {
782 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
783 global $wgVariantArticlePath, $wgContLang, $wgUser;
785 if( is_array( $query ) ) {
786 $query = wfArrayToCGI( $query );
789 // internal links should point to same variant as current page (only anonymous users)
790 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
791 $pref = $wgContLang->getPreferredVariant(false);
792 if($pref != $wgContLang->getCode())
796 if ( $this->isExternal() ) {
797 $url = $this->getFullURL();
799 // This is currently only used for edit section links in the
800 // context of interwiki transclusion. In theory we should
801 // append the query to the end of any existing query string,
802 // but interwiki transclusion is already broken in that case.
806 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
807 if ( $query == '' ) {
808 if( $variant != false && $wgContLang->hasVariants() ) {
809 if( $wgVariantArticlePath == false ) {
810 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
812 $variantArticlePath = $wgVariantArticlePath;
814 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
815 $url = str_replace( '$1', $dbkey, $url );
817 $url = str_replace( '$1', $dbkey, $wgArticlePath );
820 global $wgActionPaths;
823 if( !empty( $wgActionPaths ) &&
824 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
826 $action = urldecode( $matches[2] );
827 if( isset( $wgActionPaths[$action] ) ) {
828 $query = $matches[1];
829 if( isset( $matches[4] ) ) $query .= $matches[4];
830 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
832 $url = wfAppendQuery( $url, $query );
836 if ( $url === false ) {
837 if ( $query == '-' ) {
840 $url = "{$wgScript}?title={$dbkey}&{$query}";
844 // FIXME: this causes breakage in various places when we
845 // actually expected a local URL and end up with dupe prefixes.
846 if ($wgRequest->getVal('action') == 'render') {
847 $url = $wgServer . $url;
850 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
855 * Get a URL that's the simplest URL that will be valid to link, locally,
856 * to the current Title. It includes the fragment, but does not include
857 * the server unless action=render is used (or the link is external). If
858 * there's a fragment but the prefixed text is empty, we just return a link
861 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
862 * query string. Keys and values will be escaped.
863 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
864 * for external links. Default is "false" (same variant as current page,
865 * for anonymous users).
866 * @return \type{\string} the URL
868 public function getLinkUrl( $query = array(), $variant = false ) {
869 if( !is_array( $query ) ) {
870 throw new MWException( 'Title::getLinkUrl passed a non-array for '.
873 if( $this->isExternal() ) {
874 return $this->getFullURL( $query );
875 } elseif( $this->getPrefixedText() === ''
876 and $this->getFragment() !== '' ) {
877 return $this->getFragmentForURL();
879 return $this->getLocalURL( $query, $variant )
880 . $this->getFragmentForURL();
885 * Get an HTML-escaped version of the URL form, suitable for
886 * using in a link, without a server name or fragment
887 * @param $query \type{\string} an optional query string
888 * @return \type{\string} the URL
890 public function escapeLocalURL( $query = '' ) {
891 return htmlspecialchars( $this->getLocalURL( $query ) );
895 * Get an HTML-escaped version of the URL form, suitable for
896 * using in a link, including the server name and fragment
898 * @param $query \type{\string} an optional query string
899 * @return \type{\string} the URL
901 public function escapeFullURL( $query = '' ) {
902 return htmlspecialchars( $this->getFullURL( $query ) );
906 * Get the URL form for an internal link.
907 * - Used in various Squid-related code, in case we have a different
908 * internal hostname for the server from the exposed one.
910 * @param $query \type{\string} an optional query string
911 * @param $variant \type{\string} language variant of url (for sr, zh..)
912 * @return \type{\string} the URL
914 public function getInternalURL( $query = '', $variant = false ) {
915 global $wgInternalServer;
916 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
917 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
922 * Get the edit URL for this Title
923 * @return \type{\string} the URL, or a null string if this is an
926 public function getEditURL() {
927 if ( '' != $this->mInterwiki
) { return ''; }
928 $s = $this->getLocalURL( 'action=edit' );
934 * Get the HTML-escaped displayable text form.
935 * Used for the title field in <a> tags.
936 * @return \type{\string} the text, including any prefixes
938 public function getEscapedText() {
939 return htmlspecialchars( $this->getPrefixedText() );
943 * Is this Title interwiki?
944 * @return \type{\bool}
946 public function isExternal() { return ( '' != $this->mInterwiki
); }
949 * Is this page "semi-protected" - the *only* protection is autoconfirm?
951 * @param @action \type{\string} Action to check (default: edit)
952 * @return \type{\bool}
954 public function isSemiProtected( $action = 'edit' ) {
955 if( $this->exists() ) {
956 $restrictions = $this->getRestrictions( $action );
957 if( count( $restrictions ) > 0 ) {
958 foreach( $restrictions as $restriction ) {
959 if( strtolower( $restriction ) != 'autoconfirmed' )
968 # If it doesn't exist, it can't be protected
974 * Does the title correspond to a protected article?
975 * @param $what \type{\string} the action the page is protected from,
976 * by default checks move and edit
977 * @return \type{\bool}
979 public function isProtected( $action = '' ) {
980 global $wgRestrictionLevels, $wgRestrictionTypes;
982 # Special pages have inherent protection
983 if( $this->getNamespace() == NS_SPECIAL
)
986 # Check regular protection levels
987 foreach( $wgRestrictionTypes as $type ){
988 if( $action == $type ||
$action == '' ) {
989 $r = $this->getRestrictions( $type );
990 foreach( $wgRestrictionLevels as $level ) {
991 if( in_array( $level, $r ) && $level != '' ) {
1002 * Is $wgUser watching this page?
1003 * @return \type{\bool}
1005 public function userIsWatching() {
1008 if ( is_null( $this->mWatched
) ) {
1009 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1010 $this->mWatched
= false;
1012 $this->mWatched
= $wgUser->isWatched( $this );
1015 return $this->mWatched
;
1019 * Can $wgUser perform $action on this page?
1020 * This skips potentially expensive cascading permission checks.
1022 * Suitable for use for nonessential UI controls in common cases, but
1023 * _not_ for functional access control.
1025 * May provide false positives, but should never provide a false negative.
1027 * @param $action \type{\string} action that permission needs to be checked for
1028 * @return \type{\bool}
1030 public function quickUserCan( $action ) {
1031 return $this->userCan( $action, false );
1035 * Determines if $wgUser is unable to edit this page because it has been protected
1036 * by $wgNamespaceProtection.
1038 * @return \type{\bool}
1040 public function isNamespaceProtected() {
1041 global $wgNamespaceProtection, $wgUser;
1042 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1043 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1044 if( $right != '' && !$wgUser->isAllowed( $right ) )
1052 * Can $wgUser perform $action on this page?
1053 * @param $action \type{\string} action that permission needs to be checked for
1054 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1055 * @return \type{\bool}
1057 public function userCan( $action, $doExpensiveQueries = true ) {
1059 return ($this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array());
1063 * Can $user perform $action on this page?
1065 * FIXME: This *does not* check throttles (User::pingLimiter()).
1067 * @param $action \type{\string}action that permission needs to be checked for
1068 * @param $user \type{User} user to check
1069 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1070 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1071 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1073 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1074 if( !StubObject
::isRealObject( $user ) ) {
1075 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1077 $wgUser->_unstub( '', 5 );
1080 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1084 global $wgEmailConfirmToEdit;
1086 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1087 $errors[] = array( 'confirmedittext' );
1090 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1091 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1092 $block = $user->mBlock
;
1094 // This is from OutputPage::blockedPage
1095 // Copied at r23888 by werdna
1097 $id = $user->blockedBy();
1098 $reason = $user->blockedFor();
1099 if( $reason == '' ) {
1100 $reason = wfMsg( 'blockednoreason' );
1104 if ( is_numeric( $id ) ) {
1105 $name = User
::whoIs( $id );
1110 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1111 $blockid = $block->mId
;
1112 $blockExpiry = $user->mBlock
->mExpiry
;
1113 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1115 if ( $blockExpiry == 'infinity' ) {
1116 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1117 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1119 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1120 if ( strpos( $option, ':' ) == false )
1123 list ($show, $value) = explode( ":", $option );
1125 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1126 $blockExpiry = $show;
1131 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1134 $intended = $user->mBlock
->mAddress
;
1136 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1137 $blockid, $blockExpiry, $intended, $blockTimestamp );
1140 // Remove the errors being ignored.
1142 foreach( $errors as $index => $error ) {
1143 $error_key = is_array($error) ?
$error[0] : $error;
1145 if (in_array( $error_key, $ignoreErrors )) {
1146 unset($errors[$index]);
1154 * Can $user perform $action on this page? This is an internal function,
1155 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1156 * checks on wfReadOnly() and blocks)
1158 * @param $action \type{\string} action that permission needs to be checked for
1159 * @param $user \type{User} user to check
1160 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1161 * @param $short \type{\bool} Set this to true to stop after the first permission error.
1162 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1164 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries=true, $short=false ) {
1165 wfProfileIn( __METHOD__
);
1169 // First stop is permissions checks, which fail most often, and which are easiest to test.
1170 if ( $action == 'move' ) {
1171 if( !$user->isAllowed( 'move-rootuserpages' )
1172 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1174 // Show user page-specific message only if the user can move other pages
1175 $errors[] = array( 'cant-move-user-page' );
1178 // Check if user is allowed to move files if it's a file
1179 if( $this->getNamespace() == NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1180 $errors[] = array( 'movenotallowedfile' );
1183 if( !$user->isAllowed( 'move' ) ) {
1184 // User can't move anything
1185 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1187 } elseif ( $action == 'create' ) {
1188 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1189 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) )
1191 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1193 } elseif( !$user->isAllowed( $action ) ) {
1195 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1196 User
::getGroupsWithPermission( $action ) );
1198 $return = array( 'badaccess-groups',
1199 array( implode( ', ', $groups ), count( $groups ) ) );
1201 $return = array( "badaccess-group0" );
1203 $errors[] = $return;
1206 # Short-circuit point
1207 if( $short && count($errors) > 0 ) {
1208 wfProfileOut( __METHOD__
);
1212 // Use getUserPermissionsErrors instead
1213 if( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1214 wfProfileOut( __METHOD__
);
1215 return $result ?
array() : array( array( 'badaccess-group0' ) );
1217 // Check getUserPermissionsErrors hook
1218 if( !wfRunHooks( 'getUserPermissionsErrors', array(&$this,&$user,$action,&$result) ) ) {
1219 if( is_array($result) && count($result) && !is_array($result[0]) )
1220 $errors[] = $result; # A single array representing an error
1221 else if( is_array($result) && is_array($result[0]) )
1222 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1223 else if( $result !== '' && is_string($result) )
1224 $errors[] = array($result); # A string representing a message-id
1225 else if( $result === false )
1226 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1228 # Short-circuit point
1229 if( $short && count($errors) > 0 ) {
1230 wfProfileOut( __METHOD__
);
1233 // Check getUserPermissionsErrorsExpensive hook
1234 if( $doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array(&$this,&$user,$action,&$result) ) ) {
1235 if( is_array($result) && count($result) && !is_array($result[0]) )
1236 $errors[] = $result; # A single array representing an error
1237 else if( is_array($result) && is_array($result[0]) )
1238 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1239 else if( $result !== '' && is_string($result) )
1240 $errors[] = array($result); # A string representing a message-id
1241 else if( $result === false )
1242 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1244 # Short-circuit point
1245 if( $short && count($errors) > 0 ) {
1246 wfProfileOut( __METHOD__
);
1251 $specialOKActions = array( 'createaccount', 'execute' );
1252 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1253 $errors[] = array('ns-specialprotected');
1256 if( $this->isNamespaceProtected() ) {
1257 $ns = $this->getNamespace() == NS_MAIN ?
1258 wfMsg( 'nstab-main' ) : $this->getNsText();
1259 $errors[] = NS_MEDIAWIKI
== $this->mNamespace ?
1260 array('protectedinterface') : array( 'namespaceprotected', $ns );
1263 # protect css/js subpages of user pages
1264 # XXX: this might be better using restrictions
1265 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1266 if( $this->isCssJsSubpage() && !$user->isAllowed('editusercssjs')
1267 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1269 $errors[] = array('customcssjsprotected');
1272 if( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1273 # We /could/ use the protection level on the source page, but it's fairly ugly
1274 # as we have to establish a precedence hierarchy for pages included by multiple
1275 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1276 # as they could remove the protection anyway.
1277 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1278 # Cascading protection depends on more than this page...
1279 # Several cascading protected pages may include this page...
1280 # Check each cascading level
1281 # This is only for protection restrictions, not for all actions
1282 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1283 foreach( $restrictions[$action] as $right ) {
1284 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1285 if( '' != $right && !$user->isAllowed( $right ) ) {
1287 foreach( $cascadingSources as $page )
1288 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1289 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1294 # Short-circuit point
1295 if( $short && count($errors) > 0 ) {
1296 wfProfileOut( __METHOD__
);
1300 foreach( $this->getRestrictions($action) as $right ) {
1301 // Backwards compatibility, rewrite sysop -> protect
1302 if( $right == 'sysop' ) {
1305 if( '' != $right && !$user->isAllowed( $right ) ) {
1306 // Users with 'editprotected' permission can edit protected pages
1307 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1308 // Users with 'editprotected' permission cannot edit protected pages
1309 // with cascading option turned on.
1310 if( $this->mCascadeRestriction
) {
1311 $errors[] = array( 'protectedpagetext', $right );
1314 $errors[] = array( 'protectedpagetext', $right );
1318 # Short-circuit point
1319 if( $short && count($errors) > 0 ) {
1320 wfProfileOut( __METHOD__
);
1324 if( $action == 'protect' ) {
1325 if( $this->getUserPermissionsErrors('edit', $user) != array() ) {
1326 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1330 if( $action == 'create' ) {
1331 $title_protection = $this->getTitleProtection();
1332 if( is_array($title_protection) ) {
1333 extract($title_protection); // is this extract() really needed?
1335 if( $pt_create_perm == 'sysop' ) {
1336 $pt_create_perm = 'protect'; // B/C
1338 if( $pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm) ) {
1339 $errors[] = array( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1342 } elseif( $action == 'move' ) {
1343 // Check for immobile pages
1344 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1345 // Specific message for this case
1346 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1347 } elseif( !$this->isMovable() ) {
1348 // Less specific message for rarer cases
1349 $errors[] = array( 'immobile-page' );
1351 } elseif( $action == 'move-target' ) {
1352 if( !$user->isAllowed( 'move' ) ) {
1353 // User can't move anything
1354 $errors[] = $user->isAnon() ?
array ( 'movenologintext' ) : array ('movenotallowed');
1355 } elseif( !$user->isAllowed( 'move-rootuserpages' )
1356 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1358 // Show user page-specific message only if the user can move other pages
1359 $errors[] = array( 'cant-move-to-user-page' );
1361 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1362 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1363 } elseif( !$this->isMovable() ) {
1364 $errors[] = array( 'immobile-target-page' );
1368 wfProfileOut( __METHOD__
);
1373 * Is this title subject to title protection?
1374 * @return \type{\mixed} An associative array representing any existent title
1375 * protection, or false if there's none.
1377 private function getTitleProtection() {
1378 // Can't protect pages in special namespaces
1379 if ( $this->getNamespace() < 0 ) {
1383 $dbr = wfGetDB( DB_SLAVE
);
1384 $res = $dbr->select( 'protected_titles', '*',
1385 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1388 if ($row = $dbr->fetchRow( $res )) {
1396 * Update the title protection status
1397 * @param $create_perm \type{\string} Permission required for creation
1398 * @param $reason \type{\string} Reason for protection
1399 * @param $expiry \type{\string} Expiry timestamp
1401 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1402 global $wgUser,$wgContLang;
1404 if ($create_perm == implode(',',$this->getRestrictions('create'))
1405 && $expiry == $this->mRestrictionsExpiry
['create']) {
1410 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1412 $dbw = wfGetDB( DB_MASTER
);
1414 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1416 $expiry_description = '';
1417 if ( $encodedExpiry != 'infinity' ) {
1418 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) , $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ).')';
1421 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1424 # Update protection table
1425 if ($create_perm != '' ) {
1426 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1427 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1428 , 'pt_create_perm' => $create_perm
1429 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1430 , 'pt_expiry' => $encodedExpiry
1431 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1433 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1434 'pt_title' => $title ), __METHOD__
);
1436 # Update the protection log
1437 $log = new LogPage( 'protect' );
1439 if( $create_perm ) {
1440 $params = array("[create=$create_perm] $expiry_description",'');
1441 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason ), $params );
1443 $log->addEntry( 'unprotect', $this, $reason );
1450 * Remove any title protection due to page existing
1452 public function deleteTitleProtection() {
1453 $dbw = wfGetDB( DB_MASTER
);
1455 $dbw->delete( 'protected_titles',
1456 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1461 * Can $wgUser edit this page?
1462 * @return \type{\bool} TRUE or FALSE
1463 * @deprecated use userCan('edit')
1465 public function userCanEdit( $doExpensiveQueries = true ) {
1466 return $this->userCan( 'edit', $doExpensiveQueries );
1470 * Can $wgUser create this page?
1471 * @return \type{\bool} TRUE or FALSE
1472 * @deprecated use userCan('create')
1474 public function userCanCreate( $doExpensiveQueries = true ) {
1475 return $this->userCan( 'create', $doExpensiveQueries );
1479 * Can $wgUser move this page?
1480 * @return \type{\bool} TRUE or FALSE
1481 * @deprecated use userCan('move')
1483 public function userCanMove( $doExpensiveQueries = true ) {
1484 return $this->userCan( 'move', $doExpensiveQueries );
1488 * Would anybody with sufficient privileges be able to move this page?
1489 * Some pages just aren't movable.
1491 * @return \type{\bool} TRUE or FALSE
1493 public function isMovable() {
1494 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1498 * Can $wgUser read this page?
1499 * @return \type{\bool} TRUE or FALSE
1500 * @todo fold these checks into userCan()
1502 public function userCanRead() {
1503 global $wgUser, $wgGroupPermissions;
1506 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1507 if ( $result !== null ) {
1511 # Shortcut for public wikis, allows skipping quite a bit of code
1512 if ( !empty( $wgGroupPermissions['*']['read'] ) )
1515 if( $wgUser->isAllowed( 'read' ) ) {
1518 global $wgWhitelistRead;
1521 * Always grant access to the login page.
1522 * Even anons need to be able to log in.
1524 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1529 * Bail out if there isn't whitelist
1531 if( !is_array($wgWhitelistRead) ) {
1536 * Check for explicit whitelisting
1538 $name = $this->getPrefixedText();
1539 $dbName = $this->getPrefixedDBKey();
1540 // Check with and without underscores
1541 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1545 * Old settings might have the title prefixed with
1546 * a colon for main-namespace pages
1548 if( $this->getNamespace() == NS_MAIN
) {
1549 if( in_array( ':' . $name, $wgWhitelistRead ) )
1554 * If it's a special page, ditch the subpage bit
1557 if( $this->getNamespace() == NS_SPECIAL
) {
1558 $name = $this->getDBkey();
1559 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1560 if ( $name === false ) {
1561 # Invalid special page, but we show standard login required message
1565 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1566 if( in_array( $pure, $wgWhitelistRead, true ) )
1575 * Is this a talk page of some sort?
1576 * @return \type{\bool} TRUE or FALSE
1578 public function isTalkPage() {
1579 return MWNamespace
::isTalk( $this->getNamespace() );
1583 * Is this a subpage?
1584 * @return \type{\bool} TRUE or FALSE
1586 public function isSubpage() {
1587 return MWNamespace
::hasSubpages( $this->mNamespace
)
1588 ?
strpos( $this->getText(), '/' ) !== false
1593 * Does this have subpages? (Warning, usually requires an extra DB query.)
1594 * @return \type{\bool} TRUE or FALSE
1596 public function hasSubpages() {
1597 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1602 # We dynamically add a member variable for the purpose of this method
1603 # alone to cache the result. There's no point in having it hanging
1604 # around uninitialized in every Title object; therefore we only add it
1605 # if needed and don't declare it statically.
1606 if( isset( $this->mHasSubpages
) ) {
1607 return $this->mHasSubpages
;
1610 $db = wfGetDB( DB_SLAVE
);
1611 return $this->mHasSubpages
= (bool)$db->selectField( 'page', '1',
1612 "page_namespace = {$this->mNamespace} AND page_title LIKE '"
1613 . $db->escapeLike( $this->mDbkeyform
) . "/%'",
1619 * Could this page contain custom CSS or JavaScript, based
1622 * @return \type{\bool} TRUE or FALSE
1624 public function isCssOrJsPage() {
1625 return $this->mNamespace
== NS_MEDIAWIKI
1626 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1630 * Is this a .css or .js subpage of a user page?
1631 * @return \type{\bool} TRUE or FALSE
1633 public function isCssJsSubpage() {
1634 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1637 * Is this a *valid* .css or .js subpage of a user page?
1638 * Check that the corresponding skin exists
1639 * @return \type{\bool} TRUE or FALSE
1641 public function isValidCssJsSubpage() {
1642 if ( $this->isCssJsSubpage() ) {
1643 $skinNames = Skin
::getSkinNames();
1644 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1650 * Trim down a .css or .js subpage title to get the corresponding skin name
1652 public function getSkinFromCssJsSubpage() {
1653 $subpage = explode( '/', $this->mTextform
);
1654 $subpage = $subpage[ count( $subpage ) - 1 ];
1655 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1658 * Is this a .css subpage of a user page?
1659 * @return \type{\bool} TRUE or FALSE
1661 public function isCssSubpage() {
1662 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1665 * Is this a .js subpage of a user page?
1666 * @return \type{\bool} TRUE or FALSE
1668 public function isJsSubpage() {
1669 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1672 * Protect css/js subpages of user pages: can $wgUser edit
1675 * @return \type{\bool} TRUE or FALSE
1676 * @todo XXX: this might be better using restrictions
1678 public function userCanEditCssJsSubpage() {
1680 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1684 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1686 * @return \type{\bool} If the page is subject to cascading restrictions.
1688 public function isCascadeProtected() {
1689 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1690 return ( $sources > 0 );
1694 * Cascading protection: Get the source of any cascading restrictions on this page.
1696 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1697 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1698 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1699 * The restriction array is an array of each type, each of which contains an array of unique groups.
1701 public function getCascadeProtectionSources( $get_pages = true ) {
1702 global $wgRestrictionTypes;
1704 # Define our dimension of restrictions types
1705 $pagerestrictions = array();
1706 foreach( $wgRestrictionTypes as $action )
1707 $pagerestrictions[$action] = array();
1709 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1710 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1711 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1712 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1715 wfProfileIn( __METHOD__
);
1717 $dbr = wfGetDB( DB_SLAVE
);
1719 if ( $this->getNamespace() == NS_FILE
) {
1720 $tables = array ('imagelinks', 'page_restrictions');
1721 $where_clauses = array(
1722 'il_to' => $this->getDBkey(),
1724 'pr_cascade' => 1 );
1726 $tables = array ('templatelinks', 'page_restrictions');
1727 $where_clauses = array(
1728 'tl_namespace' => $this->getNamespace(),
1729 'tl_title' => $this->getDBkey(),
1731 'pr_cascade' => 1 );
1735 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1736 $where_clauses[] = 'page_id=pr_page';
1739 $cols = array( 'pr_expiry' );
1742 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1744 $sources = $get_pages ?
array() : false;
1745 $now = wfTimestampNow();
1746 $purgeExpired = false;
1748 foreach( $res as $row ) {
1749 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1750 if( $expiry > $now ) {
1752 $page_id = $row->pr_page
;
1753 $page_ns = $row->page_namespace
;
1754 $page_title = $row->page_title
;
1755 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1756 # Add groups needed for each restriction type if its not already there
1757 # Make sure this restriction type still exists
1758 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1759 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1765 // Trigger lazy purge of expired restrictions from the db
1766 $purgeExpired = true;
1769 if( $purgeExpired ) {
1770 Title
::purgeExpiredRestrictions();
1773 wfProfileOut( __METHOD__
);
1776 $this->mCascadeSources
= $sources;
1777 $this->mCascadingRestrictions
= $pagerestrictions;
1779 $this->mHasCascadingRestrictions
= $sources;
1781 return array( $sources, $pagerestrictions );
1784 function areRestrictionsCascading() {
1785 if (!$this->mRestrictionsLoaded
) {
1786 $this->loadRestrictions();
1789 return $this->mCascadeRestriction
;
1793 * Loads a string into mRestrictions array
1794 * @param $res \type{Resource} restrictions as an SQL result.
1796 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1797 global $wgRestrictionTypes;
1798 $dbr = wfGetDB( DB_SLAVE
);
1800 foreach( $wgRestrictionTypes as $type ){
1801 $this->mRestrictions
[$type] = array();
1802 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry('');
1805 $this->mCascadeRestriction
= false;
1807 # Backwards-compatibility: also load the restrictions from the page record (old format).
1809 if ( $oldFashionedRestrictions === NULL ) {
1810 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1811 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1814 if ($oldFashionedRestrictions != '') {
1816 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1817 $temp = explode( '=', trim( $restrict ) );
1818 if(count($temp) == 1) {
1819 // old old format should be treated as edit/move restriction
1820 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1821 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1823 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1827 $this->mOldRestrictions
= true;
1831 if( $dbr->numRows( $res ) ) {
1832 # Current system - load second to make them override.
1833 $now = wfTimestampNow();
1834 $purgeExpired = false;
1836 foreach( $res as $row ) {
1837 # Cycle through all the restrictions.
1839 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1840 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1843 // This code should be refactored, now that it's being used more generally,
1844 // But I don't really see any harm in leaving it in Block for now -werdna
1845 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1847 // Only apply the restrictions if they haven't expired!
1848 if ( !$expiry ||
$expiry > $now ) {
1849 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
1850 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1852 $this->mCascadeRestriction |
= $row->pr_cascade
;
1854 // Trigger a lazy purge of expired restrictions
1855 $purgeExpired = true;
1859 if( $purgeExpired ) {
1860 Title
::purgeExpiredRestrictions();
1864 $this->mRestrictionsLoaded
= true;
1868 * Load restrictions from the page_restrictions table
1870 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1871 if( !$this->mRestrictionsLoaded
) {
1872 if ($this->exists()) {
1873 $dbr = wfGetDB( DB_SLAVE
);
1875 $res = $dbr->select( 'page_restrictions', '*',
1876 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1878 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1880 $title_protection = $this->getTitleProtection();
1882 if (is_array($title_protection)) {
1883 extract($title_protection);
1885 $now = wfTimestampNow();
1886 $expiry = Block
::decodeExpiry($pt_expiry);
1888 if (!$expiry ||
$expiry > $now) {
1889 // Apply the restrictions
1890 $this->mRestrictionsExpiry
['create'] = $expiry;
1891 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1892 } else { // Get rid of the old restrictions
1893 Title
::purgeExpiredRestrictions();
1896 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry('');
1898 $this->mRestrictionsLoaded
= true;
1904 * Purge expired restrictions from the page_restrictions table
1906 static function purgeExpiredRestrictions() {
1907 $dbw = wfGetDB( DB_MASTER
);
1908 $dbw->delete( 'page_restrictions',
1909 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1912 $dbw->delete( 'protected_titles',
1913 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1918 * Accessor/initialisation for mRestrictions
1920 * @param $action \type{\string} action that permission needs to be checked for
1921 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
1923 public function getRestrictions( $action ) {
1924 if( !$this->mRestrictionsLoaded
) {
1925 $this->loadRestrictions();
1927 return isset( $this->mRestrictions
[$action] )
1928 ?
$this->mRestrictions
[$action]
1933 * Get the expiry time for the restriction against a given action
1934 * @return 14-char timestamp, or 'infinity' if the page is protected forever
1935 * or not protected at all, or false if the action is not recognised.
1937 public function getRestrictionExpiry( $action ) {
1938 if( !$this->mRestrictionsLoaded
) {
1939 $this->loadRestrictions();
1941 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
1945 * Is there a version of this page in the deletion archive?
1946 * @return \type{\int} the number of archived revisions
1948 public function isDeleted() {
1949 $fname = 'Title::isDeleted';
1950 if ( $this->getNamespace() < 0 ) {
1953 $dbr = wfGetDB( DB_SLAVE
);
1954 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1955 'ar_title' => $this->getDBkey() ), $fname );
1956 if( $this->getNamespace() == NS_FILE
) {
1957 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1958 array( 'fa_name' => $this->getDBkey() ), $fname );
1965 * Get the article ID for this Title from the link cache,
1966 * adding it if necessary
1967 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
1969 * @return \type{\int} the ID
1971 public function getArticleID( $flags = 0 ) {
1972 if( $this->getNamespace() < 0 ) {
1973 return $this->mArticleID
= 0;
1975 $linkCache = LinkCache
::singleton();
1976 if( $flags & GAID_FOR_UPDATE
) {
1977 $oldUpdate = $linkCache->forUpdate( true );
1978 $linkCache->clearLink( $this );
1979 $this->mArticleID
= $linkCache->addLinkObj( $this );
1980 $linkCache->forUpdate( $oldUpdate );
1982 if( -1 == $this->mArticleID
) {
1983 $this->mArticleID
= $linkCache->addLinkObj( $this );
1986 return $this->mArticleID
;
1990 * Is this an article that is a redirect page?
1991 * Uses link cache, adding it if necessary
1992 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
1993 * @return \type{\bool}
1995 public function isRedirect( $flags = 0 ) {
1996 if( !is_null($this->mRedirect
) )
1997 return $this->mRedirect
;
1998 # Calling getArticleID() loads the field from cache as needed
1999 if( !$this->getArticleID($flags) ) {
2000 return $this->mRedirect
= false;
2002 $linkCache = LinkCache
::singleton();
2003 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2005 return $this->mRedirect
;
2009 * What is the length of this page?
2010 * Uses link cache, adding it if necessary
2011 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2012 * @return \type{\bool}
2014 public function getLength( $flags = 0 ) {
2015 if( $this->mLength
!= -1 )
2016 return $this->mLength
;
2017 # Calling getArticleID() loads the field from cache as needed
2018 if( !$this->getArticleID($flags) ) {
2019 return $this->mLength
= 0;
2021 $linkCache = LinkCache
::singleton();
2022 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2024 return $this->mLength
;
2028 * What is the page_latest field for this page?
2029 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2030 * @return \type{\int}
2032 public function getLatestRevID( $flags = 0 ) {
2033 if( $this->mLatestID
!== false )
2034 return $this->mLatestID
;
2036 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
2037 $this->mLatestID
= $db->selectField( 'page', 'page_latest', $this->pageCond(), __METHOD__
);
2038 return $this->mLatestID
;
2042 * This clears some fields in this object, and clears any associated
2043 * keys in the "bad links" section of the link cache.
2045 * - This is called from Article::insertNewArticle() to allow
2046 * loading of the new page_id. It's also called from
2047 * Article::doDeleteArticle()
2049 * @param $newid \type{\int} the new Article ID
2051 public function resetArticleID( $newid ) {
2052 $linkCache = LinkCache
::singleton();
2053 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2055 if ( 0 == $newid ) { $this->mArticleID
= -1; }
2056 else { $this->mArticleID
= $newid; }
2057 $this->mRestrictionsLoaded
= false;
2058 $this->mRestrictions
= array();
2062 * Updates page_touched for this page; called from LinksUpdate.php
2063 * @return \type{\bool} true if the update succeded
2065 public function invalidateCache() {
2066 if( wfReadOnly() ) {
2069 $dbw = wfGetDB( DB_MASTER
);
2070 $success = $dbw->update( 'page',
2071 array( 'page_touched' => $dbw->timestamp() ),
2075 HTMLFileCache
::clearFileCache( $this );
2080 * Prefix some arbitrary text with the namespace or interwiki prefix
2083 * @param $name \type{\string} the text
2084 * @return \type{\string} the prefixed text
2087 /* private */ function prefix( $name ) {
2089 if ( '' != $this->mInterwiki
) {
2090 $p = $this->mInterwiki
. ':';
2092 if ( 0 != $this->mNamespace
) {
2093 $p .= $this->getNsText() . ':';
2099 * Secure and split - main initialisation function for this object
2101 * Assumes that mDbkeyform has been set, and is urldecoded
2102 * and uses underscores, but not otherwise munged. This function
2103 * removes illegal characters, splits off the interwiki and
2104 * namespace prefixes, sets the other forms, and canonicalizes
2106 * @return \type{\bool} true on success
2108 private function secureAndSplit() {
2109 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2112 static $rxTc = false;
2114 # Matching titles will be held as illegal.
2116 # Any character not allowed is forbidden...
2117 '[^' . Title
::legalChars() . ']' .
2118 # URL percent encoding sequences interfere with the ability
2119 # to round-trip titles -- you can't link to them consistently.
2120 '|%[0-9A-Fa-f]{2}' .
2121 # XML/HTML character references produce similar issues.
2122 '|&[A-Za-z0-9\x80-\xff]+;' .
2124 '|&#x[0-9A-Fa-f]+;' .
2128 $this->mInterwiki
= $this->mFragment
= '';
2129 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2131 $dbkey = $this->mDbkeyform
;
2133 # Strip Unicode bidi override characters.
2134 # Sometimes they slip into cut-n-pasted page titles, where the
2135 # override chars get included in list displays.
2136 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2138 # Clean up whitespace
2140 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2141 $dbkey = trim( $dbkey, '_' );
2143 if ( '' == $dbkey ) {
2147 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2148 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2152 $this->mDbkeyform
= $dbkey;
2154 # Initial colon indicates main namespace rather than specified default
2155 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2156 if ( ':' == $dbkey{0} ) {
2157 $this->mNamespace
= NS_MAIN
;
2158 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2159 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2162 # Namespace or interwiki prefix
2164 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2167 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2169 if ( $ns = $wgContLang->getNsIndex( $p ) ) {
2170 # Ordinary namespace
2172 $this->mNamespace
= $ns;
2173 # For Talk:X pages, check if X has a "namespace" prefix
2174 if( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2175 if( $wgContLang->getNsIndex( $x[1] ) )
2176 return false; # Disallow Talk:File:x type titles...
2177 else if( Interwiki
::isValidInterwiki( $x[1] ) )
2178 return false; # Disallow Talk:Interwiki:x type titles...
2180 } elseif( Interwiki
::isValidInterwiki( $p ) ) {
2182 # Can't make a local interwiki link to an interwiki link.
2183 # That's just crazy!
2189 $this->mInterwiki
= $wgContLang->lc( $p );
2191 # Redundant interwiki prefix to the local wiki
2192 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2193 if( $dbkey == '' ) {
2194 # Can't have an empty self-link
2197 $this->mInterwiki
= '';
2199 # Do another namespace split...
2203 # If there's an initial colon after the interwiki, that also
2204 # resets the default namespace
2205 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2206 $this->mNamespace
= NS_MAIN
;
2207 $dbkey = substr( $dbkey, 1 );
2210 # If there's no recognized interwiki or namespace,
2211 # then let the colon expression be part of the title.
2216 # We already know that some pages won't be in the database!
2218 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2219 $this->mArticleID
= 0;
2221 $fragment = strstr( $dbkey, '#' );
2222 if ( false !== $fragment ) {
2223 $this->setFragment( $fragment );
2224 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2225 # remove whitespace again: prevents "Foo_bar_#"
2226 # becoming "Foo_bar_"
2227 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2230 # Reject illegal characters.
2232 if( preg_match( $rxTc, $dbkey ) ) {
2237 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2238 * reachable due to the way web browsers deal with 'relative' URLs.
2239 * Also, they conflict with subpage syntax. Forbid them explicitly.
2241 if ( strpos( $dbkey, '.' ) !== false &&
2242 ( $dbkey === '.' ||
$dbkey === '..' ||
2243 strpos( $dbkey, './' ) === 0 ||
2244 strpos( $dbkey, '../' ) === 0 ||
2245 strpos( $dbkey, '/./' ) !== false ||
2246 strpos( $dbkey, '/../' ) !== false ||
2247 substr( $dbkey, -2 ) == '/.' ||
2248 substr( $dbkey, -3 ) == '/..' ) )
2254 * Magic tilde sequences? Nu-uh!
2256 if( strpos( $dbkey, '~~~' ) !== false ) {
2261 * Limit the size of titles to 255 bytes.
2262 * This is typically the size of the underlying database field.
2263 * We make an exception for special pages, which don't need to be stored
2264 * in the database, and may edge over 255 bytes due to subpage syntax
2265 * for long titles, e.g. [[Special:Block/Long name]]
2267 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2268 strlen( $dbkey ) > 512 )
2274 * Normally, all wiki links are forced to have
2275 * an initial capital letter so [[foo]] and [[Foo]]
2276 * point to the same place.
2278 * Don't force it for interwikis, since the other
2279 * site might be case-sensitive.
2281 $this->mUserCaseDBKey
= $dbkey;
2282 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2283 $dbkey = $wgContLang->ucfirst( $dbkey );
2287 * Can't make a link to a namespace alone...
2288 * "empty" local links can only be self-links
2289 * with a fragment identifier.
2292 $this->mInterwiki
== '' &&
2293 $this->mNamespace
!= NS_MAIN
) {
2296 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2297 // IP names are not allowed for accounts, and can only be referring to
2298 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2299 // there are numerous ways to present the same IP. Having sp:contribs scan
2300 // them all is silly and having some show the edits and others not is
2301 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2302 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2303 IP
::sanitizeIP( $dbkey ) : $dbkey;
2304 // Any remaining initial :s are illegal.
2305 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2310 $this->mDbkeyform
= $dbkey;
2311 $this->mUrlform
= wfUrlencode( $dbkey );
2313 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2319 * Set the fragment for this title. Removes the first character from the
2320 * specified fragment before setting, so it assumes you're passing it with
2323 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2324 * Still in active use privately.
2326 * @param $fragment \type{\string} text
2328 public function setFragment( $fragment ) {
2329 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2333 * Get a Title object associated with the talk page of this article
2334 * @return \type{Title} the object for the talk page
2336 public function getTalkPage() {
2337 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2341 * Get a title object associated with the subject page of this
2344 * @return \type{Title} the object for the subject page
2346 public function getSubjectPage() {
2347 // Is this the same title?
2348 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2349 if( $this->getNamespace() == $subjectNS ) {
2352 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2356 * Get an array of Title objects linking to this Title
2357 * Also stores the IDs in the link cache.
2359 * WARNING: do not use this function on arbitrary user-supplied titles!
2360 * On heavily-used templates it will max out the memory.
2362 * @param $options \type{\string} may be FOR UPDATE
2363 * @return \type{\arrayof{Title}} the Title objects linking here
2365 public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
2366 $linkCache = LinkCache
::singleton();
2369 $db = wfGetDB( DB_MASTER
);
2371 $db = wfGetDB( DB_SLAVE
);
2374 $res = $db->select( array( 'page', $table ),
2375 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2377 "{$prefix}_from=page_id",
2378 "{$prefix}_namespace" => $this->getNamespace(),
2379 "{$prefix}_title" => $this->getDBkey() ),
2384 if ( $db->numRows( $res ) ) {
2385 foreach( $res as $row ) {
2386 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2387 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2388 $retVal[] = $titleObj;
2392 $db->freeResult( $res );
2397 * Get an array of Title objects using this Title as a template
2398 * Also stores the IDs in the link cache.
2400 * WARNING: do not use this function on arbitrary user-supplied titles!
2401 * On heavily-used templates it will max out the memory.
2403 * @param $options \type{\string} may be FOR UPDATE
2404 * @return \type{\arrayof{Title}} the Title objects linking here
2406 public function getTemplateLinksTo( $options = '' ) {
2407 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2411 * Get an array of Title objects referring to non-existent articles linked from this page
2413 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2414 * @param $options \type{\string} may be FOR UPDATE
2415 * @return \type{\arrayof{Title}} the Title objects
2417 public function getBrokenLinksFrom( $options = '' ) {
2418 if ( $this->getArticleId() == 0 ) {
2419 # All links from article ID 0 are false positives
2424 $db = wfGetDB( DB_MASTER
);
2426 $db = wfGetDB( DB_SLAVE
);
2429 $res = $db->safeQuery(
2430 "SELECT pl_namespace, pl_title
2433 ON pl_namespace=page_namespace
2434 AND pl_title=page_title
2436 AND page_namespace IS NULL
2438 $db->tableName( 'pagelinks' ),
2439 $db->tableName( 'page' ),
2440 $this->getArticleId(),
2444 if ( $db->numRows( $res ) ) {
2445 foreach( $res as $row ) {
2446 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2449 $db->freeResult( $res );
2455 * Get a list of URLs to purge from the Squid cache when this
2458 * @return \type{\arrayof{\string}} the URLs
2460 public function getSquidURLs() {
2464 $this->getInternalURL(),
2465 $this->getInternalURL( 'action=history' )
2468 // purge variant urls as well
2469 if($wgContLang->hasVariants()){
2470 $variants = $wgContLang->getVariants();
2471 foreach($variants as $vCode){
2472 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2473 $urls[] = $this->getInternalURL('',$vCode);
2481 * Purge all applicable Squid URLs
2483 public function purgeSquid() {
2485 if ( $wgUseSquid ) {
2486 $urls = $this->getSquidURLs();
2487 $u = new SquidUpdate( $urls );
2493 * Move this page without authentication
2494 * @param &$nt \type{Title} the new page Title
2496 public function moveNoAuth( &$nt ) {
2497 return $this->moveTo( $nt, false );
2501 * Check whether a given move operation would be valid.
2502 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2503 * @param &$nt \type{Title} the new title
2504 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2506 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2507 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2509 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2514 // Normally we'd add this to $errors, but we'll get
2515 // lots of syntax errors if $nt is not an object
2516 return array(array('badtitletext'));
2518 if( $this->equals( $nt ) ) {
2519 $errors[] = array('selfmove');
2521 if( !$this->isMovable() ) {
2522 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2524 if ( $nt->getInterwiki() != '' ) {
2525 $errors[] = array( 'immobile-target-namespace-iw' );
2527 if ( !$nt->isMovable() ) {
2528 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2531 $oldid = $this->getArticleID();
2532 $newid = $nt->getArticleID();
2534 if ( strlen( $nt->getDBkey() ) < 1 ) {
2535 $errors[] = array('articleexists');
2537 if ( ( '' == $this->getDBkey() ) ||
2539 ( '' == $nt->getDBkey() ) ) {
2540 $errors[] = array('badarticleerror');
2543 // Image-specific checks
2544 if( $this->getNamespace() == NS_FILE
) {
2545 $file = wfLocalFile( $this );
2546 if( $file->exists() ) {
2547 if( $nt->getNamespace() != NS_FILE
) {
2548 $errors[] = array('imagenocrossnamespace');
2550 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2551 $errors[] = array('imageinvalidfilename');
2553 if( !File
::checkExtensionCompatibility( $file, $nt->getDBKey() ) ) {
2554 $errors[] = array('imagetypemismatch');
2560 $errors = wfMergeErrorArrays( $errors,
2561 $this->getUserPermissionsErrors('move', $wgUser),
2562 $this->getUserPermissionsErrors('edit', $wgUser),
2563 $nt->getUserPermissionsErrors('move-target', $wgUser),
2564 $nt->getUserPermissionsErrors('edit', $wgUser) );
2567 $match = EditPage
::matchSpamRegex( $reason );
2568 if( $match !== false ) {
2569 // This is kind of lame, won't display nice
2570 $errors[] = array('spamprotectiontext');
2574 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2575 $errors[] = array('hookaborted', $err);
2578 # The move is allowed only if (1) the target doesn't exist, or
2579 # (2) the target is a redirect to the source, and has no history
2580 # (so we can undo bad moves right after they're done).
2582 if ( 0 != $newid ) { # Target exists; check for validity
2583 if ( ! $this->isValidMoveTarget( $nt ) ) {
2584 $errors[] = array('articleexists');
2587 $tp = $nt->getTitleProtection();
2588 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2589 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2590 $errors[] = array('cantmove-titleprotected');
2599 * Move a title to a new location
2600 * @param &$nt \type{Title} the new title
2601 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2603 * @param $reason \type{\string} The reason for the move
2604 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2605 * Ignored if the user doesn't have the suppressredirect right.
2606 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2608 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2609 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2610 if( is_array( $err ) ) {
2614 $pageid = $this->getArticleID();
2615 $protected = $this->isProtected();
2616 if( $nt->exists() ) {
2617 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2618 $pageCountChange = ($createRedirect ?
0 : -1);
2619 } else { # Target didn't exist, do normal move.
2620 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2621 $pageCountChange = ($createRedirect ?
1 : 0);
2624 if( is_array( $err ) ) {
2627 $redirid = $this->getArticleID();
2629 // Category memberships include a sort key which may be customized.
2630 // If it's left as the default (the page title), we need to update
2631 // the sort key to match the new title.
2633 // Be careful to avoid resetting cl_timestamp, which may disturb
2634 // time-based lists on some sites.
2636 // Warning -- if the sort key is *explicitly* set to the old title,
2637 // we can't actually distinguish it from a default here, and it'll
2638 // be set to the new title even though it really shouldn't.
2639 // It'll get corrected on the next edit, but resetting cl_timestamp.
2640 $dbw = wfGetDB( DB_MASTER
);
2641 $dbw->update( 'categorylinks',
2643 'cl_sortkey' => $nt->getPrefixedText(),
2644 'cl_timestamp=cl_timestamp' ),
2646 'cl_from' => $pageid,
2647 'cl_sortkey' => $this->getPrefixedText() ),
2651 # Protect the redirect title as the title used to be...
2652 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2654 'pr_page' => $redirid,
2655 'pr_type' => 'pr_type',
2656 'pr_level' => 'pr_level',
2657 'pr_cascade' => 'pr_cascade',
2658 'pr_user' => 'pr_user',
2659 'pr_expiry' => 'pr_expiry'
2661 array( 'pr_page' => $pageid ),
2665 # Update the protection log
2666 $log = new LogPage( 'protect' );
2667 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2668 if( $reason ) $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2669 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2673 $oldnamespace = $this->getNamespace() & ~
1;
2674 $newnamespace = $nt->getNamespace() & ~
1;
2675 $oldtitle = $this->getDBkey();
2676 $newtitle = $nt->getDBkey();
2678 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2679 WatchedItem
::duplicateEntries( $this, $nt );
2682 # Update search engine
2683 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2685 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2689 if( $this->isContentPage() && !$nt->isContentPage() ) {
2690 # No longer a content page
2691 # Not viewed, edited, removing
2692 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2693 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2694 # Now a content page
2695 # Not viewed, edited, adding
2696 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2697 } elseif( $pageCountChange ) {
2699 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2706 # Update message cache for interface messages
2707 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2708 global $wgMessageCache;
2709 $oldarticle = new Article( $this );
2710 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2711 $newarticle = new Article( $nt );
2712 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2716 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2721 * Move page to a title which is at present a redirect to the
2724 * @param &$nt \type{Title} the page to move to, which should currently
2726 * @param $reason \type{\string} The reason for the move
2727 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2728 * Ignored if the user doesn't have the suppressredirect right
2730 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2731 global $wgUseSquid, $wgUser;
2732 $fname = 'Title::moveOverExistingRedirect';
2733 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2736 $comment .= ": $reason";
2739 $now = wfTimestampNow();
2740 $newid = $nt->getArticleID();
2741 $oldid = $this->getArticleID();
2742 $latest = $this->getLatestRevID();
2744 $dbw = wfGetDB( DB_MASTER
);
2746 # Delete the old redirect. We don't save it to history since
2747 # by definition if we've got here it's rather uninteresting.
2748 # We have to remove it so that the next step doesn't trigger
2749 # a conflict on the unique namespace+title index...
2750 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2751 if ( !$dbw->cascadingDeletes() ) {
2752 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2753 global $wgUseTrackbacks;
2754 if ($wgUseTrackbacks)
2755 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2756 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2757 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2758 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2759 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2760 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2761 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2762 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2765 # Save a null revision in the page's history notifying of the move
2766 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2767 $nullRevId = $nullRevision->insertOn( $dbw );
2769 $article = new Article( $this );
2770 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
2772 # Change the name of the target page:
2773 $dbw->update( 'page',
2775 'page_touched' => $dbw->timestamp($now),
2776 'page_namespace' => $nt->getNamespace(),
2777 'page_title' => $nt->getDBkey(),
2778 'page_latest' => $nullRevId,
2780 /* WHERE */ array( 'page_id' => $oldid ),
2783 $nt->resetArticleID( $oldid );
2785 # Recreate the redirect, this time in the other direction.
2786 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2787 $mwRedir = MagicWord
::get( 'redirect' );
2788 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2789 $redirectArticle = new Article( $this );
2790 $newid = $redirectArticle->insertOn( $dbw );
2791 $redirectRevision = new Revision( array(
2793 'comment' => $comment,
2794 'text' => $redirectText ) );
2795 $redirectRevision->insertOn( $dbw );
2796 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2798 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
2800 # Now, we record the link from the redirect to the new title.
2801 # It should have no other outgoing links...
2802 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2803 $dbw->insert( 'pagelinks',
2805 'pl_from' => $newid,
2806 'pl_namespace' => $nt->getNamespace(),
2807 'pl_title' => $nt->getDBkey() ),
2809 $redirectSuppressed = false;
2811 $this->resetArticleID( 0 );
2812 $redirectSuppressed = true;
2815 # Move an image if this is a file
2816 if( $this->getNamespace() == NS_FILE
) {
2817 $file = wfLocalFile( $this );
2818 if( $file->exists() ) {
2819 $status = $file->move( $nt );
2820 if( !$status->isOk() ) {
2822 return $status->getErrorsArray();
2828 $log = new LogPage( 'move' );
2829 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
2832 if ( $wgUseSquid ) {
2833 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2834 $u = new SquidUpdate( $urls );
2841 * Move page to non-existing title.
2842 * @param &$nt \type{Title} the new Title
2843 * @param $reason \type{\string} The reason for the move
2844 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2845 * Ignored if the user doesn't have the suppressredirect right
2847 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2848 global $wgUseSquid, $wgUser;
2849 $fname = 'MovePageForm::moveToNewTitle';
2850 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2852 $comment .= wfMsgExt( 'colon-separator',
2853 array( 'escapenoentities', 'content' ) );
2854 $comment .= $reason;
2857 $newid = $nt->getArticleID();
2858 $oldid = $this->getArticleID();
2859 $latest = $this->getLatestRevId();
2861 $dbw = wfGetDB( DB_MASTER
);
2862 $now = $dbw->timestamp();
2864 # Save a null revision in the page's history notifying of the move
2865 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2866 $nullRevId = $nullRevision->insertOn( $dbw );
2868 $article = new Article( $this );
2869 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
2872 $dbw->update( 'page',
2874 'page_touched' => $now,
2875 'page_namespace' => $nt->getNamespace(),
2876 'page_title' => $nt->getDBkey(),
2877 'page_latest' => $nullRevId,
2879 /* WHERE */ array( 'page_id' => $oldid ),
2882 $nt->resetArticleID( $oldid );
2884 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2886 $mwRedir = MagicWord
::get( 'redirect' );
2887 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2888 $redirectArticle = new Article( $this );
2889 $newid = $redirectArticle->insertOn( $dbw );
2890 $redirectRevision = new Revision( array(
2892 'comment' => $comment,
2893 'text' => $redirectText ) );
2894 $redirectRevision->insertOn( $dbw );
2895 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2897 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
2899 # Record the just-created redirect's linking to the page
2900 $dbw->insert( 'pagelinks',
2902 'pl_from' => $newid,
2903 'pl_namespace' => $nt->getNamespace(),
2904 'pl_title' => $nt->getDBkey() ),
2906 $redirectSuppressed = false;
2908 $this->resetArticleID( 0 );
2909 $redirectSuppressed = true;
2912 # Move an image if this is a file
2913 if( $this->getNamespace() == NS_FILE
) {
2914 $file = wfLocalFile( $this );
2915 if( $file->exists() ) {
2916 $status = $file->move( $nt );
2917 if( !$status->isOk() ) {
2919 return $status->getErrorsArray();
2925 $log = new LogPage( 'move' );
2926 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
2928 # Purge caches as per article creation
2929 Article
::onArticleCreate( $nt );
2931 # Purge old title from squid
2932 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2933 $this->purgeSquid();
2938 * Checks if this page is just a one-rev redirect.
2939 * Adds lock, so don't use just for light purposes.
2941 * @return \type{\bool} TRUE or FALSE
2943 public function isSingleRevRedirect() {
2944 $dbw = wfGetDB( DB_MASTER
);
2946 $row = $dbw->selectRow( 'page',
2947 array( 'page_is_redirect', 'page_latest', 'page_id' ),
2952 # Cache some fields we may want
2953 $this->mArticleID
= $row ?
intval($row->page_id
) : 0;
2954 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
2955 $this->mLatestID
= $row ?
intval($row->page_latest
) : false;
2956 if( !$this->mRedirect
) {
2959 # Does the article have a history?
2960 $row = $dbw->selectField( array( 'page', 'revision'),
2962 array( 'page_namespace' => $this->getNamespace(),
2963 'page_title' => $this->getDBkey(),
2965 'page_latest != rev_id'
2970 # Return true if there was no history
2971 return ($row === false);
2975 * Checks if $this can be moved to a given Title
2976 * - Selects for update, so don't call it unless you mean business
2978 * @param &$nt \type{Title} the new title to check
2979 * @return \type{\bool} TRUE or FALSE
2981 public function isValidMoveTarget( $nt ) {
2982 $dbw = wfGetDB( DB_MASTER
);
2983 # Is it an existsing file?
2984 if( $nt->getNamespace() == NS_FILE
) {
2985 $file = wfLocalFile( $nt );
2986 if( $file->exists() ) {
2987 wfDebug( __METHOD__
. ": file exists\n" );
2991 # Is it a redirect with no history?
2992 if( !$nt->isSingleRevRedirect() ) {
2993 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
2996 # Get the article text
2997 $rev = Revision
::newFromTitle( $nt );
2998 $text = $rev->getText();
2999 # Does the redirect point to the source?
3000 # Or is it a broken self-redirect, usually caused by namespace collisions?
3002 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3003 $redirTitle = Title
::newFromText( $m[1] );
3004 if( !is_object( $redirTitle ) ||
3005 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3006 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3007 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3012 wfDebug( __METHOD__
. ": failsafe\n" );
3019 * Can this title be added to a user's watchlist?
3021 * @return \type{\bool} TRUE or FALSE
3023 public function isWatchable() {
3024 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3028 * Get categories to which this Title belongs and return an array of
3029 * categories' names.
3031 * @return \type{\array} array an array of parents in the form:
3032 * $parent => $currentarticle
3034 public function getParentCategories() {
3037 $titlekey = $this->getArticleId();
3038 $dbr = wfGetDB( DB_SLAVE
);
3039 $categorylinks = $dbr->tableName( 'categorylinks' );
3042 $sql = "SELECT * FROM $categorylinks"
3043 ." WHERE cl_from='$titlekey'"
3044 ." AND cl_from <> '0'"
3045 ." ORDER BY cl_sortkey";
3047 $res = $dbr->query( $sql );
3049 if( $dbr->numRows( $res ) > 0 ) {
3050 foreach( $res as $row )
3051 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3052 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
3053 $dbr->freeResult( $res );
3061 * Get a tree of parent categories
3062 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3063 * @return \type{\array} Tree of parent categories
3065 public function getParentCategoryTree( $children = array() ) {
3067 $parents = $this->getParentCategories();
3070 foreach( $parents as $parent => $current ) {
3071 if ( array_key_exists( $parent, $children ) ) {
3072 # Circular reference
3073 $stack[$parent] = array();
3075 $nt = Title
::newFromText($parent);
3077 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
3089 * Get an associative array for selecting this title from
3092 * @return \type{\array} Selection array
3094 public function pageCond() {
3095 if( $this->mArticleID
> 0 ) {
3096 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3097 return array( 'page_id' => $this->mArticleID
);
3099 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3104 * Get the revision ID of the previous revision
3106 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3107 * @param $flags \type{\int} GAID_FOR_UPDATE
3108 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3110 public function getPreviousRevisionID( $revId, $flags=0 ) {
3111 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3112 return $db->selectField( 'revision', 'rev_id',
3114 'rev_page' => $this->getArticleId($flags),
3115 'rev_id < ' . intval( $revId )
3118 array( 'ORDER BY' => 'rev_id DESC' )
3123 * Get the revision ID of the next revision
3125 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3126 * @param $flags \type{\int} GAID_FOR_UPDATE
3127 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3129 public function getNextRevisionID( $revId, $flags=0 ) {
3130 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3131 return $db->selectField( 'revision', 'rev_id',
3133 'rev_page' => $this->getArticleId($flags),
3134 'rev_id > ' . intval( $revId )
3137 array( 'ORDER BY' => 'rev_id' )
3142 * Get the first revision of the page
3144 * @param $flags \type{\int} GAID_FOR_UPDATE
3145 * @return Revision (or NULL if page doesn't exist)
3147 public function getFirstRevision( $flags=0 ) {
3148 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3149 $pageId = $this->getArticleId($flags);
3150 if( !$pageId ) return NULL;
3151 $row = $db->selectRow( 'revision', '*',
3152 array( 'rev_page' => $pageId ),
3154 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3159 return new Revision( $row );
3164 * Check if this is a new page
3168 public function isNewPage() {
3169 $dbr = wfGetDB( DB_SLAVE
);
3170 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3174 * Get the oldest revision timestamp of this page
3176 * @return string, MW timestamp
3178 public function getEarliestRevTime() {
3179 $dbr = wfGetDB( DB_SLAVE
);
3180 if( $this->exists() ) {
3181 $min = $dbr->selectField( 'revision',
3182 'MIN(rev_timestamp)',
3183 array( 'rev_page' => $this->getArticleId() ),
3185 return wfTimestampOrNull( TS_MW
, $min );
3191 * Get the number of revisions between the given revision IDs.
3192 * Used for diffs and other things that really need it.
3194 * @param $old \type{\int} Revision ID.
3195 * @param $new \type{\int} Revision ID.
3196 * @return \type{\int} Number of revisions between these IDs.
3198 public function countRevisionsBetween( $old, $new ) {
3199 $dbr = wfGetDB( DB_SLAVE
);
3200 return $dbr->selectField( 'revision', 'count(*)',
3201 'rev_page = ' . intval( $this->getArticleId() ) .
3202 ' AND rev_id > ' . intval( $old ) .
3203 ' AND rev_id < ' . intval( $new ),
3205 array( 'USE INDEX' => 'PRIMARY' ) );
3209 * Compare with another title.
3211 * @param \type{Title} $title
3212 * @return \type{\bool} TRUE or FALSE
3214 public function equals( Title
$title ) {
3215 // Note: === is necessary for proper matching of number-like titles.
3216 return $this->getInterwiki() === $title->getInterwiki()
3217 && $this->getNamespace() == $title->getNamespace()
3218 && $this->getDBkey() === $title->getDBkey();
3222 * Callback for usort() to do title sorts by (namespace, title)
3224 static function compare( $a, $b ) {
3225 if( $a->getNamespace() == $b->getNamespace() ) {
3226 return strcmp( $a->getText(), $b->getText() );
3228 return $a->getNamespace() - $b->getNamespace();
3233 * Return a string representation of this title
3235 * @return \type{\string} String representation of this title
3237 public function __toString() {
3238 return $this->getPrefixedText();
3242 * Check if page exists. For historical reasons, this function simply
3243 * checks for the existence of the title in the page table, and will
3244 * thus return false for interwiki links, special pages and the like.
3245 * If you want to know if a title can be meaningfully viewed, you should
3246 * probably call the isKnown() method instead.
3248 * @return \type{\bool} TRUE or FALSE
3250 public function exists() {
3251 return $this->getArticleId() != 0;
3255 * Should links to this title be shown as potentially viewable (i.e. as
3256 * "bluelinks"), even if there's no record by this title in the page
3259 * This function is semi-deprecated for public use, as well as somewhat
3260 * misleadingly named. You probably just want to call isKnown(), which
3261 * calls this function internally.
3263 * (ISSUE: Most of these checks are cheap, but the file existence check
3264 * can potentially be quite expensive. Including it here fixes a lot of
3265 * existing code, but we might want to add an optional parameter to skip
3266 * it and any other expensive checks.)
3268 * @return \type{\bool} TRUE or FALSE
3270 public function isAlwaysKnown() {
3271 if( $this->mInterwiki
!= '' ) {
3272 return true; // any interwiki link might be viewable, for all we know
3274 switch( $this->mNamespace
) {
3277 return wfFindFile( $this ); // file exists, possibly in a foreign repo
3279 return SpecialPage
::exists( $this->getDBKey() ); // valid special page
3281 return $this->mDbkeyform
== ''; // selflink, possibly with fragment
3283 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3284 // the full l10n of that language to be loaded. That takes much memory and
3285 // isn't needed. So we strip the language part away.
3286 // Also, extension messages which are not loaded, are shown as red, because
3287 // we don't call MessageCache::loadAllMessages.
3288 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3289 return wfMsgWeirdKey( $basename ); // known system message
3296 * Does this title refer to a page that can (or might) be meaningfully
3297 * viewed? In particular, this function may be used to determine if
3298 * links to the title should be rendered as "bluelinks" (as opposed to
3299 * "redlinks" to non-existent pages).
3301 * @return \type{\bool} TRUE or FALSE
3303 public function isKnown() {
3304 return $this->exists() ||
$this->isAlwaysKnown();
3308 * Is this in a namespace that allows actual pages?
3310 * @return \type{\bool} TRUE or FALSE
3312 public function canExist() {
3313 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
3317 * Update page_touched timestamps and send squid purge messages for
3318 * pages linking to this title. May be sent to the job queue depending
3319 * on the number of links. Typically called on create and delete.
3321 public function touchLinks() {
3322 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3325 if ( $this->getNamespace() == NS_CATEGORY
) {
3326 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3332 * Get the last touched timestamp
3333 * @param Database $db, optional db
3334 * @return \type{\string} Last touched timestamp
3336 public function getTouched( $db = NULL ) {
3337 $db = isset($db) ?
$db : wfGetDB( DB_SLAVE
);
3338 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3343 * Get the timestamp when this page was updated since the user last saw it.
3345 * @return mixed string/NULL
3347 public function getNotificationTimestamp( $user = NULL ) {
3348 global $wgUser, $wgShowUpdatedMarker;
3349 // Assume current user if none given
3350 if( !$user ) $user = $wgUser;
3351 // Check cache first
3352 $uid = $user->getId();
3353 if( isset($this->mNotificationTimestamp
[$uid]) ) {
3354 return $this->mNotificationTimestamp
[$uid];
3356 if( !$uid ||
!$wgShowUpdatedMarker ) {
3357 return $this->mNotificationTimestamp
[$uid] = false;
3359 // Don't cache too much!
3360 if( count($this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3361 $this->mNotificationTimestamp
= array();
3363 $dbr = wfGetDB( DB_SLAVE
);
3364 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3365 'wl_notificationtimestamp',
3366 array( 'wl_namespace' => $this->getNamespace(),
3367 'wl_title' => $this->getDBkey(),
3368 'wl_user' => $user->getId()
3372 return $this->mNotificationTimestamp
[$uid];
3376 * Get the trackback URL for this page
3377 * @return \type{\string} Trackback URL
3379 public function trackbackURL() {
3380 global $wgScriptPath, $wgServer;
3382 return "$wgServer$wgScriptPath/trackback.php?article="
3383 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3387 * Get the trackback RDF for this page
3388 * @return \type{\string} Trackback RDF
3390 public function trackbackRDF() {
3391 $url = htmlspecialchars($this->getFullURL());
3392 $title = htmlspecialchars($this->getText());
3393 $tburl = $this->trackbackURL();
3395 // Autodiscovery RDF is placed in comments so HTML validator
3396 // won't barf. This is a rather icky workaround, but seems
3397 // frequently used by this kind of RDF thingy.
3399 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3401 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3402 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3403 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3406 dc:identifier=\"$url\"
3408 trackback:ping=\"$tburl\" />
3414 * Generate strings used for xml 'id' names in monobook tabs
3415 * @return \type{\string} XML 'id' name
3417 public function getNamespaceKey() {
3419 switch ($this->getNamespace()) {
3422 return 'nstab-main';
3425 return 'nstab-user';
3427 return 'nstab-media';
3429 return 'nstab-special';
3431 case NS_PROJECT_TALK
:
3432 return 'nstab-project';
3435 return 'nstab-image';
3437 case NS_MEDIAWIKI_TALK
:
3438 return 'nstab-mediawiki';
3440 case NS_TEMPLATE_TALK
:
3441 return 'nstab-template';
3444 return 'nstab-help';
3446 case NS_CATEGORY_TALK
:
3447 return 'nstab-category';
3449 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3454 * Returns true if this title resolves to the named special page
3455 * @param $name \type{\string} The special page name
3457 public function isSpecial( $name ) {
3458 if ( $this->getNamespace() == NS_SPECIAL
) {
3459 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3460 if ( $name == $thisName ) {
3468 * If the Title refers to a special page alias which is not the local default,
3469 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3471 public function fixSpecialName() {
3472 if ( $this->getNamespace() == NS_SPECIAL
) {
3473 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3474 if ( $canonicalName ) {
3475 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3476 if ( $localName != $this->mDbkeyform
) {
3477 return Title
::makeTitle( NS_SPECIAL
, $localName );
3485 * Is this Title in a namespace which contains content?
3486 * In other words, is this a content page, for the purposes of calculating
3489 * @return \type{\bool} TRUE or FALSE
3491 public function isContentPage() {
3492 return MWNamespace
::isContent( $this->getNamespace() );
3496 * Get all extant redirects to this Title
3498 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3499 * NULL to consider all namespaces
3500 * @return \type{\arrayof{Title}} Redirects to this title
3502 public function getRedirectsHere( $ns = null ) {
3505 $dbr = wfGetDB( DB_SLAVE
);
3507 'rd_namespace' => $this->getNamespace(),
3508 'rd_title' => $this->getDBkey(),
3511 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3513 $res = $dbr->select(
3514 array( 'redirect', 'page' ),
3515 array( 'page_namespace', 'page_title' ),
3521 foreach( $res as $row ) {
3522 $redirs[] = self
::newFromRow( $row );
3528 * Check if this Title is a valid redirect target
3530 * @return \type{\bool} TRUE or FALSE
3532 public function isValidRedirectTarget() {
3533 global $wgInvalidRedirectTargets;
3535 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
3536 if( $this->isSpecial( 'Userlogout' ) ) {
3540 foreach( $wgInvalidRedirectTargets as $target ) {
3541 if( $this->isSpecial( $target ) ) {