9 require_once( 'normal/UtfNormal.php' );
14 $wgTitleInterwikiCache = array();
15 define ( 'GAID_FOR_UPDATE', 1 );
19 * - Represents a title, which may contain an interwiki designation or namespace
20 * - Can fetch various kinds of data from the database, albeit inefficiently.
22 * @todo migrate comments to phpdoc format
26 # All member variables should be considered private
27 # Please use the accessor functions
29 var $mTextform; # Text form (spaces not underscores) of the main part
30 var $mUrlform; # URL-encoded form of the main part
31 var $mDbkeyform; # Main part with underscores
32 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
33 var $mInterwiki; # Interwiki prefix (or null string)
34 var $mFragment; # Title fragment (i.e. the bit after the #)
35 var $mArticleID; # Article ID, fetched from the link cache on demand
36 var $mRestrictions; # Array of groups allowed to edit this article
37 # Only null or "sysop" are supported
38 var $mRestrictionsLoaded; # Boolean for initialisation on demand
39 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
40 var $mDefaultNamespace; # Namespace index when there is no namespace
41 # Zero except in {{transclusion}} tags
43 #----------------------------------------------------------------------------
45 #----------------------------------------------------------------------------
47 /* private */ function Title() {
48 $this->mInterwiki
= $this->mUrlform
=
49 $this->mTextform
= $this->mDbkeyform
= '';
50 $this->mArticleID
= -1;
51 $this->mNamespace
= 0;
52 $this->mRestrictionsLoaded
= false;
53 $this->mRestrictions
= array();
54 $this->mDefaultNamespace
= 0;
57 # From a prefixed DB key
58 /* static */ function newFromDBkey( $key ) {
60 $t->mDbkeyform
= $key;
61 if( $t->secureAndSplit() )
67 # From text, such as what you would find in a link
68 /* static */ function newFromText( $text, $defaultNamespace = 0 ) {
69 $fname = 'Title::newFromText';
70 wfProfileIn( $fname );
72 if( is_object( $text ) ) {
73 wfDebugDieBacktrace( 'Called with object instead of string.' );
75 global $wgInputEncoding;
76 $text = do_html_entity_decode( $text, ENT_COMPAT
, $wgInputEncoding );
78 $text = wfMungeToUtf8( $text );
81 # What was this for? TS 2004-03-03
82 # $text = urldecode( $text );
85 $t->mDbkeyform
= str_replace( ' ', '_', $text );
86 $t->mDefaultNamespace
= $defaultNamespace;
88 wfProfileOut( $fname );
89 if ( !is_object( $t ) ) {
90 var_dump( debug_backtrace() );
92 if( $t->secureAndSplit() ) {
99 # From a URL-encoded title
100 /* static */ function newFromURL( $url ) {
101 global $wgLang, $wgServer;
104 # For compatibility with old buggy URLs. "+" is not valid in titles,
105 # but some URLs used it as a space replacement and they still come
106 # from some external search tools.
107 $s = str_replace( '+', ' ', $url );
109 # For links that came from outside, check for alternate/legacy
110 # character encoding.
111 wfDebug( "Servr: $wgServer\n" );
112 if( empty( $_SERVER['HTTP_REFERER'] ) ||
113 strncmp($wgServer, $_SERVER['HTTP_REFERER'], strlen( $wgServer ) ) )
115 $s = $wgLang->checkTitleEncoding( $s );
117 wfDebug( "Refer: {$_SERVER['HTTP_REFERER']}\n" );
120 $t->mDbkeyform
= str_replace( ' ', '_', $s );
121 if( $t->secureAndSplit() ) {
122 # check that length of title is < cur_title size
123 $dbr =& wfGetDB( DB_SLAVE
);
124 $maxSize = $dbr->textFieldSize( 'cur', 'cur_title' );
125 if ( $maxSize != -1 && strlen( $t->mDbkeyform
) > $maxSize ) {
136 # This is inefficiently implemented, the cur row is requested but not
137 # used for anything else
138 /* static */ function newFromID( $id ) {
139 $fname = 'Title::newFromID';
140 $dbr =& wfGetDB( DB_SLAVE
);
141 $row = $dbr->getArray( 'cur', array( 'cur_namespace', 'cur_title' ),
142 array( 'cur_id' => $id ), $fname );
143 if ( $row !== false ) {
144 $title = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
151 # From a namespace index and a DB key.
152 # It's assumed that $ns and $title are *valid*, for instance when
153 # they came directly from the database or a special page name.
154 /* static */ function &makeTitle( $ns, $title ) {
158 $t->mNamespace
= $ns;
159 $t->mDbkeyform
= $title;
160 $t->mArticleID
= ( $ns >= 0 ) ?
0 : -1;
161 $t->mUrlform
= wfUrlencode( $title );
162 $t->mTextform
= str_replace( '_', ' ', $title );
166 # From a namespace index and a DB key.
167 # These will be checked for validity, which is a bit slower
168 # than makeTitle() but safer for user-provided data.
169 /* static */ function makeTitleSafe( $ns, $title ) {
171 $t->mDbkeyform
= Title
::makeName( $ns, $title );
172 if( $t->secureAndSplit() ) {
179 /* static */ function newMainPage() {
180 return Title
::newFromText( wfMsg( 'mainpage' ) );
183 # Get the title object for a redirect
184 # Returns NULL if the text is not a valid redirect
185 /* static */ function newFromRedirect( $text ) {
188 if ( $wgMwRedir->matchStart( $text ) ) {
189 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/', $text, $m ) ) {
190 # categories are escaped using : for example one can enter:
191 # #REDIRECT [[:Category:Music]]. Need to remove it.
192 if ( substr($m[1],0,1) == ':') {
193 # We don't want to keep the ':'
194 $m[1] = substr( $m[1], 1 );
197 $rt = Title
::newFromText( $m[1] );
203 #----------------------------------------------------------------------------
205 #----------------------------------------------------------------------------
207 # Get the prefixed DB key associated with an ID
208 /* static */ function nameOf( $id ) {
209 $fname = 'Title::nameOf';
210 $dbr =& wfGetDB( DB_SLAVE
);
212 $s = $dbr->getArray( 'cur', array( 'cur_namespace','cur_title' ), array( 'cur_id' => $id ), $fname );
213 if ( $s === false ) { return NULL; }
215 $n = Title
::makeName( $s->cur_namespace
, $s->cur_title
);
219 # Get a regex character class describing the legal characters in a link
220 /* static */ function legalChars() {
221 # Missing characters:
222 # * []|# Needed for link syntax
223 # * % and + are corrupted by Apache when they appear in the path
225 # % seems to work though
227 # The problem with % is that URLs are double-unescaped: once by Apache's
228 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
229 # Our code does not double-escape to compensate for this, indeed double escaping
230 # would break if the double-escaped title was passed in the query string
231 # rather than the path. This is a minor security issue because articles can be
232 # created such that they are hard to view or edit. -- TS
234 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
235 # this breaks interlanguage links
237 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z{}~\\x80-\\xFF";
241 # Returns a stripped-down a title string ready for the search index
242 # Takes a namespace index and a text-form main part
243 /* static */ function indexTitle( $ns, $title ) {
244 global $wgDBminWordLen, $wgLang;
245 require_once( 'SearchEngine.php' );
247 $lc = SearchEngine
::legalSearchChars() . '&#;';
248 $t = $wgLang->stripForSearch( $title );
249 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
250 $t = strtolower( $t );
253 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
254 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
256 $t = preg_replace( "/\\s+/", ' ', $t );
258 if ( $ns == Namespace::getImage() ) {
259 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
264 # Make a prefixed DB key from a DB key and a namespace index
265 /* static */ function makeName( $ns, $title ) {
268 $n = $wgLang->getNsText( $ns );
269 if ( '' == $n ) { return $title; }
270 else { return $n.':'.$title; }
274 # Returns the URL associated with an interwiki prefix
275 # The URL contains $1, which is replaced by the title
276 function getInterwikiLink( $key ) {
277 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
278 $fname = 'Title::getInterwikiLink';
279 $k = $wgDBname.':interwiki:'.$key;
281 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
282 return $wgTitleInterwikiCache[$k]->iw_url
;
284 $s = $wgMemc->get( $k );
285 # Ignore old keys with no iw_local
286 if( $s && isset( $s->iw_local
) ) {
287 $wgTitleInterwikiCache[$k] = $s;
290 $dbr =& wfGetDB( DB_SLAVE
);
291 $res = $dbr->select( 'interwiki', array( 'iw_url', 'iw_local' ), array( 'iw_prefix' => $key ), $fname );
294 $s = $dbr->fetchObject( $res );
296 # Cache non-existence: create a blank object and save it to memcached
301 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
302 $wgTitleInterwikiCache[$k] = $s;
307 global $wgTitleInterwikiCache, $wgDBname;
309 if ( $this->mInterwiki
!= '' ) {
310 # Make sure key is loaded into cache
311 $this->getInterwikiLink( $this->mInterwiki
);
312 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
313 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
319 # Update the cur_touched field for an array of title objects
320 # Inefficient unless the IDs are already loaded into the link cache
321 /* static */ function touchArray( $titles, $timestamp = '' ) {
322 if ( count( $titles ) == 0 ) {
325 if ( $timestamp == '' ) {
326 $timestamp = wfTimestampNow();
328 $dbw =& wfGetDB( DB_MASTER
);
329 $cur = $dbw->tableName( 'cur' );
330 $sql = "UPDATE $cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
333 foreach ( $titles as $title ) {
338 $sql .= $title->getArticleID();
342 $dbw->query( $sql, 'Title::touchArray' );
346 #----------------------------------------------------------------------------
348 #----------------------------------------------------------------------------
351 # See the definitions at the top of this file
353 function getText() { return $this->mTextform
; }
354 function getPartialURL() { return $this->mUrlform
; }
355 function getDBkey() { return $this->mDbkeyform
; }
356 function getNamespace() { return $this->mNamespace
; }
357 function setNamespace( $n ) { $this->mNamespace
= $n; }
358 function getInterwiki() { return $this->mInterwiki
; }
359 function getFragment() { return $this->mFragment
; }
360 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
362 # Get title for search index
363 function getIndexTitle() {
364 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
367 # Get prefixed title with underscores
368 function getPrefixedDBkey() {
369 $s = $this->prefix( $this->mDbkeyform
);
370 $s = str_replace( ' ', '_', $s );
374 # Get prefixed title with spaces
375 # This is the form usually used for display
376 function getPrefixedText() {
377 if ( empty( $this->mPrefixedText
) ) {
378 $s = $this->prefix( $this->mTextform
);
379 $s = str_replace( '_', ' ', $s );
380 $this->mPrefixedText
= $s;
382 return $this->mPrefixedText
;
385 # As getPrefixedText(), plus fragment.
386 function getFullText() {
387 $text = $this->getPrefixedText();
388 if( '' != $this->mFragment
) {
389 $text .= '#' . $this->mFragment
;
394 # Get a URL-encoded title (not an actual URL) including interwiki
395 function getPrefixedURL() {
396 $s = $this->prefix( $this->mDbkeyform
);
397 $s = str_replace( ' ', '_', $s );
399 $s = wfUrlencode ( $s ) ;
401 # Cleaning up URL to make it look nice -- is this safe?
402 $s = preg_replace( '/%3[Aa]/', ':', $s );
403 $s = preg_replace( '/%2[Ff]/', '/', $s );
404 $s = str_replace( '%28', '(', $s );
405 $s = str_replace( '%29', ')', $s );
410 # Get a real URL referring to this title, with interwiki link and fragment
411 function getFullURL( $query = '' ) {
412 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
414 if ( '' == $this->mInterwiki
) {
416 return $wgServer . $this->getLocalUrl( $query );
418 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
419 $namespace = $wgLang->getNsText( $this->mNamespace
);
420 if ( '' != $namespace ) {
421 # Can this actually happen? Interwikis shouldn't be parsed.
424 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
425 if ( '' != $this->mFragment
) {
426 $url .= '#' . $this->mFragment
;
432 # Get a URL with an optional query string, no fragment
433 # * If $query=="", it will use $wgArticlePath
434 # * Returns a full for an interwiki link, loses any query string
435 # * Optionally adds the server and escapes for HTML
436 # * Setting $query to "-" makes an old-style URL with nothing in the
437 # query except a title
440 die( 'Call to obsolete obsolete function Title::getURL()' );
443 function getLocalURL( $query = '' ) {
444 global $wgLang, $wgArticlePath, $wgScript;
446 if ( $this->isExternal() ) {
447 return $this->getFullURL();
450 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
451 if ( $query == '' ) {
452 $url = str_replace( '$1', $dbkey, $wgArticlePath );
454 if ( $query == '-' ) {
457 if ( $wgScript != '' ) {
458 $url = "{$wgScript}?title={$dbkey}&{$query}";
461 $url = "/{$dbkey}?{$query}";
467 function escapeLocalURL( $query = '' ) {
468 return htmlspecialchars( $this->getLocalURL( $query ) );
471 function escapeFullURL( $query = '' ) {
472 return htmlspecialchars( $this->getFullURL( $query ) );
475 function getInternalURL( $query = '' ) {
476 # Used in various Squid-related code, in case we have a different
477 # internal hostname for the server than the exposed one.
478 global $wgInternalServer;
479 return $wgInternalServer . $this->getLocalURL( $query );
482 # Get the edit URL, or a null string if it is an interwiki link
483 function getEditURL() {
484 global $wgServer, $wgScript;
486 if ( '' != $this->mInterwiki
) { return ''; }
487 $s = $this->getLocalURL( 'action=edit' );
492 # Get HTML-escaped displayable text
493 # For the title field in <a> tags
494 function getEscapedText() {
495 return htmlspecialchars( $this->getPrefixedText() );
498 # Is the title interwiki?
499 function isExternal() { return ( '' != $this->mInterwiki
); }
501 # Does the title correspond to a protected article?
502 function isProtected() {
503 if ( -1 == $this->mNamespace
) { return true; }
504 $a = $this->getRestrictions();
505 if ( in_array( 'sysop', $a ) ) { return true; }
509 # Is the page a log page, i.e. one where the history is messed up by
510 # LogPage.php? This used to be used for suppressing diff links in recent
511 # changes, but now that's done by setting a flag in the recentchanges
512 # table. Hence, this probably is no longer used.
514 if ( $this->mNamespace
!= Namespace::getWikipedia() ) {
517 if ( ( 0 == strcmp( wfMsg( 'uploadlogpage' ), $this->mDbkeyform
) ) ||
518 ( 0 == strcmp( wfMsg( 'dellogpage' ), $this->mDbkeyform
) ) ) {
524 # Is $wgUser is watching this page?
525 function userIsWatching() {
528 if ( -1 == $this->mNamespace
) { return false; }
529 if ( 0 == $wgUser->getID() ) { return false; }
531 return $wgUser->isWatched( $this );
534 # Can $wgUser edit this page?
535 function userCanEdit() {
537 if ( -1 == $this->mNamespace
) { return false; }
538 if ( NS_MEDIAWIKI
== $this->mNamespace
&& !$wgUser->isSysop() ) { return false; }
539 # if ( 0 == $this->getArticleID() ) { return false; }
540 if ( $this->mDbkeyform
== '_' ) { return false; }
541 # protect global styles and js
542 if ( NS_MEDIAWIKI
== $this->mNamespace
543 && preg_match("/\\.(css|js)$/", $this->mTextform
)
544 && !$wgUser->isSysop() )
546 //if ( $this->isCssJsSubpage() and !$this->userCanEditCssJsSubpage() ) { return false; }
547 # protect css/js subpages of user pages
548 # XXX: this might be better using restrictions
549 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
550 if( Namespace::getUser() == $this->mNamespace
551 and preg_match("/\\.(css|js)$/", $this->mTextform
)
552 and !$wgUser->isSysop()
553 and !preg_match('/^'.preg_quote($wgUser->getName(), '/').'/', $this->mTextform
) )
555 $ur = $wgUser->getRights();
556 foreach ( $this->getRestrictions() as $r ) {
557 if ( '' != $r && ( ! in_array( $r, $ur ) ) ) {
564 function userCanRead() {
566 global $wgWhitelistRead;
568 if( 0 != $wgUser->getID() ) return true;
569 if( !is_array( $wgWhitelistRead ) ) return true;
571 $name = $this->getPrefixedText();
572 if( in_array( $name, $wgWhitelistRead ) ) return true;
574 # Compatibility with old settings
575 if( $this->getNamespace() == NS_MAIN
) {
576 if( in_array( ':' . $name, $wgWhitelistRead ) ) return true;
581 function isCssJsSubpage() {
582 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
584 function isCssSubpage() {
585 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
587 function isJsSubpage() {
588 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
590 function userCanEditCssJsSubpage() {
591 # protect css/js subpages of user pages
592 # XXX: this might be better using restrictions
594 return ( $wgUser->isSysop() or preg_match('/^'.preg_quote($wgUser->getName()).'/', $this->mTextform
) );
597 # Accessor/initialisation for mRestrictions
598 function getRestrictions() {
599 $id = $this->getArticleID();
600 if ( 0 == $id ) { return array(); }
602 if ( ! $this->mRestrictionsLoaded
) {
603 $dbr =& wfGetDB( DB_SLAVE
);
604 $res = $dbr->getField( 'cur', 'cur_restrictions', 'cur_id='.$id );
605 $this->mRestrictions
= explode( ',', trim( $res ) );
606 $this->mRestrictionsLoaded
= true;
608 return $this->mRestrictions
;
611 # Is there a version of this page in the deletion archive?
612 # Returns the number of archived revisions
613 function isDeleted() {
614 $fname = 'Title::isDeleted';
615 $dbr =& wfGetDB( DB_SLAVE
);
616 $n = $dbr->getField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
617 'ar_title' => $this->getDBkey() ), $fname );
621 # Get the article ID from the link cache
622 # $flags is a bit field, may be GAID_FOR_UPDATE to select for update
623 function getArticleID( $flags = 0 ) {
626 if ( $flags & GAID_FOR_UPDATE
) {
627 $oldUpdate = $wgLinkCache->forUpdate( true );
628 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
629 $wgLinkCache->forUpdate( $oldUpdate );
631 if ( -1 == $this->mArticleID
) {
632 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
635 return $this->mArticleID
;
638 # This clears some fields in this object, and clears any associated keys in the
639 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
640 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
641 function resetArticleID( $newid ) {
643 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
645 if ( 0 == $newid ) { $this->mArticleID
= -1; }
646 else { $this->mArticleID
= $newid; }
647 $this->mRestrictionsLoaded
= false;
648 $this->mRestrictions
= array();
651 # Updates cur_touched
652 # Called from LinksUpdate.php
653 function invalidateCache() {
654 $now = wfTimestampNow();
655 $dbw =& wfGetDB( DB_MASTER
);
656 $success = $dbw->updateArray( 'cur',
658 'cur_touched' => wfTimestampNow()
659 ), array( /* WHERE */
660 'cur_namespace' => $this->getNamespace() ,
661 'cur_title' => $this->getDBkey()
662 ), 'Title::invalidateCache'
667 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
668 /* private */ function prefix( $name ) {
672 if ( '' != $this->mInterwiki
) {
673 $p = $this->mInterwiki
. ':';
675 if ( 0 != $this->mNamespace
) {
676 $p .= $wgLang->getNsText( $this->mNamespace
) . ':';
681 # Secure and split - main initialisation function for this object
683 # Assumes that mDbkeyform has been set, and is urldecoded
684 # and uses underscores, but not otherwise munged. This function
685 # removes illegal characters, splits off the interwiki and
686 # namespace prefixes, sets the other forms, and canonicalizes
689 /* private */ function secureAndSplit()
691 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
692 $fname = 'Title::secureAndSplit';
693 wfProfileIn( $fname );
695 static $imgpre = false;
696 static $rxTc = false;
699 if ( $imgpre === false ) {
700 $imgpre = ':' . $wgLang->getNsText( Namespace::getImage() ) . ':';
701 # % is needed as well
702 $rxTc = '/[^' . Title
::legalChars() . ']/';
705 $this->mInterwiki
= $this->mFragment
= '';
706 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
708 # Clean up whitespace
710 $t = preg_replace( "/[\\s_]+/", '_', $this->mDbkeyform
);
711 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
714 wfProfileOut( $fname );
719 if( !$wgUseLatin1 && false !== strpos( $t, UTF8_REPLACEMENT
) ) {
720 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
721 wfProfileOut( $fname );
725 $this->mDbkeyform
= $t;
729 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
730 $t = substr( $t, 1 );
733 # Initial colon indicating main namespace
734 if ( ':' == $t{0} ) {
735 $r = substr( $t, 1 );
736 $this->mNamespace
= NS_MAIN
;
738 # Namespace or interwiki prefix
739 if ( preg_match( "/^(.+?)_*:_*(.*)$/", $t, $m ) ) {
740 #$p = strtolower( $m[1] );
742 $lowerNs = strtolower( $p );
743 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
744 # Canonical namespace
746 $this->mNamespace
= $ns;
747 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
750 $this->mNamespace
= $ns;
751 } elseif ( $this->getInterwikiLink( $p ) ) {
754 $this->mInterwiki
= $p;
756 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
758 } elseif($this->mInterwiki
!= $wgLocalInterwiki) {
766 # Redundant interwiki prefix to the local wiki
767 if ( 0 == strcmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
768 $this->mInterwiki
= '';
770 # We already know that some pages won't be in the database!
772 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
773 $this->mArticleID
= 0;
775 $f = strstr( $r, '#' );
776 if ( false !== $f ) {
777 $this->mFragment
= substr( $f, 1 );
778 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
781 # Reject illegal characters.
783 if( preg_match( $rxTc, $r ) ) {
784 wfProfileOut( $fname );
788 # "." and ".." conflict with the directories of those namesa
789 if ( strpos( $r, '.' ) !== false &&
790 ( $r === '.' ||
$r === '..' ||
791 strpos( $r, './' ) === 0 ||
792 strpos( $r, '../' ) === 0 ||
793 strpos( $r, '/./' ) !== false ||
794 strpos( $r, '/../' ) !== false ) )
796 wfProfileOut( $fname );
800 # Initial capital letter
801 if( $wgCapitalLinks && $this->mInterwiki
== '') {
802 $t = $wgLang->ucfirst( $r );
808 $this->mDbkeyform
= $t;
809 $this->mUrlform
= wfUrlencode( $t );
811 $this->mTextform
= str_replace( '_', ' ', $t );
813 wfProfileOut( $fname );
817 # Get a title object associated with the talk page of this article
818 function getTalkPage() {
819 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
822 # Get a title object associated with the subject page of this talk page
823 function getSubjectPage() {
824 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
827 # Get an array of Title objects linking to this title
828 # Also stores the IDs in the link cache
829 # $options may be FOR UPDATE
830 function getLinksTo( $options = '' ) {
832 $id = $this->getArticleID();
835 $db =& wfGetDB( DB_MASTER
);
837 $db =& wfGetDB( DB_SLAVE
);
839 $cur = $db->tableName( 'cur' );
840 $links = $db->tableName( 'links' );
842 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $cur,$links WHERE l_from=cur_id AND l_to={$id} $options";
843 $res = $db->query( $sql, 'Title::getLinksTo' );
845 if ( $db->numRows( $res ) ) {
846 while ( $row = $db->fetchObject( $res ) ) {
847 if ( $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
) ) {
848 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
849 $retVal[] = $titleObj;
853 $db->freeResult( $res );
857 # Get an array of Title objects linking to this non-existent title
858 # Also stores the IDs in the link cache
859 function getBrokenLinksTo( $options = '' ) {
863 $db =& wfGetDB( DB_MASTER
);
865 $db =& wfGetDB( DB_SLAVE
);
867 $cur = $db->tableName( 'cur' );
868 $brokenlinks = $db->tableName( 'brokenlinks' );
869 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
871 $sql = "SELECT cur_namespace,cur_title,cur_id FROM $brokenlinks,$cur " .
872 "WHERE bl_from=cur_id AND bl_to='$encTitle' $options";
873 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
875 if ( $db->numRows( $res ) ) {
876 while ( $row = $db->fetchObject( $res ) ) {
877 $titleObj = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
878 $wgLinkCache->addGoodLink( $row->cur_id
, $titleObj->getPrefixedDBkey() );
879 $retVal[] = $titleObj;
882 $db->freeResult( $res );
886 function getSquidURLs() {
888 $this->getInternalURL(),
889 $this->getInternalURL( 'action=history' )
893 function moveNoAuth( &$nt ) {
894 return $this->moveTo( $nt, false );
897 # Move a title to a new location
898 # Returns true on success, message name on failure
899 # auth indicates whether wgUser's permissions should be checked
900 function moveTo( &$nt, $auth = true ) {
901 if( !$this or !$nt ) {
902 return 'badtitletext';
905 $fname = 'Title::move';
906 $oldid = $this->getArticleID();
907 $newid = $nt->getArticleID();
909 if ( strlen( $nt->getDBkey() ) < 1 ) {
910 return 'articleexists';
912 if ( ( ! Namespace::isMovable( $this->getNamespace() ) ) ||
913 ( '' == $this->getDBkey() ) ||
914 ( '' != $this->getInterwiki() ) ||
916 ( ! Namespace::isMovable( $nt->getNamespace() ) ) ||
917 ( '' == $nt->getDBkey() ) ||
918 ( '' != $nt->getInterwiki() ) ) {
919 return 'badarticleerror';
922 if ( $auth && ( !$this->userCanEdit() ||
!$nt->userCanEdit() ) ) {
923 return 'protectedpage';
926 # The move is allowed only if (1) the target doesn't exist, or
927 # (2) the target is a redirect to the source, and has no history
928 # (so we can undo bad moves right after they're done).
930 if ( 0 != $newid ) { # Target exists; check for validity
931 if ( ! $this->isValidMoveTarget( $nt ) ) {
932 return 'articleexists';
934 $this->moveOverExistingRedirect( $nt );
935 } else { # Target didn't exist, do normal move.
936 $this->moveToNewTitle( $nt, $newid );
939 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
941 $dbw =& wfGetDB( DB_MASTER
);
942 $sql = "UPDATE categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
943 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
944 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
945 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
949 $oldnamespace = $this->getNamespace() & ~
1;
950 $newnamespace = $nt->getNamespace() & ~
1;
951 $oldtitle = $this->getDBkey();
952 $newtitle = $nt->getDBkey();
954 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
955 WatchedItem
::duplicateEntries( $this, $nt );
958 # Update search engine
959 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
961 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
967 # Move page to title which is presently a redirect to the source page
969 /* private */ function moveOverExistingRedirect( &$nt ) {
970 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
971 $fname = 'Title::moveOverExistingRedirect';
972 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
974 $now = wfTimestampNow();
975 $won = wfInvertTimestamp( $now );
976 $newid = $nt->getArticleID();
977 $oldid = $this->getArticleID();
978 $dbw =& wfGetDB( DB_MASTER
);
979 $links = $dbw->tableName( 'links' );
981 # Change the name of the target page:
982 $dbw->updateArray( 'cur',
984 'cur_touched' => $now,
985 'cur_namespace' => $nt->getNamespace(),
986 'cur_title' => $nt->getDBkey()
988 /* WHERE */ array( 'cur_id' => $oldid ),
991 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
993 # Repurpose the old redirect. We don't save it to history since
994 # by definition if we've got here it's rather uninteresting.
996 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
997 $dbw->updateArray( 'cur',
999 'cur_touched' => $now,
1000 'cur_timestamp' => $now,
1001 'inverse_timestamp' => $won,
1002 'cur_namespace' => $this->getNamespace(),
1003 'cur_title' => $this->getDBkey(),
1004 'cur_text' => $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n",
1005 'cur_comment' => $comment,
1006 'cur_user' => $wgUser->getID(),
1007 'cur_minor_edit' => 0,
1009 'cur_restrictions' => '',
1010 'cur_user_text' => $wgUser->getName(),
1011 'cur_is_redirect' => 1,
1014 /* WHERE */ array( 'cur_id' => $newid ),
1018 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1020 # Fix the redundant names for the past revisions of the target page.
1021 # The redirect should have no old revisions.
1025 'old_namespace' => $nt->getNamespace(),
1026 'old_title' => $nt->getDBkey(),
1029 'old_namespace' => $this->getNamespace(),
1030 'old_title' => $this->getDBkey(),
1035 RecentChange
::notifyMoveOverRedirect( $now, $this, $nt, $wgUser, $comment );
1039 # Load titles and IDs
1040 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1041 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1044 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1045 $dbw->query( $sql, $fname );
1048 if ( count( $linksToOld ) ||
count( $linksToNew )) {
1049 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1052 # Insert links to old title
1053 foreach ( $linksToOld as $linkTitle ) {
1059 $id = $linkTitle->getArticleID();
1060 $sql .= "($id,$newid)";
1063 # Insert links to new title
1064 foreach ( $linksToNew as $linkTitle ) {
1070 $id = $linkTitle->getArticleID();
1071 $sql .= "($id, $oldid)";
1074 $dbw->query( $sql, DB_MASTER
, $fname );
1077 # Now, we record the link from the redirect to the new title.
1078 # It should have no other outgoing links...
1079 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1080 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1083 LinkCache
::linksccClearLinksTo( $oldid );
1084 LinkCache
::linksccClearLinksTo( $newid );
1087 if ( $wgUseSquid ) {
1088 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1089 $u = new SquidUpdate( $urls );
1094 # Move page to non-existing title.
1095 # Sets $newid to be the new article ID
1097 /* private */ function moveToNewTitle( &$nt, &$newid ) {
1098 global $wgUser, $wgLinkCache, $wgUseSquid;
1099 $fname = 'MovePageForm::moveToNewTitle';
1100 $comment = wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1102 $now = wfTimestampNow();
1103 $won = wfInvertTimestamp( $now );
1104 $newid = $nt->getArticleID();
1105 $oldid = $this->getArticleID();
1106 $dbw =& wfGetDB( DB_MASTER
);
1109 $dbw->updateArray( 'cur',
1111 'cur_touched' => $now,
1112 'cur_namespace' => $nt->getNamespace(),
1113 'cur_title' => $nt->getDBkey()
1115 /* WHERE */ array( 'cur_id' => $oldid ),
1119 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1122 $dbw->insertArray( 'cur', array(
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,
1133 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1135 $newid = $dbw->insertId();
1136 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1138 # Rename old entries
1142 'old_namespace' => $nt->getNamespace(),
1143 'old_title' => $nt->getDBkey()
1146 'old_namespace' => $this->getNamespace(),
1147 'old_title' => $this->getDBkey()
1152 RecentChange
::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1154 # Purge squid and linkscc as per article creation
1155 Article
::onArticleCreate( $nt );
1157 # Any text links to the old title must be reassigned to the redirect
1158 $dbw->updateArray( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1159 LinkCache
::linksccClearLinksTo( $oldid );
1161 # Record the just-created redirect's linking to the page
1162 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1164 # Non-existent target may have had broken links to it; these must
1165 # now be removed and made into good links.
1166 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1167 $update->fixBrokenLinks();
1169 # Purge old title from squid
1170 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1171 $titles = $nt->getLinksTo();
1172 if ( $wgUseSquid ) {
1173 $urls = $this->getSquidURLs();
1174 foreach ( $titles as $linkTitle ) {
1175 $urls[] = $linkTitle->getInternalURL();
1177 $u = new SquidUpdate( $urls );
1182 # Checks if $this can be moved to $nt
1183 # Selects for update, so don't call it unless you mean business
1184 function isValidMoveTarget( $nt ) {
1185 $fname = 'Title::isValidMoveTarget';
1186 $dbw =& wfGetDB( DB_MASTER
);
1189 $id = $nt->getArticleID();
1190 $obj = $dbw->getArray( 'cur', array( 'cur_is_redirect','cur_text' ),
1191 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1193 if ( !$obj ||
0 == $obj->cur_is_redirect
) {
1198 # Does the redirect point to the source?
1199 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text
, $m ) ) {
1200 $redirTitle = Title
::newFromText( $m[1] );
1201 if( !is_object( $redirTitle ) ||
1202 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1207 # Does the article have a history?
1208 $row = $dbw->getArray( 'old', array( 'old_id' ),
1210 'old_namespace' => $nt->getNamespace(),
1211 'old_title' => $nt->getDBkey()
1212 ), $fname, 'FOR UPDATE'
1215 # Return true if there was no history
1216 return $row === false;
1219 # Create a redirect, fails if the title already exists, does not notify RC
1221 function createRedirect( $dest, $comment ) {
1223 if ( $this->getArticleID() ) {
1227 $fname = 'Title::createRedirect';
1228 $dbw =& wfGetDB( DB_MASTER
);
1229 $now = wfTimestampNow();
1230 $won = wfInvertTimestamp( $now );
1231 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1233 $dbw->insertArray( 'cur', array(
1234 'cur_id' => $seqVal,
1235 'cur_namespace' => $this->getNamespace(),
1236 'cur_title' => $this->getDBkey(),
1237 'cur_comment' => $comment,
1238 'cur_user' => $wgUser->getID(),
1239 'cur_user_text' => $wgUser->getName(),
1240 'cur_timestamp' => $now,
1241 'inverse_timestamp' => $won,
1242 'cur_touched' => $now,
1243 'cur_is_redirect' => 1,
1245 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1247 $newid = $dbw->insertId();
1248 $this->resetArticleID( $newid );
1251 if ( $dest->getArticleID() ) {
1252 $dbw->insertArray( 'links',
1254 'l_to' => $dest->getArticleID(),
1259 $dbw->insertArray( 'brokenlinks',
1261 'bl_to' => $dest->getPrefixedDBkey(),
1267 Article
::onArticleCreate( $this );
1271 # Get categories to wich belong this title and return an array of
1273 # Return an array of parents in the form:
1274 # $parent => $currentarticle
1275 function getParentCategories() {
1276 global $wgLang,$wgUser;
1278 $titlekey = $this->getArticleId();
1279 $sk =& $wgUser->getSkin();
1281 $dbr =& wfGetDB( DB_SLAVE
);
1282 $cur = $dbr->tableName( 'cur' );
1283 $categorylinks = $dbr->tableName( 'categorylinks' );
1286 $sql = "SELECT * FROM categorylinks"
1287 ." WHERE cl_from='$titlekey'"
1288 ." AND cl_from <> '0'"
1289 ." ORDER BY cl_sortkey";
1291 $res = $dbr->query ( $sql ) ;
1293 if($dbr->numRows($res) > 0) {
1294 while ( $x = $dbr->fetchObject ( $res ) )
1295 //$data[] = Title::newFromText($wgLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1296 $data[$wgLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1297 $dbr->freeResult ( $res ) ;
1304 # Go through all parents
1305 function getCategorieBrowser() {
1306 $parents = $this->getParentCategories();
1308 if($parents != '') {
1309 foreach($parents as $parent => $current)
1311 $nt = Title
::newFromText($parent);
1312 $stack[$parent] = $nt->getCategorieBrowser();
1321 # Returns an associative array for selecting this title from cur
1322 function curCond() {
1323 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1326 function oldCond() {
1327 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);