9 require_once( 'normal/UtfNormal.php' );
11 $wgTitleInterwikiCache = array();
12 $wgTitleCache = array();
14 define ( 'GAID_FOR_UPDATE', 1 );
16 # Title::newFromTitle maintains a cache to avoid
17 # expensive re-normalization of commonly used titles.
18 # On a batch operation this can become a memory leak
19 # if not bounded. After hitting this many titles,
21 define( 'MW_TITLECACHE_MAX', 1000 );
25 * - Represents a title, which may contain an interwiki designation or namespace
26 * - Can fetch various kinds of data from the database, albeit inefficiently.
32 * All member variables should be considered private
33 * Please use the accessor functions
40 var $mTextform; # Text form (spaces not underscores) of the main part
41 var $mUrlform; # URL-encoded form of the main part
42 var $mDbkeyform; # Main part with underscores
43 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
44 var $mInterwiki; # Interwiki prefix (or null string)
45 var $mFragment; # Title fragment (i.e. the bit after the #)
46 var $mArticleID; # Article ID, fetched from the link cache on demand
47 var $mLatestID; # ID of most recent revision
48 var $mRestrictions; # Array of groups allowed to edit this article
49 # Only null or "sysop" are supported
50 var $mRestrictionsLoaded; # Boolean for initialisation on demand
51 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
52 var $mDefaultNamespace; # Namespace index when there is no namespace
53 # Zero except in {{transclusion}} tags
54 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
62 /* private */ function Title() {
63 $this->mInterwiki
= $this->mUrlform
=
64 $this->mTextform
= $this->mDbkeyform
= '';
65 $this->mArticleID
= -1;
66 $this->mNamespace
= NS_MAIN
;
67 $this->mRestrictionsLoaded
= false;
68 $this->mRestrictions
= array();
69 # Dont change the following, NS_MAIN is hardcoded in several place
71 $this->mDefaultNamespace
= NS_MAIN
;
72 $this->mWatched
= NULL;
73 $this->mLatestID
= false;
77 * Create a new Title from a prefixed DB key
78 * @param string $key The database key, which has underscores
79 * instead of spaces, possibly including namespace and
81 * @return Title the new object, or NULL on an error
85 /* static */ function newFromDBkey( $key ) {
87 $t->mDbkeyform
= $key;
88 if( $t->secureAndSplit() )
95 * Create a new Title from text, such as what one would
96 * find in a link. Decodes any HTML entities in the text.
98 * @param string $text the link text; spaces, prefixes,
99 * and an initial ':' indicating the main namespace
101 * @param int $defaultNamespace the namespace to use if
102 * none is specified by a prefix
103 * @return Title the new object, or NULL on an error
107 function newFromText( $text, $defaultNamespace = NS_MAIN
) {
108 global $wgTitleCache;
109 $fname = 'Title::newFromText';
111 if( is_object( $text ) ) {
112 wfDebugDieBacktrace( 'Title::newFromText given an object' );
116 * Wiki pages often contain multiple links to the same page.
117 * Title normalization and parsing can become expensive on
118 * pages with many links, so we can save a little time by
121 * In theory these are value objects and won't get changed...
123 if( $defaultNamespace == NS_MAIN
&& isset( $wgTitleCache[$text] ) ) {
124 return $wgTitleCache[$text];
128 * Convert things like é ā or 〗 into real text...
130 $filteredText = Sanitizer
::decodeCharReferences( $text );
133 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
134 $t->mDefaultNamespace
= $defaultNamespace;
136 static $cachedcount = 0 ;
137 if( $t->secureAndSplit() ) {
138 if( $defaultNamespace == NS_MAIN
) {
139 if( $cachedcount >= MW_TITLECACHE_MAX
) {
140 # Avoid memory leaks on mass operations...
141 $wgTitleCache = array();
145 $wgTitleCache[$text] =& $t;
155 * Create a new Title from URL-encoded text. Ensures that
156 * the given title's length does not exceed the maximum.
157 * @param string $url the title, as might be taken from a URL
158 * @return Title the new object, or NULL on an error
162 function newFromURL( $url ) {
163 global $wgLegalTitleChars;
166 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
167 # but some URLs used it as a space replacement and they still come
168 # from some external search tools.
169 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
170 $url = str_replace( '+', ' ', $url );
173 $t->mDbkeyform
= str_replace( ' ', '_', $url );
174 if( $t->secureAndSplit() ) {
182 * Create a new Title from an article ID
184 * @todo This is inefficiently implemented, the page row is requested
185 * but not used for anything else
187 * @param int $id the page_id corresponding to the Title to create
188 * @return Title the new object, or NULL on an error
192 function newFromID( $id ) {
193 $fname = 'Title::newFromID';
194 $dbr =& wfGetDB( DB_SLAVE
);
195 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
196 array( 'page_id' => $id ), $fname );
197 if ( $row !== false ) {
198 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
206 * Create a new Title from a namespace index and a DB key.
207 * It's assumed that $ns and $title are *valid*, for instance when
208 * they came directly from the database or a special page name.
209 * For convenience, spaces are converted to underscores so that
210 * eg user_text fields can be used directly.
212 * @param int $ns the namespace of the article
213 * @param string $title the unprefixed database key form
214 * @return Title the new object
218 function &makeTitle( $ns, $title ) {
222 $t->mNamespace
= intval( $ns );
223 $t->mDbkeyform
= str_replace( ' ', '_', $title );
224 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
225 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
226 $t->mTextform
= str_replace( '_', ' ', $title );
231 * Create a new Title frrom a namespace index and a DB key.
232 * The parameters will be checked for validity, which is a bit slower
233 * than makeTitle() but safer for user-provided data.
235 * @param int $ns the namespace of the article
236 * @param string $title the database key form
237 * @return Title the new object, or NULL on an error
241 function makeTitleSafe( $ns, $title ) {
243 $t->mDbkeyform
= Title
::makeName( $ns, $title );
244 if( $t->secureAndSplit() ) {
252 * Create a new Title for the Main Page
255 * @return Title the new object
258 function newMainPage() {
259 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
263 * Create a new Title for a redirect
264 * @param string $text the redirect title text
265 * @return Title the new object, or NULL if the text is not a
270 function newFromRedirect( $text ) {
273 if ( $wgMwRedir->matchStart( $text ) ) {
274 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
275 # categories are escaped using : for example one can enter:
276 # #REDIRECT [[:Category:Music]]. Need to remove it.
277 if ( substr($m[1],0,1) == ':') {
278 # We don't want to keep the ':'
279 $m[1] = substr( $m[1], 1 );
282 $rt = Title
::newFromText( $m[1] );
283 # Disallow redirects to Special:Userlogout
284 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
292 #----------------------------------------------------------------------------
294 #----------------------------------------------------------------------------
297 * Get the prefixed DB key associated with an ID
298 * @param int $id the page_id of the article
299 * @return Title an object representing the article, or NULL
300 * if no such article was found
304 function nameOf( $id ) {
305 $fname = 'Title::nameOf';
306 $dbr =& wfGetDB( DB_SLAVE
);
308 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
309 if ( $s === false ) { return NULL; }
311 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
316 * Get a regex character class describing the legal characters in a link
317 * @return string the list of characters, not delimited
321 function legalChars() {
322 global $wgLegalTitleChars;
323 return $wgLegalTitleChars;
327 * Get a string representation of a title suitable for
328 * including in a search index
330 * @param int $ns a namespace index
331 * @param string $title text-form main part
332 * @return string a stripped-down title string ready for the
335 /* static */ function indexTitle( $ns, $title ) {
337 require_once( 'SearchEngine.php' );
339 $lc = SearchEngine
::legalSearchChars() . '&#;';
340 $t = $wgContLang->stripForSearch( $title );
341 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
342 $t = strtolower( $t );
345 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
346 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
348 $t = preg_replace( "/\\s+/", ' ', $t );
350 if ( $ns == NS_IMAGE
) {
351 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
357 * Make a prefixed DB key from a DB key and a namespace index
358 * @param int $ns numerical representation of the namespace
359 * @param string $title the DB key form the title
360 * @return string the prefixed form of the title
362 /* static */ function makeName( $ns, $title ) {
365 $n = $wgContLang->getNsText( $ns );
366 return $n == '' ?
$title : "$n:$title";
370 * Returns the URL associated with an interwiki prefix
371 * @param string $key the interwiki prefix (e.g. "MeatBall")
372 * @return the associated URL, containing "$1", which should be
373 * replaced by an article title
377 function getInterwikiLink( $key ) {
378 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
379 global $wgInterwikiCache;
380 $fname = 'Title::getInterwikiLink';
382 $key = strtolower( $key );
384 $k = $wgDBname.':interwiki:'.$key;
385 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
386 return $wgTitleInterwikiCache[$k]->iw_url
;
389 if ($wgInterwikiCache) {
390 return Title
::getInterwikiCached( $key );
393 $s = $wgMemc->get( $k );
394 # Ignore old keys with no iw_local
395 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
396 $wgTitleInterwikiCache[$k] = $s;
400 $dbr =& wfGetDB( DB_SLAVE
);
401 $res = $dbr->select( 'interwiki',
402 array( 'iw_url', 'iw_local', 'iw_trans' ),
403 array( 'iw_prefix' => $key ), $fname );
408 $s = $dbr->fetchObject( $res );
410 # Cache non-existence: create a blank object and save it to memcached
416 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
417 $wgTitleInterwikiCache[$k] = $s;
423 * Fetch interwiki prefix data from local cache in constant database
425 * More logic is explained in DefaultSettings
427 * @return string URL of interwiki site
430 function getInterwikiCached( $key ) {
431 global $wgDBname, $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
432 global $wgTitleInterwikiCache;
436 $db=dba_open($wgInterwikiCache,'r','cdb');
437 /* Resolve site name */
438 if ($wgInterwikiScopes>=3 and !$site) {
439 $site = dba_fetch("__sites:{$wgDBname}", $db);
441 $site = $wgInterwikiFallbackSite;
443 $value = dba_fetch("{$wgDBname}:{$key}", $db);
444 if ($value=='' and $wgInterwikiScopes>=3) {
446 $value = dba_fetch("_{$site}:{$key}", $db);
448 if ($value=='' and $wgInterwikiScopes>=2) {
450 $value = dba_fetch("__global:{$key}", $db);
459 list($local,$url)=explode(' ',$value,2);
461 $s->iw_local
=(int)$local;
463 $wgTitleInterwikiCache[$wgDBname.':interwiki:'.$key] = $s;
467 * Determine whether the object refers to a page within
470 * @return bool TRUE if this is an in-project interwiki link
471 * or a wikilink, FALSE otherwise
475 global $wgTitleInterwikiCache, $wgDBname;
477 if ( $this->mInterwiki
!= '' ) {
478 # Make sure key is loaded into cache
479 $this->getInterwikiLink( $this->mInterwiki
);
480 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
481 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
488 * Determine whether the object refers to a page within
489 * this project and is transcludable.
491 * @return bool TRUE if this is transcludable
495 global $wgTitleInterwikiCache, $wgDBname;
497 if ($this->mInterwiki
== '')
499 # Make sure key is loaded into cache
500 $this->getInterwikiLink( $this->mInterwiki
);
501 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
502 return (bool)($wgTitleInterwikiCache[$k]->iw_trans
);
506 * Update the page_touched field for an array of title objects
507 * @todo Inefficient unless the IDs are already loaded into the
509 * @param array $titles an array of Title objects to be touched
510 * @param string $timestamp the timestamp to use instead of the
511 * default current time
515 function touchArray( $titles, $timestamp = '' ) {
517 if ( count( $titles ) == 0 ) {
520 $dbw =& wfGetDB( DB_MASTER
);
521 if ( $timestamp == '' ) {
522 $timestamp = $dbw->timestamp();
525 $page = $dbw->tableName( 'page' );
526 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
529 foreach ( $titles as $title ) {
530 if ( $wgUseFileCache ) {
531 $cm = new CacheManager($title);
532 @unlink($cm->fileCacheName());
539 $sql .= $title->getArticleID();
543 $dbw->query( $sql, 'Title::touchArray' );
546 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
547 // do them in small chunks:
548 $fname = 'Title::touchArray';
549 foreach( $titles as $title ) {
550 $dbw->update( 'page',
551 array( 'page_touched' => $timestamp ),
553 'page_namespace' => $title->getNamespace(),
554 'page_title' => $title->getDBkey() ),
559 #----------------------------------------------------------------------------
561 #----------------------------------------------------------------------------
563 /** Simple accessors */
565 * Get the text form (spaces not underscores) of the main part
569 function getText() { return $this->mTextform
; }
571 * Get the URL-encoded form of the main part
575 function getPartialURL() { return $this->mUrlform
; }
577 * Get the main part with underscores
581 function getDBkey() { return $this->mDbkeyform
; }
583 * Get the namespace index, i.e. one of the NS_xxxx constants
587 function getNamespace() { return $this->mNamespace
; }
589 * Get the namespace text
593 function getNsText() {
595 return $wgContLang->getNsText( $this->mNamespace
);
598 * Get the namespace text of the subject (rather than talk) page
602 function getSubjectNsText() {
604 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
608 * Get the interwiki prefix (or null string)
612 function getInterwiki() { return $this->mInterwiki
; }
614 * Get the Title fragment (i.e. the bit after the #)
618 function getFragment() { return $this->mFragment
; }
620 * Get the default namespace index, for when there is no namespace
624 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
627 * Get title for search index
628 * @return string a stripped-down title string ready for the
631 function getIndexTitle() {
632 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
636 * Get the prefixed database key form
637 * @return string the prefixed title, with underscores and
638 * any interwiki and namespace prefixes
641 function getPrefixedDBkey() {
642 $s = $this->prefix( $this->mDbkeyform
);
643 $s = str_replace( ' ', '_', $s );
648 * Get the prefixed title with spaces.
649 * This is the form usually used for display
650 * @return string the prefixed title, with spaces
653 function getPrefixedText() {
655 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
656 $s = $this->prefix( $this->mTextform
);
657 $s = str_replace( '_', ' ', $s );
658 $this->mPrefixedText
= $s;
660 return $this->mPrefixedText
;
664 * Get the prefixed title with spaces, plus any fragment
665 * (part beginning with '#')
666 * @return string the prefixed title, with spaces and
667 * the fragment, including '#'
670 function getFullText() {
672 $text = $this->getPrefixedText();
673 if( '' != $this->mFragment
) {
674 $text .= '#' . $this->mFragment
;
680 * Get a URL-encoded title (not an actual URL) including interwiki
681 * @return string the URL-encoded form
684 function getPrefixedURL() {
685 $s = $this->prefix( $this->mDbkeyform
);
686 $s = str_replace( ' ', '_', $s );
688 $s = wfUrlencode ( $s ) ;
690 # Cleaning up URL to make it look nice -- is this safe?
691 $s = str_replace( '%28', '(', $s );
692 $s = str_replace( '%29', ')', $s );
698 * Get a real URL referring to this title, with interwiki link and
701 * @param string $query an optional query string, not used
702 * for interwiki links
703 * @return string the URL
706 function getFullURL( $query = '' ) {
707 global $wgContLang, $wgServer, $wgRequest;
709 if ( '' == $this->mInterwiki
) {
710 $url = $this->getLocalUrl( $query );
712 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
713 // Correct fix would be to move the prepending elsewhere.
714 if ($wgRequest->getVal('action') != 'render') {
715 $url = $wgServer . $url;
718 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
720 $namespace = $wgContLang->getNsText( $this->mNamespace
);
721 if ( '' != $namespace ) {
722 # Can this actually happen? Interwikis shouldn't be parsed.
725 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
727 if( false === strpos( $url, '?' ) ) {
734 if ( '' != $this->mFragment
) {
735 $url .= '#' . $this->mFragment
;
738 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
743 * Get a URL with no fragment or server name. If this page is generated
744 * with action=render, $wgServer is prepended.
745 * @param string $query an optional query string; if not specified,
746 * $wgArticlePath will be used.
747 * @return string the URL
750 function getLocalURL( $query = '' ) {
751 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
753 if ( $this->isExternal() ) {
754 $url = $this->getFullURL();
756 // This is currently only used for edit section links in the
757 // context of interwiki transclusion. In theory we should
758 // append the query to the end of any existing query string,
759 // but interwiki transclusion is already broken in that case.
763 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
764 if ( $query == '' ) {
765 $url = str_replace( '$1', $dbkey, $wgArticlePath );
767 global $wgActionPaths;
769 if( !empty( $wgActionPaths ) &&
770 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
772 $action = urldecode( $matches[2] );
773 if( isset( $wgActionPaths[$action] ) ) {
774 $query = $matches[1];
775 if( isset( $matches[4] ) ) $query .= $matches[4];
776 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
777 if( $query != '' ) $url .= '?' . $query;
780 if ( $url === false ) {
781 if ( $query == '-' ) {
784 $url = "{$wgScript}?title={$dbkey}&{$query}";
788 // FIXME: this causes breakage in various places when we
789 // actually expected a local URL and end up with dupe prefixes.
790 if ($wgRequest->getVal('action') == 'render') {
791 $url = $wgServer . $url;
794 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
799 * Get an HTML-escaped version of the URL form, suitable for
800 * using in a link, without a server name or fragment
801 * @param string $query an optional query string
802 * @return string the URL
805 function escapeLocalURL( $query = '' ) {
806 return htmlspecialchars( $this->getLocalURL( $query ) );
810 * Get an HTML-escaped version of the URL form, suitable for
811 * using in a link, including the server name and fragment
813 * @return string the URL
814 * @param string $query an optional query string
817 function escapeFullURL( $query = '' ) {
818 return htmlspecialchars( $this->getFullURL( $query ) );
822 * Get the URL form for an internal link.
823 * - Used in various Squid-related code, in case we have a different
824 * internal hostname for the server from the exposed one.
826 * @param string $query an optional query string
827 * @return string the URL
830 function getInternalURL( $query = '' ) {
831 global $wgInternalServer;
832 $url = $wgInternalServer . $this->getLocalURL( $query );
833 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
838 * Get the edit URL for this Title
839 * @return string the URL, or a null string if this is an
843 function getEditURL() {
844 global $wgServer, $wgScript;
846 if ( '' != $this->mInterwiki
) { return ''; }
847 $s = $this->getLocalURL( 'action=edit' );
853 * Get the HTML-escaped displayable text form.
854 * Used for the title field in <a> tags.
855 * @return string the text, including any prefixes
858 function getEscapedText() {
859 return htmlspecialchars( $this->getPrefixedText() );
863 * Is this Title interwiki?
867 function isExternal() { return ( '' != $this->mInterwiki
); }
870 * Does the title correspond to a protected article?
871 * @param string $what the action the page is protected from,
872 * by default checks move and edit
876 function isProtected( $action = '' ) {
877 global $wgRestrictionLevels;
878 if ( -1 == $this->mNamespace
) { return true; }
880 if( $action == 'edit' ||
$action == '' ) {
881 $r = $this->getRestrictions( 'edit' );
882 foreach( $wgRestrictionLevels as $level ) {
883 if( in_array( $level, $r ) && $level != '' ) {
889 if( $action == 'move' ||
$action == '' ) {
890 $r = $this->getRestrictions( 'move' );
891 foreach( $wgRestrictionLevels as $level ) {
892 if( in_array( $level, $r ) && $level != '' ) {
902 * Is $wgUser is watching this page?
906 function userIsWatching() {
909 if ( is_null( $this->mWatched
) ) {
910 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
911 $this->mWatched
= false;
913 $this->mWatched
= $wgUser->isWatched( $this );
916 return $this->mWatched
;
920 * Can $wgUser perform $action this page?
921 * @param string $action action that permission needs to be checked for
925 function userCan($action) {
926 $fname = 'Title::userCan';
927 wfProfileIn( $fname );
930 if( NS_SPECIAL
== $this->mNamespace
) {
931 wfProfileOut( $fname );
934 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
935 // from taking effect -ævar
936 if( NS_MEDIAWIKI
== $this->mNamespace
&&
937 !$wgUser->isAllowed('editinterface') ) {
938 wfProfileOut( $fname );
942 if( $this->mDbkeyform
== '_' ) {
943 # FIXME: Is this necessary? Shouldn't be allowed anyway...
944 wfProfileOut( $fname );
948 # protect global styles and js
949 if ( NS_MEDIAWIKI
== $this->mNamespace
950 && preg_match("/\\.(css|js)$/", $this->mTextform
)
951 && !$wgUser->isAllowed('editinterface') ) {
952 wfProfileOut( $fname );
956 # protect css/js subpages of user pages
957 # XXX: this might be better using restrictions
958 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
959 if( NS_USER
== $this->mNamespace
960 && preg_match("/\\.(css|js)$/", $this->mTextform
)
961 && !$wgUser->isAllowed('editinterface')
962 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
963 wfProfileOut( $fname );
967 foreach( $this->getRestrictions($action) as $right ) {
968 // Backwards compatibility, rewrite sysop -> protect
969 if ( $right == 'sysop' ) {
972 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
973 wfProfileOut( $fname );
978 if( $action == 'move' &&
979 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
980 wfProfileOut( $fname );
984 if( $action == 'create' ) {
985 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
986 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
991 wfProfileOut( $fname );
996 * Can $wgUser edit this page?
1000 function userCanEdit() {
1001 return $this->userCan('edit');
1005 * Can $wgUser move this page?
1009 function userCanMove() {
1010 return $this->userCan('move');
1014 * Would anybody with sufficient privileges be able to move this page?
1015 * Some pages just aren't movable.
1020 function isMovable() {
1021 return Namespace::isMovable( $this->getNamespace() )
1022 && $this->getInterwiki() == '';
1026 * Can $wgUser read this page?
1030 function userCanRead() {
1033 if( $wgUser->isAllowed('read') ) {
1036 global $wgWhitelistRead;
1038 /** If anon users can create an account,
1039 they need to reach the login page first! */
1040 if( $wgUser->isAllowed( 'createaccount' )
1041 && $this->getNamespace() == NS_SPECIAL
1042 && $this->getText() == 'Userlogin' ) {
1046 /** some pages are explicitly allowed */
1047 $name = $this->getPrefixedText();
1048 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1052 # Compatibility with old settings
1053 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1054 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1063 * Is this a talk page of some sort?
1067 function isTalkPage() {
1068 return Namespace::isTalk( $this->getNamespace() );
1072 * Is this a .css or .js subpage of a user page?
1076 function isCssJsSubpage() {
1077 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1080 * Is this a .css subpage of a user page?
1084 function isCssSubpage() {
1085 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1088 * Is this a .js subpage of a user page?
1092 function isJsSubpage() {
1093 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1096 * Protect css/js subpages of user pages: can $wgUser edit
1100 * @todo XXX: this might be better using restrictions
1103 function userCanEditCssJsSubpage() {
1105 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1109 * Loads a string into mRestrictions array
1110 * @param string $res restrictions in string format
1113 function loadRestrictions( $res ) {
1114 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1115 $temp = explode( '=', trim( $restrict ) );
1116 if(count($temp) == 1) {
1117 // old format should be treated as edit/move restriction
1118 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1119 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1121 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1124 $this->mRestrictionsLoaded
= true;
1128 * Accessor/initialisation for mRestrictions
1129 * @param string $action action that permission needs to be checked for
1130 * @return array the array of groups allowed to edit this article
1133 function getRestrictions($action) {
1134 $id = $this->getArticleID();
1135 if ( 0 == $id ) { return array(); }
1137 if ( ! $this->mRestrictionsLoaded
) {
1138 $dbr =& wfGetDB( DB_SLAVE
);
1139 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1140 $this->loadRestrictions( $res );
1142 if( isset( $this->mRestrictions
[$action] ) ) {
1143 return $this->mRestrictions
[$action];
1149 * Is there a version of this page in the deletion archive?
1150 * @return int the number of archived revisions
1153 function isDeleted() {
1154 $fname = 'Title::isDeleted';
1155 if ( $this->getNamespace() < 0 ) {
1158 $dbr =& wfGetDB( DB_SLAVE
);
1159 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1160 'ar_title' => $this->getDBkey() ), $fname );
1166 * Get the article ID for this Title from the link cache,
1167 * adding it if necessary
1168 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1170 * @return int the ID
1173 function getArticleID( $flags = 0 ) {
1174 $linkCache =& LinkCache
::singleton();
1175 if ( $flags & GAID_FOR_UPDATE
) {
1176 $oldUpdate = $linkCache->forUpdate( true );
1177 $this->mArticleID
= $linkCache->addLinkObj( $this );
1178 $linkCache->forUpdate( $oldUpdate );
1180 if ( -1 == $this->mArticleID
) {
1181 $this->mArticleID
= $linkCache->addLinkObj( $this );
1184 return $this->mArticleID
;
1187 function getLatestRevID() {
1188 if ($this->mLatestID
!== false)
1189 return $this->mLatestID
;
1191 $db =& wfGetDB(DB_SLAVE
);
1192 return $this->mLatestID
= $db->selectField( 'revision',
1194 array('rev_page' => $this->getArticleID()),
1195 'Title::getLatestRevID' );
1199 * This clears some fields in this object, and clears any associated
1200 * keys in the "bad links" section of the link cache.
1202 * - This is called from Article::insertNewArticle() to allow
1203 * loading of the new page_id. It's also called from
1204 * Article::doDeleteArticle()
1206 * @param int $newid the new Article ID
1209 function resetArticleID( $newid ) {
1210 $linkCache =& LinkCache
::singleton();
1211 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1213 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1214 else { $this->mArticleID
= $newid; }
1215 $this->mRestrictionsLoaded
= false;
1216 $this->mRestrictions
= array();
1220 * Updates page_touched for this page; called from LinksUpdate.php
1221 * @return bool true if the update succeded
1224 function invalidateCache() {
1225 global $wgUseFileCache;
1227 if ( wfReadOnly() ) {
1231 $dbw =& wfGetDB( DB_MASTER
);
1232 $success = $dbw->update( 'page',
1234 'page_touched' => $dbw->timestamp()
1235 ), array( /* WHERE */
1236 'page_namespace' => $this->getNamespace() ,
1237 'page_title' => $this->getDBkey()
1238 ), 'Title::invalidateCache'
1241 if ($wgUseFileCache) {
1242 $cache = new CacheManager($this);
1243 @unlink
($cache->fileCacheName());
1250 * Prefix some arbitrary text with the namespace or interwiki prefix
1253 * @param string $name the text
1254 * @return string the prefixed text
1257 /* private */ function prefix( $name ) {
1261 if ( '' != $this->mInterwiki
) {
1262 $p = $this->mInterwiki
. ':';
1264 if ( 0 != $this->mNamespace
) {
1265 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1271 * Secure and split - main initialisation function for this object
1273 * Assumes that mDbkeyform has been set, and is urldecoded
1274 * and uses underscores, but not otherwise munged. This function
1275 * removes illegal characters, splits off the interwiki and
1276 * namespace prefixes, sets the other forms, and canonicalizes
1278 * @return bool true on success
1281 /* private */ function secureAndSplit() {
1282 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1283 $fname = 'Title::secureAndSplit';
1286 static $rxTc = false;
1288 # % is needed as well
1289 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1292 $this->mInterwiki
= $this->mFragment
= '';
1293 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1295 # Clean up whitespace
1297 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1298 $t = trim( $t, '_' );
1304 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1305 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1309 $this->mDbkeyform
= $t;
1311 # Initial colon indicates main namespace rather than specified default
1312 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1313 if ( ':' == $t{0} ) {
1314 $this->mNamespace
= NS_MAIN
;
1315 $t = substr( $t, 1 ); # remove the colon but continue processing
1318 # Namespace or interwiki prefix
1321 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1323 $lowerNs = strtolower( $p );
1324 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1325 # Canonical namespace
1327 $this->mNamespace
= $ns;
1328 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1329 # Ordinary namespace
1331 $this->mNamespace
= $ns;
1332 } elseif( $this->getInterwikiLink( $p ) ) {
1334 # Can't make a local interwiki link to an interwiki link.
1335 # That's just crazy!
1341 $this->mInterwiki
= strtolower( $p );
1343 # Redundant interwiki prefix to the local wiki
1344 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1346 # Can't have an empty self-link
1349 $this->mInterwiki
= '';
1351 # Do another namespace split...
1355 # If there's an initial colon after the interwiki, that also
1356 # resets the default namespace
1357 if ( $t !== '' && $t[0] == ':' ) {
1358 $this->mNamespace
= NS_MAIN
;
1359 $t = substr( $t, 1 );
1362 # If there's no recognized interwiki or namespace,
1363 # then let the colon expression be part of the title.
1369 # We already know that some pages won't be in the database!
1371 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1372 $this->mArticleID
= 0;
1374 $f = strstr( $r, '#' );
1375 if ( false !== $f ) {
1376 $this->mFragment
= substr( $f, 1 );
1377 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1378 # remove whitespace again: prevents "Foo_bar_#"
1379 # becoming "Foo_bar_"
1380 $r = preg_replace( '/_*$/', '', $r );
1383 # Reject illegal characters.
1385 if( preg_match( $rxTc, $r ) ) {
1390 * Pages with "/./" or "/../" appearing in the URLs will
1391 * often be unreachable due to the way web browsers deal
1392 * with 'relative' URLs. Forbid them explicitly.
1394 if ( strpos( $r, '.' ) !== false &&
1395 ( $r === '.' ||
$r === '..' ||
1396 strpos( $r, './' ) === 0 ||
1397 strpos( $r, '../' ) === 0 ||
1398 strpos( $r, '/./' ) !== false ||
1399 strpos( $r, '/../' ) !== false ) )
1404 # We shouldn't need to query the DB for the size.
1405 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1406 if ( strlen( $r ) > 255 ) {
1411 * Normally, all wiki links are forced to have
1412 * an initial capital letter so [[foo]] and [[Foo]]
1413 * point to the same place.
1415 * Don't force it for interwikis, since the other
1416 * site might be case-sensitive.
1418 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1419 $t = $wgContLang->ucfirst( $r );
1425 * Can't make a link to a namespace alone...
1426 * "empty" local links can only be self-links
1427 * with a fragment identifier.
1430 $this->mInterwiki
== '' &&
1431 $this->mNamespace
!= NS_MAIN
) {
1436 $this->mDbkeyform
= $t;
1437 $this->mUrlform
= wfUrlencode( $t );
1439 $this->mTextform
= str_replace( '_', ' ', $t );
1445 * Get a Title object associated with the talk page of this article
1446 * @return Title the object for the talk page
1449 function getTalkPage() {
1450 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1454 * Get a title object associated with the subject page of this
1457 * @return Title the object for the subject page
1460 function getSubjectPage() {
1461 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1465 * Get an array of Title objects linking to this Title
1466 * Also stores the IDs in the link cache.
1468 * @param string $options may be FOR UPDATE
1469 * @return array the Title objects linking here
1472 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1473 $linkCache =& LinkCache
::singleton();
1474 $id = $this->getArticleID();
1477 $db =& wfGetDB( DB_MASTER
);
1479 $db =& wfGetDB( DB_SLAVE
);
1482 $res = $db->select( array( 'page', $table ),
1483 array( 'page_namespace', 'page_title', 'page_id' ),
1485 "{$prefix}_from=page_id",
1486 "{$prefix}_namespace" => $this->getNamespace(),
1487 "{$prefix}_title" => $this->getDbKey() ),
1488 'Title::getLinksTo',
1492 if ( $db->numRows( $res ) ) {
1493 while ( $row = $db->fetchObject( $res ) ) {
1494 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1495 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1496 $retVal[] = $titleObj;
1500 $db->freeResult( $res );
1505 * Get an array of Title objects using this Title as a template
1506 * Also stores the IDs in the link cache.
1508 * @param string $options may be FOR UPDATE
1509 * @return array the Title objects linking here
1512 function getTemplateLinksTo( $options = '' ) {
1513 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1517 * Get an array of Title objects referring to non-existent articles linked from this page
1519 * @param string $options may be FOR UPDATE
1520 * @return array the Title objects
1523 function getBrokenLinksFrom( $options = '' ) {
1525 $db =& wfGetDB( DB_MASTER
);
1527 $db =& wfGetDB( DB_SLAVE
);
1530 $res = $db->safeQuery(
1531 "SELECT pl_namespace, pl_title
1534 ON pl_namespace=page_namespace
1535 AND pl_title=page_title
1537 AND page_namespace IS NULL
1539 $db->tableName( 'pagelinks' ),
1540 $db->tableName( 'page' ),
1541 $this->getArticleId(),
1545 if ( $db->numRows( $res ) ) {
1546 while ( $row = $db->fetchObject( $res ) ) {
1547 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1550 $db->freeResult( $res );
1556 * Get a list of URLs to purge from the Squid cache when this
1559 * @return array the URLs
1562 function getSquidURLs() {
1564 $this->getInternalURL(),
1565 $this->getInternalURL( 'action=history' )
1570 * Move this page without authentication
1571 * @param Title &$nt the new page Title
1574 function moveNoAuth( &$nt ) {
1575 return $this->moveTo( $nt, false );
1579 * Check whether a given move operation would be valid.
1580 * Returns true if ok, or a message key string for an error message
1581 * if invalid. (Scarrrrry ugly interface this.)
1582 * @param Title &$nt the new title
1583 * @param bool $auth indicates whether $wgUser's permissions
1585 * @return mixed true on success, message name on failure
1588 function isValidMoveOperation( &$nt, $auth = true ) {
1590 if( !$this or !$nt ) {
1591 return 'badtitletext';
1593 if( $this->equals( $nt ) ) {
1596 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1597 return 'immobile_namespace';
1600 $oldid = $this->getArticleID();
1601 $newid = $nt->getArticleID();
1603 if ( strlen( $nt->getDBkey() ) < 1 ) {
1604 return 'articleexists';
1606 if ( ( '' == $this->getDBkey() ) ||
1608 ( '' == $nt->getDBkey() ) ) {
1609 return 'badarticleerror';
1613 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1614 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1615 return 'protectedpage';
1618 # The move is allowed only if (1) the target doesn't exist, or
1619 # (2) the target is a redirect to the source, and has no history
1620 # (so we can undo bad moves right after they're done).
1622 if ( 0 != $newid ) { # Target exists; check for validity
1623 if ( ! $this->isValidMoveTarget( $nt ) ) {
1624 return 'articleexists';
1631 * Move a title to a new location
1632 * @param Title &$nt the new title
1633 * @param bool $auth indicates whether $wgUser's permissions
1635 * @return mixed true on success, message name on failure
1638 function moveTo( &$nt, $auth = true, $reason = '' ) {
1639 $err = $this->isValidMoveOperation( $nt, $auth );
1640 if( is_string( $err ) ) {
1644 $pageid = $this->getArticleID();
1645 if( $nt->exists() ) {
1646 $this->moveOverExistingRedirect( $nt, $reason );
1647 $pageCountChange = 0;
1648 } else { # Target didn't exist, do normal move.
1649 $this->moveToNewTitle( $nt, $reason );
1650 $pageCountChange = 1;
1652 $redirid = $this->getArticleID();
1654 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1655 $dbw =& wfGetDB( DB_MASTER
);
1656 $categorylinks = $dbw->tableName( 'categorylinks' );
1657 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1658 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1659 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1660 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1664 $oldnamespace = $this->getNamespace() & ~
1;
1665 $newnamespace = $nt->getNamespace() & ~
1;
1666 $oldtitle = $this->getDBkey();
1667 $newtitle = $nt->getDBkey();
1669 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1670 WatchedItem
::duplicateEntries( $this, $nt );
1673 # Update search engine
1674 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1676 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1680 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1681 # Moved out of main namespace
1682 # not viewed, edited, removing
1683 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1684 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1685 # Moved into main namespace
1686 # not viewed, edited, adding
1687 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1688 } elseif ( $pageCountChange ) {
1690 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1699 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1704 * Move page to a title which is at present a redirect to the
1707 * @param Title &$nt the page to move to, which should currently
1711 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1712 global $wgUser, $wgUseSquid, $wgMwRedir;
1713 $fname = 'Title::moveOverExistingRedirect';
1714 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1717 $comment .= ": $reason";
1720 $now = wfTimestampNow();
1722 $newid = $nt->getArticleID();
1723 $oldid = $this->getArticleID();
1724 $dbw =& wfGetDB( DB_MASTER
);
1725 $linkCache =& LinkCache
::singleton();
1727 # Delete the old redirect. We don't save it to history since
1728 # by definition if we've got here it's rather uninteresting.
1729 # We have to remove it so that the next step doesn't trigger
1730 # a conflict on the unique namespace+title index...
1731 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1733 # Save a null revision in the page's history notifying of the move
1734 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1735 $nullRevId = $nullRevision->insertOn( $dbw );
1737 # Change the name of the target page:
1738 $dbw->update( 'page',
1740 'page_touched' => $dbw->timestamp($now),
1741 'page_namespace' => $nt->getNamespace(),
1742 'page_title' => $nt->getDBkey(),
1743 'page_latest' => $nullRevId,
1745 /* WHERE */ array( 'page_id' => $oldid ),
1748 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1750 # Recreate the redirect, this time in the other direction.
1751 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1752 $redirectArticle = new Article( $this );
1753 $newid = $redirectArticle->insertOn( $dbw );
1754 $redirectRevision = new Revision( array(
1756 'comment' => $comment,
1757 'text' => $redirectText ) );
1758 $revid = $redirectRevision->insertOn( $dbw );
1759 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1760 $linkCache->clearLink( $this->getPrefixedDBkey() );
1763 $log = new LogPage( 'move' );
1764 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1766 # Now, we record the link from the redirect to the new title.
1767 # It should have no other outgoing links...
1768 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1769 $dbw->insert( 'pagelinks',
1771 'pl_from' => $newid,
1772 'pl_namespace' => $nt->getNamespace(),
1773 'pl_title' => $nt->getDbKey() ),
1777 if ( $wgUseSquid ) {
1778 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1779 $u = new SquidUpdate( $urls );
1785 * Move page to non-existing title.
1786 * @param Title &$nt the new Title
1789 function moveToNewTitle( &$nt, $reason = '' ) {
1790 global $wgUser, $wgUseSquid;
1792 $fname = 'MovePageForm::moveToNewTitle';
1793 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1795 $comment .= ": $reason";
1798 $newid = $nt->getArticleID();
1799 $oldid = $this->getArticleID();
1800 $dbw =& wfGetDB( DB_MASTER
);
1801 $now = $dbw->timestamp();
1803 $linkCache =& LinkCache
::singleton();
1805 # Save a null revision in the page's history notifying of the move
1806 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1807 $nullRevId = $nullRevision->insertOn( $dbw );
1810 $dbw->update( 'page',
1812 'page_touched' => $now,
1813 'page_namespace' => $nt->getNamespace(),
1814 'page_title' => $nt->getDBkey(),
1815 'page_latest' => $nullRevId,
1817 /* WHERE */ array( 'page_id' => $oldid ),
1821 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1824 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1825 $redirectArticle = new Article( $this );
1826 $newid = $redirectArticle->insertOn( $dbw );
1827 $redirectRevision = new Revision( array(
1829 'comment' => $comment,
1830 'text' => $redirectText ) );
1831 $revid = $redirectRevision->insertOn( $dbw );
1832 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1833 $linkCache->clearLink( $this->getPrefixedDBkey() );
1836 $log = new LogPage( 'move' );
1837 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1839 # Purge caches as per article creation
1840 Article
::onArticleCreate( $nt );
1842 # Record the just-created redirect's linking to the page
1843 $dbw->insert( 'pagelinks',
1845 'pl_from' => $newid,
1846 'pl_namespace' => $nt->getNamespace(),
1847 'pl_title' => $nt->getDBkey() ),
1850 # Non-existent target may have had broken links to it; these must
1851 # now be touched to update link coloring.
1854 # Purge old title from squid
1855 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1856 $titles = $nt->getLinksTo();
1857 if ( $wgUseSquid ) {
1858 $urls = $this->getSquidURLs();
1859 foreach ( $titles as $linkTitle ) {
1860 $urls[] = $linkTitle->getInternalURL();
1862 $u = new SquidUpdate( $urls );
1868 * Checks if $this can be moved to a given Title
1869 * - Selects for update, so don't call it unless you mean business
1871 * @param Title &$nt the new title to check
1874 function isValidMoveTarget( $nt ) {
1876 $fname = 'Title::isValidMoveTarget';
1877 $dbw =& wfGetDB( DB_MASTER
);
1880 $id = $nt->getArticleID();
1881 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1882 array( 'page_is_redirect','old_text','old_flags' ),
1883 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1884 $fname, 'FOR UPDATE' );
1886 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1890 $text = Revision
::getRevisionText( $obj );
1892 # Does the redirect point to the source?
1893 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1894 $redirTitle = Title
::newFromText( $m[1] );
1895 if( !is_object( $redirTitle ) ||
1896 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1904 # Does the article have a history?
1905 $row = $dbw->selectRow( array( 'page', 'revision'),
1907 array( 'page_namespace' => $nt->getNamespace(),
1908 'page_title' => $nt->getDBkey(),
1909 'page_id=rev_page AND page_latest != rev_id'
1910 ), $fname, 'FOR UPDATE'
1913 # Return true if there was no history
1914 return $row === false;
1918 * Create a redirect; fails if the title already exists; does
1921 * @param Title $dest the destination of the redirect
1922 * @param string $comment the comment string describing the move
1923 * @return bool true on success
1926 function createRedirect( $dest, $comment ) {
1928 if ( $this->getArticleID() ) {
1932 $fname = 'Title::createRedirect';
1933 $dbw =& wfGetDB( DB_MASTER
);
1935 $article = new Article( $this );
1936 $newid = $article->insertOn( $dbw );
1937 $revision = new Revision( array(
1939 'comment' => $comment,
1940 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1942 $revisionId = $revision->insertOn( $dbw );
1943 $article->updateRevisionOn( $dbw, $revision, 0 );
1946 $dbw->insert( 'pagelinks',
1948 'pl_from' => $newid,
1949 'pl_namespace' => $dest->getNamespace(),
1950 'pl_title' => $dest->getDbKey()
1954 Article
::onArticleCreate( $this );
1959 * Get categories to which this Title belongs and return an array of
1960 * categories' names.
1962 * @return array an array of parents in the form:
1963 * $parent => $currentarticle
1966 function getParentCategories() {
1967 global $wgContLang,$wgUser;
1969 $titlekey = $this->getArticleId();
1970 $dbr =& wfGetDB( DB_SLAVE
);
1971 $categorylinks = $dbr->tableName( 'categorylinks' );
1974 $sql = "SELECT * FROM $categorylinks"
1975 ." WHERE cl_from='$titlekey'"
1976 ." AND cl_from <> '0'"
1977 ." ORDER BY cl_sortkey";
1979 $res = $dbr->query ( $sql ) ;
1981 if($dbr->numRows($res) > 0) {
1982 while ( $x = $dbr->fetchObject ( $res ) )
1983 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1984 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1985 $dbr->freeResult ( $res ) ;
1993 * Get a tree of parent categories
1994 * @param array $children an array with the children in the keys, to check for circular refs
1998 function getParentCategoryTree( $children = array() ) {
1999 $parents = $this->getParentCategories();
2001 if($parents != '') {
2002 foreach($parents as $parent => $current) {
2003 if ( array_key_exists( $parent, $children ) ) {
2004 # Circular reference
2005 $stack[$parent] = array();
2007 $nt = Title
::newFromText($parent);
2008 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2019 * Get an associative array for selecting this title from
2025 function pageCond() {
2026 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2030 * Get the revision ID of the previous revision
2032 * @param integer $revision Revision ID. Get the revision that was before this one.
2033 * @return interger $oldrevision|false
2035 function getPreviousRevisionID( $revision ) {
2036 $dbr =& wfGetDB( DB_SLAVE
);
2037 return $dbr->selectField( 'revision', 'rev_id',
2038 'rev_page=' . intval( $this->getArticleId() ) .
2039 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2043 * Get the revision ID of the next revision
2045 * @param integer $revision Revision ID. Get the revision that was after this one.
2046 * @return interger $oldrevision|false
2048 function getNextRevisionID( $revision ) {
2049 $dbr =& wfGetDB( DB_SLAVE
);
2050 return $dbr->selectField( 'revision', 'rev_id',
2051 'rev_page=' . intval( $this->getArticleId() ) .
2052 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2056 * Compare with another title.
2058 * @param Title $title
2061 function equals( $title ) {
2062 return $this->getInterwiki() == $title->getInterwiki()
2063 && $this->getNamespace() == $title->getNamespace()
2064 && $this->getDbkey() == $title->getDbkey();
2068 * Check if page exists
2072 return $this->getArticleId() != 0;
2076 * Should a link should be displayed as a known link, just based on its title?
2078 * Currently, a self-link with a fragment and special pages are in
2079 * this category. Special pages never exist in the database.
2081 function isAlwaysKnown() {
2082 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2083 || NS_SPECIAL
== $this->mNamespace
;
2087 * Update page_touched timestamps on pages linking to this title.
2088 * In principal, this could be backgrounded and could also do squid
2091 function touchLinks() {
2092 $fname = 'Title::touchLinks';
2094 $dbw =& wfGetDB( DB_MASTER
);
2096 $res = $dbw->select( 'pagelinks',
2099 'pl_namespace' => $this->getNamespace(),
2100 'pl_title' => $this->getDbKey() ),
2103 $toucharr = array();
2104 while( $row = $dbw->fetchObject( $res ) ) {
2105 $toucharr[] = $row->pl_from
;
2107 $dbw->freeResult( $res );
2109 if( $this->getNamespace() == NS_CATEGORY
) {
2110 // Categories show up in a separate set of links as well
2111 $res = $dbw->select( 'categorylinks',
2113 array( 'cl_to' => $this->getDbKey() ),
2115 while( $row = $dbw->fetchObject( $res ) ) {
2116 $toucharr[] = $row->cl_from
;
2118 $dbw->freeResult( $res );
2121 if (!count($toucharr))
2123 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2124 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2127 function trackbackURL() {
2128 global $wgTitle, $wgScriptPath, $wgServer;
2130 return "$wgServer$wgScriptPath/trackback.php?article="
2131 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2134 function trackbackRDF() {
2135 $url = htmlspecialchars($this->getFullURL());
2136 $title = htmlspecialchars($this->getText());
2137 $tburl = $this->trackbackURL();
2140 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2141 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2142 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2145 dc:identifier=\"$url\"
2147 trackback:ping=\"$tburl\" />