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 /* static */ function makeTitle( $ns, $title ) {
143 $t->mDbkeyform
= Title
::makeName( $ns, $title );
144 if( $t->secureAndSplit() ) {
151 /* static */ function newMainPage() {
152 return Title
::newFromText( wfMsg( 'mainpage' ) );
155 # Get the title object for a redirect
156 # Returns NULL if the text is not a valid redirect
157 /* static */ function newFromRedirect( $text ) {
160 if ( $wgMwRedir->matchStart( $text ) ) {
161 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/', $text, $m ) ) {
162 # categories are escaped using : for example one can enter:
163 # #REDIRECT [[:Category:Music]]. Need to remove it.
164 if ( substr($m[1],0,1) == ':') {
165 # We don't want to keep the ':'
166 $m[1] = substr( $m[1], 1 );
169 $rt = Title
::newFromText( $m[1] );
175 #----------------------------------------------------------------------------
177 #----------------------------------------------------------------------------
179 # Get the prefixed DB key associated with an ID
180 /* static */ function nameOf( $id ) {
181 $fname = 'Title::nameOf';
182 $dbr =& wfGetDB( DB_SLAVE
);
184 $s = $dbr->getArray( 'cur', array( 'cur_namespace','cur_title' ), array( 'cur_id' => $id ), $fname );
185 if ( $s === false ) { return NULL; }
187 $n = Title
::makeName( $s->cur_namespace
, $s->cur_title
);
191 # Get a regex character class describing the legal characters in a link
192 /* static */ function legalChars() {
193 # Missing characters:
194 # * []|# Needed for link syntax
195 # * % and + are corrupted by Apache when they appear in the path
197 # % seems to work though
199 # The problem with % is that URLs are double-unescaped: once by Apache's
200 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
201 # Our code does not double-escape to compensate for this, indeed double escaping
202 # would break if the double-escaped title was passed in the query string
203 # rather than the path. This is a minor security issue because articles can be
204 # created such that they are hard to view or edit. -- TS
206 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
207 # this breaks interlanguage links
209 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z{}~\\x80-\\xFF";
213 # Returns a stripped-down a title string ready for the search index
214 # Takes a namespace index and a text-form main part
215 /* static */ function indexTitle( $ns, $title ) {
216 global $wgDBminWordLen, $wgLang;
217 require_once( 'SearchEngine.php' );
219 $lc = SearchEngine
::legalSearchChars() . '&#;';
220 $t = $wgLang->stripForSearch( $title );
221 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
222 $t = strtolower( $t );
225 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
226 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
228 $t = preg_replace( "/\\s+/", ' ', $t );
230 if ( $ns == Namespace::getImage() ) {
231 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
236 # Make a prefixed DB key from a DB key and a namespace index
237 /* static */ function makeName( $ns, $title ) {
240 $n = $wgLang->getNsText( $ns );
241 if ( "" == $n ) { return $title; }
242 else { return "{$n}:{$title}"; }
246 # Returns the URL associated with an interwiki prefix
247 # The URL contains $1, which is replaced by the title
248 function getInterwikiLink( $key ) {
249 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
250 $fname = 'Title::getInterwikiLink';
251 $k = $wgDBname.':interwiki:'.$key;
253 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
254 return $wgTitleInterwikiCache[$k]->iw_url
;
256 $s = $wgMemc->get( $k );
257 # Ignore old keys with no iw_local
258 if( $s && isset( $s->iw_local
) ) {
259 $wgTitleInterwikiCache[$k] = $s;
262 $dbr =& wfGetDB( DB_SLAVE
);
263 $res = $dbr->select( 'interwiki', array( 'iw_url', 'iw_local' ), array( 'iw_prefix' => $key ), $fname );
266 $s = $dbr->fetchObject( $res );
268 # Cache non-existence: create a blank object and save it to memcached
273 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
274 $wgTitleInterwikiCache[$k] = $s;
279 global $wgTitleInterwikiCache, $wgDBname;
281 if ( $this->mInterwiki
!= '' ) {
282 # Make sure key is loaded into cache
283 $this->getInterwikiLink( $this->mInterwiki
);
284 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
285 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
291 # Update the cur_touched field for an array of title objects
292 # Inefficient unless the IDs are already loaded into the link cache
293 /* static */ function touchArray( $titles, $timestamp = '' ) {
294 if ( count( $titles ) == 0 ) {
297 if ( $timestamp == '' ) {
298 $timestamp = wfTimestampNow();
300 $dbw =& wfGetDB( DB_MASTER
);
301 $cur = $dbw->tableName( 'cur' );
302 $sql = "UPDATE $cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
305 foreach ( $titles as $title ) {
310 $sql .= $title->getArticleID();
314 $dbw->query( $sql, 'Title::touchArray' );
318 #----------------------------------------------------------------------------
320 #----------------------------------------------------------------------------
323 # See the definitions at the top of this file
325 function getText() { return $this->mTextform
; }
326 function getPartialURL() { return $this->mUrlform
; }
327 function getDBkey() { return $this->mDbkeyform
; }
328 function getNamespace() { return $this->mNamespace
; }
329 function setNamespace( $n ) { $this->mNamespace
= $n; }
330 function getInterwiki() { return $this->mInterwiki
; }
331 function getFragment() { return $this->mFragment
; }
332 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
334 # Get title for search index
335 function getIndexTitle() {
336 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
339 # Get prefixed title with underscores
340 function getPrefixedDBkey() {
341 $s = $this->prefix( $this->mDbkeyform
);
342 $s = str_replace( ' ', '_', $s );
346 # Get prefixed title with spaces
347 # This is the form usually used for display
348 function getPrefixedText() {
349 if ( empty( $this->mPrefixedText
) ) {
350 $s = $this->prefix( $this->mTextform
);
351 $s = str_replace( '_', ' ', $s );
352 $this->mPrefixedText
= $s;
354 return $this->mPrefixedText
;
357 # As getPrefixedText(), plus fragment.
358 function getFullText() {
359 $text = $this->getPrefixedText();
360 if( '' != $this->mFragment
) {
361 $text .= '#' . $this->mFragment
;
366 # Get a URL-encoded title (not an actual URL) including interwiki
367 function getPrefixedURL() {
368 $s = $this->prefix( $this->mDbkeyform
);
369 $s = str_replace( ' ', '_', $s );
371 $s = wfUrlencode ( $s ) ;
373 # Cleaning up URL to make it look nice -- is this safe?
374 $s = preg_replace( '/%3[Aa]/', ':', $s );
375 $s = preg_replace( '/%2[Ff]/', '/', $s );
376 $s = str_replace( '%28', '(', $s );
377 $s = str_replace( '%29', ')', $s );
382 # Get a real URL referring to this title, with interwiki link and fragment
383 function getFullURL( $query = '' ) {
384 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
386 if ( '' == $this->mInterwiki
) {
388 return $wgServer . $this->getLocalUrl( $query );
390 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
391 $namespace = $wgLang->getNsText( $this->mNamespace
);
392 if ( '' != $namespace ) {
393 # Can this actually happen? Interwikis shouldn't be parsed.
396 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
397 if ( '' != $this->mFragment
) {
398 $url .= '#' . $this->mFragment
;
404 # Get a URL with an optional query string, no fragment
405 # * If $query=="", it will use $wgArticlePath
406 # * Returns a full for an interwiki link, loses any query string
407 # * Optionally adds the server and escapes for HTML
408 # * Setting $query to "-" makes an old-style URL with nothing in the
409 # query except a title
412 die( 'Call to obsolete obsolete function Title::getURL()' );
415 function getLocalURL( $query = '' ) {
416 global $wgLang, $wgArticlePath, $wgScript;
418 if ( $this->isExternal() ) {
419 return $this->getFullURL();
422 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
423 if ( $query == '' ) {
424 $url = str_replace( '$1', $dbkey, $wgArticlePath );
426 if ( $query == '-' ) {
429 if ( $wgScript != '' ) {
430 $url = "{$wgScript}?title={$dbkey}&{$query}";
433 $url = "/{$dbkey}?{$query}";
439 function escapeLocalURL( $query = '' ) {
440 return htmlspecialchars( $this->getLocalURL( $query ) );
443 function escapeFullURL( $query = '' ) {
444 return htmlspecialchars( $this->getFullURL( $query ) );
447 function getInternalURL( $query = '' ) {
448 # Used in various Squid-related code, in case we have a different
449 # internal hostname for the server than the exposed one.
450 global $wgInternalServer;
451 return $wgInternalServer . $this->getLocalURL( $query );
454 # Get the edit URL, or a null string if it is an interwiki link
455 function getEditURL() {
456 global $wgServer, $wgScript;
458 if ( '' != $this->mInterwiki
) { return ''; }
459 $s = $this->getLocalURL( 'action=edit' );
464 # Get HTML-escaped displayable text
465 # For the title field in <a> tags
466 function getEscapedText() {
467 return htmlspecialchars( $this->getPrefixedText() );
470 # Is the title interwiki?
471 function isExternal() { return ( '' != $this->mInterwiki
); }
473 # Does the title correspond to a protected article?
474 function isProtected() {
475 if ( -1 == $this->mNamespace
) { return true; }
476 $a = $this->getRestrictions();
477 if ( in_array( 'sysop', $a ) ) { return true; }
481 # Is the page a log page, i.e. one where the history is messed up by
482 # LogPage.php? This used to be used for suppressing diff links in recent
483 # changes, but now that's done by setting a flag in the recentchanges
484 # table. Hence, this probably is no longer used.
486 if ( $this->mNamespace
!= Namespace::getWikipedia() ) {
489 if ( ( 0 == strcmp( wfMsg( 'uploadlogpage' ), $this->mDbkeyform
) ) ||
490 ( 0 == strcmp( wfMsg( 'dellogpage' ), $this->mDbkeyform
) ) ) {
496 # Is $wgUser is watching this page?
497 function userIsWatching() {
500 if ( -1 == $this->mNamespace
) { return false; }
501 if ( 0 == $wgUser->getID() ) { return false; }
503 return $wgUser->isWatched( $this );
506 # Can $wgUser edit this page?
507 function userCanEdit() {
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() )
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
) )
527 $ur = $wgUser->getRights();
528 foreach ( $this->getRestrictions() as $r ) {
529 if ( '' != $r && ( ! in_array( $r, $ur ) ) ) {
536 function userCanRead() {
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;
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
566 return ( $wgUser->isSysop() or preg_match('/^'.preg_quote($wgUser->getName()).'/', $this->mTextform
) );
569 # Accessor/initialisation for mRestrictions
570 function getRestrictions() {
571 $id = $this->getArticleID();
572 if ( 0 == $id ) { return array(); }
574 if ( ! $this->mRestrictionsLoaded
) {
575 $dbr =& wfGetDB( DB_SLAVE
);
576 $res = $dbr->getField( 'cur', 'cur_restrictions', 'cur_id='.$id );
577 $this->mRestrictions
= explode( ',', trim( $res ) );
578 $this->mRestrictionsLoaded
= true;
580 return $this->mRestrictions
;
583 # Is there a version of this page in the deletion archive?
584 # Returns the number of archived revisions
585 function isDeleted() {
586 $fname = 'Title::isDeleted';
587 $dbr =& wfGetDB( DB_SLAVE
);
588 $n = $dbr->getField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
589 'ar_title' => $this->getDBkey() ), $fname );
593 # Get the article ID from the link cache
594 # $flags is a bit field, may be GAID_FOR_UPDATE to select for update
595 function getArticleID( $flags = 0 ) {
598 if ( $flags & GAID_FOR_UPDATE
) {
599 $oldUpdate = $wgLinkCache->forUpdate( true );
600 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
601 $wgLinkCache->forUpdate( $oldUpdate );
603 if ( -1 == $this->mArticleID
) {
604 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
607 return $this->mArticleID
;
610 # This clears some fields in this object, and clears any associated keys in the
611 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
612 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
613 function resetArticleID( $newid ) {
615 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
617 if ( 0 == $newid ) { $this->mArticleID
= -1; }
618 else { $this->mArticleID
= $newid; }
619 $this->mRestrictionsLoaded
= false;
620 $this->mRestrictions
= array();
623 # Updates cur_touched
624 # Called from LinksUpdate.php
625 function invalidateCache() {
626 $now = wfTimestampNow();
627 $dbw =& wfGetDB( DB_MASTER
);
628 $success = $dbw->updateArray( 'cur',
630 'cur_touched' => wfTimestampNow()
631 ), array( /* WHERE */
632 'cur_namespace' => $this->getNamespace() ,
633 'cur_title' => $this->getDBkey()
634 ), 'Title::invalidateCache'
639 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
640 /* private */ function prefix( $name ) {
644 if ( '' != $this->mInterwiki
) {
645 $p = $this->mInterwiki
. ':';
647 if ( 0 != $this->mNamespace
) {
648 $p .= $wgLang->getNsText( $this->mNamespace
) . ':';
653 # Secure and split - main initialisation function for this object
655 # Assumes that mDbkeyform has been set, and is urldecoded
656 # and uses underscores, but not otherwise munged. This function
657 # removes illegal characters, splits off the interwiki and
658 # namespace prefixes, sets the other forms, and canonicalizes
661 /* private */ function secureAndSplit()
663 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
664 $fname = 'Title::secureAndSplit';
665 wfProfileIn( $fname );
667 static $imgpre = false;
668 static $rxTc = false;
671 if ( $imgpre === false ) {
672 $imgpre = ':' . $wgLang->getNsText( Namespace::getImage() ) . ":";
673 # % is needed as well
674 $rxTc = '/[^' . Title
::legalChars() . ']/';
677 $this->mInterwiki
= $this->mFragment
= '';
678 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
680 # Clean up whitespace
682 $t = preg_replace( "/[\\s_]+/", '_', $this->mDbkeyform
);
683 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
686 wfProfileOut( $fname );
690 $this->mDbkeyform
= $t;
694 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
695 $t = substr( $t, 1 );
698 # Initial colon indicating main namespace
699 if ( ':' == $t{0} ) {
700 $r = substr( $t, 1 );
701 $this->mNamespace
= NS_MAIN
;
703 # Namespace or interwiki prefix
704 if ( preg_match( "/^(.+?)_*:_*(.*)$/", $t, $m ) ) {
705 #$p = strtolower( $m[1] );
707 $lowerNs = strtolower( $p );
708 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
709 # Canonical namespace
711 $this->mNamespace
= $ns;
712 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
715 $this->mNamespace
= $ns;
716 } elseif ( $this->getInterwikiLink( $p ) ) {
719 $this->mInterwiki
= $p;
721 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
723 } elseif($this->mInterwiki
!= $wgLocalInterwiki) {
731 # Redundant interwiki prefix to the local wiki
732 if ( 0 == strcmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
733 $this->mInterwiki
= '';
735 # We already know that some pages won't be in the database!
737 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
738 $this->mArticleID
= 0;
740 $f = strstr( $r, '#' );
741 if ( false !== $f ) {
742 $this->mFragment
= substr( $f, 1 );
743 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
746 # Reject illegal characters.
748 if( preg_match( $rxTc, $r ) ) {
749 wfProfileOut( $fname );
753 # "." and ".." conflict with the directories of those namesa
754 if ( strpos( $r, '.' ) !== false &&
755 ( $r === '.' ||
$r === '..' ||
756 strpos( $r, './' ) === 0 ||
757 strpos( $r, '../' ) === 0 ||
758 strpos( $r, '/./' ) !== false ||
759 strpos( $r, '/../' ) !== false ) )
761 wfProfileOut( $fname );
765 # Initial capital letter
766 if( $wgCapitalLinks && $this->mInterwiki
== '') {
767 $t = $wgLang->ucfirst( $r );
773 $this->mDbkeyform
= $t;
774 $this->mUrlform
= wfUrlencode( $t );
776 $this->mTextform
= str_replace( '_', ' ', $t );
778 wfProfileOut( $fname );
782 # Get a title object associated with the talk page of this article
783 function getTalkPage() {
784 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
787 # Get a title object associated with the subject page of this talk page
788 function getSubjectPage() {
789 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
792 # Get an array of Title objects linking to this title
793 # Also stores the IDs in the link cache
794 # $options may be FOR UPDATE
795 function getLinksTo( $options = '' ) {
797 $id = $this->getArticleID();
800 $db =& wfGetDB( DB_MASTER
);
802 $db =& wfGetDB( DB_SLAVE
);
804 $cur = $db->tableName( 'cur' );
805 $links = $db->tableName( 'links' );
807 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
808 $res = $db->query( $sql, "Title::getLinksTo" );
810 if ( $db->numRows( $res ) ) {
811 while ( $row = $db->fetchObject( $res ) ) {
812 if ( $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
) ) {
813 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
814 $retVal[] = $titleObj;
818 $db->freeResult( $res );
822 # Get an array of Title objects linking to this non-existent title
823 # Also stores the IDs in the link cache
824 function getBrokenLinksTo( $options = '' ) {
828 $db =& wfGetDB( DB_MASTER
);
830 $db =& wfGetDB( DB_SLAVE
);
832 $cur = $db->tableName( 'cur' );
833 $brokenlinks = $db->tableName( 'brokenlinks' );
834 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
836 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
837 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
838 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
840 if ( $db->numRows( $res ) ) {
841 while ( $row = $db->fetchObject( $res ) ) {
842 $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
843 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
844 $retVal[] = $titleObj;
847 $db->freeResult( $res );
851 function getSquidURLs() {
853 $this->getInternalURL(),
854 $this->getInternalURL( 'action=history' )
858 function moveNoAuth( &$nt ) {
859 return $this->moveTo( $nt, false );
862 # Move a title to a new location
863 # Returns true on success, message name on failure
864 # auth indicates whether wgUser's permissions should be checked
865 function moveTo( &$nt, $auth = true ) {
866 if( !$this or !$nt ) {
867 return 'badtitletext';
870 $fname = 'Title::move';
871 $oldid = $this->getArticleID();
872 $newid = $nt->getArticleID();
874 if ( strlen( $nt->getDBkey() ) < 1 ) {
875 return 'articleexists';
877 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
878 ( '' == $this->getDBkey() ) ||
879 ( '' != $this->getInterwiki() ) ||
881 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
882 ( '' == $nt->getDBkey() ) ||
883 ( '' != $nt->getInterwiki() ) ) {
884 return 'badarticleerror';
887 if ( $auth && ( !$this->userCanEdit() ||
!$nt->userCanEdit() ) ) {
888 return 'protectedpage';
891 # The move is allowed only if (1) the target doesn't exist, or
892 # (2) the target is a redirect to the source, and has no history
893 # (so we can undo bad moves right after they're done).
895 if ( 0 != $newid ) { # Target exists; check for validity
896 if ( ! $this->isValidMoveTarget( $nt ) ) {
897 return 'articleexists';
899 $this->moveOverExistingRedirect( $nt );
900 } else { # Target didn't exist, do normal move.
901 $this->moveToNewTitle( $nt, $newid );
904 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
906 $dbw =& wfGetDB( DB_MASTER
);
907 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
908 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
909 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
910 $dbw->query( $sql, "SpecialMovepage::doSubmit" );
914 $oldnamespace = $this->getNamespace() & ~
1;
915 $newnamespace = $nt->getNamespace() & ~
1;
916 $oldtitle = $this->getDBkey();
917 $newtitle = $nt->getDBkey();
919 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
920 WatchedItem
::duplicateEntries( $this, $nt );
923 # Update search engine
924 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
926 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
932 # Move page to title which is presently a redirect to the source page
934 /* 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',
949 'cur_touched' => $now,
950 'cur_namespace' => $nt->getNamespace(),
951 'cur_title' => $nt->getDBkey()
953 /* WHERE */ array( 'cur_id' => $oldid ),
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',
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,
974 'cur_restrictions' => '',
975 'cur_user_text' => $wgUser->getName(),
976 'cur_is_redirect' => 1,
979 /* WHERE */ array( 'cur_id' => $newid ),
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.
990 'old_namespace' => $nt->getNamespace(),
991 'old_title' => $nt->getDBkey(),
994 'old_namespace' => $this->getNamespace(),
995 'old_title' => $this->getDBkey(),
1000 RecentChange
::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
1004 # Load titles and IDs
1005 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1006 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1009 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1010 $dbw->query( $sql, $fname );
1013 if ( count( $linksToOld ) ||
count( $linksToNew )) {
1014 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1017 # Insert links to old title
1018 foreach ( $linksToOld as $linkTitle ) {
1024 $id = $linkTitle->getArticleID();
1025 $sql .= "($id,$newid)";
1028 # Insert links to new title
1029 foreach ( $linksToNew as $linkTitle ) {
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 ) );
1048 LinkCache
::linksccClearLinksTo( $oldid );
1049 LinkCache
::linksccClearLinksTo( $newid );
1052 if ( $wgUseSquid ) {
1053 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1054 $u = new SquidUpdate( $urls );
1059 # Move page to non-existing title.
1060 # Sets $newid to be the new article ID
1062 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1063 global $wgUser, $wgLinkCache, $wgUseSquid;
1064 $fname = 'MovePageForm::moveToNewTitle';
1065 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1067 $now = wfTimestampNow();
1068 $won = wfInvertTimestamp( $now );
1069 $newid = $nt->getArticleID();
1070 $oldid = $this->getArticleID();
1071 $dbw =& wfGetDB( DB_MASTER
);
1074 $dbw->updateArray( 'cur',
1076 'cur_touched' => $now,
1077 'cur_namespace' => $nt->getNamespace(),
1078 'cur_title' => $nt->getDBkey()
1080 /* WHERE */ array( 'cur_id' => $oldid ),
1084 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1087 $dbw->insertArray( 'cur', array(
1088 'cur_namespace' => $this->getNamespace(),
1089 'cur_title' => $this->getDBkey(),
1090 'cur_comment' => $comment,
1091 'cur_user' => $wgUser->getID(),
1092 'cur_user_text' => $wgUser->getName(),
1093 'cur_timestamp' => $now,
1094 'inverse_timestamp' => $won,
1095 'cur_touched' => $now,
1096 'cur_is_redirect' => 1,
1098 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1100 $newid = $dbw->insertId();
1101 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1103 # Rename old entries
1107 'old_namespace' => $nt->getNamespace(),
1108 'old_title' => $nt->getDBkey()
1111 'old_namespace' => $this->getNamespace(),
1112 'old_title' => $this->getDBkey()
1117 RecentChange
::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1119 # Purge squid and linkscc as per article creation
1120 Article
::onArticleCreate( $nt );
1122 # Any text links to the old title must be reassigned to the redirect
1123 $dbw->updateArray( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1124 LinkCache
::linksccClearLinksTo( $oldid );
1126 # Record the just-created redirect's linking to the page
1127 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1129 # Non-existent target may have had broken links to it; these must
1130 # now be removed and made into good links.
1131 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1132 $update->fixBrokenLinks();
1134 # Purge old title from squid
1135 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1136 $titles = $nt->getLinksTo();
1137 if ( $wgUseSquid ) {
1138 $urls = $this->getSquidURLs();
1139 foreach ( $titles as $linkTitle ) {
1140 $urls[] = $linkTitle->getInternalURL();
1142 $u = new SquidUpdate( $urls );
1147 # Checks if $this can be moved to $nt
1148 # Selects for update, so don't call it unless you mean business
1149 function isValidMoveTarget( $nt ) {
1150 $fname = 'Title::isValidMoveTarget';
1151 $dbw =& wfGetDB( DB_MASTER
);
1154 $id = $nt->getArticleID();
1155 $obj = $dbw->getArray( 'cur', array( 'cur_is_redirect','cur_text' ),
1156 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1158 if ( !$obj ||
0 == $obj->cur_is_redirect
) {
1163 # Does the redirect point to the source?
1164 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text
, $m ) ) {
1165 $redirTitle = Title
::newFromText( $m[1] );
1166 if( !is_object( $redirTitle ) ||
1167 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1172 # Does the article have a history?
1173 $row = $dbw->getArray( 'old', array( 'old_id' ),
1175 'old_namespace' => $nt->getNamespace(),
1176 'old_title' => $nt->getDBkey()
1177 ), $fname, 'FOR UPDATE'
1180 # Return true if there was no history
1181 return $row === false;
1184 # Create a redirect, fails if the title already exists, does not notify RC
1186 function createRedirect( $dest, $comment ) {
1188 if ( $this->getArticleID() ) {
1192 $fname = "Title::createRedirect";
1193 $dbw =& wfGetDB( DB_MASTER
);
1194 $now = wfTimestampNow();
1195 $won = wfInvertTimestamp( $now );
1196 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1198 $dbw->insertArray( 'cur', array(
1199 'cur_id' => $seqVal,
1200 'cur_namespace' => $this->getNamespace(),
1201 'cur_title' => $this->getDBkey(),
1202 'cur_comment' => $comment,
1203 'cur_user' => $wgUser->getID(),
1204 'cur_user_text' => $wgUser->getName(),
1205 'cur_timestamp' => $now,
1206 'inverse_timestamp' => $won,
1207 'cur_touched' => $now,
1208 'cur_is_redirect' => 1,
1210 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1212 $newid = $dbw->insertId();
1213 $this->resetArticleID( $newid );
1216 if ( $dest->getArticleID() ) {
1217 $dbw->insertArray( 'links',
1219 'l_to' => $dest->getArticleID(),
1224 $dbw->insertArray( 'brokenlinks',
1226 'bl_to' => $dest->getPrefixedDBkey(),
1232 Article
::onArticleCreate( $this );
1236 # Get categories to wich belong this title and return an array of
1238 function getParentCategories( ) {
1239 global $wgLang,$wgUser;
1241 $titlekey = $this->getArticleId();
1242 $cns = Namespace::getCategory();
1243 $sk =& $wgUser->getSkin();
1245 $dbr =& wfGetDB( DB_SLAVE
);
1246 $cur = $dbr->tableName( 'cur' );
1247 $categorylinks = $dbr->tableName( 'categorylinks' );
1249 # get the parents categories of this title from the database
1250 $sql = "SELECT DISTINCT cur_id FROM $cur,$categorylinks
1251 WHERE cl_from='$titlekey' AND cl_to=cur_title AND cur_namespace='$cns'
1252 ORDER BY cl_sortkey" ;
1253 $res = $dbr->query ( $sql ) ;
1255 if($dbr->numRows($res) > 0) {
1256 while ( $x = $dbr->fetchObject ( $res ) ) $data[] = $x ;
1257 $dbr->freeResult ( $res ) ;
1264 # will get the parents and grand-parents
1265 # TODO : not sure what's happening when a loop happen like:
1266 # Encyclopedia > Astronomy > Encyclopedia
1267 function getAllParentCategories(&$stack) {
1268 global $wgUser,$wgLang;
1272 $parents = $this->getParentCategories( );
1276 # The current element has no more parent so we dump the stack
1277 # and make a clean line of categories
1278 $sk =& $wgUser->getSkin() ;
1280 foreach ( array_reverse($stack) as $child => $parent )
1282 # make a link of that parent
1283 $result .= $sk->makeLink($wgLang->getNSText ( Namespace::getCategory() ).":".$parent,$parent);
1284 $result .= ' > ';
1285 $lastchild = $child;
1287 # append the last child.
1288 # TODO : We should have a last child unless there is an error in the
1289 # "categorylinks" table.
1290 if(isset($lastchild)) { $result .= $lastchild; }
1292 $result .= "<br/>\n";
1294 # now we can empty the stack
1298 # look at parents of current category
1299 foreach($parents as $parent)
1301 # create a title object for the parent
1302 $tpar = Title
::newFromID($parent->cur_id
);
1303 # add it to the stack
1304 $stack[$this->getText()] = $tpar->getText();
1306 $result .= $tpar->getAllParentCategories($stack);
1310 if(isset($result)) { return $result; }
1311 else { return ''; };
1314 # Returns an associative array for selecting this title from cur
1315 function curCond() {
1316 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1319 function oldCond() {
1320 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);