8 require_once( 'normal/UtfNormal.php' );
10 $wgTitleInterwikiCache = array();
11 define ( 'GAID_FOR_UPDATE', 1 );
13 # Title::newFromTitle maintains a cache to avoid
14 # expensive re-normalization of commonly used titles.
15 # On a batch operation this can become a memory leak
16 # if not bounded. After hitting this many titles,
18 define( 'MW_TITLECACHE_MAX', 1000 );
22 * - Represents a title, which may contain an interwiki designation or namespace
23 * - Can fetch various kinds of data from the database, albeit inefficiently.
29 * All member variables should be considered private
30 * Please use the accessor functions
37 var $mTextform; # Text form (spaces not underscores) of the main part
38 var $mUrlform; # URL-encoded form of the main part
39 var $mDbkeyform; # Main part with underscores
40 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
41 var $mInterwiki; # Interwiki prefix (or null string)
42 var $mFragment; # Title fragment (i.e. the bit after the #)
43 var $mArticleID; # Article ID, fetched from the link cache on demand
44 var $mRestrictions; # Array of groups allowed to edit this article
45 # Only null or "sysop" are supported
46 var $mRestrictionsLoaded; # Boolean for initialisation on demand
47 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
48 var $mDefaultNamespace; # Namespace index when there is no namespace
49 # Zero except in {{transclusion}} tags
50 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
58 /* private */ function Title() {
59 $this->mInterwiki
= $this->mUrlform
=
60 $this->mTextform
= $this->mDbkeyform
= '';
61 $this->mArticleID
= -1;
62 $this->mNamespace
= NS_MAIN
;
63 $this->mRestrictionsLoaded
= false;
64 $this->mRestrictions
= array();
65 # Dont change the following, NS_MAIN is hardcoded in several place
67 $this->mDefaultNamespace
= NS_MAIN
;
68 $this->mWatched
= NULL;
72 * Create a new Title from a prefixed DB key
73 * @param string $key The database key, which has underscores
74 * instead of spaces, possibly including namespace and
76 * @return Title the new object, or NULL on an error
80 /* static */ function newFromDBkey( $key ) {
82 $t->mDbkeyform
= $key;
83 if( $t->secureAndSplit() )
90 * Create a new Title from text, such as what one would
91 * find in a link. Decodes any HTML entities in the text.
93 * @param string $text the link text; spaces, prefixes,
94 * and an initial ':' indicating the main namespace
96 * @param int $defaultNamespace the namespace to use if
97 * none is specified by a prefix
98 * @return Title the new object, or NULL on an error
102 function &newFromText( $text, $defaultNamespace = NS_MAIN
) {
103 $fname = 'Title::newFromText';
104 wfProfileIn( $fname );
106 if( is_object( $text ) ) {
107 wfDebugDieBacktrace( 'Title::newFromText given an object' );
111 * Wiki pages often contain multiple links to the same page.
112 * Title normalization and parsing can become expensive on
113 * pages with many links, so we can save a little time by
116 * In theory these are value objects and won't get changed...
118 static $titleCache = array();
119 if( $defaultNamespace == NS_MAIN
&& isset( $titleCache[$text] ) ) {
120 wfProfileOut( $fname );
121 return $titleCache[$text];
125 * Convert things like é into real text...
127 global $wgInputEncoding;
128 $filteredText = do_html_entity_decode( $text, ENT_COMPAT
, $wgInputEncoding );
131 * Convert things like ā or 〗 into real text...
132 * WARNING: Not friendly to internal links on a latin-1 wiki.
134 $filteredText = wfMungeToUtf8( $filteredText );
136 # What was this for? TS 2004-03-03
137 # $text = urldecode( $text );
140 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
141 $t->mDefaultNamespace
= $defaultNamespace;
143 if( $t->secureAndSplit() ) {
144 if( $defaultNamespace == NS_MAIN
) {
145 if( count( $titleCache ) >= MW_TITLECACHE_MAX
) {
146 # Avoid memory leaks on mass operations...
147 $titleCache = array();
149 $titleCache[$text] =& $t;
151 wfProfileOut( $fname );
154 wfProfileOut( $fname );
160 * Create a new Title from URL-encoded text. Ensures that
161 * the given title's length does not exceed the maximum.
162 * @param string $url the title, as might be taken from a URL
163 * @return Title the new object, or NULL on an error
167 function newFromURL( $url ) {
168 global $wgLang, $wgServer;
171 # For compatibility with old buggy URLs. "+" is not valid in titles,
172 # but some URLs used it as a space replacement and they still come
173 # from some external search tools.
174 $s = str_replace( '+', ' ', $url );
176 $t->mDbkeyform
= str_replace( ' ', '_', $s );
177 if( $t->secureAndSplit() ) {
185 * Create a new Title from an article ID
187 * @todo This is inefficiently implemented, the page row is requested
188 * but not used for anything else
190 * @param int $id the page_id corresponding to the Title to create
191 * @return Title the new object, or NULL on an error
195 function newFromID( $id ) {
196 $fname = 'Title::newFromID';
197 $dbr =& wfGetDB( DB_SLAVE
);
198 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
199 array( 'page_id' => $id ), $fname );
200 if ( $row !== false ) {
201 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
209 * Create a new Title from a namespace index and a DB key.
210 * It's assumed that $ns and $title are *valid*, for instance when
211 * they came directly from the database or a special page name.
212 * For convenience, spaces are converted to underscores so that
213 * eg user_text fields can be used directly.
215 * @param int $ns the namespace of the article
216 * @param string $title the unprefixed database key form
217 * @return Title the new object
221 function &makeTitle( $ns, $title ) {
225 $t->mNamespace
= IntVal( $ns );
226 $t->mDbkeyform
= str_replace( ' ', '_', $title );
227 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
228 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
229 $t->mTextform
= str_replace( '_', ' ', $title );
234 * Create a new Title frrom a namespace index and a DB key.
235 * The parameters will be checked for validity, which is a bit slower
236 * than makeTitle() but safer for user-provided data.
238 * @param int $ns the namespace of the article
239 * @param string $title the database key form
240 * @return Title the new object, or NULL on an error
244 function makeTitleSafe( $ns, $title ) {
246 $t->mDbkeyform
= Title
::makeName( $ns, $title );
247 if( $t->secureAndSplit() ) {
255 * Create a new Title for the Main Page
258 * @return Title the new object
261 function newMainPage() {
262 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
266 * Create a new Title for a redirect
267 * @param string $text the redirect title text
268 * @return Title the new object, or NULL if the text is not a
273 function newFromRedirect( $text ) {
276 if ( $wgMwRedir->matchStart( $text ) ) {
277 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
278 # categories are escaped using : for example one can enter:
279 # #REDIRECT [[:Category:Music]]. Need to remove it.
280 if ( substr($m[1],0,1) == ':') {
281 # We don't want to keep the ':'
282 $m[1] = substr( $m[1], 1 );
285 $rt = Title
::newFromText( $m[1] );
286 # Disallow redirects to Special:Userlogout
287 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
295 #----------------------------------------------------------------------------
297 #----------------------------------------------------------------------------
300 * Get the prefixed DB key associated with an ID
301 * @param int $id the page_id of the article
302 * @return Title an object representing the article, or NULL
303 * if no such article was found
307 function nameOf( $id ) {
308 $fname = 'Title::nameOf';
309 $dbr =& wfGetDB( DB_SLAVE
);
311 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
312 if ( $s === false ) { return NULL; }
314 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
319 * Get a regex character class describing the legal characters in a link
320 * @return string the list of characters, not delimited
324 /* static */ function legalChars() {
325 # Missing characters:
326 # * []|# Needed for link syntax
327 # * % and + are corrupted by Apache when they appear in the path
329 # % seems to work though
331 # The problem with % is that URLs are double-unescaped: once by Apache's
332 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
333 # Our code does not double-escape to compensate for this, indeed double escaping
334 # would break if the double-escaped title was passed in the query string
335 # rather than the path. This is a minor security issue because articles can be
336 # created such that they are hard to view or edit. -- TS
338 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
339 # this breaks interlanguage links
341 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF";
346 * Get a string representation of a title suitable for
347 * including in a search index
349 * @param int $ns a namespace index
350 * @param string $title text-form main part
351 * @return string a stripped-down title string ready for the
354 /* static */ function indexTitle( $ns, $title ) {
355 global $wgDBminWordLen, $wgContLang;
356 require_once( 'SearchEngine.php' );
358 $lc = SearchEngine
::legalSearchChars() . '&#;';
359 $t = $wgContLang->stripForSearch( $title );
360 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
361 $t = strtolower( $t );
364 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
365 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
367 $t = preg_replace( "/\\s+/", ' ', $t );
369 if ( $ns == NS_IMAGE
) {
370 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
376 * Make a prefixed DB key from a DB key and a namespace index
377 * @param int $ns numerical representation of the namespace
378 * @param string $title the DB key form the title
379 * @return string the prefixed form of the title
381 /* static */ function makeName( $ns, $title ) {
384 $n = $wgContLang->getNsText( $ns );
385 return $n == '' ?
$title : "$n:$title";
389 * Returns the URL associated with an interwiki prefix
390 * @param string $key the interwiki prefix (e.g. "MeatBall")
391 * @return the associated URL, containing "$1", which should be
392 * replaced by an article title
396 function getInterwikiLink( $key ) {
397 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
398 $fname = 'Title::getInterwikiLink';
400 wfProfileIn( $fname );
402 $k = $wgDBname.':interwiki:'.$key;
403 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
404 wfProfileOut( $fname );
405 return $wgTitleInterwikiCache[$k]->iw_url
;
408 $s = $wgMemc->get( $k );
409 # Ignore old keys with no iw_local
410 if( $s && isset( $s->iw_local
) ) {
411 $wgTitleInterwikiCache[$k] = $s;
412 wfProfileOut( $fname );
416 $dbr =& wfGetDB( DB_SLAVE
);
417 $res = $dbr->select( 'interwiki',
418 array( 'iw_url', 'iw_local' ),
419 array( 'iw_prefix' => $key ), $fname );
421 wfProfileOut( $fname );
425 $s = $dbr->fetchObject( $res );
427 # Cache non-existence: create a blank object and save it to memcached
432 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
433 $wgTitleInterwikiCache[$k] = $s;
435 wfProfileOut( $fname );
440 * Determine whether the object refers to a page within
443 * @return bool TRUE if this is an in-project interwiki link
444 * or a wikilink, FALSE otherwise
448 global $wgTitleInterwikiCache, $wgDBname;
450 if ( $this->mInterwiki
!= '' ) {
451 # Make sure key is loaded into cache
452 $this->getInterwikiLink( $this->mInterwiki
);
453 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
454 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
461 * Update the page_touched field for an array of title objects
462 * @todo Inefficient unless the IDs are already loaded into the
464 * @param array $titles an array of Title objects to be touched
465 * @param string $timestamp the timestamp to use instead of the
466 * default current time
470 function touchArray( $titles, $timestamp = '' ) {
471 if ( count( $titles ) == 0 ) {
474 $dbw =& wfGetDB( DB_MASTER
);
475 if ( $timestamp == '' ) {
476 $timestamp = $dbw->timestamp();
478 $page = $dbw->tableName( 'page' );
479 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
482 foreach ( $titles as $title ) {
487 $sql .= $title->getArticleID();
491 $dbw->query( $sql, 'Title::touchArray' );
495 #----------------------------------------------------------------------------
497 #----------------------------------------------------------------------------
499 /** Simple accessors */
501 * Get the text form (spaces not underscores) of the main part
505 function getText() { return $this->mTextform
; }
507 * Get the URL-encoded form of the main part
511 function getPartialURL() { return $this->mUrlform
; }
513 * Get the main part with underscores
517 function getDBkey() { return $this->mDbkeyform
; }
519 * Get the namespace index, i.e. one of the NS_xxxx constants
523 function getNamespace() { return $this->mNamespace
; }
525 * Get the interwiki prefix (or null string)
529 function getInterwiki() { return $this->mInterwiki
; }
531 * Get the Title fragment (i.e. the bit after the #)
535 function getFragment() { return $this->mFragment
; }
537 * Get the default namespace index, for when there is no namespace
541 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
544 * Get title for search index
545 * @return string a stripped-down title string ready for the
548 function getIndexTitle() {
549 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
553 * Get the prefixed database key form
554 * @return string the prefixed title, with underscores and
555 * any interwiki and namespace prefixes
558 function getPrefixedDBkey() {
559 $s = $this->prefix( $this->mDbkeyform
);
560 $s = str_replace( ' ', '_', $s );
565 * Get the prefixed title with spaces.
566 * This is the form usually used for display
567 * @return string the prefixed title, with spaces
570 function getPrefixedText() {
572 if ( empty( $this->mPrefixedText
) ) {
573 $s = $this->prefix( $this->mTextform
);
574 $s = str_replace( '_', ' ', $s );
575 $this->mPrefixedText
= $s;
577 return $this->mPrefixedText
;
581 * Get the prefixed title with spaces, plus any fragment
582 * (part beginning with '#')
583 * @return string the prefixed title, with spaces and
584 * the fragment, including '#'
587 function getFullText() {
589 $text = $this->getPrefixedText();
590 if( '' != $this->mFragment
) {
591 $text .= '#' . $this->mFragment
;
597 * Get a URL-encoded title (not an actual URL) including interwiki
598 * @return string the URL-encoded form
601 function getPrefixedURL() {
602 $s = $this->prefix( $this->mDbkeyform
);
603 $s = str_replace( ' ', '_', $s );
605 $s = wfUrlencode ( $s ) ;
607 # Cleaning up URL to make it look nice -- is this safe?
608 $s = str_replace( '%28', '(', $s );
609 $s = str_replace( '%29', ')', $s );
615 * Get a real URL referring to this title, with interwiki link and
618 * @param string $query an optional query string, not used
619 * for interwiki links
620 * @return string the URL
623 function getFullURL( $query = '' ) {
624 global $wgContLang, $wgServer, $wgScript;
626 if ( '' == $this->mInterwiki
) {
627 return $wgServer . $this->getLocalUrl( $query );
629 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
630 $namespace = $wgContLang->getNsText( $this->mNamespace
);
631 if ( '' != $namespace ) {
632 # Can this actually happen? Interwikis shouldn't be parsed.
635 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
637 if( false === strpos( $url, '?' ) ) {
644 if ( '' != $this->mFragment
) {
645 $url .= '#' . $this->mFragment
;
652 * Get a relative directory for putting an HTML version of this article into
654 function getHashedDirectory() {
655 $dbkey = $this->getPrefixedDBkey();
656 if ( strlen( $dbkey ) < 2 ) {
657 $dbkey = sprintf( "%2s", $dbkey );
660 for ( $i=0; $i<=1; $i++
) {
664 if ( ord( $dbkey{$i} ) < 128 && ord( $dbkey{$i} ) > 32 ) {
665 $dir .= strtolower( $dbkey{$i} );
667 $dir .= sprintf( "%02X", ord( $dbkey{$i} ) );
673 function getHashedFilename() {
674 $dbkey = $this->getPrefixedDBkey();
675 $dir = $this->getHashedDirectory();
676 $friendlyName = strtr( $dbkey, '/\\:*?"<>|', '_________' );
677 return "$dir/$friendlyName.html";
681 * Get a URL with no fragment or server name
682 * @param string $query an optional query string; if not specified,
683 * $wgArticlePath will be used.
684 * @return string the URL
687 function getLocalURL( $query = '' ) {
688 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks;
690 if ( $this->isExternal() ) {
691 return $this->getFullURL();
694 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
695 if ( $wgMakeDumpLinks ) {
696 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
697 } elseif ( $query == '' ) {
698 $url = str_replace( '$1', $dbkey, $wgArticlePath );
700 if( preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
701 global $wgActionPaths;
702 $action = urldecode( $matches[2] );
703 if( isset( $wgActionPaths[$action] ) ) {
704 $query = $matches[1];
705 if( isset( $matches[4] ) ) $query .= $matches[4];
706 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
707 if( $query != '' ) $url .= '?' . $query;
711 if ( $query == '-' ) {
714 $url = "{$wgScript}?title={$dbkey}&{$query}";
720 * Get an HTML-escaped version of the URL form, suitable for
721 * using in a link, without a server name or fragment
722 * @param string $query an optional query string
723 * @return string the URL
726 function escapeLocalURL( $query = '' ) {
727 return htmlspecialchars( $this->getLocalURL( $query ) );
731 * Get an HTML-escaped version of the URL form, suitable for
732 * using in a link, including the server name and fragment
734 * @return string the URL
735 * @param string $query an optional query string
738 function escapeFullURL( $query = '' ) {
739 return htmlspecialchars( $this->getFullURL( $query ) );
743 * Get the URL form for an internal link.
744 * - Used in various Squid-related code, in case we have a different
745 * internal hostname for the server from the exposed one.
747 * @param string $query an optional query string
748 * @return string the URL
751 function getInternalURL( $query = '' ) {
752 global $wgInternalServer;
753 return $wgInternalServer . $this->getLocalURL( $query );
757 * Get the edit URL for this Title
758 * @return string the URL, or a null string if this is an
762 function getEditURL() {
763 global $wgServer, $wgScript;
765 if ( '' != $this->mInterwiki
) { return ''; }
766 $s = $this->getLocalURL( 'action=edit' );
772 * Get the HTML-escaped displayable text form.
773 * Used for the title field in <a> tags.
774 * @return string the text, including any prefixes
777 function getEscapedText() {
778 return htmlspecialchars( $this->getPrefixedText() );
782 * Is this Title interwiki?
786 function isExternal() { return ( '' != $this->mInterwiki
); }
789 * Does the title correspond to a protected article?
790 * @param string $what the action the page is protected from,
791 * by default checks move and edit
795 function isProtected($action = '') {
796 if ( -1 == $this->mNamespace
) { return true; }
797 if($action == 'edit' ||
$action == '') {
798 $a = $this->getRestrictions("edit");
799 if ( in_array( 'sysop', $a ) ) { return true; }
801 if($action == 'move' ||
$action == '') {
802 $a = $this->getRestrictions("move");
803 if ( in_array( 'sysop', $a ) ) { return true; }
809 * Is $wgUser is watching this page?
813 function userIsWatching() {
816 if ( is_null( $this->mWatched
) ) {
817 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
818 $this->mWatched
= false;
820 $this->mWatched
= $wgUser->isWatched( $this );
823 return $this->mWatched
;
827 * Is $wgUser perform $action this page?
828 * @param string $action action that permission needs to be checked for
832 function userCan($action) {
833 $fname = 'Title::userCanEdit';
834 wfProfileIn( $fname );
837 if( NS_SPECIAL
== $this->mNamespace
) {
838 wfProfileOut( $fname );
841 if( NS_MEDIAWIKI
== $this->mNamespace
&&
842 !$wgUser->isAllowed('editinterface') ) {
843 wfProfileOut( $fname );
846 if( $this->mDbkeyform
== '_' ) {
847 # FIXME: Is this necessary? Shouldn't be allowed anyway...
848 wfProfileOut( $fname );
852 # protect global styles and js
853 if ( NS_MEDIAWIKI
== $this->mNamespace
854 && preg_match("/\\.(css|js)$/", $this->mTextform
)
855 && !$wgUser->isAllowed('editinterface') ) {
856 wfProfileOut( $fname );
860 # protect css/js subpages of user pages
861 # XXX: this might be better using restrictions
862 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
863 if( NS_USER
== $this->mNamespace
864 && preg_match("/\\.(css|js)$/", $this->mTextform
)
865 && !$wgUser->isAllowed('editinterface')
866 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
867 wfProfileOut( $fname );
871 foreach( $this->getRestrictions($action) as $right ) {
872 // Backwards compatibility, rewrite sysop -> protect
873 if ( $right == 'sysop' ) {
876 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
877 wfProfileOut( $fname );
882 if( $action == 'move' && !$this->isMovable() ) {
883 wfProfileOut( $fname );
887 wfProfileOut( $fname );
892 * Can $wgUser edit this page?
896 function userCanEdit() {
897 return $this->userCan('edit');
901 * Can $wgUser move this page?
905 function userCanMove() {
906 return $this->userCan('move');
910 * Would anybody with sufficient privileges be able to move this page?
911 * Some pages just aren't movable.
916 function isMovable() {
917 return Namespace::isMovable( $this->getNamespace() )
918 && $this->getInterwiki() == '';
922 * Can $wgUser read this page?
926 function userCanRead() {
929 if( $wgUser->isAllowed('read') ) {
932 global $wgWhitelistRead;
934 /** If anon users can create an account,
935 they need to reach the login page first! */
936 if( $wgUser->isAllowed( 'createaccount' )
937 && $this->mId
== NS_SPECIAL
938 && $this->getText() == 'Userlogin' ) {
942 /** some pages are explicitly allowed */
943 $name = $this->getPrefixedText();
944 if( in_array( $name, $wgWhitelistRead ) ) {
948 # Compatibility with old settings
949 if( $this->getNamespace() == NS_MAIN
) {
950 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
959 * Is this a talk page of some sort?
963 function isTalkPage() {
964 return Namespace::isTalk( $this->getNamespace() );
968 * Is this a .css or .js subpage of a user page?
972 function isCssJsSubpage() {
973 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
976 * Is this a .css subpage of a user page?
980 function isCssSubpage() {
981 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
984 * Is this a .js subpage of a user page?
988 function isJsSubpage() {
989 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
992 * Protect css/js subpages of user pages: can $wgUser edit
996 * @todo XXX: this might be better using restrictions
999 function userCanEditCssJsSubpage() {
1001 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1005 * Loads a string into mRestrictions array
1006 * @param string $res restrictions in string format
1009 function loadRestrictions( $res ) {
1010 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1011 $temp = explode( '=', trim( $restrict ) );
1012 if(count($temp) == 1) {
1013 // old format should be treated as edit/move restriction
1014 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1015 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1017 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1020 $this->mRestrictionsLoaded
= true;
1024 * Accessor/initialisation for mRestrictions
1025 * @param string $action action that permission needs to be checked for
1026 * @return array the array of groups allowed to edit this article
1029 function getRestrictions($action) {
1030 $id = $this->getArticleID();
1031 if ( 0 == $id ) { return array(); }
1033 if ( ! $this->mRestrictionsLoaded
) {
1034 $dbr =& wfGetDB( DB_SLAVE
);
1035 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1036 $this->loadRestrictions( $res );
1038 if( isset( $this->mRestrictions
[$action] ) ) {
1039 return $this->mRestrictions
[$action];
1045 * Is there a version of this page in the deletion archive?
1046 * @return int the number of archived revisions
1049 function isDeleted() {
1050 $fname = 'Title::isDeleted';
1051 $dbr =& wfGetDB( DB_SLAVE
);
1052 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1053 'ar_title' => $this->getDBkey() ), $fname );
1058 * Get the article ID for this Title from the link cache,
1059 * adding it if necessary
1060 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1062 * @return int the ID
1065 function getArticleID( $flags = 0 ) {
1066 global $wgLinkCache;
1068 if ( $flags & GAID_FOR_UPDATE
) {
1069 $oldUpdate = $wgLinkCache->forUpdate( true );
1070 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1071 $wgLinkCache->forUpdate( $oldUpdate );
1073 if ( -1 == $this->mArticleID
) {
1074 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1077 return $this->mArticleID
;
1081 * This clears some fields in this object, and clears any associated
1082 * keys in the "bad links" section of $wgLinkCache.
1084 * - This is called from Article::insertNewArticle() to allow
1085 * loading of the new page_id. It's also called from
1086 * Article::doDeleteArticle()
1088 * @param int $newid the new Article ID
1091 function resetArticleID( $newid ) {
1092 global $wgLinkCache;
1093 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1095 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1096 else { $this->mArticleID
= $newid; }
1097 $this->mRestrictionsLoaded
= false;
1098 $this->mRestrictions
= array();
1102 * Updates page_touched for this page; called from LinksUpdate.php
1103 * @return bool true if the update succeded
1106 function invalidateCache() {
1107 if ( wfReadOnly() ) {
1111 $now = wfTimestampNow();
1112 $dbw =& wfGetDB( DB_MASTER
);
1113 $success = $dbw->update( 'page',
1115 'page_touched' => $dbw->timestamp()
1116 ), array( /* WHERE */
1117 'page_namespace' => $this->getNamespace() ,
1118 'page_title' => $this->getDBkey()
1119 ), 'Title::invalidateCache'
1125 * Prefix some arbitrary text with the namespace or interwiki prefix
1128 * @param string $name the text
1129 * @return string the prefixed text
1132 /* private */ function prefix( $name ) {
1136 if ( '' != $this->mInterwiki
) {
1137 $p = $this->mInterwiki
. ':';
1139 if ( 0 != $this->mNamespace
) {
1140 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1146 * Secure and split - main initialisation function for this object
1148 * Assumes that mDbkeyform has been set, and is urldecoded
1149 * and uses underscores, but not otherwise munged. This function
1150 * removes illegal characters, splits off the interwiki and
1151 * namespace prefixes, sets the other forms, and canonicalizes
1153 * @return bool true on success
1156 /* private */ function secureAndSplit() {
1157 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1158 $fname = 'Title::secureAndSplit';
1159 wfProfileIn( $fname );
1162 static $rxTc = false;
1164 # % is needed as well
1165 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1168 $this->mInterwiki
= $this->mFragment
= '';
1169 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1171 # Clean up whitespace
1173 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1174 $t = trim( $t, '_' );
1177 wfProfileOut( $fname );
1181 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1182 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1183 wfProfileOut( $fname );
1187 $this->mDbkeyform
= $t;
1189 # Initial colon indicating main namespace
1190 if ( ':' == $t{0} ) {
1191 $r = substr( $t, 1 );
1192 $this->mNamespace
= NS_MAIN
;
1194 # Namespace or interwiki prefix
1197 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1199 $lowerNs = strtolower( $p );
1200 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1201 # Canonical namespace
1203 $this->mNamespace
= $ns;
1204 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1205 # Ordinary namespace
1207 $this->mNamespace
= $ns;
1208 } elseif( $this->getInterwikiLink( $p ) ) {
1210 # Can't make a local interwiki link to an interwiki link.
1211 # That's just crazy!
1212 wfProfileOut( $fname );
1218 $this->mInterwiki
= $p;
1220 # Redundant interwiki prefix to the local wiki
1221 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1223 # Can't have an empty self-link
1224 wfProfileOut( $fname );
1227 $this->mInterwiki
= '';
1229 # Do another namespace split...
1233 # If there's no recognized interwiki or namespace,
1234 # then let the colon expression be part of the title.
1241 # We already know that some pages won't be in the database!
1243 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1244 $this->mArticleID
= 0;
1246 $f = strstr( $r, '#' );
1247 if ( false !== $f ) {
1248 $this->mFragment
= substr( $f, 1 );
1249 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1250 # remove whitespace again: prevents "Foo_bar_#"
1251 # becoming "Foo_bar_"
1252 $r = preg_replace( '/_*$/', '', $r );
1255 # Reject illegal characters.
1257 if( preg_match( $rxTc, $r ) ) {
1258 wfProfileOut( $fname );
1263 * Pages with "/./" or "/../" appearing in the URLs will
1264 * often be unreachable due to the way web browsers deal
1265 * with 'relative' URLs. Forbid them explicitly.
1267 if ( strpos( $r, '.' ) !== false &&
1268 ( $r === '.' ||
$r === '..' ||
1269 strpos( $r, './' ) === 0 ||
1270 strpos( $r, '../' ) === 0 ||
1271 strpos( $r, '/./' ) !== false ||
1272 strpos( $r, '/../' ) !== false ) )
1274 wfProfileOut( $fname );
1278 # We shouldn't need to query the DB for the size.
1279 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1280 if ( strlen( $r ) > 255 ) {
1281 wfProfileOut( $fname );
1286 * Normally, all wiki links are forced to have
1287 * an initial capital letter so [[foo]] and [[Foo]]
1288 * point to the same place.
1290 * Don't force it for interwikis, since the other
1291 * site might be case-sensitive.
1293 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1294 $t = $wgContLang->ucfirst( $r );
1300 * Can't make a link to a namespace alone...
1301 * "empty" local links can only be self-links
1302 * with a fragment identifier.
1305 $this->mInterwiki
== '' &&
1306 $this->mNamespace
!= NS_MAIN
) {
1307 wfProfileOut( $fname );
1312 $this->mDbkeyform
= $t;
1313 $this->mUrlform
= wfUrlencode( $t );
1315 $this->mTextform
= str_replace( '_', ' ', $t );
1317 wfProfileOut( $fname );
1322 * Get a Title object associated with the talk page of this article
1323 * @return Title the object for the talk page
1326 function getTalkPage() {
1327 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1331 * Get a title object associated with the subject page of this
1334 * @return Title the object for the subject page
1337 function getSubjectPage() {
1338 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1342 * Get an array of Title objects linking to this Title
1343 * Also stores the IDs in the link cache.
1345 * @param string $options may be FOR UPDATE
1346 * @return array the Title objects linking here
1349 function getLinksTo( $options = '' ) {
1350 global $wgLinkCache;
1351 $id = $this->getArticleID();
1354 $db =& wfGetDB( DB_MASTER
);
1356 $db =& wfGetDB( DB_SLAVE
);
1358 $page = $db->tableName( 'page' );
1359 $links = $db->tableName( 'links' );
1361 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$links WHERE l_from=page_id AND l_to={$id} $options";
1362 $res = $db->query( $sql, 'Title::getLinksTo' );
1364 if ( $db->numRows( $res ) ) {
1365 while ( $row = $db->fetchObject( $res ) ) {
1366 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1367 $wgLinkCache->addGoodLink( $row->page_id
, $titleObj->getPrefixedDBkey() );
1368 $retVal[] = $titleObj;
1372 $db->freeResult( $res );
1377 * Get an array of Title objects linking to this non-existent title.
1378 * - Also stores the IDs in the link cache.
1380 * @param string $options may be FOR UPDATE
1381 * @return array the Title objects linking here
1384 function getBrokenLinksTo( $options = '' ) {
1385 global $wgLinkCache;
1388 $db =& wfGetDB( DB_MASTER
);
1390 $db =& wfGetDB( DB_SLAVE
);
1392 $page = $db->tableName( 'page' );
1393 $brokenlinks = $db->tableName( 'brokenlinks' );
1394 $encTitle = $db->strencode( $this->getPrefixedDBkey() );
1396 $sql = "SELECT page_namespace,page_title,page_id FROM $brokenlinks,$page " .
1397 "WHERE bl_from=page_id AND bl_to='$encTitle' $options";
1398 $res = $db->query( $sql, "Title::getBrokenLinksTo" );
1400 if ( $db->numRows( $res ) ) {
1401 while ( $row = $db->fetchObject( $res ) ) {
1402 $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
1403 $wgLinkCache->addGoodLink( $row->page_id
, $titleObj->getPrefixedDBkey() );
1404 $retVal[] = $titleObj;
1407 $db->freeResult( $res );
1413 * Get an array of Title objects referring to non-existent articles linked from this page
1415 * @param string $options may be FOR UPDATE
1416 * @return array the Title objects
1419 function getBrokenLinksFrom( $options = '' ) {
1420 global $wgLinkCache;
1423 $db =& wfGetDB( DB_MASTER
);
1425 $db =& wfGetDB( DB_SLAVE
);
1427 $page = $db->tableName( 'page' );
1428 $brokenlinks = $db->tableName( 'brokenlinks' );
1429 $id = $this->getArticleID();
1431 $sql = "SELECT bl_to FROM $brokenlinks WHERE bl_from=$id $options";
1432 $res = $db->query( $sql, "Title::getBrokenLinksFrom" );
1434 if ( $db->numRows( $res ) ) {
1435 while ( $row = $db->fetchObject( $res ) ) {
1436 $retVal[] = Title
::newFromText( $row->bl_to
);
1439 $db->freeResult( $res );
1445 * Get a list of URLs to purge from the Squid cache when this
1448 * @return array the URLs
1451 function getSquidURLs() {
1453 $this->getInternalURL(),
1454 $this->getInternalURL( 'action=history' )
1459 * Move this page without authentication
1460 * @param Title &$nt the new page Title
1463 function moveNoAuth( &$nt ) {
1464 return $this->moveTo( $nt, false );
1468 * Check whether a given move operation would be valid.
1469 * Returns true if ok, or a message key string for an error message
1470 * if invalid. (Scarrrrry ugly interface this.)
1471 * @param Title &$nt the new title
1472 * @param bool $auth indicates whether $wgUser's permissions
1474 * @return mixed true on success, message name on failure
1477 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1479 if( !$this or !$nt ) {
1480 return 'badtitletext';
1482 if( $this->equals( $nt ) ) {
1485 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1486 return 'immobile_namespace';
1489 $fname = 'Title::move';
1490 $oldid = $this->getArticleID();
1491 $newid = $nt->getArticleID();
1493 if ( strlen( $nt->getDBkey() ) < 1 ) {
1494 return 'articleexists';
1496 if ( ( '' == $this->getDBkey() ) ||
1498 ( '' == $nt->getDBkey() ) ) {
1499 return 'badarticleerror';
1503 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1504 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1505 return 'protectedpage';
1508 # The move is allowed only if (1) the target doesn't exist, or
1509 # (2) the target is a redirect to the source, and has no history
1510 # (so we can undo bad moves right after they're done).
1512 if ( 0 != $newid ) { # Target exists; check for validity
1513 if ( ! $this->isValidMoveTarget( $nt ) ) {
1514 return 'articleexists';
1521 * Move a title to a new location
1522 * @param Title &$nt the new title
1523 * @param bool $auth indicates whether $wgUser's permissions
1525 * @return mixed true on success, message name on failure
1528 function moveTo( &$nt, $auth = true, $reason = '' ) {
1529 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1530 if( is_string( $err ) ) {
1533 if( $nt->exists() ) {
1534 $this->moveOverExistingRedirect( $nt, $reason );
1535 } else { # Target didn't exist, do normal move.
1536 $this->moveToNewTitle( $nt, $newid, $reason );
1539 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1541 $dbw =& wfGetDB( DB_MASTER
);
1542 $categorylinks = $dbw->tableName( 'categorylinks' );
1543 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1544 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
1545 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1546 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1550 $oldnamespace = $this->getNamespace() & ~
1;
1551 $newnamespace = $nt->getNamespace() & ~
1;
1552 $oldtitle = $this->getDBkey();
1553 $newtitle = $nt->getDBkey();
1555 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1556 WatchedItem
::duplicateEntries( $this, $nt );
1559 # Update search engine
1560 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
1562 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
1565 wfRunHooks( 'TitleMoveComplete', array(&$this, &$nt, &$wgUser, $oldid, $newid) );
1570 * Move page to a title which is at present a redirect to the
1573 * @param Title &$nt the page to move to, which should currently
1577 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1578 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1579 $fname = 'Title::moveOverExistingRedirect';
1580 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1583 $comment .= ": $reason";
1586 $now = wfTimestampNow();
1588 $newid = $nt->getArticleID();
1589 $oldid = $this->getArticleID();
1590 $dbw =& wfGetDB( DB_MASTER
);
1591 $links = $dbw->tableName( 'links' );
1593 # Delete the old redirect. We don't save it to history since
1594 # by definition if we've got here it's rather uninteresting.
1595 # We have to remove it so that the next step doesn't trigger
1596 # a conflict on the unique namespace+title index...
1597 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1599 # Save a null revision in the page's history notifying of the move
1600 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1601 wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1603 $nullRevId = $nullRevision->insertOn( $dbw );
1605 # Change the name of the target page:
1606 $dbw->update( 'page',
1608 'page_touched' => $dbw->timestamp($now),
1609 'page_namespace' => $nt->getNamespace(),
1610 'page_title' => $nt->getDBkey(),
1611 'page_latest' => $nullRevId,
1613 /* WHERE */ array( 'page_id' => $oldid ),
1616 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1618 # Recreate the redirect, this time in the other direction.
1619 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1620 $redirectArticle = new Article( $this );
1621 $newid = $redirectArticle->insertOn( $dbw );
1622 $redirectRevision = new Revision( array(
1624 'comment' => $comment,
1625 'text' => $redirectText ) );
1626 $revid = $redirectRevision->insertOn( $dbw );
1627 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1628 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1631 $log = new LogPage( 'move' );
1632 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1636 # Load titles and IDs
1637 $linksToOld = $this->getLinksTo( 'FOR UPDATE' );
1638 $linksToNew = $nt->getLinksTo( 'FOR UPDATE' );
1641 $sql = "DELETE FROM $links WHERE l_to=$oldid OR l_to=$newid";
1642 $dbw->query( $sql, $fname );
1645 if ( count( $linksToOld ) ||
count( $linksToNew )) {
1646 $sql = "INSERT INTO $links (l_from,l_to) VALUES ";
1649 # Insert links to old title
1650 foreach ( $linksToOld as $linkTitle ) {
1656 $id = $linkTitle->getArticleID();
1657 $sql .= "($id,$newid)";
1660 # Insert links to new title
1661 foreach ( $linksToNew as $linkTitle ) {
1667 $id = $linkTitle->getArticleID();
1668 $sql .= "($id, $oldid)";
1671 $dbw->query( $sql, $fname );
1674 # Now, we record the link from the redirect to the new title.
1675 # It should have no other outgoing links...
1676 $dbw->delete( 'links', array( 'l_from' => $newid ) );
1677 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ) );
1680 LinkCache
::linksccClearLinksTo( $oldid );
1681 LinkCache
::linksccClearLinksTo( $newid );
1684 if ( $wgUseSquid ) {
1685 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1686 $u = new SquidUpdate( $urls );
1692 * Move page to non-existing title.
1693 * @param Title &$nt the new Title
1694 * @param int &$newid set to be the new article ID
1697 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1698 global $wgUser, $wgLinkCache, $wgUseSquid;
1700 $fname = 'MovePageForm::moveToNewTitle';
1701 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1703 $comment .= ": $reason";
1706 $newid = $nt->getArticleID();
1707 $oldid = $this->getArticleID();
1708 $dbw =& wfGetDB( DB_MASTER
);
1709 $now = $dbw->timestamp();
1713 # Save a null revision in the page's history notifying of the move
1714 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1715 wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1717 $nullRevId = $nullRevision->insertOn( $dbw );
1720 $dbw->update( 'page',
1722 'page_touched' => $now,
1723 'page_namespace' => $nt->getNamespace(),
1724 'page_title' => $nt->getDBkey(),
1725 'page_latest' => $nullRevId,
1727 /* WHERE */ array( 'page_id' => $oldid ),
1731 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1734 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1735 $redirectArticle = new Article( $this );
1736 $newid = $redirectArticle->insertOn( $dbw );
1737 $redirectRevision = new Revision( array(
1739 'comment' => $comment,
1740 'text' => $redirectText ) );
1741 $revid = $redirectRevision->insertOn( $dbw );
1742 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1743 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1746 $log = new LogPage( 'move' );
1747 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1749 # Purge squid and linkscc as per article creation
1750 Article
::onArticleCreate( $nt );
1752 # Any text links to the old title must be reassigned to the redirect
1753 $dbw->update( 'links', array( 'l_to' => $newid ), array( 'l_to' => $oldid ), $fname );
1754 LinkCache
::linksccClearLinksTo( $oldid );
1756 # Record the just-created redirect's linking to the page
1757 $dbw->insert( 'links', array( 'l_from' => $newid, 'l_to' => $oldid ), $fname );
1759 # Non-existent target may have had broken links to it; these must
1760 # now be removed and made into good links.
1761 $update = new LinksUpdate( $oldid, $nt->getPrefixedDBkey() );
1762 $update->fixBrokenLinks();
1764 # Purge old title from squid
1765 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1766 $titles = $nt->getLinksTo();
1767 if ( $wgUseSquid ) {
1768 $urls = $this->getSquidURLs();
1769 foreach ( $titles as $linkTitle ) {
1770 $urls[] = $linkTitle->getInternalURL();
1772 $u = new SquidUpdate( $urls );
1778 * Checks if $this can be moved to a given Title
1779 * - Selects for update, so don't call it unless you mean business
1781 * @param Title &$nt the new title to check
1784 function isValidMoveTarget( $nt ) {
1786 $fname = 'Title::isValidMoveTarget';
1787 $dbw =& wfGetDB( DB_MASTER
);
1790 $id = $nt->getArticleID();
1791 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1792 array( 'page_is_redirect','old_text' ),
1793 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1794 $fname, 'FOR UPDATE' );
1796 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1801 # Does the redirect point to the source?
1802 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text
, $m ) ) {
1803 $redirTitle = Title
::newFromText( $m[1] );
1804 if( !is_object( $redirTitle ) ||
1805 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1810 # Does the article have a history?
1811 $row = $dbw->selectRow( array( 'page', 'revision'),
1813 array( 'page_namespace' => $nt->getNamespace(),
1814 'page_title' => $nt->getDBkey(),
1815 'page_id=rev_page AND page_latest != rev_id'
1816 ), $fname, 'FOR UPDATE'
1819 # Return true if there was no history
1820 return $row === false;
1824 * Create a redirect; fails if the title already exists; does
1827 * @param Title $dest the destination of the redirect
1828 * @param string $comment the comment string describing the move
1829 * @return bool true on success
1832 function createRedirect( $dest, $comment ) {
1834 if ( $this->getArticleID() ) {
1838 $fname = 'Title::createRedirect';
1839 $dbw =& wfGetDB( DB_MASTER
);
1841 $article = new Article( $this );
1842 $newid = $article->insertOn( $dbw );
1843 $revision = new Revision( array(
1845 'comment' => $comment,
1846 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1848 $revisionId = $revision->insertOn( $dbw );
1849 $article->updateRevisionOn( $dbw, $revision, 0 );
1852 if ( $dest->getArticleID() ) {
1853 $dbw->insert( 'links',
1855 'l_to' => $dest->getArticleID(),
1860 $dbw->insert( 'brokenlinks',
1862 'bl_to' => $dest->getPrefixedDBkey(),
1868 Article
::onArticleCreate( $this );
1873 * Get categories to which this Title belongs and return an array of
1874 * categories' names.
1876 * @return array an array of parents in the form:
1877 * $parent => $currentarticle
1880 function getParentCategories() {
1881 global $wgContLang,$wgUser;
1883 $titlekey = $this->getArticleId();
1884 $sk =& $wgUser->getSkin();
1886 $dbr =& wfGetDB( DB_SLAVE
);
1887 $categorylinks = $dbr->tableName( 'categorylinks' );
1890 $sql = "SELECT * FROM $categorylinks"
1891 ." WHERE cl_from='$titlekey'"
1892 ." AND cl_from <> '0'"
1893 ." ORDER BY cl_sortkey";
1895 $res = $dbr->query ( $sql ) ;
1897 if($dbr->numRows($res) > 0) {
1898 while ( $x = $dbr->fetchObject ( $res ) )
1899 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1900 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1901 $dbr->freeResult ( $res ) ;
1909 * Get a tree of parent categories
1910 * @param array $children an array with the children in the keys, to check for circular refs
1914 function getParentCategoryTree( $children = array() ) {
1915 $parents = $this->getParentCategories();
1917 if($parents != '') {
1918 foreach($parents as $parent => $current)
1920 if ( array_key_exists( $parent, $children ) ) {
1921 # Circular reference
1922 $stack[$parent] = array();
1924 $nt = Title
::newFromText($parent);
1925 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
1936 * Get an associative array for selecting this title from
1942 function curCond() {
1943 wfDebugDieBacktrace( 'curCond called' );
1944 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1948 * Get an associative array for selecting this title from the
1954 function oldCond() {
1955 wfDebugDieBacktrace( 'oldCond called' );
1956 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);
1960 * Get the revision ID of the previous revision
1962 * @param integer $revision Revision ID. Get the revision that was before this one.
1963 * @return interger $oldrevision|false
1965 function getPreviousRevisionID( $revision ) {
1966 $dbr =& wfGetDB( DB_SLAVE
);
1967 return $dbr->selectField( 'revision', 'rev_id',
1968 'rev_page=' . IntVal( $this->getArticleId() ) .
1969 ' AND rev_id<' . IntVal( $revision ) . ' ORDER BY rev_id DESC' );
1973 * Get the revision ID of the next revision
1975 * @param integer $revision Revision ID. Get the revision that was after this one.
1976 * @return interger $oldrevision|false
1978 function getNextRevisionID( $revision ) {
1979 $dbr =& wfGetDB( DB_SLAVE
);
1980 return $dbr->selectField( 'revision', 'rev_id',
1981 'rev_page=' . IntVal( $this->getArticleId() ) .
1982 ' AND rev_id>' . IntVal( $revision ) . ' ORDER BY rev_id' );
1986 * Compare with another title.
1988 * @param Title $title
1991 function equals( &$title ) {
1992 return $this->getInterwiki() == $title->getInterwiki()
1993 && $this->getNamespace() == $title->getNamespace()
1994 && $this->getDbkey() == $title->getDbkey();
1998 * Check if page exists
2002 return $this->getArticleId() != 0;
2006 * Should a link should be displayed as a known link, just based on its title?
2008 * Currently, a self-link with a fragment, special pages and image pages are in
2009 * this category. Special pages never exist in the database. Some images do not
2010 * have description pages in the database, but the description page contains
2011 * useful history information that the user may want to link to.
2014 function isAlwaysKnown() {
2015 return ( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2016 || NS_SPECIAL
== $this->mNamespace || NS_IMAGE
== $this->mNamespace
;