9 require_once( 'normal/UtfNormal.php' );
11 $wgTitleInterwikiCache = array();
12 define ( 'GAID_FOR_UPDATE', 1 );
14 # Title::newFromTitle maintains a cache to avoid
15 # expensive re-normalization of commonly used titles.
16 # On a batch operation this can become a memory leak
17 # if not bounded. After hitting this many titles,
19 define( 'MW_TITLECACHE_MAX', 1000 );
23 * - Represents a title, which may contain an interwiki designation or namespace
24 * - Can fetch various kinds of data from the database, albeit inefficiently.
30 * All member variables should be considered private
31 * Please use the accessor functions
38 var $mTextform; # Text form (spaces not underscores) of the main part
39 var $mUrlform; # URL-encoded form of the main part
40 var $mDbkeyform; # Main part with underscores
41 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
42 var $mInterwiki; # Interwiki prefix (or null string)
43 var $mFragment; # Title fragment (i.e. the bit after the #)
44 var $mArticleID; # Article ID, fetched from the link cache on demand
45 var $mLatestID; # ID of most recent revision
46 var $mRestrictions; # Array of groups allowed to edit this article
47 # Only null or "sysop" are supported
48 var $mRestrictionsLoaded; # Boolean for initialisation on demand
49 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
50 var $mDefaultNamespace; # Namespace index when there is no namespace
51 # Zero except in {{transclusion}} tags
52 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
60 /* private */ function Title() {
61 $this->mInterwiki
= $this->mUrlform
=
62 $this->mTextform
= $this->mDbkeyform
= '';
63 $this->mArticleID
= -1;
64 $this->mNamespace
= NS_MAIN
;
65 $this->mRestrictionsLoaded
= false;
66 $this->mRestrictions
= array();
67 # Dont change the following, NS_MAIN is hardcoded in several place
69 $this->mDefaultNamespace
= NS_MAIN
;
70 $this->mWatched
= NULL;
71 $this->mLatestID
= false;
75 * Create a new Title from a prefixed DB key
76 * @param string $key The database key, which has underscores
77 * instead of spaces, possibly including namespace and
79 * @return Title the new object, or NULL on an error
83 /* static */ function newFromDBkey( $key ) {
85 $t->mDbkeyform
= $key;
86 if( $t->secureAndSplit() )
93 * Create a new Title from text, such as what one would
94 * find in a link. Decodes any HTML entities in the text.
96 * @param string $text the link text; spaces, prefixes,
97 * and an initial ':' indicating the main namespace
99 * @param int $defaultNamespace the namespace to use if
100 * none is specified by a prefix
101 * @return Title the new object, or NULL on an error
105 function newFromText( $text, $defaultNamespace = NS_MAIN
) {
106 $fname = 'Title::newFromText';
107 wfProfileIn( $fname );
109 if( is_object( $text ) ) {
110 wfDebugDieBacktrace( 'Title::newFromText given an object' );
114 * Wiki pages often contain multiple links to the same page.
115 * Title normalization and parsing can become expensive on
116 * pages with many links, so we can save a little time by
119 * In theory these are value objects and won't get changed...
121 static $titleCache = array();
122 if( $defaultNamespace == NS_MAIN
&& isset( $titleCache[$text] ) ) {
123 wfProfileOut( $fname );
124 return $titleCache[$text];
128 * Convert things like é ā or 〗 into real text...
130 $filteredText = Sanitizer
::decodeCharReferences( $text );
133 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
134 $t->mDefaultNamespace
= $defaultNamespace;
136 if( $t->secureAndSplit() ) {
137 if( $defaultNamespace == NS_MAIN
) {
138 if( count( $titleCache ) >= MW_TITLECACHE_MAX
) {
139 # Avoid memory leaks on mass operations...
140 $titleCache = array();
142 $titleCache[$text] =& $t;
144 wfProfileOut( $fname );
147 wfProfileOut( $fname );
154 * Create a new Title from URL-encoded text. Ensures that
155 * the given title's length does not exceed the maximum.
156 * @param string $url the title, as might be taken from a URL
157 * @return Title the new object, or NULL on an error
161 function newFromURL( $url ) {
162 global $wgLang, $wgServer;
165 # For compatibility with old buggy URLs. "+" is not valid in titles,
166 # but some URLs used it as a space replacement and they still come
167 # from some external search tools.
168 $s = str_replace( '+', ' ', $url );
170 $t->mDbkeyform
= str_replace( ' ', '_', $s );
171 if( $t->secureAndSplit() ) {
179 * Create a new Title from an article ID
181 * @todo This is inefficiently implemented, the page row is requested
182 * but not used for anything else
184 * @param int $id the page_id corresponding to the Title to create
185 * @return Title the new object, or NULL on an error
189 function newFromID( $id ) {
190 $fname = 'Title::newFromID';
191 $dbr =& wfGetDB( DB_SLAVE
);
192 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
193 array( 'page_id' => $id ), $fname );
194 if ( $row !== false ) {
195 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
203 * Create a new Title from a namespace index and a DB key.
204 * It's assumed that $ns and $title are *valid*, for instance when
205 * they came directly from the database or a special page name.
206 * For convenience, spaces are converted to underscores so that
207 * eg user_text fields can be used directly.
209 * @param int $ns the namespace of the article
210 * @param string $title the unprefixed database key form
211 * @return Title the new object
215 function &makeTitle( $ns, $title ) {
219 $t->mNamespace
= intval( $ns );
220 $t->mDbkeyform
= str_replace( ' ', '_', $title );
221 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
222 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
223 $t->mTextform
= str_replace( '_', ' ', $title );
228 * Create a new Title frrom a namespace index and a DB key.
229 * The parameters will be checked for validity, which is a bit slower
230 * than makeTitle() but safer for user-provided data.
232 * @param int $ns the namespace of the article
233 * @param string $title the database key form
234 * @return Title the new object, or NULL on an error
238 function makeTitleSafe( $ns, $title ) {
240 $t->mDbkeyform
= Title
::makeName( $ns, $title );
241 if( $t->secureAndSplit() ) {
249 * Create a new Title for the Main Page
252 * @return Title the new object
255 function newMainPage() {
256 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
260 * Create a new Title for a redirect
261 * @param string $text the redirect title text
262 * @return Title the new object, or NULL if the text is not a
267 function newFromRedirect( $text ) {
270 if ( $wgMwRedir->matchStart( $text ) ) {
271 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
272 # categories are escaped using : for example one can enter:
273 # #REDIRECT [[:Category:Music]]. Need to remove it.
274 if ( substr($m[1],0,1) == ':') {
275 # We don't want to keep the ':'
276 $m[1] = substr( $m[1], 1 );
279 $rt = Title
::newFromText( $m[1] );
280 # Disallow redirects to Special:Userlogout
281 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
289 #----------------------------------------------------------------------------
291 #----------------------------------------------------------------------------
294 * Get the prefixed DB key associated with an ID
295 * @param int $id the page_id of the article
296 * @return Title an object representing the article, or NULL
297 * if no such article was found
301 function nameOf( $id ) {
302 $fname = 'Title::nameOf';
303 $dbr =& wfGetDB( DB_SLAVE
);
305 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
306 if ( $s === false ) { return NULL; }
308 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
313 * Get a regex character class describing the legal characters in a link
314 * @return string the list of characters, not delimited
318 function legalChars() {
319 global $wgLegalTitleChars;
320 return $wgLegalTitleChars;
324 * Get a string representation of a title suitable for
325 * including in a search index
327 * @param int $ns a namespace index
328 * @param string $title text-form main part
329 * @return string a stripped-down title string ready for the
332 /* static */ function indexTitle( $ns, $title ) {
333 global $wgDBminWordLen, $wgContLang;
334 require_once( 'SearchEngine.php' );
336 $lc = SearchEngine
::legalSearchChars() . '&#;';
337 $t = $wgContLang->stripForSearch( $title );
338 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
339 $t = strtolower( $t );
342 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
343 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
345 $t = preg_replace( "/\\s+/", ' ', $t );
347 if ( $ns == NS_IMAGE
) {
348 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
354 * Make a prefixed DB key from a DB key and a namespace index
355 * @param int $ns numerical representation of the namespace
356 * @param string $title the DB key form the title
357 * @return string the prefixed form of the title
359 /* static */ function makeName( $ns, $title ) {
362 $n = $wgContLang->getNsText( $ns );
363 return $n == '' ?
$title : "$n:$title";
367 * Returns the URL associated with an interwiki prefix
368 * @param string $key the interwiki prefix (e.g. "MeatBall")
369 * @return the associated URL, containing "$1", which should be
370 * replaced by an article title
374 function getInterwikiLink( $key, $transludeonly = false ) {
375 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
376 $fname = 'Title::getInterwikiLink';
378 wfProfileIn( $fname );
380 $key = strtolower( $key );
382 $k = $wgDBname.':interwiki:'.$key;
383 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
384 wfProfileOut( $fname );
385 return $wgTitleInterwikiCache[$k]->iw_url
;
388 $s = $wgMemc->get( $k );
389 # Ignore old keys with no iw_local
390 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
391 $wgTitleInterwikiCache[$k] = $s;
392 wfProfileOut( $fname );
396 $dbr =& wfGetDB( DB_SLAVE
);
397 $res = $dbr->select( 'interwiki',
398 array( 'iw_url', 'iw_local', 'iw_trans' ),
399 array( 'iw_prefix' => $key ), $fname );
401 wfProfileOut( $fname );
405 $s = $dbr->fetchObject( $res );
407 # Cache non-existence: create a blank object and save it to memcached
413 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
414 $wgTitleInterwikiCache[$k] = $s;
416 wfProfileOut( $fname );
421 * Determine whether the object refers to a page within
424 * @return bool TRUE if this is an in-project interwiki link
425 * or a wikilink, FALSE otherwise
429 global $wgTitleInterwikiCache, $wgDBname;
431 if ( $this->mInterwiki
!= '' ) {
432 # Make sure key is loaded into cache
433 $this->getInterwikiLink( $this->mInterwiki
);
434 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
435 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
442 * Determine whether the object refers to a page within
443 * this project and is transcludable.
445 * @return bool TRUE if this is transcludable
449 global $wgTitleInterwikiCache, $wgDBname;
451 if ($this->mInterwiki
== '' ||
!$this->isLocal())
453 # Make sure key is loaded into cache
454 $this->getInterwikiLink( $this->mInterwiki
);
455 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
456 return (bool)($wgTitleInterwikiCache[$k]->iw_trans
);
460 * Update the page_touched field for an array of title objects
461 * @todo Inefficient unless the IDs are already loaded into the
463 * @param array $titles an array of Title objects to be touched
464 * @param string $timestamp the timestamp to use instead of the
465 * default current time
469 function touchArray( $titles, $timestamp = '' ) {
470 global $wgUseFileCache;
472 if ( count( $titles ) == 0 ) {
475 $dbw =& wfGetDB( DB_MASTER
);
476 if ( $timestamp == '' ) {
477 $timestamp = $dbw->timestamp();
479 $page = $dbw->tableName( 'page' );
481 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
484 foreach ( $titles as $title ) {
485 if ( $wgUseFileCache ) {
486 $cm = new CacheManager($title);
487 @unlink($cm->fileCacheName());
494 $sql .= $title->getArticleID();
498 $dbw->query( $sql, 'Title::touchArray' );
501 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
502 // do them in small chunks:
503 $fname = 'Title::touchArray';
504 foreach( $titles as $title ) {
505 $dbw->update( 'page',
506 array( 'page_touched' => $timestamp ),
508 'page_namespace' => $title->getNamespace(),
509 'page_title' => $title->getDBkey() ),
514 #----------------------------------------------------------------------------
516 #----------------------------------------------------------------------------
518 /** Simple accessors */
520 * Get the text form (spaces not underscores) of the main part
524 function getText() { return $this->mTextform
; }
526 * Get the URL-encoded form of the main part
530 function getPartialURL() { return $this->mUrlform
; }
532 * Get the main part with underscores
536 function getDBkey() { return $this->mDbkeyform
; }
538 * Get the namespace index, i.e. one of the NS_xxxx constants
542 function getNamespace() { return $this->mNamespace
; }
544 * Get the namespace text
548 function getNsText() {
550 return $wgContLang->getNsText( $this->mNamespace
);
553 * Get the namespace text of the subject (rather than talk) page
557 function getSubjectNsText() {
559 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
563 * Get the interwiki prefix (or null string)
567 function getInterwiki() { return $this->mInterwiki
; }
569 * Get the Title fragment (i.e. the bit after the #)
573 function getFragment() { return $this->mFragment
; }
575 * Get the default namespace index, for when there is no namespace
579 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
582 * Get title for search index
583 * @return string a stripped-down title string ready for the
586 function getIndexTitle() {
587 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
591 * Get the prefixed database key form
592 * @return string the prefixed title, with underscores and
593 * any interwiki and namespace prefixes
596 function getPrefixedDBkey() {
597 $s = $this->prefix( $this->mDbkeyform
);
598 $s = str_replace( ' ', '_', $s );
603 * Get the prefixed title with spaces.
604 * This is the form usually used for display
605 * @return string the prefixed title, with spaces
608 function getPrefixedText() {
610 if ( empty( $this->mPrefixedText
) ) {
611 $s = $this->prefix( $this->mTextform
);
612 $s = str_replace( '_', ' ', $s );
613 $this->mPrefixedText
= $s;
615 return $this->mPrefixedText
;
619 * Get the prefixed title with spaces, plus any fragment
620 * (part beginning with '#')
621 * @return string the prefixed title, with spaces and
622 * the fragment, including '#'
625 function getFullText() {
627 $text = $this->getPrefixedText();
628 if( '' != $this->mFragment
) {
629 $text .= '#' . $this->mFragment
;
635 * Get a URL-encoded title (not an actual URL) including interwiki
636 * @return string the URL-encoded form
639 function getPrefixedURL() {
640 $s = $this->prefix( $this->mDbkeyform
);
641 $s = str_replace( ' ', '_', $s );
643 $s = wfUrlencode ( $s ) ;
645 # Cleaning up URL to make it look nice -- is this safe?
646 $s = str_replace( '%28', '(', $s );
647 $s = str_replace( '%29', ')', $s );
653 * Get a real URL referring to this title, with interwiki link and
656 * @param string $query an optional query string, not used
657 * for interwiki links
658 * @return string the URL
661 function getFullURL( $query = '' ) {
662 global $wgContLang, $wgServer, $wgScript, $wgMakeDumpLinks, $wgArticlePath;
664 if ( '' == $this->mInterwiki
) {
665 return $wgServer . $this->getLocalUrl( $query );
666 } elseif ( $wgMakeDumpLinks && $wgContLang->getLanguageName( $this->mInterwiki
) ) {
667 if ( $this->getDBkey() == '' ) {
668 $url = str_replace( '$1', "../{$this->mInterwiki}/index.html", $wgArticlePath );
670 $url = str_replace( '$1', "../{$this->mInterwiki}/" . $this->getHashedFilename() ,
675 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
678 $namespace = $wgContLang->getNsText( $this->mNamespace
);
679 if ( '' != $namespace ) {
680 # Can this actually happen? Interwikis shouldn't be parsed.
683 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
685 if( false === strpos( $url, '?' ) ) {
692 if ( '' != $this->mFragment
) {
693 $url .= '#' . $this->mFragment
;
699 * Get a relative directory for putting an HTML version of this article into
701 function getHashedDirectory() {
702 global $wgMakeDumpLinks, $wgInputEncoding;
703 if ( '' != $this->mInterwiki
) {
704 $pdbk = $this->mDbkeyform
;
706 $pdbk = $this->getPrefixedDBkey();
709 # Split into characters
710 if ( $wgInputEncoding == 'UTF-8' ) {
711 preg_match_all( '/./us', $pdbk, $m );
713 preg_match_all( '/./s', $pdbk, $m );
716 $length = count( $chars );
719 for ( $i = 0; $i < $wgMakeDumpLinks; $i++
) {
724 if ( $i >= $length ) {
726 } elseif ( ord( $c ) >= 128 ||
ctype_alnum( $c ) ) {
727 $dir .= strtolower( $c );
729 $dir .= sprintf( "%02X", ord( $c ) );
735 function getHashedFilename() {
736 if ( '' != $this->mInterwiki
) {
737 $dbkey = $this->getDBkey();
739 $dbkey = $this->getPrefixedDBkey();
742 $mainPage = Title
::newMainPage();
743 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
747 $dir = $this->getHashedDirectory();
749 # Replace illegal charcters for Windows paths with underscores
750 $friendlyName = strtr( $dbkey, '/\\*?"<>|~', '_________' );
752 # Work out lower case form. We assume we're on a system with case-insensitive
753 # filenames, so unless the case is of a special form, we have to disambiguate
754 $lowerCase = ucfirst( strtolower( $dbkey ) );
756 # Make it mostly unique
757 if ( $lowerCase != $friendlyName ) {
758 $friendlyName .= '_' . substr(md5( $dbkey ), 0, 4);
760 # Handle colon specially by replacing it with tilde
761 # Thus we reduce the number of paths with hashes appended
762 $friendlyName = str_replace( ':', '~', $friendlyName );
763 return "$dir/$friendlyName.html";
767 * Get a URL with no fragment or server name. If this page is generated
768 * with action=render, $wgServer is prepended.
769 * @param string $query an optional query string; if not specified,
770 * $wgArticlePath will be used.
771 * @return string the URL
774 function getLocalURL( $query = '' ) {
775 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks, $wgServer, $action;
777 if ( $this->isExternal() ) {
778 return $this->getFullURL();
781 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
782 if ( $wgMakeDumpLinks ) {
783 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
784 } elseif ( $query == '' ) {
785 $url = str_replace( '$1', $dbkey, $wgArticlePath );
787 global $wgActionPaths;
788 if( !empty( $wgActionPaths ) &&
789 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
790 $action = urldecode( $matches[2] );
791 if( isset( $wgActionPaths[$action] ) ) {
792 $query = $matches[1];
793 if( isset( $matches[4] ) ) $query .= $matches[4];
794 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
795 if( $query != '' ) $url .= '?' . $query;
799 if ( $query == '-' ) {
802 $url = "{$wgScript}?title={$dbkey}&{$query}";
805 if ($action == 'render')
806 return $wgServer . $url;
812 * Get an HTML-escaped version of the URL form, suitable for
813 * using in a link, without a server name or fragment
814 * @param string $query an optional query string
815 * @return string the URL
818 function escapeLocalURL( $query = '' ) {
819 return htmlspecialchars( $this->getLocalURL( $query ) );
823 * Get an HTML-escaped version of the URL form, suitable for
824 * using in a link, including the server name and fragment
826 * @return string the URL
827 * @param string $query an optional query string
830 function escapeFullURL( $query = '' ) {
831 return htmlspecialchars( $this->getFullURL( $query ) );
835 * Get the URL form for an internal link.
836 * - Used in various Squid-related code, in case we have a different
837 * internal hostname for the server from the exposed one.
839 * @param string $query an optional query string
840 * @return string the URL
843 function getInternalURL( $query = '' ) {
844 global $wgInternalServer;
845 return $wgInternalServer . $this->getLocalURL( $query );
849 * Get the edit URL for this Title
850 * @return string the URL, or a null string if this is an
854 function getEditURL() {
855 global $wgServer, $wgScript;
857 if ( '' != $this->mInterwiki
) { return ''; }
858 $s = $this->getLocalURL( 'action=edit' );
864 * Get the HTML-escaped displayable text form.
865 * Used for the title field in <a> tags.
866 * @return string the text, including any prefixes
869 function getEscapedText() {
870 return htmlspecialchars( $this->getPrefixedText() );
874 * Is this Title interwiki?
878 function isExternal() { return ( '' != $this->mInterwiki
); }
881 * Does the title correspond to a protected article?
882 * @param string $what the action the page is protected from,
883 * by default checks move and edit
887 function isProtected($action = '') {
888 if ( -1 == $this->mNamespace
) { return true; }
889 if($action == 'edit' ||
$action == '') {
890 $a = $this->getRestrictions("edit");
891 if ( in_array( 'sysop', $a ) ) { return true; }
893 if($action == 'move' ||
$action == '') {
894 $a = $this->getRestrictions("move");
895 if ( in_array( 'sysop', $a ) ) { return true; }
901 * Is $wgUser is watching this page?
905 function userIsWatching() {
908 if ( is_null( $this->mWatched
) ) {
909 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
910 $this->mWatched
= false;
912 $this->mWatched
= $wgUser->isWatched( $this );
915 return $this->mWatched
;
919 * Can $wgUser perform $action this page?
920 * @param string $action action that permission needs to be checked for
924 function userCan($action) {
925 $fname = 'Title::userCanEdit';
926 wfProfileIn( $fname );
929 if( NS_SPECIAL
== $this->mNamespace
) {
930 wfProfileOut( $fname );
933 if( NS_MEDIAWIKI
== $this->mNamespace
&&
934 !$wgUser->isAllowed('editinterface') ) {
935 wfProfileOut( $fname );
938 if( $this->mDbkeyform
== '_' ) {
939 # FIXME: Is this necessary? Shouldn't be allowed anyway...
940 wfProfileOut( $fname );
944 # protect global styles and js
945 if ( NS_MEDIAWIKI
== $this->mNamespace
946 && preg_match("/\\.(css|js)$/", $this->mTextform
)
947 && !$wgUser->isAllowed('editinterface') ) {
948 wfProfileOut( $fname );
952 # protect css/js subpages of user pages
953 # XXX: this might be better using restrictions
954 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
955 if( NS_USER
== $this->mNamespace
956 && preg_match("/\\.(css|js)$/", $this->mTextform
)
957 && !$wgUser->isAllowed('editinterface')
958 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
959 wfProfileOut( $fname );
963 foreach( $this->getRestrictions($action) as $right ) {
964 // Backwards compatibility, rewrite sysop -> protect
965 if ( $right == 'sysop' ) {
968 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
969 wfProfileOut( $fname );
974 if( $action == 'move' &&
975 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
976 wfProfileOut( $fname );
980 wfProfileOut( $fname );
985 * Can $wgUser edit this page?
989 function userCanEdit() {
990 return $this->userCan('edit');
994 * Can $wgUser move this page?
998 function userCanMove() {
999 return $this->userCan('move');
1003 * Would anybody with sufficient privileges be able to move this page?
1004 * Some pages just aren't movable.
1009 function isMovable() {
1010 return Namespace::isMovable( $this->getNamespace() )
1011 && $this->getInterwiki() == '';
1015 * Can $wgUser read this page?
1019 function userCanRead() {
1022 if( $wgUser->isAllowed('read') ) {
1025 global $wgWhitelistRead;
1027 /** If anon users can create an account,
1028 they need to reach the login page first! */
1029 if( $wgUser->isAllowed( 'createaccount' )
1030 && $this->getNamespace() == NS_SPECIAL
1031 && $this->getText() == 'Userlogin' ) {
1035 /** some pages are explicitly allowed */
1036 $name = $this->getPrefixedText();
1037 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1041 # Compatibility with old settings
1042 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1043 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1052 * Is this a talk page of some sort?
1056 function isTalkPage() {
1057 return Namespace::isTalk( $this->getNamespace() );
1061 * Is this a .css or .js subpage of a user page?
1065 function isCssJsSubpage() {
1066 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1069 * Is this a .css subpage of a user page?
1073 function isCssSubpage() {
1074 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1077 * Is this a .js subpage of a user page?
1081 function isJsSubpage() {
1082 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1085 * Protect css/js subpages of user pages: can $wgUser edit
1089 * @todo XXX: this might be better using restrictions
1092 function userCanEditCssJsSubpage() {
1094 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1098 * Loads a string into mRestrictions array
1099 * @param string $res restrictions in string format
1102 function loadRestrictions( $res ) {
1103 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1104 $temp = explode( '=', trim( $restrict ) );
1105 if(count($temp) == 1) {
1106 // old format should be treated as edit/move restriction
1107 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1108 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1110 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1113 $this->mRestrictionsLoaded
= true;
1117 * Accessor/initialisation for mRestrictions
1118 * @param string $action action that permission needs to be checked for
1119 * @return array the array of groups allowed to edit this article
1122 function getRestrictions($action) {
1123 $id = $this->getArticleID();
1124 if ( 0 == $id ) { return array(); }
1126 if ( ! $this->mRestrictionsLoaded
) {
1127 $dbr =& wfGetDB( DB_SLAVE
);
1128 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1129 $this->loadRestrictions( $res );
1131 if( isset( $this->mRestrictions
[$action] ) ) {
1132 return $this->mRestrictions
[$action];
1138 * Is there a version of this page in the deletion archive?
1139 * @return int the number of archived revisions
1142 function isDeleted() {
1143 $fname = 'Title::isDeleted';
1144 if ( $this->getNamespace() < 0 ) {
1147 $dbr =& wfGetDB( DB_SLAVE
);
1148 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1149 'ar_title' => $this->getDBkey() ), $fname );
1155 * Get the article ID for this Title from the link cache,
1156 * adding it if necessary
1157 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1159 * @return int the ID
1162 function getArticleID( $flags = 0 ) {
1163 global $wgLinkCache;
1164 if ( $flags & GAID_FOR_UPDATE
) {
1165 $oldUpdate = $wgLinkCache->forUpdate( true );
1166 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1167 $wgLinkCache->forUpdate( $oldUpdate );
1169 if ( -1 == $this->mArticleID
) {
1170 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1173 return $this->mArticleID
;
1176 function getLatestRevID() {
1177 if ($this->mLatestID
!== false)
1178 return $this->mLatestID
;
1180 $db =& wfGetDB(DB_SLAVE
);
1181 return $this->mLatestID
= $db->selectField( 'revision',
1183 array('rev_page' => $this->getArticleID()),
1184 'Title::getLatestRevID' );
1188 * This clears some fields in this object, and clears any associated
1189 * keys in the "bad links" section of $wgLinkCache.
1191 * - This is called from Article::insertNewArticle() to allow
1192 * loading of the new page_id. It's also called from
1193 * Article::doDeleteArticle()
1195 * @param int $newid the new Article ID
1198 function resetArticleID( $newid ) {
1199 global $wgLinkCache;
1200 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1202 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1203 else { $this->mArticleID
= $newid; }
1204 $this->mRestrictionsLoaded
= false;
1205 $this->mRestrictions
= array();
1209 * Updates page_touched for this page; called from LinksUpdate.php
1210 * @return bool true if the update succeded
1213 function invalidateCache() {
1214 global $wgUseFileCache;
1216 if ( wfReadOnly() ) {
1220 $now = wfTimestampNow();
1221 $dbw =& wfGetDB( DB_MASTER
);
1222 $success = $dbw->update( 'page',
1224 'page_touched' => $dbw->timestamp()
1225 ), array( /* WHERE */
1226 'page_namespace' => $this->getNamespace() ,
1227 'page_title' => $this->getDBkey()
1228 ), 'Title::invalidateCache'
1231 if ($wgUseFileCache) {
1232 $cache = new CacheManager($this);
1233 @unlink
($cache->fileCacheName());
1240 * Prefix some arbitrary text with the namespace or interwiki prefix
1243 * @param string $name the text
1244 * @return string the prefixed text
1247 /* private */ function prefix( $name ) {
1251 if ( '' != $this->mInterwiki
) {
1252 $p = $this->mInterwiki
. ':';
1254 if ( 0 != $this->mNamespace
) {
1255 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1261 * Secure and split - main initialisation function for this object
1263 * Assumes that mDbkeyform has been set, and is urldecoded
1264 * and uses underscores, but not otherwise munged. This function
1265 * removes illegal characters, splits off the interwiki and
1266 * namespace prefixes, sets the other forms, and canonicalizes
1268 * @return bool true on success
1271 /* private */ function secureAndSplit() {
1272 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1273 $fname = 'Title::secureAndSplit';
1274 wfProfileIn( $fname );
1277 static $rxTc = false;
1279 # % is needed as well
1280 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1283 $this->mInterwiki
= $this->mFragment
= '';
1284 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1286 # Clean up whitespace
1288 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1289 $t = trim( $t, '_' );
1292 wfProfileOut( $fname );
1296 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1297 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1298 wfProfileOut( $fname );
1302 $this->mDbkeyform
= $t;
1304 # Initial colon indicates main namespace rather than specified default
1305 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1306 if ( ':' == $t{0} ) {
1307 $this->mNamespace
= NS_MAIN
;
1308 $t = substr( $t, 1 ); # remove the colon but continue processing
1311 # Namespace or interwiki prefix
1314 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1316 $lowerNs = strtolower( $p );
1317 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1318 # Canonical namespace
1320 $this->mNamespace
= $ns;
1321 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1322 # Ordinary namespace
1324 $this->mNamespace
= $ns;
1325 } elseif( $this->getInterwikiLink( $p ) ) {
1327 # Can't make a local interwiki link to an interwiki link.
1328 # That's just crazy!
1329 wfProfileOut( $fname );
1335 $this->mInterwiki
= strtolower( $p );
1337 # Redundant interwiki prefix to the local wiki
1338 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1340 # Can't have an empty self-link
1341 wfProfileOut( $fname );
1344 $this->mInterwiki
= '';
1346 # Do another namespace split...
1350 # If there's no recognized interwiki or namespace,
1351 # then let the colon expression be part of the title.
1357 # We already know that some pages won't be in the database!
1359 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1360 $this->mArticleID
= 0;
1362 $f = strstr( $r, '#' );
1363 if ( false !== $f ) {
1364 $this->mFragment
= substr( $f, 1 );
1365 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1366 # remove whitespace again: prevents "Foo_bar_#"
1367 # becoming "Foo_bar_"
1368 $r = preg_replace( '/_*$/', '', $r );
1371 # Reject illegal characters.
1373 if( preg_match( $rxTc, $r ) ) {
1374 wfProfileOut( $fname );
1379 * Pages with "/./" or "/../" appearing in the URLs will
1380 * often be unreachable due to the way web browsers deal
1381 * with 'relative' URLs. Forbid them explicitly.
1383 if ( strpos( $r, '.' ) !== false &&
1384 ( $r === '.' ||
$r === '..' ||
1385 strpos( $r, './' ) === 0 ||
1386 strpos( $r, '../' ) === 0 ||
1387 strpos( $r, '/./' ) !== false ||
1388 strpos( $r, '/../' ) !== false ) )
1390 wfProfileOut( $fname );
1394 # We shouldn't need to query the DB for the size.
1395 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1396 if ( strlen( $r ) > 255 ) {
1397 wfProfileOut( $fname );
1402 * Normally, all wiki links are forced to have
1403 * an initial capital letter so [[foo]] and [[Foo]]
1404 * point to the same place.
1406 * Don't force it for interwikis, since the other
1407 * site might be case-sensitive.
1409 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1410 $t = $wgContLang->ucfirst( $r );
1416 * Can't make a link to a namespace alone...
1417 * "empty" local links can only be self-links
1418 * with a fragment identifier.
1421 $this->mInterwiki
== '' &&
1422 $this->mNamespace
!= NS_MAIN
) {
1423 wfProfileOut( $fname );
1428 $this->mDbkeyform
= $t;
1429 $this->mUrlform
= wfUrlencode( $t );
1431 $this->mTextform
= str_replace( '_', ' ', $t );
1433 wfProfileOut( $fname );
1438 * Get a Title object associated with the talk page of this article
1439 * @return Title the object for the talk page
1442 function getTalkPage() {
1443 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1447 * Get a title object associated with the subject page of this
1450 * @return Title the object for the subject page
1453 function getSubjectPage() {
1454 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1458 * Get an array of Title objects linking to this Title
1459 * Also stores the IDs in the link cache.
1461 * @param string $options may be FOR UPDATE
1462 * @return array the Title objects linking here
1465 function getLinksTo( $options = '' ) {
1466 global $wgLinkCache;
1467 $id = $this->getArticleID();
1470 $db =& wfGetDB( DB_MASTER
);
1472 $db =& wfGetDB( DB_SLAVE
);
1475 $res = $db->select( array( 'page', 'pagelinks' ),
1476 array( 'page_namespace', 'page_title', 'page_id' ),
1479 'pl_namespace' => $this->getNamespace(),
1480 'pl_title' => $this->getDbKey() ),
1481 'Title::getLinksTo',
1485 if ( $db->numRows( $res ) ) {
1486 while ( $row = $db->fetchObject( $res ) ) {
1487 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1488 $wgLinkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1489 $retVal[] = $titleObj;
1493 $db->freeResult( $res );
1498 * Get an array of Title objects referring to non-existent articles linked from this page
1500 * @param string $options may be FOR UPDATE
1501 * @return array the Title objects
1504 function getBrokenLinksFrom( $options = '' ) {
1505 global $wgLinkCache;
1508 $db =& wfGetDB( DB_MASTER
);
1510 $db =& wfGetDB( DB_SLAVE
);
1513 $res = $db->safeQuery(
1514 "SELECT pl_namespace, pl_title
1517 ON pl_namespace=page_namespace
1518 AND pl_title=page_title
1520 AND page_namespace IS NULL
1522 $db->tableName( 'pagelinks' ),
1523 $db->tableName( 'page' ),
1524 $this->getArticleId(),
1528 if ( $db->numRows( $res ) ) {
1529 while ( $row = $db->fetchObject( $res ) ) {
1530 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1533 $db->freeResult( $res );
1539 * Get a list of URLs to purge from the Squid cache when this
1542 * @return array the URLs
1545 function getSquidURLs() {
1547 $this->getInternalURL(),
1548 $this->getInternalURL( 'action=history' )
1553 * Move this page without authentication
1554 * @param Title &$nt the new page Title
1557 function moveNoAuth( &$nt ) {
1558 return $this->moveTo( $nt, false );
1562 * Check whether a given move operation would be valid.
1563 * Returns true if ok, or a message key string for an error message
1564 * if invalid. (Scarrrrry ugly interface this.)
1565 * @param Title &$nt the new title
1566 * @param bool $auth indicates whether $wgUser's permissions
1568 * @return mixed true on success, message name on failure
1571 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1573 if( !$this or !$nt ) {
1574 return 'badtitletext';
1576 if( $this->equals( $nt ) ) {
1579 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1580 return 'immobile_namespace';
1583 $fname = 'Title::move';
1584 $oldid = $this->getArticleID();
1585 $newid = $nt->getArticleID();
1587 if ( strlen( $nt->getDBkey() ) < 1 ) {
1588 return 'articleexists';
1590 if ( ( '' == $this->getDBkey() ) ||
1592 ( '' == $nt->getDBkey() ) ) {
1593 return 'badarticleerror';
1597 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1598 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1599 return 'protectedpage';
1602 # The move is allowed only if (1) the target doesn't exist, or
1603 # (2) the target is a redirect to the source, and has no history
1604 # (so we can undo bad moves right after they're done).
1606 if ( 0 != $newid ) { # Target exists; check for validity
1607 if ( ! $this->isValidMoveTarget( $nt ) ) {
1608 return 'articleexists';
1615 * Move a title to a new location
1616 * @param Title &$nt the new title
1617 * @param bool $auth indicates whether $wgUser's permissions
1619 * @return mixed true on success, message name on failure
1622 function moveTo( &$nt, $auth = true, $reason = '' ) {
1623 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1624 if( is_string( $err ) ) {
1628 $pageid = $this->getArticleID();
1629 if( $nt->exists() ) {
1630 $this->moveOverExistingRedirect( $nt, $reason );
1631 $pageCountChange = 0;
1632 } else { # Target didn't exist, do normal move.
1633 $this->moveToNewTitle( $nt, $newid, $reason );
1634 $pageCountChange = 1;
1636 $redirid = $this->getArticleID();
1638 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1639 $dbw =& wfGetDB( DB_MASTER
);
1640 $categorylinks = $dbw->tableName( 'categorylinks' );
1641 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1642 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1643 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1644 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1648 $oldnamespace = $this->getNamespace() & ~
1;
1649 $newnamespace = $nt->getNamespace() & ~
1;
1650 $oldtitle = $this->getDBkey();
1651 $newtitle = $nt->getDBkey();
1653 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1654 WatchedItem
::duplicateEntries( $this, $nt );
1657 # Update search engine
1658 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1660 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1664 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1665 # Moved out of main namespace
1666 # not viewed, edited, removing
1667 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1668 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1669 # Moved into main namespace
1670 # not viewed, edited, adding
1671 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1672 } elseif ( $pageCountChange ) {
1674 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1682 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1687 * Move page to a title which is at present a redirect to the
1690 * @param Title &$nt the page to move to, which should currently
1694 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1695 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1696 $fname = 'Title::moveOverExistingRedirect';
1697 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1700 $comment .= ": $reason";
1703 $now = wfTimestampNow();
1705 $newid = $nt->getArticleID();
1706 $oldid = $this->getArticleID();
1707 $dbw =& wfGetDB( DB_MASTER
);
1708 $links = $dbw->tableName( 'links' );
1710 # Delete the old redirect. We don't save it to history since
1711 # by definition if we've got here it's rather uninteresting.
1712 # We have to remove it so that the next step doesn't trigger
1713 # a conflict on the unique namespace+title index...
1714 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1716 # Save a null revision in the page's history notifying of the move
1717 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1718 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1720 $nullRevId = $nullRevision->insertOn( $dbw );
1722 # Change the name of the target page:
1723 $dbw->update( 'page',
1725 'page_touched' => $dbw->timestamp($now),
1726 'page_namespace' => $nt->getNamespace(),
1727 'page_title' => $nt->getDBkey(),
1728 'page_latest' => $nullRevId,
1730 /* WHERE */ array( 'page_id' => $oldid ),
1733 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1735 # Recreate the redirect, this time in the other direction.
1736 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1737 $redirectArticle = new Article( $this );
1738 $newid = $redirectArticle->insertOn( $dbw );
1739 $redirectRevision = new Revision( array(
1741 'comment' => $comment,
1742 'text' => $redirectText ) );
1743 $revid = $redirectRevision->insertOn( $dbw );
1744 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1745 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1748 $log = new LogPage( 'move' );
1749 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1751 # Now, we record the link from the redirect to the new title.
1752 # It should have no other outgoing links...
1753 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1754 $dbw->insert( 'pagelinks',
1756 'pl_from' => $newid,
1757 'pl_namespace' => $nt->getNamespace(),
1758 'pl_title' => $nt->getDbKey() ),
1762 if ( $wgUseSquid ) {
1763 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1764 $u = new SquidUpdate( $urls );
1770 * Move page to non-existing title.
1771 * @param Title &$nt the new Title
1772 * @param int &$newid set to be the new article ID
1775 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1776 global $wgUser, $wgLinkCache, $wgUseSquid;
1778 $fname = 'MovePageForm::moveToNewTitle';
1779 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1781 $comment .= ": $reason";
1784 $newid = $nt->getArticleID();
1785 $oldid = $this->getArticleID();
1786 $dbw =& wfGetDB( DB_MASTER
);
1787 $now = $dbw->timestamp();
1791 # Save a null revision in the page's history notifying of the move
1792 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1793 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1795 $nullRevId = $nullRevision->insertOn( $dbw );
1798 $dbw->update( 'page',
1800 'page_touched' => $now,
1801 'page_namespace' => $nt->getNamespace(),
1802 'page_title' => $nt->getDBkey(),
1803 'page_latest' => $nullRevId,
1805 /* WHERE */ array( 'page_id' => $oldid ),
1809 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1812 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1813 $redirectArticle = new Article( $this );
1814 $newid = $redirectArticle->insertOn( $dbw );
1815 $redirectRevision = new Revision( array(
1817 'comment' => $comment,
1818 'text' => $redirectText ) );
1819 $revid = $redirectRevision->insertOn( $dbw );
1820 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1821 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1824 $log = new LogPage( 'move' );
1825 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1827 # Purge caches as per article creation
1828 Article
::onArticleCreate( $nt );
1830 # Record the just-created redirect's linking to the page
1831 $dbw->insert( 'pagelinks',
1833 'pl_from' => $newid,
1834 'pl_namespace' => $nt->getNamespace(),
1835 'pl_title' => $nt->getDBkey() ),
1838 # Non-existent target may have had broken links to it; these must
1839 # now be touched to update link coloring.
1842 # Purge old title from squid
1843 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1844 $titles = $nt->getLinksTo();
1845 if ( $wgUseSquid ) {
1846 $urls = $this->getSquidURLs();
1847 foreach ( $titles as $linkTitle ) {
1848 $urls[] = $linkTitle->getInternalURL();
1850 $u = new SquidUpdate( $urls );
1856 * Checks if $this can be moved to a given Title
1857 * - Selects for update, so don't call it unless you mean business
1859 * @param Title &$nt the new title to check
1862 function isValidMoveTarget( $nt ) {
1864 $fname = 'Title::isValidMoveTarget';
1865 $dbw =& wfGetDB( DB_MASTER
);
1868 $id = $nt->getArticleID();
1869 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1870 array( 'page_is_redirect','old_text','old_flags' ),
1871 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1872 $fname, 'FOR UPDATE' );
1874 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1878 $text = Revision
::getRevisionText( $obj );
1880 # Does the redirect point to the source?
1881 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1882 $redirTitle = Title
::newFromText( $m[1] );
1883 if( !is_object( $redirTitle ) ||
1884 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1892 # Does the article have a history?
1893 $row = $dbw->selectRow( array( 'page', 'revision'),
1895 array( 'page_namespace' => $nt->getNamespace(),
1896 'page_title' => $nt->getDBkey(),
1897 'page_id=rev_page AND page_latest != rev_id'
1898 ), $fname, 'FOR UPDATE'
1901 # Return true if there was no history
1902 return $row === false;
1906 * Create a redirect; fails if the title already exists; does
1909 * @param Title $dest the destination of the redirect
1910 * @param string $comment the comment string describing the move
1911 * @return bool true on success
1914 function createRedirect( $dest, $comment ) {
1916 if ( $this->getArticleID() ) {
1920 $fname = 'Title::createRedirect';
1921 $dbw =& wfGetDB( DB_MASTER
);
1923 $article = new Article( $this );
1924 $newid = $article->insertOn( $dbw );
1925 $revision = new Revision( array(
1927 'comment' => $comment,
1928 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1930 $revisionId = $revision->insertOn( $dbw );
1931 $article->updateRevisionOn( $dbw, $revision, 0 );
1934 $dbw->insert( 'pagelinks',
1936 'pl_from' => $newid,
1937 'pl_namespace' => $dest->getNamespace(),
1938 'pl_title' => $dest->getDbKey()
1942 Article
::onArticleCreate( $this );
1947 * Get categories to which this Title belongs and return an array of
1948 * categories' names.
1950 * @return array an array of parents in the form:
1951 * $parent => $currentarticle
1954 function getParentCategories() {
1955 global $wgContLang,$wgUser;
1957 $titlekey = $this->getArticleId();
1958 $sk =& $wgUser->getSkin();
1960 $dbr =& wfGetDB( DB_SLAVE
);
1961 $categorylinks = $dbr->tableName( 'categorylinks' );
1964 $sql = "SELECT * FROM $categorylinks"
1965 ." WHERE cl_from='$titlekey'"
1966 ." AND cl_from <> '0'"
1967 ." ORDER BY cl_sortkey";
1969 $res = $dbr->query ( $sql ) ;
1971 if($dbr->numRows($res) > 0) {
1972 while ( $x = $dbr->fetchObject ( $res ) )
1973 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1974 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1975 $dbr->freeResult ( $res ) ;
1983 * Get a tree of parent categories
1984 * @param array $children an array with the children in the keys, to check for circular refs
1988 function getParentCategoryTree( $children = array() ) {
1989 $parents = $this->getParentCategories();
1991 if($parents != '') {
1992 foreach($parents as $parent => $current)
1994 if ( array_key_exists( $parent, $children ) ) {
1995 # Circular reference
1996 $stack[$parent] = array();
1998 $nt = Title
::newFromText($parent);
1999 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2010 * Get an associative array for selecting this title from
2016 function curCond() {
2017 wfDebugDieBacktrace( 'curCond called' );
2018 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
2022 * Get an associative array for selecting this title from the
2028 function oldCond() {
2029 wfDebugDieBacktrace( 'oldCond called' );
2030 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);
2034 * Get the revision ID of the previous revision
2036 * @param integer $revision Revision ID. Get the revision that was before this one.
2037 * @return interger $oldrevision|false
2039 function getPreviousRevisionID( $revision ) {
2040 $dbr =& wfGetDB( DB_SLAVE
);
2041 return $dbr->selectField( 'revision', 'rev_id',
2042 'rev_page=' . intval( $this->getArticleId() ) .
2043 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2047 * Get the revision ID of the next revision
2049 * @param integer $revision Revision ID. Get the revision that was after this one.
2050 * @return interger $oldrevision|false
2052 function getNextRevisionID( $revision ) {
2053 $dbr =& wfGetDB( DB_SLAVE
);
2054 return $dbr->selectField( 'revision', 'rev_id',
2055 'rev_page=' . intval( $this->getArticleId() ) .
2056 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2060 * Compare with another title.
2062 * @param Title $title
2065 function equals( &$title ) {
2066 return $this->getInterwiki() == $title->getInterwiki()
2067 && $this->getNamespace() == $title->getNamespace()
2068 && $this->getDbkey() == $title->getDbkey();
2072 * Check if page exists
2076 return $this->getArticleId() != 0;
2080 * Should a link should be displayed as a known link, just based on its title?
2082 * Currently, a self-link with a fragment, special pages and image pages are in
2083 * this category. Special pages never exist in the database. Some images do not
2084 * have description pages in the database, but the description page contains
2085 * useful history information that the user may want to link to.
2087 function isAlwaysKnown() {
2088 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2089 || NS_SPECIAL
== $this->mNamespace || NS_IMAGE
== $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() ),
2108 if ( 0 == $dbw->numRows( $res ) ) {
2113 $toucharr = array();
2114 while( $row = $dbw->fetchObject( $res ) ) {
2115 $toucharr[] = $row->pl_from
;
2117 if (!count($toucharr))
2119 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2120 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2123 function trackbackURL() {
2124 global $wgTitle, $wgScriptPath, $wgServer;
2126 return "$wgServer$wgScriptPath/trackback.php?article="
2127 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2130 function trackbackRDF() {
2131 $url = htmlspecialchars($this->getFullURL());
2132 $title = htmlspecialchars($this->getText());
2133 $tburl = $this->trackbackURL();
2136 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2137 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2138 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2141 dc:identifier=\"$url\"
2143 trackback:ping=\"$tburl\" />