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