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 $key = strtolower( $key );
398 $k = $wgDBname.':interwiki:'.$key;
399 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
400 wfProfileOut( $fname );
401 return $wgTitleInterwikiCache[$k]->iw_url
;
404 $s = $wgMemc->get( $k );
405 # Ignore old keys with no iw_local
406 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
407 $wgTitleInterwikiCache[$k] = $s;
408 wfProfileOut( $fname );
412 $dbr =& wfGetDB( DB_SLAVE
);
413 $res = $dbr->select( 'interwiki',
414 array( 'iw_url', 'iw_local', 'iw_trans' ),
415 array( 'iw_prefix' => $key ), $fname );
417 wfProfileOut( $fname );
421 $s = $dbr->fetchObject( $res );
423 # Cache non-existence: create a blank object and save it to memcached
429 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
430 $wgTitleInterwikiCache[$k] = $s;
432 wfProfileOut( $fname );
437 * Determine whether the object refers to a page within
440 * @return bool TRUE if this is an in-project interwiki link
441 * or a wikilink, FALSE otherwise
445 global $wgTitleInterwikiCache, $wgDBname;
447 if ( $this->mInterwiki
!= '' ) {
448 # Make sure key is loaded into cache
449 $this->getInterwikiLink( $this->mInterwiki
);
450 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
451 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
458 * Determine whether the object refers to a page within
459 * this project and is transcludable.
461 * @return bool TRUE if this is transcludable
465 global $wgTitleInterwikiCache, $wgDBname;
467 if ($this->mInterwiki
== '' ||
!$this->isLocal())
469 # Make sure key is loaded into cache
470 $this->getInterwikiLink( $this->mInterwiki
);
471 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
472 return (bool)($wgTitleInterwikiCache[$k]->iw_trans
);
476 * Update the page_touched field for an array of title objects
477 * @todo Inefficient unless the IDs are already loaded into the
479 * @param array $titles an array of Title objects to be touched
480 * @param string $timestamp the timestamp to use instead of the
481 * default current time
485 function touchArray( $titles, $timestamp = '' ) {
486 global $wgUseFileCache;
488 if ( count( $titles ) == 0 ) {
491 $dbw =& wfGetDB( DB_MASTER
);
492 if ( $timestamp == '' ) {
493 $timestamp = $dbw->timestamp();
495 $page = $dbw->tableName( 'page' );
497 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
500 foreach ( $titles as $title ) {
501 if ( $wgUseFileCache ) {
502 $cm = new CacheManager($title);
503 @unlink($cm->fileCacheName());
510 $sql .= $title->getArticleID();
514 $dbw->query( $sql, 'Title::touchArray' );
517 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
518 // do them in small chunks:
519 $fname = 'Title::touchArray';
520 foreach( $titles as $title ) {
521 $dbw->update( 'page',
522 array( 'page_touched' => $timestamp ),
524 'page_namespace' => $title->getNamespace(),
525 'page_title' => $title->getDBkey() ),
530 #----------------------------------------------------------------------------
532 #----------------------------------------------------------------------------
534 /** Simple accessors */
536 * Get the text form (spaces not underscores) of the main part
540 function getText() { return $this->mTextform
; }
542 * Get the URL-encoded form of the main part
546 function getPartialURL() { return $this->mUrlform
; }
548 * Get the main part with underscores
552 function getDBkey() { return $this->mDbkeyform
; }
554 * Get the namespace index, i.e. one of the NS_xxxx constants
558 function getNamespace() { return $this->mNamespace
; }
560 * Get the namespace text
564 function getNsText() {
566 return $wgContLang->getNsText( $this->mNamespace
);
569 * Get the namespace text of the subject (rather than talk) page
573 function getSubjectNsText() {
575 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
579 * Get the interwiki prefix (or null string)
583 function getInterwiki() { return $this->mInterwiki
; }
585 * Get the Title fragment (i.e. the bit after the #)
589 function getFragment() { return $this->mFragment
; }
591 * Get the default namespace index, for when there is no namespace
595 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
598 * Get title for search index
599 * @return string a stripped-down title string ready for the
602 function getIndexTitle() {
603 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
607 * Get the prefixed database key form
608 * @return string the prefixed title, with underscores and
609 * any interwiki and namespace prefixes
612 function getPrefixedDBkey() {
613 $s = $this->prefix( $this->mDbkeyform
);
614 $s = str_replace( ' ', '_', $s );
619 * Get the prefixed title with spaces.
620 * This is the form usually used for display
621 * @return string the prefixed title, with spaces
624 function getPrefixedText() {
626 if ( empty( $this->mPrefixedText
) ) {
627 $s = $this->prefix( $this->mTextform
);
628 $s = str_replace( '_', ' ', $s );
629 $this->mPrefixedText
= $s;
631 return $this->mPrefixedText
;
635 * Get the prefixed title with spaces, plus any fragment
636 * (part beginning with '#')
637 * @return string the prefixed title, with spaces and
638 * the fragment, including '#'
641 function getFullText() {
643 $text = $this->getPrefixedText();
644 if( '' != $this->mFragment
) {
645 $text .= '#' . $this->mFragment
;
651 * Get a URL-encoded title (not an actual URL) including interwiki
652 * @return string the URL-encoded form
655 function getPrefixedURL() {
656 $s = $this->prefix( $this->mDbkeyform
);
657 $s = str_replace( ' ', '_', $s );
659 $s = wfUrlencode ( $s ) ;
661 # Cleaning up URL to make it look nice -- is this safe?
662 $s = str_replace( '%28', '(', $s );
663 $s = str_replace( '%29', ')', $s );
669 * Get a real URL referring to this title, with interwiki link and
672 * @param string $query an optional query string, not used
673 * for interwiki links
674 * @return string the URL
677 function getFullURL( $query = '' ) {
678 global $wgContLang, $wgServer, $wgScript, $wgMakeDumpLinks, $wgArticlePath;
680 if ( '' == $this->mInterwiki
) {
681 return $wgServer . $this->getLocalUrl( $query );
682 } elseif ( $wgMakeDumpLinks && $wgContLang->getLanguageName( $this->mInterwiki
) ) {
683 $baseUrl = str_replace( '$1', "../../{$this->mInterwiki}/$1", $wgArticlePath );
684 $baseUrl = str_replace( '$1', $this->getHashedDirectory() . '/$1', $baseUrl );
686 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
689 $namespace = $wgContLang->getNsText( $this->mNamespace
);
690 if ( '' != $namespace ) {
691 # Can this actually happen? Interwikis shouldn't be parsed.
694 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
696 if( false === strpos( $url, '?' ) ) {
703 if ( '' != $this->mFragment
) {
704 $url .= '#' . $this->mFragment
;
710 * Get a relative directory for putting an HTML version of this article into
712 function getHashedDirectory() {
713 global $wgMakeDumpLinks, $wgInputEncoding;
714 $dbkey = $this->getDBkey();
716 # Split into characters
717 if ( $wgInputEncoding == 'UTF-8' ) {
718 preg_match_all( '/./us', $dbkey, $m );
720 preg_match_all( '/./s', $dbkey, $m );
723 $length = count( $chars );
726 for ( $i = 0; $i < $wgMakeDumpLinks; $i++
) {
730 if ( $i >= $length ) {
732 } elseif ( ord( $chars[$i] ) > 32 ) {
733 $dir .= strtolower( $chars[$i] );
735 $dir .= sprintf( "%02X", ord( $chars[$i] ) );
741 function getHashedFilename() {
742 $dbkey = $this->getPrefixedDBkey();
743 $mainPage = Title
::newMainPage();
744 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
748 $dir = $this->getHashedDirectory();
750 # Replace illegal charcters for Windows paths with underscores
751 $friendlyName = strtr( $dbkey, '/\\*?"<>|~', '_________' );
753 # Work out lower case form. We assume we're on a system with case-insensitive
754 # filenames, so unless the case is of a special form, we have to disambiguate
755 $lowerCase = $this->prefix( ucfirst( strtolower( $this->getDBkey() ) ) );
757 # Make it mostly unique
758 if ( $lowerCase != $friendlyName ) {
759 $friendlyName .= '_' . substr(md5( $dbkey ), 0, 4);
761 # Handle colon specially by replacing it with tilde
762 # Thus we reduce the number of paths with hashes appended
763 $friendlyName = str_replace( ':', '~', $friendlyName );
764 return "$dir/$friendlyName.html";
768 * Get a URL with no fragment or server name. If this page is generated
769 * with action=render, $wgServer is prepended.
770 * @param string $query an optional query string; if not specified,
771 * $wgArticlePath will be used.
772 * @return string the URL
775 function getLocalURL( $query = '' ) {
776 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks, $wgServer, $action;
778 if ( $this->isExternal() ) {
779 return $this->getFullURL();
782 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
783 if ( $wgMakeDumpLinks ) {
784 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
785 } elseif ( $query == '' ) {
786 $url = str_replace( '$1', $dbkey, $wgArticlePath );
788 global $wgActionPaths;
789 if( !empty( $wgActionPaths ) &&
790 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
791 $action = urldecode( $matches[2] );
792 if( isset( $wgActionPaths[$action] ) ) {
793 $query = $matches[1];
794 if( isset( $matches[4] ) ) $query .= $matches[4];
795 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
796 if( $query != '' ) $url .= '?' . $query;
800 if ( $query == '-' ) {
803 $url = "{$wgScript}?title={$dbkey}&{$query}";
806 if ($action == 'render')
807 return $wgServer . $url;
813 * Get an HTML-escaped version of the URL form, suitable for
814 * using in a link, without a server name or fragment
815 * @param string $query an optional query string
816 * @return string the URL
819 function escapeLocalURL( $query = '' ) {
820 return htmlspecialchars( $this->getLocalURL( $query ) );
824 * Get an HTML-escaped version of the URL form, suitable for
825 * using in a link, including the server name and fragment
827 * @return string the URL
828 * @param string $query an optional query string
831 function escapeFullURL( $query = '' ) {
832 return htmlspecialchars( $this->getFullURL( $query ) );
836 * Get the URL form for an internal link.
837 * - Used in various Squid-related code, in case we have a different
838 * internal hostname for the server from the exposed one.
840 * @param string $query an optional query string
841 * @return string the URL
844 function getInternalURL( $query = '' ) {
845 global $wgInternalServer;
846 return $wgInternalServer . $this->getLocalURL( $query );
850 * Get the edit URL for this Title
851 * @return string the URL, or a null string if this is an
855 function getEditURL() {
856 global $wgServer, $wgScript;
858 if ( '' != $this->mInterwiki
) { return ''; }
859 $s = $this->getLocalURL( 'action=edit' );
865 * Get the HTML-escaped displayable text form.
866 * Used for the title field in <a> tags.
867 * @return string the text, including any prefixes
870 function getEscapedText() {
871 return htmlspecialchars( $this->getPrefixedText() );
875 * Is this Title interwiki?
879 function isExternal() { return ( '' != $this->mInterwiki
); }
882 * Does the title correspond to a protected article?
883 * @param string $what the action the page is protected from,
884 * by default checks move and edit
888 function isProtected($action = '') {
889 if ( -1 == $this->mNamespace
) { return true; }
890 if($action == 'edit' ||
$action == '') {
891 $a = $this->getRestrictions("edit");
892 if ( in_array( 'sysop', $a ) ) { return true; }
894 if($action == 'move' ||
$action == '') {
895 $a = $this->getRestrictions("move");
896 if ( in_array( 'sysop', $a ) ) { return true; }
902 * Is $wgUser is watching this page?
906 function userIsWatching() {
909 if ( is_null( $this->mWatched
) ) {
910 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
911 $this->mWatched
= false;
913 $this->mWatched
= $wgUser->isWatched( $this );
916 return $this->mWatched
;
920 * Is $wgUser perform $action this page?
921 * @param string $action action that permission needs to be checked for
925 function userCan($action) {
926 $fname = 'Title::userCanEdit';
927 wfProfileIn( $fname );
930 if( NS_SPECIAL
== $this->mNamespace
) {
931 wfProfileOut( $fname );
934 if( NS_MEDIAWIKI
== $this->mNamespace
&&
935 !$wgUser->isAllowed('editinterface') ) {
936 wfProfileOut( $fname );
939 if( $this->mDbkeyform
== '_' ) {
940 # FIXME: Is this necessary? Shouldn't be allowed anyway...
941 wfProfileOut( $fname );
945 # protect global styles and js
946 if ( NS_MEDIAWIKI
== $this->mNamespace
947 && preg_match("/\\.(css|js)$/", $this->mTextform
)
948 && !$wgUser->isAllowed('editinterface') ) {
949 wfProfileOut( $fname );
953 # protect css/js subpages of user pages
954 # XXX: this might be better using restrictions
955 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
956 if( NS_USER
== $this->mNamespace
957 && preg_match("/\\.(css|js)$/", $this->mTextform
)
958 && !$wgUser->isAllowed('editinterface')
959 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
960 wfProfileOut( $fname );
964 foreach( $this->getRestrictions($action) as $right ) {
965 // Backwards compatibility, rewrite sysop -> protect
966 if ( $right == 'sysop' ) {
969 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
970 wfProfileOut( $fname );
975 if( $action == 'move' &&
976 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
977 wfProfileOut( $fname );
981 wfProfileOut( $fname );
986 * Can $wgUser edit this page?
990 function userCanEdit() {
991 return $this->userCan('edit');
995 * Can $wgUser move this page?
999 function userCanMove() {
1000 return $this->userCan('move');
1004 * Would anybody with sufficient privileges be able to move this page?
1005 * Some pages just aren't movable.
1010 function isMovable() {
1011 return Namespace::isMovable( $this->getNamespace() )
1012 && $this->getInterwiki() == '';
1016 * Can $wgUser read this page?
1020 function userCanRead() {
1023 if( $wgUser->isAllowed('read') ) {
1026 global $wgWhitelistRead;
1028 /** If anon users can create an account,
1029 they need to reach the login page first! */
1030 if( $wgUser->isAllowed( 'createaccount' )
1031 && $this->getNamespace() == NS_SPECIAL
1032 && $this->getText() == 'Userlogin' ) {
1036 /** some pages are explicitly allowed */
1037 $name = $this->getPrefixedText();
1038 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1042 # Compatibility with old settings
1043 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1044 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1053 * Is this a talk page of some sort?
1057 function isTalkPage() {
1058 return Namespace::isTalk( $this->getNamespace() );
1062 * Is this a .css or .js subpage of a user page?
1066 function isCssJsSubpage() {
1067 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1070 * Is this a .css subpage of a user page?
1074 function isCssSubpage() {
1075 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1078 * Is this a .js subpage of a user page?
1082 function isJsSubpage() {
1083 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1086 * Protect css/js subpages of user pages: can $wgUser edit
1090 * @todo XXX: this might be better using restrictions
1093 function userCanEditCssJsSubpage() {
1095 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1099 * Loads a string into mRestrictions array
1100 * @param string $res restrictions in string format
1103 function loadRestrictions( $res ) {
1104 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1105 $temp = explode( '=', trim( $restrict ) );
1106 if(count($temp) == 1) {
1107 // old format should be treated as edit/move restriction
1108 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1109 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1111 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1114 $this->mRestrictionsLoaded
= true;
1118 * Accessor/initialisation for mRestrictions
1119 * @param string $action action that permission needs to be checked for
1120 * @return array the array of groups allowed to edit this article
1123 function getRestrictions($action) {
1124 $id = $this->getArticleID();
1125 if ( 0 == $id ) { return array(); }
1127 if ( ! $this->mRestrictionsLoaded
) {
1128 $dbr =& wfGetDB( DB_SLAVE
);
1129 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1130 $this->loadRestrictions( $res );
1132 if( isset( $this->mRestrictions
[$action] ) ) {
1133 return $this->mRestrictions
[$action];
1139 * Is there a version of this page in the deletion archive?
1140 * @return int the number of archived revisions
1143 function isDeleted() {
1144 $fname = 'Title::isDeleted';
1145 if ( $this->getNamespace() < 0 ) {
1148 $dbr =& wfGetDB( DB_SLAVE
);
1149 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1150 'ar_title' => $this->getDBkey() ), $fname );
1156 * Get the article ID for this Title from the link cache,
1157 * adding it if necessary
1158 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1160 * @return int the ID
1163 function getArticleID( $flags = 0 ) {
1164 global $wgLinkCache;
1165 if ( $flags & GAID_FOR_UPDATE
) {
1166 $oldUpdate = $wgLinkCache->forUpdate( true );
1167 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1168 $wgLinkCache->forUpdate( $oldUpdate );
1170 if ( -1 == $this->mArticleID
) {
1171 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1174 return $this->mArticleID
;
1177 function getLatestRevID() {
1178 if ($this->mLatestID
!== false)
1179 return $this->mLatestID
;
1181 $db =& wfGetDB(DB_SLAVE
);
1182 return $this->mLatestID
= $db->selectField( 'revision',
1184 array('rev_page' => $this->getArticleID()),
1185 'Title::getLatestRevID' );
1189 * This clears some fields in this object, and clears any associated
1190 * keys in the "bad links" section of $wgLinkCache.
1192 * - This is called from Article::insertNewArticle() to allow
1193 * loading of the new page_id. It's also called from
1194 * Article::doDeleteArticle()
1196 * @param int $newid the new Article ID
1199 function resetArticleID( $newid ) {
1200 global $wgLinkCache;
1201 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1203 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1204 else { $this->mArticleID
= $newid; }
1205 $this->mRestrictionsLoaded
= false;
1206 $this->mRestrictions
= array();
1210 * Updates page_touched for this page; called from LinksUpdate.php
1211 * @return bool true if the update succeded
1214 function invalidateCache() {
1215 global $wgUseFileCache;
1217 if ( wfReadOnly() ) {
1221 $now = wfTimestampNow();
1222 $dbw =& wfGetDB( DB_MASTER
);
1223 $success = $dbw->update( 'page',
1225 'page_touched' => $dbw->timestamp()
1226 ), array( /* WHERE */
1227 'page_namespace' => $this->getNamespace() ,
1228 'page_title' => $this->getDBkey()
1229 ), 'Title::invalidateCache'
1232 if ($wgUseFileCache) {
1233 $cache = new CacheManager($this);
1234 @unlink
($cache->fileCacheName());
1241 * Prefix some arbitrary text with the namespace or interwiki prefix
1244 * @param string $name the text
1245 * @return string the prefixed text
1248 /* private */ function prefix( $name ) {
1252 if ( '' != $this->mInterwiki
) {
1253 $p = $this->mInterwiki
. ':';
1255 if ( 0 != $this->mNamespace
) {
1256 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1262 * Secure and split - main initialisation function for this object
1264 * Assumes that mDbkeyform has been set, and is urldecoded
1265 * and uses underscores, but not otherwise munged. This function
1266 * removes illegal characters, splits off the interwiki and
1267 * namespace prefixes, sets the other forms, and canonicalizes
1269 * @return bool true on success
1272 /* private */ function secureAndSplit() {
1273 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1274 $fname = 'Title::secureAndSplit';
1275 wfProfileIn( $fname );
1278 static $rxTc = false;
1280 # % is needed as well
1281 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1284 $this->mInterwiki
= $this->mFragment
= '';
1285 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1287 # Clean up whitespace
1289 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1290 $t = trim( $t, '_' );
1293 wfProfileOut( $fname );
1297 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1298 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1299 wfProfileOut( $fname );
1303 $this->mDbkeyform
= $t;
1305 # Initial colon indicates main namespace rather than specified default
1306 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1307 if ( ':' == $t{0} ) {
1308 $this->mNamespace
= NS_MAIN
;
1309 $t = substr( $t, 1 ); # remove the colon but continue processing
1312 # Namespace or interwiki prefix
1315 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1317 $lowerNs = strtolower( $p );
1318 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1319 # Canonical namespace
1321 $this->mNamespace
= $ns;
1322 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1323 # Ordinary namespace
1325 $this->mNamespace
= $ns;
1326 } elseif( $this->getInterwikiLink( $p ) ) {
1328 # Can't make a local interwiki link to an interwiki link.
1329 # That's just crazy!
1330 wfProfileOut( $fname );
1336 $this->mInterwiki
= strtolower( $p );
1338 # Redundant interwiki prefix to the local wiki
1339 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1341 # Can't have an empty self-link
1342 wfProfileOut( $fname );
1345 $this->mInterwiki
= '';
1347 # Do another namespace split...
1351 # If there's no recognized interwiki or namespace,
1352 # then let the colon expression be part of the title.
1358 # We already know that some pages won't be in the database!
1360 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1361 $this->mArticleID
= 0;
1363 $f = strstr( $r, '#' );
1364 if ( false !== $f ) {
1365 $this->mFragment
= substr( $f, 1 );
1366 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1367 # remove whitespace again: prevents "Foo_bar_#"
1368 # becoming "Foo_bar_"
1369 $r = preg_replace( '/_*$/', '', $r );
1372 # Reject illegal characters.
1374 if( preg_match( $rxTc, $r ) ) {
1375 wfProfileOut( $fname );
1380 * Pages with "/./" or "/../" appearing in the URLs will
1381 * often be unreachable due to the way web browsers deal
1382 * with 'relative' URLs. Forbid them explicitly.
1384 if ( strpos( $r, '.' ) !== false &&
1385 ( $r === '.' ||
$r === '..' ||
1386 strpos( $r, './' ) === 0 ||
1387 strpos( $r, '../' ) === 0 ||
1388 strpos( $r, '/./' ) !== false ||
1389 strpos( $r, '/../' ) !== false ) )
1391 wfProfileOut( $fname );
1395 # We shouldn't need to query the DB for the size.
1396 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1397 if ( strlen( $r ) > 255 ) {
1398 wfProfileOut( $fname );
1403 * Normally, all wiki links are forced to have
1404 * an initial capital letter so [[foo]] and [[Foo]]
1405 * point to the same place.
1407 * Don't force it for interwikis, since the other
1408 * site might be case-sensitive.
1410 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1411 $t = $wgContLang->ucfirst( $r );
1417 * Can't make a link to a namespace alone...
1418 * "empty" local links can only be self-links
1419 * with a fragment identifier.
1422 $this->mInterwiki
== '' &&
1423 $this->mNamespace
!= NS_MAIN
) {
1424 wfProfileOut( $fname );
1429 $this->mDbkeyform
= $t;
1430 $this->mUrlform
= wfUrlencode( $t );
1432 $this->mTextform
= str_replace( '_', ' ', $t );
1434 wfProfileOut( $fname );
1439 * Get a Title object associated with the talk page of this article
1440 * @return Title the object for the talk page
1443 function getTalkPage() {
1444 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1448 * Get a title object associated with the subject page of this
1451 * @return Title the object for the subject page
1454 function getSubjectPage() {
1455 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1459 * Get an array of Title objects linking to this Title
1460 * Also stores the IDs in the link cache.
1462 * @param string $options may be FOR UPDATE
1463 * @return array the Title objects linking here
1466 function getLinksTo( $options = '' ) {
1467 global $wgLinkCache;
1468 $id = $this->getArticleID();
1471 $db =& wfGetDB( DB_MASTER
);
1473 $db =& wfGetDB( DB_SLAVE
);
1476 $res = $db->select( array( 'page', 'pagelinks' ),
1477 array( 'page_namespace', 'page_title', 'page_id' ),
1480 'pl_namespace' => $this->getNamespace(),
1481 'pl_title' => $this->getDbKey() ),
1482 'Title::getLinksTo',
1486 if ( $db->numRows( $res ) ) {
1487 while ( $row = $db->fetchObject( $res ) ) {
1488 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1489 $wgLinkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1490 $retVal[] = $titleObj;
1494 $db->freeResult( $res );
1499 * Get an array of Title objects referring to non-existent articles linked from this page
1501 * @param string $options may be FOR UPDATE
1502 * @return array the Title objects
1505 function getBrokenLinksFrom( $options = '' ) {
1506 global $wgLinkCache;
1509 $db =& wfGetDB( DB_MASTER
);
1511 $db =& wfGetDB( DB_SLAVE
);
1514 $res = $db->safeQuery(
1515 "SELECT pl_namespace, pl_title
1518 ON pl_namespace=page_namespace
1519 AND pl_title=page_title
1521 AND page_namespace IS NULL
1523 $db->tableName( 'pagelinks' ),
1524 $db->tableName( 'page' ),
1525 $this->getArticleId(),
1529 if ( $db->numRows( $res ) ) {
1530 while ( $row = $db->fetchObject( $res ) ) {
1531 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1534 $db->freeResult( $res );
1540 * Get a list of URLs to purge from the Squid cache when this
1543 * @return array the URLs
1546 function getSquidURLs() {
1548 $this->getInternalURL(),
1549 $this->getInternalURL( 'action=history' )
1554 * Move this page without authentication
1555 * @param Title &$nt the new page Title
1558 function moveNoAuth( &$nt ) {
1559 return $this->moveTo( $nt, false );
1563 * Check whether a given move operation would be valid.
1564 * Returns true if ok, or a message key string for an error message
1565 * if invalid. (Scarrrrry ugly interface this.)
1566 * @param Title &$nt the new title
1567 * @param bool $auth indicates whether $wgUser's permissions
1569 * @return mixed true on success, message name on failure
1572 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1574 if( !$this or !$nt ) {
1575 return 'badtitletext';
1577 if( $this->equals( $nt ) ) {
1580 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1581 return 'immobile_namespace';
1584 $fname = 'Title::move';
1585 $oldid = $this->getArticleID();
1586 $newid = $nt->getArticleID();
1588 if ( strlen( $nt->getDBkey() ) < 1 ) {
1589 return 'articleexists';
1591 if ( ( '' == $this->getDBkey() ) ||
1593 ( '' == $nt->getDBkey() ) ) {
1594 return 'badarticleerror';
1598 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1599 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1600 return 'protectedpage';
1603 # The move is allowed only if (1) the target doesn't exist, or
1604 # (2) the target is a redirect to the source, and has no history
1605 # (so we can undo bad moves right after they're done).
1607 if ( 0 != $newid ) { # Target exists; check for validity
1608 if ( ! $this->isValidMoveTarget( $nt ) ) {
1609 return 'articleexists';
1616 * Move a title to a new location
1617 * @param Title &$nt the new title
1618 * @param bool $auth indicates whether $wgUser's permissions
1620 * @return mixed true on success, message name on failure
1623 function moveTo( &$nt, $auth = true, $reason = '' ) {
1624 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1625 if( is_string( $err ) ) {
1629 $pageid = $this->getArticleID();
1630 if( $nt->exists() ) {
1631 $this->moveOverExistingRedirect( $nt, $reason );
1632 $pageCountChange = 0;
1633 } else { # Target didn't exist, do normal move.
1634 $this->moveToNewTitle( $nt, $newid, $reason );
1635 $pageCountChange = 1;
1637 $redirid = $this->getArticleID();
1639 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1640 $dbw =& wfGetDB( DB_MASTER
);
1641 $categorylinks = $dbw->tableName( 'categorylinks' );
1642 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1643 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1644 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1645 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1649 $oldnamespace = $this->getNamespace() & ~
1;
1650 $newnamespace = $nt->getNamespace() & ~
1;
1651 $oldtitle = $this->getDBkey();
1652 $newtitle = $nt->getDBkey();
1654 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1655 WatchedItem
::duplicateEntries( $this, $nt );
1658 # Update search engine
1659 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1661 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1665 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1666 # Moved out of main namespace
1667 # not viewed, edited, removing
1668 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1669 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1670 # Moved into main namespace
1671 # not viewed, edited, adding
1672 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1673 } elseif ( $pageCountChange ) {
1675 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1683 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1688 * Move page to a title which is at present a redirect to the
1691 * @param Title &$nt the page to move to, which should currently
1695 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1696 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1697 $fname = 'Title::moveOverExistingRedirect';
1698 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1701 $comment .= ": $reason";
1704 $now = wfTimestampNow();
1706 $newid = $nt->getArticleID();
1707 $oldid = $this->getArticleID();
1708 $dbw =& wfGetDB( DB_MASTER
);
1709 $links = $dbw->tableName( 'links' );
1711 # Delete the old redirect. We don't save it to history since
1712 # by definition if we've got here it's rather uninteresting.
1713 # We have to remove it so that the next step doesn't trigger
1714 # a conflict on the unique namespace+title index...
1715 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1717 # Save a null revision in the page's history notifying of the move
1718 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1719 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1721 $nullRevId = $nullRevision->insertOn( $dbw );
1723 # Change the name of the target page:
1724 $dbw->update( 'page',
1726 'page_touched' => $dbw->timestamp($now),
1727 'page_namespace' => $nt->getNamespace(),
1728 'page_title' => $nt->getDBkey(),
1729 'page_latest' => $nullRevId,
1731 /* WHERE */ array( 'page_id' => $oldid ),
1734 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1736 # Recreate the redirect, this time in the other direction.
1737 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1738 $redirectArticle = new Article( $this );
1739 $newid = $redirectArticle->insertOn( $dbw );
1740 $redirectRevision = new Revision( array(
1742 'comment' => $comment,
1743 'text' => $redirectText ) );
1744 $revid = $redirectRevision->insertOn( $dbw );
1745 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1746 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1749 $log = new LogPage( 'move' );
1750 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1752 # Now, we record the link from the redirect to the new title.
1753 # It should have no other outgoing links...
1754 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1755 $dbw->insert( 'pagelinks',
1757 'pl_from' => $newid,
1758 'pl_namespace' => $nt->getNamespace(),
1759 'pl_title' => $nt->getDbKey() ),
1763 if ( $wgUseSquid ) {
1764 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1765 $u = new SquidUpdate( $urls );
1771 * Move page to non-existing title.
1772 * @param Title &$nt the new Title
1773 * @param int &$newid set to be the new article ID
1776 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1777 global $wgUser, $wgLinkCache, $wgUseSquid;
1779 $fname = 'MovePageForm::moveToNewTitle';
1780 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1782 $comment .= ": $reason";
1785 $newid = $nt->getArticleID();
1786 $oldid = $this->getArticleID();
1787 $dbw =& wfGetDB( DB_MASTER
);
1788 $now = $dbw->timestamp();
1792 # Save a null revision in the page's history notifying of the move
1793 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1794 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1796 $nullRevId = $nullRevision->insertOn( $dbw );
1799 $dbw->update( 'page',
1801 'page_touched' => $now,
1802 'page_namespace' => $nt->getNamespace(),
1803 'page_title' => $nt->getDBkey(),
1804 'page_latest' => $nullRevId,
1806 /* WHERE */ array( 'page_id' => $oldid ),
1810 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1813 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1814 $redirectArticle = new Article( $this );
1815 $newid = $redirectArticle->insertOn( $dbw );
1816 $redirectRevision = new Revision( array(
1818 'comment' => $comment,
1819 'text' => $redirectText ) );
1820 $revid = $redirectRevision->insertOn( $dbw );
1821 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1822 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1825 $log = new LogPage( 'move' );
1826 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1828 # Purge caches as per article creation
1829 Article
::onArticleCreate( $nt );
1831 # Record the just-created redirect's linking to the page
1832 $dbw->insert( 'pagelinks',
1834 'pl_from' => $newid,
1835 'pl_namespace' => $nt->getNamespace(),
1836 'pl_title' => $nt->getDBkey() ),
1839 # Non-existent target may have had broken links to it; these must
1840 # now be touched to update link coloring.
1843 # Purge old title from squid
1844 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1845 $titles = $nt->getLinksTo();
1846 if ( $wgUseSquid ) {
1847 $urls = $this->getSquidURLs();
1848 foreach ( $titles as $linkTitle ) {
1849 $urls[] = $linkTitle->getInternalURL();
1851 $u = new SquidUpdate( $urls );
1857 * Checks if $this can be moved to a given Title
1858 * - Selects for update, so don't call it unless you mean business
1860 * @param Title &$nt the new title to check
1863 function isValidMoveTarget( $nt ) {
1865 $fname = 'Title::isValidMoveTarget';
1866 $dbw =& wfGetDB( DB_MASTER
);
1869 $id = $nt->getArticleID();
1870 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1871 array( 'page_is_redirect','old_text','old_flags' ),
1872 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1873 $fname, 'FOR UPDATE' );
1875 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1879 $text = Revision
::getRevisionText( $obj );
1881 # Does the redirect point to the source?
1882 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1883 $redirTitle = Title
::newFromText( $m[1] );
1884 if( !is_object( $redirTitle ) ||
1885 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1893 # Does the article have a history?
1894 $row = $dbw->selectRow( array( 'page', 'revision'),
1896 array( 'page_namespace' => $nt->getNamespace(),
1897 'page_title' => $nt->getDBkey(),
1898 'page_id=rev_page AND page_latest != rev_id'
1899 ), $fname, 'FOR UPDATE'
1902 # Return true if there was no history
1903 return $row === false;
1907 * Create a redirect; fails if the title already exists; does
1910 * @param Title $dest the destination of the redirect
1911 * @param string $comment the comment string describing the move
1912 * @return bool true on success
1915 function createRedirect( $dest, $comment ) {
1917 if ( $this->getArticleID() ) {
1921 $fname = 'Title::createRedirect';
1922 $dbw =& wfGetDB( DB_MASTER
);
1924 $article = new Article( $this );
1925 $newid = $article->insertOn( $dbw );
1926 $revision = new Revision( array(
1928 'comment' => $comment,
1929 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1931 $revisionId = $revision->insertOn( $dbw );
1932 $article->updateRevisionOn( $dbw, $revision, 0 );
1935 $dbw->insert( 'pagelinks',
1937 'pl_from' => $newid,
1938 'pl_namespace' => $dest->getNamespace(),
1939 'pl_title' => $dest->getDbKey()
1943 Article
::onArticleCreate( $this );
1948 * Get categories to which this Title belongs and return an array of
1949 * categories' names.
1951 * @return array an array of parents in the form:
1952 * $parent => $currentarticle
1955 function getParentCategories() {
1956 global $wgContLang,$wgUser;
1958 $titlekey = $this->getArticleId();
1959 $sk =& $wgUser->getSkin();
1961 $dbr =& wfGetDB( DB_SLAVE
);
1962 $categorylinks = $dbr->tableName( 'categorylinks' );
1965 $sql = "SELECT * FROM $categorylinks"
1966 ." WHERE cl_from='$titlekey'"
1967 ." AND cl_from <> '0'"
1968 ." ORDER BY cl_sortkey";
1970 $res = $dbr->query ( $sql ) ;
1972 if($dbr->numRows($res) > 0) {
1973 while ( $x = $dbr->fetchObject ( $res ) )
1974 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1975 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1976 $dbr->freeResult ( $res ) ;
1984 * Get a tree of parent categories
1985 * @param array $children an array with the children in the keys, to check for circular refs
1989 function getParentCategoryTree( $children = array() ) {
1990 $parents = $this->getParentCategories();
1992 if($parents != '') {
1993 foreach($parents as $parent => $current)
1995 if ( array_key_exists( $parent, $children ) ) {
1996 # Circular reference
1997 $stack[$parent] = array();
1999 $nt = Title
::newFromText($parent);
2000 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
2011 * Get an associative array for selecting this title from
2017 function curCond() {
2018 wfDebugDieBacktrace( 'curCond called' );
2019 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
2023 * Get an associative array for selecting this title from the
2029 function oldCond() {
2030 wfDebugDieBacktrace( 'oldCond called' );
2031 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);
2035 * Get the revision ID of the previous revision
2037 * @param integer $revision Revision ID. Get the revision that was before this one.
2038 * @return interger $oldrevision|false
2040 function getPreviousRevisionID( $revision ) {
2041 $dbr =& wfGetDB( DB_SLAVE
);
2042 return $dbr->selectField( 'revision', 'rev_id',
2043 'rev_page=' . intval( $this->getArticleId() ) .
2044 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2048 * Get the revision ID of the next revision
2050 * @param integer $revision Revision ID. Get the revision that was after this one.
2051 * @return interger $oldrevision|false
2053 function getNextRevisionID( $revision ) {
2054 $dbr =& wfGetDB( DB_SLAVE
);
2055 return $dbr->selectField( 'revision', 'rev_id',
2056 'rev_page=' . intval( $this->getArticleId() ) .
2057 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2061 * Compare with another title.
2063 * @param Title $title
2066 function equals( &$title ) {
2067 return $this->getInterwiki() == $title->getInterwiki()
2068 && $this->getNamespace() == $title->getNamespace()
2069 && $this->getDbkey() == $title->getDbkey();
2073 * Check if page exists
2077 return $this->getArticleId() != 0;
2081 * Should a link should be displayed as a known link, just based on its title?
2083 * Currently, a self-link with a fragment, special pages and image pages are in
2084 * this category. Special pages never exist in the database. Some images do not
2085 * have description pages in the database, but the description page contains
2086 * useful history information that the user may want to link to.
2088 function isAlwaysKnown() {
2089 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2090 || NS_SPECIAL
== $this->mNamespace || NS_IMAGE
== $this->mNamespace
;
2094 * Update page_touched timestamps on pages linking to this title.
2095 * In principal, this could be backgrounded and could also do squid
2098 function touchLinks() {
2099 $fname = 'Title::touchLinks';
2101 $dbw =& wfGetDB( DB_MASTER
);
2103 $res = $dbw->select( 'pagelinks',
2106 'pl_namespace' => $this->getNamespace(),
2107 'pl_title' => $this->getDbKey() ),
2109 if ( 0 == $dbw->numRows( $res ) ) {
2114 $toucharr = array();
2115 while( $row = $dbw->fetchObject( $res ) ) {
2116 $toucharr[] = $row->pl_from
;
2118 if (!count($toucharr))
2120 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2121 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2124 function trackbackURL() {
2125 global $wgTitle, $wgScriptPath, $wgServer;
2127 return "$wgServer$wgScriptPath/trackback.php?article="
2128 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2131 function trackbackRDF() {
2132 $url = htmlspecialchars($this->getFullURL());
2133 $title = htmlspecialchars($this->getText());
2134 $tburl = $this->trackbackURL();
2137 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2138 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2139 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2142 dc:identifier=\"$url\"
2144 trackback:ping=\"$tburl\" />