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 * Set the namespace index
471 * @param int $n the namespace index, one of the NS_xxxx constants
474 function setNamespace( $n ) { $this->mNamespace
= IntVal( $n ); }
476 * Get the interwiki prefix (or null string)
480 function getInterwiki() { return $this->mInterwiki
; }
482 * Get the Title fragment (i.e. the bit after the #)
486 function getFragment() { return $this->mFragment
; }
488 * Get the default namespace index, for when there is no namespace
492 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
495 * Get title for search index
496 * @return string a stripped-down title string ready for the
499 function getIndexTitle() {
500 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
504 * Get the prefixed database key form
505 * @return string the prefixed title, with underscores and
506 * any interwiki and namespace prefixes
509 function getPrefixedDBkey() {
510 $s = $this->prefix( $this->mDbkeyform
);
511 $s = str_replace( ' ', '_', $s );
516 * Get the prefixed title with spaces.
517 * This is the form usually used for display
518 * @return string the prefixed title, with spaces
521 function getPrefixedText() {
523 if ( empty( $this->mPrefixedText
) ) {
524 $s = $this->prefix( $this->mTextform
);
525 $s = str_replace( '_', ' ', $s );
526 $this->mPrefixedText
= $s;
528 return $this->mPrefixedText
;
532 * Get the prefixed title with spaces, plus any fragment
533 * (part beginning with '#')
534 * @return string the prefixed title, with spaces and
535 * the fragment, including '#'
538 function getFullText() {
540 $text = $this->getPrefixedText();
541 if( '' != $this->mFragment
) {
542 $text .= '#' . $this->mFragment
;
548 * Get a URL-encoded title (not an actual URL) including interwiki
549 * @return string the URL-encoded form
552 function getPrefixedURL() {
553 $s = $this->prefix( $this->mDbkeyform
);
554 $s = str_replace( ' ', '_', $s );
556 $s = wfUrlencode ( $s ) ;
558 # Cleaning up URL to make it look nice -- is this safe?
559 $s = preg_replace( '/%3[Aa]/', ':', $s );
560 $s = preg_replace( '/%2[Ff]/', '/', $s );
561 $s = str_replace( '%28', '(', $s );
562 $s = str_replace( '%29', ')', $s );
568 * Get a real URL referring to this title, with interwiki link and
571 * @param string $query an optional query string, not used
572 * for interwiki links
573 * @return string the URL
576 function getFullURL( $query = '' ) {
577 global $wgContLang, $wgArticlePath, $wgServer, $wgScript;
579 if ( '' == $this->mInterwiki
) {
581 return $wgServer . $this->getLocalUrl( $query );
583 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
584 $namespace = $wgContLang->getNsText( $this->mNamespace
);
585 if ( '' != $namespace ) {
586 # Can this actually happen? Interwikis shouldn't be parsed.
589 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
590 if ( '' != $this->mFragment
) {
591 $url .= '#' . $this->mFragment
;
601 die( 'Call to obsolete obsolete function Title::getURL()' );
605 * Get a URL with no fragment or server name
606 * @param string $query an optional query string; if not specified,
607 * $wgArticlePath will be used.
608 * @return string the URL
611 function getLocalURL( $query = '' ) {
612 global $wgLang, $wgArticlePath, $wgScript;
614 if ( $this->isExternal() ) {
615 return $this->getFullURL();
618 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
619 if ( $query == '' ) {
620 $url = str_replace( '$1', $dbkey, $wgArticlePath );
622 if ( $query == '-' ) {
625 if ( $wgScript != '' ) {
626 $url = "{$wgScript}?title={$dbkey}&{$query}";
629 $url = "/{$dbkey}?{$query}";
636 * Get an HTML-escaped version of the URL form, suitable for
637 * using in a link, without a server name or fragment
638 * @param string $query an optional query string
639 * @return string the URL
642 function escapeLocalURL( $query = '' ) {
643 return htmlspecialchars( $this->getLocalURL( $query ) );
647 * Get an HTML-escaped version of the URL form, suitable for
648 * using in a link, including the server name and fragment
650 * @return string the URL
651 * @param string $query an optional query string
654 function escapeFullURL( $query = '' ) {
655 return htmlspecialchars( $this->getFullURL( $query ) );
659 * Get the URL form for an internal link.
660 * - Used in various Squid-related code, in case we have a different
661 * internal hostname for the server from the exposed one.
663 * @param string $query an optional query string
664 * @return string the URL
667 function getInternalURL( $query = '' ) {
668 global $wgInternalServer;
669 return $wgInternalServer . $this->getLocalURL( $query );
673 * Get the edit URL for this Title
674 * @return string the URL, or a null string if this is an
678 function getEditURL() {
679 global $wgServer, $wgScript;
681 if ( '' != $this->mInterwiki
) { return ''; }
682 $s = $this->getLocalURL( 'action=edit' );
688 * Get the HTML-escaped displayable text form.
689 * Used for the title field in <a> tags.
690 * @return string the text, including any prefixes
693 function getEscapedText() {
694 return htmlspecialchars( $this->getPrefixedText() );
698 * Is this Title interwiki?
702 function isExternal() { return ( '' != $this->mInterwiki
); }
705 * Does the title correspond to a protected article?
709 function isProtected() {
710 if ( -1 == $this->mNamespace
) { return true; }
711 $a = $this->getRestrictions();
712 if ( in_array( 'sysop', $a ) ) { return true; }
717 * Is the page a log page, i.e. one where the history is messed up by
718 * LogPage.php? This used to be used for suppressing diff links in
719 * recent changes, but now that's done by setting a flag in the
720 * recentchanges table. Hence, this probably is no longer used.
726 if ( $this->mNamespace
!= Namespace::getWikipedia() ) {
729 if ( ( 0 == strcmp( wfMsg( 'uploadlogpage' ), $this->mDbkeyform
) ) ||
730 ( 0 == strcmp( wfMsg( 'dellogpage' ), $this->mDbkeyform
) ) ) {
737 * Is $wgUser is watching this page?
741 function userIsWatching() {
744 if ( -1 == $this->mNamespace
) { return false; }
745 if ( 0 == $wgUser->getID() ) { return false; }
747 return $wgUser->isWatched( $this );
751 * Can $wgUser edit this page?
755 function userCanEdit() {
757 if( NS_SPECIAL
== $this->mNamespace
) {
760 if( NS_MEDIAWIKI
== $this->mNamespace
&&
761 !$wgUser->isAllowed('editinterface') ) {
764 if( $this->mDbkeyform
== '_' ) {
765 # FIXME: Is this necessary? Shouldn't be allowed anyway...
769 # protect global styles and js
770 if ( NS_MEDIAWIKI
== $this->mNamespace
771 && preg_match("/\\.(css|js)$/", $this->mTextform
)
772 && !$wgUser->isAllowed('editinterface') ) {
776 # protect css/js subpages of user pages
777 # XXX: this might be better using restrictions
778 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
779 if( NS_USER
== $this->mNamespace
780 && preg_match("/\\.(css|js)$/", $this->mTextform
)
781 && !$wgUser->isAllowed('editinterface')
782 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
786 foreach( $this->getRestrictions() as $right ) {
787 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
795 * Can $wgUser read this page?
799 function userCanRead() {
802 if( $wgUser->isAllowed('read') ) {
805 global $wgWhitelistRead;
807 /** If anon users can create an account,
808 they need to reach the login page first! */
809 if( $wgUser->isAllowed( 'createaccount' )
810 && $this->mId
== NS_SPECIAL
811 && $this->getText() == 'Userlogin' ) {
815 /** some pages are explicitly allowed */
816 $name = $this->getPrefixedText();
817 if( in_array( $name, $wgWhitelistRead ) ) {
821 # Compatibility with old settings
822 if( $this->getNamespace() == NS_MAIN
) {
823 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
832 * Is this a .css or .js subpage of a user page?
836 function isCssJsSubpage() {
837 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
840 * Is this a .css subpage of a user page?
844 function isCssSubpage() {
845 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
848 * Is this a .js subpage of a user page?
852 function isJsSubpage() {
853 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
856 * Protect css/js subpages of user pages: can $wgUser edit
860 * @todo XXX: this might be better using restrictions
863 function userCanEditCssJsSubpage() {
865 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
869 * Accessor/initialisation for mRestrictions
870 * @return array the array of groups allowed to edit this article
873 function getRestrictions() {
874 $id = $this->getArticleID();
875 if ( 0 == $id ) { return array(); }
877 if ( ! $this->mRestrictionsLoaded
) {
878 $dbr =& wfGetDB( DB_SLAVE
);
879 $res = $dbr->selectField( 'cur', 'cur_restrictions', 'cur_id='.$id );
880 $this->mRestrictions
= explode( ',', trim( $res ) );
881 $this->mRestrictionsLoaded
= true;
883 return $this->mRestrictions
;
887 * Is there a version of this page in the deletion archive?
888 * @return int the number of archived revisions
891 function isDeleted() {
892 $fname = 'Title::isDeleted';
893 $dbr =& wfGetDB( DB_SLAVE
);
894 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
895 'ar_title' => $this->getDBkey() ), $fname );
900 * Get the article ID for this Title from the link cache,
901 * adding it if necessary
902 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
907 function getArticleID( $flags = 0 ) {
910 if ( $flags & GAID_FOR_UPDATE
) {
911 $oldUpdate = $wgLinkCache->forUpdate( true );
912 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
913 $wgLinkCache->forUpdate( $oldUpdate );
915 if ( -1 == $this->mArticleID
) {
916 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
919 return $this->mArticleID
;
923 * This clears some fields in this object, and clears any associated
924 * keys in the "bad links" section of $wgLinkCache.
926 * - This is called from Article::insertNewArticle() to allow
927 * loading of the new cur_id. It's also called from
928 * Article::doDeleteArticle()
930 * @param int $newid the new Article ID
933 function resetArticleID( $newid ) {
935 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
937 if ( 0 == $newid ) { $this->mArticleID
= -1; }
938 else { $this->mArticleID
= $newid; }
939 $this->mRestrictionsLoaded
= false;
940 $this->mRestrictions
= array();
944 * Updates cur_touched for this page; called from LinksUpdate.php
945 * @return bool true if the update succeded
948 function invalidateCache() {
949 $now = wfTimestampNow();
950 $dbw =& wfGetDB( DB_MASTER
);
951 $success = $dbw->update( 'cur',
953 'cur_touched' => $dbw->timestamp()
954 ), array( /* WHERE */
955 'cur_namespace' => $this->getNamespace() ,
956 'cur_title' => $this->getDBkey()
957 ), 'Title::invalidateCache'
963 * Prefix some arbitrary text with the namespace or interwiki prefix
966 * @param string $name the text
967 * @return string the prefixed text
970 /* private */ function prefix( $name ) {
974 if ( '' != $this->mInterwiki
) {
975 $p = $this->mInterwiki
. ':';
977 if ( 0 != $this->mNamespace
) {
978 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
984 * Secure and split - main initialisation function for this object
986 * Assumes that mDbkeyform has been set, and is urldecoded
987 * and uses underscores, but not otherwise munged. This function
988 * removes illegal characters, splits off the interwiki and
989 * namespace prefixes, sets the other forms, and canonicalizes
991 * @return bool true on success
994 /* private */ function secureAndSplit()
996 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
997 $fname = 'Title::secureAndSplit';
998 wfProfileIn( $fname );
1000 static $imgpre = false;
1001 static $rxTc = false;
1004 if ( $imgpre === false ) {
1005 $imgpre = ':' . $wgContLang->getNsText( Namespace::getImage() ) . ':';
1006 # % is needed as well
1007 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/';
1010 $this->mInterwiki
= $this->mFragment
= '';
1011 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1013 # Clean up whitespace
1015 $t = preg_replace( "/[\\s_]+/", '_', $this->mDbkeyform
);
1016 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
1019 wfProfileOut( $fname );
1023 global $wgUseLatin1;
1024 if( !$wgUseLatin1 && false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1025 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1026 wfProfileOut( $fname );
1030 $this->mDbkeyform
= $t;
1034 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
1035 $t = substr( $t, 1 );
1038 # Initial colon indicating main namespace
1039 if ( ':' == $t{0} ) {
1040 $r = substr( $t, 1 );
1041 $this->mNamespace
= NS_MAIN
;
1043 # Namespace or interwiki prefix
1044 if ( preg_match( "/^(.+?)_*:_*(.*)$/", $t, $m ) ) {
1045 #$p = strtolower( $m[1] );
1047 $lowerNs = strtolower( $p );
1048 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1049 # Canonical namespace
1051 $this->mNamespace
= $ns;
1052 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1053 # Ordinary namespace
1055 $this->mNamespace
= $ns;
1056 } elseif ( $this->getInterwikiLink( $p ) ) {
1059 $this->mInterwiki
= $p;
1061 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
1063 } elseif($this->mInterwiki
!= $wgLocalInterwiki) {
1071 # Redundant interwiki prefix to the local wiki
1072 if ( 0 == strcmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1073 $this->mInterwiki
= '';
1075 # We already know that some pages won't be in the database!
1077 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1078 $this->mArticleID
= 0;
1080 $f = strstr( $r, '#' );
1081 if ( false !== $f ) {
1082 $this->mFragment
= substr( $f, 1 );
1083 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1084 # remove whitespace again: prevents "Foo_bar_#"
1085 # becoming "Foo_bar_"
1086 $r = preg_replace( '/_*$/', '', $r );
1089 # Reject illegal characters.
1091 if( preg_match( $rxTc, $r ) ) {
1092 wfProfileOut( $fname );
1096 # "." and ".." conflict with the directories of those namesa
1097 if ( strpos( $r, '.' ) !== false &&
1098 ( $r === '.' ||
$r === '..' ||
1099 strpos( $r, './' ) === 0 ||
1100 strpos( $r, '../' ) === 0 ||
1101 strpos( $r, '/./' ) !== false ||
1102 strpos( $r, '/../' ) !== false ) )
1104 wfProfileOut( $fname );
1108 # We shouldn't need to query the DB for the size.
1109 #$maxSize = $dbr->textFieldSize( 'cur', 'cur_title' );
1110 if ( strlen( $r ) > 255 ) {
1114 # Initial capital letter
1115 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1116 $t = $wgContLang->ucfirst( $r );
1122 $this->mDbkeyform
= $t;
1123 $this->mUrlform
= wfUrlencode( $t );
1125 $this->mTextform
= str_replace( '_', ' ', $t );
1127 wfProfileOut( $fname );
1132 * Get a Title object associated with the talk page of this article
1133 * @return Title the object for the talk page
1136 function getTalkPage() {
1137 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1141 * Get a title object associated with the subject page of this
1144 * @return Title the object for the subject page
1147 function getSubjectPage() {
1148 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1152 * Get an array of Title objects linking to this Title
1153 * - Also stores the IDs in the link cache.
1155 * @param string $options may be FOR UPDATE
1156 * @return array the Title objects linking here
1159 function getLinksTo( $options = '' ) {
1160 global $wgLinkCache;
1161 $id = $this->getArticleID();
1164 $db =& wfGetDB( DB_MASTER
);
1166 $db =& wfGetDB( DB_SLAVE
);
1168 $cur = $db->tableName( 'cur' );
1169 $links = $db->tableName( 'links' );
1171 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
1172 $res = $db->query( $sql, 'Title::getLinksTo' );
1174 if ( $db->numRows( $res ) ) {
1175 while ( $row = $db->fetchObject( $res ) ) {
1176 if ( $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
) ) {
1177 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
1178 $retVal[] = $titleObj;
1182 $db->freeResult( $res );
1187 * Get an array of Title objects linking to this non-existent title.
1188 * - Also stores the IDs in the link cache.
1190 * @param string $options may be FOR UPDATE
1191 * @return array the Title objects linking here
1194 function getBrokenLinksTo( $options = '' ) {
1195 global $wgLinkCache;
1198 $db =& wfGetDB( DB_MASTER
);
1200 $db =& wfGetDB( DB_SLAVE
);
1202 $cur = $db->tableName( 'cur' );
1203 $brokenlinks = $db->tableName( 'brokenlinks' );
1204 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
1206 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
1207 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
1208 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
1210 if ( $db->numRows( $res ) ) {
1211 while ( $row = $db->fetchObject( $res ) ) {
1212 $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
1213 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
1214 $retVal[] = $titleObj;
1217 $db->freeResult( $res );
1222 * Get a list of URLs to purge from the Squid cache when this
1225 * @return array the URLs
1228 function getSquidURLs() {
1230 $this->getInternalURL(),
1231 $this->getInternalURL( 'action=history' )
1236 * Move this page without authentication
1237 * @param Title &$nt the new page Title
1240 function moveNoAuth( &$nt ) {
1241 return $this->moveTo( $nt, false );
1245 * Move a title to a new location
1246 * @param Title &$nt the new title
1247 * @param bool $auth indicates whether $wgUser's permissions
1249 * @return mixed true on success, message name on failure
1252 function moveTo( &$nt, $auth = true ) {
1253 if( !$this or !$nt ) {
1254 return 'badtitletext';
1257 $fname = 'Title::move';
1258 $oldid = $this->getArticleID();
1259 $newid = $nt->getArticleID();
1261 if ( strlen( $nt->getDBkey() ) < 1 ) {
1262 return 'articleexists';
1264 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
1265 ( '' == $this->getDBkey() ) ||
1266 ( '' != $this->getInterwiki() ) ||
1268 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
1269 ( '' == $nt->getDBkey() ) ||
1270 ( '' != $nt->getInterwiki() ) ) {
1271 return 'badarticleerror';
1274 if ( $auth && ( !$this->userCanEdit() ||
!$nt->userCanEdit() ) ) {
1275 return 'protectedpage';
1278 # The move is allowed only if (1) the target doesn't exist, or
1279 # (2) the target is a redirect to the source, and has no history
1280 # (so we can undo bad moves right after they're done).
1282 if ( 0 != $newid ) { # Target exists; check for validity
1283 if ( ! $this->isValidMoveTarget( $nt ) ) {
1284 return 'articleexists';
1286 $this->moveOverExistingRedirect( $nt );
1287 } else { # Target didn't exist, do normal move.
1288 $this->moveToNewTitle( $nt, $newid );
1291 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1293 $dbw =& wfGetDB( DB_MASTER
);
1294 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1295 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
1296 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1297 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1301 $oldnamespace = $this->getNamespace() & ~
1;
1302 $newnamespace = $nt->getNamespace() & ~
1;
1303 $oldtitle = $this->getDBkey();
1304 $newtitle = $nt->getDBkey();
1306 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1307 WatchedItem
::duplicateEntries( $this, $nt );
1310 # Update search engine
1311 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
1313 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
1320 * Move page to a title which is at present a redirect to the
1323 * @param Title &$nt the page to move to, which should currently
1327 /* private */ function moveOverExistingRedirect( &$nt ) {
1328 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1329 $fname = 'Title::moveOverExistingRedirect';
1330 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1332 $now = wfTimestampNow();
1333 $won = wfInvertTimestamp( $now );
1334 $newid = $nt->getArticleID();
1335 $oldid = $this->getArticleID();
1336 $dbw =& wfGetDB( DB_MASTER
);
1337 $links = $dbw->tableName( 'links' );
1339 # Change the name of the target page:
1340 $dbw->update( 'cur',
1342 'cur_touched' => $dbw->timestamp($now),
1343 'cur_namespace' => $nt->getNamespace(),
1344 'cur_title' => $nt->getDBkey()
1346 /* WHERE */ array( 'cur_id' => $oldid ),
1349 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1351 # Repurpose the old redirect. We don't save it to history since
1352 # by definition if we've got here it's rather uninteresting.
1354 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1355 $dbw->update( 'cur',
1357 'cur_touched' => $dbw->timestamp($now),
1358 'cur_timestamp' => $dbw->timestamp($now),
1359 'inverse_timestamp' => $won,
1360 'cur_namespace' => $this->getNamespace(),
1361 'cur_title' => $this->getDBkey(),
1362 'cur_text' => $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n",
1363 'cur_comment' => $comment,
1364 'cur_user' => $wgUser->getID(),
1365 'cur_minor_edit' => 0,
1367 'cur_restrictions' => '',
1368 'cur_user_text' => $wgUser->getName(),
1369 'cur_is_redirect' => 1,
1372 /* WHERE */ array( 'cur_id' => $newid ),
1376 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1378 # Fix the redundant names for the past revisions of the target page.
1379 # The redirect should have no old revisions.
1383 'old_namespace' => $nt->getNamespace(),
1384 'old_title' => $nt->getDBkey(),
1387 'old_namespace' => $this->getNamespace(),
1388 'old_title' => $this->getDBkey(),
1393 RecentChange
::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
1397 # Load titles and IDs
1398 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1399 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1402 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1403 $dbw->query( $sql, $fname );
1406 if ( count( $linksToOld ) ||
count( $linksToNew )) {
1407 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1410 # Insert links to old title
1411 foreach ( $linksToOld as $linkTitle ) {
1417 $id = $linkTitle->getArticleID();
1418 $sql .= "($id,$newid)";
1421 # Insert links to new title
1422 foreach ( $linksToNew as $linkTitle ) {
1428 $id = $linkTitle->getArticleID();
1429 $sql .= "($id, $oldid)";
1432 $dbw->query( $sql, DB_MASTER
, $fname );
1435 # Now, we record the link from the redirect to the new title.
1436 # It should have no other outgoing links...
1437 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1438 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1441 LinkCache
::linksccClearLinksTo( $oldid );
1442 LinkCache
::linksccClearLinksTo( $newid );
1445 if ( $wgUseSquid ) {
1446 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1447 $u = new SquidUpdate( $urls );
1453 * Move page to non-existing title.
1454 * @param Title &$nt the new Title
1455 * @param int &$newid set to be the new article ID
1458 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1459 global $wgUser, $wgLinkCache, $wgUseSquid;
1460 $fname = 'MovePageForm::moveToNewTitle';
1461 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1463 $newid = $nt->getArticleID();
1464 $oldid = $this->getArticleID();
1465 $dbw =& wfGetDB( DB_MASTER
);
1466 $now = $dbw->timestamp();
1467 $won = wfInvertTimestamp( wfTimestamp(TS_MW
,$now) );
1472 $dbw->update( 'cur',
1474 'cur_touched' => $now,
1475 'cur_namespace' => $nt->getNamespace(),
1476 'cur_title' => $nt->getDBkey()
1478 /* WHERE */ array( 'cur_id' => $oldid ),
1482 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1485 $dbw->insert( 'cur', array(
1486 'cur_id' => $dbw->nextSequenceValue('cur_cur_id_seq'),
1487 'cur_namespace' => $this->getNamespace(),
1488 'cur_title' => $this->getDBkey(),
1489 'cur_comment' => $comment,
1490 'cur_user' => $wgUser->getID(),
1491 'cur_user_text' => $wgUser->getName(),
1492 'cur_timestamp' => $now,
1493 'inverse_timestamp' => $won,
1494 'cur_touched' => $now,
1495 'cur_is_redirect' => 1,
1496 'cur_random' => $rand,
1498 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1500 $newid = $dbw->insertId();
1501 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1503 # Rename old entries
1507 'old_namespace' => $nt->getNamespace(),
1508 'old_title' => $nt->getDBkey()
1511 'old_namespace' => $this->getNamespace(),
1512 'old_title' => $this->getDBkey()
1517 RecentChange
::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1519 # Purge squid and linkscc as per article creation
1520 Article
::onArticleCreate( $nt );
1522 # Any text links to the old title must be reassigned to the redirect
1523 $dbw->update( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1524 LinkCache
::linksccClearLinksTo( $oldid );
1526 # Record the just-created redirect's linking to the page
1527 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1529 # Non-existent target may have had broken links to it; these must
1530 # now be removed and made into good links.
1531 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1532 $update->fixBrokenLinks();
1534 # Purge old title from squid
1535 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1536 $titles = $nt->getLinksTo();
1537 if ( $wgUseSquid ) {
1538 $urls = $this->getSquidURLs();
1539 foreach ( $titles as $linkTitle ) {
1540 $urls[] = $linkTitle->getInternalURL();
1542 $u = new SquidUpdate( $urls );
1548 * Checks if $this can be moved to a given Title
1549 * - Selects for update, so don't call it unless you mean business
1551 * @param Title &$nt the new title to check
1554 function isValidMoveTarget( $nt ) {
1555 $fname = 'Title::isValidMoveTarget';
1556 $dbw =& wfGetDB( DB_MASTER
);
1559 $id = $nt->getArticleID();
1560 $obj = $dbw->selectRow( 'cur', array( 'cur_is_redirect','cur_text' ),
1561 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1563 if ( !$obj ||
0 == $obj->cur_is_redirect
) {
1568 # Does the redirect point to the source?
1569 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text
, $m ) ) {
1570 $redirTitle = Title
::newFromText( $m[1] );
1571 if( !is_object( $redirTitle ) ||
1572 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1577 # Does the article have a history?
1578 $row = $dbw->selectRow( 'old', array( 'old_id' ),
1580 'old_namespace' => $nt->getNamespace(),
1581 'old_title' => $nt->getDBkey()
1582 ), $fname, 'FOR UPDATE'
1585 # Return true if there was no history
1586 return $row === false;
1590 * Create a redirect; fails if the title already exists; does
1593 * @param Title $dest the destination of the redirect
1594 * @param string $comment the comment string describing the move
1595 * @return bool true on success
1598 function createRedirect( $dest, $comment ) {
1600 if ( $this->getArticleID() ) {
1604 $fname = 'Title::createRedirect';
1605 $dbw =& wfGetDB( DB_MASTER
);
1606 $now = wfTimestampNow();
1607 $won = wfInvertTimestamp( $now );
1608 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1610 $dbw->insert( 'cur', array(
1611 'cur_id' => $seqVal,
1612 'cur_namespace' => $this->getNamespace(),
1613 'cur_title' => $this->getDBkey(),
1614 'cur_comment' => $comment,
1615 'cur_user' => $wgUser->getID(),
1616 'cur_user_text' => $wgUser->getName(),
1617 'cur_timestamp' => $now,
1618 'inverse_timestamp' => $won,
1619 'cur_touched' => $now,
1620 'cur_is_redirect' => 1,
1622 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1624 $newid = $dbw->insertId();
1625 $this->resetArticleID( $newid );
1628 if ( $dest->getArticleID() ) {
1629 $dbw->insert( 'links',
1631 'l_to' => $dest->getArticleID(),
1636 $dbw->insert( 'brokenlinks',
1638 'bl_to' => $dest->getPrefixedDBkey(),
1644 Article
::onArticleCreate( $this );
1649 * Get categories to which this Title belongs and return an array of
1650 * categories' names.
1652 * @return array an array of parents in the form:
1653 * $parent => $currentarticle
1656 function getParentCategories() {
1657 global $wgContLang,$wgUser;
1659 $titlekey = $this->getArticleId();
1660 $sk =& $wgUser->getSkin();
1662 $dbr =& wfGetDB( DB_SLAVE
);
1663 $cur = $dbr->tableName( 'cur' );
1664 $categorylinks = $dbr->tableName( 'categorylinks' );
1667 $sql = "SELECT * FROM categorylinks"
1668 ." WHERE cl_from='$titlekey'"
1669 ." AND cl_from <> '0'"
1670 ." ORDER BY cl_sortkey";
1672 $res = $dbr->query ( $sql ) ;
1674 if($dbr->numRows($res) > 0) {
1675 while ( $x = $dbr->fetchObject ( $res ) )
1676 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1677 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1678 $dbr->freeResult ( $res ) ;
1686 * Go through all parent categories of this Title
1690 function getCategorieBrowser() {
1691 $parents = $this->getParentCategories();
1693 if($parents != '') {
1694 foreach($parents as $parent => $current)
1696 $nt = Title
::newFromText($parent);
1697 $stack[$parent] = $nt->getCategorieBrowser();
1707 * Get an associative array for selecting this title from
1713 function curCond() {
1714 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1718 * Get an associative array for selecting this title from the
1724 function oldCond() {
1725 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);
1729 * Get the revision ID of the previous revision
1731 * @param integer $revision Revision ID. Get the revision that was before this one.
1732 * @return interger $oldrevision|false
1734 function getPreviousRevisionID( $revision ) {
1735 $dbr =& wfGetDB( DB_SLAVE
);
1736 return $dbr->selectField( 'old', 'old_id',
1737 'old_title=' . $dbr->addQuotes( $this->getDBkey() ) .
1738 ' AND old_namespace=' . IntVal( $this->getNamespace() ) .
1739 ' AND old_id<' . IntVal( $revision ) . ' ORDER BY old_id DESC' );
1743 * Get the revision ID of the next revision
1745 * @param integer $revision Revision ID. Get the revision that was after this one.
1746 * @return interger $oldrevision|false
1748 function getNextRevisionID( $revision ) {
1749 $dbr =& wfGetDB( DB_SLAVE
);
1750 return $dbr->selectField( 'old', 'old_id',
1751 'old_title=' . $dbr->addQuotes( $this->getDBkey() ) .
1752 ' AND old_namespace=' . IntVal( $this->getNamespace() ) .
1753 ' AND old_id>' . IntVal( $revision ) . ' ORDER BY old_id' );