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() ) {
143 # check that length of title is < cur_title size
144 $dbr =& wfGetDB( DB_SLAVE
);
145 $maxSize = $dbr->textFieldSize( 'cur', 'cur_title' );
146 if ( $maxSize != -1 && strlen( $t->mDbkeyform
) > $maxSize ) {
157 * Create a new Title from an article ID
158 * @todo This is inefficiently implemented, the cur row is requested
159 * but not used for anything else
160 * @param int $id the cur_id corresponding to the Title to create
161 * @return Title the new object, or NULL on an error
164 /* static */ function newFromID( $id ) {
165 $fname = 'Title::newFromID';
166 $dbr =& wfGetDB( DB_SLAVE
);
167 $row = $dbr->getArray( 'cur', array( 'cur_namespace', 'cur_title' ),
168 array( 'cur_id' => $id ), $fname );
169 if ( $row !== false ) {
170 $title = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
178 * Create a new Title from a namespace index and a DB key.
179 * It's assumed that $ns and $title are *valid*, for instance when
180 * they came directly from the database or a special page name.
181 * @param int $ns the namespace of the article
182 * @param string $title the unprefixed database key form
183 * @return Title the new object
187 /* static */ function &makeTitle( $ns, $title ) {
191 $t->mNamespace
= IntVal( $ns );
192 $t->mDbkeyform
= $title;
193 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
194 $t->mUrlform
= wfUrlencode( $title );
195 $t->mTextform
= str_replace( '_', ' ', $title );
200 * Create a new Title frrom a namespace index and a DB key.
201 * The parameters will be checked for validity, which is a bit slower
202 * than makeTitle() but safer for user-provided data.
203 * @param int $ns the namespace of the article
204 * @param string $title the database key form
205 * @return Title the new object, or NULL on an error
209 /* static */ function makeTitleSafe( $ns, $title ) {
211 $t->mDbkeyform
= Title
::makeName( $ns, $title );
212 if( $t->secureAndSplit() ) {
220 * Create a new Title for the Main Page
222 * @return Title the new object
225 /* static */ function newMainPage() {
226 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
230 * Create a new Title for a redirect
231 * @param string $text the redirect title text
232 * @return Title the new object, or NULL if the text is not a
237 /* static */ function newFromRedirect( $text ) {
240 if ( $wgMwRedir->matchStart( $text ) ) {
241 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/', $text, $m ) ) {
242 # categories are escaped using : for example one can enter:
243 # #REDIRECT [[:Category:Music]]. Need to remove it.
244 if ( substr($m[1],0,1) == ':') {
245 # We don't want to keep the ':'
246 $m[1] = substr( $m[1], 1 );
249 $rt = Title
::newFromText( $m[1] );
250 # Disallow redirects to Special:Userlogout
251 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
259 #----------------------------------------------------------------------------
261 #----------------------------------------------------------------------------
264 * Get the prefixed DB key associated with an ID
265 * @param int $id the cur_id of the article
266 * @return Title an object representing the article, or NULL
267 * if no such article was found
271 /* static */ function nameOf( $id ) {
272 $fname = 'Title::nameOf';
273 $dbr =& wfGetDB( DB_SLAVE
);
275 $s = $dbr->getArray( 'cur', array( 'cur_namespace','cur_title' ), array( 'cur_id' => $id ), $fname );
276 if ( $s === false ) { return NULL; }
278 $n = Title
::makeName( $s->cur_namespace
, $s->cur_title
);
283 * Get a regex character class describing the legal characters in a link
284 * @return string the list of characters, not delimited
288 /* static */ function legalChars() {
289 # Missing characters:
290 # * []|# Needed for link syntax
291 # * % and + are corrupted by Apache when they appear in the path
293 # % seems to work though
295 # The problem with % is that URLs are double-unescaped: once by Apache's
296 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
297 # Our code does not double-escape to compensate for this, indeed double escaping
298 # would break if the double-escaped title was passed in the query string
299 # rather than the path. This is a minor security issue because articles can be
300 # created such that they are hard to view or edit. -- TS
302 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
303 # this breaks interlanguage links
305 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF";
310 * Get a string representation of a title suitable for
311 * including in a search index
313 * @param int $ns a namespace index
314 * @param string $title text-form main part
315 * @return string a stripped-down title string ready for the
318 /* static */ function indexTitle( $ns, $title ) {
319 global $wgDBminWordLen, $wgContLang;
320 require_once( 'SearchEngine.php' );
322 $lc = SearchEngine
::legalSearchChars() . '&#;';
323 $t = $wgContLang->stripForSearch( $title );
324 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
325 $t = strtolower( $t );
328 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
329 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
331 $t = preg_replace( "/\\s+/", ' ', $t );
333 if ( $ns == Namespace::getImage() ) {
334 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
340 * Make a prefixed DB key from a DB key and a namespace index
341 * @param int $ns numerical representation of the namespace
342 * @param string $title the DB key form the title
343 * @return string the prefixed form of the title
345 /* static */ function makeName( $ns, $title ) {
348 $n = $wgContLang->getNsText( $ns );
349 if ( '' == $n ) { return $title; }
350 else { return $n.':'.$title; }
354 * Returns the URL associated with an interwiki prefix
355 * @param string $key the interwiki prefix (e.g. "MeatBall")
356 * @return the associated URL, containing "$1", which should be
357 * replaced by an article title
361 function getInterwikiLink( $key ) {
362 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
363 $fname = 'Title::getInterwikiLink';
364 $k = $wgDBname.':interwiki:'.$key;
366 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
367 return $wgTitleInterwikiCache[$k]->iw_url
;
369 $s = $wgMemc->get( $k );
370 # Ignore old keys with no iw_local
371 if( $s && isset( $s->iw_local
) ) {
372 $wgTitleInterwikiCache[$k] = $s;
375 $dbr =& wfGetDB( DB_SLAVE
);
376 $res = $dbr->select( 'interwiki', array( 'iw_url', 'iw_local' ), array( 'iw_prefix' => $key ), $fname );
379 $s = $dbr->fetchObject( $res );
381 # Cache non-existence: create a blank object and save it to memcached
386 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
387 $wgTitleInterwikiCache[$k] = $s;
392 * Determine whether the object refers to a page within
395 * @return bool TRUE if this is an in-project interwiki link
396 * or a wikilink, FALSE otherwise
400 global $wgTitleInterwikiCache, $wgDBname;
402 if ( $this->mInterwiki
!= '' ) {
403 # Make sure key is loaded into cache
404 $this->getInterwikiLink( $this->mInterwiki
);
405 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
406 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
413 * Update the cur_touched field for an array of title objects
414 * @todo Inefficient unless the IDs are already loaded into the
416 * @param array $titles an array of Title objects to be touched
417 * @param string $timestamp the timestamp to use instead of the
418 * default current time
422 /* static */ function touchArray( $titles, $timestamp = '' ) {
423 if ( count( $titles ) == 0 ) {
426 $dbw =& wfGetDB( DB_MASTER
);
427 if ( $timestamp == '' ) {
428 $timestamp = $dbw->timestamp();
430 $cur = $dbw->tableName( 'cur' );
431 $sql = "UPDATE $cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
434 foreach ( $titles as $title ) {
439 $sql .= $title->getArticleID();
443 $dbw->query( $sql, 'Title::touchArray' );
447 #----------------------------------------------------------------------------
449 #----------------------------------------------------------------------------
451 /** Simple accessors */
453 * Get the text form (spaces not underscores) of the main part
457 function getText() { return $this->mTextform
; }
459 * Get the URL-encoded form of the main part
463 function getPartialURL() { return $this->mUrlform
; }
465 * Get the main part with underscores
469 function getDBkey() { return $this->mDbkeyform
; }
471 * Get the namespace index, i.e. one of the NS_xxxx constants
475 function getNamespace() { return $this->mNamespace
; }
477 * Set the namespace index
478 * @param int $n the namespace index, one of the NS_xxxx constants
481 function setNamespace( $n ) { $this->mNamespace
= IntVal( $n ); }
483 * Get the interwiki prefix (or null string)
487 function getInterwiki() { return $this->mInterwiki
; }
489 * Get the Title fragment (i.e. the bit after the #)
493 function getFragment() { return $this->mFragment
; }
495 * Get the default namespace index, for when there is no namespace
499 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
502 * Get title for search index
503 * @return string a stripped-down title string ready for the
506 function getIndexTitle() {
507 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
511 * Get the prefixed database key form
512 * @return string the prefixed title, with underscores and
513 * any interwiki and namespace prefixes
516 function getPrefixedDBkey() {
517 $s = $this->prefix( $this->mDbkeyform
);
518 $s = str_replace( ' ', '_', $s );
523 * Get the prefixed title with spaces.
524 * This is the form usually used for display
525 * @return string the prefixed title, with spaces
528 function getPrefixedText() {
530 if ( empty( $this->mPrefixedText
) ) {
531 $s = $this->prefix( $this->mTextform
);
532 $s = str_replace( '_', ' ', $s );
533 $this->mPrefixedText
= $s;
535 //convert to the desired language variant
536 $t = $wgContLang->convert($this->mPrefixedText
);
541 * Get the prefixed title with spaces, plus any fragment
542 * (part beginning with '#')
543 * @return string the prefixed title, with spaces and
544 * the fragment, including '#'
547 function getFullText() {
549 $text = $this->getPrefixedText();
550 if( '' != $this->mFragment
) {
551 $text .= '#' . $this->mFragment
;
553 //convert to desired language variant
554 $t = $wgContLang->convert($text);
559 * Get a URL-encoded title (not an actual URL) including interwiki
560 * @return string the URL-encoded form
563 function getPrefixedURL() {
564 $s = $this->prefix( $this->mDbkeyform
);
565 $s = str_replace( ' ', '_', $s );
567 $s = wfUrlencode ( $s ) ;
569 # Cleaning up URL to make it look nice -- is this safe?
570 $s = preg_replace( '/%3[Aa]/', ':', $s );
571 $s = preg_replace( '/%2[Ff]/', '/', $s );
572 $s = str_replace( '%28', '(', $s );
573 $s = str_replace( '%29', ')', $s );
579 * Get a real URL referring to this title, with interwiki link and
582 * @param string $query an optional query string, not used
583 * for interwiki links
584 * @return string the URL
587 function getFullURL( $query = '' ) {
588 global $wgContLang, $wgArticlePath, $wgServer, $wgScript;
590 if ( '' == $this->mInterwiki
) {
592 return $wgServer . $this->getLocalUrl( $query );
594 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
595 $namespace = $wgContLang->getNsText( $this->mNamespace
);
596 if ( '' != $namespace ) {
597 # Can this actually happen? Interwikis shouldn't be parsed.
600 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
601 if ( '' != $this->mFragment
) {
602 $url .= '#' . $this->mFragment
;
612 die( 'Call to obsolete obsolete function Title::getURL()' );
616 * Get a URL with no fragment or server name
617 * @param string $query an optional query string; if not specified,
618 * $wgArticlePath will be used.
619 * @return string the URL
622 function getLocalURL( $query = '' ) {
623 global $wgLang, $wgArticlePath, $wgScript;
625 if ( $this->isExternal() ) {
626 return $this->getFullURL();
629 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
630 if ( $query == '' ) {
631 $url = str_replace( '$1', $dbkey, $wgArticlePath );
633 if ( $query == '-' ) {
636 if ( $wgScript != '' ) {
637 $url = "{$wgScript}?title={$dbkey}&{$query}";
640 $url = "/{$dbkey}?{$query}";
647 * Get an HTML-escaped version of the URL form, suitable for
648 * using in a link, without a server name or fragment
649 * @param string $query an optional query string
650 * @return string the URL
653 function escapeLocalURL( $query = '' ) {
654 return htmlspecialchars( $this->getLocalURL( $query ) );
658 * Get an HTML-escaped version of the URL form, suitable for
659 * using in a link, including the server name and fragment
661 * @return string the URL
662 * @param string $query an optional query string
665 function escapeFullURL( $query = '' ) {
666 return htmlspecialchars( $this->getFullURL( $query ) );
670 * Get the URL form for an internal link.
671 * - Used in various Squid-related code, in case we have a different
672 * internal hostname for the server from the exposed one.
674 * @param string $query an optional query string
675 * @return string the URL
678 function getInternalURL( $query = '' ) {
679 global $wgInternalServer;
680 return $wgInternalServer . $this->getLocalURL( $query );
684 * Get the edit URL for this Title
685 * @return string the URL, or a null string if this is an
689 function getEditURL() {
690 global $wgServer, $wgScript;
692 if ( '' != $this->mInterwiki
) { return ''; }
693 $s = $this->getLocalURL( 'action=edit' );
699 * Get the HTML-escaped displayable text form.
700 * Used for the title field in <a> tags.
701 * @return string the text, including any prefixes
704 function getEscapedText() {
705 return htmlspecialchars( $this->getPrefixedText() );
709 * Is this Title interwiki?
713 function isExternal() { return ( '' != $this->mInterwiki
); }
716 * Does the title correspond to a protected article?
720 function isProtected() {
721 if ( -1 == $this->mNamespace
) { return true; }
722 $a = $this->getRestrictions();
723 if ( in_array( 'sysop', $a ) ) { return true; }
728 * Is the page a log page, i.e. one where the history is messed up by
729 * LogPage.php? This used to be used for suppressing diff links in
730 * recent changes, but now that's done by setting a flag in the
731 * recentchanges table. Hence, this probably is no longer used.
737 if ( $this->mNamespace
!= Namespace::getWikipedia() ) {
740 if ( ( 0 == strcmp( wfMsg( 'uploadlogpage' ), $this->mDbkeyform
) ) ||
741 ( 0 == strcmp( wfMsg( 'dellogpage' ), $this->mDbkeyform
) ) ) {
748 * Is $wgUser is watching this page?
752 function userIsWatching() {
755 if ( -1 == $this->mNamespace
) { return false; }
756 if ( 0 == $wgUser->getID() ) { return false; }
758 return $wgUser->isWatched( $this );
762 * Can $wgUser edit this page?
766 function userCanEdit() {
768 if ( -1 == $this->mNamespace
) { return false; }
769 if ( NS_MEDIAWIKI
== $this->mNamespace
&& !$wgUser->isSysop() ) { return false; }
770 # if ( 0 == $this->getArticleID() ) { return false; }
771 if ( $this->mDbkeyform
== '_' ) { return false; }
772 # protect global styles and js
773 if ( NS_MEDIAWIKI
== $this->mNamespace
774 && preg_match("/\\.(css|js)$/", $this->mTextform
)
775 && !$wgUser->isSysop() )
777 //if ( $this->isCssJsSubpage() and !$this->userCanEditCssJsSubpage() ) { return false; }
778 # protect css/js subpages of user pages
779 # XXX: this might be better using restrictions
780 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
781 if( Namespace::getUser() == $this->mNamespace
782 and preg_match("/\\.(css|js)$/", $this->mTextform
)
783 and !$wgUser->isSysop()
784 and !preg_match('/^'.preg_quote($wgUser->getName(), '/').'/', $this->mTextform
) )
786 $ur = $wgUser->getRights();
787 foreach ( $this->getRestrictions() as $r ) {
788 if ( '' != $r && ( ! in_array( $r, $ur ) ) ) {
796 * Can $wgUser read this page?
800 function userCanRead() {
802 global $wgWhitelistRead;
804 if( 0 != $wgUser->getID() ) return true;
805 if( !is_array( $wgWhitelistRead ) ) return true;
807 $name = $this->getPrefixedText();
808 if( in_array( $name, $wgWhitelistRead ) ) return true;
810 # Compatibility with old settings
811 if( $this->getNamespace() == NS_MAIN
) {
812 if( in_array( ':' . $name, $wgWhitelistRead ) ) return true;
818 * Is this a .css or .js subpage of a user page?
822 function isCssJsSubpage() {
823 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
826 * Is this a .css subpage of a user page?
830 function isCssSubpage() {
831 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
834 * Is this a .js subpage of a user page?
838 function isJsSubpage() {
839 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
842 * Protect css/js subpages of user pages: can $wgUser edit
846 * @todo XXX: this might be better using restrictions
849 function userCanEditCssJsSubpage() {
851 return ( $wgUser->isSysop() or preg_match('/^'.preg_quote($wgUser->getName()).'/', $this->mTextform
) );
855 * Accessor/initialisation for mRestrictions
856 * @return array the array of groups allowed to edit this article
859 function getRestrictions() {
860 $id = $this->getArticleID();
861 if ( 0 == $id ) { return array(); }
863 if ( ! $this->mRestrictionsLoaded
) {
864 $dbr =& wfGetDB( DB_SLAVE
);
865 $res = $dbr->getField( 'cur', 'cur_restrictions', 'cur_id='.$id );
866 $this->mRestrictions
= explode( ',', trim( $res ) );
867 $this->mRestrictionsLoaded
= true;
869 return $this->mRestrictions
;
873 * Is there a version of this page in the deletion archive?
874 * @return int the number of archived revisions
877 function isDeleted() {
878 $fname = 'Title::isDeleted';
879 $dbr =& wfGetDB( DB_SLAVE
);
880 $n = $dbr->getField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
881 'ar_title' => $this->getDBkey() ), $fname );
886 * Get the article ID for this Title from the link cache,
887 * adding it if necessary
888 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
893 function getArticleID( $flags = 0 ) {
896 if ( $flags & GAID_FOR_UPDATE
) {
897 $oldUpdate = $wgLinkCache->forUpdate( true );
898 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
899 $wgLinkCache->forUpdate( $oldUpdate );
901 if ( -1 == $this->mArticleID
) {
902 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
905 return $this->mArticleID
;
909 * This clears some fields in this object, and clears any associated
910 * keys in the "bad links" section of $wgLinkCache.
912 * - This is called from Article::insertNewArticle() to allow
913 * loading of the new cur_id. It's also called from
914 * Article::doDeleteArticle()
916 * @param int $newid the new Article ID
919 function resetArticleID( $newid ) {
921 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
923 if ( 0 == $newid ) { $this->mArticleID
= -1; }
924 else { $this->mArticleID
= $newid; }
925 $this->mRestrictionsLoaded
= false;
926 $this->mRestrictions
= array();
930 * Updates cur_touched for this page; called from LinksUpdate.php
931 * @return bool true if the update succeded
934 function invalidateCache() {
935 $now = wfTimestampNow();
936 $dbw =& wfGetDB( DB_MASTER
);
937 $success = $dbw->updateArray( 'cur',
939 'cur_touched' => $dbw->timestamp()
940 ), array( /* WHERE */
941 'cur_namespace' => $this->getNamespace() ,
942 'cur_title' => $this->getDBkey()
943 ), 'Title::invalidateCache'
949 * Prefix some arbitrary text with the namespace or interwiki prefix
952 * @param string $name the text
953 * @return string the prefixed text
956 /* private */ function prefix( $name ) {
960 if ( '' != $this->mInterwiki
) {
961 $p = $this->mInterwiki
. ':';
963 if ( 0 != $this->mNamespace
) {
964 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
970 * Secure and split - main initialisation function for this object
972 * Assumes that mDbkeyform has been set, and is urldecoded
973 * and uses underscores, but not otherwise munged. This function
974 * removes illegal characters, splits off the interwiki and
975 * namespace prefixes, sets the other forms, and canonicalizes
977 * @return bool true on success
980 /* private */ function secureAndSplit()
982 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
983 $fname = 'Title::secureAndSplit';
984 wfProfileIn( $fname );
986 static $imgpre = false;
987 static $rxTc = false;
990 if ( $imgpre === false ) {
991 $imgpre = ':' . $wgContLang->getNsText( Namespace::getImage() ) . ':';
992 # % is needed as well
993 $rxTc = '/[^' . Title
::legalChars() . ']/';
996 $this->mInterwiki
= $this->mFragment
= '';
997 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
999 # Clean up whitespace
1001 $t = preg_replace( "/[\\s_]+/", '_', $this->mDbkeyform
);
1002 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
1005 wfProfileOut( $fname );
1009 global $wgUseLatin1;
1010 if( !$wgUseLatin1 && false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1011 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1012 wfProfileOut( $fname );
1016 $this->mDbkeyform
= $t;
1020 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
1021 $t = substr( $t, 1 );
1024 # Initial colon indicating main namespace
1025 if ( ':' == $t{0} ) {
1026 $r = substr( $t, 1 );
1027 $this->mNamespace
= NS_MAIN
;
1029 # Namespace or interwiki prefix
1030 if ( preg_match( "/^(.+?)_*:_*(.*)$/", $t, $m ) ) {
1031 #$p = strtolower( $m[1] );
1033 $lowerNs = strtolower( $p );
1034 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1035 # Canonical namespace
1037 $this->mNamespace
= $ns;
1038 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1039 # Ordinary namespace
1041 $this->mNamespace
= $ns;
1042 } elseif ( $this->getInterwikiLink( $p ) ) {
1045 $this->mInterwiki
= $p;
1047 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
1049 } elseif($this->mInterwiki
!= $wgLocalInterwiki) {
1057 # Redundant interwiki prefix to the local wiki
1058 if ( 0 == strcmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1059 $this->mInterwiki
= '';
1061 # We already know that some pages won't be in the database!
1063 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1064 $this->mArticleID
= 0;
1066 $f = strstr( $r, '#' );
1067 if ( false !== $f ) {
1068 $this->mFragment
= substr( $f, 1 );
1069 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1070 # remove whitespace again: prevents "Foo_bar_#"
1071 # becoming "Foo_bar_"
1072 $r = preg_replace( '/_*$/', '', $r );
1075 # Reject illegal characters.
1077 if( preg_match( $rxTc, $r ) ) {
1078 wfProfileOut( $fname );
1082 # "." and ".." conflict with the directories of those namesa
1083 if ( strpos( $r, '.' ) !== false &&
1084 ( $r === '.' ||
$r === '..' ||
1085 strpos( $r, './' ) === 0 ||
1086 strpos( $r, '../' ) === 0 ||
1087 strpos( $r, '/./' ) !== false ||
1088 strpos( $r, '/../' ) !== false ) )
1090 wfProfileOut( $fname );
1094 # Initial capital letter
1095 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1096 $t = $wgContLang->ucfirst( $r );
1102 $this->mDbkeyform
= $t;
1103 $this->mUrlform
= wfUrlencode( $t );
1105 $this->mTextform
= str_replace( '_', ' ', $t );
1107 wfProfileOut( $fname );
1112 * Get a Title object associated with the talk page of this article
1113 * @return Title the object for the talk page
1116 function getTalkPage() {
1117 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1121 * Get a title object associated with the subject page of this
1124 * @return Title the object for the subject page
1127 function getSubjectPage() {
1128 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1132 * Get an array of Title objects linking to this Title
1133 * - Also stores the IDs in the link cache.
1135 * @param string $options may be FOR UPDATE
1136 * @return array the Title objects linking here
1139 function getLinksTo( $options = '' ) {
1140 global $wgLinkCache;
1141 $id = $this->getArticleID();
1144 $db =& wfGetDB( DB_MASTER
);
1146 $db =& wfGetDB( DB_SLAVE
);
1148 $cur = $db->tableName( 'cur' );
1149 $links = $db->tableName( 'links' );
1151 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
1152 $res = $db->query( $sql, 'Title::getLinksTo' );
1154 if ( $db->numRows( $res ) ) {
1155 while ( $row = $db->fetchObject( $res ) ) {
1156 if ( $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
) ) {
1157 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
1158 $retVal[] = $titleObj;
1162 $db->freeResult( $res );
1167 * Get an array of Title objects linking to this non-existent title.
1168 * - Also stores the IDs in the link cache.
1170 * @param string $options may be FOR UPDATE
1171 * @return array the Title objects linking here
1174 function getBrokenLinksTo( $options = '' ) {
1175 global $wgLinkCache;
1178 $db =& wfGetDB( DB_MASTER
);
1180 $db =& wfGetDB( DB_SLAVE
);
1182 $cur = $db->tableName( 'cur' );
1183 $brokenlinks = $db->tableName( 'brokenlinks' );
1184 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
1186 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
1187 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
1188 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
1190 if ( $db->numRows( $res ) ) {
1191 while ( $row = $db->fetchObject( $res ) ) {
1192 $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
1193 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
1194 $retVal[] = $titleObj;
1197 $db->freeResult( $res );
1202 * Get a list of URLs to purge from the Squid cache when this
1205 * @return array the URLs
1208 function getSquidURLs() {
1210 $this->getInternalURL(),
1211 $this->getInternalURL( 'action=history' )
1216 * Move this page without authentication
1217 * @param Title &$nt the new page Title
1220 function moveNoAuth( &$nt ) {
1221 return $this->moveTo( $nt, false );
1225 * Move a title to a new location
1226 * @param Title &$nt the new title
1227 * @param bool $auth indicates whether $wgUser's permissions
1229 * @return mixed true on success, message name on failure
1232 function moveTo( &$nt, $auth = true ) {
1233 if( !$this or !$nt ) {
1234 return 'badtitletext';
1237 $fname = 'Title::move';
1238 $oldid = $this->getArticleID();
1239 $newid = $nt->getArticleID();
1241 if ( strlen( $nt->getDBkey() ) < 1 ) {
1242 return 'articleexists';
1244 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
1245 ( '' == $this->getDBkey() ) ||
1246 ( '' != $this->getInterwiki() ) ||
1248 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
1249 ( '' == $nt->getDBkey() ) ||
1250 ( '' != $nt->getInterwiki() ) ) {
1251 return 'badarticleerror';
1254 if ( $auth && ( !$this->userCanEdit() ||
!$nt->userCanEdit() ) ) {
1255 return 'protectedpage';
1258 # The move is allowed only if (1) the target doesn't exist, or
1259 # (2) the target is a redirect to the source, and has no history
1260 # (so we can undo bad moves right after they're done).
1262 if ( 0 != $newid ) { # Target exists; check for validity
1263 if ( ! $this->isValidMoveTarget( $nt ) ) {
1264 return 'articleexists';
1266 $this->moveOverExistingRedirect( $nt );
1267 } else { # Target didn't exist, do normal move.
1268 $this->moveToNewTitle( $nt, $newid );
1271 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1273 $dbw =& wfGetDB( DB_MASTER
);
1274 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1275 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
1276 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1277 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1281 $oldnamespace = $this->getNamespace() & ~
1;
1282 $newnamespace = $nt->getNamespace() & ~
1;
1283 $oldtitle = $this->getDBkey();
1284 $newtitle = $nt->getDBkey();
1286 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1287 WatchedItem
::duplicateEntries( $this, $nt );
1290 # Update search engine
1291 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
1293 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
1300 * Move page to a title which is at present a redirect to the
1303 * @param Title &$nt the page to move to, which should currently
1307 /* private */ function moveOverExistingRedirect( &$nt ) {
1308 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1309 $fname = 'Title::moveOverExistingRedirect';
1310 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1312 $now = wfTimestampNow();
1313 $won = wfInvertTimestamp( $now );
1314 $newid = $nt->getArticleID();
1315 $oldid = $this->getArticleID();
1316 $dbw =& wfGetDB( DB_MASTER
);
1317 $links = $dbw->tableName( 'links' );
1319 # Change the name of the target page:
1320 $dbw->updateArray( 'cur',
1322 'cur_touched' => $dbw->timestamp($now),
1323 'cur_namespace' => $nt->getNamespace(),
1324 'cur_title' => $nt->getDBkey()
1326 /* WHERE */ array( 'cur_id' => $oldid ),
1329 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1331 # Repurpose the old redirect. We don't save it to history since
1332 # by definition if we've got here it's rather uninteresting.
1334 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1335 $dbw->updateArray( 'cur',
1337 'cur_touched' => $dbw->timestamp($now),
1338 'cur_timestamp' => $dbw->timestamp($now),
1339 'inverse_timestamp' => $won,
1340 'cur_namespace' => $this->getNamespace(),
1341 'cur_title' => $this->getDBkey(),
1342 'cur_text' => $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n",
1343 'cur_comment' => $comment,
1344 'cur_user' => $wgUser->getID(),
1345 'cur_minor_edit' => 0,
1347 'cur_restrictions' => '',
1348 'cur_user_text' => $wgUser->getName(),
1349 'cur_is_redirect' => 1,
1352 /* WHERE */ array( 'cur_id' => $newid ),
1356 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1358 # Fix the redundant names for the past revisions of the target page.
1359 # The redirect should have no old revisions.
1363 'old_namespace' => $nt->getNamespace(),
1364 'old_title' => $nt->getDBkey(),
1367 'old_namespace' => $this->getNamespace(),
1368 'old_title' => $this->getDBkey(),
1373 RecentChange
::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
1377 # Load titles and IDs
1378 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1379 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1382 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1383 $dbw->query( $sql, $fname );
1386 if ( count( $linksToOld ) ||
count( $linksToNew )) {
1387 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1390 # Insert links to old title
1391 foreach ( $linksToOld as $linkTitle ) {
1397 $id = $linkTitle->getArticleID();
1398 $sql .= "($id,$newid)";
1401 # Insert links to new title
1402 foreach ( $linksToNew as $linkTitle ) {
1408 $id = $linkTitle->getArticleID();
1409 $sql .= "($id, $oldid)";
1412 $dbw->query( $sql, DB_MASTER
, $fname );
1415 # Now, we record the link from the redirect to the new title.
1416 # It should have no other outgoing links...
1417 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1418 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1421 LinkCache
::linksccClearLinksTo( $oldid );
1422 LinkCache
::linksccClearLinksTo( $newid );
1425 if ( $wgUseSquid ) {
1426 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1427 $u = new SquidUpdate( $urls );
1433 * Move page to non-existing title.
1434 * @param Title &$nt the new Title
1435 * @param int &$newid set to be the new article ID
1438 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1439 global $wgUser, $wgLinkCache, $wgUseSquid;
1440 $fname = 'MovePageForm::moveToNewTitle';
1441 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1443 $newid = $nt->getArticleID();
1444 $oldid = $this->getArticleID();
1445 $dbw =& wfGetDB( DB_MASTER
);
1446 $now = $dbw->timestamp();
1447 $won = wfInvertTimestamp( wfTimestamp(TS_MW
,$now) );
1449 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
1452 $dbw->updateArray( 'cur',
1454 'cur_touched' => $now,
1455 'cur_namespace' => $nt->getNamespace(),
1456 'cur_title' => $nt->getDBkey()
1458 /* WHERE */ array( 'cur_id' => $oldid ),
1462 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1465 $dbw->insertArray( 'cur', array(
1466 'cur_id' => $dbw->nextSequenceValue('cur_cur_id_seq'),
1467 'cur_namespace' => $this->getNamespace(),
1468 'cur_title' => $this->getDBkey(),
1469 'cur_comment' => $comment,
1470 'cur_user' => $wgUser->getID(),
1471 'cur_user_text' => $wgUser->getName(),
1472 'cur_timestamp' => $now,
1473 'inverse_timestamp' => $won,
1474 'cur_touched' => $now,
1475 'cur_is_redirect' => 1,
1476 'cur_random' => $rand,
1478 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1480 $newid = $dbw->insertId();
1481 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1483 # Rename old entries
1487 'old_namespace' => $nt->getNamespace(),
1488 'old_title' => $nt->getDBkey()
1491 'old_namespace' => $this->getNamespace(),
1492 'old_title' => $this->getDBkey()
1497 RecentChange
::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1499 # Purge squid and linkscc as per article creation
1500 Article
::onArticleCreate( $nt );
1502 # Any text links to the old title must be reassigned to the redirect
1503 $dbw->updateArray( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1504 LinkCache
::linksccClearLinksTo( $oldid );
1506 # Record the just-created redirect's linking to the page
1507 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1509 # Non-existent target may have had broken links to it; these must
1510 # now be removed and made into good links.
1511 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1512 $update->fixBrokenLinks();
1514 # Purge old title from squid
1515 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1516 $titles = $nt->getLinksTo();
1517 if ( $wgUseSquid ) {
1518 $urls = $this->getSquidURLs();
1519 foreach ( $titles as $linkTitle ) {
1520 $urls[] = $linkTitle->getInternalURL();
1522 $u = new SquidUpdate( $urls );
1528 * Checks if $this can be moved to a given Title
1529 * - Selects for update, so don't call it unless you mean business
1531 * @param Title &$nt the new title to check
1534 function isValidMoveTarget( $nt ) {
1535 $fname = 'Title::isValidMoveTarget';
1536 $dbw =& wfGetDB( DB_MASTER
);
1539 $id = $nt->getArticleID();
1540 $obj = $dbw->getArray( 'cur', array( 'cur_is_redirect','cur_text' ),
1541 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1543 if ( !$obj ||
0 == $obj->cur_is_redirect
) {
1548 # Does the redirect point to the source?
1549 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text
, $m ) ) {
1550 $redirTitle = Title
::newFromText( $m[1] );
1551 if( !is_object( $redirTitle ) ||
1552 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1557 # Does the article have a history?
1558 $row = $dbw->getArray( 'old', array( 'old_id' ),
1560 'old_namespace' => $nt->getNamespace(),
1561 'old_title' => $nt->getDBkey()
1562 ), $fname, 'FOR UPDATE'
1565 # Return true if there was no history
1566 return $row === false;
1570 * Create a redirect; fails if the title already exists; does
1573 * @param Title $dest the destination of the redirect
1574 * @param string $comment the comment string describing the move
1575 * @return bool true on success
1578 function createRedirect( $dest, $comment ) {
1580 if ( $this->getArticleID() ) {
1584 $fname = 'Title::createRedirect';
1585 $dbw =& wfGetDB( DB_MASTER
);
1586 $now = wfTimestampNow();
1587 $won = wfInvertTimestamp( $now );
1588 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1590 $dbw->insertArray( 'cur', array(
1591 'cur_id' => $seqVal,
1592 'cur_namespace' => $this->getNamespace(),
1593 'cur_title' => $this->getDBkey(),
1594 'cur_comment' => $comment,
1595 'cur_user' => $wgUser->getID(),
1596 'cur_user_text' => $wgUser->getName(),
1597 'cur_timestamp' => $now,
1598 'inverse_timestamp' => $won,
1599 'cur_touched' => $now,
1600 'cur_is_redirect' => 1,
1602 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1604 $newid = $dbw->insertId();
1605 $this->resetArticleID( $newid );
1608 if ( $dest->getArticleID() ) {
1609 $dbw->insertArray( 'links',
1611 'l_to' => $dest->getArticleID(),
1616 $dbw->insertArray( 'brokenlinks',
1618 'bl_to' => $dest->getPrefixedDBkey(),
1624 Article
::onArticleCreate( $this );
1629 * Get categories to which this Title belongs and return an array of
1630 * categories' names.
1632 * @return array an array of parents in the form:
1633 * $parent => $currentarticle
1636 function getParentCategories() {
1637 global $wgContLang,$wgUser;
1639 $titlekey = $this->getArticleId();
1640 $sk =& $wgUser->getSkin();
1642 $dbr =& wfGetDB( DB_SLAVE
);
1643 $cur = $dbr->tableName( 'cur' );
1644 $categorylinks = $dbr->tableName( 'categorylinks' );
1647 $sql = "SELECT * FROM categorylinks"
1648 ." WHERE cl_from='$titlekey'"
1649 ." AND cl_from <> '0'"
1650 ." ORDER BY cl_sortkey";
1652 $res = $dbr->query ( $sql ) ;
1654 if($dbr->numRows($res) > 0) {
1655 while ( $x = $dbr->fetchObject ( $res ) )
1656 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1657 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1658 $dbr->freeResult ( $res ) ;
1666 * Go through all parent categories of this Title
1670 function getCategorieBrowser() {
1671 $parents = $this->getParentCategories();
1673 if($parents != '') {
1674 foreach($parents as $parent => $current)
1676 $nt = Title
::newFromText($parent);
1677 $stack[$parent] = $nt->getCategorieBrowser();
1687 * Get an associative array for selecting this title from
1693 function curCond() {
1694 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1698 * Get an associative array for selecting this title from the
1704 function oldCond() {
1705 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);
1709 * Get the revision ID of the previous revision
1711 * @param integer $revision Revision ID. Get the revision that was before this one.
1712 * @return interger $oldrevision|false
1714 function getPreviousRevisionID( $revision ) {
1715 $dbr =& wfGetDB( DB_SLAVE
);
1716 return $dbr->selectField( 'old', 'old_id',
1717 'old_title=' . $dbr->addQuotes( $this->getDBkey() ) .
1718 ' AND old_namespace=' . IntVal( $this->getNamespace() ) .
1719 ' AND old_id<' . IntVal( $revision ) . ' ORDER BY old_id DESC' );
1723 * Get the revision ID of the next revision
1725 * @param integer $revision Revision ID. Get the revision that was after this one.
1726 * @return interger $oldrevision|false
1728 function getNextRevisionID( $revision ) {
1729 $dbr =& wfGetDB( DB_SLAVE
);
1730 return $dbr->selectField( 'old', 'old_id',
1731 'old_title=' . $dbr->addQuotes( $this->getDBkey() ) .
1732 ' AND old_namespace=' . IntVal( $this->getNamespace() ) .
1733 ' AND old_id>' . IntVal( $revision ) . ' ORDER BY old_id' );