4 $wgTitleInterwikiCache = array();
8 # * Represents a title, which may contain an interwiki designation or namespace
9 # * Can fetch various kinds of data from the database, albeit inefficiently.
12 define ( 'GAID_FOR_UPDATE', 1 );
15 # All member variables should be considered private
16 # Please use the accessor functions
18 var $mTextform; # Text form (spaces not underscores) of the main part
19 var $mUrlform; # URL-encoded form of the main part
20 var $mDbkeyform; # Main part with underscores
21 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
22 var $mInterwiki; # Interwiki prefix (or null string)
23 var $mFragment; # Title fragment (i.e. the bit after the #)
24 var $mArticleID; # Article ID, fetched from the link cache on demand
25 var $mRestrictions; # Array of groups allowed to edit this article
26 # Only null or "sysop" are supported
27 var $mRestrictionsLoaded; # Boolean for initialisation on demand
28 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
29 var $mDefaultNamespace; # Namespace index when there is no namespace
30 # Zero except in {{transclusion}} tags
32 #----------------------------------------------------------------------------
34 #----------------------------------------------------------------------------
36 /* private */ function Title() {
37 $this->mInterwiki
= $this->mUrlform
=
38 $this->mTextform
= $this->mDbkeyform
= '';
39 $this->mArticleID
= -1;
40 $this->mNamespace
= 0;
41 $this->mRestrictionsLoaded
= false;
42 $this->mRestrictions
= array();
43 $this->mDefaultNamespace
= 0;
46 # From a prefixed DB key
47 /* static */ function newFromDBkey( $key ) {
49 $t->mDbkeyform
= $key;
50 if( $t->secureAndSplit() )
56 # From text, such as what you would find in a link
57 /* 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 );
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() ) {
88 # From a URL-encoded title
89 /* static */ function newFromURL( $url ) {
90 global $wgLang, $wgServer;
93 # For compatibility with old buggy URLs. "+" is not valid in titles,
94 # but some URLs used it as a space replacement and they still come
95 # from some external search tools.
96 $s = str_replace( '+', ' ', $url );
98 # For links that came from outside, check for alternate/legacy
100 wfDebug( "Servr: $wgServer\n" );
101 if( empty( $_SERVER['HTTP_REFERER'] ) ||
102 strncmp($wgServer, $_SERVER['HTTP_REFERER'], strlen( $wgServer ) ) )
104 $s = $wgLang->checkTitleEncoding( $s );
106 wfDebug( "Refer: {$_SERVER['HTTP_REFERER']}\n" );
109 $t->mDbkeyform
= str_replace( ' ', '_', $s );
110 if( $t->secureAndSplit() ) {
111 # check that length of title is < cur_title size
112 $dbr =& wfGetDB( DB_SLAVE
);
113 $maxSize = $dbr->textFieldSize( 'cur', 'cur_title' );
114 if ( $maxSize != -1 && strlen( $t->mDbkeyform
) > $maxSize ) {
125 # This is inefficiently implemented, the cur row is requested but not
126 # used for anything else
127 /* static */ function newFromID( $id ) {
128 $fname = 'Title::newFromID';
129 $dbr =& wfGetDB( DB_SLAVE
);
130 $row = $dbr->getArray( 'cur', array( 'cur_namespace', 'cur_title' ),
131 array( 'cur_id' => $id ), $fname );
132 if ( $row !== false ) {
133 $title = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
140 # From a namespace index and a DB key.
141 # It's assumed that $ns and $title are *valid*, for instance
142 # when they came directly from the database.
143 /* static */ function &makeTitle( $ns, $title ) {
147 $t->mNamespace
= $ns;
148 $t->mDbkeyform
= $title;
149 $t->mArticleID
= ( $ns >= 0 ) ?
0 : -1;
150 $t->mUrlform
= wfUrlencode( $title );
151 $t->mTextform
= str_replace( '_', ' ', $title );
155 /* static */ function newMainPage() {
156 return Title
::newFromText( wfMsg( 'mainpage' ) );
159 # Get the title object for a redirect
160 # Returns NULL if the text is not a valid redirect
161 /* static */ function newFromRedirect( $text ) {
164 if ( $wgMwRedir->matchStart( $text ) ) {
165 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/', $text, $m ) ) {
166 # categories are escaped using : for example one can enter:
167 # #REDIRECT [[:Category:Music]]. Need to remove it.
168 if ( substr($m[1],0,1) == ':') {
169 # We don't want to keep the ':'
170 $m[1] = substr( $m[1], 1 );
173 $rt = Title
::newFromText( $m[1] );
179 #----------------------------------------------------------------------------
181 #----------------------------------------------------------------------------
183 # Get the prefixed DB key associated with an ID
184 /* static */ function nameOf( $id ) {
185 $fname = 'Title::nameOf';
186 $dbr =& wfGetDB( DB_SLAVE
);
188 $s = $dbr->getArray( 'cur', array( 'cur_namespace','cur_title' ), array( 'cur_id' => $id ), $fname );
189 if ( $s === false ) { return NULL; }
191 $n = Title
::makeName( $s->cur_namespace
, $s->cur_title
);
195 # Get a regex character class describing the legal characters in a link
196 /* static */ function legalChars() {
197 # Missing characters:
198 # * []|# Needed for link syntax
199 # * % and + are corrupted by Apache when they appear in the path
201 # % seems to work though
203 # The problem with % is that URLs are double-unescaped: once by Apache's
204 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
205 # Our code does not double-escape to compensate for this, indeed double escaping
206 # would break if the double-escaped title was passed in the query string
207 # rather than the path. This is a minor security issue because articles can be
208 # created such that they are hard to view or edit. -- TS
210 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
211 # this breaks interlanguage links
213 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z{}~\\x80-\\xFF";
217 # Returns a stripped-down a title string ready for the search index
218 # Takes a namespace index and a text-form main part
219 /* static */ function indexTitle( $ns, $title ) {
220 global $wgDBminWordLen, $wgLang;
221 require_once( 'SearchEngine.php' );
223 $lc = SearchEngine
::legalSearchChars() . '&#;';
224 $t = $wgLang->stripForSearch( $title );
225 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
226 $t = strtolower( $t );
229 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
230 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
232 $t = preg_replace( "/\\s+/", ' ', $t );
234 if ( $ns == Namespace::getImage() ) {
235 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
240 # Make a prefixed DB key from a DB key and a namespace index
241 /* static */ function makeName( $ns, $title ) {
244 $n = $wgLang->getNsText( $ns );
245 if ( '' == $n ) { return $title; }
246 else { return $n.':'.$title; }
250 # Returns the URL associated with an interwiki prefix
251 # The URL contains $1, which is replaced by the title
252 function getInterwikiLink( $key ) {
253 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
254 $fname = 'Title::getInterwikiLink';
255 $k = $wgDBname.':interwiki:'.$key;
257 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
258 return $wgTitleInterwikiCache[$k]->iw_url
;
260 $s = $wgMemc->get( $k );
261 # Ignore old keys with no iw_local
262 if( $s && isset( $s->iw_local
) ) {
263 $wgTitleInterwikiCache[$k] = $s;
266 $dbr =& wfGetDB( DB_SLAVE
);
267 $res = $dbr->select( 'interwiki', array( 'iw_url', 'iw_local' ), array( 'iw_prefix' => $key ), $fname );
270 $s = $dbr->fetchObject( $res );
272 # Cache non-existence: create a blank object and save it to memcached
277 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
278 $wgTitleInterwikiCache[$k] = $s;
283 global $wgTitleInterwikiCache, $wgDBname;
285 if ( $this->mInterwiki
!= '' ) {
286 # Make sure key is loaded into cache
287 $this->getInterwikiLink( $this->mInterwiki
);
288 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
289 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
295 # Update the cur_touched field for an array of title objects
296 # Inefficient unless the IDs are already loaded into the link cache
297 /* static */ function touchArray( $titles, $timestamp = '' ) {
298 if ( count( $titles ) == 0 ) {
301 if ( $timestamp == '' ) {
302 $timestamp = wfTimestampNow();
304 $dbw =& wfGetDB( DB_MASTER
);
305 $cur = $dbw->tableName( 'cur' );
306 $sql = "UPDATE $cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
309 foreach ( $titles as $title ) {
314 $sql .= $title->getArticleID();
318 $dbw->query( $sql, 'Title::touchArray' );
322 #----------------------------------------------------------------------------
324 #----------------------------------------------------------------------------
327 # See the definitions at the top of this file
329 function getText() { return $this->mTextform
; }
330 function getPartialURL() { return $this->mUrlform
; }
331 function getDBkey() { return $this->mDbkeyform
; }
332 function getNamespace() { return $this->mNamespace
; }
333 function setNamespace( $n ) { $this->mNamespace
= $n; }
334 function getInterwiki() { return $this->mInterwiki
; }
335 function getFragment() { return $this->mFragment
; }
336 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
338 # Get title for search index
339 function getIndexTitle() {
340 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
343 # Get prefixed title with underscores
344 function getPrefixedDBkey() {
345 $s = $this->prefix( $this->mDbkeyform
);
346 $s = str_replace( ' ', '_', $s );
350 # Get prefixed title with spaces
351 # This is the form usually used for display
352 function getPrefixedText() {
353 if ( empty( $this->mPrefixedText
) ) {
354 $s = $this->prefix( $this->mTextform
);
355 $s = str_replace( '_', ' ', $s );
356 $this->mPrefixedText
= $s;
358 return $this->mPrefixedText
;
361 # As getPrefixedText(), plus fragment.
362 function getFullText() {
363 $text = $this->getPrefixedText();
364 if( '' != $this->mFragment
) {
365 $text .= '#' . $this->mFragment
;
370 # Get a URL-encoded title (not an actual URL) including interwiki
371 function getPrefixedURL() {
372 $s = $this->prefix( $this->mDbkeyform
);
373 $s = str_replace( ' ', '_', $s );
375 $s = wfUrlencode ( $s ) ;
377 # Cleaning up URL to make it look nice -- is this safe?
378 $s = preg_replace( '/%3[Aa]/', ':', $s );
379 $s = preg_replace( '/%2[Ff]/', '/', $s );
380 $s = str_replace( '%28', '(', $s );
381 $s = str_replace( '%29', ')', $s );
386 # Get a real URL referring to this title, with interwiki link and fragment
387 function getFullURL( $query = '' ) {
388 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
390 if ( '' == $this->mInterwiki
) {
392 return $wgServer . $this->getLocalUrl( $query );
394 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
395 $namespace = $wgLang->getNsText( $this->mNamespace
);
396 if ( '' != $namespace ) {
397 # Can this actually happen? Interwikis shouldn't be parsed.
400 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
401 if ( '' != $this->mFragment
) {
402 $url .= '#' . $this->mFragment
;
408 # Get a URL with an optional query string, no fragment
409 # * If $query=="", it will use $wgArticlePath
410 # * Returns a full for an interwiki link, loses any query string
411 # * Optionally adds the server and escapes for HTML
412 # * Setting $query to "-" makes an old-style URL with nothing in the
413 # query except a title
416 die( 'Call to obsolete obsolete function Title::getURL()' );
419 function getLocalURL( $query = '' ) {
420 global $wgLang, $wgArticlePath, $wgScript;
422 if ( $this->isExternal() ) {
423 return $this->getFullURL();
426 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
427 if ( $query == '' ) {
428 $url = str_replace( '$1', $dbkey, $wgArticlePath );
430 if ( $query == '-' ) {
433 if ( $wgScript != '' ) {
434 $url = "{$wgScript}?title={$dbkey}&{$query}";
437 $url = "/{$dbkey}?{$query}";
443 function escapeLocalURL( $query = '' ) {
444 return htmlspecialchars( $this->getLocalURL( $query ) );
447 function escapeFullURL( $query = '' ) {
448 return htmlspecialchars( $this->getFullURL( $query ) );
451 function getInternalURL( $query = '' ) {
452 # Used in various Squid-related code, in case we have a different
453 # internal hostname for the server than the exposed one.
454 global $wgInternalServer;
455 return $wgInternalServer . $this->getLocalURL( $query );
458 # Get the edit URL, or a null string if it is an interwiki link
459 function getEditURL() {
460 global $wgServer, $wgScript;
462 if ( '' != $this->mInterwiki
) { return ''; }
463 $s = $this->getLocalURL( 'action=edit' );
468 # Get HTML-escaped displayable text
469 # For the title field in <a> tags
470 function getEscapedText() {
471 return htmlspecialchars( $this->getPrefixedText() );
474 # Is the title interwiki?
475 function isExternal() { return ( '' != $this->mInterwiki
); }
477 # Does the title correspond to a protected article?
478 function isProtected() {
479 if ( -1 == $this->mNamespace
) { return true; }
480 $a = $this->getRestrictions();
481 if ( in_array( 'sysop', $a ) ) { return true; }
485 # Is the page a log page, i.e. one where the history is messed up by
486 # LogPage.php? This used to be used for suppressing diff links in recent
487 # changes, but now that's done by setting a flag in the recentchanges
488 # table. Hence, this probably is no longer used.
490 if ( $this->mNamespace
!= Namespace::getWikipedia() ) {
493 if ( ( 0 == strcmp( wfMsg( 'uploadlogpage' ), $this->mDbkeyform
) ) ||
494 ( 0 == strcmp( wfMsg( 'dellogpage' ), $this->mDbkeyform
) ) ) {
500 # Is $wgUser is watching this page?
501 function userIsWatching() {
504 if ( -1 == $this->mNamespace
) { return false; }
505 if ( 0 == $wgUser->getID() ) { return false; }
507 return $wgUser->isWatched( $this );
510 # Can $wgUser edit this page?
511 function userCanEdit() {
513 if ( -1 == $this->mNamespace
) { return false; }
514 if ( NS_MEDIAWIKI
== $this->mNamespace
&& !$wgUser->isSysop() ) { return false; }
515 # if ( 0 == $this->getArticleID() ) { return false; }
516 if ( $this->mDbkeyform
== '_' ) { return false; }
517 # protect global styles and js
518 if ( NS_MEDIAWIKI
== $this->mNamespace
519 && preg_match("/\\.(css|js)$/", $this->mTextform
)
520 && !$wgUser->isSysop() )
522 //if ( $this->isCssJsSubpage() and !$this->userCanEditCssJsSubpage() ) { return false; }
523 # protect css/js subpages of user pages
524 # XXX: this might be better using restrictions
525 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
526 if( Namespace::getUser() == $this->mNamespace
527 and preg_match("/\\.(css|js)$/", $this->mTextform
)
528 and !$wgUser->isSysop()
529 and !preg_match('/^'.preg_quote($wgUser->getName(), '/').'/', $this->mTextform
) )
531 $ur = $wgUser->getRights();
532 foreach ( $this->getRestrictions() as $r ) {
533 if ( '' != $r && ( ! in_array( $r, $ur ) ) ) {
540 function userCanRead() {
542 global $wgWhitelistRead;
544 if( 0 != $wgUser->getID() ) return true;
545 if( !is_array( $wgWhitelistRead ) ) return true;
547 $name = $this->getPrefixedText();
548 if( in_array( $name, $wgWhitelistRead ) ) return true;
550 # Compatibility with old settings
551 if( $this->getNamespace() == NS_MAIN
) {
552 if( in_array( ':' . $name, $wgWhitelistRead ) ) return true;
557 function isCssJsSubpage() {
558 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
560 function isCssSubpage() {
561 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
563 function isJsSubpage() {
564 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
566 function userCanEditCssJsSubpage() {
567 # protect css/js subpages of user pages
568 # XXX: this might be better using restrictions
570 return ( $wgUser->isSysop() or preg_match('/^'.preg_quote($wgUser->getName()).'/', $this->mTextform
) );
573 # Accessor/initialisation for mRestrictions
574 function getRestrictions() {
575 $id = $this->getArticleID();
576 if ( 0 == $id ) { return array(); }
578 if ( ! $this->mRestrictionsLoaded
) {
579 $dbr =& wfGetDB( DB_SLAVE
);
580 $res = $dbr->getField( 'cur', 'cur_restrictions', 'cur_id='.$id );
581 $this->mRestrictions
= explode( ',', trim( $res ) );
582 $this->mRestrictionsLoaded
= true;
584 return $this->mRestrictions
;
587 # Is there a version of this page in the deletion archive?
588 # Returns the number of archived revisions
589 function isDeleted() {
590 $fname = 'Title::isDeleted';
591 $dbr =& wfGetDB( DB_SLAVE
);
592 $n = $dbr->getField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
593 'ar_title' => $this->getDBkey() ), $fname );
597 # Get the article ID from the link cache
598 # $flags is a bit field, may be GAID_FOR_UPDATE to select for update
599 function getArticleID( $flags = 0 ) {
602 if ( $flags & GAID_FOR_UPDATE
) {
603 $oldUpdate = $wgLinkCache->forUpdate( true );
604 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
605 $wgLinkCache->forUpdate( $oldUpdate );
607 if ( -1 == $this->mArticleID
) {
608 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
611 return $this->mArticleID
;
614 # This clears some fields in this object, and clears any associated keys in the
615 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
616 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
617 function resetArticleID( $newid ) {
619 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
621 if ( 0 == $newid ) { $this->mArticleID
= -1; }
622 else { $this->mArticleID
= $newid; }
623 $this->mRestrictionsLoaded
= false;
624 $this->mRestrictions
= array();
627 # Updates cur_touched
628 # Called from LinksUpdate.php
629 function invalidateCache() {
630 $now = wfTimestampNow();
631 $dbw =& wfGetDB( DB_MASTER
);
632 $success = $dbw->updateArray( 'cur',
634 'cur_touched' => wfTimestampNow()
635 ), array( /* WHERE */
636 'cur_namespace' => $this->getNamespace() ,
637 'cur_title' => $this->getDBkey()
638 ), 'Title::invalidateCache'
643 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
644 /* private */ function prefix( $name ) {
648 if ( '' != $this->mInterwiki
) {
649 $p = $this->mInterwiki
. ':';
651 if ( 0 != $this->mNamespace
) {
652 $p .= $wgLang->getNsText( $this->mNamespace
) . ':';
657 # Secure and split - main initialisation function for this object
659 # Assumes that mDbkeyform has been set, and is urldecoded
660 # and uses underscores, but not otherwise munged. This function
661 # removes illegal characters, splits off the interwiki and
662 # namespace prefixes, sets the other forms, and canonicalizes
665 /* private */ function secureAndSplit()
667 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
668 $fname = 'Title::secureAndSplit';
669 wfProfileIn( $fname );
671 static $imgpre = false;
672 static $rxTc = false;
675 if ( $imgpre === false ) {
676 $imgpre = ':' . $wgLang->getNsText( Namespace::getImage() ) . ':';
677 # % is needed as well
678 $rxTc = '/[^' . Title
::legalChars() . ']/';
681 $this->mInterwiki
= $this->mFragment
= '';
682 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
684 # Clean up whitespace
686 $t = preg_replace( "/[\\s_]+/", '_', $this->mDbkeyform
);
687 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
690 wfProfileOut( $fname );
694 $this->mDbkeyform
= $t;
698 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
699 $t = substr( $t, 1 );
702 # Initial colon indicating main namespace
703 if ( ':' == $t{0} ) {
704 $r = substr( $t, 1 );
705 $this->mNamespace
= NS_MAIN
;
707 # Namespace or interwiki prefix
708 if ( preg_match( "/^(.+?)_*:_*(.*)$/", $t, $m ) ) {
709 #$p = strtolower( $m[1] );
711 $lowerNs = strtolower( $p );
712 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
713 # Canonical namespace
715 $this->mNamespace
= $ns;
716 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
719 $this->mNamespace
= $ns;
720 } elseif ( $this->getInterwikiLink( $p ) ) {
723 $this->mInterwiki
= $p;
725 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
727 } elseif($this->mInterwiki
!= $wgLocalInterwiki) {
735 # Redundant interwiki prefix to the local wiki
736 if ( 0 == strcmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
737 $this->mInterwiki
= '';
739 # We already know that some pages won't be in the database!
741 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
742 $this->mArticleID
= 0;
744 $f = strstr( $r, '#' );
745 if ( false !== $f ) {
746 $this->mFragment
= substr( $f, 1 );
747 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
750 # Reject illegal characters.
752 if( preg_match( $rxTc, $r ) ) {
753 wfProfileOut( $fname );
757 # "." and ".." conflict with the directories of those namesa
758 if ( strpos( $r, '.' ) !== false &&
759 ( $r === '.' ||
$r === '..' ||
760 strpos( $r, './' ) === 0 ||
761 strpos( $r, '../' ) === 0 ||
762 strpos( $r, '/./' ) !== false ||
763 strpos( $r, '/../' ) !== false ) )
765 wfProfileOut( $fname );
769 # Initial capital letter
770 if( $wgCapitalLinks && $this->mInterwiki
== '') {
771 $t = $wgLang->ucfirst( $r );
777 $this->mDbkeyform
= $t;
778 $this->mUrlform
= wfUrlencode( $t );
780 $this->mTextform
= str_replace( '_', ' ', $t );
782 wfProfileOut( $fname );
786 # Get a title object associated with the talk page of this article
787 function getTalkPage() {
788 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
791 # Get a title object associated with the subject page of this talk page
792 function getSubjectPage() {
793 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
796 # Get an array of Title objects linking to this title
797 # Also stores the IDs in the link cache
798 # $options may be FOR UPDATE
799 function getLinksTo( $options = '' ) {
801 $id = $this->getArticleID();
804 $db =& wfGetDB( DB_MASTER
);
806 $db =& wfGetDB( DB_SLAVE
);
808 $cur = $db->tableName( 'cur' );
809 $links = $db->tableName( 'links' );
811 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
812 $res = $db->query( $sql, 'Title::getLinksTo' );
814 if ( $db->numRows( $res ) ) {
815 while ( $row = $db->fetchObject( $res ) ) {
816 if ( $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
) ) {
817 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
818 $retVal[] = $titleObj;
822 $db->freeResult( $res );
826 # Get an array of Title objects linking to this non-existent title
827 # Also stores the IDs in the link cache
828 function getBrokenLinksTo( $options = '' ) {
832 $db =& wfGetDB( DB_MASTER
);
834 $db =& wfGetDB( DB_SLAVE
);
836 $cur = $db->tableName( 'cur' );
837 $brokenlinks = $db->tableName( 'brokenlinks' );
838 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
840 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
841 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
842 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
844 if ( $db->numRows( $res ) ) {
845 while ( $row = $db->fetchObject( $res ) ) {
846 $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
847 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
848 $retVal[] = $titleObj;
851 $db->freeResult( $res );
855 function getSquidURLs() {
857 $this->getInternalURL(),
858 $this->getInternalURL( 'action=history' )
862 function moveNoAuth( &$nt ) {
863 return $this->moveTo( $nt, false );
866 # Move a title to a new location
867 # Returns true on success, message name on failure
868 # auth indicates whether wgUser's permissions should be checked
869 function moveTo( &$nt, $auth = true ) {
870 if( !$this or !$nt ) {
871 return 'badtitletext';
874 $fname = 'Title::move';
875 $oldid = $this->getArticleID();
876 $newid = $nt->getArticleID();
878 if ( strlen( $nt->getDBkey() ) < 1 ) {
879 return 'articleexists';
881 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
882 ( '' == $this->getDBkey() ) ||
883 ( '' != $this->getInterwiki() ) ||
885 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
886 ( '' == $nt->getDBkey() ) ||
887 ( '' != $nt->getInterwiki() ) ) {
888 return 'badarticleerror';
891 if ( $auth && ( !$this->userCanEdit() ||
!$nt->userCanEdit() ) ) {
892 return 'protectedpage';
895 # The move is allowed only if (1) the target doesn't exist, or
896 # (2) the target is a redirect to the source, and has no history
897 # (so we can undo bad moves right after they're done).
899 if ( 0 != $newid ) { # Target exists; check for validity
900 if ( ! $this->isValidMoveTarget( $nt ) ) {
901 return 'articleexists';
903 $this->moveOverExistingRedirect( $nt );
904 } else { # Target didn't exist, do normal move.
905 $this->moveToNewTitle( $nt, $newid );
908 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
910 $dbw =& wfGetDB( DB_MASTER
);
911 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
912 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
913 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
914 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
918 $oldnamespace = $this->getNamespace() & ~
1;
919 $newnamespace = $nt->getNamespace() & ~
1;
920 $oldtitle = $this->getDBkey();
921 $newtitle = $nt->getDBkey();
923 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
924 WatchedItem
::duplicateEntries( $this, $nt );
927 # Update search engine
928 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
930 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
936 # Move page to title which is presently a redirect to the source page
938 /* private */ function moveOverExistingRedirect( &$nt ) {
939 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
940 $fname = 'Title::moveOverExistingRedirect';
941 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
943 $now = wfTimestampNow();
944 $won = wfInvertTimestamp( $now );
945 $newid = $nt->getArticleID();
946 $oldid = $this->getArticleID();
947 $dbw =& wfGetDB( DB_MASTER
);
948 $links = $dbw->tableName( 'links' );
950 # Change the name of the target page:
951 $dbw->updateArray( 'cur',
953 'cur_touched' => $now,
954 'cur_namespace' => $nt->getNamespace(),
955 'cur_title' => $nt->getDBkey()
957 /* WHERE */ array( 'cur_id' => $oldid ),
960 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
962 # Repurpose the old redirect. We don't save it to history since
963 # by definition if we've got here it's rather uninteresting.
965 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
966 $dbw->updateArray( 'cur',
968 'cur_touched' => $now,
969 'cur_timestamp' => $now,
970 'inverse_timestamp' => $won,
971 'cur_namespace' => $this->getNamespace(),
972 'cur_title' => $this->getDBkey(),
973 'cur_text' => $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n",
974 'cur_comment' => $comment,
975 'cur_user' => $wgUser->getID(),
976 'cur_minor_edit' => 0,
978 'cur_restrictions' => '',
979 'cur_user_text' => $wgUser->getName(),
980 'cur_is_redirect' => 1,
983 /* WHERE */ array( 'cur_id' => $newid ),
987 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
989 # Fix the redundant names for the past revisions of the target page.
990 # The redirect should have no old revisions.
994 'old_namespace' => $nt->getNamespace(),
995 'old_title' => $nt->getDBkey(),
998 'old_namespace' => $this->getNamespace(),
999 'old_title' => $this->getDBkey(),
1004 RecentChange
::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
1008 # Load titles and IDs
1009 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1010 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1013 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1014 $dbw->query( $sql, $fname );
1017 if ( count( $linksToOld ) ||
count( $linksToNew )) {
1018 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1021 # Insert links to old title
1022 foreach ( $linksToOld as $linkTitle ) {
1028 $id = $linkTitle->getArticleID();
1029 $sql .= "($id,$newid)";
1032 # Insert links to new title
1033 foreach ( $linksToNew as $linkTitle ) {
1039 $id = $linkTitle->getArticleID();
1040 $sql .= "($id, $oldid)";
1043 $dbw->query( $sql, DB_MASTER
, $fname );
1046 # Now, we record the link from the redirect to the new title.
1047 # It should have no other outgoing links...
1048 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1049 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1052 LinkCache
::linksccClearLinksTo( $oldid );
1053 LinkCache
::linksccClearLinksTo( $newid );
1056 if ( $wgUseSquid ) {
1057 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1058 $u = new SquidUpdate( $urls );
1063 # Move page to non-existing title.
1064 # Sets $newid to be the new article ID
1066 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1067 global $wgUser, $wgLinkCache, $wgUseSquid;
1068 $fname = 'MovePageForm::moveToNewTitle';
1069 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1071 $now = wfTimestampNow();
1072 $won = wfInvertTimestamp( $now );
1073 $newid = $nt->getArticleID();
1074 $oldid = $this->getArticleID();
1075 $dbw =& wfGetDB( DB_MASTER
);
1078 $dbw->updateArray( 'cur',
1080 'cur_touched' => $now,
1081 'cur_namespace' => $nt->getNamespace(),
1082 'cur_title' => $nt->getDBkey()
1084 /* WHERE */ array( 'cur_id' => $oldid ),
1088 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1091 $dbw->insertArray( 'cur', array(
1092 'cur_namespace' => $this->getNamespace(),
1093 'cur_title' => $this->getDBkey(),
1094 'cur_comment' => $comment,
1095 'cur_user' => $wgUser->getID(),
1096 'cur_user_text' => $wgUser->getName(),
1097 'cur_timestamp' => $now,
1098 'inverse_timestamp' => $won,
1099 'cur_touched' => $now,
1100 'cur_is_redirect' => 1,
1102 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1104 $newid = $dbw->insertId();
1105 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1107 # Rename old entries
1111 'old_namespace' => $nt->getNamespace(),
1112 'old_title' => $nt->getDBkey()
1115 'old_namespace' => $this->getNamespace(),
1116 'old_title' => $this->getDBkey()
1121 RecentChange
::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1123 # Purge squid and linkscc as per article creation
1124 Article
::onArticleCreate( $nt );
1126 # Any text links to the old title must be reassigned to the redirect
1127 $dbw->updateArray( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1128 LinkCache
::linksccClearLinksTo( $oldid );
1130 # Record the just-created redirect's linking to the page
1131 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1133 # Non-existent target may have had broken links to it; these must
1134 # now be removed and made into good links.
1135 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1136 $update->fixBrokenLinks();
1138 # Purge old title from squid
1139 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1140 $titles = $nt->getLinksTo();
1141 if ( $wgUseSquid ) {
1142 $urls = $this->getSquidURLs();
1143 foreach ( $titles as $linkTitle ) {
1144 $urls[] = $linkTitle->getInternalURL();
1146 $u = new SquidUpdate( $urls );
1151 # Checks if $this can be moved to $nt
1152 # Selects for update, so don't call it unless you mean business
1153 function isValidMoveTarget( $nt ) {
1154 $fname = 'Title::isValidMoveTarget';
1155 $dbw =& wfGetDB( DB_MASTER
);
1158 $id = $nt->getArticleID();
1159 $obj = $dbw->getArray( 'cur', array( 'cur_is_redirect','cur_text' ),
1160 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1162 if ( !$obj ||
0 == $obj->cur_is_redirect
) {
1167 # Does the redirect point to the source?
1168 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text
, $m ) ) {
1169 $redirTitle = Title
::newFromText( $m[1] );
1170 if( !is_object( $redirTitle ) ||
1171 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1176 # Does the article have a history?
1177 $row = $dbw->getArray( 'old', array( 'old_id' ),
1179 'old_namespace' => $nt->getNamespace(),
1180 'old_title' => $nt->getDBkey()
1181 ), $fname, 'FOR UPDATE'
1184 # Return true if there was no history
1185 return $row === false;
1188 # Create a redirect, fails if the title already exists, does not notify RC
1190 function createRedirect( $dest, $comment ) {
1192 if ( $this->getArticleID() ) {
1196 $fname = 'Title::createRedirect';
1197 $dbw =& wfGetDB( DB_MASTER
);
1198 $now = wfTimestampNow();
1199 $won = wfInvertTimestamp( $now );
1200 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1202 $dbw->insertArray( 'cur', array(
1203 'cur_id' => $seqVal,
1204 'cur_namespace' => $this->getNamespace(),
1205 'cur_title' => $this->getDBkey(),
1206 'cur_comment' => $comment,
1207 'cur_user' => $wgUser->getID(),
1208 'cur_user_text' => $wgUser->getName(),
1209 'cur_timestamp' => $now,
1210 'inverse_timestamp' => $won,
1211 'cur_touched' => $now,
1212 'cur_is_redirect' => 1,
1214 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1216 $newid = $dbw->insertId();
1217 $this->resetArticleID( $newid );
1220 if ( $dest->getArticleID() ) {
1221 $dbw->insertArray( 'links',
1223 'l_to' => $dest->getArticleID(),
1228 $dbw->insertArray( 'brokenlinks',
1230 'bl_to' => $dest->getPrefixedDBkey(),
1236 Article
::onArticleCreate( $this );
1240 # Get categories to wich belong this title and return an array of
1242 function getParentCategories( ) {
1243 global $wgLang,$wgUser;
1245 $titlekey = $this->getArticleId();
1246 $cns = Namespace::getCategory();
1247 $sk =& $wgUser->getSkin();
1249 $dbr =& wfGetDB( DB_SLAVE
);
1250 $cur = $dbr->tableName( 'cur' );
1251 $categorylinks = $dbr->tableName( 'categorylinks' );
1253 # get the parents categories of this title from the database
1254 $sql = "SELECT DISTINCT cur_id FROM $cur,$categorylinks
1255 WHERE cl_from='$titlekey' AND cl_to=cur_title AND cur_namespace='$cns'
1256 ORDER BY cl_sortkey" ;
1257 $res = $dbr->query ( $sql ) ;
1259 if($dbr->numRows($res) > 0) {
1260 while ( $x = $dbr->fetchObject ( $res ) ) $data[] = $x ;
1261 $dbr->freeResult ( $res ) ;
1268 # will get the parents and grand-parents
1269 # TODO : not sure what's happening when a loop happen like:
1270 # Encyclopedia > Astronomy > Encyclopedia
1271 function getAllParentCategories(&$stack) {
1272 global $wgUser,$wgLang;
1276 $parents = $this->getParentCategories( );
1280 # The current element has no more parent so we dump the stack
1281 # and make a clean line of categories
1282 $sk =& $wgUser->getSkin() ;
1284 foreach ( array_reverse($stack) as $child => $parent )
1286 # make a link of that parent
1287 $result .= $sk->makeLink($wgLang->getNSText ( Namespace::getCategory() ).':'.$parent,$parent);
1288 $result .= ' > ';
1289 $lastchild = $child;
1291 # append the last child.
1292 # TODO : We should have a last child unless there is an error in the
1293 # "categorylinks" table.
1294 if(isset($lastchild)) { $result .= $lastchild; }
1296 $result .= "<br/>\n";
1298 # now we can empty the stack
1302 # look at parents of current category
1303 foreach($parents as $parent)
1305 # create a title object for the parent
1306 $tpar = Title
::newFromID($parent->cur_id
);
1307 # add it to the stack
1308 $stack[$this->getText()] = $tpar->getText();
1310 $result .= $tpar->getAllParentCategories($stack);
1314 if(isset($result)) { return $result; }
1315 else { return ''; };
1318 # Returns an associative array for selecting this title from cur
1319 function curCond() {
1320 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1323 function oldCond() {
1324 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);