khtml fix stylesheet
[mediawiki.git] / includes / Title.php
blobc4d49739c22b29a10f355b3a6c67b00a7b7e6f01
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();
93 $s = urldecode( $url ); # This is technically wrong, as anything
94 # we've gotten is already decoded by PHP.
95 # Kept for backwards compatibility with
96 # buggy URLs we had for a while...
97 $s = $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() ) {
113 # check that lenght of title is < cur_title size
114 $sql = "SHOW COLUMNS FROM cur LIKE \"cur_title\";";
115 $cur_title_object = wfFetchObject(wfQuery( $sql, DB_READ ));
117 preg_match( "/\((.*)\)/", $cur_title_object->Type, $cur_title_size);
119 if (strlen($t->mDbkeyform) > $cur_title_size[1] ) {
120 return NULL;
123 return $t;
124 } else {
125 return NULL;
129 # From a cur_id
130 # This is inefficiently implemented, the cur row is requested but not
131 # used for anything else
132 /* static */ function newFromID( $id )
134 $fname = "Title::newFromID";
135 $row = wfGetArray( "cur", array( "cur_namespace", "cur_title" ),
136 array( "cur_id" => $id ), $fname );
137 if ( $row !== false ) {
138 $title = Title::makeTitle( $row->cur_namespace, $row->cur_title );
139 } else {
140 $title = NULL;
142 return $title;
145 # From a namespace index and a DB key
146 /* static */ function makeTitle( $ns, $title )
148 $t = new Title();
149 $t->mDbkeyform = Title::makeName( $ns, $title );
150 if( $t->secureAndSplit() ) {
151 return $t;
152 } else {
153 return NULL;
157 function newMainPage()
159 return Title::newFromText( wfMsg( "mainpage" ) );
162 #----------------------------------------------------------------------------
163 # Static functions
164 #----------------------------------------------------------------------------
166 # Get the prefixed DB key associated with an ID
167 /* static */ function nameOf( $id )
169 $sql = "SELECT cur_namespace,cur_title FROM cur WHERE " .
170 "cur_id={$id}";
171 $res = wfQuery( $sql, DB_READ, "Article::nameOf" );
172 if ( 0 == wfNumRows( $res ) ) { return NULL; }
174 $s = wfFetchObject( $res );
175 $n = Title::makeName( $s->cur_namespace, $s->cur_title );
176 return $n;
179 # Get a regex character class describing the legal characters in a link
180 /* static */ function legalChars()
182 # Missing characters:
183 # * []|# Needed for link syntax
184 # * % and + are corrupted by Apache when they appear in the path
186 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
187 # this breaks interlanguage links
189 $set = " !\"$&'()*,\\-.\\/0-9:;<=>?@A-Z\\\\^_`a-z{}~\\x80-\\xFF";
190 return $set;
193 # Returns a stripped-down a title string ready for the search index
194 # Takes a namespace index and a text-form main part
195 /* static */ function indexTitle( $ns, $title )
197 global $wgDBminWordLen, $wgLang;
199 $lc = SearchEngine::legalSearchChars() . "&#;";
200 $t = $wgLang->stripForSearch( $title );
201 $t = preg_replace( "/[^{$lc}]+/", " ", $t );
202 $t = strtolower( $t );
204 # Handle 's, s'
205 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
206 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
208 $t = preg_replace( "/\\s+/", " ", $t );
210 if ( $ns == Namespace::getImage() ) {
211 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
213 return trim( $t );
216 # Make a prefixed DB key from a DB key and a namespace index
217 /* static */ function makeName( $ns, $title )
219 global $wgLang;
221 $n = $wgLang->getNsText( $ns );
222 if ( "" == $n ) { return $title; }
223 else { return "{$n}:{$title}"; }
226 # Arguably static
227 # Returns the URL associated with an interwiki prefix
228 # The URL contains $1, which is replaced by the title
229 function getInterwikiLink( $key )
231 global $wgMemc, $wgDBname, $wgInterwikiExpiry;
232 static $wgTitleInterwikiCache = array();
234 $k = "$wgDBname:interwiki:$key";
236 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
237 return $wgTitleInterwikiCache[$k]->iw_url;
239 $s = $wgMemc->get( $k );
240 # Ignore old keys with no iw_local
241 if( $s && isset( $s->iw_local ) ) {
242 $wgTitleInterwikiCache[$k] = $s;
243 return $s->iw_url;
245 $dkey = wfStrencode( $key );
246 $query = "SELECT iw_url,iw_local FROM interwiki WHERE iw_prefix='$dkey'";
247 $res = wfQuery( $query, DB_READ, "Title::getInterwikiLink" );
248 if(!$res) return "";
250 $s = wfFetchObject( $res );
251 if(!$s) {
252 $s = (object)false;
253 $s->iw_url = "";
255 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
256 $wgTitleInterwikiCache[$k] = $s;
257 return $s->iw_url;
260 function isLocal() {
261 global $wgTitleInterwikiCache, $wgDBname;
263 if ( $this->mInterwiki != "" ) {
264 # Make sure key is loaded into cache
265 $this->getInterwikiLink( $this->mInterwiki );
266 $k = "$wgDBname:interwiki:" . $this->mInterwiki;
267 return (bool)($wgTitleInterwikiCache[$k]->iw_local);
268 } else {
269 return true;
273 # Update the cur_touched field for an array of title objects
274 # Inefficient unless the IDs are already loaded into the link cache
275 /* static */ function touchArray( $titles, $timestamp = "" ) {
276 if ( count( $titles ) == 0 ) {
277 return;
279 if ( $timestamp == "" ) {
280 $timestamp = wfTimestampNow();
282 $sql = "UPDATE cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
283 $first = true;
285 foreach ( $titles as $title ) {
286 if ( ! $first ) {
287 $sql .= ",";
290 $first = false;
291 $sql .= $title->getArticleID();
293 $sql .= ")";
294 if ( ! $first ) {
295 wfQuery( $sql, DB_WRITE, "Title::touchArray" );
299 #----------------------------------------------------------------------------
300 # Other stuff
301 #----------------------------------------------------------------------------
303 # Simple accessors
304 # See the definitions at the top of this file
306 function getText() { return $this->mTextform; }
307 function getPartialURL() { return $this->mUrlform; }
308 function getDBkey() { return $this->mDbkeyform; }
309 function getNamespace() { return $this->mNamespace; }
310 function setNamespace( $n ) { $this->mNamespace = $n; }
311 function getInterwiki() { return $this->mInterwiki; }
312 function getFragment() { return $this->mFragment; }
313 function getDefaultNamespace() { return $this->mDefaultNamespace; }
315 # Get title for search index
316 function getIndexTitle()
318 return Title::indexTitle( $this->mNamespace, $this->mTextform );
321 # Get prefixed title with underscores
322 function getPrefixedDBkey()
324 $s = $this->prefix( $this->mDbkeyform );
325 $s = str_replace( " ", "_", $s );
326 return $s;
329 # Get prefixed title with spaces
330 # This is the form usually used for display
331 function getPrefixedText()
333 if ( empty( $this->mPrefixedText ) ) {
334 $s = $this->prefix( $this->mTextform );
335 $s = str_replace( "_", " ", $s );
336 $this->mPrefixedText = $s;
338 return $this->mPrefixedText;
341 # Get a URL-encoded title (not an actual URL) including interwiki
342 function getPrefixedURL()
344 $s = $this->prefix( $this->mDbkeyform );
345 $s = str_replace( " ", "_", $s );
347 $s = wfUrlencode ( $s ) ;
349 # Cleaning up URL to make it look nice -- is this safe?
350 $s = preg_replace( "/%3[Aa]/", ":", $s );
351 $s = preg_replace( "/%2[Ff]/", "/", $s );
352 $s = str_replace( "%28", "(", $s );
353 $s = str_replace( "%29", ")", $s );
355 return $s;
358 # Get a real URL referring to this title, with interwiki link and fragment
359 function getFullURL( $query = "" )
361 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
363 if ( "" == $this->mInterwiki ) {
364 $p = $wgArticlePath;
365 return $wgServer . $this->getLocalUrl( $query );
368 $p = $this->getInterwikiLink( $this->mInterwiki );
369 $n = $wgLang->getNsText( $this->mNamespace );
370 if ( "" != $n ) { $n .= ":"; }
371 $u = str_replace( "$1", $n . $this->mUrlform, $p );
372 if ( "" != $this->mFragment ) {
373 $u .= "#" . wfUrlencode( $this->mFragment );
375 return $u;
378 # Get a URL with an optional query string, no fragment
379 # * If $query=="", it will use $wgArticlePath
380 # * Returns a full for an interwiki link, loses any query string
381 # * Optionally adds the server and escapes for HTML
382 # * Setting $query to "-" makes an old-style URL with nothing in the
383 # query except a title
385 function getURL() {
386 die( "Call to obsolete obsolete function Title::getURL()" );
389 function getLocalURL( $query = "" )
391 global $wgLang, $wgArticlePath, $wgScript;
393 if ( $this->isExternal() ) {
394 return $this->getFullURL();
397 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
398 if ( $query == "" ) {
399 $url = str_replace( "$1", $dbkey, $wgArticlePath );
400 } else {
401 if ( $query == "-" ) {
402 $query = "";
404 if ( $wgScript != "" ) {
405 $url = "{$wgScript}?title={$dbkey}&{$query}";
406 } else {
407 # Top level wiki
408 $url = "/{$dbkey}?{$query}";
411 return $url;
414 function escapeLocalURL( $query = "" ) {
415 return wfEscapeHTML( $this->getLocalURL( $query ) );
418 function escapeFullURL( $query = "" ) {
419 return wfEscapeHTML( $this->getFullURL( $query ) );
422 function getInternalURL( $query = "" ) {
423 # Used in various Squid-related code, in case we have a different
424 # internal hostname for the server than the exposed one.
425 global $wgInternalServer;
426 return $wgInternalServer . $this->getLocalURL( $query );
429 # Get the edit URL, or a null string if it is an interwiki link
430 function getEditURL()
432 global $wgServer, $wgScript;
434 if ( "" != $this->mInterwiki ) { return ""; }
435 $s = $this->getLocalURL( "action=edit" );
437 return $s;
440 # Get HTML-escaped displayable text
441 # For the title field in <a> tags
442 function getEscapedText()
444 return wfEscapeHTML( $this->getPrefixedText() );
447 # Is the title interwiki?
448 function isExternal() { return ( "" != $this->mInterwiki ); }
450 # Does the title correspond to a protected article?
451 function isProtected()
453 if ( -1 == $this->mNamespace ) { return true; }
454 $a = $this->getRestrictions();
455 if ( in_array( "sysop", $a ) ) { return true; }
456 return false;
459 # Is the page a log page, i.e. one where the history is messed up by
460 # LogPage.php? This used to be used for suppressing diff links in recent
461 # changes, but now that's done by setting a flag in the recentchanges
462 # table. Hence, this probably is no longer used.
463 function isLog()
465 if ( $this->mNamespace != Namespace::getWikipedia() ) {
466 return false;
468 if ( ( 0 == strcmp( wfMsg( "uploadlogpage" ), $this->mDbkeyform ) ) ||
469 ( 0 == strcmp( wfMsg( "dellogpage" ), $this->mDbkeyform ) ) ) {
470 return true;
472 return false;
475 # Is $wgUser is watching this page?
476 function userIsWatching()
478 global $wgUser;
480 if ( -1 == $this->mNamespace ) { return false; }
481 if ( 0 == $wgUser->getID() ) { return false; }
483 return $wgUser->isWatched( $this );
486 # Can $wgUser edit this page?
487 function userCanEdit()
490 if ( -1 == $this->mNamespace ) { return false; }
491 # if ( 0 == $this->getArticleID() ) { return false; }
492 if ( $this->mDbkeyform == "_" ) { return false; }
493 //if ( $this->isCssJsSubpage() and !$this->userCanEditCssJsSubpage() ) { return false; }
494 # protect css/js subpages of user pages
495 # XXX: this might be better using restrictions
496 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
497 global $wgUser;
498 if( Namespace::getUser() == $this->mNamespace
499 and preg_match("/\\.(css|js)$/", $this->mTextform )
500 and !$wgUser->isSysop()
501 and !preg_match("/^".$wgUser->getName()."/", $this->mTextform) )
502 { return false; }
503 $ur = $wgUser->getRights();
504 foreach ( $this->getRestrictions() as $r ) {
505 if ( "" != $r && ( ! in_array( $r, $ur ) ) ) {
506 return false;
509 return true;
512 function isCssJsSubpage() {
513 return ( Namespace::getUser() == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
515 function isCssSubpage() {
516 return ( Namespace::getUser() == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
518 function isJsSubpage() {
519 return ( Namespace::getUser() == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
521 function userCanEditCssJsSubpage() {
522 # protect css/js subpages of user pages
523 # XXX: this might be better using restrictions
524 global $wgUser;
525 return ( $wgUser->isSysop() or preg_match("/^".$wgUser->getName()."/", $this->mTextform) );
528 # Accessor/initialisation for mRestrictions
529 function getRestrictions()
531 $id = $this->getArticleID();
532 if ( 0 == $id ) { return array(); }
534 if ( ! $this->mRestrictionsLoaded ) {
535 $res = wfGetSQL( "cur", "cur_restrictions", "cur_id=$id" );
536 $this->mRestrictions = explode( ",", trim( $res ) );
537 $this->mRestrictionsLoaded = true;
539 return $this->mRestrictions;
542 # Is there a version of this page in the deletion archive?
543 function isDeleted() {
544 $ns = $this->getNamespace();
545 $t = wfStrencode( $this->getDBkey() );
546 $sql = "SELECT COUNT(*) AS n FROM archive WHERE ar_namespace=$ns AND ar_title='$t'";
547 if( $res = wfQuery( $sql, DB_READ ) ) {
548 $s = wfFetchObject( $res );
549 return $s->n;
551 return 0;
554 # Get the article ID from the link cache
555 # Used very heavily, e.g. in Parser::replaceInternalLinks()
556 function getArticleID()
558 global $wgLinkCache;
560 if ( -1 != $this->mArticleID ) { return $this->mArticleID; }
561 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
562 return $this->mArticleID;
565 # This clears some fields in this object, and clears any associated keys in the
566 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
567 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
568 function resetArticleID( $newid )
570 global $wgLinkCache;
571 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
573 if ( 0 == $newid ) { $this->mArticleID = -1; }
574 else { $this->mArticleID = $newid; }
575 $this->mRestrictionsLoaded = false;
576 $this->mRestrictions = array();
579 # Updates cur_touched
580 # Called from LinksUpdate.php
581 function invalidateCache() {
582 $now = wfTimestampNow();
583 $ns = $this->getNamespace();
584 $ti = wfStrencode( $this->getDBkey() );
585 $sql = "UPDATE cur SET cur_touched='$now' WHERE cur_namespace=$ns AND cur_title='$ti'";
586 return wfQuery( $sql, DB_WRITE, "Title::invalidateCache" );
589 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
590 /* private */ function prefix( $name )
592 global $wgLang;
594 $p = "";
595 if ( "" != $this->mInterwiki ) {
596 $p = $this->mInterwiki . ":";
598 if ( 0 != $this->mNamespace ) {
599 $p .= $wgLang->getNsText( $this->mNamespace ) . ":";
601 return $p . $name;
604 # Secure and split - main initialisation function for this object
606 # Assumes that mDbkeyform has been set, and is urldecoded
607 # and uses undersocres, but not otherwise munged. This function
608 # removes illegal characters, splits off the winterwiki and
609 # namespace prefixes, sets the other forms, and canonicalizes
610 # everything.
612 /* private */ function secureAndSplit()
614 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
615 $fname = "Title::secureAndSplit";
616 wfProfileIn( $fname );
618 static $imgpre = false;
619 static $rxTc = false;
621 # Initialisation
622 if ( $imgpre === false ) {
623 $imgpre = ":" . $wgLang->getNsText( Namespace::getImage() ) . ":";
624 $rxTc = "/[^" . Title::legalChars() . "]/";
627 $this->mInterwiki = $this->mFragment = "";
628 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
630 # Clean up whitespace
632 $t = preg_replace( "/[\\s_]+/", "_", $this->mDbkeyform );
633 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
635 if ( "" == $t ) {
636 wfProfileOut( $fname );
637 return false;
640 $this->mDbkeyform = $t;
641 $done = false;
643 # :Image: namespace
644 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
645 $t = substr( $t, 1 );
648 # Initial colon indicating main namespace
649 if ( ":" == $t{0} ) {
650 $r = substr( $t, 1 );
651 $this->mNamespace = NS_MAIN;
652 } else {
653 # Namespace or interwiki prefix
654 if ( preg_match( "/^((?:i|x|[a-z]{2,3})(?:-[a-z0-9]+)?|[A-Za-z0-9_\\x80-\\xff]+?)_*:_*(.*)$/", $t, $m ) ) {
655 #$p = strtolower( $m[1] );
656 $p = $m[1];
657 $lowerNs = strtolower( $p );
658 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
659 # Canonical namespace
660 $t = $m[2];
661 $this->mNamespace = $ns;
662 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
663 # Ordinary namespace
664 $t = $m[2];
665 $this->mNamespace = $ns;
666 } elseif ( $this->getInterwikiLink( $p ) ) {
667 # Interwiki link
668 $t = $m[2];
669 $this->mInterwiki = $p;
671 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
672 $done = true;
673 } elseif($this->mInterwiki != $wgLocalInterwiki) {
674 $done = true;
678 $r = $t;
681 # Redundant interwiki prefix to the local wiki
682 if ( 0 == strcmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
683 $this->mInterwiki = "";
685 # We already know that some pages won't be in the database!
687 if ( "" != $this->mInterwiki || -1 == $this->mNamespace ) {
688 $this->mArticleID = 0;
690 $f = strstr( $r, "#" );
691 if ( false !== $f ) {
692 $this->mFragment = substr( $f, 1 );
693 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
696 # Reject illegal characters.
698 if( preg_match( $rxTc, $r ) ) {
699 return false;
702 # "." and ".." conflict with the directories of those names
703 if ( $r === "." || $r === ".." ) {
704 return false;
707 # Initial capital letter
708 if( $wgCapitalLinks && $this->mInterwiki == "") {
709 $t = $wgLang->ucfirst( $r );
712 # Fill fields
713 $this->mDbkeyform = $t;
714 $this->mUrlform = wfUrlencode( $t );
716 $this->mTextform = str_replace( "_", " ", $t );
718 wfProfileOut( $fname );
719 return true;
722 # Get a title object associated with the talk page of this article
723 function getTalkPage() {
724 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
727 # Get a title object associated with the subject page of this talk page
728 function getSubjectPage() {
729 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
732 # Get an array of Title objects linking to this title
733 # Also stores the IDs in the link cache
734 function getLinksTo() {
735 global $wgLinkCache;
736 $id = $this->getArticleID();
737 $sql = "SELECT cur_namespace,cur_title,cur_id FROM cur,links WHERE l_from=cur_id AND l_to={$id}";
738 $res = wfQuery( $sql, DB_READ, "Title::getLinksTo" );
739 $retVal = array();
740 if ( wfNumRows( $res ) ) {
741 while ( $row = wfFetchObject( $res ) ) {
742 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
743 $wgLinkCache->addGoodLink( $row->cur_id, $titleObj->getPrefixedDBkey() );
744 $retVal[] = $titleObj;
747 wfFreeResult( $res );
748 return $retVal;
751 # Get an array of Title objects linking to this non-existent title
752 # Also stores the IDs in the link cache
753 function getBrokenLinksTo() {
754 global $wgLinkCache;
755 $encTitle = wfStrencode( $this->getPrefixedDBkey() );
756 $sql = "SELECT cur_namespace,cur_title,cur_id FROM brokenlinks,cur " .
757 "WHERE bl_from=cur_id AND bl_to='$encTitle'";
758 $res = wfQuery( $sql, DB_READ, "Title::getBrokenLinksTo" );
759 $retVal = array();
760 if ( wfNumRows( $res ) ) {
761 while ( $row = wfFetchObject( $res ) ) {
762 $titleObj = Title::makeTitle( $row->cur_namespace, $row->cur_title );
763 $wgLinkCache->addGoodLink( $titleObj->getPrefixedDBkey(), $row->cur_id );
764 $retVal[] = $titleObj;
767 wfFreeResult( $res );
768 return $retVal;
771 function getSquidURLs() {
772 return array(
773 $this->getInternalURL(),
774 $this->getInternalURL( "action=history" )
778 function moveNoAuth( &$nt ) {
779 return $this->moveTo( $nt, false );
782 # Move a title to a new location
783 # Returns true on success, message name on failure
784 # auth indicates whether wgUser's permissions should be checked
785 function moveTo( &$nt, $auth = true ) {
786 if( !$this or !$nt ) {
787 return "badtitletext";
790 $fname = "Title::move";
791 $oldid = $this->getArticleID();
792 $newid = $nt->getArticleID();
794 if ( strlen( $nt->getDBkey() ) < 1 ) {
795 return "articleexists";
797 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
798 ( "" == $this->getDBkey() ) ||
799 ( "" != $this->getInterwiki() ) ||
800 ( !$oldid ) ||
801 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
802 ( "" == $nt->getDBkey() ) ||
803 ( "" != $nt->getInterwiki() ) ) {
804 return "badarticleerror";
807 if ( $auth && ( !$this->userCanEdit() || !$nt->userCanEdit() ) ) {
808 return "protectedpage";
811 # The move is allowed only if (1) the target doesn't exist, or
812 # (2) the target is a redirect to the source, and has no history
813 # (so we can undo bad moves right after they're done).
815 if ( 0 != $newid ) { # Target exists; check for validity
816 if ( ! $this->isValidMoveTarget( $nt ) ) {
817 return "articleexists";
819 $this->moveOverExistingRedirect( $nt );
820 } else { # Target didn't exist, do normal move.
821 $this->moveToNewTitle( $nt, $newid );
824 # Update watchlists
826 $oldnamespace = $this->getNamespace() & ~1;
827 $newnamespace = $nt->getNamespace() & ~1;
828 $oldtitle = $this->getDBkey();
829 $newtitle = $nt->getDBkey();
831 if( $oldnamespace != $newnamespace && $oldtitle != $newtitle ) {
832 WatchedItem::duplicateEntries( $this, $nt );
835 # Update search engine
836 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
837 $u->doUpdate();
838 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
839 $u->doUpdate();
841 return true;
844 # Move page to title which is presently a redirect to the source page
846 /* private */ function moveOverExistingRedirect( &$nt )
848 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
849 $fname = "Title::moveOverExistingRedirect";
850 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
852 $now = wfTimestampNow();
853 $won = wfInvertTimestamp( $now );
854 $newid = $nt->getArticleID();
855 $oldid = $this->getArticleID();
857 # Change the name of the target page:
858 wfUpdateArray(
859 /* table */ 'cur',
860 /* SET */ array(
861 'cur_touched' => $now,
862 'cur_namespace' => $nt->getNamespace(),
863 'cur_title' => $nt->getDBkey()
865 /* WHERE */ array( 'cur_id' => $oldid ),
866 $fname
868 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
870 # Repurpose the old redirect. We don't save it to history since
871 # by definition if we've got here it's rather uninteresting.
873 $redirectText = $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n";
874 wfUpdateArray(
875 /* table */ 'cur',
876 /* SET */ array(
877 'cur_touched' => $now,
878 'cur_timestamp' => $now,
879 'inverse_timestamp' => $won,
880 'cur_namespace' => $this->getNamespace(),
881 'cur_title' => $this->getDBkey(),
882 'cur_text' => $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n",
883 'cur_comment' => $comment,
884 'cur_user' => $wgUser->getID(),
885 'cur_minor_edit' => 0,
886 'cur_counter' => 0,
887 'cur_restrictions' => '',
888 'cur_user_text' => $wgUser->getName(),
889 'cur_is_redirect' => 1,
890 'cur_is_new' => 1
892 /* WHERE */ array( 'cur_id' => $newid ),
893 $fname
896 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
898 # Fix the redundant names for the past revisions of the target page.
899 # The redirect should have no old revisions.
900 wfUpdateArray(
901 /* table */ 'old',
902 /* SET */ array(
903 'old_namespace' => $nt->getNamespace(),
904 'old_title' => $nt->getDBkey(),
906 /* WHERE */ array(
907 'old_namespace' => $this->getNamespace(),
908 'old_title' => $this->getDBkey(),
910 $fname
913 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
915 # Swap links
917 # Load titles and IDs
918 $linksToOld = $this->getLinksTo();
919 $linksToNew = $nt->getLinksTo();
921 # Make function to convert Titles to IDs
922 $titleToID = create_function('$t', 'return $t->getArticleID();');
924 # Reassign links to old title
925 if ( count( $linksToOld ) ) {
926 $sql = "UPDATE links SET l_to=$newid WHERE l_from IN (";
927 $sql .= implode( ",", array_map( $titleToID, $linksToOld ) );
928 $sql .= ")";
929 wfQuery( $sql, DB_WRITE, $fname );
932 # Reassign links to new title
933 if ( count( $linksToNew ) ) {
934 $sql = "UPDATE links SET l_to=$oldid WHERE l_from IN (";
935 $sql .= implode( ",", array_map( $titleToID, $linksToNew ) );
936 $sql .= ")";
937 wfQuery( $sql, DB_WRITE, $fname );
940 # Note: the insert below must be after the updates above!
942 # Now, we record the link from the redirect to the new title.
943 # It should have no other outgoing links...
944 $sql = "DELETE FROM links WHERE l_from={$newid}";
945 wfQuery( $sql, DB_WRITE, $fname );
946 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
947 wfQuery( $sql, DB_WRITE, $fname );
949 # Purge squid
950 if ( $wgUseSquid ) {
951 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
952 $u = new SquidUpdate( $urls );
953 $u->doUpdate();
957 # Move page to non-existing title.
958 # Sets $newid to be the new article ID
960 /* private */ function moveToNewTitle( &$nt, &$newid )
962 global $wgUser, $wgLinkCache, $wgUseSquid;
963 $fname = "MovePageForm::moveToNewTitle";
964 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
966 $now = wfTimestampNow();
967 $won = wfInvertTimestamp( $now );
968 $newid = $nt->getArticleID();
969 $oldid = $this->getArticleID();
971 # Rename cur entry
972 wfUpdateArray(
973 /* table */ 'cur',
974 /* SET */ array(
975 'cur_touched' => $now,
976 'cur_namespace' => $nt->getNamespace(),
977 'cur_title' => $nt->getDBkey()
979 /* WHERE */ array( 'cur_id' => $oldid ),
980 $fname
983 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
985 # Insert redirct
986 wfInsertArray( 'cur', array(
987 'cur_namespace' => $this->getNamespace(),
988 'cur_title' => $this->getDBkey(),
989 'cur_comment' => $comment,
990 'cur_user' => $wgUser->getID(),
991 'cur_user_text' => $wgUser->getName(),
992 'cur_timestamp' => $now,
993 'inverse_timestamp' => $won,
994 'cur_touched' => $now,
995 'cur_is_redirect' => 1,
996 'cur_is_new' => 1,
997 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" )
999 $newid = wfInsertId();
1000 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1002 # Rename old entries
1003 wfUpdateArray(
1004 /* table */ 'old',
1005 /* SET */ array(
1006 'old_namespace' => $nt->getNamespace(),
1007 'old_title' => $nt->getDBkey()
1009 /* WHERE */ array(
1010 'old_namespace' => $this->getNamespace(),
1011 'old_title' => $this->getDBkey()
1012 ), $fname
1015 # Miscellaneous updates
1017 RecentChange::notifyMove( $now, $this, $nt, $wgUser, $comment );
1018 Article::onArticleCreate( $nt );
1020 # Any text links to the old title must be reassigned to the redirect
1021 $sql = "UPDATE links SET l_to={$newid} WHERE l_to={$oldid}";
1022 wfQuery( $sql, DB_WRITE, $fname );
1024 # Record the just-created redirect's linking to the page
1025 $sql = "INSERT INTO links (l_from,l_to) VALUES ({$newid},{$oldid})";
1026 wfQuery( $sql, DB_WRITE, $fname );
1028 # Non-existent target may have had broken links to it; these must
1029 # now be removed and made into good links.
1030 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1031 $update->fixBrokenLinks();
1033 # Purge old title from squid
1034 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1035 $titles = $nt->getLinksTo();
1036 if ( $wgUseSquid ) {
1037 $urls = $this->getSquidURLs();
1038 foreach ( $titles as $linkTitle ) {
1039 $urls[] = $linkTitle->getInternalURL();
1041 $u = new SquidUpdate( $urls );
1042 $u->doUpdate();
1046 # Checks if $this can be moved to $nt
1047 # Both titles must exist in the database, otherwise it will blow up
1048 function isValidMoveTarget( $nt )
1050 $fname = "Title::isValidMoveTarget";
1052 # Is it a redirect?
1053 $id = $nt->getArticleID();
1054 $sql = "SELECT cur_is_redirect,cur_text FROM cur " .
1055 "WHERE cur_id={$id}";
1056 $res = wfQuery( $sql, DB_READ, $fname );
1057 $obj = wfFetchObject( $res );
1059 if ( 0 == $obj->cur_is_redirect ) {
1060 # Not a redirect
1061 return false;
1064 # Does the redirect point to the source?
1065 if ( preg_match( "/\\[\\[\\s*([^\\]]*)]]/", $obj->cur_text, $m ) ) {
1066 $redirTitle = Title::newFromText( $m[1] );
1067 if ( 0 != strcmp( $redirTitle->getPrefixedDBkey(), $this->getPrefixedDBkey() ) ) {
1068 return false;
1072 # Does the article have a history?
1073 $row = wfGetArray( 'old', array( 'old_id' ), array(
1074 'old_namespace' => $nt->getNamespace(),
1075 'old_title' => $nt->getDBkey() )
1078 # Return true if there was no history
1079 return $row === false;
1082 # Create a redirect, fails if the title already exists, does not notify RC
1083 # Returns success
1084 function createRedirect( $dest, $comment ) {
1085 global $wgUser;
1086 if ( $this->getArticleID() ) {
1087 return false;
1090 $now = wfTimestampNow();
1091 $won = wfInvertTimestamp( $now );
1093 wfInsertArray( 'cur', array(
1094 'cur_namespace' => $this->getNamespace(),
1095 'cur_title' => $this->getDBkey(),
1096 'cur_comment' => $comment,
1097 'cur_user' => $wgUser->getID(),
1098 'cur_user_text' => $wgUser->getName(),
1099 'cur_timestamp' => $now,
1100 'inverse_timestamp' => $won,
1101 'cur_touched' => $now,
1102 'cur_is_redirect' => 1,
1103 'cur_is_new' => 1,
1104 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1106 $newid = wfInsertId();
1107 $this->resetArticleID( $newid );
1109 # Link table
1110 if ( $dest->getArticleID() ) {
1111 wfInsertArray( 'links', array(
1112 'l_to' => $dest->getArticleID(),
1113 'l_from' => $newid
1115 } else {
1116 wfInsertArray( 'brokenlinks', array(
1117 'bl_to' => $dest->getPrefixedDBkey(),
1118 'bl_from' => $newid
1122 Article::onArticleCreate( $this );
1123 return true;