9 require_once( 'normal/UtfNormal.php' );
11 define ( 'GAID_FOR_UPDATE', 1 );
13 # Title::newFromTitle maintains a cache to avoid
14 # expensive re-normalization of commonly used titles.
15 # On a batch operation this can become a memory leak
16 # if not bounded. After hitting this many titles,
18 define( 'MW_TITLECACHE_MAX', 1000 );
22 * - Represents a title, which may contain an interwiki designation or namespace
23 * - Can fetch various kinds of data from the database, albeit inefficiently.
29 * Static cache variables
31 static private $titleCache=array();
32 static private $interwikiCache=array();
36 * All member variables should be considered private
37 * Please use the accessor functions
44 var $mTextform; # Text form (spaces not underscores) of the main part
45 var $mUrlform; # URL-encoded form of the main part
46 var $mDbkeyform; # Main part with underscores
47 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
48 var $mInterwiki; # Interwiki prefix (or null string)
49 var $mFragment; # Title fragment (i.e. the bit after the #)
50 var $mArticleID; # Article ID, fetched from the link cache on demand
51 var $mLatestID; # ID of most recent revision
52 var $mRestrictions; # Array of groups allowed to edit this article
53 # Only null or "sysop" are supported
54 var $mRestrictionsLoaded; # Boolean for initialisation on demand
55 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
56 var $mDefaultNamespace; # Namespace index when there is no namespace
57 # Zero except in {{transclusion}} tags
58 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
66 /* private */ function Title() {
67 $this->mInterwiki
= $this->mUrlform
=
68 $this->mTextform
= $this->mDbkeyform
= '';
69 $this->mArticleID
= -1;
70 $this->mNamespace
= NS_MAIN
;
71 $this->mRestrictionsLoaded
= false;
72 $this->mRestrictions
= array();
73 # Dont change the following, NS_MAIN is hardcoded in several place
75 $this->mDefaultNamespace
= NS_MAIN
;
76 $this->mWatched
= NULL;
77 $this->mLatestID
= false;
81 * Create a new Title from a prefixed DB key
82 * @param string $key The database key, which has underscores
83 * instead of spaces, possibly including namespace and
85 * @return Title the new object, or NULL on an error
89 /* static */ function newFromDBkey( $key ) {
91 $t->mDbkeyform
= $key;
92 if( $t->secureAndSplit() )
99 * Create a new Title from text, such as what one would
100 * find in a link. Decodes any HTML entities in the text.
102 * @param string $text the link text; spaces, prefixes,
103 * and an initial ':' indicating the main namespace
105 * @param int $defaultNamespace the namespace to use if
106 * none is specified by a prefix
107 * @return Title the new object, or NULL on an error
111 public static function newFromText( $text, $defaultNamespace = NS_MAIN
) {
112 $fname = 'Title::newFromText';
114 if( is_object( $text ) ) {
115 throw new MWException( 'Title::newFromText given an object' );
119 * Wiki pages often contain multiple links to the same page.
120 * Title normalization and parsing can become expensive on
121 * pages with many links, so we can save a little time by
124 * In theory these are value objects and won't get changed...
126 if( $defaultNamespace == NS_MAIN
&& isset( Title
::$titleCache[$text] ) ) {
127 return Title
::$titleCache[$text];
131 * Convert things like é ā or 〗 into real text...
133 $filteredText = Sanitizer
::decodeCharReferences( $text );
136 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
137 $t->mDefaultNamespace
= $defaultNamespace;
139 static $cachedcount = 0 ;
140 if( $t->secureAndSplit() ) {
141 if( $defaultNamespace == NS_MAIN
) {
142 if( $cachedcount >= MW_TITLECACHE_MAX
) {
143 # Avoid memory leaks on mass operations...
144 Title
::$titleCache = array();
148 Title
::$titleCache[$text] =& $t;
158 * Create a new Title from URL-encoded text. Ensures that
159 * the given title's length does not exceed the maximum.
160 * @param string $url the title, as might be taken from a URL
161 * @return Title the new object, or NULL on an error
165 function newFromURL( $url ) {
166 global $wgLegalTitleChars;
169 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
170 # but some URLs used it as a space replacement and they still come
171 # from some external search tools.
172 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
173 $url = str_replace( '+', ' ', $url );
176 $t->mDbkeyform
= str_replace( ' ', '_', $url );
177 if( $t->secureAndSplit() ) {
185 * Create a new Title from an article ID
187 * @todo This is inefficiently implemented, the page row is requested
188 * but not used for anything else
190 * @param int $id the page_id corresponding to the Title to create
191 * @return Title the new object, or NULL on an error
195 function newFromID( $id ) {
196 $fname = 'Title::newFromID';
197 $dbr =& wfGetDB( DB_SLAVE
);
198 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
199 array( 'page_id' => $id ), $fname );
200 if ( $row !== false ) {
201 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
209 * Make an array of titles from an array of IDs
211 function newFromIDs( $ids ) {
212 $dbr =& wfGetDB( DB_SLAVE
);
213 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
214 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__
);
217 while ( $row = $dbr->fetchObject( $res ) ) {
218 $titles[] = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
224 * Create a new Title from a namespace index and a DB key.
225 * It's assumed that $ns and $title are *valid*, for instance when
226 * they came directly from the database or a special page name.
227 * For convenience, spaces are converted to underscores so that
228 * eg user_text fields can be used directly.
230 * @param int $ns the namespace of the article
231 * @param string $title the unprefixed database key form
232 * @return Title the new object
236 public static function &makeTitle( $ns, $title ) {
240 $t->mNamespace
= intval( $ns );
241 $t->mDbkeyform
= str_replace( ' ', '_', $title );
242 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
243 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
244 $t->mTextform
= str_replace( '_', ' ', $title );
249 * Create a new Title from a namespace index and a DB key.
250 * The parameters will be checked for validity, which is a bit slower
251 * than makeTitle() but safer for user-provided data.
253 * @param int $ns the namespace of the article
254 * @param string $title the database key form
255 * @return Title the new object, or NULL on an error
259 public static function makeTitleSafe( $ns, $title ) {
261 $t->mDbkeyform
= Title
::makeName( $ns, $title );
262 if( $t->secureAndSplit() ) {
270 * Create a new Title for the Main Page
273 * @return Title the new object
276 public static function newMainPage() {
277 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
281 * Create a new Title for a redirect
282 * @param string $text the redirect title text
283 * @return Title the new object, or NULL if the text is not a
288 public static function newFromRedirect( $text ) {
289 $mwRedir = MagicWord
::get( 'redirect' );
291 if ( $mwRedir->matchStart( $text ) ) {
292 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
293 # categories are escaped using : for example one can enter:
294 # #REDIRECT [[:Category:Music]]. Need to remove it.
295 if ( substr($m[1],0,1) == ':') {
296 # We don't want to keep the ':'
297 $m[1] = substr( $m[1], 1 );
300 $rt = Title
::newFromText( $m[1] );
301 # Disallow redirects to Special:Userlogout
302 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
310 #----------------------------------------------------------------------------
312 #----------------------------------------------------------------------------
315 * Get the prefixed DB key associated with an ID
316 * @param int $id the page_id of the article
317 * @return Title an object representing the article, or NULL
318 * if no such article was found
322 function nameOf( $id ) {
323 $fname = 'Title::nameOf';
324 $dbr =& wfGetDB( DB_SLAVE
);
326 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
327 if ( $s === false ) { return NULL; }
329 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
334 * Get a regex character class describing the legal characters in a link
335 * @return string the list of characters, not delimited
339 public static function legalChars() {
340 global $wgLegalTitleChars;
341 return $wgLegalTitleChars;
345 * Get a string representation of a title suitable for
346 * including in a search index
348 * @param int $ns a namespace index
349 * @param string $title text-form main part
350 * @return string a stripped-down title string ready for the
353 /* static */ function indexTitle( $ns, $title ) {
356 $lc = SearchEngine
::legalSearchChars() . '&#;';
357 $t = $wgContLang->stripForSearch( $title );
358 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
359 $t = $wgContLang->lc( $t );
362 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
363 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
365 $t = preg_replace( "/\\s+/", ' ', $t );
367 if ( $ns == NS_IMAGE
) {
368 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
374 * Make a prefixed DB key from a DB key and a namespace index
375 * @param int $ns numerical representation of the namespace
376 * @param string $title the DB key form the title
377 * @return string the prefixed form of the title
379 public static function makeName( $ns, $title ) {
382 $n = $wgContLang->getNsText( $ns );
383 return $n == '' ?
$title : "$n:$title";
387 * Returns the URL associated with an interwiki prefix
388 * @param string $key the interwiki prefix (e.g. "MeatBall")
389 * @return the associated URL, containing "$1", which should be
390 * replaced by an article title
394 function getInterwikiLink( $key ) {
395 global $wgMemc, $wgInterwikiExpiry;
396 global $wgInterwikiCache, $wgContLang;
397 $fname = 'Title::getInterwikiLink';
399 $key = $wgContLang->lc( $key );
401 $k = wfMemcKey( 'interwiki', $key );
402 if( array_key_exists( $k, Title
::$interwikiCache ) ) {
403 return Title
::$interwikiCache[$k]->iw_url
;
406 if ($wgInterwikiCache) {
407 return Title
::getInterwikiCached( $key );
410 $s = $wgMemc->get( $k );
411 # Ignore old keys with no iw_local
412 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
413 Title
::$interwikiCache[$k] = $s;
417 $dbr =& wfGetDB( DB_SLAVE
);
418 $res = $dbr->select( 'interwiki',
419 array( 'iw_url', 'iw_local', 'iw_trans' ),
420 array( 'iw_prefix' => $key ), $fname );
425 $s = $dbr->fetchObject( $res );
427 # Cache non-existence: create a blank object and save it to memcached
433 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
434 Title
::$interwikiCache[$k] = $s;
440 * Fetch interwiki prefix data from local cache in constant database
442 * More logic is explained in DefaultSettings
444 * @return string URL of interwiki site
447 function getInterwikiCached( $key ) {
448 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
452 $db=dba_open($wgInterwikiCache,'r','cdb');
453 /* Resolve site name */
454 if ($wgInterwikiScopes>=3 and !$site) {
455 $site = dba_fetch('__sites:' . wfWikiID(), $db);
457 $site = $wgInterwikiFallbackSite;
459 $value = dba_fetch( wfMemcKey( $key ), $db);
460 if ($value=='' and $wgInterwikiScopes>=3) {
462 $value = dba_fetch("_{$site}:{$key}", $db);
464 if ($value=='' and $wgInterwikiScopes>=2) {
466 $value = dba_fetch("__global:{$key}", $db);
475 list($local,$url)=explode(' ',$value,2);
477 $s->iw_local
=(int)$local;
479 Title
::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
483 * Determine whether the object refers to a page within
486 * @return bool TRUE if this is an in-project interwiki link
487 * or a wikilink, FALSE otherwise
491 if ( $this->mInterwiki
!= '' ) {
492 # Make sure key is loaded into cache
493 $this->getInterwikiLink( $this->mInterwiki
);
494 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
495 return (bool)(Title
::$interwikiCache[$k]->iw_local
);
502 * Determine whether the object refers to a page within
503 * this project and is transcludable.
505 * @return bool TRUE if this is transcludable
509 if ($this->mInterwiki
== '')
511 # Make sure key is loaded into cache
512 $this->getInterwikiLink( $this->mInterwiki
);
513 $k = wfMemcKey( 'interwiki', $this->mInterwiki
);
514 return (bool)(Title
::$interwikiCache[$k]->iw_trans
);
518 * Update the page_touched field for an array of title objects
519 * @todo Inefficient unless the IDs are already loaded into the
521 * @param array $titles an array of Title objects to be touched
522 * @param string $timestamp the timestamp to use instead of the
523 * default current time
527 function touchArray( $titles, $timestamp = '' ) {
529 if ( count( $titles ) == 0 ) {
532 $dbw =& wfGetDB( DB_MASTER
);
533 if ( $timestamp == '' ) {
534 $timestamp = $dbw->timestamp();
537 $page = $dbw->tableName( 'page' );
538 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
541 foreach ( $titles as $title ) {
542 if ( $wgUseFileCache ) {
543 $cm = new HTMLFileCache($title);
544 @unlink($cm->fileCacheName());
551 $sql .= $title->getArticleID();
555 $dbw->query( $sql, 'Title::touchArray' );
558 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
559 // do them in small chunks:
560 $fname = 'Title::touchArray';
561 foreach( $titles as $title ) {
562 $dbw->update( 'page',
563 array( 'page_touched' => $timestamp ),
565 'page_namespace' => $title->getNamespace(),
566 'page_title' => $title->getDBkey() ),
571 #----------------------------------------------------------------------------
573 #----------------------------------------------------------------------------
575 /** Simple accessors */
577 * Get the text form (spaces not underscores) of the main part
581 function getText() { return $this->mTextform
; }
583 * Get the URL-encoded form of the main part
587 function getPartialURL() { return $this->mUrlform
; }
589 * Get the main part with underscores
593 function getDBkey() { return $this->mDbkeyform
; }
595 * Get the namespace index, i.e. one of the NS_xxxx constants
599 function getNamespace() { return $this->mNamespace
; }
601 * Get the namespace text
605 function getNsText() {
607 return $wgContLang->getNsText( $this->mNamespace
);
610 * Get the namespace text of the subject (rather than talk) page
614 function getSubjectNsText() {
616 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
620 * Get the namespace text of the talk page
623 function getTalkNsText() {
625 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace
) ) );
629 * Could this title have a corresponding talk page?
633 return( Namespace::canTalk( $this->mNamespace
) );
637 * Get the interwiki prefix (or null string)
641 function getInterwiki() { return $this->mInterwiki
; }
643 * Get the Title fragment (i.e. the bit after the #)
647 function getFragment() { return $this->mFragment
; }
649 * Get the default namespace index, for when there is no namespace
653 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
656 * Get title for search index
657 * @return string a stripped-down title string ready for the
660 function getIndexTitle() {
661 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
665 * Get the prefixed database key form
666 * @return string the prefixed title, with underscores and
667 * any interwiki and namespace prefixes
670 function getPrefixedDBkey() {
671 $s = $this->prefix( $this->mDbkeyform
);
672 $s = str_replace( ' ', '_', $s );
677 * Get the prefixed title with spaces.
678 * This is the form usually used for display
679 * @return string the prefixed title, with spaces
682 function getPrefixedText() {
683 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
684 $s = $this->prefix( $this->mTextform
);
685 $s = str_replace( '_', ' ', $s );
686 $this->mPrefixedText
= $s;
688 return $this->mPrefixedText
;
692 * Get the prefixed title with spaces, plus any fragment
693 * (part beginning with '#')
694 * @return string the prefixed title, with spaces and
695 * the fragment, including '#'
698 function getFullText() {
699 $text = $this->getPrefixedText();
700 if( '' != $this->mFragment
) {
701 $text .= '#' . $this->mFragment
;
707 * Get the base name, i.e. the leftmost parts before the /
708 * @return string Base name
710 function getBaseText() {
711 global $wgNamespacesWithSubpages;
712 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
713 $parts = explode( '/', $this->getText() );
714 # Don't discard the real title if there's no subpage involved
715 if( count( $parts ) > 1 )
716 unset( $parts[ count( $parts ) - 1 ] );
717 return implode( '/', $parts );
719 return $this->getText();
724 * Get the lowest-level subpage name, i.e. the rightmost part after /
725 * @return string Subpage name
727 function getSubpageText() {
728 global $wgNamespacesWithSubpages;
729 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace
] ) && $wgNamespacesWithSubpages[ $this->mNamespace
] ) {
730 $parts = explode( '/', $this->mTextform
);
731 return( $parts[ count( $parts ) - 1 ] );
733 return( $this->mTextform
);
738 * Get a URL-encoded form of the subpage text
739 * @return string URL-encoded subpage name
741 function getSubpageUrlForm() {
742 $text = $this->getSubpageText();
743 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
744 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
749 * Get a URL-encoded title (not an actual URL) including interwiki
750 * @return string the URL-encoded form
753 function getPrefixedURL() {
754 $s = $this->prefix( $this->mDbkeyform
);
755 $s = str_replace( ' ', '_', $s );
757 $s = wfUrlencode ( $s ) ;
759 # Cleaning up URL to make it look nice -- is this safe?
760 $s = str_replace( '%28', '(', $s );
761 $s = str_replace( '%29', ')', $s );
767 * Get a real URL referring to this title, with interwiki link and
770 * @param string $query an optional query string, not used
771 * for interwiki links
772 * @param string $variant language variant of url (for sr, zh..)
773 * @return string the URL
776 function getFullURL( $query = '', $variant = false ) {
777 global $wgContLang, $wgServer, $wgRequest;
779 if ( '' == $this->mInterwiki
) {
780 $url = $this->getLocalUrl( $query, $variant );
782 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
783 // Correct fix would be to move the prepending elsewhere.
784 if ($wgRequest->getVal('action') != 'render') {
785 $url = $wgServer . $url;
788 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
790 $namespace = $wgContLang->getNsText( $this->mNamespace
);
791 if ( '' != $namespace ) {
792 # Can this actually happen? Interwikis shouldn't be parsed.
795 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
797 if( false === strpos( $url, '?' ) ) {
806 # Finally, add the fragment.
807 if ( '' != $this->mFragment
) {
808 $url .= '#' . $this->mFragment
;
811 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
816 * Get a URL with no fragment or server name. If this page is generated
817 * with action=render, $wgServer is prepended.
818 * @param string $query an optional query string; if not specified,
819 * $wgArticlePath will be used.
820 * @param string $variant language variant of url (for sr, zh..)
821 * @return string the URL
824 function getLocalURL( $query = '', $variant = false ) {
825 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
826 global $wgVariantArticlePath, $wgContLang, $wgUser;
828 // internal links should point to same variant as current page (only anonymous users)
829 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
830 $pref = $wgContLang->getPreferredVariant(false);
831 if($pref != $wgContLang->getCode())
835 if ( $this->isExternal() ) {
836 $url = $this->getFullURL();
838 // This is currently only used for edit section links in the
839 // context of interwiki transclusion. In theory we should
840 // append the query to the end of any existing query string,
841 // but interwiki transclusion is already broken in that case.
845 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
846 if ( $query == '' ) {
847 if($variant!=false && $wgContLang->hasVariants()){
848 if($wgVariantArticlePath==false)
849 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
851 $variantArticlePath = $wgVariantArticlePath;
853 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
854 $url = str_replace( '$1', $dbkey, $url );
858 $url = str_replace( '$1', $dbkey, $wgArticlePath );
860 global $wgActionPaths;
862 if( !empty( $wgActionPaths ) &&
863 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
865 $action = urldecode( $matches[2] );
866 if( isset( $wgActionPaths[$action] ) ) {
867 $query = $matches[1];
868 if( isset( $matches[4] ) ) $query .= $matches[4];
869 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
870 if( $query != '' ) $url .= '?' . $query;
873 if ( $url === false ) {
874 if ( $query == '-' ) {
877 $url = "{$wgScript}?title={$dbkey}&{$query}";
881 // FIXME: this causes breakage in various places when we
882 // actually expected a local URL and end up with dupe prefixes.
883 if ($wgRequest->getVal('action') == 'render') {
884 $url = $wgServer . $url;
887 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
892 * Get an HTML-escaped version of the URL form, suitable for
893 * using in a link, without a server name or fragment
894 * @param string $query an optional query string
895 * @return string the URL
898 function escapeLocalURL( $query = '' ) {
899 return htmlspecialchars( $this->getLocalURL( $query ) );
903 * Get an HTML-escaped version of the URL form, suitable for
904 * using in a link, including the server name and fragment
906 * @return string the URL
907 * @param string $query an optional query string
910 function escapeFullURL( $query = '' ) {
911 return htmlspecialchars( $this->getFullURL( $query ) );
915 * Get the URL form for an internal link.
916 * - Used in various Squid-related code, in case we have a different
917 * internal hostname for the server from the exposed one.
919 * @param string $query an optional query string
920 * @param string $variant language variant of url (for sr, zh..)
921 * @return string the URL
924 function getInternalURL( $query = '', $variant = false ) {
925 global $wgInternalServer;
926 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
927 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
932 * Get the edit URL for this Title
933 * @return string the URL, or a null string if this is an
937 function getEditURL() {
938 if ( '' != $this->mInterwiki
) { return ''; }
939 $s = $this->getLocalURL( 'action=edit' );
945 * Get the HTML-escaped displayable text form.
946 * Used for the title field in <a> tags.
947 * @return string the text, including any prefixes
950 function getEscapedText() {
951 return htmlspecialchars( $this->getPrefixedText() );
955 * Is this Title interwiki?
959 function isExternal() { return ( '' != $this->mInterwiki
); }
962 * Is this page "semi-protected" - the *only* protection is autoconfirm?
964 * @param string Action to check (default: edit)
967 function isSemiProtected( $action = 'edit' ) {
968 $restrictions = $this->getRestrictions( $action );
969 # We do a full compare because this could be an array
970 foreach( $restrictions as $restriction ) {
971 if( strtolower( $restriction ) != 'autoconfirmed' ) {
979 * Does the title correspond to a protected article?
980 * @param string $what the action the page is protected from,
981 * by default checks move and edit
985 function isProtected( $action = '' ) {
986 global $wgRestrictionLevels;
987 if ( -1 == $this->mNamespace
) { return true; }
989 if( $action == 'edit' ||
$action == '' ) {
990 $r = $this->getRestrictions( 'edit' );
991 foreach( $wgRestrictionLevels as $level ) {
992 if( in_array( $level, $r ) && $level != '' ) {
998 if( $action == 'move' ||
$action == '' ) {
999 $r = $this->getRestrictions( 'move' );
1000 foreach( $wgRestrictionLevels as $level ) {
1001 if( in_array( $level, $r ) && $level != '' ) {
1011 * Is $wgUser is watching this page?
1015 function userIsWatching() {
1018 if ( is_null( $this->mWatched
) ) {
1019 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
1020 $this->mWatched
= false;
1022 $this->mWatched
= $wgUser->isWatched( $this );
1025 return $this->mWatched
;
1029 * Can $wgUser perform $action this page?
1030 * @param string $action action that permission needs to be checked for
1034 function userCan($action) {
1035 $fname = 'Title::userCan';
1036 wfProfileIn( $fname );
1041 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
1042 if ( $result !== null ) {
1043 wfProfileOut( $fname );
1047 if( NS_SPECIAL
== $this->mNamespace
) {
1048 wfProfileOut( $fname );
1051 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
1052 // from taking effect -ævar
1053 if( NS_MEDIAWIKI
== $this->mNamespace
&&
1054 !$wgUser->isAllowed('editinterface') ) {
1055 wfProfileOut( $fname );
1059 if( $this->mDbkeyform
== '_' ) {
1060 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1061 wfProfileOut( $fname );
1065 # protect css/js subpages of user pages
1066 # XXX: this might be better using restrictions
1067 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1068 if( NS_USER
== $this->mNamespace
1069 && preg_match("/\\.(css|js)$/", $this->mTextform
)
1070 && !$wgUser->isAllowed('editinterface')
1071 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
1072 wfProfileOut( $fname );
1076 foreach( $this->getRestrictions($action) as $right ) {
1077 // Backwards compatibility, rewrite sysop -> protect
1078 if ( $right == 'sysop' ) {
1081 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1082 wfProfileOut( $fname );
1087 if( $action == 'move' &&
1088 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1089 wfProfileOut( $fname );
1093 if( $action == 'create' ) {
1094 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1095 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1096 wfProfileOut( $fname );
1101 wfProfileOut( $fname );
1106 * Can $wgUser edit this page?
1110 function userCanEdit() {
1111 return $this->userCan('edit');
1115 * Can $wgUser create this page?
1119 function userCanCreate() {
1120 return $this->userCan('create');
1124 * Can $wgUser move this page?
1128 function userCanMove() {
1129 return $this->userCan('move');
1133 * Would anybody with sufficient privileges be able to move this page?
1134 * Some pages just aren't movable.
1139 function isMovable() {
1140 return Namespace::isMovable( $this->getNamespace() )
1141 && $this->getInterwiki() == '';
1145 * Can $wgUser read this page?
1149 function userCanRead() {
1153 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1154 if ( $result !== null ) {
1158 if( $wgUser->isAllowed('read') ) {
1161 global $wgWhitelistRead;
1163 /** If anon users can create an account,
1164 they need to reach the login page first! */
1165 if( $wgUser->isAllowed( 'createaccount' )
1166 && $this->getNamespace() == NS_SPECIAL
1167 && $this->getText() == 'Userlogin' ) {
1171 /** some pages are explicitly allowed */
1172 $name = $this->getPrefixedText();
1173 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1177 # Compatibility with old settings
1178 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1179 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1188 * Is this a talk page of some sort?
1192 function isTalkPage() {
1193 return Namespace::isTalk( $this->getNamespace() );
1197 * Is this a .css or .js subpage of a user page?
1201 function isCssJsSubpage() {
1202 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1205 * Is this a *valid* .css or .js subpage of a user page?
1206 * Check that the corresponding skin exists
1208 function isValidCssJsSubpage() {
1209 if ( $this->isCssJsSubpage() ) {
1210 $skinNames = Skin
::getSkinNames();
1211 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1217 * Trim down a .css or .js subpage title to get the corresponding skin name
1219 function getSkinFromCssJsSubpage() {
1220 $subpage = explode( '/', $this->mTextform
);
1221 $subpage = $subpage[ count( $subpage ) - 1 ];
1222 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1225 * Is this a .css subpage of a user page?
1229 function isCssSubpage() {
1230 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1233 * Is this a .js subpage of a user page?
1237 function isJsSubpage() {
1238 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1241 * Protect css/js subpages of user pages: can $wgUser edit
1245 * @todo XXX: this might be better using restrictions
1248 function userCanEditCssJsSubpage() {
1250 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1254 * Loads a string into mRestrictions array
1255 * @param string $res restrictions in string format
1258 function loadRestrictions( $res ) {
1259 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1260 $temp = explode( '=', trim( $restrict ) );
1261 if(count($temp) == 1) {
1262 // old format should be treated as edit/move restriction
1263 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1264 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1266 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1269 $this->mRestrictionsLoaded
= true;
1273 * Accessor/initialisation for mRestrictions
1274 * @param string $action action that permission needs to be checked for
1275 * @return array the array of groups allowed to edit this article
1278 function getRestrictions($action) {
1279 $id = $this->getArticleID();
1280 if ( 0 == $id ) { return array(); }
1282 if ( ! $this->mRestrictionsLoaded
) {
1283 $dbr =& wfGetDB( DB_SLAVE
);
1284 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1285 $this->loadRestrictions( $res );
1287 if( isset( $this->mRestrictions
[$action] ) ) {
1288 return $this->mRestrictions
[$action];
1294 * Is there a version of this page in the deletion archive?
1295 * @return int the number of archived revisions
1298 function isDeleted() {
1299 $fname = 'Title::isDeleted';
1300 if ( $this->getNamespace() < 0 ) {
1303 $dbr =& wfGetDB( DB_SLAVE
);
1304 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1305 'ar_title' => $this->getDBkey() ), $fname );
1306 if( $this->getNamespace() == NS_IMAGE
) {
1307 $n +
= $dbr->selectField( 'filearchive', 'COUNT(*)',
1308 array( 'fa_name' => $this->getDBkey() ), $fname );
1315 * Get the article ID for this Title from the link cache,
1316 * adding it if necessary
1317 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1319 * @return int the ID
1322 function getArticleID( $flags = 0 ) {
1323 $linkCache =& LinkCache
::singleton();
1324 if ( $flags & GAID_FOR_UPDATE
) {
1325 $oldUpdate = $linkCache->forUpdate( true );
1326 $this->mArticleID
= $linkCache->addLinkObj( $this );
1327 $linkCache->forUpdate( $oldUpdate );
1329 if ( -1 == $this->mArticleID
) {
1330 $this->mArticleID
= $linkCache->addLinkObj( $this );
1333 return $this->mArticleID
;
1336 function getLatestRevID() {
1337 if ($this->mLatestID
!== false)
1338 return $this->mLatestID
;
1340 $db =& wfGetDB(DB_SLAVE
);
1341 return $this->mLatestID
= $db->selectField( 'revision',
1343 array('rev_page' => $this->getArticleID()),
1344 'Title::getLatestRevID' );
1348 * This clears some fields in this object, and clears any associated
1349 * keys in the "bad links" section of the link cache.
1351 * - This is called from Article::insertNewArticle() to allow
1352 * loading of the new page_id. It's also called from
1353 * Article::doDeleteArticle()
1355 * @param int $newid the new Article ID
1358 function resetArticleID( $newid ) {
1359 $linkCache =& LinkCache
::singleton();
1360 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1362 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1363 else { $this->mArticleID
= $newid; }
1364 $this->mRestrictionsLoaded
= false;
1365 $this->mRestrictions
= array();
1369 * Updates page_touched for this page; called from LinksUpdate.php
1370 * @return bool true if the update succeded
1373 function invalidateCache() {
1374 global $wgUseFileCache;
1376 if ( wfReadOnly() ) {
1380 $dbw =& wfGetDB( DB_MASTER
);
1381 $success = $dbw->update( 'page',
1383 'page_touched' => $dbw->timestamp()
1384 ), array( /* WHERE */
1385 'page_namespace' => $this->getNamespace() ,
1386 'page_title' => $this->getDBkey()
1387 ), 'Title::invalidateCache'
1390 if ($wgUseFileCache) {
1391 $cache = new HTMLFileCache($this);
1392 @unlink
($cache->fileCacheName());
1399 * Prefix some arbitrary text with the namespace or interwiki prefix
1402 * @param string $name the text
1403 * @return string the prefixed text
1406 /* private */ function prefix( $name ) {
1410 if ( '' != $this->mInterwiki
) {
1411 $p = $this->mInterwiki
. ':';
1413 if ( 0 != $this->mNamespace
) {
1414 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1420 * Secure and split - main initialisation function for this object
1422 * Assumes that mDbkeyform has been set, and is urldecoded
1423 * and uses underscores, but not otherwise munged. This function
1424 * removes illegal characters, splits off the interwiki and
1425 * namespace prefixes, sets the other forms, and canonicalizes
1427 * @return bool true on success
1430 /* private */ function secureAndSplit() {
1431 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1432 $fname = 'Title::secureAndSplit';
1435 static $rxTc = false;
1437 # % is needed as well
1438 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1441 $this->mInterwiki
= $this->mFragment
= '';
1442 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1444 # Clean up whitespace
1446 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1447 $t = trim( $t, '_' );
1453 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1454 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1458 $this->mDbkeyform
= $t;
1460 # Initial colon indicates main namespace rather than specified default
1461 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1462 if ( ':' == $t{0} ) {
1463 $this->mNamespace
= NS_MAIN
;
1464 $t = substr( $t, 1 ); # remove the colon but continue processing
1467 # Namespace or interwiki prefix
1470 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1472 $lowerNs = $wgContLang->lc( $p );
1473 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1474 # Canonical namespace
1476 $this->mNamespace
= $ns;
1477 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1478 # Ordinary namespace
1480 $this->mNamespace
= $ns;
1481 } elseif( $this->getInterwikiLink( $p ) ) {
1483 # Can't make a local interwiki link to an interwiki link.
1484 # That's just crazy!
1490 $this->mInterwiki
= $wgContLang->lc( $p );
1492 # Redundant interwiki prefix to the local wiki
1493 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1495 # Can't have an empty self-link
1498 $this->mInterwiki
= '';
1500 # Do another namespace split...
1504 # If there's an initial colon after the interwiki, that also
1505 # resets the default namespace
1506 if ( $t !== '' && $t[0] == ':' ) {
1507 $this->mNamespace
= NS_MAIN
;
1508 $t = substr( $t, 1 );
1511 # If there's no recognized interwiki or namespace,
1512 # then let the colon expression be part of the title.
1518 # We already know that some pages won't be in the database!
1520 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1521 $this->mArticleID
= 0;
1523 $f = strstr( $r, '#' );
1524 if ( false !== $f ) {
1525 $this->mFragment
= substr( $f, 1 );
1526 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1527 # remove whitespace again: prevents "Foo_bar_#"
1528 # becoming "Foo_bar_"
1529 $r = preg_replace( '/_*$/', '', $r );
1532 # Reject illegal characters.
1534 if( preg_match( $rxTc, $r ) ) {
1539 * Pages with "/./" or "/../" appearing in the URLs will
1540 * often be unreachable due to the way web browsers deal
1541 * with 'relative' URLs. Forbid them explicitly.
1543 if ( strpos( $r, '.' ) !== false &&
1544 ( $r === '.' ||
$r === '..' ||
1545 strpos( $r, './' ) === 0 ||
1546 strpos( $r, '../' ) === 0 ||
1547 strpos( $r, '/./' ) !== false ||
1548 strpos( $r, '/../' ) !== false ) )
1553 # We shouldn't need to query the DB for the size.
1554 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1555 if ( strlen( $r ) > 255 ) {
1560 * Normally, all wiki links are forced to have
1561 * an initial capital letter so [[foo]] and [[Foo]]
1562 * point to the same place.
1564 * Don't force it for interwikis, since the other
1565 * site might be case-sensitive.
1567 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1568 $t = $wgContLang->ucfirst( $r );
1574 * Can't make a link to a namespace alone...
1575 * "empty" local links can only be self-links
1576 * with a fragment identifier.
1579 $this->mInterwiki
== '' &&
1580 $this->mNamespace
!= NS_MAIN
) {
1584 // Any remaining initial :s are illegal.
1585 if ( $t !== '' && ':' == $t{0} ) {
1590 $this->mDbkeyform
= $t;
1591 $this->mUrlform
= wfUrlencode( $t );
1593 $this->mTextform
= str_replace( '_', ' ', $t );
1599 * Get a Title object associated with the talk page of this article
1600 * @return Title the object for the talk page
1603 function getTalkPage() {
1604 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1608 * Get a title object associated with the subject page of this
1611 * @return Title the object for the subject page
1614 function getSubjectPage() {
1615 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1619 * Get an array of Title objects linking to this Title
1620 * Also stores the IDs in the link cache.
1622 * WARNING: do not use this function on arbitrary user-supplied titles!
1623 * On heavily-used templates it will max out the memory.
1625 * @param string $options may be FOR UPDATE
1626 * @return array the Title objects linking here
1629 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1630 $linkCache =& LinkCache
::singleton();
1631 $id = $this->getArticleID();
1634 $db =& wfGetDB( DB_MASTER
);
1636 $db =& wfGetDB( DB_SLAVE
);
1639 $res = $db->select( array( 'page', $table ),
1640 array( 'page_namespace', 'page_title', 'page_id' ),
1642 "{$prefix}_from=page_id",
1643 "{$prefix}_namespace" => $this->getNamespace(),
1644 "{$prefix}_title" => $this->getDbKey() ),
1645 'Title::getLinksTo',
1649 if ( $db->numRows( $res ) ) {
1650 while ( $row = $db->fetchObject( $res ) ) {
1651 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1652 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1653 $retVal[] = $titleObj;
1657 $db->freeResult( $res );
1662 * Get an array of Title objects using this Title as a template
1663 * Also stores the IDs in the link cache.
1665 * WARNING: do not use this function on arbitrary user-supplied titles!
1666 * On heavily-used templates it will max out the memory.
1668 * @param string $options may be FOR UPDATE
1669 * @return array the Title objects linking here
1672 function getTemplateLinksTo( $options = '' ) {
1673 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1677 * Get an array of Title objects referring to non-existent articles linked from this page
1679 * @param string $options may be FOR UPDATE
1680 * @return array the Title objects
1683 function getBrokenLinksFrom( $options = '' ) {
1685 $db =& wfGetDB( DB_MASTER
);
1687 $db =& wfGetDB( DB_SLAVE
);
1690 $res = $db->safeQuery(
1691 "SELECT pl_namespace, pl_title
1694 ON pl_namespace=page_namespace
1695 AND pl_title=page_title
1697 AND page_namespace IS NULL
1699 $db->tableName( 'pagelinks' ),
1700 $db->tableName( 'page' ),
1701 $this->getArticleId(),
1705 if ( $db->numRows( $res ) ) {
1706 while ( $row = $db->fetchObject( $res ) ) {
1707 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1710 $db->freeResult( $res );
1716 * Get a list of URLs to purge from the Squid cache when this
1719 * @return array the URLs
1722 function getSquidURLs() {
1726 $this->getInternalURL(),
1727 $this->getInternalURL( 'action=history' )
1730 // purge variant urls as well
1731 if($wgContLang->hasVariants()){
1732 $variants = $wgContLang->getVariants();
1733 foreach($variants as $vCode){
1734 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
1735 $urls[] = $this->getInternalURL('',$vCode);
1742 function purgeSquid() {
1744 if ( $wgUseSquid ) {
1745 $urls = $this->getSquidURLs();
1746 $u = new SquidUpdate( $urls );
1752 * Move this page without authentication
1753 * @param Title &$nt the new page Title
1756 function moveNoAuth( &$nt ) {
1757 return $this->moveTo( $nt, false );
1761 * Check whether a given move operation would be valid.
1762 * Returns true if ok, or a message key string for an error message
1763 * if invalid. (Scarrrrry ugly interface this.)
1764 * @param Title &$nt the new title
1765 * @param bool $auth indicates whether $wgUser's permissions
1767 * @return mixed true on success, message name on failure
1770 function isValidMoveOperation( &$nt, $auth = true ) {
1771 if( !$this or !$nt ) {
1772 return 'badtitletext';
1774 if( $this->equals( $nt ) ) {
1777 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1778 return 'immobile_namespace';
1781 $oldid = $this->getArticleID();
1782 $newid = $nt->getArticleID();
1784 if ( strlen( $nt->getDBkey() ) < 1 ) {
1785 return 'articleexists';
1787 if ( ( '' == $this->getDBkey() ) ||
1789 ( '' == $nt->getDBkey() ) ) {
1790 return 'badarticleerror';
1794 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1795 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1796 return 'protectedpage';
1799 # The move is allowed only if (1) the target doesn't exist, or
1800 # (2) the target is a redirect to the source, and has no history
1801 # (so we can undo bad moves right after they're done).
1803 if ( 0 != $newid ) { # Target exists; check for validity
1804 if ( ! $this->isValidMoveTarget( $nt ) ) {
1805 return 'articleexists';
1812 * Move a title to a new location
1813 * @param Title &$nt the new title
1814 * @param bool $auth indicates whether $wgUser's permissions
1816 * @return mixed true on success, message name on failure
1819 function moveTo( &$nt, $auth = true, $reason = '' ) {
1820 $err = $this->isValidMoveOperation( $nt, $auth );
1821 if( is_string( $err ) ) {
1825 $pageid = $this->getArticleID();
1826 if( $nt->exists() ) {
1827 $this->moveOverExistingRedirect( $nt, $reason );
1828 $pageCountChange = 0;
1829 } else { # Target didn't exist, do normal move.
1830 $this->moveToNewTitle( $nt, $reason );
1831 $pageCountChange = 1;
1833 $redirid = $this->getArticleID();
1835 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1836 $dbw =& wfGetDB( DB_MASTER
);
1837 $categorylinks = $dbw->tableName( 'categorylinks' );
1838 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1839 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1840 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1841 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1845 $oldnamespace = $this->getNamespace() & ~
1;
1846 $newnamespace = $nt->getNamespace() & ~
1;
1847 $oldtitle = $this->getDBkey();
1848 $newtitle = $nt->getDBkey();
1850 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1851 WatchedItem
::duplicateEntries( $this, $nt );
1854 # Update search engine
1855 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1857 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1861 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1862 # Moved out of main namespace
1863 # not viewed, edited, removing
1864 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1865 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1866 # Moved into main namespace
1867 # not viewed, edited, adding
1868 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1869 } elseif ( $pageCountChange ) {
1871 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1880 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1885 * Move page to a title which is at present a redirect to the
1888 * @param Title &$nt the page to move to, which should currently
1892 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1894 $fname = 'Title::moveOverExistingRedirect';
1895 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1898 $comment .= ": $reason";
1901 $now = wfTimestampNow();
1903 $newid = $nt->getArticleID();
1904 $oldid = $this->getArticleID();
1905 $dbw =& wfGetDB( DB_MASTER
);
1906 $linkCache =& LinkCache
::singleton();
1908 # Delete the old redirect. We don't save it to history since
1909 # by definition if we've got here it's rather uninteresting.
1910 # We have to remove it so that the next step doesn't trigger
1911 # a conflict on the unique namespace+title index...
1912 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1914 # Save a null revision in the page's history notifying of the move
1915 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1916 $nullRevId = $nullRevision->insertOn( $dbw );
1918 # Change the name of the target page:
1919 $dbw->update( 'page',
1921 'page_touched' => $dbw->timestamp($now),
1922 'page_namespace' => $nt->getNamespace(),
1923 'page_title' => $nt->getDBkey(),
1924 'page_latest' => $nullRevId,
1926 /* WHERE */ array( 'page_id' => $oldid ),
1929 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1931 # Recreate the redirect, this time in the other direction.
1932 $mwRedir = MagicWord
::get( 'redirect' );
1933 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1934 $redirectArticle = new Article( $this );
1935 $newid = $redirectArticle->insertOn( $dbw );
1936 $redirectRevision = new Revision( array(
1938 'comment' => $comment,
1939 'text' => $redirectText ) );
1940 $revid = $redirectRevision->insertOn( $dbw );
1941 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1942 $linkCache->clearLink( $this->getPrefixedDBkey() );
1945 $log = new LogPage( 'move' );
1946 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1948 # Now, we record the link from the redirect to the new title.
1949 # It should have no other outgoing links...
1950 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1951 $dbw->insert( 'pagelinks',
1953 'pl_from' => $newid,
1954 'pl_namespace' => $nt->getNamespace(),
1955 'pl_title' => $nt->getDbKey() ),
1959 if ( $wgUseSquid ) {
1960 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1961 $u = new SquidUpdate( $urls );
1967 * Move page to non-existing title.
1968 * @param Title &$nt the new Title
1971 function moveToNewTitle( &$nt, $reason = '' ) {
1973 $fname = 'MovePageForm::moveToNewTitle';
1974 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1976 $comment .= ": $reason";
1979 $newid = $nt->getArticleID();
1980 $oldid = $this->getArticleID();
1981 $dbw =& wfGetDB( DB_MASTER
);
1982 $now = $dbw->timestamp();
1984 $linkCache =& LinkCache
::singleton();
1986 # Save a null revision in the page's history notifying of the move
1987 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1988 $nullRevId = $nullRevision->insertOn( $dbw );
1991 $dbw->update( 'page',
1993 'page_touched' => $now,
1994 'page_namespace' => $nt->getNamespace(),
1995 'page_title' => $nt->getDBkey(),
1996 'page_latest' => $nullRevId,
1998 /* WHERE */ array( 'page_id' => $oldid ),
2002 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2005 $mwRedir = MagicWord
::get( 'redirect' );
2006 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2007 $redirectArticle = new Article( $this );
2008 $newid = $redirectArticle->insertOn( $dbw );
2009 $redirectRevision = new Revision( array(
2011 'comment' => $comment,
2012 'text' => $redirectText ) );
2013 $revid = $redirectRevision->insertOn( $dbw );
2014 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2015 $linkCache->clearLink( $this->getPrefixedDBkey() );
2018 $log = new LogPage( 'move' );
2019 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2021 # Purge caches as per article creation
2022 Article
::onArticleCreate( $nt );
2024 # Record the just-created redirect's linking to the page
2025 $dbw->insert( 'pagelinks',
2027 'pl_from' => $newid,
2028 'pl_namespace' => $nt->getNamespace(),
2029 'pl_title' => $nt->getDBkey() ),
2032 # Purge old title from squid
2033 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2034 $this->purgeSquid();
2038 * Checks if $this can be moved to a given Title
2039 * - Selects for update, so don't call it unless you mean business
2041 * @param Title &$nt the new title to check
2044 function isValidMoveTarget( $nt ) {
2046 $fname = 'Title::isValidMoveTarget';
2047 $dbw =& wfGetDB( DB_MASTER
);
2050 $id = $nt->getArticleID();
2051 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2052 array( 'page_is_redirect','old_text','old_flags' ),
2053 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2054 $fname, 'FOR UPDATE' );
2056 if ( !$obj ||
0 == $obj->page_is_redirect
) {
2058 wfDebug( __METHOD__
. ": not a redirect\n" );
2061 $text = Revision
::getRevisionText( $obj );
2063 # Does the redirect point to the source?
2064 # Or is it a broken self-redirect, usually caused by namespace collisions?
2065 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2066 $redirTitle = Title
::newFromText( $m[1] );
2067 if( !is_object( $redirTitle ) ||
2068 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2069 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2070 wfDebug( __METHOD__
. ": redirect points to other page\n" );
2075 wfDebug( __METHOD__
. ": failsafe\n" );
2079 # Does the article have a history?
2080 $row = $dbw->selectRow( array( 'page', 'revision'),
2082 array( 'page_namespace' => $nt->getNamespace(),
2083 'page_title' => $nt->getDBkey(),
2084 'page_id=rev_page AND page_latest != rev_id'
2085 ), $fname, 'FOR UPDATE'
2088 # Return true if there was no history
2089 return $row === false;
2093 * Create a redirect; fails if the title already exists; does
2096 * @param Title $dest the destination of the redirect
2097 * @param string $comment the comment string describing the move
2098 * @return bool true on success
2101 function createRedirect( $dest, $comment ) {
2102 if ( $this->getArticleID() ) {
2106 $fname = 'Title::createRedirect';
2107 $dbw =& wfGetDB( DB_MASTER
);
2109 $article = new Article( $this );
2110 $newid = $article->insertOn( $dbw );
2111 $revision = new Revision( array(
2113 'comment' => $comment,
2114 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
2116 $revisionId = $revision->insertOn( $dbw );
2117 $article->updateRevisionOn( $dbw, $revision, 0 );
2120 $dbw->insert( 'pagelinks',
2122 'pl_from' => $newid,
2123 'pl_namespace' => $dest->getNamespace(),
2124 'pl_title' => $dest->getDbKey()
2128 Article
::onArticleCreate( $this );
2133 * Get categories to which this Title belongs and return an array of
2134 * categories' names.
2136 * @return array an array of parents in the form:
2137 * $parent => $currentarticle
2140 function getParentCategories() {
2143 $titlekey = $this->getArticleId();
2144 $dbr =& wfGetDB( DB_SLAVE
);
2145 $categorylinks = $dbr->tableName( 'categorylinks' );
2148 $sql = "SELECT * FROM $categorylinks"
2149 ." WHERE cl_from='$titlekey'"
2150 ." AND cl_from <> '0'"
2151 ." ORDER BY cl_sortkey";
2153 $res = $dbr->query ( $sql ) ;
2155 if($dbr->numRows($res) > 0) {
2156 while ( $x = $dbr->fetchObject ( $res ) )
2157 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2158 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
2159 $dbr->freeResult ( $res ) ;
2167 * Get a tree of parent categories
2168 * @param array $children an array with the children in the keys, to check for circular refs
2172 function getParentCategoryTree( $children = array() ) {
2173 $parents = $this->getParentCategories();
2175 if($parents != '') {
2176 foreach($parents as $parent => $current) {
2177 if ( array_key_exists( $parent, $children ) ) {
2178 # Circular reference
2179 $stack[$parent] = array();
2181 $nt = Title
::newFromText($parent);
2183 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2195 * Get an associative array for selecting this title from
2201 function pageCond() {
2202 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2206 * Get the revision ID of the previous revision
2208 * @param integer $revision Revision ID. Get the revision that was before this one.
2209 * @return interger $oldrevision|false
2211 function getPreviousRevisionID( $revision ) {
2212 $dbr =& wfGetDB( DB_SLAVE
);
2213 return $dbr->selectField( 'revision', 'rev_id',
2214 'rev_page=' . intval( $this->getArticleId() ) .
2215 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2219 * Get the revision ID of the next revision
2221 * @param integer $revision Revision ID. Get the revision that was after this one.
2222 * @return interger $oldrevision|false
2224 function getNextRevisionID( $revision ) {
2225 $dbr =& wfGetDB( DB_SLAVE
);
2226 return $dbr->selectField( 'revision', 'rev_id',
2227 'rev_page=' . intval( $this->getArticleId() ) .
2228 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2232 * Compare with another title.
2234 * @param Title $title
2237 function equals( $title ) {
2238 // Note: === is necessary for proper matching of number-like titles.
2239 return $this->getInterwiki() === $title->getInterwiki()
2240 && $this->getNamespace() == $title->getNamespace()
2241 && $this->getDbkey() === $title->getDbkey();
2245 * Check if page exists
2249 return $this->getArticleId() != 0;
2253 * Should a link should be displayed as a known link, just based on its title?
2255 * Currently, a self-link with a fragment and special pages are in
2256 * this category. Special pages never exist in the database.
2258 function isAlwaysKnown() {
2259 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2260 || NS_SPECIAL
== $this->mNamespace
;
2264 * Update page_touched timestamps and send squid purge messages for
2265 * pages linking to this title. May be sent to the job queue depending
2266 * on the number of links. Typically called on create and delete.
2268 function touchLinks() {
2269 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2272 if ( $this->getNamespace() == NS_CATEGORY
) {
2273 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2279 * Get the last touched timestamp
2281 function getTouched() {
2282 $dbr =& wfGetDB( DB_SLAVE
);
2283 $touched = $dbr->selectField( 'page', 'page_touched',
2285 'page_namespace' => $this->getNamespace(),
2286 'page_title' => $this->getDBkey()
2293 * Get a cached value from a global cache that is invalidated when this page changes
2294 * @param string $key the key
2295 * @param callback $callback A callback function which generates the value on cache miss
2297 function getRelatedCache( $memc, $key, $expiry, $callback, $params = array() ) {
2298 $touched = $this->getTouched();
2299 $cacheEntry = $memc->get( $key );
2300 if ( $cacheEntry ) {
2301 if ( $cacheEntry['touched'] >= $touched ) {
2302 return $cacheEntry['value'];
2304 wfDebug( __METHOD__
.": $key expired\n" );
2307 wfDebug( __METHOD__
.": $key not found\n" );
2309 $value = call_user_func_array( $callback, $params );
2310 $cacheEntry = array(
2312 'touched' => $touched
2314 $memc->set( $key, $cacheEntry, $expiry );
2318 function trackbackURL() {
2319 global $wgTitle, $wgScriptPath, $wgServer;
2321 return "$wgServer$wgScriptPath/trackback.php?article="
2322 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2325 function trackbackRDF() {
2326 $url = htmlspecialchars($this->getFullURL());
2327 $title = htmlspecialchars($this->getText());
2328 $tburl = $this->trackbackURL();
2331 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2332 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2333 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2336 dc:identifier=\"$url\"
2338 trackback:ping=\"$tburl\" />
2343 * Generate strings used for xml 'id' names in monobook tabs
2346 function getNamespaceKey() {
2348 switch ($this->getNamespace()) {
2351 return 'nstab-main';
2354 return 'nstab-user';
2356 return 'nstab-media';
2358 return 'nstab-special';
2360 case NS_PROJECT_TALK
:
2361 return 'nstab-project';
2364 return 'nstab-image';
2366 case NS_MEDIAWIKI_TALK
:
2367 return 'nstab-mediawiki';
2369 case NS_TEMPLATE_TALK
:
2370 return 'nstab-template';
2373 return 'nstab-help';
2375 case NS_CATEGORY_TALK
:
2376 return 'nstab-category';
2378 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );