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 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
157 * Example of wrong and broken code:
158 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
160 * Example of right code:
161 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
163 * Create a new Title from URL-encoded text. Ensures that
164 * the given title's length does not exceed the maximum.
165 * @param $url \type{\string} the title, as might be taken from a URL
166 * @return \type{Title} the new object, or NULL on an error
168 public static function newFromURL( $url ) {
169 global $wgLegalTitleChars;
172 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
173 # but some URLs used it as a space replacement and they still come
174 # from some external search tools.
175 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
176 $url = str_replace( '+', ' ', $url );
179 $t->mDbkeyform
= str_replace( ' ', '_', $url );
180 if( $t->secureAndSplit() ) {
188 * Create a new Title from an article ID
190 * @param $id \type{\int} the page_id corresponding to the Title to create
191 * @param $flags \type{\int} use GAID_FOR_UPDATE to use master
192 * @return \type{Title} the new object, or NULL on an error
194 public static function newFromID( $id, $flags = 0 ) {
195 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
196 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
197 if( $row !== false ) {
198 $title = Title
::newFromRow( $row );
206 * Make an array of titles from an array of IDs
207 * @param $ids \type{\arrayof{\int}} Array of IDs
208 * @return \type{\arrayof{Title}} Array of Titles
210 public static function newFromIDs( $ids ) {
211 if ( !count( $ids ) ) {
214 $dbr = wfGetDB( DB_SLAVE
);
215 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
216 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
219 foreach( $res as $row ) {
220 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
226 * Make a Title object from a DB row
227 * @param $row \type{Row} (needs at least page_title,page_namespace)
228 * @return \type{Title} corresponding Title
230 public static function newFromRow( $row ) {
231 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
233 $t->mArticleID
= isset($row->page_id
) ?
intval($row->page_id
) : -1;
234 $t->mLength
= isset($row->page_len
) ?
intval($row->page_len
) : -1;
235 $t->mRedirect
= isset($row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: NULL;
236 $t->mLatestID
= isset($row->page_latest
) ?
$row->page_latest
: false;
242 * Create a new Title from a namespace index and a DB key.
243 * It's assumed that $ns and $title are *valid*, for instance when
244 * they came directly from the database or a special page name.
245 * For convenience, spaces are converted to underscores so that
246 * eg user_text fields can be used directly.
248 * @param $ns \type{\int} the namespace of the article
249 * @param $title \type{\string} the unprefixed database key form
250 * @param $fragment \type{\string} The link fragment (after the "#")
251 * @return \type{Title} the new object
253 public static function &makeTitle( $ns, $title, $fragment = '' ) {
256 $t->mFragment
= $fragment;
257 $t->mNamespace
= $ns = intval( $ns );
258 $t->mDbkeyform
= str_replace( ' ', '_', $title );
259 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
260 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
261 $t->mTextform
= str_replace( '_', ' ', $title );
266 * Create a new Title from a namespace index and a DB key.
267 * The parameters will be checked for validity, which is a bit slower
268 * than makeTitle() but safer for user-provided data.
270 * @param $ns \type{\int} the namespace of the article
271 * @param $title \type{\string} the database key form
272 * @param $fragment \type{\string} The link fragment (after the "#")
273 * @return \type{Title} the new object, or NULL on an error
275 public static function makeTitleSafe( $ns, $title, $fragment = '' ) {
277 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment );
278 if( $t->secureAndSplit() ) {
286 * Create a new Title for the Main Page
287 * @return \type{Title} the new object
289 public static function newMainPage() {
290 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
291 // Don't give fatal errors if the message is broken
293 $title = Title
::newFromText( 'Main Page' );
299 * Extract a redirect destination from a string and return the
300 * Title, or null if the text doesn't contain a valid redirect
301 * This will only return the very next target, useful for
302 * the redirect table and other checks that don't need full recursion
304 * @param $text \type{\string} Text with possible redirect
305 * @return \type{Title} The corresponding Title
307 public static function newFromRedirect( $text ) {
308 return self
::newFromRedirectInternal( $text );
312 * Extract a redirect destination from a string and return the
313 * Title, or null if the text doesn't contain a valid redirect
314 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
315 * in order to provide (hopefully) the Title of the final destination instead of another redirect
317 * @param $text \type{\string} Text with possible redirect
318 * @return \type{Title} The corresponding Title
320 public static function newFromRedirectRecurse( $text ) {
321 $titles = self
::newFromRedirectArray( $text );
322 return $titles ?
array_pop( $titles ) : null;
326 * Extract a redirect destination from a string and return an
327 * array of Titles, or null if the text doesn't contain a valid redirect
328 * The last element in the array is the final destination after all redirects
329 * have been resolved (up to $wgMaxRedirects times)
331 * @param $text \type{\string} Text with possible redirect
332 * @return \type{\array} Array of Titles, with the destination last
334 public static function newFromRedirectArray( $text ) {
335 global $wgMaxRedirects;
336 // are redirects disabled?
337 if( $wgMaxRedirects < 1 )
339 $title = self
::newFromRedirectInternal( $text );
340 if( is_null( $title ) )
342 // recursive check to follow double redirects
343 $recurse = $wgMaxRedirects;
344 $titles = array( $title );
345 while( --$recurse > 0 ) {
346 if( $title->isRedirect() ) {
347 $article = new Article( $title, 0 );
348 $newtitle = $article->getRedirectTarget();
352 // Redirects to some special pages are not permitted
353 if( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
354 // the new title passes the checks, so make that our current title so that further recursion can be checked
356 $titles[] = $newtitle;
365 * Really extract the redirect destination
366 * Do not call this function directly, use one of the newFromRedirect* functions above
368 * @param $text \type{\string} Text with possible redirect
369 * @return \type{Title} The corresponding Title
371 protected static function newFromRedirectInternal( $text ) {
372 $redir = MagicWord
::get( 'redirect' );
374 if( $redir->matchStartAndRemove( $text ) ) {
375 // Extract the first link and see if it's usable
376 // Ensure that it really does come directly after #REDIRECT
377 // Some older redirects included a colon, so don't freak about that!
379 if( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
380 // Strip preceding colon used to "escape" categories, etc.
381 // and URL-decode links
382 if( strpos( $m[1], '%' ) !== false ) {
383 // Match behavior of inline link parsing here;
384 // don't interpret + as " " most of the time!
385 // It might be safe to just use rawurldecode instead, though.
386 $m[1] = urldecode( ltrim( $m[1], ':' ) );
388 $title = Title
::newFromText( $m[1] );
389 // If the title is a redirect to bad special pages or is invalid, return null
390 if( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
399 #----------------------------------------------------------------------------
401 #----------------------------------------------------------------------------
404 * Get the prefixed DB key associated with an ID
405 * @param $id \type{\int} the page_id of the article
406 * @return \type{Title} an object representing the article, or NULL
407 * if no such article was found
409 public static function nameOf( $id ) {
410 $dbr = wfGetDB( DB_SLAVE
);
412 $s = $dbr->selectRow( 'page',
413 array( 'page_namespace','page_title' ),
414 array( 'page_id' => $id ),
416 if ( $s === false ) { return NULL; }
418 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
423 * Get a regex character class describing the legal characters in a link
424 * @return \type{\string} the list of characters, not delimited
426 public static function legalChars() {
427 global $wgLegalTitleChars;
428 return $wgLegalTitleChars;
432 * Get a string representation of a title suitable for
433 * including in a search index
435 * @param $ns \type{\int} a namespace index
436 * @param $title \type{\string} text-form main part
437 * @return \type{\string} a stripped-down title string ready for the
440 public static function indexTitle( $ns, $title ) {
443 $lc = SearchEngine
::legalSearchChars() . '&#;';
444 $t = $wgContLang->stripForSearch( $title );
445 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
446 $t = $wgContLang->lc( $t );
449 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
450 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
452 $t = preg_replace( "/\\s+/", ' ', $t );
454 if ( $ns == NS_FILE
) {
455 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
461 * Make a prefixed DB key from a DB key and a namespace index
462 * @param $ns \type{\int} numerical representation of the namespace
463 * @param $title \type{\string} the DB key form the title
464 * @param $fragment \type{\string} The link fragment (after the "#")
465 * @return \type{\string} the prefixed form of the title
467 public static function makeName( $ns, $title, $fragment = '' ) {
470 $namespace = $wgContLang->getNsText( $ns );
471 $name = $namespace == '' ?
$title : "$namespace:$title";
472 if ( strval( $fragment ) != '' ) {
473 $name .= '#' . $fragment;
479 * Determine whether the object refers to a page within
482 * @return \type{\bool} TRUE if this is an in-project interwiki link
483 * or a wikilink, FALSE otherwise
485 public function isLocal() {
486 if ( $this->mInterwiki
!= '' ) {
487 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
494 * Determine whether the object refers to a page within
495 * this project and is transcludable.
497 * @return \type{\bool} TRUE if this is transcludable
499 public function isTrans() {
500 if ($this->mInterwiki
== '')
503 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
507 * Escape a text fragment, say from a link, for a URL
509 static function escapeFragmentForURL( $fragment ) {
510 global $wgEnforceHtmlIds;
511 # Note that we don't urlencode the fragment. urlencoded Unicode
512 # fragments appear not to work in IE (at least up to 7) or in at least
513 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
514 # to care if they aren't encoded.
515 return Sanitizer
::escapeId( $fragment,
516 $wgEnforceHtmlIds ?
'noninitial' : 'xml' );
519 #----------------------------------------------------------------------------
521 #----------------------------------------------------------------------------
523 /** Simple accessors */
525 * Get the text form (spaces not underscores) of the main part
526 * @return \type{\string} Main part of the title
528 public function getText() { return $this->mTextform
; }
530 * Get the URL-encoded form of the main part
531 * @return \type{\string} Main part of the title, URL-encoded
533 public function getPartialURL() { return $this->mUrlform
; }
535 * Get the main part with underscores
536 * @return \type{\string} Main part of the title, with underscores
538 public function getDBkey() { return $this->mDbkeyform
; }
540 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
541 * @return \type{\int} Namespace index
543 public function getNamespace() { return $this->mNamespace
; }
545 * Get the namespace text
546 * @return \type{\string} Namespace text
548 public function getNsText() {
549 global $wgContLang, $wgCanonicalNamespaceNames;
551 if ( '' != $this->mInterwiki
) {
552 // This probably shouldn't even happen. ohh man, oh yuck.
553 // But for interwiki transclusion it sometimes does.
554 // Shit. Shit shit shit.
556 // Use the canonical namespaces if possible to try to
557 // resolve a foreign namespace.
558 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace
] ) ) {
559 return $wgCanonicalNamespaceNames[$this->mNamespace
];
562 return $wgContLang->getNsText( $this->mNamespace
);
565 * Get the DB key with the initial letter case as specified by the user
566 * @return \type{\string} DB key
568 function getUserCaseDBKey() {
569 return $this->mUserCaseDBKey
;
572 * Get the namespace text of the subject (rather than talk) page
573 * @return \type{\string} Namespace text
575 public function getSubjectNsText() {
577 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
580 * Get the namespace text of the talk page
581 * @return \type{\string} Namespace text
583 public function getTalkNsText() {
585 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
588 * Could this title have a corresponding talk page?
589 * @return \type{\bool} TRUE or FALSE
591 public function canTalk() {
592 return( MWNamespace
::canTalk( $this->mNamespace
) );
595 * Get the interwiki prefix (or null string)
596 * @return \type{\string} Interwiki prefix
598 public function getInterwiki() { return $this->mInterwiki
; }
600 * Get the Title fragment (i.e.\ the bit after the #) in text form
601 * @return \type{\string} Title fragment
603 public function getFragment() { return $this->mFragment
; }
605 * Get the fragment in URL form, including the "#" character if there is one
606 * @return \type{\string} Fragment in URL form
608 public function getFragmentForURL() {
609 if ( $this->mFragment
== '' ) {
612 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
616 * Get the default namespace index, for when there is no namespace
617 * @return \type{\int} Default namespace index
619 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
622 * Get title for search index
623 * @return \type{\string} a stripped-down title string ready for the
626 public function getIndexTitle() {
627 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
631 * Get the prefixed database key form
632 * @return \type{\string} the prefixed title, with underscores and
633 * any interwiki and namespace prefixes
635 public function getPrefixedDBkey() {
636 $s = $this->prefix( $this->mDbkeyform
);
637 $s = str_replace( ' ', '_', $s );
642 * Get the prefixed title with spaces.
643 * This is the form usually used for display
644 * @return \type{\string} the prefixed title, with spaces
646 public function getPrefixedText() {
647 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
648 $s = $this->prefix( $this->mTextform
);
649 $s = str_replace( '_', ' ', $s );
650 $this->mPrefixedText
= $s;
652 return $this->mPrefixedText
;
656 * Get the prefixed title with spaces, plus any fragment
657 * (part beginning with '#')
658 * @return \type{\string} the prefixed title, with spaces and
659 * the fragment, including '#'
661 public function getFullText() {
662 $text = $this->getPrefixedText();
663 if( '' != $this->mFragment
) {
664 $text .= '#' . $this->mFragment
;
670 * Get the base name, i.e. the leftmost parts before the /
671 * @return \type{\string} Base name
673 public function getBaseText() {
674 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
675 return $this->getText();
678 $parts = explode( '/', $this->getText() );
679 # Don't discard the real title if there's no subpage involved
680 if( count( $parts ) > 1 )
681 unset( $parts[ count( $parts ) - 1 ] );
682 return implode( '/', $parts );
686 * Get the lowest-level subpage name, i.e. the rightmost part after /
687 * @return \type{\string} Subpage name
689 public function getSubpageText() {
690 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
691 return( $this->mTextform
);
693 $parts = explode( '/', $this->mTextform
);
694 return( $parts[ count( $parts ) - 1 ] );
698 * Get a URL-encoded form of the subpage text
699 * @return \type{\string} URL-encoded subpage name
701 public function getSubpageUrlForm() {
702 $text = $this->getSubpageText();
703 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
708 * Get a URL-encoded title (not an actual URL) including interwiki
709 * @return \type{\string} the URL-encoded form
711 public function getPrefixedURL() {
712 $s = $this->prefix( $this->mDbkeyform
);
713 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
718 * Get a real URL referring to this title, with interwiki link and
721 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
722 * links. Can be specified as an associative array as well, e.g.,
723 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
724 * @param $variant \type{\string} language variant of url (for sr, zh..)
725 * @return \type{\string} the URL
727 public function getFullURL( $query = '', $variant = false ) {
728 global $wgContLang, $wgServer, $wgRequest;
730 if( is_array( $query ) ) {
731 $query = wfArrayToCGI( $query );
734 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
736 $url = $this->getLocalUrl( $query, $variant );
738 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
739 // Correct fix would be to move the prepending elsewhere.
740 if ($wgRequest->getVal('action') != 'render') {
741 $url = $wgServer . $url;
744 $baseUrl = $interwiki->getURL( );
746 $namespace = wfUrlencode( $this->getNsText() );
747 if ( '' != $namespace ) {
748 # Can this actually happen? Interwikis shouldn't be parsed.
749 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
752 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
753 $url = wfAppendQuery( $url, $query );
756 # Finally, add the fragment.
757 $url .= $this->getFragmentForURL();
759 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
764 * Get a URL with no fragment or server name. If this page is generated
765 * with action=render, $wgServer is prepended.
766 * @param mixed $query an optional query string; if not specified,
767 * $wgArticlePath will be used. Can be specified as an associative array
768 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
770 * @param $variant \type{\string} language variant of url (for sr, zh..)
771 * @return \type{\string} the URL
773 public function getLocalURL( $query = '', $variant = false ) {
774 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
775 global $wgVariantArticlePath, $wgContLang, $wgUser;
777 if( is_array( $query ) ) {
778 $query = wfArrayToCGI( $query );
781 // internal links should point to same variant as current page (only anonymous users)
782 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
783 $pref = $wgContLang->getPreferredVariant(false);
784 if($pref != $wgContLang->getCode())
788 if ( $this->isExternal() ) {
789 $url = $this->getFullURL();
791 // This is currently only used for edit section links in the
792 // context of interwiki transclusion. In theory we should
793 // append the query to the end of any existing query string,
794 // but interwiki transclusion is already broken in that case.
798 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
799 if ( $query == '' ) {
800 if( $variant != false && $wgContLang->hasVariants() ) {
801 if( $wgVariantArticlePath == false ) {
802 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
804 $variantArticlePath = $wgVariantArticlePath;
806 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
807 $url = str_replace( '$1', $dbkey, $url );
809 $url = str_replace( '$1', $dbkey, $wgArticlePath );
812 global $wgActionPaths;
815 if( !empty( $wgActionPaths ) &&
816 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
818 $action = urldecode( $matches[2] );
819 if( isset( $wgActionPaths[$action] ) ) {
820 $query = $matches[1];
821 if( isset( $matches[4] ) ) $query .= $matches[4];
822 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
824 $url = wfAppendQuery( $url, $query );
828 if ( $url === false ) {
829 if ( $query == '-' ) {
832 $url = "{$wgScript}?title={$dbkey}&{$query}";
836 // FIXME: this causes breakage in various places when we
837 // actually expected a local URL and end up with dupe prefixes.
838 if ($wgRequest->getVal('action') == 'render') {
839 $url = $wgServer . $url;
842 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
847 * Get a URL that's the simplest URL that will be valid to link, locally,
848 * to the current Title. It includes the fragment, but does not include
849 * the server unless action=render is used (or the link is external). If
850 * there's a fragment but the prefixed text is empty, we just return a link
853 * The result obviously should not be URL-escaped, but does need to be
854 * HTML-escaped if it's being output in HTML.
856 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
857 * query string. Keys and values will be escaped.
858 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
859 * for external links. Default is "false" (same variant as current page,
860 * for anonymous users).
861 * @return \type{\string} the URL
863 public function getLinkUrl( $query = array(), $variant = false ) {
864 wfProfileIn( __METHOD__
);
865 if( $this->isExternal() ) {
866 $ret = $this->getFullURL( $query );
867 } elseif( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
868 $ret = $this->getFragmentForURL();
870 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
872 wfProfileOut( __METHOD__
);
877 * Get an HTML-escaped version of the URL form, suitable for
878 * using in a link, without a server name or fragment
879 * @param $query \type{\string} an optional query string
880 * @return \type{\string} the URL
882 public function escapeLocalURL( $query = '' ) {
883 return htmlspecialchars( $this->getLocalURL( $query ) );
887 * Get an HTML-escaped version of the URL form, suitable for
888 * using in a link, including the server name and fragment
890 * @param $query \type{\string} an optional query string
891 * @return \type{\string} the URL
893 public function escapeFullURL( $query = '' ) {
894 return htmlspecialchars( $this->getFullURL( $query ) );
898 * Get the URL form for an internal link.
899 * - Used in various Squid-related code, in case we have a different
900 * internal hostname for the server from the exposed one.
902 * @param $query \type{\string} an optional query string
903 * @param $variant \type{\string} language variant of url (for sr, zh..)
904 * @return \type{\string} the URL
906 public function getInternalURL( $query = '', $variant = false ) {
907 global $wgInternalServer;
908 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
909 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
914 * Get the edit URL for this Title
915 * @return \type{\string} the URL, or a null string if this is an
918 public function getEditURL() {
919 if ( '' != $this->mInterwiki
) { return ''; }
920 $s = $this->getLocalURL( 'action=edit' );
926 * Get the HTML-escaped displayable text form.
927 * Used for the title field in <a> tags.
928 * @return \type{\string} the text, including any prefixes
930 public function getEscapedText() {
931 return htmlspecialchars( $this->getPrefixedText() );
935 * Is this Title interwiki?
936 * @return \type{\bool}
938 public function isExternal() { return ( '' != $this->mInterwiki
); }
941 * Is this page "semi-protected" - the *only* protection is autoconfirm?
943 * @param @action \type{\string} Action to check (default: edit)
944 * @return \type{\bool}
946 public function isSemiProtected( $action = 'edit' ) {
947 if( $this->exists() ) {
948 $restrictions = $this->getRestrictions( $action );
949 if( count( $restrictions ) > 0 ) {
950 foreach( $restrictions as $restriction ) {
951 if( strtolower( $restriction ) != 'autoconfirmed' )
960 # If it doesn't exist, it can't be protected
966 * Does the title correspond to a protected article?
967 * @param $what \type{\string} the action the page is protected from,
968 * by default checks move and edit
969 * @return \type{\bool}
971 public function isProtected( $action = '' ) {
972 global $wgRestrictionLevels, $wgRestrictionTypes;
974 # Special pages have inherent protection
975 if( $this->getNamespace() == NS_SPECIAL
)
978 # Check regular protection levels
979 foreach( $wgRestrictionTypes as $type ){
980 if( $action == $type ||
$action == '' ) {
981 $r = $this->getRestrictions( $type );
982 foreach( $wgRestrictionLevels as $level ) {
983 if( in_array( $level, $r ) && $level != '' ) {
994 * Is $wgUser watching this page?
995 * @return \type{\bool}
997 public function userIsWatching() {
1000 if ( is_null( $this->mWatched
) ) {
1001 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn()) {
1002 $this->mWatched
= false;
1004 $this->mWatched
= $wgUser->isWatched( $this );
1007 return $this->mWatched
;
1011 * Can $wgUser perform $action on this page?
1012 * This skips potentially expensive cascading permission checks.
1014 * Suitable for use for nonessential UI controls in common cases, but
1015 * _not_ for functional access control.
1017 * May provide false positives, but should never provide a false negative.
1019 * @param $action \type{\string} action that permission needs to be checked for
1020 * @return \type{\bool}
1022 public function quickUserCan( $action ) {
1023 return $this->userCan( $action, false );
1027 * Determines if $wgUser is unable to edit this page because it has been protected
1028 * by $wgNamespaceProtection.
1030 * @return \type{\bool}
1032 public function isNamespaceProtected() {
1033 global $wgNamespaceProtection, $wgUser;
1034 if( isset( $wgNamespaceProtection[ $this->mNamespace
] ) ) {
1035 foreach( (array)$wgNamespaceProtection[ $this->mNamespace
] as $right ) {
1036 if( $right != '' && !$wgUser->isAllowed( $right ) )
1044 * Can $wgUser perform $action on this page?
1045 * @param $action \type{\string} action that permission needs to be checked for
1046 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1047 * @return \type{\bool}
1049 public function userCan( $action, $doExpensiveQueries = true ) {
1051 return ($this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array());
1055 * Can $user perform $action on this page?
1057 * FIXME: This *does not* check throttles (User::pingLimiter()).
1059 * @param $action \type{\string}action that permission needs to be checked for
1060 * @param $user \type{User} user to check
1061 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1062 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1063 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1065 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1066 if( !StubObject
::isRealObject( $user ) ) {
1067 //Since StubObject is always used on globals, we can unstub $wgUser here and set $user = $wgUser
1069 $wgUser->_unstub( '', 5 );
1072 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1076 global $wgEmailConfirmToEdit;
1078 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1079 $errors[] = array( 'confirmedittext' );
1082 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1083 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1084 $block = $user->mBlock
;
1086 // This is from OutputPage::blockedPage
1087 // Copied at r23888 by werdna
1089 $id = $user->blockedBy();
1090 $reason = $user->blockedFor();
1091 if( $reason == '' ) {
1092 $reason = wfMsg( 'blockednoreason' );
1096 if ( is_numeric( $id ) ) {
1097 $name = User
::whoIs( $id );
1102 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1103 $blockid = $block->mId
;
1104 $blockExpiry = $user->mBlock
->mExpiry
;
1105 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1107 if ( $blockExpiry == 'infinity' ) {
1108 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1109 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1111 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1112 if ( strpos( $option, ':' ) == false )
1115 list ($show, $value) = explode( ":", $option );
1117 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1118 $blockExpiry = $show;
1123 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1126 $intended = $user->mBlock
->mAddress
;
1128 $errors[] = array( ($block->mAuto ?
'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name,
1129 $blockid, $blockExpiry, $intended, $blockTimestamp );
1132 // Remove the errors being ignored.
1134 foreach( $errors as $index => $error ) {
1135 $error_key = is_array($error) ?
$error[0] : $error;
1137 if (in_array( $error_key, $ignoreErrors )) {
1138 unset($errors[$index]);
1146 * Can $user perform $action on this page? This is an internal function,
1147 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1148 * checks on wfReadOnly() and blocks)
1150 * @param $action \type{\string} action that permission needs to be checked for
1151 * @param $user \type{User} user to check
1152 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1153 * @param $short \type{\bool} Set this to true to stop after the first permission error.
1154 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1156 private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries=true, $short=false ) {
1157 wfProfileIn( __METHOD__
);
1161 // First stop is permissions checks, which fail most often, and which are easiest to test.
1162 if ( $action == 'move' ) {
1163 if( !$user->isAllowed( 'move-rootuserpages' )
1164 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1166 // Show user page-specific message only if the user can move other pages
1167 $errors[] = array( 'cant-move-user-page' );
1170 // Check if user is allowed to move files if it's a file
1171 if( $this->getNamespace() == NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1172 $errors[] = array( 'movenotallowedfile' );
1175 if( !$user->isAllowed( 'move' ) ) {
1176 // User can't move anything
1177 global $wgGroupPermissions;
1178 $userCanMove = false;
1179 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1180 $userCanMove = $wgGroupPermissions['user']['move'];
1182 $autoconfirmedCanMove = false;
1183 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1184 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1186 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1187 // custom message if logged-in users without any special rights can move
1188 $errors[] = array ( 'movenologintext' );
1190 $errors[] = array ('movenotallowed');
1193 } elseif ( $action == 'create' ) {
1194 if( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1195 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) )
1197 $errors[] = $user->isAnon() ?
array ('nocreatetext') : array ('nocreate-loggedin');
1199 } elseif( $action == 'move-target' ) {
1200 if( !$user->isAllowed( 'move' ) ) {
1201 // User can't move anything
1202 $errors[] = array ('movenotallowed');
1203 } elseif( !$user->isAllowed( 'move-rootuserpages' )
1204 && $this->getNamespace() == NS_USER
&& !$this->isSubpage() )
1206 // Show user page-specific message only if the user can move other pages
1207 $errors[] = array( 'cant-move-to-user-page' );
1209 } elseif( !$user->isAllowed( $action ) ) {
1211 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1212 User
::getGroupsWithPermission( $action ) );
1214 $return = array( 'badaccess-groups',
1215 array( implode( ', ', $groups ), count( $groups ) ) );
1217 $return = array( "badaccess-group0" );
1219 $errors[] = $return;
1222 # Short-circuit point
1223 if( $short && count($errors) > 0 ) {
1224 wfProfileOut( __METHOD__
);
1228 // Use getUserPermissionsErrors instead
1229 if( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1230 wfProfileOut( __METHOD__
);
1231 return $result ?
array() : array( array( 'badaccess-group0' ) );
1233 // Check getUserPermissionsErrors hook
1234 if( !wfRunHooks( 'getUserPermissionsErrors', array(&$this,&$user,$action,&$result) ) ) {
1235 if( is_array($result) && count($result) && !is_array($result[0]) )
1236 $errors[] = $result; # A single array representing an error
1237 else if( is_array($result) && is_array($result[0]) )
1238 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1239 else if( $result !== '' && is_string($result) )
1240 $errors[] = array($result); # A string representing a message-id
1241 else if( $result === false )
1242 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1244 # Short-circuit point
1245 if( $short && count($errors) > 0 ) {
1246 wfProfileOut( __METHOD__
);
1249 // Check getUserPermissionsErrorsExpensive hook
1250 if( $doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array(&$this,&$user,$action,&$result) ) ) {
1251 if( is_array($result) && count($result) && !is_array($result[0]) )
1252 $errors[] = $result; # A single array representing an error
1253 else if( is_array($result) && is_array($result[0]) )
1254 $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
1255 else if( $result !== '' && is_string($result) )
1256 $errors[] = array($result); # A string representing a message-id
1257 else if( $result === false )
1258 $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
1260 # Short-circuit point
1261 if( $short && count($errors) > 0 ) {
1262 wfProfileOut( __METHOD__
);
1266 # Only 'createaccount' and 'execute' can be performed on
1267 # special pages, which don't actually exist in the DB.
1268 $specialOKActions = array( 'createaccount', 'execute' );
1269 if( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions) ) {
1270 $errors[] = array('ns-specialprotected');
1273 # Check $wgNamespaceProtection for restricted namespaces
1274 if( $this->isNamespaceProtected() ) {
1275 $ns = $this->getNamespace() == NS_MAIN ?
1276 wfMsg( 'nstab-main' ) : $this->getNsText();
1277 $errors[] = NS_MEDIAWIKI
== $this->mNamespace ?
1278 array('protectedinterface') : array( 'namespaceprotected', $ns );
1281 # Protect css/js subpages of user pages
1282 # XXX: this might be better using restrictions
1283 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1284 if( $this->isCssJsSubpage() && !$user->isAllowed('editusercssjs' ) && $action != 'patrol'
1285 && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform
) )
1287 $errors[] = array('customcssjsprotected');
1290 # Check against page_restrictions table requirements on this
1291 # page. The user must possess all required rights for this action.
1292 foreach( $this->getRestrictions($action) as $right ) {
1293 // Backwards compatibility, rewrite sysop -> protect
1294 if( $right == 'sysop' ) {
1297 if( '' != $right && !$user->isAllowed( $right ) ) {
1298 // Users with 'editprotected' permission can edit protected pages
1299 if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
1300 // Users with 'editprotected' permission cannot edit protected pages
1301 // with cascading option turned on.
1302 if( $this->mCascadeRestriction
) {
1303 $errors[] = array( 'protectedpagetext', $right );
1306 $errors[] = array( 'protectedpagetext', $right );
1310 # Short-circuit point
1311 if( $short && count($errors) > 0 ) {
1312 wfProfileOut( __METHOD__
);
1316 if( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1317 # We /could/ use the protection level on the source page, but it's fairly ugly
1318 # as we have to establish a precedence hierarchy for pages included by multiple
1319 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1320 # as they could remove the protection anyway.
1321 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1322 # Cascading protection depends on more than this page...
1323 # Several cascading protected pages may include this page...
1324 # Check each cascading level
1325 # This is only for protection restrictions, not for all actions
1326 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1327 foreach( $restrictions[$action] as $right ) {
1328 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1329 if( '' != $right && !$user->isAllowed( $right ) ) {
1331 foreach( $cascadingSources as $page )
1332 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1333 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1338 # Short-circuit point
1339 if( $short && count($errors) > 0 ) {
1340 wfProfileOut( __METHOD__
);
1344 if( $action == 'protect' ) {
1345 if( $this->getUserPermissionsErrors('edit', $user) != array() ) {
1346 $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
1350 if( $action == 'create' ) {
1351 $title_protection = $this->getTitleProtection();
1352 if( is_array($title_protection) ) {
1353 extract($title_protection); // is this extract() really needed?
1355 if( $pt_create_perm == 'sysop' ) {
1356 $pt_create_perm = 'protect'; // B/C
1358 if( $pt_create_perm == '' ||
!$user->isAllowed($pt_create_perm) ) {
1359 $errors[] = array( 'titleprotected', User
::whoIs($pt_user), $pt_reason );
1362 } elseif( $action == 'move' ) {
1363 // Check for immobile pages
1364 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1365 // Specific message for this case
1366 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1367 } elseif( !$this->isMovable() ) {
1368 // Less specific message for rarer cases
1369 $errors[] = array( 'immobile-page' );
1371 } elseif( $action == 'move-target' ) {
1372 if( !MWNamespace
::isMovable( $this->getNamespace() ) ) {
1373 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1374 } elseif( !$this->isMovable() ) {
1375 $errors[] = array( 'immobile-target-page' );
1379 wfProfileOut( __METHOD__
);
1384 * Is this title subject to title protection?
1385 * @return \type{\mixed} An associative array representing any existent title
1386 * protection, or false if there's none.
1388 private function getTitleProtection() {
1389 // Can't protect pages in special namespaces
1390 if ( $this->getNamespace() < 0 ) {
1394 $dbr = wfGetDB( DB_SLAVE
);
1395 $res = $dbr->select( 'protected_titles', '*',
1396 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1399 if ($row = $dbr->fetchRow( $res )) {
1407 * Update the title protection status
1408 * @param $create_perm \type{\string} Permission required for creation
1409 * @param $reason \type{\string} Reason for protection
1410 * @param $expiry \type{\string} Expiry timestamp
1412 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1413 global $wgUser,$wgContLang;
1415 if ($create_perm == implode(',',$this->getRestrictions('create'))
1416 && $expiry == $this->mRestrictionsExpiry
['create']) {
1421 list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
1423 $dbw = wfGetDB( DB_MASTER
);
1425 $encodedExpiry = Block
::encodeExpiry($expiry, $dbw );
1427 $expiry_description = '';
1428 if ( $encodedExpiry != 'infinity' ) {
1429 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) , $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ).')';
1432 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ).')';
1435 # Update protection table
1436 if ($create_perm != '' ) {
1437 $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
1438 array( 'pt_namespace' => $namespace, 'pt_title' => $title
1439 , 'pt_create_perm' => $create_perm
1440 , 'pt_timestamp' => Block
::encodeExpiry(wfTimestampNow(), $dbw)
1441 , 'pt_expiry' => $encodedExpiry
1442 , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__
);
1444 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1445 'pt_title' => $title ), __METHOD__
);
1447 # Update the protection log
1448 $log = new LogPage( 'protect' );
1450 if( $create_perm ) {
1451 $params = array("[create=$create_perm] $expiry_description",'');
1452 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1454 $log->addEntry( 'unprotect', $this, $reason );
1461 * Remove any title protection due to page existing
1463 public function deleteTitleProtection() {
1464 $dbw = wfGetDB( DB_MASTER
);
1466 $dbw->delete( 'protected_titles',
1467 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1472 * Would anybody with sufficient privileges be able to move this page?
1473 * Some pages just aren't movable.
1475 * @return \type{\bool} TRUE or FALSE
1477 public function isMovable() {
1478 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1482 * Can $wgUser read this page?
1483 * @return \type{\bool} TRUE or FALSE
1484 * @todo fold these checks into userCan()
1486 public function userCanRead() {
1487 global $wgUser, $wgGroupPermissions;
1489 static $useShortcut = null;
1491 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1492 if( is_null( $useShortcut ) ) {
1493 global $wgRevokePermissions;
1494 $useShortcut = true;
1495 if( empty( $wgGroupPermissions['*']['read'] ) ) {
1496 # Not a public wiki, so no shortcut
1497 $useShortcut = false;
1498 } elseif( !empty( $wgRevokePermissions ) ) {
1500 * Iterate through each group with permissions being revoked (key not included since we don't care
1501 * what the group name is), then check if the read permission is being revoked. If it is, then
1502 * we don't use the shortcut below since the user might not be able to read, even though anon
1503 * reading is allowed.
1505 foreach( $wgRevokePermissions as $perms ) {
1506 if( !empty( $perms['read'] ) ) {
1507 # We might be removing the read right from the user, so no shortcut
1508 $useShortcut = false;
1516 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1517 if ( $result !== null ) {
1521 # Shortcut for public wikis, allows skipping quite a bit of code
1525 if( $wgUser->isAllowed( 'read' ) ) {
1528 global $wgWhitelistRead;
1531 * Always grant access to the login page.
1532 * Even anons need to be able to log in.
1534 if( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1539 * Bail out if there isn't whitelist
1541 if( !is_array($wgWhitelistRead) ) {
1546 * Check for explicit whitelisting
1548 $name = $this->getPrefixedText();
1549 $dbName = $this->getPrefixedDBKey();
1550 // Check with and without underscores
1551 if( in_array($name,$wgWhitelistRead,true) ||
in_array($dbName,$wgWhitelistRead,true) )
1555 * Old settings might have the title prefixed with
1556 * a colon for main-namespace pages
1558 if( $this->getNamespace() == NS_MAIN
) {
1559 if( in_array( ':' . $name, $wgWhitelistRead ) )
1564 * If it's a special page, ditch the subpage bit
1567 if( $this->getNamespace() == NS_SPECIAL
) {
1568 $name = $this->getDBkey();
1569 list( $name, /* $subpage */) = SpecialPage
::resolveAliasWithSubpage( $name );
1570 if ( $name === false ) {
1571 # Invalid special page, but we show standard login required message
1575 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1576 if( in_array( $pure, $wgWhitelistRead, true ) )
1585 * Is this a talk page of some sort?
1586 * @return \type{\bool} TRUE or FALSE
1588 public function isTalkPage() {
1589 return MWNamespace
::isTalk( $this->getNamespace() );
1593 * Is this a subpage?
1594 * @return \type{\bool} TRUE or FALSE
1596 public function isSubpage() {
1597 return MWNamespace
::hasSubpages( $this->mNamespace
)
1598 ?
strpos( $this->getText(), '/' ) !== false
1603 * Does this have subpages? (Warning, usually requires an extra DB query.)
1604 * @return \type{\bool} TRUE or FALSE
1606 public function hasSubpages() {
1607 if( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1612 # We dynamically add a member variable for the purpose of this method
1613 # alone to cache the result. There's no point in having it hanging
1614 # around uninitialized in every Title object; therefore we only add it
1615 # if needed and don't declare it statically.
1616 if( isset( $this->mHasSubpages
) ) {
1617 return $this->mHasSubpages
;
1620 $subpages = $this->getSubpages( 1 );
1621 if( $subpages instanceof TitleArray
)
1622 return $this->mHasSubpages
= (bool)$subpages->count();
1623 return $this->mHasSubpages
= false;
1627 * Get all subpages of this page.
1628 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1629 * @return mixed TitleArray, or empty array if this page's namespace
1630 * doesn't allow subpages
1632 public function getSubpages( $limit = -1 ) {
1633 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
1636 $dbr = wfGetDB( DB_SLAVE
);
1637 $conds['page_namespace'] = $this->getNamespace();
1638 $conds[] = 'page_title LIKE ' . $dbr->addQuotes(
1639 $dbr->escapeLike( $this->getDBkey() ) . '/%' );
1642 $options['LIMIT'] = $limit;
1643 return $this->mSubpages
= TitleArray
::newFromResult(
1644 $dbr->select( 'page',
1645 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1654 * Could this page contain custom CSS or JavaScript, based
1657 * @return \type{\bool} TRUE or FALSE
1659 public function isCssOrJsPage() {
1660 return $this->mNamespace
== NS_MEDIAWIKI
1661 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1665 * Is this a .css or .js subpage of a user page?
1666 * @return \type{\bool} TRUE or FALSE
1668 public function isCssJsSubpage() {
1669 return ( NS_USER
== $this->mNamespace
and preg_match("/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1672 * Is this a *valid* .css or .js subpage of a user page?
1673 * Check that the corresponding skin exists
1674 * @return \type{\bool} TRUE or FALSE
1676 public function isValidCssJsSubpage() {
1677 if ( $this->isCssJsSubpage() ) {
1678 $skinNames = Skin
::getSkinNames();
1679 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1685 * Trim down a .css or .js subpage title to get the corresponding skin name
1687 public function getSkinFromCssJsSubpage() {
1688 $subpage = explode( '/', $this->mTextform
);
1689 $subpage = $subpage[ count( $subpage ) - 1 ];
1690 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1693 * Is this a .css subpage of a user page?
1694 * @return \type{\bool} TRUE or FALSE
1696 public function isCssSubpage() {
1697 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.css$/", $this->mTextform
) );
1700 * Is this a .js subpage of a user page?
1701 * @return \type{\bool} TRUE or FALSE
1703 public function isJsSubpage() {
1704 return ( NS_USER
== $this->mNamespace
&& preg_match("/\\/.*\\.js$/", $this->mTextform
) );
1707 * Protect css/js subpages of user pages: can $wgUser edit
1710 * @return \type{\bool} TRUE or FALSE
1711 * @todo XXX: this might be better using restrictions
1713 public function userCanEditCssJsSubpage() {
1715 return ( $wgUser->isAllowed('editusercssjs') ||
preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1719 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1721 * @return \type{\bool} If the page is subject to cascading restrictions.
1723 public function isCascadeProtected() {
1724 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1725 return ( $sources > 0 );
1729 * Cascading protection: Get the source of any cascading restrictions on this page.
1731 * @param $get_pages \type{\bool} Whether or not to retrieve the actual pages that the restrictions have come from.
1732 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title objects of the pages from
1733 * which cascading restrictions have come, false for none, or true if such restrictions exist, but $get_pages was not set.
1734 * The restriction array is an array of each type, each of which contains an array of unique groups.
1736 public function getCascadeProtectionSources( $get_pages = true ) {
1737 global $wgRestrictionTypes;
1739 # Define our dimension of restrictions types
1740 $pagerestrictions = array();
1741 foreach( $wgRestrictionTypes as $action )
1742 $pagerestrictions[$action] = array();
1744 if ( isset( $this->mCascadeSources
) && $get_pages ) {
1745 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1746 } else if ( isset( $this->mHasCascadingRestrictions
) && !$get_pages ) {
1747 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1750 wfProfileIn( __METHOD__
);
1752 $dbr = wfGetDB( DB_SLAVE
);
1754 if ( $this->getNamespace() == NS_FILE
) {
1755 $tables = array ('imagelinks', 'page_restrictions');
1756 $where_clauses = array(
1757 'il_to' => $this->getDBkey(),
1759 'pr_cascade' => 1 );
1761 $tables = array ('templatelinks', 'page_restrictions');
1762 $where_clauses = array(
1763 'tl_namespace' => $this->getNamespace(),
1764 'tl_title' => $this->getDBkey(),
1766 'pr_cascade' => 1 );
1770 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1771 $where_clauses[] = 'page_id=pr_page';
1774 $cols = array( 'pr_expiry' );
1777 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
1779 $sources = $get_pages ?
array() : false;
1780 $now = wfTimestampNow();
1781 $purgeExpired = false;
1783 foreach( $res as $row ) {
1784 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1785 if( $expiry > $now ) {
1787 $page_id = $row->pr_page
;
1788 $page_ns = $row->page_namespace
;
1789 $page_title = $row->page_title
;
1790 $sources[$page_id] = Title
::makeTitle($page_ns, $page_title);
1791 # Add groups needed for each restriction type if its not already there
1792 # Make sure this restriction type still exists
1793 if ( isset($pagerestrictions[$row->pr_type
]) && !in_array($row->pr_level
, $pagerestrictions[$row->pr_type
]) ) {
1794 $pagerestrictions[$row->pr_type
][]=$row->pr_level
;
1800 // Trigger lazy purge of expired restrictions from the db
1801 $purgeExpired = true;
1804 if( $purgeExpired ) {
1805 Title
::purgeExpiredRestrictions();
1808 wfProfileOut( __METHOD__
);
1811 $this->mCascadeSources
= $sources;
1812 $this->mCascadingRestrictions
= $pagerestrictions;
1814 $this->mHasCascadingRestrictions
= $sources;
1816 return array( $sources, $pagerestrictions );
1819 function areRestrictionsCascading() {
1820 if (!$this->mRestrictionsLoaded
) {
1821 $this->loadRestrictions();
1824 return $this->mCascadeRestriction
;
1828 * Loads a string into mRestrictions array
1829 * @param $res \type{Resource} restrictions as an SQL result.
1831 private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1832 global $wgRestrictionTypes;
1833 $dbr = wfGetDB( DB_SLAVE
);
1835 foreach( $wgRestrictionTypes as $type ){
1836 $this->mRestrictions
[$type] = array();
1837 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry('');
1840 $this->mCascadeRestriction
= false;
1842 # Backwards-compatibility: also load the restrictions from the page record (old format).
1844 if ( $oldFashionedRestrictions === NULL ) {
1845 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
1846 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
1849 if ($oldFashionedRestrictions != '') {
1851 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1852 $temp = explode( '=', trim( $restrict ) );
1853 if(count($temp) == 1) {
1854 // old old format should be treated as edit/move restriction
1855 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
1856 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
1858 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1862 $this->mOldRestrictions
= true;
1866 if( $dbr->numRows( $res ) ) {
1867 # Current system - load second to make them override.
1868 $now = wfTimestampNow();
1869 $purgeExpired = false;
1871 foreach( $res as $row ) {
1872 # Cycle through all the restrictions.
1874 // Don't take care of restrictions types that aren't in $wgRestrictionTypes
1875 if( !in_array( $row->pr_type
, $wgRestrictionTypes ) )
1878 // This code should be refactored, now that it's being used more generally,
1879 // But I don't really see any harm in leaving it in Block for now -werdna
1880 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
1882 // Only apply the restrictions if they haven't expired!
1883 if ( !$expiry ||
$expiry > $now ) {
1884 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
1885 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
1887 $this->mCascadeRestriction |
= $row->pr_cascade
;
1889 // Trigger a lazy purge of expired restrictions
1890 $purgeExpired = true;
1894 if( $purgeExpired ) {
1895 Title
::purgeExpiredRestrictions();
1899 $this->mRestrictionsLoaded
= true;
1903 * Load restrictions from the page_restrictions table
1905 public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1906 if( !$this->mRestrictionsLoaded
) {
1907 if ($this->exists()) {
1908 $dbr = wfGetDB( DB_SLAVE
);
1910 $res = $dbr->select( 'page_restrictions', '*',
1911 array ( 'pr_page' => $this->getArticleId() ), __METHOD__
);
1913 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1915 $title_protection = $this->getTitleProtection();
1917 if (is_array($title_protection)) {
1918 extract($title_protection);
1920 $now = wfTimestampNow();
1921 $expiry = Block
::decodeExpiry($pt_expiry);
1923 if (!$expiry ||
$expiry > $now) {
1924 // Apply the restrictions
1925 $this->mRestrictionsExpiry
['create'] = $expiry;
1926 $this->mRestrictions
['create'] = explode(',', trim($pt_create_perm) );
1927 } else { // Get rid of the old restrictions
1928 Title
::purgeExpiredRestrictions();
1931 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry('');
1933 $this->mRestrictionsLoaded
= true;
1939 * Purge expired restrictions from the page_restrictions table
1941 static function purgeExpiredRestrictions() {
1942 $dbw = wfGetDB( DB_MASTER
);
1943 $dbw->delete( 'page_restrictions',
1944 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1947 $dbw->delete( 'protected_titles',
1948 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1953 * Accessor/initialisation for mRestrictions
1955 * @param $action \type{\string} action that permission needs to be checked for
1956 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
1958 public function getRestrictions( $action ) {
1959 if( !$this->mRestrictionsLoaded
) {
1960 $this->loadRestrictions();
1962 return isset( $this->mRestrictions
[$action] )
1963 ?
$this->mRestrictions
[$action]
1968 * Get the expiry time for the restriction against a given action
1969 * @return 14-char timestamp, or 'infinity' if the page is protected forever
1970 * or not protected at all, or false if the action is not recognised.
1972 public function getRestrictionExpiry( $action ) {
1973 if( !$this->mRestrictionsLoaded
) {
1974 $this->loadRestrictions();
1976 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
1980 * Is there a version of this page in the deletion archive?
1981 * @return \type{\int} the number of archived revisions
1983 public function isDeleted() {
1984 if( $this->getNamespace() < 0 ) {
1987 $dbr = wfGetDB( DB_SLAVE
);
1988 $n = $dbr->selectField( 'archive', 'COUNT(*)',
1989 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
1992 if( $this->getNamespace() == NS_FILE
) {
1993 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1994 array( 'fa_name' => $this->getDBkey() ),
2003 * Is there a version of this page in the deletion archive?
2006 public function isDeletedQuick() {
2007 if( $this->getNamespace() < 0 ) {
2010 $dbr = wfGetDB( DB_SLAVE
);
2011 $deleted = (bool)$dbr->selectField( 'archive', '1',
2012 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2015 if( !$deleted && $this->getNamespace() == NS_FILE
) {
2016 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2017 array( 'fa_name' => $this->getDBkey() ),
2025 * Get the article ID for this Title from the link cache,
2026 * adding it if necessary
2027 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select
2029 * @return \type{\int} the ID
2031 public function getArticleID( $flags = 0 ) {
2032 if( $this->getNamespace() < 0 ) {
2033 return $this->mArticleID
= 0;
2035 $linkCache = LinkCache
::singleton();
2036 if( $flags & GAID_FOR_UPDATE
) {
2037 $oldUpdate = $linkCache->forUpdate( true );
2038 $linkCache->clearLink( $this );
2039 $this->mArticleID
= $linkCache->addLinkObj( $this );
2040 $linkCache->forUpdate( $oldUpdate );
2042 if( -1 == $this->mArticleID
) {
2043 $this->mArticleID
= $linkCache->addLinkObj( $this );
2046 return $this->mArticleID
;
2050 * Is this an article that is a redirect page?
2051 * Uses link cache, adding it if necessary
2052 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2053 * @return \type{\bool}
2055 public function isRedirect( $flags = 0 ) {
2056 if( !is_null($this->mRedirect
) )
2057 return $this->mRedirect
;
2058 # Calling getArticleID() loads the field from cache as needed
2059 if( !$this->getArticleID($flags) ) {
2060 return $this->mRedirect
= false;
2062 $linkCache = LinkCache
::singleton();
2063 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2065 return $this->mRedirect
;
2069 * What is the length of this page?
2070 * Uses link cache, adding it if necessary
2071 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2072 * @return \type{\bool}
2074 public function getLength( $flags = 0 ) {
2075 if( $this->mLength
!= -1 )
2076 return $this->mLength
;
2077 # Calling getArticleID() loads the field from cache as needed
2078 if( !$this->getArticleID($flags) ) {
2079 return $this->mLength
= 0;
2081 $linkCache = LinkCache
::singleton();
2082 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2084 return $this->mLength
;
2088 * What is the page_latest field for this page?
2089 * @param $flags \type{\int} a bit field; may be GAID_FOR_UPDATE to select for update
2090 * @return \type{\int}
2092 public function getLatestRevID( $flags = 0 ) {
2093 if( $this->mLatestID
!== false )
2094 return $this->mLatestID
;
2096 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB(DB_MASTER
) : wfGetDB(DB_SLAVE
);
2097 $this->mLatestID
= $db->selectField( 'page', 'page_latest', $this->pageCond(), __METHOD__
);
2098 return $this->mLatestID
;
2102 * This clears some fields in this object, and clears any associated
2103 * keys in the "bad links" section of the link cache.
2105 * - This is called from Article::insertNewArticle() to allow
2106 * loading of the new page_id. It's also called from
2107 * Article::doDeleteArticle()
2109 * @param $newid \type{\int} the new Article ID
2111 public function resetArticleID( $newid ) {
2112 $linkCache = LinkCache
::singleton();
2113 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2115 if ( $newid === false ) { $this->mArticleID
= -1; }
2116 else { $this->mArticleID
= $newid; }
2117 $this->mRestrictionsLoaded
= false;
2118 $this->mRestrictions
= array();
2122 * Updates page_touched for this page; called from LinksUpdate.php
2123 * @return \type{\bool} true if the update succeded
2125 public function invalidateCache() {
2126 if( wfReadOnly() ) {
2129 $dbw = wfGetDB( DB_MASTER
);
2130 $success = $dbw->update( 'page',
2131 array( 'page_touched' => $dbw->timestamp() ),
2135 HTMLFileCache
::clearFileCache( $this );
2140 * Prefix some arbitrary text with the namespace or interwiki prefix
2143 * @param $name \type{\string} the text
2144 * @return \type{\string} the prefixed text
2147 /* private */ function prefix( $name ) {
2149 if ( '' != $this->mInterwiki
) {
2150 $p = $this->mInterwiki
. ':';
2152 if ( 0 != $this->mNamespace
) {
2153 $p .= $this->getNsText() . ':';
2159 * Secure and split - main initialisation function for this object
2161 * Assumes that mDbkeyform has been set, and is urldecoded
2162 * and uses underscores, but not otherwise munged. This function
2163 * removes illegal characters, splits off the interwiki and
2164 * namespace prefixes, sets the other forms, and canonicalizes
2166 * @return \type{\bool} true on success
2168 private function secureAndSplit() {
2169 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
2172 static $rxTc = false;
2174 # Matching titles will be held as illegal.
2176 # Any character not allowed is forbidden...
2177 '[^' . Title
::legalChars() . ']' .
2178 # URL percent encoding sequences interfere with the ability
2179 # to round-trip titles -- you can't link to them consistently.
2180 '|%[0-9A-Fa-f]{2}' .
2181 # XML/HTML character references produce similar issues.
2182 '|&[A-Za-z0-9\x80-\xff]+;' .
2184 '|&#x[0-9A-Fa-f]+;' .
2188 $this->mInterwiki
= $this->mFragment
= '';
2189 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2191 $dbkey = $this->mDbkeyform
;
2193 # Strip Unicode bidi override characters.
2194 # Sometimes they slip into cut-n-pasted page titles, where the
2195 # override chars get included in list displays.
2196 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2198 # Clean up whitespace
2200 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
2201 $dbkey = trim( $dbkey, '_' );
2203 if ( '' == $dbkey ) {
2207 if( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2208 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2212 $this->mDbkeyform
= $dbkey;
2214 # Initial colon indicates main namespace rather than specified default
2215 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2216 if ( ':' == $dbkey{0} ) {
2217 $this->mNamespace
= NS_MAIN
;
2218 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2219 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2222 # Namespace or interwiki prefix
2224 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2227 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2229 if ( $ns = $wgContLang->getNsIndex( $p ) ) {
2230 # Ordinary namespace
2232 $this->mNamespace
= $ns;
2233 # For Talk:X pages, check if X has a "namespace" prefix
2234 if( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2235 if( $wgContLang->getNsIndex( $x[1] ) )
2236 return false; # Disallow Talk:File:x type titles...
2237 else if( Interwiki
::isValidInterwiki( $x[1] ) )
2238 return false; # Disallow Talk:Interwiki:x type titles...
2240 } elseif( Interwiki
::isValidInterwiki( $p ) ) {
2242 # Can't make a local interwiki link to an interwiki link.
2243 # That's just crazy!
2249 $this->mInterwiki
= $wgContLang->lc( $p );
2251 # Redundant interwiki prefix to the local wiki
2252 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2253 if( $dbkey == '' ) {
2254 # Can't have an empty self-link
2257 $this->mInterwiki
= '';
2259 # Do another namespace split...
2263 # If there's an initial colon after the interwiki, that also
2264 # resets the default namespace
2265 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2266 $this->mNamespace
= NS_MAIN
;
2267 $dbkey = substr( $dbkey, 1 );
2270 # If there's no recognized interwiki or namespace,
2271 # then let the colon expression be part of the title.
2276 # We already know that some pages won't be in the database!
2278 if ( '' != $this->mInterwiki || NS_SPECIAL
== $this->mNamespace
) {
2279 $this->mArticleID
= 0;
2281 $fragment = strstr( $dbkey, '#' );
2282 if ( false !== $fragment ) {
2283 $this->setFragment( $fragment );
2284 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2285 # remove whitespace again: prevents "Foo_bar_#"
2286 # becoming "Foo_bar_"
2287 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2290 # Reject illegal characters.
2292 if( preg_match( $rxTc, $dbkey ) ) {
2297 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2298 * reachable due to the way web browsers deal with 'relative' URLs.
2299 * Also, they conflict with subpage syntax. Forbid them explicitly.
2301 if ( strpos( $dbkey, '.' ) !== false &&
2302 ( $dbkey === '.' ||
$dbkey === '..' ||
2303 strpos( $dbkey, './' ) === 0 ||
2304 strpos( $dbkey, '../' ) === 0 ||
2305 strpos( $dbkey, '/./' ) !== false ||
2306 strpos( $dbkey, '/../' ) !== false ||
2307 substr( $dbkey, -2 ) == '/.' ||
2308 substr( $dbkey, -3 ) == '/..' ) )
2314 * Magic tilde sequences? Nu-uh!
2316 if( strpos( $dbkey, '~~~' ) !== false ) {
2321 * Limit the size of titles to 255 bytes.
2322 * This is typically the size of the underlying database field.
2323 * We make an exception for special pages, which don't need to be stored
2324 * in the database, and may edge over 255 bytes due to subpage syntax
2325 * for long titles, e.g. [[Special:Block/Long name]]
2327 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2328 strlen( $dbkey ) > 512 )
2334 * Normally, all wiki links are forced to have
2335 * an initial capital letter so [[foo]] and [[Foo]]
2336 * point to the same place.
2338 * Don't force it for interwikis, since the other
2339 * site might be case-sensitive.
2341 $this->mUserCaseDBKey
= $dbkey;
2342 if( $wgCapitalLinks && $this->mInterwiki
== '') {
2343 $dbkey = $wgContLang->ucfirst( $dbkey );
2347 * Can't make a link to a namespace alone...
2348 * "empty" local links can only be self-links
2349 * with a fragment identifier.
2352 $this->mInterwiki
== '' &&
2353 $this->mNamespace
!= NS_MAIN
) {
2356 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2357 // IP names are not allowed for accounts, and can only be referring to
2358 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2359 // there are numerous ways to present the same IP. Having sp:contribs scan
2360 // them all is silly and having some show the edits and others not is
2361 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2362 $dbkey = ($this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2363 IP
::sanitizeIP( $dbkey ) : $dbkey;
2364 // Any remaining initial :s are illegal.
2365 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
2370 $this->mDbkeyform
= $dbkey;
2371 $this->mUrlform
= wfUrlencode( $dbkey );
2373 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2379 * Set the fragment for this title. Removes the first character from the
2380 * specified fragment before setting, so it assumes you're passing it with
2383 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2384 * Still in active use privately.
2386 * @param $fragment \type{\string} text
2388 public function setFragment( $fragment ) {
2389 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2393 * Get a Title object associated with the talk page of this article
2394 * @return \type{Title} the object for the talk page
2396 public function getTalkPage() {
2397 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2401 * Get a title object associated with the subject page of this
2404 * @return \type{Title} the object for the subject page
2406 public function getSubjectPage() {
2407 // Is this the same title?
2408 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2409 if( $this->getNamespace() == $subjectNS ) {
2412 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2416 * Get an array of Title objects linking to this Title
2417 * Also stores the IDs in the link cache.
2419 * WARNING: do not use this function on arbitrary user-supplied titles!
2420 * On heavily-used templates it will max out the memory.
2422 * @param array $options may be FOR UPDATE
2423 * @return \type{\arrayof{Title}} the Title objects linking here
2425 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2426 $linkCache = LinkCache
::singleton();
2428 if ( count( $options ) > 0 ) {
2429 $db = wfGetDB( DB_MASTER
);
2431 $db = wfGetDB( DB_SLAVE
);
2434 $res = $db->select( array( 'page', $table ),
2435 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
2437 "{$prefix}_from=page_id",
2438 "{$prefix}_namespace" => $this->getNamespace(),
2439 "{$prefix}_title" => $this->getDBkey() ),
2444 if ( $db->numRows( $res ) ) {
2445 foreach( $res as $row ) {
2446 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2447 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
2448 $retVal[] = $titleObj;
2452 $db->freeResult( $res );
2457 * Get an array of Title objects using this Title as a template
2458 * Also stores the IDs in the link cache.
2460 * WARNING: do not use this function on arbitrary user-supplied titles!
2461 * On heavily-used templates it will max out the memory.
2463 * @param array $options may be FOR UPDATE
2464 * @return \type{\arrayof{Title}} the Title objects linking here
2466 public function getTemplateLinksTo( $options = array() ) {
2467 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2471 * Get an array of Title objects referring to non-existent articles linked from this page
2473 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2474 * @return \type{\arrayof{Title}} the Title objects
2476 public function getBrokenLinksFrom() {
2477 if ( $this->getArticleId() == 0 ) {
2478 # All links from article ID 0 are false positives
2482 $dbr = wfGetDB( DB_SLAVE
);
2483 $res = $dbr->select(
2484 array( 'page', 'pagelinks' ),
2485 array( 'pl_namespace', 'pl_title' ),
2487 'pl_from' => $this->getArticleId(),
2488 'page_namespace IS NULL'
2490 __METHOD__
, array(),
2494 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2500 foreach( $res as $row ) {
2501 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2508 * Get a list of URLs to purge from the Squid cache when this
2511 * @return \type{\arrayof{\string}} the URLs
2513 public function getSquidURLs() {
2517 $this->getInternalURL(),
2518 $this->getInternalURL( 'action=history' )
2521 // purge variant urls as well
2522 if($wgContLang->hasVariants()){
2523 $variants = $wgContLang->getVariants();
2524 foreach($variants as $vCode){
2525 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2526 $urls[] = $this->getInternalURL('',$vCode);
2534 * Purge all applicable Squid URLs
2536 public function purgeSquid() {
2538 if ( $wgUseSquid ) {
2539 $urls = $this->getSquidURLs();
2540 $u = new SquidUpdate( $urls );
2546 * Move this page without authentication
2547 * @param &$nt \type{Title} the new page Title
2549 public function moveNoAuth( &$nt ) {
2550 return $this->moveTo( $nt, false );
2554 * Check whether a given move operation would be valid.
2555 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2556 * @param &$nt \type{Title} the new title
2557 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2559 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2560 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2562 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2567 // Normally we'd add this to $errors, but we'll get
2568 // lots of syntax errors if $nt is not an object
2569 return array(array('badtitletext'));
2571 if( $this->equals( $nt ) ) {
2572 $errors[] = array('selfmove');
2574 if( !$this->isMovable() ) {
2575 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2577 if ( $nt->getInterwiki() != '' ) {
2578 $errors[] = array( 'immobile-target-namespace-iw' );
2580 if ( !$nt->isMovable() ) {
2581 $errors[] = array('immobile-target-namespace', $nt->getNsText() );
2584 $oldid = $this->getArticleID();
2585 $newid = $nt->getArticleID();
2587 if ( strlen( $nt->getDBkey() ) < 1 ) {
2588 $errors[] = array('articleexists');
2590 if ( ( '' == $this->getDBkey() ) ||
2592 ( '' == $nt->getDBkey() ) ) {
2593 $errors[] = array('badarticleerror');
2596 // Image-specific checks
2597 if( $this->getNamespace() == NS_FILE
) {
2598 $file = wfLocalFile( $this );
2599 if( $file->exists() ) {
2600 if( $nt->getNamespace() != NS_FILE
) {
2601 $errors[] = array('imagenocrossnamespace');
2603 if( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2604 $errors[] = array('imageinvalidfilename');
2606 if( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2607 $errors[] = array('imagetypemismatch');
2613 $errors = wfMergeErrorArrays( $errors,
2614 $this->getUserPermissionsErrors('move', $wgUser),
2615 $this->getUserPermissionsErrors('edit', $wgUser),
2616 $nt->getUserPermissionsErrors('move-target', $wgUser),
2617 $nt->getUserPermissionsErrors('edit', $wgUser) );
2620 $match = EditPage
::matchSummarySpamRegex( $reason );
2621 if( $match !== false ) {
2622 // This is kind of lame, won't display nice
2623 $errors[] = array('spamprotectiontext');
2627 if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2628 $errors[] = array('hookaborted', $err);
2631 # The move is allowed only if (1) the target doesn't exist, or
2632 # (2) the target is a redirect to the source, and has no history
2633 # (so we can undo bad moves right after they're done).
2635 if ( 0 != $newid ) { # Target exists; check for validity
2636 if ( ! $this->isValidMoveTarget( $nt ) ) {
2637 $errors[] = array('articleexists');
2640 $tp = $nt->getTitleProtection();
2641 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
2642 if ( $tp and !$wgUser->isAllowed( $right ) ) {
2643 $errors[] = array('cantmove-titleprotected');
2652 * Move a title to a new location
2653 * @param &$nt \type{Title} the new title
2654 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2656 * @param $reason \type{\string} The reason for the move
2657 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
2658 * Ignored if the user doesn't have the suppressredirect right.
2659 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2661 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
2662 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
2663 if( is_array( $err ) ) {
2667 // If it is a file, more it first. It is done before all other moving stuff is done because it's hard to revert
2668 $dbw = wfGetDB( DB_MASTER
);
2669 if( $this->getNamespace() == NS_FILE
) {
2670 $file = wfLocalFile( $this );
2671 if( $file->exists() ) {
2672 $status = $file->move( $nt );
2673 if( !$status->isOk() ) {
2674 return $status->getErrorsArray();
2679 $pageid = $this->getArticleID();
2680 $protected = $this->isProtected();
2681 if( $nt->exists() ) {
2682 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
2683 $pageCountChange = ($createRedirect ?
0 : -1);
2684 } else { # Target didn't exist, do normal move.
2685 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
2686 $pageCountChange = ($createRedirect ?
1 : 0);
2689 if( is_array( $err ) ) {
2692 $redirid = $this->getArticleID();
2694 // Category memberships include a sort key which may be customized.
2695 // If it's left as the default (the page title), we need to update
2696 // the sort key to match the new title.
2698 // Be careful to avoid resetting cl_timestamp, which may disturb
2699 // time-based lists on some sites.
2701 // Warning -- if the sort key is *explicitly* set to the old title,
2702 // we can't actually distinguish it from a default here, and it'll
2703 // be set to the new title even though it really shouldn't.
2704 // It'll get corrected on the next edit, but resetting cl_timestamp.
2705 $dbw->update( 'categorylinks',
2707 'cl_sortkey' => $nt->getPrefixedText(),
2708 'cl_timestamp=cl_timestamp' ),
2710 'cl_from' => $pageid,
2711 'cl_sortkey' => $this->getPrefixedText() ),
2715 # Protect the redirect title as the title used to be...
2716 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
2718 'pr_page' => $redirid,
2719 'pr_type' => 'pr_type',
2720 'pr_level' => 'pr_level',
2721 'pr_cascade' => 'pr_cascade',
2722 'pr_user' => 'pr_user',
2723 'pr_expiry' => 'pr_expiry'
2725 array( 'pr_page' => $pageid ),
2729 # Update the protection log
2730 $log = new LogPage( 'protect' );
2731 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2732 if( $reason ) $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
2733 $log->addEntry( 'move_prot', $nt, $comment, array($this->getPrefixedText()) ); // FIXME: $params?
2737 $oldnamespace = $this->getNamespace() & ~
1;
2738 $newnamespace = $nt->getNamespace() & ~
1;
2739 $oldtitle = $this->getDBkey();
2740 $newtitle = $nt->getDBkey();
2742 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
2743 WatchedItem
::duplicateEntries( $this, $nt );
2746 # Update search engine
2747 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2749 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2753 if( $this->isContentPage() && !$nt->isContentPage() ) {
2754 # No longer a content page
2755 # Not viewed, edited, removing
2756 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2757 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2758 # Now a content page
2759 # Not viewed, edited, adding
2760 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
2761 } elseif( $pageCountChange ) {
2763 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2770 # Update message cache for interface messages
2771 if( $nt->getNamespace() == NS_MEDIAWIKI
) {
2772 global $wgMessageCache;
2774 # @bug 17860: old article can be deleted, if this the case,
2775 # delete it from message cache
2776 if ( $this->getArticleID() === 0 ) {
2777 $wgMessageCache->replace( $this->getDBkey(), false );
2779 $oldarticle = new Article( $this );
2780 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
2783 $newarticle = new Article( $nt );
2784 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
2788 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2793 * Move page to a title which is at present a redirect to the
2796 * @param &$nt \type{Title} the page to move to, which should currently
2798 * @param $reason \type{\string} The reason for the move
2799 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
2800 * Ignored if the user doesn't have the suppressredirect right
2802 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
2803 global $wgUseSquid, $wgUser;
2804 $fname = 'Title::moveOverExistingRedirect';
2805 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2808 $comment .= ": $reason";
2811 $now = wfTimestampNow();
2812 $newid = $nt->getArticleID();
2813 $oldid = $this->getArticleID();
2814 $latest = $this->getLatestRevID();
2815 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
2816 $newns = $nt->getNamespace();
2817 $newdbk = $nt->getDBkey();
2819 $dbw = wfGetDB( DB_MASTER
);
2821 # Delete the old redirect. We don't save it to history since
2822 # by definition if we've got here it's rather uninteresting.
2823 # We have to remove it so that the next step doesn't trigger
2824 # a conflict on the unique namespace+title index...
2825 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2826 if ( !$dbw->cascadingDeletes() ) {
2827 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
2828 global $wgUseTrackbacks;
2829 if ($wgUseTrackbacks)
2830 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
2831 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
2832 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
2833 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
2834 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
2835 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
2836 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
2837 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
2839 // If the redirect was recently created, it may have an entry in recentchanges still
2840 $dbw->delete( 'recentchanges',
2841 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
2845 # Save a null revision in the page's history notifying of the move
2846 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2847 $nullRevId = $nullRevision->insertOn( $dbw );
2849 $article = new Article( $this );
2850 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
2852 # Change the name of the target page:
2853 $dbw->update( 'page',
2855 'page_touched' => $dbw->timestamp($now),
2856 'page_namespace' => $nt->getNamespace(),
2857 'page_title' => $nt->getDBkey(),
2858 'page_latest' => $nullRevId,
2860 /* WHERE */ array( 'page_id' => $oldid ),
2863 $nt->resetArticleID( $oldid );
2865 # Recreate the redirect, this time in the other direction.
2866 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2867 $mwRedir = MagicWord
::get( 'redirect' );
2868 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2869 $redirectArticle = new Article( $this );
2870 $newid = $redirectArticle->insertOn( $dbw );
2871 $redirectRevision = new Revision( array(
2873 'comment' => $comment,
2874 'text' => $redirectText ) );
2875 $redirectRevision->insertOn( $dbw );
2876 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2878 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
2880 # Now, we record the link from the redirect to the new title.
2881 # It should have no other outgoing links...
2882 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2883 $dbw->insert( 'pagelinks',
2885 'pl_from' => $newid,
2886 'pl_namespace' => $nt->getNamespace(),
2887 'pl_title' => $nt->getDBkey() ),
2889 $redirectSuppressed = false;
2891 $this->resetArticleID( 0 );
2892 $redirectSuppressed = true;
2896 $log = new LogPage( 'move' );
2897 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
2900 if ( $wgUseSquid ) {
2901 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2902 $u = new SquidUpdate( $urls );
2909 * Move page to non-existing title.
2910 * @param &$nt \type{Title} the new Title
2911 * @param $reason \type{\string} The reason for the move
2912 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
2913 * Ignored if the user doesn't have the suppressredirect right
2915 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
2916 global $wgUseSquid, $wgUser;
2917 $fname = 'MovePageForm::moveToNewTitle';
2918 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2920 $comment .= wfMsgExt( 'colon-separator',
2921 array( 'escapenoentities', 'content' ) );
2922 $comment .= $reason;
2925 $newid = $nt->getArticleID();
2926 $oldid = $this->getArticleID();
2927 $latest = $this->getLatestRevId();
2929 $dbw = wfGetDB( DB_MASTER
);
2930 $now = $dbw->timestamp();
2932 # Save a null revision in the page's history notifying of the move
2933 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
2934 $nullRevId = $nullRevision->insertOn( $dbw );
2936 $article = new Article( $this );
2937 wfRunHooks( 'NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $wgUser) );
2940 $dbw->update( 'page',
2942 'page_touched' => $now,
2943 'page_namespace' => $nt->getNamespace(),
2944 'page_title' => $nt->getDBkey(),
2945 'page_latest' => $nullRevId,
2947 /* WHERE */ array( 'page_id' => $oldid ),
2950 $nt->resetArticleID( $oldid );
2952 if( $createRedirect ||
!$wgUser->isAllowed('suppressredirect') ) {
2954 $mwRedir = MagicWord
::get( 'redirect' );
2955 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2956 $redirectArticle = new Article( $this );
2957 $newid = $redirectArticle->insertOn( $dbw );
2958 $redirectRevision = new Revision( array(
2960 'comment' => $comment,
2961 'text' => $redirectText ) );
2962 $redirectRevision->insertOn( $dbw );
2963 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2965 wfRunHooks( 'NewRevisionFromEditComplete', array($redirectArticle, $redirectRevision, false, $wgUser) );
2967 # Record the just-created redirect's linking to the page
2968 $dbw->insert( 'pagelinks',
2970 'pl_from' => $newid,
2971 'pl_namespace' => $nt->getNamespace(),
2972 'pl_title' => $nt->getDBkey() ),
2974 $redirectSuppressed = false;
2976 $this->resetArticleID( 0 );
2977 $redirectSuppressed = true;
2981 $log = new LogPage( 'move' );
2982 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
2984 # Purge caches as per article creation
2985 Article
::onArticleCreate( $nt );
2987 # Purge old title from squid
2988 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2989 $this->purgeSquid();
2994 * Move this page's subpages to be subpages of $nt
2995 * @param $nt Title Move target
2996 * @param $auth bool Whether $wgUser's permissions should be checked
2997 * @param $reason string The reason for the move
2998 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
2999 * Ignored if the user doesn't have the 'suppressredirect' right
3000 * @return mixed array with old page titles as keys, and strings (new page titles) or
3001 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
3003 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3004 global $wgMaximumMovedPages;
3005 // Check permissions
3006 if( !$this->userCan( 'move-subpages' ) )
3007 return array( 'cant-move-subpages' );
3008 // Do the source and target namespaces support subpages?
3009 if( !MWNamespace
::hasSubpages( $this->getNamespace() ) )
3010 return array( 'namespace-nosubpages',
3011 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3012 if( !MWNamespace
::hasSubpages( $nt->getNamespace() ) )
3013 return array( 'namespace-nosubpages',
3014 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3016 $subpages = $this->getSubpages($wgMaximumMovedPages +
1);
3019 foreach( $subpages as $oldSubpage ) {
3021 if( $count > $wgMaximumMovedPages ) {
3022 $retval[$oldSubpage->getPrefixedTitle()] =
3023 array( 'movepage-max-pages',
3024 $wgMaximumMovedPages );
3028 if( $oldSubpage->getArticleId() == $this->getArticleId() )
3029 // When moving a page to a subpage of itself,
3030 // don't move it twice
3032 $newPageName = preg_replace(
3033 '#^'.preg_quote( $this->getDBkey(), '#' ).'#',
3034 $nt->getDBkey(), $oldSubpage->getDBkey() );
3035 if( $oldSubpage->isTalkPage() ) {
3036 $newNs = $nt->getTalkPage()->getNamespace();
3038 $newNs = $nt->getSubjectPage()->getNamespace();
3040 # Bug 14385: we need makeTitleSafe because the new page names may
3041 # be longer than 255 characters.
3042 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3044 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3045 if( $success === true ) {
3046 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3048 $retval[$oldSubpage->getPrefixedText()] = $success;
3055 * Checks if this page is just a one-rev redirect.
3056 * Adds lock, so don't use just for light purposes.
3058 * @return \type{\bool} TRUE or FALSE
3060 public function isSingleRevRedirect() {
3061 $dbw = wfGetDB( DB_MASTER
);
3063 $row = $dbw->selectRow( 'page',
3064 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3067 array( 'FOR UPDATE' )
3069 # Cache some fields we may want
3070 $this->mArticleID
= $row ?
intval($row->page_id
) : 0;
3071 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3072 $this->mLatestID
= $row ?
intval($row->page_latest
) : false;
3073 if( !$this->mRedirect
) {
3076 # Does the article have a history?
3077 $row = $dbw->selectField( array( 'page', 'revision'),
3079 array( 'page_namespace' => $this->getNamespace(),
3080 'page_title' => $this->getDBkey(),
3082 'page_latest != rev_id'
3085 array( 'FOR UPDATE' )
3087 # Return true if there was no history
3088 return ($row === false);
3092 * Checks if $this can be moved to a given Title
3093 * - Selects for update, so don't call it unless you mean business
3095 * @param &$nt \type{Title} the new title to check
3096 * @return \type{\bool} TRUE or FALSE
3098 public function isValidMoveTarget( $nt ) {
3099 $dbw = wfGetDB( DB_MASTER
);
3100 # Is it an existsing file?
3101 if( $nt->getNamespace() == NS_FILE
) {
3102 $file = wfLocalFile( $nt );
3103 if( $file->exists() ) {
3104 wfDebug( __METHOD__
. ": file exists\n" );
3108 # Is it a redirect with no history?
3109 if( !$nt->isSingleRevRedirect() ) {
3110 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3113 # Get the article text
3114 $rev = Revision
::newFromTitle( $nt );
3115 $text = $rev->getText();
3116 # Does the redirect point to the source?
3117 # Or is it a broken self-redirect, usually caused by namespace collisions?
3119 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3120 $redirTitle = Title
::newFromText( $m[1] );
3121 if( !is_object( $redirTitle ) ||
3122 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3123 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3124 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3129 wfDebug( __METHOD__
. ": failsafe\n" );
3136 * Can this title be added to a user's watchlist?
3138 * @return \type{\bool} TRUE or FALSE
3140 public function isWatchable() {
3141 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3145 * Get categories to which this Title belongs and return an array of
3146 * categories' names.
3148 * @return \type{\array} array an array of parents in the form:
3149 * $parent => $currentarticle
3151 public function getParentCategories() {
3154 $titlekey = $this->getArticleId();
3155 $dbr = wfGetDB( DB_SLAVE
);
3156 $categorylinks = $dbr->tableName( 'categorylinks' );
3159 $sql = "SELECT * FROM $categorylinks"
3160 ." WHERE cl_from='$titlekey'"
3161 ." AND cl_from <> '0'"
3162 ." ORDER BY cl_sortkey";
3164 $res = $dbr->query( $sql );
3166 if( $dbr->numRows( $res ) > 0 ) {
3167 foreach( $res as $row )
3168 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3169 $data[$wgContLang->getNSText( NS_CATEGORY
).':'.$row->cl_to
] = $this->getFullText();
3170 $dbr->freeResult( $res );
3178 * Get a tree of parent categories
3179 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3180 * @return \type{\array} Tree of parent categories
3182 public function getParentCategoryTree( $children = array() ) {
3184 $parents = $this->getParentCategories();
3187 foreach( $parents as $parent => $current ) {
3188 if ( array_key_exists( $parent, $children ) ) {
3189 # Circular reference
3190 $stack[$parent] = array();
3192 $nt = Title
::newFromText($parent);
3194 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
3206 * Get an associative array for selecting this title from
3209 * @return \type{\array} Selection array
3211 public function pageCond() {
3212 if( $this->mArticleID
> 0 ) {
3213 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3214 return array( 'page_id' => $this->mArticleID
);
3216 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3221 * Get the revision ID of the previous revision
3223 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3224 * @param $flags \type{\int} GAID_FOR_UPDATE
3225 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3227 public function getPreviousRevisionID( $revId, $flags=0 ) {
3228 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3229 return $db->selectField( 'revision', 'rev_id',
3231 'rev_page' => $this->getArticleId($flags),
3232 'rev_id < ' . intval( $revId )
3235 array( 'ORDER BY' => 'rev_id DESC' )
3240 * Get the revision ID of the next revision
3242 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3243 * @param $flags \type{\int} GAID_FOR_UPDATE
3244 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3246 public function getNextRevisionID( $revId, $flags=0 ) {
3247 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3248 return $db->selectField( 'revision', 'rev_id',
3250 'rev_page' => $this->getArticleId($flags),
3251 'rev_id > ' . intval( $revId )
3254 array( 'ORDER BY' => 'rev_id' )
3259 * Get the first revision of the page
3261 * @param $flags \type{\int} GAID_FOR_UPDATE
3262 * @return Revision (or NULL if page doesn't exist)
3264 public function getFirstRevision( $flags=0 ) {
3265 $db = ($flags & GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3266 $pageId = $this->getArticleId($flags);
3267 if( !$pageId ) return NULL;
3268 $row = $db->selectRow( 'revision', '*',
3269 array( 'rev_page' => $pageId ),
3271 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3276 return new Revision( $row );
3281 * Check if this is a new page
3285 public function isNewPage() {
3286 $dbr = wfGetDB( DB_SLAVE
);
3287 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3291 * Get the oldest revision timestamp of this page
3293 * @return string, MW timestamp
3295 public function getEarliestRevTime() {
3296 $dbr = wfGetDB( DB_SLAVE
);
3297 if( $this->exists() ) {
3298 $min = $dbr->selectField( 'revision',
3299 'MIN(rev_timestamp)',
3300 array( 'rev_page' => $this->getArticleId() ),
3302 return wfTimestampOrNull( TS_MW
, $min );
3308 * Get the number of revisions between the given revision IDs.
3309 * Used for diffs and other things that really need it.
3311 * @param $old \type{\int} Revision ID.
3312 * @param $new \type{\int} Revision ID.
3313 * @return \type{\int} Number of revisions between these IDs.
3315 public function countRevisionsBetween( $old, $new ) {
3316 $dbr = wfGetDB( DB_SLAVE
);
3317 return $dbr->selectField( 'revision', 'count(*)',
3318 'rev_page = ' . intval( $this->getArticleId() ) .
3319 ' AND rev_id > ' . intval( $old ) .
3320 ' AND rev_id < ' . intval( $new ),
3326 * Compare with another title.
3328 * @param \type{Title} $title
3329 * @return \type{\bool} TRUE or FALSE
3331 public function equals( Title
$title ) {
3332 // Note: === is necessary for proper matching of number-like titles.
3333 return $this->getInterwiki() === $title->getInterwiki()
3334 && $this->getNamespace() == $title->getNamespace()
3335 && $this->getDBkey() === $title->getDBkey();
3339 * Callback for usort() to do title sorts by (namespace, title)
3341 public static function compare( $a, $b ) {
3342 if( $a->getNamespace() == $b->getNamespace() ) {
3343 return strcmp( $a->getText(), $b->getText() );
3345 return $a->getNamespace() - $b->getNamespace();
3350 * Return a string representation of this title
3352 * @return \type{\string} String representation of this title
3354 public function __toString() {
3355 return $this->getPrefixedText();
3359 * Check if page exists. For historical reasons, this function simply
3360 * checks for the existence of the title in the page table, and will
3361 * thus return false for interwiki links, special pages and the like.
3362 * If you want to know if a title can be meaningfully viewed, you should
3363 * probably call the isKnown() method instead.
3365 * @return \type{\bool} TRUE or FALSE
3367 public function exists() {
3368 return $this->getArticleId() != 0;
3372 * Should links to this title be shown as potentially viewable (i.e. as
3373 * "bluelinks"), even if there's no record by this title in the page
3376 * This function is semi-deprecated for public use, as well as somewhat
3377 * misleadingly named. You probably just want to call isKnown(), which
3378 * calls this function internally.
3380 * (ISSUE: Most of these checks are cheap, but the file existence check
3381 * can potentially be quite expensive. Including it here fixes a lot of
3382 * existing code, but we might want to add an optional parameter to skip
3383 * it and any other expensive checks.)
3385 * @return \type{\bool} TRUE or FALSE
3387 public function isAlwaysKnown() {
3388 if( $this->mInterwiki
!= '' ) {
3389 return true; // any interwiki link might be viewable, for all we know
3391 switch( $this->mNamespace
) {
3394 return wfFindFile( $this ); // file exists, possibly in a foreign repo
3396 return SpecialPage
::exists( $this->getDBkey() ); // valid special page
3398 return $this->mDbkeyform
== ''; // selflink, possibly with fragment
3400 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3401 // the full l10n of that language to be loaded. That takes much memory and
3402 // isn't needed. So we strip the language part away.
3403 // Also, extension messages which are not loaded, are shown as red, because
3404 // we don't call MessageCache::loadAllMessages.
3405 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3406 return wfMsgWeirdKey( $basename ); // known system message
3413 * Does this title refer to a page that can (or might) be meaningfully
3414 * viewed? In particular, this function may be used to determine if
3415 * links to the title should be rendered as "bluelinks" (as opposed to
3416 * "redlinks" to non-existent pages).
3418 * @return \type{\bool} TRUE or FALSE
3420 public function isKnown() {
3421 return $this->exists() ||
$this->isAlwaysKnown();
3425 * Is this in a namespace that allows actual pages?
3427 * @return \type{\bool} TRUE or FALSE
3429 public function canExist() {
3430 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
3434 * Update page_touched timestamps and send squid purge messages for
3435 * pages linking to this title. May be sent to the job queue depending
3436 * on the number of links. Typically called on create and delete.
3438 public function touchLinks() {
3439 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3442 if ( $this->getNamespace() == NS_CATEGORY
) {
3443 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3449 * Get the last touched timestamp
3450 * @param Database $db, optional db
3451 * @return \type{\string} Last touched timestamp
3453 public function getTouched( $db = NULL ) {
3454 $db = isset($db) ?
$db : wfGetDB( DB_SLAVE
);
3455 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3460 * Get the timestamp when this page was updated since the user last saw it.
3462 * @return mixed string/NULL
3464 public function getNotificationTimestamp( $user = NULL ) {
3465 global $wgUser, $wgShowUpdatedMarker;
3466 // Assume current user if none given
3467 if( !$user ) $user = $wgUser;
3468 // Check cache first
3469 $uid = $user->getId();
3470 if( isset($this->mNotificationTimestamp
[$uid]) ) {
3471 return $this->mNotificationTimestamp
[$uid];
3473 if( !$uid ||
!$wgShowUpdatedMarker ) {
3474 return $this->mNotificationTimestamp
[$uid] = false;
3476 // Don't cache too much!
3477 if( count($this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3478 $this->mNotificationTimestamp
= array();
3480 $dbr = wfGetDB( DB_SLAVE
);
3481 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3482 'wl_notificationtimestamp',
3483 array( 'wl_namespace' => $this->getNamespace(),
3484 'wl_title' => $this->getDBkey(),
3485 'wl_user' => $user->getId()
3489 return $this->mNotificationTimestamp
[$uid];
3493 * Get the trackback URL for this page
3494 * @return \type{\string} Trackback URL
3496 public function trackbackURL() {
3497 global $wgScriptPath, $wgServer, $wgScriptExtension;
3499 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3500 . htmlspecialchars(urlencode($this->getPrefixedDBkey()));
3504 * Get the trackback RDF for this page
3505 * @return \type{\string} Trackback RDF
3507 public function trackbackRDF() {
3508 $url = htmlspecialchars($this->getFullURL());
3509 $title = htmlspecialchars($this->getText());
3510 $tburl = $this->trackbackURL();
3512 // Autodiscovery RDF is placed in comments so HTML validator
3513 // won't barf. This is a rather icky workaround, but seems
3514 // frequently used by this kind of RDF thingy.
3516 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3518 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3519 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3520 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3523 dc:identifier=\"$url\"
3525 trackback:ping=\"$tburl\" />
3531 * Generate strings used for xml 'id' names in monobook tabs
3532 * @return \type{\string} XML 'id' name
3534 public function getNamespaceKey( $prepend = 'nstab-' ) {
3535 global $wgContLang, $wgCanonicalNamespaceNames;
3536 // Gets the subject namespace if this title
3537 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
3538 // Checks if cononical namespace name exists for namespace
3539 if ( isset( $wgCanonicalNamespaceNames[$namespace] ) ) {
3540 // Uses canonical namespace name
3541 $namespaceKey = $wgCanonicalNamespaceNames[$namespace];
3543 // Uses text of namespace
3544 $namespaceKey = $this->getSubjectNsText();
3546 // Makes namespace key lowercase
3547 $namespaceKey = $wgContLang->lc( $namespaceKey );
3549 if ( $namespaceKey == '' ) {
3550 $namespaceKey = 'main';
3552 // Changes file to image for backwards compatibility
3553 if ( $namespaceKey == 'file' ) {
3554 $namespaceKey = 'image';
3556 return $prepend . $namespaceKey;
3560 * Returns true if this title resolves to the named special page
3561 * @param $name \type{\string} The special page name
3563 public function isSpecial( $name ) {
3564 if ( $this->getNamespace() == NS_SPECIAL
) {
3565 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3566 if ( $name == $thisName ) {
3574 * If the Title refers to a special page alias which is not the local default,
3575 * @return \type{Title} A new Title which points to the local default. Otherwise, returns $this.
3577 public function fixSpecialName() {
3578 if ( $this->getNamespace() == NS_SPECIAL
) {
3579 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
3580 if ( $canonicalName ) {
3581 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
3582 if ( $localName != $this->mDbkeyform
) {
3583 return Title
::makeTitle( NS_SPECIAL
, $localName );
3591 * Is this Title in a namespace which contains content?
3592 * In other words, is this a content page, for the purposes of calculating
3595 * @return \type{\bool} TRUE or FALSE
3597 public function isContentPage() {
3598 return MWNamespace
::isContent( $this->getNamespace() );
3602 * Get all extant redirects to this Title
3604 * @param $ns \twotypes{\int,\null} Single namespace to consider;
3605 * NULL to consider all namespaces
3606 * @return \type{\arrayof{Title}} Redirects to this title
3608 public function getRedirectsHere( $ns = null ) {
3611 $dbr = wfGetDB( DB_SLAVE
);
3613 'rd_namespace' => $this->getNamespace(),
3614 'rd_title' => $this->getDBkey(),
3617 if ( !is_null($ns) ) $where['page_namespace'] = $ns;
3619 $res = $dbr->select(
3620 array( 'redirect', 'page' ),
3621 array( 'page_namespace', 'page_title' ),
3627 foreach( $res as $row ) {
3628 $redirs[] = self
::newFromRow( $row );
3634 * Check if this Title is a valid redirect target
3636 * @return \type{\bool} TRUE or FALSE
3638 public function isValidRedirectTarget() {
3639 global $wgInvalidRedirectTargets;
3641 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
3642 if( $this->isSpecial( 'Userlogout' ) ) {
3646 foreach( $wgInvalidRedirectTargets as $target ) {
3647 if( $this->isSpecial( $target ) ) {
3656 * Get a backlink cache object
3658 function getBacklinkCache() {
3659 if ( is_null( $this->mBacklinkCache
) ) {
3660 $this->mBacklinkCache
= new BacklinkCache( $this );
3662 return $this->mBacklinkCache
;