9 require_once( 'normal/UtfNormal.php' );
11 $wgTitleInterwikiCache = array();
12 define ( 'GAID_FOR_UPDATE', 1 );
14 # Title::newFromTitle maintains a cache to avoid
15 # expensive re-normalization of commonly used titles.
16 # On a batch operation this can become a memory leak
17 # if not bounded. After hitting this many titles,
19 define( 'MW_TITLECACHE_MAX', 1000 );
23 * - Represents a title, which may contain an interwiki designation or namespace
24 * - Can fetch various kinds of data from the database, albeit inefficiently.
30 * All member variables should be considered private
31 * Please use the accessor functions
38 var $mTextform; # Text form (spaces not underscores) of the main part
39 var $mUrlform; # URL-encoded form of the main part
40 var $mDbkeyform; # Main part with underscores
41 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
42 var $mInterwiki; # Interwiki prefix (or null string)
43 var $mFragment; # Title fragment (i.e. the bit after the #)
44 var $mArticleID; # Article ID, fetched from the link cache on demand
45 var $mLatestID; # ID of most recent revision
46 var $mRestrictions; # Array of groups allowed to edit this article
47 # Only null or "sysop" are supported
48 var $mRestrictionsLoaded; # Boolean for initialisation on demand
49 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
50 var $mDefaultNamespace; # Namespace index when there is no namespace
51 # Zero except in {{transclusion}} tags
52 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
60 /* private */ function Title() {
61 $this->mInterwiki
= $this->mUrlform
=
62 $this->mTextform
= $this->mDbkeyform
= '';
63 $this->mArticleID
= -1;
64 $this->mNamespace
= NS_MAIN
;
65 $this->mRestrictionsLoaded
= false;
66 $this->mRestrictions
= array();
67 # Dont change the following, NS_MAIN is hardcoded in several place
69 $this->mDefaultNamespace
= NS_MAIN
;
70 $this->mWatched
= NULL;
71 $this->mLatestID
= false;
75 * Create a new Title from a prefixed DB key
76 * @param string $key The database key, which has underscores
77 * instead of spaces, possibly including namespace and
79 * @return Title the new object, or NULL on an error
83 /* static */ function newFromDBkey( $key ) {
85 $t->mDbkeyform
= $key;
86 if( $t->secureAndSplit() )
93 * Create a new Title from text, such as what one would
94 * find in a link. Decodes any HTML entities in the text.
96 * @param string $text the link text; spaces, prefixes,
97 * and an initial ':' indicating the main namespace
99 * @param int $defaultNamespace the namespace to use if
100 * none is specified by a prefix
101 * @return Title the new object, or NULL on an error
105 function newFromText( $text, $defaultNamespace = NS_MAIN
) {
106 $fname = 'Title::newFromText';
107 wfProfileIn( $fname );
109 if( is_object( $text ) ) {
110 wfDebugDieBacktrace( 'Title::newFromText given an object' );
114 * Wiki pages often contain multiple links to the same page.
115 * Title normalization and parsing can become expensive on
116 * pages with many links, so we can save a little time by
119 * In theory these are value objects and won't get changed...
121 static $titleCache = array();
122 if( $defaultNamespace == NS_MAIN
&& isset( $titleCache[$text] ) ) {
123 wfProfileOut( $fname );
124 return $titleCache[$text];
128 * Convert things like é ā or 〗 into real text...
130 $filteredText = Sanitizer
::decodeCharReferences( $text );
133 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
134 $t->mDefaultNamespace
= $defaultNamespace;
136 if( $t->secureAndSplit() ) {
137 if( $defaultNamespace == NS_MAIN
) {
138 if( count( $titleCache ) >= MW_TITLECACHE_MAX
) {
139 # Avoid memory leaks on mass operations...
140 $titleCache = array();
142 $titleCache[$text] =& $t;
144 wfProfileOut( $fname );
147 wfProfileOut( $fname );
154 * Create a new Title from URL-encoded text. Ensures that
155 * the given title's length does not exceed the maximum.
156 * @param string $url the title, as might be taken from a URL
157 * @return Title the new object, or NULL on an error
161 function newFromURL( $url ) {
162 global $wgLang, $wgServer;
165 # For compatibility with old buggy URLs. "+" is not valid in titles,
166 # but some URLs used it as a space replacement and they still come
167 # from some external search tools.
168 $s = str_replace( '+', ' ', $url );
170 $t->mDbkeyform
= str_replace( ' ', '_', $s );
171 if( $t->secureAndSplit() ) {
179 * Create a new Title from an article ID
181 * @todo This is inefficiently implemented, the page row is requested
182 * but not used for anything else
184 * @param int $id the page_id corresponding to the Title to create
185 * @return Title the new object, or NULL on an error
189 function newFromID( $id ) {
190 $fname = 'Title::newFromID';
191 $dbr =& wfGetDB( DB_SLAVE
);
192 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
193 array( 'page_id' => $id ), $fname );
194 if ( $row !== false ) {
195 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
203 * Create a new Title from a namespace index and a DB key.
204 * It's assumed that $ns and $title are *valid*, for instance when
205 * they came directly from the database or a special page name.
206 * For convenience, spaces are converted to underscores so that
207 * eg user_text fields can be used directly.
209 * @param int $ns the namespace of the article
210 * @param string $title the unprefixed database key form
211 * @return Title the new object
215 function &makeTitle( $ns, $title ) {
219 $t->mNamespace
= intval( $ns );
220 $t->mDbkeyform
= str_replace( ' ', '_', $title );
221 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
222 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
223 $t->mTextform
= str_replace( '_', ' ', $title );
228 * Create a new Title frrom a namespace index and a DB key.
229 * The parameters will be checked for validity, which is a bit slower
230 * than makeTitle() but safer for user-provided data.
232 * @param int $ns the namespace of the article
233 * @param string $title the database key form
234 * @return Title the new object, or NULL on an error
238 function makeTitleSafe( $ns, $title ) {
240 $t->mDbkeyform
= Title
::makeName( $ns, $title );
241 if( $t->secureAndSplit() ) {
249 * Create a new Title for the Main Page
252 * @return Title the new object
255 function newMainPage() {
256 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
260 * Create a new Title for a redirect
261 * @param string $text the redirect title text
262 * @return Title the new object, or NULL if the text is not a
267 function newFromRedirect( $text ) {
270 if ( $wgMwRedir->matchStart( $text ) ) {
271 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
272 # categories are escaped using : for example one can enter:
273 # #REDIRECT [[:Category:Music]]. Need to remove it.
274 if ( substr($m[1],0,1) == ':') {
275 # We don't want to keep the ':'
276 $m[1] = substr( $m[1], 1 );
279 $rt = Title
::newFromText( $m[1] );
280 # Disallow redirects to Special:Userlogout
281 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
289 #----------------------------------------------------------------------------
291 #----------------------------------------------------------------------------
294 * Get the prefixed DB key associated with an ID
295 * @param int $id the page_id of the article
296 * @return Title an object representing the article, or NULL
297 * if no such article was found
301 function nameOf( $id ) {
302 $fname = 'Title::nameOf';
303 $dbr =& wfGetDB( DB_SLAVE
);
305 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
306 if ( $s === false ) { return NULL; }
308 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
313 * Get a regex character class describing the legal characters in a link
314 * @return string the list of characters, not delimited
318 function legalChars() {
319 # Missing characters:
320 # * []|# Needed for link syntax
321 # * % and + are corrupted by Apache when they appear in the path
323 # % seems to work though
325 # The problem with % is that URLs are double-unescaped: once by Apache's
326 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
327 # Our code does not double-escape to compensate for this, indeed double escaping
328 # would break if the double-escaped title was passed in the query string
329 # rather than the path. This is a minor security issue because articles can be
330 # created such that they are hard to view or edit. -- TS
332 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
333 # this breaks interlanguage links
335 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF";
340 * Get a string representation of a title suitable for
341 * including in a search index
343 * @param int $ns a namespace index
344 * @param string $title text-form main part
345 * @return string a stripped-down title string ready for the
348 /* static */ function indexTitle( $ns, $title ) {
349 global $wgDBminWordLen, $wgContLang;
350 require_once( 'SearchEngine.php' );
352 $lc = SearchEngine
::legalSearchChars() . '&#;';
353 $t = $wgContLang->stripForSearch( $title );
354 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
355 $t = strtolower( $t );
358 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
359 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
361 $t = preg_replace( "/\\s+/", ' ', $t );
363 if ( $ns == NS_IMAGE
) {
364 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
370 * Make a prefixed DB key from a DB key and a namespace index
371 * @param int $ns numerical representation of the namespace
372 * @param string $title the DB key form the title
373 * @return string the prefixed form of the title
375 /* static */ function makeName( $ns, $title ) {
378 $n = $wgContLang->getNsText( $ns );
379 return $n == '' ?
$title : "$n:$title";
383 * Returns the URL associated with an interwiki prefix
384 * @param string $key the interwiki prefix (e.g. "MeatBall")
385 * @return the associated URL, containing "$1", which should be
386 * replaced by an article title
390 function getInterwikiLink( $key, $transludeonly = false ) {
391 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
392 $fname = 'Title::getInterwikiLink';
394 wfProfileIn( $fname );
396 $k = $wgDBname.':interwiki:'.$key;
397 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
398 wfProfileOut( $fname );
399 return $wgTitleInterwikiCache[$k]->iw_url
;
402 $s = $wgMemc->get( $k );
403 # Ignore old keys with no iw_local
404 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
405 $wgTitleInterwikiCache[$k] = $s;
406 wfProfileOut( $fname );
410 $dbr =& wfGetDB( DB_SLAVE
);
411 $res = $dbr->select( 'interwiki',
412 array( 'iw_url', 'iw_local', 'iw_trans' ),
413 array( 'iw_prefix' => $key ), $fname );
415 wfProfileOut( $fname );
419 $s = $dbr->fetchObject( $res );
421 # Cache non-existence: create a blank object and save it to memcached
427 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
428 $wgTitleInterwikiCache[$k] = $s;
430 wfProfileOut( $fname );
435 * Determine whether the object refers to a page within
438 * @return bool TRUE if this is an in-project interwiki link
439 * or a wikilink, FALSE otherwise
443 global $wgTitleInterwikiCache, $wgDBname;
445 if ( $this->mInterwiki
!= '' ) {
446 # Make sure key is loaded into cache
447 $this->getInterwikiLink( $this->mInterwiki
);
448 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
449 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
456 * Determine whether the object refers to a page within
457 * this project and is transcludable.
459 * @return bool TRUE if this is transcludable
463 global $wgTitleInterwikiCache, $wgDBname;
465 if ($this->mInterwiki
== '' ||
!$this->isLocal())
467 # Make sure key is loaded into cache
468 $this->getInterwikiLink( $this->mInterwiki
);
469 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
470 return (bool)($wgTitleInterwikiCache[$k]->iw_trans
);
474 * Update the page_touched field for an array of title objects
475 * @todo Inefficient unless the IDs are already loaded into the
477 * @param array $titles an array of Title objects to be touched
478 * @param string $timestamp the timestamp to use instead of the
479 * default current time
483 function touchArray( $titles, $timestamp = '' ) {
484 global $wgUseFileCache;
486 if ( count( $titles ) == 0 ) {
489 $dbw =& wfGetDB( DB_MASTER
);
490 if ( $timestamp == '' ) {
491 $timestamp = $dbw->timestamp();
493 $page = $dbw->tableName( 'page' );
495 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
498 foreach ( $titles as $title ) {
499 if ( $wgUseFileCache ) {
500 $cm = new CacheManager($title);
501 @unlink($cm->fileCacheName());
508 $sql .= $title->getArticleID();
512 $dbw->query( $sql, 'Title::touchArray' );
515 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
516 // do them in small chunks:
517 $fname = 'Title::touchArray';
518 foreach( $titles as $title ) {
519 $dbw->update( 'page',
520 array( 'page_touched' => $timestamp ),
522 'page_namespace' => $title->getNamespace(),
523 'page_title' => $title->getDBkey() ),
528 #----------------------------------------------------------------------------
530 #----------------------------------------------------------------------------
532 /** Simple accessors */
534 * Get the text form (spaces not underscores) of the main part
538 function getText() { return $this->mTextform
; }
540 * Get the URL-encoded form of the main part
544 function getPartialURL() { return $this->mUrlform
; }
546 * Get the main part with underscores
550 function getDBkey() { return $this->mDbkeyform
; }
552 * Get the namespace index, i.e. one of the NS_xxxx constants
556 function getNamespace() { return $this->mNamespace
; }
558 * Get the namespace text
562 function getNsText() {
564 return $wgLang->getNsText( $this->mNamespace
);
567 * Get the interwiki prefix (or null string)
571 function getInterwiki() { return $this->mInterwiki
; }
573 * Get the Title fragment (i.e. the bit after the #)
577 function getFragment() { return $this->mFragment
; }
579 * Get the default namespace index, for when there is no namespace
583 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
586 * Get title for search index
587 * @return string a stripped-down title string ready for the
590 function getIndexTitle() {
591 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
595 * Get the prefixed database key form
596 * @return string the prefixed title, with underscores and
597 * any interwiki and namespace prefixes
600 function getPrefixedDBkey() {
601 $s = $this->prefix( $this->mDbkeyform
);
602 $s = str_replace( ' ', '_', $s );
607 * Get the prefixed title with spaces.
608 * This is the form usually used for display
609 * @return string the prefixed title, with spaces
612 function getPrefixedText() {
614 if ( empty( $this->mPrefixedText
) ) {
615 $s = $this->prefix( $this->mTextform
);
616 $s = str_replace( '_', ' ', $s );
617 $this->mPrefixedText
= $s;
619 return $this->mPrefixedText
;
623 * Get the prefixed title with spaces, plus any fragment
624 * (part beginning with '#')
625 * @return string the prefixed title, with spaces and
626 * the fragment, including '#'
629 function getFullText() {
631 $text = $this->getPrefixedText();
632 if( '' != $this->mFragment
) {
633 $text .= '#' . $this->mFragment
;
639 * Get a URL-encoded title (not an actual URL) including interwiki
640 * @return string the URL-encoded form
643 function getPrefixedURL() {
644 $s = $this->prefix( $this->mDbkeyform
);
645 $s = str_replace( ' ', '_', $s );
647 $s = wfUrlencode ( $s ) ;
649 # Cleaning up URL to make it look nice -- is this safe?
650 $s = str_replace( '%28', '(', $s );
651 $s = str_replace( '%29', ')', $s );
657 * Get a real URL referring to this title, with interwiki link and
660 * @param string $query an optional query string, not used
661 * for interwiki links
662 * @return string the URL
665 function getFullURL( $query = '' ) {
666 global $wgContLang, $wgServer, $wgScript, $wgMakeDumpLinks, $wgArticlePath;
668 if ( '' == $this->mInterwiki
) {
669 return $wgServer . $this->getLocalUrl( $query );
670 } elseif ( $wgMakeDumpLinks && $wgContLang->getLanguageName( $this->mInterwiki
) ) {
671 $baseUrl = str_replace( '$1', "../../{$this->mInterwiki}/$1", $wgArticlePath );
672 $baseUrl = str_replace( '$1', $this->getHashedDirectory() . '/$1', $baseUrl );
674 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
677 $namespace = $wgContLang->getNsText( $this->mNamespace
);
678 if ( '' != $namespace ) {
679 # Can this actually happen? Interwikis shouldn't be parsed.
682 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
684 if( false === strpos( $url, '?' ) ) {
691 if ( '' != $this->mFragment
) {
692 $url .= '#' . $this->mFragment
;
698 * Get a relative directory for putting an HTML version of this article into
700 function getHashedDirectory() {
701 global $wgMakeDumpLinks, $wgInputEncoding;
702 $dbkey = $this->getDBkey();
704 # Split into characters
705 if ( $wgInputEncoding == 'UTF-8' ) {
706 preg_match_all( '/./us', $dbkey, $m );
708 preg_match_all( '/./s', $dbkey, $m );
711 $length = count( $chars );
714 for ( $i = 0; $i < $wgMakeDumpLinks; $i++
) {
718 if ( $i >= $length ) {
720 } elseif ( ord( $chars[$i] ) > 32 ) {
721 $dir .= strtolower( $chars[$i] );
723 $dir .= sprintf( "%02X", ord( $chars[$i] ) );
729 function getHashedFilename() {
730 $dbkey = $this->getPrefixedDBkey();
731 $mainPage = Title
::newMainPage();
732 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
736 $dir = $this->getHashedDirectory();
738 # Replace illegal charcters for Windows paths with underscores
739 $friendlyName = strtr( $dbkey, '/\\*?"<>|~', '_________' );
741 # Work out lower case form. We assume we're on a system with case-insensitive
742 # filenames, so unless the case is of a special form, we have to disambiguate
743 $lowerCase = $this->prefix( ucfirst( strtolower( $this->getDBkey() ) ) );
745 # Make it mostly unique
746 if ( $lowerCase != $friendlyName ) {
747 $friendlyName .= '_' . substr(md5( $dbkey ), 0, 4);
749 # Handle colon specially by replacing it with tilde
750 # Thus we reduce the number of paths with hashes appended
751 $friendlyName = str_replace( ':', '~', $friendlyName );
752 return "$dir/$friendlyName.html";
756 * Get a URL with no fragment or server name. If this page is generated
757 * with action=render, $wgServer is prepended.
758 * @param string $query an optional query string; if not specified,
759 * $wgArticlePath will be used.
760 * @return string the URL
763 function getLocalURL( $query = '' ) {
764 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks, $wgServer, $action;
766 if ( $this->isExternal() ) {
767 return $this->getFullURL();
770 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
771 if ( $wgMakeDumpLinks ) {
772 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
773 } elseif ( $query == '' ) {
774 $url = str_replace( '$1', $dbkey, $wgArticlePath );
776 global $wgActionPaths;
777 if( !empty( $wgActionPaths ) &&
778 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
779 $action = urldecode( $matches[2] );
780 if( isset( $wgActionPaths[$action] ) ) {
781 $query = $matches[1];
782 if( isset( $matches[4] ) ) $query .= $matches[4];
783 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
784 if( $query != '' ) $url .= '?' . $query;
788 if ( $query == '-' ) {
791 $url = "{$wgScript}?title={$dbkey}&{$query}";
794 if ($action == 'render')
795 return $wgServer . $url;
801 * Get an HTML-escaped version of the URL form, suitable for
802 * using in a link, without a server name or fragment
803 * @param string $query an optional query string
804 * @return string the URL
807 function escapeLocalURL( $query = '' ) {
808 return htmlspecialchars( $this->getLocalURL( $query ) );
812 * Get an HTML-escaped version of the URL form, suitable for
813 * using in a link, including the server name and fragment
815 * @return string the URL
816 * @param string $query an optional query string
819 function escapeFullURL( $query = '' ) {
820 return htmlspecialchars( $this->getFullURL( $query ) );
824 * Get the URL form for an internal link.
825 * - Used in various Squid-related code, in case we have a different
826 * internal hostname for the server from the exposed one.
828 * @param string $query an optional query string
829 * @return string the URL
832 function getInternalURL( $query = '' ) {
833 global $wgInternalServer;
834 return $wgInternalServer . $this->getLocalURL( $query );
838 * Get the edit URL for this Title
839 * @return string the URL, or a null string if this is an
843 function getEditURL() {
844 global $wgServer, $wgScript;
846 if ( '' != $this->mInterwiki
) { return ''; }
847 $s = $this->getLocalURL( 'action=edit' );
853 * Get the HTML-escaped displayable text form.
854 * Used for the title field in <a> tags.
855 * @return string the text, including any prefixes
858 function getEscapedText() {
859 return htmlspecialchars( $this->getPrefixedText() );
863 * Is this Title interwiki?
867 function isExternal() { return ( '' != $this->mInterwiki
); }
870 * Does the title correspond to a protected article?
871 * @param string $what the action the page is protected from,
872 * by default checks move and edit
876 function isProtected($action = '') {
877 if ( -1 == $this->mNamespace
) { return true; }
878 if($action == 'edit' ||
$action == '') {
879 $a = $this->getRestrictions("edit");
880 if ( in_array( 'sysop', $a ) ) { return true; }
882 if($action == 'move' ||
$action == '') {
883 $a = $this->getRestrictions("move");
884 if ( in_array( 'sysop', $a ) ) { return true; }
890 * Is $wgUser is watching this page?
894 function userIsWatching() {
897 if ( is_null( $this->mWatched
) ) {
898 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
899 $this->mWatched
= false;
901 $this->mWatched
= $wgUser->isWatched( $this );
904 return $this->mWatched
;
908 * Is $wgUser perform $action this page?
909 * @param string $action action that permission needs to be checked for
913 function userCan($action) {
914 $fname = 'Title::userCanEdit';
915 wfProfileIn( $fname );
918 if( NS_SPECIAL
== $this->mNamespace
) {
919 wfProfileOut( $fname );
922 if( NS_MEDIAWIKI
== $this->mNamespace
&&
923 !$wgUser->isAllowed('editinterface') ) {
924 wfProfileOut( $fname );
927 if( $this->mDbkeyform
== '_' ) {
928 # FIXME: Is this necessary? Shouldn't be allowed anyway...
929 wfProfileOut( $fname );
933 # protect global styles and js
934 if ( NS_MEDIAWIKI
== $this->mNamespace
935 && preg_match("/\\.(css|js)$/", $this->mTextform
)
936 && !$wgUser->isAllowed('editinterface') ) {
937 wfProfileOut( $fname );
941 # protect css/js subpages of user pages
942 # XXX: this might be better using restrictions
943 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
944 if( NS_USER
== $this->mNamespace
945 && preg_match("/\\.(css|js)$/", $this->mTextform
)
946 && !$wgUser->isAllowed('editinterface')
947 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
948 wfProfileOut( $fname );
952 foreach( $this->getRestrictions($action) as $right ) {
953 // Backwards compatibility, rewrite sysop -> protect
954 if ( $right == 'sysop' ) {
957 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
958 wfProfileOut( $fname );
963 if( $action == 'move' &&
964 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
965 wfProfileOut( $fname );
969 wfProfileOut( $fname );
974 * Can $wgUser edit this page?
978 function userCanEdit() {
979 return $this->userCan('edit');
983 * Can $wgUser move this page?
987 function userCanMove() {
988 return $this->userCan('move');
992 * Would anybody with sufficient privileges be able to move this page?
993 * Some pages just aren't movable.
998 function isMovable() {
999 return Namespace::isMovable( $this->getNamespace() )
1000 && $this->getInterwiki() == '';
1004 * Can $wgUser read this page?
1008 function userCanRead() {
1011 if( $wgUser->isAllowed('read') ) {
1014 global $wgWhitelistRead;
1016 /** If anon users can create an account,
1017 they need to reach the login page first! */
1018 if( $wgUser->isAllowed( 'createaccount' )
1019 && $this->getNamespace() == NS_SPECIAL
1020 && $this->getText() == 'Userlogin' ) {
1024 /** some pages are explicitly allowed */
1025 $name = $this->getPrefixedText();
1026 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1030 # Compatibility with old settings
1031 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1032 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1041 * Is this a talk page of some sort?
1045 function isTalkPage() {
1046 return Namespace::isTalk( $this->getNamespace() );
1050 * Is this a .css or .js subpage of a user page?
1054 function isCssJsSubpage() {
1055 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1058 * Is this a .css subpage of a user page?
1062 function isCssSubpage() {
1063 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1066 * Is this a .js subpage of a user page?
1070 function isJsSubpage() {
1071 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1074 * Protect css/js subpages of user pages: can $wgUser edit
1078 * @todo XXX: this might be better using restrictions
1081 function userCanEditCssJsSubpage() {
1083 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1087 * Loads a string into mRestrictions array
1088 * @param string $res restrictions in string format
1091 function loadRestrictions( $res ) {
1092 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1093 $temp = explode( '=', trim( $restrict ) );
1094 if(count($temp) == 1) {
1095 // old format should be treated as edit/move restriction
1096 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1097 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1099 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1102 $this->mRestrictionsLoaded
= true;
1106 * Accessor/initialisation for mRestrictions
1107 * @param string $action action that permission needs to be checked for
1108 * @return array the array of groups allowed to edit this article
1111 function getRestrictions($action) {
1112 $id = $this->getArticleID();
1113 if ( 0 == $id ) { return array(); }
1115 if ( ! $this->mRestrictionsLoaded
) {
1116 $dbr =& wfGetDB( DB_SLAVE
);
1117 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1118 $this->loadRestrictions( $res );
1120 if( isset( $this->mRestrictions
[$action] ) ) {
1121 return $this->mRestrictions
[$action];
1127 * Is there a version of this page in the deletion archive?
1128 * @return int the number of archived revisions
1131 function isDeleted() {
1132 $fname = 'Title::isDeleted';
1133 if ( $this->getNamespace() < 0 ) {
1136 $dbr =& wfGetDB( DB_SLAVE
);
1137 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1138 'ar_title' => $this->getDBkey() ), $fname );
1144 * Get the article ID for this Title from the link cache,
1145 * adding it if necessary
1146 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1148 * @return int the ID
1151 function getArticleID( $flags = 0 ) {
1152 global $wgLinkCache;
1153 if ( $flags & GAID_FOR_UPDATE
) {
1154 $oldUpdate = $wgLinkCache->forUpdate( true );
1155 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1156 $wgLinkCache->forUpdate( $oldUpdate );
1158 if ( -1 == $this->mArticleID
) {
1159 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1162 return $this->mArticleID
;
1165 function getLatestRevID() {
1166 if ($this->mLatestID
!== false)
1167 return $this->mLatestID
;
1169 $db =& wfGetDB(DB_SLAVE
);
1170 return $this->mLatestID
= $db->selectField( 'revision',
1172 array('rev_page' => $this->getArticleID()),
1173 'Title::getLatestRevID' );
1177 * This clears some fields in this object, and clears any associated
1178 * keys in the "bad links" section of $wgLinkCache.
1180 * - This is called from Article::insertNewArticle() to allow
1181 * loading of the new page_id. It's also called from
1182 * Article::doDeleteArticle()
1184 * @param int $newid the new Article ID
1187 function resetArticleID( $newid ) {
1188 global $wgLinkCache;
1189 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1191 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1192 else { $this->mArticleID
= $newid; }
1193 $this->mRestrictionsLoaded
= false;
1194 $this->mRestrictions
= array();
1198 * Updates page_touched for this page; called from LinksUpdate.php
1199 * @return bool true if the update succeded
1202 function invalidateCache() {
1203 global $wgUseFileCache;
1205 if ( wfReadOnly() ) {
1209 $now = wfTimestampNow();
1210 $dbw =& wfGetDB( DB_MASTER
);
1211 $success = $dbw->update( 'page',
1213 'page_touched' => $dbw->timestamp()
1214 ), array( /* WHERE */
1215 'page_namespace' => $this->getNamespace() ,
1216 'page_title' => $this->getDBkey()
1217 ), 'Title::invalidateCache'
1220 if ($wgUseFileCache) {
1221 $cache = new CacheManager($this);
1222 @unlink
($cache->fileCacheName());
1229 * Prefix some arbitrary text with the namespace or interwiki prefix
1232 * @param string $name the text
1233 * @return string the prefixed text
1236 /* private */ function prefix( $name ) {
1240 if ( '' != $this->mInterwiki
) {
1241 $p = $this->mInterwiki
. ':';
1243 if ( 0 != $this->mNamespace
) {
1244 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1250 * Secure and split - main initialisation function for this object
1252 * Assumes that mDbkeyform has been set, and is urldecoded
1253 * and uses underscores, but not otherwise munged. This function
1254 * removes illegal characters, splits off the interwiki and
1255 * namespace prefixes, sets the other forms, and canonicalizes
1257 * @return bool true on success
1260 /* private */ function secureAndSplit() {
1261 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1262 $fname = 'Title::secureAndSplit';
1263 wfProfileIn( $fname );
1266 static $rxTc = false;
1268 # % is needed as well
1269 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1272 $this->mInterwiki
= $this->mFragment
= '';
1273 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1275 # Clean up whitespace
1277 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1278 $t = trim( $t, '_' );
1281 wfProfileOut( $fname );
1285 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1286 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1287 wfProfileOut( $fname );
1291 $this->mDbkeyform
= $t;
1293 # Initial colon indicates main namespace rather than specified default
1294 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1295 if ( ':' == $t{0} ) {
1296 $this->mNamespace
= NS_MAIN
;
1297 $t = substr( $t, 1 ); # remove the colon but continue processing
1300 # Namespace or interwiki prefix
1303 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1305 $lowerNs = strtolower( $p );
1306 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1307 # Canonical namespace
1309 $this->mNamespace
= $ns;
1310 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1311 # Ordinary namespace
1313 $this->mNamespace
= $ns;
1314 } elseif( $this->getInterwikiLink( $p ) ) {
1316 # Can't make a local interwiki link to an interwiki link.
1317 # That's just crazy!
1318 wfProfileOut( $fname );
1324 $this->mInterwiki
= $p;
1326 # Redundant interwiki prefix to the local wiki
1327 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1329 # Can't have an empty self-link
1330 wfProfileOut( $fname );
1333 $this->mInterwiki
= '';
1335 # Do another namespace split...
1339 # If there's no recognized interwiki or namespace,
1340 # then let the colon expression be part of the title.
1346 # We already know that some pages won't be in the database!
1348 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1349 $this->mArticleID
= 0;
1351 $f = strstr( $r, '#' );
1352 if ( false !== $f ) {
1353 $this->mFragment
= substr( $f, 1 );
1354 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1355 # remove whitespace again: prevents "Foo_bar_#"
1356 # becoming "Foo_bar_"
1357 $r = preg_replace( '/_*$/', '', $r );
1360 # Reject illegal characters.
1362 if( preg_match( $rxTc, $r ) ) {
1363 wfProfileOut( $fname );
1368 * Pages with "/./" or "/../" appearing in the URLs will
1369 * often be unreachable due to the way web browsers deal
1370 * with 'relative' URLs. Forbid them explicitly.
1372 if ( strpos( $r, '.' ) !== false &&
1373 ( $r === '.' ||
$r === '..' ||
1374 strpos( $r, './' ) === 0 ||
1375 strpos( $r, '../' ) === 0 ||
1376 strpos( $r, '/./' ) !== false ||
1377 strpos( $r, '/../' ) !== false ) )
1379 wfProfileOut( $fname );
1383 # We shouldn't need to query the DB for the size.
1384 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1385 if ( strlen( $r ) > 255 ) {
1386 wfProfileOut( $fname );
1391 * Normally, all wiki links are forced to have
1392 * an initial capital letter so [[foo]] and [[Foo]]
1393 * point to the same place.
1395 * Don't force it for interwikis, since the other
1396 * site might be case-sensitive.
1398 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1399 $t = $wgContLang->ucfirst( $r );
1405 * Can't make a link to a namespace alone...
1406 * "empty" local links can only be self-links
1407 * with a fragment identifier.
1410 $this->mInterwiki
== '' &&
1411 $this->mNamespace
!= NS_MAIN
) {
1412 wfProfileOut( $fname );
1417 $this->mDbkeyform
= $t;
1418 $this->mUrlform
= wfUrlencode( $t );
1420 $this->mTextform
= str_replace( '_', ' ', $t );
1422 wfProfileOut( $fname );
1427 * Get a Title object associated with the talk page of this article
1428 * @return Title the object for the talk page
1431 function getTalkPage() {
1432 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1436 * Get a title object associated with the subject page of this
1439 * @return Title the object for the subject page
1442 function getSubjectPage() {
1443 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1447 * Get an array of Title objects linking to this Title
1448 * Also stores the IDs in the link cache.
1450 * @param string $options may be FOR UPDATE
1451 * @return array the Title objects linking here
1454 function getLinksTo( $options = '' ) {
1455 global $wgLinkCache;
1456 $id = $this->getArticleID();
1459 $db =& wfGetDB( DB_MASTER
);
1461 $db =& wfGetDB( DB_SLAVE
);
1464 $res = $db->select( array( 'page', 'pagelinks' ),
1465 array( 'page_namespace', 'page_title', 'page_id' ),
1468 'pl_namespace' => $this->getNamespace(),
1469 'pl_title' => $this->getDbKey() ),
1470 'Title::getLinksTo',
1474 if ( $db->numRows( $res ) ) {
1475 while ( $row = $db->fetchObject( $res ) ) {
1476 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1477 $wgLinkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1478 $retVal[] = $titleObj;
1482 $db->freeResult( $res );
1487 * Get an array of Title objects referring to non-existent articles linked from this page
1489 * @param string $options may be FOR UPDATE
1490 * @return array the Title objects
1493 function getBrokenLinksFrom( $options = '' ) {
1494 global $wgLinkCache;
1497 $db =& wfGetDB( DB_MASTER
);
1499 $db =& wfGetDB( DB_SLAVE
);
1502 $res = $db->safeQuery(
1503 "SELECT pl_namespace, pl_title
1506 ON pl_namespace=page_namespace
1507 AND pl_title=page_title
1509 AND page_namespace IS NULL
1511 $db->tableName( 'pagelinks' ),
1512 $db->tableName( 'page' ),
1513 $this->getArticleId(),
1517 if ( $db->numRows( $res ) ) {
1518 while ( $row = $db->fetchObject( $res ) ) {
1519 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1522 $db->freeResult( $res );
1528 * Get a list of URLs to purge from the Squid cache when this
1531 * @return array the URLs
1534 function getSquidURLs() {
1536 $this->getInternalURL(),
1537 $this->getInternalURL( 'action=history' )
1542 * Move this page without authentication
1543 * @param Title &$nt the new page Title
1546 function moveNoAuth( &$nt ) {
1547 return $this->moveTo( $nt, false );
1551 * Check whether a given move operation would be valid.
1552 * Returns true if ok, or a message key string for an error message
1553 * if invalid. (Scarrrrry ugly interface this.)
1554 * @param Title &$nt the new title
1555 * @param bool $auth indicates whether $wgUser's permissions
1557 * @return mixed true on success, message name on failure
1560 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1562 if( !$this or !$nt ) {
1563 return 'badtitletext';
1565 if( $this->equals( $nt ) ) {
1568 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1569 return 'immobile_namespace';
1572 $fname = 'Title::move';
1573 $oldid = $this->getArticleID();
1574 $newid = $nt->getArticleID();
1576 if ( strlen( $nt->getDBkey() ) < 1 ) {
1577 return 'articleexists';
1579 if ( ( '' == $this->getDBkey() ) ||
1581 ( '' == $nt->getDBkey() ) ) {
1582 return 'badarticleerror';
1586 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1587 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1588 return 'protectedpage';
1591 # The move is allowed only if (1) the target doesn't exist, or
1592 # (2) the target is a redirect to the source, and has no history
1593 # (so we can undo bad moves right after they're done).
1595 if ( 0 != $newid ) { # Target exists; check for validity
1596 if ( ! $this->isValidMoveTarget( $nt ) ) {
1597 return 'articleexists';
1604 * Move a title to a new location
1605 * @param Title &$nt the new title
1606 * @param bool $auth indicates whether $wgUser's permissions
1608 * @return mixed true on success, message name on failure
1611 function moveTo( &$nt, $auth = true, $reason = '' ) {
1612 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1613 if( is_string( $err ) ) {
1617 $pageid = $this->getArticleID();
1618 if( $nt->exists() ) {
1619 $this->moveOverExistingRedirect( $nt, $reason );
1620 $pageCountChange = 0;
1621 } else { # Target didn't exist, do normal move.
1622 $this->moveToNewTitle( $nt, $newid, $reason );
1623 $pageCountChange = 1;
1625 $redirid = $this->getArticleID();
1627 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1628 $dbw =& wfGetDB( DB_MASTER
);
1629 $categorylinks = $dbw->tableName( 'categorylinks' );
1630 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1631 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1632 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1633 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1637 $oldnamespace = $this->getNamespace() & ~
1;
1638 $newnamespace = $nt->getNamespace() & ~
1;
1639 $oldtitle = $this->getDBkey();
1640 $newtitle = $nt->getDBkey();
1642 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1643 WatchedItem
::duplicateEntries( $this, $nt );
1646 # Update search engine
1647 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1649 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1653 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1654 # Moved out of main namespace
1655 # not viewed, edited, removing
1656 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1657 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1658 # Moved into main namespace
1659 # not viewed, edited, adding
1660 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1661 } elseif ( $pageCountChange ) {
1663 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1671 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1676 * Move page to a title which is at present a redirect to the
1679 * @param Title &$nt the page to move to, which should currently
1683 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1684 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1685 $fname = 'Title::moveOverExistingRedirect';
1686 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1689 $comment .= ": $reason";
1692 $now = wfTimestampNow();
1694 $newid = $nt->getArticleID();
1695 $oldid = $this->getArticleID();
1696 $dbw =& wfGetDB( DB_MASTER
);
1697 $links = $dbw->tableName( 'links' );
1699 # Delete the old redirect. We don't save it to history since
1700 # by definition if we've got here it's rather uninteresting.
1701 # We have to remove it so that the next step doesn't trigger
1702 # a conflict on the unique namespace+title index...
1703 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1705 # Save a null revision in the page's history notifying of the move
1706 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1707 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1709 $nullRevId = $nullRevision->insertOn( $dbw );
1711 # Change the name of the target page:
1712 $dbw->update( 'page',
1714 'page_touched' => $dbw->timestamp($now),
1715 'page_namespace' => $nt->getNamespace(),
1716 'page_title' => $nt->getDBkey(),
1717 'page_latest' => $nullRevId,
1719 /* WHERE */ array( 'page_id' => $oldid ),
1722 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1724 # Recreate the redirect, this time in the other direction.
1725 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1726 $redirectArticle = new Article( $this );
1727 $newid = $redirectArticle->insertOn( $dbw );
1728 $redirectRevision = new Revision( array(
1730 'comment' => $comment,
1731 'text' => $redirectText ) );
1732 $revid = $redirectRevision->insertOn( $dbw );
1733 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1734 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1737 $log = new LogPage( 'move' );
1738 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1740 # Now, we record the link from the redirect to the new title.
1741 # It should have no other outgoing links...
1742 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1743 $dbw->insert( 'pagelinks',
1745 'pl_from' => $newid,
1746 'pl_namespace' => $nt->getNamespace(),
1747 'pl_title' => $nt->getDbKey() ),
1751 if ( $wgUseSquid ) {
1752 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1753 $u = new SquidUpdate( $urls );
1759 * Move page to non-existing title.
1760 * @param Title &$nt the new Title
1761 * @param int &$newid set to be the new article ID
1764 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1765 global $wgUser, $wgLinkCache, $wgUseSquid;
1767 $fname = 'MovePageForm::moveToNewTitle';
1768 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1770 $comment .= ": $reason";
1773 $newid = $nt->getArticleID();
1774 $oldid = $this->getArticleID();
1775 $dbw =& wfGetDB( DB_MASTER
);
1776 $now = $dbw->timestamp();
1780 # Save a null revision in the page's history notifying of the move
1781 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1782 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1784 $nullRevId = $nullRevision->insertOn( $dbw );
1787 $dbw->update( 'page',
1789 'page_touched' => $now,
1790 'page_namespace' => $nt->getNamespace(),
1791 'page_title' => $nt->getDBkey(),
1792 'page_latest' => $nullRevId,
1794 /* WHERE */ array( 'page_id' => $oldid ),
1798 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1801 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1802 $redirectArticle = new Article( $this );
1803 $newid = $redirectArticle->insertOn( $dbw );
1804 $redirectRevision = new Revision( array(
1806 'comment' => $comment,
1807 'text' => $redirectText ) );
1808 $revid = $redirectRevision->insertOn( $dbw );
1809 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1810 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1813 $log = new LogPage( 'move' );
1814 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1816 # Purge caches as per article creation
1817 Article
::onArticleCreate( $nt );
1819 # Record the just-created redirect's linking to the page
1820 $dbw->insert( 'pagelinks',
1822 'pl_from' => $newid,
1823 'pl_namespace' => $nt->getNamespace(),
1824 'pl_title' => $nt->getDBkey() ),
1827 # Non-existent target may have had broken links to it; these must
1828 # now be touched to update link coloring.
1831 # Purge old title from squid
1832 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1833 $titles = $nt->getLinksTo();
1834 if ( $wgUseSquid ) {
1835 $urls = $this->getSquidURLs();
1836 foreach ( $titles as $linkTitle ) {
1837 $urls[] = $linkTitle->getInternalURL();
1839 $u = new SquidUpdate( $urls );
1845 * Checks if $this can be moved to a given Title
1846 * - Selects for update, so don't call it unless you mean business
1848 * @param Title &$nt the new title to check
1851 function isValidMoveTarget( $nt ) {
1853 $fname = 'Title::isValidMoveTarget';
1854 $dbw =& wfGetDB( DB_MASTER
);
1857 $id = $nt->getArticleID();
1858 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1859 array( 'page_is_redirect','old_text' ),
1860 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1861 $fname, 'FOR UPDATE' );
1863 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1868 # Does the redirect point to the source?
1869 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text
, $m ) ) {
1870 $redirTitle = Title
::newFromText( $m[1] );
1871 if( !is_object( $redirTitle ) ||
1872 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1877 # Does the article have a history?
1878 $row = $dbw->selectRow( array( 'page', 'revision'),
1880 array( 'page_namespace' => $nt->getNamespace(),
1881 'page_title' => $nt->getDBkey(),
1882 'page_id=rev_page AND page_latest != rev_id'
1883 ), $fname, 'FOR UPDATE'
1886 # Return true if there was no history
1887 return $row === false;
1891 * Create a redirect; fails if the title already exists; does
1894 * @param Title $dest the destination of the redirect
1895 * @param string $comment the comment string describing the move
1896 * @return bool true on success
1899 function createRedirect( $dest, $comment ) {
1901 if ( $this->getArticleID() ) {
1905 $fname = 'Title::createRedirect';
1906 $dbw =& wfGetDB( DB_MASTER
);
1908 $article = new Article( $this );
1909 $newid = $article->insertOn( $dbw );
1910 $revision = new Revision( array(
1912 'comment' => $comment,
1913 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1915 $revisionId = $revision->insertOn( $dbw );
1916 $article->updateRevisionOn( $dbw, $revision, 0 );
1919 $dbw->insert( 'pagelinks',
1921 'pl_from' => $newid,
1922 'pl_namespace' => $dest->getNamespace(),
1923 'pl_title' => $dest->getDbKey()
1927 Article
::onArticleCreate( $this );
1932 * Get categories to which this Title belongs and return an array of
1933 * categories' names.
1935 * @return array an array of parents in the form:
1936 * $parent => $currentarticle
1939 function getParentCategories() {
1940 global $wgContLang,$wgUser;
1942 $titlekey = $this->getArticleId();
1943 $sk =& $wgUser->getSkin();
1945 $dbr =& wfGetDB( DB_SLAVE
);
1946 $categorylinks = $dbr->tableName( 'categorylinks' );
1949 $sql = "SELECT * FROM $categorylinks"
1950 ." WHERE cl_from='$titlekey'"
1951 ." AND cl_from <> '0'"
1952 ." ORDER BY cl_sortkey";
1954 $res = $dbr->query ( $sql ) ;
1956 if($dbr->numRows($res) > 0) {
1957 while ( $x = $dbr->fetchObject ( $res ) )
1958 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1959 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1960 $dbr->freeResult ( $res ) ;
1968 * Get a tree of parent categories
1969 * @param array $children an array with the children in the keys, to check for circular refs
1973 function getParentCategoryTree( $children = array() ) {
1974 $parents = $this->getParentCategories();
1976 if($parents != '') {
1977 foreach($parents as $parent => $current)
1979 if ( array_key_exists( $parent, $children ) ) {
1980 # Circular reference
1981 $stack[$parent] = array();
1983 $nt = Title
::newFromText($parent);
1984 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
1995 * Get an associative array for selecting this title from
2001 function curCond() {
2002 wfDebugDieBacktrace( 'curCond called' );
2003 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
2007 * Get an associative array for selecting this title from the
2013 function oldCond() {
2014 wfDebugDieBacktrace( 'oldCond called' );
2015 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);
2019 * Get the revision ID of the previous revision
2021 * @param integer $revision Revision ID. Get the revision that was before this one.
2022 * @return interger $oldrevision|false
2024 function getPreviousRevisionID( $revision ) {
2025 $dbr =& wfGetDB( DB_SLAVE
);
2026 return $dbr->selectField( 'revision', 'rev_id',
2027 'rev_page=' . intval( $this->getArticleId() ) .
2028 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2032 * Get the revision ID of the next revision
2034 * @param integer $revision Revision ID. Get the revision that was after this one.
2035 * @return interger $oldrevision|false
2037 function getNextRevisionID( $revision ) {
2038 $dbr =& wfGetDB( DB_SLAVE
);
2039 return $dbr->selectField( 'revision', 'rev_id',
2040 'rev_page=' . intval( $this->getArticleId() ) .
2041 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2045 * Compare with another title.
2047 * @param Title $title
2050 function equals( &$title ) {
2051 return $this->getInterwiki() == $title->getInterwiki()
2052 && $this->getNamespace() == $title->getNamespace()
2053 && $this->getDbkey() == $title->getDbkey();
2057 * Check if page exists
2061 return $this->getArticleId() != 0;
2065 * Should a link should be displayed as a known link, just based on its title?
2067 * Currently, a self-link with a fragment, special pages and image pages are in
2068 * this category. Special pages never exist in the database. Some images do not
2069 * have description pages in the database, but the description page contains
2070 * useful history information that the user may want to link to.
2072 function isAlwaysKnown() {
2073 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2074 || NS_SPECIAL
== $this->mNamespace || NS_IMAGE
== $this->mNamespace
;
2078 * Update page_touched timestamps on pages linking to this title.
2079 * In principal, this could be backgrounded and could also do squid
2082 function touchLinks() {
2083 $fname = 'Title::touchLinks';
2085 $dbw =& wfGetDB( DB_MASTER
);
2087 $res = $dbw->select( 'pagelinks',
2090 'pl_namespace' => $this->getNamespace(),
2091 'pl_title' => $this->getDbKey() ),
2093 if ( 0 == $dbw->numRows( $res ) ) {
2098 $toucharr = array();
2099 while( $row = $dbw->fetchObject( $res ) ) {
2100 $toucharr[] = $row->pl_from
;
2102 if (!count($toucharr))
2104 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2105 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2108 function trackbackURL() {
2109 global $wgTitle, $wgScriptPath, $wgServer;
2111 return "$wgServer$wgScriptPath/trackback.php?article="
2112 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2115 function trackbackRDF() {
2116 $url = htmlspecialchars($this->getFullURL());
2117 $title = htmlspecialchars($this->getText());
2118 $tburl = $this->trackbackURL();
2121 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2122 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2123 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2126 dc:identifier=\"$url\"
2128 trackback:ping=\"$tburl\" />