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 interwiki prefix (or null string)
562 function getInterwiki() { return $this->mInterwiki
; }
564 * Get the Title fragment (i.e. the bit after the #)
568 function getFragment() { return $this->mFragment
; }
570 * Get the default namespace index, for when there is no namespace
574 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
577 * Get title for search index
578 * @return string a stripped-down title string ready for the
581 function getIndexTitle() {
582 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
586 * Get the prefixed database key form
587 * @return string the prefixed title, with underscores and
588 * any interwiki and namespace prefixes
591 function getPrefixedDBkey() {
592 $s = $this->prefix( $this->mDbkeyform
);
593 $s = str_replace( ' ', '_', $s );
598 * Get the prefixed title with spaces.
599 * This is the form usually used for display
600 * @return string the prefixed title, with spaces
603 function getPrefixedText() {
605 if ( empty( $this->mPrefixedText
) ) {
606 $s = $this->prefix( $this->mTextform
);
607 $s = str_replace( '_', ' ', $s );
608 $this->mPrefixedText
= $s;
610 return $this->mPrefixedText
;
614 * Get the prefixed title with spaces, plus any fragment
615 * (part beginning with '#')
616 * @return string the prefixed title, with spaces and
617 * the fragment, including '#'
620 function getFullText() {
622 $text = $this->getPrefixedText();
623 if( '' != $this->mFragment
) {
624 $text .= '#' . $this->mFragment
;
630 * Get a URL-encoded title (not an actual URL) including interwiki
631 * @return string the URL-encoded form
634 function getPrefixedURL() {
635 $s = $this->prefix( $this->mDbkeyform
);
636 $s = str_replace( ' ', '_', $s );
638 $s = wfUrlencode ( $s ) ;
640 # Cleaning up URL to make it look nice -- is this safe?
641 $s = str_replace( '%28', '(', $s );
642 $s = str_replace( '%29', ')', $s );
648 * Get a real URL referring to this title, with interwiki link and
651 * @param string $query an optional query string, not used
652 * for interwiki links
653 * @return string the URL
656 function getFullURL( $query = '' ) {
657 global $wgContLang, $wgServer, $wgScript, $wgMakeDumpLinks, $wgArticlePath;
659 if ( '' == $this->mInterwiki
) {
660 return $wgServer . $this->getLocalUrl( $query );
661 } elseif ( $wgMakeDumpLinks && $wgContLang->getLanguageName( $this->mInterwiki
) ) {
662 $baseUrl = str_replace( '$1', "../../{$this->mInterwiki}/$1", $wgArticlePath );
663 $baseUrl = str_replace( '$1', $this->getHashedDirectory() . '/$1', $baseUrl );
665 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
668 $namespace = $wgContLang->getNsText( $this->mNamespace
);
669 if ( '' != $namespace ) {
670 # Can this actually happen? Interwikis shouldn't be parsed.
673 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
675 if( false === strpos( $url, '?' ) ) {
682 if ( '' != $this->mFragment
) {
683 $url .= '#' . $this->mFragment
;
689 * Get a relative directory for putting an HTML version of this article into
691 function getHashedDirectory() {
692 global $wgMakeDumpLinks, $wgInputEncoding;
693 $dbkey = $this->getDBkey();
695 # Split into characters
696 if ( $wgInputEncoding == 'UTF-8' ) {
697 preg_match_all( '/./us', $dbkey, $m );
699 preg_match_all( '/./s', $dbkey, $m );
702 $length = count( $chars );
705 for ( $i = 0; $i < $wgMakeDumpLinks; $i++
) {
709 if ( $i >= $length ) {
711 } elseif ( ord( $chars[$i] ) > 32 ) {
712 $dir .= strtolower( $chars[$i] );
714 $dir .= sprintf( "%02X", ord( $chars[$i] ) );
720 function getHashedFilename() {
721 $dbkey = $this->getPrefixedDBkey();
722 $mainPage = Title
::newMainPage();
723 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
727 $dir = $this->getHashedDirectory();
729 # Replace illegal charcters for Windows paths with underscores
730 $friendlyName = strtr( $dbkey, '/\\*?"<>|~', '_________' );
732 # Work out lower case form. We assume we're on a system with case-insensitive
733 # filenames, so unless the case is of a special form, we have to disambiguate
734 $lowerCase = $this->prefix( ucfirst( strtolower( $this->getDBkey() ) ) );
736 # Make it mostly unique
737 if ( $lowerCase != $friendlyName ) {
738 $friendlyName .= '_' . substr(md5( $dbkey ), 0, 4);
740 # Handle colon specially by replacing it with tilde
741 # Thus we reduce the number of paths with hashes appended
742 $friendlyName = str_replace( ':', '~', $friendlyName );
743 return "$dir/$friendlyName.html";
747 * Get a URL with no fragment or server name. If this page is generated
748 * with action=render, $wgServer is prepended.
749 * @param string $query an optional query string; if not specified,
750 * $wgArticlePath will be used.
751 * @return string the URL
754 function getLocalURL( $query = '' ) {
755 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks, $wgServer, $action;
757 if ( $this->isExternal() ) {
758 return $this->getFullURL();
761 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
762 if ( $wgMakeDumpLinks ) {
763 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
764 } elseif ( $query == '' ) {
765 $url = str_replace( '$1', $dbkey, $wgArticlePath );
767 global $wgActionPaths;
768 if( !empty( $wgActionPaths ) &&
769 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
770 $action = urldecode( $matches[2] );
771 if( isset( $wgActionPaths[$action] ) ) {
772 $query = $matches[1];
773 if( isset( $matches[4] ) ) $query .= $matches[4];
774 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
775 if( $query != '' ) $url .= '?' . $query;
779 if ( $query == '-' ) {
782 $url = "{$wgScript}?title={$dbkey}&{$query}";
785 if ($action == 'render')
786 return $wgServer . $url;
792 * Get an HTML-escaped version of the URL form, suitable for
793 * using in a link, without a server name or fragment
794 * @param string $query an optional query string
795 * @return string the URL
798 function escapeLocalURL( $query = '' ) {
799 return htmlspecialchars( $this->getLocalURL( $query ) );
803 * Get an HTML-escaped version of the URL form, suitable for
804 * using in a link, including the server name and fragment
806 * @return string the URL
807 * @param string $query an optional query string
810 function escapeFullURL( $query = '' ) {
811 return htmlspecialchars( $this->getFullURL( $query ) );
815 * Get the URL form for an internal link.
816 * - Used in various Squid-related code, in case we have a different
817 * internal hostname for the server from the exposed one.
819 * @param string $query an optional query string
820 * @return string the URL
823 function getInternalURL( $query = '' ) {
824 global $wgInternalServer;
825 return $wgInternalServer . $this->getLocalURL( $query );
829 * Get the edit URL for this Title
830 * @return string the URL, or a null string if this is an
834 function getEditURL() {
835 global $wgServer, $wgScript;
837 if ( '' != $this->mInterwiki
) { return ''; }
838 $s = $this->getLocalURL( 'action=edit' );
844 * Get the HTML-escaped displayable text form.
845 * Used for the title field in <a> tags.
846 * @return string the text, including any prefixes
849 function getEscapedText() {
850 return htmlspecialchars( $this->getPrefixedText() );
854 * Is this Title interwiki?
858 function isExternal() { return ( '' != $this->mInterwiki
); }
861 * Does the title correspond to a protected article?
862 * @param string $what the action the page is protected from,
863 * by default checks move and edit
867 function isProtected($action = '') {
868 if ( -1 == $this->mNamespace
) { return true; }
869 if($action == 'edit' ||
$action == '') {
870 $a = $this->getRestrictions("edit");
871 if ( in_array( 'sysop', $a ) ) { return true; }
873 if($action == 'move' ||
$action == '') {
874 $a = $this->getRestrictions("move");
875 if ( in_array( 'sysop', $a ) ) { return true; }
881 * Is $wgUser is watching this page?
885 function userIsWatching() {
888 if ( is_null( $this->mWatched
) ) {
889 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
890 $this->mWatched
= false;
892 $this->mWatched
= $wgUser->isWatched( $this );
895 return $this->mWatched
;
899 * Is $wgUser perform $action this page?
900 * @param string $action action that permission needs to be checked for
904 function userCan($action) {
905 $fname = 'Title::userCanEdit';
906 wfProfileIn( $fname );
909 if( NS_SPECIAL
== $this->mNamespace
) {
910 wfProfileOut( $fname );
913 if( NS_MEDIAWIKI
== $this->mNamespace
&&
914 !$wgUser->isAllowed('editinterface') ) {
915 wfProfileOut( $fname );
918 if( $this->mDbkeyform
== '_' ) {
919 # FIXME: Is this necessary? Shouldn't be allowed anyway...
920 wfProfileOut( $fname );
924 # protect global styles and js
925 if ( NS_MEDIAWIKI
== $this->mNamespace
926 && preg_match("/\\.(css|js)$/", $this->mTextform
)
927 && !$wgUser->isAllowed('editinterface') ) {
928 wfProfileOut( $fname );
932 # protect css/js subpages of user pages
933 # XXX: this might be better using restrictions
934 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
935 if( NS_USER
== $this->mNamespace
936 && preg_match("/\\.(css|js)$/", $this->mTextform
)
937 && !$wgUser->isAllowed('editinterface')
938 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
939 wfProfileOut( $fname );
943 foreach( $this->getRestrictions($action) as $right ) {
944 // Backwards compatibility, rewrite sysop -> protect
945 if ( $right == 'sysop' ) {
948 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
949 wfProfileOut( $fname );
954 if( $action == 'move' && !$this->isMovable() ) {
955 wfProfileOut( $fname );
959 wfProfileOut( $fname );
964 * Can $wgUser edit this page?
968 function userCanEdit() {
969 return $this->userCan('edit');
973 * Can $wgUser move this page?
977 function userCanMove() {
978 return $this->userCan('move');
982 * Would anybody with sufficient privileges be able to move this page?
983 * Some pages just aren't movable.
988 function isMovable() {
989 return Namespace::isMovable( $this->getNamespace() )
990 && $this->getInterwiki() == '';
994 * Can $wgUser read this page?
998 function userCanRead() {
1001 if( $wgUser->isAllowed('read') ) {
1004 global $wgWhitelistRead;
1006 /** If anon users can create an account,
1007 they need to reach the login page first! */
1008 if( $wgUser->isAllowed( 'createaccount' )
1009 && $this->getNamespace() == NS_SPECIAL
1010 && $this->getText() == 'Userlogin' ) {
1014 /** some pages are explicitly allowed */
1015 $name = $this->getPrefixedText();
1016 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1020 # Compatibility with old settings
1021 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1022 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1031 * Is this a talk page of some sort?
1035 function isTalkPage() {
1036 return Namespace::isTalk( $this->getNamespace() );
1040 * Is this a .css or .js subpage of a user page?
1044 function isCssJsSubpage() {
1045 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1048 * Is this a .css subpage of a user page?
1052 function isCssSubpage() {
1053 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1056 * Is this a .js subpage of a user page?
1060 function isJsSubpage() {
1061 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1064 * Protect css/js subpages of user pages: can $wgUser edit
1068 * @todo XXX: this might be better using restrictions
1071 function userCanEditCssJsSubpage() {
1073 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1077 * Loads a string into mRestrictions array
1078 * @param string $res restrictions in string format
1081 function loadRestrictions( $res ) {
1082 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1083 $temp = explode( '=', trim( $restrict ) );
1084 if(count($temp) == 1) {
1085 // old format should be treated as edit/move restriction
1086 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1087 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1089 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1092 $this->mRestrictionsLoaded
= true;
1096 * Accessor/initialisation for mRestrictions
1097 * @param string $action action that permission needs to be checked for
1098 * @return array the array of groups allowed to edit this article
1101 function getRestrictions($action) {
1102 $id = $this->getArticleID();
1103 if ( 0 == $id ) { return array(); }
1105 if ( ! $this->mRestrictionsLoaded
) {
1106 $dbr =& wfGetDB( DB_SLAVE
);
1107 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1108 $this->loadRestrictions( $res );
1110 if( isset( $this->mRestrictions
[$action] ) ) {
1111 return $this->mRestrictions
[$action];
1117 * Is there a version of this page in the deletion archive?
1118 * @return int the number of archived revisions
1121 function isDeleted() {
1122 $fname = 'Title::isDeleted';
1123 if ( $this->getNamespace() < 0 ) {
1126 $dbr =& wfGetDB( DB_SLAVE
);
1127 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1128 'ar_title' => $this->getDBkey() ), $fname );
1134 * Get the article ID for this Title from the link cache,
1135 * adding it if necessary
1136 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1138 * @return int the ID
1141 function getArticleID( $flags = 0 ) {
1142 global $wgLinkCache;
1143 if ( $flags & GAID_FOR_UPDATE
) {
1144 $oldUpdate = $wgLinkCache->forUpdate( true );
1145 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1146 $wgLinkCache->forUpdate( $oldUpdate );
1148 if ( -1 == $this->mArticleID
) {
1149 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1152 wfdebug("title: articleid = ".$this->mArticleID
."\n");
1153 return $this->mArticleID
;
1156 function getLatestRevID() {
1157 if ($this->mLatestID
!== false)
1158 return $this->mLatestID
;
1160 $db =& wfGetDB(DB_SLAVE
);
1161 return $this->mLatestID
= $db->selectField( 'revision',
1163 array('rev_page' => $this->getArticleID()),
1164 'Title::getLatestRevID' );
1168 * This clears some fields in this object, and clears any associated
1169 * keys in the "bad links" section of $wgLinkCache.
1171 * - This is called from Article::insertNewArticle() to allow
1172 * loading of the new page_id. It's also called from
1173 * Article::doDeleteArticle()
1175 * @param int $newid the new Article ID
1178 function resetArticleID( $newid ) {
1179 global $wgLinkCache;
1180 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1182 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1183 else { $this->mArticleID
= $newid; }
1184 $this->mRestrictionsLoaded
= false;
1185 $this->mRestrictions
= array();
1189 * Updates page_touched for this page; called from LinksUpdate.php
1190 * @return bool true if the update succeded
1193 function invalidateCache() {
1194 global $wgUseFileCache;
1196 if ( wfReadOnly() ) {
1200 $now = wfTimestampNow();
1201 $dbw =& wfGetDB( DB_MASTER
);
1202 $success = $dbw->update( 'page',
1204 'page_touched' => $dbw->timestamp()
1205 ), array( /* WHERE */
1206 'page_namespace' => $this->getNamespace() ,
1207 'page_title' => $this->getDBkey()
1208 ), 'Title::invalidateCache'
1211 if ($wgUseFileCache) {
1212 $cache = new CacheManager($this);
1213 @unlink
($cache->fileCacheName());
1220 * Prefix some arbitrary text with the namespace or interwiki prefix
1223 * @param string $name the text
1224 * @return string the prefixed text
1227 /* private */ function prefix( $name ) {
1231 if ( '' != $this->mInterwiki
) {
1232 $p = $this->mInterwiki
. ':';
1234 if ( 0 != $this->mNamespace
) {
1235 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1241 * Secure and split - main initialisation function for this object
1243 * Assumes that mDbkeyform has been set, and is urldecoded
1244 * and uses underscores, but not otherwise munged. This function
1245 * removes illegal characters, splits off the interwiki and
1246 * namespace prefixes, sets the other forms, and canonicalizes
1248 * @return bool true on success
1251 /* private */ function secureAndSplit() {
1252 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1253 $fname = 'Title::secureAndSplit';
1254 wfProfileIn( $fname );
1257 static $rxTc = false;
1259 # % is needed as well
1260 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1263 $this->mInterwiki
= $this->mFragment
= '';
1264 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1266 # Clean up whitespace
1268 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1269 $t = trim( $t, '_' );
1272 wfProfileOut( $fname );
1276 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1277 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1278 wfProfileOut( $fname );
1282 $this->mDbkeyform
= $t;
1284 # Initial colon indicating main namespace
1285 if ( ':' == $t{0} ) {
1286 $r = substr( $t, 1 );
1287 $this->mNamespace
= NS_MAIN
;
1289 # Namespace or interwiki prefix
1292 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1294 $lowerNs = strtolower( $p );
1295 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1296 # Canonical namespace
1298 $this->mNamespace
= $ns;
1299 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1300 # Ordinary namespace
1302 $this->mNamespace
= $ns;
1303 } elseif( $this->getInterwikiLink( $p ) ) {
1305 # Can't make a local interwiki link to an interwiki link.
1306 # That's just crazy!
1307 wfProfileOut( $fname );
1313 $this->mInterwiki
= $p;
1315 # Redundant interwiki prefix to the local wiki
1316 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1318 # Can't have an empty self-link
1319 wfProfileOut( $fname );
1322 $this->mInterwiki
= '';
1324 # Do another namespace split...
1328 # If there's no recognized interwiki or namespace,
1329 # then let the colon expression be part of the title.
1336 # We already know that some pages won't be in the database!
1338 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1339 $this->mArticleID
= 0;
1341 $f = strstr( $r, '#' );
1342 if ( false !== $f ) {
1343 $this->mFragment
= substr( $f, 1 );
1344 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1345 # remove whitespace again: prevents "Foo_bar_#"
1346 # becoming "Foo_bar_"
1347 $r = preg_replace( '/_*$/', '', $r );
1350 # Reject illegal characters.
1352 if( preg_match( $rxTc, $r ) ) {
1353 wfProfileOut( $fname );
1358 * Pages with "/./" or "/../" appearing in the URLs will
1359 * often be unreachable due to the way web browsers deal
1360 * with 'relative' URLs. Forbid them explicitly.
1362 if ( strpos( $r, '.' ) !== false &&
1363 ( $r === '.' ||
$r === '..' ||
1364 strpos( $r, './' ) === 0 ||
1365 strpos( $r, '../' ) === 0 ||
1366 strpos( $r, '/./' ) !== false ||
1367 strpos( $r, '/../' ) !== false ) )
1369 wfProfileOut( $fname );
1373 # We shouldn't need to query the DB for the size.
1374 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1375 if ( strlen( $r ) > 255 ) {
1376 wfProfileOut( $fname );
1381 * Normally, all wiki links are forced to have
1382 * an initial capital letter so [[foo]] and [[Foo]]
1383 * point to the same place.
1385 * Don't force it for interwikis, since the other
1386 * site might be case-sensitive.
1388 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1389 $t = $wgContLang->ucfirst( $r );
1395 * Can't make a link to a namespace alone...
1396 * "empty" local links can only be self-links
1397 * with a fragment identifier.
1400 $this->mInterwiki
== '' &&
1401 $this->mNamespace
!= NS_MAIN
) {
1402 wfProfileOut( $fname );
1407 $this->mDbkeyform
= $t;
1408 $this->mUrlform
= wfUrlencode( $t );
1410 $this->mTextform
= str_replace( '_', ' ', $t );
1412 wfProfileOut( $fname );
1417 * Get a Title object associated with the talk page of this article
1418 * @return Title the object for the talk page
1421 function getTalkPage() {
1422 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1426 * Get a title object associated with the subject page of this
1429 * @return Title the object for the subject page
1432 function getSubjectPage() {
1433 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1437 * Get an array of Title objects linking to this Title
1438 * Also stores the IDs in the link cache.
1440 * @param string $options may be FOR UPDATE
1441 * @return array the Title objects linking here
1444 function getLinksTo( $options = '' ) {
1445 global $wgLinkCache;
1446 $id = $this->getArticleID();
1449 $db =& wfGetDB( DB_MASTER
);
1451 $db =& wfGetDB( DB_SLAVE
);
1454 $res = $db->select( array( 'page', 'pagelinks' ),
1455 array( 'page_namespace', 'page_title', 'page_id' ),
1458 'pl_namespace' => $this->getNamespace(),
1459 'pl_title' => $this->getDbKey() ),
1460 'Title::getLinksTo',
1464 if ( $db->numRows( $res ) ) {
1465 while ( $row = $db->fetchObject( $res ) ) {
1466 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1467 $wgLinkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1468 $retVal[] = $titleObj;
1472 $db->freeResult( $res );
1477 * Get an array of Title objects referring to non-existent articles linked from this page
1479 * @param string $options may be FOR UPDATE
1480 * @return array the Title objects
1483 function getBrokenLinksFrom( $options = '' ) {
1484 global $wgLinkCache;
1487 $db =& wfGetDB( DB_MASTER
);
1489 $db =& wfGetDB( DB_SLAVE
);
1492 $res = $db->safeQuery(
1493 "SELECT pl_namespace, pl_title
1496 ON pl_namespace=page_namespace
1497 AND pl_title=page_title
1499 AND page_namespace IS NULL
1501 $db->tableName( 'pagelinks' ),
1502 $db->tableName( 'page' ),
1503 $this->getArticleId(),
1507 if ( $db->numRows( $res ) ) {
1508 while ( $row = $db->fetchObject( $res ) ) {
1509 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1512 $db->freeResult( $res );
1518 * Get a list of URLs to purge from the Squid cache when this
1521 * @return array the URLs
1524 function getSquidURLs() {
1526 $this->getInternalURL(),
1527 $this->getInternalURL( 'action=history' )
1532 * Move this page without authentication
1533 * @param Title &$nt the new page Title
1536 function moveNoAuth( &$nt ) {
1537 return $this->moveTo( $nt, false );
1541 * Check whether a given move operation would be valid.
1542 * Returns true if ok, or a message key string for an error message
1543 * if invalid. (Scarrrrry ugly interface this.)
1544 * @param Title &$nt the new title
1545 * @param bool $auth indicates whether $wgUser's permissions
1547 * @return mixed true on success, message name on failure
1550 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1552 if( !$this or !$nt ) {
1553 return 'badtitletext';
1555 if( $this->equals( $nt ) ) {
1558 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1559 return 'immobile_namespace';
1562 $fname = 'Title::move';
1563 $oldid = $this->getArticleID();
1564 $newid = $nt->getArticleID();
1566 if ( strlen( $nt->getDBkey() ) < 1 ) {
1567 return 'articleexists';
1569 if ( ( '' == $this->getDBkey() ) ||
1571 ( '' == $nt->getDBkey() ) ) {
1572 return 'badarticleerror';
1576 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1577 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1578 return 'protectedpage';
1581 # The move is allowed only if (1) the target doesn't exist, or
1582 # (2) the target is a redirect to the source, and has no history
1583 # (so we can undo bad moves right after they're done).
1585 if ( 0 != $newid ) { # Target exists; check for validity
1586 if ( ! $this->isValidMoveTarget( $nt ) ) {
1587 return 'articleexists';
1594 * Move a title to a new location
1595 * @param Title &$nt the new title
1596 * @param bool $auth indicates whether $wgUser's permissions
1598 * @return mixed true on success, message name on failure
1601 function moveTo( &$nt, $auth = true, $reason = '' ) {
1602 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1603 if( is_string( $err ) ) {
1607 $pageid = $this->getArticleID();
1608 if( $nt->exists() ) {
1609 $this->moveOverExistingRedirect( $nt, $reason );
1610 $pageCountChange = 0;
1611 } else { # Target didn't exist, do normal move.
1612 $this->moveToNewTitle( $nt, $newid, $reason );
1613 $pageCountChange = 1;
1615 $redirid = $this->getArticleID();
1617 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1618 $dbw =& wfGetDB( DB_MASTER
);
1619 $categorylinks = $dbw->tableName( 'categorylinks' );
1620 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1621 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1622 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1623 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1627 $oldnamespace = $this->getNamespace() & ~
1;
1628 $newnamespace = $nt->getNamespace() & ~
1;
1629 $oldtitle = $this->getDBkey();
1630 $newtitle = $nt->getDBkey();
1632 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1633 WatchedItem
::duplicateEntries( $this, $nt );
1636 # Update search engine
1637 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1639 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1643 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1644 # Moved out of main namespace
1645 # not viewed, edited, removing
1646 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1647 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1648 # Moved into main namespace
1649 # not viewed, edited, adding
1650 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1651 } elseif ( $pageCountChange ) {
1653 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1661 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1666 * Move page to a title which is at present a redirect to the
1669 * @param Title &$nt the page to move to, which should currently
1673 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1674 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1675 $fname = 'Title::moveOverExistingRedirect';
1676 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1679 $comment .= ": $reason";
1682 $now = wfTimestampNow();
1684 $newid = $nt->getArticleID();
1685 $oldid = $this->getArticleID();
1686 $dbw =& wfGetDB( DB_MASTER
);
1687 $links = $dbw->tableName( 'links' );
1689 # Delete the old redirect. We don't save it to history since
1690 # by definition if we've got here it's rather uninteresting.
1691 # We have to remove it so that the next step doesn't trigger
1692 # a conflict on the unique namespace+title index...
1693 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1695 # Save a null revision in the page's history notifying of the move
1696 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1697 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1699 $nullRevId = $nullRevision->insertOn( $dbw );
1701 # Change the name of the target page:
1702 $dbw->update( 'page',
1704 'page_touched' => $dbw->timestamp($now),
1705 'page_namespace' => $nt->getNamespace(),
1706 'page_title' => $nt->getDBkey(),
1707 'page_latest' => $nullRevId,
1709 /* WHERE */ array( 'page_id' => $oldid ),
1712 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1714 # Recreate the redirect, this time in the other direction.
1715 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1716 $redirectArticle = new Article( $this );
1717 $newid = $redirectArticle->insertOn( $dbw );
1718 $redirectRevision = new Revision( array(
1720 'comment' => $comment,
1721 'text' => $redirectText ) );
1722 $revid = $redirectRevision->insertOn( $dbw );
1723 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1724 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1727 $log = new LogPage( 'move' );
1728 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1730 # Now, we record the link from the redirect to the new title.
1731 # It should have no other outgoing links...
1732 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1733 $dbw->insert( 'pagelinks',
1735 'pl_from' => $newid,
1736 'pl_namespace' => $nt->getNamespace(),
1737 'pl_title' => $nt->getDbKey() ),
1741 if ( $wgUseSquid ) {
1742 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1743 $u = new SquidUpdate( $urls );
1749 * Move page to non-existing title.
1750 * @param Title &$nt the new Title
1751 * @param int &$newid set to be the new article ID
1754 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1755 global $wgUser, $wgLinkCache, $wgUseSquid;
1757 $fname = 'MovePageForm::moveToNewTitle';
1758 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1760 $comment .= ": $reason";
1763 $newid = $nt->getArticleID();
1764 $oldid = $this->getArticleID();
1765 $dbw =& wfGetDB( DB_MASTER
);
1766 $now = $dbw->timestamp();
1770 # Save a null revision in the page's history notifying of the move
1771 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1772 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1774 $nullRevId = $nullRevision->insertOn( $dbw );
1777 $dbw->update( 'page',
1779 'page_touched' => $now,
1780 'page_namespace' => $nt->getNamespace(),
1781 'page_title' => $nt->getDBkey(),
1782 'page_latest' => $nullRevId,
1784 /* WHERE */ array( 'page_id' => $oldid ),
1788 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1791 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1792 $redirectArticle = new Article( $this );
1793 $newid = $redirectArticle->insertOn( $dbw );
1794 $redirectRevision = new Revision( array(
1796 'comment' => $comment,
1797 'text' => $redirectText ) );
1798 $revid = $redirectRevision->insertOn( $dbw );
1799 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1800 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1803 $log = new LogPage( 'move' );
1804 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1806 # Purge caches as per article creation
1807 Article
::onArticleCreate( $nt );
1809 # Record the just-created redirect's linking to the page
1810 $dbw->insert( 'pagelinks',
1812 'pl_from' => $newid,
1813 'pl_namespace' => $nt->getNamespace(),
1814 'pl_title' => $nt->getDBkey() ),
1817 # Non-existent target may have had broken links to it; these must
1818 # now be touched to update link coloring.
1821 # Purge old title from squid
1822 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1823 $titles = $nt->getLinksTo();
1824 if ( $wgUseSquid ) {
1825 $urls = $this->getSquidURLs();
1826 foreach ( $titles as $linkTitle ) {
1827 $urls[] = $linkTitle->getInternalURL();
1829 $u = new SquidUpdate( $urls );
1835 * Checks if $this can be moved to a given Title
1836 * - Selects for update, so don't call it unless you mean business
1838 * @param Title &$nt the new title to check
1841 function isValidMoveTarget( $nt ) {
1843 $fname = 'Title::isValidMoveTarget';
1844 $dbw =& wfGetDB( DB_MASTER
);
1847 $id = $nt->getArticleID();
1848 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1849 array( 'page_is_redirect','old_text' ),
1850 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1851 $fname, 'FOR UPDATE' );
1853 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1858 # Does the redirect point to the source?
1859 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text
, $m ) ) {
1860 $redirTitle = Title
::newFromText( $m[1] );
1861 if( !is_object( $redirTitle ) ||
1862 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1867 # Does the article have a history?
1868 $row = $dbw->selectRow( array( 'page', 'revision'),
1870 array( 'page_namespace' => $nt->getNamespace(),
1871 'page_title' => $nt->getDBkey(),
1872 'page_id=rev_page AND page_latest != rev_id'
1873 ), $fname, 'FOR UPDATE'
1876 # Return true if there was no history
1877 return $row === false;
1881 * Create a redirect; fails if the title already exists; does
1884 * @param Title $dest the destination of the redirect
1885 * @param string $comment the comment string describing the move
1886 * @return bool true on success
1889 function createRedirect( $dest, $comment ) {
1891 if ( $this->getArticleID() ) {
1895 $fname = 'Title::createRedirect';
1896 $dbw =& wfGetDB( DB_MASTER
);
1898 $article = new Article( $this );
1899 $newid = $article->insertOn( $dbw );
1900 $revision = new Revision( array(
1902 'comment' => $comment,
1903 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1905 $revisionId = $revision->insertOn( $dbw );
1906 $article->updateRevisionOn( $dbw, $revision, 0 );
1909 $dbw->insert( 'pagelinks',
1911 'pl_from' => $newid,
1912 'pl_namespace' => $dest->getNamespace(),
1913 'pl_title' => $dest->getDbKey()
1917 Article
::onArticleCreate( $this );
1922 * Get categories to which this Title belongs and return an array of
1923 * categories' names.
1925 * @return array an array of parents in the form:
1926 * $parent => $currentarticle
1929 function getParentCategories() {
1930 global $wgContLang,$wgUser;
1932 $titlekey = $this->getArticleId();
1933 $sk =& $wgUser->getSkin();
1935 $dbr =& wfGetDB( DB_SLAVE
);
1936 $categorylinks = $dbr->tableName( 'categorylinks' );
1939 $sql = "SELECT * FROM $categorylinks"
1940 ." WHERE cl_from='$titlekey'"
1941 ." AND cl_from <> '0'"
1942 ." ORDER BY cl_sortkey";
1944 $res = $dbr->query ( $sql ) ;
1946 if($dbr->numRows($res) > 0) {
1947 while ( $x = $dbr->fetchObject ( $res ) )
1948 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1949 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1950 $dbr->freeResult ( $res ) ;
1958 * Get a tree of parent categories
1959 * @param array $children an array with the children in the keys, to check for circular refs
1963 function getParentCategoryTree( $children = array() ) {
1964 $parents = $this->getParentCategories();
1966 if($parents != '') {
1967 foreach($parents as $parent => $current)
1969 if ( array_key_exists( $parent, $children ) ) {
1970 # Circular reference
1971 $stack[$parent] = array();
1973 $nt = Title
::newFromText($parent);
1974 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
1985 * Get an associative array for selecting this title from
1991 function curCond() {
1992 wfDebugDieBacktrace( 'curCond called' );
1993 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1997 * Get an associative array for selecting this title from the
2003 function oldCond() {
2004 wfDebugDieBacktrace( 'oldCond called' );
2005 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);
2009 * Get the revision ID of the previous revision
2011 * @param integer $revision Revision ID. Get the revision that was before this one.
2012 * @return interger $oldrevision|false
2014 function getPreviousRevisionID( $revision ) {
2015 $dbr =& wfGetDB( DB_SLAVE
);
2016 return $dbr->selectField( 'revision', 'rev_id',
2017 'rev_page=' . IntVal( $this->getArticleId() ) .
2018 ' AND rev_id<' . IntVal( $revision ) . ' ORDER BY rev_id DESC' );
2022 * Get the revision ID of the next revision
2024 * @param integer $revision Revision ID. Get the revision that was after this one.
2025 * @return interger $oldrevision|false
2027 function getNextRevisionID( $revision ) {
2028 $dbr =& wfGetDB( DB_SLAVE
);
2029 return $dbr->selectField( 'revision', 'rev_id',
2030 'rev_page=' . IntVal( $this->getArticleId() ) .
2031 ' AND rev_id>' . IntVal( $revision ) . ' ORDER BY rev_id' );
2035 * Compare with another title.
2037 * @param Title $title
2040 function equals( &$title ) {
2041 return $this->getInterwiki() == $title->getInterwiki()
2042 && $this->getNamespace() == $title->getNamespace()
2043 && $this->getDbkey() == $title->getDbkey();
2047 * Check if page exists
2051 return $this->getArticleId() != 0;
2055 * Should a link should be displayed as a known link, just based on its title?
2057 * Currently, a self-link with a fragment, special pages and image pages are in
2058 * this category. Special pages never exist in the database. Some images do not
2059 * have description pages in the database, but the description page contains
2060 * useful history information that the user may want to link to.
2062 function isAlwaysKnown() {
2063 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2064 || NS_SPECIAL
== $this->mNamespace || NS_IMAGE
== $this->mNamespace
;
2068 * Update page_touched timestamps on pages linking to this title.
2069 * In principal, this could be backgrounded and could also do squid
2072 function touchLinks() {
2073 $fname = 'Title::touchLinks';
2075 $dbw =& wfGetDB( DB_MASTER
);
2077 $res = $dbw->select( 'pagelinks',
2080 'pl_namespace' => $this->getNamespace(),
2081 'pl_title' => $this->getDbKey() ),
2083 if ( 0 == $dbw->numRows( $res ) ) {
2088 $toucharr = array();
2089 while( $row = $dbw->fetchObject( $res ) ) {
2090 $toucharr[] = $row->pl_from
;
2092 if (!count($toucharr))
2094 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2095 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2098 function trackbackURL() {
2099 global $wgTitle, $wgScriptPath, $wgServer;
2101 return "$wgServer$wgScriptPath/trackback.php?article="
2102 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2105 function trackbackRDF() {
2106 $url = htmlspecialchars($this->getFullURL());
2107 $title = htmlspecialchars($this->getText());
2108 $tburl = $this->trackbackURL();
2111 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2112 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2113 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2116 dc:identifier=\"$url\"
2118 trackback:ping=\"$tburl\" />