Somewhat less hacky fix to the French l''''homme''' problem.
[mediawiki.git] / includes / Title.php
blob74c11c567696fcb15bb71ba5327a8e5a7236cd1c
1 <?php
2 # See title.doc
4 $wgTitleInterwikiCache = 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
26 var $mDefaultNamespace; # Namespace index when there is no namespace
27 # Zero except in {{transclusion}} tags
29 #----------------------------------------------------------------------------
30 # Construction
31 #----------------------------------------------------------------------------
33 /* private */ function Title()
35 $this->mInterwiki = $this->mUrlform =
36 $this->mTextform = $this->mDbkeyform = "";
37 $this->mArticleID = -1;
38 $this->mNamespace = 0;
39 $this->mRestrictionsLoaded = false;
40 $this->mRestrictions = array();
41 $this->mDefaultNamespace = 0;
44 # From a prefixed DB key
45 /* static */ function newFromDBkey( $key )
47 $t = new Title();
48 $t->mDbkeyform = $key;
49 if( $t->secureAndSplit() )
50 return $t;
51 else
52 return NULL;
55 # From text, such as what you would find in a link
56 /* static */ function newFromText( $text, $defaultNamespace = 0 )
58 $fname = "Title::newFromText";
59 wfProfileIn( $fname );
61 if( is_object( $text ) ) {
62 wfDebugDieBacktrace( "Called with object instead of string." );
64 global $wgInputEncoding;
65 $text = do_html_entity_decode( $text, ENT_COMPAT, $wgInputEncoding );
67 $text = wfMungeToUtf8( $text );
70 # What was this for? TS 2004-03-03
71 # $text = urldecode( $text );
73 $t = new Title();
74 $t->mDbkeyform = str_replace( " ", "_", $text );
75 $t->mDefaultNamespace = $defaultNamespace;
77 wfProfileOut( $fname );
78 if ( !is_object( $t ) ) {
79 var_dump( debug_backtrace() );
81 if( $t->secureAndSplit() ) {
82 return $t;
83 } else {
84 return NULL;
88 # From a URL-encoded title
89 /* static */ function newFromURL( $url )
91 global $wgLang, $wgServer;
92 $t = new Title();
94 # For compatibility with old buggy URLs. "+" is not valid in titles,
95 # but some URLs used it as a space replacement and they still come
96 # from some external search tools.
97 $s = str_replace( "+", " ", $url );
99 # For links that came from outside, check for alternate/legacy
100 # character encoding.
101 wfDebug( "Servr: $wgServer\n" );
102 if( empty( $_SERVER["HTTP_REFERER"] ) ||
103 strncmp($wgServer, $_SERVER["HTTP_REFERER"], strlen( $wgServer ) ) )
105 $s = $wgLang->checkTitleEncoding( $s );
106 } else {
107 wfDebug( "Refer: {$_SERVER['HTTP_REFERER']}\n" );
110 $t->mDbkeyform = str_replace( " ", "_", $s );
111 if( $t->secureAndSplit() ) {
112 # check that length of title is < cur_title size
113 $dbr =& wfGetDB( DB_SLAVE );
114 $maxSize = $dbr->textFieldSize( 'cur', 'cur_title' );
115 if ( $maxSize != -1 && strlen( $t->mDbkeyform ) > $maxSize ) {
116 return NULL;
119 return $t;
120 } else {
121 return NULL;
125 # From a cur_id
126 # This is inefficiently implemented, the cur row is requested but not
127 # used for anything else
128 /* static */ function newFromID( $id )
130 $fname = "Title::newFromID";
131 $dbr =& wfGetDB( DB_SLAVE );
132 $row = $dbr->getArray( "cur", array( "cur_namespace", "cur_title" ),
133 array( "cur_id" => $id ), $fname );
134 if ( $row !== false ) {
135 $title = Title::makeTitle( $row->cur_namespace, $row->cur_title );
136 } else {
137 $title = NULL;
139 return $title;
142 # From a namespace index and a DB key
143 /* static */ function makeTitle( $ns, $title )
145 $t = new Title();
146 $t->mDbkeyform = Title::makeName( $ns, $title );
147 if( $t->secureAndSplit() ) {
148 return $t;
149 } else {
150 return NULL;
154 function newMainPage()
156 return Title::newFromText( wfMsg( "mainpage" ) );
159 #----------------------------------------------------------------------------
160 # Static functions
161 #----------------------------------------------------------------------------
163 # Get the prefixed DB key associated with an ID
164 /* static */ function nameOf( $id )
166 $fname = 'Title::nameOf';
167 $dbr =& wfGetDB( DB_SLAVE );
169 $s = $dbr->getArray( 'cur', array( 'cur_namespace','cur_title' ), array( 'cur_id' => $id ), $fname );
170 if ( $s === false ) { return NULL; }
172 $n = Title::makeName( $s->cur_namespace, $s->cur_title );
173 return $n;
176 # Get a regex character class describing the legal characters in a link
177 /* static */ function legalChars()
179 # Missing characters:
180 # * []|# Needed for link syntax
181 # * % and + are corrupted by Apache when they appear in the path
183 # % seems to work though
185 # The problem with % is that URLs are double-unescaped: once by Apache's
186 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
187 # Our code does not double-escape to compensate for this, indeed double escaping
188 # would break if the double-escaped title was passed in the query string
189 # rather than the path. This is a minor security issue because articles can be
190 # created such that they are hard to view or edit. -- TS
192 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
193 # this breaks interlanguage links
195 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z{}~\\x80-\\xFF";
196 return $set;
199 # Returns a stripped-down a title string ready for the search index
200 # Takes a namespace index and a text-form main part
201 /* static */ function indexTitle( $ns, $title )
203 global $wgDBminWordLen, $wgLang;
205 $lc = SearchEngine::legalSearchChars() . "&#;";
206 $t = $wgLang->stripForSearch( $title );
207 $t = preg_replace( "/[^{$lc}]+/", " ", $t );
208 $t = strtolower( $t );
210 # Handle 's, s'
211 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
212 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
214 $t = preg_replace( "/\\s+/", " ", $t );
216 if ( $ns == Namespace::getImage() ) {
217 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
219 return trim( $t );
222 # Make a prefixed DB key from a DB key and a namespace index
223 /* static */ function makeName( $ns, $title )
225 global $wgLang;
227 $n = $wgLang->getNsText( $ns );
228 if ( "" == $n ) { return $title; }
229 else { return "{$n}:{$title}"; }
232 # Arguably static
233 # Returns the URL associated with an interwiki prefix
234 # The URL contains $1, which is replaced by the title
235 function getInterwikiLink( $key )
237 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
238 $fname = 'Title::getInterwikiLink';
239 $k = "$wgDBname:interwiki:$key";
241 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
242 return $wgTitleInterwikiCache[$k]->iw_url;
244 $s = $wgMemc->get( $k );
245 # Ignore old keys with no iw_local
246 if( $s && isset( $s->iw_local ) ) {
247 $wgTitleInterwikiCache[$k] = $s;
248 return $s->iw_url;
250 $dbr =& wfGetDB( DB_SLAVE );
251 $res = $dbr->select( 'interwiki', array( 'iw_url', 'iw_local' ), array( 'iw_prefix' => $key ), $fname );
252 if(!$res) return "";
254 $s = $dbr->fetchObject( $res );
255 if(!$s) {
256 # Cache non-existence: create a blank object and save it to memcached
257 $s = (object)false;
258 $s->iw_url = "";
259 $s->iw_local = 0;
261 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
262 $wgTitleInterwikiCache[$k] = $s;
263 return $s->iw_url;
266 function isLocal() {
267 global $wgTitleInterwikiCache, $wgDBname;
269 if ( $this->mInterwiki != "" ) {
270 # Make sure key is loaded into cache
271 $this->getInterwikiLink( $this->mInterwiki );
272 $k = "$wgDBname:interwiki:" . $this->mInterwiki;
273 return (bool)($wgTitleInterwikiCache[$k]->iw_local);
274 } else {
275 return true;
279 # Update the cur_touched field for an array of title objects
280 # Inefficient unless the IDs are already loaded into the link cache
281 /* static */ function touchArray( $titles, $timestamp = "" ) {
282 if ( count( $titles ) == 0 ) {
283 return;
285 if ( $timestamp == "" ) {
286 $timestamp = wfTimestampNow();
288 $dbw =& wfGetDB( DB_MASTER );
289 $cur = $dbw->tableName( 'cur' );
290 $sql = "UPDATE $cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
291 $first = true;
293 foreach ( $titles as $title ) {
294 if ( ! $first ) {
295 $sql .= ",";
297 $first = false;
298 $sql .= $title->getArticleID();
300 $sql .= ")";
301 if ( ! $first ) {
302 $dbw->query( $sql, "Title::touchArray" );
306 #----------------------------------------------------------------------------
307 # Other stuff
308 #----------------------------------------------------------------------------
310 # Simple accessors
311 # See the definitions at the top of this file
313 function getText() { return $this->mTextform; }
314 function getPartialURL() { return $this->mUrlform; }
315 function getDBkey() { return $this->mDbkeyform; }
316 function getNamespace() { return $this->mNamespace; }
317 function setNamespace( $n ) { $this->mNamespace = $n; }
318 function getInterwiki() { return $this->mInterwiki; }
319 function getFragment() { return $this->mFragment; }
320 function getDefaultNamespace() { return $this->mDefaultNamespace; }
322 # Get title for search index
323 function getIndexTitle()
325 return Title::indexTitle( $this->mNamespace, $this->mTextform );
328 # Get prefixed title with underscores
329 function getPrefixedDBkey()
331 $s = $this->prefix( $this->mDbkeyform );
332 $s = str_replace( " ", "_", $s );
333 return $s;
336 # Get prefixed title with spaces
337 # This is the form usually used for display
338 function getPrefixedText()
340 if ( empty( $this->mPrefixedText ) ) {
341 $s = $this->prefix( $this->mTextform );
342 $s = str_replace( "_", " ", $s );
343 $this->mPrefixedText = $s;
345 return $this->mPrefixedText;
348 # As getPrefixedText(), plus fragment.
349 function getFullText() {
350 $text = $this->getPrefixedText();
351 if( '' != $this->mFragment ) {
352 $text .= '#' . $this->mFragment;
354 return $text;
357 # Get a URL-encoded title (not an actual URL) including interwiki
358 function getPrefixedURL()
360 $s = $this->prefix( $this->mDbkeyform );
361 $s = str_replace( " ", "_", $s );
363 $s = wfUrlencode ( $s ) ;
365 # Cleaning up URL to make it look nice -- is this safe?
366 $s = preg_replace( "/%3[Aa]/", ":", $s );
367 $s = preg_replace( "/%2[Ff]/", "/", $s );
368 $s = str_replace( "%28", "(", $s );
369 $s = str_replace( "%29", ")", $s );
371 return $s;
374 # Get a real URL referring to this title, with interwiki link and fragment
375 function getFullURL( $query = "" )
377 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
379 if ( "" == $this->mInterwiki ) {
380 $p = $wgArticlePath;
381 return $wgServer . $this->getLocalUrl( $query );
382 } else {
383 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
384 $namespace = $wgLang->getNsText( $this->mNamespace );
385 if ( "" != $namespace ) {
386 # Can this actually happen? Interwikis shouldn't be parsed.
387 $namepace .= ":";
389 $url = str_replace( "$1", $namespace . $this->mUrlform, $baseUrl );
390 if ( '' != $this->mFragment ) {
391 $url .= '#' . $this->mFragment;
393 return $url;
397 # Get a URL with an optional query string, no fragment
398 # * If $query=="", it will use $wgArticlePath
399 # * Returns a full for an interwiki link, loses any query string
400 # * Optionally adds the server and escapes for HTML
401 # * Setting $query to "-" makes an old-style URL with nothing in the
402 # query except a title
404 function getURL() {
405 die( "Call to obsolete obsolete function Title::getURL()" );
408 function getLocalURL( $query = "" )
410 global $wgLang, $wgArticlePath, $wgScript;
412 if ( $this->isExternal() ) {
413 return $this->getFullURL();
416 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
417 if ( $query == "" ) {
418 $url = str_replace( "$1", $dbkey, $wgArticlePath );
419 } else {
420 if ( $query == "-" ) {
421 $query = "";
423 if ( $wgScript != "" ) {
424 $url = "{$wgScript}?title={$dbkey}&{$query}";
425 } else {
426 # Top level wiki
427 $url = "/{$dbkey}?{$query}";
430 return $url;
433 function escapeLocalURL( $query = "" ) {
434 return wfEscapeHTML( $this->getLocalURL( $query ) );
437 function escapeFullURL( $query = "" ) {
438 return wfEscapeHTML( $this->getFullURL( $query ) );
441 function getInternalURL( $query = "" ) {
442 # Used in various Squid-related code, in case we have a different
443 # internal hostname for the server than the exposed one.
444 global $wgInternalServer;
445 return $wgInternalServer . $this->getLocalURL( $query );
448 # Get the edit URL, or a null string if it is an interwiki link
449 function getEditURL()
451 global $wgServer, $wgScript;
453 if ( "" != $this->mInterwiki ) { return ""; }
454 $s = $this->getLocalURL( "action=edit" );
456 return $s;
459 # Get HTML-escaped displayable text
460 # For the title field in <a> tags
461 function getEscapedText()
463 return wfEscapeHTML( $this->getPrefixedText() );
466 # Is the title interwiki?
467 function isExternal() { return ( "" != $this->mInterwiki ); }
469 # Does the title correspond to a protected article?
470 function isProtected()
472 if ( -1 == $this->mNamespace ) { return true; }
473 $a = $this->getRestrictions();
474 if ( in_array( "sysop", $a ) ) { return true; }
475 return false;
478 # Is the page a log page, i.e. one where the history is messed up by
479 # LogPage.php? This used to be used for suppressing diff links in recent
480 # changes, but now that's done by setting a flag in the recentchanges
481 # table. Hence, this probably is no longer used.
482 function isLog()
484 if ( $this->mNamespace != Namespace::getWikipedia() ) {
485 return false;
487 if ( ( 0 == strcmp( wfMsg( "uploadlogpage" ), $this->mDbkeyform ) ) ||
488 ( 0 == strcmp( wfMsg( "dellogpage" ), $this->mDbkeyform ) ) ) {
489 return true;
491 return false;
494 # Is $wgUser is watching this page?
495 function userIsWatching()
497 global $wgUser;
499 if ( -1 == $this->mNamespace ) { return false; }
500 if ( 0 == $wgUser->getID() ) { return false; }
502 return $wgUser->isWatched( $this );
505 # Can $wgUser edit this page?
506 function userCanEdit()
508 global $wgUser;
509 if ( -1 == $this->mNamespace ) { return false; }
510 if ( NS_MEDIAWIKI == $this->mNamespace && !$wgUser->isSysop() ) { return false; }
511 # if ( 0 == $this->getArticleID() ) { return false; }
512 if ( $this->mDbkeyform == "_" ) { return false; }
513 # protect global styles and js
514 if ( NS_MEDIAWIKI == $this->mNamespace
515 && preg_match("/\\.(css|js)$/", $this->mTextform )
516 && !$wgUser->isSysop() )
517 { return false; }
518 //if ( $this->isCssJsSubpage() and !$this->userCanEditCssJsSubpage() ) { return false; }
519 # protect css/js subpages of user pages
520 # XXX: this might be better using restrictions
521 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
522 if( Namespace::getUser() == $this->mNamespace
523 and preg_match("/\\.(css|js)$/", $this->mTextform )
524 and !$wgUser->isSysop()
525 and !preg_match("/^".preg_quote($wgUser->getName(), '/')."/", $this->mTextform) )
526 { return false; }
527 $ur = $wgUser->getRights();
528 foreach ( $this->getRestrictions() as $r ) {
529 if ( "" != $r && ( ! in_array( $r, $ur ) ) ) {
530 return false;
533 return true;
536 function userCanRead() {
537 global $wgUser;
538 global $wgWhitelistRead;
540 if( 0 != $wgUser->getID() ) return true;
541 if( !is_array( $wgWhitelistRead ) ) return true;
543 $name = $this->getPrefixedText();
544 if( in_array( $name, $wgWhitelistRead ) ) return true;
546 # Compatibility with old settings
547 if( $this->getNamespace() == NS_MAIN ) {
548 if( in_array( ":" . $name, $wgWhitelistRead ) ) return true;
550 return false;
553 function isCssJsSubpage() {
554 return ( Namespace::getUser() == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
556 function isCssSubpage() {
557 return ( Namespace::getUser() == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
559 function isJsSubpage() {
560 return ( Namespace::getUser() == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
562 function userCanEditCssJsSubpage() {
563 # protect css/js subpages of user pages
564 # XXX: this might be better using restrictions
565 global $wgUser;
566 return ( $wgUser->isSysop() or preg_match("/^".preg_quote($wgUser->getName())."/", $this->mTextform) );
569 # Accessor/initialisation for mRestrictions
570 function getRestrictions()
572 $id = $this->getArticleID();
573 if ( 0 == $id ) { return array(); }
575 if ( ! $this->mRestrictionsLoaded ) {
576 $dbr =& wfGetDB( DB_SLAVE );
577 $res = $dbr->getField( "cur", "cur_restrictions", "cur_id=$id" );
578 $this->mRestrictions = explode( ",", trim( $res ) );
579 $this->mRestrictionsLoaded = true;
581 return $this->mRestrictions;
584 # Is there a version of this page in the deletion archive?
585 # Returns the number of archived revisions
586 function isDeleted() {
587 $fname = 'Title::isDeleted';
588 $dbr =& wfGetDB( DB_SLAVE );
589 $n = $dbr->getField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
590 'ar_title' => $this->getDBkey() ), $fname );
591 return (int)$n;
594 # Get the article ID from the link cache
595 # Used very heavily, e.g. in Parser::replaceInternalLinks()
596 function getArticleID()
598 global $wgLinkCache;
600 if ( -1 != $this->mArticleID ) { return $this->mArticleID; }
601 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
602 return $this->mArticleID;
605 # This clears some fields in this object, and clears any associated keys in the
606 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
607 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
608 function resetArticleID( $newid )
610 global $wgLinkCache;
611 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
613 if ( 0 == $newid ) { $this->mArticleID = -1; }
614 else { $this->mArticleID = $newid; }
615 $this->mRestrictionsLoaded = false;
616 $this->mRestrictions = array();
619 # Updates cur_touched
620 # Called from LinksUpdate.php
621 function invalidateCache() {
622 $now = wfTimestampNow();
623 $dbw =& wfGetDB( DB_MASTER );
624 $success = $dbw->updateArray( 'cur',
625 array( /* SET */
626 'cur_touched' => wfTimestampNow()
627 ), array( /* WHERE */
628 'cur_namespace' => $this->getNamespace() ,
629 'cur_title' => $this->getDBkey()
630 ), 'Title::invalidateCache'
632 return $success;
635 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
636 /* private */ function prefix( $name )
638 global $wgLang;
640 $p = "";
641 if ( "" != $this->mInterwiki ) {
642 $p = $this->mInterwiki . ":";
644 if ( 0 != $this->mNamespace ) {
645 $p .= $wgLang->getNsText( $this->mNamespace ) . ":";
647 return $p . $name;
650 # Secure and split - main initialisation function for this object
652 # Assumes that mDbkeyform has been set, and is urldecoded
653 # and uses underscores, but not otherwise munged. This function
654 # removes illegal characters, splits off the interwiki and
655 # namespace prefixes, sets the other forms, and canonicalizes
656 # everything.
658 /* private */ function secureAndSplit()
660 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
661 $fname = "Title::secureAndSplit";
662 wfProfileIn( $fname );
664 static $imgpre = false;
665 static $rxTc = false;
667 # Initialisation
668 if ( $imgpre === false ) {
669 $imgpre = ":" . $wgLang->getNsText( Namespace::getImage() ) . ":";
670 # % is needed as well
671 $rxTc = "/[^" . Title::legalChars() . "]/";
674 $this->mInterwiki = $this->mFragment = "";
675 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
677 # Clean up whitespace
679 $t = preg_replace( "/[\\s_]+/", "_", $this->mDbkeyform );
680 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
682 if ( "" == $t ) {
683 wfProfileOut( $fname );
684 return false;
687 $this->mDbkeyform = $t;
688 $done = false;
690 # :Image: namespace
691 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
692 $t = substr( $t, 1 );
695 # Initial colon indicating main namespace
696 if ( ":" == $t{0} ) {
697 $r = substr( $t, 1 );
698 $this->mNamespace = NS_MAIN;
699 } else {
700 # Namespace or interwiki prefix
701 if ( preg_match( "/^(.+?)_*:_*(.*)$/", $t, $m ) ) {
702 #$p = strtolower( $m[1] );
703 $p = $m[1];
704 $lowerNs = strtolower( $p );
705 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
706 # Canonical namespace
707 $t = $m[2];
708 $this->mNamespace = $ns;
709 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
710 # Ordinary namespace
711 $t = $m[2];
712 $this->mNamespace = $ns;
713 } elseif ( $this->getInterwikiLink( $p ) ) {
714 # Interwiki link
715 $t = $m[2];
716 $this->mInterwiki = $p;
718 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
719 $done = true;
720 } elseif($this->mInterwiki != $wgLocalInterwiki) {
721 $done = true;
725 $r = $t;
728 # Redundant interwiki prefix to the local wiki
729 if ( 0 == strcmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
730 $this->mInterwiki = "";
732 # We already know that some pages won't be in the database!
734 if ( "" != $this->mInterwiki || -1 == $this->mNamespace ) {
735 $this->mArticleID = 0;
737 $f = strstr( $r, "#" );
738 if ( false !== $f ) {
739 $this->mFragment = substr( $f, 1 );
740 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
743 # Reject illegal characters.
745 if( preg_match( $rxTc, $r ) ) {
746 wfProfileOut( $fname );
747 return false;
750 # "." and ".." conflict with the directories of those namesa
751 if ( strpos( $r, "." ) !== false &&
752 ( $r === "." || $r === ".." ||
753 strpos( $r, "./" ) === 0 ||
754 strpos( $r, "../" ) === 0 ||
755 strpos( $r, "/./" ) !== false ||
756 strpos( $r, "/../" ) !== false ) )
758 wfProfileOut( $fname );
759 return false;
762 # Initial capital letter
763 if( $wgCapitalLinks && $this->mInterwiki == "") {
764 $t = $wgLang->ucfirst( $r );
765 } else {
766 $t = $r;
769 # Fill fields
770 $this->mDbkeyform = $t;
771 $this->mUrlform = wfUrlencode( $t );
773 $this->mTextform = str_replace( "_", " ", $t );
775 wfProfileOut( $fname );
776 return true;
779 # Get a title object associated with the talk page of this article
780 function getTalkPage() {
781 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
784 # Get a title object associated with the subject page of this talk page
785 function getSubjectPage() {
786 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
789 # Get an array of Title objects linking to this title
790 # Also stores the IDs in the link cache
791 # $options may be FOR UPDATE
792 function getLinksTo( $options = '' ) {
793 global $wgLinkCache;
794 $id = $this->getArticleID();
796 if ( $options ) {
797 $db =& wfGetDB( DB_MASTER );
798 } else {
799 $db =& wfGetDB( DB_SLAVE );
801 $cur = $db->tableName( 'cur' );
802 $links = $db->tableName( 'links' );
804 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
805 $res = $db->query( $sql, "Title::getLinksTo" );
806 $retVal = array();
807 if ( $db->numRows( $res ) ) {
808 while ( $row = $db->fetchObject( $res ) ) {
809 if ( $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title ) ) {
810 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
811 $retVal[] = $titleObj;
815 $db->freeResult( $res );
816 return $retVal;
819 # Get an array of Title objects linking to this non-existent title
820 # Also stores the IDs in the link cache
821 function getBrokenLinksTo( $options = '' ) {
822 global $wgLinkCache;
824 if ( $options ) {
825 $db =& wfGetDB( DB_MASTER );
826 } else {
827 $db =& wfGetDB( DB_SLAVE );
829 $cur = $db->tableName( 'cur' );
830 $brokenlinks = $db->tableName( 'brokenlinks' );
831 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
833 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
834 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
835 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
836 $retVal = array();
837 if ( $db->numRows( $res ) ) {
838 while ( $row = $db->fetchObject( $res ) ) {
839 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
840 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
841 $retVal[] = $titleObj;
844 $db->freeResult( $res );
845 return $retVal;
848 function getSquidURLs() {
849 return array(
850 $this->getInternalURL(),
851 $this->getInternalURL( "action=history" )
855 function moveNoAuth( &$nt ) {
856 return $this->moveTo( $nt, false );
859 # Move a title to a new location
860 # Returns true on success, message name on failure
861 # auth indicates whether wgUser's permissions should be checked
862 function moveTo( &$nt, $auth = true ) {
863 if( !$this or !$nt ) {
864 return "badtitletext";
867 $fname = "Title::move";
868 $oldid = $this->getArticleID();
869 $newid = $nt->getArticleID();
871 if ( strlen( $nt->getDBkey() ) < 1 ) {
872 return "articleexists";
874 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
875 ( "" == $this->getDBkey() ) ||
876 ( "" != $this->getInterwiki() ) ||
877 ( !$oldid ) ||
878 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
879 ( "" == $nt->getDBkey() ) ||
880 ( "" != $nt->getInterwiki() ) ) {
881 return "badarticleerror";
884 if ( $auth && ( !$this->userCanEdit() || !$nt->userCanEdit() ) ) {
885 return "protectedpage";
888 # The move is allowed only if (1) the target doesn't exist, or
889 # (2) the target is a redirect to the source, and has no history
890 # (so we can undo bad moves right after they're done).
892 if ( 0 != $newid ) { # Target exists; check for validity
893 if ( ! $this->isValidMoveTarget( $nt ) ) {
894 return "articleexists";
896 $this->moveOverExistingRedirect( $nt );
897 } else { # Target didn't exist, do normal move.
898 $this->moveToNewTitle( $nt, $newid );
902 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
904 $dbw =& wfGetDB( DB_MASTER );
905 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
906 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
907 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
908 $dbw->query( $sql, "SpecialMovepage::doSubmit" );
911 # Update watchlists
913 $oldnamespace = $this->getNamespace() & ~1;
914 $newnamespace = $nt->getNamespace() & ~1;
915 $oldtitle = $this->getDBkey();
916 $newtitle = $nt->getDBkey();
918 if( $oldnamespace != $newnamespace && $oldtitle != $newtitle ) {
919 WatchedItem::duplicateEntries( $this, $nt );
922 # Update search engine
923 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
924 $u->doUpdate();
925 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
926 $u->doUpdate();
928 return true;
931 # Move page to title which is presently a redirect to the source page
933 /* private */ function moveOverExistingRedirect( &$nt )
935 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
936 $fname = "Title::moveOverExistingRedirect";
937 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
939 $now = wfTimestampNow();
940 $won = wfInvertTimestamp( $now );
941 $newid = $nt->getArticleID();
942 $oldid = $this->getArticleID();
943 $dbw =& wfGetDB( DB_MASTER );
944 $links = $dbw->tableName( 'links' );
946 # Change the name of the target page:
947 $dbw->updateArray( 'cur',
948 /* SET */ array(
949 'cur_touched' => $now,
950 'cur_namespace' => $nt->getNamespace(),
951 'cur_title' => $nt->getDBkey()
953 /* WHERE */ array( 'cur_id' => $oldid ),
954 $fname
956 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
958 # Repurpose the old redirect. We don't save it to history since
959 # by definition if we've got here it's rather uninteresting.
961 $redirectText = $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n";
962 $dbw->updateArray( 'cur',
963 /* SET */ array(
964 'cur_touched' => $now,
965 'cur_timestamp' => $now,
966 'inverse_timestamp' => $won,
967 'cur_namespace' => $this->getNamespace(),
968 'cur_title' => $this->getDBkey(),
969 'cur_text' => $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n",
970 'cur_comment' => $comment,
971 'cur_user' => $wgUser->getID(),
972 'cur_minor_edit' => 0,
973 'cur_counter' => 0,
974 'cur_restrictions' => '',
975 'cur_user_text' => $wgUser->getName(),
976 'cur_is_redirect' => 1,
977 'cur_is_new' => 1
979 /* WHERE */ array( 'cur_id' => $newid ),
980 $fname
983 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
985 # Fix the redundant names for the past revisions of the target page.
986 # The redirect should have no old revisions.
987 $dbw->updateArray(
988 /* table */ 'old',
989 /* SET */ array(
990 'old_namespace' => $nt->getNamespace(),
991 'old_title' => $nt->getDBkey(),
993 /* WHERE */ array(
994 'old_namespace' => $this->getNamespace(),
995 'old_title' => $this->getDBkey(),
997 $fname
1000 RecentChange::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
1002 # Swap links
1004 # Load titles and IDs
1005 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1006 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1008 # Delete them all
1009 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1010 $dbw->query( $sql, $fname );
1012 # Reinsert
1013 if ( count( $linksToOld ) || count( $linksToNew )) {
1014 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1015 $first = true;
1017 # Insert links to old title
1018 foreach ( $linksToOld as $linkTitle ) {
1019 if ( $first ) {
1020 $first = false;
1021 } else {
1022 $sql .= ",";
1024 $id = $linkTitle->getArticleID();
1025 $sql .= "($id,$newid)";
1028 # Insert links to new title
1029 foreach ( $linksToNew as $linkTitle ) {
1030 if ( $first ) {
1031 $first = false;
1032 } else {
1033 $sql .= ",";
1035 $id = $linkTitle->getArticleID();
1036 $sql .= "($id, $oldid)";
1039 $dbw->query( $sql, DB_MASTER, $fname );
1042 # Now, we record the link from the redirect to the new title.
1043 # It should have no other outgoing links...
1044 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1045 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1047 # Clear linkscc
1048 LinkCache::linksccClearLinksTo( $oldid );
1049 LinkCache::linksccClearLinksTo( $newid );
1051 # Purge squid
1052 if ( $wgUseSquid ) {
1053 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1054 $u = new SquidUpdate( $urls );
1055 $u->doUpdate();
1059 # Move page to non-existing title.
1060 # Sets $newid to be the new article ID
1062 /* private */ function moveToNewTitle( &$nt, &$newid )
1064 global $wgUser, $wgLinkCache, $wgUseSquid;
1065 $fname = "MovePageForm::moveToNewTitle";
1066 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
1068 $now = wfTimestampNow();
1069 $won = wfInvertTimestamp( $now );
1070 $newid = $nt->getArticleID();
1071 $oldid = $this->getArticleID();
1072 $dbw =& wfGetDB( DB_MASTER );
1074 # Rename cur entry
1075 $dbw->updateArray( 'cur',
1076 /* SET */ array(
1077 'cur_touched' => $now,
1078 'cur_namespace' => $nt->getNamespace(),
1079 'cur_title' => $nt->getDBkey()
1081 /* WHERE */ array( 'cur_id' => $oldid ),
1082 $fname
1085 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1087 # Insert redirct
1088 $dbw->insertArray( 'cur', array(
1089 'cur_namespace' => $this->getNamespace(),
1090 'cur_title' => $this->getDBkey(),
1091 'cur_comment' => $comment,
1092 'cur_user' => $wgUser->getID(),
1093 'cur_user_text' => $wgUser->getName(),
1094 'cur_timestamp' => $now,
1095 'inverse_timestamp' => $won,
1096 'cur_touched' => $now,
1097 'cur_is_redirect' => 1,
1098 'cur_is_new' => 1,
1099 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1101 $newid = $dbw->insertId();
1102 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1104 # Rename old entries
1105 $dbw->updateArray(
1106 /* table */ 'old',
1107 /* SET */ array(
1108 'old_namespace' => $nt->getNamespace(),
1109 'old_title' => $nt->getDBkey()
1111 /* WHERE */ array(
1112 'old_namespace' => $this->getNamespace(),
1113 'old_title' => $this->getDBkey()
1114 ), $fname
1117 # Record in RC
1118 RecentChange::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1120 # Purge squid and linkscc as per article creation
1121 Article::onArticleCreate( $nt );
1123 # Any text links to the old title must be reassigned to the redirect
1124 $dbw->updateArray( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1125 LinkCache::linksccClearLinksTo( $oldid );
1127 # Record the just-created redirect's linking to the page
1128 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1130 # Non-existent target may have had broken links to it; these must
1131 # now be removed and made into good links.
1132 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1133 $update->fixBrokenLinks();
1135 # Purge old title from squid
1136 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1137 $titles = $nt->getLinksTo();
1138 if ( $wgUseSquid ) {
1139 $urls = $this->getSquidURLs();
1140 foreach ( $titles as $linkTitle ) {
1141 $urls[] = $linkTitle->getInternalURL();
1143 $u = new SquidUpdate( $urls );
1144 $u->doUpdate();
1148 # Checks if $this can be moved to $nt
1149 # Selects for update, so don't call it unless you mean business
1150 function isValidMoveTarget( $nt )
1152 $fname = "Title::isValidMoveTarget";
1153 $dbw =& wfGetDB( DB_MASTER );
1155 # Is it a redirect?
1156 $id = $nt->getArticleID();
1157 $obj = $dbw->getArray( 'cur', array( 'cur_is_redirect','cur_text' ),
1158 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1160 if ( !$obj || 0 == $obj->cur_is_redirect ) {
1161 # Not a redirect
1162 return false;
1165 # Does the redirect point to the source?
1166 if ( preg_match( "/\\[\\[\\s*([^\\]]*)]]/", $obj->cur_text, $m ) ) {
1167 $redirTitle = Title::newFromText( $m[1] );
1168 if ( 0 != strcmp( $redirTitle->getPrefixedDBkey(), $this->getPrefixedDBkey() ) ) {
1169 return false;
1173 # Does the article have a history?
1174 $row = $dbw->getArray( 'old', array( 'old_id' ),
1175 array(
1176 'old_namespace' => $nt->getNamespace(),
1177 'old_title' => $nt->getDBkey()
1178 ), $fname, 'FOR UPDATE'
1181 # Return true if there was no history
1182 return $row === false;
1185 # Create a redirect, fails if the title already exists, does not notify RC
1186 # Returns success
1187 function createRedirect( $dest, $comment ) {
1188 global $wgUser;
1189 if ( $this->getArticleID() ) {
1190 return false;
1193 $fname = "Title::createRedirect";
1194 $dbw =& wfGetDB( DB_MASTER );
1195 $now = wfTimestampNow();
1196 $won = wfInvertTimestamp( $now );
1197 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1199 $dbw->insertArray( 'cur', array(
1200 'cur_id' => $seqVal,
1201 'cur_namespace' => $this->getNamespace(),
1202 'cur_title' => $this->getDBkey(),
1203 'cur_comment' => $comment,
1204 'cur_user' => $wgUser->getID(),
1205 'cur_user_text' => $wgUser->getName(),
1206 'cur_timestamp' => $now,
1207 'inverse_timestamp' => $won,
1208 'cur_touched' => $now,
1209 'cur_is_redirect' => 1,
1210 'cur_is_new' => 1,
1211 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1212 ), $fname );
1213 $newid = $dbw->insertId();
1214 $this->resetArticleID( $newid );
1216 # Link table
1217 if ( $dest->getArticleID() ) {
1218 $dbw->insertArray( 'links',
1219 array(
1220 'l_to' => $dest->getArticleID(),
1221 'l_from' => $newid
1222 ), $fname
1224 } else {
1225 $dbw->insertArray( 'brokenlinks',
1226 array(
1227 'bl_to' => $dest->getPrefixedDBkey(),
1228 'bl_from' => $newid
1229 ), $fname
1233 Article::onArticleCreate( $this );
1234 return true;
1237 # Get categories to wich belong this title and return an array of
1238 # categories names.
1239 function getParentCategories( )
1241 global $wgLang,$wgUser;
1243 $titlekey = $this->getArticleId();
1244 $cns = Namespace::getCategory();
1245 $sk =& $wgUser->getSkin();
1246 $parents = array();
1247 $dbr =& wfGetDB( DB_SLAVE );
1248 $cur = $dbr->tableName( 'cur' );
1249 $categorylinks = $dbr->tableName( 'categorylinks' );
1251 # get the parents categories of this title from the database
1252 $sql = "SELECT DISTINCT cur_id FROM $cur,$categorylinks
1253 WHERE cl_from='$titlekey' AND cl_to=cur_title AND cur_namespace='$cns'
1254 ORDER BY cl_sortkey" ;
1255 $res = $dbr->query ( $sql ) ;
1257 if($dbr->numRows($res) > 0) {
1258 while ( $x = $dbr->fetchObject ( $res ) ) $data[] = $x ;
1259 $dbr->freeResult ( $res ) ;
1260 } else {
1261 $data = '';
1263 return $data;
1266 # will get the parents and grand-parents
1267 # TODO : not sure what's happening when a loop happen like:
1268 # Encyclopedia > Astronomy > Encyclopedia
1269 function getAllParentCategories(&$stack)
1271 global $wgUser,$wgLang;
1272 $result = '';
1274 # getting parents
1275 $parents = $this->getParentCategories( );
1277 if($parents == '')
1279 # The current element has no more parent so we dump the stack
1280 # and make a clean line of categories
1281 $sk =& $wgUser->getSkin() ;
1283 foreach ( array_reverse($stack) as $child => $parent )
1285 # make a link of that parent
1286 $result .= $sk->makeLink($wgLang->getNSText ( Namespace::getCategory() ).":".$parent,$parent);
1287 $result .= ' &gt; ';
1288 $lastchild = $child;
1290 # append the last child.
1291 # TODO : We should have a last child unless there is an error in the
1292 # "categorylinks" table.
1293 if(isset($lastchild)) { $result .= $lastchild; }
1295 $result .= "<br/>\n";
1297 # now we can empty the stack
1298 $stack = array();
1300 } else {
1301 # look at parents of current category
1302 foreach($parents as $parent)
1304 # create a title object for the parent
1305 $tpar = Title::newFromID($parent->cur_id);
1306 # add it to the stack
1307 $stack[$this->getText()] = $tpar->getText();
1308 # grab its parents
1309 $result .= $tpar->getAllParentCategories($stack);
1313 if(isset($result)) { return $result; }
1314 else { return ''; };
1317 # Returns an associative array for selecting this title from cur
1318 function curCond() {
1319 return array( 'cur_namespace' => $this->mNamespace, 'cur_title' => $this->mDbkeyform );
1322 function oldCond() {
1323 return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );