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 );
153 * Create a new Title from URL-encoded text. Ensures that
154 * the given title's length does not exceed the maximum.
155 * @param string $url the title, as might be taken from a URL
156 * @return Title the new object, or NULL on an error
160 function newFromURL( $url ) {
161 global $wgLang, $wgServer;
164 # For compatibility with old buggy URLs. "+" is not valid in titles,
165 # but some URLs used it as a space replacement and they still come
166 # from some external search tools.
167 $s = str_replace( '+', ' ', $url );
169 $t->mDbkeyform
= str_replace( ' ', '_', $s );
170 if( $t->secureAndSplit() ) {
178 * Create a new Title from an article ID
180 * @todo This is inefficiently implemented, the page row is requested
181 * but not used for anything else
183 * @param int $id the page_id corresponding to the Title to create
184 * @return Title the new object, or NULL on an error
188 function newFromID( $id ) {
189 $fname = 'Title::newFromID';
190 $dbr =& wfGetDB( DB_SLAVE
);
191 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
192 array( 'page_id' => $id ), $fname );
193 if ( $row !== false ) {
194 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
202 * Create a new Title from a namespace index and a DB key.
203 * It's assumed that $ns and $title are *valid*, for instance when
204 * they came directly from the database or a special page name.
205 * For convenience, spaces are converted to underscores so that
206 * eg user_text fields can be used directly.
208 * @param int $ns the namespace of the article
209 * @param string $title the unprefixed database key form
210 * @return Title the new object
214 function &makeTitle( $ns, $title ) {
218 $t->mNamespace
= IntVal( $ns );
219 $t->mDbkeyform
= str_replace( ' ', '_', $title );
220 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
221 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
222 $t->mTextform
= str_replace( '_', ' ', $title );
227 * Create a new Title frrom a namespace index and a DB key.
228 * The parameters will be checked for validity, which is a bit slower
229 * than makeTitle() but safer for user-provided data.
231 * @param int $ns the namespace of the article
232 * @param string $title the database key form
233 * @return Title the new object, or NULL on an error
237 function makeTitleSafe( $ns, $title ) {
239 $t->mDbkeyform
= Title
::makeName( $ns, $title );
240 if( $t->secureAndSplit() ) {
248 * Create a new Title for the Main Page
251 * @return Title the new object
254 function newMainPage() {
255 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
259 * Create a new Title for a redirect
260 * @param string $text the redirect title text
261 * @return Title the new object, or NULL if the text is not a
266 function newFromRedirect( $text ) {
269 if ( $wgMwRedir->matchStart( $text ) ) {
270 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
271 # categories are escaped using : for example one can enter:
272 # #REDIRECT [[:Category:Music]]. Need to remove it.
273 if ( substr($m[1],0,1) == ':') {
274 # We don't want to keep the ':'
275 $m[1] = substr( $m[1], 1 );
278 $rt = Title
::newFromText( $m[1] );
279 # Disallow redirects to Special:Userlogout
280 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
288 #----------------------------------------------------------------------------
290 #----------------------------------------------------------------------------
293 * Get the prefixed DB key associated with an ID
294 * @param int $id the page_id of the article
295 * @return Title an object representing the article, or NULL
296 * if no such article was found
300 function nameOf( $id ) {
301 $fname = 'Title::nameOf';
302 $dbr =& wfGetDB( DB_SLAVE
);
304 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
305 if ( $s === false ) { return NULL; }
307 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
312 * Get a regex character class describing the legal characters in a link
313 * @return string the list of characters, not delimited
317 function legalChars() {
318 # Missing characters:
319 # * []|# Needed for link syntax
320 # * % and + are corrupted by Apache when they appear in the path
322 # % seems to work though
324 # The problem with % is that URLs are double-unescaped: once by Apache's
325 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
326 # Our code does not double-escape to compensate for this, indeed double escaping
327 # would break if the double-escaped title was passed in the query string
328 # rather than the path. This is a minor security issue because articles can be
329 # created such that they are hard to view or edit. -- TS
331 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
332 # this breaks interlanguage links
334 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF";
339 * Get a string representation of a title suitable for
340 * including in a search index
342 * @param int $ns a namespace index
343 * @param string $title text-form main part
344 * @return string a stripped-down title string ready for the
347 /* static */ function indexTitle( $ns, $title ) {
348 global $wgDBminWordLen, $wgContLang;
349 require_once( 'SearchEngine.php' );
351 $lc = SearchEngine
::legalSearchChars() . '&#;';
352 $t = $wgContLang->stripForSearch( $title );
353 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
354 $t = strtolower( $t );
357 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
358 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
360 $t = preg_replace( "/\\s+/", ' ', $t );
362 if ( $ns == NS_IMAGE
) {
363 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
369 * Make a prefixed DB key from a DB key and a namespace index
370 * @param int $ns numerical representation of the namespace
371 * @param string $title the DB key form the title
372 * @return string the prefixed form of the title
374 /* static */ function makeName( $ns, $title ) {
377 $n = $wgContLang->getNsText( $ns );
378 return $n == '' ?
$title : "$n:$title";
382 * Returns the URL associated with an interwiki prefix
383 * @param string $key the interwiki prefix (e.g. "MeatBall")
384 * @return the associated URL, containing "$1", which should be
385 * replaced by an article title
389 function getInterwikiLink( $key, $transludeonly = false ) {
390 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
391 $fname = 'Title::getInterwikiLink';
393 wfProfileIn( $fname );
395 $k = $wgDBname.':interwiki:'.$key;
396 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
397 wfProfileOut( $fname );
398 return $wgTitleInterwikiCache[$k]->iw_url
;
401 $s = $wgMemc->get( $k );
402 # Ignore old keys with no iw_local
403 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
404 $wgTitleInterwikiCache[$k] = $s;
405 wfProfileOut( $fname );
409 $dbr =& wfGetDB( DB_SLAVE
);
410 $res = $dbr->select( 'interwiki',
411 array( 'iw_url', 'iw_local', 'iw_trans' ),
412 array( 'iw_prefix' => $key ), $fname );
414 wfProfileOut( $fname );
418 $s = $dbr->fetchObject( $res );
420 # Cache non-existence: create a blank object and save it to memcached
426 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
427 $wgTitleInterwikiCache[$k] = $s;
429 wfProfileOut( $fname );
434 * Determine whether the object refers to a page within
437 * @return bool TRUE if this is an in-project interwiki link
438 * or a wikilink, FALSE otherwise
442 global $wgTitleInterwikiCache, $wgDBname;
444 if ( $this->mInterwiki
!= '' ) {
445 # Make sure key is loaded into cache
446 $this->getInterwikiLink( $this->mInterwiki
);
447 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
448 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
455 * Determine whether the object refers to a page within
456 * this project and is transcludable.
458 * @return bool TRUE if this is transcludable
462 global $wgTitleInterwikiCache, $wgDBname;
464 if ($this->mInterwiki
== '' ||
!$this->isLocal())
466 # Make sure key is loaded into cache
467 $this->getInterwikiLink( $this->mInterwiki
);
468 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
469 return (bool)($wgTitleInterwikiCache[$k]->iw_trans
);
473 * Update the page_touched field for an array of title objects
474 * @todo Inefficient unless the IDs are already loaded into the
476 * @param array $titles an array of Title objects to be touched
477 * @param string $timestamp the timestamp to use instead of the
478 * default current time
482 function touchArray( $titles, $timestamp = '' ) {
483 if ( count( $titles ) == 0 ) {
486 $dbw =& wfGetDB( DB_MASTER
);
487 if ( $timestamp == '' ) {
488 $timestamp = $dbw->timestamp();
490 $page = $dbw->tableName( 'page' );
491 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
494 foreach ( $titles as $title ) {
499 $sql .= $title->getArticleID();
503 $dbw->query( $sql, 'Title::touchArray' );
507 #----------------------------------------------------------------------------
509 #----------------------------------------------------------------------------
511 /** Simple accessors */
513 * Get the text form (spaces not underscores) of the main part
517 function getText() { return $this->mTextform
; }
519 * Get the URL-encoded form of the main part
523 function getPartialURL() { return $this->mUrlform
; }
525 * Get the main part with underscores
529 function getDBkey() { return $this->mDbkeyform
; }
531 * Get the namespace index, i.e. one of the NS_xxxx constants
535 function getNamespace() { return $this->mNamespace
; }
537 * Get the interwiki prefix (or null string)
541 function getInterwiki() { return $this->mInterwiki
; }
543 * Get the Title fragment (i.e. the bit after the #)
547 function getFragment() { return $this->mFragment
; }
549 * Get the default namespace index, for when there is no namespace
553 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
556 * Get title for search index
557 * @return string a stripped-down title string ready for the
560 function getIndexTitle() {
561 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
565 * Get the prefixed database key form
566 * @return string the prefixed title, with underscores and
567 * any interwiki and namespace prefixes
570 function getPrefixedDBkey() {
571 $s = $this->prefix( $this->mDbkeyform
);
572 $s = str_replace( ' ', '_', $s );
577 * Get the prefixed title with spaces.
578 * This is the form usually used for display
579 * @return string the prefixed title, with spaces
582 function getPrefixedText() {
584 if ( empty( $this->mPrefixedText
) ) {
585 $s = $this->prefix( $this->mTextform
);
586 $s = str_replace( '_', ' ', $s );
587 $this->mPrefixedText
= $s;
589 return $this->mPrefixedText
;
593 * Get the prefixed title with spaces, plus any fragment
594 * (part beginning with '#')
595 * @return string the prefixed title, with spaces and
596 * the fragment, including '#'
599 function getFullText() {
601 $text = $this->getPrefixedText();
602 if( '' != $this->mFragment
) {
603 $text .= '#' . $this->mFragment
;
609 * Get a URL-encoded title (not an actual URL) including interwiki
610 * @return string the URL-encoded form
613 function getPrefixedURL() {
614 $s = $this->prefix( $this->mDbkeyform
);
615 $s = str_replace( ' ', '_', $s );
617 $s = wfUrlencode ( $s ) ;
619 # Cleaning up URL to make it look nice -- is this safe?
620 $s = str_replace( '%28', '(', $s );
621 $s = str_replace( '%29', ')', $s );
627 * Get a real URL referring to this title, with interwiki link and
630 * @param string $query an optional query string, not used
631 * for interwiki links
632 * @return string the URL
635 function getFullURL( $query = '' ) {
636 global $wgContLang, $wgServer, $wgScript, $wgMakeDumpLinks, $wgArticlePath;
638 if ( '' == $this->mInterwiki
) {
639 return $wgServer . $this->getLocalUrl( $query );
640 } elseif ( $wgMakeDumpLinks && $wgContLang->getLanguageName( $this->mInterwiki
) ) {
641 $baseUrl = str_replace( '$1', "../../{$this->mInterwiki}/$1", $wgArticlePath );
642 $baseUrl = str_replace( '$1', $this->getHashedDirectory() . '/$1', $baseUrl );
644 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
647 $namespace = $wgContLang->getNsText( $this->mNamespace
);
648 if ( '' != $namespace ) {
649 # Can this actually happen? Interwikis shouldn't be parsed.
652 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
654 if( false === strpos( $url, '?' ) ) {
661 if ( '' != $this->mFragment
) {
662 $url .= '#' . $this->mFragment
;
668 * Get a relative directory for putting an HTML version of this article into
670 function getHashedDirectory() {
671 global $wgMakeDumpLinks, $wgInputEncoding;
672 $dbkey = $this->getDBkey();
674 # Split into characters
675 if ( $wgInputEncoding == 'UTF-8' ) {
676 preg_match_all( '/./us', $dbkey, $m );
678 preg_match_all( '/./s', $dbkey, $m );
681 $length = count( $chars );
684 for ( $i = 0; $i < $wgMakeDumpLinks; $i++
) {
688 if ( $i >= $length ) {
690 } elseif ( ord( $chars[$i] ) > 32 ) {
691 $dir .= strtolower( $chars[$i] );
693 $dir .= sprintf( "%02X", ord( $chars[$i] ) );
699 function getHashedFilename() {
700 $dbkey = $this->getPrefixedDBkey();
701 $mainPage = Title
::newMainPage();
702 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
706 $dir = $this->getHashedDirectory();
708 # Replace illegal charcters for Windows paths with underscores
709 $friendlyName = strtr( $dbkey, '/\\*?"<>|~', '_________' );
711 # Work out lower case form. We assume we're on a system with case-insensitive
712 # filenames, so unless the case is of a special form, we have to disambiguate
713 $lowerCase = $this->prefix( ucfirst( strtolower( $this->getDBkey() ) ) );
715 # Make it mostly unique
716 if ( $lowerCase != $friendlyName ) {
717 $friendlyName .= '_' . substr(md5( $dbkey ), 0, 4);
719 # Handle colon specially by replacing it with tilde
720 # Thus we reduce the number of paths with hashes appended
721 $friendlyName = str_replace( ':', '~', $friendlyName );
722 return "$dir/$friendlyName.html";
726 * Get a URL with no fragment or server name. If this page is generated
727 * with action=render, $wgServer is prepended.
728 * @param string $query an optional query string; if not specified,
729 * $wgArticlePath will be used.
730 * @return string the URL
733 function getLocalURL( $query = '' ) {
734 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks, $wgServer, $action;
736 if ( $this->isExternal() ) {
737 return $this->getFullURL();
740 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
741 if ( $wgMakeDumpLinks ) {
742 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
743 } elseif ( $query == '' ) {
744 $url = str_replace( '$1', $dbkey, $wgArticlePath );
746 global $wgActionPaths;
747 if( !empty( $wgActionPaths ) &&
748 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
749 $action = urldecode( $matches[2] );
750 if( isset( $wgActionPaths[$action] ) ) {
751 $query = $matches[1];
752 if( isset( $matches[4] ) ) $query .= $matches[4];
753 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
754 if( $query != '' ) $url .= '?' . $query;
758 if ( $query == '-' ) {
761 $url = "{$wgScript}?title={$dbkey}&{$query}";
764 if ($action == 'render')
765 return $wgServer . $url;
771 * Get an HTML-escaped version of the URL form, suitable for
772 * using in a link, without a server name or fragment
773 * @param string $query an optional query string
774 * @return string the URL
777 function escapeLocalURL( $query = '' ) {
778 return htmlspecialchars( $this->getLocalURL( $query ) );
782 * Get an HTML-escaped version of the URL form, suitable for
783 * using in a link, including the server name and fragment
785 * @return string the URL
786 * @param string $query an optional query string
789 function escapeFullURL( $query = '' ) {
790 return htmlspecialchars( $this->getFullURL( $query ) );
794 * Get the URL form for an internal link.
795 * - Used in various Squid-related code, in case we have a different
796 * internal hostname for the server from the exposed one.
798 * @param string $query an optional query string
799 * @return string the URL
802 function getInternalURL( $query = '' ) {
803 global $wgInternalServer;
804 return $wgInternalServer . $this->getLocalURL( $query );
808 * Get the edit URL for this Title
809 * @return string the URL, or a null string if this is an
813 function getEditURL() {
814 global $wgServer, $wgScript;
816 if ( '' != $this->mInterwiki
) { return ''; }
817 $s = $this->getLocalURL( 'action=edit' );
823 * Get the HTML-escaped displayable text form.
824 * Used for the title field in <a> tags.
825 * @return string the text, including any prefixes
828 function getEscapedText() {
829 return htmlspecialchars( $this->getPrefixedText() );
833 * Is this Title interwiki?
837 function isExternal() { return ( '' != $this->mInterwiki
); }
840 * Does the title correspond to a protected article?
841 * @param string $what the action the page is protected from,
842 * by default checks move and edit
846 function isProtected($action = '') {
847 if ( -1 == $this->mNamespace
) { return true; }
848 if($action == 'edit' ||
$action == '') {
849 $a = $this->getRestrictions("edit");
850 if ( in_array( 'sysop', $a ) ) { return true; }
852 if($action == 'move' ||
$action == '') {
853 $a = $this->getRestrictions("move");
854 if ( in_array( 'sysop', $a ) ) { return true; }
860 * Is $wgUser is watching this page?
864 function userIsWatching() {
867 if ( is_null( $this->mWatched
) ) {
868 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
869 $this->mWatched
= false;
871 $this->mWatched
= $wgUser->isWatched( $this );
874 return $this->mWatched
;
878 * Is $wgUser perform $action this page?
879 * @param string $action action that permission needs to be checked for
883 function userCan($action) {
884 $fname = 'Title::userCanEdit';
885 wfProfileIn( $fname );
888 if( NS_SPECIAL
== $this->mNamespace
) {
889 wfProfileOut( $fname );
892 if( NS_MEDIAWIKI
== $this->mNamespace
&&
893 !$wgUser->isAllowed('editinterface') ) {
894 wfProfileOut( $fname );
897 if( $this->mDbkeyform
== '_' ) {
898 # FIXME: Is this necessary? Shouldn't be allowed anyway...
899 wfProfileOut( $fname );
903 # protect global styles and js
904 if ( NS_MEDIAWIKI
== $this->mNamespace
905 && preg_match("/\\.(css|js)$/", $this->mTextform
)
906 && !$wgUser->isAllowed('editinterface') ) {
907 wfProfileOut( $fname );
911 # protect css/js subpages of user pages
912 # XXX: this might be better using restrictions
913 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
914 if( NS_USER
== $this->mNamespace
915 && preg_match("/\\.(css|js)$/", $this->mTextform
)
916 && !$wgUser->isAllowed('editinterface')
917 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
918 wfProfileOut( $fname );
922 foreach( $this->getRestrictions($action) as $right ) {
923 // Backwards compatibility, rewrite sysop -> protect
924 if ( $right == 'sysop' ) {
927 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
928 wfProfileOut( $fname );
933 if( $action == 'move' && !$this->isMovable() ) {
934 wfProfileOut( $fname );
938 wfProfileOut( $fname );
943 * Can $wgUser edit this page?
947 function userCanEdit() {
948 return $this->userCan('edit');
952 * Can $wgUser move this page?
956 function userCanMove() {
957 return $this->userCan('move');
961 * Would anybody with sufficient privileges be able to move this page?
962 * Some pages just aren't movable.
967 function isMovable() {
968 return Namespace::isMovable( $this->getNamespace() )
969 && $this->getInterwiki() == '';
973 * Can $wgUser read this page?
977 function userCanRead() {
980 if( $wgUser->isAllowed('read') ) {
983 global $wgWhitelistRead;
985 /** If anon users can create an account,
986 they need to reach the login page first! */
987 if( $wgUser->isAllowed( 'createaccount' )
988 && $this->getNamespace() == NS_SPECIAL
989 && $this->getText() == 'Userlogin' ) {
993 /** some pages are explicitly allowed */
994 $name = $this->getPrefixedText();
995 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
999 # Compatibility with old settings
1000 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
1001 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1010 * Is this a talk page of some sort?
1014 function isTalkPage() {
1015 return Namespace::isTalk( $this->getNamespace() );
1019 * Is this a .css or .js subpage of a user page?
1023 function isCssJsSubpage() {
1024 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1027 * Is this a .css subpage of a user page?
1031 function isCssSubpage() {
1032 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1035 * Is this a .js subpage of a user page?
1039 function isJsSubpage() {
1040 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1043 * Protect css/js subpages of user pages: can $wgUser edit
1047 * @todo XXX: this might be better using restrictions
1050 function userCanEditCssJsSubpage() {
1052 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1056 * Loads a string into mRestrictions array
1057 * @param string $res restrictions in string format
1060 function loadRestrictions( $res ) {
1061 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1062 $temp = explode( '=', trim( $restrict ) );
1063 if(count($temp) == 1) {
1064 // old format should be treated as edit/move restriction
1065 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1066 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1068 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1071 $this->mRestrictionsLoaded
= true;
1075 * Accessor/initialisation for mRestrictions
1076 * @param string $action action that permission needs to be checked for
1077 * @return array the array of groups allowed to edit this article
1080 function getRestrictions($action) {
1081 $id = $this->getArticleID();
1082 if ( 0 == $id ) { return array(); }
1084 if ( ! $this->mRestrictionsLoaded
) {
1085 $dbr =& wfGetDB( DB_SLAVE
);
1086 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1087 $this->loadRestrictions( $res );
1089 if( isset( $this->mRestrictions
[$action] ) ) {
1090 return $this->mRestrictions
[$action];
1096 * Is there a version of this page in the deletion archive?
1097 * @return int the number of archived revisions
1100 function isDeleted() {
1101 $fname = 'Title::isDeleted';
1102 if ( $this->getNamespace() < 0 ) {
1105 $dbr =& wfGetDB( DB_SLAVE
);
1106 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1107 'ar_title' => $this->getDBkey() ), $fname );
1113 * Get the article ID for this Title from the link cache,
1114 * adding it if necessary
1115 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1117 * @return int the ID
1120 function getArticleID( $flags = 0 ) {
1121 global $wgLinkCache;
1123 if ( $flags & GAID_FOR_UPDATE
) {
1124 $oldUpdate = $wgLinkCache->forUpdate( true );
1125 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1126 $wgLinkCache->forUpdate( $oldUpdate );
1128 if ( -1 == $this->mArticleID
) {
1129 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1132 return $this->mArticleID
;
1135 function getLatestRevID() {
1136 if ($this->mLatestID
!== false)
1137 return $this->mLatestID
;
1139 $db =& wfGetDB(DB_SLAVE
);
1140 return $this->mLatestID
= $db->selectField( 'revision',
1142 array('rev_page' => $this->getArticleID()),
1143 'Title::getLatestRevID' );
1147 * This clears some fields in this object, and clears any associated
1148 * keys in the "bad links" section of $wgLinkCache.
1150 * - This is called from Article::insertNewArticle() to allow
1151 * loading of the new page_id. It's also called from
1152 * Article::doDeleteArticle()
1154 * @param int $newid the new Article ID
1157 function resetArticleID( $newid ) {
1158 global $wgLinkCache;
1159 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1161 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1162 else { $this->mArticleID
= $newid; }
1163 $this->mRestrictionsLoaded
= false;
1164 $this->mRestrictions
= array();
1168 * Updates page_touched for this page; called from LinksUpdate.php
1169 * @return bool true if the update succeded
1172 function invalidateCache() {
1173 global $wgUseFileCache;
1175 if ( wfReadOnly() ) {
1179 $now = wfTimestampNow();
1180 $dbw =& wfGetDB( DB_MASTER
);
1181 $success = $dbw->update( 'page',
1183 'page_touched' => $dbw->timestamp()
1184 ), array( /* WHERE */
1185 'page_namespace' => $this->getNamespace() ,
1186 'page_title' => $this->getDBkey()
1187 ), 'Title::invalidateCache'
1190 if ($wgUseFileCache) {
1191 $cache = new CacheManager($this);
1192 @unlink
($cache->fileCacheName());
1199 * Prefix some arbitrary text with the namespace or interwiki prefix
1202 * @param string $name the text
1203 * @return string the prefixed text
1206 /* private */ function prefix( $name ) {
1210 if ( '' != $this->mInterwiki
) {
1211 $p = $this->mInterwiki
. ':';
1213 if ( 0 != $this->mNamespace
) {
1214 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1220 * Secure and split - main initialisation function for this object
1222 * Assumes that mDbkeyform has been set, and is urldecoded
1223 * and uses underscores, but not otherwise munged. This function
1224 * removes illegal characters, splits off the interwiki and
1225 * namespace prefixes, sets the other forms, and canonicalizes
1227 * @return bool true on success
1230 /* private */ function secureAndSplit() {
1231 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1232 $fname = 'Title::secureAndSplit';
1233 wfProfileIn( $fname );
1236 static $rxTc = false;
1238 # % is needed as well
1239 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1242 $this->mInterwiki
= $this->mFragment
= '';
1243 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1245 # Clean up whitespace
1247 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1248 $t = trim( $t, '_' );
1251 wfProfileOut( $fname );
1255 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1256 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1257 wfProfileOut( $fname );
1261 $this->mDbkeyform
= $t;
1263 # Initial colon indicating main namespace
1264 if ( ':' == $t{0} ) {
1265 $r = substr( $t, 1 );
1266 $this->mNamespace
= NS_MAIN
;
1268 # Namespace or interwiki prefix
1271 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1273 $lowerNs = strtolower( $p );
1274 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1275 # Canonical namespace
1277 $this->mNamespace
= $ns;
1278 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1279 # Ordinary namespace
1281 $this->mNamespace
= $ns;
1282 } elseif( $this->getInterwikiLink( $p ) ) {
1284 # Can't make a local interwiki link to an interwiki link.
1285 # That's just crazy!
1286 wfProfileOut( $fname );
1292 $this->mInterwiki
= $p;
1294 # Redundant interwiki prefix to the local wiki
1295 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1297 # Can't have an empty self-link
1298 wfProfileOut( $fname );
1301 $this->mInterwiki
= '';
1303 # Do another namespace split...
1307 # If there's no recognized interwiki or namespace,
1308 # then let the colon expression be part of the title.
1315 # We already know that some pages won't be in the database!
1317 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1318 $this->mArticleID
= 0;
1320 $f = strstr( $r, '#' );
1321 if ( false !== $f ) {
1322 $this->mFragment
= substr( $f, 1 );
1323 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1324 # remove whitespace again: prevents "Foo_bar_#"
1325 # becoming "Foo_bar_"
1326 $r = preg_replace( '/_*$/', '', $r );
1329 # Reject illegal characters.
1331 if( preg_match( $rxTc, $r ) ) {
1332 wfProfileOut( $fname );
1337 * Pages with "/./" or "/../" appearing in the URLs will
1338 * often be unreachable due to the way web browsers deal
1339 * with 'relative' URLs. Forbid them explicitly.
1341 if ( strpos( $r, '.' ) !== false &&
1342 ( $r === '.' ||
$r === '..' ||
1343 strpos( $r, './' ) === 0 ||
1344 strpos( $r, '../' ) === 0 ||
1345 strpos( $r, '/./' ) !== false ||
1346 strpos( $r, '/../' ) !== false ) )
1348 wfProfileOut( $fname );
1352 # We shouldn't need to query the DB for the size.
1353 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1354 if ( strlen( $r ) > 255 ) {
1355 wfProfileOut( $fname );
1360 * Normally, all wiki links are forced to have
1361 * an initial capital letter so [[foo]] and [[Foo]]
1362 * point to the same place.
1364 * Don't force it for interwikis, since the other
1365 * site might be case-sensitive.
1367 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1368 $t = $wgContLang->ucfirst( $r );
1374 * Can't make a link to a namespace alone...
1375 * "empty" local links can only be self-links
1376 * with a fragment identifier.
1379 $this->mInterwiki
== '' &&
1380 $this->mNamespace
!= NS_MAIN
) {
1381 wfProfileOut( $fname );
1386 $this->mDbkeyform
= $t;
1387 $this->mUrlform
= wfUrlencode( $t );
1389 $this->mTextform
= str_replace( '_', ' ', $t );
1391 wfProfileOut( $fname );
1396 * Get a Title object associated with the talk page of this article
1397 * @return Title the object for the talk page
1400 function getTalkPage() {
1401 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1405 * Get a title object associated with the subject page of this
1408 * @return Title the object for the subject page
1411 function getSubjectPage() {
1412 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1416 * Get an array of Title objects linking to this Title
1417 * Also stores the IDs in the link cache.
1419 * @param string $options may be FOR UPDATE
1420 * @return array the Title objects linking here
1423 function getLinksTo( $options = '' ) {
1424 global $wgLinkCache;
1425 $id = $this->getArticleID();
1428 $db =& wfGetDB( DB_MASTER
);
1430 $db =& wfGetDB( DB_SLAVE
);
1433 $res = $db->select( array( 'page', 'pagelinks' ),
1434 array( 'page_namespace', 'page_title', 'page_id' ),
1437 'pl_namespace' => $this->getNamespace(),
1438 'pl_title' => $this->getDbKey() ),
1439 'Title::getLinksTo',
1443 if ( $db->numRows( $res ) ) {
1444 while ( $row = $db->fetchObject( $res ) ) {
1445 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1446 $wgLinkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1447 $retVal[] = $titleObj;
1451 $db->freeResult( $res );
1456 * Get an array of Title objects referring to non-existent articles linked from this page
1458 * @param string $options may be FOR UPDATE
1459 * @return array the Title objects
1462 function getBrokenLinksFrom( $options = '' ) {
1463 global $wgLinkCache;
1466 $db =& wfGetDB( DB_MASTER
);
1468 $db =& wfGetDB( DB_SLAVE
);
1471 $res = $db->safeQuery(
1472 "SELECT pl_namespace, pl_title
1475 ON pl_namespace=page_namespace
1476 AND pl_title=page_title
1478 AND page_namespace IS NULL
1480 $db->tableName( 'pagelinks' ),
1481 $db->tableName( 'page' ),
1482 $this->getArticleId(),
1486 if ( $db->numRows( $res ) ) {
1487 while ( $row = $db->fetchObject( $res ) ) {
1488 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1491 $db->freeResult( $res );
1497 * Get a list of URLs to purge from the Squid cache when this
1500 * @return array the URLs
1503 function getSquidURLs() {
1505 $this->getInternalURL(),
1506 $this->getInternalURL( 'action=history' )
1511 * Move this page without authentication
1512 * @param Title &$nt the new page Title
1515 function moveNoAuth( &$nt ) {
1516 return $this->moveTo( $nt, false );
1520 * Check whether a given move operation would be valid.
1521 * Returns true if ok, or a message key string for an error message
1522 * if invalid. (Scarrrrry ugly interface this.)
1523 * @param Title &$nt the new title
1524 * @param bool $auth indicates whether $wgUser's permissions
1526 * @return mixed true on success, message name on failure
1529 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1531 if( !$this or !$nt ) {
1532 return 'badtitletext';
1534 if( $this->equals( $nt ) ) {
1537 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1538 return 'immobile_namespace';
1541 $fname = 'Title::move';
1542 $oldid = $this->getArticleID();
1543 $newid = $nt->getArticleID();
1545 if ( strlen( $nt->getDBkey() ) < 1 ) {
1546 return 'articleexists';
1548 if ( ( '' == $this->getDBkey() ) ||
1550 ( '' == $nt->getDBkey() ) ) {
1551 return 'badarticleerror';
1555 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1556 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1557 return 'protectedpage';
1560 # The move is allowed only if (1) the target doesn't exist, or
1561 # (2) the target is a redirect to the source, and has no history
1562 # (so we can undo bad moves right after they're done).
1564 if ( 0 != $newid ) { # Target exists; check for validity
1565 if ( ! $this->isValidMoveTarget( $nt ) ) {
1566 return 'articleexists';
1573 * Move a title to a new location
1574 * @param Title &$nt the new title
1575 * @param bool $auth indicates whether $wgUser's permissions
1577 * @return mixed true on success, message name on failure
1580 function moveTo( &$nt, $auth = true, $reason = '' ) {
1581 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1582 if( is_string( $err ) ) {
1586 $pageid = $this->getArticleID();
1587 if( $nt->exists() ) {
1588 $this->moveOverExistingRedirect( $nt, $reason );
1589 $pageCountChange = 0;
1590 } else { # Target didn't exist, do normal move.
1591 $this->moveToNewTitle( $nt, $newid, $reason );
1592 $pageCountChange = 1;
1594 $redirid = $this->getArticleID();
1596 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1597 $dbw =& wfGetDB( DB_MASTER
);
1598 $categorylinks = $dbw->tableName( 'categorylinks' );
1599 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1600 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1601 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1602 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1606 $oldnamespace = $this->getNamespace() & ~
1;
1607 $newnamespace = $nt->getNamespace() & ~
1;
1608 $oldtitle = $this->getDBkey();
1609 $newtitle = $nt->getDBkey();
1611 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1612 WatchedItem
::duplicateEntries( $this, $nt );
1615 # Update search engine
1616 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1618 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1622 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1623 # Moved out of main namespace
1624 # not viewed, edited, removing
1625 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1626 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1627 # Moved into main namespace
1628 # not viewed, edited, adding
1629 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1630 } elseif ( $pageCountChange ) {
1632 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1640 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1645 * Move page to a title which is at present a redirect to the
1648 * @param Title &$nt the page to move to, which should currently
1652 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1653 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1654 $fname = 'Title::moveOverExistingRedirect';
1655 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1658 $comment .= ": $reason";
1661 $now = wfTimestampNow();
1663 $newid = $nt->getArticleID();
1664 $oldid = $this->getArticleID();
1665 $dbw =& wfGetDB( DB_MASTER
);
1666 $links = $dbw->tableName( 'links' );
1668 # Delete the old redirect. We don't save it to history since
1669 # by definition if we've got here it's rather uninteresting.
1670 # We have to remove it so that the next step doesn't trigger
1671 # a conflict on the unique namespace+title index...
1672 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1674 # Save a null revision in the page's history notifying of the move
1675 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1676 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1678 $nullRevId = $nullRevision->insertOn( $dbw );
1680 # Change the name of the target page:
1681 $dbw->update( 'page',
1683 'page_touched' => $dbw->timestamp($now),
1684 'page_namespace' => $nt->getNamespace(),
1685 'page_title' => $nt->getDBkey(),
1686 'page_latest' => $nullRevId,
1688 /* WHERE */ array( 'page_id' => $oldid ),
1691 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1693 # Recreate the redirect, this time in the other direction.
1694 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1695 $redirectArticle = new Article( $this );
1696 $newid = $redirectArticle->insertOn( $dbw );
1697 $redirectRevision = new Revision( array(
1699 'comment' => $comment,
1700 'text' => $redirectText ) );
1701 $revid = $redirectRevision->insertOn( $dbw );
1702 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1703 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1706 $log = new LogPage( 'move' );
1707 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1709 # Now, we record the link from the redirect to the new title.
1710 # It should have no other outgoing links...
1711 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1712 $dbw->insert( 'pagelinks',
1714 'pl_from' => $newid,
1715 'pl_namespace' => $nt->getNamespace(),
1716 'pl_title' => $nt->getDbKey() ),
1720 if ( $wgUseSquid ) {
1721 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1722 $u = new SquidUpdate( $urls );
1728 * Move page to non-existing title.
1729 * @param Title &$nt the new Title
1730 * @param int &$newid set to be the new article ID
1733 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1734 global $wgUser, $wgLinkCache, $wgUseSquid;
1736 $fname = 'MovePageForm::moveToNewTitle';
1737 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1739 $comment .= ": $reason";
1742 $newid = $nt->getArticleID();
1743 $oldid = $this->getArticleID();
1744 $dbw =& wfGetDB( DB_MASTER
);
1745 $now = $dbw->timestamp();
1749 # Save a null revision in the page's history notifying of the move
1750 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1751 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1753 $nullRevId = $nullRevision->insertOn( $dbw );
1756 $dbw->update( 'page',
1758 'page_touched' => $now,
1759 'page_namespace' => $nt->getNamespace(),
1760 'page_title' => $nt->getDBkey(),
1761 'page_latest' => $nullRevId,
1763 /* WHERE */ array( 'page_id' => $oldid ),
1767 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1770 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1771 $redirectArticle = new Article( $this );
1772 $newid = $redirectArticle->insertOn( $dbw );
1773 $redirectRevision = new Revision( array(
1775 'comment' => $comment,
1776 'text' => $redirectText ) );
1777 $revid = $redirectRevision->insertOn( $dbw );
1778 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1779 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1782 $log = new LogPage( 'move' );
1783 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1785 # Purge caches as per article creation
1786 Article
::onArticleCreate( $nt );
1788 # Record the just-created redirect's linking to the page
1789 $dbw->insert( 'pagelinks',
1791 'pl_from' => $newid,
1792 'pl_namespace' => $nt->getNamespace(),
1793 'pl_title' => $nt->getDBkey() ),
1796 # Non-existent target may have had broken links to it; these must
1797 # now be touched to update link coloring.
1800 # Purge old title from squid
1801 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1802 $titles = $nt->getLinksTo();
1803 if ( $wgUseSquid ) {
1804 $urls = $this->getSquidURLs();
1805 foreach ( $titles as $linkTitle ) {
1806 $urls[] = $linkTitle->getInternalURL();
1808 $u = new SquidUpdate( $urls );
1814 * Checks if $this can be moved to a given Title
1815 * - Selects for update, so don't call it unless you mean business
1817 * @param Title &$nt the new title to check
1820 function isValidMoveTarget( $nt ) {
1822 $fname = 'Title::isValidMoveTarget';
1823 $dbw =& wfGetDB( DB_MASTER
);
1826 $id = $nt->getArticleID();
1827 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1828 array( 'page_is_redirect','old_text' ),
1829 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1830 $fname, 'FOR UPDATE' );
1832 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1837 # Does the redirect point to the source?
1838 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text
, $m ) ) {
1839 $redirTitle = Title
::newFromText( $m[1] );
1840 if( !is_object( $redirTitle ) ||
1841 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1846 # Does the article have a history?
1847 $row = $dbw->selectRow( array( 'page', 'revision'),
1849 array( 'page_namespace' => $nt->getNamespace(),
1850 'page_title' => $nt->getDBkey(),
1851 'page_id=rev_page AND page_latest != rev_id'
1852 ), $fname, 'FOR UPDATE'
1855 # Return true if there was no history
1856 return $row === false;
1860 * Create a redirect; fails if the title already exists; does
1863 * @param Title $dest the destination of the redirect
1864 * @param string $comment the comment string describing the move
1865 * @return bool true on success
1868 function createRedirect( $dest, $comment ) {
1870 if ( $this->getArticleID() ) {
1874 $fname = 'Title::createRedirect';
1875 $dbw =& wfGetDB( DB_MASTER
);
1877 $article = new Article( $this );
1878 $newid = $article->insertOn( $dbw );
1879 $revision = new Revision( array(
1881 'comment' => $comment,
1882 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1884 $revisionId = $revision->insertOn( $dbw );
1885 $article->updateRevisionOn( $dbw, $revision, 0 );
1888 $dbw->insert( 'pagelinks',
1890 'pl_from' => $newid,
1891 'pl_namespace' => $dest->getNamespace(),
1892 'pl_title' => $dest->getDbKey()
1896 Article
::onArticleCreate( $this );
1901 * Get categories to which this Title belongs and return an array of
1902 * categories' names.
1904 * @return array an array of parents in the form:
1905 * $parent => $currentarticle
1908 function getParentCategories() {
1909 global $wgContLang,$wgUser;
1911 $titlekey = $this->getArticleId();
1912 $sk =& $wgUser->getSkin();
1914 $dbr =& wfGetDB( DB_SLAVE
);
1915 $categorylinks = $dbr->tableName( 'categorylinks' );
1918 $sql = "SELECT * FROM $categorylinks"
1919 ." WHERE cl_from='$titlekey'"
1920 ." AND cl_from <> '0'"
1921 ." ORDER BY cl_sortkey";
1923 $res = $dbr->query ( $sql ) ;
1925 if($dbr->numRows($res) > 0) {
1926 while ( $x = $dbr->fetchObject ( $res ) )
1927 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1928 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1929 $dbr->freeResult ( $res ) ;
1937 * Get a tree of parent categories
1938 * @param array $children an array with the children in the keys, to check for circular refs
1942 function getParentCategoryTree( $children = array() ) {
1943 $parents = $this->getParentCategories();
1945 if($parents != '') {
1946 foreach($parents as $parent => $current)
1948 if ( array_key_exists( $parent, $children ) ) {
1949 # Circular reference
1950 $stack[$parent] = array();
1952 $nt = Title
::newFromText($parent);
1953 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
1964 * Get an associative array for selecting this title from
1970 function curCond() {
1971 wfDebugDieBacktrace( 'curCond called' );
1972 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1976 * Get an associative array for selecting this title from the
1982 function oldCond() {
1983 wfDebugDieBacktrace( 'oldCond called' );
1984 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);
1988 * Get the revision ID of the previous revision
1990 * @param integer $revision Revision ID. Get the revision that was before this one.
1991 * @return interger $oldrevision|false
1993 function getPreviousRevisionID( $revision ) {
1994 $dbr =& wfGetDB( DB_SLAVE
);
1995 return $dbr->selectField( 'revision', 'rev_id',
1996 'rev_page=' . IntVal( $this->getArticleId() ) .
1997 ' AND rev_id<' . IntVal( $revision ) . ' ORDER BY rev_id DESC' );
2001 * Get the revision ID of the next revision
2003 * @param integer $revision Revision ID. Get the revision that was after this one.
2004 * @return interger $oldrevision|false
2006 function getNextRevisionID( $revision ) {
2007 $dbr =& wfGetDB( DB_SLAVE
);
2008 return $dbr->selectField( 'revision', 'rev_id',
2009 'rev_page=' . IntVal( $this->getArticleId() ) .
2010 ' AND rev_id>' . IntVal( $revision ) . ' ORDER BY rev_id' );
2014 * Compare with another title.
2016 * @param Title $title
2019 function equals( &$title ) {
2020 return $this->getInterwiki() == $title->getInterwiki()
2021 && $this->getNamespace() == $title->getNamespace()
2022 && $this->getDbkey() == $title->getDbkey();
2026 * Check if page exists
2030 return $this->getArticleId() != 0;
2034 * Should a link should be displayed as a known link, just based on its title?
2036 * Currently, a self-link with a fragment, special pages and image pages are in
2037 * this category. Special pages never exist in the database. Some images do not
2038 * have description pages in the database, but the description page contains
2039 * useful history information that the user may want to link to.
2041 function isAlwaysKnown() {
2042 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2043 || NS_SPECIAL
== $this->mNamespace || NS_IMAGE
== $this->mNamespace
;
2047 * Update page_touched timestamps on pages linking to this title.
2048 * In principal, this could be backgrounded and could also do squid
2051 function touchLinks() {
2052 $fname = 'Title::touchLinks';
2054 $dbw =& wfGetDB( DB_MASTER
);
2056 $res = $dbw->select( 'pagelinks',
2059 'pl_namespace' => $this->getNamespace(),
2060 'pl_title' => $this->getDbKey() ),
2062 if ( 0 == $dbw->numRows( $res ) ) {
2067 $toucharr = array();
2068 while( $row = $dbw->fetchObject( $res ) ) {
2069 $toucharr[] = $row->pl_from
;
2072 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2073 /* WHERE */ array( 'page_id' => $toucharr ),$fname);