10 require_once( 'normal/UtfNormal.php' );
15 $wgTitleInterwikiCache = array();
16 define ( 'GAID_FOR_UPDATE', 1 );
20 * - Represents a title, which may contain an interwiki designation or namespace
21 * - Can fetch various kinds of data from the database, albeit inefficiently.
23 * @todo migrate comments to phpdoc format
27 # All member variables should be considered private
28 # Please use the accessor functions
30 var $mTextform; # Text form (spaces not underscores) of the main part
31 var $mUrlform; # URL-encoded form of the main part
32 var $mDbkeyform; # Main part with underscores
33 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
34 var $mInterwiki; # Interwiki prefix (or null string)
35 var $mFragment; # Title fragment (i.e. the bit after the #)
36 var $mArticleID; # Article ID, fetched from the link cache on demand
37 var $mRestrictions; # Array of groups allowed to edit this article
38 # Only null or "sysop" are supported
39 var $mRestrictionsLoaded; # Boolean for initialisation on demand
40 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
41 var $mDefaultNamespace; # Namespace index when there is no namespace
42 # Zero except in {{transclusion}} tags
44 #----------------------------------------------------------------------------
46 #----------------------------------------------------------------------------
48 /* private */ function Title() {
49 $this->mInterwiki
= $this->mUrlform
=
50 $this->mTextform
= $this->mDbkeyform
= '';
51 $this->mArticleID
= -1;
52 $this->mNamespace
= 0;
53 $this->mRestrictionsLoaded
= false;
54 $this->mRestrictions
= array();
55 $this->mDefaultNamespace
= 0;
58 # From a prefixed DB key
59 /* static */ function newFromDBkey( $key ) {
61 $t->mDbkeyform
= $key;
62 if( $t->secureAndSplit() )
68 # From text, such as what you would find in a link
69 /* static */ function newFromText( $text, $defaultNamespace = 0 ) {
70 $fname = 'Title::newFromText';
71 wfProfileIn( $fname );
73 if( is_object( $text ) ) {
74 wfDebugDieBacktrace( 'Called with object instead of string.' );
76 global $wgInputEncoding;
77 $text = do_html_entity_decode( $text, ENT_COMPAT
, $wgInputEncoding );
79 $text = wfMungeToUtf8( $text );
82 # What was this for? TS 2004-03-03
83 # $text = urldecode( $text );
86 $t->mDbkeyform
= str_replace( ' ', '_', $text );
87 $t->mDefaultNamespace
= $defaultNamespace;
89 wfProfileOut( $fname );
90 if ( !is_object( $t ) ) {
91 var_dump( debug_backtrace() );
93 if( $t->secureAndSplit() ) {
100 # From a URL-encoded title
101 /* static */ function newFromURL( $url ) {
102 global $wgLang, $wgServer;
105 # For compatibility with old buggy URLs. "+" is not valid in titles,
106 # but some URLs used it as a space replacement and they still come
107 # from some external search tools.
108 $s = str_replace( '+', ' ', $url );
110 $t->mDbkeyform
= str_replace( ' ', '_', $s );
111 if( $t->secureAndSplit() ) {
112 # check that length of title is < cur_title size
113 $dbr =& wfGetDB( DB_SLAVE
);
114 $maxSize = $dbr->textFieldSize( 'cur', 'cur_title' );
115 if ( $maxSize != -1 && strlen( $t->mDbkeyform
) > $maxSize ) {
126 # This is inefficiently implemented, the cur row is requested but not
127 # used for anything else
128 /* static */ function newFromID( $id ) {
129 $fname = 'Title::newFromID';
130 $dbr =& wfGetDB( DB_SLAVE
);
131 $row = $dbr->getArray( 'cur', array( 'cur_namespace', 'cur_title' ),
132 array( 'cur_id' => $id ), $fname );
133 if ( $row !== false ) {
134 $title = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
141 # From a namespace index and a DB key.
142 # It's assumed that $ns and $title are *valid*, for instance when
143 # they came directly from the database or a special page name.
144 /* static */ function &makeTitle( $ns, $title ) {
148 $t->mNamespace
= $ns;
149 $t->mDbkeyform
= $title;
150 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
151 $t->mUrlform
= wfUrlencode( $title );
152 $t->mTextform
= str_replace( '_', ' ', $title );
156 # From a namespace index and a DB key.
157 # These will be checked for validity, which is a bit slower
158 # than makeTitle() but safer for user-provided data.
159 /* static */ function makeTitleSafe( $ns, $title ) {
161 $t->mDbkeyform
= Title
::makeName( $ns, $title );
162 if( $t->secureAndSplit() ) {
169 /* static */ function newMainPage() {
170 return Title
::newFromText( wfMsg( 'mainpage' ) );
173 # Get the title object for a redirect
174 # Returns NULL if the text is not a valid redirect
175 /* static */ function newFromRedirect( $text ) {
178 if ( $wgMwRedir->matchStart( $text ) ) {
179 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/', $text, $m ) ) {
180 # categories are escaped using : for example one can enter:
181 # #REDIRECT [[:Category:Music]]. Need to remove it.
182 if ( substr($m[1],0,1) == ':') {
183 # We don't want to keep the ':'
184 $m[1] = substr( $m[1], 1 );
187 $rt = Title
::newFromText( $m[1] );
188 # Disallow redirects to Special:Userlogout
189 if ( $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
197 #----------------------------------------------------------------------------
199 #----------------------------------------------------------------------------
201 # Get the prefixed DB key associated with an ID
202 /* static */ function nameOf( $id ) {
203 $fname = 'Title::nameOf';
204 $dbr =& wfGetDB( DB_SLAVE
);
206 $s = $dbr->getArray( 'cur', array( 'cur_namespace','cur_title' ), array( 'cur_id' => $id ), $fname );
207 if ( $s === false ) { return NULL; }
209 $n = Title
::makeName( $s->cur_namespace
, $s->cur_title
);
213 # Get a regex character class describing the legal characters in a link
214 /* static */ function legalChars() {
215 # Missing characters:
216 # * []|# Needed for link syntax
217 # * % and + are corrupted by Apache when they appear in the path
219 # % seems to work though
221 # The problem with % is that URLs are double-unescaped: once by Apache's
222 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
223 # Our code does not double-escape to compensate for this, indeed double escaping
224 # would break if the double-escaped title was passed in the query string
225 # rather than the path. This is a minor security issue because articles can be
226 # created such that they are hard to view or edit. -- TS
228 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
229 # this breaks interlanguage links
231 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z{}~\\x80-\\xFF";
235 # Returns a stripped-down a title string ready for the search index
236 # Takes a namespace index and a text-form main part
237 /* static */ function indexTitle( $ns, $title ) {
238 global $wgDBminWordLen, $wgLang;
239 require_once( 'SearchEngine.php' );
241 $lc = SearchEngine
::legalSearchChars() . '&#;';
242 $t = $wgLang->stripForSearch( $title );
243 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
244 $t = strtolower( $t );
247 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
248 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
250 $t = preg_replace( "/\\s+/", ' ', $t );
252 if ( $ns == Namespace::getImage() ) {
253 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
258 # Make a prefixed DB key from a DB key and a namespace index
259 /* static */ function makeName( $ns, $title ) {
262 $n = $wgLang->getNsText( $ns );
263 if ( '' == $n ) { return $title; }
264 else { return $n.':'.$title; }
268 # Returns the URL associated with an interwiki prefix
269 # The URL contains $1, which is replaced by the title
270 function getInterwikiLink( $key ) {
271 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
272 $fname = 'Title::getInterwikiLink';
273 $k = $wgDBname.':interwiki:'.$key;
275 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
276 return $wgTitleInterwikiCache[$k]->iw_url
;
278 $s = $wgMemc->get( $k );
279 # Ignore old keys with no iw_local
280 if( $s && isset( $s->iw_local
) ) {
281 $wgTitleInterwikiCache[$k] = $s;
284 $dbr =& wfGetDB( DB_SLAVE
);
285 $res = $dbr->select( 'interwiki', array( 'iw_url', 'iw_local' ), array( 'iw_prefix' => $key ), $fname );
288 $s = $dbr->fetchObject( $res );
290 # Cache non-existence: create a blank object and save it to memcached
295 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
296 $wgTitleInterwikiCache[$k] = $s;
301 global $wgTitleInterwikiCache, $wgDBname;
303 if ( $this->mInterwiki
!= '' ) {
304 # Make sure key is loaded into cache
305 $this->getInterwikiLink( $this->mInterwiki
);
306 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
307 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
313 # Update the cur_touched field for an array of title objects
314 # Inefficient unless the IDs are already loaded into the link cache
315 /* static */ function touchArray( $titles, $timestamp = '' ) {
316 if ( count( $titles ) == 0 ) {
319 $dbw =& wfGetDB( DB_MASTER
);
320 if ( $timestamp == '' ) {
321 $timestamp = $dbw->timestamp();
323 $cur = $dbw->tableName( 'cur' );
324 $sql = "UPDATE $cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
327 foreach ( $titles as $title ) {
332 $sql .= $title->getArticleID();
336 $dbw->query( $sql, 'Title::touchArray' );
340 #----------------------------------------------------------------------------
342 #----------------------------------------------------------------------------
345 # See the definitions at the top of this file
347 function getText() { return $this->mTextform
; }
348 function getPartialURL() { return $this->mUrlform
; }
349 function getDBkey() { return $this->mDbkeyform
; }
350 function getNamespace() { return $this->mNamespace
; }
351 function setNamespace( $n ) { $this->mNamespace
= $n; }
352 function getInterwiki() { return $this->mInterwiki
; }
353 function getFragment() { return $this->mFragment
; }
354 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
356 # Get title for search index
357 function getIndexTitle() {
358 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
361 # Get prefixed title with underscores
362 function getPrefixedDBkey() {
363 $s = $this->prefix( $this->mDbkeyform
);
364 $s = str_replace( ' ', '_', $s );
368 # Get prefixed title with spaces
369 # This is the form usually used for display
370 function getPrefixedText() {
371 if ( empty( $this->mPrefixedText
) ) {
372 $s = $this->prefix( $this->mTextform
);
373 $s = str_replace( '_', ' ', $s );
374 $this->mPrefixedText
= $s;
376 return $this->mPrefixedText
;
379 # As getPrefixedText(), plus fragment.
380 function getFullText() {
381 $text = $this->getPrefixedText();
382 if( '' != $this->mFragment
) {
383 $text .= '#' . $this->mFragment
;
388 # Get a URL-encoded title (not an actual URL) including interwiki
389 function getPrefixedURL() {
390 $s = $this->prefix( $this->mDbkeyform
);
391 $s = str_replace( ' ', '_', $s );
393 $s = wfUrlencode ( $s ) ;
395 # Cleaning up URL to make it look nice -- is this safe?
396 $s = preg_replace( '/%3[Aa]/', ':', $s );
397 $s = preg_replace( '/%2[Ff]/', '/', $s );
398 $s = str_replace( '%28', '(', $s );
399 $s = str_replace( '%29', ')', $s );
404 # Get a real URL referring to this title, with interwiki link and fragment
405 function getFullURL( $query = '' ) {
406 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
408 if ( '' == $this->mInterwiki
) {
410 return $wgServer . $this->getLocalUrl( $query );
412 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
413 $namespace = $wgLang->getNsText( $this->mNamespace
);
414 if ( '' != $namespace ) {
415 # Can this actually happen? Interwikis shouldn't be parsed.
418 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
419 if ( '' != $this->mFragment
) {
420 $url .= '#' . $this->mFragment
;
426 # Get a URL with an optional query string, no fragment
427 # * If $query=="", it will use $wgArticlePath
428 # * Returns a full for an interwiki link, loses any query string
429 # * Optionally adds the server and escapes for HTML
430 # * Setting $query to "-" makes an old-style URL with nothing in the
431 # query except a title
434 die( 'Call to obsolete obsolete function Title::getURL()' );
437 function getLocalURL( $query = '' ) {
438 global $wgLang, $wgArticlePath, $wgScript;
440 if ( $this->isExternal() ) {
441 return $this->getFullURL();
444 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
445 if ( $query == '' ) {
446 $url = str_replace( '$1', $dbkey, $wgArticlePath );
448 if ( $query == '-' ) {
451 if ( $wgScript != '' ) {
452 $url = "{$wgScript}?title={$dbkey}&{$query}";
455 $url = "/{$dbkey}?{$query}";
461 function escapeLocalURL( $query = '' ) {
462 return htmlspecialchars( $this->getLocalURL( $query ) );
465 function escapeFullURL( $query = '' ) {
466 return htmlspecialchars( $this->getFullURL( $query ) );
469 function getInternalURL( $query = '' ) {
470 # Used in various Squid-related code, in case we have a different
471 # internal hostname for the server than the exposed one.
472 global $wgInternalServer;
473 return $wgInternalServer . $this->getLocalURL( $query );
476 # Get the edit URL, or a null string if it is an interwiki link
477 function getEditURL() {
478 global $wgServer, $wgScript;
480 if ( '' != $this->mInterwiki
) { return ''; }
481 $s = $this->getLocalURL( 'action=edit' );
486 # Get HTML-escaped displayable text
487 # For the title field in <a> tags
488 function getEscapedText() {
489 return htmlspecialchars( $this->getPrefixedText() );
492 # Is the title interwiki?
493 function isExternal() { return ( '' != $this->mInterwiki
); }
495 # Does the title correspond to a protected article?
496 function isProtected() {
497 if ( -1 == $this->mNamespace
) { return true; }
498 $a = $this->getRestrictions();
499 if ( in_array( 'sysop', $a ) ) { return true; }
503 # Is the page a log page, i.e. one where the history is messed up by
504 # LogPage.php? This used to be used for suppressing diff links in recent
505 # changes, but now that's done by setting a flag in the recentchanges
506 # table. Hence, this probably is no longer used.
508 if ( $this->mNamespace
!= Namespace::getWikipedia() ) {
511 if ( ( 0 == strcmp( wfMsg( 'uploadlogpage' ), $this->mDbkeyform
) ) ||
512 ( 0 == strcmp( wfMsg( 'dellogpage' ), $this->mDbkeyform
) ) ) {
518 # Is $wgUser is watching this page?
519 function userIsWatching() {
522 if ( -1 == $this->mNamespace
) { return false; }
523 if ( 0 == $wgUser->getID() ) { return false; }
525 return $wgUser->isWatched( $this );
528 # Can $wgUser edit this page?
529 function userCanEdit() {
531 if ( -1 == $this->mNamespace
) { return false; }
532 if ( NS_MEDIAWIKI
== $this->mNamespace
&& !$wgUser->isSysop() ) { return false; }
533 # if ( 0 == $this->getArticleID() ) { return false; }
534 if ( $this->mDbkeyform
== '_' ) { return false; }
535 # protect global styles and js
536 if ( NS_MEDIAWIKI
== $this->mNamespace
537 && preg_match("/\\.(css|js)$/", $this->mTextform
)
538 && !$wgUser->isSysop() )
540 //if ( $this->isCssJsSubpage() and !$this->userCanEditCssJsSubpage() ) { return false; }
541 # protect css/js subpages of user pages
542 # XXX: this might be better using restrictions
543 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
544 if( Namespace::getUser() == $this->mNamespace
545 and preg_match("/\\.(css|js)$/", $this->mTextform
)
546 and !$wgUser->isSysop()
547 and !preg_match('/^'.preg_quote($wgUser->getName(), '/').'/', $this->mTextform
) )
549 $ur = $wgUser->getRights();
550 foreach ( $this->getRestrictions() as $r ) {
551 if ( '' != $r && ( ! in_array( $r, $ur ) ) ) {
558 function userCanRead() {
560 global $wgWhitelistRead;
562 if( 0 != $wgUser->getID() ) return true;
563 if( !is_array( $wgWhitelistRead ) ) return true;
565 $name = $this->getPrefixedText();
566 if( in_array( $name, $wgWhitelistRead ) ) return true;
568 # Compatibility with old settings
569 if( $this->getNamespace() == NS_MAIN
) {
570 if( in_array( ':' . $name, $wgWhitelistRead ) ) return true;
575 function isCssJsSubpage() {
576 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
578 function isCssSubpage() {
579 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
581 function isJsSubpage() {
582 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
584 function userCanEditCssJsSubpage() {
585 # protect css/js subpages of user pages
586 # XXX: this might be better using restrictions
588 return ( $wgUser->isSysop() or preg_match('/^'.preg_quote($wgUser->getName()).'/', $this->mTextform
) );
591 # Accessor/initialisation for mRestrictions
592 function getRestrictions() {
593 $id = $this->getArticleID();
594 if ( 0 == $id ) { return array(); }
596 if ( ! $this->mRestrictionsLoaded
) {
597 $dbr =& wfGetDB( DB_SLAVE
);
598 $res = $dbr->getField( 'cur', 'cur_restrictions', 'cur_id='.$id );
599 $this->mRestrictions
= explode( ',', trim( $res ) );
600 $this->mRestrictionsLoaded
= true;
602 return $this->mRestrictions
;
605 # Is there a version of this page in the deletion archive?
606 # Returns the number of archived revisions
607 function isDeleted() {
608 $fname = 'Title::isDeleted';
609 $dbr =& wfGetDB( DB_SLAVE
);
610 $n = $dbr->getField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
611 'ar_title' => $this->getDBkey() ), $fname );
615 # Get the article ID from the link cache
616 # $flags is a bit field, may be GAID_FOR_UPDATE to select for update
617 function getArticleID( $flags = 0 ) {
620 if ( $flags & GAID_FOR_UPDATE
) {
621 $oldUpdate = $wgLinkCache->forUpdate( true );
622 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
623 $wgLinkCache->forUpdate( $oldUpdate );
625 if ( -1 == $this->mArticleID
) {
626 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
629 return $this->mArticleID
;
632 # This clears some fields in this object, and clears any associated keys in the
633 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
634 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
635 function resetArticleID( $newid ) {
637 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
639 if ( 0 == $newid ) { $this->mArticleID
= -1; }
640 else { $this->mArticleID
= $newid; }
641 $this->mRestrictionsLoaded
= false;
642 $this->mRestrictions
= array();
645 # Updates cur_touched
646 # Called from LinksUpdate.php
647 function invalidateCache() {
648 $now = wfTimestampNow();
649 $dbw =& wfGetDB( DB_MASTER
);
650 $success = $dbw->updateArray( 'cur',
652 'cur_touched' => $dbw->timestamp()
653 ), array( /* WHERE */
654 'cur_namespace' => $this->getNamespace() ,
655 'cur_title' => $this->getDBkey()
656 ), 'Title::invalidateCache'
661 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
662 /* private */ function prefix( $name ) {
666 if ( '' != $this->mInterwiki
) {
667 $p = $this->mInterwiki
. ':';
669 if ( 0 != $this->mNamespace
) {
670 $p .= $wgLang->getNsText( $this->mNamespace
) . ':';
675 # Secure and split - main initialisation function for this object
677 # Assumes that mDbkeyform has been set, and is urldecoded
678 # and uses underscores, but not otherwise munged. This function
679 # removes illegal characters, splits off the interwiki and
680 # namespace prefixes, sets the other forms, and canonicalizes
683 /* private */ function secureAndSplit()
685 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
686 $fname = 'Title::secureAndSplit';
687 wfProfileIn( $fname );
689 static $imgpre = false;
690 static $rxTc = false;
693 if ( $imgpre === false ) {
694 $imgpre = ':' . $wgLang->getNsText( Namespace::getImage() ) . ':';
695 # % is needed as well
696 $rxTc = '/[^' . Title
::legalChars() . ']/';
699 $this->mInterwiki
= $this->mFragment
= '';
700 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
702 # Clean up whitespace
704 $t = preg_replace( "/[\\s_]+/", '_', $this->mDbkeyform
);
705 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
708 wfProfileOut( $fname );
713 if( !$wgUseLatin1 && false !== strpos( $t, UTF8_REPLACEMENT
) ) {
714 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
715 wfProfileOut( $fname );
719 $this->mDbkeyform
= $t;
723 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
724 $t = substr( $t, 1 );
727 # Initial colon indicating main namespace
728 if ( ':' == $t{0} ) {
729 $r = substr( $t, 1 );
730 $this->mNamespace
= NS_MAIN
;
732 # Namespace or interwiki prefix
733 if ( preg_match( "/^(.+?)_*:_*(.*)$/", $t, $m ) ) {
734 #$p = strtolower( $m[1] );
736 $lowerNs = strtolower( $p );
737 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
738 # Canonical namespace
740 $this->mNamespace
= $ns;
741 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
744 $this->mNamespace
= $ns;
745 } elseif ( $this->getInterwikiLink( $p ) ) {
748 $this->mInterwiki
= $p;
750 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
752 } elseif($this->mInterwiki
!= $wgLocalInterwiki) {
760 # Redundant interwiki prefix to the local wiki
761 if ( 0 == strcmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
762 $this->mInterwiki
= '';
764 # We already know that some pages won't be in the database!
766 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
767 $this->mArticleID
= 0;
769 $f = strstr( $r, '#' );
770 if ( false !== $f ) {
771 $this->mFragment
= substr( $f, 1 );
772 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
775 # Reject illegal characters.
777 if( preg_match( $rxTc, $r ) ) {
778 wfProfileOut( $fname );
782 # "." and ".." conflict with the directories of those namesa
783 if ( strpos( $r, '.' ) !== false &&
784 ( $r === '.' ||
$r === '..' ||
785 strpos( $r, './' ) === 0 ||
786 strpos( $r, '../' ) === 0 ||
787 strpos( $r, '/./' ) !== false ||
788 strpos( $r, '/../' ) !== false ) )
790 wfProfileOut( $fname );
794 # Initial capital letter
795 if( $wgCapitalLinks && $this->mInterwiki
== '') {
796 $t = $wgLang->ucfirst( $r );
802 $this->mDbkeyform
= $t;
803 $this->mUrlform
= wfUrlencode( $t );
805 $this->mTextform
= str_replace( '_', ' ', $t );
807 wfProfileOut( $fname );
811 # Get a title object associated with the talk page of this article
812 function getTalkPage() {
813 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
816 # Get a title object associated with the subject page of this talk page
817 function getSubjectPage() {
818 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
821 # Get an array of Title objects linking to this title
822 # Also stores the IDs in the link cache
823 # $options may be FOR UPDATE
824 function getLinksTo( $options = '' ) {
826 $id = $this->getArticleID();
829 $db =& wfGetDB( DB_MASTER
);
831 $db =& wfGetDB( DB_SLAVE
);
833 $cur = $db->tableName( 'cur' );
834 $links = $db->tableName( 'links' );
836 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
837 $res = $db->query( $sql, 'Title::getLinksTo' );
839 if ( $db->numRows( $res ) ) {
840 while ( $row = $db->fetchObject( $res ) ) {
841 if ( $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
) ) {
842 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
843 $retVal[] = $titleObj;
847 $db->freeResult( $res );
851 # Get an array of Title objects linking to this non-existent title
852 # Also stores the IDs in the link cache
853 function getBrokenLinksTo( $options = '' ) {
857 $db =& wfGetDB( DB_MASTER
);
859 $db =& wfGetDB( DB_SLAVE
);
861 $cur = $db->tableName( 'cur' );
862 $brokenlinks = $db->tableName( 'brokenlinks' );
863 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
865 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
866 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
867 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
869 if ( $db->numRows( $res ) ) {
870 while ( $row = $db->fetchObject( $res ) ) {
871 $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
872 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
873 $retVal[] = $titleObj;
876 $db->freeResult( $res );
880 function getSquidURLs() {
882 $this->getInternalURL(),
883 $this->getInternalURL( 'action=history' )
887 function moveNoAuth( &$nt ) {
888 return $this->moveTo( $nt, false );
891 # Move a title to a new location
892 # Returns true on success, message name on failure
893 # auth indicates whether wgUser's permissions should be checked
894 function moveTo( &$nt, $auth = true ) {
895 if( !$this or !$nt ) {
896 return 'badtitletext';
899 $fname = 'Title::move';
900 $oldid = $this->getArticleID();
901 $newid = $nt->getArticleID();
903 if ( strlen( $nt->getDBkey() ) < 1 ) {
904 return 'articleexists';
906 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
907 ( '' == $this->getDBkey() ) ||
908 ( '' != $this->getInterwiki() ) ||
910 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
911 ( '' == $nt->getDBkey() ) ||
912 ( '' != $nt->getInterwiki() ) ) {
913 return 'badarticleerror';
916 if ( $auth && ( !$this->userCanEdit() ||
!$nt->userCanEdit() ) ) {
917 return 'protectedpage';
920 # The move is allowed only if (1) the target doesn't exist, or
921 # (2) the target is a redirect to the source, and has no history
922 # (so we can undo bad moves right after they're done).
924 if ( 0 != $newid ) { # Target exists; check for validity
925 if ( ! $this->isValidMoveTarget( $nt ) ) {
926 return 'articleexists';
928 $this->moveOverExistingRedirect( $nt );
929 } else { # Target didn't exist, do normal move.
930 $this->moveToNewTitle( $nt, $newid );
933 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
935 $dbw =& wfGetDB( DB_MASTER
);
936 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
937 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
938 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
939 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
943 $oldnamespace = $this->getNamespace() & ~
1;
944 $newnamespace = $nt->getNamespace() & ~
1;
945 $oldtitle = $this->getDBkey();
946 $newtitle = $nt->getDBkey();
948 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
949 WatchedItem
::duplicateEntries( $this, $nt );
952 # Update search engine
953 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
955 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
961 # Move page to title which is presently a redirect to the source page
963 /* private */ function moveOverExistingRedirect( &$nt ) {
964 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
965 $fname = 'Title::moveOverExistingRedirect';
966 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
968 $now = wfTimestampNow();
969 $won = wfInvertTimestamp( $now );
970 $newid = $nt->getArticleID();
971 $oldid = $this->getArticleID();
972 $dbw =& wfGetDB( DB_MASTER
);
973 $links = $dbw->tableName( 'links' );
975 # Change the name of the target page:
976 $dbw->updateArray( 'cur',
978 'cur_touched' => $dbw->timestamp($now),
979 'cur_namespace' => $nt->getNamespace(),
980 'cur_title' => $nt->getDBkey()
982 /* WHERE */ array( 'cur_id' => $oldid ),
985 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
987 # Repurpose the old redirect. We don't save it to history since
988 # by definition if we've got here it's rather uninteresting.
990 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
991 $dbw->updateArray( 'cur',
993 'cur_touched' => $dbw->timestamp($now),
994 'cur_timestamp' => $dbw->timestamp($now),
995 'inverse_timestamp' => $won,
996 'cur_namespace' => $this->getNamespace(),
997 'cur_title' => $this->getDBkey(),
998 'cur_text' => $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n",
999 'cur_comment' => $comment,
1000 'cur_user' => $wgUser->getID(),
1001 'cur_minor_edit' => 0,
1003 'cur_restrictions' => '',
1004 'cur_user_text' => $wgUser->getName(),
1005 'cur_is_redirect' => 1,
1008 /* WHERE */ array( 'cur_id' => $newid ),
1012 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1014 # Fix the redundant names for the past revisions of the target page.
1015 # The redirect should have no old revisions.
1019 'old_namespace' => $nt->getNamespace(),
1020 'old_title' => $nt->getDBkey(),
1023 'old_namespace' => $this->getNamespace(),
1024 'old_title' => $this->getDBkey(),
1029 RecentChange
::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
1033 # Load titles and IDs
1034 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1035 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1038 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1039 $dbw->query( $sql, $fname );
1042 if ( count( $linksToOld ) ||
count( $linksToNew )) {
1043 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1046 # Insert links to old title
1047 foreach ( $linksToOld as $linkTitle ) {
1053 $id = $linkTitle->getArticleID();
1054 $sql .= "($id,$newid)";
1057 # Insert links to new title
1058 foreach ( $linksToNew as $linkTitle ) {
1064 $id = $linkTitle->getArticleID();
1065 $sql .= "($id, $oldid)";
1068 $dbw->query( $sql, DB_MASTER
, $fname );
1071 # Now, we record the link from the redirect to the new title.
1072 # It should have no other outgoing links...
1073 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1074 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1077 LinkCache
::linksccClearLinksTo( $oldid );
1078 LinkCache
::linksccClearLinksTo( $newid );
1081 if ( $wgUseSquid ) {
1082 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1083 $u = new SquidUpdate( $urls );
1088 # Move page to non-existing title.
1089 # Sets $newid to be the new article ID
1091 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1092 global $wgUser, $wgLinkCache, $wgUseSquid;
1093 $fname = 'MovePageForm::moveToNewTitle';
1094 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1096 $newid = $nt->getArticleID();
1097 $oldid = $this->getArticleID();
1098 $dbw =& wfGetDB( DB_MASTER
);
1099 $now = $dbw->timestamp();
1100 $won = wfInvertTimestamp( wfTimestamp(TS_MW
,$now) );
1103 $dbw->updateArray( 'cur',
1105 'cur_touched' => $now,
1106 'cur_namespace' => $nt->getNamespace(),
1107 'cur_title' => $nt->getDBkey()
1109 /* WHERE */ array( 'cur_id' => $oldid ),
1113 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1116 $dbw->insertArray( 'cur', array(
1117 'cur_id' => $dbw->nextSequenceValue('cur_cur_id_seq'),
1118 'cur_namespace' => $this->getNamespace(),
1119 'cur_title' => $this->getDBkey(),
1120 'cur_comment' => $comment,
1121 'cur_user' => $wgUser->getID(),
1122 'cur_user_text' => $wgUser->getName(),
1123 'cur_timestamp' => $now,
1124 'inverse_timestamp' => $won,
1125 'cur_touched' => $now,
1126 'cur_is_redirect' => 1,
1128 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1130 $newid = $dbw->insertId();
1131 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1133 # Rename old entries
1137 'old_namespace' => $nt->getNamespace(),
1138 'old_title' => $nt->getDBkey()
1141 'old_namespace' => $this->getNamespace(),
1142 'old_title' => $this->getDBkey()
1147 RecentChange
::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1149 # Purge squid and linkscc as per article creation
1150 Article
::onArticleCreate( $nt );
1152 # Any text links to the old title must be reassigned to the redirect
1153 $dbw->updateArray( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1154 LinkCache
::linksccClearLinksTo( $oldid );
1156 # Record the just-created redirect's linking to the page
1157 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1159 # Non-existent target may have had broken links to it; these must
1160 # now be removed and made into good links.
1161 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1162 $update->fixBrokenLinks();
1164 # Purge old title from squid
1165 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1166 $titles = $nt->getLinksTo();
1167 if ( $wgUseSquid ) {
1168 $urls = $this->getSquidURLs();
1169 foreach ( $titles as $linkTitle ) {
1170 $urls[] = $linkTitle->getInternalURL();
1172 $u = new SquidUpdate( $urls );
1177 # Checks if $this can be moved to $nt
1178 # Selects for update, so don't call it unless you mean business
1179 function isValidMoveTarget( $nt ) {
1180 $fname = 'Title::isValidMoveTarget';
1181 $dbw =& wfGetDB( DB_MASTER
);
1184 $id = $nt->getArticleID();
1185 $obj = $dbw->getArray( 'cur', array( 'cur_is_redirect','cur_text' ),
1186 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1188 if ( !$obj ||
0 == $obj->cur_is_redirect
) {
1193 # Does the redirect point to the source?
1194 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text
, $m ) ) {
1195 $redirTitle = Title
::newFromText( $m[1] );
1196 if( !is_object( $redirTitle ) ||
1197 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1202 # Does the article have a history?
1203 $row = $dbw->getArray( 'old', array( 'old_id' ),
1205 'old_namespace' => $nt->getNamespace(),
1206 'old_title' => $nt->getDBkey()
1207 ), $fname, 'FOR UPDATE'
1210 # Return true if there was no history
1211 return $row === false;
1214 # Create a redirect, fails if the title already exists, does not notify RC
1216 function createRedirect( $dest, $comment ) {
1218 if ( $this->getArticleID() ) {
1222 $fname = 'Title::createRedirect';
1223 $dbw =& wfGetDB( DB_MASTER
);
1224 $now = wfTimestampNow();
1225 $won = wfInvertTimestamp( $now );
1226 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1228 $dbw->insertArray( 'cur', array(
1229 'cur_id' => $seqVal,
1230 'cur_namespace' => $this->getNamespace(),
1231 'cur_title' => $this->getDBkey(),
1232 'cur_comment' => $comment,
1233 'cur_user' => $wgUser->getID(),
1234 'cur_user_text' => $wgUser->getName(),
1235 'cur_timestamp' => $now,
1236 'inverse_timestamp' => $won,
1237 'cur_touched' => $now,
1238 'cur_is_redirect' => 1,
1240 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1242 $newid = $dbw->insertId();
1243 $this->resetArticleID( $newid );
1246 if ( $dest->getArticleID() ) {
1247 $dbw->insertArray( 'links',
1249 'l_to' => $dest->getArticleID(),
1254 $dbw->insertArray( 'brokenlinks',
1256 'bl_to' => $dest->getPrefixedDBkey(),
1262 Article
::onArticleCreate( $this );
1266 # Get categories to wich belong this title and return an array of
1268 # Return an array of parents in the form:
1269 # $parent => $currentarticle
1270 function getParentCategories() {
1271 global $wgLang,$wgUser;
1273 $titlekey = $this->getArticleId();
1274 $sk =& $wgUser->getSkin();
1276 $dbr =& wfGetDB( DB_SLAVE
);
1277 $cur = $dbr->tableName( 'cur' );
1278 $categorylinks = $dbr->tableName( 'categorylinks' );
1281 $sql = "SELECT * FROM categorylinks"
1282 ." WHERE cl_from='$titlekey'"
1283 ." AND cl_from <> '0'"
1284 ." ORDER BY cl_sortkey";
1286 $res = $dbr->query ( $sql ) ;
1288 if($dbr->numRows($res) > 0) {
1289 while ( $x = $dbr->fetchObject ( $res ) )
1290 //$data[] = Title::newFromText($wgLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1291 $data[$wgLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1292 $dbr->freeResult ( $res ) ;
1299 # Go through all parents
1300 function getCategorieBrowser() {
1301 $parents = $this->getParentCategories();
1303 if($parents != '') {
1304 foreach($parents as $parent => $current)
1306 $nt = Title
::newFromText($parent);
1307 $stack[$parent] = $nt->getCategorieBrowser();
1316 # Returns an associative array for selecting this title from cur
1317 function curCond() {
1318 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1321 function oldCond() {
1322 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);