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