8 require_once( 'normal/UtfNormal.php' );
10 $wgTitleInterwikiCache = array();
11 define ( 'GAID_FOR_UPDATE', 1 );
13 # Title::newFromTitle maintains a cache to avoid
14 # expensive re-normalization of commonly used titles.
15 # On a batch operation this can become a memory leak
16 # if not bounded. After hitting this many titles,
18 define( 'MW_TITLECACHE_MAX', 1000 );
22 * - Represents a title, which may contain an interwiki designation or namespace
23 * - Can fetch various kinds of data from the database, albeit inefficiently.
29 * All member variables should be considered private
30 * Please use the accessor functions
37 var $mTextform; # Text form (spaces not underscores) of the main part
38 var $mUrlform; # URL-encoded form of the main part
39 var $mDbkeyform; # Main part with underscores
40 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
41 var $mInterwiki; # Interwiki prefix (or null string)
42 var $mFragment; # Title fragment (i.e. the bit after the #)
43 var $mArticleID; # Article ID, fetched from the link cache on demand
44 var $mLatestID; # ID of most recent revision
45 var $mRestrictions; # Array of groups allowed to edit this article
46 # Only null or "sysop" are supported
47 var $mRestrictionsLoaded; # Boolean for initialisation on demand
48 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
49 var $mDefaultNamespace; # Namespace index when there is no namespace
50 # Zero except in {{transclusion}} tags
51 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
59 /* private */ function Title() {
60 $this->mInterwiki
= $this->mUrlform
=
61 $this->mTextform
= $this->mDbkeyform
= '';
62 $this->mArticleID
= -1;
63 $this->mNamespace
= NS_MAIN
;
64 $this->mRestrictionsLoaded
= false;
65 $this->mRestrictions
= array();
66 # Dont change the following, NS_MAIN is hardcoded in several place
68 $this->mDefaultNamespace
= NS_MAIN
;
69 $this->mWatched
= NULL;
70 $this->mLatestID
= false;
74 * Create a new Title from a prefixed DB key
75 * @param string $key The database key, which has underscores
76 * instead of spaces, possibly including namespace and
78 * @return Title the new object, or NULL on an error
82 /* static */ function newFromDBkey( $key ) {
84 $t->mDbkeyform
= $key;
85 if( $t->secureAndSplit() )
92 * Create a new Title from text, such as what one would
93 * find in a link. Decodes any HTML entities in the text.
95 * @param string $text the link text; spaces, prefixes,
96 * and an initial ':' indicating the main namespace
98 * @param int $defaultNamespace the namespace to use if
99 * none is specified by a prefix
100 * @return Title the new object, or NULL on an error
104 function &newFromText( $text, $defaultNamespace = NS_MAIN
) {
105 $fname = 'Title::newFromText';
106 wfProfileIn( $fname );
108 if( is_object( $text ) ) {
109 wfDebugDieBacktrace( 'Title::newFromText given an object' );
113 * Wiki pages often contain multiple links to the same page.
114 * Title normalization and parsing can become expensive on
115 * pages with many links, so we can save a little time by
118 * In theory these are value objects and won't get changed...
120 static $titleCache = array();
121 if( $defaultNamespace == NS_MAIN
&& isset( $titleCache[$text] ) ) {
122 wfProfileOut( $fname );
123 return $titleCache[$text];
127 * Convert things like é ā or 〗 into real text...
129 $filteredText = Sanitizer
::decodeCharReferences( $text );
132 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
133 $t->mDefaultNamespace
= $defaultNamespace;
135 if( $t->secureAndSplit() ) {
136 if( $defaultNamespace == NS_MAIN
) {
137 if( count( $titleCache ) >= MW_TITLECACHE_MAX
) {
138 # Avoid memory leaks on mass operations...
139 $titleCache = array();
141 $titleCache[$text] =& $t;
143 wfProfileOut( $fname );
146 wfProfileOut( $fname );
152 * Create a new Title from URL-encoded text. Ensures that
153 * the given title's length does not exceed the maximum.
154 * @param string $url the title, as might be taken from a URL
155 * @return Title the new object, or NULL on an error
159 function newFromURL( $url ) {
160 global $wgLang, $wgServer;
163 # For compatibility with old buggy URLs. "+" is not valid in titles,
164 # but some URLs used it as a space replacement and they still come
165 # from some external search tools.
166 $s = str_replace( '+', ' ', $url );
168 $t->mDbkeyform
= str_replace( ' ', '_', $s );
169 if( $t->secureAndSplit() ) {
177 * Create a new Title from an article ID
179 * @todo This is inefficiently implemented, the page row is requested
180 * but not used for anything else
182 * @param int $id the page_id corresponding to the Title to create
183 * @return Title the new object, or NULL on an error
187 function newFromID( $id ) {
188 $fname = 'Title::newFromID';
189 $dbr =& wfGetDB( DB_SLAVE
);
190 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
191 array( 'page_id' => $id ), $fname );
192 if ( $row !== false ) {
193 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
201 * Create a new Title from a namespace index and a DB key.
202 * It's assumed that $ns and $title are *valid*, for instance when
203 * they came directly from the database or a special page name.
204 * For convenience, spaces are converted to underscores so that
205 * eg user_text fields can be used directly.
207 * @param int $ns the namespace of the article
208 * @param string $title the unprefixed database key form
209 * @return Title the new object
213 function &makeTitle( $ns, $title ) {
217 $t->mNamespace
= IntVal( $ns );
218 $t->mDbkeyform
= str_replace( ' ', '_', $title );
219 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
220 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
221 $t->mTextform
= str_replace( '_', ' ', $title );
226 * Create a new Title frrom a namespace index and a DB key.
227 * The parameters will be checked for validity, which is a bit slower
228 * than makeTitle() but safer for user-provided data.
230 * @param int $ns the namespace of the article
231 * @param string $title the database key form
232 * @return Title the new object, or NULL on an error
236 function makeTitleSafe( $ns, $title ) {
238 $t->mDbkeyform
= Title
::makeName( $ns, $title );
239 if( $t->secureAndSplit() ) {
247 * Create a new Title for the Main Page
250 * @return Title the new object
253 function newMainPage() {
254 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
258 * Create a new Title for a redirect
259 * @param string $text the redirect title text
260 * @return Title the new object, or NULL if the text is not a
265 function newFromRedirect( $text ) {
268 if ( $wgMwRedir->matchStart( $text ) ) {
269 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
270 # categories are escaped using : for example one can enter:
271 # #REDIRECT [[:Category:Music]]. Need to remove it.
272 if ( substr($m[1],0,1) == ':') {
273 # We don't want to keep the ':'
274 $m[1] = substr( $m[1], 1 );
277 $rt = Title
::newFromText( $m[1] );
278 # Disallow redirects to Special:Userlogout
279 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
287 #----------------------------------------------------------------------------
289 #----------------------------------------------------------------------------
292 * Get the prefixed DB key associated with an ID
293 * @param int $id the page_id of the article
294 * @return Title an object representing the article, or NULL
295 * if no such article was found
299 function nameOf( $id ) {
300 $fname = 'Title::nameOf';
301 $dbr =& wfGetDB( DB_SLAVE
);
303 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
304 if ( $s === false ) { return NULL; }
306 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
311 * Get a regex character class describing the legal characters in a link
312 * @return string the list of characters, not delimited
316 /* static */ function legalChars() {
317 # Missing characters:
318 # * []|# Needed for link syntax
319 # * % and + are corrupted by Apache when they appear in the path
321 # % seems to work though
323 # The problem with % is that URLs are double-unescaped: once by Apache's
324 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
325 # Our code does not double-escape to compensate for this, indeed double escaping
326 # would break if the double-escaped title was passed in the query string
327 # rather than the path. This is a minor security issue because articles can be
328 # created such that they are hard to view or edit. -- TS
330 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
331 # this breaks interlanguage links
333 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF";
338 * Get a string representation of a title suitable for
339 * including in a search index
341 * @param int $ns a namespace index
342 * @param string $title text-form main part
343 * @return string a stripped-down title string ready for the
346 /* static */ function indexTitle( $ns, $title ) {
347 global $wgDBminWordLen, $wgContLang;
348 require_once( 'SearchEngine.php' );
350 $lc = SearchEngine
::legalSearchChars() . '&#;';
351 $t = $wgContLang->stripForSearch( $title );
352 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
353 $t = strtolower( $t );
356 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
357 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
359 $t = preg_replace( "/\\s+/", ' ', $t );
361 if ( $ns == NS_IMAGE
) {
362 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
368 * Make a prefixed DB key from a DB key and a namespace index
369 * @param int $ns numerical representation of the namespace
370 * @param string $title the DB key form the title
371 * @return string the prefixed form of the title
373 /* static */ function makeName( $ns, $title ) {
376 $n = $wgContLang->getNsText( $ns );
377 return $n == '' ?
$title : "$n:$title";
381 * Returns the URL associated with an interwiki prefix
382 * @param string $key the interwiki prefix (e.g. "MeatBall")
383 * @return the associated URL, containing "$1", which should be
384 * replaced by an article title
388 function getInterwikiLink( $key, $transludeonly = false ) {
389 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
390 $fname = 'Title::getInterwikiLink';
392 wfProfileIn( $fname );
394 $k = $wgDBname.':interwiki:'.$key;
395 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
396 wfProfileOut( $fname );
397 return $wgTitleInterwikiCache[$k]->iw_url
;
400 $s = $wgMemc->get( $k );
401 # Ignore old keys with no iw_local
402 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
403 $wgTitleInterwikiCache[$k] = $s;
404 wfProfileOut( $fname );
408 $dbr =& wfGetDB( DB_SLAVE
);
409 $res = $dbr->select( 'interwiki',
410 array( 'iw_url', 'iw_local', 'iw_trans' ),
411 array( 'iw_prefix' => $key ), $fname );
413 wfProfileOut( $fname );
417 $s = $dbr->fetchObject( $res );
419 # Cache non-existence: create a blank object and save it to memcached
425 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
426 $wgTitleInterwikiCache[$k] = $s;
428 wfProfileOut( $fname );
433 * Determine whether the object refers to a page within
436 * @return bool TRUE if this is an in-project interwiki link
437 * or a wikilink, FALSE otherwise
441 global $wgTitleInterwikiCache, $wgDBname;
443 if ( $this->mInterwiki
!= '' ) {
444 # Make sure key is loaded into cache
445 $this->getInterwikiLink( $this->mInterwiki
);
446 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
447 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
454 * Determine whether the object refers to a page within
455 * this project and is transcludable.
457 * @return bool TRUE if this is transcludable
461 global $wgTitleInterwikiCache, $wgDBname;
463 if ($this->mInterwiki
== '' ||
!$this->isLocal())
465 # Make sure key is loaded into cache
466 $this->getInterwikiLink( $this->mInterwiki
);
467 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
468 return (bool)($wgTitleInterwikiCache[$k]->iw_trans
);
472 * Update the page_touched field for an array of title objects
473 * @todo Inefficient unless the IDs are already loaded into the
475 * @param array $titles an array of Title objects to be touched
476 * @param string $timestamp the timestamp to use instead of the
477 * default current time
481 function touchArray( $titles, $timestamp = '' ) {
482 if ( count( $titles ) == 0 ) {
485 $dbw =& wfGetDB( DB_MASTER
);
486 if ( $timestamp == '' ) {
487 $timestamp = $dbw->timestamp();
489 $page = $dbw->tableName( 'page' );
490 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
493 foreach ( $titles as $title ) {
498 $sql .= $title->getArticleID();
502 $dbw->query( $sql, 'Title::touchArray' );
506 #----------------------------------------------------------------------------
508 #----------------------------------------------------------------------------
510 /** Simple accessors */
512 * Get the text form (spaces not underscores) of the main part
516 function getText() { return $this->mTextform
; }
518 * Get the URL-encoded form of the main part
522 function getPartialURL() { return $this->mUrlform
; }
524 * Get the main part with underscores
528 function getDBkey() { return $this->mDbkeyform
; }
530 * Get the namespace index, i.e. one of the NS_xxxx constants
534 function getNamespace() { return $this->mNamespace
; }
536 * Get the interwiki prefix (or null string)
540 function getInterwiki() { return $this->mInterwiki
; }
542 * Get the Title fragment (i.e. the bit after the #)
546 function getFragment() { return $this->mFragment
; }
548 * Get the default namespace index, for when there is no namespace
552 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
555 * Get title for search index
556 * @return string a stripped-down title string ready for the
559 function getIndexTitle() {
560 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
564 * Get the prefixed database key form
565 * @return string the prefixed title, with underscores and
566 * any interwiki and namespace prefixes
569 function getPrefixedDBkey() {
570 $s = $this->prefix( $this->mDbkeyform
);
571 $s = str_replace( ' ', '_', $s );
576 * Get the prefixed title with spaces.
577 * This is the form usually used for display
578 * @return string the prefixed title, with spaces
581 function getPrefixedText() {
583 if ( empty( $this->mPrefixedText
) ) {
584 $s = $this->prefix( $this->mTextform
);
585 $s = str_replace( '_', ' ', $s );
586 $this->mPrefixedText
= $s;
588 return $this->mPrefixedText
;
592 * Get the prefixed title with spaces, plus any fragment
593 * (part beginning with '#')
594 * @return string the prefixed title, with spaces and
595 * the fragment, including '#'
598 function getFullText() {
600 $text = $this->getPrefixedText();
601 if( '' != $this->mFragment
) {
602 $text .= '#' . $this->mFragment
;
608 * Get a URL-encoded title (not an actual URL) including interwiki
609 * @return string the URL-encoded form
612 function getPrefixedURL() {
613 $s = $this->prefix( $this->mDbkeyform
);
614 $s = str_replace( ' ', '_', $s );
616 $s = wfUrlencode ( $s ) ;
618 # Cleaning up URL to make it look nice -- is this safe?
619 $s = str_replace( '%28', '(', $s );
620 $s = str_replace( '%29', ')', $s );
626 * Get a real URL referring to this title, with interwiki link and
629 * @param string $query an optional query string, not used
630 * for interwiki links
631 * @return string the URL
634 function getFullURL( $query = '' ) {
635 global $wgContLang, $wgServer, $wgScript, $wgMakeDumpLinks, $wgArticlePath;
637 if ( '' == $this->mInterwiki
) {
638 return $wgServer . $this->getLocalUrl( $query );
639 } elseif ( $wgMakeDumpLinks && $wgContLang->getLanguageName( $this->mInterwiki
) ) {
640 $baseUrl = str_replace( '$1', "../../{$this->mInterwiki}/$1", $wgArticlePath );
641 $baseUrl = str_replace( '$1', $this->getHashedDirectory() . '/$1', $baseUrl );
643 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
646 $namespace = $wgContLang->getNsText( $this->mNamespace
);
647 if ( '' != $namespace ) {
648 # Can this actually happen? Interwikis shouldn't be parsed.
651 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
653 if( false === strpos( $url, '?' ) ) {
660 if ( '' != $this->mFragment
) {
661 $url .= '#' . $this->mFragment
;
667 * Get a relative directory for putting an HTML version of this article into
669 function getHashedDirectory() {
670 global $wgMakeDumpLinks, $wgInputEncoding;
671 $dbkey = $this->getDBkey();
673 # Split into characters
674 if ( $wgInputEncoding == 'UTF-8' ) {
675 preg_match_all( '/./us', $dbkey, $m );
677 preg_match_all( '/./s', $dbkey, $m );
680 $length = count( $chars );
683 for ( $i = 0; $i < $wgMakeDumpLinks; $i++
) {
687 if ( $i >= $length ) {
689 } elseif ( ord( $chars[$i] ) > 32 ) {
690 $dir .= strtolower( $chars[$i] );
692 $dir .= sprintf( "%02X", ord( $chars[$i] ) );
698 function getHashedFilename() {
699 $dbkey = $this->getPrefixedDBkey();
700 $mainPage = Title
::newMainPage();
701 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
705 $dir = $this->getHashedDirectory();
707 # Replace illegal charcters for Windows paths with underscores
708 $friendlyName = strtr( $dbkey, '/\\*?"<>|~', '_________' );
710 # Work out lower case form. We assume we're on a system with case-insensitive
711 # filenames, so unless the case is of a special form, we have to disambiguate
712 $lowerCase = $this->prefix( ucfirst( strtolower( $this->getDBkey() ) ) );
714 # Make it mostly unique
715 if ( $lowerCase != $friendlyName ) {
716 $friendlyName .= '_' . substr(md5( $dbkey ), 0, 4);
718 # Handle colon specially by replacing it with tilde
719 # Thus we reduce the number of paths with hashes appended
720 $friendlyName = str_replace( ':', '~', $friendlyName );
721 return "$dir/$friendlyName.html";
725 * Get a URL with no fragment or server name
726 * @param string $query an optional query string; if not specified,
727 * $wgArticlePath will be used.
728 * @return string the URL
731 function getLocalURL( $query = '' ) {
732 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks, $wgServer, $action;
734 if ( $this->isExternal() ) {
735 return $this->getFullURL();
738 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
739 if ( $wgMakeDumpLinks ) {
740 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
741 } elseif ( $query == '' ) {
742 $url = str_replace( '$1', $dbkey, $wgArticlePath );
744 global $wgActionPaths;
745 if( !empty( $wgActionPaths ) &&
746 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
747 $action = urldecode( $matches[2] );
748 if( isset( $wgActionPaths[$action] ) ) {
749 $query = $matches[1];
750 if( isset( $matches[4] ) ) $query .= $matches[4];
751 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
752 if( $query != '' ) $url .= '?' . $query;
756 if ( $query == '-' ) {
759 $url = "{$wgScript}?title={$dbkey}&{$query}";
762 if ($action == 'render')
763 return $wgServer . $url;
769 * Get an HTML-escaped version of the URL form, suitable for
770 * using in a link, without a server name or fragment
771 * @param string $query an optional query string
772 * @return string the URL
775 function escapeLocalURL( $query = '' ) {
776 return htmlspecialchars( $this->getLocalURL( $query ) );
780 * Get an HTML-escaped version of the URL form, suitable for
781 * using in a link, including the server name and fragment
783 * @return string the URL
784 * @param string $query an optional query string
787 function escapeFullURL( $query = '' ) {
788 return htmlspecialchars( $this->getFullURL( $query ) );
792 * Get the URL form for an internal link.
793 * - Used in various Squid-related code, in case we have a different
794 * internal hostname for the server from the exposed one.
796 * @param string $query an optional query string
797 * @return string the URL
800 function getInternalURL( $query = '' ) {
801 global $wgInternalServer;
802 return $wgInternalServer . $this->getLocalURL( $query );
806 * Get the edit URL for this Title
807 * @return string the URL, or a null string if this is an
811 function getEditURL() {
812 global $wgServer, $wgScript;
814 if ( '' != $this->mInterwiki
) { return ''; }
815 $s = $this->getLocalURL( 'action=edit' );
821 * Get the HTML-escaped displayable text form.
822 * Used for the title field in <a> tags.
823 * @return string the text, including any prefixes
826 function getEscapedText() {
827 return htmlspecialchars( $this->getPrefixedText() );
831 * Is this Title interwiki?
835 function isExternal() { return ( '' != $this->mInterwiki
); }
838 * Does the title correspond to a protected article?
839 * @param string $what the action the page is protected from,
840 * by default checks move and edit
844 function isProtected($action = '') {
845 if ( -1 == $this->mNamespace
) { return true; }
846 if($action == 'edit' ||
$action == '') {
847 $a = $this->getRestrictions("edit");
848 if ( in_array( 'sysop', $a ) ) { return true; }
850 if($action == 'move' ||
$action == '') {
851 $a = $this->getRestrictions("move");
852 if ( in_array( 'sysop', $a ) ) { return true; }
858 * Is $wgUser is watching this page?
862 function userIsWatching() {
865 if ( is_null( $this->mWatched
) ) {
866 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
867 $this->mWatched
= false;
869 $this->mWatched
= $wgUser->isWatched( $this );
872 return $this->mWatched
;
876 * Is $wgUser perform $action this page?
877 * @param string $action action that permission needs to be checked for
881 function userCan($action) {
882 $fname = 'Title::userCanEdit';
883 wfProfileIn( $fname );
886 if( NS_SPECIAL
== $this->mNamespace
) {
887 wfProfileOut( $fname );
890 if( NS_MEDIAWIKI
== $this->mNamespace
&&
891 !$wgUser->isAllowed('editinterface') ) {
892 wfProfileOut( $fname );
895 if( $this->mDbkeyform
== '_' ) {
896 # FIXME: Is this necessary? Shouldn't be allowed anyway...
897 wfProfileOut( $fname );
901 # protect global styles and js
902 if ( NS_MEDIAWIKI
== $this->mNamespace
903 && preg_match("/\\.(css|js)$/", $this->mTextform
)
904 && !$wgUser->isAllowed('editinterface') ) {
905 wfProfileOut( $fname );
909 # protect css/js subpages of user pages
910 # XXX: this might be better using restrictions
911 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
912 if( NS_USER
== $this->mNamespace
913 && preg_match("/\\.(css|js)$/", $this->mTextform
)
914 && !$wgUser->isAllowed('editinterface')
915 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
916 wfProfileOut( $fname );
920 foreach( $this->getRestrictions($action) as $right ) {
921 // Backwards compatibility, rewrite sysop -> protect
922 if ( $right == 'sysop' ) {
925 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
926 wfProfileOut( $fname );
931 if( $action == 'move' && !$this->isMovable() ) {
932 wfProfileOut( $fname );
936 wfProfileOut( $fname );
941 * Can $wgUser edit this page?
945 function userCanEdit() {
946 return $this->userCan('edit');
950 * Can $wgUser move this page?
954 function userCanMove() {
955 return $this->userCan('move');
959 * Would anybody with sufficient privileges be able to move this page?
960 * Some pages just aren't movable.
965 function isMovable() {
966 return Namespace::isMovable( $this->getNamespace() )
967 && $this->getInterwiki() == '';
971 * Can $wgUser read this page?
975 function userCanRead() {
978 if( $wgUser->isAllowed('read') ) {
981 global $wgWhitelistRead;
983 /** If anon users can create an account,
984 they need to reach the login page first! */
985 if( $wgUser->isAllowed( 'createaccount' )
986 && $this->getNamespace() == NS_SPECIAL
987 && $this->getText() == 'Userlogin' ) {
991 /** some pages are explicitly allowed */
992 $name = $this->getPrefixedText();
993 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
997 # Compatibility with old settings
998 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
999 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1008 * Is this a talk page of some sort?
1012 function isTalkPage() {
1013 return Namespace::isTalk( $this->getNamespace() );
1017 * Is this a .css or .js subpage of a user page?
1021 function isCssJsSubpage() {
1022 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1025 * Is this a .css subpage of a user page?
1029 function isCssSubpage() {
1030 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1033 * Is this a .js subpage of a user page?
1037 function isJsSubpage() {
1038 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1041 * Protect css/js subpages of user pages: can $wgUser edit
1045 * @todo XXX: this might be better using restrictions
1048 function userCanEditCssJsSubpage() {
1050 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1054 * Loads a string into mRestrictions array
1055 * @param string $res restrictions in string format
1058 function loadRestrictions( $res ) {
1059 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1060 $temp = explode( '=', trim( $restrict ) );
1061 if(count($temp) == 1) {
1062 // old format should be treated as edit/move restriction
1063 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1064 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1066 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1069 $this->mRestrictionsLoaded
= true;
1073 * Accessor/initialisation for mRestrictions
1074 * @param string $action action that permission needs to be checked for
1075 * @return array the array of groups allowed to edit this article
1078 function getRestrictions($action) {
1079 $id = $this->getArticleID();
1080 if ( 0 == $id ) { return array(); }
1082 if ( ! $this->mRestrictionsLoaded
) {
1083 $dbr =& wfGetDB( DB_SLAVE
);
1084 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1085 $this->loadRestrictions( $res );
1087 if( isset( $this->mRestrictions
[$action] ) ) {
1088 return $this->mRestrictions
[$action];
1094 * Is there a version of this page in the deletion archive?
1095 * @return int the number of archived revisions
1098 function isDeleted() {
1099 $fname = 'Title::isDeleted';
1100 if ( $this->getNamespace() < 0 ) {
1103 $dbr =& wfGetDB( DB_SLAVE
);
1104 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1105 'ar_title' => $this->getDBkey() ), $fname );
1111 * Get the article ID for this Title from the link cache,
1112 * adding it if necessary
1113 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1115 * @return int the ID
1118 function getArticleID( $flags = 0 ) {
1119 global $wgLinkCache;
1121 if ( $flags & GAID_FOR_UPDATE
) {
1122 $oldUpdate = $wgLinkCache->forUpdate( true );
1123 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1124 $wgLinkCache->forUpdate( $oldUpdate );
1126 if ( -1 == $this->mArticleID
) {
1127 $this->mArticleID
= $wgLinkCache->addLinkObj( $this );
1130 return $this->mArticleID
;
1133 function getLatestRevID() {
1134 if ($this->mLatestID
!== false)
1135 return $this->mLatestID
;
1137 $db =& wfGetDB(DB_SLAVE
);
1138 return $this->mLatestID
= $db->selectField( 'revision',
1140 array('rev_page' => $this->getArticleID()),
1141 'Title::getLatestRevID' );
1145 * This clears some fields in this object, and clears any associated
1146 * keys in the "bad links" section of $wgLinkCache.
1148 * - This is called from Article::insertNewArticle() to allow
1149 * loading of the new page_id. It's also called from
1150 * Article::doDeleteArticle()
1152 * @param int $newid the new Article ID
1155 function resetArticleID( $newid ) {
1156 global $wgLinkCache;
1157 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1159 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1160 else { $this->mArticleID
= $newid; }
1161 $this->mRestrictionsLoaded
= false;
1162 $this->mRestrictions
= array();
1166 * Updates page_touched for this page; called from LinksUpdate.php
1167 * @return bool true if the update succeded
1170 function invalidateCache() {
1171 if ( wfReadOnly() ) {
1175 $now = wfTimestampNow();
1176 $dbw =& wfGetDB( DB_MASTER
);
1177 $success = $dbw->update( 'page',
1179 'page_touched' => $dbw->timestamp()
1180 ), array( /* WHERE */
1181 'page_namespace' => $this->getNamespace() ,
1182 'page_title' => $this->getDBkey()
1183 ), 'Title::invalidateCache'
1189 * Prefix some arbitrary text with the namespace or interwiki prefix
1192 * @param string $name the text
1193 * @return string the prefixed text
1196 /* private */ function prefix( $name ) {
1200 if ( '' != $this->mInterwiki
) {
1201 $p = $this->mInterwiki
. ':';
1203 if ( 0 != $this->mNamespace
) {
1204 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1210 * Secure and split - main initialisation function for this object
1212 * Assumes that mDbkeyform has been set, and is urldecoded
1213 * and uses underscores, but not otherwise munged. This function
1214 * removes illegal characters, splits off the interwiki and
1215 * namespace prefixes, sets the other forms, and canonicalizes
1217 * @return bool true on success
1220 /* private */ function secureAndSplit() {
1221 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1222 $fname = 'Title::secureAndSplit';
1223 wfProfileIn( $fname );
1226 static $rxTc = false;
1228 # % is needed as well
1229 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1232 $this->mInterwiki
= $this->mFragment
= '';
1233 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1235 # Clean up whitespace
1237 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1238 $t = trim( $t, '_' );
1241 wfProfileOut( $fname );
1245 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1246 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1247 wfProfileOut( $fname );
1251 $this->mDbkeyform
= $t;
1253 # Initial colon indicating main namespace
1254 if ( ':' == $t{0} ) {
1255 $r = substr( $t, 1 );
1256 $this->mNamespace
= NS_MAIN
;
1258 # Namespace or interwiki prefix
1261 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1263 $lowerNs = strtolower( $p );
1264 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1265 # Canonical namespace
1267 $this->mNamespace
= $ns;
1268 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1269 # Ordinary namespace
1271 $this->mNamespace
= $ns;
1272 } elseif( $this->getInterwikiLink( $p ) ) {
1274 # Can't make a local interwiki link to an interwiki link.
1275 # That's just crazy!
1276 wfProfileOut( $fname );
1282 $this->mInterwiki
= $p;
1284 # Redundant interwiki prefix to the local wiki
1285 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1287 # Can't have an empty self-link
1288 wfProfileOut( $fname );
1291 $this->mInterwiki
= '';
1293 # Do another namespace split...
1297 # If there's no recognized interwiki or namespace,
1298 # then let the colon expression be part of the title.
1305 # We already know that some pages won't be in the database!
1307 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1308 $this->mArticleID
= 0;
1310 $f = strstr( $r, '#' );
1311 if ( false !== $f ) {
1312 $this->mFragment
= substr( $f, 1 );
1313 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1314 # remove whitespace again: prevents "Foo_bar_#"
1315 # becoming "Foo_bar_"
1316 $r = preg_replace( '/_*$/', '', $r );
1319 # Reject illegal characters.
1321 if( preg_match( $rxTc, $r ) ) {
1322 wfProfileOut( $fname );
1327 * Pages with "/./" or "/../" appearing in the URLs will
1328 * often be unreachable due to the way web browsers deal
1329 * with 'relative' URLs. Forbid them explicitly.
1331 if ( strpos( $r, '.' ) !== false &&
1332 ( $r === '.' ||
$r === '..' ||
1333 strpos( $r, './' ) === 0 ||
1334 strpos( $r, '../' ) === 0 ||
1335 strpos( $r, '/./' ) !== false ||
1336 strpos( $r, '/../' ) !== false ) )
1338 wfProfileOut( $fname );
1342 # We shouldn't need to query the DB for the size.
1343 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1344 if ( strlen( $r ) > 255 ) {
1345 wfProfileOut( $fname );
1350 * Normally, all wiki links are forced to have
1351 * an initial capital letter so [[foo]] and [[Foo]]
1352 * point to the same place.
1354 * Don't force it for interwikis, since the other
1355 * site might be case-sensitive.
1357 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1358 $t = $wgContLang->ucfirst( $r );
1364 * Can't make a link to a namespace alone...
1365 * "empty" local links can only be self-links
1366 * with a fragment identifier.
1369 $this->mInterwiki
== '' &&
1370 $this->mNamespace
!= NS_MAIN
) {
1371 wfProfileOut( $fname );
1376 $this->mDbkeyform
= $t;
1377 $this->mUrlform
= wfUrlencode( $t );
1379 $this->mTextform
= str_replace( '_', ' ', $t );
1381 wfProfileOut( $fname );
1386 * Get a Title object associated with the talk page of this article
1387 * @return Title the object for the talk page
1390 function getTalkPage() {
1391 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1395 * Get a title object associated with the subject page of this
1398 * @return Title the object for the subject page
1401 function getSubjectPage() {
1402 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1406 * Get an array of Title objects linking to this Title
1407 * Also stores the IDs in the link cache.
1409 * @param string $options may be FOR UPDATE
1410 * @return array the Title objects linking here
1413 function getLinksTo( $options = '' ) {
1414 global $wgLinkCache;
1415 $id = $this->getArticleID();
1418 $db =& wfGetDB( DB_MASTER
);
1420 $db =& wfGetDB( DB_SLAVE
);
1423 $res = $db->select( array( 'page', 'pagelinks' ),
1424 array( 'page_namespace', 'page_title', 'page_id' ),
1427 'pl_namespace' => $this->getNamespace(),
1428 'pl_title' => $this->getDbKey() ),
1429 'Title::getLinksTo',
1433 if ( $db->numRows( $res ) ) {
1434 while ( $row = $db->fetchObject( $res ) ) {
1435 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1436 $wgLinkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1437 $retVal[] = $titleObj;
1441 $db->freeResult( $res );
1446 * Get an array of Title objects referring to non-existent articles linked from this page
1448 * @param string $options may be FOR UPDATE
1449 * @return array the Title objects
1452 function getBrokenLinksFrom( $options = '' ) {
1453 global $wgLinkCache;
1456 $db =& wfGetDB( DB_MASTER
);
1458 $db =& wfGetDB( DB_SLAVE
);
1461 $res = $db->safeQuery(
1462 "SELECT pl_namespace, pl_title
1465 ON pl_namespace=page_namespace
1466 AND pl_title=page_title
1468 AND page_namespace IS NULL
1470 $db->tableName( 'pagelinks' ),
1471 $db->tableName( 'page' ),
1472 $this->getArticleId(),
1476 if ( $db->numRows( $res ) ) {
1477 while ( $row = $db->fetchObject( $res ) ) {
1478 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1481 $db->freeResult( $res );
1487 * Get a list of URLs to purge from the Squid cache when this
1490 * @return array the URLs
1493 function getSquidURLs() {
1495 $this->getInternalURL(),
1496 $this->getInternalURL( 'action=history' )
1501 * Move this page without authentication
1502 * @param Title &$nt the new page Title
1505 function moveNoAuth( &$nt ) {
1506 return $this->moveTo( $nt, false );
1510 * Check whether a given move operation would be valid.
1511 * Returns true if ok, or a message key string for an error message
1512 * if invalid. (Scarrrrry ugly interface this.)
1513 * @param Title &$nt the new title
1514 * @param bool $auth indicates whether $wgUser's permissions
1516 * @return mixed true on success, message name on failure
1519 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1521 if( !$this or !$nt ) {
1522 return 'badtitletext';
1524 if( $this->equals( $nt ) ) {
1527 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1528 return 'immobile_namespace';
1531 $fname = 'Title::move';
1532 $oldid = $this->getArticleID();
1533 $newid = $nt->getArticleID();
1535 if ( strlen( $nt->getDBkey() ) < 1 ) {
1536 return 'articleexists';
1538 if ( ( '' == $this->getDBkey() ) ||
1540 ( '' == $nt->getDBkey() ) ) {
1541 return 'badarticleerror';
1545 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1546 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1547 return 'protectedpage';
1550 # The move is allowed only if (1) the target doesn't exist, or
1551 # (2) the target is a redirect to the source, and has no history
1552 # (so we can undo bad moves right after they're done).
1554 if ( 0 != $newid ) { # Target exists; check for validity
1555 if ( ! $this->isValidMoveTarget( $nt ) ) {
1556 return 'articleexists';
1563 * Move a title to a new location
1564 * @param Title &$nt the new title
1565 * @param bool $auth indicates whether $wgUser's permissions
1567 * @return mixed true on success, message name on failure
1570 function moveTo( &$nt, $auth = true, $reason = '' ) {
1571 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1572 if( is_string( $err ) ) {
1576 $pageid = $this->getArticleID();
1577 if( $nt->exists() ) {
1578 $this->moveOverExistingRedirect( $nt, $reason );
1579 $pageCountChange = 0;
1580 } else { # Target didn't exist, do normal move.
1581 $this->moveToNewTitle( $nt, $newid, $reason );
1582 $pageCountChange = 1;
1584 $redirid = $this->getArticleID();
1586 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1587 $dbw =& wfGetDB( DB_MASTER
);
1588 $categorylinks = $dbw->tableName( 'categorylinks' );
1589 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1590 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1591 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1592 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1596 $oldnamespace = $this->getNamespace() & ~
1;
1597 $newnamespace = $nt->getNamespace() & ~
1;
1598 $oldtitle = $this->getDBkey();
1599 $newtitle = $nt->getDBkey();
1601 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1602 WatchedItem
::duplicateEntries( $this, $nt );
1605 # Update search engine
1606 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1608 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1612 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1613 # Moved out of main namespace
1614 # not viewed, edited, removing
1615 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1616 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1617 # Moved into main namespace
1618 # not viewed, edited, adding
1619 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1620 } elseif ( $pageCountChange ) {
1622 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1630 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1635 * Move page to a title which is at present a redirect to the
1638 * @param Title &$nt the page to move to, which should currently
1642 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1643 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1644 $fname = 'Title::moveOverExistingRedirect';
1645 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1648 $comment .= ": $reason";
1651 $now = wfTimestampNow();
1653 $newid = $nt->getArticleID();
1654 $oldid = $this->getArticleID();
1655 $dbw =& wfGetDB( DB_MASTER
);
1656 $links = $dbw->tableName( 'links' );
1658 # Delete the old redirect. We don't save it to history since
1659 # by definition if we've got here it's rather uninteresting.
1660 # We have to remove it so that the next step doesn't trigger
1661 # a conflict on the unique namespace+title index...
1662 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1664 # Save a null revision in the page's history notifying of the move
1665 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1666 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1668 $nullRevId = $nullRevision->insertOn( $dbw );
1670 # Change the name of the target page:
1671 $dbw->update( 'page',
1673 'page_touched' => $dbw->timestamp($now),
1674 'page_namespace' => $nt->getNamespace(),
1675 'page_title' => $nt->getDBkey(),
1676 'page_latest' => $nullRevId,
1678 /* WHERE */ array( 'page_id' => $oldid ),
1681 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1683 # Recreate the redirect, this time in the other direction.
1684 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1685 $redirectArticle = new Article( $this );
1686 $newid = $redirectArticle->insertOn( $dbw );
1687 $redirectRevision = new Revision( array(
1689 'comment' => $comment,
1690 'text' => $redirectText ) );
1691 $revid = $redirectRevision->insertOn( $dbw );
1692 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1693 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1696 $log = new LogPage( 'move' );
1697 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1699 # Now, we record the link from the redirect to the new title.
1700 # It should have no other outgoing links...
1701 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1702 $dbw->insert( 'pagelinks',
1704 'pl_from' => $newid,
1705 'pl_namespace' => $nt->getNamespace(),
1706 'pl_title' => $nt->getDbKey() ),
1710 if ( $wgUseSquid ) {
1711 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1712 $u = new SquidUpdate( $urls );
1718 * Move page to non-existing title.
1719 * @param Title &$nt the new Title
1720 * @param int &$newid set to be the new article ID
1723 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1724 global $wgUser, $wgLinkCache, $wgUseSquid;
1726 $fname = 'MovePageForm::moveToNewTitle';
1727 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1729 $comment .= ": $reason";
1732 $newid = $nt->getArticleID();
1733 $oldid = $this->getArticleID();
1734 $dbw =& wfGetDB( DB_MASTER
);
1735 $now = $dbw->timestamp();
1739 # Save a null revision in the page's history notifying of the move
1740 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1741 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1743 $nullRevId = $nullRevision->insertOn( $dbw );
1746 $dbw->update( 'page',
1748 'page_touched' => $now,
1749 'page_namespace' => $nt->getNamespace(),
1750 'page_title' => $nt->getDBkey(),
1751 'page_latest' => $nullRevId,
1753 /* WHERE */ array( 'page_id' => $oldid ),
1757 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1760 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1761 $redirectArticle = new Article( $this );
1762 $newid = $redirectArticle->insertOn( $dbw );
1763 $redirectRevision = new Revision( array(
1765 'comment' => $comment,
1766 'text' => $redirectText ) );
1767 $revid = $redirectRevision->insertOn( $dbw );
1768 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1769 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1772 $log = new LogPage( 'move' );
1773 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1775 # Purge caches as per article creation
1776 Article
::onArticleCreate( $nt );
1778 # Record the just-created redirect's linking to the page
1779 $dbw->insert( 'pagelinks',
1781 'pl_from' => $newid,
1782 'pl_namespace' => $nt->getNamespace(),
1783 'pl_title' => $nt->getDBkey() ),
1786 # Non-existent target may have had broken links to it; these must
1787 # now be touched to update link coloring.
1790 # Purge old title from squid
1791 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1792 $titles = $nt->getLinksTo();
1793 if ( $wgUseSquid ) {
1794 $urls = $this->getSquidURLs();
1795 foreach ( $titles as $linkTitle ) {
1796 $urls[] = $linkTitle->getInternalURL();
1798 $u = new SquidUpdate( $urls );
1804 * Checks if $this can be moved to a given Title
1805 * - Selects for update, so don't call it unless you mean business
1807 * @param Title &$nt the new title to check
1810 function isValidMoveTarget( $nt ) {
1812 $fname = 'Title::isValidMoveTarget';
1813 $dbw =& wfGetDB( DB_MASTER
);
1816 $id = $nt->getArticleID();
1817 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1818 array( 'page_is_redirect','old_text' ),
1819 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1820 $fname, 'FOR UPDATE' );
1822 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1827 # Does the redirect point to the source?
1828 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text
, $m ) ) {
1829 $redirTitle = Title
::newFromText( $m[1] );
1830 if( !is_object( $redirTitle ) ||
1831 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1836 # Does the article have a history?
1837 $row = $dbw->selectRow( array( 'page', 'revision'),
1839 array( 'page_namespace' => $nt->getNamespace(),
1840 'page_title' => $nt->getDBkey(),
1841 'page_id=rev_page AND page_latest != rev_id'
1842 ), $fname, 'FOR UPDATE'
1845 # Return true if there was no history
1846 return $row === false;
1850 * Create a redirect; fails if the title already exists; does
1853 * @param Title $dest the destination of the redirect
1854 * @param string $comment the comment string describing the move
1855 * @return bool true on success
1858 function createRedirect( $dest, $comment ) {
1860 if ( $this->getArticleID() ) {
1864 $fname = 'Title::createRedirect';
1865 $dbw =& wfGetDB( DB_MASTER
);
1867 $article = new Article( $this );
1868 $newid = $article->insertOn( $dbw );
1869 $revision = new Revision( array(
1871 'comment' => $comment,
1872 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1874 $revisionId = $revision->insertOn( $dbw );
1875 $article->updateRevisionOn( $dbw, $revision, 0 );
1878 $dbw->insert( 'pagelinks',
1880 'pl_from' => $newid,
1881 'pl_namespace' => $dest->getNamespace(),
1882 'pl_title' => $dest->getDbKey()
1886 Article
::onArticleCreate( $this );
1891 * Get categories to which this Title belongs and return an array of
1892 * categories' names.
1894 * @return array an array of parents in the form:
1895 * $parent => $currentarticle
1898 function getParentCategories() {
1899 global $wgContLang,$wgUser;
1901 $titlekey = $this->getArticleId();
1902 $sk =& $wgUser->getSkin();
1904 $dbr =& wfGetDB( DB_SLAVE
);
1905 $categorylinks = $dbr->tableName( 'categorylinks' );
1908 $sql = "SELECT * FROM $categorylinks"
1909 ." WHERE cl_from='$titlekey'"
1910 ." AND cl_from <> '0'"
1911 ." ORDER BY cl_sortkey";
1913 $res = $dbr->query ( $sql ) ;
1915 if($dbr->numRows($res) > 0) {
1916 while ( $x = $dbr->fetchObject ( $res ) )
1917 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1918 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1919 $dbr->freeResult ( $res ) ;
1927 * Get a tree of parent categories
1928 * @param array $children an array with the children in the keys, to check for circular refs
1932 function getParentCategoryTree( $children = array() ) {
1933 $parents = $this->getParentCategories();
1935 if($parents != '') {
1936 foreach($parents as $parent => $current)
1938 if ( array_key_exists( $parent, $children ) ) {
1939 # Circular reference
1940 $stack[$parent] = array();
1942 $nt = Title
::newFromText($parent);
1943 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
1954 * Get an associative array for selecting this title from
1960 function curCond() {
1961 wfDebugDieBacktrace( 'curCond called' );
1962 return array( 'cur_namespace' => $this->mNamespace
, 'cur_title' => $this->mDbkeyform
);
1966 * Get an associative array for selecting this title from the
1972 function oldCond() {
1973 wfDebugDieBacktrace( 'oldCond called' );
1974 return array( 'old_namespace' => $this->mNamespace
, 'old_title' => $this->mDbkeyform
);
1978 * Get the revision ID of the previous revision
1980 * @param integer $revision Revision ID. Get the revision that was before this one.
1981 * @return interger $oldrevision|false
1983 function getPreviousRevisionID( $revision ) {
1984 $dbr =& wfGetDB( DB_SLAVE
);
1985 return $dbr->selectField( 'revision', 'rev_id',
1986 'rev_page=' . IntVal( $this->getArticleId() ) .
1987 ' AND rev_id<' . IntVal( $revision ) . ' ORDER BY rev_id DESC' );
1991 * Get the revision ID of the next revision
1993 * @param integer $revision Revision ID. Get the revision that was after this one.
1994 * @return interger $oldrevision|false
1996 function getNextRevisionID( $revision ) {
1997 $dbr =& wfGetDB( DB_SLAVE
);
1998 return $dbr->selectField( 'revision', 'rev_id',
1999 'rev_page=' . IntVal( $this->getArticleId() ) .
2000 ' AND rev_id>' . IntVal( $revision ) . ' ORDER BY rev_id' );
2004 * Compare with another title.
2006 * @param Title $title
2009 function equals( &$title ) {
2010 return $this->getInterwiki() == $title->getInterwiki()
2011 && $this->getNamespace() == $title->getNamespace()
2012 && $this->getDbkey() == $title->getDbkey();
2016 * Check if page exists
2020 return $this->getArticleId() != 0;
2024 * Should a link should be displayed as a known link, just based on its title?
2026 * Currently, a self-link with a fragment, special pages and image pages are in
2027 * this category. Special pages never exist in the database. Some images do not
2028 * have description pages in the database, but the description page contains
2029 * useful history information that the user may want to link to.
2031 function isAlwaysKnown() {
2032 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2033 || NS_SPECIAL
== $this->mNamespace || NS_IMAGE
== $this->mNamespace
;
2037 * Update page_touched timestamps on pages linking to this title.
2038 * In principal, this could be backgrounded and could also do squid
2041 function touchLinks() {
2042 $fname = 'Title::touchLinks';
2044 $dbw =& wfGetDB( DB_MASTER
);
2046 $res = $dbw->select( 'pagelinks',
2049 'pl_namespace' => $this->getNamespace(),
2050 'pl_title' => $this->getDbKey() ),
2052 if ( 0 == $dbw->numRows( $res ) ) {
2057 $toucharr = array();
2058 while( $row = $dbw->fetchObject( $res ) ) {
2059 $toucharr[] = $row->pl_from
;
2062 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2063 /* WHERE */ array( 'page_id' => $toucharr ),$fname);