8 require_once( 'normal/UtfNormal.php' );
10 $wgTitleInterwikiCache = array();
11 define ( 'GAID_FOR_UPDATE', 1 );
13 # Title::newFromTitle maintains a cache to avoid
14 # expensive re-normalization of commonly used titles.
15 # On a batch operation this can become a memory leak
16 # if not bounded. After hitting this many titles,
18 define( 'MW_TITLECACHE_MAX', 1000 );
22 * - Represents a title, which may contain an interwiki designation or namespace
23 * - Can fetch various kinds of data from the database, albeit inefficiently.
29 * All member variables should be considered private
30 * Please use the accessor functions
37 var $mTextform; # Text form (spaces not underscores) of the main part
38 var $mUrlform; # URL-encoded form of the main part
39 var $mDbkeyform; # Main part with underscores
40 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
41 var $mInterwiki; # Interwiki prefix (or null string)
42 var $mFragment; # Title fragment (i.e. the bit after the #)
43 var $mArticleID; # Article ID, fetched from the link cache on demand
44 var $mLatestID; # ID of most recent revision
45 var $mRestrictions; # Array of groups allowed to edit this article
46 # Only null or "sysop" are supported
47 var $mRestrictionsLoaded; # Boolean for initialisation on demand
48 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
49 var $mDefaultNamespace; # Namespace index when there is no namespace
50 # Zero except in {{transclusion}} tags
51 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
59 /* private */ function Title() {
60 $this->mInterwiki
= $this->mUrlform
=
61 $this->mTextform
= $this->mDbkeyform
= '';
62 $this->mArticleID
= -1;
63 $this->mNamespace
= NS_MAIN
;
64 $this->mRestrictionsLoaded
= false;
65 $this->mRestrictions
= array();
66 # Dont change the following, NS_MAIN is hardcoded in several place
68 $this->mDefaultNamespace
= NS_MAIN
;
69 $this->mWatched
= NULL;
70 $this->mLatestID
= false;
74 * Create a new Title from a prefixed DB key
75 * @param string $key The database key, which has underscores
76 * instead of spaces, possibly including namespace and
78 * @return Title the new object, or NULL on an error
82 /* static */ function newFromDBkey( $key ) {
84 $t->mDbkeyform
= $key;
85 if( $t->secureAndSplit() )
92 * Create a new Title from text, such as what one would
93 * find in a link. Decodes any HTML entities in the text.
95 * @param string $text the link text; spaces, prefixes,
96 * and an initial ':' indicating the main namespace
98 * @param int $defaultNamespace the namespace to use if
99 * none is specified by a prefix
100 * @return Title the new object, or NULL on an error
104 function &newFromText( $text, $defaultNamespace = NS_MAIN
) {
105 $fname = 'Title::newFromText';
106 wfProfileIn( $fname );
108 if( is_object( $text ) ) {
109 wfDebugDieBacktrace( 'Title::newFromText given an object' );
113 * Wiki pages often contain multiple links to the same page.
114 * Title normalization and parsing can become expensive on
115 * pages with many links, so we can save a little time by
118 * In theory these are value objects and won't get changed...
120 static $titleCache = array();
121 if( $defaultNamespace == NS_MAIN
&& isset( $titleCache[$text] ) ) {
122 wfProfileOut( $fname );
123 return $titleCache[$text];
127 * Convert things like é ā or 〗 into real text...
129 $filteredText = Sanitizer
::decodeCharReferences( $text );
132 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
133 $t->mDefaultNamespace
= $defaultNamespace;
135 if( $t->secureAndSplit() ) {
136 if( $defaultNamespace == NS_MAIN
) {
137 if( count( $titleCache ) >= MW_TITLECACHE_MAX
) {
138 # Avoid memory leaks on mass operations...
139 $titleCache = array();
141 $titleCache[$text] =& $t;
143 wfProfileOut( $fname );
146 wfProfileOut( $fname );
152 * Create a new Title from URL-encoded text. Ensures that
153 * the given title's length does not exceed the maximum.
154 * @param string $url the title, as might be taken from a URL
155 * @return Title the new object, or NULL on an error
159 function newFromURL( $url ) {
160 global $wgLang, $wgServer;
163 # For compatibility with old buggy URLs. "+" is not valid in titles,
164 # but some URLs used it as a space replacement and they still come
165 # from some external search tools.
166 $s = str_replace( '+', ' ', $url );
168 $t->mDbkeyform
= str_replace( ' ', '_', $s );
169 if( $t->secureAndSplit() ) {
177 * Create a new Title from an article ID
179 * @todo This is inefficiently implemented, the page row is requested
180 * but not used for anything else
182 * @param int $id the page_id corresponding to the Title to create
183 * @return Title the new object, or NULL on an error
187 function newFromID( $id ) {
188 $fname = 'Title::newFromID';
189 $dbr =& wfGetDB( DB_SLAVE
);
190 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
191 array( 'page_id' => $id ), $fname );
192 if ( $row !== false ) {
193 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
201 * Create a new Title from a namespace index and a DB key.
202 * It's assumed that $ns and $title are *valid*, for instance when
203 * they came directly from the database or a special page name.
204 * For convenience, spaces are converted to underscores so that
205 * eg user_text fields can be used directly.
207 * @param int $ns the namespace of the article
208 * @param string $title the unprefixed database key form
209 * @return Title the new object
213 function &makeTitle( $ns, $title ) {
217 $t->mNamespace
= IntVal( $ns );
218 $t->mDbkeyform
= str_replace( ' ', '_', $title );
219 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
220 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
221 $t->mTextform
= str_replace( '_', ' ', $title );
226 * Create a new Title frrom a namespace index and a DB key.
227 * The parameters will be checked for validity, which is a bit slower
228 * than makeTitle() but safer for user-provided data.
230 * @param int $ns the namespace of the article
231 * @param string $title the database key form
232 * @return Title the new object, or NULL on an error
236 function makeTitleSafe( $ns, $title ) {
238 $t->mDbkeyform
= Title
::makeName( $ns, $title );
239 if( $t->secureAndSplit() ) {
247 * Create a new Title for the Main Page
250 * @return Title the new object
253 function newMainPage() {
254 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
258 * Create a new Title for a redirect
259 * @param string $text the redirect title text
260 * @return Title the new object, or NULL if the text is not a
265 function newFromRedirect( $text ) {
268 if ( $wgMwRedir->matchStart( $text ) ) {
269 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
270 # categories are escaped using : for example one can enter:
271 # #REDIRECT [[:Category:Music]]. Need to remove it.
272 if ( substr($m[1],0,1) == ':') {
273 # We don't want to keep the ':'
274 $m[1] = substr( $m[1], 1 );
277 $rt = Title
::newFromText( $m[1] );
278 # Disallow redirects to Special:Userlogout
279 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
287 #----------------------------------------------------------------------------
289 #----------------------------------------------------------------------------
292 * Get the prefixed DB key associated with an ID
293 * @param int $id the page_id of the article
294 * @return Title an object representing the article, or NULL
295 * if no such article was found
299 function nameOf( $id ) {
300 $fname = 'Title::nameOf';
301 $dbr =& wfGetDB( DB_SLAVE
);
303 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
304 if ( $s === false ) { return NULL; }
306 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
311 * Get a regex character class describing the legal characters in a link
312 * @return string the list of characters, not delimited
316 /* static */ function legalChars() {
317 # Missing characters:
318 # * []|# Needed for link syntax
319 # * % and + are corrupted by Apache when they appear in the path
321 # % seems to work though
323 # The problem with % is that URLs are double-unescaped: once by Apache's
324 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
325 # Our code does not double-escape to compensate for this, indeed double escaping
326 # would break if the double-escaped title was passed in the query string
327 # rather than the path. This is a minor security issue because articles can be
328 # created such that they are hard to view or edit. -- TS
330 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
331 # this breaks interlanguage links
333 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF";
338 * Get a string representation of a title suitable for
339 * including in a search index
341 * @param int $ns a namespace index
342 * @param string $title text-form main part
343 * @return string a stripped-down title string ready for the
346 /* static */ function indexTitle( $ns, $title ) {
347 global $wgDBminWordLen, $wgContLang;
348 require_once( 'SearchEngine.php' );
350 $lc = SearchEngine
::legalSearchChars() . '&#;';
351 $t = $wgContLang->stripForSearch( $title );
352 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
353 $t = strtolower( $t );
356 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
357 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
359 $t = preg_replace( "/\\s+/", ' ', $t );
361 if ( $ns == NS_IMAGE
) {
362 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
368 * Make a prefixed DB key from a DB key and a namespace index
369 * @param int $ns numerical representation of the namespace
370 * @param string $title the DB key form the title
371 * @return string the prefixed form of the title
373 /* static */ function makeName( $ns, $title ) {
376 $n = $wgContLang->getNsText( $ns );
377 return $n == '' ?
$title : "$n:$title";
381 * Returns the URL associated with an interwiki prefix
382 * @param string $key the interwiki prefix (e.g. "MeatBall")
383 * @return the associated URL, containing "$1", which should be
384 * replaced by an article title
388 function getInterwikiLink( $key ) {
389 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
390 $fname = 'Title::getInterwikiLink';
392 wfProfileIn( $fname );
394 $k = $wgDBname.':interwiki:'.$key;
395 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
396 wfProfileOut( $fname );
397 return $wgTitleInterwikiCache[$k]->iw_url
;
400 $s = $wgMemc->get( $k );
401 # Ignore old keys with no iw_local
402 if( $s && isset( $s->iw_local
) ) {
403 $wgTitleInterwikiCache[$k] = $s;
404 wfProfileOut( $fname );
408 $dbr =& wfGetDB( DB_SLAVE
);
409 $res = $dbr->select( 'interwiki',
410 array( 'iw_url', 'iw_local' ),
411 array( 'iw_prefix' => $key ), $fname );
413 wfProfileOut( $fname );
417 $s = $dbr->fetchObject( $res );
419 # Cache non-existence: create a blank object and save it to memcached
424 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
425 $wgTitleInterwikiCache[$k] = $s;
427 wfProfileOut( $fname );
432 * Determine whether the object refers to a page within
435 * @return bool TRUE if this is an in-project interwiki link
436 * or a wikilink, FALSE otherwise
440 global $wgTitleInterwikiCache, $wgDBname;
442 if ( $this->mInterwiki
!= '' ) {
443 # Make sure key is loaded into cache
444 $this->getInterwikiLink( $this->mInterwiki
);
445 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
446 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
453 * Update the page_touched field for an array of title objects
454 * @todo Inefficient unless the IDs are already loaded into the
456 * @param array $titles an array of Title objects to be touched
457 * @param string $timestamp the timestamp to use instead of the
458 * default current time
462 function touchArray( $titles, $timestamp = '' ) {
463 if ( count( $titles ) == 0 ) {
466 $dbw =& wfGetDB( DB_MASTER
);
467 if ( $timestamp == '' ) {
468 $timestamp = $dbw->timestamp();
470 $page = $dbw->tableName( 'page' );
471 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
474 foreach ( $titles as $title ) {
479 $sql .= $title->getArticleID();
483 $dbw->query( $sql, 'Title::touchArray' );
487 #----------------------------------------------------------------------------
489 #----------------------------------------------------------------------------
491 /** Simple accessors */
493 * Get the text form (spaces not underscores) of the main part
497 function getText() { return $this->mTextform
; }
499 * Get the URL-encoded form of the main part
503 function getPartialURL() { return $this->mUrlform
; }
505 * Get the main part with underscores
509 function getDBkey() { return $this->mDbkeyform
; }
511 * Get the namespace index, i.e. one of the NS_xxxx constants
515 function getNamespace() { return $this->mNamespace
; }
517 * Get the interwiki prefix (or null string)
521 function getInterwiki() { return $this->mInterwiki
; }
523 * Get the Title fragment (i.e. the bit after the #)
527 function getFragment() { return $this->mFragment
; }
529 * Get the default namespace index, for when there is no namespace
533 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
536 * Get title for search index
537 * @return string a stripped-down title string ready for the
540 function getIndexTitle() {
541 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
545 * Get the prefixed database key form
546 * @return string the prefixed title, with underscores and
547 * any interwiki and namespace prefixes
550 function getPrefixedDBkey() {
551 $s = $this->prefix( $this->mDbkeyform
);
552 $s = str_replace( ' ', '_', $s );
557 * Get the prefixed title with spaces.
558 * This is the form usually used for display
559 * @return string the prefixed title, with spaces
562 function getPrefixedText() {
564 if ( empty( $this->mPrefixedText
) ) {
565 $s = $this->prefix( $this->mTextform
);
566 $s = str_replace( '_', ' ', $s );
567 $this->mPrefixedText
= $s;
569 return $this->mPrefixedText
;
573 * Get the prefixed title with spaces, plus any fragment
574 * (part beginning with '#')
575 * @return string the prefixed title, with spaces and
576 * the fragment, including '#'
579 function getFullText() {
581 $text = $this->getPrefixedText();
582 if( '' != $this->mFragment
) {
583 $text .= '#' . $this->mFragment
;
589 * Get a URL-encoded title (not an actual URL) including interwiki
590 * @return string the URL-encoded form
593 function getPrefixedURL() {
594 $s = $this->prefix( $this->mDbkeyform
);
595 $s = str_replace( ' ', '_', $s );
597 $s = wfUrlencode ( $s ) ;
599 # Cleaning up URL to make it look nice -- is this safe?
600 $s = str_replace( '%28', '(', $s );
601 $s = str_replace( '%29', ')', $s );
607 * Get a real URL referring to this title, with interwiki link and
610 * @param string $query an optional query string, not used
611 * for interwiki links
612 * @return string the URL
615 function getFullURL( $query = '' ) {
616 global $wgContLang, $wgServer, $wgScript, $wgMakeDumpLinks, $wgArticlePath;
618 if ( '' == $this->mInterwiki
) {
619 return $wgServer . $this->getLocalUrl( $query );
620 } elseif ( $wgMakeDumpLinks && $wgContLang->getLanguageName( $this->mInterwiki
) ) {
621 $baseUrl = str_replace( '$1', "../../{$this->mInterwiki}/$1", $wgArticlePath );
622 $baseUrl = str_replace( '$1', $this->getHashedDirectory() . '/$1', $baseUrl );
624 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
627 $namespace = $wgContLang->getNsText( $this->mNamespace
);
628 if ( '' != $namespace ) {
629 # Can this actually happen? Interwikis shouldn't be parsed.
632 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
634 if( false === strpos( $url, '?' ) ) {
641 if ( '' != $this->mFragment
) {
642 $url .= '#' . $this->mFragment
;
648 * Get a relative directory for putting an HTML version of this article into
650 function getHashedDirectory() {
651 global $wgMakeDumpLinks, $wgInputEncoding;
652 $dbkey = $this->getDBkey();
654 # Split into characters
655 if ( $wgInputEncoding == 'UTF-8' ) {
656 preg_match_all( '/./us', $dbkey, $m );
658 preg_match_all( '/./s', $dbkey, $m );
661 $length = count( $chars );
664 for ( $i = 0; $i < $wgMakeDumpLinks; $i++
) {
668 if ( $i >= $length ) {
670 } elseif ( ord( $chars[$i] ) > 32 ) {
671 $dir .= strtolower( $chars[$i] );
673 $dir .= sprintf( "%02X", ord( $chars[$i] ) );
679 function getHashedFilename() {
680 $dbkey = $this->getPrefixedDBkey();
681 $mainPage = Title
::newMainPage();
682 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
686 $dir = $this->getHashedDirectory();
688 # Replace illegal charcters for Windows paths with underscores
689 $friendlyName = strtr( $dbkey, '/\\*?"<>|~', '_________' );
691 # Work out lower case form. We assume we're on a system with case-insensitive
692 # filenames, so unless the case is of a special form, we have to disambiguate
693 $lowerCase = $this->prefix( ucfirst( strtolower( $this->getDBkey() ) ) );
695 # Make it mostly unique
696 if ( $lowerCase != $friendlyName ) {
697 $friendlyName .= '_' . substr(md5( $dbkey ), 0, 4);
699 # Handle colon specially by replacing it with tilde
700 # Thus we reduce the number of paths with hashes appended
701 $friendlyName = str_replace( ':', '~', $friendlyName );
702 return "$dir/$friendlyName.html";
706 * Get a URL with no fragment or server name
707 * @param string $query an optional query string; if not specified,
708 * $wgArticlePath will be used.
709 * @return string the URL
712 function getLocalURL( $query = '' ) {
713 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks;
715 if ( $this->isExternal() ) {
716 return $this->getFullURL();
719 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
720 if ( $wgMakeDumpLinks ) {
721 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
722 } elseif ( $query == '' ) {
723 $url = str_replace( '$1', $dbkey, $wgArticlePath );
725 global $wgActionPaths;
726 if( !empty( $wgActionPaths ) &&
727 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
728 $action = urldecode( $matches[2] );
729 if( isset( $wgActionPaths[$action] ) ) {
730 $query = $matches[1];
731 if( isset( $matches[4] ) ) $query .= $matches[4];
732 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
733 if( $query != '' ) $url .= '?' . $query;
737 if ( $query == '-' ) {
740 $url = "{$wgScript}?title={$dbkey}&{$query}";
746 * Get an HTML-escaped version of the URL form, suitable for
747 * using in a link, without a server name or fragment
748 * @param string $query an optional query string
749 * @return string the URL
752 function escapeLocalURL( $query = '' ) {
753 return htmlspecialchars( $this->getLocalURL( $query ) );
757 * Get an HTML-escaped version of the URL form, suitable for
758 * using in a link, including the server name and fragment
760 * @return string the URL
761 * @param string $query an optional query string
764 function escapeFullURL( $query = '' ) {
765 return htmlspecialchars( $this->getFullURL( $query ) );
769 * Get the URL form for an internal link.
770 * - Used in various Squid-related code, in case we have a different
771 * internal hostname for the server from the exposed one.
773 * @param string $query an optional query string
774 * @return string the URL
777 function getInternalURL( $query = '' ) {
778 global $wgInternalServer;
779 return $wgInternalServer . $this->getLocalURL( $query );
783 * Get the edit URL for this Title
784 * @return string the URL, or a null string if this is an
788 function getEditURL() {
789 global $wgServer, $wgScript;
791 if ( '' != $this->mInterwiki
) { return ''; }
792 $s = $this->getLocalURL( 'action=edit' );
798 * Get the HTML-escaped displayable text form.
799 * Used for the title field in <a> tags.
800 * @return string the text, including any prefixes
803 function getEscapedText() {
804 return htmlspecialchars( $this->getPrefixedText() );
808 * Is this Title interwiki?
812 function isExternal() { return ( '' != $this->mInterwiki
); }
815 * Does the title correspond to a protected article?
816 * @param string $what the action the page is protected from,
817 * by default checks move and edit
821 function isProtected($action = '') {
822 if ( -1 == $this->mNamespace
) { return true; }
823 if($action == 'edit' ||
$action == '') {
824 $a = $this->getRestrictions("edit");
825 if ( in_array( 'sysop', $a ) ) { return true; }
827 if($action == 'move' ||
$action == '') {
828 $a = $this->getRestrictions("move");
829 if ( in_array( 'sysop', $a ) ) { return true; }
835 * Is $wgUser is watching this page?
839 function userIsWatching() {
842 if ( is_null( $this->mWatched
) ) {
843 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
844 $this->mWatched
= false;
846 $this->mWatched
= $wgUser->isWatched( $this );
849 return $this->mWatched
;
853 * Is $wgUser perform $action this page?
854 * @param string $action action that permission needs to be checked for
858 function userCan($action) {
859 $fname = 'Title::userCanEdit';
860 wfProfileIn( $fname );
863 if( NS_SPECIAL
== $this->mNamespace
) {
864 wfProfileOut( $fname );
867 if( NS_MEDIAWIKI
== $this->mNamespace
&&
868 !$wgUser->isAllowed('editinterface') ) {
869 wfProfileOut( $fname );
872 if( $this->mDbkeyform
== '_' ) {
873 # FIXME: Is this necessary? Shouldn't be allowed anyway...
874 wfProfileOut( $fname );
878 # protect global styles and js
879 if ( NS_MEDIAWIKI
== $this->mNamespace
880 && preg_match("/\\.(css|js)$/", $this->mTextform
)
881 && !$wgUser->isAllowed('editinterface') ) {
882 wfProfileOut( $fname );
886 # protect css/js subpages of user pages
887 # XXX: this might be better using restrictions
888 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
889 if( NS_USER
== $this->mNamespace
890 && preg_match("/\\.(css|js)$/", $this->mTextform
)
891 && !$wgUser->isAllowed('editinterface')
892 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
893 wfProfileOut( $fname );
897 foreach( $this->getRestrictions($action) as $right ) {
898 // Backwards compatibility, rewrite sysop -> protect
899 if ( $right == 'sysop' ) {
902 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
903 wfProfileOut( $fname );
908 if( $action == 'move' && !$this->isMovable() ) {
909 wfProfileOut( $fname );
913 wfProfileOut( $fname );
918 * Can $wgUser edit this page?
922 function userCanEdit() {
923 return $this->userCan('edit');
927 * Can $wgUser move this page?
931 function userCanMove() {
932 return $this->userCan('move');
936 * Would anybody with sufficient privileges be able to move this page?
937 * Some pages just aren't movable.
942 function isMovable() {
943 return Namespace::isMovable( $this->getNamespace() )
944 && $this->getInterwiki() == '';
948 * Can $wgUser read this page?
952 function userCanRead() {
955 if( $wgUser->isAllowed('read') ) {
958 global $wgWhitelistRead;
960 /** If anon users can create an account,
961 they need to reach the login page first! */
962 if( $wgUser->isAllowed( 'createaccount' )
963 && $this->getNamespace() == NS_SPECIAL
964 && $this->getText() == 'Userlogin' ) {
968 /** some pages are explicitly allowed */
969 $name = $this->getPrefixedText();
970 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
974 # Compatibility with old settings
975 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
976 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
985 * Is this a talk page of some sort?
989 function isTalkPage() {
990 return Namespace::isTalk( $this->getNamespace() );
994 * Is this a .css or .js subpage of a user page?
998 function isCssJsSubpage() {
999 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1002 * Is this a .css subpage of a user page?
1006 function isCssSubpage() {
1007 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1010 * Is this a .js subpage of a user page?
1014 function isJsSubpage() {
1015 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1018 * Protect css/js subpages of user pages: can $wgUser edit
1022 * @todo XXX: this might be better using restrictions
1025 function userCanEditCssJsSubpage() {
1027 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1031 * Loads a string into mRestrictions array
1032 * @param string $res restrictions in string format
1035 function loadRestrictions( $res ) {
1036 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1037 $temp = explode( '=', trim( $restrict ) );
1038 if(count($temp) == 1) {
1039 // old format should be treated as edit/move restriction
1040 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1041 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1043 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1046 $this->mRestrictionsLoaded
= true;
1050 * Accessor/initialisation for mRestrictions
1051 * @param string $action action that permission needs to be checked for
1052 * @return array the array of groups allowed to edit this article
1055 function getRestrictions($action) {
1056 $id = $this->getArticleID();
1057 if ( 0 == $id ) { return array(); }
1059 if ( ! $this->mRestrictionsLoaded
) {
1060 $dbr =& wfGetDB( DB_SLAVE
);
1061 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1062 $this->loadRestrictions( $res );
1064 if( isset( $this->mRestrictions
[$action] ) ) {
1065 return $this->mRestrictions
[$action];
1071 * Is there a version of this page in the deletion archive?
1072 * @return int the number of archived revisions
1075 function isDeleted() {
1076 $fname = 'Title::isDeleted';
1077 if ( $this->getNamespace() < 0 ) {
1080 $dbr =& wfGetDB( DB_SLAVE
);
1081 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1082 'ar_title' => $this->getDBkey() ), $fname );
1088 * Get the article ID for this Title from the link cache,
1089 * adding it if necessary
1090 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1092 * @return int the ID
1095 function getArticleID( $flags = 0 ) {
1096 global $wgLinkCache;
1098 if ( $flags & GAID_FOR_UPDATE
) {
1099 $oldUpdate = $wgLinkCache->forUpdate( true );
1100 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1101 $wgLinkCache->forUpdate( $oldUpdate );
1103 if ( -1 == $this->mArticleID
) {
1104 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1107 return $this->mArticleID
;
1110 function getLatestRevID() {
1111 if ($this->mLatestID
!== false)
1112 return $this->mLatestID
;
1114 $db =& wfGetDB(DB_SLAVE
);
1115 return $this->mLatestID
= $db->selectField( 'revision',
1117 array('rev_page' => $this->getArticleID()),
1118 'Title::getLatestRevID' );
1122 * This clears some fields in this object, and clears any associated
1123 * keys in the "bad links" section of $wgLinkCache.
1125 * - This is called from Article::insertNewArticle() to allow
1126 * loading of the new page_id. It's also called from
1127 * Article::doDeleteArticle()
1129 * @param int $newid the new Article ID
1132 function resetArticleID( $newid ) {
1133 global $wgLinkCache;
1134 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1136 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1137 else { $this->mArticleID
= $newid; }
1138 $this->mRestrictionsLoaded
= false;
1139 $this->mRestrictions
= array();
1143 * Updates page_touched for this page; called from LinksUpdate.php
1144 * @return bool true if the update succeded
1147 function invalidateCache() {
1148 if ( wfReadOnly() ) {
1152 $now = wfTimestampNow();
1153 $dbw =& wfGetDB( DB_MASTER
);
1154 $success = $dbw->update( 'page',
1156 'page_touched' => $dbw->timestamp()
1157 ), array( /* WHERE */
1158 'page_namespace' => $this->getNamespace() ,
1159 'page_title' => $this->getDBkey()
1160 ), 'Title::invalidateCache'
1166 * Prefix some arbitrary text with the namespace or interwiki prefix
1169 * @param string $name the text
1170 * @return string the prefixed text
1173 /* private */ function prefix( $name ) {
1177 if ( '' != $this->mInterwiki
) {
1178 $p = $this->mInterwiki
. ':';
1180 if ( 0 != $this->mNamespace
) {
1181 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1187 * Secure and split - main initialisation function for this object
1189 * Assumes that mDbkeyform has been set, and is urldecoded
1190 * and uses underscores, but not otherwise munged. This function
1191 * removes illegal characters, splits off the interwiki and
1192 * namespace prefixes, sets the other forms, and canonicalizes
1194 * @return bool true on success
1197 /* private */ function secureAndSplit() {
1198 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1199 $fname = 'Title::secureAndSplit';
1200 wfProfileIn( $fname );
1203 static $rxTc = false;
1205 # % is needed as well
1206 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1209 $this->mInterwiki
= $this->mFragment
= '';
1210 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1212 # Clean up whitespace
1214 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1215 $t = trim( $t, '_' );
1218 wfProfileOut( $fname );
1222 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1223 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1224 wfProfileOut( $fname );
1228 $this->mDbkeyform
= $t;
1230 # Initial colon indicating main namespace
1231 if ( ':' == $t{0} ) {
1232 $r = substr( $t, 1 );
1233 $this->mNamespace
= NS_MAIN
;
1235 # Namespace or interwiki prefix
1238 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1240 $lowerNs = strtolower( $p );
1241 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1242 # Canonical namespace
1244 $this->mNamespace
= $ns;
1245 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1246 # Ordinary namespace
1248 $this->mNamespace
= $ns;
1249 } elseif( $this->getInterwikiLink( $p ) ) {
1251 # Can't make a local interwiki link to an interwiki link.
1252 # That's just crazy!
1253 wfProfileOut( $fname );
1259 $this->mInterwiki
= $p;
1261 # Redundant interwiki prefix to the local wiki
1262 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1264 # Can't have an empty self-link
1265 wfProfileOut( $fname );
1268 $this->mInterwiki
= '';
1270 # Do another namespace split...
1274 # If there's no recognized interwiki or namespace,
1275 # then let the colon expression be part of the title.
1282 # We already know that some pages won't be in the database!
1284 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1285 $this->mArticleID
= 0;
1287 $f = strstr( $r, '#' );
1288 if ( false !== $f ) {
1289 $this->mFragment
= substr( $f, 1 );
1290 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1291 # remove whitespace again: prevents "Foo_bar_#"
1292 # becoming "Foo_bar_"
1293 $r = preg_replace( '/_*$/', '', $r );
1296 # Reject illegal characters.
1298 if( preg_match( $rxTc, $r ) ) {
1299 wfProfileOut( $fname );
1304 * Pages with "/./" or "/../" appearing in the URLs will
1305 * often be unreachable due to the way web browsers deal
1306 * with 'relative' URLs. Forbid them explicitly.
1308 if ( strpos( $r, '.' ) !== false &&
1309 ( $r === '.' ||
$r === '..' ||
1310 strpos( $r, './' ) === 0 ||
1311 strpos( $r, '../' ) === 0 ||
1312 strpos( $r, '/./' ) !== false ||
1313 strpos( $r, '/../' ) !== false ) )
1315 wfProfileOut( $fname );
1319 # We shouldn't need to query the DB for the size.
1320 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1321 if ( strlen( $r ) > 255 ) {
1322 wfProfileOut( $fname );
1327 * Normally, all wiki links are forced to have
1328 * an initial capital letter so [[foo]] and [[Foo]]
1329 * point to the same place.
1331 * Don't force it for interwikis, since the other
1332 * site might be case-sensitive.
1334 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1335 $t = $wgContLang->ucfirst( $r );
1341 * Can't make a link to a namespace alone...
1342 * "empty" local links can only be self-links
1343 * with a fragment identifier.
1346 $this->mInterwiki
== '' &&
1347 $this->mNamespace
!= NS_MAIN
) {
1348 wfProfileOut( $fname );
1353 $this->mDbkeyform
= $t;
1354 $this->mUrlform
= wfUrlencode( $t );
1356 $this->mTextform
= str_replace( '_', ' ', $t );
1358 wfProfileOut( $fname );
1363 * Get a Title object associated with the talk page of this article
1364 * @return Title the object for the talk page
1367 function getTalkPage() {
1368 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1372 * Get a title object associated with the subject page of this
1375 * @return Title the object for the subject page
1378 function getSubjectPage() {
1379 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1383 * Get an array of Title objects linking to this Title
1384 * Also stores the IDs in the link cache.
1386 * @param string $options may be FOR UPDATE
1387 * @return array the Title objects linking here
1390 function getLinksTo( $options = '' ) {
1391 global $wgLinkCache;
1392 $id = $this->getArticleID();
1395 $db =& wfGetDB( DB_MASTER
);
1397 $db =& wfGetDB( DB_SLAVE
);
1400 $res = $db->select( array( 'page', 'pagelinks' ),
1401 array( 'page_namespace', 'page_title', 'page_id' ),
1404 'pl_namespace' => $this->getNamespace(),
1405 'pl_title' => $this->getDbKey() ),
1406 'Title::getLinksTo',
1410 if ( $db->numRows( $res ) ) {
1411 while ( $row = $db->fetchObject( $res ) ) {
1412 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1413 $wgLinkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1414 $retVal[] = $titleObj;
1418 $db->freeResult( $res );
1423 * Get an array of Title objects referring to non-existent articles linked from this page
1425 * @param string $options may be FOR UPDATE
1426 * @return array the Title objects
1429 function getBrokenLinksFrom( $options = '' ) {
1430 global $wgLinkCache;
1433 $db =& wfGetDB( DB_MASTER
);
1435 $db =& wfGetDB( DB_SLAVE
);
1438 $res = $db->safeQuery(
1439 "SELECT pl_namespace, pl_title
1442 ON pl_namespace=page_namespace
1443 AND pl_title=page_title
1445 AND page_namespace IS NULL
1447 $db->tableName( 'pagelinks' ),
1448 $db->tableName( 'page' ),
1449 $this->getArticleId(),
1453 if ( $db->numRows( $res ) ) {
1454 while ( $row = $db->fetchObject( $res ) ) {
1455 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1458 $db->freeResult( $res );
1464 * Get a list of URLs to purge from the Squid cache when this
1467 * @return array the URLs
1470 function getSquidURLs() {
1472 $this->getInternalURL(),
1473 $this->getInternalURL( 'action=history' )
1478 * Move this page without authentication
1479 * @param Title &$nt the new page Title
1482 function moveNoAuth( &$nt ) {
1483 return $this->moveTo( $nt, false );
1487 * Check whether a given move operation would be valid.
1488 * Returns true if ok, or a message key string for an error message
1489 * if invalid. (Scarrrrry ugly interface this.)
1490 * @param Title &$nt the new title
1491 * @param bool $auth indicates whether $wgUser's permissions
1493 * @return mixed true on success, message name on failure
1496 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1498 if( !$this or !$nt ) {
1499 return 'badtitletext';
1501 if( $this->equals( $nt ) ) {
1504 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1505 return 'immobile_namespace';
1508 $fname = 'Title::move';
1509 $oldid = $this->getArticleID();
1510 $newid = $nt->getArticleID();
1512 if ( strlen( $nt->getDBkey() ) < 1 ) {
1513 return 'articleexists';
1515 if ( ( '' == $this->getDBkey() ) ||
1517 ( '' == $nt->getDBkey() ) ) {
1518 return 'badarticleerror';
1522 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1523 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1524 return 'protectedpage';
1527 # The move is allowed only if (1) the target doesn't exist, or
1528 # (2) the target is a redirect to the source, and has no history
1529 # (so we can undo bad moves right after they're done).
1531 if ( 0 != $newid ) { # Target exists; check for validity
1532 if ( ! $this->isValidMoveTarget( $nt ) ) {
1533 return 'articleexists';
1540 * Move a title to a new location
1541 * @param Title &$nt the new title
1542 * @param bool $auth indicates whether $wgUser's permissions
1544 * @return mixed true on success, message name on failure
1547 function moveTo( &$nt, $auth = true, $reason = '' ) {
1548 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1549 if( is_string( $err ) ) {
1553 $pageid = $this->getArticleID();
1554 if( $nt->exists() ) {
1555 $this->moveOverExistingRedirect( $nt, $reason );
1556 $pageCountChange = 0;
1557 } else { # Target didn't exist, do normal move.
1558 $this->moveToNewTitle( $nt, $newid, $reason );
1559 $pageCountChange = 1;
1561 $redirid = $this->getArticleID();
1563 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1564 $dbw =& wfGetDB( DB_MASTER
);
1565 $categorylinks = $dbw->tableName( 'categorylinks' );
1566 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1567 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1568 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1569 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1573 $oldnamespace = $this->getNamespace() & ~
1;
1574 $newnamespace = $nt->getNamespace() & ~
1;
1575 $oldtitle = $this->getDBkey();
1576 $newtitle = $nt->getDBkey();
1578 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1579 WatchedItem
::duplicateEntries( $this, $nt );
1582 # Update search engine
1583 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1585 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1589 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1590 # Moved out of main namespace
1591 # not viewed, edited, removing
1592 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1593 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1594 # Moved into main namespace
1595 # not viewed, edited, adding
1596 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1597 } elseif ( $pageCountChange ) {
1599 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1607 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1612 * Move page to a title which is at present a redirect to the
1615 * @param Title &$nt the page to move to, which should currently
1619 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1620 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1621 $fname = 'Title::moveOverExistingRedirect';
1622 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1625 $comment .= ": $reason";
1628 $now = wfTimestampNow();
1630 $newid = $nt->getArticleID();
1631 $oldid = $this->getArticleID();
1632 $dbw =& wfGetDB( DB_MASTER
);
1633 $links = $dbw->tableName( 'links' );
1635 # Delete the old redirect. We don't save it to history since
1636 # by definition if we've got here it's rather uninteresting.
1637 # We have to remove it so that the next step doesn't trigger
1638 # a conflict on the unique namespace+title index...
1639 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1641 # Save a null revision in the page's history notifying of the move
1642 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1643 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1645 $nullRevId = $nullRevision->insertOn( $dbw );
1647 # Change the name of the target page:
1648 $dbw->update( 'page',
1650 'page_touched' => $dbw->timestamp($now),
1651 'page_namespace' => $nt->getNamespace(),
1652 'page_title' => $nt->getDBkey(),
1653 'page_latest' => $nullRevId,
1655 /* WHERE */ array( 'page_id' => $oldid ),
1658 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1660 # Recreate the redirect, this time in the other direction.
1661 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1662 $redirectArticle = new Article( $this );
1663 $newid = $redirectArticle->insertOn( $dbw );
1664 $redirectRevision = new Revision( array(
1666 'comment' => $comment,
1667 'text' => $redirectText ) );
1668 $revid = $redirectRevision->insertOn( $dbw );
1669 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1670 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1673 $log = new LogPage( 'move' );
1674 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1676 # Now, we record the link from the redirect to the new title.
1677 # It should have no other outgoing links...
1678 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1679 $dbw->insert( 'pagelinks',
1681 'pl_from' => $newid,
1682 'pl_namespace' => $nt->getNamespace(),
1683 'pl_title' => $nt->getDbKey() ),
1687 if ( $wgUseSquid ) {
1688 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1689 $u = new SquidUpdate( $urls );
1695 * Move page to non-existing title.
1696 * @param Title &$nt the new Title
1697 * @param int &$newid set to be the new article ID
1700 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1701 global $wgUser, $wgLinkCache, $wgUseSquid;
1703 $fname = 'MovePageForm::moveToNewTitle';
1704 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1706 $comment .= ": $reason";
1709 $newid = $nt->getArticleID();
1710 $oldid = $this->getArticleID();
1711 $dbw =& wfGetDB( DB_MASTER
);
1712 $now = $dbw->timestamp();
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 );
1723 $dbw->update( 'page',
1725 'page_touched' => $now,
1726 'page_namespace' => $nt->getNamespace(),
1727 'page_title' => $nt->getDBkey(),
1728 'page_latest' => $nullRevId,
1730 /* WHERE */ array( 'page_id' => $oldid ),
1734 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1737 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1738 $redirectArticle = new Article( $this );
1739 $newid = $redirectArticle->insertOn( $dbw );
1740 $redirectRevision = new Revision( array(
1742 'comment' => $comment,
1743 'text' => $redirectText ) );
1744 $revid = $redirectRevision->insertOn( $dbw );
1745 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1746 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1749 $log = new LogPage( 'move' );
1750 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1752 # Purge caches as per article creation
1753 Article
::onArticleCreate( $nt );
1755 # Record the just-created redirect's linking to the page
1756 $dbw->insert( 'pagelinks',
1758 'pl_from' => $newid,
1759 'pl_namespace' => $nt->getNamespace(),
1760 'pl_title' => $nt->getDBkey() ),
1763 # Non-existent target may have had broken links to it; these must
1764 # now be touched to update link coloring.
1767 # Purge old title from squid
1768 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1769 $titles = $nt->getLinksTo();
1770 if ( $wgUseSquid ) {
1771 $urls = $this->getSquidURLs();
1772 foreach ( $titles as $linkTitle ) {
1773 $urls[] = $linkTitle->getInternalURL();
1775 $u = new SquidUpdate( $urls );
1781 * Checks if $this can be moved to a given Title
1782 * - Selects for update, so don't call it unless you mean business
1784 * @param Title &$nt the new title to check
1787 function isValidMoveTarget( $nt ) {
1789 $fname = 'Title::isValidMoveTarget';
1790 $dbw =& wfGetDB( DB_MASTER
);
1793 $id = $nt->getArticleID();
1794 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1795 array( 'page_is_redirect','old_text' ),
1796 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1797 $fname, 'FOR UPDATE' );
1799 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1804 # Does the redirect point to the source?
1805 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text
, $m ) ) {
1806 $redirTitle = Title
::newFromText( $m[1] );
1807 if( !is_object( $redirTitle ) ||
1808 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1813 # Does the article have a history?
1814 $row = $dbw->selectRow( array( 'page', 'revision'),
1816 array( 'page_namespace' => $nt->getNamespace(),
1817 'page_title' => $nt->getDBkey(),
1818 'page_id=rev_page AND page_latest != rev_id'
1819 ), $fname, 'FOR UPDATE'
1822 # Return true if there was no history
1823 return $row === false;
1827 * Create a redirect; fails if the title already exists; does
1830 * @param Title $dest the destination of the redirect
1831 * @param string $comment the comment string describing the move
1832 * @return bool true on success
1835 function createRedirect( $dest, $comment ) {
1837 if ( $this->getArticleID() ) {
1841 $fname = 'Title::createRedirect';
1842 $dbw =& wfGetDB( DB_MASTER
);
1844 $article = new Article( $this );
1845 $newid = $article->insertOn( $dbw );
1846 $revision = new Revision( array(
1848 'comment' => $comment,
1849 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1851 $revisionId = $revision->insertOn( $dbw );
1852 $article->updateRevisionOn( $dbw, $revision, 0 );
1855 $dbw->insert( 'pagelinks',
1857 'pl_from' => $newid,
1858 'pl_namespace' => $dest->getNamespace(),
1859 'pl_title' => $dest->getDbKey()
1863 Article
::onArticleCreate( $this );
1868 * Get categories to which this Title belongs and return an array of
1869 * categories' names.
1871 * @return array an array of parents in the form:
1872 * $parent => $currentarticle
1875 function getParentCategories() {
1876 global $wgContLang,$wgUser;
1878 $titlekey = $this->getArticleId();
1879 $sk =& $wgUser->getSkin();
1881 $dbr =& wfGetDB( DB_SLAVE
);
1882 $categorylinks = $dbr->tableName( 'categorylinks' );
1885 $sql = "SELECT * FROM $categorylinks"
1886 ." WHERE cl_from='$titlekey'"
1887 ." AND cl_from <> '0'"
1888 ." ORDER BY cl_sortkey";
1890 $res = $dbr->query ( $sql ) ;
1892 if($dbr->numRows($res) > 0) {
1893 while ( $x = $dbr->fetchObject ( $res ) )
1894 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1895 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1896 $dbr->freeResult ( $res ) ;
1904 * Get a tree of parent categories
1905 * @param array $children an array with the children in the keys, to check for circular refs
1909 function getParentCategoryTree( $children = array() ) {
1910 $parents = $this->getParentCategories();
1912 if($parents != '') {
1913 foreach($parents as $parent => $current)
1915 if ( array_key_exists( $parent, $children ) ) {
1916 # Circular reference
1917 $stack[$parent] = array();
1919 $nt = Title
::newFromText($parent);
1920 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
1931 * Get an associative array for selecting this title from
1937 function curCond() {
1938 wfDebugDieBacktrace( 'curCond called' );
1939 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1943 * Get an associative array for selecting this title from the
1949 function oldCond() {
1950 wfDebugDieBacktrace( 'oldCond called' );
1951 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);
1955 * Get the revision ID of the previous revision
1957 * @param integer $revision Revision ID. Get the revision that was before this one.
1958 * @return interger $oldrevision|false
1960 function getPreviousRevisionID( $revision ) {
1961 $dbr =& wfGetDB( DB_SLAVE
);
1962 return $dbr->selectField( 'revision', 'rev_id',
1963 'rev_page=' . IntVal( $this->getArticleId() ) .
1964 ' AND rev_id<' . IntVal( $revision ) . ' ORDER BY rev_id DESC' );
1968 * Get the revision ID of the next revision
1970 * @param integer $revision Revision ID. Get the revision that was after this one.
1971 * @return interger $oldrevision|false
1973 function getNextRevisionID( $revision ) {
1974 $dbr =& wfGetDB( DB_SLAVE
);
1975 return $dbr->selectField( 'revision', 'rev_id',
1976 'rev_page=' . IntVal( $this->getArticleId() ) .
1977 ' AND rev_id>' . IntVal( $revision ) . ' ORDER BY rev_id' );
1981 * Compare with another title.
1983 * @param Title $title
1986 function equals( &$title ) {
1987 return $this->getInterwiki() == $title->getInterwiki()
1988 && $this->getNamespace() == $title->getNamespace()
1989 && $this->getDbkey() == $title->getDbkey();
1993 * Check if page exists
1997 return $this->getArticleId() != 0;
2001 * Should a link should be displayed as a known link, just based on its title?
2003 * Currently, a self-link with a fragment, special pages and image pages are in
2004 * this category. Special pages never exist in the database. Some images do not
2005 * have description pages in the database, but the description page contains
2006 * useful history information that the user may want to link to.
2008 function isAlwaysKnown() {
2009 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2010 || NS_SPECIAL
== $this->mNamespace || NS_IMAGE
== $this->mNamespace
;
2014 * Update page_touched timestamps on pages linking to this title.
2015 * In principal, this could be backgrounded and could also do squid
2018 function touchLinks() {
2019 $fname = 'Title::touchLinks';
2021 $dbw =& wfGetDB( DB_MASTER
);
2023 $res = $dbw->select( 'pagelinks',
2026 'pl_namespace' => $this->getNamespace(),
2027 'pl_title' => $this->getDbKey() ),
2029 if ( 0 == $dbw->numRows( $res ) ) {
2034 $toucharr = array();
2035 while( $row = $dbw->fetchObject( $res ) ) {
2036 $toucharr[] = $row->pl_from
;
2039 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2040 /* WHERE */ array( 'page_id' => $toucharr ),$fname);