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 # All member variables should be considered private
13 # Please use the accessor functions
15 var $mTextform; # Text form (spaces not underscores) of the main part
16 var $mUrlform; # URL-encoded form of the main part
17 var $mDbkeyform; # Main part with underscores
18 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
19 var $mInterwiki; # Interwiki prefix (or null string)
20 var $mFragment; # Title fragment (i.e. the bit after the #)
21 var $mArticleID; # Article ID, fetched from the link cache on demand
22 var $mRestrictions; # Array of groups allowed to edit this article
23 # Only null or "sysop" are supported
24 var $mRestrictionsLoaded; # Boolean for initialisation on demand
25 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
26 var $mDefaultNamespace; # Namespace index when there is no namespace
27 # Zero except in {{transclusion}} tags
29 #----------------------------------------------------------------------------
31 #----------------------------------------------------------------------------
33 /* private */ function Title() {
34 $this->mInterwiki
= $this->mUrlform
=
35 $this->mTextform
= $this->mDbkeyform
= '';
36 $this->mArticleID
= -1;
37 $this->mNamespace
= 0;
38 $this->mRestrictionsLoaded
= false;
39 $this->mRestrictions
= array();
40 $this->mDefaultNamespace
= 0;
43 # From a prefixed DB key
44 /* static */ function newFromDBkey( $key ) {
46 $t->mDbkeyform
= $key;
47 if( $t->secureAndSplit() )
53 # From text, such as what you would find in a link
54 /* static */ function newFromText( $text, $defaultNamespace = 0 ) {
55 $fname = 'Title::newFromText';
56 wfProfileIn( $fname );
58 if( is_object( $text ) ) {
59 wfDebugDieBacktrace( 'Called with object instead of string.' );
61 global $wgInputEncoding;
62 $text = do_html_entity_decode( $text, ENT_COMPAT
, $wgInputEncoding );
64 $text = wfMungeToUtf8( $text );
67 # What was this for? TS 2004-03-03
68 # $text = urldecode( $text );
71 $t->mDbkeyform
= str_replace( ' ', '_', $text );
72 $t->mDefaultNamespace
= $defaultNamespace;
74 wfProfileOut( $fname );
75 if ( !is_object( $t ) ) {
76 var_dump( debug_backtrace() );
78 if( $t->secureAndSplit() ) {
85 # From a URL-encoded title
86 /* static */ function newFromURL( $url ) {
87 global $wgLang, $wgServer;
90 # For compatibility with old buggy URLs. "+" is not valid in titles,
91 # but some URLs used it as a space replacement and they still come
92 # from some external search tools.
93 $s = str_replace( '+', ' ', $url );
95 # For links that came from outside, check for alternate/legacy
97 wfDebug( "Servr: $wgServer\n" );
98 if( empty( $_SERVER['HTTP_REFERER'] ) ||
99 strncmp($wgServer, $_SERVER['HTTP_REFERER'], strlen( $wgServer ) ) )
101 $s = $wgLang->checkTitleEncoding( $s );
103 wfDebug( "Refer: {$_SERVER['HTTP_REFERER']}\n" );
106 $t->mDbkeyform
= str_replace( ' ', '_', $s );
107 if( $t->secureAndSplit() ) {
108 # check that length of title is < cur_title size
109 $dbr =& wfGetDB( DB_SLAVE
);
110 $maxSize = $dbr->textFieldSize( 'cur', 'cur_title' );
111 if ( $maxSize != -1 && strlen( $t->mDbkeyform
) > $maxSize ) {
122 # This is inefficiently implemented, the cur row is requested but not
123 # used for anything else
124 /* static */ function newFromID( $id ) {
125 $fname = 'Title::newFromID';
126 $dbr =& wfGetDB( DB_SLAVE
);
127 $row = $dbr->getArray( 'cur', array( 'cur_namespace', 'cur_title' ),
128 array( 'cur_id' => $id ), $fname );
129 if ( $row !== false ) {
130 $title = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
137 # From a namespace index and a DB key
138 /* static */ function makeTitle( $ns, $title ) {
140 $t->mDbkeyform
= Title
::makeName( $ns, $title );
141 if( $t->secureAndSplit() ) {
148 /* static */ function newMainPage() {
149 return Title
::newFromText( wfMsg( 'mainpage' ) );
152 # Get the title object for a redirect
153 # Returns NULL if the text is not a valid redirect
154 /* static */ function newFromRedirect( $text ) {
157 if ( $wgMwRedir->matchStart( $text ) ) {
158 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/', $text, $m ) ) {
159 $rt = Title
::newFromText( $m[1] );
165 #----------------------------------------------------------------------------
167 #----------------------------------------------------------------------------
169 # Get the prefixed DB key associated with an ID
170 /* static */ function nameOf( $id ) {
171 $fname = 'Title::nameOf';
172 $dbr =& wfGetDB( DB_SLAVE
);
174 $s = $dbr->getArray( 'cur', array( 'cur_namespace','cur_title' ), array( 'cur_id' => $id ), $fname );
175 if ( $s === false ) { return NULL; }
177 $n = Title
::makeName( $s->cur_namespace
, $s->cur_title
);
181 # Get a regex character class describing the legal characters in a link
182 /* static */ function legalChars() {
183 # Missing characters:
184 # * []|# Needed for link syntax
185 # * % and + are corrupted by Apache when they appear in the path
187 # % seems to work though
189 # The problem with % is that URLs are double-unescaped: once by Apache's
190 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
191 # Our code does not double-escape to compensate for this, indeed double escaping
192 # would break if the double-escaped title was passed in the query string
193 # rather than the path. This is a minor security issue because articles can be
194 # created such that they are hard to view or edit. -- TS
196 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
197 # this breaks interlanguage links
199 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z{}~\\x80-\\xFF";
203 # Returns a stripped-down a title string ready for the search index
204 # Takes a namespace index and a text-form main part
205 /* static */ function indexTitle( $ns, $title ) {
206 global $wgDBminWordLen, $wgLang;
208 $lc = SearchEngine
::legalSearchChars() . '&#;';
209 $t = $wgLang->stripForSearch( $title );
210 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
211 $t = strtolower( $t );
214 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
215 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
217 $t = preg_replace( "/\\s+/", ' ', $t );
219 if ( $ns == Namespace::getImage() ) {
220 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
225 # Make a prefixed DB key from a DB key and a namespace index
226 /* static */ function makeName( $ns, $title ) {
229 $n = $wgLang->getNsText( $ns );
230 if ( "" == $n ) { return $title; }
231 else { return "{$n}:{$title}"; }
235 # Returns the URL associated with an interwiki prefix
236 # The URL contains $1, which is replaced by the title
237 function getInterwikiLink( $key ) {
238 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
239 $fname = 'Title::getInterwikiLink';
240 $k = $wgDBname.':interwiki:'.$key;
242 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
243 return $wgTitleInterwikiCache[$k]->iw_url
;
245 $s = $wgMemc->get( $k );
246 # Ignore old keys with no iw_local
247 if( $s && isset( $s->iw_local
) ) {
248 $wgTitleInterwikiCache[$k] = $s;
251 $dbr =& wfGetDB( DB_SLAVE
);
252 $res = $dbr->select( 'interwiki', array( 'iw_url', 'iw_local' ), array( 'iw_prefix' => $key ), $fname );
255 $s = $dbr->fetchObject( $res );
257 # Cache non-existence: create a blank object and save it to memcached
262 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
263 $wgTitleInterwikiCache[$k] = $s;
268 global $wgTitleInterwikiCache, $wgDBname;
270 if ( $this->mInterwiki
!= '' ) {
271 # Make sure key is loaded into cache
272 $this->getInterwikiLink( $this->mInterwiki
);
273 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
274 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
280 # Update the cur_touched field for an array of title objects
281 # Inefficient unless the IDs are already loaded into the link cache
282 /* static */ function touchArray( $titles, $timestamp = '' ) {
283 if ( count( $titles ) == 0 ) {
286 if ( $timestamp == '' ) {
287 $timestamp = wfTimestampNow();
289 $dbw =& wfGetDB( DB_MASTER
);
290 $cur = $dbw->tableName( 'cur' );
291 $sql = "UPDATE $cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
294 foreach ( $titles as $title ) {
299 $sql .= $title->getArticleID();
303 $dbw->query( $sql, 'Title::touchArray' );
307 #----------------------------------------------------------------------------
309 #----------------------------------------------------------------------------
312 # See the definitions at the top of this file
314 function getText() { return $this->mTextform
; }
315 function getPartialURL() { return $this->mUrlform
; }
316 function getDBkey() { return $this->mDbkeyform
; }
317 function getNamespace() { return $this->mNamespace
; }
318 function setNamespace( $n ) { $this->mNamespace
= $n; }
319 function getInterwiki() { return $this->mInterwiki
; }
320 function getFragment() { return $this->mFragment
; }
321 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
323 # Get title for search index
324 function getIndexTitle() {
325 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
328 # Get prefixed title with underscores
329 function getPrefixedDBkey() {
330 $s = $this->prefix( $this->mDbkeyform
);
331 $s = str_replace( ' ', '_', $s );
335 # Get prefixed title with spaces
336 # This is the form usually used for display
337 function getPrefixedText() {
338 if ( empty( $this->mPrefixedText
) ) {
339 $s = $this->prefix( $this->mTextform
);
340 $s = str_replace( '_', ' ', $s );
341 $this->mPrefixedText
= $s;
343 return $this->mPrefixedText
;
346 # As getPrefixedText(), plus fragment.
347 function getFullText() {
348 $text = $this->getPrefixedText();
349 if( '' != $this->mFragment
) {
350 $text .= '#' . $this->mFragment
;
355 # Get a URL-encoded title (not an actual URL) including interwiki
356 function getPrefixedURL() {
357 $s = $this->prefix( $this->mDbkeyform
);
358 $s = str_replace( ' ', '_', $s );
360 $s = wfUrlencode ( $s ) ;
362 # Cleaning up URL to make it look nice -- is this safe?
363 $s = preg_replace( '/%3[Aa]/', ':', $s );
364 $s = preg_replace( '/%2[Ff]/', '/', $s );
365 $s = str_replace( '%28', '(', $s );
366 $s = str_replace( '%29', ')', $s );
371 # Get a real URL referring to this title, with interwiki link and fragment
372 function getFullURL( $query = '' ) {
373 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
375 if ( '' == $this->mInterwiki
) {
377 return $wgServer . $this->getLocalUrl( $query );
379 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
380 $namespace = $wgLang->getNsText( $this->mNamespace
);
381 if ( '' != $namespace ) {
382 # Can this actually happen? Interwikis shouldn't be parsed.
385 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
386 if ( '' != $this->mFragment
) {
387 $url .= '#' . $this->mFragment
;
393 # Get a URL with an optional query string, no fragment
394 # * If $query=="", it will use $wgArticlePath
395 # * Returns a full for an interwiki link, loses any query string
396 # * Optionally adds the server and escapes for HTML
397 # * Setting $query to "-" makes an old-style URL with nothing in the
398 # query except a title
401 die( 'Call to obsolete obsolete function Title::getURL()' );
404 function getLocalURL( $query = '' ) {
405 global $wgLang, $wgArticlePath, $wgScript;
407 if ( $this->isExternal() ) {
408 return $this->getFullURL();
411 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
412 if ( $query == '' ) {
413 $url = str_replace( '$1', $dbkey, $wgArticlePath );
415 if ( $query == '-' ) {
418 if ( $wgScript != '' ) {
419 $url = "{$wgScript}?title={$dbkey}&{$query}";
422 $url = "/{$dbkey}?{$query}";
428 function escapeLocalURL( $query = '' ) {
429 return htmlspecialchars( $this->getLocalURL( $query ) );
432 function escapeFullURL( $query = '' ) {
433 return htmlspecialchars( $this->getFullURL( $query ) );
436 function getInternalURL( $query = '' ) {
437 # Used in various Squid-related code, in case we have a different
438 # internal hostname for the server than the exposed one.
439 global $wgInternalServer;
440 return $wgInternalServer . $this->getLocalURL( $query );
443 # Get the edit URL, or a null string if it is an interwiki link
444 function getEditURL() {
445 global $wgServer, $wgScript;
447 if ( '' != $this->mInterwiki
) { return ''; }
448 $s = $this->getLocalURL( 'action=edit' );
453 # Get HTML-escaped displayable text
454 # For the title field in <a> tags
455 function getEscapedText() {
456 return htmlspecialchars( $this->getPrefixedText() );
459 # Is the title interwiki?
460 function isExternal() { return ( '' != $this->mInterwiki
); }
462 # Does the title correspond to a protected article?
463 function isProtected() {
464 if ( -1 == $this->mNamespace
) { return true; }
465 $a = $this->getRestrictions();
466 if ( in_array( 'sysop', $a ) ) { return true; }
470 # Is the page a log page, i.e. one where the history is messed up by
471 # LogPage.php? This used to be used for suppressing diff links in recent
472 # changes, but now that's done by setting a flag in the recentchanges
473 # table. Hence, this probably is no longer used.
475 if ( $this->mNamespace
!= Namespace::getWikipedia() ) {
478 if ( ( 0 == strcmp( wfMsg( 'uploadlogpage' ), $this->mDbkeyform
) ) ||
479 ( 0 == strcmp( wfMsg( 'dellogpage' ), $this->mDbkeyform
) ) ) {
485 # Is $wgUser is watching this page?
486 function userIsWatching() {
489 if ( -1 == $this->mNamespace
) { return false; }
490 if ( 0 == $wgUser->getID() ) { return false; }
492 return $wgUser->isWatched( $this );
495 # Can $wgUser edit this page?
496 function userCanEdit() {
498 if ( -1 == $this->mNamespace
) { return false; }
499 if ( NS_MEDIAWIKI
== $this->mNamespace
&& !$wgUser->isSysop() ) { return false; }
500 # if ( 0 == $this->getArticleID() ) { return false; }
501 if ( $this->mDbkeyform
== '_' ) { return false; }
502 # protect global styles and js
503 if ( NS_MEDIAWIKI
== $this->mNamespace
504 && preg_match("/\\.(css|js)$/", $this->mTextform
)
505 && !$wgUser->isSysop() )
507 //if ( $this->isCssJsSubpage() and !$this->userCanEditCssJsSubpage() ) { return false; }
508 # protect css/js subpages of user pages
509 # XXX: this might be better using restrictions
510 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
511 if( Namespace::getUser() == $this->mNamespace
512 and preg_match("/\\.(css|js)$/", $this->mTextform
)
513 and !$wgUser->isSysop()
514 and !preg_match('/^'.preg_quote($wgUser->getName(), '/').'/', $this->mTextform
) )
516 $ur = $wgUser->getRights();
517 foreach ( $this->getRestrictions() as $r ) {
518 if ( '' != $r && ( ! in_array( $r, $ur ) ) ) {
525 function userCanRead() {
527 global $wgWhitelistRead;
529 if( 0 != $wgUser->getID() ) return true;
530 if( !is_array( $wgWhitelistRead ) ) return true;
532 $name = $this->getPrefixedText();
533 if( in_array( $name, $wgWhitelistRead ) ) return true;
535 # Compatibility with old settings
536 if( $this->getNamespace() == NS_MAIN
) {
537 if( in_array( ":" . $name, $wgWhitelistRead ) ) return true;
542 function isCssJsSubpage() {
543 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
545 function isCssSubpage() {
546 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
548 function isJsSubpage() {
549 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
551 function userCanEditCssJsSubpage() {
552 # protect css/js subpages of user pages
553 # XXX: this might be better using restrictions
555 return ( $wgUser->isSysop() or preg_match('/^'.preg_quote($wgUser->getName()).'/', $this->mTextform
) );
558 # Accessor/initialisation for mRestrictions
559 function getRestrictions() {
560 $id = $this->getArticleID();
561 if ( 0 == $id ) { return array(); }
563 if ( ! $this->mRestrictionsLoaded
) {
564 $dbr =& wfGetDB( DB_SLAVE
);
565 $res = $dbr->getField( 'cur', 'cur_restrictions', 'cur_id='.$id );
566 $this->mRestrictions
= explode( ',', trim( $res ) );
567 $this->mRestrictionsLoaded
= true;
569 return $this->mRestrictions
;
572 # Is there a version of this page in the deletion archive?
573 # Returns the number of archived revisions
574 function isDeleted() {
575 $fname = 'Title::isDeleted';
576 $dbr =& wfGetDB( DB_SLAVE
);
577 $n = $dbr->getField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
578 'ar_title' => $this->getDBkey() ), $fname );
582 # Get the article ID from the link cache
583 # Used very heavily, e.g. in Parser::replaceInternalLinks()
584 function getArticleID() {
587 if ( -1 != $this->mArticleID
) { return $this->mArticleID
; }
588 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
589 return $this->mArticleID
;
592 # This clears some fields in this object, and clears any associated keys in the
593 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
594 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
595 function resetArticleID( $newid ) {
597 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
599 if ( 0 == $newid ) { $this->mArticleID
= -1; }
600 else { $this->mArticleID
= $newid; }
601 $this->mRestrictionsLoaded
= false;
602 $this->mRestrictions
= array();
605 # Updates cur_touched
606 # Called from LinksUpdate.php
607 function invalidateCache() {
608 $now = wfTimestampNow();
609 $dbw =& wfGetDB( DB_MASTER
);
610 $success = $dbw->updateArray( 'cur',
612 'cur_touched' => wfTimestampNow()
613 ), array( /* WHERE */
614 'cur_namespace' => $this->getNamespace() ,
615 'cur_title' => $this->getDBkey()
616 ), 'Title::invalidateCache'
621 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
622 /* private */ function prefix( $name ) {
626 if ( '' != $this->mInterwiki
) {
627 $p = $this->mInterwiki
. ':';
629 if ( 0 != $this->mNamespace
) {
630 $p .= $wgLang->getNsText( $this->mNamespace
) . ':';
635 # Secure and split - main initialisation function for this object
637 # Assumes that mDbkeyform has been set, and is urldecoded
638 # and uses underscores, but not otherwise munged. This function
639 # removes illegal characters, splits off the interwiki and
640 # namespace prefixes, sets the other forms, and canonicalizes
643 /* private */ function secureAndSplit()
645 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
646 $fname = 'Title::secureAndSplit';
647 wfProfileIn( $fname );
649 static $imgpre = false;
650 static $rxTc = false;
653 if ( $imgpre === false ) {
654 $imgpre = ':' . $wgLang->getNsText( Namespace::getImage() ) . ":";
655 # % is needed as well
656 $rxTc = '/[^' . Title
::legalChars() . ']/';
659 $this->mInterwiki
= $this->mFragment
= '';
660 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
662 # Clean up whitespace
664 $t = preg_replace( "/[\\s_]+/", '_', $this->mDbkeyform
);
665 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
668 wfProfileOut( $fname );
672 $this->mDbkeyform
= $t;
676 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
677 $t = substr( $t, 1 );
680 # Initial colon indicating main namespace
681 if ( ':' == $t{0} ) {
682 $r = substr( $t, 1 );
683 $this->mNamespace
= NS_MAIN
;
685 # Namespace or interwiki prefix
686 if ( preg_match( "/^(.+?)_*:_*(.*)$/", $t, $m ) ) {
687 #$p = strtolower( $m[1] );
689 $lowerNs = strtolower( $p );
690 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
691 # Canonical namespace
693 $this->mNamespace
= $ns;
694 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
697 $this->mNamespace
= $ns;
698 } elseif ( $this->getInterwikiLink( $p ) ) {
701 $this->mInterwiki
= $p;
703 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
705 } elseif($this->mInterwiki
!= $wgLocalInterwiki) {
713 # Redundant interwiki prefix to the local wiki
714 if ( 0 == strcmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
715 $this->mInterwiki
= '';
717 # We already know that some pages won't be in the database!
719 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
720 $this->mArticleID
= 0;
722 $f = strstr( $r, '#' );
723 if ( false !== $f ) {
724 $this->mFragment
= substr( $f, 1 );
725 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
728 # Reject illegal characters.
730 if( preg_match( $rxTc, $r ) ) {
731 wfProfileOut( $fname );
735 # "." and ".." conflict with the directories of those namesa
736 if ( strpos( $r, '.' ) !== false &&
737 ( $r === '.' ||
$r === '..' ||
738 strpos( $r, './' ) === 0 ||
739 strpos( $r, '../' ) === 0 ||
740 strpos( $r, '/./' ) !== false ||
741 strpos( $r, '/../' ) !== false ) )
743 wfProfileOut( $fname );
747 # Initial capital letter
748 if( $wgCapitalLinks && $this->mInterwiki
== '') {
749 $t = $wgLang->ucfirst( $r );
755 $this->mDbkeyform
= $t;
756 $this->mUrlform
= wfUrlencode( $t );
758 $this->mTextform
= str_replace( '_', ' ', $t );
760 wfProfileOut( $fname );
764 # Get a title object associated with the talk page of this article
765 function getTalkPage() {
766 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
769 # Get a title object associated with the subject page of this talk page
770 function getSubjectPage() {
771 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
774 # Get an array of Title objects linking to this title
775 # Also stores the IDs in the link cache
776 # $options may be FOR UPDATE
777 function getLinksTo( $options = '' ) {
779 $id = $this->getArticleID();
782 $db =& wfGetDB( DB_MASTER
);
784 $db =& wfGetDB( DB_SLAVE
);
786 $cur = $db->tableName( 'cur' );
787 $links = $db->tableName( 'links' );
789 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
790 $res = $db->query( $sql, "Title::getLinksTo" );
792 if ( $db->numRows( $res ) ) {
793 while ( $row = $db->fetchObject( $res ) ) {
794 if ( $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
) ) {
795 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
796 $retVal[] = $titleObj;
800 $db->freeResult( $res );
804 # Get an array of Title objects linking to this non-existent title
805 # Also stores the IDs in the link cache
806 function getBrokenLinksTo( $options = '' ) {
810 $db =& wfGetDB( DB_MASTER
);
812 $db =& wfGetDB( DB_SLAVE
);
814 $cur = $db->tableName( 'cur' );
815 $brokenlinks = $db->tableName( 'brokenlinks' );
816 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
818 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
819 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
820 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
822 if ( $db->numRows( $res ) ) {
823 while ( $row = $db->fetchObject( $res ) ) {
824 $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
825 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
826 $retVal[] = $titleObj;
829 $db->freeResult( $res );
833 function getSquidURLs() {
835 $this->getInternalURL(),
836 $this->getInternalURL( 'action=history' )
840 function moveNoAuth( &$nt ) {
841 return $this->moveTo( $nt, false );
844 # Move a title to a new location
845 # Returns true on success, message name on failure
846 # auth indicates whether wgUser's permissions should be checked
847 function moveTo( &$nt, $auth = true ) {
848 if( !$this or !$nt ) {
849 return 'badtitletext';
852 $fname = 'Title::move';
853 $oldid = $this->getArticleID();
854 $newid = $nt->getArticleID();
856 if ( strlen( $nt->getDBkey() ) < 1 ) {
857 return 'articleexists';
859 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
860 ( '' == $this->getDBkey() ) ||
861 ( '' != $this->getInterwiki() ) ||
863 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
864 ( '' == $nt->getDBkey() ) ||
865 ( '' != $nt->getInterwiki() ) ) {
866 return 'badarticleerror';
869 if ( $auth && ( !$this->userCanEdit() ||
!$nt->userCanEdit() ) ) {
870 return 'protectedpage';
873 # The move is allowed only if (1) the target doesn't exist, or
874 # (2) the target is a redirect to the source, and has no history
875 # (so we can undo bad moves right after they're done).
877 if ( 0 != $newid ) { # Target exists; check for validity
878 if ( ! $this->isValidMoveTarget( $nt ) ) {
879 return 'articleexists';
881 $this->moveOverExistingRedirect( $nt );
882 } else { # Target didn't exist, do normal move.
883 $this->moveToNewTitle( $nt, $newid );
886 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
888 $dbw =& wfGetDB( DB_MASTER
);
889 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
890 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
891 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
892 $dbw->query( $sql, "SpecialMovepage::doSubmit" );
896 $oldnamespace = $this->getNamespace() & ~
1;
897 $newnamespace = $nt->getNamespace() & ~
1;
898 $oldtitle = $this->getDBkey();
899 $newtitle = $nt->getDBkey();
901 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
902 WatchedItem
::duplicateEntries( $this, $nt );
905 # Update search engine
906 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
908 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), "" );
914 # Move page to title which is presently a redirect to the source page
916 /* private */ function moveOverExistingRedirect( &$nt ) {
917 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
918 $fname = 'Title::moveOverExistingRedirect';
919 $comment = wfMsg( "1movedto2", $this->getPrefixedText(), $nt->getPrefixedText() );
921 $now = wfTimestampNow();
922 $won = wfInvertTimestamp( $now );
923 $newid = $nt->getArticleID();
924 $oldid = $this->getArticleID();
925 $dbw =& wfGetDB( DB_MASTER
);
926 $links = $dbw->tableName( 'links' );
928 # Change the name of the target page:
929 $dbw->updateArray( 'cur',
931 'cur_touched' => $now,
932 'cur_namespace' => $nt->getNamespace(),
933 'cur_title' => $nt->getDBkey()
935 /* WHERE */ array( 'cur_id' => $oldid ),
938 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
940 # Repurpose the old redirect. We don't save it to history since
941 # by definition if we've got here it's rather uninteresting.
943 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
944 $dbw->updateArray( 'cur',
946 'cur_touched' => $now,
947 'cur_timestamp' => $now,
948 'inverse_timestamp' => $won,
949 'cur_namespace' => $this->getNamespace(),
950 'cur_title' => $this->getDBkey(),
951 'cur_text' => $wgMwRedir->getSynonym( 0 ) . " [[" . $nt->getPrefixedText() . "]]\n",
952 'cur_comment' => $comment,
953 'cur_user' => $wgUser->getID(),
954 'cur_minor_edit' => 0,
956 'cur_restrictions' => '',
957 'cur_user_text' => $wgUser->getName(),
958 'cur_is_redirect' => 1,
961 /* WHERE */ array( 'cur_id' => $newid ),
965 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
967 # Fix the redundant names for the past revisions of the target page.
968 # The redirect should have no old revisions.
972 'old_namespace' => $nt->getNamespace(),
973 'old_title' => $nt->getDBkey(),
976 'old_namespace' => $this->getNamespace(),
977 'old_title' => $this->getDBkey(),
982 RecentChange
::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
986 # Load titles and IDs
987 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
988 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
991 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
992 $dbw->query( $sql, $fname );
995 if ( count( $linksToOld ) ||
count( $linksToNew )) {
996 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
999 # Insert links to old title
1000 foreach ( $linksToOld as $linkTitle ) {
1006 $id = $linkTitle->getArticleID();
1007 $sql .= "($id,$newid)";
1010 # Insert links to new title
1011 foreach ( $linksToNew as $linkTitle ) {
1017 $id = $linkTitle->getArticleID();
1018 $sql .= "($id, $oldid)";
1021 $dbw->query( $sql, DB_MASTER
, $fname );
1024 # Now, we record the link from the redirect to the new title.
1025 # It should have no other outgoing links...
1026 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1027 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1030 LinkCache
::linksccClearLinksTo( $oldid );
1031 LinkCache
::linksccClearLinksTo( $newid );
1034 if ( $wgUseSquid ) {
1035 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1036 $u = new SquidUpdate( $urls );
1041 # Move page to non-existing title.
1042 # Sets $newid to be the new article ID
1044 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1045 global $wgUser, $wgLinkCache, $wgUseSquid;
1046 $fname = 'MovePageForm::moveToNewTitle';
1047 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1049 $now = wfTimestampNow();
1050 $won = wfInvertTimestamp( $now );
1051 $newid = $nt->getArticleID();
1052 $oldid = $this->getArticleID();
1053 $dbw =& wfGetDB( DB_MASTER
);
1056 $dbw->updateArray( 'cur',
1058 'cur_touched' => $now,
1059 'cur_namespace' => $nt->getNamespace(),
1060 'cur_title' => $nt->getDBkey()
1062 /* WHERE */ array( 'cur_id' => $oldid ),
1066 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1069 $dbw->insertArray( 'cur', array(
1070 'cur_namespace' => $this->getNamespace(),
1071 'cur_title' => $this->getDBkey(),
1072 'cur_comment' => $comment,
1073 'cur_user' => $wgUser->getID(),
1074 'cur_user_text' => $wgUser->getName(),
1075 'cur_timestamp' => $now,
1076 'inverse_timestamp' => $won,
1077 'cur_touched' => $now,
1078 'cur_is_redirect' => 1,
1080 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1082 $newid = $dbw->insertId();
1083 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1085 # Rename old entries
1089 'old_namespace' => $nt->getNamespace(),
1090 'old_title' => $nt->getDBkey()
1093 'old_namespace' => $this->getNamespace(),
1094 'old_title' => $this->getDBkey()
1099 RecentChange
::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1101 # Purge squid and linkscc as per article creation
1102 Article
::onArticleCreate( $nt );
1104 # Any text links to the old title must be reassigned to the redirect
1105 $dbw->updateArray( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1106 LinkCache
::linksccClearLinksTo( $oldid );
1108 # Record the just-created redirect's linking to the page
1109 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1111 # Non-existent target may have had broken links to it; these must
1112 # now be removed and made into good links.
1113 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1114 $update->fixBrokenLinks();
1116 # Purge old title from squid
1117 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1118 $titles = $nt->getLinksTo();
1119 if ( $wgUseSquid ) {
1120 $urls = $this->getSquidURLs();
1121 foreach ( $titles as $linkTitle ) {
1122 $urls[] = $linkTitle->getInternalURL();
1124 $u = new SquidUpdate( $urls );
1129 # Checks if $this can be moved to $nt
1130 # Selects for update, so don't call it unless you mean business
1131 function isValidMoveTarget( $nt ) {
1132 $fname = 'Title::isValidMoveTarget';
1133 $dbw =& wfGetDB( DB_MASTER
);
1136 $id = $nt->getArticleID();
1137 $obj = $dbw->getArray( 'cur', array( 'cur_is_redirect','cur_text' ),
1138 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1140 if ( !$obj ||
0 == $obj->cur_is_redirect
) {
1145 # Does the redirect point to the source?
1146 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text
, $m ) ) {
1147 $redirTitle = Title
::newFromText( $m[1] );
1148 if( !is_object( $redirTitle ) ||
1149 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1154 # Does the article have a history?
1155 $row = $dbw->getArray( 'old', array( 'old_id' ),
1157 'old_namespace' => $nt->getNamespace(),
1158 'old_title' => $nt->getDBkey()
1159 ), $fname, 'FOR UPDATE'
1162 # Return true if there was no history
1163 return $row === false;
1166 # Create a redirect, fails if the title already exists, does not notify RC
1168 function createRedirect( $dest, $comment ) {
1170 if ( $this->getArticleID() ) {
1174 $fname = "Title::createRedirect";
1175 $dbw =& wfGetDB( DB_MASTER
);
1176 $now = wfTimestampNow();
1177 $won = wfInvertTimestamp( $now );
1178 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1180 $dbw->insertArray( 'cur', array(
1181 'cur_id' => $seqVal,
1182 'cur_namespace' => $this->getNamespace(),
1183 'cur_title' => $this->getDBkey(),
1184 'cur_comment' => $comment,
1185 'cur_user' => $wgUser->getID(),
1186 'cur_user_text' => $wgUser->getName(),
1187 'cur_timestamp' => $now,
1188 'inverse_timestamp' => $won,
1189 'cur_touched' => $now,
1190 'cur_is_redirect' => 1,
1192 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1194 $newid = $dbw->insertId();
1195 $this->resetArticleID( $newid );
1198 if ( $dest->getArticleID() ) {
1199 $dbw->insertArray( 'links',
1201 'l_to' => $dest->getArticleID(),
1206 $dbw->insertArray( 'brokenlinks',
1208 'bl_to' => $dest->getPrefixedDBkey(),
1214 Article
::onArticleCreate( $this );
1218 # Get categories to wich belong this title and return an array of
1220 function getParentCategories( ) {
1221 global $wgLang,$wgUser;
1223 $titlekey = $this->getArticleId();
1224 $cns = Namespace::getCategory();
1225 $sk =& $wgUser->getSkin();
1227 $dbr =& wfGetDB( DB_SLAVE
);
1228 $cur = $dbr->tableName( 'cur' );
1229 $categorylinks = $dbr->tableName( 'categorylinks' );
1231 # get the parents categories of this title from the database
1232 $sql = "SELECT DISTINCT cur_id FROM $cur,$categorylinks
1233 WHERE cl_from='$titlekey' AND cl_to=cur_title AND cur_namespace='$cns'
1234 ORDER BY cl_sortkey" ;
1235 $res = $dbr->query ( $sql ) ;
1237 if($dbr->numRows($res) > 0) {
1238 while ( $x = $dbr->fetchObject ( $res ) ) $data[] = $x ;
1239 $dbr->freeResult ( $res ) ;
1246 # will get the parents and grand-parents
1247 # TODO : not sure what's happening when a loop happen like:
1248 # Encyclopedia > Astronomy > Encyclopedia
1249 function getAllParentCategories(&$stack) {
1250 global $wgUser,$wgLang;
1254 $parents = $this->getParentCategories( );
1258 # The current element has no more parent so we dump the stack
1259 # and make a clean line of categories
1260 $sk =& $wgUser->getSkin() ;
1262 foreach ( array_reverse($stack) as $child => $parent )
1264 # make a link of that parent
1265 $result .= $sk->makeLink($wgLang->getNSText ( Namespace::getCategory() ).":".$parent,$parent);
1266 $result .= ' > ';
1267 $lastchild = $child;
1269 # append the last child.
1270 # TODO : We should have a last child unless there is an error in the
1271 # "categorylinks" table.
1272 if(isset($lastchild)) { $result .= $lastchild; }
1274 $result .= "<br/>\n";
1276 # now we can empty the stack
1280 # look at parents of current category
1281 foreach($parents as $parent)
1283 # create a title object for the parent
1284 $tpar = Title
::newFromID($parent->cur_id
);
1285 # add it to the stack
1286 $stack[$this->getText()] = $tpar->getText();
1288 $result .= $tpar->getAllParentCategories($stack);
1292 if(isset($result)) { return $result; }
1293 else { return ''; };
1296 # Returns an associative array for selecting this title from cur
1297 function curCond() {
1298 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1301 function oldCond() {
1302 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);