revert api clutter from r18995
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * See title.txt
4 *
5 * @package MediaWiki
6 */
7
8 /** */
9 require_once( 'normal/UtfNormal.php' );
10
11 define ( 'GAID_FOR_UPDATE', 1 );
12
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,
17 # reset the cache.
18 define( 'MW_TITLECACHE_MAX', 1000 );
19
20 /**
21 * Title class
22 * - Represents a title, which may contain an interwiki designation or namespace
23 * - Can fetch various kinds of data from the database, albeit inefficiently.
24 *
25 * @package MediaWiki
26 */
27 class Title {
28 /**
29 * Static cache variables
30 */
31 static private $titleCache=array();
32 static private $interwikiCache=array();
33
34
35 /**
36 * All member variables should be considered private
37 * Please use the accessor functions
38 */
39
40 /**#@+
41 * @private
42 */
43
44 var $mTextform; # Text form (spaces not underscores) of the main part
45 var $mUrlform; # URL-encoded form of the main part
46 var $mDbkeyform; # Main part with underscores
47 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
48 var $mInterwiki; # Interwiki prefix (or null string)
49 var $mFragment; # Title fragment (i.e. the bit after the #)
50 var $mArticleID; # Article ID, fetched from the link cache on demand
51 var $mLatestID; # ID of most recent revision
52 var $mRestrictions; # Array of groups allowed to edit this article
53 # Only null or "sysop" are supported
54 var $mRestrictionsLoaded; # Boolean for initialisation on demand
55 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
56 var $mDefaultNamespace; # Namespace index when there is no namespace
57 # Zero except in {{transclusion}} tags
58 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
59 /**#@-*/
60
61
62 /**
63 * Constructor
64 * @private
65 */
66 /* private */ function Title() {
67 $this->mInterwiki = $this->mUrlform =
68 $this->mTextform = $this->mDbkeyform = '';
69 $this->mArticleID = -1;
70 $this->mNamespace = NS_MAIN;
71 $this->mRestrictionsLoaded = false;
72 $this->mRestrictions = array();
73 # Dont change the following, NS_MAIN is hardcoded in several place
74 # See bug #696
75 $this->mDefaultNamespace = NS_MAIN;
76 $this->mWatched = NULL;
77 $this->mLatestID = false;
78 }
79
80 /**
81 * Create a new Title from a prefixed DB key
82 * @param string $key The database key, which has underscores
83 * instead of spaces, possibly including namespace and
84 * interwiki prefixes
85 * @return Title the new object, or NULL on an error
86 * @static
87 * @access public
88 */
89 /* static */ function newFromDBkey( $key ) {
90 $t = new Title();
91 $t->mDbkeyform = $key;
92 if( $t->secureAndSplit() )
93 return $t;
94 else
95 return NULL;
96 }
97
98 /**
99 * Create a new Title from text, such as what one would
100 * find in a link. Decodes any HTML entities in the text.
101 *
102 * @param string $text the link text; spaces, prefixes,
103 * and an initial ':' indicating the main namespace
104 * are accepted
105 * @param int $defaultNamespace the namespace to use if
106 * none is specified by a prefix
107 * @return Title the new object, or NULL on an error
108 * @static
109 * @access public
110 */
111 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
112 if( is_object( $text ) ) {
113 throw new MWException( 'Title::newFromText given an object' );
114 }
115
116 /**
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
120 * caching them.
121 *
122 * In theory these are value objects and won't get changed...
123 */
124 if( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
125 return Title::$titleCache[$text];
126 }
127
128 /**
129 * Convert things like &eacute; &#257; or &#x3017; into real text...
130 */
131 $filteredText = Sanitizer::decodeCharReferences( $text );
132
133 $t = new Title();
134 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
135 $t->mDefaultNamespace = $defaultNamespace;
136
137 static $cachedcount = 0 ;
138 if( $t->secureAndSplit() ) {
139 if( $defaultNamespace == NS_MAIN ) {
140 if( $cachedcount >= MW_TITLECACHE_MAX ) {
141 # Avoid memory leaks on mass operations...
142 Title::$titleCache = array();
143 $cachedcount=0;
144 }
145 $cachedcount++;
146 Title::$titleCache[$text] =& $t;
147 }
148 return $t;
149 } else {
150 $ret = NULL;
151 return $ret;
152 }
153 }
154
155 /**
156 * Create a new Title from URL-encoded text. Ensures that
157 * the given title's length does not exceed the maximum.
158 * @param string $url the title, as might be taken from a URL
159 * @return Title the new object, or NULL on an error
160 * @static
161 * @access public
162 */
163 public static function newFromURL( $url ) {
164 global $wgLegalTitleChars;
165 $t = new Title();
166
167 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
168 # but some URLs used it as a space replacement and they still come
169 # from some external search tools.
170 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
171 $url = str_replace( '+', ' ', $url );
172 }
173
174 $t->mDbkeyform = str_replace( ' ', '_', $url );
175 if( $t->secureAndSplit() ) {
176 return $t;
177 } else {
178 return NULL;
179 }
180 }
181
182 /**
183 * Create a new Title from an article ID
184 *
185 * @todo This is inefficiently implemented, the page row is requested
186 * but not used for anything else
187 *
188 * @param int $id the page_id corresponding to the Title to create
189 * @return Title the new object, or NULL on an error
190 * @access public
191 * @static
192 */
193 public static function newFromID( $id ) {
194 $fname = 'Title::newFromID';
195 $dbr =& wfGetDB( DB_SLAVE );
196 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
197 array( 'page_id' => $id ), $fname );
198 if ( $row !== false ) {
199 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
200 } else {
201 $title = NULL;
202 }
203 return $title;
204 }
205
206 /**
207 * Make an array of titles from an array of IDs
208 */
209 function newFromIDs( $ids ) {
210 $dbr =& wfGetDB( DB_SLAVE );
211 $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
212 'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ );
213
214 $titles = array();
215 while ( $row = $dbr->fetchObject( $res ) ) {
216 $titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
217 }
218 return $titles;
219 }
220
221 /**
222 * Create a new Title from a namespace index and a DB key.
223 * It's assumed that $ns and $title are *valid*, for instance when
224 * they came directly from the database or a special page name.
225 * For convenience, spaces are converted to underscores so that
226 * eg user_text fields can be used directly.
227 *
228 * @param int $ns the namespace of the article
229 * @param string $title the unprefixed database key form
230 * @return Title the new object
231 * @static
232 * @access public
233 */
234 public static function &makeTitle( $ns, $title ) {
235 $t = new Title();
236 $t->mInterwiki = '';
237 $t->mFragment = '';
238 $t->mNamespace = intval( $ns );
239 $t->mDbkeyform = str_replace( ' ', '_', $title );
240 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
241 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
242 $t->mTextform = str_replace( '_', ' ', $title );
243 return $t;
244 }
245
246 /**
247 * Create a new Title from a namespace index and a DB key.
248 * The parameters will be checked for validity, which is a bit slower
249 * than makeTitle() but safer for user-provided data.
250 *
251 * @param int $ns the namespace of the article
252 * @param string $title the database key form
253 * @return Title the new object, or NULL on an error
254 * @static
255 * @access public
256 */
257 public static function makeTitleSafe( $ns, $title ) {
258 $t = new Title();
259 $t->mDbkeyform = Title::makeName( $ns, $title );
260 if( $t->secureAndSplit() ) {
261 return $t;
262 } else {
263 return NULL;
264 }
265 }
266
267 /**
268 * Create a new Title for the Main Page
269 *
270 * @static
271 * @return Title the new object
272 * @access public
273 */
274 public static function newMainPage() {
275 return Title::newFromText( wfMsgForContent( 'mainpage' ) );
276 }
277
278 /**
279 * Create a new Title for a redirect
280 * @param string $text the redirect title text
281 * @return Title the new object, or NULL if the text is not a
282 * valid redirect
283 */
284 public static function newFromRedirect( $text ) {
285 $mwRedir = MagicWord::get( 'redirect' );
286 $rt = NULL;
287 if ( $mwRedir->matchStart( $text ) ) {
288 $m = array();
289 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
290 # categories are escaped using : for example one can enter:
291 # #REDIRECT [[:Category:Music]]. Need to remove it.
292 if ( substr($m[1],0,1) == ':') {
293 # We don't want to keep the ':'
294 $m[1] = substr( $m[1], 1 );
295 }
296
297 $rt = Title::newFromText( $m[1] );
298 # Disallow redirects to Special:Userlogout
299 if ( !is_null($rt) && $rt->isSpecial( 'Userlogout' ) ) {
300 $rt = NULL;
301 }
302 }
303 }
304 return $rt;
305 }
306
307 #----------------------------------------------------------------------------
308 # Static functions
309 #----------------------------------------------------------------------------
310
311 /**
312 * Get the prefixed DB key associated with an ID
313 * @param int $id the page_id of the article
314 * @return Title an object representing the article, or NULL
315 * if no such article was found
316 * @static
317 * @access public
318 */
319 function nameOf( $id ) {
320 $fname = 'Title::nameOf';
321 $dbr =& wfGetDB( DB_SLAVE );
322
323 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
324 if ( $s === false ) { return NULL; }
325
326 $n = Title::makeName( $s->page_namespace, $s->page_title );
327 return $n;
328 }
329
330 /**
331 * Get a regex character class describing the legal characters in a link
332 * @return string the list of characters, not delimited
333 * @static
334 * @access public
335 */
336 public static function legalChars() {
337 global $wgLegalTitleChars;
338 return $wgLegalTitleChars;
339 }
340
341 /**
342 * Get a string representation of a title suitable for
343 * including in a search index
344 *
345 * @param int $ns a namespace index
346 * @param string $title text-form main part
347 * @return string a stripped-down title string ready for the
348 * search index
349 */
350 public static function indexTitle( $ns, $title ) {
351 global $wgContLang;
352
353 $lc = SearchEngine::legalSearchChars() . '&#;';
354 $t = $wgContLang->stripForSearch( $title );
355 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
356 $t = $wgContLang->lc( $t );
357
358 # Handle 's, s'
359 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
360 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
361
362 $t = preg_replace( "/\\s+/", ' ', $t );
363
364 if ( $ns == NS_IMAGE ) {
365 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
366 }
367 return trim( $t );
368 }
369
370 /*
371 * Make a prefixed DB key from a DB key and a namespace index
372 * @param int $ns numerical representation of the namespace
373 * @param string $title the DB key form the title
374 * @return string the prefixed form of the title
375 */
376 public static function makeName( $ns, $title ) {
377 global $wgContLang;
378
379 $n = $wgContLang->getNsText( $ns );
380 return $n == '' ? $title : "$n:$title";
381 }
382
383 /**
384 * Returns the URL associated with an interwiki prefix
385 * @param string $key the interwiki prefix (e.g. "MeatBall")
386 * @return the associated URL, containing "$1", which should be
387 * replaced by an article title
388 * @static (arguably)
389 * @access public
390 */
391 function getInterwikiLink( $key ) {
392 global $wgMemc, $wgInterwikiExpiry;
393 global $wgInterwikiCache, $wgContLang;
394 $fname = 'Title::getInterwikiLink';
395
396 $key = $wgContLang->lc( $key );
397
398 $k = wfMemcKey( 'interwiki', $key );
399 if( array_key_exists( $k, Title::$interwikiCache ) ) {
400 return Title::$interwikiCache[$k]->iw_url;
401 }
402
403 if ($wgInterwikiCache) {
404 return Title::getInterwikiCached( $key );
405 }
406
407 $s = $wgMemc->get( $k );
408 # Ignore old keys with no iw_local
409 if( $s && isset( $s->iw_local ) && isset($s->iw_trans)) {
410 Title::$interwikiCache[$k] = $s;
411 return $s->iw_url;
412 }
413
414 $dbr =& wfGetDB( DB_SLAVE );
415 $res = $dbr->select( 'interwiki',
416 array( 'iw_url', 'iw_local', 'iw_trans' ),
417 array( 'iw_prefix' => $key ), $fname );
418 if( !$res ) {
419 return '';
420 }
421
422 $s = $dbr->fetchObject( $res );
423 if( !$s ) {
424 # Cache non-existence: create a blank object and save it to memcached
425 $s = (object)false;
426 $s->iw_url = '';
427 $s->iw_local = 0;
428 $s->iw_trans = 0;
429 }
430 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
431 Title::$interwikiCache[$k] = $s;
432
433 return $s->iw_url;
434 }
435
436 /**
437 * Fetch interwiki prefix data from local cache in constant database
438 *
439 * More logic is explained in DefaultSettings
440 *
441 * @return string URL of interwiki site
442 * @access public
443 */
444 function getInterwikiCached( $key ) {
445 global $wgInterwikiCache, $wgInterwikiScopes, $wgInterwikiFallbackSite;
446 static $db, $site;
447
448 if (!$db)
449 $db=dba_open($wgInterwikiCache,'r','cdb');
450 /* Resolve site name */
451 if ($wgInterwikiScopes>=3 and !$site) {
452 $site = dba_fetch('__sites:' . wfWikiID(), $db);
453 if ($site=="")
454 $site = $wgInterwikiFallbackSite;
455 }
456 $value = dba_fetch( wfMemcKey( $key ), $db);
457 if ($value=='' and $wgInterwikiScopes>=3) {
458 /* try site-level */
459 $value = dba_fetch("_{$site}:{$key}", $db);
460 }
461 if ($value=='' and $wgInterwikiScopes>=2) {
462 /* try globals */
463 $value = dba_fetch("__global:{$key}", $db);
464 }
465 if ($value=='undef')
466 $value='';
467 $s = (object)false;
468 $s->iw_url = '';
469 $s->iw_local = 0;
470 $s->iw_trans = 0;
471 if ($value!='') {
472 list($local,$url)=explode(' ',$value,2);
473 $s->iw_url=$url;
474 $s->iw_local=(int)$local;
475 }
476 Title::$interwikiCache[wfMemcKey( 'interwiki', $key )] = $s;
477 return $s->iw_url;
478 }
479 /**
480 * Determine whether the object refers to a page within
481 * this project.
482 *
483 * @return bool TRUE if this is an in-project interwiki link
484 * or a wikilink, FALSE otherwise
485 * @access public
486 */
487 function isLocal() {
488 if ( $this->mInterwiki != '' ) {
489 # Make sure key is loaded into cache
490 $this->getInterwikiLink( $this->mInterwiki );
491 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
492 return (bool)(Title::$interwikiCache[$k]->iw_local);
493 } else {
494 return true;
495 }
496 }
497
498 /**
499 * Determine whether the object refers to a page within
500 * this project and is transcludable.
501 *
502 * @return bool TRUE if this is transcludable
503 * @access public
504 */
505 function isTrans() {
506 if ($this->mInterwiki == '')
507 return false;
508 # Make sure key is loaded into cache
509 $this->getInterwikiLink( $this->mInterwiki );
510 $k = wfMemcKey( 'interwiki', $this->mInterwiki );
511 return (bool)(Title::$interwikiCache[$k]->iw_trans);
512 }
513
514 /**
515 * Update the page_touched field for an array of title objects
516 * @todo Inefficient unless the IDs are already loaded into the
517 * link cache
518 * @param array $titles an array of Title objects to be touched
519 * @param string $timestamp the timestamp to use instead of the
520 * default current time
521 * @static
522 * @access public
523 */
524 function touchArray( $titles, $timestamp = '' ) {
525
526 if ( count( $titles ) == 0 ) {
527 return;
528 }
529 $dbw =& wfGetDB( DB_MASTER );
530 if ( $timestamp == '' ) {
531 $timestamp = $dbw->timestamp();
532 }
533 /*
534 $page = $dbw->tableName( 'page' );
535 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
536 $first = true;
537
538 foreach ( $titles as $title ) {
539 if ( $wgUseFileCache ) {
540 $cm = new HTMLFileCache($title);
541 @unlink($cm->fileCacheName());
542 }
543
544 if ( ! $first ) {
545 $sql .= ',';
546 }
547 $first = false;
548 $sql .= $title->getArticleID();
549 }
550 $sql .= ')';
551 if ( ! $first ) {
552 $dbw->query( $sql, 'Title::touchArray' );
553 }
554 */
555 // hack hack hack -- brion 2005-07-11. this was unfriendly to db.
556 // do them in small chunks:
557 $fname = 'Title::touchArray';
558 foreach( $titles as $title ) {
559 $dbw->update( 'page',
560 array( 'page_touched' => $timestamp ),
561 array(
562 'page_namespace' => $title->getNamespace(),
563 'page_title' => $title->getDBkey() ),
564 $fname );
565 }
566 }
567
568 /**
569 * Escape a text fragment, say from a link, for a URL
570 */
571 static function escapeFragmentForURL( $fragment ) {
572 $fragment = str_replace( ' ', '_', $fragment );
573 $fragment = urlencode( Sanitizer::decodeCharReferences( $fragment ) );
574 $replaceArray = array(
575 '%3A' => ':',
576 '%' => '.'
577 );
578 return strtr( $fragment, $replaceArray );
579 }
580
581 #----------------------------------------------------------------------------
582 # Other stuff
583 #----------------------------------------------------------------------------
584
585 /** Simple accessors */
586 /**
587 * Get the text form (spaces not underscores) of the main part
588 * @return string
589 * @access public
590 */
591 function getText() { return $this->mTextform; }
592 /**
593 * Get the URL-encoded form of the main part
594 * @return string
595 * @access public
596 */
597 function getPartialURL() { return $this->mUrlform; }
598 /**
599 * Get the main part with underscores
600 * @return string
601 * @access public
602 */
603 function getDBkey() { return $this->mDbkeyform; }
604 /**
605 * Get the namespace index, i.e. one of the NS_xxxx constants
606 * @return int
607 * @access public
608 */
609 function getNamespace() { return $this->mNamespace; }
610 /**
611 * Get the namespace text
612 * @return string
613 * @access public
614 */
615 function getNsText() {
616 global $wgContLang, $wgCanonicalNamespaceNames;
617
618 if ( '' != $this->mInterwiki ) {
619 // This probably shouldn't even happen. ohh man, oh yuck.
620 // But for interwiki transclusion it sometimes does.
621 // Shit. Shit shit shit.
622 //
623 // Use the canonical namespaces if possible to try to
624 // resolve a foreign namespace.
625 if( isset( $wgCanonicalNamespaceNames[$this->mNamespace] ) ) {
626 return $wgCanonicalNamespaceNames[$this->mNamespace];
627 }
628 }
629 return $wgContLang->getNsText( $this->mNamespace );
630 }
631 /**
632 * Get the namespace text of the subject (rather than talk) page
633 * @return string
634 * @access public
635 */
636 function getSubjectNsText() {
637 global $wgContLang;
638 return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace ) );
639 }
640
641 /**
642 * Get the namespace text of the talk page
643 * @return string
644 */
645 function getTalkNsText() {
646 global $wgContLang;
647 return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace ) ) );
648 }
649
650 /**
651 * Could this title have a corresponding talk page?
652 * @return bool
653 */
654 function canTalk() {
655 return( Namespace::canTalk( $this->mNamespace ) );
656 }
657
658 /**
659 * Get the interwiki prefix (or null string)
660 * @return string
661 * @access public
662 */
663 function getInterwiki() { return $this->mInterwiki; }
664 /**
665 * Get the Title fragment (i.e. the bit after the #) in text form
666 * @return string
667 * @access public
668 */
669 function getFragment() { return $this->mFragment; }
670 /**
671 * Get the fragment in URL form, including the "#" character if there is one
672 *
673 * @return string
674 * @access public
675 */
676 function getFragmentForURL() {
677 if ( $this->mFragment == '' ) {
678 return '';
679 } else {
680 return '#' . Title::escapeFragmentForURL( $this->mFragment );
681 }
682 }
683 /**
684 * Get the default namespace index, for when there is no namespace
685 * @return int
686 * @access public
687 */
688 function getDefaultNamespace() { return $this->mDefaultNamespace; }
689
690 /**
691 * Get title for search index
692 * @return string a stripped-down title string ready for the
693 * search index
694 */
695 function getIndexTitle() {
696 return Title::indexTitle( $this->mNamespace, $this->mTextform );
697 }
698
699 /**
700 * Get the prefixed database key form
701 * @return string the prefixed title, with underscores and
702 * any interwiki and namespace prefixes
703 * @access public
704 */
705 function getPrefixedDBkey() {
706 $s = $this->prefix( $this->mDbkeyform );
707 $s = str_replace( ' ', '_', $s );
708 return $s;
709 }
710
711 /**
712 * Get the prefixed title with spaces.
713 * This is the form usually used for display
714 * @return string the prefixed title, with spaces
715 * @access public
716 */
717 function getPrefixedText() {
718 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
719 $s = $this->prefix( $this->mTextform );
720 $s = str_replace( '_', ' ', $s );
721 $this->mPrefixedText = $s;
722 }
723 return $this->mPrefixedText;
724 }
725
726 /**
727 * Get the prefixed title with spaces, plus any fragment
728 * (part beginning with '#')
729 * @return string the prefixed title, with spaces and
730 * the fragment, including '#'
731 * @access public
732 */
733 function getFullText() {
734 $text = $this->getPrefixedText();
735 if( '' != $this->mFragment ) {
736 $text .= '#' . $this->mFragment;
737 }
738 return $text;
739 }
740
741 /**
742 * Get the base name, i.e. the leftmost parts before the /
743 * @return string Base name
744 */
745 function getBaseText() {
746 global $wgNamespacesWithSubpages;
747 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
748 $parts = explode( '/', $this->getText() );
749 # Don't discard the real title if there's no subpage involved
750 if( count( $parts ) > 1 )
751 unset( $parts[ count( $parts ) - 1 ] );
752 return implode( '/', $parts );
753 } else {
754 return $this->getText();
755 }
756 }
757
758 /**
759 * Get the lowest-level subpage name, i.e. the rightmost part after /
760 * @return string Subpage name
761 */
762 function getSubpageText() {
763 global $wgNamespacesWithSubpages;
764 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
765 $parts = explode( '/', $this->mTextform );
766 return( $parts[ count( $parts ) - 1 ] );
767 } else {
768 return( $this->mTextform );
769 }
770 }
771
772 /**
773 * Get a URL-encoded form of the subpage text
774 * @return string URL-encoded subpage name
775 */
776 function getSubpageUrlForm() {
777 $text = $this->getSubpageText();
778 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
779 $text = str_replace( '%28', '(', str_replace( '%29', ')', $text ) ); # Clean up the URL; per below, this might not be safe
780 return( $text );
781 }
782
783 /**
784 * Get a URL-encoded title (not an actual URL) including interwiki
785 * @return string the URL-encoded form
786 * @access public
787 */
788 function getPrefixedURL() {
789 $s = $this->prefix( $this->mDbkeyform );
790 $s = str_replace( ' ', '_', $s );
791
792 $s = wfUrlencode ( $s ) ;
793
794 # Cleaning up URL to make it look nice -- is this safe?
795 $s = str_replace( '%28', '(', $s );
796 $s = str_replace( '%29', ')', $s );
797
798 return $s;
799 }
800
801 /**
802 * Get a real URL referring to this title, with interwiki link and
803 * fragment
804 *
805 * @param string $query an optional query string, not used
806 * for interwiki links
807 * @param string $variant language variant of url (for sr, zh..)
808 * @return string the URL
809 * @access public
810 */
811 function getFullURL( $query = '', $variant = false ) {
812 global $wgContLang, $wgServer, $wgRequest;
813
814 if ( '' == $this->mInterwiki ) {
815 $url = $this->getLocalUrl( $query, $variant );
816
817 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
818 // Correct fix would be to move the prepending elsewhere.
819 if ($wgRequest->getVal('action') != 'render') {
820 $url = $wgServer . $url;
821 }
822 } else {
823 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
824
825 $namespace = wfUrlencode( $this->getNsText() );
826 if ( '' != $namespace ) {
827 # Can this actually happen? Interwikis shouldn't be parsed.
828 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
829 $namespace .= ':';
830 }
831 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
832 if( $query != '' ) {
833 if( false === strpos( $url, '?' ) ) {
834 $url .= '?';
835 } else {
836 $url .= '&';
837 }
838 $url .= $query;
839 }
840 }
841
842 # Finally, add the fragment.
843 $url .= $this->getFragmentForURL();
844
845 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
846 return $url;
847 }
848
849 /**
850 * Get a URL with no fragment or server name. If this page is generated
851 * with action=render, $wgServer is prepended.
852 * @param string $query an optional query string; if not specified,
853 * $wgArticlePath will be used.
854 * @param string $variant language variant of url (for sr, zh..)
855 * @return string the URL
856 * @access public
857 */
858 function getLocalURL( $query = '', $variant = false ) {
859 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
860 global $wgVariantArticlePath, $wgContLang, $wgUser;
861
862 // internal links should point to same variant as current page (only anonymous users)
863 if($variant == false && $wgContLang->hasVariants() && !$wgUser->isLoggedIn()){
864 $pref = $wgContLang->getPreferredVariant(false);
865 if($pref != $wgContLang->getCode())
866 $variant = $pref;
867 }
868
869 if ( $this->isExternal() ) {
870 $url = $this->getFullURL();
871 if ( $query ) {
872 // This is currently only used for edit section links in the
873 // context of interwiki transclusion. In theory we should
874 // append the query to the end of any existing query string,
875 // but interwiki transclusion is already broken in that case.
876 $url .= "?$query";
877 }
878 } else {
879 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
880 if ( $query == '' ) {
881 if($variant!=false && $wgContLang->hasVariants()){
882 if($wgVariantArticlePath==false)
883 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
884 else
885 $variantArticlePath = $wgVariantArticlePath;
886
887 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
888 $url = str_replace( '$1', $dbkey, $url );
889
890 }
891 else
892 $url = str_replace( '$1', $dbkey, $wgArticlePath );
893 } else {
894 global $wgActionPaths;
895 $url = false;
896 $matches = array();
897 if( !empty( $wgActionPaths ) &&
898 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
899 {
900 $action = urldecode( $matches[2] );
901 if( isset( $wgActionPaths[$action] ) ) {
902 $query = $matches[1];
903 if( isset( $matches[4] ) ) $query .= $matches[4];
904 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
905 if( $query != '' ) $url .= '?' . $query;
906 }
907 }
908 if ( $url === false ) {
909 if ( $query == '-' ) {
910 $query = '';
911 }
912 $url = "{$wgScript}?title={$dbkey}&{$query}";
913 }
914 }
915
916 // FIXME: this causes breakage in various places when we
917 // actually expected a local URL and end up with dupe prefixes.
918 if ($wgRequest->getVal('action') == 'render') {
919 $url = $wgServer . $url;
920 }
921 }
922 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
923 return $url;
924 }
925
926 /**
927 * Get an HTML-escaped version of the URL form, suitable for
928 * using in a link, without a server name or fragment
929 * @param string $query an optional query string
930 * @return string the URL
931 * @access public
932 */
933 function escapeLocalURL( $query = '' ) {
934 return htmlspecialchars( $this->getLocalURL( $query ) );
935 }
936
937 /**
938 * Get an HTML-escaped version of the URL form, suitable for
939 * using in a link, including the server name and fragment
940 *
941 * @return string the URL
942 * @param string $query an optional query string
943 * @access public
944 */
945 function escapeFullURL( $query = '' ) {
946 return htmlspecialchars( $this->getFullURL( $query ) );
947 }
948
949 /**
950 * Get the URL form for an internal link.
951 * - Used in various Squid-related code, in case we have a different
952 * internal hostname for the server from the exposed one.
953 *
954 * @param string $query an optional query string
955 * @param string $variant language variant of url (for sr, zh..)
956 * @return string the URL
957 * @access public
958 */
959 function getInternalURL( $query = '', $variant = false ) {
960 global $wgInternalServer;
961 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
962 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
963 return $url;
964 }
965
966 /**
967 * Get the edit URL for this Title
968 * @return string the URL, or a null string if this is an
969 * interwiki link
970 * @access public
971 */
972 function getEditURL() {
973 if ( '' != $this->mInterwiki ) { return ''; }
974 $s = $this->getLocalURL( 'action=edit' );
975
976 return $s;
977 }
978
979 /**
980 * Get the HTML-escaped displayable text form.
981 * Used for the title field in <a> tags.
982 * @return string the text, including any prefixes
983 * @access public
984 */
985 function getEscapedText() {
986 return htmlspecialchars( $this->getPrefixedText() );
987 }
988
989 /**
990 * Is this Title interwiki?
991 * @return boolean
992 * @access public
993 */
994 function isExternal() { return ( '' != $this->mInterwiki ); }
995
996 /**
997 * Is this page "semi-protected" - the *only* protection is autoconfirm?
998 *
999 * @param string Action to check (default: edit)
1000 * @return bool
1001 */
1002 function isSemiProtected( $action = 'edit' ) {
1003 if( $this->exists() ) {
1004 $restrictions = $this->getRestrictions( $action );
1005 if( count( $restrictions ) > 0 ) {
1006 foreach( $restrictions as $restriction ) {
1007 if( strtolower( $restriction ) != 'autoconfirmed' )
1008 return false;
1009 }
1010 } else {
1011 # Not protected
1012 return false;
1013 }
1014 return true;
1015 } else {
1016 # If it doesn't exist, it can't be protected
1017 return false;
1018 }
1019 }
1020
1021 /**
1022 * Does the title correspond to a protected article?
1023 * @param string $what the action the page is protected from,
1024 * by default checks move and edit
1025 * @return boolean
1026 * @access public
1027 */
1028 function isProtected( $action = '' ) {
1029 global $wgRestrictionLevels;
1030 if ( NS_SPECIAL == $this->mNamespace ) { return true; }
1031
1032 if( $action == 'edit' || $action == '' ) {
1033 $r = $this->getRestrictions( 'edit' );
1034 foreach( $wgRestrictionLevels as $level ) {
1035 if( in_array( $level, $r ) && $level != '' ) {
1036 return( true );
1037 }
1038 }
1039 }
1040
1041 if( $action == 'move' || $action == '' ) {
1042 $r = $this->getRestrictions( 'move' );
1043 foreach( $wgRestrictionLevels as $level ) {
1044 if( in_array( $level, $r ) && $level != '' ) {
1045 return( true );
1046 }
1047 }
1048 }
1049
1050 return false;
1051 }
1052
1053 /**
1054 * Is $wgUser is watching this page?
1055 * @return boolean
1056 * @access public
1057 */
1058 function userIsWatching() {
1059 global $wgUser;
1060
1061 if ( is_null( $this->mWatched ) ) {
1062 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) {
1063 $this->mWatched = false;
1064 } else {
1065 $this->mWatched = $wgUser->isWatched( $this );
1066 }
1067 }
1068 return $this->mWatched;
1069 }
1070
1071 /**
1072 * Can $wgUser perform $action this page?
1073 * @param string $action action that permission needs to be checked for
1074 * @return boolean
1075 * @private
1076 */
1077 function userCan($action) {
1078 $fname = 'Title::userCan';
1079 wfProfileIn( $fname );
1080
1081 global $wgUser;
1082
1083 $result = null;
1084 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
1085 if ( $result !== null ) {
1086 wfProfileOut( $fname );
1087 return $result;
1088 }
1089
1090 if( NS_SPECIAL == $this->mNamespace ) {
1091 wfProfileOut( $fname );
1092 return false;
1093 }
1094 // XXX: This is the code that prevents unprotecting a page in NS_MEDIAWIKI
1095 // from taking effect -ævar
1096 if( NS_MEDIAWIKI == $this->mNamespace &&
1097 !$wgUser->isAllowed('editinterface') ) {
1098 wfProfileOut( $fname );
1099 return false;
1100 }
1101
1102 if( $this->mDbkeyform == '_' ) {
1103 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1104 wfProfileOut( $fname );
1105 return false;
1106 }
1107
1108 # protect css/js subpages of user pages
1109 # XXX: this might be better using restrictions
1110 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1111 if( $this->isCssJsSubpage()
1112 && !$wgUser->isAllowed('editinterface')
1113 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
1114 wfProfileOut( $fname );
1115 return false;
1116 }
1117
1118 foreach( $this->getRestrictions($action) as $right ) {
1119 // Backwards compatibility, rewrite sysop -> protect
1120 if ( $right == 'sysop' ) {
1121 $right = 'protect';
1122 }
1123 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1124 wfProfileOut( $fname );
1125 return false;
1126 }
1127 }
1128
1129 if( $action == 'move' &&
1130 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1131 wfProfileOut( $fname );
1132 return false;
1133 }
1134
1135 if( $action == 'create' ) {
1136 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1137 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1138 wfProfileOut( $fname );
1139 return false;
1140 }
1141 }
1142
1143 wfProfileOut( $fname );
1144 return true;
1145 }
1146
1147 /**
1148 * Can $wgUser edit this page?
1149 * @return boolean
1150 * @access public
1151 */
1152 function userCanEdit() {
1153 return $this->userCan('edit');
1154 }
1155
1156 /**
1157 * Can $wgUser create this page?
1158 * @return boolean
1159 * @access public
1160 */
1161 function userCanCreate() {
1162 return $this->userCan('create');
1163 }
1164
1165 /**
1166 * Can $wgUser move this page?
1167 * @return boolean
1168 * @access public
1169 */
1170 function userCanMove() {
1171 return $this->userCan('move');
1172 }
1173
1174 /**
1175 * Would anybody with sufficient privileges be able to move this page?
1176 * Some pages just aren't movable.
1177 *
1178 * @return boolean
1179 * @access public
1180 */
1181 function isMovable() {
1182 return Namespace::isMovable( $this->getNamespace() )
1183 && $this->getInterwiki() == '';
1184 }
1185
1186 /**
1187 * Can $wgUser read this page?
1188 * @return boolean
1189 * @access public
1190 */
1191 function userCanRead() {
1192 global $wgUser;
1193
1194 $result = null;
1195 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1196 if ( $result !== null ) {
1197 return $result;
1198 }
1199
1200 if( $wgUser->isAllowed('read') ) {
1201 return true;
1202 } else {
1203 global $wgWhitelistRead;
1204
1205 /**
1206 * Always grant access to the login page.
1207 * Even anons need to be able to log in.
1208 */
1209 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1210 return true;
1211 }
1212
1213 /** some pages are explicitly allowed */
1214 $name = $this->getPrefixedText();
1215 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1216 return true;
1217 }
1218
1219 # Compatibility with old settings
1220 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
1221 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1222 return true;
1223 }
1224 }
1225 }
1226 return false;
1227 }
1228
1229 /**
1230 * Is this a talk page of some sort?
1231 * @return bool
1232 * @access public
1233 */
1234 function isTalkPage() {
1235 return Namespace::isTalk( $this->getNamespace() );
1236 }
1237
1238 /**
1239 * Is this a subpage?
1240 * @return bool
1241 * @access public
1242 */
1243 function isSubpage() {
1244 global $wgNamespacesWithSubpages;
1245
1246 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) ) {
1247 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace ] == true );
1248 } else {
1249 return false;
1250 }
1251 }
1252
1253 /**
1254 * Is this a .css or .js subpage of a user page?
1255 * @return bool
1256 * @access public
1257 */
1258 function isCssJsSubpage() {
1259 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(css|js)$/", $this->mTextform ) );
1260 }
1261 /**
1262 * Is this a *valid* .css or .js subpage of a user page?
1263 * Check that the corresponding skin exists
1264 */
1265 function isValidCssJsSubpage() {
1266 if ( $this->isCssJsSubpage() ) {
1267 $skinNames = Skin::getSkinNames();
1268 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1269 } else {
1270 return false;
1271 }
1272 }
1273 /**
1274 * Trim down a .css or .js subpage title to get the corresponding skin name
1275 */
1276 function getSkinFromCssJsSubpage() {
1277 $subpage = explode( '/', $this->mTextform );
1278 $subpage = $subpage[ count( $subpage ) - 1 ];
1279 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1280 }
1281 /**
1282 * Is this a .css subpage of a user page?
1283 * @return bool
1284 * @access public
1285 */
1286 function isCssSubpage() {
1287 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1288 }
1289 /**
1290 * Is this a .js subpage of a user page?
1291 * @return bool
1292 * @access public
1293 */
1294 function isJsSubpage() {
1295 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1296 }
1297 /**
1298 * Protect css/js subpages of user pages: can $wgUser edit
1299 * this page?
1300 *
1301 * @return boolean
1302 * @todo XXX: this might be better using restrictions
1303 * @access public
1304 */
1305 function userCanEditCssJsSubpage() {
1306 global $wgUser;
1307 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1308 }
1309
1310 /**
1311 * Loads a string into mRestrictions array
1312 * @param string $res restrictions in string format
1313 * @access public
1314 */
1315 function loadRestrictions( $res ) {
1316 $this->mRestrictions['edit'] = array();
1317 $this->mRestrictions['move'] = array();
1318
1319 if( !$res ) {
1320 # No restrictions (page_restrictions blank)
1321 $this->mRestrictionsLoaded = true;
1322 return;
1323 }
1324
1325 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1326 $temp = explode( '=', trim( $restrict ) );
1327 if(count($temp) == 1) {
1328 // old format should be treated as edit/move restriction
1329 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1330 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1331 } else {
1332 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1333 }
1334 }
1335 $this->mRestrictionsLoaded = true;
1336 }
1337
1338 /**
1339 * Accessor/initialisation for mRestrictions
1340 *
1341 * @access public
1342 * @param string $action action that permission needs to be checked for
1343 * @return array the array of groups allowed to edit this article
1344 */
1345 function getRestrictions( $action ) {
1346 if( $this->exists() ) {
1347 if( !$this->mRestrictionsLoaded ) {
1348 $dbr =& wfGetDB( DB_SLAVE );
1349 $res = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ) );
1350 $this->loadRestrictions( $res );
1351 }
1352 return isset( $this->mRestrictions[$action] )
1353 ? $this->mRestrictions[$action]
1354 : array();
1355 } else {
1356 return array();
1357 }
1358 }
1359
1360 /**
1361 * Is there a version of this page in the deletion archive?
1362 * @return int the number of archived revisions
1363 * @access public
1364 */
1365 function isDeleted() {
1366 $fname = 'Title::isDeleted';
1367 if ( $this->getNamespace() < 0 ) {
1368 $n = 0;
1369 } else {
1370 $dbr =& wfGetDB( DB_SLAVE );
1371 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1372 'ar_title' => $this->getDBkey() ), $fname );
1373 if( $this->getNamespace() == NS_IMAGE ) {
1374 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1375 array( 'fa_name' => $this->getDBkey() ), $fname );
1376 }
1377 }
1378 return (int)$n;
1379 }
1380
1381 /**
1382 * Get the article ID for this Title from the link cache,
1383 * adding it if necessary
1384 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1385 * for update
1386 * @return int the ID
1387 */
1388 public function getArticleID( $flags = 0 ) {
1389 $linkCache =& LinkCache::singleton();
1390 if ( $flags & GAID_FOR_UPDATE ) {
1391 $oldUpdate = $linkCache->forUpdate( true );
1392 $this->mArticleID = $linkCache->addLinkObj( $this );
1393 $linkCache->forUpdate( $oldUpdate );
1394 } else {
1395 if ( -1 == $this->mArticleID ) {
1396 $this->mArticleID = $linkCache->addLinkObj( $this );
1397 }
1398 }
1399 return $this->mArticleID;
1400 }
1401
1402 function getLatestRevID() {
1403 if ($this->mLatestID !== false)
1404 return $this->mLatestID;
1405
1406 $db =& wfGetDB(DB_SLAVE);
1407 return $this->mLatestID = $db->selectField( 'revision',
1408 "max(rev_id)",
1409 array('rev_page' => $this->getArticleID()),
1410 'Title::getLatestRevID' );
1411 }
1412
1413 /**
1414 * This clears some fields in this object, and clears any associated
1415 * keys in the "bad links" section of the link cache.
1416 *
1417 * - This is called from Article::insertNewArticle() to allow
1418 * loading of the new page_id. It's also called from
1419 * Article::doDeleteArticle()
1420 *
1421 * @param int $newid the new Article ID
1422 * @access public
1423 */
1424 function resetArticleID( $newid ) {
1425 $linkCache =& LinkCache::singleton();
1426 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1427
1428 if ( 0 == $newid ) { $this->mArticleID = -1; }
1429 else { $this->mArticleID = $newid; }
1430 $this->mRestrictionsLoaded = false;
1431 $this->mRestrictions = array();
1432 }
1433
1434 /**
1435 * Updates page_touched for this page; called from LinksUpdate.php
1436 * @return bool true if the update succeded
1437 * @access public
1438 */
1439 function invalidateCache() {
1440 global $wgUseFileCache;
1441
1442 if ( wfReadOnly() ) {
1443 return;
1444 }
1445
1446 $dbw =& wfGetDB( DB_MASTER );
1447 $success = $dbw->update( 'page',
1448 array( /* SET */
1449 'page_touched' => $dbw->timestamp()
1450 ), array( /* WHERE */
1451 'page_namespace' => $this->getNamespace() ,
1452 'page_title' => $this->getDBkey()
1453 ), 'Title::invalidateCache'
1454 );
1455
1456 if ($wgUseFileCache) {
1457 $cache = new HTMLFileCache($this);
1458 @unlink($cache->fileCacheName());
1459 }
1460
1461 return $success;
1462 }
1463
1464 /**
1465 * Prefix some arbitrary text with the namespace or interwiki prefix
1466 * of this object
1467 *
1468 * @param string $name the text
1469 * @return string the prefixed text
1470 * @private
1471 */
1472 /* private */ function prefix( $name ) {
1473 $p = '';
1474 if ( '' != $this->mInterwiki ) {
1475 $p = $this->mInterwiki . ':';
1476 }
1477 if ( 0 != $this->mNamespace ) {
1478 $p .= $this->getNsText() . ':';
1479 }
1480 return $p . $name;
1481 }
1482
1483 /**
1484 * Secure and split - main initialisation function for this object
1485 *
1486 * Assumes that mDbkeyform has been set, and is urldecoded
1487 * and uses underscores, but not otherwise munged. This function
1488 * removes illegal characters, splits off the interwiki and
1489 * namespace prefixes, sets the other forms, and canonicalizes
1490 * everything.
1491 * @return bool true on success
1492 * @private
1493 */
1494 /* private */ function secureAndSplit() {
1495 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1496
1497 # Initialisation
1498 static $rxTc = false;
1499 if( !$rxTc ) {
1500 # % is needed as well
1501 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1502 }
1503
1504 $this->mInterwiki = $this->mFragment = '';
1505 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1506
1507 $dbkey = $this->mDbkeyform;
1508
1509 # Strip Unicode bidi override characters.
1510 # Sometimes they slip into cut-n-pasted page titles, where the
1511 # override chars get included in list displays.
1512 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1513 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1514
1515 # Clean up whitespace
1516 #
1517 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1518 $dbkey = trim( $dbkey, '_' );
1519
1520 if ( '' == $dbkey ) {
1521 return false;
1522 }
1523
1524 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
1525 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1526 return false;
1527 }
1528
1529 $this->mDbkeyform = $dbkey;
1530
1531 # Initial colon indicates main namespace rather than specified default
1532 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1533 if ( ':' == $dbkey{0} ) {
1534 $this->mNamespace = NS_MAIN;
1535 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1536 }
1537
1538 # Namespace or interwiki prefix
1539 $firstPass = true;
1540 do {
1541 $m = array();
1542 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1543 $p = $m[1];
1544 $lowerNs = $wgContLang->lc( $p );
1545 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1546 # Canonical namespace
1547 $dbkey = $m[2];
1548 $this->mNamespace = $ns;
1549 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1550 # Ordinary namespace
1551 $dbkey = $m[2];
1552 $this->mNamespace = $ns;
1553 } elseif( $this->getInterwikiLink( $p ) ) {
1554 if( !$firstPass ) {
1555 # Can't make a local interwiki link to an interwiki link.
1556 # That's just crazy!
1557 return false;
1558 }
1559
1560 # Interwiki link
1561 $dbkey = $m[2];
1562 $this->mInterwiki = $wgContLang->lc( $p );
1563
1564 # Redundant interwiki prefix to the local wiki
1565 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1566 if( $dbkey == '' ) {
1567 # Can't have an empty self-link
1568 return false;
1569 }
1570 $this->mInterwiki = '';
1571 $firstPass = false;
1572 # Do another namespace split...
1573 continue;
1574 }
1575
1576 # If there's an initial colon after the interwiki, that also
1577 # resets the default namespace
1578 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1579 $this->mNamespace = NS_MAIN;
1580 $dbkey = substr( $dbkey, 1 );
1581 }
1582 }
1583 # If there's no recognized interwiki or namespace,
1584 # then let the colon expression be part of the title.
1585 }
1586 break;
1587 } while( true );
1588
1589 # We already know that some pages won't be in the database!
1590 #
1591 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
1592 $this->mArticleID = 0;
1593 }
1594 $fragment = strstr( $dbkey, '#' );
1595 if ( false !== $fragment ) {
1596 $this->setFragment( $fragment );
1597 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1598 # remove whitespace again: prevents "Foo_bar_#"
1599 # becoming "Foo_bar_"
1600 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1601 }
1602
1603 # Reject illegal characters.
1604 #
1605 if( preg_match( $rxTc, $dbkey ) ) {
1606 return false;
1607 }
1608
1609 /**
1610 * Pages with "/./" or "/../" appearing in the URLs will
1611 * often be unreachable due to the way web browsers deal
1612 * with 'relative' URLs. Forbid them explicitly.
1613 */
1614 if ( strpos( $dbkey, '.' ) !== false &&
1615 ( $dbkey === '.' || $dbkey === '..' ||
1616 strpos( $dbkey, './' ) === 0 ||
1617 strpos( $dbkey, '../' ) === 0 ||
1618 strpos( $dbkey, '/./' ) !== false ||
1619 strpos( $dbkey, '/../' ) !== false ) )
1620 {
1621 return false;
1622 }
1623
1624 /**
1625 * Limit the size of titles to 255 bytes.
1626 * This is typically the size of the underlying database field.
1627 * We make an exception for special pages, which don't need to be stored
1628 * in the database, and may edge over 255 bytes due to subpage syntax
1629 * for long titles, e.g. [[Special:Block/Long name]]
1630 */
1631 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
1632 strlen( $dbkey ) > 512 )
1633 {
1634 return false;
1635 }
1636
1637 /**
1638 * Normally, all wiki links are forced to have
1639 * an initial capital letter so [[foo]] and [[Foo]]
1640 * point to the same place.
1641 *
1642 * Don't force it for interwikis, since the other
1643 * site might be case-sensitive.
1644 */
1645 if( $wgCapitalLinks && $this->mInterwiki == '') {
1646 $dbkey = $wgContLang->ucfirst( $dbkey );
1647 }
1648
1649 /**
1650 * Can't make a link to a namespace alone...
1651 * "empty" local links can only be self-links
1652 * with a fragment identifier.
1653 */
1654 if( $dbkey == '' &&
1655 $this->mInterwiki == '' &&
1656 $this->mNamespace != NS_MAIN ) {
1657 return false;
1658 }
1659
1660 // Any remaining initial :s are illegal.
1661 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1662 return false;
1663 }
1664
1665 # Fill fields
1666 $this->mDbkeyform = $dbkey;
1667 $this->mUrlform = wfUrlencode( $dbkey );
1668
1669 $this->mTextform = str_replace( '_', ' ', $dbkey );
1670
1671 return true;
1672 }
1673
1674 /**
1675 * Set the fragment for this title
1676 * This is kind of bad, since except for this rarely-used function, Title objects
1677 * are immutable. The reason this is here is because it's better than setting the
1678 * members directly, which is what Linker::formatComment was doing previously.
1679 *
1680 * @param string $fragment text
1681 * @access kind of public
1682 */
1683 function setFragment( $fragment ) {
1684 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1685 }
1686
1687 /**
1688 * Get a Title object associated with the talk page of this article
1689 * @return Title the object for the talk page
1690 * @access public
1691 */
1692 function getTalkPage() {
1693 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1694 }
1695
1696 /**
1697 * Get a title object associated with the subject page of this
1698 * talk page
1699 *
1700 * @return Title the object for the subject page
1701 * @access public
1702 */
1703 function getSubjectPage() {
1704 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1705 }
1706
1707 /**
1708 * Get an array of Title objects linking to this Title
1709 * Also stores the IDs in the link cache.
1710 *
1711 * WARNING: do not use this function on arbitrary user-supplied titles!
1712 * On heavily-used templates it will max out the memory.
1713 *
1714 * @param string $options may be FOR UPDATE
1715 * @return array the Title objects linking here
1716 * @access public
1717 */
1718 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1719 $linkCache =& LinkCache::singleton();
1720
1721 if ( $options ) {
1722 $db =& wfGetDB( DB_MASTER );
1723 } else {
1724 $db =& wfGetDB( DB_SLAVE );
1725 }
1726
1727 $res = $db->select( array( 'page', $table ),
1728 array( 'page_namespace', 'page_title', 'page_id' ),
1729 array(
1730 "{$prefix}_from=page_id",
1731 "{$prefix}_namespace" => $this->getNamespace(),
1732 "{$prefix}_title" => $this->getDbKey() ),
1733 'Title::getLinksTo',
1734 $options );
1735
1736 $retVal = array();
1737 if ( $db->numRows( $res ) ) {
1738 while ( $row = $db->fetchObject( $res ) ) {
1739 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1740 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1741 $retVal[] = $titleObj;
1742 }
1743 }
1744 }
1745 $db->freeResult( $res );
1746 return $retVal;
1747 }
1748
1749 /**
1750 * Get an array of Title objects using this Title as a template
1751 * Also stores the IDs in the link cache.
1752 *
1753 * WARNING: do not use this function on arbitrary user-supplied titles!
1754 * On heavily-used templates it will max out the memory.
1755 *
1756 * @param string $options may be FOR UPDATE
1757 * @return array the Title objects linking here
1758 * @access public
1759 */
1760 function getTemplateLinksTo( $options = '' ) {
1761 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1762 }
1763
1764 /**
1765 * Get an array of Title objects referring to non-existent articles linked from this page
1766 *
1767 * @param string $options may be FOR UPDATE
1768 * @return array the Title objects
1769 * @access public
1770 */
1771 function getBrokenLinksFrom( $options = '' ) {
1772 if ( $options ) {
1773 $db =& wfGetDB( DB_MASTER );
1774 } else {
1775 $db =& wfGetDB( DB_SLAVE );
1776 }
1777
1778 $res = $db->safeQuery(
1779 "SELECT pl_namespace, pl_title
1780 FROM !
1781 LEFT JOIN !
1782 ON pl_namespace=page_namespace
1783 AND pl_title=page_title
1784 WHERE pl_from=?
1785 AND page_namespace IS NULL
1786 !",
1787 $db->tableName( 'pagelinks' ),
1788 $db->tableName( 'page' ),
1789 $this->getArticleId(),
1790 $options );
1791
1792 $retVal = array();
1793 if ( $db->numRows( $res ) ) {
1794 while ( $row = $db->fetchObject( $res ) ) {
1795 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
1796 }
1797 }
1798 $db->freeResult( $res );
1799 return $retVal;
1800 }
1801
1802
1803 /**
1804 * Get a list of URLs to purge from the Squid cache when this
1805 * page changes
1806 *
1807 * @return array the URLs
1808 * @access public
1809 */
1810 function getSquidURLs() {
1811 global $wgContLang;
1812
1813 $urls = array(
1814 $this->getInternalURL(),
1815 $this->getInternalURL( 'action=history' )
1816 );
1817
1818 // purge variant urls as well
1819 if($wgContLang->hasVariants()){
1820 $variants = $wgContLang->getVariants();
1821 foreach($variants as $vCode){
1822 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
1823 $urls[] = $this->getInternalURL('',$vCode);
1824 }
1825 }
1826
1827 return $urls;
1828 }
1829
1830 function purgeSquid() {
1831 global $wgUseSquid;
1832 if ( $wgUseSquid ) {
1833 $urls = $this->getSquidURLs();
1834 $u = new SquidUpdate( $urls );
1835 $u->doUpdate();
1836 }
1837 }
1838
1839 /**
1840 * Move this page without authentication
1841 * @param Title &$nt the new page Title
1842 * @access public
1843 */
1844 function moveNoAuth( &$nt ) {
1845 return $this->moveTo( $nt, false );
1846 }
1847
1848 /**
1849 * Check whether a given move operation would be valid.
1850 * Returns true if ok, or a message key string for an error message
1851 * if invalid. (Scarrrrry ugly interface this.)
1852 * @param Title &$nt the new title
1853 * @param bool $auth indicates whether $wgUser's permissions
1854 * should be checked
1855 * @return mixed true on success, message name on failure
1856 * @access public
1857 */
1858 function isValidMoveOperation( &$nt, $auth = true ) {
1859 if( !$this or !$nt ) {
1860 return 'badtitletext';
1861 }
1862 if( $this->equals( $nt ) ) {
1863 return 'selfmove';
1864 }
1865 if( !$this->isMovable() || !$nt->isMovable() ) {
1866 return 'immobile_namespace';
1867 }
1868
1869 $oldid = $this->getArticleID();
1870 $newid = $nt->getArticleID();
1871
1872 if ( strlen( $nt->getDBkey() ) < 1 ) {
1873 return 'articleexists';
1874 }
1875 if ( ( '' == $this->getDBkey() ) ||
1876 ( !$oldid ) ||
1877 ( '' == $nt->getDBkey() ) ) {
1878 return 'badarticleerror';
1879 }
1880
1881 if ( $auth && (
1882 !$this->userCanEdit() || !$nt->userCanEdit() ||
1883 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1884 return 'protectedpage';
1885 }
1886
1887 # The move is allowed only if (1) the target doesn't exist, or
1888 # (2) the target is a redirect to the source, and has no history
1889 # (so we can undo bad moves right after they're done).
1890
1891 if ( 0 != $newid ) { # Target exists; check for validity
1892 if ( ! $this->isValidMoveTarget( $nt ) ) {
1893 return 'articleexists';
1894 }
1895 }
1896 return true;
1897 }
1898
1899 /**
1900 * Move a title to a new location
1901 * @param Title &$nt the new title
1902 * @param bool $auth indicates whether $wgUser's permissions
1903 * should be checked
1904 * @return mixed true on success, message name on failure
1905 * @access public
1906 */
1907 function moveTo( &$nt, $auth = true, $reason = '' ) {
1908 $err = $this->isValidMoveOperation( $nt, $auth );
1909 if( is_string( $err ) ) {
1910 return $err;
1911 }
1912
1913 $pageid = $this->getArticleID();
1914 if( $nt->exists() ) {
1915 $this->moveOverExistingRedirect( $nt, $reason );
1916 $pageCountChange = 0;
1917 } else { # Target didn't exist, do normal move.
1918 $this->moveToNewTitle( $nt, $reason );
1919 $pageCountChange = 1;
1920 }
1921 $redirid = $this->getArticleID();
1922
1923 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1924 $dbw =& wfGetDB( DB_MASTER );
1925 $categorylinks = $dbw->tableName( 'categorylinks' );
1926 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1927 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
1928 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1929 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1930
1931 # Update watchlists
1932
1933 $oldnamespace = $this->getNamespace() & ~1;
1934 $newnamespace = $nt->getNamespace() & ~1;
1935 $oldtitle = $this->getDBkey();
1936 $newtitle = $nt->getDBkey();
1937
1938 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1939 WatchedItem::duplicateEntries( $this, $nt );
1940 }
1941
1942 # Update search engine
1943 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
1944 $u->doUpdate();
1945 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
1946 $u->doUpdate();
1947
1948 # Update site_stats
1949 if( $this->isContentPage() && !$nt->isContentPage() ) {
1950 # No longer a content page
1951 # Not viewed, edited, removing
1952 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
1953 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
1954 # Now a content page
1955 # Not viewed, edited, adding
1956 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
1957 } elseif( $pageCountChange ) {
1958 # Redirect added
1959 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
1960 } else {
1961 # Nothing special
1962 $u = false;
1963 }
1964 if( $u )
1965 $u->doUpdate();
1966
1967 global $wgUser;
1968 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
1969 return true;
1970 }
1971
1972 /**
1973 * Move page to a title which is at present a redirect to the
1974 * source page
1975 *
1976 * @param Title &$nt the page to move to, which should currently
1977 * be a redirect
1978 * @private
1979 */
1980 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1981 global $wgUseSquid;
1982 $fname = 'Title::moveOverExistingRedirect';
1983 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1984
1985 if ( $reason ) {
1986 $comment .= ": $reason";
1987 }
1988
1989 $now = wfTimestampNow();
1990 $newid = $nt->getArticleID();
1991 $oldid = $this->getArticleID();
1992 $dbw =& wfGetDB( DB_MASTER );
1993 $linkCache =& LinkCache::singleton();
1994
1995 # Delete the old redirect. We don't save it to history since
1996 # by definition if we've got here it's rather uninteresting.
1997 # We have to remove it so that the next step doesn't trigger
1998 # a conflict on the unique namespace+title index...
1999 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2000
2001 # Save a null revision in the page's history notifying of the move
2002 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2003 $nullRevId = $nullRevision->insertOn( $dbw );
2004
2005 # Change the name of the target page:
2006 $dbw->update( 'page',
2007 /* SET */ array(
2008 'page_touched' => $dbw->timestamp($now),
2009 'page_namespace' => $nt->getNamespace(),
2010 'page_title' => $nt->getDBkey(),
2011 'page_latest' => $nullRevId,
2012 ),
2013 /* WHERE */ array( 'page_id' => $oldid ),
2014 $fname
2015 );
2016 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2017
2018 # Recreate the redirect, this time in the other direction.
2019 $mwRedir = MagicWord::get( 'redirect' );
2020 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2021 $redirectArticle = new Article( $this );
2022 $newid = $redirectArticle->insertOn( $dbw );
2023 $redirectRevision = new Revision( array(
2024 'page' => $newid,
2025 'comment' => $comment,
2026 'text' => $redirectText ) );
2027 $redirectRevision->insertOn( $dbw );
2028 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2029 $linkCache->clearLink( $this->getPrefixedDBkey() );
2030
2031 # Log the move
2032 $log = new LogPage( 'move' );
2033 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2034
2035 # Now, we record the link from the redirect to the new title.
2036 # It should have no other outgoing links...
2037 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2038 $dbw->insert( 'pagelinks',
2039 array(
2040 'pl_from' => $newid,
2041 'pl_namespace' => $nt->getNamespace(),
2042 'pl_title' => $nt->getDbKey() ),
2043 $fname );
2044
2045 # Purge squid
2046 if ( $wgUseSquid ) {
2047 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2048 $u = new SquidUpdate( $urls );
2049 $u->doUpdate();
2050 }
2051 }
2052
2053 /**
2054 * Move page to non-existing title.
2055 * @param Title &$nt the new Title
2056 * @private
2057 */
2058 function moveToNewTitle( &$nt, $reason = '' ) {
2059 global $wgUseSquid;
2060 $fname = 'MovePageForm::moveToNewTitle';
2061 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2062 if ( $reason ) {
2063 $comment .= ": $reason";
2064 }
2065
2066 $newid = $nt->getArticleID();
2067 $oldid = $this->getArticleID();
2068 $dbw =& wfGetDB( DB_MASTER );
2069 $now = $dbw->timestamp();
2070 $linkCache =& LinkCache::singleton();
2071
2072 # Save a null revision in the page's history notifying of the move
2073 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2074 $nullRevId = $nullRevision->insertOn( $dbw );
2075
2076 # Rename cur entry
2077 $dbw->update( 'page',
2078 /* SET */ array(
2079 'page_touched' => $now,
2080 'page_namespace' => $nt->getNamespace(),
2081 'page_title' => $nt->getDBkey(),
2082 'page_latest' => $nullRevId,
2083 ),
2084 /* WHERE */ array( 'page_id' => $oldid ),
2085 $fname
2086 );
2087
2088 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2089
2090 # Insert redirect
2091 $mwRedir = MagicWord::get( 'redirect' );
2092 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2093 $redirectArticle = new Article( $this );
2094 $newid = $redirectArticle->insertOn( $dbw );
2095 $redirectRevision = new Revision( array(
2096 'page' => $newid,
2097 'comment' => $comment,
2098 'text' => $redirectText ) );
2099 $redirectRevision->insertOn( $dbw );
2100 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2101 $linkCache->clearLink( $this->getPrefixedDBkey() );
2102
2103 # Log the move
2104 $log = new LogPage( 'move' );
2105 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2106
2107 # Purge caches as per article creation
2108 Article::onArticleCreate( $nt );
2109
2110 # Record the just-created redirect's linking to the page
2111 $dbw->insert( 'pagelinks',
2112 array(
2113 'pl_from' => $newid,
2114 'pl_namespace' => $nt->getNamespace(),
2115 'pl_title' => $nt->getDBkey() ),
2116 $fname );
2117
2118 # Purge old title from squid
2119 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2120 $this->purgeSquid();
2121 }
2122
2123 /**
2124 * Checks if $this can be moved to a given Title
2125 * - Selects for update, so don't call it unless you mean business
2126 *
2127 * @param Title &$nt the new title to check
2128 * @access public
2129 */
2130 function isValidMoveTarget( $nt ) {
2131
2132 $fname = 'Title::isValidMoveTarget';
2133 $dbw =& wfGetDB( DB_MASTER );
2134
2135 # Is it a redirect?
2136 $id = $nt->getArticleID();
2137 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2138 array( 'page_is_redirect','old_text','old_flags' ),
2139 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2140 $fname, 'FOR UPDATE' );
2141
2142 if ( !$obj || 0 == $obj->page_is_redirect ) {
2143 # Not a redirect
2144 wfDebug( __METHOD__ . ": not a redirect\n" );
2145 return false;
2146 }
2147 $text = Revision::getRevisionText( $obj );
2148
2149 # Does the redirect point to the source?
2150 # Or is it a broken self-redirect, usually caused by namespace collisions?
2151 $m = array();
2152 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2153 $redirTitle = Title::newFromText( $m[1] );
2154 if( !is_object( $redirTitle ) ||
2155 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2156 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2157 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2158 return false;
2159 }
2160 } else {
2161 # Fail safe
2162 wfDebug( __METHOD__ . ": failsafe\n" );
2163 return false;
2164 }
2165
2166 # Does the article have a history?
2167 $row = $dbw->selectRow( array( 'page', 'revision'),
2168 array( 'rev_id' ),
2169 array( 'page_namespace' => $nt->getNamespace(),
2170 'page_title' => $nt->getDBkey(),
2171 'page_id=rev_page AND page_latest != rev_id'
2172 ), $fname, 'FOR UPDATE'
2173 );
2174
2175 # Return true if there was no history
2176 return $row === false;
2177 }
2178
2179 /**
2180 * Create a redirect; fails if the title already exists; does
2181 * not notify RC
2182 *
2183 * @param Title $dest the destination of the redirect
2184 * @param string $comment the comment string describing the move
2185 * @return bool true on success
2186 * @access public
2187 */
2188 function createRedirect( $dest, $comment ) {
2189 if ( $this->getArticleID() ) {
2190 return false;
2191 }
2192
2193 $fname = 'Title::createRedirect';
2194 $dbw =& wfGetDB( DB_MASTER );
2195
2196 $article = new Article( $this );
2197 $newid = $article->insertOn( $dbw );
2198 $revision = new Revision( array(
2199 'page' => $newid,
2200 'comment' => $comment,
2201 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
2202 ) );
2203 $revision->insertOn( $dbw );
2204 $article->updateRevisionOn( $dbw, $revision, 0 );
2205
2206 # Link table
2207 $dbw->insert( 'pagelinks',
2208 array(
2209 'pl_from' => $newid,
2210 'pl_namespace' => $dest->getNamespace(),
2211 'pl_title' => $dest->getDbKey()
2212 ), $fname
2213 );
2214
2215 Article::onArticleCreate( $this );
2216 return true;
2217 }
2218
2219 /**
2220 * Get categories to which this Title belongs and return an array of
2221 * categories' names.
2222 *
2223 * @return array an array of parents in the form:
2224 * $parent => $currentarticle
2225 * @access public
2226 */
2227 function getParentCategories() {
2228 global $wgContLang;
2229
2230 $titlekey = $this->getArticleId();
2231 $dbr =& wfGetDB( DB_SLAVE );
2232 $categorylinks = $dbr->tableName( 'categorylinks' );
2233
2234 # NEW SQL
2235 $sql = "SELECT * FROM $categorylinks"
2236 ." WHERE cl_from='$titlekey'"
2237 ." AND cl_from <> '0'"
2238 ." ORDER BY cl_sortkey";
2239
2240 $res = $dbr->query ( $sql ) ;
2241
2242 if($dbr->numRows($res) > 0) {
2243 while ( $x = $dbr->fetchObject ( $res ) )
2244 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2245 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
2246 $dbr->freeResult ( $res ) ;
2247 } else {
2248 $data = '';
2249 }
2250 return $data;
2251 }
2252
2253 /**
2254 * Get a tree of parent categories
2255 * @param array $children an array with the children in the keys, to check for circular refs
2256 * @return array
2257 * @access public
2258 */
2259 function getParentCategoryTree( $children = array() ) {
2260 $parents = $this->getParentCategories();
2261
2262 if($parents != '') {
2263 foreach($parents as $parent => $current) {
2264 if ( array_key_exists( $parent, $children ) ) {
2265 # Circular reference
2266 $stack[$parent] = array();
2267 } else {
2268 $nt = Title::newFromText($parent);
2269 if ( $nt ) {
2270 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2271 }
2272 }
2273 }
2274 return $stack;
2275 } else {
2276 return array();
2277 }
2278 }
2279
2280
2281 /**
2282 * Get an associative array for selecting this title from
2283 * the "page" table
2284 *
2285 * @return array
2286 * @access public
2287 */
2288 function pageCond() {
2289 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2290 }
2291
2292 /**
2293 * Get the revision ID of the previous revision
2294 *
2295 * @param integer $revision Revision ID. Get the revision that was before this one.
2296 * @return integer $oldrevision|false
2297 */
2298 function getPreviousRevisionID( $revision ) {
2299 $dbr =& wfGetDB( DB_SLAVE );
2300 return $dbr->selectField( 'revision', 'rev_id',
2301 'rev_page=' . intval( $this->getArticleId() ) .
2302 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2303 }
2304
2305 /**
2306 * Get the revision ID of the next revision
2307 *
2308 * @param integer $revision Revision ID. Get the revision that was after this one.
2309 * @return integer $oldrevision|false
2310 */
2311 function getNextRevisionID( $revision ) {
2312 $dbr =& wfGetDB( DB_SLAVE );
2313 return $dbr->selectField( 'revision', 'rev_id',
2314 'rev_page=' . intval( $this->getArticleId() ) .
2315 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2316 }
2317
2318 /**
2319 * Get the number of revisions between the given revision IDs.
2320 *
2321 * @param integer $old Revision ID.
2322 * @param integer $new Revision ID.
2323 * @return integer Number of revisions between these IDs.
2324 */
2325 function countRevisionsBetween( $old, $new ) {
2326 $dbr =& wfGetDB( DB_SLAVE );
2327 return $dbr->selectField( 'revision', 'count(*)',
2328 'rev_page = ' . intval( $this->getArticleId() ) .
2329 ' AND rev_id > ' . intval( $old ) .
2330 ' AND rev_id < ' . intval( $new ) );
2331 }
2332
2333 /**
2334 * Compare with another title.
2335 *
2336 * @param Title $title
2337 * @return bool
2338 */
2339 function equals( $title ) {
2340 // Note: === is necessary for proper matching of number-like titles.
2341 return $this->getInterwiki() === $title->getInterwiki()
2342 && $this->getNamespace() == $title->getNamespace()
2343 && $this->getDbkey() === $title->getDbkey();
2344 }
2345
2346 /**
2347 * Check if page exists
2348 * @return bool
2349 */
2350 function exists() {
2351 return $this->getArticleId() != 0;
2352 }
2353
2354 /**
2355 * Should a link should be displayed as a known link, just based on its title?
2356 *
2357 * Currently, a self-link with a fragment and special pages are in
2358 * this category. Special pages never exist in the database.
2359 */
2360 function isAlwaysKnown() {
2361 return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
2362 || NS_SPECIAL == $this->mNamespace;
2363 }
2364
2365 /**
2366 * Update page_touched timestamps and send squid purge messages for
2367 * pages linking to this title. May be sent to the job queue depending
2368 * on the number of links. Typically called on create and delete.
2369 */
2370 function touchLinks() {
2371 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2372 $u->doUpdate();
2373
2374 if ( $this->getNamespace() == NS_CATEGORY ) {
2375 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2376 $u->doUpdate();
2377 }
2378 }
2379
2380 /**
2381 * Get the last touched timestamp
2382 */
2383 function getTouched() {
2384 $dbr =& wfGetDB( DB_SLAVE );
2385 $touched = $dbr->selectField( 'page', 'page_touched',
2386 array(
2387 'page_namespace' => $this->getNamespace(),
2388 'page_title' => $this->getDBkey()
2389 ), __METHOD__
2390 );
2391 return $touched;
2392 }
2393
2394 /**
2395 * Get a cached value from a global cache that is invalidated when this page changes
2396 * @param string $key the key
2397 * @param callback $callback A callback function which generates the value on cache miss
2398 *
2399 * @deprecated use DependencyWrapper
2400 */
2401 function getRelatedCache( $memc, $key, $expiry, $callback, $params = array() ) {
2402 return DependencyWrapper::getValueFromCache( $memc, $key, $expiry, $callback,
2403 $params, new TitleDependency( $this ) );
2404 }
2405
2406 function trackbackURL() {
2407 global $wgTitle, $wgScriptPath, $wgServer;
2408
2409 return "$wgServer$wgScriptPath/trackback.php?article="
2410 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2411 }
2412
2413 function trackbackRDF() {
2414 $url = htmlspecialchars($this->getFullURL());
2415 $title = htmlspecialchars($this->getText());
2416 $tburl = $this->trackbackURL();
2417
2418 return "
2419 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2420 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2421 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2422 <rdf:Description
2423 rdf:about=\"$url\"
2424 dc:identifier=\"$url\"
2425 dc:title=\"$title\"
2426 trackback:ping=\"$tburl\" />
2427 </rdf:RDF>";
2428 }
2429
2430 /**
2431 * Generate strings used for xml 'id' names in monobook tabs
2432 * @return string
2433 */
2434 function getNamespaceKey() {
2435 global $wgContLang;
2436 switch ($this->getNamespace()) {
2437 case NS_MAIN:
2438 case NS_TALK:
2439 return 'nstab-main';
2440 case NS_USER:
2441 case NS_USER_TALK:
2442 return 'nstab-user';
2443 case NS_MEDIA:
2444 return 'nstab-media';
2445 case NS_SPECIAL:
2446 return 'nstab-special';
2447 case NS_PROJECT:
2448 case NS_PROJECT_TALK:
2449 return 'nstab-project';
2450 case NS_IMAGE:
2451 case NS_IMAGE_TALK:
2452 return 'nstab-image';
2453 case NS_MEDIAWIKI:
2454 case NS_MEDIAWIKI_TALK:
2455 return 'nstab-mediawiki';
2456 case NS_TEMPLATE:
2457 case NS_TEMPLATE_TALK:
2458 return 'nstab-template';
2459 case NS_HELP:
2460 case NS_HELP_TALK:
2461 return 'nstab-help';
2462 case NS_CATEGORY:
2463 case NS_CATEGORY_TALK:
2464 return 'nstab-category';
2465 default:
2466 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2467 }
2468 }
2469
2470 /**
2471 * Returns true if this title resolves to the named special page
2472 * @param string $name The special page name
2473 * @access public
2474 */
2475 function isSpecial( $name ) {
2476 if ( $this->getNamespace() == NS_SPECIAL ) {
2477 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
2478 if ( $name == $thisName ) {
2479 return true;
2480 }
2481 }
2482 return false;
2483 }
2484
2485 /**
2486 * If the Title refers to a special page alias which is not the local default,
2487 * returns a new Title which points to the local default. Otherwise, returns $this.
2488 */
2489 function fixSpecialName() {
2490 if ( $this->getNamespace() == NS_SPECIAL ) {
2491 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
2492 if ( $canonicalName ) {
2493 $localName = SpecialPage::getLocalNameFor( $canonicalName );
2494 if ( $localName != $this->mDbkeyform ) {
2495 return Title::makeTitle( NS_SPECIAL, $localName );
2496 }
2497 }
2498 }
2499 return $this;
2500 }
2501
2502 /**
2503 * Is this Title in a namespace which contains content?
2504 * In other words, is this a content page, for the purposes of calculating
2505 * statistics, etc?
2506 *
2507 * @return bool
2508 */
2509 public function isContentPage() {
2510 return Namespace::isContent( $this->getNamespace() );
2511 }
2512
2513 }
2514
2515 ?>