10 require_once( 'normal/UtfNormal.php' );
12 $wgTitleInterwikiCache = array();
13 define ( 'GAID_FOR_UPDATE', 1 );
17 * - Represents a title, which may contain an interwiki designation or namespace
18 * - Can fetch various kinds of data from the database, albeit inefficiently.
24 * All member variables should be considered private
25 * Please use the accessor functions
32 var $mTextform; # Text form (spaces not underscores) of the main part
33 var $mUrlform; # URL-encoded form of the main part
34 var $mDbkeyform; # Main part with underscores
35 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
36 var $mInterwiki; # Interwiki prefix (or null string)
37 var $mFragment; # Title fragment (i.e. the bit after the #)
38 var $mArticleID; # Article ID, fetched from the link cache on demand
39 var $mRestrictions; # Array of groups allowed to edit this article
40 # Only null or "sysop" are supported
41 var $mRestrictionsLoaded; # Boolean for initialisation on demand
42 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
43 var $mDefaultNamespace; # Namespace index when there is no namespace
44 # Zero except in {{transclusion}} tags
52 /* private */ function Title() {
53 $this->mInterwiki
= $this->mUrlform
=
54 $this->mTextform
= $this->mDbkeyform
= '';
55 $this->mArticleID
= -1;
56 $this->mNamespace
= 0;
57 $this->mRestrictionsLoaded
= false;
58 $this->mRestrictions
= array();
59 $this->mDefaultNamespace
= 0;
63 * Create a new Title from a prefixed DB key
64 * @param string $key The database key, which has underscores
65 * instead of spaces, possibly including namespace and
67 * @return Title the new object, or NULL on an error
71 /* static */ function newFromDBkey( $key ) {
73 $t->mDbkeyform
= $key;
74 if( $t->secureAndSplit() )
81 * Create a new Title from text, such as what one would
82 * find in a link. Decodes any HTML entities in the text.
84 * @param string $text the link text; spaces, prefixes,
85 * and an initial ':' indicating the main namespace
87 * @param int $defaultNamespace the namespace to use if
88 * none is specified by a prefix
89 * @return Title the new object, or NULL on an error
93 /* static */ function newFromText( $text, $defaultNamespace = 0 ) {
94 $fname = 'Title::newFromText';
95 wfProfileIn( $fname );
97 if( is_object( $text ) ) {
98 wfDebugDieBacktrace( 'Called with object instead of string.' );
100 global $wgInputEncoding;
101 $text = do_html_entity_decode( $text, ENT_COMPAT
, $wgInputEncoding );
103 $text = wfMungeToUtf8( $text );
106 # What was this for? TS 2004-03-03
107 # $text = urldecode( $text );
110 $t->mDbkeyform
= str_replace( ' ', '_', $text );
111 $t->mDefaultNamespace
= $defaultNamespace;
113 wfProfileOut( $fname );
114 if ( !is_object( $t ) ) {
115 var_dump( debug_backtrace() );
117 if( $t->secureAndSplit() ) {
125 * Create a new Title from URL-encoded text. Ensures that
126 * the given title's length does not exceed the maximum.
127 * @param string $url the title, as might be taken from a URL
128 * @return Title the new object, or NULL on an error
132 /* static */ function newFromURL( $url ) {
133 global $wgLang, $wgServer;
136 # For compatibility with old buggy URLs. "+" is not valid in titles,
137 # but some URLs used it as a space replacement and they still come
138 # from some external search tools.
139 $s = str_replace( '+', ' ', $url );
141 $t->mDbkeyform
= str_replace( ' ', '_', $s );
142 if( $t->secureAndSplit() ) {
150 * Create a new Title from an article ID
151 * @todo This is inefficiently implemented, the cur row is requested
152 * but not used for anything else
153 * @param int $id the cur_id corresponding to the Title to create
154 * @return Title the new object, or NULL on an error
157 /* static */ function newFromID( $id ) {
158 $fname = 'Title::newFromID';
159 $dbr =& wfGetDB( DB_SLAVE
);
160 $row = $dbr->selectRow( 'cur', array( 'cur_namespace', 'cur_title' ),
161 array( 'cur_id' => $id ), $fname );
162 if ( $row !== false ) {
163 $title = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
171 * Create a new Title from a namespace index and a DB key.
172 * It's assumed that $ns and $title are *valid*, for instance when
173 * they came directly from the database or a special page name.
174 * @param int $ns the namespace of the article
175 * @param string $title the unprefixed database key form
176 * @return Title the new object
180 /* static */ function &makeTitle( $ns, $title ) {
184 $t->mNamespace
= IntVal( $ns );
185 $t->mDbkeyform
= $title;
186 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
187 $t->mUrlform
= wfUrlencode( $title );
188 $t->mTextform
= str_replace( '_', ' ', $title );
193 * Create a new Title frrom a namespace index and a DB key.
194 * The parameters will be checked for validity, which is a bit slower
195 * than makeTitle() but safer for user-provided data.
196 * @param int $ns the namespace of the article
197 * @param string $title the database key form
198 * @return Title the new object, or NULL on an error
202 /* static */ function makeTitleSafe( $ns, $title ) {
204 $t->mDbkeyform
= Title
::makeName( $ns, $title );
205 if( $t->secureAndSplit() ) {
213 * Create a new Title for the Main Page
215 * @return Title the new object
218 /* static */ function newMainPage() {
219 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
223 * Create a new Title for a redirect
224 * @param string $text the redirect title text
225 * @return Title the new object, or NULL if the text is not a
230 /* static */ function newFromRedirect( $text ) {
233 if ( $wgMwRedir->matchStart( $text ) ) {
234 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/', $text, $m ) ) {
235 # categories are escaped using : for example one can enter:
236 # #REDIRECT [[:Category:Music]]. Need to remove it.
237 if ( substr($m[1],0,1) == ':') {
238 # We don't want to keep the ':'
239 $m[1] = substr( $m[1], 1 );
242 $rt = Title
::newFromText( $m[1] );
243 # Disallow redirects to Special:Userlogout
244 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
252 #----------------------------------------------------------------------------
254 #----------------------------------------------------------------------------
257 * Get the prefixed DB key associated with an ID
258 * @param int $id the cur_id of the article
259 * @return Title an object representing the article, or NULL
260 * if no such article was found
264 /* static */ function nameOf( $id ) {
265 $fname = 'Title::nameOf';
266 $dbr =& wfGetDB( DB_SLAVE
);
268 $s = $dbr->selectRow( 'cur', array( 'cur_namespace','cur_title' ), array( 'cur_id' => $id ), $fname );
269 if ( $s === false ) { return NULL; }
271 $n = Title
::makeName( $s->cur_namespace
, $s->cur_title
);
276 * Get a regex character class describing the legal characters in a link
277 * @return string the list of characters, not delimited
281 /* static */ function legalChars() {
282 # Missing characters:
283 # * []|# Needed for link syntax
284 # * % and + are corrupted by Apache when they appear in the path
286 # % seems to work though
288 # The problem with % is that URLs are double-unescaped: once by Apache's
289 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
290 # Our code does not double-escape to compensate for this, indeed double escaping
291 # would break if the double-escaped title was passed in the query string
292 # rather than the path. This is a minor security issue because articles can be
293 # created such that they are hard to view or edit. -- TS
295 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
296 # this breaks interlanguage links
298 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF";
303 * Get a string representation of a title suitable for
304 * including in a search index
306 * @param int $ns a namespace index
307 * @param string $title text-form main part
308 * @return string a stripped-down title string ready for the
311 /* static */ function indexTitle( $ns, $title ) {
312 global $wgDBminWordLen, $wgContLang;
313 require_once( 'SearchEngine.php' );
315 $lc = SearchEngine
::legalSearchChars() . '&#;';
316 $t = $wgContLang->stripForSearch( $title );
317 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
318 $t = strtolower( $t );
321 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
322 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
324 $t = preg_replace( "/\\s+/", ' ', $t );
326 if ( $ns == Namespace::getImage() ) {
327 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
333 * Make a prefixed DB key from a DB key and a namespace index
334 * @param int $ns numerical representation of the namespace
335 * @param string $title the DB key form the title
336 * @return string the prefixed form of the title
338 /* static */ function makeName( $ns, $title ) {
341 $n = $wgContLang->getNsText( $ns );
342 if ( '' == $n ) { return $title; }
343 else { return $n.':'.$title; }
347 * Returns the URL associated with an interwiki prefix
348 * @param string $key the interwiki prefix (e.g. "MeatBall")
349 * @return the associated URL, containing "$1", which should be
350 * replaced by an article title
354 function getInterwikiLink( $key ) {
355 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
356 $fname = 'Title::getInterwikiLink';
357 $k = $wgDBname.':interwiki:'.$key;
359 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
360 return $wgTitleInterwikiCache[$k]->iw_url
;
362 $s = $wgMemc->get( $k );
363 # Ignore old keys with no iw_local
364 if( $s && isset( $s->iw_local
) ) {
365 $wgTitleInterwikiCache[$k] = $s;
368 $dbr =& wfGetDB( DB_SLAVE
);
369 $res = $dbr->select( 'interwiki', array( 'iw_url', 'iw_local' ), array( 'iw_prefix' => $key ), $fname );
372 $s = $dbr->fetchObject( $res );
374 # Cache non-existence: create a blank object and save it to memcached
379 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
380 $wgTitleInterwikiCache[$k] = $s;
385 * Determine whether the object refers to a page within
388 * @return bool TRUE if this is an in-project interwiki link
389 * or a wikilink, FALSE otherwise
393 global $wgTitleInterwikiCache, $wgDBname;
395 if ( $this->mInterwiki
!= '' ) {
396 # Make sure key is loaded into cache
397 $this->getInterwikiLink( $this->mInterwiki
);
398 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
399 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
406 * Update the cur_touched field for an array of title objects
407 * @todo Inefficient unless the IDs are already loaded into the
409 * @param array $titles an array of Title objects to be touched
410 * @param string $timestamp the timestamp to use instead of the
411 * default current time
415 /* static */ function touchArray( $titles, $timestamp = '' ) {
416 if ( count( $titles ) == 0 ) {
419 $dbw =& wfGetDB( DB_MASTER
);
420 if ( $timestamp == '' ) {
421 $timestamp = $dbw->timestamp();
423 $cur = $dbw->tableName( 'cur' );
424 $sql = "UPDATE $cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
427 foreach ( $titles as $title ) {
432 $sql .= $title->getArticleID();
436 $dbw->query( $sql, 'Title::touchArray' );
440 #----------------------------------------------------------------------------
442 #----------------------------------------------------------------------------
444 /** Simple accessors */
446 * Get the text form (spaces not underscores) of the main part
450 function getText() { return $this->mTextform
; }
452 * Get the URL-encoded form of the main part
456 function getPartialURL() { return $this->mUrlform
; }
458 * Get the main part with underscores
462 function getDBkey() { return $this->mDbkeyform
; }
464 * Get the namespace index, i.e. one of the NS_xxxx constants
468 function getNamespace() { return $this->mNamespace
; }
470 * Get the interwiki prefix (or null string)
474 function getInterwiki() { return $this->mInterwiki
; }
476 * Get the Title fragment (i.e. the bit after the #)
480 function getFragment() { return $this->mFragment
; }
482 * Get the default namespace index, for when there is no namespace
486 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
489 * Get title for search index
490 * @return string a stripped-down title string ready for the
493 function getIndexTitle() {
494 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
498 * Get the prefixed database key form
499 * @return string the prefixed title, with underscores and
500 * any interwiki and namespace prefixes
503 function getPrefixedDBkey() {
504 $s = $this->prefix( $this->mDbkeyform
);
505 $s = str_replace( ' ', '_', $s );
510 * Get the prefixed title with spaces.
511 * This is the form usually used for display
512 * @return string the prefixed title, with spaces
515 function getPrefixedText() {
517 if ( empty( $this->mPrefixedText
) ) {
518 $s = $this->prefix( $this->mTextform
);
519 $s = str_replace( '_', ' ', $s );
520 $this->mPrefixedText
= $s;
522 return $this->mPrefixedText
;
526 * Get the prefixed title with spaces, plus any fragment
527 * (part beginning with '#')
528 * @return string the prefixed title, with spaces and
529 * the fragment, including '#'
532 function getFullText() {
534 $text = $this->getPrefixedText();
535 if( '' != $this->mFragment
) {
536 $text .= '#' . $this->mFragment
;
542 * Get a URL-encoded title (not an actual URL) including interwiki
543 * @return string the URL-encoded form
546 function getPrefixedURL() {
547 $s = $this->prefix( $this->mDbkeyform
);
548 $s = str_replace( ' ', '_', $s );
550 $s = wfUrlencode ( $s ) ;
552 # Cleaning up URL to make it look nice -- is this safe?
553 $s = preg_replace( '/%3[Aa]/', ':', $s );
554 $s = preg_replace( '/%2[Ff]/', '/', $s );
555 $s = str_replace( '%28', '(', $s );
556 $s = str_replace( '%29', ')', $s );
562 * Get a real URL referring to this title, with interwiki link and
565 * @param string $query an optional query string, not used
566 * for interwiki links
567 * @return string the URL
570 function getFullURL( $query = '' ) {
571 global $wgContLang, $wgArticlePath, $wgServer, $wgScript;
573 if ( '' == $this->mInterwiki
) {
575 return $wgServer . $this->getLocalUrl( $query );
577 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
578 $namespace = $wgContLang->getNsText( $this->mNamespace
);
579 if ( '' != $namespace ) {
580 # Can this actually happen? Interwikis shouldn't be parsed.
583 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
584 if ( '' != $this->mFragment
) {
585 $url .= '#' . $this->mFragment
;
592 * Get a URL with no fragment or server name
593 * @param string $query an optional query string; if not specified,
594 * $wgArticlePath will be used.
595 * @return string the URL
598 function getLocalURL( $query = '' ) {
599 global $wgLang, $wgArticlePath, $wgScript;
601 if ( $this->isExternal() ) {
602 return $this->getFullURL();
605 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
606 if ( $query == '' ) {
607 $url = str_replace( '$1', $dbkey, $wgArticlePath );
609 if ( $query == '-' ) {
612 $url = "{$wgScript}?title={$dbkey}&{$query}";
618 * Get an HTML-escaped version of the URL form, suitable for
619 * using in a link, without a server name or fragment
620 * @param string $query an optional query string
621 * @return string the URL
624 function escapeLocalURL( $query = '' ) {
625 return htmlspecialchars( $this->getLocalURL( $query ) );
629 * Get an HTML-escaped version of the URL form, suitable for
630 * using in a link, including the server name and fragment
632 * @return string the URL
633 * @param string $query an optional query string
636 function escapeFullURL( $query = '' ) {
637 return htmlspecialchars( $this->getFullURL( $query ) );
641 * Get the URL form for an internal link.
642 * - Used in various Squid-related code, in case we have a different
643 * internal hostname for the server from the exposed one.
645 * @param string $query an optional query string
646 * @return string the URL
649 function getInternalURL( $query = '' ) {
650 global $wgInternalServer;
651 return $wgInternalServer . $this->getLocalURL( $query );
655 * Get the edit URL for this Title
656 * @return string the URL, or a null string if this is an
660 function getEditURL() {
661 global $wgServer, $wgScript;
663 if ( '' != $this->mInterwiki
) { return ''; }
664 $s = $this->getLocalURL( 'action=edit' );
670 * Get the HTML-escaped displayable text form.
671 * Used for the title field in <a> tags.
672 * @return string the text, including any prefixes
675 function getEscapedText() {
676 return htmlspecialchars( $this->getPrefixedText() );
680 * Is this Title interwiki?
684 function isExternal() { return ( '' != $this->mInterwiki
); }
687 * Does the title correspond to a protected article?
691 function isProtected() {
692 if ( -1 == $this->mNamespace
) { return true; }
693 $a = $this->getRestrictions();
694 if ( in_array( 'sysop', $a ) ) { return true; }
699 * Is the page a log page, i.e. one where the history is messed up by
700 * LogPage.php? This used to be used for suppressing diff links in
701 * recent changes, but now that's done by setting a flag in the
702 * recentchanges table. Hence, this probably is no longer used.
708 if ( $this->mNamespace
!= Namespace::getWikipedia() ) {
711 if ( ( 0 == strcmp( wfMsg( 'uploadlogpage' ), $this->mDbkeyform
) ) ||
712 ( 0 == strcmp( wfMsg( 'dellogpage' ), $this->mDbkeyform
) ) ) {
719 * Is $wgUser is watching this page?
723 function userIsWatching() {
726 if ( -1 == $this->mNamespace
) { return false; }
727 if ( 0 == $wgUser->getID() ) { return false; }
729 return $wgUser->isWatched( $this );
733 * Can $wgUser edit this page?
737 function userCanEdit() {
739 if( NS_SPECIAL
== $this->mNamespace
) {
742 if( NS_MEDIAWIKI
== $this->mNamespace
&&
743 !$wgUser->isAllowed('editinterface') ) {
746 if( $this->mDbkeyform
== '_' ) {
747 # FIXME: Is this necessary? Shouldn't be allowed anyway...
751 # protect global styles and js
752 if ( NS_MEDIAWIKI
== $this->mNamespace
753 && preg_match("/\\.(css|js)$/", $this->mTextform
)
754 && !$wgUser->isAllowed('editinterface') ) {
758 # protect css/js subpages of user pages
759 # XXX: this might be better using restrictions
760 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
761 if( NS_USER
== $this->mNamespace
762 && preg_match("/\\.(css|js)$/", $this->mTextform
)
763 && !$wgUser->isAllowed('editinterface')
764 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
768 foreach( $this->getRestrictions() as $right ) {
769 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
777 * Can $wgUser read this page?
781 function userCanRead() {
784 if( $wgUser->isAllowed('read') ) {
787 global $wgWhitelistRead;
789 /** If anon users can create an account,
790 they need to reach the login page first! */
791 if( $wgUser->isAllowed( 'createaccount' )
792 && $this->mId
== NS_SPECIAL
793 && $this->getText() == 'Userlogin' ) {
797 /** some pages are explicitly allowed */
798 $name = $this->getPrefixedText();
799 if( in_array( $name, $wgWhitelistRead ) ) {
803 # Compatibility with old settings
804 if( $this->getNamespace() == NS_MAIN
) {
805 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
814 * Is this a .css or .js subpage of a user page?
818 function isCssJsSubpage() {
819 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
822 * Is this a .css subpage of a user page?
826 function isCssSubpage() {
827 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
830 * Is this a .js subpage of a user page?
834 function isJsSubpage() {
835 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
838 * Protect css/js subpages of user pages: can $wgUser edit
842 * @todo XXX: this might be better using restrictions
845 function userCanEditCssJsSubpage() {
847 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
851 * Accessor/initialisation for mRestrictions
852 * @return array the array of groups allowed to edit this article
855 function getRestrictions() {
856 $id = $this->getArticleID();
857 if ( 0 == $id ) { return array(); }
859 if ( ! $this->mRestrictionsLoaded
) {
860 $dbr =& wfGetDB( DB_SLAVE
);
861 $res = $dbr->selectField( 'cur', 'cur_restrictions', 'cur_id='.$id );
862 $this->mRestrictions
= explode( ',', trim( $res ) );
863 $this->mRestrictionsLoaded
= true;
865 return $this->mRestrictions
;
869 * Is there a version of this page in the deletion archive?
870 * @return int the number of archived revisions
873 function isDeleted() {
874 $fname = 'Title::isDeleted';
875 $dbr =& wfGetDB( DB_SLAVE
);
876 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
877 'ar_title' => $this->getDBkey() ), $fname );
882 * Get the article ID for this Title from the link cache,
883 * adding it if necessary
884 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
889 function getArticleID( $flags = 0 ) {
892 if ( $flags & GAID_FOR_UPDATE
) {
893 $oldUpdate = $wgLinkCache->forUpdate( true );
894 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
895 $wgLinkCache->forUpdate( $oldUpdate );
897 if ( -1 == $this->mArticleID
) {
898 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
901 return $this->mArticleID
;
905 * This clears some fields in this object, and clears any associated
906 * keys in the "bad links" section of $wgLinkCache.
908 * - This is called from Article::insertNewArticle() to allow
909 * loading of the new cur_id. It's also called from
910 * Article::doDeleteArticle()
912 * @param int $newid the new Article ID
915 function resetArticleID( $newid ) {
917 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
919 if ( 0 == $newid ) { $this->mArticleID
= -1; }
920 else { $this->mArticleID
= $newid; }
921 $this->mRestrictionsLoaded
= false;
922 $this->mRestrictions
= array();
926 * Updates cur_touched for this page; called from LinksUpdate.php
927 * @return bool true if the update succeded
930 function invalidateCache() {
931 $now = wfTimestampNow();
932 $dbw =& wfGetDB( DB_MASTER
);
933 $success = $dbw->update( 'cur',
935 'cur_touched' => $dbw->timestamp()
936 ), array( /* WHERE */
937 'cur_namespace' => $this->getNamespace() ,
938 'cur_title' => $this->getDBkey()
939 ), 'Title::invalidateCache'
945 * Prefix some arbitrary text with the namespace or interwiki prefix
948 * @param string $name the text
949 * @return string the prefixed text
952 /* private */ function prefix( $name ) {
956 if ( '' != $this->mInterwiki
) {
957 $p = $this->mInterwiki
. ':';
959 if ( 0 != $this->mNamespace
) {
960 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
966 * Secure and split - main initialisation function for this object
968 * Assumes that mDbkeyform has been set, and is urldecoded
969 * and uses underscores, but not otherwise munged. This function
970 * removes illegal characters, splits off the interwiki and
971 * namespace prefixes, sets the other forms, and canonicalizes
973 * @return bool true on success
976 /* private */ function secureAndSplit()
978 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
979 $fname = 'Title::secureAndSplit';
980 wfProfileIn( $fname );
982 static $imgpre = false;
983 static $rxTc = false;
986 if ( $imgpre === false ) {
987 $imgpre = ':' . $wgContLang->getNsText( Namespace::getImage() ) . ':';
988 # % is needed as well
989 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/';
992 $this->mInterwiki
= $this->mFragment
= '';
993 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
995 # Clean up whitespace
997 $t = preg_replace( "/[\\s_]+/", '_', $this->mDbkeyform
);
998 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
1001 wfProfileOut( $fname );
1005 global $wgUseLatin1;
1006 if( !$wgUseLatin1 && false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1007 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1008 wfProfileOut( $fname );
1012 $this->mDbkeyform
= $t;
1016 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
1017 $t = substr( $t, 1 );
1020 # Initial colon indicating main namespace
1021 if ( ':' == $t{0} ) {
1022 $r = substr( $t, 1 );
1023 $this->mNamespace
= NS_MAIN
;
1025 # Namespace or interwiki prefix
1026 if ( preg_match( "/^(.+?)_*:_*(.*)$/", $t, $m ) ) {
1027 #$p = strtolower( $m[1] );
1029 $lowerNs = strtolower( $p );
1030 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1031 # Canonical namespace
1033 $this->mNamespace
= $ns;
1034 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1035 # Ordinary namespace
1037 $this->mNamespace
= $ns;
1038 } elseif ( $this->getInterwikiLink( $p ) ) {
1041 $this->mInterwiki
= $p;
1043 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
1045 } elseif($this->mInterwiki
!= $wgLocalInterwiki) {
1053 # Redundant interwiki prefix to the local wiki
1054 if ( 0 == strcmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1055 $this->mInterwiki
= '';
1057 # We already know that some pages won't be in the database!
1059 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1060 $this->mArticleID
= 0;
1062 $f = strstr( $r, '#' );
1063 if ( false !== $f ) {
1064 $this->mFragment
= substr( $f, 1 );
1065 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1066 # remove whitespace again: prevents "Foo_bar_#"
1067 # becoming "Foo_bar_"
1068 $r = preg_replace( '/_*$/', '', $r );
1071 # Reject illegal characters.
1073 if( preg_match( $rxTc, $r ) ) {
1074 wfProfileOut( $fname );
1078 # "." and ".." conflict with the directories of those namesa
1079 if ( strpos( $r, '.' ) !== false &&
1080 ( $r === '.' ||
$r === '..' ||
1081 strpos( $r, './' ) === 0 ||
1082 strpos( $r, '../' ) === 0 ||
1083 strpos( $r, '/./' ) !== false ||
1084 strpos( $r, '/../' ) !== false ) )
1086 wfProfileOut( $fname );
1090 # We shouldn't need to query the DB for the size.
1091 #$maxSize = $dbr->textFieldSize( 'cur', 'cur_title' );
1092 if ( strlen( $r ) > 255 ) {
1096 # Initial capital letter
1097 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1098 $t = $wgContLang->ucfirst( $r );
1104 $this->mDbkeyform
= $t;
1105 $this->mUrlform
= wfUrlencode( $t );
1107 $this->mTextform
= str_replace( '_', ' ', $t );
1109 wfProfileOut( $fname );
1114 * Get a Title object associated with the talk page of this article
1115 * @return Title the object for the talk page
1118 function getTalkPage() {
1119 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1123 * Get a title object associated with the subject page of this
1126 * @return Title the object for the subject page
1129 function getSubjectPage() {
1130 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1134 * Get an array of Title objects linking to this Title
1135 * - Also stores the IDs in the link cache.
1137 * @param string $options may be FOR UPDATE
1138 * @return array the Title objects linking here
1141 function getLinksTo( $options = '' ) {
1142 global $wgLinkCache;
1143 $id = $this->getArticleID();
1146 $db =& wfGetDB( DB_MASTER
);
1148 $db =& wfGetDB( DB_SLAVE
);
1150 $cur = $db->tableName( 'cur' );
1151 $links = $db->tableName( 'links' );
1153 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
1154 $res = $db->query( $sql, 'Title::getLinksTo' );
1156 if ( $db->numRows( $res ) ) {
1157 while ( $row = $db->fetchObject( $res ) ) {
1158 if ( $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
) ) {
1159 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
1160 $retVal[] = $titleObj;
1164 $db->freeResult( $res );
1169 * Get an array of Title objects linking to this non-existent title.
1170 * - Also stores the IDs in the link cache.
1172 * @param string $options may be FOR UPDATE
1173 * @return array the Title objects linking here
1176 function getBrokenLinksTo( $options = '' ) {
1177 global $wgLinkCache;
1180 $db =& wfGetDB( DB_MASTER
);
1182 $db =& wfGetDB( DB_SLAVE
);
1184 $cur = $db->tableName( 'cur' );
1185 $brokenlinks = $db->tableName( 'brokenlinks' );
1186 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
1188 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
1189 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
1190 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
1192 if ( $db->numRows( $res ) ) {
1193 while ( $row = $db->fetchObject( $res ) ) {
1194 $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
1195 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
1196 $retVal[] = $titleObj;
1199 $db->freeResult( $res );
1204 * Get a list of URLs to purge from the Squid cache when this
1207 * @return array the URLs
1210 function getSquidURLs() {
1212 $this->getInternalURL(),
1213 $this->getInternalURL( 'action=history' )
1218 * Move this page without authentication
1219 * @param Title &$nt the new page Title
1222 function moveNoAuth( &$nt ) {
1223 return $this->moveTo( $nt, false );
1227 * Move a title to a new location
1228 * @param Title &$nt the new title
1229 * @param bool $auth indicates whether $wgUser's permissions
1231 * @return mixed true on success, message name on failure
1234 function moveTo( &$nt, $auth = true ) {
1235 if( !$this or !$nt ) {
1236 return 'badtitletext';
1239 $fname = 'Title::move';
1240 $oldid = $this->getArticleID();
1241 $newid = $nt->getArticleID();
1243 if ( strlen( $nt->getDBkey() ) < 1 ) {
1244 return 'articleexists';
1246 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
1247 ( '' == $this->getDBkey() ) ||
1248 ( '' != $this->getInterwiki() ) ||
1250 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
1251 ( '' == $nt->getDBkey() ) ||
1252 ( '' != $nt->getInterwiki() ) ) {
1253 return 'badarticleerror';
1256 if ( $auth && ( !$this->userCanEdit() ||
!$nt->userCanEdit() ) ) {
1257 return 'protectedpage';
1260 # The move is allowed only if (1) the target doesn't exist, or
1261 # (2) the target is a redirect to the source, and has no history
1262 # (so we can undo bad moves right after they're done).
1264 if ( 0 != $newid ) { # Target exists; check for validity
1265 if ( ! $this->isValidMoveTarget( $nt ) ) {
1266 return 'articleexists';
1268 $this->moveOverExistingRedirect( $nt );
1269 } else { # Target didn't exist, do normal move.
1270 $this->moveToNewTitle( $nt, $newid );
1273 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1275 $dbw =& wfGetDB( DB_MASTER
);
1276 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1277 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
1278 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1279 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1283 $oldnamespace = $this->getNamespace() & ~
1;
1284 $newnamespace = $nt->getNamespace() & ~
1;
1285 $oldtitle = $this->getDBkey();
1286 $newtitle = $nt->getDBkey();
1288 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1289 WatchedItem
::duplicateEntries( $this, $nt );
1292 # Update search engine
1293 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
1295 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
1302 * Move page to a title which is at present a redirect to the
1305 * @param Title &$nt the page to move to, which should currently
1309 /* private */ function moveOverExistingRedirect( &$nt ) {
1310 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1311 $fname = 'Title::moveOverExistingRedirect';
1312 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1314 $now = wfTimestampNow();
1315 $won = wfInvertTimestamp( $now );
1316 $newid = $nt->getArticleID();
1317 $oldid = $this->getArticleID();
1318 $dbw =& wfGetDB( DB_MASTER
);
1319 $links = $dbw->tableName( 'links' );
1321 # Change the name of the target page:
1322 $dbw->update( 'cur',
1324 'cur_touched' => $dbw->timestamp($now),
1325 'cur_namespace' => $nt->getNamespace(),
1326 'cur_title' => $nt->getDBkey()
1328 /* WHERE */ array( 'cur_id' => $oldid ),
1331 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1333 # Repurpose the old redirect. We don't save it to history since
1334 # by definition if we've got here it's rather uninteresting.
1336 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1337 $dbw->update( 'cur',
1339 'cur_touched' => $dbw->timestamp($now),
1340 'cur_timestamp' => $dbw->timestamp($now),
1341 'inverse_timestamp' => $won,
1342 'cur_namespace' => $this->getNamespace(),
1343 'cur_title' => $this->getDBkey(),
1344 'cur_text' => $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n",
1345 'cur_comment' => $comment,
1346 'cur_user' => $wgUser->getID(),
1347 'cur_minor_edit' => 0,
1349 'cur_restrictions' => '',
1350 'cur_user_text' => $wgUser->getName(),
1351 'cur_is_redirect' => 1,
1354 /* WHERE */ array( 'cur_id' => $newid ),
1358 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1360 # Fix the redundant names for the past revisions of the target page.
1361 # The redirect should have no old revisions.
1365 'old_namespace' => $nt->getNamespace(),
1366 'old_title' => $nt->getDBkey(),
1369 'old_namespace' => $this->getNamespace(),
1370 'old_title' => $this->getDBkey(),
1375 RecentChange
::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
1379 # Load titles and IDs
1380 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1381 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1384 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1385 $dbw->query( $sql, $fname );
1388 if ( count( $linksToOld ) ||
count( $linksToNew )) {
1389 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1392 # Insert links to old title
1393 foreach ( $linksToOld as $linkTitle ) {
1399 $id = $linkTitle->getArticleID();
1400 $sql .= "($id,$newid)";
1403 # Insert links to new title
1404 foreach ( $linksToNew as $linkTitle ) {
1410 $id = $linkTitle->getArticleID();
1411 $sql .= "($id, $oldid)";
1414 $dbw->query( $sql, DB_MASTER
, $fname );
1417 # Now, we record the link from the redirect to the new title.
1418 # It should have no other outgoing links...
1419 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1420 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1423 LinkCache
::linksccClearLinksTo( $oldid );
1424 LinkCache
::linksccClearLinksTo( $newid );
1427 if ( $wgUseSquid ) {
1428 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1429 $u = new SquidUpdate( $urls );
1435 * Move page to non-existing title.
1436 * @param Title &$nt the new Title
1437 * @param int &$newid set to be the new article ID
1440 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1441 global $wgUser, $wgLinkCache, $wgUseSquid;
1442 $fname = 'MovePageForm::moveToNewTitle';
1443 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1445 $newid = $nt->getArticleID();
1446 $oldid = $this->getArticleID();
1447 $dbw =& wfGetDB( DB_MASTER
);
1448 $now = $dbw->timestamp();
1449 $won = wfInvertTimestamp( wfTimestamp(TS_MW
,$now) );
1454 $dbw->update( 'cur',
1456 'cur_touched' => $now,
1457 'cur_namespace' => $nt->getNamespace(),
1458 'cur_title' => $nt->getDBkey()
1460 /* WHERE */ array( 'cur_id' => $oldid ),
1464 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1467 $dbw->insert( 'cur', array(
1468 'cur_id' => $dbw->nextSequenceValue('cur_cur_id_seq'),
1469 'cur_namespace' => $this->getNamespace(),
1470 'cur_title' => $this->getDBkey(),
1471 'cur_comment' => $comment,
1472 'cur_user' => $wgUser->getID(),
1473 'cur_user_text' => $wgUser->getName(),
1474 'cur_timestamp' => $now,
1475 'inverse_timestamp' => $won,
1476 'cur_touched' => $now,
1477 'cur_is_redirect' => 1,
1478 'cur_random' => $rand,
1480 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1482 $newid = $dbw->insertId();
1483 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1485 # Rename old entries
1489 'old_namespace' => $nt->getNamespace(),
1490 'old_title' => $nt->getDBkey()
1493 'old_namespace' => $this->getNamespace(),
1494 'old_title' => $this->getDBkey()
1499 RecentChange
::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1501 # Purge squid and linkscc as per article creation
1502 Article
::onArticleCreate( $nt );
1504 # Any text links to the old title must be reassigned to the redirect
1505 $dbw->update( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1506 LinkCache
::linksccClearLinksTo( $oldid );
1508 # Record the just-created redirect's linking to the page
1509 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1511 # Non-existent target may have had broken links to it; these must
1512 # now be removed and made into good links.
1513 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1514 $update->fixBrokenLinks();
1516 # Purge old title from squid
1517 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1518 $titles = $nt->getLinksTo();
1519 if ( $wgUseSquid ) {
1520 $urls = $this->getSquidURLs();
1521 foreach ( $titles as $linkTitle ) {
1522 $urls[] = $linkTitle->getInternalURL();
1524 $u = new SquidUpdate( $urls );
1530 * Checks if $this can be moved to a given Title
1531 * - Selects for update, so don't call it unless you mean business
1533 * @param Title &$nt the new title to check
1536 function isValidMoveTarget( $nt ) {
1537 $fname = 'Title::isValidMoveTarget';
1538 $dbw =& wfGetDB( DB_MASTER
);
1541 $id = $nt->getArticleID();
1542 $obj = $dbw->selectRow( 'cur', array( 'cur_is_redirect','cur_text' ),
1543 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1545 if ( !$obj ||
0 == $obj->cur_is_redirect
) {
1550 # Does the redirect point to the source?
1551 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text
, $m ) ) {
1552 $redirTitle = Title
::newFromText( $m[1] );
1553 if( !is_object( $redirTitle ) ||
1554 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1559 # Does the article have a history?
1560 $row = $dbw->selectRow( 'old', array( 'old_id' ),
1562 'old_namespace' => $nt->getNamespace(),
1563 'old_title' => $nt->getDBkey()
1564 ), $fname, 'FOR UPDATE'
1567 # Return true if there was no history
1568 return $row === false;
1572 * Create a redirect; fails if the title already exists; does
1575 * @param Title $dest the destination of the redirect
1576 * @param string $comment the comment string describing the move
1577 * @return bool true on success
1580 function createRedirect( $dest, $comment ) {
1582 if ( $this->getArticleID() ) {
1586 $fname = 'Title::createRedirect';
1587 $dbw =& wfGetDB( DB_MASTER
);
1588 $now = wfTimestampNow();
1589 $won = wfInvertTimestamp( $now );
1590 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1592 $dbw->insert( 'cur', array(
1593 'cur_id' => $seqVal,
1594 'cur_namespace' => $this->getNamespace(),
1595 'cur_title' => $this->getDBkey(),
1596 'cur_comment' => $comment,
1597 'cur_user' => $wgUser->getID(),
1598 'cur_user_text' => $wgUser->getName(),
1599 'cur_timestamp' => $now,
1600 'inverse_timestamp' => $won,
1601 'cur_touched' => $now,
1602 'cur_is_redirect' => 1,
1604 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1606 $newid = $dbw->insertId();
1607 $this->resetArticleID( $newid );
1610 if ( $dest->getArticleID() ) {
1611 $dbw->insert( 'links',
1613 'l_to' => $dest->getArticleID(),
1618 $dbw->insert( 'brokenlinks',
1620 'bl_to' => $dest->getPrefixedDBkey(),
1626 Article
::onArticleCreate( $this );
1631 * Get categories to which this Title belongs and return an array of
1632 * categories' names.
1634 * @return array an array of parents in the form:
1635 * $parent => $currentarticle
1638 function getParentCategories() {
1639 global $wgContLang,$wgUser;
1641 $titlekey = $this->getArticleId();
1642 $sk =& $wgUser->getSkin();
1644 $dbr =& wfGetDB( DB_SLAVE
);
1645 $categorylinks = $dbr->tableName( 'categorylinks' );
1648 $sql = "SELECT * FROM $categorylinks"
1649 ." WHERE cl_from='$titlekey'"
1650 ." AND cl_from <> '0'"
1651 ." ORDER BY cl_sortkey";
1653 $res = $dbr->query ( $sql ) ;
1655 if($dbr->numRows($res) > 0) {
1656 while ( $x = $dbr->fetchObject ( $res ) )
1657 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1658 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1659 $dbr->freeResult ( $res ) ;
1667 * Get a tree of parent categories
1668 * @param array $children an array with the children in the keys, to check for circular refs
1672 function getParentCategoryTree( $children = array() ) {
1673 $parents = $this->getParentCategories();
1675 if($parents != '') {
1676 foreach($parents as $parent => $current)
1678 if ( array_key_exists( $parent, $children ) ) {
1679 # Circular reference
1680 $stack[$parent] = array();
1682 $nt = Title
::newFromText($parent);
1683 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
1694 * Get an associative array for selecting this title from
1700 function curCond() {
1701 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1705 * Get an associative array for selecting this title from the
1711 function oldCond() {
1712 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);
1716 * Get the revision ID of the previous revision
1718 * @param integer $revision Revision ID. Get the revision that was before this one.
1719 * @return interger $oldrevision|false
1721 function getPreviousRevisionID( $revision ) {
1722 $dbr =& wfGetDB( DB_SLAVE
);
1723 return $dbr->selectField( 'old', 'old_id',
1724 'old_title=' . $dbr->addQuotes( $this->getDBkey() ) .
1725 ' AND old_namespace=' . IntVal( $this->getNamespace() ) .
1726 ' AND old_id<' . IntVal( $revision ) . ' ORDER BY old_id DESC' );
1730 * Get the revision ID of the next revision
1732 * @param integer $revision Revision ID. Get the revision that was after this one.
1733 * @return interger $oldrevision|false
1735 function getNextRevisionID( $revision ) {
1736 $dbr =& wfGetDB( DB_SLAVE
);
1737 return $dbr->selectField( 'old', 'old_id',
1738 'old_title=' . $dbr->addQuotes( $this->getDBkey() ) .
1739 ' AND old_namespace=' . IntVal( $this->getNamespace() ) .
1740 ' AND old_id>' . IntVal( $revision ) . ' ORDER BY old_id' );