Autodiscovery <link> for RSS feed. Added helper functions for query stuff:
[mediawiki.git] / includes / Title.php
blobc8373ce4d7471ab24c53cd1a383afa13300590df
1 <?php
2 # See title.doc
4 /* private static */ $title_interwiki_cache = array();
6 # Title class
7 #
8 # * Represents a title, which may contain an interwiki designation or namespace
9 # * Can fetch various kinds of data from the database, albeit inefficiently.
11 class Title {
12 # All member variables should be considered private
13 # Please use the accessor functions
15 var $mTextform; # Text form (spaces not underscores) of the main part
16 var $mUrlform; # URL-encoded form of the main part
17 var $mDbkeyform; # Main part with underscores
18 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
19 var $mInterwiki; # Interwiki prefix (or null string)
20 var $mFragment; # Title fragment (i.e. the bit after the #)
21 var $mArticleID; # Article ID, fetched from the link cache on demand
22 var $mRestrictions; # Array of groups allowed to edit this article
23 # Only null or "sysop" are supported
24 var $mRestrictionsLoaded; # Boolean for initialisation on demand
25 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
27 #----------------------------------------------------------------------------
28 # Construction
29 #----------------------------------------------------------------------------
31 /* private */ function Title()
33 $this->mInterwiki = $this->mUrlform =
34 $this->mTextform = $this->mDbkeyform = "";
35 $this->mArticleID = -1;
36 $this->mNamespace = 0;
37 $this->mRestrictionsLoaded = false;
38 $this->mRestrictions = array();
41 # From a prefixed DB key
42 /* static */ function newFromDBkey( $key )
44 $t = new Title();
45 $t->mDbkeyform = $key;
46 if( $t->secureAndSplit() )
47 return $t;
48 else
49 return NULL;
52 # From text, such as what you would find in a link
53 /* static */ function newFromText( $text )
55 static $trans;
56 $fname = "Title::newFromText";
57 wfProfileIn( $fname );
59 # Note - mixing latin1 named entities and unicode numbered
60 # ones will result in a bad link.
61 if( !isset( $trans ) ) {
62 global $wgInputEncoding;
63 $trans = array_flip( get_html_translation_table( HTML_ENTITIES ) );
64 if( strcasecmp( "utf-8", $wgInputEncoding ) == 0 ) {
65 $trans = array_map( "utf8_encode", $trans );
69 if( is_object( $text ) ) {
70 wfDebugDieBacktrace( "Called with object instead of string." );
72 $text = strtr( $text, $trans );
74 $text = wfMungeToUtf8( $text );
77 # What was this for? TS 2004-03-03
78 # $text = urldecode( $text );
80 $t = new Title();
81 $t->mDbkeyform = str_replace( " ", "_", $text );
82 wfProfileOut( $fname );
83 if( $t->secureAndSplit() ) {
84 return $t;
85 } else {
86 return NULL;
90 # From a URL-encoded title
91 /* static */ function newFromURL( $url )
93 global $wgLang, $wgServer;
94 $t = new Title();
95 $s = urldecode( $url ); # This is technically wrong, as anything
96 # we've gotten is already decoded by PHP.
97 # Kept for backwards compatibility with
98 # buggy URLs we had for a while...
99 $s = $url;
101 # For links that came from outside, check for alternate/legacy
102 # character encoding.
103 wfDebug( "Servr: $wgServer\n" );
104 if( empty( $_SERVER["HTTP_REFERER"] ) ||
105 strncmp($wgServer, $_SERVER["HTTP_REFERER"], strlen( $wgServer ) ) )
107 $s = $wgLang->checkTitleEncoding( $s );
108 } else {
109 wfDebug( "Refer: {$_SERVER['HTTP_REFERER']}\n" );
112 $t->mDbkeyform = str_replace( " ", "_", $s );
113 if( $t->secureAndSplit() ) {
115 # check that lenght of title is < cur_title size
116 $sql = "SHOW COLUMNS FROM cur LIKE \"cur_title\";";
117 $cur_title_object = wfFetchObject(wfQuery( $sql, DB_READ ));
119 preg_match( "/\((.*)\)/", $cur_title_object->Type, $cur_title_size);
121 if (strlen($t->mDbkeyform) > $cur_title_size[1] ) {
122 return NULL;
125 return $t;
126 } else {
127 return NULL;
131 # From a cur_id
132 # This is inefficiently implemented, the cur row is requested but not
133 # used for anything else
134 /* static */ function newFromID( $id )
136 $fname = "Title::newFromID";
137 $row = wfGetArray( "cur", array( "cur_namespace", "cur_title" ),
138 array( "cur_id" => $id ), $fname );
139 if ( $row !== false ) {
140 $title = Title::makeTitle( $row->cur_namespace, $row->cur_title );
141 } else {
142 $title = NULL;
144 return $title;
147 # From a namespace index and a DB key
148 /* static */ function makeTitle( $ns, $title )
150 $t = new Title();
151 $t->mDbkeyform = Title::makeName( $ns, $title );
152 if( $t->secureAndSplit() ) {
153 return $t;
154 } else {
155 return NULL;
159 function newMainPage()
161 return Title::newFromText( wfMsg( "mainpage" ) );
164 #----------------------------------------------------------------------------
165 # Static functions
166 #----------------------------------------------------------------------------
168 # Get the prefixed DB key associated with an ID
169 /* static */ function nameOf( $id )
171 $sql = "SELECT cur_namespace,cur_title FROM cur WHERE " .
172 "cur_id={$id}";
173 $res = wfQuery( $sql, DB_READ, "Article::nameOf" );
174 if ( 0 == wfNumRows( $res ) ) { return NULL; }
176 $s = wfFetchObject( $res );
177 $n = Title::makeName( $s->cur_namespace, $s->cur_title );
178 return $n;
181 # Get a regex character class describing the legal characters in a link
182 /* static */ function legalChars()
184 # Missing characters:
185 # * []|# Needed for link syntax
186 # * % and + are corrupted by Apache when they appear in the path
188 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
189 # this breaks interlanguage links
191 $set = " !\"$&'()*,\\-.\\/0-9:;<=>?@A-Z\\\\^_`a-z{}~\\x80-\\xFF";
192 return $set;
195 # Returns a stripped-down a title string ready for the search index
196 # Takes a namespace index and a text-form main part
197 /* static */ function indexTitle( $ns, $title )
199 global $wgDBminWordLen, $wgLang;
201 $lc = SearchEngine::legalSearchChars() . "&#;";
202 $t = $wgLang->stripForSearch( $title );
203 $t = preg_replace( "/[^{$lc}]+/", " ", $t );
204 $t = strtolower( $t );
206 # Handle 's, s'
207 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
208 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
210 $t = preg_replace( "/\\s+/", " ", $t );
212 if ( $ns == Namespace::getImage() ) {
213 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
215 return trim( $t );
218 # Make a prefixed DB key from a DB key and a namespace index
219 /* static */ function makeName( $ns, $title )
221 global $wgLang;
223 $n = $wgLang->getNsText( $ns );
224 if ( "" == $n ) { return $title; }
225 else { return "{$n}:{$title}"; }
228 # Arguably static
229 # Returns the URL associated with an interwiki prefix
230 # The URL contains $1, which is replaced by the title
231 function getInterwikiLink( $key )
233 global $wgMemc, $wgDBname, $title_interwiki_cache;
234 $k = "$wgDBname:interwiki:$key";
236 if( array_key_exists( $k, $title_interwiki_cache ) )
237 return $title_interwiki_cache[$k]->iw_url;
239 $s = $wgMemc->get( $k );
240 if( $s ) {
241 $title_interwiki_cache[$k] = $s;
242 return $s->iw_url;
244 $dkey = wfStrencode( $key );
245 $query = "SELECT iw_url FROM interwiki WHERE iw_prefix='$dkey'";
246 $res = wfQuery( $query, DB_READ, "Title::getInterwikiLink" );
247 if(!$res) return "";
249 $s = wfFetchObject( $res );
250 if(!$s) {
251 $s = (object)false;
252 $s->iw_url = "";
254 $wgMemc->set( $k, $s );
255 $title_interwiki_cache[$k] = $s;
256 return $s->iw_url;
259 #----------------------------------------------------------------------------
260 # Other stuff
261 #----------------------------------------------------------------------------
263 # Simple accessors
264 # See the definitions at the top of this file
266 function getText() { return $this->mTextform; }
267 function getPartialURL() { return $this->mUrlform; }
268 function getDBkey() { return $this->mDbkeyform; }
269 function getNamespace() { return $this->mNamespace; }
270 function setNamespace( $n ) { $this->mNamespace = $n; }
271 function getInterwiki() { return $this->mInterwiki; }
272 function getFragment() { return $this->mFragment; }
274 # Get title for search index
275 function getIndexTitle()
277 return Title::indexTitle( $this->mNamespace, $this->mTextform );
280 # Get prefixed title with underscores
281 function getPrefixedDBkey()
283 $s = $this->prefix( $this->mDbkeyform );
284 $s = str_replace( " ", "_", $s );
285 return $s;
288 # Get prefixed title with spaces
289 # This is the form usually used for display
290 function getPrefixedText()
292 if ( empty( $this->mPrefixedText ) ) {
293 $s = $this->prefix( $this->mTextform );
294 $s = str_replace( "_", " ", $s );
295 $this->mPrefixedText = $s;
297 return $this->mPrefixedText;
300 # Get a URL-encoded title (not an actual URL) including interwiki
301 function getPrefixedURL()
303 $s = $this->prefix( $this->mDbkeyform );
304 $s = str_replace( " ", "_", $s );
306 $s = wfUrlencode ( $s ) ;
308 # Cleaning up URL to make it look nice -- is this safe?
309 $s = preg_replace( "/%3[Aa]/", ":", $s );
310 $s = preg_replace( "/%2[Ff]/", "/", $s );
311 $s = str_replace( "%28", "(", $s );
312 $s = str_replace( "%29", ")", $s );
314 return $s;
317 # Get a real URL referring to this title, with interwiki link and fragment
318 function getFullURL( $query = "" )
320 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
322 if ( "" == $this->mInterwiki ) {
323 $p = $wgArticlePath;
324 return $wgServer . $this->getLocalUrl( $query );
327 $p = $this->getInterwikiLink( $this->mInterwiki );
328 $n = $wgLang->getNsText( $this->mNamespace );
329 if ( "" != $n ) { $n .= ":"; }
330 $u = str_replace( "$1", $n . $this->mUrlform, $p );
331 if ( "" != $this->mFragment ) {
332 $u .= "#" . wfUrlencode( $this->mFragment );
334 return $u;
337 # Get a URL with an optional query string, no fragment
338 # * If $query=="", it will use $wgArticlePath
339 # * Returns a full for an interwiki link, loses any query string
340 # * Optionally adds the server and escapes for HTML
341 # * Setting $query to "-" makes an old-style URL with nothing in the
342 # query except a title
344 function getURL() {
345 die( "Call to obsolete obsolete function Title::getURL()" );
348 function getLocalURL( $query = "" )
350 global $wgLang, $wgArticlePath, $wgScript;
352 if ( $this->isExternal() ) {
353 return $this->getFullURL();
356 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
357 if ( $query == "" ) {
358 $url = str_replace( "$1", $dbkey, $wgArticlePath );
359 } else {
360 if ( $query == "-" ) {
361 $query = "";
363 if ( $wgScript != "" ) {
364 $url = "{$wgScript}?title={$dbkey}&{$query}";
365 } else {
366 # Top level wiki
367 $url = "/{$dbkey}?{$query}";
370 return $url;
373 function escapeLocalURL( $query = "" ) {
374 return wfEscapeHTML( $this->getLocalURL( $query ) );
377 function escapeFullURL( $query = "" ) {
378 return wfEscapeHTML( $this->getFullURL( $query ) );
381 function getInternalURL( $query = "" ) {
382 # Used in various Squid-related code, in case we have a different
383 # internal hostname for the server than the exposed one.
384 global $wgInternalServer;
385 return $wgInternalServer . $this->getLocalURL( $query );
388 # Get the edit URL, or a null string if it is an interwiki link
389 function getEditURL()
391 global $wgServer, $wgScript;
393 if ( "" != $this->mInterwiki ) { return ""; }
394 $s = $this->getLocalURL( "action=edit" );
396 return $s;
399 # Get HTML-escaped displayable text
400 # For the title field in <a> tags
401 function getEscapedText()
403 return wfEscapeHTML( $this->getPrefixedText() );
406 # Is the title interwiki?
407 function isExternal() { return ( "" != $this->mInterwiki ); }
409 # Does the title correspond to a protected article?
410 function isProtected()
412 if ( -1 == $this->mNamespace ) { return true; }
413 $a = $this->getRestrictions();
414 if ( in_array( "sysop", $a ) ) { return true; }
415 return false;
418 # Is the page a log page, i.e. one where the history is messed up by
419 # LogPage.php? This used to be used for suppressing diff links in recent
420 # changes, but now that's done by setting a flag in the recentchanges
421 # table. Hence, this probably is no longer used.
422 function isLog()
424 if ( $this->mNamespace != Namespace::getWikipedia() ) {
425 return false;
427 if ( ( 0 == strcmp( wfMsg( "uploadlogpage" ), $this->mDbkeyform ) ) ||
428 ( 0 == strcmp( wfMsg( "dellogpage" ), $this->mDbkeyform ) ) ) {
429 return true;
431 return false;
434 # Is $wgUser is watching this page?
435 function userIsWatching()
437 global $wgUser;
439 if ( -1 == $this->mNamespace ) { return false; }
440 if ( 0 == $wgUser->getID() ) { return false; }
442 return $wgUser->isWatched( $this );
445 # Can $wgUser edit this page?
446 function userCanEdit()
448 global $wgUser;
450 if ( -1 == $this->mNamespace ) { return false; }
451 # if ( 0 == $this->getArticleID() ) { return false; }
452 if ( $this->mDbkeyform == "_" ) { return false; }
454 $ur = $wgUser->getRights();
455 foreach ( $this->getRestrictions() as $r ) {
456 if ( "" != $r && ( ! in_array( $r, $ur ) ) ) {
457 return false;
460 return true;
463 # Accessor/initialisation for mRestrictions
464 function getRestrictions()
466 $id = $this->getArticleID();
467 if ( 0 == $id ) { return array(); }
469 if ( ! $this->mRestrictionsLoaded ) {
470 $res = wfGetSQL( "cur", "cur_restrictions", "cur_id=$id" );
471 $this->mRestrictions = explode( ",", trim( $res ) );
472 $this->mRestrictionsLoaded = true;
474 return $this->mRestrictions;
477 # Is there a version of this page in the deletion archive?
478 function isDeleted() {
479 $ns = $this->getNamespace();
480 $t = wfStrencode( $this->getDBkey() );
481 $sql = "SELECT COUNT(*) AS n FROM archive WHERE ar_namespace=$ns AND ar_title='$t'";
482 if( $res = wfQuery( $sql, DB_READ ) ) {
483 $s = wfFetchObject( $res );
484 return $s->n;
486 return 0;
489 # Get the article ID from the link cache
490 # Used very heavily, e.g. in Parser::replaceInternalLinks()
491 function getArticleID()
493 global $wgLinkCache;
495 if ( -1 != $this->mArticleID ) { return $this->mArticleID; }
496 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
497 return $this->mArticleID;
500 # This clears some fields in this object, and clears any associated keys in the
501 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
502 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
503 function resetArticleID( $newid )
505 global $wgLinkCache;
506 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
508 if ( 0 == $newid ) { $this->mArticleID = -1; }
509 else { $this->mArticleID = $newid; }
510 $this->mRestrictionsLoaded = false;
511 $this->mRestrictions = array();
514 # Updates cur_touched
515 # Called from LinksUpdate.php
516 function invalidateCache() {
517 $now = wfTimestampNow();
518 $ns = $this->getNamespace();
519 $ti = wfStrencode( $this->getDBkey() );
520 $sql = "UPDATE cur SET cur_touched='$now' WHERE cur_namespace=$ns AND cur_title='$ti'";
521 return wfQuery( $sql, DB_WRITE, "Title::invalidateCache" );
524 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
525 /* private */ function prefix( $name )
527 global $wgLang;
529 $p = "";
530 if ( "" != $this->mInterwiki ) {
531 $p = $this->mInterwiki . ":";
533 if ( 0 != $this->mNamespace ) {
534 $p .= $wgLang->getNsText( $this->mNamespace ) . ":";
536 return $p . $name;
539 # Secure and split - main initialisation function for this object
541 # Assumes that mDbkeyform has been set, and is urldecoded
542 # and uses undersocres, but not otherwise munged. This function
543 # removes illegal characters, splits off the winterwiki and
544 # namespace prefixes, sets the other forms, and canonicalizes
545 # everything.
547 /* private */ function secureAndSplit()
549 global $wgLang, $wgLocalInterwiki;
550 $fname = "Title::secureAndSplit";
551 wfProfileIn( $fname );
553 static $imgpre = false;
554 static $rxTc = false;
556 # Initialisation
557 if ( $imgpre === false ) {
558 $imgpre = ":" . $wgLang->getNsText( Namespace::getImage() ) . ":";
559 $rxTc = "/[^" . Title::legalChars() . "]/";
563 $this->mInterwiki = $this->mFragment = "";
564 $this->mNamespace = 0;
566 # Clean up whitespace
568 $t = preg_replace( "/[\\s_]+/", "_", $this->mDbkeyform );
569 if ( "_" == $t{0} ) {
570 $t = substr( $t, 1 );
572 $l = strlen( $t );
573 if ( $l && ( "_" == $t{$l-1} ) ) {
574 $t = substr( $t, 0, $l-1 );
576 if ( "" == $t ) {
577 wfProfileOut( $fname );
578 return false;
581 $this->mDbkeyform = $t;
582 $done = false;
584 # :Image: namespace
585 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
586 $t = substr( $t, 1 );
589 # Redundant initial colon
590 if ( ":" == $t{0} ) {
591 $r = substr( $t, 1 );
592 } else {
593 # Namespace or interwiki prefix
594 if ( preg_match( "/^((?:i|x|[a-z]{2,3})(?:-[a-z0-9]+)?|[A-Za-z0-9_\\x80-\\xff]+?)_*:_*(.*)$/", $t, $m ) ) {
595 #$p = strtolower( $m[1] );
596 $p = $m[1];
597 if ( $ns = $wgLang->getNsIndex( strtolower( $p ) )) {
598 # Ordinary namespace
599 $t = $m[2];
600 $this->mNamespace = $ns;
601 } elseif ( $this->getInterwikiLink( $p ) ) {
602 # Interwiki link
603 $t = $m[2];
604 $this->mInterwiki = $p;
606 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
607 $done = true;
608 } elseif($this->mInterwiki != $wgLocalInterwiki) {
609 $done = true;
613 $r = $t;
616 # Redundant interwiki prefix to the local wiki
617 if ( 0 == strcmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
618 $this->mInterwiki = "";
620 # We already know that some pages won't be in the database!
622 if ( "" != $this->mInterwiki || -1 == $this->mNamespace ) {
623 $this->mArticleID = 0;
625 $f = strstr( $r, "#" );
626 if ( false !== $f ) {
627 $this->mFragment = substr( $f, 1 );
628 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
631 # Reject illegal characters.
633 if( preg_match( $rxTc, $r ) ) {
634 return false;
637 # "." and ".." conflict with the directories of those names
638 if ( $r === "." || $r === ".." ) {
639 return false;
642 # Initial capital letter
643 if( $this->mInterwiki == "") $t = $wgLang->ucfirst( $r );
645 # Fill fields
646 $this->mDbkeyform = $t;
647 $this->mUrlform = wfUrlencode( $t );
649 $this->mTextform = str_replace( "_", " ", $t );
651 wfProfileOut( $fname );
652 return true;
655 # Get a title object associated with the talk page of this article
656 function getTalkPage() {
657 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
660 # Get a title object associated with the subject page of this talk page
661 function getSubjectPage() {
662 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );