8 * @todo: determine if it is really necessary to load this. Appears to be left over from pre-autoloader versions, and
9 * is only really needed to provide access to constant UTF8_REPLACEMENT, which actually resides in UtfNormalDefines.php
10 * and is loaded by UtfNormalUtil.php, which is loaded by UtfNormal.php.
12 if ( !class_exists( 'UtfNormal' ) ) {
13 require_once( dirname( __FILE__
) . '/normal/UtfNormal.php' );
17 * Represents a title within MediaWiki.
18 * Optionally may contain an interwiki designation or namespace.
19 * @note This class can fetch various kinds of data from the database;
20 * however, it does so inefficiently.
22 * @internal documentation reviewed 15 Mar 2010
25 /** @name Static cache variables */
27 static private $titleCache = array();
31 * Title::newFromText maintains a cache to avoid expensive re-normalization of
32 * commonly used titles. On a batch operation this can become a memory leak
33 * if not bounded. After hitting this many titles reset the cache.
35 const CACHE_MAX
= 1000;
38 * Used to be GAID_FOR_UPDATE define. Used with getArticleId() and friends
39 * to use the master DB
41 const GAID_FOR_UPDATE
= 1;
45 * @name Private member variables
46 * Please use the accessor functions instead.
51 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
52 var $mUrlform = ''; // /< URL-encoded form of the main part
53 var $mDbkeyform = ''; // /< Main part with underscores
54 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
55 var $mNamespace = NS_MAIN
; // /< Namespace index, i.e. one of the NS_xxxx constants
56 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
57 var $mFragment; // /< Title fragment (i.e. the bit after the #)
58 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
59 var $mLatestID = false; // /< ID of most recent revision
60 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
61 var $mOldRestrictions = false;
62 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
63 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
64 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
65 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
66 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
67 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
68 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
69 var $mTitleProtection; ///< Cached value of getTitleProtection
70 # Don't change the following default, NS_MAIN is hardcoded in several
71 # places. See bug 696.
72 var $mDefaultNamespace = NS_MAIN
; // /< Namespace index when there is no namespace
73 # Zero except in {{transclusion}} tags
74 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
75 var $mLength = -1; // /< The page length, 0 for special pages
76 var $mRedirect = null; // /< Is the article at this title a redirect?
77 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
78 var $mBacklinkCache = null; // /< Cache of links to this title
86 /* private */ function __construct() { }
89 * Create a new Title from a prefixed DB key
91 * @param $key \type{\string} The database key, which has underscores
92 * instead of spaces, possibly including namespace and
94 * @return \type{Title} the new object, or NULL on an error
96 public static function newFromDBkey( $key ) {
98 $t->mDbkeyform
= $key;
99 if ( $t->secureAndSplit() ) {
107 * Create a new Title from text, such as what one would find in a link. De-
108 * codes any HTML entities in the text.
110 * @param $text string The link text; spaces, prefixes, and an
111 * initial ':' indicating the main namespace are accepted.
112 * @param $defaultNamespace int The namespace to use if none is speci-
113 * fied by a prefix. If you want to force a specific namespace even if
114 * $text might begin with a namespace prefix, use makeTitle() or
116 * @return Title The new object, or null on an error.
118 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
119 if ( is_object( $text ) ) {
120 throw new MWException( 'Title::newFromText given an object' );
124 * Wiki pages often contain multiple links to the same page.
125 * Title normalization and parsing can become expensive on
126 * pages with many links, so we can save a little time by
129 * In theory these are value objects and won't get changed...
131 if ( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
132 return Title
::$titleCache[$text];
136 * Convert things like é ā or 〗 into normalized (bug 14952) text
138 $filteredText = Sanitizer
::decodeCharReferencesAndNormalize( $text );
141 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
142 $t->mDefaultNamespace
= $defaultNamespace;
144 static $cachedcount = 0 ;
145 if ( $t->secureAndSplit() ) {
146 if ( $defaultNamespace == NS_MAIN
) {
147 if ( $cachedcount >= self
::CACHE_MAX
) {
148 # Avoid memory leaks on mass operations...
149 Title
::$titleCache = array();
153 Title
::$titleCache[$text] =& $t;
163 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
165 * Example of wrong and broken code:
166 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
168 * Example of right code:
169 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
171 * Create a new Title from URL-encoded text. Ensures that
172 * the given title's length does not exceed the maximum.
174 * @param $url \type{\string} the title, as might be taken from a URL
175 * @return \type{Title} the new object, or NULL on an error
177 public static function newFromURL( $url ) {
178 global $wgLegalTitleChars;
181 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
182 # but some URLs used it as a space replacement and they still come
183 # from some external search tools.
184 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
185 $url = str_replace( '+', ' ', $url );
188 $t->mDbkeyform
= str_replace( ' ', '_', $url );
189 if ( $t->secureAndSplit() ) {
197 * Create a new Title from an article ID
199 * @param $id \type{\int} the page_id corresponding to the Title to create
200 * @param $flags \type{\int} use Title::GAID_FOR_UPDATE to use master
201 * @return \type{Title} the new object, or NULL on an error
203 public static function newFromID( $id, $flags = 0 ) {
204 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
205 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__
);
206 if ( $row !== false ) {
207 $title = Title
::newFromRow( $row );
215 * Make an array of titles from an array of IDs
217 * @param $ids \type{\arrayof{\int}} Array of IDs
218 * @return \type{\arrayof{Title}} Array of Titles
220 public static function newFromIDs( $ids ) {
221 if ( !count( $ids ) ) {
224 $dbr = wfGetDB( DB_SLAVE
);
229 'page_namespace', 'page_title', 'page_id',
230 'page_len', 'page_is_redirect', 'page_latest',
232 array( 'page_id' => $ids ),
237 foreach ( $res as $row ) {
238 $titles[] = Title
::newFromRow( $row );
244 * Make a Title object from a DB row
246 * @param $row \type{Row} (needs at least page_title,page_namespace)
247 * @return \type{Title} corresponding Title
249 public static function newFromRow( $row ) {
250 $t = self
::makeTitle( $row->page_namespace
, $row->page_title
);
252 $t->mArticleID
= isset( $row->page_id
) ?
intval( $row->page_id
) : -1;
253 $t->mLength
= isset( $row->page_len
) ?
intval( $row->page_len
) : -1;
254 $t->mRedirect
= isset( $row->page_is_redirect
) ?
(bool)$row->page_is_redirect
: null;
255 $t->mLatestID
= isset( $row->page_latest
) ?
intval( $row->page_latest
) : false;
261 * Create a new Title from a namespace index and a DB key.
262 * It's assumed that $ns and $title are *valid*, for instance when
263 * they came directly from the database or a special page name.
264 * For convenience, spaces are converted to underscores so that
265 * eg user_text fields can be used directly.
267 * @param $ns \type{\int} the namespace of the article
268 * @param $title \type{\string} the unprefixed database key form
269 * @param $fragment \type{\string} The link fragment (after the "#")
270 * @param $interwiki \type{\string} The interwiki prefix
271 * @return \type{Title} the new object
273 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
275 $t->mInterwiki
= $interwiki;
276 $t->mFragment
= $fragment;
277 $t->mNamespace
= $ns = intval( $ns );
278 $t->mDbkeyform
= str_replace( ' ', '_', $title );
279 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
280 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
281 $t->mTextform
= str_replace( '_', ' ', $title );
286 * Create a new Title from a namespace index and a DB key.
287 * The parameters will be checked for validity, which is a bit slower
288 * than makeTitle() but safer for user-provided data.
290 * @param $ns \type{\int} the namespace of the article
291 * @param $title \type{\string} the database key form
292 * @param $fragment \type{\string} The link fragment (after the "#")
293 * @param $interwiki \type{\string} The interwiki prefix
294 * @return \type{Title} the new object, or NULL on an error
296 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
298 $t->mDbkeyform
= Title
::makeName( $ns, $title, $fragment, $interwiki );
299 if ( $t->secureAndSplit() ) {
307 * Create a new Title for the Main Page
309 * @return \type{Title} the new object
311 public static function newMainPage() {
312 $title = Title
::newFromText( wfMsgForContent( 'mainpage' ) );
313 // Don't give fatal errors if the message is broken
315 $title = Title
::newFromText( 'Main Page' );
321 * Extract a redirect destination from a string and return the
322 * Title, or null if the text doesn't contain a valid redirect
323 * This will only return the very next target, useful for
324 * the redirect table and other checks that don't need full recursion
326 * @param $text \type{\string} Text with possible redirect
327 * @return \type{Title} The corresponding Title
329 public static function newFromRedirect( $text ) {
330 return self
::newFromRedirectInternal( $text );
334 * Extract a redirect destination from a string and return the
335 * Title, or null if the text doesn't contain a valid redirect
336 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
337 * in order to provide (hopefully) the Title of the final destination instead of another redirect
339 * @param $text \type{\string} Text with possible redirect
340 * @return \type{Title} The corresponding Title
342 public static function newFromRedirectRecurse( $text ) {
343 $titles = self
::newFromRedirectArray( $text );
344 return $titles ?
array_pop( $titles ) : null;
348 * Extract a redirect destination from a string and return an
349 * array of Titles, or null if the text doesn't contain a valid redirect
350 * The last element in the array is the final destination after all redirects
351 * have been resolved (up to $wgMaxRedirects times)
353 * @param $text \type{\string} Text with possible redirect
354 * @return \type{\array} Array of Titles, with the destination last
356 public static function newFromRedirectArray( $text ) {
357 global $wgMaxRedirects;
358 // are redirects disabled?
359 if ( $wgMaxRedirects < 1 ) {
362 $title = self
::newFromRedirectInternal( $text );
363 if ( is_null( $title ) ) {
366 // recursive check to follow double redirects
367 $recurse = $wgMaxRedirects;
368 $titles = array( $title );
369 while ( --$recurse > 0 ) {
370 if ( $title->isRedirect() ) {
371 $article = new Article( $title, 0 );
372 $newtitle = $article->getRedirectTarget();
376 // Redirects to some special pages are not permitted
377 if ( $newtitle instanceOf Title
&& $newtitle->isValidRedirectTarget() ) {
378 // the new title passes the checks, so make that our current title so that further recursion can be checked
380 $titles[] = $newtitle;
389 * Really extract the redirect destination
390 * Do not call this function directly, use one of the newFromRedirect* functions above
392 * @param $text \type{\string} Text with possible redirect
393 * @return \type{Title} The corresponding Title
395 protected static function newFromRedirectInternal( $text ) {
396 $redir = MagicWord
::get( 'redirect' );
397 $text = trim( $text );
398 if ( $redir->matchStartAndRemove( $text ) ) {
399 // Extract the first link and see if it's usable
400 // Ensure that it really does come directly after #REDIRECT
401 // Some older redirects included a colon, so don't freak about that!
403 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
404 // Strip preceding colon used to "escape" categories, etc.
405 // and URL-decode links
406 if ( strpos( $m[1], '%' ) !== false ) {
407 // Match behavior of inline link parsing here;
408 // don't interpret + as " " most of the time!
409 // It might be safe to just use rawurldecode instead, though.
410 $m[1] = urldecode( ltrim( $m[1], ':' ) );
412 $title = Title
::newFromText( $m[1] );
413 // If the title is a redirect to bad special pages or is invalid, return null
414 if ( !$title instanceof Title ||
!$title->isValidRedirectTarget() ) {
423 # ----------------------------------------------------------------------------
425 # ----------------------------------------------------------------------------
428 * Get the prefixed DB key associated with an ID
430 * @param $id \type{\int} the page_id of the article
431 * @return \type{Title} an object representing the article, or NULL
432 * if no such article was found
434 public static function nameOf( $id ) {
435 $dbr = wfGetDB( DB_SLAVE
);
437 $s = $dbr->selectRow(
439 array( 'page_namespace', 'page_title' ),
440 array( 'page_id' => $id ),
443 if ( $s === false ) {
447 $n = self
::makeName( $s->page_namespace
, $s->page_title
);
452 * Get a regex character class describing the legal characters in a link
454 * @return \type{\string} the list of characters, not delimited
456 public static function legalChars() {
457 global $wgLegalTitleChars;
458 return $wgLegalTitleChars;
462 * Get a string representation of a title suitable for
463 * including in a search index
465 * @param $ns \type{\int} a namespace index
466 * @param $title \type{\string} text-form main part
467 * @return \type{\string} a stripped-down title string ready for the
470 public static function indexTitle( $ns, $title ) {
473 $lc = SearchEngine
::legalSearchChars() . '&#;';
474 $t = $wgContLang->normalizeForSearch( $title );
475 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
476 $t = $wgContLang->lc( $t );
479 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
480 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
482 $t = preg_replace( "/\\s+/", ' ', $t );
484 if ( $ns == NS_FILE
) {
485 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
491 * Make a prefixed DB key from a DB key and a namespace index
493 * @param $ns \type{\int} numerical representation of the namespace
494 * @param $title \type{\string} the DB key form the title
495 * @param $fragment \type{\string} The link fragment (after the "#")
496 * @param $interwiki \type{\string} The interwiki prefix
497 * @return \type{\string} the prefixed form of the title
499 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
502 $namespace = $wgContLang->getNsText( $ns );
503 $name = $namespace == '' ?
$title : "$namespace:$title";
504 if ( strval( $interwiki ) != '' ) {
505 $name = "$interwiki:$name";
507 if ( strval( $fragment ) != '' ) {
508 $name .= '#' . $fragment;
514 * Determine whether the object refers to a page within
517 * @return \type{\bool} TRUE if this is an in-project interwiki link
518 * or a wikilink, FALSE otherwise
520 public function isLocal() {
521 if ( $this->mInterwiki
!= '' ) {
522 return Interwiki
::fetch( $this->mInterwiki
)->isLocal();
529 * Determine whether the object refers to a page within
530 * this project and is transcludable.
532 * @return \type{\bool} TRUE if this is transcludable
534 public function isTrans() {
535 if ( $this->mInterwiki
== '' ) {
539 return Interwiki
::fetch( $this->mInterwiki
)->isTranscludable();
543 * Returns the DB name of the distant wiki
544 * which owns the object.
546 * @return \type{\string} the DB name
548 public function getTransWikiID() {
549 if ( $this->mInterwiki
== '' ) {
553 return Interwiki
::fetch( $this->mInterwiki
)->getWikiID();
557 * Escape a text fragment, say from a link, for a URL
559 * @param $fragment string containing a URL or link fragment (after the "#")
560 * @return String: escaped string
562 static function escapeFragmentForURL( $fragment ) {
563 # Note that we don't urlencode the fragment. urlencoded Unicode
564 # fragments appear not to work in IE (at least up to 7) or in at least
565 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
566 # to care if they aren't encoded.
567 return Sanitizer
::escapeId( $fragment, 'noninitial' );
570 # ----------------------------------------------------------------------------
572 # ----------------------------------------------------------------------------
574 /** Simple accessors */
576 * Get the text form (spaces not underscores) of the main part
578 * @return \type{\string} Main part of the title
580 public function getText() { return $this->mTextform
; }
583 * Get the URL-encoded form of the main part
585 * @return \type{\string} Main part of the title, URL-encoded
587 public function getPartialURL() { return $this->mUrlform
; }
590 * Get the main part with underscores
592 * @return \type{\string} Main part of the title, with underscores
594 public function getDBkey() { return $this->mDbkeyform
; }
597 * Get the namespace index, i.e.\ one of the NS_xxxx constants.
599 * @return \type{\int} Namespace index
601 public function getNamespace() { return $this->mNamespace
; }
604 * Get the namespace text
606 * @return \type{\string} Namespace text
608 public function getNsText() {
611 if ( $this->mInterwiki
!= '' ) {
612 // This probably shouldn't even happen. ohh man, oh yuck.
613 // But for interwiki transclusion it sometimes does.
614 // Shit. Shit shit shit.
616 // Use the canonical namespaces if possible to try to
617 // resolve a foreign namespace.
618 if ( MWNamespace
::exists( $this->mNamespace
) ) {
619 return MWNamespace
::getCanonicalName( $this->mNamespace
);
622 return $wgContLang->getNsText( $this->mNamespace
);
626 * Get the DB key with the initial letter case as specified by the user
628 * @return \type{\string} DB key
630 function getUserCaseDBKey() {
631 return $this->mUserCaseDBKey
;
635 * Get the namespace text of the subject (rather than talk) page
637 * @return \type{\string} Namespace text
639 public function getSubjectNsText() {
641 return $wgContLang->getNsText( MWNamespace
::getSubject( $this->mNamespace
) );
645 * Get the namespace text of the talk page
647 * @return \type{\string} Namespace text
649 public function getTalkNsText() {
651 return( $wgContLang->getNsText( MWNamespace
::getTalk( $this->mNamespace
) ) );
655 * Could this title have a corresponding talk page?
657 * @return \type{\bool} TRUE or FALSE
659 public function canTalk() {
660 return( MWNamespace
::canTalk( $this->mNamespace
) );
664 * Get the interwiki prefix (or null string)
666 * @return \type{\string} Interwiki prefix
668 public function getInterwiki() { return $this->mInterwiki
; }
671 * Get the Title fragment (i.e.\ the bit after the #) in text form
673 * @return \type{\string} Title fragment
675 public function getFragment() { return $this->mFragment
; }
678 * Get the fragment in URL form, including the "#" character if there is one
679 * @return \type{\string} Fragment in URL form
681 public function getFragmentForURL() {
682 if ( $this->mFragment
== '' ) {
685 return '#' . Title
::escapeFragmentForURL( $this->mFragment
);
690 * Get the default namespace index, for when there is no namespace
692 * @return \type{\int} Default namespace index
694 public function getDefaultNamespace() { return $this->mDefaultNamespace
; }
697 * Get title for search index
699 * @return \type{\string} a stripped-down title string ready for the
702 public function getIndexTitle() {
703 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
707 * Get the prefixed database key form
709 * @return \type{\string} the prefixed title, with underscores and
710 * any interwiki and namespace prefixes
712 public function getPrefixedDBkey() {
713 $s = $this->prefix( $this->mDbkeyform
);
714 $s = str_replace( ' ', '_', $s );
719 * Get the prefixed title with spaces.
720 * This is the form usually used for display
722 * @return \type{\string} the prefixed title, with spaces
724 public function getPrefixedText() {
725 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
726 $s = $this->prefix( $this->mTextform
);
727 $s = str_replace( '_', ' ', $s );
728 $this->mPrefixedText
= $s;
730 return $this->mPrefixedText
;
734 * Get the prefixed title with spaces, plus any fragment
735 * (part beginning with '#')
737 * @return \type{\string} the prefixed title, with spaces and
738 * the fragment, including '#'
740 public function getFullText() {
741 $text = $this->getPrefixedText();
742 if ( $this->mFragment
!= '' ) {
743 $text .= '#' . $this->mFragment
;
749 * Get the base name, i.e. the leftmost parts before the /
751 * @return \type{\string} Base name
753 public function getBaseText() {
754 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
755 return $this->getText();
758 $parts = explode( '/', $this->getText() );
759 # Don't discard the real title if there's no subpage involved
760 if ( count( $parts ) > 1 ) {
761 unset( $parts[count( $parts ) - 1] );
763 return implode( '/', $parts );
767 * Get the lowest-level subpage name, i.e. the rightmost part after /
769 * @return \type{\string} Subpage name
771 public function getSubpageText() {
772 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
773 return( $this->mTextform
);
775 $parts = explode( '/', $this->mTextform
);
776 return( $parts[count( $parts ) - 1] );
780 * Get a URL-encoded form of the subpage text
782 * @return \type{\string} URL-encoded subpage name
784 public function getSubpageUrlForm() {
785 $text = $this->getSubpageText();
786 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
791 * Get a URL-encoded title (not an actual URL) including interwiki
793 * @return \type{\string} the URL-encoded form
795 public function getPrefixedURL() {
796 $s = $this->prefix( $this->mDbkeyform
);
797 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
802 * Get a real URL referring to this title, with interwiki link and
805 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
806 * links. Can be specified as an associative array as well, e.g.,
807 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
808 * @param $variant \type{\string} language variant of url (for sr, zh..)
809 * @return \type{\string} the URL
811 public function getFullURL( $query = '', $variant = false ) {
812 global $wgServer, $wgRequest;
814 if ( is_array( $query ) ) {
815 $query = wfArrayToCGI( $query );
818 $interwiki = Interwiki
::fetch( $this->mInterwiki
);
820 $url = $this->getLocalURL( $query, $variant );
822 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
823 // Correct fix would be to move the prepending elsewhere.
824 if ( $wgRequest->getVal( 'action' ) != 'render' ) {
825 $url = $wgServer . $url;
828 $baseUrl = $interwiki->getURL();
830 $namespace = wfUrlencode( $this->getNsText() );
831 if ( $namespace != '' ) {
832 # Can this actually happen? Interwikis shouldn't be parsed.
833 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
836 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
837 $url = wfAppendQuery( $url, $query );
840 # Finally, add the fragment.
841 $url .= $this->getFragmentForURL();
843 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
848 * Get a URL with no fragment or server name. If this page is generated
849 * with action=render, $wgServer is prepended.
851 * @param $query Mixed: an optional query string; if not specified,
852 * $wgArticlePath will be used. Can be specified as an associative array
853 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
855 * @param $variant \type{\string} language variant of url (for sr, zh..)
856 * @return \type{\string} the URL
858 public function getLocalURL( $query = '', $variant = false ) {
859 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
860 global $wgVariantArticlePath, $wgContLang, $wgUser;
862 if ( is_array( $query ) ) {
863 $query = wfArrayToCGI( $query );
866 // internal links should point to same variant as current page (only anonymous users)
867 if ( !$variant && $wgContLang->hasVariants() && !$wgUser->isLoggedIn() ) {
868 $pref = $wgContLang->getPreferredVariant( false );
869 if ( $pref != $wgContLang->getCode() ) {
874 if ( $this->isExternal() ) {
875 $url = $this->getFullURL();
877 // This is currently only used for edit section links in the
878 // context of interwiki transclusion. In theory we should
879 // append the query to the end of any existing query string,
880 // but interwiki transclusion is already broken in that case.
884 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
885 if ( $query == '' ) {
886 if ( $variant != false && $wgContLang->hasVariants() ) {
887 if ( !$wgVariantArticlePath ) {
888 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
890 $variantArticlePath = $wgVariantArticlePath;
892 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
893 $url = str_replace( '$1', $dbkey, $url );
895 $url = str_replace( '$1', $dbkey, $wgArticlePath );
898 global $wgActionPaths;
901 if ( !empty( $wgActionPaths ) &&
902 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
904 $action = urldecode( $matches[2] );
905 if ( isset( $wgActionPaths[$action] ) ) {
906 $query = $matches[1];
907 if ( isset( $matches[4] ) ) {
908 $query .= $matches[4];
910 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
911 if ( $query != '' ) {
912 $url = wfAppendQuery( $url, $query );
916 if ( $url === false ) {
917 if ( $query == '-' ) {
920 $url = "{$wgScript}?title={$dbkey}&{$query}";
924 // FIXME: this causes breakage in various places when we
925 // actually expected a local URL and end up with dupe prefixes.
926 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
927 $url = $wgServer . $url;
930 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
935 * Get a URL that's the simplest URL that will be valid to link, locally,
936 * to the current Title. It includes the fragment, but does not include
937 * the server unless action=render is used (or the link is external). If
938 * there's a fragment but the prefixed text is empty, we just return a link
941 * The result obviously should not be URL-escaped, but does need to be
942 * HTML-escaped if it's being output in HTML.
944 * @param $query \type{\arrayof{\string}} An associative array of key => value pairs for the
945 * query string. Keys and values will be escaped.
946 * @param $variant \type{\string} Language variant of URL (for sr, zh..). Ignored
947 * for external links. Default is "false" (same variant as current page,
948 * for anonymous users).
949 * @return \type{\string} the URL
951 public function getLinkUrl( $query = array(), $variant = false ) {
952 wfProfileIn( __METHOD__
);
953 if ( $this->isExternal() ) {
954 $ret = $this->getFullURL( $query );
955 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
956 $ret = $this->getFragmentForURL();
958 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
960 wfProfileOut( __METHOD__
);
965 * Get an HTML-escaped version of the URL form, suitable for
966 * using in a link, without a server name or fragment
968 * @param $query \type{\string} an optional query string
969 * @return \type{\string} the URL
971 public function escapeLocalURL( $query = '' ) {
972 return htmlspecialchars( $this->getLocalURL( $query ) );
976 * Get an HTML-escaped version of the URL form, suitable for
977 * using in a link, including the server name and fragment
979 * @param $query \type{\string} an optional query string
980 * @return \type{\string} the URL
982 public function escapeFullURL( $query = '' ) {
983 return htmlspecialchars( $this->getFullURL( $query ) );
987 * Get the URL form for an internal link.
988 * - Used in various Squid-related code, in case we have a different
989 * internal hostname for the server from the exposed one.
991 * @param $query \type{\string} an optional query string
992 * @param $variant \type{\string} language variant of url (for sr, zh..)
993 * @return \type{\string} the URL
995 public function getInternalURL( $query = '', $variant = false ) {
996 global $wgInternalServer;
997 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
998 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1003 * Get the edit URL for this Title
1005 * @return \type{\string} the URL, or a null string if this is an
1008 public function getEditURL() {
1009 if ( $this->mInterwiki
!= '' ) {
1012 $s = $this->getLocalURL( 'action=edit' );
1018 * Get the HTML-escaped displayable text form.
1019 * Used for the title field in <a> tags.
1021 * @return \type{\string} the text, including any prefixes
1023 public function getEscapedText() {
1024 return htmlspecialchars( $this->getPrefixedText() );
1028 * Is this Title interwiki?
1030 * @return \type{\bool}
1032 public function isExternal() {
1033 return ( $this->mInterwiki
!= '' );
1037 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1039 * @param $action \type{\string} Action to check (default: edit)
1040 * @return \type{\bool}
1042 public function isSemiProtected( $action = 'edit' ) {
1043 if ( $this->exists() ) {
1044 $restrictions = $this->getRestrictions( $action );
1045 if ( count( $restrictions ) > 0 ) {
1046 foreach ( $restrictions as $restriction ) {
1047 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1057 # If it doesn't exist, it can't be protected
1063 * Does the title correspond to a protected article?
1065 * @param $action \type{\string} the action the page is protected from,
1066 * by default checks all actions.
1067 * @return \type{\bool}
1069 public function isProtected( $action = '' ) {
1070 global $wgRestrictionLevels;
1072 $restrictionTypes = $this->getRestrictionTypes();
1074 # Special pages have inherent protection
1075 if( $this->getNamespace() == NS_SPECIAL
) {
1079 # Check regular protection levels
1080 foreach ( $restrictionTypes as $type ) {
1081 if ( $action == $type ||
$action == '' ) {
1082 $r = $this->getRestrictions( $type );
1083 foreach ( $wgRestrictionLevels as $level ) {
1084 if ( in_array( $level, $r ) && $level != '' ) {
1095 * Is this a conversion table for the LanguageConverter?
1097 * @return \type{\bool}
1099 public function isConversionTable() {
1101 $this->getNamespace() == NS_MEDIAWIKI
&&
1102 strpos( $this->getText(), 'Conversiontable' ) !== false
1112 * Is $wgUser watching this page?
1114 * @return \type{\bool}
1116 public function userIsWatching() {
1119 if ( is_null( $this->mWatched
) ) {
1120 if ( NS_SPECIAL
== $this->mNamespace ||
!$wgUser->isLoggedIn() ) {
1121 $this->mWatched
= false;
1123 $this->mWatched
= $wgUser->isWatched( $this );
1126 return $this->mWatched
;
1130 * Can $wgUser perform $action on this page?
1131 * This skips potentially expensive cascading permission checks
1132 * as well as avoids expensive error formatting
1134 * Suitable for use for nonessential UI controls in common cases, but
1135 * _not_ for functional access control.
1137 * May provide false positives, but should never provide a false negative.
1139 * @param $action \type{\string} action that permission needs to be checked for
1140 * @return \type{\bool}
1142 public function quickUserCan( $action ) {
1143 return $this->userCan( $action, false );
1147 * Determines if $wgUser is unable to edit this page because it has been protected
1148 * by $wgNamespaceProtection.
1150 * @return \type{\bool}
1152 public function isNamespaceProtected() {
1153 global $wgNamespaceProtection, $wgUser;
1154 if ( isset( $wgNamespaceProtection[$this->mNamespace
] ) ) {
1155 foreach ( (array)$wgNamespaceProtection[$this->mNamespace
] as $right ) {
1156 if ( $right != '' && !$wgUser->isAllowed( $right ) ) {
1165 * Can $wgUser perform $action on this page?
1167 * @param $action \type{\string} action that permission needs to be checked for
1168 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1169 * @return \type{\bool}
1171 public function userCan( $action, $doExpensiveQueries = true ) {
1173 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1177 * Can $user perform $action on this page?
1179 * FIXME: This *does not* check throttles (User::pingLimiter()).
1181 * @param $action \type{\string}action that permission needs to be checked for
1182 * @param $user \type{User} user to check
1183 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1184 * @param $ignoreErrors \type{\arrayof{\string}} Set this to a list of message keys whose corresponding errors may be ignored.
1185 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1187 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1188 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1190 // Remove the errors being ignored.
1191 foreach ( $errors as $index => $error ) {
1192 $error_key = is_array( $error ) ?
$error[0] : $error;
1194 if ( in_array( $error_key, $ignoreErrors ) ) {
1195 unset( $errors[$index] );
1203 * Permissions checks that fail most often, and which are easiest to test.
1205 * @param $action String the action to check
1206 * @param $user User user to check
1207 * @param $errors Array list of current errors
1208 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1209 * @param $short Boolean short circuit on first error
1211 * @return Array list of errors
1213 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1214 if ( $action == 'create' ) {
1215 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1216 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1217 $errors[] = $user->isAnon() ?
array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1219 } elseif ( $action == 'move' ) {
1220 if ( !$user->isAllowed( 'move-rootuserpages' )
1221 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1222 // Show user page-specific message only if the user can move other pages
1223 $errors[] = array( 'cant-move-user-page' );
1226 // Check if user is allowed to move files if it's a file
1227 if ( $this->mNamespace
== NS_FILE
&& !$user->isAllowed( 'movefile' ) ) {
1228 $errors[] = array( 'movenotallowedfile' );
1231 if ( !$user->isAllowed( 'move' ) ) {
1232 // User can't move anything
1233 global $wgGroupPermissions;
1234 $userCanMove = false;
1235 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1236 $userCanMove = $wgGroupPermissions['user']['move'];
1238 $autoconfirmedCanMove = false;
1239 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1240 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1242 if ( $user->isAnon() && ( $userCanMove ||
$autoconfirmedCanMove ) ) {
1243 // custom message if logged-in users without any special rights can move
1244 $errors[] = array( 'movenologintext' );
1246 $errors[] = array( 'movenotallowed' );
1249 } elseif ( $action == 'move-target' ) {
1250 if ( !$user->isAllowed( 'move' ) ) {
1251 // User can't move anything
1252 $errors[] = array( 'movenotallowed' );
1253 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1254 && $this->mNamespace
== NS_USER
&& !$this->isSubpage() ) {
1255 // Show user page-specific message only if the user can move other pages
1256 $errors[] = array( 'cant-move-to-user-page' );
1258 } elseif ( !$user->isAllowed( $action ) ) {
1259 // We avoid expensive display logic for quickUserCan's and such
1262 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1263 User
::getGroupsWithPermission( $action ) );
1270 $wgLang->commaList( $groups ),
1274 $return = array( 'badaccess-group0' );
1276 $errors[] = $return;
1283 * Add the resulting error code to the errors array
1285 * @param $errors Array list of current errors
1286 * @param $result Mixed result of errors
1288 * @return Array list of errors
1290 private function resultToError( $errors, $result ) {
1291 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1292 // A single array representing an error
1293 $errors[] = $result;
1294 } else if ( is_array( $result ) && is_array( $result[0] ) ) {
1295 // A nested array representing multiple errors
1296 $errors = array_merge( $errors, $result );
1297 } else if ( $result !== '' && is_string( $result ) ) {
1298 // A string representing a message-id
1299 $errors[] = array( $result );
1300 } else if ( $result === false ) {
1301 // a generic "We don't want them to do that"
1302 $errors[] = array( 'badaccess-group0' );
1308 * Check various permission hooks
1309 * @see checkQuickPermissions for parameter information
1311 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1312 // Use getUserPermissionsErrors instead
1314 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1315 return $result ?
array() : array( array( 'badaccess-group0' ) );
1317 // Check getUserPermissionsErrors hook
1318 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1319 $errors = $this->resultToError( $errors, $result );
1321 // Check getUserPermissionsErrorsExpensive hook
1322 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1323 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1324 $errors = $this->resultToError( $errors, $result );
1331 * Check permissions on special pages & namespaces
1332 * @see checkQuickPermissions for parameter information
1334 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1335 # Only 'createaccount' and 'execute' can be performed on
1336 # special pages, which don't actually exist in the DB.
1337 $specialOKActions = array( 'createaccount', 'execute' );
1338 if ( NS_SPECIAL
== $this->mNamespace
&& !in_array( $action, $specialOKActions ) ) {
1339 $errors[] = array( 'ns-specialprotected' );
1342 # Check $wgNamespaceProtection for restricted namespaces
1343 if ( $this->isNamespaceProtected() ) {
1344 $ns = $this->mNamespace
== NS_MAIN ?
1345 wfMsg( 'nstab-main' ) : $this->getNsText();
1346 $errors[] = $this->mNamespace
== NS_MEDIAWIKI ?
1347 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1354 * Check CSS/JS sub-page permissions
1355 * @see checkQuickPermissions for parameter information
1357 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1358 # Protect css/js subpages of user pages
1359 # XXX: this might be better using restrictions
1360 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1361 # and $this->userCanEditJsSubpage() from working
1362 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1363 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1364 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform
) ) {
1365 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1366 $errors[] = array( 'customcssjsprotected' );
1367 } else if ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1368 $errors[] = array( 'customcssjsprotected' );
1376 * Check against page_restrictions table requirements on this
1377 * page. The user must possess all required rights for this
1379 * @see checkQuickPermissions for parameter information
1381 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1382 foreach ( $this->getRestrictions( $action ) as $right ) {
1383 // Backwards compatibility, rewrite sysop -> protect
1384 if ( $right == 'sysop' ) {
1387 if ( $right != '' && !$user->isAllowed( $right ) ) {
1388 // Users with 'editprotected' permission can edit protected pages
1389 if ( $action == 'edit' && $user->isAllowed( 'editprotected' ) ) {
1390 // Users with 'editprotected' permission cannot edit protected pages
1391 // with cascading option turned on.
1392 if ( $this->mCascadeRestriction
) {
1393 $errors[] = array( 'protectedpagetext', $right );
1396 $errors[] = array( 'protectedpagetext', $right );
1405 * Check restrictions on cascading pages.
1406 * @see checkQuickPermissions for parameter information
1408 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1409 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1410 # We /could/ use the protection level on the source page, but it's
1411 # fairly ugly as we have to establish a precedence hierarchy for pages
1412 # included by multiple cascade-protected pages. So just restrict
1413 # it to people with 'protect' permission, as they could remove the
1414 # protection anyway.
1415 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1416 # Cascading protection depends on more than this page...
1417 # Several cascading protected pages may include this page...
1418 # Check each cascading level
1419 # This is only for protection restrictions, not for all actions
1420 if ( isset( $restrictions[$action] ) ) {
1421 foreach ( $restrictions[$action] as $right ) {
1422 $right = ( $right == 'sysop' ) ?
'protect' : $right;
1423 if ( $right != '' && !$user->isAllowed( $right ) ) {
1425 foreach ( $cascadingSources as $page )
1426 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1427 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1437 * Check action permissions not already checked in checkQuickPermissions
1438 * @see checkQuickPermissions for parameter information
1440 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1441 if ( $action == 'protect' ) {
1442 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1443 // If they can't edit, they shouldn't protect.
1444 $errors[] = array( 'protect-cantedit' );
1446 } elseif ( $action == 'create' ) {
1447 $title_protection = $this->getTitleProtection();
1448 if( $title_protection ) {
1449 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1450 $title_protection['pt_create_perm'] = 'protect'; // B/C
1452 if( $title_protection['pt_create_perm'] == '' ||
!$user->isAllowed( $title_protection['pt_create_perm'] ) ) {
1453 $errors[] = array( 'titleprotected', User
::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1456 } elseif ( $action == 'move' ) {
1457 // Check for immobile pages
1458 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1459 // Specific message for this case
1460 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1461 } elseif ( !$this->isMovable() ) {
1462 // Less specific message for rarer cases
1463 $errors[] = array( 'immobile-page' );
1465 } elseif ( $action == 'move-target' ) {
1466 if ( !MWNamespace
::isMovable( $this->mNamespace
) ) {
1467 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1468 } elseif ( !$this->isMovable() ) {
1469 $errors[] = array( 'immobile-target-page' );
1476 * Check that the user isn't blocked from editting.
1477 * @see checkQuickPermissions for parameter information
1479 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1484 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1486 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1487 $errors[] = array( 'confirmedittext' );
1490 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1491 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1492 $block = $user->mBlock
;
1494 // This is from OutputPage::blockedPage
1495 // Copied at r23888 by werdna
1497 $id = $user->blockedBy();
1498 $reason = $user->blockedFor();
1499 if ( $reason == '' ) {
1500 $reason = wfMsg( 'blockednoreason' );
1504 if ( is_numeric( $id ) ) {
1505 $name = User
::whoIs( $id );
1510 $link = '[[' . $wgContLang->getNsText( NS_USER
) . ":{$name}|{$name}]]";
1511 $blockid = $block->mId
;
1512 $blockExpiry = $user->mBlock
->mExpiry
;
1513 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW
, $user->mBlock
->mTimestamp
), true );
1514 if ( $blockExpiry == 'infinity' ) {
1515 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1516 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1518 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1519 if ( !strpos( $option, ':' ) )
1522 list( $show, $value ) = explode( ':', $option );
1524 if ( $value == 'infinite' ||
$value == 'indefinite' ) {
1525 $blockExpiry = $show;
1530 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW
, $blockExpiry ), true );
1533 $intended = $user->mBlock
->mAddress
;
1535 $errors[] = array( ( $block->mAuto ?
'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1536 $blockid, $blockExpiry, $intended, $blockTimestamp );
1543 * Can $user perform $action on this page? This is an internal function,
1544 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1545 * checks on wfReadOnly() and blocks)
1547 * @param $action \type{\string} action that permission needs to be checked for
1548 * @param $user \type{User} user to check
1549 * @param $doExpensiveQueries \type{\bool} Set this to false to avoid doing unnecessary queries.
1550 * @param $short \type{\bool} Set this to true to stop after the first permission error.
1551 * @return \type{\array} Array of arrays of the arguments to wfMsg to explain permissions problems.
1553 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1554 wfProfileIn( __METHOD__
);
1558 'checkQuickPermissions',
1559 'checkPermissionHooks',
1560 'checkSpecialsAndNSPermissions',
1561 'checkCSSandJSPermissions',
1562 'checkPageRestrictions',
1563 'checkCascadingSourcesRestrictions',
1564 'checkActionPermissions',
1568 while( count( $checks ) > 0 &&
1569 !( $short && count( $errors ) > 0 ) ) {
1570 $method = array_shift( $checks );
1571 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1574 wfProfileOut( __METHOD__
);
1579 * Is this title subject to title protection?
1581 * @return \type{\mixed} An associative array representing any existent title
1582 * protection, or false if there's none.
1584 private function getTitleProtection() {
1585 // Can't protect pages in special namespaces
1586 if ( $this->getNamespace() < 0 ) {
1590 // Can't protect pages that exist.
1591 if ( $this->exists() ) {
1595 if ( !isset( $this->mTitleProtection
) ) {
1596 $dbr = wfGetDB( DB_SLAVE
);
1597 $res = $dbr->select( 'protected_titles', '*',
1598 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1601 // fetchRow returns false if there are no rows.
1602 $this->mTitleProtection
= $dbr->fetchRow( $res );
1604 return $this->mTitleProtection
;
1608 * Update the title protection status
1610 * @param $create_perm \type{\string} Permission required for creation
1611 * @param $reason \type{\string} Reason for protection
1612 * @param $expiry \type{\string} Expiry timestamp
1613 * @return boolean true
1615 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1616 global $wgUser, $wgContLang;
1618 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1619 && $expiry == $this->mRestrictionsExpiry
['create'] ) {
1624 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1626 $dbw = wfGetDB( DB_MASTER
);
1628 $encodedExpiry = Block
::encodeExpiry( $expiry, $dbw );
1630 $expiry_description = '';
1631 if ( $encodedExpiry != 'infinity' ) {
1632 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1633 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1635 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1638 # Update protection table
1639 if ( $create_perm != '' ) {
1640 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1642 'pt_namespace' => $namespace,
1643 'pt_title' => $title,
1644 'pt_create_perm' => $create_perm,
1645 'pt_timestamp' => Block
::encodeExpiry( wfTimestampNow(), $dbw ),
1646 'pt_expiry' => $encodedExpiry,
1647 'pt_user' => $wgUser->getId(),
1648 'pt_reason' => $reason,
1652 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1653 'pt_title' => $title ), __METHOD__
);
1655 # Update the protection log
1656 if ( $dbw->affectedRows() ) {
1657 $log = new LogPage( 'protect' );
1659 if ( $create_perm ) {
1660 $params = array( "[create=$create_perm] $expiry_description", '' );
1661 $log->addEntry( ( isset( $this->mRestrictions
['create'] ) && $this->mRestrictions
['create'] ) ?
'modify' : 'protect', $this, trim( $reason ), $params );
1663 $log->addEntry( 'unprotect', $this, $reason );
1671 * Remove any title protection due to page existing
1673 public function deleteTitleProtection() {
1674 $dbw = wfGetDB( DB_MASTER
);
1678 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1684 * Would anybody with sufficient privileges be able to move this page?
1685 * Some pages just aren't movable.
1687 * @return \type{\bool} TRUE or FALSE
1689 public function isMovable() {
1690 return MWNamespace
::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1694 * Can $wgUser read this page?
1696 * @return \type{\bool}
1697 * @todo fold these checks into userCan()
1699 public function userCanRead() {
1700 global $wgUser, $wgGroupPermissions;
1702 static $useShortcut = null;
1704 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1705 if ( is_null( $useShortcut ) ) {
1706 global $wgRevokePermissions;
1707 $useShortcut = true;
1708 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1709 # Not a public wiki, so no shortcut
1710 $useShortcut = false;
1711 } elseif ( !empty( $wgRevokePermissions ) ) {
1713 * Iterate through each group with permissions being revoked (key not included since we don't care
1714 * what the group name is), then check if the read permission is being revoked. If it is, then
1715 * we don't use the shortcut below since the user might not be able to read, even though anon
1716 * reading is allowed.
1718 foreach ( $wgRevokePermissions as $perms ) {
1719 if ( !empty( $perms['read'] ) ) {
1720 # We might be removing the read right from the user, so no shortcut
1721 $useShortcut = false;
1729 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1730 if ( $result !== null ) {
1734 # Shortcut for public wikis, allows skipping quite a bit of code
1735 if ( $useShortcut ) {
1739 if ( $wgUser->isAllowed( 'read' ) ) {
1742 global $wgWhitelistRead;
1745 * Always grant access to the login page.
1746 * Even anons need to be able to log in.
1748 if ( $this->isSpecial( 'Userlogin' ) ||
$this->isSpecial( 'Resetpass' ) ) {
1753 * Bail out if there isn't whitelist
1755 if ( !is_array( $wgWhitelistRead ) ) {
1760 * Check for explicit whitelisting
1762 $name = $this->getPrefixedText();
1763 $dbName = $this->getPrefixedDBKey();
1764 // Check with and without underscores
1765 if ( in_array( $name, $wgWhitelistRead, true ) ||
in_array( $dbName, $wgWhitelistRead, true ) )
1769 * Old settings might have the title prefixed with
1770 * a colon for main-namespace pages
1772 if ( $this->getNamespace() == NS_MAIN
) {
1773 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1779 * If it's a special page, ditch the subpage bit
1782 if ( $this->getNamespace() == NS_SPECIAL
) {
1783 $name = $this->getDBkey();
1784 list( $name, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $name );
1785 if ( $name === false ) {
1786 # Invalid special page, but we show standard login required message
1790 $pure = SpecialPage
::getTitleFor( $name )->getPrefixedText();
1791 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1801 * Is this a talk page of some sort?
1803 * @return \type{\bool}
1805 public function isTalkPage() {
1806 return MWNamespace
::isTalk( $this->getNamespace() );
1810 * Is this a subpage?
1812 * @return \type{\bool}
1814 public function isSubpage() {
1815 return MWNamespace
::hasSubpages( $this->mNamespace
)
1816 ?
strpos( $this->getText(), '/' ) !== false
1821 * Does this have subpages? (Warning, usually requires an extra DB query.)
1823 * @return \type{\bool}
1825 public function hasSubpages() {
1826 if ( !MWNamespace
::hasSubpages( $this->mNamespace
) ) {
1831 # We dynamically add a member variable for the purpose of this method
1832 # alone to cache the result. There's no point in having it hanging
1833 # around uninitialized in every Title object; therefore we only add it
1834 # if needed and don't declare it statically.
1835 if ( isset( $this->mHasSubpages
) ) {
1836 return $this->mHasSubpages
;
1839 $subpages = $this->getSubpages( 1 );
1840 if ( $subpages instanceof TitleArray
) {
1841 return $this->mHasSubpages
= (bool)$subpages->count();
1843 return $this->mHasSubpages
= false;
1847 * Get all subpages of this page.
1849 * @param $limit Maximum number of subpages to fetch; -1 for no limit
1850 * @return mixed TitleArray, or empty array if this page's namespace
1851 * doesn't allow subpages
1853 public function getSubpages( $limit = -1 ) {
1854 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
1858 $dbr = wfGetDB( DB_SLAVE
);
1859 $conds['page_namespace'] = $this->getNamespace();
1860 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1862 if ( $limit > -1 ) {
1863 $options['LIMIT'] = $limit;
1865 return $this->mSubpages
= TitleArray
::newFromResult(
1866 $dbr->select( 'page',
1867 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1876 * Could this page contain custom CSS or JavaScript, based
1879 * @return \type{\bool}
1881 public function isCssOrJsPage() {
1882 return $this->mNamespace
== NS_MEDIAWIKI
1883 && preg_match( '!\.(?:css|js)$!u', $this->mTextform
) > 0;
1887 * Is this a .css or .js subpage of a user page?
1888 * @return \type{\bool}
1890 public function isCssJsSubpage() {
1891 return ( NS_USER
== $this->mNamespace
and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform
) );
1895 * Is this a *valid* .css or .js subpage of a user page?
1896 * Check that the corresponding skin exists
1898 * @return \type{\bool}
1900 public function isValidCssJsSubpage() {
1901 if ( $this->isCssJsSubpage() ) {
1902 $name = $this->getSkinFromCssJsSubpage();
1903 if ( $name == 'common' ) {
1906 $skinNames = Skin
::getSkinNames();
1907 return array_key_exists( $name, $skinNames );
1914 * Trim down a .css or .js subpage title to get the corresponding skin name
1916 * @return string containing skin name from .css or .js subpage title
1918 public function getSkinFromCssJsSubpage() {
1919 $subpage = explode( '/', $this->mTextform
);
1920 $subpage = $subpage[ count( $subpage ) - 1 ];
1921 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1925 * Is this a .css subpage of a user page?
1927 * @return \type{\bool}
1929 public function isCssSubpage() {
1930 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.css$/", $this->mTextform
) );
1934 * Is this a .js subpage of a user page?
1936 * @return \type{\bool}
1938 public function isJsSubpage() {
1939 return ( NS_USER
== $this->mNamespace
&& preg_match( "/\\/.*\\.js$/", $this->mTextform
) );
1943 * Protect css subpages of user pages: can $wgUser edit
1946 * @return \type{\bool}
1947 * @todo XXX: this might be better using restrictions
1949 public function userCanEditCssSubpage() {
1951 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'editusercss' ) )
1952 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
1956 * Protect js subpages of user pages: can $wgUser edit
1959 * @return \type{\bool}
1960 * @todo XXX: this might be better using restrictions
1962 public function userCanEditJsSubpage() {
1964 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'edituserjs' ) )
1965 ||
preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform
) );
1969 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1971 * @return \type{\bool} If the page is subject to cascading restrictions.
1973 public function isCascadeProtected() {
1974 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
1975 return ( $sources > 0 );
1979 * Cascading protection: Get the source of any cascading restrictions on this page.
1981 * @param $getPages \type{\bool} Whether or not to retrieve the actual pages
1982 * that the restrictions have come from.
1983 * @return \type{\arrayof{mixed title array, restriction array}} Array of the Title
1984 * objects of the pages from which cascading restrictions have come,
1985 * false for none, or true if such restrictions exist, but $getPages was not set.
1986 * The restriction array is an array of each type, each of which contains a
1987 * array of unique groups.
1989 public function getCascadeProtectionSources( $getPages = true ) {
1990 $pagerestrictions = array();
1992 if ( isset( $this->mCascadeSources
) && $getPages ) {
1993 return array( $this->mCascadeSources
, $this->mCascadingRestrictions
);
1994 } else if ( isset( $this->mHasCascadingRestrictions
) && !$getPages ) {
1995 return array( $this->mHasCascadingRestrictions
, $pagerestrictions );
1998 wfProfileIn( __METHOD__
);
2000 $dbr = wfGetDB( DB_SLAVE
);
2002 if ( $this->getNamespace() == NS_FILE
) {
2003 $tables = array( 'imagelinks', 'page_restrictions' );
2004 $where_clauses = array(
2005 'il_to' => $this->getDBkey(),
2010 $tables = array( 'templatelinks', 'page_restrictions' );
2011 $where_clauses = array(
2012 'tl_namespace' => $this->getNamespace(),
2013 'tl_title' => $this->getDBkey(),
2020 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2021 'pr_expiry', 'pr_type', 'pr_level' );
2022 $where_clauses[] = 'page_id=pr_page';
2025 $cols = array( 'pr_expiry' );
2028 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__
);
2030 $sources = $getPages ?
array() : false;
2031 $now = wfTimestampNow();
2032 $purgeExpired = false;
2034 foreach ( $res as $row ) {
2035 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
2036 if ( $expiry > $now ) {
2038 $page_id = $row->pr_page
;
2039 $page_ns = $row->page_namespace
;
2040 $page_title = $row->page_title
;
2041 $sources[$page_id] = Title
::makeTitle( $page_ns, $page_title );
2042 # Add groups needed for each restriction type if its not already there
2043 # Make sure this restriction type still exists
2045 if ( !isset( $pagerestrictions[$row->pr_type
] ) ) {
2046 $pagerestrictions[$row->pr_type
] = array();
2049 if ( isset( $pagerestrictions[$row->pr_type
] ) &&
2050 !in_array( $row->pr_level
, $pagerestrictions[$row->pr_type
] ) ) {
2051 $pagerestrictions[$row->pr_type
][] = $row->pr_level
;
2057 // Trigger lazy purge of expired restrictions from the db
2058 $purgeExpired = true;
2061 if ( $purgeExpired ) {
2062 Title
::purgeExpiredRestrictions();
2065 wfProfileOut( __METHOD__
);
2068 $this->mCascadeSources
= $sources;
2069 $this->mCascadingRestrictions
= $pagerestrictions;
2071 $this->mHasCascadingRestrictions
= $sources;
2074 return array( $sources, $pagerestrictions );
2078 * Returns cascading restrictions for the current article
2082 function areRestrictionsCascading() {
2083 if ( !$this->mRestrictionsLoaded
) {
2084 $this->loadRestrictions();
2087 return $this->mCascadeRestriction
;
2091 * Loads a string into mRestrictions array
2093 * @param $res \type{Resource} restrictions as an SQL result.
2094 * @param $oldFashionedRestrictions string comma-separated list of page
2095 * restrictions from page table (pre 1.10)
2097 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2100 foreach ( $res as $row ) {
2104 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2108 * Compiles list of active page restrictions from both page table (pre 1.10)
2109 * and page_restrictions table
2111 * @param $rows array of db result objects
2112 * @param $oldFashionedRestrictions string comma-separated list of page
2113 * restrictions from page table (pre 1.10)
2115 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2116 $dbr = wfGetDB( DB_SLAVE
);
2118 $restrictionTypes = $this->getRestrictionTypes();
2120 foreach ( $restrictionTypes as $type ) {
2121 $this->mRestrictions
[$type] = array();
2122 $this->mRestrictionsExpiry
[$type] = Block
::decodeExpiry( '' );
2125 $this->mCascadeRestriction
= false;
2127 # Backwards-compatibility: also load the restrictions from the page record (old format).
2129 if ( $oldFashionedRestrictions === null ) {
2130 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2131 array( 'page_id' => $this->getArticleId() ), __METHOD__
);
2134 if ( $oldFashionedRestrictions != '' ) {
2136 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2137 $temp = explode( '=', trim( $restrict ) );
2138 if ( count( $temp ) == 1 ) {
2139 // old old format should be treated as edit/move restriction
2140 $this->mRestrictions
['edit'] = explode( ',', trim( $temp[0] ) );
2141 $this->mRestrictions
['move'] = explode( ',', trim( $temp[0] ) );
2143 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
2147 $this->mOldRestrictions
= true;
2151 if ( count( $rows ) ) {
2152 # Current system - load second to make them override.
2153 $now = wfTimestampNow();
2154 $purgeExpired = false;
2156 foreach ( $rows as $row ) {
2157 # Cycle through all the restrictions.
2159 // Don't take care of restrictions types that aren't allowed
2161 if ( !in_array( $row->pr_type
, $restrictionTypes ) )
2164 // This code should be refactored, now that it's being used more generally,
2165 // But I don't really see any harm in leaving it in Block for now -werdna
2166 $expiry = Block
::decodeExpiry( $row->pr_expiry
);
2168 // Only apply the restrictions if they haven't expired!
2169 if ( !$expiry ||
$expiry > $now ) {
2170 $this->mRestrictionsExpiry
[$row->pr_type
] = $expiry;
2171 $this->mRestrictions
[$row->pr_type
] = explode( ',', trim( $row->pr_level
) );
2173 $this->mCascadeRestriction |
= $row->pr_cascade
;
2175 // Trigger a lazy purge of expired restrictions
2176 $purgeExpired = true;
2180 if ( $purgeExpired ) {
2181 Title
::purgeExpiredRestrictions();
2185 $this->mRestrictionsLoaded
= true;
2189 * Load restrictions from the page_restrictions table
2191 * @param $oldFashionedRestrictions string comma-separated list of page
2192 * restrictions from page table (pre 1.10)
2194 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2195 if ( !$this->mRestrictionsLoaded
) {
2196 if ( $this->exists() ) {
2197 $dbr = wfGetDB( DB_SLAVE
);
2199 $res = $dbr->select( 'page_restrictions', '*',
2200 array( 'pr_page' => $this->getArticleId() ), __METHOD__
);
2202 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2204 $title_protection = $this->getTitleProtection();
2206 if ( $title_protection ) {
2207 $now = wfTimestampNow();
2208 $expiry = Block
::decodeExpiry( $title_protection['pt_expiry'] );
2210 if ( !$expiry ||
$expiry > $now ) {
2211 // Apply the restrictions
2212 $this->mRestrictionsExpiry
['create'] = $expiry;
2213 $this->mRestrictions
['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2214 } else { // Get rid of the old restrictions
2215 Title
::purgeExpiredRestrictions();
2218 $this->mRestrictionsExpiry
['create'] = Block
::decodeExpiry( '' );
2220 $this->mRestrictionsLoaded
= true;
2226 * Purge expired restrictions from the page_restrictions table
2228 static function purgeExpiredRestrictions() {
2229 $dbw = wfGetDB( DB_MASTER
);
2231 'page_restrictions',
2232 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2238 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2244 * Accessor/initialisation for mRestrictions
2246 * @param $action \type{\string} action that permission needs to be checked for
2247 * @return \type{\arrayof{\string}} the array of groups allowed to edit this article
2249 public function getRestrictions( $action ) {
2250 if ( !$this->mRestrictionsLoaded
) {
2251 $this->loadRestrictions();
2253 return isset( $this->mRestrictions
[$action] )
2254 ?
$this->mRestrictions
[$action]
2259 * Get the expiry time for the restriction against a given action
2261 * @return 14-char timestamp, or 'infinity' if the page is protected forever
2262 * or not protected at all, or false if the action is not recognised.
2264 public function getRestrictionExpiry( $action ) {
2265 if ( !$this->mRestrictionsLoaded
) {
2266 $this->loadRestrictions();
2268 return isset( $this->mRestrictionsExpiry
[$action] ) ?
$this->mRestrictionsExpiry
[$action] : false;
2272 * Is there a version of this page in the deletion archive?
2274 * @return \type{\int} the number of archived revisions
2276 public function isDeleted() {
2277 if ( $this->getNamespace() < 0 ) {
2280 $dbr = wfGetDB( DB_SLAVE
);
2281 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2282 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2285 if ( $this->getNamespace() == NS_FILE
) {
2286 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
2287 array( 'fa_name' => $this->getDBkey() ),
2296 * Is there a version of this page in the deletion archive?
2300 public function isDeletedQuick() {
2301 if ( $this->getNamespace() < 0 ) {
2304 $dbr = wfGetDB( DB_SLAVE
);
2305 $deleted = (bool)$dbr->selectField( 'archive', '1',
2306 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2309 if ( !$deleted && $this->getNamespace() == NS_FILE
) {
2310 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2311 array( 'fa_name' => $this->getDBkey() ),
2319 * Get the article ID for this Title from the link cache,
2320 * adding it if necessary
2322 * @param $flags \type{\int} a bit field; may be Title::GAID_FOR_UPDATE to select
2324 * @return \type{\int} the ID
2326 public function getArticleID( $flags = 0 ) {
2327 if ( $this->getNamespace() < 0 ) {
2328 return $this->mArticleID
= 0;
2330 $linkCache = LinkCache
::singleton();
2331 if ( $flags & self
::GAID_FOR_UPDATE
) {
2332 $oldUpdate = $linkCache->forUpdate( true );
2333 $linkCache->clearLink( $this );
2334 $this->mArticleID
= $linkCache->addLinkObj( $this );
2335 $linkCache->forUpdate( $oldUpdate );
2337 if ( -1 == $this->mArticleID
) {
2338 $this->mArticleID
= $linkCache->addLinkObj( $this );
2341 return $this->mArticleID
;
2345 * Is this an article that is a redirect page?
2346 * Uses link cache, adding it if necessary
2348 * @param $flags \type{\int} a bit field; may be Title::GAID_FOR_UPDATE to select for update
2349 * @return \type{\bool}
2351 public function isRedirect( $flags = 0 ) {
2352 if ( !is_null( $this->mRedirect
) ) {
2353 return $this->mRedirect
;
2355 # Calling getArticleID() loads the field from cache as needed
2356 if ( !$this->getArticleID( $flags ) ) {
2357 return $this->mRedirect
= false;
2359 $linkCache = LinkCache
::singleton();
2360 $this->mRedirect
= (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2362 return $this->mRedirect
;
2366 * What is the length of this page?
2367 * Uses link cache, adding it if necessary
2369 * @param $flags \type{\int} a bit field; may be Title::GAID_FOR_UPDATE to select for update
2370 * @return \type{\bool}
2372 public function getLength( $flags = 0 ) {
2373 if ( $this->mLength
!= -1 ) {
2374 return $this->mLength
;
2376 # Calling getArticleID() loads the field from cache as needed
2377 if ( !$this->getArticleID( $flags ) ) {
2378 return $this->mLength
= 0;
2380 $linkCache = LinkCache
::singleton();
2381 $this->mLength
= intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2383 return $this->mLength
;
2387 * What is the page_latest field for this page?
2389 * @param $flags \type{\int} a bit field; may be Title::GAID_FOR_UPDATE to select for update
2390 * @return \type{\int} or 0 if the page doesn't exist
2392 public function getLatestRevID( $flags = 0 ) {
2393 if ( $this->mLatestID
!== false ) {
2394 return intval( $this->mLatestID
);
2396 # Calling getArticleID() loads the field from cache as needed
2397 if ( !$this->getArticleID( $flags ) ) {
2398 return $this->mLatestID
= 0;
2400 $linkCache = LinkCache
::singleton();
2401 $this->mLatestID
= intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2403 return $this->mLatestID
;
2407 * This clears some fields in this object, and clears any associated
2408 * keys in the "bad links" section of the link cache.
2410 * - This is called from Article::insertNewArticle() to allow
2411 * loading of the new page_id. It's also called from
2412 * Article::doDeleteArticle()
2414 * @param $newid \type{\int} the new Article ID
2416 public function resetArticleID( $newid ) {
2417 $linkCache = LinkCache
::singleton();
2418 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2420 if ( $newid === false ) {
2421 $this->mArticleID
= -1;
2423 $this->mArticleID
= intval( $newid );
2425 $this->mRestrictionsLoaded
= false;
2426 $this->mRestrictions
= array();
2427 $this->mRedirect
= null;
2428 $this->mLength
= -1;
2429 $this->mLatestID
= false;
2433 * Updates page_touched for this page; called from LinksUpdate.php
2435 * @return \type{\bool} true if the update succeded
2437 public function invalidateCache() {
2438 if ( wfReadOnly() ) {
2441 $dbw = wfGetDB( DB_MASTER
);
2442 $success = $dbw->update(
2444 array( 'page_touched' => $dbw->timestamp() ),
2448 HTMLFileCache
::clearFileCache( $this );
2453 * Prefix some arbitrary text with the namespace or interwiki prefix
2456 * @param $name \type{\string} the text
2457 * @return \type{\string} the prefixed text
2460 /* private */ function prefix( $name ) {
2462 if ( $this->mInterwiki
!= '' ) {
2463 $p = $this->mInterwiki
. ':';
2465 if ( 0 != $this->mNamespace
) {
2466 $p .= $this->getNsText() . ':';
2472 * Returns a simple regex that will match on characters and sequences invalid in titles.
2473 * Note that this doesn't pick up many things that could be wrong with titles, but that
2474 * replacing this regex with something valid will make many titles valid.
2476 * @return string regex string
2478 static function getTitleInvalidRegex() {
2479 static $rxTc = false;
2481 # Matching titles will be held as illegal.
2483 # Any character not allowed is forbidden...
2484 '[^' . Title
::legalChars() . ']' .
2485 # URL percent encoding sequences interfere with the ability
2486 # to round-trip titles -- you can't link to them consistently.
2487 '|%[0-9A-Fa-f]{2}' .
2488 # XML/HTML character references produce similar issues.
2489 '|&[A-Za-z0-9\x80-\xff]+;' .
2491 '|&#x[0-9A-Fa-f]+;' .
2499 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2501 * @param $text string containing title to capitalize
2502 * @param $ns int namespace index, defaults to NS_MAIN
2503 * @return String containing capitalized title
2505 public static function capitalize( $text, $ns = NS_MAIN
) {
2508 if ( MWNamespace
::isCapitalized( $ns ) ) {
2509 return $wgContLang->ucfirst( $text );
2516 * Secure and split - main initialisation function for this object
2518 * Assumes that mDbkeyform has been set, and is urldecoded
2519 * and uses underscores, but not otherwise munged. This function
2520 * removes illegal characters, splits off the interwiki and
2521 * namespace prefixes, sets the other forms, and canonicalizes
2524 * @return \type{\bool} true on success
2526 private function secureAndSplit() {
2527 global $wgContLang, $wgLocalInterwiki;
2530 $rxTc = self
::getTitleInvalidRegex();
2532 $this->mInterwiki
= $this->mFragment
= '';
2533 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
2535 $dbkey = $this->mDbkeyform
;
2537 # Strip Unicode bidi override characters.
2538 # Sometimes they slip into cut-n-pasted page titles, where the
2539 # override chars get included in list displays.
2540 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2542 # Clean up whitespace
2543 # Note: use of the /u option on preg_replace here will cause
2544 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2545 # conveniently disabling them.
2547 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2548 $dbkey = trim( $dbkey, '_' );
2550 if ( $dbkey == '' ) {
2554 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT
) ) {
2555 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2559 $this->mDbkeyform
= $dbkey;
2561 # Initial colon indicates main namespace rather than specified default
2562 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2563 if ( ':' == $dbkey { 0 } ) {
2564 $this->mNamespace
= NS_MAIN
;
2565 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2566 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2569 # Namespace or interwiki prefix
2571 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2574 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2576 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2577 # Ordinary namespace
2579 $this->mNamespace
= $ns;
2580 # For Talk:X pages, check if X has a "namespace" prefix
2581 if ( $ns == NS_TALK
&& preg_match( $prefixRegexp, $dbkey, $x ) ) {
2582 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2583 return false; # Disallow Talk:File:x type titles...
2584 } else if ( Interwiki
::isValidInterwiki( $x[1] ) ) {
2585 return false; # Disallow Talk:Interwiki:x type titles...
2588 } elseif ( Interwiki
::isValidInterwiki( $p ) ) {
2589 if ( !$firstPass ) {
2590 # Can't make a local interwiki link to an interwiki link.
2591 # That's just crazy!
2597 $this->mInterwiki
= $wgContLang->lc( $p );
2599 # Redundant interwiki prefix to the local wiki
2600 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
2601 if ( $dbkey == '' ) {
2602 # Can't have an empty self-link
2605 $this->mInterwiki
= '';
2607 # Do another namespace split...
2611 # If there's an initial colon after the interwiki, that also
2612 # resets the default namespace
2613 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2614 $this->mNamespace
= NS_MAIN
;
2615 $dbkey = substr( $dbkey, 1 );
2618 # If there's no recognized interwiki or namespace,
2619 # then let the colon expression be part of the title.
2624 # We already know that some pages won't be in the database!
2626 if ( $this->mInterwiki
!= '' || NS_SPECIAL
== $this->mNamespace
) {
2627 $this->mArticleID
= 0;
2629 $fragment = strstr( $dbkey, '#' );
2630 if ( false !== $fragment ) {
2631 $this->setFragment( preg_replace( '/^#_*/', '#', $fragment ) );
2632 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2633 # remove whitespace again: prevents "Foo_bar_#"
2634 # becoming "Foo_bar_"
2635 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2638 # Reject illegal characters.
2640 if ( preg_match( $rxTc, $dbkey ) ) {
2645 * Pages with "/./" or "/../" appearing in the URLs will often be un-
2646 * reachable due to the way web browsers deal with 'relative' URLs.
2647 * Also, they conflict with subpage syntax. Forbid them explicitly.
2649 if ( strpos( $dbkey, '.' ) !== false &&
2650 ( $dbkey === '.' ||
$dbkey === '..' ||
2651 strpos( $dbkey, './' ) === 0 ||
2652 strpos( $dbkey, '../' ) === 0 ||
2653 strpos( $dbkey, '/./' ) !== false ||
2654 strpos( $dbkey, '/../' ) !== false ||
2655 substr( $dbkey, -2 ) == '/.' ||
2656 substr( $dbkey, -3 ) == '/..' ) )
2662 * Magic tilde sequences? Nu-uh!
2664 if ( strpos( $dbkey, '~~~' ) !== false ) {
2669 * Limit the size of titles to 255 bytes.
2670 * This is typically the size of the underlying database field.
2671 * We make an exception for special pages, which don't need to be stored
2672 * in the database, and may edge over 255 bytes due to subpage syntax
2673 * for long titles, e.g. [[Special:Block/Long name]]
2675 if ( ( $this->mNamespace
!= NS_SPECIAL
&& strlen( $dbkey ) > 255 ) ||
2676 strlen( $dbkey ) > 512 )
2682 * Normally, all wiki links are forced to have
2683 * an initial capital letter so [[foo]] and [[Foo]]
2684 * point to the same place.
2686 * Don't force it for interwikis, since the other
2687 * site might be case-sensitive.
2689 $this->mUserCaseDBKey
= $dbkey;
2690 if ( $this->mInterwiki
== '' ) {
2691 $dbkey = self
::capitalize( $dbkey, $this->mNamespace
);
2695 * Can't make a link to a namespace alone...
2696 * "empty" local links can only be self-links
2697 * with a fragment identifier.
2699 if ( $dbkey == '' &&
2700 $this->mInterwiki
== '' &&
2701 $this->mNamespace
!= NS_MAIN
) {
2704 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2705 // IP names are not allowed for accounts, and can only be referring to
2706 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2707 // there are numerous ways to present the same IP. Having sp:contribs scan
2708 // them all is silly and having some show the edits and others not is
2709 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2710 $dbkey = ( $this->mNamespace
== NS_USER ||
$this->mNamespace
== NS_USER_TALK
) ?
2711 IP
::sanitizeIP( $dbkey ) : $dbkey;
2712 // Any remaining initial :s are illegal.
2713 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2718 $this->mDbkeyform
= $dbkey;
2719 $this->mUrlform
= wfUrlencode( $dbkey );
2721 $this->mTextform
= str_replace( '_', ' ', $dbkey );
2727 * Set the fragment for this title. Removes the first character from the
2728 * specified fragment before setting, so it assumes you're passing it with
2731 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2732 * Still in active use privately.
2734 * @param $fragment \type{\string} text
2736 public function setFragment( $fragment ) {
2737 $this->mFragment
= str_replace( '_', ' ', substr( $fragment, 1 ) );
2741 * Get a Title object associated with the talk page of this article
2743 * @return \type{Title} the object for the talk page
2745 public function getTalkPage() {
2746 return Title
::makeTitle( MWNamespace
::getTalk( $this->getNamespace() ), $this->getDBkey() );
2750 * Get a title object associated with the subject page of this
2753 * @return \type{Title} the object for the subject page
2755 public function getSubjectPage() {
2756 // Is this the same title?
2757 $subjectNS = MWNamespace
::getSubject( $this->getNamespace() );
2758 if ( $this->getNamespace() == $subjectNS ) {
2761 return Title
::makeTitle( $subjectNS, $this->getDBkey() );
2765 * Get an array of Title objects linking to this Title
2766 * Also stores the IDs in the link cache.
2768 * WARNING: do not use this function on arbitrary user-supplied titles!
2769 * On heavily-used templates it will max out the memory.
2771 * @param $options Array: may be FOR UPDATE
2772 * @param $table String: table name
2773 * @param $prefix String: fields prefix
2774 * @return \type{\arrayof{Title}} the Title objects linking here
2776 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2777 $linkCache = LinkCache
::singleton();
2779 if ( count( $options ) > 0 ) {
2780 $db = wfGetDB( DB_MASTER
);
2782 $db = wfGetDB( DB_SLAVE
);
2786 array( 'page', $table ),
2787 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2789 "{$prefix}_from=page_id",
2790 "{$prefix}_namespace" => $this->getNamespace(),
2791 "{$prefix}_title" => $this->getDBkey() ),
2797 if ( $db->numRows( $res ) ) {
2798 foreach ( $res as $row ) {
2799 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
2800 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
, $row->page_latest
);
2801 $retVal[] = $titleObj;
2809 * Get an array of Title objects using this Title as a template
2810 * Also stores the IDs in the link cache.
2812 * WARNING: do not use this function on arbitrary user-supplied titles!
2813 * On heavily-used templates it will max out the memory.
2815 * @param $options Array: may be FOR UPDATE
2816 * @return \type{\arrayof{Title}} the Title objects linking here
2818 public function getTemplateLinksTo( $options = array() ) {
2819 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2823 * Get an array of Title objects referring to non-existent articles linked from this page
2825 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2826 * @return \type{\arrayof{Title}} the Title objects
2828 public function getBrokenLinksFrom() {
2829 if ( $this->getArticleId() == 0 ) {
2830 # All links from article ID 0 are false positives
2834 $dbr = wfGetDB( DB_SLAVE
);
2835 $res = $dbr->select(
2836 array( 'page', 'pagelinks' ),
2837 array( 'pl_namespace', 'pl_title' ),
2839 'pl_from' => $this->getArticleId(),
2840 'page_namespace IS NULL'
2842 __METHOD__
, array(),
2846 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2852 foreach ( $res as $row ) {
2853 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
2860 * Get a list of URLs to purge from the Squid cache when this
2863 * @return \type{\arrayof{\string}} the URLs
2865 public function getSquidURLs() {
2869 $this->getInternalURL(),
2870 $this->getInternalURL( 'action=history' )
2873 // purge variant urls as well
2874 if ( $wgContLang->hasVariants() ) {
2875 $variants = $wgContLang->getVariants();
2876 foreach ( $variants as $vCode ) {
2877 $urls[] = $this->getInternalURL( '', $vCode );
2885 * Purge all applicable Squid URLs
2887 public function purgeSquid() {
2889 if ( $wgUseSquid ) {
2890 $urls = $this->getSquidURLs();
2891 $u = new SquidUpdate( $urls );
2897 * Move this page without authentication
2899 * @param $nt \type{Title} the new page Title
2900 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
2902 public function moveNoAuth( &$nt ) {
2903 return $this->moveTo( $nt, false );
2907 * Check whether a given move operation would be valid.
2908 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2910 * @param $nt \type{Title} the new title
2911 * @param $auth \type{\bool} indicates whether $wgUser's permissions
2913 * @param $reason \type{\string} is the log summary of the move, used for spam checking
2914 * @return \type{\mixed} True on success, getUserPermissionsErrors()-like array on failure
2916 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2921 // Normally we'd add this to $errors, but we'll get
2922 // lots of syntax errors if $nt is not an object
2923 return array( array( 'badtitletext' ) );
2925 if ( $this->equals( $nt ) ) {
2926 $errors[] = array( 'selfmove' );
2928 if ( !$this->isMovable() ) {
2929 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2931 if ( $nt->getInterwiki() != '' ) {
2932 $errors[] = array( 'immobile-target-namespace-iw' );
2934 if ( !$nt->isMovable() ) {
2935 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
2938 $oldid = $this->getArticleID();
2939 $newid = $nt->getArticleID();
2941 if ( strlen( $nt->getDBkey() ) < 1 ) {
2942 $errors[] = array( 'articleexists' );
2944 if ( ( $this->getDBkey() == '' ) ||
2946 ( $nt->getDBkey() == '' ) ) {
2947 $errors[] = array( 'badarticleerror' );
2950 // Image-specific checks
2951 if ( $this->getNamespace() == NS_FILE
) {
2952 if ( $nt->getNamespace() != NS_FILE
) {
2953 $errors[] = array( 'imagenocrossnamespace' );
2955 $file = wfLocalFile( $this );
2956 if ( $file->exists() ) {
2957 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
2958 $errors[] = array( 'imageinvalidfilename' );
2960 if ( !File
::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
2961 $errors[] = array( 'imagetypemismatch' );
2964 $destfile = wfLocalFile( $nt );
2965 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
2966 $errors[] = array( 'file-exists-sharedrepo' );
2970 if ( $nt->getNamespace() == NS_FILE
&& $this->getNamespace() != NS_FILE
) {
2971 $errors[] = array( 'nonfile-cannot-move-to-file' );
2975 $errors = wfMergeErrorArrays( $errors,
2976 $this->getUserPermissionsErrors( 'move', $wgUser ),
2977 $this->getUserPermissionsErrors( 'edit', $wgUser ),
2978 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
2979 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
2982 $match = EditPage
::matchSummarySpamRegex( $reason );
2983 if ( $match !== false ) {
2984 // This is kind of lame, won't display nice
2985 $errors[] = array( 'spamprotectiontext' );
2989 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
2990 $errors[] = array( 'hookaborted', $err );
2993 # The move is allowed only if (1) the target doesn't exist, or
2994 # (2) the target is a redirect to the source, and has no history
2995 # (so we can undo bad moves right after they're done).
2997 if ( 0 != $newid ) { # Target exists; check for validity
2998 if ( !$this->isValidMoveTarget( $nt ) ) {
2999 $errors[] = array( 'articleexists' );
3002 $tp = $nt->getTitleProtection();
3003 $right = ( $tp['pt_create_perm'] == 'sysop' ) ?
'protect' : $tp['pt_create_perm'];
3004 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3005 $errors[] = array( 'cantmove-titleprotected' );
3008 if ( empty( $errors ) ) {
3015 * Move a title to a new location
3017 * @param $nt \type{Title} the new title
3018 * @param $auth \type{\bool} indicates whether $wgUser's permissions
3020 * @param $reason \type{\string} The reason for the move
3021 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title.
3022 * Ignored if the user doesn't have the suppressredirect right.
3023 * @return \type{\mixed} true on success, getUserPermissionsErrors()-like array on failure
3025 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3028 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3029 if ( is_array( $err ) ) {
3033 // If it is a file, move it first. It is done before all other moving stuff is done because it's hard to revert
3034 $dbw = wfGetDB( DB_MASTER
);
3035 if ( $this->getNamespace() == NS_FILE
) {
3036 $file = wfLocalFile( $this );
3037 if ( $file->exists() ) {
3038 $status = $file->move( $nt );
3039 if ( !$status->isOk() ) {
3040 return $status->getErrorsArray();
3045 $pageid = $this->getArticleID();
3046 $protected = $this->isProtected();
3047 if ( $nt->exists() ) {
3048 $err = $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
3049 $pageCountChange = ( $createRedirect ?
0 : -1 );
3050 } else { # Target didn't exist, do normal move.
3051 $err = $this->moveToNewTitle( $nt, $reason, $createRedirect );
3052 $pageCountChange = ( $createRedirect ?
1 : 0 );
3055 if ( is_array( $err ) ) {
3058 $redirid = $this->getArticleID();
3060 // Refresh the sortkey for this row. Be careful to avoid resetting
3061 // cl_timestamp, which may disturb time-based lists on some sites.
3062 $prefix = $dbw->selectField(
3064 'cl_sortkey_prefix',
3065 array( 'cl_from' => $pageid ),
3068 $dbw->update( 'categorylinks',
3070 'cl_sortkey' => $wgContLang->convertToSortkey( $nt->getCategorySortkey( $prefix ) ),
3071 'cl_timestamp=cl_timestamp' ),
3072 array( 'cl_from' => $pageid ),
3076 # Protect the redirect title as the title used to be...
3077 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3079 'pr_page' => $redirid,
3080 'pr_type' => 'pr_type',
3081 'pr_level' => 'pr_level',
3082 'pr_cascade' => 'pr_cascade',
3083 'pr_user' => 'pr_user',
3084 'pr_expiry' => 'pr_expiry'
3086 array( 'pr_page' => $pageid ),
3090 # Update the protection log
3091 $log = new LogPage( 'protect' );
3092 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3094 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3096 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) ); // FIXME: $params?
3100 $oldnamespace = $this->getNamespace() & ~
1;
3101 $newnamespace = $nt->getNamespace() & ~
1;
3102 $oldtitle = $this->getDBkey();
3103 $newtitle = $nt->getDBkey();
3105 if ( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
3106 WatchedItem
::duplicateEntries( $this, $nt );
3109 # Update search engine
3110 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3112 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3116 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3117 # No longer a content page
3118 # Not viewed, edited, removing
3119 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3120 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3121 # Now a content page
3122 # Not viewed, edited, adding
3123 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
3124 } elseif ( $pageCountChange ) {
3126 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3134 # Update message cache for interface messages
3135 global $wgMessageCache;
3136 if ( $this->getNamespace() == NS_MEDIAWIKI
) {
3137 # @bug 17860: old article can be deleted, if this the case,
3138 # delete it from message cache
3139 if ( $this->getArticleID() === 0 ) {
3140 $wgMessageCache->replace( $this->getDBkey(), false );
3142 $oldarticle = new Article( $this );
3143 $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
3146 if ( $nt->getNamespace() == NS_MEDIAWIKI
) {
3147 $newarticle = new Article( $nt );
3148 $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
3152 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3157 * Move page to a title which is at present a redirect to the
3160 * @param $nt \type{Title} the page to move to, which should currently
3162 * @param $reason \type{\string} The reason for the move
3163 * @param $createRedirect \type{\bool} Whether to leave a redirect at the old title.
3164 * Ignored if the user doesn't have the suppressredirect right
3166 private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
3167 global $wgUseSquid, $wgUser, $wgContLang;
3169 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
3172 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3174 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3175 $comment = $wgContLang->truncate( $comment, 250 );
3177 $now = wfTimestampNow();
3178 $newid = $nt->getArticleID();
3179 $oldid = $this->getArticleID();
3180 $latest = $this->getLatestRevID();
3182 $dbw = wfGetDB( DB_MASTER
);
3184 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3185 $newns = $nt->getNamespace();
3186 $newdbk = $nt->getDBkey();
3188 # Delete the old redirect. We don't save it to history since
3189 # by definition if we've got here it's rather uninteresting.
3190 # We have to remove it so that the next step doesn't trigger
3191 # a conflict on the unique namespace+title index...
3192 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__
);
3193 if ( !$dbw->cascadingDeletes() ) {
3194 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__
);
3195 global $wgUseTrackbacks;
3196 if ( $wgUseTrackbacks ) {
3197 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__
);
3199 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3200 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__
);
3201 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__
);
3202 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__
);
3203 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__
);
3204 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__
);
3205 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__
);
3207 // If the redirect was recently created, it may have an entry in recentchanges still
3208 $dbw->delete( 'recentchanges',
3209 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3213 # Save a null revision in the page's history notifying of the move
3214 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3215 $nullRevId = $nullRevision->insertOn( $dbw );
3217 $article = new Article( $this );
3218 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3220 # Change the name of the target page:
3221 $dbw->update( 'page',
3223 'page_touched' => $dbw->timestamp( $now ),
3224 'page_namespace' => $nt->getNamespace(),
3225 'page_title' => $nt->getDBkey(),
3226 'page_latest' => $nullRevId,
3228 /* WHERE */ array( 'page_id' => $oldid ),
3231 $nt->resetArticleID( $oldid );
3233 # Recreate the redirect, this time in the other direction.
3234 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3235 $mwRedir = MagicWord
::get( 'redirect' );
3236 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3237 $redirectArticle = new Article( $this );
3238 $newid = $redirectArticle->insertOn( $dbw );
3239 $redirectRevision = new Revision( array(
3241 'comment' => $comment,
3242 'text' => $redirectText ) );
3243 $redirectRevision->insertOn( $dbw );
3244 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3246 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3248 # Now, we record the link from the redirect to the new title.
3249 # It should have no other outgoing links...
3250 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__
);
3251 $dbw->insert( 'pagelinks',
3253 'pl_from' => $newid,
3254 'pl_namespace' => $nt->getNamespace(),
3255 'pl_title' => $nt->getDBkey() ),
3257 $redirectSuppressed = false;
3259 $this->resetArticleID( 0 );
3260 $redirectSuppressed = true;
3264 $log = new LogPage( 'move' );
3265 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3268 if ( $wgUseSquid ) {
3269 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
3270 $u = new SquidUpdate( $urls );
3277 * Move page to non-existing title.
3279 * @param $nt \type{Title} the new Title
3280 * @param $reason \type{\string} The reason for the move
3281 * @param $createRedirect \type{\bool} Whether to create a redirect from the old title to the new title
3282 * Ignored if the user doesn't have the suppressredirect right
3284 private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
3285 global $wgUser, $wgContLang;
3287 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3289 $comment .= wfMsgExt( 'colon-separator',
3290 array( 'escapenoentities', 'content' ) );
3291 $comment .= $reason;
3293 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3294 $comment = $wgContLang->truncate( $comment, 250 );
3296 $newid = $nt->getArticleID();
3297 $oldid = $this->getArticleID();
3298 $latest = $this->getLatestRevId();
3300 $dbw = wfGetDB( DB_MASTER
);
3301 $now = $dbw->timestamp();
3303 # Save a null revision in the page's history notifying of the move
3304 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
3305 if ( !is_object( $nullRevision ) ) {
3306 throw new MWException( 'No valid null revision produced in ' . __METHOD__
);
3308 $nullRevId = $nullRevision->insertOn( $dbw );
3310 $article = new Article( $this );
3311 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3314 $dbw->update( 'page',
3316 'page_touched' => $now,
3317 'page_namespace' => $nt->getNamespace(),
3318 'page_title' => $nt->getDBkey(),
3319 'page_latest' => $nullRevId,
3321 /* WHERE */ array( 'page_id' => $oldid ),
3324 $nt->resetArticleID( $oldid );
3326 if ( $createRedirect ||
!$wgUser->isAllowed( 'suppressredirect' ) ) {
3328 $mwRedir = MagicWord
::get( 'redirect' );
3329 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3330 $redirectArticle = new Article( $this );
3331 $newid = $redirectArticle->insertOn( $dbw );
3332 $redirectRevision = new Revision( array(
3334 'comment' => $comment,
3335 'text' => $redirectText ) );
3336 $redirectRevision->insertOn( $dbw );
3337 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3339 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3341 # Record the just-created redirect's linking to the page
3342 $dbw->insert( 'pagelinks',
3344 'pl_from' => $newid,
3345 'pl_namespace' => $nt->getNamespace(),
3346 'pl_title' => $nt->getDBkey() ),
3348 $redirectSuppressed = false;
3350 $this->resetArticleID( 0 );
3351 $redirectSuppressed = true;
3355 $log = new LogPage( 'move' );
3356 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3358 # Purge caches as per article creation
3359 Article
::onArticleCreate( $nt );
3361 # Purge old title from squid
3362 # The new title, and links to the new title, are purged in Article::onArticleCreate()
3363 $this->purgeSquid();
3367 * Move this page's subpages to be subpages of $nt
3369 * @param $nt Title Move target
3370 * @param $auth bool Whether $wgUser's permissions should be checked
3371 * @param $reason string The reason for the move
3372 * @param $createRedirect bool Whether to create redirects from the old subpages to the new ones
3373 * Ignored if the user doesn't have the 'suppressredirect' right
3374 * @return mixed array with old page titles as keys, and strings (new page titles) or
3375 * arrays (errors) as values, or an error array with numeric indices if no pages were moved
3377 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3378 global $wgMaximumMovedPages;
3379 // Check permissions
3380 if ( !$this->userCan( 'move-subpages' ) ) {
3381 return array( 'cant-move-subpages' );
3383 // Do the source and target namespaces support subpages?
3384 if ( !MWNamespace
::hasSubpages( $this->getNamespace() ) ) {
3385 return array( 'namespace-nosubpages',
3386 MWNamespace
::getCanonicalName( $this->getNamespace() ) );
3388 if ( !MWNamespace
::hasSubpages( $nt->getNamespace() ) ) {
3389 return array( 'namespace-nosubpages',
3390 MWNamespace
::getCanonicalName( $nt->getNamespace() ) );
3393 $subpages = $this->getSubpages( $wgMaximumMovedPages +
1 );
3396 foreach ( $subpages as $oldSubpage ) {
3398 if ( $count > $wgMaximumMovedPages ) {
3399 $retval[$oldSubpage->getPrefixedTitle()] =
3400 array( 'movepage-max-pages',
3401 $wgMaximumMovedPages );
3405 // We don't know whether this function was called before
3406 // or after moving the root page, so check both
3408 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3409 $oldSubpage->getArticleID() == $nt->getArticleId() )
3411 // When moving a page to a subpage of itself,
3412 // don't move it twice
3415 $newPageName = preg_replace(
3416 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3417 StringUtils
::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3418 $oldSubpage->getDBkey() );
3419 if ( $oldSubpage->isTalkPage() ) {
3420 $newNs = $nt->getTalkPage()->getNamespace();
3422 $newNs = $nt->getSubjectPage()->getNamespace();
3424 # Bug 14385: we need makeTitleSafe because the new page names may
3425 # be longer than 255 characters.
3426 $newSubpage = Title
::makeTitleSafe( $newNs, $newPageName );
3428 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3429 if ( $success === true ) {
3430 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3432 $retval[$oldSubpage->getPrefixedText()] = $success;
3439 * Checks if this page is just a one-rev redirect.
3440 * Adds lock, so don't use just for light purposes.
3442 * @return \type{\bool}
3444 public function isSingleRevRedirect() {
3445 $dbw = wfGetDB( DB_MASTER
);
3447 $row = $dbw->selectRow( 'page',
3448 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3451 array( 'FOR UPDATE' )
3453 # Cache some fields we may want
3454 $this->mArticleID
= $row ?
intval( $row->page_id
) : 0;
3455 $this->mRedirect
= $row ?
(bool)$row->page_is_redirect
: false;
3456 $this->mLatestID
= $row ?
intval( $row->page_latest
) : false;
3457 if ( !$this->mRedirect
) {
3460 # Does the article have a history?
3461 $row = $dbw->selectField( array( 'page', 'revision' ),
3463 array( 'page_namespace' => $this->getNamespace(),
3464 'page_title' => $this->getDBkey(),
3466 'page_latest != rev_id'
3469 array( 'FOR UPDATE' )
3471 # Return true if there was no history
3472 return ( $row === false );
3476 * Checks if $this can be moved to a given Title
3477 * - Selects for update, so don't call it unless you mean business
3479 * @param $nt \type{Title} the new title to check
3480 * @return \type{\bool} TRUE or FALSE
3482 public function isValidMoveTarget( $nt ) {
3483 # Is it an existing file?
3484 if ( $nt->getNamespace() == NS_FILE
) {
3485 $file = wfLocalFile( $nt );
3486 if ( $file->exists() ) {
3487 wfDebug( __METHOD__
. ": file exists\n" );
3491 # Is it a redirect with no history?
3492 if ( !$nt->isSingleRevRedirect() ) {
3493 wfDebug( __METHOD__
. ": not a one-rev redirect\n" );
3496 # Get the article text
3497 $rev = Revision
::newFromTitle( $nt );
3498 $text = $rev->getText();
3499 # Does the redirect point to the source?
3500 # Or is it a broken self-redirect, usually caused by namespace collisions?
3502 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3503 $redirTitle = Title
::newFromText( $m[1] );
3504 if ( !is_object( $redirTitle ) ||
3505 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3506 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3507 wfDebug( __METHOD__
. ": redirect points to other page\n" );
3512 wfDebug( __METHOD__
. ": failsafe\n" );
3519 * Can this title be added to a user's watchlist?
3521 * @return \type{\bool} TRUE or FALSE
3523 public function isWatchable() {
3524 return !$this->isExternal() && MWNamespace
::isWatchable( $this->getNamespace() );
3528 * Get categories to which this Title belongs and return an array of
3529 * categories' names.
3531 * @return \type{\array} array an array of parents in the form:
3532 * $parent => $currentarticle
3534 public function getParentCategories() {
3537 $titlekey = $this->getArticleId();
3538 $dbr = wfGetDB( DB_SLAVE
);
3539 $categorylinks = $dbr->tableName( 'categorylinks' );
3542 $sql = "SELECT * FROM $categorylinks"
3543 . " WHERE cl_from='$titlekey'"
3544 . " AND cl_from <> '0'"
3545 . " ORDER BY cl_sortkey";
3547 $res = $dbr->query( $sql );
3550 if ( $dbr->numRows( $res ) > 0 ) {
3551 foreach ( $res as $row ) {
3552 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3553 $data[$wgContLang->getNSText( NS_CATEGORY
) . ':' . $row->cl_to
] = $this->getFullText();
3560 * Get a tree of parent categories
3562 * @param $children \type{\array} an array with the children in the keys, to check for circular refs
3563 * @return \type{\array} Tree of parent categories
3565 public function getParentCategoryTree( $children = array() ) {
3567 $parents = $this->getParentCategories();
3570 foreach ( $parents as $parent => $current ) {
3571 if ( array_key_exists( $parent, $children ) ) {
3572 # Circular reference
3573 $stack[$parent] = array();
3575 $nt = Title
::newFromText( $parent );
3577 $stack[$parent] = $nt->getParentCategoryTree( $children +
array( $parent => 1 ) );
3588 * Get an associative array for selecting this title from
3591 * @return \type{\array} Selection array
3593 public function pageCond() {
3594 if ( $this->mArticleID
> 0 ) {
3595 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3596 return array( 'page_id' => $this->mArticleID
);
3598 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
3603 * Get the revision ID of the previous revision
3605 * @param $revId \type{\int} Revision ID. Get the revision that was before this one.
3606 * @param $flags \type{\int} Title::GAID_FOR_UPDATE
3607 * @return \twotypes{\int,\bool} Old revision ID, or FALSE if none exists
3609 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3610 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3611 return $db->selectField( 'revision', 'rev_id',
3613 'rev_page' => $this->getArticleId( $flags ),
3614 'rev_id < ' . intval( $revId )
3617 array( 'ORDER BY' => 'rev_id DESC' )
3622 * Get the revision ID of the next revision
3624 * @param $revId \type{\int} Revision ID. Get the revision that was after this one.
3625 * @param $flags \type{\int} Title::GAID_FOR_UPDATE
3626 * @return \twotypes{\int,\bool} Next revision ID, or FALSE if none exists
3628 public function getNextRevisionID( $revId, $flags = 0 ) {
3629 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3630 return $db->selectField( 'revision', 'rev_id',
3632 'rev_page' => $this->getArticleId( $flags ),
3633 'rev_id > ' . intval( $revId )
3636 array( 'ORDER BY' => 'rev_id' )
3641 * Get the first revision of the page
3643 * @param $flags \type{\int} Title::GAID_FOR_UPDATE
3644 * @return Revision (or NULL if page doesn't exist)
3646 public function getFirstRevision( $flags = 0 ) {
3647 $db = ( $flags & self
::GAID_FOR_UPDATE
) ?
wfGetDB( DB_MASTER
) : wfGetDB( DB_SLAVE
);
3648 $pageId = $this->getArticleId( $flags );
3652 $row = $db->selectRow( 'revision', '*',
3653 array( 'rev_page' => $pageId ),
3655 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3660 return new Revision( $row );
3665 * Check if this is a new page
3669 public function isNewPage() {
3670 $dbr = wfGetDB( DB_SLAVE
);
3671 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__
);
3675 * Get the oldest revision timestamp of this page
3677 * @return String: MW timestamp
3679 public function getEarliestRevTime() {
3680 $dbr = wfGetDB( DB_SLAVE
);
3681 if ( $this->exists() ) {
3682 $min = $dbr->selectField( 'revision',
3683 'MIN(rev_timestamp)',
3684 array( 'rev_page' => $this->getArticleId() ),
3686 return wfTimestampOrNull( TS_MW
, $min );
3692 * Get the number of revisions between the given revision IDs.
3693 * Used for diffs and other things that really need it.
3695 * @param $old \type{\int} Revision ID.
3696 * @param $new \type{\int} Revision ID.
3697 * @return \type{\int} Number of revisions between these IDs.
3699 public function countRevisionsBetween( $old, $new ) {
3700 $dbr = wfGetDB( DB_SLAVE
);
3701 return (int)$dbr->selectField( 'revision', 'count(*)',
3702 'rev_page = ' . intval( $this->getArticleId() ) .
3703 ' AND rev_id > ' . intval( $old ) .
3704 ' AND rev_id < ' . intval( $new ),
3710 * Compare with another title.
3712 * @param $title \type{Title}
3713 * @return \type{\bool} TRUE or FALSE
3715 public function equals( Title
$title ) {
3716 // Note: === is necessary for proper matching of number-like titles.
3717 return $this->getInterwiki() === $title->getInterwiki()
3718 && $this->getNamespace() == $title->getNamespace()
3719 && $this->getDBkey() === $title->getDBkey();
3723 * Callback for usort() to do title sorts by (namespace, title)
3725 * @return Integer: result of string comparison, or namespace comparison
3727 public static function compare( $a, $b ) {
3728 if ( $a->getNamespace() == $b->getNamespace() ) {
3729 return strcmp( $a->getText(), $b->getText() );
3731 return $a->getNamespace() - $b->getNamespace();
3736 * Return a string representation of this title
3738 * @return \type{\string} String representation of this title
3740 public function __toString() {
3741 return $this->getPrefixedText();
3745 * Check if page exists. For historical reasons, this function simply
3746 * checks for the existence of the title in the page table, and will
3747 * thus return false for interwiki links, special pages and the like.
3748 * If you want to know if a title can be meaningfully viewed, you should
3749 * probably call the isKnown() method instead.
3751 * @return \type{\bool}
3753 public function exists() {
3754 return $this->getArticleId() != 0;
3758 * Should links to this title be shown as potentially viewable (i.e. as
3759 * "bluelinks"), even if there's no record by this title in the page
3762 * This function is semi-deprecated for public use, as well as somewhat
3763 * misleadingly named. You probably just want to call isKnown(), which
3764 * calls this function internally.
3766 * (ISSUE: Most of these checks are cheap, but the file existence check
3767 * can potentially be quite expensive. Including it here fixes a lot of
3768 * existing code, but we might want to add an optional parameter to skip
3769 * it and any other expensive checks.)
3771 * @return \type{\bool}
3773 public function isAlwaysKnown() {
3774 if ( $this->mInterwiki
!= '' ) {
3775 return true; // any interwiki link might be viewable, for all we know
3777 switch( $this->mNamespace
) {
3780 return (bool)wfFindFile( $this ); // file exists, possibly in a foreign repo
3782 return SpecialPage
::exists( $this->getDBkey() ); // valid special page
3784 return $this->mDbkeyform
== ''; // selflink, possibly with fragment
3786 // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
3787 // the full l10n of that language to be loaded. That takes much memory and
3788 // isn't needed. So we strip the language part away.
3789 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3790 return (bool)wfMsgWeirdKey( $basename ); // known system message
3797 * Does this title refer to a page that can (or might) be meaningfully
3798 * viewed? In particular, this function may be used to determine if
3799 * links to the title should be rendered as "bluelinks" (as opposed to
3800 * "redlinks" to non-existent pages).
3802 * @return \type{\bool}
3804 public function isKnown() {
3805 return $this->isAlwaysKnown() ||
$this->exists();
3809 * Does this page have source text?
3813 public function hasSourceText() {
3814 if ( $this->exists() ) {
3818 if ( $this->mNamespace
== NS_MEDIAWIKI
) {
3819 // If the page doesn't exist but is a known system message, default
3820 // message content will be displayed, same for language subpages
3821 // Also, if the page is form Mediawiki:message/lang, calling wfMsgWeirdKey
3822 // causes the full l10n of that language to be loaded. That takes much
3823 // memory and isn't needed. So we strip the language part away.
3824 list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform
, 2 );
3825 return (bool)wfMsgWeirdKey( $basename );
3832 * Is this in a namespace that allows actual pages?
3834 * @return \type{\bool}
3835 * @internal note -- uses hardcoded namespace index instead of constants
3837 public function canExist() {
3838 return $this->mNamespace
>= 0 && $this->mNamespace
!= NS_MEDIA
;
3842 * Update page_touched timestamps and send squid purge messages for
3843 * pages linking to this title. May be sent to the job queue depending
3844 * on the number of links. Typically called on create and delete.
3846 public function touchLinks() {
3847 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3850 if ( $this->getNamespace() == NS_CATEGORY
) {
3851 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3857 * Get the last touched timestamp
3859 * @param $db DatabaseBase: optional db
3860 * @return \type{\string} Last touched timestamp
3862 public function getTouched( $db = null ) {
3863 $db = isset( $db ) ?
$db : wfGetDB( DB_SLAVE
);
3864 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__
);
3869 * Get the timestamp when this page was updated since the user last saw it.
3872 * @return Mixed: string/null
3874 public function getNotificationTimestamp( $user = null ) {
3875 global $wgUser, $wgShowUpdatedMarker;
3876 // Assume current user if none given
3880 // Check cache first
3881 $uid = $user->getId();
3882 if ( isset( $this->mNotificationTimestamp
[$uid] ) ) {
3883 return $this->mNotificationTimestamp
[$uid];
3885 if ( !$uid ||
!$wgShowUpdatedMarker ) {
3886 return $this->mNotificationTimestamp
[$uid] = false;
3888 // Don't cache too much!
3889 if ( count( $this->mNotificationTimestamp
) >= self
::CACHE_MAX
) {
3890 $this->mNotificationTimestamp
= array();
3892 $dbr = wfGetDB( DB_SLAVE
);
3893 $this->mNotificationTimestamp
[$uid] = $dbr->selectField( 'watchlist',
3894 'wl_notificationtimestamp',
3895 array( 'wl_namespace' => $this->getNamespace(),
3896 'wl_title' => $this->getDBkey(),
3897 'wl_user' => $user->getId()
3901 return $this->mNotificationTimestamp
[$uid];
3905 * Get the trackback URL for this page
3907 * @return \type{\string} Trackback URL
3909 public function trackbackURL() {
3910 global $wgScriptPath, $wgServer, $wgScriptExtension;
3912 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3913 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3917 * Get the trackback RDF for this page
3919 * @return \type{\string} Trackback RDF
3921 public function trackbackRDF() {
3922 $url = htmlspecialchars( $this->getFullURL() );
3923 $title = htmlspecialchars( $this->getText() );
3924 $tburl = $this->trackbackURL();
3926 // Autodiscovery RDF is placed in comments so HTML validator
3927 // won't barf. This is a rather icky workaround, but seems
3928 // frequently used by this kind of RDF thingy.
3930 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3932 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3933 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3934 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3937 dc:identifier=\"$url\"
3939 trackback:ping=\"$tburl\" />
3945 * Generate strings used for xml 'id' names in monobook tabs
3947 * @param $prepend string defaults to 'nstab-'
3948 * @return \type{\string} XML 'id' name
3950 public function getNamespaceKey( $prepend = 'nstab-' ) {
3952 // Gets the subject namespace if this title
3953 $namespace = MWNamespace
::getSubject( $this->getNamespace() );
3954 // Checks if cononical namespace name exists for namespace
3955 if ( MWNamespace
::exists( $this->getNamespace() ) ) {
3956 // Uses canonical namespace name
3957 $namespaceKey = MWNamespace
::getCanonicalName( $namespace );
3959 // Uses text of namespace
3960 $namespaceKey = $this->getSubjectNsText();
3962 // Makes namespace key lowercase
3963 $namespaceKey = $wgContLang->lc( $namespaceKey );
3965 if ( $namespaceKey == '' ) {
3966 $namespaceKey = 'main';
3968 // Changes file to image for backwards compatibility
3969 if ( $namespaceKey == 'file' ) {
3970 $namespaceKey = 'image';
3972 return $prepend . $namespaceKey;
3976 * Returns true if this is a special page.
3980 public function isSpecialPage() {
3981 return $this->getNamespace() == NS_SPECIAL
;
3985 * Returns true if this title resolves to the named special page
3987 * @param $name \type{\string} The special page name
3990 public function isSpecial( $name ) {
3991 if ( $this->getNamespace() == NS_SPECIAL
) {
3992 list( $thisName, /* $subpage */ ) = SpecialPage
::resolveAliasWithSubpage( $this->getDBkey() );
3993 if ( $name == $thisName ) {
4001 * If the Title refers to a special page alias which is not the local default,
4003 * @return \type{Title} A new Title which points to the local default.
4004 * Otherwise, returns $this.
4006 public function fixSpecialName() {
4007 if ( $this->getNamespace() == NS_SPECIAL
) {
4008 $canonicalName = SpecialPage
::resolveAlias( $this->mDbkeyform
);
4009 if ( $canonicalName ) {
4010 $localName = SpecialPage
::getLocalNameFor( $canonicalName );
4011 if ( $localName != $this->mDbkeyform
) {
4012 return Title
::makeTitle( NS_SPECIAL
, $localName );
4020 * Is this Title in a namespace which contains content?
4021 * In other words, is this a content page, for the purposes of calculating
4024 * @return \type{\bool}
4026 public function isContentPage() {
4027 return MWNamespace
::isContent( $this->getNamespace() );
4031 * Get all extant redirects to this Title
4033 * @param $ns \twotypes{\int,\null} Single namespace to consider;
4034 * NULL to consider all namespaces
4035 * @return \type{\arrayof{Title}} Redirects to this title
4037 public function getRedirectsHere( $ns = null ) {
4040 $dbr = wfGetDB( DB_SLAVE
);
4042 'rd_namespace' => $this->getNamespace(),
4043 'rd_title' => $this->getDBkey(),
4046 if ( !is_null( $ns ) ) {
4047 $where['page_namespace'] = $ns;
4050 $res = $dbr->select(
4051 array( 'redirect', 'page' ),
4052 array( 'page_namespace', 'page_title' ),
4057 foreach ( $res as $row ) {
4058 $redirs[] = self
::newFromRow( $row );
4064 * Check if this Title is a valid redirect target
4066 * @return \type{\bool}
4068 public function isValidRedirectTarget() {
4069 global $wgInvalidRedirectTargets;
4071 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4072 if ( $this->isSpecial( 'Userlogout' ) ) {
4076 foreach ( $wgInvalidRedirectTargets as $target ) {
4077 if ( $this->isSpecial( $target ) ) {
4086 * Get a backlink cache object
4088 * @return object BacklinkCache
4090 function getBacklinkCache() {
4091 if ( is_null( $this->mBacklinkCache
) ) {
4092 $this->mBacklinkCache
= new BacklinkCache( $this );
4094 return $this->mBacklinkCache
;
4098 * Whether the magic words __INDEX__ and __NOINDEX__ function for
4103 public function canUseNoindex() {
4104 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4106 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4107 ?
$wgContentNamespaces
4108 : $wgExemptFromUserRobotsControl;
4110 return !in_array( $this->mNamespace
, $bannedNamespaces );
4115 * Returns restriction types for the current Title
4117 * @return array applicable restriction types
4119 public function getRestrictionTypes() {
4120 global $wgRestrictionTypes;
4121 $types = $this->exists() ?
$wgRestrictionTypes : array( 'create' );
4123 if ( $this->getNamespace() == NS_FILE
) {
4124 $types[] = 'upload';
4127 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4133 * Returns the raw sort key to be used for categories, with the specified
4134 * prefix. This will be fed to Language::convertToSortkey() to get a
4135 * binary sortkey that can be used for actual sorting.
4137 * @param $prefix string The prefix to be used, specified using
4138 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4142 public function getCategorySortkey( $prefix = '' ) {
4143 $unprefixed = $this->getText();
4144 if ( $prefix !== '' ) {
4145 # Separate with a null byte, so the unprefixed part is only used as
4146 # a tiebreaker when two pages have the exact same prefix -- null
4147 # sorts before everything else (hopefully).
4148 return "$prefix\0$unprefixed";