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 $this->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;
446 $db=dba_open($wgInterwikiCache,'r','cdb');
447 /* Resolve site name */
448 if ($wgInterwikiScopes>=3 and !$site) {
449 $site = dba_fetch("__sites:{$wgDBname}", $db);
451 $site = $wgInterwikiFallbackSite;
453 $value = dba_fetch("{$wgDBname}:{$key}", $db);
454 if ($value=='' and $wgInterwikiScopes>=3) {
456 $value = dba_fetch("_{$site}:{$key}", $db);
458 if ($value=='' and $wgInterwikiScopes>=2) {
460 $value = dba_fetch("__globals:{$key}", $db);
469 list($local,$url)=explode(' ',$value,2);
473 $wgTitleInterwikiCache[$wgDBname.':interwiki:'.$key] = $s;
477 * Determine whether the object refers to a page within
480 * @return bool TRUE if this is an in-project interwiki link
481 * or a wikilink, FALSE otherwise
485 global $wgTitleInterwikiCache, $wgDBname;
487 if ( $this->mInterwiki
!= '' ) {
488 # Make sure key is loaded into cache
489 $this->getInterwikiLink( $this->mInterwiki
);
490 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
491 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
498 * Determine whether the object refers to a page within
499 * this project and is transcludable.
501 * @return bool TRUE if this is transcludable
505 global $wgTitleInterwikiCache, $wgDBname;
507 if ($this->mInterwiki
== '' ||
!$this->isLocal())
509 # Make sure key is loaded into cache
510 $this->getInterwikiLink( $this->mInterwiki
);
511 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
512 return (bool)($wgTitleInterwikiCache[$k]->iw_trans
);
516 * Update the page_touched field for an array of title objects
517 * @todo Inefficient unless the IDs are already loaded into the
519 * @param array $titles an array of Title objects to be touched
520 * @param string $timestamp the timestamp to use instead of the
521 * default current time
525 function touchArray( $titles, $timestamp = '' ) {
527 if ( count( $titles ) == 0 ) {
530 $dbw =& wfGetDB( DB_MASTER
);
531 if ( $timestamp == '' ) {
532 $timestamp = $dbw->timestamp();
535 $page = $dbw->tableName( 'page' );
536 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
539 foreach ( $titles as $title ) {
540 if ( $wgUseFileCache ) {
541 $cm = new CacheManager($title);
542 @unlink($cm->fileCacheName());
549 $sql .= $title->getArticleID();
553 $dbw->query( $sql, 'Title::touchArray' );
556 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
557 // do them in small chunks:
558 $fname = 'Title::touchArray';
559 foreach( $titles as $title ) {
560 $dbw->update( 'page',
561 array( 'page_touched' => $timestamp ),
563 'page_namespace' => $title->getNamespace(),
564 'page_title' => $title->getDBkey() ),
569 #----------------------------------------------------------------------------
571 #----------------------------------------------------------------------------
573 /** Simple accessors */
575 * Get the text form (spaces not underscores) of the main part
579 function getText() { return $this->mTextform
; }
581 * Get the URL-encoded form of the main part
585 function getPartialURL() { return $this->mUrlform
; }
587 * Get the main part with underscores
591 function getDBkey() { return $this->mDbkeyform
; }
593 * Get the namespace index, i.e. one of the NS_xxxx constants
597 function getNamespace() { return $this->mNamespace
; }
599 * Get the namespace text
603 function getNsText() {
605 return $wgContLang->getNsText( $this->mNamespace
);
608 * Get the namespace text of the subject (rather than talk) page
612 function getSubjectNsText() {
614 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
618 * Get the interwiki prefix (or null string)
622 function getInterwiki() { return $this->mInterwiki
; }
624 * Get the Title fragment (i.e. the bit after the #)
628 function getFragment() { return $this->mFragment
; }
630 * Get the default namespace index, for when there is no namespace
634 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
637 * Get title for search index
638 * @return string a stripped-down title string ready for the
641 function getIndexTitle() {
642 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
646 * Get the prefixed database key form
647 * @return string the prefixed title, with underscores and
648 * any interwiki and namespace prefixes
651 function getPrefixedDBkey() {
652 $s = $this->prefix( $this->mDbkeyform
);
653 $s = str_replace( ' ', '_', $s );
658 * Get the prefixed title with spaces.
659 * This is the form usually used for display
660 * @return string the prefixed title, with spaces
663 function getPrefixedText() {
665 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
666 $s = $this->prefix( $this->mTextform
);
667 $s = str_replace( '_', ' ', $s );
668 $this->mPrefixedText
= $s;
670 return $this->mPrefixedText
;
674 * Get the prefixed title with spaces, plus any fragment
675 * (part beginning with '#')
676 * @return string the prefixed title, with spaces and
677 * the fragment, including '#'
680 function getFullText() {
682 $text = $this->getPrefixedText();
683 if( '' != $this->mFragment
) {
684 $text .= '#' . $this->mFragment
;
690 * Get a URL-encoded title (not an actual URL) including interwiki
691 * @return string the URL-encoded form
694 function getPrefixedURL() {
695 $s = $this->prefix( $this->mDbkeyform
);
696 $s = str_replace( ' ', '_', $s );
698 $s = wfUrlencode ( $s ) ;
700 # Cleaning up URL to make it look nice -- is this safe?
701 $s = str_replace( '%28', '(', $s );
702 $s = str_replace( '%29', ')', $s );
708 * Get a real URL referring to this title, with interwiki link and
711 * @param string $query an optional query string, not used
712 * for interwiki links
713 * @return string the URL
716 function getFullURL( $query = '' ) {
717 global $wgContLang, $wgServer, $wgRequest;
719 if ( '' == $this->mInterwiki
) {
720 $url = $this->getLocalUrl( $query );
722 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
723 // Correct fix would be to move the prepending elsewhere.
724 if ($wgRequest->getVal('action') != 'render') {
725 $url = $wgServer . $url;
728 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
730 $namespace = $wgContLang->getNsText( $this->mNamespace
);
731 if ( '' != $namespace ) {
732 # Can this actually happen? Interwikis shouldn't be parsed.
735 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
737 if( false === strpos( $url, '?' ) ) {
744 if ( '' != $this->mFragment
) {
745 $url .= '#' . $this->mFragment
;
748 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
753 * Get a URL with no fragment or server name. If this page is generated
754 * with action=render, $wgServer is prepended.
755 * @param string $query an optional query string; if not specified,
756 * $wgArticlePath will be used.
757 * @return string the URL
760 function getLocalURL( $query = '' ) {
761 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
763 if ( $this->isExternal() ) {
764 $url = $this->getFullURL();
766 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
767 if ( $query == '' ) {
768 $url = str_replace( '$1', $dbkey, $wgArticlePath );
770 global $wgActionPaths;
772 if( !empty( $wgActionPaths ) &&
773 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
775 $action = urldecode( $matches[2] );
776 if( isset( $wgActionPaths[$action] ) ) {
777 $query = $matches[1];
778 if( isset( $matches[4] ) ) $query .= $matches[4];
779 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
780 if( $query != '' ) $url .= '?' . $query;
783 if ( $url === false ) {
784 if ( $query == '-' ) {
787 $url = "{$wgScript}?title={$dbkey}&{$query}";
791 // FIXME: this causes breakage in various places when we
792 // actually expected a local URL and end up with dupe prefixes.
793 if ($wgRequest->getVal('action') == 'render') {
794 $url = $wgServer . $url;
797 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
802 * Get an HTML-escaped version of the URL form, suitable for
803 * using in a link, without a server name or fragment
804 * @param string $query an optional query string
805 * @return string the URL
808 function escapeLocalURL( $query = '' ) {
809 return htmlspecialchars( $this->getLocalURL( $query ) );
813 * Get an HTML-escaped version of the URL form, suitable for
814 * using in a link, including the server name and fragment
816 * @return string the URL
817 * @param string $query an optional query string
820 function escapeFullURL( $query = '' ) {
821 return htmlspecialchars( $this->getFullURL( $query ) );
825 * Get the URL form for an internal link.
826 * - Used in various Squid-related code, in case we have a different
827 * internal hostname for the server from the exposed one.
829 * @param string $query an optional query string
830 * @return string the URL
833 function getInternalURL( $query = '' ) {
834 global $wgInternalServer;
835 $url = $wgInternalServer . $this->getLocalURL( $query );
836 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
841 * Get the edit URL for this Title
842 * @return string the URL, or a null string if this is an
846 function getEditURL() {
847 global $wgServer, $wgScript;
849 if ( '' != $this->mInterwiki
) { return ''; }
850 $s = $this->getLocalURL( 'action=edit' );
856 * Get the HTML-escaped displayable text form.
857 * Used for the title field in <a> tags.
858 * @return string the text, including any prefixes
861 function getEscapedText() {
862 return htmlspecialchars( $this->getPrefixedText() );
866 * Is this Title interwiki?
870 function isExternal() { return ( '' != $this->mInterwiki
); }
873 * Does the title correspond to a protected article?
874 * @param string $what the action the page is protected from,
875 * by default checks move and edit
879 function isProtected( $action = '' ) {
880 global $wgRestrictionLevels;
881 if ( -1 == $this->mNamespace
) { return true; }
883 if( $action == 'edit' ||
$action == '' ) {
884 $r = $this->getRestrictions( 'edit' );
885 foreach( $wgRestrictionLevels as $level ) {
886 if( in_array( $level, $r ) && $level != '' ) {
892 if( $action == 'move' ||
$action == '' ) {
893 $r = $this->getRestrictions( 'move' );
894 foreach( $wgRestrictionLevels as $level ) {
895 if( in_array( $level, $r ) && $level != '' ) {
905 * Is $wgUser is watching this page?
909 function userIsWatching() {
912 if ( is_null( $this->mWatched
) ) {
913 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
914 $this->mWatched
= false;
916 $this->mWatched
= $wgUser->isWatched( $this );
919 return $this->mWatched
;
923 * Can $wgUser perform $action this page?
924 * @param string $action action that permission needs to be checked for
928 function userCan($action) {
929 $fname = 'Title::userCan';
930 wfProfileIn( $fname );
933 if( NS_SPECIAL
== $this->mNamespace
) {
934 wfProfileOut( $fname );
937 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
938 // from taking effect -ævar
939 if( NS_MEDIAWIKI
== $this->mNamespace
&&
940 !$wgUser->isAllowed('editinterface') ) {
941 wfProfileOut( $fname );
945 if( $this->mDbkeyform
== '_' ) {
946 # FIXME: Is this necessary? Shouldn't be allowed anyway...
947 wfProfileOut( $fname );
951 # protect global styles and js
952 if ( NS_MEDIAWIKI
== $this->mNamespace
953 && preg_match("/\\.(css|js)$/", $this->mTextform
)
954 && !$wgUser->isAllowed('editinterface') ) {
955 wfProfileOut( $fname );
959 # protect css/js subpages of user pages
960 # XXX: this might be better using restrictions
961 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
962 if( NS_USER
== $this->mNamespace
963 && preg_match("/\\.(css|js)$/", $this->mTextform
)
964 && !$wgUser->isAllowed('editinterface')
965 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
966 wfProfileOut( $fname );
970 foreach( $this->getRestrictions($action) as $right ) {
971 // Backwards compatibility, rewrite sysop -> protect
972 if ( $right == 'sysop' ) {
975 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
976 wfProfileOut( $fname );
981 if( $action == 'move' &&
982 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
983 wfProfileOut( $fname );
987 if( $action == 'create' ) {
988 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
989 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
994 wfProfileOut( $fname );
999 * Can $wgUser edit this page?
1003 function userCanEdit() {
1004 return $this->userCan('edit');
1008 * Can $wgUser move this page?
1012 function userCanMove() {
1013 return $this->userCan('move');
1017 * Would anybody with sufficient privileges be able to move this page?
1018 * Some pages just aren't movable.
1023 function isMovable() {
1024 return Namespace::isMovable( $this->getNamespace() )
1025 && $this->getInterwiki() == '';
1029 * Can $wgUser read this page?
1033 function userCanRead() {
1036 if( $wgUser->isAllowed('read') ) {
1039 global $wgWhitelistRead;
1041 /** If anon users can create an account,
1042 they need to reach the login page first! */
1043 if( $wgUser->isAllowed( 'createaccount' )
1044 && $this->getNamespace() == NS_SPECIAL
1045 && $this->getText() == 'Userlogin' ) {
1049 /** some pages are explicitly allowed */
1050 $name = $this->getPrefixedText();
1051 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1055 # Compatibility with old settings
1056 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1057 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1066 * Is this a talk page of some sort?
1070 function isTalkPage() {
1071 return Namespace::isTalk( $this->getNamespace() );
1075 * Is this a .css or .js subpage of a user page?
1079 function isCssJsSubpage() {
1080 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1083 * Is this a .css subpage of a user page?
1087 function isCssSubpage() {
1088 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1091 * Is this a .js subpage of a user page?
1095 function isJsSubpage() {
1096 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1099 * Protect css/js subpages of user pages: can $wgUser edit
1103 * @todo XXX: this might be better using restrictions
1106 function userCanEditCssJsSubpage() {
1108 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1112 * Loads a string into mRestrictions array
1113 * @param string $res restrictions in string format
1116 function loadRestrictions( $res ) {
1117 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1118 $temp = explode( '=', trim( $restrict ) );
1119 if(count($temp) == 1) {
1120 // old format should be treated as edit/move restriction
1121 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1122 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1124 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1127 $this->mRestrictionsLoaded
= true;
1131 * Accessor/initialisation for mRestrictions
1132 * @param string $action action that permission needs to be checked for
1133 * @return array the array of groups allowed to edit this article
1136 function getRestrictions($action) {
1137 $id = $this->getArticleID();
1138 if ( 0 == $id ) { return array(); }
1140 if ( ! $this->mRestrictionsLoaded
) {
1141 $dbr =& wfGetDB( DB_SLAVE
);
1142 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1143 $this->loadRestrictions( $res );
1145 if( isset( $this->mRestrictions
[$action] ) ) {
1146 return $this->mRestrictions
[$action];
1152 * Is there a version of this page in the deletion archive?
1153 * @return int the number of archived revisions
1156 function isDeleted() {
1157 $fname = 'Title::isDeleted';
1158 if ( $this->getNamespace() < 0 ) {
1161 $dbr =& wfGetDB( DB_SLAVE
);
1162 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1163 'ar_title' => $this->getDBkey() ), $fname );
1169 * Get the article ID for this Title from the link cache,
1170 * adding it if necessary
1171 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1173 * @return int the ID
1176 function getArticleID( $flags = 0 ) {
1177 $linkCache =& LinkCache
::singleton();
1178 if ( $flags & GAID_FOR_UPDATE
) {
1179 $oldUpdate = $linkCache->forUpdate( true );
1180 $this->mArticleID
= $linkCache->addLinkObj( $this );
1181 $linkCache->forUpdate( $oldUpdate );
1183 if ( -1 == $this->mArticleID
) {
1184 $this->mArticleID
= $linkCache->addLinkObj( $this );
1187 return $this->mArticleID
;
1190 function getLatestRevID() {
1191 if ($this->mLatestID
!== false)
1192 return $this->mLatestID
;
1194 $db =& wfGetDB(DB_SLAVE
);
1195 return $this->mLatestID
= $db->selectField( 'revision',
1197 array('rev_page' => $this->getArticleID()),
1198 'Title::getLatestRevID' );
1202 * This clears some fields in this object, and clears any associated
1203 * keys in the "bad links" section of the link cache.
1205 * - This is called from Article::insertNewArticle() to allow
1206 * loading of the new page_id. It's also called from
1207 * Article::doDeleteArticle()
1209 * @param int $newid the new Article ID
1212 function resetArticleID( $newid ) {
1213 $linkCache =& LinkCache
::singleton();
1214 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1216 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1217 else { $this->mArticleID
= $newid; }
1218 $this->mRestrictionsLoaded
= false;
1219 $this->mRestrictions
= array();
1223 * Updates page_touched for this page; called from LinksUpdate.php
1224 * @return bool true if the update succeded
1227 function invalidateCache() {
1228 global $wgUseFileCache;
1230 if ( wfReadOnly() ) {
1234 $dbw =& wfGetDB( DB_MASTER
);
1235 $success = $dbw->update( 'page',
1237 'page_touched' => $dbw->timestamp()
1238 ), array( /* WHERE */
1239 'page_namespace' => $this->getNamespace() ,
1240 'page_title' => $this->getDBkey()
1241 ), 'Title::invalidateCache'
1244 if ($wgUseFileCache) {
1245 $cache = new CacheManager($this);
1246 @unlink
($cache->fileCacheName());
1253 * Prefix some arbitrary text with the namespace or interwiki prefix
1256 * @param string $name the text
1257 * @return string the prefixed text
1260 /* private */ function prefix( $name ) {
1264 if ( '' != $this->mInterwiki
) {
1265 $p = $this->mInterwiki
. ':';
1267 if ( 0 != $this->mNamespace
) {
1268 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1274 * Secure and split - main initialisation function for this object
1276 * Assumes that mDbkeyform has been set, and is urldecoded
1277 * and uses underscores, but not otherwise munged. This function
1278 * removes illegal characters, splits off the interwiki and
1279 * namespace prefixes, sets the other forms, and canonicalizes
1281 * @return bool true on success
1284 /* private */ function secureAndSplit() {
1285 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1286 $fname = 'Title::secureAndSplit';
1287 wfProfileIn( $fname );
1290 static $rxTc = false;
1292 # % is needed as well
1293 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1296 $this->mInterwiki
= $this->mFragment
= '';
1297 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1299 # Clean up whitespace
1301 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1302 $t = trim( $t, '_' );
1305 wfProfileOut( $fname );
1309 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1310 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1311 wfProfileOut( $fname );
1315 $this->mDbkeyform
= $t;
1317 # Initial colon indicates main namespace rather than specified default
1318 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1319 if ( ':' == $t{0} ) {
1320 $this->mNamespace
= NS_MAIN
;
1321 $t = substr( $t, 1 ); # remove the colon but continue processing
1324 # Namespace or interwiki prefix
1327 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1329 $lowerNs = strtolower( $p );
1330 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1331 # Canonical namespace
1333 $this->mNamespace
= $ns;
1334 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1335 # Ordinary namespace
1337 $this->mNamespace
= $ns;
1338 } elseif( $this->getInterwikiLink( $p ) ) {
1340 # Can't make a local interwiki link to an interwiki link.
1341 # That's just crazy!
1342 wfProfileOut( $fname );
1348 $this->mInterwiki
= strtolower( $p );
1350 # Redundant interwiki prefix to the local wiki
1351 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1353 # Can't have an empty self-link
1354 wfProfileOut( $fname );
1357 $this->mInterwiki
= '';
1359 # Do another namespace split...
1363 # If there's no recognized interwiki or namespace,
1364 # then let the colon expression be part of the title.
1370 # We already know that some pages won't be in the database!
1372 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1373 $this->mArticleID
= 0;
1375 $f = strstr( $r, '#' );
1376 if ( false !== $f ) {
1377 $this->mFragment
= substr( $f, 1 );
1378 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1379 # remove whitespace again: prevents "Foo_bar_#"
1380 # becoming "Foo_bar_"
1381 $r = preg_replace( '/_*$/', '', $r );
1384 # Reject illegal characters.
1386 if( preg_match( $rxTc, $r ) ) {
1387 wfProfileOut( $fname );
1392 * Pages with "/./" or "/../" appearing in the URLs will
1393 * often be unreachable due to the way web browsers deal
1394 * with 'relative' URLs. Forbid them explicitly.
1396 if ( strpos( $r, '.' ) !== false &&
1397 ( $r === '.' ||
$r === '..' ||
1398 strpos( $r, './' ) === 0 ||
1399 strpos( $r, '../' ) === 0 ||
1400 strpos( $r, '/./' ) !== false ||
1401 strpos( $r, '/../' ) !== false ) )
1403 wfProfileOut( $fname );
1407 # We shouldn't need to query the DB for the size.
1408 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1409 if ( strlen( $r ) > 255 ) {
1410 wfProfileOut( $fname );
1415 * Normally, all wiki links are forced to have
1416 * an initial capital letter so [[foo]] and [[Foo]]
1417 * point to the same place.
1419 * Don't force it for interwikis, since the other
1420 * site might be case-sensitive.
1422 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1423 $t = $wgContLang->ucfirst( $r );
1429 * Can't make a link to a namespace alone...
1430 * "empty" local links can only be self-links
1431 * with a fragment identifier.
1434 $this->mInterwiki
== '' &&
1435 $this->mNamespace
!= NS_MAIN
) {
1436 wfProfileOut( $fname );
1441 $this->mDbkeyform
= $t;
1442 $this->mUrlform
= wfUrlencode( $t );
1444 $this->mTextform
= str_replace( '_', ' ', $t );
1446 wfProfileOut( $fname );
1451 * Get a Title object associated with the talk page of this article
1452 * @return Title the object for the talk page
1455 function getTalkPage() {
1456 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1460 * Get a title object associated with the subject page of this
1463 * @return Title the object for the subject page
1466 function getSubjectPage() {
1467 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1471 * Get an array of Title objects linking to this Title
1472 * Also stores the IDs in the link cache.
1474 * @param string $options may be FOR UPDATE
1475 * @return array the Title objects linking here
1478 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1479 $linkCache =& LinkCache
::singleton();
1480 $id = $this->getArticleID();
1483 $db =& wfGetDB( DB_MASTER
);
1485 $db =& wfGetDB( DB_SLAVE
);
1488 $res = $db->select( array( 'page', $table ),
1489 array( 'page_namespace', 'page_title', 'page_id' ),
1491 "{$prefix}_from=page_id",
1492 "{$prefix}_namespace" => $this->getNamespace(),
1493 "{$prefix}_title" => $this->getDbKey() ),
1494 'Title::getLinksTo',
1498 if ( $db->numRows( $res ) ) {
1499 while ( $row = $db->fetchObject( $res ) ) {
1500 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1501 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1502 $retVal[] = $titleObj;
1506 $db->freeResult( $res );
1511 * Get an array of Title objects using this Title as a template
1512 * Also stores the IDs in the link cache.
1514 * @param string $options may be FOR UPDATE
1515 * @return array the Title objects linking here
1518 function getTemplateLinksTo( $options = '' ) {
1519 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1523 * Get an array of Title objects referring to non-existent articles linked from this page
1525 * @param string $options may be FOR UPDATE
1526 * @return array the Title objects
1529 function getBrokenLinksFrom( $options = '' ) {
1531 $db =& wfGetDB( DB_MASTER
);
1533 $db =& wfGetDB( DB_SLAVE
);
1536 $res = $db->safeQuery(
1537 "SELECT pl_namespace, pl_title
1540 ON pl_namespace=page_namespace
1541 AND pl_title=page_title
1543 AND page_namespace IS NULL
1545 $db->tableName( 'pagelinks' ),
1546 $db->tableName( 'page' ),
1547 $this->getArticleId(),
1551 if ( $db->numRows( $res ) ) {
1552 while ( $row = $db->fetchObject( $res ) ) {
1553 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1556 $db->freeResult( $res );
1562 * Get a list of URLs to purge from the Squid cache when this
1565 * @return array the URLs
1568 function getSquidURLs() {
1570 $this->getInternalURL(),
1571 $this->getInternalURL( 'action=history' )
1576 * Move this page without authentication
1577 * @param Title &$nt the new page Title
1580 function moveNoAuth( &$nt ) {
1581 return $this->moveTo( $nt, false );
1585 * Check whether a given move operation would be valid.
1586 * Returns true if ok, or a message key string for an error message
1587 * if invalid. (Scarrrrry ugly interface this.)
1588 * @param Title &$nt the new title
1589 * @param bool $auth indicates whether $wgUser's permissions
1591 * @return mixed true on success, message name on failure
1594 function isValidMoveOperation( &$nt, $auth = true ) {
1596 if( !$this or !$nt ) {
1597 return 'badtitletext';
1599 if( $this->equals( $nt ) ) {
1602 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1603 return 'immobile_namespace';
1606 $oldid = $this->getArticleID();
1607 $newid = $nt->getArticleID();
1609 if ( strlen( $nt->getDBkey() ) < 1 ) {
1610 return 'articleexists';
1612 if ( ( '' == $this->getDBkey() ) ||
1614 ( '' == $nt->getDBkey() ) ) {
1615 return 'badarticleerror';
1619 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1620 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1621 return 'protectedpage';
1624 # The move is allowed only if (1) the target doesn't exist, or
1625 # (2) the target is a redirect to the source, and has no history
1626 # (so we can undo bad moves right after they're done).
1628 if ( 0 != $newid ) { # Target exists; check for validity
1629 if ( ! $this->isValidMoveTarget( $nt ) ) {
1630 return 'articleexists';
1637 * Move a title to a new location
1638 * @param Title &$nt the new title
1639 * @param bool $auth indicates whether $wgUser's permissions
1641 * @return mixed true on success, message name on failure
1644 function moveTo( &$nt, $auth = true, $reason = '' ) {
1645 $err = $this->isValidMoveOperation( $nt, $auth );
1646 if( is_string( $err ) ) {
1650 $pageid = $this->getArticleID();
1651 if( $nt->exists() ) {
1652 $this->moveOverExistingRedirect( $nt, $reason );
1653 $pageCountChange = 0;
1654 } else { # Target didn't exist, do normal move.
1655 $this->moveToNewTitle( $nt, $reason );
1656 $pageCountChange = 1;
1658 $redirid = $this->getArticleID();
1660 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1661 $dbw =& wfGetDB( DB_MASTER
);
1662 $categorylinks = $dbw->tableName( 'categorylinks' );
1663 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1664 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1665 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1666 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1670 $oldnamespace = $this->getNamespace() & ~
1;
1671 $newnamespace = $nt->getNamespace() & ~
1;
1672 $oldtitle = $this->getDBkey();
1673 $newtitle = $nt->getDBkey();
1675 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1676 WatchedItem
::duplicateEntries( $this, $nt );
1679 # Update search engine
1680 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1682 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1686 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1687 # Moved out of main namespace
1688 # not viewed, edited, removing
1689 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1690 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1691 # Moved into main namespace
1692 # not viewed, edited, adding
1693 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1694 } elseif ( $pageCountChange ) {
1696 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1705 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1710 * Move page to a title which is at present a redirect to the
1713 * @param Title &$nt the page to move to, which should currently
1717 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1718 global $wgUser, $wgUseSquid, $wgMwRedir;
1719 $fname = 'Title::moveOverExistingRedirect';
1720 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1723 $comment .= ": $reason";
1726 $now = wfTimestampNow();
1728 $newid = $nt->getArticleID();
1729 $oldid = $this->getArticleID();
1730 $dbw =& wfGetDB( DB_MASTER
);
1731 $linkCache =& LinkCache
::singleton();
1733 # Delete the old redirect. We don't save it to history since
1734 # by definition if we've got here it's rather uninteresting.
1735 # We have to remove it so that the next step doesn't trigger
1736 # a conflict on the unique namespace+title index...
1737 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1739 # Save a null revision in the page's history notifying of the move
1740 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1741 $nullRevId = $nullRevision->insertOn( $dbw );
1743 # Change the name of the target page:
1744 $dbw->update( 'page',
1746 'page_touched' => $dbw->timestamp($now),
1747 'page_namespace' => $nt->getNamespace(),
1748 'page_title' => $nt->getDBkey(),
1749 'page_latest' => $nullRevId,
1751 /* WHERE */ array( 'page_id' => $oldid ),
1754 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1756 # Recreate the redirect, this time in the other direction.
1757 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1758 $redirectArticle = new Article( $this );
1759 $newid = $redirectArticle->insertOn( $dbw );
1760 $redirectRevision = new Revision( array(
1762 'comment' => $comment,
1763 'text' => $redirectText ) );
1764 $revid = $redirectRevision->insertOn( $dbw );
1765 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1766 $linkCache->clearLink( $this->getPrefixedDBkey() );
1769 $log = new LogPage( 'move' );
1770 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1772 # Now, we record the link from the redirect to the new title.
1773 # It should have no other outgoing links...
1774 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1775 $dbw->insert( 'pagelinks',
1777 'pl_from' => $newid,
1778 'pl_namespace' => $nt->getNamespace(),
1779 'pl_title' => $nt->getDbKey() ),
1783 if ( $wgUseSquid ) {
1784 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1785 $u = new SquidUpdate( $urls );
1791 * Move page to non-existing title.
1792 * @param Title &$nt the new Title
1795 function moveToNewTitle( &$nt, $reason = '' ) {
1796 global $wgUser, $wgUseSquid;
1798 $fname = 'MovePageForm::moveToNewTitle';
1799 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1801 $comment .= ": $reason";
1804 $newid = $nt->getArticleID();
1805 $oldid = $this->getArticleID();
1806 $dbw =& wfGetDB( DB_MASTER
);
1807 $now = $dbw->timestamp();
1809 $linkCache =& LinkCache
::singleton();
1811 # Save a null revision in the page's history notifying of the move
1812 $nullRevision = Revision
::newNullRevision( $dbw, $oldid, $comment, true );
1813 $nullRevId = $nullRevision->insertOn( $dbw );
1816 $dbw->update( 'page',
1818 'page_touched' => $now,
1819 'page_namespace' => $nt->getNamespace(),
1820 'page_title' => $nt->getDBkey(),
1821 'page_latest' => $nullRevId,
1823 /* WHERE */ array( 'page_id' => $oldid ),
1827 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1830 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1831 $redirectArticle = new Article( $this );
1832 $newid = $redirectArticle->insertOn( $dbw );
1833 $redirectRevision = new Revision( array(
1835 'comment' => $comment,
1836 'text' => $redirectText ) );
1837 $revid = $redirectRevision->insertOn( $dbw );
1838 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1839 $linkCache->clearLink( $this->getPrefixedDBkey() );
1842 $log = new LogPage( 'move' );
1843 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1845 # Purge caches as per article creation
1846 Article
::onArticleCreate( $nt );
1848 # Record the just-created redirect's linking to the page
1849 $dbw->insert( 'pagelinks',
1851 'pl_from' => $newid,
1852 'pl_namespace' => $nt->getNamespace(),
1853 'pl_title' => $nt->getDBkey() ),
1856 # Non-existent target may have had broken links to it; these must
1857 # now be touched to update link coloring.
1860 # Purge old title from squid
1861 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1862 $titles = $nt->getLinksTo();
1863 if ( $wgUseSquid ) {
1864 $urls = $this->getSquidURLs();
1865 foreach ( $titles as $linkTitle ) {
1866 $urls[] = $linkTitle->getInternalURL();
1868 $u = new SquidUpdate( $urls );
1874 * Checks if $this can be moved to a given Title
1875 * - Selects for update, so don't call it unless you mean business
1877 * @param Title &$nt the new title to check
1880 function isValidMoveTarget( $nt ) {
1882 $fname = 'Title::isValidMoveTarget';
1883 $dbw =& wfGetDB( DB_MASTER
);
1886 $id = $nt->getArticleID();
1887 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1888 array( 'page_is_redirect','old_text','old_flags' ),
1889 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1890 $fname, 'FOR UPDATE' );
1892 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1896 $text = Revision
::getRevisionText( $obj );
1898 # Does the redirect point to the source?
1899 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1900 $redirTitle = Title
::newFromText( $m[1] );
1901 if( !is_object( $redirTitle ) ||
1902 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1910 # Does the article have a history?
1911 $row = $dbw->selectRow( array( 'page', 'revision'),
1913 array( 'page_namespace' => $nt->getNamespace(),
1914 'page_title' => $nt->getDBkey(),
1915 'page_id=rev_page AND page_latest != rev_id'
1916 ), $fname, 'FOR UPDATE'
1919 # Return true if there was no history
1920 return $row === false;
1924 * Create a redirect; fails if the title already exists; does
1927 * @param Title $dest the destination of the redirect
1928 * @param string $comment the comment string describing the move
1929 * @return bool true on success
1932 function createRedirect( $dest, $comment ) {
1934 if ( $this->getArticleID() ) {
1938 $fname = 'Title::createRedirect';
1939 $dbw =& wfGetDB( DB_MASTER
);
1941 $article = new Article( $this );
1942 $newid = $article->insertOn( $dbw );
1943 $revision = new Revision( array(
1945 'comment' => $comment,
1946 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1948 $revisionId = $revision->insertOn( $dbw );
1949 $article->updateRevisionOn( $dbw, $revision, 0 );
1952 $dbw->insert( 'pagelinks',
1954 'pl_from' => $newid,
1955 'pl_namespace' => $dest->getNamespace(),
1956 'pl_title' => $dest->getDbKey()
1960 Article
::onArticleCreate( $this );
1965 * Get categories to which this Title belongs and return an array of
1966 * categories' names.
1968 * @return array an array of parents in the form:
1969 * $parent => $currentarticle
1972 function getParentCategories() {
1973 global $wgContLang,$wgUser;
1975 $titlekey = $this->getArticleId();
1976 $dbr =& wfGetDB( DB_SLAVE
);
1977 $categorylinks = $dbr->tableName( 'categorylinks' );
1980 $sql = "SELECT * FROM $categorylinks"
1981 ." WHERE cl_from='$titlekey'"
1982 ." AND cl_from <> '0'"
1983 ." ORDER BY cl_sortkey";
1985 $res = $dbr->query ( $sql ) ;
1987 if($dbr->numRows($res) > 0) {
1988 while ( $x = $dbr->fetchObject ( $res ) )
1989 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1990 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1991 $dbr->freeResult ( $res ) ;
1999 * Get a tree of parent categories
2000 * @param array $children an array with the children in the keys, to check for circular refs
2004 function getParentCategoryTree( $children = array() ) {
2005 $parents = $this->getParentCategories();
2007 if($parents != '') {
2008 foreach($parents as $parent => $current) {
2009 if ( array_key_exists( $parent, $children ) ) {
2010 # Circular reference
2011 $stack[$parent] = array();
2013 $nt = Title
::newFromText($parent);
2014 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2025 * Get an associative array for selecting this title from
2031 function pageCond() {
2032 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
2036 * Get the revision ID of the previous revision
2038 * @param integer $revision Revision ID. Get the revision that was before this one.
2039 * @return interger $oldrevision|false
2041 function getPreviousRevisionID( $revision ) {
2042 $dbr =& wfGetDB( DB_SLAVE
);
2043 return $dbr->selectField( 'revision', 'rev_id',
2044 'rev_page=' . intval( $this->getArticleId() ) .
2045 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2049 * Get the revision ID of the next revision
2051 * @param integer $revision Revision ID. Get the revision that was after this one.
2052 * @return interger $oldrevision|false
2054 function getNextRevisionID( $revision ) {
2055 $dbr =& wfGetDB( DB_SLAVE
);
2056 return $dbr->selectField( 'revision', 'rev_id',
2057 'rev_page=' . intval( $this->getArticleId() ) .
2058 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2062 * Compare with another title.
2064 * @param Title $title
2067 function equals( $title ) {
2068 return $this->getInterwiki() == $title->getInterwiki()
2069 && $this->getNamespace() == $title->getNamespace()
2070 && $this->getDbkey() == $title->getDbkey();
2074 * Check if page exists
2078 return $this->getArticleId() != 0;
2082 * Should a link should be displayed as a known link, just based on its title?
2084 * Currently, a self-link with a fragment and special pages are in
2085 * this category. Special pages never exist in the database.
2087 function isAlwaysKnown() {
2088 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2089 || NS_SPECIAL
== $this->mNamespace
;
2093 * Update page_touched timestamps on pages linking to this title.
2094 * In principal, this could be backgrounded and could also do squid
2097 function touchLinks() {
2098 $fname = 'Title::touchLinks';
2100 $dbw =& wfGetDB( DB_MASTER
);
2102 $res = $dbw->select( 'pagelinks',
2105 'pl_namespace' => $this->getNamespace(),
2106 'pl_title' => $this->getDbKey() ),
2109 $toucharr = array();
2110 while( $row = $dbw->fetchObject( $res ) ) {
2111 $toucharr[] = $row->pl_from
;
2113 $dbw->freeResult( $res );
2115 if( $this->getNamespace() == NS_CATEGORY
) {
2116 // Categories show up in a separate set of links as well
2117 $res = $dbw->select( 'categorylinks',
2119 array( 'cl_to' => $this->getDbKey() ),
2121 while( $row = $dbw->fetchObject( $res ) ) {
2122 $toucharr[] = $row->cl_from
;
2124 $dbw->freeResult( $res );
2127 if (!count($toucharr))
2129 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2130 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2133 function trackbackURL() {
2134 global $wgTitle, $wgScriptPath, $wgServer;
2136 return "$wgServer$wgScriptPath/trackback.php?article="
2137 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2140 function trackbackRDF() {
2141 $url = htmlspecialchars($this->getFullURL());
2142 $title = htmlspecialchars($this->getText());
2143 $tburl = $this->trackbackURL();
2146 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2147 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2148 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2151 dc:identifier=\"$url\"
2153 trackback:ping=\"$tburl\" />