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 ( !is_null($rt) && $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 ) );
773 # remove whitespace again: prevents "Foo_bar_#"
774 # becoming "Foo_bar_"
775 $r = preg_replace( '/_*$/', '', $r );
778 # Reject illegal characters.
780 if( preg_match( $rxTc, $r ) ) {
781 wfProfileOut( $fname );
785 # "." and ".." conflict with the directories of those namesa
786 if ( strpos( $r, '.' ) !== false &&
787 ( $r === '.' ||
$r === '..' ||
788 strpos( $r, './' ) === 0 ||
789 strpos( $r, '../' ) === 0 ||
790 strpos( $r, '/./' ) !== false ||
791 strpos( $r, '/../' ) !== false ) )
793 wfProfileOut( $fname );
797 # Initial capital letter
798 if( $wgCapitalLinks && $this->mInterwiki
== '') {
799 $t = $wgLang->ucfirst( $r );
805 $this->mDbkeyform
= $t;
806 $this->mUrlform
= wfUrlencode( $t );
808 $this->mTextform
= str_replace( '_', ' ', $t );
810 wfProfileOut( $fname );
814 # Get a title object associated with the talk page of this article
815 function getTalkPage() {
816 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
819 # Get a title object associated with the subject page of this talk page
820 function getSubjectPage() {
821 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
824 # Get an array of Title objects linking to this title
825 # Also stores the IDs in the link cache
826 # $options may be FOR UPDATE
827 function getLinksTo( $options = '' ) {
829 $id = $this->getArticleID();
832 $db =& wfGetDB( DB_MASTER
);
834 $db =& wfGetDB( DB_SLAVE
);
836 $cur = $db->tableName( 'cur' );
837 $links = $db->tableName( 'links' );
839 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
840 $res = $db->query( $sql, 'Title::getLinksTo' );
842 if ( $db->numRows( $res ) ) {
843 while ( $row = $db->fetchObject( $res ) ) {
844 if ( $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
) ) {
845 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
846 $retVal[] = $titleObj;
850 $db->freeResult( $res );
854 # Get an array of Title objects linking to this non-existent title
855 # Also stores the IDs in the link cache
856 function getBrokenLinksTo( $options = '' ) {
860 $db =& wfGetDB( DB_MASTER
);
862 $db =& wfGetDB( DB_SLAVE
);
864 $cur = $db->tableName( 'cur' );
865 $brokenlinks = $db->tableName( 'brokenlinks' );
866 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
868 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
869 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
870 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
872 if ( $db->numRows( $res ) ) {
873 while ( $row = $db->fetchObject( $res ) ) {
874 $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
875 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
876 $retVal[] = $titleObj;
879 $db->freeResult( $res );
883 function getSquidURLs() {
885 $this->getInternalURL(),
886 $this->getInternalURL( 'action=history' )
890 function moveNoAuth( &$nt ) {
891 return $this->moveTo( $nt, false );
894 # Move a title to a new location
895 # Returns true on success, message name on failure
896 # auth indicates whether wgUser's permissions should be checked
897 function moveTo( &$nt, $auth = true ) {
898 if( !$this or !$nt ) {
899 return 'badtitletext';
902 $fname = 'Title::move';
903 $oldid = $this->getArticleID();
904 $newid = $nt->getArticleID();
906 if ( strlen( $nt->getDBkey() ) < 1 ) {
907 return 'articleexists';
909 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
910 ( '' == $this->getDBkey() ) ||
911 ( '' != $this->getInterwiki() ) ||
913 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
914 ( '' == $nt->getDBkey() ) ||
915 ( '' != $nt->getInterwiki() ) ) {
916 return 'badarticleerror';
919 if ( $auth && ( !$this->userCanEdit() ||
!$nt->userCanEdit() ) ) {
920 return 'protectedpage';
923 # The move is allowed only if (1) the target doesn't exist, or
924 # (2) the target is a redirect to the source, and has no history
925 # (so we can undo bad moves right after they're done).
927 if ( 0 != $newid ) { # Target exists; check for validity
928 if ( ! $this->isValidMoveTarget( $nt ) ) {
929 return 'articleexists';
931 $this->moveOverExistingRedirect( $nt );
932 } else { # Target didn't exist, do normal move.
933 $this->moveToNewTitle( $nt, $newid );
936 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
938 $dbw =& wfGetDB( DB_MASTER
);
939 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
940 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
941 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
942 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
946 $oldnamespace = $this->getNamespace() & ~
1;
947 $newnamespace = $nt->getNamespace() & ~
1;
948 $oldtitle = $this->getDBkey();
949 $newtitle = $nt->getDBkey();
951 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
952 WatchedItem
::duplicateEntries( $this, $nt );
955 # Update search engine
956 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
958 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
964 # Move page to title which is presently a redirect to the source page
966 /* private */ function moveOverExistingRedirect( &$nt ) {
967 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
968 $fname = 'Title::moveOverExistingRedirect';
969 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
971 $now = wfTimestampNow();
972 $won = wfInvertTimestamp( $now );
973 $newid = $nt->getArticleID();
974 $oldid = $this->getArticleID();
975 $dbw =& wfGetDB( DB_MASTER
);
976 $links = $dbw->tableName( 'links' );
978 # Change the name of the target page:
979 $dbw->updateArray( 'cur',
981 'cur_touched' => $dbw->timestamp($now),
982 'cur_namespace' => $nt->getNamespace(),
983 'cur_title' => $nt->getDBkey()
985 /* WHERE */ array( 'cur_id' => $oldid ),
988 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
990 # Repurpose the old redirect. We don't save it to history since
991 # by definition if we've got here it's rather uninteresting.
993 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
994 $dbw->updateArray( 'cur',
996 'cur_touched' => $dbw->timestamp($now),
997 'cur_timestamp' => $dbw->timestamp($now),
998 'inverse_timestamp' => $won,
999 'cur_namespace' => $this->getNamespace(),
1000 'cur_title' => $this->getDBkey(),
1001 'cur_text' => $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n",
1002 'cur_comment' => $comment,
1003 'cur_user' => $wgUser->getID(),
1004 'cur_minor_edit' => 0,
1006 'cur_restrictions' => '',
1007 'cur_user_text' => $wgUser->getName(),
1008 'cur_is_redirect' => 1,
1011 /* WHERE */ array( 'cur_id' => $newid ),
1015 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1017 # Fix the redundant names for the past revisions of the target page.
1018 # The redirect should have no old revisions.
1022 'old_namespace' => $nt->getNamespace(),
1023 'old_title' => $nt->getDBkey(),
1026 'old_namespace' => $this->getNamespace(),
1027 'old_title' => $this->getDBkey(),
1032 RecentChange
::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
1036 # Load titles and IDs
1037 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1038 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1041 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1042 $dbw->query( $sql, $fname );
1045 if ( count( $linksToOld ) ||
count( $linksToNew )) {
1046 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1049 # Insert links to old title
1050 foreach ( $linksToOld as $linkTitle ) {
1056 $id = $linkTitle->getArticleID();
1057 $sql .= "($id,$newid)";
1060 # Insert links to new title
1061 foreach ( $linksToNew as $linkTitle ) {
1067 $id = $linkTitle->getArticleID();
1068 $sql .= "($id, $oldid)";
1071 $dbw->query( $sql, DB_MASTER
, $fname );
1074 # Now, we record the link from the redirect to the new title.
1075 # It should have no other outgoing links...
1076 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1077 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1080 LinkCache
::linksccClearLinksTo( $oldid );
1081 LinkCache
::linksccClearLinksTo( $newid );
1084 if ( $wgUseSquid ) {
1085 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1086 $u = new SquidUpdate( $urls );
1091 # Move page to non-existing title.
1092 # Sets $newid to be the new article ID
1094 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1095 global $wgUser, $wgLinkCache, $wgUseSquid;
1096 $fname = 'MovePageForm::moveToNewTitle';
1097 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1099 $newid = $nt->getArticleID();
1100 $oldid = $this->getArticleID();
1101 $dbw =& wfGetDB( DB_MASTER
);
1102 $now = $dbw->timestamp();
1103 $won = wfInvertTimestamp( wfTimestamp(TS_MW
,$now) );
1105 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
1108 $dbw->updateArray( 'cur',
1110 'cur_touched' => $now,
1111 'cur_namespace' => $nt->getNamespace(),
1112 'cur_title' => $nt->getDBkey()
1114 /* WHERE */ array( 'cur_id' => $oldid ),
1118 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1121 $dbw->insertArray( 'cur', array(
1122 'cur_id' => $dbw->nextSequenceValue('cur_cur_id_seq'),
1123 'cur_namespace' => $this->getNamespace(),
1124 'cur_title' => $this->getDBkey(),
1125 'cur_comment' => $comment,
1126 'cur_user' => $wgUser->getID(),
1127 'cur_user_text' => $wgUser->getName(),
1128 'cur_timestamp' => $now,
1129 'inverse_timestamp' => $won,
1130 'cur_touched' => $now,
1131 'cur_is_redirect' => 1,
1132 'cur_random' => $rand,
1134 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1136 $newid = $dbw->insertId();
1137 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1139 # Rename old entries
1143 'old_namespace' => $nt->getNamespace(),
1144 'old_title' => $nt->getDBkey()
1147 'old_namespace' => $this->getNamespace(),
1148 'old_title' => $this->getDBkey()
1153 RecentChange
::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1155 # Purge squid and linkscc as per article creation
1156 Article
::onArticleCreate( $nt );
1158 # Any text links to the old title must be reassigned to the redirect
1159 $dbw->updateArray( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1160 LinkCache
::linksccClearLinksTo( $oldid );
1162 # Record the just-created redirect's linking to the page
1163 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1165 # Non-existent target may have had broken links to it; these must
1166 # now be removed and made into good links.
1167 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1168 $update->fixBrokenLinks();
1170 # Purge old title from squid
1171 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1172 $titles = $nt->getLinksTo();
1173 if ( $wgUseSquid ) {
1174 $urls = $this->getSquidURLs();
1175 foreach ( $titles as $linkTitle ) {
1176 $urls[] = $linkTitle->getInternalURL();
1178 $u = new SquidUpdate( $urls );
1183 # Checks if $this can be moved to $nt
1184 # Selects for update, so don't call it unless you mean business
1185 function isValidMoveTarget( $nt ) {
1186 $fname = 'Title::isValidMoveTarget';
1187 $dbw =& wfGetDB( DB_MASTER
);
1190 $id = $nt->getArticleID();
1191 $obj = $dbw->getArray( 'cur', array( 'cur_is_redirect','cur_text' ),
1192 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1194 if ( !$obj ||
0 == $obj->cur_is_redirect
) {
1199 # Does the redirect point to the source?
1200 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text
, $m ) ) {
1201 $redirTitle = Title
::newFromText( $m[1] );
1202 if( !is_object( $redirTitle ) ||
1203 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1208 # Does the article have a history?
1209 $row = $dbw->getArray( 'old', array( 'old_id' ),
1211 'old_namespace' => $nt->getNamespace(),
1212 'old_title' => $nt->getDBkey()
1213 ), $fname, 'FOR UPDATE'
1216 # Return true if there was no history
1217 return $row === false;
1220 # Create a redirect, fails if the title already exists, does not notify RC
1222 function createRedirect( $dest, $comment ) {
1224 if ( $this->getArticleID() ) {
1228 $fname = 'Title::createRedirect';
1229 $dbw =& wfGetDB( DB_MASTER
);
1230 $now = wfTimestampNow();
1231 $won = wfInvertTimestamp( $now );
1232 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1234 $dbw->insertArray( 'cur', array(
1235 'cur_id' => $seqVal,
1236 'cur_namespace' => $this->getNamespace(),
1237 'cur_title' => $this->getDBkey(),
1238 'cur_comment' => $comment,
1239 'cur_user' => $wgUser->getID(),
1240 'cur_user_text' => $wgUser->getName(),
1241 'cur_timestamp' => $now,
1242 'inverse_timestamp' => $won,
1243 'cur_touched' => $now,
1244 'cur_is_redirect' => 1,
1246 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1248 $newid = $dbw->insertId();
1249 $this->resetArticleID( $newid );
1252 if ( $dest->getArticleID() ) {
1253 $dbw->insertArray( 'links',
1255 'l_to' => $dest->getArticleID(),
1260 $dbw->insertArray( 'brokenlinks',
1262 'bl_to' => $dest->getPrefixedDBkey(),
1268 Article
::onArticleCreate( $this );
1272 # Get categories to wich belong this title and return an array of
1274 # Return an array of parents in the form:
1275 # $parent => $currentarticle
1276 function getParentCategories() {
1277 global $wgLang,$wgUser;
1279 $titlekey = $this->getArticleId();
1280 $sk =& $wgUser->getSkin();
1282 $dbr =& wfGetDB( DB_SLAVE
);
1283 $cur = $dbr->tableName( 'cur' );
1284 $categorylinks = $dbr->tableName( 'categorylinks' );
1287 $sql = "SELECT * FROM categorylinks"
1288 ." WHERE cl_from='$titlekey'"
1289 ." AND cl_from <> '0'"
1290 ." ORDER BY cl_sortkey";
1292 $res = $dbr->query ( $sql ) ;
1294 if($dbr->numRows($res) > 0) {
1295 while ( $x = $dbr->fetchObject ( $res ) )
1296 //$data[] = Title::newFromText($wgLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1297 $data[$wgLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1298 $dbr->freeResult ( $res ) ;
1305 # Go through all parents
1306 function getCategorieBrowser() {
1307 $parents = $this->getParentCategories();
1309 if($parents != '') {
1310 foreach($parents as $parent => $current)
1312 $nt = Title
::newFromText($parent);
1313 $stack[$parent] = $nt->getCategorieBrowser();
1322 # Returns an associative array for selecting this title from cur
1323 function curCond() {
1324 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1327 function oldCond() {
1328 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);