7 if ( !class_exists( 'UtfNormal' ) ) {
8 require_once( dirname(__FILE__
) . '/normal/UtfNormal.php' );
11 define ( 'GAID_FOR_UPDATE', 1 );
15 * Constants for pr_cascade bitfield
17 define( 'CASCADE', 1 );
20 * Represents a title within MediaWiki.
21 * Optionally may contain an interwiki designation or namespace.
22 * @note This class can fetch various kinds of data from the database;
23 * however, it does so inefficiently.
26 /** @name Static cache variables */
28 static private $titleCache=array();
29 static private $interwikiCache=array();
33 * Title::newFromText maintains a cache to avoid expensive re-normalization of
34 * commonly used titles. On a batch operation this can become a memory leak
35 * if not bounded. After hitting this many titles reset the cache.
37 const CACHE_MAX
= 1000;
41 * @name Private member variables
42 * Please use the accessor functions instead.
47 var $mTextform = ''; ///< Text form (spaces not underscores) of the main part
48 var $mUrlform = ''; ///< URL-encoded form of the main part
49 var $mDbkeyform = ''; ///< Main part with underscores
50 var $mUserCaseDBKey; ///< DB key with the initial letter in the case specified by the user
51 var $mNamespace = NS_MAIN
; ///< Namespace index, i.e. one of the NS_xxxx constants
52 var $mInterwiki = ''; ///< Interwiki prefix (or null string)
53 var $mFragment; ///< Title fragment (i.e. the bit after the #)
54 var $mArticleID = -1; ///< Article ID, fetched from the link cache on demand
55 var $mLatestID = false; ///< ID of most recent revision
56 var $mRestrictions = array(); ///< Array of groups allowed to edit this article
57 var $mOldRestrictions = false;
58 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
59 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
60 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
61 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
62 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
63 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
64 # Don't change the following default, NS_MAIN is hardcoded in several
65 # places. See bug 696.
66 var $mDefaultNamespace = NS_MAIN
; ///< Namespace index when there is no namespace
67 # Zero except in {{transclusion}} tags
68 var $mWatched = null; ///< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
69 var $mLength = -1; ///< The page length, 0 for special pages
70 var $mRedirect = null; ///< Is the article at this title a redirect?
71 var $mNotificationTimestamp = array(); ///< Associative array of user ID -> timestamp/false
72 var $mBacklinkCache = null; ///< Cache of links to this title
80 /* private */ function __construct() {}
83 * Create a new Title from a prefixed DB key
84 * @param $key \type{\string} The database key, which has underscores
85 * instead of spaces, possibly including namespace and
87 * @return \type{Title} the new object, or NULL on an error
89 public static function newFromDBkey( $key ) {
91 $t->mDbkeyform
= $key;
92 if( $t->secureAndSplit() )
99 * Create a new Title from text, such as what one would find in a link. De-
100 * codes any HTML entities in the text.
102 * @param $text string The link text; spaces, prefixes, and an
103 * initial ':' indicating the main namespace are accepted.
104 * @param $defaultNamespace int The namespace to use if none is speci-
105 * fied by a prefix. If you want to force a specific namespace even if
106 * $text might begin with a namespace prefix, use makeTitle() or
108 * @return Title The new object, or null on an error.
110 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
111 if( is_object( $text ) ) {
112 throw new MWException( 'Title::newFromText given an object' );
116 * Wiki pages often contain multiple links to the same page.
117 * Title normalization and parsing can become expensive on
118 * pages with many links, so we can save a little time by
121 * In theory these are value objects and won't get changed...
123 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
124 return Title
::$titleCache[$text];
128 * Convert things like é ā or 〗 into real text...
130 $filteredText = Sanitizer
::decodeCharReferences( $text );
133 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
134 $t->mDefaultNamespace
= $defaultNamespace;
136 static $cachedcount = 0 ;
137 if( $t->secureAndSplit() ) {
138 if( $defaultNamespace == NS_MAIN
) {
139 if( $cachedcount >= self
::CACHE_MAX
) {
140 # Avoid memory leaks on mass operations...
141 Title
::$titleCache = array();
145 Title
::$titleCache[$text] =& $t;
155 * Create a new Title from URL-encoded text. Ensures that
156 * the given title's length does not exceed the maximum.
157 * @param $url \type{\string} the title, as might be taken from a URL
158 * @return \type{Title} the new object, or NULL on an error
160 public static function newFromURL( $url ) {
161 global $wgLegalTitleChars;
164 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
165 # but some URLs used it as a space replacement and they still come
166 # from some external search tools.
167 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
168 $url = str_replace( '+', ' ', $url );
171 $t->mDbkeyform
= str_replace( ' ', '_', $url );
172 if( $t->secureAndSplit() ) {
180 * Create a new Title from an article ID
182 * @param $id \type{\int} the page_id corresponding to the Title to create
183 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
184 * @return \type{Title} the new object, or NULL on an error
186 public static function newFromID( $id, $flags = 0 ) {
187 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
188 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
189 if( $row !== false ) {
190 $title = Title
::newFromRow( $row );
198 * Make an array of titles from an array of IDs
199 * @param $ids \type{\arrayof{\int}} Array of IDs
200 * @return \type{\arrayof{Title}} Array of Titles
202 public static function newFromIDs( $ids ) {
203 if ( !count( $ids ) ) {
206 $dbr = wfGetDB( DB_SLAVE
);
207 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
208 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
211 foreach( $res as $row ) {
212 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
218 * Make a Title object from a DB row
219 * @param $row \type{Row} (needs at least page_title,page_namespace)
220 * @return \type{Title} corresponding Title
222 public static function newFromRow( $row ) {
223 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
225 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
226 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
227 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: NULL;
228 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
234 * Create a new Title from a namespace index and a DB key.
235 * It's assumed that $ns and $title are *valid*, for instance when
236 * they came directly from the database or a special page name.
237 * For convenience, spaces are converted to underscores so that
238 * eg user_text fields can be used directly.
240 * @param $ns \type{\int} the namespace of the article
241 * @param $title \type{\string} the unprefixed database key form
242 * @param $fragment \type{\string} The link fragment (after the "#")
243 * @return \type{Title} the new object
245 public static function &makeTitle( $ns, $title, $fragment = '' ) {
248 $t->mFragment
= $fragment;
249 $t->mNamespace
= $ns = intval( $ns );
250 $t->mDbkeyform
= str_replace( ' ', '_', $title );
251 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
252 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
253 $t->mTextform
= str_replace( '_', ' ', $title );
258 * Create a new Title from a namespace index and a DB key.
259 * The parameters will be checked for validity, which is a bit slower
260 * than makeTitle() but safer for user-provided data.
262 * @param $ns \type{\int} the namespace of the article
263 * @param $title \type{\string} the database key form
264 * @param $fragment \type{\string} The link fragment (after the "#")
265 * @return \type{Title} the new object, or NULL on an error
267 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
269 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
270 if( $t->secureAndSplit() ) {
278 * Create a new Title for the Main Page
279 * @return \type{Title} the new object
281 public static function newMainPage() {
282 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
283 // Don't give fatal errors if the message is broken
285 $title = Title
::newFromText( 'Main Page' );
291 * Extract a redirect destination from a string and return the
292 * Title, or null if the text doesn't contain a valid redirect
293 * This will only return the very next target, useful for
294 * the redirect table and other checks that don't need full recursion
296 * @param $text \type{\string} Text with possible redirect
297 * @return \type{Title} The corresponding Title
299 public static function newFromRedirect( $text ) {
300 return self
::newFromRedirectInternal( $text );
304 * Extract a redirect destination from a string and return the
305 * Title, or null if the text doesn't contain a valid redirect
306 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
307 * in order to provide (hopefully) the Title of the final destination instead of another redirect
309 * @param $text \type{\string} Text with possible redirect
310 * @return \type{Title} The corresponding Title
312 public static function newFromRedirectRecurse( $text ) {
313 $titles = self
::newFromRedirectArray( $text );
314 return $titles ?
array_pop( $titles ) : null;
318 * Extract a redirect destination from a string and return an
319 * array of Titles, or null if the text doesn't contain a valid redirect
320 * The last element in the array is the final destination after all redirects
321 * have been resolved (up to $wgMaxRedirects times)
323 * @param $text \type{\string} Text with possible redirect
324 * @return \type{\array} Array of Titles, with the destination last
326 public static function newFromRedirectArray( $text ) {
327 global $wgMaxRedirects;
328 // are redirects disabled?
329 if( $wgMaxRedirects < 1 )
331 $title = self
::newFromRedirectInternal( $text );
332 if( is_null( $title ) )
334 // recursive check to follow double redirects
335 $recurse = $wgMaxRedirects;
336 $titles = array( $title );
337 while( --$recurse > 0 ) {
338 if( $title->isRedirect() ) {
339 $article = new Article( $title, 0 );
340 $newtitle = $article->getRedirectTarget();
344 // Redirects to some special pages are not permitted
345 if( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
346 // the new title passes the checks, so make that our current title so that further recursion can be checked
348 $titles[] = $newtitle;
357 * Really extract the redirect destination
358 * Do not call this function directly, use one of the newFromRedirect* functions above
360 * @param $text \type{\string} Text with possible redirect
361 * @return \type{Title} The corresponding Title
363 protected static function newFromRedirectInternal( $text ) {
364 $redir = MagicWord
::get( 'redirect' );
366 if( $redir->matchStartAndRemove( $text ) ) {
367 // Extract the first link and see if it's usable
368 // Ensure that it really does come directly after #REDIRECT
369 // Some older redirects included a colon, so don't freak about that!
371 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
372 // Strip preceding colon used to "escape" categories, etc.
373 // and URL-decode links
374 if( strpos( $m[1], '%' ) !== false ) {
375 // Match behavior of inline link parsing here;
376 // don't interpret + as " " most of the time!
377 // It might be safe to just use rawurldecode instead, though.
378 $m[1] = urldecode( ltrim( $m[1], ':' ) );
380 $title = Title
::newFromText( $m[1] );
381 // If the title is a redirect to bad special pages or is invalid, return null
382 if( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
391 #----------------------------------------------------------------------------
393 #----------------------------------------------------------------------------
396 * Get the prefixed DB key associated with an ID
397 * @param $id \type{\int} the page_id of the article
398 * @return \type{Title} an object representing the article, or NULL
399 * if no such article was found
401 public static function nameOf( $id ) {
402 $dbr = wfGetDB( DB_SLAVE
);
404 $s = $dbr->selectRow( 'page',
405 array( 'page_namespace','page_title' ),
406 array( 'page_id' => $id ),
408 if ( $s === false ) { return NULL; }
410 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
415 * Get a regex character class describing the legal characters in a link
416 * @return \type{\string} the list of characters, not delimited
418 public static function legalChars() {
419 global $wgLegalTitleChars;
420 return $wgLegalTitleChars;
424 * Get a string representation of a title suitable for
425 * including in a search index
427 * @param $ns \type{\int} a namespace index
428 * @param $title \type{\string} text-form main part
429 * @return \type{\string} a stripped-down title string ready for the
432 public static function indexTitle( $ns, $title ) {
435 $lc = SearchEngine
::legalSearchChars() . '&#;';
436 $t = $wgContLang->stripForSearch( $title );
437 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
438 $t = $wgContLang->lc( $t );
441 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
442 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
444 $t = preg_replace( "/\\s+/", ' ', $t );
446 if ( $ns == NS_FILE
) {
447 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
453 * Make a prefixed DB key from a DB key and a namespace index
454 * @param $ns \type{\int} numerical representation of the namespace
455 * @param $title \type{\string} the DB key form the title
456 * @param $fragment \type{\string} The link fragment (after the "#")
457 * @return \type{\string} the prefixed form of the title
459 public static function makeName( $ns, $title, $fragment = '' ) {
462 $namespace = $wgContLang->getNsText( $ns );
463 $name = $namespace == '' ?
$title : "$namespace:$title";
464 if ( strval( $fragment ) != '' ) {
465 $name .= '#' . $fragment;
471 * Determine whether the object refers to a page within
474 * @return \type{\bool} TRUE if this is an in-project interwiki link
475 * or a wikilink, FALSE otherwise
477 public function isLocal() {
478 if ( $this->mInterwiki
!= '' ) {
479 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
486 * Determine whether the object refers to a page within
487 * this project and is transcludable.
489 * @return \type{\bool} TRUE if this is transcludable
491 public function isTrans() {
492 if ($this->mInterwiki
== '')
495 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
499 * Escape a text fragment, say from a link, for a URL
501 static function escapeFragmentForURL( $fragment ) {
502 global $wgEnforceHtmlIds;
503 # Note that we don't urlencode the fragment. urlencoded Unicode
504 # fragments appear not to work in IE (at least up to 7) or in at least
505 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
506 # to care if they aren't encoded.
507 return Sanitizer
::escapeId( $fragment,
508 $wgEnforceHtmlIds ?
'noninitial' : 'xml' );
511 #----------------------------------------------------------------------------
513 #----------------------------------------------------------------------------
515 /** Simple accessors */
517 * Get the text form (spaces not underscores) of the main part
518 * @return \type{\string} Main part of the title
520 public function getText() { return $this->mTextform
; }
522 * Get the URL-encoded form of the main part
523 * @return \type{\string} Main part of the title, URL-encoded
525 public function getPartialURL() { return $this->mUrlform
; }
527 * Get the main part with underscores
528 * @return \type{\string} Main part of the title, with underscores
530 public function getDBkey() { return $this->mDbkeyform
; }
532 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
533 * @return \type{\int} Namespace index
535 public function getNamespace() { return $this->mNamespace
; }
537 * Get the namespace text
538 * @return \type{\string} Namespace text
540 public function getNsText() {
541 global $wgContLang, $wgCanonicalNamespaceNames;
543 if ( '' != $this->mInterwiki
) {
544 // This probably shouldn't even happen. ohh man, oh yuck.
545 // But for interwiki transclusion it sometimes does.
546 // Shit. Shit shit shit.
548 // Use the canonical namespaces if possible to try to
549 // resolve a foreign namespace.
550 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
551 return $wgCanonicalNamespaceNames[$this->mNamespace
];
554 return $wgContLang->getNsText( $this->mNamespace
);
557 * Get the DB key with the initial letter case as specified by the user
558 * @return \type{\string} DB key
560 function getUserCaseDBKey() {
561 return $this->mUserCaseDBKey
;
564 * Get the namespace text of the subject (rather than talk) page
565 * @return \type{\string} Namespace text
567 public function getSubjectNsText() {
569 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
572 * Get the namespace text of the talk page
573 * @return \type{\string} Namespace text
575 public function getTalkNsText() {
577 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
580 * Could this title have a corresponding talk page?
581 * @return \type{\bool} TRUE or FALSE
583 public function canTalk() {
584 return( MWNamespace
::canTalk( $this->mNamespace
) );
587 * Get the interwiki prefix (or null string)
588 * @return \type{\string} Interwiki prefix
590 public function getInterwiki() { return $this->mInterwiki
; }
592 * Get the Title fragment (i.e.\ the bit after the #) in text form
593 * @return \type{\string} Title fragment
595 public function getFragment() { return $this->mFragment
; }
597 * Get the fragment in URL form, including the "#" character if there is one
598 * @return \type{\string} Fragment in URL form
600 public function getFragmentForURL() {
601 if ( $this->mFragment
== '' ) {
604 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
608 * Get the default namespace index, for when there is no namespace
609 * @return \type{\int} Default namespace index
611 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
614 * Get title for search index
615 * @return \type{\string} a stripped-down title string ready for the
618 public function getIndexTitle() {
619 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
623 * Get the prefixed database key form
624 * @return \type{\string} the prefixed title, with underscores and
625 * any interwiki and namespace prefixes
627 public function getPrefixedDBkey() {
628 $s = $this->prefix( $this->mDbkeyform
);
629 $s = str_replace( ' ', '_', $s );
634 * Get the prefixed title with spaces.
635 * This is the form usually used for display
636 * @return \type{\string} the prefixed title, with spaces
638 public function getPrefixedText() {
639 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
640 $s = $this->prefix( $this->mTextform
);
641 $s = str_replace( '_', ' ', $s );
642 $this->mPrefixedText
= $s;
644 return $this->mPrefixedText
;
648 * Get the prefixed title with spaces, plus any fragment
649 * (part beginning with '#')
650 * @return \type{\string} the prefixed title, with spaces and
651 * the fragment, including '#'
653 public function getFullText() {
654 $text = $this->getPrefixedText();
655 if( '' != $this->mFragment
) {
656 $text .= '#' . $this->mFragment
;
662 * Get the base name, i.e. the leftmost parts before the /
663 * @return \type{\string} Base name
665 public function getBaseText() {
666 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
667 return $this->getText();
670 $parts = explode( '/', $this->getText() );
671 # Don't discard the real title if there's no subpage involved
672 if( count( $parts ) > 1 )
673 unset( $parts[ count( $parts ) - 1 ] );
674 return implode( '/', $parts );
678 * Get the lowest-level subpage name, i.e. the rightmost part after /
679 * @return \type{\string} Subpage name
681 public function getSubpageText() {
682 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
683 return( $this->mTextform
);
685 $parts = explode( '/', $this->mTextform
);
686 return( $parts[ count( $parts ) - 1 ] );
690 * Get a URL-encoded form of the subpage text
691 * @return \type{\string} URL-encoded subpage name
693 public function getSubpageUrlForm() {
694 $text = $this->getSubpageText();
695 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
700 * Get a URL-encoded title (not an actual URL) including interwiki
701 * @return \type{\string} the URL-encoded form
703 public function getPrefixedURL() {
704 $s = $this->prefix( $this->mDbkeyform
);
705 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
710 * Get a real URL referring to this title, with interwiki link and
713 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
714 * links. Can be specified as an associative array as well, e.g.,
715 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
716 * @param $variant \type{\string} language variant of url (for sr, zh..)
717 * @return \type{\string} the URL
719 public function getFullURL( $query = '', $variant = false ) {
720 global $wgContLang, $wgServer, $wgRequest;
722 if( is_array( $query ) ) {
723 $query = wfArrayToCGI( $query );
726 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
728 $url = $this->getLocalUrl( $query, $variant );
730 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
731 // Correct fix would be to move the prepending elsewhere.
732 if ($wgRequest->getVal('action') != 'render') {
733 $url = $wgServer . $url;
736 $baseUrl = $interwiki->getURL( );
738 $namespace = wfUrlencode( $this->getNsText() );
739 if ( '' != $namespace ) {
740 # Can this actually happen? Interwikis shouldn't be parsed.
741 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
744 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
745 $url = wfAppendQuery( $url, $query );
748 # Finally, add the fragment.
749 $url .= $this->getFragmentForURL();
751 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
756 * Get a URL with no fragment or server name. If this page is generated
757 * with action=render, $wgServer is prepended.
758 * @param mixed $query an optional query string; if not specified,
759 * $wgArticlePath will be used. Can be specified as an associative array
760 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
762 * @param $variant \type{\string} language variant of url (for sr, zh..)
763 * @return \type{\string} the URL
765 public function getLocalURL( $query = '', $variant = false ) {
766 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
767 global $wgVariantArticlePath, $wgContLang, $wgUser;
769 if( is_array( $query ) ) {
770 $query = wfArrayToCGI( $query );
773 // internal links should point to same variant as current page (only anonymous users)
774 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
775 $pref = $wgContLang->getPreferredVariant(false);
776 if($pref != $wgContLang->getCode())
780 if ( $this->isExternal() ) {
781 $url = $this->getFullURL();
783 // This is currently only used for edit section links in the
784 // context of interwiki transclusion. In theory we should
785 // append the query to the end of any existing query string,
786 // but interwiki transclusion is already broken in that case.
790 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
791 if ( $query == '' ) {
792 if( $variant != false && $wgContLang->hasVariants() ) {
793 if( $wgVariantArticlePath == false ) {
794 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
796 $variantArticlePath = $wgVariantArticlePath;
798 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
799 $url = str_replace( '$1', $dbkey, $url );
801 $url = str_replace( '$1', $dbkey, $wgArticlePath );
804 global $wgActionPaths;
807 if( !empty( $wgActionPaths ) &&
808 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
810 $action = urldecode( $matches[2] );
811 if( isset( $wgActionPaths[$action] ) ) {
812 $query = $matches[1];
813 if( isset( $matches[4] ) ) $query .= $matches[4];
814 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
816 $url = wfAppendQuery( $url, $query );
820 if ( $url === false ) {
821 if ( $query == '-' ) {
824 $url = "{$wgScript}?title={$dbkey}&{$query}";
828 // FIXME: this causes breakage in various places when we
829 // actually expected a local URL and end up with dupe prefixes.
830 if ($wgRequest->getVal('action') == 'render') {
831 $url = $wgServer . $url;
834 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
839 * Get a URL that's the simplest URL that will be valid to link, locally,
840 * to the current Title. It includes the fragment, but does not include
841 * the server unless action=render is used (or the link is external). If
842 * there's a fragment but the prefixed text is empty, we just return a link
845 * The result obviously should not be URL-escaped, but does need to be
846 * HTML-escaped if it's being output in HTML.
848 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
849 * query string. Keys and values will be escaped.
850 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
851 * for external links. Default is "false" (same variant as current page,
852 * for anonymous users).
853 * @return \type{\string} the URL
855 public function getLinkUrl( $query = array(), $variant = false ) {
856 wfProfileIn( __METHOD__
);
857 if( !is_array( $query ) ) {
858 wfProfileOut( __METHOD__
);
859 throw new MWException( 'Title::getLinkUrl passed a non-array for '.
862 if( $this->isExternal() ) {
863 $ret = $this->getFullURL( $query );
864 } elseif( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
865 $ret = $this->getFragmentForURL();
867 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
869 wfProfileOut( __METHOD__
);
874 * Get an HTML-escaped version of the URL form, suitable for
875 * using in a link, without a server name or fragment
876 * @param $query \type{\string} an optional query string
877 * @return \type{\string} the URL
879 public function escapeLocalURL( $query = '' ) {
880 return htmlspecialchars( $this->getLocalURL( $query ) );
884 * Get an HTML-escaped version of the URL form, suitable for
885 * using in a link, including the server name and fragment
887 * @param $query \type{\string} an optional query string
888 * @return \type{\string} the URL
890 public function escapeFullURL( $query = '' ) {
891 return htmlspecialchars( $this->getFullURL( $query ) );
895 * Get the URL form for an internal link.
896 * - Used in various Squid-related code, in case we have a different
897 * internal hostname for the server from the exposed one.
899 * @param $query \type{\string} an optional query string
900 * @param $variant \type{\string} language variant of url (for sr, zh..)
901 * @return \type{\string} the URL
903 public function getInternalURL( $query = '', $variant = false ) {
904 global $wgInternalServer;
905 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
906 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
911 * Get the edit URL for this Title
912 * @return \type{\string} the URL, or a null string if this is an
915 public function getEditURL() {
916 if ( '' != $this->mInterwiki
) { return ''; }
917 $s = $this->getLocalURL( 'action=edit' );
923 * Get the HTML-escaped displayable text form.
924 * Used for the title field in <a> tags.
925 * @return \type{\string} the text, including any prefixes
927 public function getEscapedText() {
928 return htmlspecialchars( $this->getPrefixedText() );
932 * Is this Title interwiki?
933 * @return \type{\bool}
935 public function isExternal() { return ( '' != $this->mInterwiki
); }
938 * Is this page "semi-protected" - the *only* protection is autoconfirm?
940 * @param @action \type{\string} Action to check (default: edit)
941 * @return \type{\bool}
943 public function isSemiProtected( $action = 'edit' ) {
944 if( $this->exists() ) {
945 $restrictions = $this->getRestrictions( $action );
946 if( count( $restrictions ) > 0 ) {
947 foreach( $restrictions as $restriction ) {
948 if( strtolower( $restriction ) != 'autoconfirmed' )
957 # If it doesn't exist, it can't be protected
963 * Does the title correspond to a protected article?
964 * @param $what \type{\string} the action the page is protected from,
965 * by default checks move and edit
966 * @return \type{\bool}
968 public function isProtected( $action = '' ) {
969 global $wgRestrictionLevels, $wgRestrictionTypes;
971 # Special pages have inherent protection
972 if( $this->getNamespace() == NS_SPECIAL
)
975 # Check regular protection levels
976 foreach( $wgRestrictionTypes as $type ){
977 if( $action == $type ||
$action == '' ) {
978 $r = $this->getRestrictions( $type );
979 foreach( $wgRestrictionLevels as $level ) {
980 if( in_array( $level, $r ) && $level != '' ) {
991 * Is $wgUser watching this page?
992 * @return \type{\bool}
994 public function userIsWatching() {
997 if ( is_null( $this->mWatched
) ) {
998 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
999 $this->mWatched
= false;
1001 $this->mWatched
= $wgUser->isWatched( $this );
1004 return $this->mWatched
;
1008 * Can $wgUser perform $action on this page?
1009 * This skips potentially expensive cascading permission checks.
1011 * Suitable for use for nonessential UI controls in common cases, but
1012 * _not_ for functional access control.
1014 * May provide false positives, but should never provide a false negative.
1016 * @param $action \type{\string} action that permission needs to be checked for
1017 * @return \type{\bool}
1019 public function quickUserCan( $action ) {
1020 return $this->userCan( $action, false );
1024 * Determines if $wgUser is unable to edit this page because it has been protected
1025 * by $wgNamespaceProtection.
1027 * @return \type{\bool}
1029 public function isNamespaceProtected() {
1030 global $wgNamespaceProtection, $wgUser;
1031 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1032 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1033 if( $right != '' && !$wgUser->isAllowed( $right ) )
1041 * Can $wgUser perform $action on this page?
1042 * @param $action \type{\string} action that permission needs to be checked for
1043 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1044 * @return \type{\bool}
1046 public function userCan( $action, $doExpensiveQueries = true ) {
1048 return ($this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array());
1052 * Can $user perform $action on this page?
1054 * FIXME: This *does not* check throttles (User::pingLimiter()).
1056 * @param $action \type{\string}action that permission needs to be checked for
1057 * @param $user \type{User} user to check
1058 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1059 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1060 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1062 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1063 if( !StubObject
::isRealObject( $user ) ) {
1064 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1066 $wgUser->_unstub( '', 5 );
1069 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1073 global $wgEmailConfirmToEdit;
1075 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1076 $errors[] = array( 'confirmedittext' );
1079 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1080 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1081 $block = $user->mBlock
;
1083 // This is from OutputPage::blockedPage
1084 // Copied at r23888 by werdna
1086 $id = $user->blockedBy();
1087 $reason = $user->blockedFor();
1088 if( $reason == '' ) {
1089 $reason = wfMsg( 'blockednoreason' );
1093 if ( is_numeric( $id ) ) {
1094 $name = User
::whoIs( $id );
1099 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1100 $blockid = $block->mId
;
1101 $blockExpiry = $user->mBlock
->mExpiry
;
1102 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1104 if ( $blockExpiry == 'infinity' ) {
1105 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1106 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1108 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1109 if ( strpos( $option, ':' ) == false )
1112 list ($show, $value) = explode( ":", $option );
1114 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1115 $blockExpiry = $show;
1120 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1123 $intended = $user->mBlock
->mAddress
;
1125 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1126 $blockid, $blockExpiry, $intended, $blockTimestamp );
1129 // Remove the errors being ignored.
1131 foreach( $errors as $index => $error ) {
1132 $error_key = is_array($error) ?
$error[0] : $error;
1134 if (in_array( $error_key, $ignoreErrors )) {
1135 unset($errors[$index]);
1143 * Can $user perform $action on this page? This is an internal function,
1144 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1145 * checks on wfReadOnly() and blocks)
1147 * @param $action \type{\string} action that permission needs to be checked for
1148 * @param $user \type{User} user to check
1149 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1150 * @param $short \type{\bool} Set this to true to stop after the first permission error.
1151 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1153 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries=true, $short=false ) {
1154 wfProfileIn( __METHOD__
);
1158 // First stop is permissions checks, which fail most often, and which are easiest to test.
1159 if ( $action == 'move' ) {
1160 if( !$user->isAllowed( 'move-rootuserpages' )
1161 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1163 // Show user page-specific message only if the user can move other pages
1164 $errors[] = array( 'cant-move-user-page' );
1167 // Check if user is allowed to move files if it's a file
1168 if( $this->getNamespace() == NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1169 $errors[] = array( 'movenotallowedfile' );
1172 if( !$user->isAllowed( 'move' ) ) {
1173 // User can't move anything
1174 $errors[] = array ('movenotallowed');
1176 } elseif ( $action == 'create' ) {
1177 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1178 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) )
1180 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1182 } elseif( $action == 'move-target' ) {
1183 if( !$user->isAllowed( 'move' ) ) {
1184 // User can't move anything
1185 $errors[] = array ('movenotallowed');
1186 } elseif( !$user->isAllowed( 'move-rootuserpages' )
1187 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1189 // Show user page-specific message only if the user can move other pages
1190 $errors[] = array( 'cant-move-to-user-page' );
1192 } elseif( !$user->isAllowed( $action ) ) {
1194 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1195 User
::getGroupsWithPermission( $action ) );
1197 $return = array( 'badaccess-groups',
1198 array( implode( ', ', $groups ), count( $groups ) ) );
1200 $return = array( "badaccess-group0" );
1202 $errors[] = $return;
1205 # Short-circuit point
1206 if( $short && count($errors) > 0 ) {
1207 wfProfileOut( __METHOD__
);
1211 // Use getUserPermissionsErrors instead
1212 if( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1213 wfProfileOut( __METHOD__
);
1214 return $result ?
array() : array( array( 'badaccess-group0' ) );
1216 // Check getUserPermissionsErrors hook
1217 if( !wfRunHooks( 'getUserPermissionsErrors', array(&$this,&$user,$action,&$result) ) ) {
1218 if( is_array($result) && count($result) && !is_array($result[0]) )
1219 $errors[] = $result; # A single array representing an error
1220 else if( is_array($result) && is_array($result[0]) )
1221 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1222 else if( $result !== '' && is_string($result) )
1223 $errors[] = array($result); # A string representing a message-id
1224 else if( $result === false )
1225 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1227 # Short-circuit point
1228 if( $short && count($errors) > 0 ) {
1229 wfProfileOut( __METHOD__
);
1232 // Check getUserPermissionsErrorsExpensive hook
1233 if( $doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array(&$this,&$user,$action,&$result) ) ) {
1234 if( is_array($result) && count($result) && !is_array($result[0]) )
1235 $errors[] = $result; # A single array representing an error
1236 else if( is_array($result) && is_array($result[0]) )
1237 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1238 else if( $result !== '' && is_string($result) )
1239 $errors[] = array($result); # A string representing a message-id
1240 else if( $result === false )
1241 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1243 # Short-circuit point
1244 if( $short && count($errors) > 0 ) {
1245 wfProfileOut( __METHOD__
);
1249 # Only 'createaccount' and 'execute' can be performed on
1250 # special pages, which don't actually exist in the DB.
1251 $specialOKActions = array( 'createaccount', 'execute' );
1252 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1253 $errors[] = array('ns-specialprotected');
1256 # Check $wgNamespaceProtection for restricted namespaces
1257 if( $this->isNamespaceProtected() ) {
1258 $ns = $this->getNamespace() == NS_MAIN ?
1259 wfMsg( 'nstab-main' ) : $this->getNsText();
1260 $errors[] = NS_MEDIAWIKI
== $this->mNamespace ?
1261 array('protectedinterface') : array( 'namespaceprotected', $ns );
1264 # Protect css/js subpages of user pages
1265 # XXX: this might be better using restrictions
1266 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1267 if( $this->isCssJsSubpage() && !$user->isAllowed('editusercssjs')
1268 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1270 $errors[] = array('customcssjsprotected');
1273 # Check against page_restrictions table requirements on this
1274 # page. The user must possess all required rights for this action.
1275 foreach( $this->getRestrictions($action) as $right ) {
1276 // Backwards compatibility, rewrite sysop -> protect
1277 if( $right == 'sysop' ) {
1280 if( '' != $right && !$user->isAllowed( $right ) ) {
1281 // Users with 'editprotected' permission can edit protected pages
1282 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1283 // Users with 'editprotected' permission cannot edit protected pages
1284 // with cascading option turned on.
1285 if( $this->mCascadeRestriction
) {
1286 $errors[] = array( 'protectedpagetext', $right );
1289 $errors[] = array( 'protectedpagetext', $right );
1293 # Short-circuit point
1294 if( $short && count($errors) > 0 ) {
1295 wfProfileOut( __METHOD__
);
1299 if( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1300 # We /could/ use the protection level on the source page, but it's fairly ugly
1301 # as we have to establish a precedence hierarchy for pages included by multiple
1302 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1303 # as they could remove the protection anyway.
1304 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1305 # Cascading protection depends on more than this page...
1306 # Several cascading protected pages may include this page...
1307 # Check each cascading level
1308 # This is only for protection restrictions, not for all actions
1309 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1310 foreach( $restrictions[$action] as $right ) {
1311 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1312 if( '' != $right && !$user->isAllowed( $right ) ) {
1314 foreach( $cascadingSources as $page )
1315 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1316 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1321 # Short-circuit point
1322 if( $short && count($errors) > 0 ) {
1323 wfProfileOut( __METHOD__
);
1327 if( $action == 'protect' ) {
1328 if( $this->getUserPermissionsErrors('edit', $user) != array() ) {
1329 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1333 if( $action == 'create' ) {
1334 $title_protection = $this->getTitleProtection();
1335 if( is_array($title_protection) ) {
1336 extract($title_protection); // is this extract() really needed?
1338 if( $pt_create_perm == 'sysop' ) {
1339 $pt_create_perm = 'protect'; // B/C
1341 if( $pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm) ) {
1342 $errors[] = array( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1345 } elseif( $action == 'move' ) {
1346 // Check for immobile pages
1347 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1348 // Specific message for this case
1349 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1350 } elseif( !$this->isMovable() ) {
1351 // Less specific message for rarer cases
1352 $errors[] = array( 'immobile-page' );
1354 } elseif( $action == 'move-target' ) {
1355 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1356 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1357 } elseif( !$this->isMovable() ) {
1358 $errors[] = array( 'immobile-target-page' );
1362 wfProfileOut( __METHOD__
);
1367 * Is this title subject to title protection?
1368 * @return \type{\mixed} An associative array representing any existent title
1369 * protection, or false if there's none.
1371 private function getTitleProtection() {
1372 // Can't protect pages in special namespaces
1373 if ( $this->getNamespace() < 0 ) {
1377 $dbr = wfGetDB( DB_SLAVE
);
1378 $res = $dbr->select( 'protected_titles', '*',
1379 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1382 if ($row = $dbr->fetchRow( $res )) {
1390 * Update the title protection status
1391 * @param $create_perm \type{\string} Permission required for creation
1392 * @param $reason \type{\string} Reason for protection
1393 * @param $expiry \type{\string} Expiry timestamp
1395 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1396 global $wgUser,$wgContLang;
1398 if ($create_perm == implode(',',$this->getRestrictions('create'))
1399 && $expiry == $this->mRestrictionsExpiry
['create']) {
1404 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1406 $dbw = wfGetDB( DB_MASTER
);
1408 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1410 $expiry_description = '';
1411 if ( $encodedExpiry != 'infinity' ) {
1412 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) , $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ).')';
1415 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1418 # Update protection table
1419 if ($create_perm != '' ) {
1420 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1421 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1422 , 'pt_create_perm' => $create_perm
1423 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1424 , 'pt_expiry' => $encodedExpiry
1425 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1427 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1428 'pt_title' => $title ), __METHOD__
);
1430 # Update the protection log
1431 $log = new LogPage( 'protect' );
1433 if( $create_perm ) {
1434 $params = array("[create=$create_perm] $expiry_description",'');
1435 $log->addEntry( $this->mRestrictions
['create'] ?
'modify' : 'protect', $this, trim( $reason ), $params );
1437 $log->addEntry( 'unprotect', $this, $reason );
1444 * Remove any title protection due to page existing
1446 public function deleteTitleProtection() {
1447 $dbw = wfGetDB( DB_MASTER
);
1449 $dbw->delete( 'protected_titles',
1450 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1455 * Would anybody with sufficient privileges be able to move this page?
1456 * Some pages just aren't movable.
1458 * @return \type{\bool} TRUE or FALSE
1460 public function isMovable() {
1461 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1465 * Can $wgUser read this page?
1466 * @return \type{\bool} TRUE or FALSE
1467 * @todo fold these checks into userCan()
1469 public function userCanRead() {
1470 global $wgUser, $wgGroupPermissions;
1473 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1474 if ( $result !== null ) {
1478 # Shortcut for public wikis, allows skipping quite a bit of code
1479 if ( !empty( $wgGroupPermissions['*']['read'] ) )
1482 if( $wgUser->isAllowed( 'read' ) ) {
1485 global $wgWhitelistRead;
1488 * Always grant access to the login page.
1489 * Even anons need to be able to log in.
1491 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1496 * Bail out if there isn't whitelist
1498 if( !is_array($wgWhitelistRead) ) {
1503 * Check for explicit whitelisting
1505 $name = $this->getPrefixedText();
1506 $dbName = $this->getPrefixedDBKey();
1507 // Check with and without underscores
1508 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1512 * Old settings might have the title prefixed with
1513 * a colon for main-namespace pages
1515 if( $this->getNamespace() == NS_MAIN
) {
1516 if( in_array( ':' . $name, $wgWhitelistRead ) )
1521 * If it's a special page, ditch the subpage bit
1524 if( $this->getNamespace() == NS_SPECIAL
) {
1525 $name = $this->getDBkey();
1526 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1527 if ( $name === false ) {
1528 # Invalid special page, but we show standard login required message
1532 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1533 if( in_array( $pure, $wgWhitelistRead, true ) )
1542 * Is this a talk page of some sort?
1543 * @return \type{\bool} TRUE or FALSE
1545 public function isTalkPage() {
1546 return MWNamespace
::isTalk( $this->getNamespace() );
1550 * Is this a subpage?
1551 * @return \type{\bool} TRUE or FALSE
1553 public function isSubpage() {
1554 return MWNamespace
::hasSubpages( $this->mNamespace
)
1555 ?
strpos( $this->getText(), '/' ) !== false
1560 * Does this have subpages? (Warning, usually requires an extra DB query.)
1561 * @return \type{\bool} TRUE or FALSE
1563 public function hasSubpages() {
1564 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1569 # We dynamically add a member variable for the purpose of this method
1570 # alone to cache the result. There's no point in having it hanging
1571 # around uninitialized in every Title object; therefore we only add it
1572 # if needed and don't declare it statically.
1573 if( isset( $this->mHasSubpages
) ) {
1574 return $this->mHasSubpages
;
1577 $subpages = $this->getSubpages( 1 );
1578 if( $subpages instanceof TitleArray
)
1579 return $this->mHasSubpages
= (bool)$subpages->count();
1580 return $this->mHasSubpages
= false;
1584 * Get all subpages of this page.
1585 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1586 * @return mixed TitleArray, or empty array if this page's namespace
1587 * doesn't allow subpages
1589 public function getSubpages( $limit = -1 ) {
1590 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
1593 $dbr = wfGetDB( DB_SLAVE
);
1594 $conds['page_namespace'] = $this->getNamespace();
1595 $conds[] = 'page_title LIKE ' . $dbr->addQuotes(
1596 $dbr->escapeLike( $this->getDBkey() ) . '/%' );
1599 $options['LIMIT'] = $limit;
1600 return $this->mSubpages
= TitleArray
::newFromResult(
1601 $dbr->select( 'page',
1602 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1611 * Could this page contain custom CSS or JavaScript, based
1614 * @return \type{\bool} TRUE or FALSE
1616 public function isCssOrJsPage() {
1617 return $this->mNamespace
== NS_MEDIAWIKI
1618 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1622 * Is this a .css or .js subpage of a user page?
1623 * @return \type{\bool} TRUE or FALSE
1625 public function isCssJsSubpage() {
1626 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1629 * Is this a *valid* .css or .js subpage of a user page?
1630 * Check that the corresponding skin exists
1631 * @return \type{\bool} TRUE or FALSE
1633 public function isValidCssJsSubpage() {
1634 if ( $this->isCssJsSubpage() ) {
1635 $skinNames = Skin
::getSkinNames();
1636 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1642 * Trim down a .css or .js subpage title to get the corresponding skin name
1644 public function getSkinFromCssJsSubpage() {
1645 $subpage = explode( '/', $this->mTextform
);
1646 $subpage = $subpage[ count( $subpage ) - 1 ];
1647 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1650 * Is this a .css subpage of a user page?
1651 * @return \type{\bool} TRUE or FALSE
1653 public function isCssSubpage() {
1654 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1657 * Is this a .js subpage of a user page?
1658 * @return \type{\bool} TRUE or FALSE
1660 public function isJsSubpage() {
1661 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1664 * Protect css/js subpages of user pages: can $wgUser edit
1667 * @return \type{\bool} TRUE or FALSE
1668 * @todo XXX: this might be better using restrictions
1670 public function userCanEditCssJsSubpage() {
1672 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1676 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1678 * @return \type{\bool} If the page is subject to cascading restrictions.
1680 public function isCascadeProtected() {
1681 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1682 return ( $sources > 0 );
1686 * Cascading protection: Get the source of any cascading restrictions on this page.
1688 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1689 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1690 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1691 * The restriction array is an array of each type, each of which contains an array of unique groups.
1693 public function getCascadeProtectionSources( $get_pages = true ) {
1694 global $wgRestrictionTypes;
1696 # Define our dimension of restrictions types
1697 $pagerestrictions = array();
1698 foreach( $wgRestrictionTypes as $action )
1699 $pagerestrictions[$action] = array();
1701 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1702 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1703 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1704 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1707 wfProfileIn( __METHOD__
);
1709 $dbr = wfGetDB( DB_SLAVE
);
1711 if ( $this->getNamespace() == NS_FILE
) {
1712 $tables = array ('imagelinks', 'page_restrictions');
1713 $where_clauses = array(
1714 'il_to' => $this->getDBkey(),
1716 'pr_cascade' => 1 );
1718 $tables = array ('templatelinks', 'page_restrictions');
1719 $where_clauses = array(
1720 'tl_namespace' => $this->getNamespace(),
1721 'tl_title' => $this->getDBkey(),
1723 'pr_cascade' => 1 );
1727 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1728 $where_clauses[] = 'page_id=pr_page';
1731 $cols = array( 'pr_expiry' );
1734 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1736 $sources = $get_pages ?
array() : false;
1737 $now = wfTimestampNow();
1738 $purgeExpired = false;
1740 foreach( $res as $row ) {
1741 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1742 if( $expiry > $now ) {
1744 $page_id = $row->pr_page
;
1745 $page_ns = $row->page_namespace
;
1746 $page_title = $row->page_title
;
1747 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1748 # Add groups needed for each restriction type if its not already there
1749 # Make sure this restriction type still exists
1750 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1751 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1757 // Trigger lazy purge of expired restrictions from the db
1758 $purgeExpired = true;
1761 if( $purgeExpired ) {
1762 Title
::purgeExpiredRestrictions();
1765 wfProfileOut( __METHOD__
);
1768 $this->mCascadeSources
= $sources;
1769 $this->mCascadingRestrictions
= $pagerestrictions;
1771 $this->mHasCascadingRestrictions
= $sources;
1773 return array( $sources, $pagerestrictions );
1776 function areRestrictionsCascading() {
1777 if (!$this->mRestrictionsLoaded
) {
1778 $this->loadRestrictions();
1781 return $this->mCascadeRestriction
;
1785 * Loads a string into mRestrictions array
1786 * @param $res \type{Resource} restrictions as an SQL result.
1788 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1789 global $wgRestrictionTypes;
1790 $dbr = wfGetDB( DB_SLAVE
);
1792 foreach( $wgRestrictionTypes as $type ){
1793 $this->mRestrictions
[$type] = array();
1794 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry('');
1797 $this->mCascadeRestriction
= false;
1799 # Backwards-compatibility: also load the restrictions from the page record (old format).
1801 if ( $oldFashionedRestrictions === NULL ) {
1802 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1803 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1806 if ($oldFashionedRestrictions != '') {
1808 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1809 $temp = explode( '=', trim( $restrict ) );
1810 if(count($temp) == 1) {
1811 // old old format should be treated as edit/move restriction
1812 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1813 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1815 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1819 $this->mOldRestrictions
= true;
1823 if( $dbr->numRows( $res ) ) {
1824 # Current system - load second to make them override.
1825 $now = wfTimestampNow();
1826 $purgeExpired = false;
1828 foreach( $res as $row ) {
1829 # Cycle through all the restrictions.
1831 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1832 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1835 // This code should be refactored, now that it's being used more generally,
1836 // But I don't really see any harm in leaving it in Block for now -werdna
1837 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1839 // Only apply the restrictions if they haven't expired!
1840 if ( !$expiry ||
$expiry > $now ) {
1841 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
1842 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1844 $this->mCascadeRestriction |
= $row->pr_cascade
;
1846 // Trigger a lazy purge of expired restrictions
1847 $purgeExpired = true;
1851 if( $purgeExpired ) {
1852 Title
::purgeExpiredRestrictions();
1856 $this->mRestrictionsLoaded
= true;
1860 * Load restrictions from the page_restrictions table
1862 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1863 if( !$this->mRestrictionsLoaded
) {
1864 if ($this->exists()) {
1865 $dbr = wfGetDB( DB_SLAVE
);
1867 $res = $dbr->select( 'page_restrictions', '*',
1868 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1870 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1872 $title_protection = $this->getTitleProtection();
1874 if (is_array($title_protection)) {
1875 extract($title_protection);
1877 $now = wfTimestampNow();
1878 $expiry = Block
::decodeExpiry($pt_expiry);
1880 if (!$expiry ||
$expiry > $now) {
1881 // Apply the restrictions
1882 $this->mRestrictionsExpiry
['create'] = $expiry;
1883 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1884 } else { // Get rid of the old restrictions
1885 Title
::purgeExpiredRestrictions();
1888 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry('');
1890 $this->mRestrictionsLoaded
= true;
1896 * Purge expired restrictions from the page_restrictions table
1898 static function purgeExpiredRestrictions() {
1899 $dbw = wfGetDB( DB_MASTER
);
1900 $dbw->delete( 'page_restrictions',
1901 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1904 $dbw->delete( 'protected_titles',
1905 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1910 * Accessor/initialisation for mRestrictions
1912 * @param $action \type{\string} action that permission needs to be checked for
1913 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
1915 public function getRestrictions( $action ) {
1916 if( !$this->mRestrictionsLoaded
) {
1917 $this->loadRestrictions();
1919 return isset( $this->mRestrictions
[$action] )
1920 ?
$this->mRestrictions
[$action]
1925 * Get the expiry time for the restriction against a given action
1926 * @return 14-char timestamp, or 'infinity' if the page is protected forever
1927 * or not protected at all, or false if the action is not recognised.
1929 public function getRestrictionExpiry( $action ) {
1930 if( !$this->mRestrictionsLoaded
) {
1931 $this->loadRestrictions();
1933 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
1937 * Is there a version of this page in the deletion archive?
1938 * @return \type{\int} the number of archived revisions
1940 public function isDeleted() {
1941 if( $this->getNamespace() < 0 ) {
1944 $dbr = wfGetDB( DB_SLAVE
);
1945 $n = $dbr->selectField( 'archive', 'COUNT(*)',
1946 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
1949 if( $this->getNamespace() == NS_FILE
) {
1950 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1951 array( 'fa_name' => $this->getDBkey() ),
1960 * Is there a version of this page in the deletion archive?
1963 public function isDeletedQuick() {
1964 if( $this->getNamespace() < 0 ) {
1967 $dbr = wfGetDB( DB_SLAVE
);
1968 $deleted = (bool)$dbr->selectField( 'archive', '1',
1969 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
1972 if( !$deleted && $this->getNamespace() == NS_FILE
) {
1973 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
1974 array( 'fa_name' => $this->getDBkey() ),
1982 * Get the article ID for this Title from the link cache,
1983 * adding it if necessary
1984 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
1986 * @return \type{\int} the ID
1988 public function getArticleID( $flags = 0 ) {
1989 if( $this->getNamespace() < 0 ) {
1990 return $this->mArticleID
= 0;
1992 $linkCache = LinkCache
::singleton();
1993 if( $flags & GAID_FOR_UPDATE
) {
1994 $oldUpdate = $linkCache->forUpdate( true );
1995 $linkCache->clearLink( $this );
1996 $this->mArticleID
= $linkCache->addLinkObj( $this );
1997 $linkCache->forUpdate( $oldUpdate );
1999 if( -1 == $this->mArticleID
) {
2000 $this->mArticleID
= $linkCache->addLinkObj( $this );
2003 return $this->mArticleID
;
2007 * Is this an article that is a redirect page?
2008 * Uses link cache, adding it if necessary
2009 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2010 * @return \type{\bool}
2012 public function isRedirect( $flags = 0 ) {
2013 if( !is_null($this->mRedirect
) )
2014 return $this->mRedirect
;
2015 # Calling getArticleID() loads the field from cache as needed
2016 if( !$this->getArticleID($flags) ) {
2017 return $this->mRedirect
= false;
2019 $linkCache = LinkCache
::singleton();
2020 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2022 return $this->mRedirect
;
2026 * What is the length of this page?
2027 * Uses link cache, adding it if necessary
2028 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2029 * @return \type{\bool}
2031 public function getLength( $flags = 0 ) {
2032 if( $this->mLength
!= -1 )
2033 return $this->mLength
;
2034 # Calling getArticleID() loads the field from cache as needed
2035 if( !$this->getArticleID($flags) ) {
2036 return $this->mLength
= 0;
2038 $linkCache = LinkCache
::singleton();
2039 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2041 return $this->mLength
;
2045 * What is the page_latest field for this page?
2046 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2047 * @return \type{\int}
2049 public function getLatestRevID( $flags = 0 ) {
2050 if( $this->mLatestID
!== false )
2051 return $this->mLatestID
;
2053 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
2054 $this->mLatestID
= $db->selectField( 'page', 'page_latest', $this->pageCond(), __METHOD__
);
2055 return $this->mLatestID
;
2059 * This clears some fields in this object, and clears any associated
2060 * keys in the "bad links" section of the link cache.
2062 * - This is called from Article::insertNewArticle() to allow
2063 * loading of the new page_id. It's also called from
2064 * Article::doDeleteArticle()
2066 * @param $newid \type{\int} the new Article ID
2068 public function resetArticleID( $newid ) {
2069 $linkCache = LinkCache
::singleton();
2070 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2072 if ( $newid === false ) { $this->mArticleID
= -1; }
2073 else { $this->mArticleID
= $newid; }
2074 $this->mRestrictionsLoaded
= false;
2075 $this->mRestrictions
= array();
2079 * Updates page_touched for this page; called from LinksUpdate.php
2080 * @return \type{\bool} true if the update succeded
2082 public function invalidateCache() {
2083 if( wfReadOnly() ) {
2086 $dbw = wfGetDB( DB_MASTER
);
2087 $success = $dbw->update( 'page',
2088 array( 'page_touched' => $dbw->timestamp() ),
2092 HTMLFileCache
::clearFileCache( $this );
2097 * Prefix some arbitrary text with the namespace or interwiki prefix
2100 * @param $name \type{\string} the text
2101 * @return \type{\string} the prefixed text
2104 /* private */ function prefix( $name ) {
2106 if ( '' != $this->mInterwiki
) {
2107 $p = $this->mInterwiki
. ':';
2109 if ( 0 != $this->mNamespace
) {
2110 $p .= $this->getNsText() . ':';
2116 * Secure and split - main initialisation function for this object
2118 * Assumes that mDbkeyform has been set, and is urldecoded
2119 * and uses underscores, but not otherwise munged. This function
2120 * removes illegal characters, splits off the interwiki and
2121 * namespace prefixes, sets the other forms, and canonicalizes
2123 * @return \type{\bool} true on success
2125 private function secureAndSplit() {
2126 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2129 static $rxTc = false;
2131 # Matching titles will be held as illegal.
2133 # Any character not allowed is forbidden...
2134 '[^' . Title
::legalChars() . ']' .
2135 # URL percent encoding sequences interfere with the ability
2136 # to round-trip titles -- you can't link to them consistently.
2137 '|%[0-9A-Fa-f]{2}' .
2138 # XML/HTML character references produce similar issues.
2139 '|&[A-Za-z0-9\x80-\xff]+;' .
2141 '|&#x[0-9A-Fa-f]+;' .
2145 $this->mInterwiki
= $this->mFragment
= '';
2146 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2148 $dbkey = $this->mDbkeyform
;
2150 # Strip Unicode bidi override characters.
2151 # Sometimes they slip into cut-n-pasted page titles, where the
2152 # override chars get included in list displays.
2153 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2155 # Clean up whitespace
2157 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2158 $dbkey = trim( $dbkey, '_' );
2160 if ( '' == $dbkey ) {
2164 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2165 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2169 $this->mDbkeyform
= $dbkey;
2171 # Initial colon indicates main namespace rather than specified default
2172 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2173 if ( ':' == $dbkey{0} ) {
2174 $this->mNamespace
= NS_MAIN
;
2175 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2176 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2179 # Namespace or interwiki prefix
2181 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2184 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2186 if ( $ns = $wgContLang->getNsIndex( $p ) ) {
2187 # Ordinary namespace
2189 $this->mNamespace
= $ns;
2190 # For Talk:X pages, check if X has a "namespace" prefix
2191 if( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2192 if( $wgContLang->getNsIndex( $x[1] ) )
2193 return false; # Disallow Talk:File:x type titles...
2194 else if( Interwiki
::isValidInterwiki( $x[1] ) )
2195 return false; # Disallow Talk:Interwiki:x type titles...
2197 } elseif( Interwiki
::isValidInterwiki( $p ) ) {
2199 # Can't make a local interwiki link to an interwiki link.
2200 # That's just crazy!
2206 $this->mInterwiki
= $wgContLang->lc( $p );
2208 # Redundant interwiki prefix to the local wiki
2209 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2210 if( $dbkey == '' ) {
2211 # Can't have an empty self-link
2214 $this->mInterwiki
= '';
2216 # Do another namespace split...
2220 # If there's an initial colon after the interwiki, that also
2221 # resets the default namespace
2222 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2223 $this->mNamespace
= NS_MAIN
;
2224 $dbkey = substr( $dbkey, 1 );
2227 # If there's no recognized interwiki or namespace,
2228 # then let the colon expression be part of the title.
2233 # We already know that some pages won't be in the database!
2235 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2236 $this->mArticleID
= 0;
2238 $fragment = strstr( $dbkey, '#' );
2239 if ( false !== $fragment ) {
2240 $this->setFragment( $fragment );
2241 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2242 # remove whitespace again: prevents "Foo_bar_#"
2243 # becoming "Foo_bar_"
2244 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2247 # Reject illegal characters.
2249 if( preg_match( $rxTc, $dbkey ) ) {
2254 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2255 * reachable due to the way web browsers deal with 'relative' URLs.
2256 * Also, they conflict with subpage syntax. Forbid them explicitly.
2258 if ( strpos( $dbkey, '.' ) !== false &&
2259 ( $dbkey === '.' ||
$dbkey === '..' ||
2260 strpos( $dbkey, './' ) === 0 ||
2261 strpos( $dbkey, '../' ) === 0 ||
2262 strpos( $dbkey, '/./' ) !== false ||
2263 strpos( $dbkey, '/../' ) !== false ||
2264 substr( $dbkey, -2 ) == '/.' ||
2265 substr( $dbkey, -3 ) == '/..' ) )
2271 * Magic tilde sequences? Nu-uh!
2273 if( strpos( $dbkey, '~~~' ) !== false ) {
2278 * Limit the size of titles to 255 bytes.
2279 * This is typically the size of the underlying database field.
2280 * We make an exception for special pages, which don't need to be stored
2281 * in the database, and may edge over 255 bytes due to subpage syntax
2282 * for long titles, e.g. [[Special:Block/Long name]]
2284 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2285 strlen( $dbkey ) > 512 )
2291 * Normally, all wiki links are forced to have
2292 * an initial capital letter so [[foo]] and [[Foo]]
2293 * point to the same place.
2295 * Don't force it for interwikis, since the other
2296 * site might be case-sensitive.
2298 $this->mUserCaseDBKey
= $dbkey;
2299 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2300 $dbkey = $wgContLang->ucfirst( $dbkey );
2304 * Can't make a link to a namespace alone...
2305 * "empty" local links can only be self-links
2306 * with a fragment identifier.
2309 $this->mInterwiki
== '' &&
2310 $this->mNamespace
!= NS_MAIN
) {
2313 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2314 // IP names are not allowed for accounts, and can only be referring to
2315 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2316 // there are numerous ways to present the same IP. Having sp:contribs scan
2317 // them all is silly and having some show the edits and others not is
2318 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2319 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2320 IP
::sanitizeIP( $dbkey ) : $dbkey;
2321 // Any remaining initial :s are illegal.
2322 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2327 $this->mDbkeyform
= $dbkey;
2328 $this->mUrlform
= wfUrlencode( $dbkey );
2330 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2336 * Set the fragment for this title. Removes the first character from the
2337 * specified fragment before setting, so it assumes you're passing it with
2340 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2341 * Still in active use privately.
2343 * @param $fragment \type{\string} text
2345 public function setFragment( $fragment ) {
2346 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2350 * Get a Title object associated with the talk page of this article
2351 * @return \type{Title} the object for the talk page
2353 public function getTalkPage() {
2354 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2358 * Get a title object associated with the subject page of this
2361 * @return \type{Title} the object for the subject page
2363 public function getSubjectPage() {
2364 // Is this the same title?
2365 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2366 if( $this->getNamespace() == $subjectNS ) {
2369 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2373 * Get an array of Title objects linking to this Title
2374 * Also stores the IDs in the link cache.
2376 * WARNING: do not use this function on arbitrary user-supplied titles!
2377 * On heavily-used templates it will max out the memory.
2379 * @param array $options may be FOR UPDATE
2380 * @return \type{\arrayof{Title}} the Title objects linking here
2382 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2383 $linkCache = LinkCache
::singleton();
2385 if ( count( $options ) > 0 ) {
2386 $db = wfGetDB( DB_MASTER
);
2388 $db = wfGetDB( DB_SLAVE
);
2391 $res = $db->select( array( 'page', $table ),
2392 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2394 "{$prefix}_from=page_id",
2395 "{$prefix}_namespace" => $this->getNamespace(),
2396 "{$prefix}_title" => $this->getDBkey() ),
2401 if ( $db->numRows( $res ) ) {
2402 foreach( $res as $row ) {
2403 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2404 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2405 $retVal[] = $titleObj;
2409 $db->freeResult( $res );
2414 * Get an array of Title objects using this Title as a template
2415 * Also stores the IDs in the link cache.
2417 * WARNING: do not use this function on arbitrary user-supplied titles!
2418 * On heavily-used templates it will max out the memory.
2420 * @param array $options may be FOR UPDATE
2421 * @return \type{\arrayof{Title}} the Title objects linking here
2423 public function getTemplateLinksTo( $options = array() ) {
2424 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2428 * Get an array of Title objects referring to non-existent articles linked from this page
2430 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2431 * @return \type{\arrayof{Title}} the Title objects
2433 public function getBrokenLinksFrom() {
2434 if ( $this->getArticleId() == 0 ) {
2435 # All links from article ID 0 are false positives
2439 $dbr = wfGetDB( DB_SLAVE
);
2440 $res = $dbr->select(
2441 array( 'page', 'pagelinks' ),
2442 array( 'pl_namespace', 'pl_title' ),
2444 'pl_from' => $this->getArticleId(),
2445 'page_namespace IS NULL'
2447 __METHOD__
, array(),
2451 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2457 foreach( $res as $row ) {
2458 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2465 * Get a list of URLs to purge from the Squid cache when this
2468 * @return \type{\arrayof{\string}} the URLs
2470 public function getSquidURLs() {
2474 $this->getInternalURL(),
2475 $this->getInternalURL( 'action=history' )
2478 // purge variant urls as well
2479 if($wgContLang->hasVariants()){
2480 $variants = $wgContLang->getVariants();
2481 foreach($variants as $vCode){
2482 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2483 $urls[] = $this->getInternalURL('',$vCode);
2491 * Purge all applicable Squid URLs
2493 public function purgeSquid() {
2495 if ( $wgUseSquid ) {
2496 $urls = $this->getSquidURLs();
2497 $u = new SquidUpdate( $urls );
2503 * Move this page without authentication
2504 * @param &$nt \type{Title} the new page Title
2506 public function moveNoAuth( &$nt ) {
2507 return $this->moveTo( $nt, false );
2511 * Check whether a given move operation would be valid.
2512 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2513 * @param &$nt \type{Title} the new title
2514 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2516 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2517 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2519 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2524 // Normally we'd add this to $errors, but we'll get
2525 // lots of syntax errors if $nt is not an object
2526 return array(array('badtitletext'));
2528 if( $this->equals( $nt ) ) {
2529 $errors[] = array('selfmove');
2531 if( !$this->isMovable() ) {
2532 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2534 if ( $nt->getInterwiki() != '' ) {
2535 $errors[] = array( 'immobile-target-namespace-iw' );
2537 if ( !$nt->isMovable() ) {
2538 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2541 $oldid = $this->getArticleID();
2542 $newid = $nt->getArticleID();
2544 if ( strlen( $nt->getDBkey() ) < 1 ) {
2545 $errors[] = array('articleexists');
2547 if ( ( '' == $this->getDBkey() ) ||
2549 ( '' == $nt->getDBkey() ) ) {
2550 $errors[] = array('badarticleerror');
2553 // Image-specific checks
2554 if( $this->getNamespace() == NS_FILE
) {
2555 $file = wfLocalFile( $this );
2556 if( $file->exists() ) {
2557 if( $nt->getNamespace() != NS_FILE
) {
2558 $errors[] = array('imagenocrossnamespace');
2560 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2561 $errors[] = array('imageinvalidfilename');
2563 if( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2564 $errors[] = array('imagetypemismatch');
2570 $errors = wfMergeErrorArrays( $errors,
2571 $this->getUserPermissionsErrors('move', $wgUser),
2572 $this->getUserPermissionsErrors('edit', $wgUser),
2573 $nt->getUserPermissionsErrors('move-target', $wgUser),
2574 $nt->getUserPermissionsErrors('edit', $wgUser) );
2577 $match = EditPage
::matchSummarySpamRegex( $reason );
2578 if( $match !== false ) {
2579 // This is kind of lame, won't display nice
2580 $errors[] = array('spamprotectiontext');
2584 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2585 $errors[] = array('hookaborted', $err);
2588 # The move is allowed only if (1) the target doesn't exist, or
2589 # (2) the target is a redirect to the source, and has no history
2590 # (so we can undo bad moves right after they're done).
2592 if ( 0 != $newid ) { # Target exists; check for validity
2593 if ( ! $this->isValidMoveTarget( $nt ) ) {
2594 $errors[] = array('articleexists');
2597 $tp = $nt->getTitleProtection();
2598 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2599 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2600 $errors[] = array('cantmove-titleprotected');
2609 * Move a title to a new location
2610 * @param &$nt \type{Title} the new title
2611 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2613 * @param $reason \type{\string} The reason for the move
2614 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2615 * Ignored if the user doesn't have the suppressredirect right.
2616 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2618 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2619 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2620 if( is_array( $err ) ) {
2624 // If it is a file, more it first. It is done before all other moving stuff is done because it's hard to revert
2625 $dbw = wfGetDB( DB_MASTER
);
2626 if( $this->getNamespace() == NS_FILE
) {
2627 $file = wfLocalFile( $this );
2628 if( $file->exists() ) {
2629 $status = $file->move( $nt );
2630 if( !$status->isOk() ) {
2631 return $status->getErrorsArray();
2636 $pageid = $this->getArticleID();
2637 $protected = $this->isProtected();
2638 if( $nt->exists() ) {
2639 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2640 $pageCountChange = ($createRedirect ?
0 : -1);
2641 } else { # Target didn't exist, do normal move.
2642 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2643 $pageCountChange = ($createRedirect ?
1 : 0);
2646 if( is_array( $err ) ) {
2649 $redirid = $this->getArticleID();
2651 // Category memberships include a sort key which may be customized.
2652 // If it's left as the default (the page title), we need to update
2653 // the sort key to match the new title.
2655 // Be careful to avoid resetting cl_timestamp, which may disturb
2656 // time-based lists on some sites.
2658 // Warning -- if the sort key is *explicitly* set to the old title,
2659 // we can't actually distinguish it from a default here, and it'll
2660 // be set to the new title even though it really shouldn't.
2661 // It'll get corrected on the next edit, but resetting cl_timestamp.
2662 $dbw->update( 'categorylinks',
2664 'cl_sortkey' => $nt->getPrefixedText(),
2665 'cl_timestamp=cl_timestamp' ),
2667 'cl_from' => $pageid,
2668 'cl_sortkey' => $this->getPrefixedText() ),
2672 # Protect the redirect title as the title used to be...
2673 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2675 'pr_page' => $redirid,
2676 'pr_type' => 'pr_type',
2677 'pr_level' => 'pr_level',
2678 'pr_cascade' => 'pr_cascade',
2679 'pr_user' => 'pr_user',
2680 'pr_expiry' => 'pr_expiry'
2682 array( 'pr_page' => $pageid ),
2686 # Update the protection log
2687 $log = new LogPage( 'protect' );
2688 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2689 if( $reason ) $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2690 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2694 $oldnamespace = $this->getNamespace() & ~
1;
2695 $newnamespace = $nt->getNamespace() & ~
1;
2696 $oldtitle = $this->getDBkey();
2697 $newtitle = $nt->getDBkey();
2699 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2700 WatchedItem
::duplicateEntries( $this, $nt );
2703 # Update search engine
2704 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2706 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2710 if( $this->isContentPage() && !$nt->isContentPage() ) {
2711 # No longer a content page
2712 # Not viewed, edited, removing
2713 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2714 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2715 # Now a content page
2716 # Not viewed, edited, adding
2717 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2718 } elseif( $pageCountChange ) {
2720 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2727 # Update message cache for interface messages
2728 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2729 global $wgMessageCache;
2731 # @bug 17860: old article can be deleted, if this the case,
2732 # delete it from message cache
2733 if ( $this->getArticleID() === 0 ) {
2734 $wgMessageCache->replace( $this->getDBkey(), false );
2736 $oldarticle = new Article( $this );
2737 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2740 $newarticle = new Article( $nt );
2741 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2745 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2750 * Move page to a title which is at present a redirect to the
2753 * @param &$nt \type{Title} the page to move to, which should currently
2755 * @param $reason \type{\string} The reason for the move
2756 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2757 * Ignored if the user doesn't have the suppressredirect right
2759 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2760 global $wgUseSquid, $wgUser;
2761 $fname = 'Title::moveOverExistingRedirect';
2762 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2765 $comment .= ": $reason";
2768 $now = wfTimestampNow();
2769 $newid = $nt->getArticleID();
2770 $oldid = $this->getArticleID();
2771 $latest = $this->getLatestRevID();
2773 $dbw = wfGetDB( DB_MASTER
);
2775 # Delete the old redirect. We don't save it to history since
2776 # by definition if we've got here it's rather uninteresting.
2777 # We have to remove it so that the next step doesn't trigger
2778 # a conflict on the unique namespace+title index...
2779 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2780 if ( !$dbw->cascadingDeletes() ) {
2781 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2782 global $wgUseTrackbacks;
2783 if ($wgUseTrackbacks)
2784 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2785 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2786 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2787 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2788 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2789 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2790 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2791 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2794 # Save a null revision in the page's history notifying of the move
2795 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2796 $nullRevId = $nullRevision->insertOn( $dbw );
2798 $article = new Article( $this );
2799 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
2801 # Change the name of the target page:
2802 $dbw->update( 'page',
2804 'page_touched' => $dbw->timestamp($now),
2805 'page_namespace' => $nt->getNamespace(),
2806 'page_title' => $nt->getDBkey(),
2807 'page_latest' => $nullRevId,
2809 /* WHERE */ array( 'page_id' => $oldid ),
2812 $nt->resetArticleID( $oldid );
2814 # Recreate the redirect, this time in the other direction.
2815 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2816 $mwRedir = MagicWord
::get( 'redirect' );
2817 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2818 $redirectArticle = new Article( $this );
2819 $newid = $redirectArticle->insertOn( $dbw );
2820 $redirectRevision = new Revision( array(
2822 'comment' => $comment,
2823 'text' => $redirectText ) );
2824 $redirectRevision->insertOn( $dbw );
2825 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2827 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
2829 # Now, we record the link from the redirect to the new title.
2830 # It should have no other outgoing links...
2831 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2832 $dbw->insert( 'pagelinks',
2834 'pl_from' => $newid,
2835 'pl_namespace' => $nt->getNamespace(),
2836 'pl_title' => $nt->getDBkey() ),
2838 $redirectSuppressed = false;
2840 $this->resetArticleID( 0 );
2841 $redirectSuppressed = true;
2845 $log = new LogPage( 'move' );
2846 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
2849 if ( $wgUseSquid ) {
2850 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2851 $u = new SquidUpdate( $urls );
2858 * Move page to non-existing title.
2859 * @param &$nt \type{Title} the new Title
2860 * @param $reason \type{\string} The reason for the move
2861 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2862 * Ignored if the user doesn't have the suppressredirect right
2864 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2865 global $wgUseSquid, $wgUser;
2866 $fname = 'MovePageForm::moveToNewTitle';
2867 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2869 $comment .= wfMsgExt( 'colon-separator',
2870 array( 'escapenoentities', 'content' ) );
2871 $comment .= $reason;
2874 $newid = $nt->getArticleID();
2875 $oldid = $this->getArticleID();
2876 $latest = $this->getLatestRevId();
2878 $dbw = wfGetDB( DB_MASTER
);
2879 $now = $dbw->timestamp();
2881 # Save a null revision in the page's history notifying of the move
2882 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2883 $nullRevId = $nullRevision->insertOn( $dbw );
2885 $article = new Article( $this );
2886 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
2889 $dbw->update( 'page',
2891 'page_touched' => $now,
2892 'page_namespace' => $nt->getNamespace(),
2893 'page_title' => $nt->getDBkey(),
2894 'page_latest' => $nullRevId,
2896 /* WHERE */ array( 'page_id' => $oldid ),
2899 $nt->resetArticleID( $oldid );
2901 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2903 $mwRedir = MagicWord
::get( 'redirect' );
2904 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2905 $redirectArticle = new Article( $this );
2906 $newid = $redirectArticle->insertOn( $dbw );
2907 $redirectRevision = new Revision( array(
2909 'comment' => $comment,
2910 'text' => $redirectText ) );
2911 $redirectRevision->insertOn( $dbw );
2912 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2914 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
2916 # Record the just-created redirect's linking to the page
2917 $dbw->insert( 'pagelinks',
2919 'pl_from' => $newid,
2920 'pl_namespace' => $nt->getNamespace(),
2921 'pl_title' => $nt->getDBkey() ),
2923 $redirectSuppressed = false;
2925 $this->resetArticleID( 0 );
2926 $redirectSuppressed = true;
2930 $log = new LogPage( 'move' );
2931 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
2933 # Purge caches as per article creation
2934 Article
::onArticleCreate( $nt );
2936 # Purge old title from squid
2937 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2938 $this->purgeSquid();
2943 * Move this page's subpages to be subpages of $nt
2944 * @param $nt Title Move target
2945 * @param $auth bool Whether $wgUser's permissions should be checked
2946 * @param $reason string The reason for the move
2947 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
2948 * Ignored if the user doesn't have the 'suppressredirect' right
2949 * @return mixed array with old page titles as keys, and strings (new page titles) or
2950 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
2952 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
2953 global $wgMaximumMovedPages;
2954 // Check permissions
2955 if( !$this->userCan( 'move-subpages' ) )
2956 return array( 'cant-move-subpages' );
2957 // Do the source and target namespaces support subpages?
2958 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
2959 return array( 'namespace-nosubpages',
2960 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
2961 if( !MWNamespace
::hasSubpages( $nt->getNamespace() ) )
2962 return array( 'namespace-nosubpages',
2963 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
2965 $subpages = $this->getSubpages($wgMaximumMovedPages +
1);
2968 foreach( $subpages as $oldSubpage ) {
2970 if( $count > $wgMaximumMovedPages ) {
2971 $retval[$oldSubpage->getPrefixedTitle()] =
2972 array( 'movepage-max-pages',
2973 $wgMaximumMovedPages );
2977 if( $oldSubpage->getArticleId() == $this->getArticleId() )
2978 // When moving a page to a subpage of itself,
2979 // don't move it twice
2981 $newPageName = preg_replace(
2982 '#^'.preg_quote( $this->getDBkey(), '#' ).'#',
2983 $nt->getDBkey(), $oldSubpage->getDBkey() );
2984 if( $oldSubpage->isTalkPage() ) {
2985 $newNs = $nt->getTalkPage()->getNamespace();
2987 $newNs = $nt->getSubjectPage()->getNamespace();
2989 # Bug 14385: we need makeTitleSafe because the new page names may
2990 # be longer than 255 characters.
2991 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
2993 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
2994 if( $success === true ) {
2995 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
2997 $retval[$oldSubpage->getPrefixedText()] = $success;
3004 * Checks if this page is just a one-rev redirect.
3005 * Adds lock, so don't use just for light purposes.
3007 * @return \type{\bool} TRUE or FALSE
3009 public function isSingleRevRedirect() {
3010 $dbw = wfGetDB( DB_MASTER
);
3012 $row = $dbw->selectRow( 'page',
3013 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3016 array( 'FOR UPDATE' )
3018 # Cache some fields we may want
3019 $this->mArticleID
= $row ?
intval($row->page_id
) : 0;
3020 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3021 $this->mLatestID
= $row ?
intval($row->page_latest
) : false;
3022 if( !$this->mRedirect
) {
3025 # Does the article have a history?
3026 $row = $dbw->selectField( array( 'page', 'revision'),
3028 array( 'page_namespace' => $this->getNamespace(),
3029 'page_title' => $this->getDBkey(),
3031 'page_latest != rev_id'
3034 array( 'FOR UPDATE' )
3036 # Return true if there was no history
3037 return ($row === false);
3041 * Checks if $this can be moved to a given Title
3042 * - Selects for update, so don't call it unless you mean business
3044 * @param &$nt \type{Title} the new title to check
3045 * @return \type{\bool} TRUE or FALSE
3047 public function isValidMoveTarget( $nt ) {
3048 $dbw = wfGetDB( DB_MASTER
);
3049 # Is it an existsing file?
3050 if( $nt->getNamespace() == NS_FILE
) {
3051 $file = wfLocalFile( $nt );
3052 if( $file->exists() ) {
3053 wfDebug( __METHOD__
. ": file exists\n" );
3057 # Is it a redirect with no history?
3058 if( !$nt->isSingleRevRedirect() ) {
3059 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3062 # Get the article text
3063 $rev = Revision
::newFromTitle( $nt );
3064 $text = $rev->getText();
3065 # Does the redirect point to the source?
3066 # Or is it a broken self-redirect, usually caused by namespace collisions?
3068 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3069 $redirTitle = Title
::newFromText( $m[1] );
3070 if( !is_object( $redirTitle ) ||
3071 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3072 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3073 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3078 wfDebug( __METHOD__
. ": failsafe\n" );
3085 * Can this title be added to a user's watchlist?
3087 * @return \type{\bool} TRUE or FALSE
3089 public function isWatchable() {
3090 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3094 * Get categories to which this Title belongs and return an array of
3095 * categories' names.
3097 * @return \type{\array} array an array of parents in the form:
3098 * $parent => $currentarticle
3100 public function getParentCategories() {
3103 $titlekey = $this->getArticleId();
3104 $dbr = wfGetDB( DB_SLAVE
);
3105 $categorylinks = $dbr->tableName( 'categorylinks' );
3108 $sql = "SELECT * FROM $categorylinks"
3109 ." WHERE cl_from='$titlekey'"
3110 ." AND cl_from <> '0'"
3111 ." ORDER BY cl_sortkey";
3113 $res = $dbr->query( $sql );
3115 if( $dbr->numRows( $res ) > 0 ) {
3116 foreach( $res as $row )
3117 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3118 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
3119 $dbr->freeResult( $res );
3127 * Get a tree of parent categories
3128 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3129 * @return \type{\array} Tree of parent categories
3131 public function getParentCategoryTree( $children = array() ) {
3133 $parents = $this->getParentCategories();
3136 foreach( $parents as $parent => $current ) {
3137 if ( array_key_exists( $parent, $children ) ) {
3138 # Circular reference
3139 $stack[$parent] = array();
3141 $nt = Title
::newFromText($parent);
3143 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
3155 * Get an associative array for selecting this title from
3158 * @return \type{\array} Selection array
3160 public function pageCond() {
3161 if( $this->mArticleID
> 0 ) {
3162 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3163 return array( 'page_id' => $this->mArticleID
);
3165 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3170 * Get the revision ID of the previous revision
3172 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3173 * @param $flags \type{\int} GAID_FOR_UPDATE
3174 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3176 public function getPreviousRevisionID( $revId, $flags=0 ) {
3177 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3178 return $db->selectField( 'revision', 'rev_id',
3180 'rev_page' => $this->getArticleId($flags),
3181 'rev_id < ' . intval( $revId )
3184 array( 'ORDER BY' => 'rev_id DESC' )
3189 * Get the revision ID of the next revision
3191 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3192 * @param $flags \type{\int} GAID_FOR_UPDATE
3193 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3195 public function getNextRevisionID( $revId, $flags=0 ) {
3196 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3197 return $db->selectField( 'revision', 'rev_id',
3199 'rev_page' => $this->getArticleId($flags),
3200 'rev_id > ' . intval( $revId )
3203 array( 'ORDER BY' => 'rev_id' )
3208 * Get the first revision of the page
3210 * @param $flags \type{\int} GAID_FOR_UPDATE
3211 * @return Revision (or NULL if page doesn't exist)
3213 public function getFirstRevision( $flags=0 ) {
3214 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3215 $pageId = $this->getArticleId($flags);
3216 if( !$pageId ) return NULL;
3217 $row = $db->selectRow( 'revision', '*',
3218 array( 'rev_page' => $pageId ),
3220 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3225 return new Revision( $row );
3230 * Check if this is a new page
3234 public function isNewPage() {
3235 $dbr = wfGetDB( DB_SLAVE
);
3236 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3240 * Get the oldest revision timestamp of this page
3242 * @return string, MW timestamp
3244 public function getEarliestRevTime() {
3245 $dbr = wfGetDB( DB_SLAVE
);
3246 if( $this->exists() ) {
3247 $min = $dbr->selectField( 'revision',
3248 'MIN(rev_timestamp)',
3249 array( 'rev_page' => $this->getArticleId() ),
3251 return wfTimestampOrNull( TS_MW
, $min );
3257 * Get the number of revisions between the given revision IDs.
3258 * Used for diffs and other things that really need it.
3260 * @param $old \type{\int} Revision ID.
3261 * @param $new \type{\int} Revision ID.
3262 * @return \type{\int} Number of revisions between these IDs.
3264 public function countRevisionsBetween( $old, $new ) {
3265 $dbr = wfGetDB( DB_SLAVE
);
3266 return $dbr->selectField( 'revision', 'count(*)',
3267 'rev_page = ' . intval( $this->getArticleId() ) .
3268 ' AND rev_id > ' . intval( $old ) .
3269 ' AND rev_id < ' . intval( $new ),
3275 * Compare with another title.
3277 * @param \type{Title} $title
3278 * @return \type{\bool} TRUE or FALSE
3280 public function equals( Title
$title ) {
3281 // Note: === is necessary for proper matching of number-like titles.
3282 return $this->getInterwiki() === $title->getInterwiki()
3283 && $this->getNamespace() == $title->getNamespace()
3284 && $this->getDBkey() === $title->getDBkey();
3288 * Callback for usort() to do title sorts by (namespace, title)
3290 public static function compare( $a, $b ) {
3291 if( $a->getNamespace() == $b->getNamespace() ) {
3292 return strcmp( $a->getText(), $b->getText() );
3294 return $a->getNamespace() - $b->getNamespace();
3299 * Return a string representation of this title
3301 * @return \type{\string} String representation of this title
3303 public function __toString() {
3304 return $this->getPrefixedText();
3308 * Check if page exists. For historical reasons, this function simply
3309 * checks for the existence of the title in the page table, and will
3310 * thus return false for interwiki links, special pages and the like.
3311 * If you want to know if a title can be meaningfully viewed, you should
3312 * probably call the isKnown() method instead.
3314 * @return \type{\bool} TRUE or FALSE
3316 public function exists() {
3317 return $this->getArticleId() != 0;
3321 * Should links to this title be shown as potentially viewable (i.e. as
3322 * "bluelinks"), even if there's no record by this title in the page
3325 * This function is semi-deprecated for public use, as well as somewhat
3326 * misleadingly named. You probably just want to call isKnown(), which
3327 * calls this function internally.
3329 * (ISSUE: Most of these checks are cheap, but the file existence check
3330 * can potentially be quite expensive. Including it here fixes a lot of
3331 * existing code, but we might want to add an optional parameter to skip
3332 * it and any other expensive checks.)
3334 * @return \type{\bool} TRUE or FALSE
3336 public function isAlwaysKnown() {
3337 if( $this->mInterwiki
!= '' ) {
3338 return true; // any interwiki link might be viewable, for all we know
3340 switch( $this->mNamespace
) {
3343 return wfFindFile( $this ); // file exists, possibly in a foreign repo
3345 return SpecialPage
::exists( $this->getDBkey() ); // valid special page
3347 return $this->mDbkeyform
== ''; // selflink, possibly with fragment
3349 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3350 // the full l10n of that language to be loaded. That takes much memory and
3351 // isn't needed. So we strip the language part away.
3352 // Also, extension messages which are not loaded, are shown as red, because
3353 // we don't call MessageCache::loadAllMessages.
3354 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3355 return wfMsgWeirdKey( $basename ); // known system message
3362 * Does this title refer to a page that can (or might) be meaningfully
3363 * viewed? In particular, this function may be used to determine if
3364 * links to the title should be rendered as "bluelinks" (as opposed to
3365 * "redlinks" to non-existent pages).
3367 * @return \type{\bool} TRUE or FALSE
3369 public function isKnown() {
3370 return $this->exists() ||
$this->isAlwaysKnown();
3374 * Is this in a namespace that allows actual pages?
3376 * @return \type{\bool} TRUE or FALSE
3378 public function canExist() {
3379 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
3383 * Update page_touched timestamps and send squid purge messages for
3384 * pages linking to this title. May be sent to the job queue depending
3385 * on the number of links. Typically called on create and delete.
3387 public function touchLinks() {
3388 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3391 if ( $this->getNamespace() == NS_CATEGORY
) {
3392 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3398 * Get the last touched timestamp
3399 * @param Database $db, optional db
3400 * @return \type{\string} Last touched timestamp
3402 public function getTouched( $db = NULL ) {
3403 $db = isset($db) ?
$db : wfGetDB( DB_SLAVE
);
3404 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3409 * Get the timestamp when this page was updated since the user last saw it.
3411 * @return mixed string/NULL
3413 public function getNotificationTimestamp( $user = NULL ) {
3414 global $wgUser, $wgShowUpdatedMarker;
3415 // Assume current user if none given
3416 if( !$user ) $user = $wgUser;
3417 // Check cache first
3418 $uid = $user->getId();
3419 if( isset($this->mNotificationTimestamp
[$uid]) ) {
3420 return $this->mNotificationTimestamp
[$uid];
3422 if( !$uid ||
!$wgShowUpdatedMarker ) {
3423 return $this->mNotificationTimestamp
[$uid] = false;
3425 // Don't cache too much!
3426 if( count($this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3427 $this->mNotificationTimestamp
= array();
3429 $dbr = wfGetDB( DB_SLAVE
);
3430 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3431 'wl_notificationtimestamp',
3432 array( 'wl_namespace' => $this->getNamespace(),
3433 'wl_title' => $this->getDBkey(),
3434 'wl_user' => $user->getId()
3438 return $this->mNotificationTimestamp
[$uid];
3442 * Get the trackback URL for this page
3443 * @return \type{\string} Trackback URL
3445 public function trackbackURL() {
3446 global $wgScriptPath, $wgServer, $wgScriptExtension;
3448 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3449 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3453 * Get the trackback RDF for this page
3454 * @return \type{\string} Trackback RDF
3456 public function trackbackRDF() {
3457 $url = htmlspecialchars($this->getFullURL());
3458 $title = htmlspecialchars($this->getText());
3459 $tburl = $this->trackbackURL();
3461 // Autodiscovery RDF is placed in comments so HTML validator
3462 // won't barf. This is a rather icky workaround, but seems
3463 // frequently used by this kind of RDF thingy.
3465 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3467 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3468 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3469 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3472 dc:identifier=\"$url\"
3474 trackback:ping=\"$tburl\" />
3480 * Generate strings used for xml 'id' names in monobook tabs
3481 * @return \type{\string} XML 'id' name
3483 public function getNamespaceKey() {
3485 switch ($this->getNamespace()) {
3488 return 'nstab-main';
3491 return 'nstab-user';
3493 return 'nstab-media';
3495 return 'nstab-special';
3497 case NS_PROJECT_TALK
:
3498 return 'nstab-project';
3501 return 'nstab-image';
3503 case NS_MEDIAWIKI_TALK
:
3504 return 'nstab-mediawiki';
3506 case NS_TEMPLATE_TALK
:
3507 return 'nstab-template';
3510 return 'nstab-help';
3512 case NS_CATEGORY_TALK
:
3513 return 'nstab-category';
3515 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
3520 * Returns true if this title resolves to the named special page
3521 * @param $name \type{\string} The special page name
3523 public function isSpecial( $name ) {
3524 if ( $this->getNamespace() == NS_SPECIAL
) {
3525 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3526 if ( $name == $thisName ) {
3534 * If the Title refers to a special page alias which is not the local default,
3535 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3537 public function fixSpecialName() {
3538 if ( $this->getNamespace() == NS_SPECIAL
) {
3539 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3540 if ( $canonicalName ) {
3541 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3542 if ( $localName != $this->mDbkeyform
) {
3543 return Title
::makeTitle( NS_SPECIAL
, $localName );
3551 * Is this Title in a namespace which contains content?
3552 * In other words, is this a content page, for the purposes of calculating
3555 * @return \type{\bool} TRUE or FALSE
3557 public function isContentPage() {
3558 return MWNamespace
::isContent( $this->getNamespace() );
3562 * Get all extant redirects to this Title
3564 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3565 * NULL to consider all namespaces
3566 * @return \type{\arrayof{Title}} Redirects to this title
3568 public function getRedirectsHere( $ns = null ) {
3571 $dbr = wfGetDB( DB_SLAVE
);
3573 'rd_namespace' => $this->getNamespace(),
3574 'rd_title' => $this->getDBkey(),
3577 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3579 $res = $dbr->select(
3580 array( 'redirect', 'page' ),
3581 array( 'page_namespace', 'page_title' ),
3587 foreach( $res as $row ) {
3588 $redirs[] = self
::newFromRow( $row );
3594 * Check if this Title is a valid redirect target
3596 * @return \type{\bool} TRUE or FALSE
3598 public function isValidRedirectTarget() {
3599 global $wgInvalidRedirectTargets;
3601 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
3602 if( $this->isSpecial( 'Userlogout' ) ) {
3606 foreach( $wgInvalidRedirectTargets as $target ) {
3607 if( $this->isSpecial( $target ) ) {
3616 * Get a backlink cache object
3618 function getBacklinkCache() {
3619 if ( is_null( $this->mBacklinkCache
) ) {
3620 $this->mBacklinkCache
= new BacklinkCache( $this );
3622 return $this->mBacklinkCache
;