2b4e562324a8ed4c27973081f4076bcf74673700
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 $rt = Title
::newFromText( $m[1] );
168 #----------------------------------------------------------------------------
170 #----------------------------------------------------------------------------
172 # Get the prefixed DB key associated with an ID
173 /* static */ function nameOf( $id ) {
174 $fname = 'Title::nameOf';
175 $dbr =& wfGetDB( DB_SLAVE
);
177 $s = $dbr->getArray( 'cur', array( 'cur_namespace','cur_title' ), array( 'cur_id' => $id ), $fname );
178 if ( $s === false ) { return NULL; }
180 $n = Title
::makeName( $s->cur_namespace
, $s->cur_title
);
184 # Get a regex character class describing the legal characters in a link
185 /* static */ function legalChars() {
186 # Missing characters:
187 # * []|# Needed for link syntax
188 # * % and + are corrupted by Apache when they appear in the path
190 # % seems to work though
192 # The problem with % is that URLs are double-unescaped: once by Apache's
193 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
194 # Our code does not double-escape to compensate for this, indeed double escaping
195 # would break if the double-escaped title was passed in the query string
196 # rather than the path. This is a minor security issue because articles can be
197 # created such that they are hard to view or edit. -- TS
199 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
200 # this breaks interlanguage links
202 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z{}~\\x80-\\xFF";
206 # Returns a stripped-down a title string ready for the search index
207 # Takes a namespace index and a text-form main part
208 /* static */ function indexTitle( $ns, $title ) {
209 global $wgDBminWordLen, $wgLang;
211 $lc = SearchEngine
::legalSearchChars() . '&#;';
212 $t = $wgLang->stripForSearch( $title );
213 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
214 $t = strtolower( $t );
217 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
218 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
220 $t = preg_replace( "/\\s+/", ' ', $t );
222 if ( $ns == Namespace::getImage() ) {
223 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
228 # Make a prefixed DB key from a DB key and a namespace index
229 /* static */ function makeName( $ns, $title ) {
232 $n = $wgLang->getNsText( $ns );
233 if ( "" == $n ) { return $title; }
234 else { return "{$n}:{$title}"; }
238 # Returns the URL associated with an interwiki prefix
239 # The URL contains $1, which is replaced by the title
240 function getInterwikiLink( $key ) {
241 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
242 $fname = 'Title::getInterwikiLink';
243 $k = $wgDBname.':interwiki:'.$key;
245 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
246 return $wgTitleInterwikiCache[$k]->iw_url
;
248 $s = $wgMemc->get( $k );
249 # Ignore old keys with no iw_local
250 if( $s && isset( $s->iw_local
) ) {
251 $wgTitleInterwikiCache[$k] = $s;
254 $dbr =& wfGetDB( DB_SLAVE
);
255 $res = $dbr->select( 'interwiki', array( 'iw_url', 'iw_local' ), array( 'iw_prefix' => $key ), $fname );
258 $s = $dbr->fetchObject( $res );
260 # Cache non-existence: create a blank object and save it to memcached
265 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
266 $wgTitleInterwikiCache[$k] = $s;
271 global $wgTitleInterwikiCache, $wgDBname;
273 if ( $this->mInterwiki
!= '' ) {
274 # Make sure key is loaded into cache
275 $this->getInterwikiLink( $this->mInterwiki
);
276 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
277 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
283 # Update the cur_touched field for an array of title objects
284 # Inefficient unless the IDs are already loaded into the link cache
285 /* static */ function touchArray( $titles, $timestamp = '' ) {
286 if ( count( $titles ) == 0 ) {
289 if ( $timestamp == '' ) {
290 $timestamp = wfTimestampNow();
292 $dbw =& wfGetDB( DB_MASTER
);
293 $cur = $dbw->tableName( 'cur' );
294 $sql = "UPDATE $cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
297 foreach ( $titles as $title ) {
302 $sql .= $title->getArticleID();
306 $dbw->query( $sql, 'Title::touchArray' );
310 #----------------------------------------------------------------------------
312 #----------------------------------------------------------------------------
315 # See the definitions at the top of this file
317 function getText() { return $this->mTextform
; }
318 function getPartialURL() { return $this->mUrlform
; }
319 function getDBkey() { return $this->mDbkeyform
; }
320 function getNamespace() { return $this->mNamespace
; }
321 function setNamespace( $n ) { $this->mNamespace
= $n; }
322 function getInterwiki() { return $this->mInterwiki
; }
323 function getFragment() { return $this->mFragment
; }
324 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
326 # Get title for search index
327 function getIndexTitle() {
328 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
331 # Get prefixed title with underscores
332 function getPrefixedDBkey() {
333 $s = $this->prefix( $this->mDbkeyform
);
334 $s = str_replace( ' ', '_', $s );
338 # Get prefixed title with spaces
339 # This is the form usually used for display
340 function getPrefixedText() {
341 if ( empty( $this->mPrefixedText
) ) {
342 $s = $this->prefix( $this->mTextform
);
343 $s = str_replace( '_', ' ', $s );
344 $this->mPrefixedText
= $s;
346 return $this->mPrefixedText
;
349 # As getPrefixedText(), plus fragment.
350 function getFullText() {
351 $text = $this->getPrefixedText();
352 if( '' != $this->mFragment
) {
353 $text .= '#' . $this->mFragment
;
358 # Get a URL-encoded title (not an actual URL) including interwiki
359 function getPrefixedURL() {
360 $s = $this->prefix( $this->mDbkeyform
);
361 $s = str_replace( ' ', '_', $s );
363 $s = wfUrlencode ( $s ) ;
365 # Cleaning up URL to make it look nice -- is this safe?
366 $s = preg_replace( '/%3[Aa]/', ':', $s );
367 $s = preg_replace( '/%2[Ff]/', '/', $s );
368 $s = str_replace( '%28', '(', $s );
369 $s = str_replace( '%29', ')', $s );
374 # Get a real URL referring to this title, with interwiki link and fragment
375 function getFullURL( $query = '' ) {
376 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
378 if ( '' == $this->mInterwiki
) {
380 return $wgServer . $this->getLocalUrl( $query );
382 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
383 $namespace = $wgLang->getNsText( $this->mNamespace
);
384 if ( '' != $namespace ) {
385 # Can this actually happen? Interwikis shouldn't be parsed.
388 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
389 if ( '' != $this->mFragment
) {
390 $url .= '#' . $this->mFragment
;
396 # Get a URL with an optional query string, no fragment
397 # * If $query=="", it will use $wgArticlePath
398 # * Returns a full for an interwiki link, loses any query string
399 # * Optionally adds the server and escapes for HTML
400 # * Setting $query to "-" makes an old-style URL with nothing in the
401 # query except a title
404 die( 'Call to obsolete obsolete function Title::getURL()' );
407 function getLocalURL( $query = '' ) {
408 global $wgLang, $wgArticlePath, $wgScript;
410 if ( $this->isExternal() ) {
411 return $this->getFullURL();
414 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
415 if ( $query == '' ) {
416 $url = str_replace( '$1', $dbkey, $wgArticlePath );
418 if ( $query == '-' ) {
421 if ( $wgScript != '' ) {
422 $url = "{$wgScript}?title={$dbkey}&{$query}";
425 $url = "/{$dbkey}?{$query}";
431 function escapeLocalURL( $query = '' ) {
432 return htmlspecialchars( $this->getLocalURL( $query ) );
435 function escapeFullURL( $query = '' ) {
436 return htmlspecialchars( $this->getFullURL( $query ) );
439 function getInternalURL( $query = '' ) {
440 # Used in various Squid-related code, in case we have a different
441 # internal hostname for the server than the exposed one.
442 global $wgInternalServer;
443 return $wgInternalServer . $this->getLocalURL( $query );
446 # Get the edit URL, or a null string if it is an interwiki link
447 function getEditURL() {
448 global $wgServer, $wgScript;
450 if ( '' != $this->mInterwiki
) { return ''; }
451 $s = $this->getLocalURL( 'action=edit' );
456 # Get HTML-escaped displayable text
457 # For the title field in <a> tags
458 function getEscapedText() {
459 return htmlspecialchars( $this->getPrefixedText() );
462 # Is the title interwiki?
463 function isExternal() { return ( '' != $this->mInterwiki
); }
465 # Does the title correspond to a protected article?
466 function isProtected() {
467 if ( -1 == $this->mNamespace
) { return true; }
468 $a = $this->getRestrictions();
469 if ( in_array( 'sysop', $a ) ) { return true; }
473 # Is the page a log page, i.e. one where the history is messed up by
474 # LogPage.php? This used to be used for suppressing diff links in recent
475 # changes, but now that's done by setting a flag in the recentchanges
476 # table. Hence, this probably is no longer used.
478 if ( $this->mNamespace
!= Namespace::getWikipedia() ) {
481 if ( ( 0 == strcmp( wfMsg( 'uploadlogpage' ), $this->mDbkeyform
) ) ||
482 ( 0 == strcmp( wfMsg( 'dellogpage' ), $this->mDbkeyform
) ) ) {
488 # Is $wgUser is watching this page?
489 function userIsWatching() {
492 if ( -1 == $this->mNamespace
) { return false; }
493 if ( 0 == $wgUser->getID() ) { return false; }
495 return $wgUser->isWatched( $this );
498 # Can $wgUser edit this page?
499 function userCanEdit() {
501 if ( -1 == $this->mNamespace
) { return false; }
502 if ( NS_MEDIAWIKI
== $this->mNamespace
&& !$wgUser->isSysop() ) { return false; }
503 # if ( 0 == $this->getArticleID() ) { return false; }
504 if ( $this->mDbkeyform
== '_' ) { return false; }
505 # protect global styles and js
506 if ( NS_MEDIAWIKI
== $this->mNamespace
507 && preg_match("/\\.(css|js)$/", $this->mTextform
)
508 && !$wgUser->isSysop() )
510 //if ( $this->isCssJsSubpage() and !$this->userCanEditCssJsSubpage() ) { return false; }
511 # protect css/js subpages of user pages
512 # XXX: this might be better using restrictions
513 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
514 if( Namespace::getUser() == $this->mNamespace
515 and preg_match("/\\.(css|js)$/", $this->mTextform
)
516 and !$wgUser->isSysop()
517 and !preg_match('/^'.preg_quote($wgUser->getName(), '/').'/', $this->mTextform
) )
519 $ur = $wgUser->getRights();
520 foreach ( $this->getRestrictions() as $r ) {
521 if ( '' != $r && ( ! in_array( $r, $ur ) ) ) {
528 function userCanRead() {
530 global $wgWhitelistRead;
532 if( 0 != $wgUser->getID() ) return true;
533 if( !is_array( $wgWhitelistRead ) ) return true;
535 $name = $this->getPrefixedText();
536 if( in_array( $name, $wgWhitelistRead ) ) return true;
538 # Compatibility with old settings
539 if( $this->getNamespace() == NS_MAIN
) {
540 if( in_array( ":" . $name, $wgWhitelistRead ) ) return true;
545 function isCssJsSubpage() {
546 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
548 function isCssSubpage() {
549 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
551 function isJsSubpage() {
552 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
554 function userCanEditCssJsSubpage() {
555 # protect css/js subpages of user pages
556 # XXX: this might be better using restrictions
558 return ( $wgUser->isSysop() or preg_match('/^'.preg_quote($wgUser->getName()).'/', $this->mTextform
) );
561 # Accessor/initialisation for mRestrictions
562 function getRestrictions() {
563 $id = $this->getArticleID();
564 if ( 0 == $id ) { return array(); }
566 if ( ! $this->mRestrictionsLoaded
) {
567 $dbr =& wfGetDB( DB_SLAVE
);
568 $res = $dbr->getField( 'cur', 'cur_restrictions', 'cur_id='.$id );
569 $this->mRestrictions
= explode( ',', trim( $res ) );
570 $this->mRestrictionsLoaded
= true;
572 return $this->mRestrictions
;
575 # Is there a version of this page in the deletion archive?
576 # Returns the number of archived revisions
577 function isDeleted() {
578 $fname = 'Title::isDeleted';
579 $dbr =& wfGetDB( DB_SLAVE
);
580 $n = $dbr->getField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
581 'ar_title' => $this->getDBkey() ), $fname );
585 # Get the article ID from the link cache
586 # $flags is a bit field, may be GAID_FOR_UPDATE to select for update
587 function getArticleID( $flags = 0 ) {
590 if ( $flags & GAID_FOR_UPDATE
) {
591 $oldUpdate = $wgLinkCache->forUpdate( true );
592 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
593 $wgLinkCache->forUpdate( $oldUpdate );
595 if ( -1 == $this->mArticleID
) {
596 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
599 return $this->mArticleID
;
602 # This clears some fields in this object, and clears any associated keys in the
603 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
604 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
605 function resetArticleID( $newid ) {
607 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
609 if ( 0 == $newid ) { $this->mArticleID
= -1; }
610 else { $this->mArticleID
= $newid; }
611 $this->mRestrictionsLoaded
= false;
612 $this->mRestrictions
= array();
615 # Updates cur_touched
616 # Called from LinksUpdate.php
617 function invalidateCache() {
618 $now = wfTimestampNow();
619 $dbw =& wfGetDB( DB_MASTER
);
620 $success = $dbw->updateArray( 'cur',
622 'cur_touched' => wfTimestampNow()
623 ), array( /* WHERE */
624 'cur_namespace' => $this->getNamespace() ,
625 'cur_title' => $this->getDBkey()
626 ), 'Title::invalidateCache'
631 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
632 /* private */ function prefix( $name ) {
636 if ( '' != $this->mInterwiki
) {
637 $p = $this->mInterwiki
. ':';
639 if ( 0 != $this->mNamespace
) {
640 $p .= $wgLang->getNsText( $this->mNamespace
) . ':';
645 # Secure and split - main initialisation function for this object
647 # Assumes that mDbkeyform has been set, and is urldecoded
648 # and uses underscores, but not otherwise munged. This function
649 # removes illegal characters, splits off the interwiki and
650 # namespace prefixes, sets the other forms, and canonicalizes
653 /* private */ function secureAndSplit()
655 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
656 $fname = 'Title::secureAndSplit';
657 wfProfileIn( $fname );
659 static $imgpre = false;
660 static $rxTc = false;
663 if ( $imgpre === false ) {
664 $imgpre = ':' . $wgLang->getNsText( Namespace::getImage() ) . ":";
665 # % is needed as well
666 $rxTc = '/[^' . Title
::legalChars() . ']/';
669 $this->mInterwiki
= $this->mFragment
= '';
670 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
672 # Clean up whitespace
674 $t = preg_replace( "/[\\s_]+/", '_', $this->mDbkeyform
);
675 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
678 wfProfileOut( $fname );
682 $this->mDbkeyform
= $t;
686 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
687 $t = substr( $t, 1 );
690 # Initial colon indicating main namespace
691 if ( ':' == $t{0} ) {
692 $r = substr( $t, 1 );
693 $this->mNamespace
= NS_MAIN
;
695 # Namespace or interwiki prefix
696 if ( preg_match( "/^(.+?)_*:_*(.*)$/", $t, $m ) ) {
697 #$p = strtolower( $m[1] );
699 $lowerNs = strtolower( $p );
700 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
701 # Canonical namespace
703 $this->mNamespace
= $ns;
704 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
707 $this->mNamespace
= $ns;
708 } elseif ( $this->getInterwikiLink( $p ) ) {
711 $this->mInterwiki
= $p;
713 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
715 } elseif($this->mInterwiki
!= $wgLocalInterwiki) {
723 # Redundant interwiki prefix to the local wiki
724 if ( 0 == strcmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
725 $this->mInterwiki
= '';
727 # We already know that some pages won't be in the database!
729 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
730 $this->mArticleID
= 0;
732 $f = strstr( $r, '#' );
733 if ( false !== $f ) {
734 $this->mFragment
= substr( $f, 1 );
735 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
738 # Reject illegal characters.
740 if( preg_match( $rxTc, $r ) ) {
741 wfProfileOut( $fname );
745 # "." and ".." conflict with the directories of those namesa
746 if ( strpos( $r, '.' ) !== false &&
747 ( $r === '.' ||
$r === '..' ||
748 strpos( $r, './' ) === 0 ||
749 strpos( $r, '../' ) === 0 ||
750 strpos( $r, '/./' ) !== false ||
751 strpos( $r, '/../' ) !== false ) )
753 wfProfileOut( $fname );
757 # Initial capital letter
758 if( $wgCapitalLinks && $this->mInterwiki
== '') {
759 $t = $wgLang->ucfirst( $r );
765 $this->mDbkeyform
= $t;
766 $this->mUrlform
= wfUrlencode( $t );
768 $this->mTextform
= str_replace( '_', ' ', $t );
770 wfProfileOut( $fname );
774 # Get a title object associated with the talk page of this article
775 function getTalkPage() {
776 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
779 # Get a title object associated with the subject page of this talk page
780 function getSubjectPage() {
781 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
784 # Get an array of Title objects linking to this title
785 # Also stores the IDs in the link cache
786 # $options may be FOR UPDATE
787 function getLinksTo( $options = '' ) {
789 $id = $this->getArticleID();
792 $db =& wfGetDB( DB_MASTER
);
794 $db =& wfGetDB( DB_SLAVE
);
796 $cur = $db->tableName( 'cur' );
797 $links = $db->tableName( 'links' );
799 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
800 $res = $db->query( $sql, "Title::getLinksTo" );
802 if ( $db->numRows( $res ) ) {
803 while ( $row = $db->fetchObject( $res ) ) {
804 if ( $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
) ) {
805 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
806 $retVal[] = $titleObj;
810 $db->freeResult( $res );
814 # Get an array of Title objects linking to this non-existent title
815 # Also stores the IDs in the link cache
816 function getBrokenLinksTo( $options = '' ) {
820 $db =& wfGetDB( DB_MASTER
);
822 $db =& wfGetDB( DB_SLAVE
);
824 $cur = $db->tableName( 'cur' );
825 $brokenlinks = $db->tableName( 'brokenlinks' );
826 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
828 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
829 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
830 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
832 if ( $db->numRows( $res ) ) {
833 while ( $row = $db->fetchObject( $res ) ) {
834 $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
835 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
836 $retVal[] = $titleObj;
839 $db->freeResult( $res );
843 function getSquidURLs() {
845 $this->getInternalURL(),
846 $this->getInternalURL( 'action=history' )
850 function moveNoAuth( &$nt ) {
851 return $this->moveTo( $nt, false );
854 # Move a title to a new location
855 # Returns true on success, message name on failure
856 # auth indicates whether wgUser's permissions should be checked
857 function moveTo( &$nt, $auth = true ) {
858 if( !$this or !$nt ) {
859 return 'badtitletext';
862 $fname = 'Title::move';
863 $oldid = $this->getArticleID();
864 $newid = $nt->getArticleID();
866 if ( strlen( $nt->getDBkey() ) < 1 ) {
867 return 'articleexists';
869 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
870 ( '' == $this->getDBkey() ) ||
871 ( '' != $this->getInterwiki() ) ||
873 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
874 ( '' == $nt->getDBkey() ) ||
875 ( '' != $nt->getInterwiki() ) ) {
876 return 'badarticleerror';
879 if ( $auth && ( !$this->userCanEdit() ||
!$nt->userCanEdit() ) ) {
880 return 'protectedpage';
883 # The move is allowed only if (1) the target doesn't exist, or
884 # (2) the target is a redirect to the source, and has no history
885 # (so we can undo bad moves right after they're done).
887 if ( 0 != $newid ) { # Target exists; check for validity
888 if ( ! $this->isValidMoveTarget( $nt ) ) {
889 return 'articleexists';
891 $this->moveOverExistingRedirect( $nt );
892 } else { # Target didn't exist, do normal move.
893 $this->moveToNewTitle( $nt, $newid );
896 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
898 $dbw =& wfGetDB( DB_MASTER
);
899 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
900 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
901 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
902 $dbw->query( $sql, "SpecialMovepage::doSubmit" );
906 $oldnamespace = $this->getNamespace() & ~
1;
907 $newnamespace = $nt->getNamespace() & ~
1;
908 $oldtitle = $this->getDBkey();
909 $newtitle = $nt->getDBkey();
911 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
912 WatchedItem
::duplicateEntries( $this, $nt );
915 # Update search engine
916 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
918 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
924 # Move page to title which is presently a redirect to the source page
926 /* private */ function moveOverExistingRedirect( &$nt ) {
927 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
928 $fname = 'Title::moveOverExistingRedirect';
929 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
931 $now = wfTimestampNow();
932 $won = wfInvertTimestamp( $now );
933 $newid = $nt->getArticleID();
934 $oldid = $this->getArticleID();
935 $dbw =& wfGetDB( DB_MASTER
);
936 $links = $dbw->tableName( 'links' );
938 # Change the name of the target page:
939 $dbw->updateArray( 'cur',
941 'cur_touched' => $now,
942 'cur_namespace' => $nt->getNamespace(),
943 'cur_title' => $nt->getDBkey()
945 /* WHERE */ array( 'cur_id' => $oldid ),
948 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
950 # Repurpose the old redirect. We don't save it to history since
951 # by definition if we've got here it's rather uninteresting.
953 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
954 $dbw->updateArray( 'cur',
956 'cur_touched' => $now,
957 'cur_timestamp' => $now,
958 'inverse_timestamp' => $won,
959 'cur_namespace' => $this->getNamespace(),
960 'cur_title' => $this->getDBkey(),
961 'cur_text' => $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n",
962 'cur_comment' => $comment,
963 'cur_user' => $wgUser->getID(),
964 'cur_minor_edit' => 0,
966 'cur_restrictions' => '',
967 'cur_user_text' => $wgUser->getName(),
968 'cur_is_redirect' => 1,
971 /* WHERE */ array( 'cur_id' => $newid ),
975 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
977 # Fix the redundant names for the past revisions of the target page.
978 # The redirect should have no old revisions.
982 'old_namespace' => $nt->getNamespace(),
983 'old_title' => $nt->getDBkey(),
986 'old_namespace' => $this->getNamespace(),
987 'old_title' => $this->getDBkey(),
992 RecentChange
::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
996 # Load titles and IDs
997 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
998 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1001 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1002 $dbw->query( $sql, $fname );
1005 if ( count( $linksToOld ) ||
count( $linksToNew )) {
1006 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1009 # Insert links to old title
1010 foreach ( $linksToOld as $linkTitle ) {
1016 $id = $linkTitle->getArticleID();
1017 $sql .= "($id,$newid)";
1020 # Insert links to new title
1021 foreach ( $linksToNew as $linkTitle ) {
1027 $id = $linkTitle->getArticleID();
1028 $sql .= "($id, $oldid)";
1031 $dbw->query( $sql, DB_MASTER
, $fname );
1034 # Now, we record the link from the redirect to the new title.
1035 # It should have no other outgoing links...
1036 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1037 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1040 LinkCache
::linksccClearLinksTo( $oldid );
1041 LinkCache
::linksccClearLinksTo( $newid );
1044 if ( $wgUseSquid ) {
1045 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1046 $u = new SquidUpdate( $urls );
1051 # Move page to non-existing title.
1052 # Sets $newid to be the new article ID
1054 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1055 global $wgUser, $wgLinkCache, $wgUseSquid;
1056 $fname = 'MovePageForm::moveToNewTitle';
1057 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1059 $now = wfTimestampNow();
1060 $won = wfInvertTimestamp( $now );
1061 $newid = $nt->getArticleID();
1062 $oldid = $this->getArticleID();
1063 $dbw =& wfGetDB( DB_MASTER
);
1066 $dbw->updateArray( 'cur',
1068 'cur_touched' => $now,
1069 'cur_namespace' => $nt->getNamespace(),
1070 'cur_title' => $nt->getDBkey()
1072 /* WHERE */ array( 'cur_id' => $oldid ),
1076 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1079 $dbw->insertArray( 'cur', array(
1080 'cur_namespace' => $this->getNamespace(),
1081 'cur_title' => $this->getDBkey(),
1082 'cur_comment' => $comment,
1083 'cur_user' => $wgUser->getID(),
1084 'cur_user_text' => $wgUser->getName(),
1085 'cur_timestamp' => $now,
1086 'inverse_timestamp' => $won,
1087 'cur_touched' => $now,
1088 'cur_is_redirect' => 1,
1090 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1092 $newid = $dbw->insertId();
1093 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1095 # Rename old entries
1099 'old_namespace' => $nt->getNamespace(),
1100 'old_title' => $nt->getDBkey()
1103 'old_namespace' => $this->getNamespace(),
1104 'old_title' => $this->getDBkey()
1109 RecentChange
::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1111 # Purge squid and linkscc as per article creation
1112 Article
::onArticleCreate( $nt );
1114 # Any text links to the old title must be reassigned to the redirect
1115 $dbw->updateArray( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1116 LinkCache
::linksccClearLinksTo( $oldid );
1118 # Record the just-created redirect's linking to the page
1119 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1121 # Non-existent target may have had broken links to it; these must
1122 # now be removed and made into good links.
1123 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1124 $update->fixBrokenLinks();
1126 # Purge old title from squid
1127 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1128 $titles = $nt->getLinksTo();
1129 if ( $wgUseSquid ) {
1130 $urls = $this->getSquidURLs();
1131 foreach ( $titles as $linkTitle ) {
1132 $urls[] = $linkTitle->getInternalURL();
1134 $u = new SquidUpdate( $urls );
1139 # Checks if $this can be moved to $nt
1140 # Selects for update, so don't call it unless you mean business
1141 function isValidMoveTarget( $nt ) {
1142 $fname = 'Title::isValidMoveTarget';
1143 $dbw =& wfGetDB( DB_MASTER
);
1146 $id = $nt->getArticleID();
1147 $obj = $dbw->getArray( 'cur', array( 'cur_is_redirect','cur_text' ),
1148 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1150 if ( !$obj ||
0 == $obj->cur_is_redirect
) {
1155 # Does the redirect point to the source?
1156 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text
, $m ) ) {
1157 $redirTitle = Title
::newFromText( $m[1] );
1158 if( !is_object( $redirTitle ) ||
1159 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1164 # Does the article have a history?
1165 $row = $dbw->getArray( 'old', array( 'old_id' ),
1167 'old_namespace' => $nt->getNamespace(),
1168 'old_title' => $nt->getDBkey()
1169 ), $fname, 'FOR UPDATE'
1172 # Return true if there was no history
1173 return $row === false;
1176 # Create a redirect, fails if the title already exists, does not notify RC
1178 function createRedirect( $dest, $comment ) {
1180 if ( $this->getArticleID() ) {
1184 $fname = "Title::createRedirect";
1185 $dbw =& wfGetDB( DB_MASTER
);
1186 $now = wfTimestampNow();
1187 $won = wfInvertTimestamp( $now );
1188 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1190 $dbw->insertArray( 'cur', array(
1191 'cur_id' => $seqVal,
1192 'cur_namespace' => $this->getNamespace(),
1193 'cur_title' => $this->getDBkey(),
1194 'cur_comment' => $comment,
1195 'cur_user' => $wgUser->getID(),
1196 'cur_user_text' => $wgUser->getName(),
1197 'cur_timestamp' => $now,
1198 'inverse_timestamp' => $won,
1199 'cur_touched' => $now,
1200 'cur_is_redirect' => 1,
1202 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1204 $newid = $dbw->insertId();
1205 $this->resetArticleID( $newid );
1208 if ( $dest->getArticleID() ) {
1209 $dbw->insertArray( 'links',
1211 'l_to' => $dest->getArticleID(),
1216 $dbw->insertArray( 'brokenlinks',
1218 'bl_to' => $dest->getPrefixedDBkey(),
1224 Article
::onArticleCreate( $this );
1228 # Get categories to wich belong this title and return an array of
1230 function getParentCategories( ) {
1231 global $wgLang,$wgUser;
1233 $titlekey = $this->getArticleId();
1234 $cns = Namespace::getCategory();
1235 $sk =& $wgUser->getSkin();
1237 $dbr =& wfGetDB( DB_SLAVE
);
1238 $cur = $dbr->tableName( 'cur' );
1239 $categorylinks = $dbr->tableName( 'categorylinks' );
1241 # get the parents categories of this title from the database
1242 $sql = "SELECT DISTINCT cur_id FROM $cur,$categorylinks
1243 WHERE cl_from='$titlekey' AND cl_to=cur_title AND cur_namespace='$cns'
1244 ORDER BY cl_sortkey" ;
1245 $res = $dbr->query ( $sql ) ;
1247 if($dbr->numRows($res) > 0) {
1248 while ( $x = $dbr->fetchObject ( $res ) ) $data[] = $x ;
1249 $dbr->freeResult ( $res ) ;
1256 # will get the parents and grand-parents
1257 # TODO : not sure what's happening when a loop happen like:
1258 # Encyclopedia > Astronomy > Encyclopedia
1259 function getAllParentCategories(&$stack) {
1260 global $wgUser,$wgLang;
1264 $parents = $this->getParentCategories( );
1268 # The current element has no more parent so we dump the stack
1269 # and make a clean line of categories
1270 $sk =& $wgUser->getSkin() ;
1272 foreach ( array_reverse($stack) as $child => $parent )
1274 # make a link of that parent
1275 $result .= $sk->makeLink($wgLang->getNSText ( Namespace::getCategory() ).":".$parent,$parent);
1276 $result .= ' > ';
1277 $lastchild = $child;
1279 # append the last child.
1280 # TODO : We should have a last child unless there is an error in the
1281 # "categorylinks" table.
1282 if(isset($lastchild)) { $result .= $lastchild; }
1284 $result .= "<br/>\n";
1286 # now we can empty the stack
1290 # look at parents of current category
1291 foreach($parents as $parent)
1293 # create a title object for the parent
1294 $tpar = Title
::newFromID($parent->cur_id
);
1295 # add it to the stack
1296 $stack[$this->getText()] = $tpar->getText();
1298 $result .= $tpar->getAllParentCategories($stack);
1302 if(isset($result)) { return $result; }
1303 else { return ''; };
1306 # Returns an associative array for selecting this title from cur
1307 function curCond() {
1308 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1311 function oldCond() {
1312 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);