9 require_once( 'normal/UtfNormal.php' );
11 $wgTitleInterwikiCache = array();
12 define ( 'GAID_FOR_UPDATE', 1 );
14 # Title::newFromTitle maintains a cache to avoid
15 # expensive re-normalization of commonly used titles.
16 # On a batch operation this can become a memory leak
17 # if not bounded. After hitting this many titles,
19 define( 'MW_TITLECACHE_MAX', 1000 );
23 * - Represents a title, which may contain an interwiki designation or namespace
24 * - Can fetch various kinds of data from the database, albeit inefficiently.
30 * All member variables should be considered private
31 * Please use the accessor functions
38 var $mTextform; # Text form (spaces not underscores) of the main part
39 var $mUrlform; # URL-encoded form of the main part
40 var $mDbkeyform; # Main part with underscores
41 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
42 var $mInterwiki; # Interwiki prefix (or null string)
43 var $mFragment; # Title fragment (i.e. the bit after the #)
44 var $mArticleID; # Article ID, fetched from the link cache on demand
45 var $mLatestID; # ID of most recent revision
46 var $mRestrictions; # Array of groups allowed to edit this article
47 # Only null or "sysop" are supported
48 var $mRestrictionsLoaded; # Boolean for initialisation on demand
49 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
50 var $mDefaultNamespace; # Namespace index when there is no namespace
51 # Zero except in {{transclusion}} tags
52 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
60 /* private */ function Title() {
61 $this->mInterwiki
= $this->mUrlform
=
62 $this->mTextform
= $this->mDbkeyform
= '';
63 $this->mArticleID
= -1;
64 $this->mNamespace
= NS_MAIN
;
65 $this->mRestrictionsLoaded
= false;
66 $this->mRestrictions
= array();
67 # Dont change the following, NS_MAIN is hardcoded in several place
69 $this->mDefaultNamespace
= NS_MAIN
;
70 $this->mWatched
= NULL;
71 $this->mLatestID
= false;
75 * Create a new Title from a prefixed DB key
76 * @param string $key The database key, which has underscores
77 * instead of spaces, possibly including namespace and
79 * @return Title the new object, or NULL on an error
83 /* static */ function newFromDBkey( $key ) {
85 $t->mDbkeyform
= $key;
86 if( $t->secureAndSplit() )
93 * Create a new Title from text, such as what one would
94 * find in a link. Decodes any HTML entities in the text.
96 * @param string $text the link text; spaces, prefixes,
97 * and an initial ':' indicating the main namespace
99 * @param int $defaultNamespace the namespace to use if
100 * none is specified by a prefix
101 * @return Title the new object, or NULL on an error
105 function newFromText( $text, $defaultNamespace = NS_MAIN
) {
106 $fname = 'Title::newFromText';
107 wfProfileIn( $fname );
109 if( is_object( $text ) ) {
110 wfDebugDieBacktrace( 'Title::newFromText given an object' );
114 * Wiki pages often contain multiple links to the same page.
115 * Title normalization and parsing can become expensive on
116 * pages with many links, so we can save a little time by
119 * In theory these are value objects and won't get changed...
121 static $titleCache = array();
122 if( $defaultNamespace == NS_MAIN
&& isset( $titleCache[$text] ) ) {
123 wfProfileOut( $fname );
124 return $titleCache[$text];
128 * Convert things like é ā or 〗 into real text...
130 $filteredText = Sanitizer
::decodeCharReferences( $text );
133 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
134 $t->mDefaultNamespace
= $defaultNamespace;
136 if( $t->secureAndSplit() ) {
137 if( $defaultNamespace == NS_MAIN
) {
138 if( count( $titleCache ) >= MW_TITLECACHE_MAX
) {
139 # Avoid memory leaks on mass operations...
140 $titleCache = array();
142 $titleCache[$text] =& $t;
144 wfProfileOut( $fname );
147 wfProfileOut( $fname );
154 * Create a new Title from URL-encoded text. Ensures that
155 * the given title's length does not exceed the maximum.
156 * @param string $url the title, as might be taken from a URL
157 * @return Title the new object, or NULL on an error
161 function newFromURL( $url ) {
162 global $wgLang, $wgServer;
165 # For compatibility with old buggy URLs. "+" is not valid in titles,
166 # but some URLs used it as a space replacement and they still come
167 # from some external search tools.
168 $s = str_replace( '+', ' ', $url );
170 $t->mDbkeyform
= str_replace( ' ', '_', $s );
171 if( $t->secureAndSplit() ) {
179 * Create a new Title from an article ID
181 * @todo This is inefficiently implemented, the page row is requested
182 * but not used for anything else
184 * @param int $id the page_id corresponding to the Title to create
185 * @return Title the new object, or NULL on an error
189 function newFromID( $id ) {
190 $fname = 'Title::newFromID';
191 $dbr =& wfGetDB( DB_SLAVE
);
192 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
193 array( 'page_id' => $id ), $fname );
194 if ( $row !== false ) {
195 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
203 * Create a new Title from a namespace index and a DB key.
204 * It's assumed that $ns and $title are *valid*, for instance when
205 * they came directly from the database or a special page name.
206 * For convenience, spaces are converted to underscores so that
207 * eg user_text fields can be used directly.
209 * @param int $ns the namespace of the article
210 * @param string $title the unprefixed database key form
211 * @return Title the new object
215 function &makeTitle( $ns, $title ) {
219 $t->mNamespace
= intval( $ns );
220 $t->mDbkeyform
= str_replace( ' ', '_', $title );
221 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
222 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
223 $t->mTextform
= str_replace( '_', ' ', $title );
228 * Create a new Title frrom a namespace index and a DB key.
229 * The parameters will be checked for validity, which is a bit slower
230 * than makeTitle() but safer for user-provided data.
232 * @param int $ns the namespace of the article
233 * @param string $title the database key form
234 * @return Title the new object, or NULL on an error
238 function makeTitleSafe( $ns, $title ) {
240 $t->mDbkeyform
= Title
::makeName( $ns, $title );
241 if( $t->secureAndSplit() ) {
249 * Create a new Title for the Main Page
252 * @return Title the new object
255 function newMainPage() {
256 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
260 * Create a new Title for a redirect
261 * @param string $text the redirect title text
262 * @return Title the new object, or NULL if the text is not a
267 function newFromRedirect( $text ) {
270 if ( $wgMwRedir->matchStart( $text ) ) {
271 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
272 # categories are escaped using : for example one can enter:
273 # #REDIRECT [[:Category:Music]]. Need to remove it.
274 if ( substr($m[1],0,1) == ':') {
275 # We don't want to keep the ':'
276 $m[1] = substr( $m[1], 1 );
279 $rt = Title
::newFromText( $m[1] );
280 # Disallow redirects to Special:Userlogout
281 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
289 #----------------------------------------------------------------------------
291 #----------------------------------------------------------------------------
294 * Get the prefixed DB key associated with an ID
295 * @param int $id the page_id of the article
296 * @return Title an object representing the article, or NULL
297 * if no such article was found
301 function nameOf( $id ) {
302 $fname = 'Title::nameOf';
303 $dbr =& wfGetDB( DB_SLAVE
);
305 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
306 if ( $s === false ) { return NULL; }
308 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
313 * Get a regex character class describing the legal characters in a link
314 * @return string the list of characters, not delimited
318 function legalChars() {
319 # Missing characters:
320 # * []|# Needed for link syntax
321 # * % and + are corrupted by Apache when they appear in the path
323 # % seems to work though
325 # The problem with % is that URLs are double-unescaped: once by Apache's
326 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
327 # Our code does not double-escape to compensate for this, indeed double escaping
328 # would break if the double-escaped title was passed in the query string
329 # rather than the path. This is a minor security issue because articles can be
330 # created such that they are hard to view or edit. -- TS
332 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
333 # this breaks interlanguage links
335 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF";
340 * Get a string representation of a title suitable for
341 * including in a search index
343 * @param int $ns a namespace index
344 * @param string $title text-form main part
345 * @return string a stripped-down title string ready for the
348 /* static */ function indexTitle( $ns, $title ) {
349 global $wgDBminWordLen, $wgContLang;
350 require_once( 'SearchEngine.php' );
352 $lc = SearchEngine
::legalSearchChars() . '&#;';
353 $t = $wgContLang->stripForSearch( $title );
354 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
355 $t = strtolower( $t );
358 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
359 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
361 $t = preg_replace( "/\\s+/", ' ', $t );
363 if ( $ns == NS_IMAGE
) {
364 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
370 * Make a prefixed DB key from a DB key and a namespace index
371 * @param int $ns numerical representation of the namespace
372 * @param string $title the DB key form the title
373 * @return string the prefixed form of the title
375 /* static */ function makeName( $ns, $title ) {
378 $n = $wgContLang->getNsText( $ns );
379 return $n == '' ?
$title : "$n:$title";
383 * Returns the URL associated with an interwiki prefix
384 * @param string $key the interwiki prefix (e.g. "MeatBall")
385 * @return the associated URL, containing "$1", which should be
386 * replaced by an article title
390 function getInterwikiLink( $key, $transludeonly = false ) {
391 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
392 $fname = 'Title::getInterwikiLink';
394 wfProfileIn( $fname );
396 $k = $wgDBname.':interwiki:'.$key;
397 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
398 wfProfileOut( $fname );
399 return $wgTitleInterwikiCache[$k]->iw_url
;
402 $s = $wgMemc->get( $k );
403 # Ignore old keys with no iw_local
404 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
405 $wgTitleInterwikiCache[$k] = $s;
406 wfProfileOut( $fname );
410 $dbr =& wfGetDB( DB_SLAVE
);
411 $res = $dbr->select( 'interwiki',
412 array( 'iw_url', 'iw_local', 'iw_trans' ),
413 array( 'iw_prefix' => $key ), $fname );
415 wfProfileOut( $fname );
419 $s = $dbr->fetchObject( $res );
421 # Cache non-existence: create a blank object and save it to memcached
427 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
428 $wgTitleInterwikiCache[$k] = $s;
430 wfProfileOut( $fname );
435 * Determine whether the object refers to a page within
438 * @return bool TRUE if this is an in-project interwiki link
439 * or a wikilink, FALSE otherwise
443 global $wgTitleInterwikiCache, $wgDBname;
445 if ( $this->mInterwiki
!= '' ) {
446 # Make sure key is loaded into cache
447 $this->getInterwikiLink( $this->mInterwiki
);
448 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
449 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
456 * Determine whether the object refers to a page within
457 * this project and is transcludable.
459 * @return bool TRUE if this is transcludable
463 global $wgTitleInterwikiCache, $wgDBname;
465 if ($this->mInterwiki
== '' ||
!$this->isLocal())
467 # Make sure key is loaded into cache
468 $this->getInterwikiLink( $this->mInterwiki
);
469 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
470 return (bool)($wgTitleInterwikiCache[$k]->iw_trans
);
474 * Update the page_touched field for an array of title objects
475 * @todo Inefficient unless the IDs are already loaded into the
477 * @param array $titles an array of Title objects to be touched
478 * @param string $timestamp the timestamp to use instead of the
479 * default current time
483 function touchArray( $titles, $timestamp = '' ) {
484 global $wgUseFileCache;
486 if ( count( $titles ) == 0 ) {
489 $dbw =& wfGetDB( DB_MASTER
);
490 if ( $timestamp == '' ) {
491 $timestamp = $dbw->timestamp();
493 $page = $dbw->tableName( 'page' );
495 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
498 foreach ( $titles as $title ) {
499 if ( $wgUseFileCache ) {
500 $cm = new CacheManager($title);
501 @unlink($cm->fileCacheName());
508 $sql .= $title->getArticleID();
512 $dbw->query( $sql, 'Title::touchArray' );
515 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
516 // do them in small chunks:
517 $fname = 'Title::touchArray';
518 foreach( $titles as $title ) {
519 $dbw->update( 'page',
520 array( 'page_touched' => $timestamp ),
522 'page_namespace' => $title->getNamespace(),
523 'page_title' => $title->getDBkey() ),
528 #----------------------------------------------------------------------------
530 #----------------------------------------------------------------------------
532 /** Simple accessors */
534 * Get the text form (spaces not underscores) of the main part
538 function getText() { return $this->mTextform
; }
540 * Get the URL-encoded form of the main part
544 function getPartialURL() { return $this->mUrlform
; }
546 * Get the main part with underscores
550 function getDBkey() { return $this->mDbkeyform
; }
552 * Get the namespace index, i.e. one of the NS_xxxx constants
556 function getNamespace() { return $this->mNamespace
; }
558 * Get the namespace text
562 function getNsText() {
564 return $wgContLang->getNsText( $this->mNamespace
);
567 * Get the namespace text of the subject (rather than talk) page
571 function getSubjectNsText() {
573 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
577 * Get the interwiki prefix (or null string)
581 function getInterwiki() { return $this->mInterwiki
; }
583 * Get the Title fragment (i.e. the bit after the #)
587 function getFragment() { return $this->mFragment
; }
589 * Get the default namespace index, for when there is no namespace
593 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
596 * Get title for search index
597 * @return string a stripped-down title string ready for the
600 function getIndexTitle() {
601 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
605 * Get the prefixed database key form
606 * @return string the prefixed title, with underscores and
607 * any interwiki and namespace prefixes
610 function getPrefixedDBkey() {
611 $s = $this->prefix( $this->mDbkeyform
);
612 $s = str_replace( ' ', '_', $s );
617 * Get the prefixed title with spaces.
618 * This is the form usually used for display
619 * @return string the prefixed title, with spaces
622 function getPrefixedText() {
624 if ( empty( $this->mPrefixedText
) ) {
625 $s = $this->prefix( $this->mTextform
);
626 $s = str_replace( '_', ' ', $s );
627 $this->mPrefixedText
= $s;
629 return $this->mPrefixedText
;
633 * Get the prefixed title with spaces, plus any fragment
634 * (part beginning with '#')
635 * @return string the prefixed title, with spaces and
636 * the fragment, including '#'
639 function getFullText() {
641 $text = $this->getPrefixedText();
642 if( '' != $this->mFragment
) {
643 $text .= '#' . $this->mFragment
;
649 * Get a URL-encoded title (not an actual URL) including interwiki
650 * @return string the URL-encoded form
653 function getPrefixedURL() {
654 $s = $this->prefix( $this->mDbkeyform
);
655 $s = str_replace( ' ', '_', $s );
657 $s = wfUrlencode ( $s ) ;
659 # Cleaning up URL to make it look nice -- is this safe?
660 $s = str_replace( '%28', '(', $s );
661 $s = str_replace( '%29', ')', $s );
667 * Get a real URL referring to this title, with interwiki link and
670 * @param string $query an optional query string, not used
671 * for interwiki links
672 * @return string the URL
675 function getFullURL( $query = '' ) {
676 global $wgContLang, $wgServer, $wgScript, $wgMakeDumpLinks, $wgArticlePath;
678 if ( '' == $this->mInterwiki
) {
679 return $wgServer . $this->getLocalUrl( $query );
680 } elseif ( $wgMakeDumpLinks && $wgContLang->getLanguageName( $this->mInterwiki
) ) {
681 $baseUrl = str_replace( '$1', "../../{$this->mInterwiki}/$1", $wgArticlePath );
682 $baseUrl = str_replace( '$1', $this->getHashedDirectory() . '/$1', $baseUrl );
684 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
687 $namespace = $wgContLang->getNsText( $this->mNamespace
);
688 if ( '' != $namespace ) {
689 # Can this actually happen? Interwikis shouldn't be parsed.
692 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
694 if( false === strpos( $url, '?' ) ) {
701 if ( '' != $this->mFragment
) {
702 $url .= '#' . $this->mFragment
;
708 * Get a relative directory for putting an HTML version of this article into
710 function getHashedDirectory() {
711 global $wgMakeDumpLinks, $wgInputEncoding;
712 $dbkey = $this->getDBkey();
714 # Split into characters
715 if ( $wgInputEncoding == 'UTF-8' ) {
716 preg_match_all( '/./us', $dbkey, $m );
718 preg_match_all( '/./s', $dbkey, $m );
721 $length = count( $chars );
724 for ( $i = 0; $i < $wgMakeDumpLinks; $i++
) {
728 if ( $i >= $length ) {
730 } elseif ( ord( $chars[$i] ) > 32 ) {
731 $dir .= strtolower( $chars[$i] );
733 $dir .= sprintf( "%02X", ord( $chars[$i] ) );
739 function getHashedFilename() {
740 $dbkey = $this->getPrefixedDBkey();
741 $mainPage = Title
::newMainPage();
742 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
746 $dir = $this->getHashedDirectory();
748 # Replace illegal charcters for Windows paths with underscores
749 $friendlyName = strtr( $dbkey, '/\\*?"<>|~', '_________' );
751 # Work out lower case form. We assume we're on a system with case-insensitive
752 # filenames, so unless the case is of a special form, we have to disambiguate
753 $lowerCase = $this->prefix( ucfirst( strtolower( $this->getDBkey() ) ) );
755 # Make it mostly unique
756 if ( $lowerCase != $friendlyName ) {
757 $friendlyName .= '_' . substr(md5( $dbkey ), 0, 4);
759 # Handle colon specially by replacing it with tilde
760 # Thus we reduce the number of paths with hashes appended
761 $friendlyName = str_replace( ':', '~', $friendlyName );
762 return "$dir/$friendlyName.html";
766 * Get a URL with no fragment or server name. If this page is generated
767 * with action=render, $wgServer is prepended.
768 * @param string $query an optional query string; if not specified,
769 * $wgArticlePath will be used.
770 * @return string the URL
773 function getLocalURL( $query = '' ) {
774 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks, $wgServer, $action;
776 if ( $this->isExternal() ) {
777 return $this->getFullURL();
780 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
781 if ( $wgMakeDumpLinks ) {
782 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
783 } elseif ( $query == '' ) {
784 $url = str_replace( '$1', $dbkey, $wgArticlePath );
786 global $wgActionPaths;
787 if( !empty( $wgActionPaths ) &&
788 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
789 $action = urldecode( $matches[2] );
790 if( isset( $wgActionPaths[$action] ) ) {
791 $query = $matches[1];
792 if( isset( $matches[4] ) ) $query .= $matches[4];
793 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
794 if( $query != '' ) $url .= '?' . $query;
798 if ( $query == '-' ) {
801 $url = "{$wgScript}?title={$dbkey}&{$query}";
804 if ($action == 'render')
805 return $wgServer . $url;
811 * Get an HTML-escaped version of the URL form, suitable for
812 * using in a link, without a server name or fragment
813 * @param string $query an optional query string
814 * @return string the URL
817 function escapeLocalURL( $query = '' ) {
818 return htmlspecialchars( $this->getLocalURL( $query ) );
822 * Get an HTML-escaped version of the URL form, suitable for
823 * using in a link, including the server name and fragment
825 * @return string the URL
826 * @param string $query an optional query string
829 function escapeFullURL( $query = '' ) {
830 return htmlspecialchars( $this->getFullURL( $query ) );
834 * Get the URL form for an internal link.
835 * - Used in various Squid-related code, in case we have a different
836 * internal hostname for the server from the exposed one.
838 * @param string $query an optional query string
839 * @return string the URL
842 function getInternalURL( $query = '' ) {
843 global $wgInternalServer;
844 return $wgInternalServer . $this->getLocalURL( $query );
848 * Get the edit URL for this Title
849 * @return string the URL, or a null string if this is an
853 function getEditURL() {
854 global $wgServer, $wgScript;
856 if ( '' != $this->mInterwiki
) { return ''; }
857 $s = $this->getLocalURL( 'action=edit' );
863 * Get the HTML-escaped displayable text form.
864 * Used for the title field in <a> tags.
865 * @return string the text, including any prefixes
868 function getEscapedText() {
869 return htmlspecialchars( $this->getPrefixedText() );
873 * Is this Title interwiki?
877 function isExternal() { return ( '' != $this->mInterwiki
); }
880 * Does the title correspond to a protected article?
881 * @param string $what the action the page is protected from,
882 * by default checks move and edit
886 function isProtected($action = '') {
887 if ( -1 == $this->mNamespace
) { return true; }
888 if($action == 'edit' ||
$action == '') {
889 $a = $this->getRestrictions("edit");
890 if ( in_array( 'sysop', $a ) ) { return true; }
892 if($action == 'move' ||
$action == '') {
893 $a = $this->getRestrictions("move");
894 if ( in_array( 'sysop', $a ) ) { return true; }
900 * Is $wgUser is watching this page?
904 function userIsWatching() {
907 if ( is_null( $this->mWatched
) ) {
908 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
909 $this->mWatched
= false;
911 $this->mWatched
= $wgUser->isWatched( $this );
914 return $this->mWatched
;
918 * Is $wgUser perform $action this page?
919 * @param string $action action that permission needs to be checked for
923 function userCan($action) {
924 $fname = 'Title::userCanEdit';
925 wfProfileIn( $fname );
928 if( NS_SPECIAL
== $this->mNamespace
) {
929 wfProfileOut( $fname );
932 if( NS_MEDIAWIKI
== $this->mNamespace
&&
933 !$wgUser->isAllowed('editinterface') ) {
934 wfProfileOut( $fname );
937 if( $this->mDbkeyform
== '_' ) {
938 # FIXME: Is this necessary? Shouldn't be allowed anyway...
939 wfProfileOut( $fname );
943 # protect global styles and js
944 if ( NS_MEDIAWIKI
== $this->mNamespace
945 && preg_match("/\\.(css|js)$/", $this->mTextform
)
946 && !$wgUser->isAllowed('editinterface') ) {
947 wfProfileOut( $fname );
951 # protect css/js subpages of user pages
952 # XXX: this might be better using restrictions
953 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
954 if( NS_USER
== $this->mNamespace
955 && preg_match("/\\.(css|js)$/", $this->mTextform
)
956 && !$wgUser->isAllowed('editinterface')
957 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
958 wfProfileOut( $fname );
962 foreach( $this->getRestrictions($action) as $right ) {
963 // Backwards compatibility, rewrite sysop -> protect
964 if ( $right == 'sysop' ) {
967 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
968 wfProfileOut( $fname );
973 if( $action == 'move' &&
974 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
975 wfProfileOut( $fname );
979 wfProfileOut( $fname );
984 * Can $wgUser edit this page?
988 function userCanEdit() {
989 return $this->userCan('edit');
993 * Can $wgUser move this page?
997 function userCanMove() {
998 return $this->userCan('move');
1002 * Would anybody with sufficient privileges be able to move this page?
1003 * Some pages just aren't movable.
1008 function isMovable() {
1009 return Namespace::isMovable( $this->getNamespace() )
1010 && $this->getInterwiki() == '';
1014 * Can $wgUser read this page?
1018 function userCanRead() {
1021 if( $wgUser->isAllowed('read') ) {
1024 global $wgWhitelistRead;
1026 /** If anon users can create an account,
1027 they need to reach the login page first! */
1028 if( $wgUser->isAllowed( 'createaccount' )
1029 && $this->getNamespace() == NS_SPECIAL
1030 && $this->getText() == 'Userlogin' ) {
1034 /** some pages are explicitly allowed */
1035 $name = $this->getPrefixedText();
1036 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1040 # Compatibility with old settings
1041 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1042 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1051 * Is this a talk page of some sort?
1055 function isTalkPage() {
1056 return Namespace::isTalk( $this->getNamespace() );
1060 * Is this a .css or .js subpage of a user page?
1064 function isCssJsSubpage() {
1065 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1068 * Is this a .css subpage of a user page?
1072 function isCssSubpage() {
1073 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1076 * Is this a .js subpage of a user page?
1080 function isJsSubpage() {
1081 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1084 * Protect css/js subpages of user pages: can $wgUser edit
1088 * @todo XXX: this might be better using restrictions
1091 function userCanEditCssJsSubpage() {
1093 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1097 * Loads a string into mRestrictions array
1098 * @param string $res restrictions in string format
1101 function loadRestrictions( $res ) {
1102 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1103 $temp = explode( '=', trim( $restrict ) );
1104 if(count($temp) == 1) {
1105 // old format should be treated as edit/move restriction
1106 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1107 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1109 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1112 $this->mRestrictionsLoaded
= true;
1116 * Accessor/initialisation for mRestrictions
1117 * @param string $action action that permission needs to be checked for
1118 * @return array the array of groups allowed to edit this article
1121 function getRestrictions($action) {
1122 $id = $this->getArticleID();
1123 if ( 0 == $id ) { return array(); }
1125 if ( ! $this->mRestrictionsLoaded
) {
1126 $dbr =& wfGetDB( DB_SLAVE
);
1127 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1128 $this->loadRestrictions( $res );
1130 if( isset( $this->mRestrictions
[$action] ) ) {
1131 return $this->mRestrictions
[$action];
1137 * Is there a version of this page in the deletion archive?
1138 * @return int the number of archived revisions
1141 function isDeleted() {
1142 $fname = 'Title::isDeleted';
1143 if ( $this->getNamespace() < 0 ) {
1146 $dbr =& wfGetDB( DB_SLAVE
);
1147 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1148 'ar_title' => $this->getDBkey() ), $fname );
1154 * Get the article ID for this Title from the link cache,
1155 * adding it if necessary
1156 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1158 * @return int the ID
1161 function getArticleID( $flags = 0 ) {
1162 global $wgLinkCache;
1163 if ( $flags & GAID_FOR_UPDATE
) {
1164 $oldUpdate = $wgLinkCache->forUpdate( true );
1165 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1166 $wgLinkCache->forUpdate( $oldUpdate );
1168 if ( -1 == $this->mArticleID
) {
1169 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1172 return $this->mArticleID
;
1175 function getLatestRevID() {
1176 if ($this->mLatestID
!== false)
1177 return $this->mLatestID
;
1179 $db =& wfGetDB(DB_SLAVE
);
1180 return $this->mLatestID
= $db->selectField( 'revision',
1182 array('rev_page' => $this->getArticleID()),
1183 'Title::getLatestRevID' );
1187 * This clears some fields in this object, and clears any associated
1188 * keys in the "bad links" section of $wgLinkCache.
1190 * - This is called from Article::insertNewArticle() to allow
1191 * loading of the new page_id. It's also called from
1192 * Article::doDeleteArticle()
1194 * @param int $newid the new Article ID
1197 function resetArticleID( $newid ) {
1198 global $wgLinkCache;
1199 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1201 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1202 else { $this->mArticleID
= $newid; }
1203 $this->mRestrictionsLoaded
= false;
1204 $this->mRestrictions
= array();
1208 * Updates page_touched for this page; called from LinksUpdate.php
1209 * @return bool true if the update succeded
1212 function invalidateCache() {
1213 global $wgUseFileCache;
1215 if ( wfReadOnly() ) {
1219 $now = wfTimestampNow();
1220 $dbw =& wfGetDB( DB_MASTER
);
1221 $success = $dbw->update( 'page',
1223 'page_touched' => $dbw->timestamp()
1224 ), array( /* WHERE */
1225 'page_namespace' => $this->getNamespace() ,
1226 'page_title' => $this->getDBkey()
1227 ), 'Title::invalidateCache'
1230 if ($wgUseFileCache) {
1231 $cache = new CacheManager($this);
1232 @unlink
($cache->fileCacheName());
1239 * Prefix some arbitrary text with the namespace or interwiki prefix
1242 * @param string $name the text
1243 * @return string the prefixed text
1246 /* private */ function prefix( $name ) {
1250 if ( '' != $this->mInterwiki
) {
1251 $p = $this->mInterwiki
. ':';
1253 if ( 0 != $this->mNamespace
) {
1254 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1260 * Secure and split - main initialisation function for this object
1262 * Assumes that mDbkeyform has been set, and is urldecoded
1263 * and uses underscores, but not otherwise munged. This function
1264 * removes illegal characters, splits off the interwiki and
1265 * namespace prefixes, sets the other forms, and canonicalizes
1267 * @return bool true on success
1270 /* private */ function secureAndSplit() {
1271 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1272 $fname = 'Title::secureAndSplit';
1273 wfProfileIn( $fname );
1276 static $rxTc = false;
1278 # % is needed as well
1279 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1282 $this->mInterwiki
= $this->mFragment
= '';
1283 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1285 # Clean up whitespace
1287 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1288 $t = trim( $t, '_' );
1291 wfProfileOut( $fname );
1295 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1296 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1297 wfProfileOut( $fname );
1301 $this->mDbkeyform
= $t;
1303 # Initial colon indicates main namespace rather than specified default
1304 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1305 if ( ':' == $t{0} ) {
1306 $this->mNamespace
= NS_MAIN
;
1307 $t = substr( $t, 1 ); # remove the colon but continue processing
1310 # Namespace or interwiki prefix
1313 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1315 $lowerNs = strtolower( $p );
1316 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1317 # Canonical namespace
1319 $this->mNamespace
= $ns;
1320 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1321 # Ordinary namespace
1323 $this->mNamespace
= $ns;
1324 } elseif( $this->getInterwikiLink( $p ) ) {
1326 # Can't make a local interwiki link to an interwiki link.
1327 # That's just crazy!
1328 wfProfileOut( $fname );
1334 $this->mInterwiki
= $p;
1336 # Redundant interwiki prefix to the local wiki
1337 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1339 # Can't have an empty self-link
1340 wfProfileOut( $fname );
1343 $this->mInterwiki
= '';
1345 # Do another namespace split...
1349 # If there's no recognized interwiki or namespace,
1350 # then let the colon expression be part of the title.
1356 # We already know that some pages won't be in the database!
1358 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1359 $this->mArticleID
= 0;
1361 $f = strstr( $r, '#' );
1362 if ( false !== $f ) {
1363 $this->mFragment
= substr( $f, 1 );
1364 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1365 # remove whitespace again: prevents "Foo_bar_#"
1366 # becoming "Foo_bar_"
1367 $r = preg_replace( '/_*$/', '', $r );
1370 # Reject illegal characters.
1372 if( preg_match( $rxTc, $r ) ) {
1373 wfProfileOut( $fname );
1378 * Pages with "/./" or "/../" appearing in the URLs will
1379 * often be unreachable due to the way web browsers deal
1380 * with 'relative' URLs. Forbid them explicitly.
1382 if ( strpos( $r, '.' ) !== false &&
1383 ( $r === '.' ||
$r === '..' ||
1384 strpos( $r, './' ) === 0 ||
1385 strpos( $r, '../' ) === 0 ||
1386 strpos( $r, '/./' ) !== false ||
1387 strpos( $r, '/../' ) !== false ) )
1389 wfProfileOut( $fname );
1393 # We shouldn't need to query the DB for the size.
1394 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1395 if ( strlen( $r ) > 255 ) {
1396 wfProfileOut( $fname );
1401 * Normally, all wiki links are forced to have
1402 * an initial capital letter so [[foo]] and [[Foo]]
1403 * point to the same place.
1405 * Don't force it for interwikis, since the other
1406 * site might be case-sensitive.
1408 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1409 $t = $wgContLang->ucfirst( $r );
1415 * Can't make a link to a namespace alone...
1416 * "empty" local links can only be self-links
1417 * with a fragment identifier.
1420 $this->mInterwiki
== '' &&
1421 $this->mNamespace
!= NS_MAIN
) {
1422 wfProfileOut( $fname );
1427 $this->mDbkeyform
= $t;
1428 $this->mUrlform
= wfUrlencode( $t );
1430 $this->mTextform
= str_replace( '_', ' ', $t );
1432 wfProfileOut( $fname );
1437 * Get a Title object associated with the talk page of this article
1438 * @return Title the object for the talk page
1441 function getTalkPage() {
1442 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1446 * Get a title object associated with the subject page of this
1449 * @return Title the object for the subject page
1452 function getSubjectPage() {
1453 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1457 * Get an array of Title objects linking to this Title
1458 * Also stores the IDs in the link cache.
1460 * @param string $options may be FOR UPDATE
1461 * @return array the Title objects linking here
1464 function getLinksTo( $options = '' ) {
1465 global $wgLinkCache;
1466 $id = $this->getArticleID();
1469 $db =& wfGetDB( DB_MASTER
);
1471 $db =& wfGetDB( DB_SLAVE
);
1474 $res = $db->select( array( 'page', 'pagelinks' ),
1475 array( 'page_namespace', 'page_title', 'page_id' ),
1478 'pl_namespace' => $this->getNamespace(),
1479 'pl_title' => $this->getDbKey() ),
1480 'Title::getLinksTo',
1484 if ( $db->numRows( $res ) ) {
1485 while ( $row = $db->fetchObject( $res ) ) {
1486 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1487 $wgLinkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1488 $retVal[] = $titleObj;
1492 $db->freeResult( $res );
1497 * Get an array of Title objects referring to non-existent articles linked from this page
1499 * @param string $options may be FOR UPDATE
1500 * @return array the Title objects
1503 function getBrokenLinksFrom( $options = '' ) {
1504 global $wgLinkCache;
1507 $db =& wfGetDB( DB_MASTER
);
1509 $db =& wfGetDB( DB_SLAVE
);
1512 $res = $db->safeQuery(
1513 "SELECT pl_namespace, pl_title
1516 ON pl_namespace=page_namespace
1517 AND pl_title=page_title
1519 AND page_namespace IS NULL
1521 $db->tableName( 'pagelinks' ),
1522 $db->tableName( 'page' ),
1523 $this->getArticleId(),
1527 if ( $db->numRows( $res ) ) {
1528 while ( $row = $db->fetchObject( $res ) ) {
1529 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1532 $db->freeResult( $res );
1538 * Get a list of URLs to purge from the Squid cache when this
1541 * @return array the URLs
1544 function getSquidURLs() {
1546 $this->getInternalURL(),
1547 $this->getInternalURL( 'action=history' )
1552 * Move this page without authentication
1553 * @param Title &$nt the new page Title
1556 function moveNoAuth( &$nt ) {
1557 return $this->moveTo( $nt, false );
1561 * Check whether a given move operation would be valid.
1562 * Returns true if ok, or a message key string for an error message
1563 * if invalid. (Scarrrrry ugly interface this.)
1564 * @param Title &$nt the new title
1565 * @param bool $auth indicates whether $wgUser's permissions
1567 * @return mixed true on success, message name on failure
1570 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1572 if( !$this or !$nt ) {
1573 return 'badtitletext';
1575 if( $this->equals( $nt ) ) {
1578 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1579 return 'immobile_namespace';
1582 $fname = 'Title::move';
1583 $oldid = $this->getArticleID();
1584 $newid = $nt->getArticleID();
1586 if ( strlen( $nt->getDBkey() ) < 1 ) {
1587 return 'articleexists';
1589 if ( ( '' == $this->getDBkey() ) ||
1591 ( '' == $nt->getDBkey() ) ) {
1592 return 'badarticleerror';
1596 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1597 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1598 return 'protectedpage';
1601 # The move is allowed only if (1) the target doesn't exist, or
1602 # (2) the target is a redirect to the source, and has no history
1603 # (so we can undo bad moves right after they're done).
1605 if ( 0 != $newid ) { # Target exists; check for validity
1606 if ( ! $this->isValidMoveTarget( $nt ) ) {
1607 return 'articleexists';
1614 * Move a title to a new location
1615 * @param Title &$nt the new title
1616 * @param bool $auth indicates whether $wgUser's permissions
1618 * @return mixed true on success, message name on failure
1621 function moveTo( &$nt, $auth = true, $reason = '' ) {
1622 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1623 if( is_string( $err ) ) {
1627 $pageid = $this->getArticleID();
1628 if( $nt->exists() ) {
1629 $this->moveOverExistingRedirect( $nt, $reason );
1630 $pageCountChange = 0;
1631 } else { # Target didn't exist, do normal move.
1632 $this->moveToNewTitle( $nt, $newid, $reason );
1633 $pageCountChange = 1;
1635 $redirid = $this->getArticleID();
1637 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1638 $dbw =& wfGetDB( DB_MASTER
);
1639 $categorylinks = $dbw->tableName( 'categorylinks' );
1640 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1641 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1642 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1643 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1647 $oldnamespace = $this->getNamespace() & ~
1;
1648 $newnamespace = $nt->getNamespace() & ~
1;
1649 $oldtitle = $this->getDBkey();
1650 $newtitle = $nt->getDBkey();
1652 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1653 WatchedItem
::duplicateEntries( $this, $nt );
1656 # Update search engine
1657 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1659 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1663 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1664 # Moved out of main namespace
1665 # not viewed, edited, removing
1666 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1667 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1668 # Moved into main namespace
1669 # not viewed, edited, adding
1670 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1671 } elseif ( $pageCountChange ) {
1673 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1681 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1686 * Move page to a title which is at present a redirect to the
1689 * @param Title &$nt the page to move to, which should currently
1693 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1694 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1695 $fname = 'Title::moveOverExistingRedirect';
1696 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1699 $comment .= ": $reason";
1702 $now = wfTimestampNow();
1704 $newid = $nt->getArticleID();
1705 $oldid = $this->getArticleID();
1706 $dbw =& wfGetDB( DB_MASTER
);
1707 $links = $dbw->tableName( 'links' );
1709 # Delete the old redirect. We don't save it to history since
1710 # by definition if we've got here it's rather uninteresting.
1711 # We have to remove it so that the next step doesn't trigger
1712 # a conflict on the unique namespace+title index...
1713 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1715 # Save a null revision in the page's history notifying of the move
1716 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1717 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1719 $nullRevId = $nullRevision->insertOn( $dbw );
1721 # Change the name of the target page:
1722 $dbw->update( 'page',
1724 'page_touched' => $dbw->timestamp($now),
1725 'page_namespace' => $nt->getNamespace(),
1726 'page_title' => $nt->getDBkey(),
1727 'page_latest' => $nullRevId,
1729 /* WHERE */ array( 'page_id' => $oldid ),
1732 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1734 # Recreate the redirect, this time in the other direction.
1735 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1736 $redirectArticle = new Article( $this );
1737 $newid = $redirectArticle->insertOn( $dbw );
1738 $redirectRevision = new Revision( array(
1740 'comment' => $comment,
1741 'text' => $redirectText ) );
1742 $revid = $redirectRevision->insertOn( $dbw );
1743 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1744 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1747 $log = new LogPage( 'move' );
1748 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1750 # Now, we record the link from the redirect to the new title.
1751 # It should have no other outgoing links...
1752 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1753 $dbw->insert( 'pagelinks',
1755 'pl_from' => $newid,
1756 'pl_namespace' => $nt->getNamespace(),
1757 'pl_title' => $nt->getDbKey() ),
1761 if ( $wgUseSquid ) {
1762 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1763 $u = new SquidUpdate( $urls );
1769 * Move page to non-existing title.
1770 * @param Title &$nt the new Title
1771 * @param int &$newid set to be the new article ID
1774 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1775 global $wgUser, $wgLinkCache, $wgUseSquid;
1777 $fname = 'MovePageForm::moveToNewTitle';
1778 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1780 $comment .= ": $reason";
1783 $newid = $nt->getArticleID();
1784 $oldid = $this->getArticleID();
1785 $dbw =& wfGetDB( DB_MASTER
);
1786 $now = $dbw->timestamp();
1790 # Save a null revision in the page's history notifying of the move
1791 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1792 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1794 $nullRevId = $nullRevision->insertOn( $dbw );
1797 $dbw->update( 'page',
1799 'page_touched' => $now,
1800 'page_namespace' => $nt->getNamespace(),
1801 'page_title' => $nt->getDBkey(),
1802 'page_latest' => $nullRevId,
1804 /* WHERE */ array( 'page_id' => $oldid ),
1808 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1811 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1812 $redirectArticle = new Article( $this );
1813 $newid = $redirectArticle->insertOn( $dbw );
1814 $redirectRevision = new Revision( array(
1816 'comment' => $comment,
1817 'text' => $redirectText ) );
1818 $revid = $redirectRevision->insertOn( $dbw );
1819 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1820 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1823 $log = new LogPage( 'move' );
1824 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1826 # Purge caches as per article creation
1827 Article
::onArticleCreate( $nt );
1829 # Record the just-created redirect's linking to the page
1830 $dbw->insert( 'pagelinks',
1832 'pl_from' => $newid,
1833 'pl_namespace' => $nt->getNamespace(),
1834 'pl_title' => $nt->getDBkey() ),
1837 # Non-existent target may have had broken links to it; these must
1838 # now be touched to update link coloring.
1841 # Purge old title from squid
1842 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1843 $titles = $nt->getLinksTo();
1844 if ( $wgUseSquid ) {
1845 $urls = $this->getSquidURLs();
1846 foreach ( $titles as $linkTitle ) {
1847 $urls[] = $linkTitle->getInternalURL();
1849 $u = new SquidUpdate( $urls );
1855 * Checks if $this can be moved to a given Title
1856 * - Selects for update, so don't call it unless you mean business
1858 * @param Title &$nt the new title to check
1861 function isValidMoveTarget( $nt ) {
1863 $fname = 'Title::isValidMoveTarget';
1864 $dbw =& wfGetDB( DB_MASTER
);
1867 $id = $nt->getArticleID();
1868 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1869 array( 'page_is_redirect','old_text' ),
1870 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1871 $fname, 'FOR UPDATE' );
1873 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1878 # Does the redirect point to the source?
1879 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text
, $m ) ) {
1880 $redirTitle = Title
::newFromText( $m[1] );
1881 if( !is_object( $redirTitle ) ||
1882 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1887 # Does the article have a history?
1888 $row = $dbw->selectRow( array( 'page', 'revision'),
1890 array( 'page_namespace' => $nt->getNamespace(),
1891 'page_title' => $nt->getDBkey(),
1892 'page_id=rev_page AND page_latest != rev_id'
1893 ), $fname, 'FOR UPDATE'
1896 # Return true if there was no history
1897 return $row === false;
1901 * Create a redirect; fails if the title already exists; does
1904 * @param Title $dest the destination of the redirect
1905 * @param string $comment the comment string describing the move
1906 * @return bool true on success
1909 function createRedirect( $dest, $comment ) {
1911 if ( $this->getArticleID() ) {
1915 $fname = 'Title::createRedirect';
1916 $dbw =& wfGetDB( DB_MASTER
);
1918 $article = new Article( $this );
1919 $newid = $article->insertOn( $dbw );
1920 $revision = new Revision( array(
1922 'comment' => $comment,
1923 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1925 $revisionId = $revision->insertOn( $dbw );
1926 $article->updateRevisionOn( $dbw, $revision, 0 );
1929 $dbw->insert( 'pagelinks',
1931 'pl_from' => $newid,
1932 'pl_namespace' => $dest->getNamespace(),
1933 'pl_title' => $dest->getDbKey()
1937 Article
::onArticleCreate( $this );
1942 * Get categories to which this Title belongs and return an array of
1943 * categories' names.
1945 * @return array an array of parents in the form:
1946 * $parent => $currentarticle
1949 function getParentCategories() {
1950 global $wgContLang,$wgUser;
1952 $titlekey = $this->getArticleId();
1953 $sk =& $wgUser->getSkin();
1955 $dbr =& wfGetDB( DB_SLAVE
);
1956 $categorylinks = $dbr->tableName( 'categorylinks' );
1959 $sql = "SELECT * FROM $categorylinks"
1960 ." WHERE cl_from='$titlekey'"
1961 ." AND cl_from <> '0'"
1962 ." ORDER BY cl_sortkey";
1964 $res = $dbr->query ( $sql ) ;
1966 if($dbr->numRows($res) > 0) {
1967 while ( $x = $dbr->fetchObject ( $res ) )
1968 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1969 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1970 $dbr->freeResult ( $res ) ;
1978 * Get a tree of parent categories
1979 * @param array $children an array with the children in the keys, to check for circular refs
1983 function getParentCategoryTree( $children = array() ) {
1984 $parents = $this->getParentCategories();
1986 if($parents != '') {
1987 foreach($parents as $parent => $current)
1989 if ( array_key_exists( $parent, $children ) ) {
1990 # Circular reference
1991 $stack[$parent] = array();
1993 $nt = Title
::newFromText($parent);
1994 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2005 * Get an associative array for selecting this title from
2011 function curCond() {
2012 wfDebugDieBacktrace( 'curCond called' );
2013 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
2017 * Get an associative array for selecting this title from the
2023 function oldCond() {
2024 wfDebugDieBacktrace( 'oldCond called' );
2025 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);
2029 * Get the revision ID of the previous revision
2031 * @param integer $revision Revision ID. Get the revision that was before this one.
2032 * @return interger $oldrevision|false
2034 function getPreviousRevisionID( $revision ) {
2035 $dbr =& wfGetDB( DB_SLAVE
);
2036 return $dbr->selectField( 'revision', 'rev_id',
2037 'rev_page=' . intval( $this->getArticleId() ) .
2038 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2042 * Get the revision ID of the next revision
2044 * @param integer $revision Revision ID. Get the revision that was after this one.
2045 * @return interger $oldrevision|false
2047 function getNextRevisionID( $revision ) {
2048 $dbr =& wfGetDB( DB_SLAVE
);
2049 return $dbr->selectField( 'revision', 'rev_id',
2050 'rev_page=' . intval( $this->getArticleId() ) .
2051 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2055 * Compare with another title.
2057 * @param Title $title
2060 function equals( &$title ) {
2061 return $this->getInterwiki() == $title->getInterwiki()
2062 && $this->getNamespace() == $title->getNamespace()
2063 && $this->getDbkey() == $title->getDbkey();
2067 * Check if page exists
2071 return $this->getArticleId() != 0;
2075 * Should a link should be displayed as a known link, just based on its title?
2077 * Currently, a self-link with a fragment, special pages and image pages are in
2078 * this category. Special pages never exist in the database. Some images do not
2079 * have description pages in the database, but the description page contains
2080 * useful history information that the user may want to link to.
2082 function isAlwaysKnown() {
2083 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2084 || NS_SPECIAL
== $this->mNamespace || NS_IMAGE
== $this->mNamespace
;
2088 * Update page_touched timestamps on pages linking to this title.
2089 * In principal, this could be backgrounded and could also do squid
2092 function touchLinks() {
2093 $fname = 'Title::touchLinks';
2095 $dbw =& wfGetDB( DB_MASTER
);
2097 $res = $dbw->select( 'pagelinks',
2100 'pl_namespace' => $this->getNamespace(),
2101 'pl_title' => $this->getDbKey() ),
2103 if ( 0 == $dbw->numRows( $res ) ) {
2108 $toucharr = array();
2109 while( $row = $dbw->fetchObject( $res ) ) {
2110 $toucharr[] = $row->pl_from
;
2112 if (!count($toucharr))
2114 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2115 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2118 function trackbackURL() {
2119 global $wgTitle, $wgScriptPath, $wgServer;
2121 return "$wgServer$wgScriptPath/trackback.php?article="
2122 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2125 function trackbackRDF() {
2126 $url = htmlspecialchars($this->getFullURL());
2127 $title = htmlspecialchars($this->getText());
2128 $tburl = $this->trackbackURL();
2131 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2132 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2133 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2136 dc:identifier=\"$url\"
2138 trackback:ping=\"$tburl\" />