7 require_once( 'normal/UtfNormal.php' );
12 $wgTitleInterwikiCache = array();
13 define ( 'GAID_FOR_UPDATE', 1 );
17 * - Represents a title, which may contain an interwiki designation or namespace
18 * - Can fetch various kinds of data from the database, albeit inefficiently.
20 * @todo migrate comments to phpdoc format
23 # All member variables should be considered private
24 # Please use the accessor functions
26 var $mTextform; # Text form (spaces not underscores) of the main part
27 var $mUrlform; # URL-encoded form of the main part
28 var $mDbkeyform; # Main part with underscores
29 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
30 var $mInterwiki; # Interwiki prefix (or null string)
31 var $mFragment; # Title fragment (i.e. the bit after the #)
32 var $mArticleID; # Article ID, fetched from the link cache on demand
33 var $mRestrictions; # Array of groups allowed to edit this article
34 # Only null or "sysop" are supported
35 var $mRestrictionsLoaded; # Boolean for initialisation on demand
36 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
37 var $mDefaultNamespace; # Namespace index when there is no namespace
38 # Zero except in {{transclusion}} tags
40 #----------------------------------------------------------------------------
42 #----------------------------------------------------------------------------
44 /* private */ function Title() {
45 $this->mInterwiki
= $this->mUrlform
=
46 $this->mTextform
= $this->mDbkeyform
= '';
47 $this->mArticleID
= -1;
48 $this->mNamespace
= 0;
49 $this->mRestrictionsLoaded
= false;
50 $this->mRestrictions
= array();
51 $this->mDefaultNamespace
= 0;
54 # From a prefixed DB key
55 /* static */ function newFromDBkey( $key ) {
57 $t->mDbkeyform
= $key;
58 if( $t->secureAndSplit() )
64 # From text, such as what you would find in a link
65 /* static */ function newFromText( $text, $defaultNamespace = 0 ) {
66 $fname = 'Title::newFromText';
67 wfProfileIn( $fname );
69 if( is_object( $text ) ) {
70 wfDebugDieBacktrace( 'Called with object instead of string.' );
72 global $wgInputEncoding;
73 $text = do_html_entity_decode( $text, ENT_COMPAT
, $wgInputEncoding );
75 $text = wfMungeToUtf8( $text );
78 # What was this for? TS 2004-03-03
79 # $text = urldecode( $text );
82 $t->mDbkeyform
= str_replace( ' ', '_', $text );
83 $t->mDefaultNamespace
= $defaultNamespace;
85 wfProfileOut( $fname );
86 if ( !is_object( $t ) ) {
87 var_dump( debug_backtrace() );
89 if( $t->secureAndSplit() ) {
96 # From a URL-encoded title
97 /* static */ function newFromURL( $url ) {
98 global $wgLang, $wgServer;
101 # For compatibility with old buggy URLs. "+" is not valid in titles,
102 # but some URLs used it as a space replacement and they still come
103 # from some external search tools.
104 $s = str_replace( '+', ' ', $url );
106 # For links that came from outside, check for alternate/legacy
107 # character encoding.
108 wfDebug( "Servr: $wgServer\n" );
109 if( empty( $_SERVER['HTTP_REFERER'] ) ||
110 strncmp($wgServer, $_SERVER['HTTP_REFERER'], strlen( $wgServer ) ) )
112 $s = $wgLang->checkTitleEncoding( $s );
114 wfDebug( "Refer: {$_SERVER['HTTP_REFERER']}\n" );
117 $t->mDbkeyform
= str_replace( ' ', '_', $s );
118 if( $t->secureAndSplit() ) {
119 # check that length of title is < cur_title size
120 $dbr =& wfGetDB( DB_SLAVE
);
121 $maxSize = $dbr->textFieldSize( 'cur', 'cur_title' );
122 if ( $maxSize != -1 && strlen( $t->mDbkeyform
) > $maxSize ) {
133 # This is inefficiently implemented, the cur row is requested but not
134 # used for anything else
135 /* static */ function newFromID( $id ) {
136 $fname = 'Title::newFromID';
137 $dbr =& wfGetDB( DB_SLAVE
);
138 $row = $dbr->getArray( 'cur', array( 'cur_namespace', 'cur_title' ),
139 array( 'cur_id' => $id ), $fname );
140 if ( $row !== false ) {
141 $title = Title
::makeTitle( $row->cur_namespace
, $row->cur_title
);
148 # From a namespace index and a DB key.
149 # It's assumed that $ns and $title are *valid*, for instance when
150 # they came directly from the database or a special page name.
151 /* static */ function &makeTitle( $ns, $title ) {
155 $t->mNamespace
= $ns;
156 $t->mDbkeyform
= $title;
157 $t->mArticleID
= ( $ns >= 0 ) ?
0 : -1;
158 $t->mUrlform
= wfUrlencode( $title );
159 $t->mTextform
= str_replace( '_', ' ', $title );
163 # From a namespace index and a DB key.
164 # These will be checked for validity, which is a bit slower
165 # than makeTitle() but safer for user-provided data.
166 /* static */ function makeTitleSafe( $ns, $title ) {
168 $t->mDbkeyform
= Title
::makeName( $ns, $title );
169 if( $t->secureAndSplit() ) {
176 /* static */ function newMainPage() {
177 return Title
::newFromText( wfMsg( 'mainpage' ) );
180 # Get the title object for a redirect
181 # Returns NULL if the text is not a valid redirect
182 /* static */ function newFromRedirect( $text ) {
185 if ( $wgMwRedir->matchStart( $text ) ) {
186 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/', $text, $m ) ) {
187 # categories are escaped using : for example one can enter:
188 # #REDIRECT [[:Category:Music]]. Need to remove it.
189 if ( substr($m[1],0,1) == ':') {
190 # We don't want to keep the ':'
191 $m[1] = substr( $m[1], 1 );
194 $rt = Title
::newFromText( $m[1] );
200 #----------------------------------------------------------------------------
202 #----------------------------------------------------------------------------
204 # Get the prefixed DB key associated with an ID
205 /* static */ function nameOf( $id ) {
206 $fname = 'Title::nameOf';
207 $dbr =& wfGetDB( DB_SLAVE
);
209 $s = $dbr->getArray( 'cur', array( 'cur_namespace','cur_title' ), array( 'cur_id' => $id ), $fname );
210 if ( $s === false ) { return NULL; }
212 $n = Title
::makeName( $s->cur_namespace
, $s->cur_title
);
216 # Get a regex character class describing the legal characters in a link
217 /* static */ function legalChars() {
218 # Missing characters:
219 # * []|# Needed for link syntax
220 # * % and + are corrupted by Apache when they appear in the path
222 # % seems to work though
224 # The problem with % is that URLs are double-unescaped: once by Apache's
225 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
226 # Our code does not double-escape to compensate for this, indeed double escaping
227 # would break if the double-escaped title was passed in the query string
228 # rather than the path. This is a minor security issue because articles can be
229 # created such that they are hard to view or edit. -- TS
231 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
232 # this breaks interlanguage links
234 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z{}~\\x80-\\xFF";
238 # Returns a stripped-down a title string ready for the search index
239 # Takes a namespace index and a text-form main part
240 /* static */ function indexTitle( $ns, $title ) {
241 global $wgDBminWordLen, $wgLang;
242 require_once( 'SearchEngine.php' );
244 $lc = SearchEngine
::legalSearchChars() . '&#;';
245 $t = $wgLang->stripForSearch( $title );
246 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
247 $t = strtolower( $t );
250 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
251 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
253 $t = preg_replace( "/\\s+/", ' ', $t );
255 if ( $ns == Namespace::getImage() ) {
256 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
261 # Make a prefixed DB key from a DB key and a namespace index
262 /* static */ function makeName( $ns, $title ) {
265 $n = $wgLang->getNsText( $ns );
266 if ( '' == $n ) { return $title; }
267 else { return $n.':'.$title; }
271 # Returns the URL associated with an interwiki prefix
272 # The URL contains $1, which is replaced by the title
273 function getInterwikiLink( $key ) {
274 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
275 $fname = 'Title::getInterwikiLink';
276 $k = $wgDBname.':interwiki:'.$key;
278 if( array_key_exists( $k, $wgTitleInterwikiCache ) )
279 return $wgTitleInterwikiCache[$k]->iw_url
;
281 $s = $wgMemc->get( $k );
282 # Ignore old keys with no iw_local
283 if( $s && isset( $s->iw_local
) ) {
284 $wgTitleInterwikiCache[$k] = $s;
287 $dbr =& wfGetDB( DB_SLAVE
);
288 $res = $dbr->select( 'interwiki', array( 'iw_url', 'iw_local' ), array( 'iw_prefix' => $key ), $fname );
291 $s = $dbr->fetchObject( $res );
293 # Cache non-existence: create a blank object and save it to memcached
298 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
299 $wgTitleInterwikiCache[$k] = $s;
304 global $wgTitleInterwikiCache, $wgDBname;
306 if ( $this->mInterwiki
!= '' ) {
307 # Make sure key is loaded into cache
308 $this->getInterwikiLink( $this->mInterwiki
);
309 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
310 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
316 # Update the cur_touched field for an array of title objects
317 # Inefficient unless the IDs are already loaded into the link cache
318 /* static */ function touchArray( $titles, $timestamp = '' ) {
319 if ( count( $titles ) == 0 ) {
322 if ( $timestamp == '' ) {
323 $timestamp = wfTimestampNow();
325 $dbw =& wfGetDB( DB_MASTER
);
326 $cur = $dbw->tableName( 'cur' );
327 $sql = "UPDATE $cur SET cur_touched='{$timestamp}' WHERE cur_id IN (";
330 foreach ( $titles as $title ) {
335 $sql .= $title->getArticleID();
339 $dbw->query( $sql, 'Title::touchArray' );
343 #----------------------------------------------------------------------------
345 #----------------------------------------------------------------------------
348 # See the definitions at the top of this file
350 function getText() { return $this->mTextform
; }
351 function getPartialURL() { return $this->mUrlform
; }
352 function getDBkey() { return $this->mDbkeyform
; }
353 function getNamespace() { return $this->mNamespace
; }
354 function setNamespace( $n ) { $this->mNamespace
= $n; }
355 function getInterwiki() { return $this->mInterwiki
; }
356 function getFragment() { return $this->mFragment
; }
357 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
359 # Get title for search index
360 function getIndexTitle() {
361 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
364 # Get prefixed title with underscores
365 function getPrefixedDBkey() {
366 $s = $this->prefix( $this->mDbkeyform
);
367 $s = str_replace( ' ', '_', $s );
371 # Get prefixed title with spaces
372 # This is the form usually used for display
373 function getPrefixedText() {
374 if ( empty( $this->mPrefixedText
) ) {
375 $s = $this->prefix( $this->mTextform
);
376 $s = str_replace( '_', ' ', $s );
377 $this->mPrefixedText
= $s;
379 return $this->mPrefixedText
;
382 # As getPrefixedText(), plus fragment.
383 function getFullText() {
384 $text = $this->getPrefixedText();
385 if( '' != $this->mFragment
) {
386 $text .= '#' . $this->mFragment
;
391 # Get a URL-encoded title (not an actual URL) including interwiki
392 function getPrefixedURL() {
393 $s = $this->prefix( $this->mDbkeyform
);
394 $s = str_replace( ' ', '_', $s );
396 $s = wfUrlencode ( $s ) ;
398 # Cleaning up URL to make it look nice -- is this safe?
399 $s = preg_replace( '/%3[Aa]/', ':', $s );
400 $s = preg_replace( '/%2[Ff]/', '/', $s );
401 $s = str_replace( '%28', '(', $s );
402 $s = str_replace( '%29', ')', $s );
407 # Get a real URL referring to this title, with interwiki link and fragment
408 function getFullURL( $query = '' ) {
409 global $wgLang, $wgArticlePath, $wgServer, $wgScript;
411 if ( '' == $this->mInterwiki
) {
413 return $wgServer . $this->getLocalUrl( $query );
415 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
416 $namespace = $wgLang->getNsText( $this->mNamespace
);
417 if ( '' != $namespace ) {
418 # Can this actually happen? Interwikis shouldn't be parsed.
421 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
422 if ( '' != $this->mFragment
) {
423 $url .= '#' . $this->mFragment
;
429 # Get a URL with an optional query string, no fragment
430 # * If $query=="", it will use $wgArticlePath
431 # * Returns a full for an interwiki link, loses any query string
432 # * Optionally adds the server and escapes for HTML
433 # * Setting $query to "-" makes an old-style URL with nothing in the
434 # query except a title
437 die( 'Call to obsolete obsolete function Title::getURL()' );
440 function getLocalURL( $query = '' ) {
441 global $wgLang, $wgArticlePath, $wgScript;
443 if ( $this->isExternal() ) {
444 return $this->getFullURL();
447 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
448 if ( $query == '' ) {
449 $url = str_replace( '$1', $dbkey, $wgArticlePath );
451 if ( $query == '-' ) {
454 if ( $wgScript != '' ) {
455 $url = "{$wgScript}?title={$dbkey}&{$query}";
458 $url = "/{$dbkey}?{$query}";
464 function escapeLocalURL( $query = '' ) {
465 return htmlspecialchars( $this->getLocalURL( $query ) );
468 function escapeFullURL( $query = '' ) {
469 return htmlspecialchars( $this->getFullURL( $query ) );
472 function getInternalURL( $query = '' ) {
473 # Used in various Squid-related code, in case we have a different
474 # internal hostname for the server than the exposed one.
475 global $wgInternalServer;
476 return $wgInternalServer . $this->getLocalURL( $query );
479 # Get the edit URL, or a null string if it is an interwiki link
480 function getEditURL() {
481 global $wgServer, $wgScript;
483 if ( '' != $this->mInterwiki
) { return ''; }
484 $s = $this->getLocalURL( 'action=edit' );
489 # Get HTML-escaped displayable text
490 # For the title field in <a> tags
491 function getEscapedText() {
492 return htmlspecialchars( $this->getPrefixedText() );
495 # Is the title interwiki?
496 function isExternal() { return ( '' != $this->mInterwiki
); }
498 # Does the title correspond to a protected article?
499 function isProtected() {
500 if ( -1 == $this->mNamespace
) { return true; }
501 $a = $this->getRestrictions();
502 if ( in_array( 'sysop', $a ) ) { return true; }
506 # Is the page a log page, i.e. one where the history is messed up by
507 # LogPage.php? This used to be used for suppressing diff links in recent
508 # changes, but now that's done by setting a flag in the recentchanges
509 # table. Hence, this probably is no longer used.
511 if ( $this->mNamespace
!= Namespace::getWikipedia() ) {
514 if ( ( 0 == strcmp( wfMsg( 'uploadlogpage' ), $this->mDbkeyform
) ) ||
515 ( 0 == strcmp( wfMsg( 'dellogpage' ), $this->mDbkeyform
) ) ) {
521 # Is $wgUser is watching this page?
522 function userIsWatching() {
525 if ( -1 == $this->mNamespace
) { return false; }
526 if ( 0 == $wgUser->getID() ) { return false; }
528 return $wgUser->isWatched( $this );
531 # Can $wgUser edit this page?
532 function userCanEdit() {
534 if ( -1 == $this->mNamespace
) { return false; }
535 if ( NS_MEDIAWIKI
== $this->mNamespace
&& !$wgUser->isSysop() ) { return false; }
536 # if ( 0 == $this->getArticleID() ) { return false; }
537 if ( $this->mDbkeyform
== '_' ) { return false; }
538 # protect global styles and js
539 if ( NS_MEDIAWIKI
== $this->mNamespace
540 && preg_match("/\\.(css|js)$/", $this->mTextform
)
541 && !$wgUser->isSysop() )
543 //if ( $this->isCssJsSubpage() and !$this->userCanEditCssJsSubpage() ) { return false; }
544 # protect css/js subpages of user pages
545 # XXX: this might be better using restrictions
546 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
547 if( Namespace::getUser() == $this->mNamespace
548 and preg_match("/\\.(css|js)$/", $this->mTextform
)
549 and !$wgUser->isSysop()
550 and !preg_match('/^'.preg_quote($wgUser->getName(), '/').'/', $this->mTextform
) )
552 $ur = $wgUser->getRights();
553 foreach ( $this->getRestrictions() as $r ) {
554 if ( '' != $r && ( ! in_array( $r, $ur ) ) ) {
561 function userCanRead() {
563 global $wgWhitelistRead;
565 if( 0 != $wgUser->getID() ) return true;
566 if( !is_array( $wgWhitelistRead ) ) return true;
568 $name = $this->getPrefixedText();
569 if( in_array( $name, $wgWhitelistRead ) ) return true;
571 # Compatibility with old settings
572 if( $this->getNamespace() == NS_MAIN
) {
573 if( in_array( ':' . $name, $wgWhitelistRead ) ) return true;
578 function isCssJsSubpage() {
579 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
581 function isCssSubpage() {
582 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
584 function isJsSubpage() {
585 return ( Namespace::getUser() == $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
587 function userCanEditCssJsSubpage() {
588 # protect css/js subpages of user pages
589 # XXX: this might be better using restrictions
591 return ( $wgUser->isSysop() or preg_match('/^'.preg_quote($wgUser->getName()).'/', $this->mTextform
) );
594 # Accessor/initialisation for mRestrictions
595 function getRestrictions() {
596 $id = $this->getArticleID();
597 if ( 0 == $id ) { return array(); }
599 if ( ! $this->mRestrictionsLoaded
) {
600 $dbr =& wfGetDB( DB_SLAVE
);
601 $res = $dbr->getField( 'cur', 'cur_restrictions', 'cur_id='.$id );
602 $this->mRestrictions
= explode( ',', trim( $res ) );
603 $this->mRestrictionsLoaded
= true;
605 return $this->mRestrictions
;
608 # Is there a version of this page in the deletion archive?
609 # Returns the number of archived revisions
610 function isDeleted() {
611 $fname = 'Title::isDeleted';
612 $dbr =& wfGetDB( DB_SLAVE
);
613 $n = $dbr->getField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
614 'ar_title' => $this->getDBkey() ), $fname );
618 # Get the article ID from the link cache
619 # $flags is a bit field, may be GAID_FOR_UPDATE to select for update
620 function getArticleID( $flags = 0 ) {
623 if ( $flags & GAID_FOR_UPDATE
) {
624 $oldUpdate = $wgLinkCache->forUpdate( true );
625 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
626 $wgLinkCache->forUpdate( $oldUpdate );
628 if ( -1 == $this->mArticleID
) {
629 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
632 return $this->mArticleID
;
635 # This clears some fields in this object, and clears any associated keys in the
636 # "bad links" section of $wgLinkCache. This is called from Article::insertNewArticle()
637 # to allow loading of the new cur_id. It's also called from Article::doDeleteArticle()
638 function resetArticleID( $newid ) {
640 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
642 if ( 0 == $newid ) { $this->mArticleID
= -1; }
643 else { $this->mArticleID
= $newid; }
644 $this->mRestrictionsLoaded
= false;
645 $this->mRestrictions
= array();
648 # Updates cur_touched
649 # Called from LinksUpdate.php
650 function invalidateCache() {
651 $now = wfTimestampNow();
652 $dbw =& wfGetDB( DB_MASTER
);
653 $success = $dbw->updateArray( 'cur',
655 'cur_touched' => wfTimestampNow()
656 ), array( /* WHERE */
657 'cur_namespace' => $this->getNamespace() ,
658 'cur_title' => $this->getDBkey()
659 ), 'Title::invalidateCache'
664 # Prefixes some arbitrary text with the namespace or interwiki prefix of this object
665 /* private */ function prefix( $name ) {
669 if ( '' != $this->mInterwiki
) {
670 $p = $this->mInterwiki
. ':';
672 if ( 0 != $this->mNamespace
) {
673 $p .= $wgLang->getNsText( $this->mNamespace
) . ':';
678 # Secure and split - main initialisation function for this object
680 # Assumes that mDbkeyform has been set, and is urldecoded
681 # and uses underscores, but not otherwise munged. This function
682 # removes illegal characters, splits off the interwiki and
683 # namespace prefixes, sets the other forms, and canonicalizes
686 /* private */ function secureAndSplit()
688 global $wgLang, $wgLocalInterwiki, $wgCapitalLinks;
689 $fname = 'Title::secureAndSplit';
690 wfProfileIn( $fname );
692 static $imgpre = false;
693 static $rxTc = false;
696 if ( $imgpre === false ) {
697 $imgpre = ':' . $wgLang->getNsText( Namespace::getImage() ) . ':';
698 # % is needed as well
699 $rxTc = '/[^' . Title
::legalChars() . ']/';
702 $this->mInterwiki
= $this->mFragment
= '';
703 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
705 # Clean up whitespace
707 $t = preg_replace( "/[\\s_]+/", '_', $this->mDbkeyform
);
708 $t = preg_replace( '/^_*(.*?)_*$/', '$1', $t );
711 wfProfileOut( $fname );
716 if( !$wgUseLatin1 && false !== strpos( $t, UTF8_REPLACEMENT
, $t ) ) {
717 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
718 wfProfileOut( $fname );
722 $this->mDbkeyform
= $t;
726 if ( 0 == strncasecmp( $imgpre, $t, strlen( $imgpre ) ) ) {
727 $t = substr( $t, 1 );
730 # Initial colon indicating main namespace
731 if ( ':' == $t{0} ) {
732 $r = substr( $t, 1 );
733 $this->mNamespace
= NS_MAIN
;
735 # Namespace or interwiki prefix
736 if ( preg_match( "/^(.+?)_*:_*(.*)$/", $t, $m ) ) {
737 #$p = strtolower( $m[1] );
739 $lowerNs = strtolower( $p );
740 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
741 # Canonical namespace
743 $this->mNamespace
= $ns;
744 } elseif ( $ns = $wgLang->getNsIndex( $lowerNs )) {
747 $this->mNamespace
= $ns;
748 } elseif ( $this->getInterwikiLink( $p ) ) {
751 $this->mInterwiki
= $p;
753 if ( !preg_match( "/^([A-Za-z0-9_\\x80-\\xff]+):(.*)$/", $t, $m ) ) {
755 } elseif($this->mInterwiki
!= $wgLocalInterwiki) {
763 # Redundant interwiki prefix to the local wiki
764 if ( 0 == strcmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
765 $this->mInterwiki
= '';
767 # We already know that some pages won't be in the database!
769 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
770 $this->mArticleID
= 0;
772 $f = strstr( $r, '#' );
773 if ( false !== $f ) {
774 $this->mFragment
= substr( $f, 1 );
775 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
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' => $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' => $now,
997 'cur_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 $now = wfTimestampNow();
1100 $won = wfInvertTimestamp( $now );
1101 $newid = $nt->getArticleID();
1102 $oldid = $this->getArticleID();
1103 $dbw =& wfGetDB( DB_MASTER
);
1106 $dbw->updateArray( 'cur',
1108 'cur_touched' => $now,
1109 'cur_namespace' => $nt->getNamespace(),
1110 'cur_title' => $nt->getDBkey()
1112 /* WHERE */ array( 'cur_id' => $oldid ),
1116 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1119 $dbw->insertArray( 'cur', array(
1120 'cur_namespace' => $this->getNamespace(),
1121 'cur_title' => $this->getDBkey(),
1122 'cur_comment' => $comment,
1123 'cur_user' => $wgUser->getID(),
1124 'cur_user_text' => $wgUser->getName(),
1125 'cur_timestamp' => $now,
1126 'inverse_timestamp' => $won,
1127 'cur_touched' => $now,
1128 'cur_is_redirect' => 1,
1130 'cur_text' => "#REDIRECT [[" . $nt->getPrefixedText() . "]]\n" ), $fname
1132 $newid = $dbw->insertId();
1133 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1135 # Rename old entries
1139 'old_namespace' => $nt->getNamespace(),
1140 'old_title' => $nt->getDBkey()
1143 'old_namespace' => $this->getNamespace(),
1144 'old_title' => $this->getDBkey()
1149 RecentChange
::notifyMoveToNew( $now, $this, $nt, $wgUser, $comment );
1151 # Purge squid and linkscc as per article creation
1152 Article
::onArticleCreate( $nt );
1154 # Any text links to the old title must be reassigned to the redirect
1155 $dbw->updateArray( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1156 LinkCache
::linksccClearLinksTo( $oldid );
1158 # Record the just-created redirect's linking to the page
1159 $dbw->insertArray( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1161 # Non-existent target may have had broken links to it; these must
1162 # now be removed and made into good links.
1163 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1164 $update->fixBrokenLinks();
1166 # Purge old title from squid
1167 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1168 $titles = $nt->getLinksTo();
1169 if ( $wgUseSquid ) {
1170 $urls = $this->getSquidURLs();
1171 foreach ( $titles as $linkTitle ) {
1172 $urls[] = $linkTitle->getInternalURL();
1174 $u = new SquidUpdate( $urls );
1179 # Checks if $this can be moved to $nt
1180 # Selects for update, so don't call it unless you mean business
1181 function isValidMoveTarget( $nt ) {
1182 $fname = 'Title::isValidMoveTarget';
1183 $dbw =& wfGetDB( DB_MASTER
);
1186 $id = $nt->getArticleID();
1187 $obj = $dbw->getArray( 'cur', array( 'cur_is_redirect','cur_text' ),
1188 array( 'cur_id' => $id ), $fname, 'FOR UPDATE' );
1190 if ( !$obj ||
0 == $obj->cur_is_redirect
) {
1195 # Does the redirect point to the source?
1196 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->cur_text
, $m ) ) {
1197 $redirTitle = Title
::newFromText( $m[1] );
1198 if( !is_object( $redirTitle ) ||
1199 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1204 # Does the article have a history?
1205 $row = $dbw->getArray( 'old', array( 'old_id' ),
1207 'old_namespace' => $nt->getNamespace(),
1208 'old_title' => $nt->getDBkey()
1209 ), $fname, 'FOR UPDATE'
1212 # Return true if there was no history
1213 return $row === false;
1216 # Create a redirect, fails if the title already exists, does not notify RC
1218 function createRedirect( $dest, $comment ) {
1220 if ( $this->getArticleID() ) {
1224 $fname = 'Title::createRedirect';
1225 $dbw =& wfGetDB( DB_MASTER
);
1226 $now = wfTimestampNow();
1227 $won = wfInvertTimestamp( $now );
1228 $seqVal = $dbw->nextSequenceValue( 'cur_cur_id_seq' );
1230 $dbw->insertArray( 'cur', array(
1231 'cur_id' => $seqVal,
1232 'cur_namespace' => $this->getNamespace(),
1233 'cur_title' => $this->getDBkey(),
1234 'cur_comment' => $comment,
1235 'cur_user' => $wgUser->getID(),
1236 'cur_user_text' => $wgUser->getName(),
1237 'cur_timestamp' => $now,
1238 'inverse_timestamp' => $won,
1239 'cur_touched' => $now,
1240 'cur_is_redirect' => 1,
1242 'cur_text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n"
1244 $newid = $dbw->insertId();
1245 $this->resetArticleID( $newid );
1248 if ( $dest->getArticleID() ) {
1249 $dbw->insertArray( 'links',
1251 'l_to' => $dest->getArticleID(),
1256 $dbw->insertArray( 'brokenlinks',
1258 'bl_to' => $dest->getPrefixedDBkey(),
1264 Article
::onArticleCreate( $this );
1268 # Get categories to wich belong this title and return an array of
1270 # Return an array of parents in the form:
1271 # $parent => $currentarticle
1272 function getParentCategories() {
1273 global $wgLang,$wgUser;
1275 $titlekey = $this->getArticleId();
1276 $sk =& $wgUser->getSkin();
1278 $dbr =& wfGetDB( DB_SLAVE
);
1279 $cur = $dbr->tableName( 'cur' );
1280 $categorylinks = $dbr->tableName( 'categorylinks' );
1283 $sql = "SELECT * FROM categorylinks"
1284 ." WHERE cl_from='$titlekey'"
1285 ." AND cl_from <> '0'"
1286 ." ORDER BY cl_sortkey";
1288 $res = $dbr->query ( $sql ) ;
1290 if($dbr->numRows($res) > 0) {
1291 while ( $x = $dbr->fetchObject ( $res ) )
1292 //$data[] = Title::newFromText($wgLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1293 $data[$wgLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1294 $dbr->freeResult ( $res ) ;
1301 # Go through all parents
1302 function getCategorieBrowser() {
1303 $parents = $this->getParentCategories();
1305 if($parents != '') {
1306 foreach($parents as $parent => $current)
1308 $nt = Title
::newFromText($parent);
1309 $stack[$parent] = $nt->getCategorieBrowser();
1318 # Returns an associative array for selecting this title from cur
1319 function curCond() {
1320 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1323 function oldCond() {
1324 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);