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;
53 $this->mNamespace
= 0;
54 $this->mRestrictionsLoaded
= false;
55 $this->mRestrictions
= array();
56 $this->mDefaultNamespace
= 0;
59 # From a prefixed DB key
60 /* static */ function newFromDBkey( $key ) {
62 $t->mDbkeyform
= $key;
63 if( $t->secureAndSplit() )
69 # From text, such as what you would find in a link
70 /* static */ function newFromText( $text, $defaultNamespace = 0 ) {
71 $fname = 'Title::newFromText';
72 wfProfileIn( $fname );
74 if( is_object( $text ) ) {
75 wfDebugDieBacktrace( 'Called with object instead of string.' );
77 global $wgInputEncoding;
78 $text = do_html_entity_decode( $text, ENT_COMPAT
, $wgInputEncoding );
80 $text = wfMungeToUtf8( $text );
83 # What was this for? TS 2004-03-03
84 # $text = urldecode( $text );
87 $t->mDbkeyform
= str_replace( ' ', '_', $text );
88 $t->mDefaultNamespace
= $defaultNamespace;
90 wfProfileOut( $fname );
91 if ( !is_object( $t ) ) {
92 var_dump( debug_backtrace() );
94 if( $t->secureAndSplit() ) {
101 # From a URL-encoded title
102 /* static */ function newFromURL( $url ) {
103 global $wgLang, $wgServer;
106 # For compatibility with old buggy URLs. "+" is not valid in titles,
107 # but some URLs used it as a space replacement and they still come
108 # from some external search tools.
109 $s = str_replace( '+', ' ', $url );
111 $t->mDbkeyform
= str_replace( ' ', '_', $s );
112 if( $t->secureAndSplit() ) {
113 # check that length of title is < cur_title size
114 $dbr =& wfGetDB( DB_SLAVE
);
115 $maxSize = $dbr->textFieldSize( 'cur', 'cur_title' );
116 if ( $maxSize != -1 && strlen( $t->mDbkeyform
) > $maxSize ) {
127 # This is inefficiently implemented, the cur row is requested but not
128 # used for anything else
129 /* static */ function newFromID( $id ) {
130 $fname = 'Title::newFromID';
131 $dbr =& wfGetDB( DB_SLAVE
);
132 $row = $dbr->getArray( 'cur', array( 'cur_namespace', 'cur_title' ),
133 array( 'cur_id' => $id ), $fname );
134 if ( $row !== false ) {
135 $title = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
142 # From a namespace index and a DB key.
143 # It's assumed that $ns and $title are *valid*, for instance when
144 # they came directly from the database or a special page name.
145 /* static */ function &makeTitle( $ns, $title ) {
149 $t->mNamespace
= $ns;
150 $t->mDbkeyform
= $title;
151 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
152 $t->mUrlform
= wfUrlencode( $title );
153 $t->mTextform
= str_replace( '_', ' ', $title );
157 # From a namespace index and a DB key.
158 # These will be checked for validity, which is a bit slower
159 # than makeTitle() but safer for user-provided data.
160 /* static */ function makeTitleSafe( $ns, $title ) {
162 $t->mDbkeyform
= Title
::makeName( $ns, $title );
163 if( $t->secureAndSplit() ) {
170 /* static */ function newMainPage() {
171 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
174 # Get the title object for a redirect
175 # Returns NULL if the text is not a valid redirect
176 /* static */ function newFromRedirect( $text ) {
179 if ( $wgMwRedir->matchStart( $text ) ) {
180 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/', $text, $m ) ) {
181 # categories are escaped using : for example one can enter:
182 # #REDIRECT [[:Category:Music]]. Need to remove it.
183 if ( substr($m[1],0,1) == ':') {
184 # We don't want to keep the ':'
185 $m[1] = substr( $m[1], 1 );
188 $rt = Title
::newFromText( $m[1] );
189 # Disallow redirects to Special:Userlogout
190 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
198 #----------------------------------------------------------------------------
200 #----------------------------------------------------------------------------
202 # Get the prefixed DB key associated with an ID
203 /* static */ function nameOf( $id ) {
204 $fname = 'Title::nameOf';
205 $dbr =& wfGetDB( DB_SLAVE
);
207 $s = $dbr->getArray( 'cur', array( 'cur_namespace','cur_title' ), array( 'cur_id' => $id ), $fname );
208 if ( $s === false ) { return NULL; }
210 $n = Title
::makeName( $s->cur_namespace
, $s->cur_title
);
214 # Get a regex character class describing the legal characters in a link
215 /* static */ function legalChars() {
216 # Missing characters:
217 # * []|# Needed for link syntax
218 # * % and + are corrupted by Apache when they appear in the path
220 # % seems to work though
222 # The problem with % is that URLs are double-unescaped: once by Apache's
223 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
224 # Our code does not double-escape to compensate for this, indeed double escaping
225 # would break if the double-escaped title was passed in the query string
226 # rather than the path. This is a minor security issue because articles can be
227 # created such that they are hard to view or edit. -- TS
229 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
230 # this breaks interlanguage links
232 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF";
236 # Returns a stripped-down a title string ready for the search index
237 # Takes a namespace index and a text-form main part
238 /* static */ function indexTitle( $ns, $title ) {
239 global $wgDBminWordLen, $wgContLang;
240 require_once( 'SearchEngine.php' );
242 $lc = SearchEngine
::legalSearchChars() . '&#;';
243 $t = $wgContLang->stripForSearch( $title );
244 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
245 $t = strtolower( $t );
248 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
249 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
251 $t = preg_replace( "/\\s+/", ' ', $t );
253 if ( $ns == Namespace::getImage() ) {
254 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
259 # Make a prefixed DB key from a DB key and a namespace index
260 /* static */ function makeName( $ns, $title ) {
263 $n = $wgContLang->getNsText( $ns );
264 if ( '' == $n ) { return $title; }
265 else { return $n.':'.$title; }
269 # Returns the URL associated with an interwiki prefix
270 # The URL contains $1, which is replaced by the title
271 function getInterwikiLink( $key ) {
272 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
273 $fname = 'Title::getInterwikiLink';
274 $k = $wgDBname.':interwiki:'.$key;
276 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
277 return $wgTitleInterwikiCache[$k]->iw_url
;
279 $s = $wgMemc->get( $k );
280 # Ignore old keys with no iw_local
281 if( $s && isset( $s->iw_local
) ) {
282 $wgTitleInterwikiCache[$k] = $s;
285 $dbr =& wfGetDB( DB_SLAVE
);
286 $res = $dbr->select( 'interwiki', array( 'iw_url', 'iw_local' ), array( 'iw_prefix' => $key ), $fname );
289 $s = $dbr->fetchObject( $res );
291 # Cache non-existence: create a blank object and save it to memcached
296 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
297 $wgTitleInterwikiCache[$k] = $s;
302 global $wgTitleInterwikiCache, $wgDBname;
304 if ( $this->mInterwiki
!= '' ) {
305 # Make sure key is loaded into cache
306 $this->getInterwikiLink( $this->mInterwiki
);
307 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
308 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
314 # Update the cur_touched field for an array of title objects
315 # Inefficient unless the IDs are already loaded into the link cache
316 /* static */ function touchArray( $titles, $timestamp = '' ) {
317 if ( count( $titles ) == 0 ) {
320 $dbw =& wfGetDB( DB_MASTER
);
321 if ( $timestamp == '' ) {
322 $timestamp = $dbw->timestamp();
324 $cur = $dbw->tableName( 'cur' );
325 $sql = "UPDATE $cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
328 foreach ( $titles as $title ) {
333 $sql .= $title->getArticleID();
337 $dbw->query( $sql, 'Title::touchArray' );
341 #----------------------------------------------------------------------------
343 #----------------------------------------------------------------------------
346 # See the definitions at the top of this file
348 function getText() { return $this->mTextform
; }
349 function getPartialURL() { return $this->mUrlform
; }
350 function getDBkey() { return $this->mDbkeyform
; }
351 function getNamespace() { return $this->mNamespace
; }
352 function setNamespace( $n ) { $this->mNamespace
= $n; }
353 function getInterwiki() { return $this->mInterwiki
; }
354 function getFragment() { return $this->mFragment
; }
355 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
357 # Get title for search index
358 function getIndexTitle() {
359 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
362 # Get prefixed title with underscores
363 function getPrefixedDBkey() {
364 $s = $this->prefix( $this->mDbkeyform
);
365 $s = str_replace( ' ', '_', $s );
369 # Get prefixed title with spaces
370 # This is the form usually used for display
371 function getPrefixedText() {
372 if ( empty( $this->mPrefixedText
) ) {
373 $s = $this->prefix( $this->mTextform
);
374 $s = str_replace( '_', ' ', $s );
375 $this->mPrefixedText
= $s;
377 return $this->mPrefixedText
;
380 # As getPrefixedText(), plus fragment.
381 function getFullText() {
382 $text = $this->getPrefixedText();
383 if( '' != $this->mFragment
) {
384 $text .= '#' . $this->mFragment
;
389 # Get a URL-encoded title (not an actual URL) including interwiki
390 function getPrefixedURL() {
391 $s = $this->prefix( $this->mDbkeyform
);
392 $s = str_replace( ' ', '_', $s );
394 $s = wfUrlencode ( $s ) ;
396 # Cleaning up URL to make it look nice -- is this safe?
397 $s = preg_replace( '/%3[Aa]/', ':', $s );
398 $s = preg_replace( '/%2[Ff]/', '/', $s );
399 $s = str_replace( '%28', '(', $s );
400 $s = str_replace( '%29', ')', $s );
405 # Get a real URL referring to this title, with interwiki link and fragment
406 function getFullURL( $query = '' ) {
407 global $wgContLang, $wgArticlePath, $wgServer, $wgScript;
409 if ( '' == $this->mInterwiki
) {
411 return $wgServer . $this->getLocalUrl( $query );
413 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
414 $namespace = $wgContLang->getNsText( $this->mNamespace
);
415 if ( '' != $namespace ) {
416 # Can this actually happen? Interwikis shouldn't be parsed.
419 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
420 if ( '' != $this->mFragment
) {
421 $url .= '#' . $this->mFragment
;
427 # Get a URL with an optional query string, no fragment
428 # * If $query=="", it will use $wgArticlePath
429 # * Returns a full for an interwiki link, loses any query string
430 # * Optionally adds the server and escapes for HTML
431 # * Setting $query to "-" makes an old-style URL with nothing in the
432 # query except a title
435 die( 'Call to obsolete obsolete function Title::getURL()' );
438 function getLocalURL( $query = '' ) {
439 global $wgLang, $wgArticlePath, $wgScript;
441 if ( $this->isExternal() ) {
442 return $this->getFullURL();
445 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
446 if ( $query == '' ) {
447 $url = str_replace( '$1', $dbkey, $wgArticlePath );
449 if ( $query == '-' ) {
452 if ( $wgScript != '' ) {
453 $url = "{$wgScript}?title={$dbkey}&{$query}";
456 $url = "/{$dbkey}?{$query}";
462 function escapeLocalURL( $query = '' ) {
463 return htmlspecialchars( $this->getLocalURL( $query ) );
466 function escapeFullURL( $query = '' ) {
467 return htmlspecialchars( $this->getFullURL( $query ) );
470 function getInternalURL( $query = '' ) {
471 # Used in various Squid-related code, in case we have a different
472 # internal hostname for the server than the exposed one.
473 global $wgInternalServer;
474 return $wgInternalServer . $this->getLocalURL( $query );
477 # Get the edit URL, or a null string if it is an interwiki link
478 function getEditURL() {
479 global $wgServer, $wgScript;
481 if ( '' != $this->mInterwiki
) { return ''; }
482 $s = $this->getLocalURL( 'action=edit' );
487 # Get HTML-escaped displayable text
488 # For the title field in <a> tags
489 function getEscapedText() {
490 return htmlspecialchars( $this->getPrefixedText() );
493 # Is the title interwiki?
494 function isExternal() { return ( '' != $this->mInterwiki
); }
496 # Does the title correspond to a protected article?
497 function isProtected() {
498 if ( -1 == $this->mNamespace
) { return true; }
499 $a = $this->getRestrictions();
500 if ( in_array( 'sysop', $a ) ) { return true; }
504 # Is the page a log page, i.e. one where the history is messed up by
505 # LogPage.php? This used to be used for suppressing diff links in recent
506 # changes, but now that's done by setting a flag in the recentchanges
507 # table. Hence, this probably is no longer used.
509 if ( $this->mNamespace
!= Namespace::getWikipedia() ) {
512 if ( ( 0 == strcmp( wfMsg( 'uploadlogpage' ), $this->mDbkeyform
) ) ||
513 ( 0 == strcmp( wfMsg( 'dellogpage' ), $this->mDbkeyform
) ) ) {
519 # Is $wgUser is watching this page?
520 function userIsWatching() {
523 if ( -1 == $this->mNamespace
) { return false; }
524 if ( 0 == $wgUser->getID() ) { return false; }
526 return $wgUser->isWatched( $this );
529 # Can $wgUser edit this page?
530 function userCanEdit() {
532 if ( -1 == $this->mNamespace
) { return false; }
533 if ( NS_MEDIAWIKI
== $this->mNamespace
&& !$wgUser->isSysop() ) { return false; }
534 # if ( 0 == $this->getArticleID() ) { return false; }
535 if ( $this->mDbkeyform
== '_' ) { return false; }
536 # protect global styles and js
537 if ( NS_MEDIAWIKI
== $this->mNamespace
538 && preg_match("/\\.(css|js)$/", $this->mTextform
)
539 && !$wgUser->isSysop() )
541 //if ( $this->isCssJsSubpage() and !$this->userCanEditCssJsSubpage() ) { return false; }
542 # protect css/js subpages of user pages
543 # XXX: this might be better using restrictions
544 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
545 if( Namespace::getUser() == $this->mNamespace
546 and preg_match("/\\.(css|js)$/", $this->mTextform
)
547 and !$wgUser->isSysop()
548 and !preg_match('/^'.preg_quote($wgUser->getName(), '/').'/', $this->mTextform
) )
550 $ur = $wgUser->getRights();
551 foreach ( $this->getRestrictions() as $r ) {
552 if ( '' != $r && ( ! in_array( $r, $ur ) ) ) {
559 function userCanRead() {
561 global $wgWhitelistRead;
563 if( 0 != $wgUser->getID() ) return true;
564 if( !is_array( $wgWhitelistRead ) ) return true;
566 $name = $this->getPrefixedText();
567 if( in_array( $name, $wgWhitelistRead ) ) return true;
569 # Compatibility with old settings
570 if( $this->getNamespace() == NS_MAIN
) {
571 if( in_array( ':' . $name, $wgWhitelistRead ) ) return true;
576 function isCssJsSubpage() {
577 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
579 function isCssSubpage() {
580 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
582 function isJsSubpage() {
583 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
585 function userCanEditCssJsSubpage() {
586 # protect css/js subpages of user pages
587 # XXX: this might be better using restrictions
589 return ( $wgUser->isSysop() or preg_match('/^'.preg_quote($wgUser->getName()).'/', $this->mTextform
) );
592 # Accessor/initialisation for mRestrictions
593 function getRestrictions() {
594 $id = $this->getArticleID();
595 if ( 0 == $id ) { return array(); }
597 if ( ! $this->mRestrictionsLoaded
) {
598 $dbr =& wfGetDB( DB_SLAVE
);
599 $res = $dbr->getField( 'cur', 'cur_restrictions', 'cur_id='.$id );
600 $this->mRestrictions
= explode( ',', trim( $res ) );
601 $this->mRestrictionsLoaded
= true;
603 return $this->mRestrictions
;
606 # Is there a version of this page in the deletion archive?
607 # Returns the number of archived revisions
608 function isDeleted() {
609 $fname = 'Title::isDeleted';
610 $dbr =& wfGetDB( DB_SLAVE
);
611 $n = $dbr->getField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
612 'ar_title' => $this->getDBkey() ), $fname );
616 # Get the article ID from the link cache
617 # $flags is a bit field, may be GAID_FOR_UPDATE to select for update
618 function getArticleID( $flags = 0 ) {
621 if ( $flags & GAID_FOR_UPDATE
) {
622 $oldUpdate = $wgLinkCache->forUpdate( true );
623 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
624 $wgLinkCache->forUpdate( $oldUpdate );
626 if ( -1 == $this->mArticleID
) {
627 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
630 return $this->mArticleID
;
633 # This clears some fields in this object, and clears any associated keys in the
634 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
635 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
636 function resetArticleID( $newid ) {
638 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
640 if ( 0 == $newid ) { $this->mArticleID
= -1; }
641 else { $this->mArticleID
= $newid; }
642 $this->mRestrictionsLoaded
= false;
643 $this->mRestrictions
= array();
646 # Updates cur_touched
647 # Called from LinksUpdate.php
648 function invalidateCache() {
649 $now = wfTimestampNow();
650 $dbw =& wfGetDB( DB_MASTER
);
651 $success = $dbw->updateArray( 'cur',
653 'cur_touched' => $dbw->timestamp()
654 ), array( /* WHERE */
655 'cur_namespace' => $this->getNamespace() ,
656 'cur_title' => $this->getDBkey()
657 ), 'Title::invalidateCache'
662 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
663 /* private */ function prefix( $name ) {
667 if ( '' != $this->mInterwiki
) {
668 $p = $this->mInterwiki
. ':';
670 if ( 0 != $this->mNamespace
) {
671 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
676 # Secure and split - main initialisation function for this object
678 # Assumes that mDbkeyform has been set, and is urldecoded
679 # and uses underscores, but not otherwise munged. This function
680 # removes illegal characters, splits off the interwiki and
681 # namespace prefixes, sets the other forms, and canonicalizes
684 /* private */ function secureAndSplit()
686 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
687 $fname = 'Title::secureAndSplit';
688 wfProfileIn( $fname );
690 static $imgpre = false;
691 static $rxTc = false;
694 if ( $imgpre === false ) {
695 $imgpre = ':' . $wgContLang->getNsText( Namespace::getImage() ) . ':';
696 # % is needed as well
697 $rxTc = '/[^' . Title
::legalChars() . ']/';
700 $this->mInterwiki
= $this->mFragment
= '';
701 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
703 # Clean up whitespace
705 $t = preg_replace( "/[\\s_]+/", '_', $this->mDbkeyform
);
706 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
709 wfProfileOut( $fname );
714 if( !$wgUseLatin1 && false !== strpos( $t, UTF8_REPLACEMENT
) ) {
715 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
716 wfProfileOut( $fname );
720 $this->mDbkeyform
= $t;
724 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
725 $t = substr( $t, 1 );
728 # Initial colon indicating main namespace
729 if ( ':' == $t{0} ) {
730 $r = substr( $t, 1 );
731 $this->mNamespace
= NS_MAIN
;
733 # Namespace or interwiki prefix
734 if ( preg_match( "/^(.+?)_*:_*(.*)$/", $t, $m ) ) {
735 #$p = strtolower( $m[1] );
737 $lowerNs = strtolower( $p );
738 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
739 # Canonical namespace
741 $this->mNamespace
= $ns;
742 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
745 $this->mNamespace
= $ns;
746 } elseif ( $this->getInterwikiLink( $p ) ) {
749 $this->mInterwiki
= $p;
751 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
753 } elseif($this->mInterwiki
!= $wgLocalInterwiki) {
761 # Redundant interwiki prefix to the local wiki
762 if ( 0 == strcmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
763 $this->mInterwiki
= '';
765 # We already know that some pages won't be in the database!
767 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
768 $this->mArticleID
= 0;
770 $f = strstr( $r, '#' );
771 if ( false !== $f ) {
772 $this->mFragment
= substr( $f, 1 );
773 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
774 # remove whitespace again: prevents "Foo_bar_#"
775 # becoming "Foo_bar_"
776 $r = preg_replace( '/_*$/', '', $r );
779 # Reject illegal characters.
781 if( preg_match( $rxTc, $r ) ) {
782 wfProfileOut( $fname );
786 # "." and ".." conflict with the directories of those namesa
787 if ( strpos( $r, '.' ) !== false &&
788 ( $r === '.' ||
$r === '..' ||
789 strpos( $r, './' ) === 0 ||
790 strpos( $r, '../' ) === 0 ||
791 strpos( $r, '/./' ) !== false ||
792 strpos( $r, '/../' ) !== false ) )
794 wfProfileOut( $fname );
798 # Initial capital letter
799 if( $wgCapitalLinks && $this->mInterwiki
== '') {
800 $t = $wgContLang->ucfirst( $r );
806 $this->mDbkeyform
= $t;
807 $this->mUrlform
= wfUrlencode( $t );
809 $this->mTextform
= str_replace( '_', ' ', $t );
811 wfProfileOut( $fname );
815 # Get a title object associated with the talk page of this article
816 function getTalkPage() {
817 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
820 # Get a title object associated with the subject page of this talk page
821 function getSubjectPage() {
822 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
825 # Get an array of Title objects linking to this title
826 # Also stores the IDs in the link cache
827 # $options may be FOR UPDATE
828 function getLinksTo( $options = '' ) {
830 $id = $this->getArticleID();
833 $db =& wfGetDB( DB_MASTER
);
835 $db =& wfGetDB( DB_SLAVE
);
837 $cur = $db->tableName( 'cur' );
838 $links = $db->tableName( 'links' );
840 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
841 $res = $db->query( $sql, 'Title::getLinksTo' );
843 if ( $db->numRows( $res ) ) {
844 while ( $row = $db->fetchObject( $res ) ) {
845 if ( $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
) ) {
846 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
847 $retVal[] = $titleObj;
851 $db->freeResult( $res );
855 # Get an array of Title objects linking to this non-existent title
856 # Also stores the IDs in the link cache
857 function getBrokenLinksTo( $options = '' ) {
861 $db =& wfGetDB( DB_MASTER
);
863 $db =& wfGetDB( DB_SLAVE
);
865 $cur = $db->tableName( 'cur' );
866 $brokenlinks = $db->tableName( 'brokenlinks' );
867 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
869 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
870 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
871 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
873 if ( $db->numRows( $res ) ) {
874 while ( $row = $db->fetchObject( $res ) ) {
875 $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
876 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
877 $retVal[] = $titleObj;
880 $db->freeResult( $res );
884 function getSquidURLs() {
886 $this->getInternalURL(),
887 $this->getInternalURL( 'action=history' )
891 function moveNoAuth( &$nt ) {
892 return $this->moveTo( $nt, false );
895 # Move a title to a new location
896 # Returns true on success, message name on failure
897 # auth indicates whether wgUser's permissions should be checked
898 function moveTo( &$nt, $auth = true ) {
899 if( !$this or !$nt ) {
900 return 'badtitletext';
903 $fname = 'Title::move';
904 $oldid = $this->getArticleID();
905 $newid = $nt->getArticleID();
907 if ( strlen( $nt->getDBkey() ) < 1 ) {
908 return 'articleexists';
910 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
911 ( '' == $this->getDBkey() ) ||
912 ( '' != $this->getInterwiki() ) ||
914 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
915 ( '' == $nt->getDBkey() ) ||
916 ( '' != $nt->getInterwiki() ) ) {
917 return 'badarticleerror';
920 if ( $auth && ( !$this->userCanEdit() ||
!$nt->userCanEdit() ) ) {
921 return 'protectedpage';
924 # The move is allowed only if (1) the target doesn't exist, or
925 # (2) the target is a redirect to the source, and has no history
926 # (so we can undo bad moves right after they're done).
928 if ( 0 != $newid ) { # Target exists; check for validity
929 if ( ! $this->isValidMoveTarget( $nt ) ) {
930 return 'articleexists';
932 $this->moveOverExistingRedirect( $nt );
933 } else { # Target didn't exist, do normal move.
934 $this->moveToNewTitle( $nt, $newid );
937 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
939 $dbw =& wfGetDB( DB_MASTER
);
940 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
941 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
942 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
943 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
947 $oldnamespace = $this->getNamespace() & ~
1;
948 $newnamespace = $nt->getNamespace() & ~
1;
949 $oldtitle = $this->getDBkey();
950 $newtitle = $nt->getDBkey();
952 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
953 WatchedItem
::duplicateEntries( $this, $nt );
956 # Update search engine
957 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
959 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
965 # Move page to title which is presently a redirect to the source page
967 /* private */ function moveOverExistingRedirect( &$nt ) {
968 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
969 $fname = 'Title::moveOverExistingRedirect';
970 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
972 $now = wfTimestampNow();
973 $won = wfInvertTimestamp( $now );
974 $newid = $nt->getArticleID();
975 $oldid = $this->getArticleID();
976 $dbw =& wfGetDB( DB_MASTER
);
977 $links = $dbw->tableName( 'links' );
979 # Change the name of the target page:
980 $dbw->updateArray( 'cur',
982 'cur_touched' => $dbw->timestamp($now),
983 'cur_namespace' => $nt->getNamespace(),
984 'cur_title' => $nt->getDBkey()
986 /* WHERE */ array( 'cur_id' => $oldid ),
989 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
991 # Repurpose the old redirect. We don't save it to history since
992 # by definition if we've got here it's rather uninteresting.
994 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
995 $dbw->updateArray( 'cur',
997 'cur_touched' => $dbw->timestamp($now),
998 'cur_timestamp' => $dbw->timestamp($now),
999 'inverse_timestamp' => $won,
1000 'cur_namespace' => $this->getNamespace(),
1001 'cur_title' => $this->getDBkey(),
1002 'cur_text' => $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n",
1003 'cur_comment' => $comment,
1004 'cur_user' => $wgUser->getID(),
1005 'cur_minor_edit' => 0,
1007 'cur_restrictions' => '',
1008 'cur_user_text' => $wgUser->getName(),
1009 'cur_is_redirect' => 1,
1012 /* WHERE */ array( 'cur_id' => $newid ),
1016 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1018 RecentChange
::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
1022 # Load titles and IDs
1023 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1024 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1027 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1028 $dbw->query( $sql, $fname );
1031 if ( count( $linksToOld ) ||
count( $linksToNew )) {
1032 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1035 # Insert links to old title
1036 foreach ( $linksToOld as $linkTitle ) {
1042 $id = $linkTitle->getArticleID();
1043 $sql .= "($id,$newid)";
1046 # Insert links to new title
1047 foreach ( $linksToNew as $linkTitle ) {
1053 $id = $linkTitle->getArticleID();
1054 $sql .= "($id, $oldid)";
1057 $dbw->query( $sql, DB_MASTER
, $fname );
1060 # Now, we record the link from the redirect to the new title.
1061 # It should have no other outgoing links...
1062 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1063 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1066 LinkCache
::linksccClearLinksTo( $oldid );
1067 LinkCache
::linksccClearLinksTo( $newid );
1070 if ( $wgUseSquid ) {
1071 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1072 $u = new SquidUpdate( $urls );
1077 # Move page to non-existing title.
1078 # Sets $newid to be the new article ID
1080 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1081 global $wgUser, $wgLinkCache, $wgUseSquid;
1082 $fname = 'MovePageForm::moveToNewTitle';
1083 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1085 $newid = $nt->getArticleID();
1086 $oldid = $this->getArticleID();
1087 $dbw =& wfGetDB( DB_MASTER
);
1088 $now = $dbw->timestamp();
1089 $won = wfInvertTimestamp( wfTimestamp(TS_MW
,$now) );
1091 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
1094 $dbw->updateArray( 'cur',
1096 'cur_touched' => $now,
1097 'cur_namespace' => $nt->getNamespace(),
1098 'cur_title' => $nt->getDBkey()
1100 /* WHERE */ array( 'cur_id' => $oldid ),
1104 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1107 $dbw->insertArray( 'cur', array(
1108 'cur_id' => $dbw->nextSequenceValue('cur_cur_id_seq'),
1109 'cur_namespace' => $this->getNamespace(),
1110 'cur_title' => $this->getDBkey(),
1111 'cur_comment' => $comment,
1112 'cur_user' => $wgUser->getID(),
1113 'cur_user_text' => $wgUser->getName(),
1114 'cur_timestamp' => $now,
1115 'inverse_timestamp' => $won,
1116 'cur_touched' => $now,
1117 'cur_is_redirect' => 1,
1118 'cur_random' => $rand,
1120 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1122 $newid = $dbw->insertId();
1123 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1126 RecentChange
::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1128 # Purge squid and linkscc as per article creation
1129 Article
::onArticleCreate( $nt );
1131 # Any text links to the old title must be reassigned to the redirect
1132 $dbw->updateArray( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1133 LinkCache
::linksccClearLinksTo( $oldid );
1135 # Record the just-created redirect's linking to the page
1136 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1138 # Non-existent target may have had broken links to it; these must
1139 # now be removed and made into good links.
1140 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1141 $update->fixBrokenLinks();
1143 # Purge old title from squid
1144 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1145 $titles = $nt->getLinksTo();
1146 if ( $wgUseSquid ) {
1147 $urls = $this->getSquidURLs();
1148 foreach ( $titles as $linkTitle ) {
1149 $urls[] = $linkTitle->getInternalURL();
1151 $u = new SquidUpdate( $urls );
1156 # Checks if $this can be moved to $nt
1157 # Selects for update, so don't call it unless you mean business
1158 function isValidMoveTarget( $nt ) {
1159 $fname = 'Title::isValidMoveTarget';
1160 $dbw =& wfGetDB( DB_MASTER
);
1163 $id = $nt->getArticleID();
1164 $obj = $dbw->getArray( 'cur', array( 'cur_is_redirect','cur_text' ),
1165 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1167 if ( !$obj ||
0 == $obj->cur_is_redirect
) {
1172 # Does the redirect point to the source?
1173 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text
, $m ) ) {
1174 $redirTitle = Title
::newFromText( $m[1] );
1175 if( !is_object( $redirTitle ) ||
1176 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1181 # Does the article have a history?
1182 $row = $dbw->getArray( 'old', array( 'old_id' ),
1184 'old_articleid' => $nt->getArticleID()
1185 ), $fname, 'FOR UPDATE'
1188 # Return true if there was no history
1189 return $row === false;
1192 # Create a redirect, fails if the title already exists, does not notify RC
1194 function createRedirect( $dest, $comment ) {
1196 if ( $this->getArticleID() ) {
1200 $fname = 'Title::createRedirect';
1201 $dbw =& wfGetDB( DB_MASTER
);
1202 $now = wfTimestampNow();
1203 $won = wfInvertTimestamp( $now );
1204 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1206 $dbw->insertArray( 'cur', array(
1207 'cur_id' => $seqVal,
1208 'cur_namespace' => $this->getNamespace(),
1209 'cur_title' => $this->getDBkey(),
1210 'cur_comment' => $comment,
1211 'cur_user' => $wgUser->getID(),
1212 'cur_user_text' => $wgUser->getName(),
1213 'cur_timestamp' => $now,
1214 'inverse_timestamp' => $won,
1215 'cur_touched' => $now,
1216 'cur_is_redirect' => 1,
1218 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1220 $newid = $dbw->insertId();
1221 $this->resetArticleID( $newid );
1224 if ( $dest->getArticleID() ) {
1225 $dbw->insertArray( 'links',
1227 'l_to' => $dest->getArticleID(),
1232 $dbw->insertArray( 'brokenlinks',
1234 'bl_to' => $dest->getPrefixedDBkey(),
1240 Article
::onArticleCreate( $this );
1244 # Get categories to wich belong this title and return an array of
1246 # Return an array of parents in the form:
1247 # $parent => $currentarticle
1248 function getParentCategories() {
1249 global $wgContLang,$wgUser;
1251 $titlekey = $this->getArticleId();
1252 $sk =& $wgUser->getSkin();
1254 $dbr =& wfGetDB( DB_SLAVE
);
1255 $cur = $dbr->tableName( 'cur' );
1256 $categorylinks = $dbr->tableName( 'categorylinks' );
1259 $sql = "SELECT * FROM categorylinks"
1260 ." WHERE cl_from='$titlekey'"
1261 ." AND cl_from <> '0'"
1262 ." ORDER BY cl_sortkey";
1264 $res = $dbr->query ( $sql ) ;
1266 if($dbr->numRows($res) > 0) {
1267 while ( $x = $dbr->fetchObject ( $res ) )
1268 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1269 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1270 $dbr->freeResult ( $res ) ;
1277 # Go through all parents
1278 function getCategorieBrowser() {
1279 $parents = $this->getParentCategories();
1281 if($parents != '') {
1282 foreach($parents as $parent => $current)
1284 $nt = Title
::newFromText($parent);
1285 $stack[$parent] = $nt->getCategorieBrowser();
1294 # Returns an associative array for selecting this title from cur
1295 function curCond() {
1296 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1299 function oldCond() {
1300 #return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );
1301 return array( 'old_articleid' => $this->getArticleID() );