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';
110 wfProfileIn( $fname );
112 if( is_object( $text ) ) {
113 wfDebugDieBacktrace( 'Title::newFromText given an object' );
117 * Wiki pages often contain multiple links to the same page.
118 * Title normalization and parsing can become expensive on
119 * pages with many links, so we can save a little time by
122 * In theory these are value objects and won't get changed...
124 if( $defaultNamespace == NS_MAIN
&& isset( $wgTitleCache[$text] ) ) {
125 wfProfileOut( $fname );
126 return $wgTitleCache[$text];
130 * Convert things like é ā or 〗 into real text...
132 $filteredText = Sanitizer
::decodeCharReferences( $text );
135 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
136 $t->mDefaultNamespace
= $defaultNamespace;
138 static $cachedcount = 0 ;
139 if( $t->secureAndSplit() ) {
140 if( $defaultNamespace == NS_MAIN
) {
141 if( $cachedcount >= MW_TITLECACHE_MAX
) {
142 # Avoid memory leaks on mass operations...
143 $wgTitleCache = array();
147 $wgTitleCache[$text] =& $t;
149 wfProfileOut( $fname );
152 wfProfileOut( $fname );
159 * Create a new Title from URL-encoded text. Ensures that
160 * the given title's length does not exceed the maximum.
161 * @param string $url the title, as might be taken from a URL
162 * @return Title the new object, or NULL on an error
166 function newFromURL( $url ) {
167 global $wgLegalTitleChars;
170 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
171 # but some URLs used it as a space replacement and they still come
172 # from some external search tools.
173 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
174 $url = str_replace( '+', ' ', $url );
177 $t->mDbkeyform
= str_replace( ' ', '_', $url );
178 if( $t->secureAndSplit() ) {
186 * Create a new Title from an article ID
188 * @todo This is inefficiently implemented, the page row is requested
189 * but not used for anything else
191 * @param int $id the page_id corresponding to the Title to create
192 * @return Title the new object, or NULL on an error
196 function newFromID( $id ) {
197 $fname = 'Title::newFromID';
198 $dbr =& wfGetDB( DB_SLAVE
);
199 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
200 array( 'page_id' => $id ), $fname );
201 if ( $row !== false ) {
202 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
210 * Create a new Title from a namespace index and a DB key.
211 * It's assumed that $ns and $title are *valid*, for instance when
212 * they came directly from the database or a special page name.
213 * For convenience, spaces are converted to underscores so that
214 * eg user_text fields can be used directly.
216 * @param int $ns the namespace of the article
217 * @param string $title the unprefixed database key form
218 * @return Title the new object
222 function &makeTitle( $ns, $title ) {
226 $t->mNamespace
= intval( $ns );
227 $t->mDbkeyform
= str_replace( ' ', '_', $title );
228 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
229 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
230 $t->mTextform
= str_replace( '_', ' ', $title );
235 * Create a new Title frrom a namespace index and a DB key.
236 * The parameters will be checked for validity, which is a bit slower
237 * than makeTitle() but safer for user-provided data.
239 * @param int $ns the namespace of the article
240 * @param string $title the database key form
241 * @return Title the new object, or NULL on an error
245 function makeTitleSafe( $ns, $title ) {
247 $t->mDbkeyform
= Title
::makeName( $ns, $title );
248 if( $t->secureAndSplit() ) {
256 * Create a new Title for the Main Page
259 * @return Title the new object
262 function newMainPage() {
263 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
267 * Create a new Title for a redirect
268 * @param string $text the redirect title text
269 * @return Title the new object, or NULL if the text is not a
274 function newFromRedirect( $text ) {
277 if ( $wgMwRedir->matchStart( $text ) ) {
278 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
279 # categories are escaped using : for example one can enter:
280 # #REDIRECT [[:Category:Music]]. Need to remove it.
281 if ( substr($m[1],0,1) == ':') {
282 # We don't want to keep the ':'
283 $m[1] = substr( $m[1], 1 );
286 $rt = Title
::newFromText( $m[1] );
287 # Disallow redirects to Special:Userlogout
288 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
296 #----------------------------------------------------------------------------
298 #----------------------------------------------------------------------------
301 * Get the prefixed DB key associated with an ID
302 * @param int $id the page_id of the article
303 * @return Title an object representing the article, or NULL
304 * if no such article was found
308 function nameOf( $id ) {
309 $fname = 'Title::nameOf';
310 $dbr =& wfGetDB( DB_SLAVE
);
312 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
313 if ( $s === false ) { return NULL; }
315 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
320 * Get a regex character class describing the legal characters in a link
321 * @return string the list of characters, not delimited
325 function legalChars() {
326 global $wgLegalTitleChars;
327 return $wgLegalTitleChars;
331 * Get a string representation of a title suitable for
332 * including in a search index
334 * @param int $ns a namespace index
335 * @param string $title text-form main part
336 * @return string a stripped-down title string ready for the
339 /* static */ function indexTitle( $ns, $title ) {
341 require_once( 'SearchEngine.php' );
343 $lc = SearchEngine
::legalSearchChars() . '&#;';
344 $t = $wgContLang->stripForSearch( $title );
345 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
346 $t = strtolower( $t );
349 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
350 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
352 $t = preg_replace( "/\\s+/", ' ', $t );
354 if ( $ns == NS_IMAGE
) {
355 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
361 * Make a prefixed DB key from a DB key and a namespace index
362 * @param int $ns numerical representation of the namespace
363 * @param string $title the DB key form the title
364 * @return string the prefixed form of the title
366 /* static */ function makeName( $ns, $title ) {
369 $n = $wgContLang->getNsText( $ns );
370 return $n == '' ?
$title : "$n:$title";
374 * Returns the URL associated with an interwiki prefix
375 * @param string $key the interwiki prefix (e.g. "MeatBall")
376 * @return the associated URL, containing "$1", which should be
377 * replaced by an article title
381 function getInterwikiLink( $key ) {
382 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
383 global $wgInterwikiCache;
384 $fname = 'Title::getInterwikiLink';
386 wfProfileIn( $fname );
388 $key = strtolower( $key );
390 $k = $wgDBname.':interwiki:'.$key;
391 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
392 wfProfileOut( $fname );
393 return $wgTitleInterwikiCache[$k]->iw_url
;
396 if ($wgInterwikiCache) {
397 wfProfileOut( $fname );
398 return Title
::getInterwikiCached( $key );
401 $s = $wgMemc->get( $k );
402 # Ignore old keys with no iw_local
403 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
404 $wgTitleInterwikiCache[$k] = $s;
405 wfProfileOut( $fname );
409 $dbr =& wfGetDB( DB_SLAVE
);
410 $res = $dbr->select( 'interwiki',
411 array( 'iw_url', 'iw_local', 'iw_trans' ),
412 array( 'iw_prefix' => $key ), $fname );
414 wfProfileOut( $fname );
418 $s = $dbr->fetchObject( $res );
420 # Cache non-existence: create a blank object and save it to memcached
426 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
427 $wgTitleInterwikiCache[$k] = $s;
429 wfProfileOut( $fname );
434 * Fetch interwiki prefix data from local cache in constant database
436 * More logic is explained in DefaultSettings
438 * @return string URL of interwiki site
441 function getInterwikiCached( $key ) {
442 global $wgDBname, $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
443 global $wgTitleInterwikiCache;
447 $db=dba_open($wgInterwikiCache,'r','cdb');
448 /* Resolve site name */
449 if ($wgInterwikiScopes>=3 and !$site) {
450 $site = dba_fetch("__sites:{$wgDBname}", $db);
452 $site = $wgInterwikiFallbackSite;
454 $value = dba_fetch("{$wgDBname}:{$key}", $db);
455 if ($value=='' and $wgInterwikiScopes>=3) {
457 $value = dba_fetch("_{$site}:{$key}", $db);
459 if ($value=='' and $wgInterwikiScopes>=2) {
461 $value = dba_fetch("__global:{$key}", $db);
470 list($local,$url)=explode(' ',$value,2);
472 $s->iw_local
=(int)$local;
474 $wgTitleInterwikiCache[$wgDBname.':interwiki:'.$key] = $s;
478 * Determine whether the object refers to a page within
481 * @return bool TRUE if this is an in-project interwiki link
482 * or a wikilink, FALSE otherwise
486 global $wgTitleInterwikiCache, $wgDBname;
488 if ( $this->mInterwiki
!= '' ) {
489 # Make sure key is loaded into cache
490 $this->getInterwikiLink( $this->mInterwiki
);
491 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
492 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
499 * Determine whether the object refers to a page within
500 * this project and is transcludable.
502 * @return bool TRUE if this is transcludable
506 global $wgTitleInterwikiCache, $wgDBname;
508 if ($this->mInterwiki
== '' ||
!$this->isLocal())
510 # Make sure key is loaded into cache
511 $this->getInterwikiLink( $this->mInterwiki
);
512 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
513 return (bool)($wgTitleInterwikiCache[$k]->iw_trans
);
517 * Update the page_touched field for an array of title objects
518 * @todo Inefficient unless the IDs are already loaded into the
520 * @param array $titles an array of Title objects to be touched
521 * @param string $timestamp the timestamp to use instead of the
522 * default current time
526 function touchArray( $titles, $timestamp = '' ) {
528 if ( count( $titles ) == 0 ) {
531 $dbw =& wfGetDB( DB_MASTER
);
532 if ( $timestamp == '' ) {
533 $timestamp = $dbw->timestamp();
536 $page = $dbw->tableName( 'page' );
537 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
540 foreach ( $titles as $title ) {
541 if ( $wgUseFileCache ) {
542 $cm = new CacheManager($title);
543 @unlink($cm->fileCacheName());
550 $sql .= $title->getArticleID();
554 $dbw->query( $sql, 'Title::touchArray' );
557 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
558 // do them in small chunks:
559 $fname = 'Title::touchArray';
560 foreach( $titles as $title ) {
561 $dbw->update( 'page',
562 array( 'page_touched' => $timestamp ),
564 'page_namespace' => $title->getNamespace(),
565 'page_title' => $title->getDBkey() ),
570 #----------------------------------------------------------------------------
572 #----------------------------------------------------------------------------
574 /** Simple accessors */
576 * Get the text form (spaces not underscores) of the main part
580 function getText() { return $this->mTextform
; }
582 * Get the URL-encoded form of the main part
586 function getPartialURL() { return $this->mUrlform
; }
588 * Get the main part with underscores
592 function getDBkey() { return $this->mDbkeyform
; }
594 * Get the namespace index, i.e. one of the NS_xxxx constants
598 function getNamespace() { return $this->mNamespace
; }
600 * Get the namespace text
604 function getNsText() {
606 return $wgContLang->getNsText( $this->mNamespace
);
609 * Get the namespace text of the subject (rather than talk) page
613 function getSubjectNsText() {
615 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
619 * Get the interwiki prefix (or null string)
623 function getInterwiki() { return $this->mInterwiki
; }
625 * Get the Title fragment (i.e. the bit after the #)
629 function getFragment() { return $this->mFragment
; }
631 * Get the default namespace index, for when there is no namespace
635 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
638 * Get title for search index
639 * @return string a stripped-down title string ready for the
642 function getIndexTitle() {
643 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
647 * Get the prefixed database key form
648 * @return string the prefixed title, with underscores and
649 * any interwiki and namespace prefixes
652 function getPrefixedDBkey() {
653 $s = $this->prefix( $this->mDbkeyform
);
654 $s = str_replace( ' ', '_', $s );
659 * Get the prefixed title with spaces.
660 * This is the form usually used for display
661 * @return string the prefixed title, with spaces
664 function getPrefixedText() {
666 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
667 $s = $this->prefix( $this->mTextform
);
668 $s = str_replace( '_', ' ', $s );
669 $this->mPrefixedText
= $s;
671 return $this->mPrefixedText
;
675 * Get the prefixed title with spaces, plus any fragment
676 * (part beginning with '#')
677 * @return string the prefixed title, with spaces and
678 * the fragment, including '#'
681 function getFullText() {
683 $text = $this->getPrefixedText();
684 if( '' != $this->mFragment
) {
685 $text .= '#' . $this->mFragment
;
691 * Get a URL-encoded title (not an actual URL) including interwiki
692 * @return string the URL-encoded form
695 function getPrefixedURL() {
696 $s = $this->prefix( $this->mDbkeyform
);
697 $s = str_replace( ' ', '_', $s );
699 $s = wfUrlencode ( $s ) ;
701 # Cleaning up URL to make it look nice -- is this safe?
702 $s = str_replace( '%28', '(', $s );
703 $s = str_replace( '%29', ')', $s );
709 * Get a real URL referring to this title, with interwiki link and
712 * @param string $query an optional query string, not used
713 * for interwiki links
714 * @return string the URL
717 function getFullURL( $query = '' ) {
718 global $wgContLang, $wgServer, $wgRequest;
720 if ( '' == $this->mInterwiki
) {
721 $url = $this->getLocalUrl( $query );
723 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
724 // Correct fix would be to move the prepending elsewhere.
725 if ($wgRequest->getVal('action') != 'render') {
726 $url = $wgServer . $url;
729 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
731 $namespace = $wgContLang->getNsText( $this->mNamespace
);
732 if ( '' != $namespace ) {
733 # Can this actually happen? Interwikis shouldn't be parsed.
736 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
738 if( false === strpos( $url, '?' ) ) {
745 if ( '' != $this->mFragment
) {
746 $url .= '#' . $this->mFragment
;
749 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
754 * Get a URL with no fragment or server name. If this page is generated
755 * with action=render, $wgServer is prepended.
756 * @param string $query an optional query string; if not specified,
757 * $wgArticlePath will be used.
758 * @return string the URL
761 function getLocalURL( $query = '' ) {
762 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
764 if ( $this->isExternal() ) {
765 $url = $this->getFullURL();
767 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
768 if ( $query == '' ) {
769 $url = str_replace( '$1', $dbkey, $wgArticlePath );
771 global $wgActionPaths;
773 if( !empty( $wgActionPaths ) &&
774 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
776 $action = urldecode( $matches[2] );
777 if( isset( $wgActionPaths[$action] ) ) {
778 $query = $matches[1];
779 if( isset( $matches[4] ) ) $query .= $matches[4];
780 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
781 if( $query != '' ) $url .= '?' . $query;
784 if ( $url === false ) {
785 if ( $query == '-' ) {
788 $url = "{$wgScript}?title={$dbkey}&{$query}";
792 // FIXME: this causes breakage in various places when we
793 // actually expected a local URL and end up with dupe prefixes.
794 if ($wgRequest->getVal('action') == 'render') {
795 $url = $wgServer . $url;
798 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
803 * Get an HTML-escaped version of the URL form, suitable for
804 * using in a link, without a server name or fragment
805 * @param string $query an optional query string
806 * @return string the URL
809 function escapeLocalURL( $query = '' ) {
810 return htmlspecialchars( $this->getLocalURL( $query ) );
814 * Get an HTML-escaped version of the URL form, suitable for
815 * using in a link, including the server name and fragment
817 * @return string the URL
818 * @param string $query an optional query string
821 function escapeFullURL( $query = '' ) {
822 return htmlspecialchars( $this->getFullURL( $query ) );
826 * Get the URL form for an internal link.
827 * - Used in various Squid-related code, in case we have a different
828 * internal hostname for the server from the exposed one.
830 * @param string $query an optional query string
831 * @return string the URL
834 function getInternalURL( $query = '' ) {
835 global $wgInternalServer;
836 $url = $wgInternalServer . $this->getLocalURL( $query );
837 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
842 * Get the edit URL for this Title
843 * @return string the URL, or a null string if this is an
847 function getEditURL() {
848 global $wgServer, $wgScript;
850 if ( '' != $this->mInterwiki
) { return ''; }
851 $s = $this->getLocalURL( 'action=edit' );
857 * Get the HTML-escaped displayable text form.
858 * Used for the title field in <a> tags.
859 * @return string the text, including any prefixes
862 function getEscapedText() {
863 return htmlspecialchars( $this->getPrefixedText() );
867 * Is this Title interwiki?
871 function isExternal() { return ( '' != $this->mInterwiki
); }
874 * Does the title correspond to a protected article?
875 * @param string $what the action the page is protected from,
876 * by default checks move and edit
880 function isProtected( $action = '' ) {
881 global $wgRestrictionLevels;
882 if ( -1 == $this->mNamespace
) { return true; }
884 if( $action == 'edit' ||
$action == '' ) {
885 $r = $this->getRestrictions( 'edit' );
886 foreach( $wgRestrictionLevels as $level ) {
887 if( in_array( $level, $r ) && $level != '' ) {
893 if( $action == 'move' ||
$action == '' ) {
894 $r = $this->getRestrictions( 'move' );
895 foreach( $wgRestrictionLevels as $level ) {
896 if( in_array( $level, $r ) && $level != '' ) {
906 * Is $wgUser is watching this page?
910 function userIsWatching() {
913 if ( is_null( $this->mWatched
) ) {
914 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
915 $this->mWatched
= false;
917 $this->mWatched
= $wgUser->isWatched( $this );
920 return $this->mWatched
;
924 * Can $wgUser perform $action this page?
925 * @param string $action action that permission needs to be checked for
929 function userCan($action) {
930 $fname = 'Title::userCan';
931 wfProfileIn( $fname );
934 if( NS_SPECIAL
== $this->mNamespace
) {
935 wfProfileOut( $fname );
938 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
939 // from taking effect -ævar
940 if( NS_MEDIAWIKI
== $this->mNamespace
&&
941 !$wgUser->isAllowed('editinterface') ) {
942 wfProfileOut( $fname );
946 if( $this->mDbkeyform
== '_' ) {
947 # FIXME: Is this necessary? Shouldn't be allowed anyway...
948 wfProfileOut( $fname );
952 # protect global styles and js
953 if ( NS_MEDIAWIKI
== $this->mNamespace
954 && preg_match("/\\.(css|js)$/", $this->mTextform
)
955 && !$wgUser->isAllowed('editinterface') ) {
956 wfProfileOut( $fname );
960 # protect css/js subpages of user pages
961 # XXX: this might be better using restrictions
962 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
963 if( NS_USER
== $this->mNamespace
964 && preg_match("/\\.(css|js)$/", $this->mTextform
)
965 && !$wgUser->isAllowed('editinterface')
966 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
967 wfProfileOut( $fname );
971 foreach( $this->getRestrictions($action) as $right ) {
972 // Backwards compatibility, rewrite sysop -> protect
973 if ( $right == 'sysop' ) {
976 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
977 wfProfileOut( $fname );
982 if( $action == 'move' &&
983 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
984 wfProfileOut( $fname );
988 if( $action == 'create' ) {
989 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
990 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
995 wfProfileOut( $fname );
1000 * Can $wgUser edit this page?
1004 function userCanEdit() {
1005 return $this->userCan('edit');
1009 * Can $wgUser move this page?
1013 function userCanMove() {
1014 return $this->userCan('move');
1018 * Would anybody with sufficient privileges be able to move this page?
1019 * Some pages just aren't movable.
1024 function isMovable() {
1025 return Namespace::isMovable( $this->getNamespace() )
1026 && $this->getInterwiki() == '';
1030 * Can $wgUser read this page?
1034 function userCanRead() {
1037 if( $wgUser->isAllowed('read') ) {
1040 global $wgWhitelistRead;
1042 /** If anon users can create an account,
1043 they need to reach the login page first! */
1044 if( $wgUser->isAllowed( 'createaccount' )
1045 && $this->getNamespace() == NS_SPECIAL
1046 && $this->getText() == 'Userlogin' ) {
1050 /** some pages are explicitly allowed */
1051 $name = $this->getPrefixedText();
1052 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1056 # Compatibility with old settings
1057 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1058 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1067 * Is this a talk page of some sort?
1071 function isTalkPage() {
1072 return Namespace::isTalk( $this->getNamespace() );
1076 * Is this a .css or .js subpage of a user page?
1080 function isCssJsSubpage() {
1081 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1084 * Is this a .css subpage of a user page?
1088 function isCssSubpage() {
1089 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1092 * Is this a .js subpage of a user page?
1096 function isJsSubpage() {
1097 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1100 * Protect css/js subpages of user pages: can $wgUser edit
1104 * @todo XXX: this might be better using restrictions
1107 function userCanEditCssJsSubpage() {
1109 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1113 * Loads a string into mRestrictions array
1114 * @param string $res restrictions in string format
1117 function loadRestrictions( $res ) {
1118 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1119 $temp = explode( '=', trim( $restrict ) );
1120 if(count($temp) == 1) {
1121 // old format should be treated as edit/move restriction
1122 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1123 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1125 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1128 $this->mRestrictionsLoaded
= true;
1132 * Accessor/initialisation for mRestrictions
1133 * @param string $action action that permission needs to be checked for
1134 * @return array the array of groups allowed to edit this article
1137 function getRestrictions($action) {
1138 $id = $this->getArticleID();
1139 if ( 0 == $id ) { return array(); }
1141 if ( ! $this->mRestrictionsLoaded
) {
1142 $dbr =& wfGetDB( DB_SLAVE
);
1143 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1144 $this->loadRestrictions( $res );
1146 if( isset( $this->mRestrictions
[$action] ) ) {
1147 return $this->mRestrictions
[$action];
1153 * Is there a version of this page in the deletion archive?
1154 * @return int the number of archived revisions
1157 function isDeleted() {
1158 $fname = 'Title::isDeleted';
1159 if ( $this->getNamespace() < 0 ) {
1162 $dbr =& wfGetDB( DB_SLAVE
);
1163 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1164 'ar_title' => $this->getDBkey() ), $fname );
1170 * Get the article ID for this Title from the link cache,
1171 * adding it if necessary
1172 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1174 * @return int the ID
1177 function getArticleID( $flags = 0 ) {
1178 $linkCache =& LinkCache
::singleton();
1179 if ( $flags & GAID_FOR_UPDATE
) {
1180 $oldUpdate = $linkCache->forUpdate( true );
1181 $this->mArticleID
= $linkCache->addLinkObj( $this );
1182 $linkCache->forUpdate( $oldUpdate );
1184 if ( -1 == $this->mArticleID
) {
1185 $this->mArticleID
= $linkCache->addLinkObj( $this );
1188 return $this->mArticleID
;
1191 function getLatestRevID() {
1192 if ($this->mLatestID
!== false)
1193 return $this->mLatestID
;
1195 $db =& wfGetDB(DB_SLAVE
);
1196 return $this->mLatestID
= $db->selectField( 'revision',
1198 array('rev_page' => $this->getArticleID()),
1199 'Title::getLatestRevID' );
1203 * This clears some fields in this object, and clears any associated
1204 * keys in the "bad links" section of the link cache.
1206 * - This is called from Article::insertNewArticle() to allow
1207 * loading of the new page_id. It's also called from
1208 * Article::doDeleteArticle()
1210 * @param int $newid the new Article ID
1213 function resetArticleID( $newid ) {
1214 $linkCache =& LinkCache
::singleton();
1215 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1217 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1218 else { $this->mArticleID
= $newid; }
1219 $this->mRestrictionsLoaded
= false;
1220 $this->mRestrictions
= array();
1224 * Updates page_touched for this page; called from LinksUpdate.php
1225 * @return bool true if the update succeded
1228 function invalidateCache() {
1229 global $wgUseFileCache;
1231 if ( wfReadOnly() ) {
1235 $dbw =& wfGetDB( DB_MASTER
);
1236 $success = $dbw->update( 'page',
1238 'page_touched' => $dbw->timestamp()
1239 ), array( /* WHERE */
1240 'page_namespace' => $this->getNamespace() ,
1241 'page_title' => $this->getDBkey()
1242 ), 'Title::invalidateCache'
1245 if ($wgUseFileCache) {
1246 $cache = new CacheManager($this);
1247 @unlink
($cache->fileCacheName());
1254 * Prefix some arbitrary text with the namespace or interwiki prefix
1257 * @param string $name the text
1258 * @return string the prefixed text
1261 /* private */ function prefix( $name ) {
1265 if ( '' != $this->mInterwiki
) {
1266 $p = $this->mInterwiki
. ':';
1268 if ( 0 != $this->mNamespace
) {
1269 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1275 * Secure and split - main initialisation function for this object
1277 * Assumes that mDbkeyform has been set, and is urldecoded
1278 * and uses underscores, but not otherwise munged. This function
1279 * removes illegal characters, splits off the interwiki and
1280 * namespace prefixes, sets the other forms, and canonicalizes
1282 * @return bool true on success
1285 /* private */ function secureAndSplit() {
1286 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1287 $fname = 'Title::secureAndSplit';
1288 wfProfileIn( $fname );
1291 static $rxTc = false;
1293 # % is needed as well
1294 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1297 $this->mInterwiki
= $this->mFragment
= '';
1298 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1300 # Clean up whitespace
1302 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1303 $t = trim( $t, '_' );
1306 wfProfileOut( $fname );
1310 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1311 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1312 wfProfileOut( $fname );
1316 $this->mDbkeyform
= $t;
1318 # Initial colon indicates main namespace rather than specified default
1319 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1320 if ( ':' == $t{0} ) {
1321 $this->mNamespace
= NS_MAIN
;
1322 $t = substr( $t, 1 ); # remove the colon but continue processing
1325 # Namespace or interwiki prefix
1328 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1330 $lowerNs = strtolower( $p );
1331 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1332 # Canonical namespace
1334 $this->mNamespace
= $ns;
1335 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1336 # Ordinary namespace
1338 $this->mNamespace
= $ns;
1339 } elseif( $this->getInterwikiLink( $p ) ) {
1341 # Can't make a local interwiki link to an interwiki link.
1342 # That's just crazy!
1343 wfProfileOut( $fname );
1349 $this->mInterwiki
= strtolower( $p );
1351 # Redundant interwiki prefix to the local wiki
1352 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1354 # Can't have an empty self-link
1355 wfProfileOut( $fname );
1358 $this->mInterwiki
= '';
1360 # Do another namespace split...
1364 # If there's no recognized interwiki or namespace,
1365 # then let the colon expression be part of the title.
1371 # We already know that some pages won't be in the database!
1373 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1374 $this->mArticleID
= 0;
1376 $f = strstr( $r, '#' );
1377 if ( false !== $f ) {
1378 $this->mFragment
= substr( $f, 1 );
1379 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1380 # remove whitespace again: prevents "Foo_bar_#"
1381 # becoming "Foo_bar_"
1382 $r = preg_replace( '/_*$/', '', $r );
1385 # Reject illegal characters.
1387 if( preg_match( $rxTc, $r ) ) {
1388 wfProfileOut( $fname );
1393 * Pages with "/./" or "/../" appearing in the URLs will
1394 * often be unreachable due to the way web browsers deal
1395 * with 'relative' URLs. Forbid them explicitly.
1397 if ( strpos( $r, '.' ) !== false &&
1398 ( $r === '.' ||
$r === '..' ||
1399 strpos( $r, './' ) === 0 ||
1400 strpos( $r, '../' ) === 0 ||
1401 strpos( $r, '/./' ) !== false ||
1402 strpos( $r, '/../' ) !== false ) )
1404 wfProfileOut( $fname );
1408 # We shouldn't need to query the DB for the size.
1409 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1410 if ( strlen( $r ) > 255 ) {
1411 wfProfileOut( $fname );
1416 * Normally, all wiki links are forced to have
1417 * an initial capital letter so [[foo]] and [[Foo]]
1418 * point to the same place.
1420 * Don't force it for interwikis, since the other
1421 * site might be case-sensitive.
1423 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1424 $t = $wgContLang->ucfirst( $r );
1430 * Can't make a link to a namespace alone...
1431 * "empty" local links can only be self-links
1432 * with a fragment identifier.
1435 $this->mInterwiki
== '' &&
1436 $this->mNamespace
!= NS_MAIN
) {
1437 wfProfileOut( $fname );
1442 $this->mDbkeyform
= $t;
1443 $this->mUrlform
= wfUrlencode( $t );
1445 $this->mTextform
= str_replace( '_', ' ', $t );
1447 wfProfileOut( $fname );
1452 * Get a Title object associated with the talk page of this article
1453 * @return Title the object for the talk page
1456 function getTalkPage() {
1457 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1461 * Get a title object associated with the subject page of this
1464 * @return Title the object for the subject page
1467 function getSubjectPage() {
1468 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1472 * Get an array of Title objects linking to this Title
1473 * Also stores the IDs in the link cache.
1475 * @param string $options may be FOR UPDATE
1476 * @return array the Title objects linking here
1479 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1480 $linkCache =& LinkCache
::singleton();
1481 $id = $this->getArticleID();
1484 $db =& wfGetDB( DB_MASTER
);
1486 $db =& wfGetDB( DB_SLAVE
);
1489 $res = $db->select( array( 'page', $table ),
1490 array( 'page_namespace', 'page_title', 'page_id' ),
1492 "{$prefix}_from=page_id",
1493 "{$prefix}_namespace" => $this->getNamespace(),
1494 "{$prefix}_title" => $this->getDbKey() ),
1495 'Title::getLinksTo',
1499 if ( $db->numRows( $res ) ) {
1500 while ( $row = $db->fetchObject( $res ) ) {
1501 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1502 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1503 $retVal[] = $titleObj;
1507 $db->freeResult( $res );
1512 * Get an array of Title objects using this Title as a template
1513 * Also stores the IDs in the link cache.
1515 * @param string $options may be FOR UPDATE
1516 * @return array the Title objects linking here
1519 function getTemplateLinksTo( $options = '' ) {
1520 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1524 * Get an array of Title objects referring to non-existent articles linked from this page
1526 * @param string $options may be FOR UPDATE
1527 * @return array the Title objects
1530 function getBrokenLinksFrom( $options = '' ) {
1532 $db =& wfGetDB( DB_MASTER
);
1534 $db =& wfGetDB( DB_SLAVE
);
1537 $res = $db->safeQuery(
1538 "SELECT pl_namespace, pl_title
1541 ON pl_namespace=page_namespace
1542 AND pl_title=page_title
1544 AND page_namespace IS NULL
1546 $db->tableName( 'pagelinks' ),
1547 $db->tableName( 'page' ),
1548 $this->getArticleId(),
1552 if ( $db->numRows( $res ) ) {
1553 while ( $row = $db->fetchObject( $res ) ) {
1554 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1557 $db->freeResult( $res );
1563 * Get a list of URLs to purge from the Squid cache when this
1566 * @return array the URLs
1569 function getSquidURLs() {
1571 $this->getInternalURL(),
1572 $this->getInternalURL( 'action=history' )
1577 * Move this page without authentication
1578 * @param Title &$nt the new page Title
1581 function moveNoAuth( &$nt ) {
1582 return $this->moveTo( $nt, false );
1586 * Check whether a given move operation would be valid.
1587 * Returns true if ok, or a message key string for an error message
1588 * if invalid. (Scarrrrry ugly interface this.)
1589 * @param Title &$nt the new title
1590 * @param bool $auth indicates whether $wgUser's permissions
1592 * @return mixed true on success, message name on failure
1595 function isValidMoveOperation( &$nt, $auth = true ) {
1597 if( !$this or !$nt ) {
1598 return 'badtitletext';
1600 if( $this->equals( $nt ) ) {
1603 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1604 return 'immobile_namespace';
1607 $oldid = $this->getArticleID();
1608 $newid = $nt->getArticleID();
1610 if ( strlen( $nt->getDBkey() ) < 1 ) {
1611 return 'articleexists';
1613 if ( ( '' == $this->getDBkey() ) ||
1615 ( '' == $nt->getDBkey() ) ) {
1616 return 'badarticleerror';
1620 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1621 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1622 return 'protectedpage';
1625 # The move is allowed only if (1) the target doesn't exist, or
1626 # (2) the target is a redirect to the source, and has no history
1627 # (so we can undo bad moves right after they're done).
1629 if ( 0 != $newid ) { # Target exists; check for validity
1630 if ( ! $this->isValidMoveTarget( $nt ) ) {
1631 return 'articleexists';
1638 * Move a title to a new location
1639 * @param Title &$nt the new title
1640 * @param bool $auth indicates whether $wgUser's permissions
1642 * @return mixed true on success, message name on failure
1645 function moveTo( &$nt, $auth = true, $reason = '' ) {
1646 $err = $this->isValidMoveOperation( $nt, $auth );
1647 if( is_string( $err ) ) {
1651 $pageid = $this->getArticleID();
1652 if( $nt->exists() ) {
1653 $this->moveOverExistingRedirect( $nt, $reason );
1654 $pageCountChange = 0;
1655 } else { # Target didn't exist, do normal move.
1656 $this->moveToNewTitle( $nt, $reason );
1657 $pageCountChange = 1;
1659 $redirid = $this->getArticleID();
1661 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1662 $dbw =& wfGetDB( DB_MASTER
);
1663 $categorylinks = $dbw->tableName( 'categorylinks' );
1664 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1665 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1666 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1667 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1671 $oldnamespace = $this->getNamespace() & ~
1;
1672 $newnamespace = $nt->getNamespace() & ~
1;
1673 $oldtitle = $this->getDBkey();
1674 $newtitle = $nt->getDBkey();
1676 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1677 WatchedItem
::duplicateEntries( $this, $nt );
1680 # Update search engine
1681 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1683 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1687 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1688 # Moved out of main namespace
1689 # not viewed, edited, removing
1690 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1691 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1692 # Moved into main namespace
1693 # not viewed, edited, adding
1694 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1695 } elseif ( $pageCountChange ) {
1697 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1706 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1711 * Move page to a title which is at present a redirect to the
1714 * @param Title &$nt the page to move to, which should currently
1718 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1719 global $wgUser, $wgUseSquid, $wgMwRedir;
1720 $fname = 'Title::moveOverExistingRedirect';
1721 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1724 $comment .= ": $reason";
1727 $now = wfTimestampNow();
1729 $newid = $nt->getArticleID();
1730 $oldid = $this->getArticleID();
1731 $dbw =& wfGetDB( DB_MASTER
);
1732 $linkCache =& LinkCache
::singleton();
1734 # Delete the old redirect. We don't save it to history since
1735 # by definition if we've got here it's rather uninteresting.
1736 # We have to remove it so that the next step doesn't trigger
1737 # a conflict on the unique namespace+title index...
1738 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1740 # Save a null revision in the page's history notifying of the move
1741 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1742 $nullRevId = $nullRevision->insertOn( $dbw );
1744 # Change the name of the target page:
1745 $dbw->update( 'page',
1747 'page_touched' => $dbw->timestamp($now),
1748 'page_namespace' => $nt->getNamespace(),
1749 'page_title' => $nt->getDBkey(),
1750 'page_latest' => $nullRevId,
1752 /* WHERE */ array( 'page_id' => $oldid ),
1755 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1757 # Recreate the redirect, this time in the other direction.
1758 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1759 $redirectArticle = new Article( $this );
1760 $newid = $redirectArticle->insertOn( $dbw );
1761 $redirectRevision = new Revision( array(
1763 'comment' => $comment,
1764 'text' => $redirectText ) );
1765 $revid = $redirectRevision->insertOn( $dbw );
1766 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1767 $linkCache->clearLink( $this->getPrefixedDBkey() );
1770 $log = new LogPage( 'move' );
1771 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1773 # Now, we record the link from the redirect to the new title.
1774 # It should have no other outgoing links...
1775 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1776 $dbw->insert( 'pagelinks',
1778 'pl_from' => $newid,
1779 'pl_namespace' => $nt->getNamespace(),
1780 'pl_title' => $nt->getDbKey() ),
1784 if ( $wgUseSquid ) {
1785 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1786 $u = new SquidUpdate( $urls );
1792 * Move page to non-existing title.
1793 * @param Title &$nt the new Title
1796 function moveToNewTitle( &$nt, $reason = '' ) {
1797 global $wgUser, $wgUseSquid;
1799 $fname = 'MovePageForm::moveToNewTitle';
1800 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1802 $comment .= ": $reason";
1805 $newid = $nt->getArticleID();
1806 $oldid = $this->getArticleID();
1807 $dbw =& wfGetDB( DB_MASTER
);
1808 $now = $dbw->timestamp();
1810 $linkCache =& LinkCache
::singleton();
1812 # Save a null revision in the page's history notifying of the move
1813 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1814 $nullRevId = $nullRevision->insertOn( $dbw );
1817 $dbw->update( 'page',
1819 'page_touched' => $now,
1820 'page_namespace' => $nt->getNamespace(),
1821 'page_title' => $nt->getDBkey(),
1822 'page_latest' => $nullRevId,
1824 /* WHERE */ array( 'page_id' => $oldid ),
1828 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1831 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1832 $redirectArticle = new Article( $this );
1833 $newid = $redirectArticle->insertOn( $dbw );
1834 $redirectRevision = new Revision( array(
1836 'comment' => $comment,
1837 'text' => $redirectText ) );
1838 $revid = $redirectRevision->insertOn( $dbw );
1839 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1840 $linkCache->clearLink( $this->getPrefixedDBkey() );
1843 $log = new LogPage( 'move' );
1844 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1846 # Purge caches as per article creation
1847 Article
::onArticleCreate( $nt );
1849 # Record the just-created redirect's linking to the page
1850 $dbw->insert( 'pagelinks',
1852 'pl_from' => $newid,
1853 'pl_namespace' => $nt->getNamespace(),
1854 'pl_title' => $nt->getDBkey() ),
1857 # Non-existent target may have had broken links to it; these must
1858 # now be touched to update link coloring.
1861 # Purge old title from squid
1862 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1863 $titles = $nt->getLinksTo();
1864 if ( $wgUseSquid ) {
1865 $urls = $this->getSquidURLs();
1866 foreach ( $titles as $linkTitle ) {
1867 $urls[] = $linkTitle->getInternalURL();
1869 $u = new SquidUpdate( $urls );
1875 * Checks if $this can be moved to a given Title
1876 * - Selects for update, so don't call it unless you mean business
1878 * @param Title &$nt the new title to check
1881 function isValidMoveTarget( $nt ) {
1883 $fname = 'Title::isValidMoveTarget';
1884 $dbw =& wfGetDB( DB_MASTER
);
1887 $id = $nt->getArticleID();
1888 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1889 array( 'page_is_redirect','old_text','old_flags' ),
1890 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1891 $fname, 'FOR UPDATE' );
1893 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1897 $text = Revision
::getRevisionText( $obj );
1899 # Does the redirect point to the source?
1900 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1901 $redirTitle = Title
::newFromText( $m[1] );
1902 if( !is_object( $redirTitle ) ||
1903 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1911 # Does the article have a history?
1912 $row = $dbw->selectRow( array( 'page', 'revision'),
1914 array( 'page_namespace' => $nt->getNamespace(),
1915 'page_title' => $nt->getDBkey(),
1916 'page_id=rev_page AND page_latest != rev_id'
1917 ), $fname, 'FOR UPDATE'
1920 # Return true if there was no history
1921 return $row === false;
1925 * Create a redirect; fails if the title already exists; does
1928 * @param Title $dest the destination of the redirect
1929 * @param string $comment the comment string describing the move
1930 * @return bool true on success
1933 function createRedirect( $dest, $comment ) {
1935 if ( $this->getArticleID() ) {
1939 $fname = 'Title::createRedirect';
1940 $dbw =& wfGetDB( DB_MASTER
);
1942 $article = new Article( $this );
1943 $newid = $article->insertOn( $dbw );
1944 $revision = new Revision( array(
1946 'comment' => $comment,
1947 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1949 $revisionId = $revision->insertOn( $dbw );
1950 $article->updateRevisionOn( $dbw, $revision, 0 );
1953 $dbw->insert( 'pagelinks',
1955 'pl_from' => $newid,
1956 'pl_namespace' => $dest->getNamespace(),
1957 'pl_title' => $dest->getDbKey()
1961 Article
::onArticleCreate( $this );
1966 * Get categories to which this Title belongs and return an array of
1967 * categories' names.
1969 * @return array an array of parents in the form:
1970 * $parent => $currentarticle
1973 function getParentCategories() {
1974 global $wgContLang,$wgUser;
1976 $titlekey = $this->getArticleId();
1977 $dbr =& wfGetDB( DB_SLAVE
);
1978 $categorylinks = $dbr->tableName( 'categorylinks' );
1981 $sql = "SELECT * FROM $categorylinks"
1982 ." WHERE cl_from='$titlekey'"
1983 ." AND cl_from <> '0'"
1984 ." ORDER BY cl_sortkey";
1986 $res = $dbr->query ( $sql ) ;
1988 if($dbr->numRows($res) > 0) {
1989 while ( $x = $dbr->fetchObject ( $res ) )
1990 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1991 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1992 $dbr->freeResult ( $res ) ;
2000 * Get a tree of parent categories
2001 * @param array $children an array with the children in the keys, to check for circular refs
2005 function getParentCategoryTree( $children = array() ) {
2006 $parents = $this->getParentCategories();
2008 if($parents != '') {
2009 foreach($parents as $parent => $current) {
2010 if ( array_key_exists( $parent, $children ) ) {
2011 # Circular reference
2012 $stack[$parent] = array();
2014 $nt = Title
::newFromText($parent);
2015 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2026 * Get an associative array for selecting this title from
2032 function pageCond() {
2033 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2037 * Get the revision ID of the previous revision
2039 * @param integer $revision Revision ID. Get the revision that was before this one.
2040 * @return interger $oldrevision|false
2042 function getPreviousRevisionID( $revision ) {
2043 $dbr =& wfGetDB( DB_SLAVE
);
2044 return $dbr->selectField( 'revision', 'rev_id',
2045 'rev_page=' . intval( $this->getArticleId() ) .
2046 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2050 * Get the revision ID of the next revision
2052 * @param integer $revision Revision ID. Get the revision that was after this one.
2053 * @return interger $oldrevision|false
2055 function getNextRevisionID( $revision ) {
2056 $dbr =& wfGetDB( DB_SLAVE
);
2057 return $dbr->selectField( 'revision', 'rev_id',
2058 'rev_page=' . intval( $this->getArticleId() ) .
2059 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2063 * Compare with another title.
2065 * @param Title $title
2068 function equals( $title ) {
2069 return $this->getInterwiki() == $title->getInterwiki()
2070 && $this->getNamespace() == $title->getNamespace()
2071 && $this->getDbkey() == $title->getDbkey();
2075 * Check if page exists
2079 return $this->getArticleId() != 0;
2083 * Should a link should be displayed as a known link, just based on its title?
2085 * Currently, a self-link with a fragment and special pages are in
2086 * this category. Special pages never exist in the database.
2088 function isAlwaysKnown() {
2089 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2090 || NS_SPECIAL
== $this->mNamespace
;
2094 * Update page_touched timestamps on pages linking to this title.
2095 * In principal, this could be backgrounded and could also do squid
2098 function touchLinks() {
2099 $fname = 'Title::touchLinks';
2101 $dbw =& wfGetDB( DB_MASTER
);
2103 $res = $dbw->select( 'pagelinks',
2106 'pl_namespace' => $this->getNamespace(),
2107 'pl_title' => $this->getDbKey() ),
2110 $toucharr = array();
2111 while( $row = $dbw->fetchObject( $res ) ) {
2112 $toucharr[] = $row->pl_from
;
2114 $dbw->freeResult( $res );
2116 if( $this->getNamespace() == NS_CATEGORY
) {
2117 // Categories show up in a separate set of links as well
2118 $res = $dbw->select( 'categorylinks',
2120 array( 'cl_to' => $this->getDbKey() ),
2122 while( $row = $dbw->fetchObject( $res ) ) {
2123 $toucharr[] = $row->cl_from
;
2125 $dbw->freeResult( $res );
2128 if (!count($toucharr))
2130 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2131 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2134 function trackbackURL() {
2135 global $wgTitle, $wgScriptPath, $wgServer;
2137 return "$wgServer$wgScriptPath/trackback.php?article="
2138 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2141 function trackbackRDF() {
2142 $url = htmlspecialchars($this->getFullURL());
2143 $title = htmlspecialchars($this->getText());
2144 $tburl = $this->trackbackURL();
2147 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2148 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2149 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2152 dc:identifier=\"$url\"
2154 trackback:ping=\"$tburl\" />