9 require_once( 'normal/UtfNormal.php' );
11 $wgTitleInterwikiCache = array();
12 $wgTitleCache = array();
14 define ( 'GAID_FOR_UPDATE', 1 );
16 # Title::newFromTitle maintains a cache to avoid
17 # expensive re-normalization of commonly used titles.
18 # On a batch operation this can become a memory leak
19 # if not bounded. After hitting this many titles,
21 define( 'MW_TITLECACHE_MAX', 1000 );
25 * - Represents a title, which may contain an interwiki designation or namespace
26 * - Can fetch various kinds of data from the database, albeit inefficiently.
32 * All member variables should be considered private
33 * Please use the accessor functions
40 var $mTextform; # Text form (spaces not underscores) of the main part
41 var $mUrlform; # URL-encoded form of the main part
42 var $mDbkeyform; # Main part with underscores
43 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
44 var $mInterwiki; # Interwiki prefix (or null string)
45 var $mFragment; # Title fragment (i.e. the bit after the #)
46 var $mArticleID; # Article ID, fetched from the link cache on demand
47 var $mLatestID; # ID of most recent revision
48 var $mRestrictions; # Array of groups allowed to edit this article
49 # Only null or "sysop" are supported
50 var $mRestrictionsLoaded; # Boolean for initialisation on demand
51 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
52 var $mDefaultNamespace; # Namespace index when there is no namespace
53 # Zero except in {{transclusion}} tags
54 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
62 /* private */ function Title() {
63 $this->mInterwiki
= $this->mUrlform
=
64 $this->mTextform
= $this->mDbkeyform
= '';
65 $this->mArticleID
= -1;
66 $this->mNamespace
= NS_MAIN
;
67 $this->mRestrictionsLoaded
= false;
68 $this->mRestrictions
= array();
69 # Dont change the following, NS_MAIN is hardcoded in several place
71 $this->mDefaultNamespace
= NS_MAIN
;
72 $this->mWatched
= NULL;
73 $this->mLatestID
= false;
77 * Create a new Title from a prefixed DB key
78 * @param string $key The database key, which has underscores
79 * instead of spaces, possibly including namespace and
81 * @return Title the new object, or NULL on an error
85 /* static */ function newFromDBkey( $key ) {
87 $t->mDbkeyform
= $key;
88 if( $t->secureAndSplit() )
95 * Create a new Title from text, such as what one would
96 * find in a link. Decodes any HTML entities in the text.
98 * @param string $text the link text; spaces, prefixes,
99 * and an initial ':' indicating the main namespace
101 * @param int $defaultNamespace the namespace to use if
102 * none is specified by a prefix
103 * @return Title the new object, or NULL on an error
107 function newFromText( $text, $defaultNamespace = NS_MAIN
) {
108 global $wgTitleCache;
109 $fname = 'Title::newFromText';
110 wfProfileIn( $fname );
112 if( is_object( $text ) ) {
113 wfDebugDieBacktrace( 'Title::newFromText given an object' );
117 * Wiki pages often contain multiple links to the same page.
118 * Title normalization and parsing can become expensive on
119 * pages with many links, so we can save a little time by
122 * In theory these are value objects and won't get changed...
124 if( $defaultNamespace == NS_MAIN
&& isset( $wgTitleCache[$text] ) ) {
125 wfProfileOut( $fname );
126 return $wgTitleCache[$text];
130 * Convert things like é ā or 〗 into real text...
132 $filteredText = Sanitizer
::decodeCharReferences( $text );
135 $t->mDbkeyform
= str_replace( ' ', '_', $filteredText );
136 $t->mDefaultNamespace
= $defaultNamespace;
138 static $cachedcount = 0 ;
139 if( $t->secureAndSplit() ) {
140 if( $defaultNamespace == NS_MAIN
) {
141 if( $cachedcount >= MW_TITLECACHE_MAX
) {
142 # Avoid memory leaks on mass operations...
143 $wgTitleCache = array();
147 $wgTitleCache[$text] =& $t;
149 wfProfileOut( $fname );
152 wfProfileOut( $fname );
159 * Create a new Title from URL-encoded text. Ensures that
160 * the given title's length does not exceed the maximum.
161 * @param string $url the title, as might be taken from a URL
162 * @return Title the new object, or NULL on an error
166 function newFromURL( $url ) {
167 global $wgLegalTitleChars;
170 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
171 # but some URLs used it as a space replacement and they still come
172 # from some external search tools.
173 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
174 $url = str_replace( '+', ' ', $url );
177 $t->mDbkeyform
= str_replace( ' ', '_', $url );
178 if( $t->secureAndSplit() ) {
186 * Create a new Title from an article ID
188 * @todo This is inefficiently implemented, the page row is requested
189 * but not used for anything else
191 * @param int $id the page_id corresponding to the Title to create
192 * @return Title the new object, or NULL on an error
196 function newFromID( $id ) {
197 $fname = 'Title::newFromID';
198 $dbr =& wfGetDB( DB_SLAVE
);
199 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
200 array( 'page_id' => $id ), $fname );
201 if ( $row !== false ) {
202 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
210 * Create a new Title from a namespace index and a DB key.
211 * It's assumed that $ns and $title are *valid*, for instance when
212 * they came directly from the database or a special page name.
213 * For convenience, spaces are converted to underscores so that
214 * eg user_text fields can be used directly.
216 * @param int $ns the namespace of the article
217 * @param string $title the unprefixed database key form
218 * @return Title the new object
222 function &makeTitle( $ns, $title ) {
226 $t->mNamespace
= intval( $ns );
227 $t->mDbkeyform
= str_replace( ' ', '_', $title );
228 $t->mArticleID
= ( $ns >= 0 ) ?
-1 : 0;
229 $t->mUrlform
= wfUrlencode( $t->mDbkeyform
);
230 $t->mTextform
= str_replace( '_', ' ', $title );
235 * Create a new Title frrom a namespace index and a DB key.
236 * The parameters will be checked for validity, which is a bit slower
237 * than makeTitle() but safer for user-provided data.
239 * @param int $ns the namespace of the article
240 * @param string $title the database key form
241 * @return Title the new object, or NULL on an error
245 function makeTitleSafe( $ns, $title ) {
247 $t->mDbkeyform
= Title
::makeName( $ns, $title );
248 if( $t->secureAndSplit() ) {
256 * Create a new Title for the Main Page
259 * @return Title the new object
262 function newMainPage() {
263 return Title
::newFromText( wfMsgForContent( 'mainpage' ) );
267 * Create a new Title for a redirect
268 * @param string $text the redirect title text
269 * @return Title the new object, or NULL if the text is not a
274 function newFromRedirect( $text ) {
277 if ( $wgMwRedir->matchStart( $text ) ) {
278 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
279 # categories are escaped using : for example one can enter:
280 # #REDIRECT [[:Category:Music]]. Need to remove it.
281 if ( substr($m[1],0,1) == ':') {
282 # We don't want to keep the ':'
283 $m[1] = substr( $m[1], 1 );
286 $rt = Title
::newFromText( $m[1] );
287 # Disallow redirects to Special:Userlogout
288 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL
&& preg_match( '/^Userlogout/i', $rt->getText() ) ) {
296 #----------------------------------------------------------------------------
298 #----------------------------------------------------------------------------
301 * Get the prefixed DB key associated with an ID
302 * @param int $id the page_id of the article
303 * @return Title an object representing the article, or NULL
304 * if no such article was found
308 function nameOf( $id ) {
309 $fname = 'Title::nameOf';
310 $dbr =& wfGetDB( DB_SLAVE
);
312 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
313 if ( $s === false ) { return NULL; }
315 $n = Title
::makeName( $s->page_namespace
, $s->page_title
);
320 * Get a regex character class describing the legal characters in a link
321 * @return string the list of characters, not delimited
325 function legalChars() {
326 global $wgLegalTitleChars;
327 return $wgLegalTitleChars;
331 * Get a string representation of a title suitable for
332 * including in a search index
334 * @param int $ns a namespace index
335 * @param string $title text-form main part
336 * @return string a stripped-down title string ready for the
339 /* static */ function indexTitle( $ns, $title ) {
341 require_once( 'SearchEngine.php' );
343 $lc = SearchEngine
::legalSearchChars() . '&#;';
344 $t = $wgContLang->stripForSearch( $title );
345 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
346 $t = strtolower( $t );
349 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
350 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
352 $t = preg_replace( "/\\s+/", ' ', $t );
354 if ( $ns == NS_IMAGE
) {
355 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
361 * Make a prefixed DB key from a DB key and a namespace index
362 * @param int $ns numerical representation of the namespace
363 * @param string $title the DB key form the title
364 * @return string the prefixed form of the title
366 /* static */ function makeName( $ns, $title ) {
369 $n = $wgContLang->getNsText( $ns );
370 return $n == '' ?
$title : "$n:$title";
374 * Returns the URL associated with an interwiki prefix
375 * @param string $key the interwiki prefix (e.g. "MeatBall")
376 * @return the associated URL, containing "$1", which should be
377 * replaced by an article title
381 function getInterwikiLink( $key ) {
382 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
383 $fname = 'Title::getInterwikiLink';
385 wfProfileIn( $fname );
387 $key = strtolower( $key );
389 $k = $wgDBname.':interwiki:'.$key;
390 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
391 wfProfileOut( $fname );
392 return $wgTitleInterwikiCache[$k]->iw_url
;
395 $s = $wgMemc->get( $k );
396 # Ignore old keys with no iw_local
397 if( $s && isset( $s->iw_local
) && isset($s->iw_trans
)) {
398 $wgTitleInterwikiCache[$k] = $s;
399 wfProfileOut( $fname );
403 $dbr =& wfGetDB( DB_SLAVE
);
404 $res = $dbr->select( 'interwiki',
405 array( 'iw_url', 'iw_local', 'iw_trans' ),
406 array( 'iw_prefix' => $key ), $fname );
408 wfProfileOut( $fname );
412 $s = $dbr->fetchObject( $res );
414 # Cache non-existence: create a blank object and save it to memcached
420 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
421 $wgTitleInterwikiCache[$k] = $s;
423 wfProfileOut( $fname );
428 * Determine whether the object refers to a page within
431 * @return bool TRUE if this is an in-project interwiki link
432 * or a wikilink, FALSE otherwise
436 global $wgTitleInterwikiCache, $wgDBname;
438 if ( $this->mInterwiki
!= '' ) {
439 # Make sure key is loaded into cache
440 $this->getInterwikiLink( $this->mInterwiki
);
441 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
442 return (bool)($wgTitleInterwikiCache[$k]->iw_local
);
449 * Determine whether the object refers to a page within
450 * this project and is transcludable.
452 * @return bool TRUE if this is transcludable
456 global $wgTitleInterwikiCache, $wgDBname;
458 if ($this->mInterwiki
== '' ||
!$this->isLocal())
460 # Make sure key is loaded into cache
461 $this->getInterwikiLink( $this->mInterwiki
);
462 $k = $wgDBname.':interwiki:' . $this->mInterwiki
;
463 return (bool)($wgTitleInterwikiCache[$k]->iw_trans
);
467 * Update the page_touched field for an array of title objects
468 * @todo Inefficient unless the IDs are already loaded into the
470 * @param array $titles an array of Title objects to be touched
471 * @param string $timestamp the timestamp to use instead of the
472 * default current time
476 function touchArray( $titles, $timestamp = '' ) {
478 if ( count( $titles ) == 0 ) {
481 $dbw =& wfGetDB( DB_MASTER
);
482 if ( $timestamp == '' ) {
483 $timestamp = $dbw->timestamp();
486 $page = $dbw->tableName( 'page' );
487 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
490 foreach ( $titles as $title ) {
491 if ( $wgUseFileCache ) {
492 $cm = new CacheManager($title);
493 @unlink($cm->fileCacheName());
500 $sql .= $title->getArticleID();
504 $dbw->query( $sql, 'Title::touchArray' );
507 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
508 // do them in small chunks:
509 $fname = 'Title::touchArray';
510 foreach( $titles as $title ) {
511 $dbw->update( 'page',
512 array( 'page_touched' => $timestamp ),
514 'page_namespace' => $title->getNamespace(),
515 'page_title' => $title->getDBkey() ),
520 #----------------------------------------------------------------------------
522 #----------------------------------------------------------------------------
524 /** Simple accessors */
526 * Get the text form (spaces not underscores) of the main part
530 function getText() { return $this->mTextform
; }
532 * Get the URL-encoded form of the main part
536 function getPartialURL() { return $this->mUrlform
; }
538 * Get the main part with underscores
542 function getDBkey() { return $this->mDbkeyform
; }
544 * Get the namespace index, i.e. one of the NS_xxxx constants
548 function getNamespace() { return $this->mNamespace
; }
550 * Get the namespace text
554 function getNsText() {
556 return $wgContLang->getNsText( $this->mNamespace
);
559 * Get the namespace text of the subject (rather than talk) page
563 function getSubjectNsText() {
565 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace
) );
569 * Get the interwiki prefix (or null string)
573 function getInterwiki() { return $this->mInterwiki
; }
575 * Get the Title fragment (i.e. the bit after the #)
579 function getFragment() { return $this->mFragment
; }
581 * Get the default namespace index, for when there is no namespace
585 function getDefaultNamespace() { return $this->mDefaultNamespace
; }
588 * Get title for search index
589 * @return string a stripped-down title string ready for the
592 function getIndexTitle() {
593 return Title
::indexTitle( $this->mNamespace
, $this->mTextform
);
597 * Get the prefixed database key form
598 * @return string the prefixed title, with underscores and
599 * any interwiki and namespace prefixes
602 function getPrefixedDBkey() {
603 $s = $this->prefix( $this->mDbkeyform
);
604 $s = str_replace( ' ', '_', $s );
609 * Get the prefixed title with spaces.
610 * This is the form usually used for display
611 * @return string the prefixed title, with spaces
614 function getPrefixedText() {
616 if ( empty( $this->mPrefixedText
) ) { // FIXME: bad usage of empty() ?
617 $s = $this->prefix( $this->mTextform
);
618 $s = str_replace( '_', ' ', $s );
619 $this->mPrefixedText
= $s;
621 return $this->mPrefixedText
;
625 * Get the prefixed title with spaces, plus any fragment
626 * (part beginning with '#')
627 * @return string the prefixed title, with spaces and
628 * the fragment, including '#'
631 function getFullText() {
633 $text = $this->getPrefixedText();
634 if( '' != $this->mFragment
) {
635 $text .= '#' . $this->mFragment
;
641 * Get a URL-encoded title (not an actual URL) including interwiki
642 * @return string the URL-encoded form
645 function getPrefixedURL() {
646 $s = $this->prefix( $this->mDbkeyform
);
647 $s = str_replace( ' ', '_', $s );
649 $s = wfUrlencode ( $s ) ;
651 # Cleaning up URL to make it look nice -- is this safe?
652 $s = str_replace( '%28', '(', $s );
653 $s = str_replace( '%29', ')', $s );
659 * Get a real URL referring to this title, with interwiki link and
662 * @param string $query an optional query string, not used
663 * for interwiki links
664 * @return string the URL
667 function getFullURL( $query = '' ) {
668 global $wgContLang, $wgServer, $wgRequest;
670 if ( '' == $this->mInterwiki
) {
671 $url = $this->getLocalUrl( $query );
673 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
674 // Correct fix would be to move the prepending elsewhere.
675 if ($wgRequest->getVal('action') != 'render') {
676 $url = $wgServer . $url;
679 $baseUrl = $this->getInterwikiLink( $this->mInterwiki
);
681 $namespace = $wgContLang->getNsText( $this->mNamespace
);
682 if ( '' != $namespace ) {
683 # Can this actually happen? Interwikis shouldn't be parsed.
686 $url = str_replace( '$1', $namespace . $this->mUrlform
, $baseUrl );
688 if( false === strpos( $url, '?' ) ) {
695 if ( '' != $this->mFragment
) {
696 $url .= '#' . $this->mFragment
;
699 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
704 * Get a URL with no fragment or server name. If this page is generated
705 * with action=render, $wgServer is prepended.
706 * @param string $query an optional query string; if not specified,
707 * $wgArticlePath will be used.
708 * @return string the URL
711 function getLocalURL( $query = '' ) {
712 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
714 if ( $this->isExternal() ) {
715 $url = $this->getFullURL();
717 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
718 if ( $query == '' ) {
719 $url = str_replace( '$1', $dbkey, $wgArticlePath );
721 global $wgActionPaths;
723 if( !empty( $wgActionPaths ) &&
724 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
726 $action = urldecode( $matches[2] );
727 if( isset( $wgActionPaths[$action] ) ) {
728 $query = $matches[1];
729 if( isset( $matches[4] ) ) $query .= $matches[4];
730 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
731 if( $query != '' ) $url .= '?' . $query;
734 if ( $url === false ) {
735 if ( $query == '-' ) {
738 $url = "{$wgScript}?title={$dbkey}&{$query}";
742 // FIXME: this causes breakage in various places when we
743 // actually expected a local URL and end up with dupe prefixes.
744 if ($wgRequest->getVal('action') == 'render') {
745 $url = $wgServer . $url;
748 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
753 * Get an HTML-escaped version of the URL form, suitable for
754 * using in a link, without a server name or fragment
755 * @param string $query an optional query string
756 * @return string the URL
759 function escapeLocalURL( $query = '' ) {
760 return htmlspecialchars( $this->getLocalURL( $query ) );
764 * Get an HTML-escaped version of the URL form, suitable for
765 * using in a link, including the server name and fragment
767 * @return string the URL
768 * @param string $query an optional query string
771 function escapeFullURL( $query = '' ) {
772 return htmlspecialchars( $this->getFullURL( $query ) );
776 * Get the URL form for an internal link.
777 * - Used in various Squid-related code, in case we have a different
778 * internal hostname for the server from the exposed one.
780 * @param string $query an optional query string
781 * @return string the URL
784 function getInternalURL( $query = '' ) {
785 global $wgInternalServer;
786 $url = $wgInternalServer . $this->getLocalURL( $query );
787 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
792 * Get the edit URL for this Title
793 * @return string the URL, or a null string if this is an
797 function getEditURL() {
798 global $wgServer, $wgScript;
800 if ( '' != $this->mInterwiki
) { return ''; }
801 $s = $this->getLocalURL( 'action=edit' );
807 * Get the HTML-escaped displayable text form.
808 * Used for the title field in <a> tags.
809 * @return string the text, including any prefixes
812 function getEscapedText() {
813 return htmlspecialchars( $this->getPrefixedText() );
817 * Is this Title interwiki?
821 function isExternal() { return ( '' != $this->mInterwiki
); }
824 * Does the title correspond to a protected article?
825 * @param string $what the action the page is protected from,
826 * by default checks move and edit
830 function isProtected($action = '') {
831 if ( -1 == $this->mNamespace
) { return true; }
832 if($action == 'edit' ||
$action == '') {
833 $a = $this->getRestrictions("edit");
834 if ( in_array( 'sysop', $a ) ) { return true; }
836 if($action == 'move' ||
$action == '') {
837 $a = $this->getRestrictions("move");
838 if ( in_array( 'sysop', $a ) ) { return true; }
844 * Is $wgUser is watching this page?
848 function userIsWatching() {
851 if ( is_null( $this->mWatched
) ) {
852 if ( -1 == $this->mNamespace ||
0 == $wgUser->getID()) {
853 $this->mWatched
= false;
855 $this->mWatched
= $wgUser->isWatched( $this );
858 return $this->mWatched
;
862 * Can $wgUser perform $action this page?
863 * @param string $action action that permission needs to be checked for
867 function userCan($action) {
868 $fname = 'Title::userCan';
869 wfProfileIn( $fname );
872 if( NS_SPECIAL
== $this->mNamespace
) {
873 wfProfileOut( $fname );
876 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
877 // from taking effect -ævar
878 if( NS_MEDIAWIKI
== $this->mNamespace
&&
879 !$wgUser->isAllowed('editinterface') ) {
880 wfProfileOut( $fname );
884 if( $this->mDbkeyform
== '_' ) {
885 # FIXME: Is this necessary? Shouldn't be allowed anyway...
886 wfProfileOut( $fname );
890 # protect global styles and js
891 if ( NS_MEDIAWIKI
== $this->mNamespace
892 && preg_match("/\\.(css|js)$/", $this->mTextform
)
893 && !$wgUser->isAllowed('editinterface') ) {
894 wfProfileOut( $fname );
898 # protect css/js subpages of user pages
899 # XXX: this might be better using restrictions
900 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
901 if( NS_USER
== $this->mNamespace
902 && preg_match("/\\.(css|js)$/", $this->mTextform
)
903 && !$wgUser->isAllowed('editinterface')
904 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) ) {
905 wfProfileOut( $fname );
909 foreach( $this->getRestrictions($action) as $right ) {
910 // Backwards compatibility, rewrite sysop -> protect
911 if ( $right == 'sysop' ) {
914 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
915 wfProfileOut( $fname );
920 if( $action == 'move' &&
921 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
922 wfProfileOut( $fname );
926 if( $action == 'create' ) {
927 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
928 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
933 wfProfileOut( $fname );
938 * Can $wgUser edit this page?
942 function userCanEdit() {
943 return $this->userCan('edit');
947 * Can $wgUser move this page?
951 function userCanMove() {
952 return $this->userCan('move');
956 * Would anybody with sufficient privileges be able to move this page?
957 * Some pages just aren't movable.
962 function isMovable() {
963 return Namespace::isMovable( $this->getNamespace() )
964 && $this->getInterwiki() == '';
968 * Can $wgUser read this page?
972 function userCanRead() {
975 if( $wgUser->isAllowed('read') ) {
978 global $wgWhitelistRead;
980 /** If anon users can create an account,
981 they need to reach the login page first! */
982 if( $wgUser->isAllowed( 'createaccount' )
983 && $this->getNamespace() == NS_SPECIAL
984 && $this->getText() == 'Userlogin' ) {
988 /** some pages are explicitly allowed */
989 $name = $this->getPrefixedText();
990 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
994 # Compatibility with old settings
995 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN
) {
996 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1005 * Is this a talk page of some sort?
1009 function isTalkPage() {
1010 return Namespace::isTalk( $this->getNamespace() );
1014 * Is this a .css or .js subpage of a user page?
1018 function isCssJsSubpage() {
1019 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.(css|js)$/", $this->mTextform
) );
1022 * Is this a .css subpage of a user page?
1026 function isCssSubpage() {
1027 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.css$/", $this->mTextform
) );
1030 * Is this a .js subpage of a user page?
1034 function isJsSubpage() {
1035 return ( NS_USER
== $this->mNamespace
and preg_match("/\\.js$/", $this->mTextform
) );
1038 * Protect css/js subpages of user pages: can $wgUser edit
1042 * @todo XXX: this might be better using restrictions
1045 function userCanEditCssJsSubpage() {
1047 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform
) );
1051 * Loads a string into mRestrictions array
1052 * @param string $res restrictions in string format
1055 function loadRestrictions( $res ) {
1056 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1057 $temp = explode( '=', trim( $restrict ) );
1058 if(count($temp) == 1) {
1059 // old format should be treated as edit/move restriction
1060 $this->mRestrictions
["edit"] = explode( ',', trim( $temp[0] ) );
1061 $this->mRestrictions
["move"] = explode( ',', trim( $temp[0] ) );
1063 $this->mRestrictions
[$temp[0]] = explode( ',', trim( $temp[1] ) );
1066 $this->mRestrictionsLoaded
= true;
1070 * Accessor/initialisation for mRestrictions
1071 * @param string $action action that permission needs to be checked for
1072 * @return array the array of groups allowed to edit this article
1075 function getRestrictions($action) {
1076 $id = $this->getArticleID();
1077 if ( 0 == $id ) { return array(); }
1079 if ( ! $this->mRestrictionsLoaded
) {
1080 $dbr =& wfGetDB( DB_SLAVE
);
1081 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1082 $this->loadRestrictions( $res );
1084 if( isset( $this->mRestrictions
[$action] ) ) {
1085 return $this->mRestrictions
[$action];
1091 * Is there a version of this page in the deletion archive?
1092 * @return int the number of archived revisions
1095 function isDeleted() {
1096 $fname = 'Title::isDeleted';
1097 if ( $this->getNamespace() < 0 ) {
1100 $dbr =& wfGetDB( DB_SLAVE
);
1101 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1102 'ar_title' => $this->getDBkey() ), $fname );
1108 * Get the article ID for this Title from the link cache,
1109 * adding it if necessary
1110 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1112 * @return int the ID
1115 function getArticleID( $flags = 0 ) {
1116 $linkCache =& LinkCache
::singleton();
1117 if ( $flags & GAID_FOR_UPDATE
) {
1118 $oldUpdate = $linkCache->forUpdate( true );
1119 $this->mArticleID
= $linkCache->addLinkObj( $this );
1120 $linkCache->forUpdate( $oldUpdate );
1122 if ( -1 == $this->mArticleID
) {
1123 $this->mArticleID
= $linkCache->addLinkObj( $this );
1126 return $this->mArticleID
;
1129 function getLatestRevID() {
1130 if ($this->mLatestID
!== false)
1131 return $this->mLatestID
;
1133 $db =& wfGetDB(DB_SLAVE
);
1134 return $this->mLatestID
= $db->selectField( 'revision',
1136 array('rev_page' => $this->getArticleID()),
1137 'Title::getLatestRevID' );
1141 * This clears some fields in this object, and clears any associated
1142 * keys in the "bad links" section of the link cache.
1144 * - This is called from Article::insertNewArticle() to allow
1145 * loading of the new page_id. It's also called from
1146 * Article::doDeleteArticle()
1148 * @param int $newid the new Article ID
1151 function resetArticleID( $newid ) {
1152 $linkCache =& LinkCache
::singleton();
1153 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1155 if ( 0 == $newid ) { $this->mArticleID
= -1; }
1156 else { $this->mArticleID
= $newid; }
1157 $this->mRestrictionsLoaded
= false;
1158 $this->mRestrictions
= array();
1162 * Updates page_touched for this page; called from LinksUpdate.php
1163 * @return bool true if the update succeded
1166 function invalidateCache() {
1167 global $wgUseFileCache;
1169 if ( wfReadOnly() ) {
1173 $dbw =& wfGetDB( DB_MASTER
);
1174 $success = $dbw->update( 'page',
1176 'page_touched' => $dbw->timestamp()
1177 ), array( /* WHERE */
1178 'page_namespace' => $this->getNamespace() ,
1179 'page_title' => $this->getDBkey()
1180 ), 'Title::invalidateCache'
1183 if ($wgUseFileCache) {
1184 $cache = new CacheManager($this);
1185 @unlink
($cache->fileCacheName());
1192 * Prefix some arbitrary text with the namespace or interwiki prefix
1195 * @param string $name the text
1196 * @return string the prefixed text
1199 /* private */ function prefix( $name ) {
1203 if ( '' != $this->mInterwiki
) {
1204 $p = $this->mInterwiki
. ':';
1206 if ( 0 != $this->mNamespace
) {
1207 $p .= $wgContLang->getNsText( $this->mNamespace
) . ':';
1213 * Secure and split - main initialisation function for this object
1215 * Assumes that mDbkeyform has been set, and is urldecoded
1216 * and uses underscores, but not otherwise munged. This function
1217 * removes illegal characters, splits off the interwiki and
1218 * namespace prefixes, sets the other forms, and canonicalizes
1220 * @return bool true on success
1223 /* private */ function secureAndSplit() {
1224 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1225 $fname = 'Title::secureAndSplit';
1226 wfProfileIn( $fname );
1229 static $rxTc = false;
1231 # % is needed as well
1232 $rxTc = '/[^' . Title
::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1235 $this->mInterwiki
= $this->mFragment
= '';
1236 $this->mNamespace
= $this->mDefaultNamespace
; # Usually NS_MAIN
1238 # Clean up whitespace
1240 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform
);
1241 $t = trim( $t, '_' );
1244 wfProfileOut( $fname );
1248 if( false !== strpos( $t, UTF8_REPLACEMENT
) ) {
1249 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1250 wfProfileOut( $fname );
1254 $this->mDbkeyform
= $t;
1256 # Initial colon indicates main namespace rather than specified default
1257 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1258 if ( ':' == $t{0} ) {
1259 $this->mNamespace
= NS_MAIN
;
1260 $t = substr( $t, 1 ); # remove the colon but continue processing
1263 # Namespace or interwiki prefix
1266 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1268 $lowerNs = strtolower( $p );
1269 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1270 # Canonical namespace
1272 $this->mNamespace
= $ns;
1273 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1274 # Ordinary namespace
1276 $this->mNamespace
= $ns;
1277 } elseif( $this->getInterwikiLink( $p ) ) {
1279 # Can't make a local interwiki link to an interwiki link.
1280 # That's just crazy!
1281 wfProfileOut( $fname );
1287 $this->mInterwiki
= strtolower( $p );
1289 # Redundant interwiki prefix to the local wiki
1290 if ( 0 == strcasecmp( $this->mInterwiki
, $wgLocalInterwiki ) ) {
1292 # Can't have an empty self-link
1293 wfProfileOut( $fname );
1296 $this->mInterwiki
= '';
1298 # Do another namespace split...
1302 # If there's no recognized interwiki or namespace,
1303 # then let the colon expression be part of the title.
1309 # We already know that some pages won't be in the database!
1311 if ( '' != $this->mInterwiki ||
-1 == $this->mNamespace
) {
1312 $this->mArticleID
= 0;
1314 $f = strstr( $r, '#' );
1315 if ( false !== $f ) {
1316 $this->mFragment
= substr( $f, 1 );
1317 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1318 # remove whitespace again: prevents "Foo_bar_#"
1319 # becoming "Foo_bar_"
1320 $r = preg_replace( '/_*$/', '', $r );
1323 # Reject illegal characters.
1325 if( preg_match( $rxTc, $r ) ) {
1326 wfProfileOut( $fname );
1331 * Pages with "/./" or "/../" appearing in the URLs will
1332 * often be unreachable due to the way web browsers deal
1333 * with 'relative' URLs. Forbid them explicitly.
1335 if ( strpos( $r, '.' ) !== false &&
1336 ( $r === '.' ||
$r === '..' ||
1337 strpos( $r, './' ) === 0 ||
1338 strpos( $r, '../' ) === 0 ||
1339 strpos( $r, '/./' ) !== false ||
1340 strpos( $r, '/../' ) !== false ) )
1342 wfProfileOut( $fname );
1346 # We shouldn't need to query the DB for the size.
1347 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1348 if ( strlen( $r ) > 255 ) {
1349 wfProfileOut( $fname );
1354 * Normally, all wiki links are forced to have
1355 * an initial capital letter so [[foo]] and [[Foo]]
1356 * point to the same place.
1358 * Don't force it for interwikis, since the other
1359 * site might be case-sensitive.
1361 if( $wgCapitalLinks && $this->mInterwiki
== '') {
1362 $t = $wgContLang->ucfirst( $r );
1368 * Can't make a link to a namespace alone...
1369 * "empty" local links can only be self-links
1370 * with a fragment identifier.
1373 $this->mInterwiki
== '' &&
1374 $this->mNamespace
!= NS_MAIN
) {
1375 wfProfileOut( $fname );
1380 $this->mDbkeyform
= $t;
1381 $this->mUrlform
= wfUrlencode( $t );
1383 $this->mTextform
= str_replace( '_', ' ', $t );
1385 wfProfileOut( $fname );
1390 * Get a Title object associated with the talk page of this article
1391 * @return Title the object for the talk page
1394 function getTalkPage() {
1395 return Title
::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1399 * Get a title object associated with the subject page of this
1402 * @return Title the object for the subject page
1405 function getSubjectPage() {
1406 return Title
::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1410 * Get an array of Title objects linking to this Title
1411 * Also stores the IDs in the link cache.
1413 * @param string $options may be FOR UPDATE
1414 * @return array the Title objects linking here
1417 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1418 $linkCache =& LinkCache
::singleton();
1419 $id = $this->getArticleID();
1422 $db =& wfGetDB( DB_MASTER
);
1424 $db =& wfGetDB( DB_SLAVE
);
1427 $res = $db->select( array( 'page', $table ),
1428 array( 'page_namespace', 'page_title', 'page_id' ),
1430 "{$prefix}_from=page_id",
1431 "{$prefix}_namespace" => $this->getNamespace(),
1432 "{$prefix}_title" => $this->getDbKey() ),
1433 'Title::getLinksTo',
1437 if ( $db->numRows( $res ) ) {
1438 while ( $row = $db->fetchObject( $res ) ) {
1439 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1440 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1441 $retVal[] = $titleObj;
1445 $db->freeResult( $res );
1450 * Get an array of Title objects using this Title as a template
1451 * Also stores the IDs in the link cache.
1453 * @param string $options may be FOR UPDATE
1454 * @return array the Title objects linking here
1457 function getTemplateLinksTo( $options = '' ) {
1458 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1462 * Get an array of Title objects referring to non-existent articles linked from this page
1464 * @param string $options may be FOR UPDATE
1465 * @return array the Title objects
1468 function getBrokenLinksFrom( $options = '' ) {
1470 $db =& wfGetDB( DB_MASTER
);
1472 $db =& wfGetDB( DB_SLAVE
);
1475 $res = $db->safeQuery(
1476 "SELECT pl_namespace, pl_title
1479 ON pl_namespace=page_namespace
1480 AND pl_title=page_title
1482 AND page_namespace IS NULL
1484 $db->tableName( 'pagelinks' ),
1485 $db->tableName( 'page' ),
1486 $this->getArticleId(),
1490 if ( $db->numRows( $res ) ) {
1491 while ( $row = $db->fetchObject( $res ) ) {
1492 $retVal[] = Title
::makeTitle( $row->pl_namespace
, $row->pl_title
);
1495 $db->freeResult( $res );
1501 * Get a list of URLs to purge from the Squid cache when this
1504 * @return array the URLs
1507 function getSquidURLs() {
1509 $this->getInternalURL(),
1510 $this->getInternalURL( 'action=history' )
1515 * Move this page without authentication
1516 * @param Title &$nt the new page Title
1519 function moveNoAuth( &$nt ) {
1520 return $this->moveTo( $nt, false );
1524 * Check whether a given move operation would be valid.
1525 * Returns true if ok, or a message key string for an error message
1526 * if invalid. (Scarrrrry ugly interface this.)
1527 * @param Title &$nt the new title
1528 * @param bool $auth indicates whether $wgUser's permissions
1530 * @return mixed true on success, message name on failure
1533 function isValidMoveOperation( &$nt, $auth = true ) {
1535 if( !$this or !$nt ) {
1536 return 'badtitletext';
1538 if( $this->equals( $nt ) ) {
1541 if( !$this->isMovable() ||
!$nt->isMovable() ) {
1542 return 'immobile_namespace';
1545 $oldid = $this->getArticleID();
1546 $newid = $nt->getArticleID();
1548 if ( strlen( $nt->getDBkey() ) < 1 ) {
1549 return 'articleexists';
1551 if ( ( '' == $this->getDBkey() ) ||
1553 ( '' == $nt->getDBkey() ) ) {
1554 return 'badarticleerror';
1558 !$this->userCanEdit() ||
!$nt->userCanEdit() ||
1559 !$this->userCanMove() ||
!$nt->userCanMove() ) ) {
1560 return 'protectedpage';
1563 # The move is allowed only if (1) the target doesn't exist, or
1564 # (2) the target is a redirect to the source, and has no history
1565 # (so we can undo bad moves right after they're done).
1567 if ( 0 != $newid ) { # Target exists; check for validity
1568 if ( ! $this->isValidMoveTarget( $nt ) ) {
1569 return 'articleexists';
1576 * Move a title to a new location
1577 * @param Title &$nt the new title
1578 * @param bool $auth indicates whether $wgUser's permissions
1580 * @return mixed true on success, message name on failure
1583 function moveTo( &$nt, $auth = true, $reason = '' ) {
1584 $err = $this->isValidMoveOperation( $nt, $auth );
1585 if( is_string( $err ) ) {
1589 $pageid = $this->getArticleID();
1590 if( $nt->exists() ) {
1591 $this->moveOverExistingRedirect( $nt, $reason );
1592 $pageCountChange = 0;
1593 } else { # Target didn't exist, do normal move.
1594 $this->moveToNewTitle( $nt, $reason );
1595 $pageCountChange = 1;
1597 $redirid = $this->getArticleID();
1599 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1600 $dbw =& wfGetDB( DB_MASTER
);
1601 $categorylinks = $dbw->tableName( 'categorylinks' );
1602 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1603 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1604 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1605 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1609 $oldnamespace = $this->getNamespace() & ~
1;
1610 $newnamespace = $nt->getNamespace() & ~
1;
1611 $oldtitle = $this->getDBkey();
1612 $newtitle = $nt->getDBkey();
1614 if( $oldnamespace != $newnamespace ||
$oldtitle != $newtitle ) {
1615 WatchedItem
::duplicateEntries( $this, $nt );
1618 # Update search engine
1619 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1621 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1625 if ( $this->getNamespace() == NS_MAIN
and $nt->getNamespace() != NS_MAIN
) {
1626 # Moved out of main namespace
1627 # not viewed, edited, removing
1628 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange);
1629 } elseif ( $this->getNamespace() != NS_MAIN
and $nt->getNamespace() == NS_MAIN
) {
1630 # Moved into main namespace
1631 # not viewed, edited, adding
1632 $u = new SiteStatsUpdate( 0, 1, +
1, $pageCountChange );
1633 } elseif ( $pageCountChange ) {
1635 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1644 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1649 * Move page to a title which is at present a redirect to the
1652 * @param Title &$nt the page to move to, which should currently
1656 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1657 global $wgUser, $wgUseSquid, $wgMwRedir;
1658 $fname = 'Title::moveOverExistingRedirect';
1659 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1662 $comment .= ": $reason";
1665 $now = wfTimestampNow();
1667 $newid = $nt->getArticleID();
1668 $oldid = $this->getArticleID();
1669 $dbw =& wfGetDB( DB_MASTER
);
1670 $linkCache =& LinkCache
::singleton();
1672 # Delete the old redirect. We don't save it to history since
1673 # by definition if we've got here it's rather uninteresting.
1674 # We have to remove it so that the next step doesn't trigger
1675 # a conflict on the unique namespace+title index...
1676 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1678 # Save a null revision in the page's history notifying of the move
1679 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1680 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1682 $nullRevId = $nullRevision->insertOn( $dbw );
1684 # Change the name of the target page:
1685 $dbw->update( 'page',
1687 'page_touched' => $dbw->timestamp($now),
1688 'page_namespace' => $nt->getNamespace(),
1689 'page_title' => $nt->getDBkey(),
1690 'page_latest' => $nullRevId,
1692 /* WHERE */ array( 'page_id' => $oldid ),
1695 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1697 # Recreate the redirect, this time in the other direction.
1698 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1699 $redirectArticle = new Article( $this );
1700 $newid = $redirectArticle->insertOn( $dbw );
1701 $redirectRevision = new Revision( array(
1703 'comment' => $comment,
1704 'text' => $redirectText ) );
1705 $revid = $redirectRevision->insertOn( $dbw );
1706 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1707 $linkCache->clearLink( $this->getPrefixedDBkey() );
1710 $log = new LogPage( 'move' );
1711 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1713 # Now, we record the link from the redirect to the new title.
1714 # It should have no other outgoing links...
1715 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1716 $dbw->insert( 'pagelinks',
1718 'pl_from' => $newid,
1719 'pl_namespace' => $nt->getNamespace(),
1720 'pl_title' => $nt->getDbKey() ),
1724 if ( $wgUseSquid ) {
1725 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1726 $u = new SquidUpdate( $urls );
1732 * Move page to non-existing title.
1733 * @param Title &$nt the new Title
1736 function moveToNewTitle( &$nt, $reason = '' ) {
1737 global $wgUser, $wgUseSquid;
1739 $fname = 'MovePageForm::moveToNewTitle';
1740 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1742 $comment .= ": $reason";
1745 $newid = $nt->getArticleID();
1746 $oldid = $this->getArticleID();
1747 $dbw =& wfGetDB( DB_MASTER
);
1748 $now = $dbw->timestamp();
1750 $linkCache =& LinkCache
::singleton();
1752 # Save a null revision in the page's history notifying of the move
1753 $nullRevision = Revision
::newNullRevision( $dbw, $oldid,
1754 wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1756 $nullRevId = $nullRevision->insertOn( $dbw );
1759 $dbw->update( 'page',
1761 'page_touched' => $now,
1762 'page_namespace' => $nt->getNamespace(),
1763 'page_title' => $nt->getDBkey(),
1764 'page_latest' => $nullRevId,
1766 /* WHERE */ array( 'page_id' => $oldid ),
1770 $linkCache->clearLink( $nt->getPrefixedDBkey() );
1773 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1774 $redirectArticle = new Article( $this );
1775 $newid = $redirectArticle->insertOn( $dbw );
1776 $redirectRevision = new Revision( array(
1778 'comment' => $comment,
1779 'text' => $redirectText ) );
1780 $revid = $redirectRevision->insertOn( $dbw );
1781 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1782 $linkCache->clearLink( $this->getPrefixedDBkey() );
1785 $log = new LogPage( 'move' );
1786 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1788 # Purge caches as per article creation
1789 Article
::onArticleCreate( $nt );
1791 # Record the just-created redirect's linking to the page
1792 $dbw->insert( 'pagelinks',
1794 'pl_from' => $newid,
1795 'pl_namespace' => $nt->getNamespace(),
1796 'pl_title' => $nt->getDBkey() ),
1799 # Non-existent target may have had broken links to it; these must
1800 # now be touched to update link coloring.
1803 # Purge old title from squid
1804 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1805 $titles = $nt->getLinksTo();
1806 if ( $wgUseSquid ) {
1807 $urls = $this->getSquidURLs();
1808 foreach ( $titles as $linkTitle ) {
1809 $urls[] = $linkTitle->getInternalURL();
1811 $u = new SquidUpdate( $urls );
1817 * Checks if $this can be moved to a given Title
1818 * - Selects for update, so don't call it unless you mean business
1820 * @param Title &$nt the new title to check
1823 function isValidMoveTarget( $nt ) {
1825 $fname = 'Title::isValidMoveTarget';
1826 $dbw =& wfGetDB( DB_MASTER
);
1829 $id = $nt->getArticleID();
1830 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1831 array( 'page_is_redirect','old_text','old_flags' ),
1832 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1833 $fname, 'FOR UPDATE' );
1835 if ( !$obj ||
0 == $obj->page_is_redirect
) {
1839 $text = Revision
::getRevisionText( $obj );
1841 # Does the redirect point to the source?
1842 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
1843 $redirTitle = Title
::newFromText( $m[1] );
1844 if( !is_object( $redirTitle ) ||
1845 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1853 # Does the article have a history?
1854 $row = $dbw->selectRow( array( 'page', 'revision'),
1856 array( 'page_namespace' => $nt->getNamespace(),
1857 'page_title' => $nt->getDBkey(),
1858 'page_id=rev_page AND page_latest != rev_id'
1859 ), $fname, 'FOR UPDATE'
1862 # Return true if there was no history
1863 return $row === false;
1867 * Create a redirect; fails if the title already exists; does
1870 * @param Title $dest the destination of the redirect
1871 * @param string $comment the comment string describing the move
1872 * @return bool true on success
1875 function createRedirect( $dest, $comment ) {
1877 if ( $this->getArticleID() ) {
1881 $fname = 'Title::createRedirect';
1882 $dbw =& wfGetDB( DB_MASTER
);
1884 $article = new Article( $this );
1885 $newid = $article->insertOn( $dbw );
1886 $revision = new Revision( array(
1888 'comment' => $comment,
1889 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1891 $revisionId = $revision->insertOn( $dbw );
1892 $article->updateRevisionOn( $dbw, $revision, 0 );
1895 $dbw->insert( 'pagelinks',
1897 'pl_from' => $newid,
1898 'pl_namespace' => $dest->getNamespace(),
1899 'pl_title' => $dest->getDbKey()
1903 Article
::onArticleCreate( $this );
1908 * Get categories to which this Title belongs and return an array of
1909 * categories' names.
1911 * @return array an array of parents in the form:
1912 * $parent => $currentarticle
1915 function getParentCategories() {
1916 global $wgContLang,$wgUser;
1918 $titlekey = $this->getArticleId();
1919 $dbr =& wfGetDB( DB_SLAVE
);
1920 $categorylinks = $dbr->tableName( 'categorylinks' );
1923 $sql = "SELECT * FROM $categorylinks"
1924 ." WHERE cl_from='$titlekey'"
1925 ." AND cl_from <> '0'"
1926 ." ORDER BY cl_sortkey";
1928 $res = $dbr->query ( $sql ) ;
1930 if($dbr->numRows($res) > 0) {
1931 while ( $x = $dbr->fetchObject ( $res ) )
1932 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1933 $data[$wgContLang->getNSText ( NS_CATEGORY
).':'.$x->cl_to
] = $this->getFullText();
1934 $dbr->freeResult ( $res ) ;
1942 * Get a tree of parent categories
1943 * @param array $children an array with the children in the keys, to check for circular refs
1947 function getParentCategoryTree( $children = array() ) {
1948 $parents = $this->getParentCategories();
1950 if($parents != '') {
1951 foreach($parents as $parent => $current) {
1952 if ( array_key_exists( $parent, $children ) ) {
1953 # Circular reference
1954 $stack[$parent] = array();
1956 $nt = Title
::newFromText($parent);
1957 $stack[$parent] = $nt->getParentCategoryTree( $children +
array($parent => 1) );
1968 * Get an associative array for selecting this title from
1974 function pageCond() {
1975 return array( 'page_namespace' => $this->mNamespace
, 'page_title' => $this->mDbkeyform
);
1979 * Get the revision ID of the previous revision
1981 * @param integer $revision Revision ID. Get the revision that was before this one.
1982 * @return interger $oldrevision|false
1984 function getPreviousRevisionID( $revision ) {
1985 $dbr =& wfGetDB( DB_SLAVE
);
1986 return $dbr->selectField( 'revision', 'rev_id',
1987 'rev_page=' . intval( $this->getArticleId() ) .
1988 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
1992 * Get the revision ID of the next revision
1994 * @param integer $revision Revision ID. Get the revision that was after this one.
1995 * @return interger $oldrevision|false
1997 function getNextRevisionID( $revision ) {
1998 $dbr =& wfGetDB( DB_SLAVE
);
1999 return $dbr->selectField( 'revision', 'rev_id',
2000 'rev_page=' . intval( $this->getArticleId() ) .
2001 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2005 * Compare with another title.
2007 * @param Title $title
2010 function equals( $title ) {
2011 return $this->getInterwiki() == $title->getInterwiki()
2012 && $this->getNamespace() == $title->getNamespace()
2013 && $this->getDbkey() == $title->getDbkey();
2017 * Check if page exists
2021 return $this->getArticleId() != 0;
2025 * Should a link should be displayed as a known link, just based on its title?
2027 * Currently, a self-link with a fragment and special pages are in
2028 * this category. Special pages never exist in the database.
2030 function isAlwaysKnown() {
2031 return $this->isExternal() ||
( 0 == $this->mNamespace
&& "" == $this->mDbkeyform
)
2032 || NS_SPECIAL
== $this->mNamespace
;
2036 * Update page_touched timestamps on pages linking to this title.
2037 * In principal, this could be backgrounded and could also do squid
2040 function touchLinks() {
2041 $fname = 'Title::touchLinks';
2043 $dbw =& wfGetDB( DB_MASTER
);
2045 $res = $dbw->select( 'pagelinks',
2048 'pl_namespace' => $this->getNamespace(),
2049 'pl_title' => $this->getDbKey() ),
2052 $toucharr = array();
2053 while( $row = $dbw->fetchObject( $res ) ) {
2054 $toucharr[] = $row->pl_from
;
2056 $dbw->freeResult( $res );
2058 if( $this->getNamespace() == NS_CATEGORY
) {
2059 // Categories show up in a separate set of links as well
2060 $res = $dbw->select( 'categorylinks',
2062 array( 'cl_to' => $this->getDbKey() ),
2064 while( $row = $dbw->fetchObject( $res ) ) {
2065 $toucharr[] = $row->cl_from
;
2067 $dbw->freeResult( $res );
2070 if (!count($toucharr))
2072 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2073 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2076 function trackbackURL() {
2077 global $wgTitle, $wgScriptPath, $wgServer;
2079 return "$wgServer$wgScriptPath/trackback.php?article="
2080 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2083 function trackbackRDF() {
2084 $url = htmlspecialchars($this->getFullURL());
2085 $title = htmlspecialchars($this->getText());
2086 $tburl = $this->trackbackURL();
2089 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2090 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2091 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2094 dc:identifier=\"$url\"
2096 trackback:ping=\"$tburl\" />