*Add framework for proper protection cascading
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * See title.txt
4 *
5 */
6
7 /** */
8 require_once( dirname(__FILE__) . '/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 $mRestrictionsExpiry; # When do the restrictions on this page expire?
56 var $mHasCascadingRestrictions; # Are cascading restrictions in effect on this page?
57 var $mCascadeRestrictionSources;# Where are the cascading restrictions coming from on this page?
58 var $mRestrictionsLoaded; # Boolean for initialisation on demand
59 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
60 var $mDefaultNamespace; # Namespace index when there is no namespace
61 # Zero except in {{transclusion}} tags
62 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
63 /**#@-*/
64
65
66 /**
67 * Constructor
68 * @private
69 */
70 /* private */ function __construct() {
71 $this->mInterwiki = $this->mUrlform =
72 $this->mTextform = $this->mDbkeyform = '';
73 $this->mArticleID = -1;
74 $this->mNamespace = NS_MAIN;
75 $this->mRestrictionsLoaded = false;
76 $this->mRestrictions = array();
77 # Dont change the following, NS_MAIN is hardcoded in several place
78 # See bug #696
79 $this->mDefaultNamespace = NS_MAIN;
80 $this->mWatched = NULL;
81 $this->mLatestID = false;
82 $this->mOldRestrictions = false;
83 }
84
85 /**
86 * Create a new Title from a prefixed DB key
87 * @param string $key The database key, which has underscores
88 * instead of spaces, possibly including namespace and
89 * interwiki prefixes
90 * @return Title the new object, or NULL on an error
91 * @static
92 * @access public
93 */
94 /* static */ function newFromDBkey( $key ) {
95 $t = new Title();
96 $t->mDbkeyform = $key;
97 if( $t->secureAndSplit() )
98 return $t;
99 else
100 return NULL;
101 }
102
103 /**
104 * Create a new Title from text, such as what one would
105 * find in a link. Decodes any HTML entities in the text.
106 *
107 * @param string $text the link text; spaces, prefixes,
108 * and an initial ':' indicating the main namespace
109 * are accepted
110 * @param int $defaultNamespace the namespace to use if
111 * none is specified by a prefix
112 * @return Title the new object, or NULL on an error
113 * @static
114 * @access public
115 */
116 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
117 if( is_object( $text ) ) {
118 throw new MWException( 'Title::newFromText given an object' );
119 }
120
121 /**
122 * Wiki pages often contain multiple links to the same page.
123 * Title normalization and parsing can become expensive on
124 * pages with many links, so we can save a little time by
125 * caching them.
126 *
127 * In theory these are value objects and won't get changed...
128 */
129 if( $defaultNamespace == NS_MAIN && isset( Title::$titleCache[$text] ) ) {
130 return Title::$titleCache[$text];
131 }
132
133 /**
134 * Convert things like &eacute; &#257; or &#x3017; into real text...
135 */
136 $filteredText = Sanitizer::decodeCharReferences( $text );
137
138 $t = new Title();
139 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
140 $t->mDefaultNamespace = $defaultNamespace;
141
142 static $cachedcount = 0 ;
143 if( $t->secureAndSplit() ) {
144 if( $defaultNamespace == NS_MAIN ) {
145 if( $cachedcount >= MW_TITLECACHE_MAX ) {
146 # Avoid memory leaks on mass operations...
147 Title::$titleCache = array();
148 $cachedcount=0;
149 }
150 $cachedcount++;
151 Title::$titleCache[$text] =& $t;
152 }
153 return $t;
154 } else {
155 $ret = NULL;
156 return $ret;
157 }
158 }
159
160 /**
161 * Create a new Title from URL-encoded text. Ensures that
162 * the given title's length does not exceed the maximum.
163 * @param string $url the title, as might be taken from a URL
164 * @param bool $isvalid, allows for multiple colons and characters set as illegal
165 * @return Title the new object, or NULL on an error
166 * @static
167 * @access public
168 */
169 public static function newFromURL( $url, $isvalid=true ) {
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( $isvalid ) ) {
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 # Special pages have inherent protection
1038 if( $this->getNamespace() == NS_SPECIAL )
1039 return true;
1040
1041 # Check regular protection levels
1042 if( $action == 'edit' || $action == '' ) {
1043 $r = $this->getRestrictions( 'edit' );
1044 foreach( $wgRestrictionLevels as $level ) {
1045 if( in_array( $level, $r ) && $level != '' ) {
1046 return( true );
1047 }
1048 }
1049 }
1050
1051 if( $action == 'move' || $action == '' ) {
1052 $r = $this->getRestrictions( 'move' );
1053 foreach( $wgRestrictionLevels as $level ) {
1054 if( in_array( $level, $r ) && $level != '' ) {
1055 return( true );
1056 }
1057 }
1058 }
1059
1060 return false;
1061 }
1062
1063 /**
1064 * Is $wgUser is watching this page?
1065 * @return boolean
1066 * @access public
1067 */
1068 function userIsWatching() {
1069 global $wgUser;
1070
1071 if ( is_null( $this->mWatched ) ) {
1072 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn()) {
1073 $this->mWatched = false;
1074 } else {
1075 $this->mWatched = $wgUser->isWatched( $this );
1076 }
1077 }
1078 return $this->mWatched;
1079 }
1080
1081 /**
1082 * Can $wgUser perform $action on this page?
1083 * This skips potentially expensive cascading permission checks.
1084 *
1085 * Suitable for use for nonessential UI controls in common cases, but
1086 * _not_ for functional access control.
1087 *
1088 * May provide false positives, but should never provide a false negative.
1089 *
1090 * @param string $action action that permission needs to be checked for
1091 * @return boolean
1092 */
1093 public function quickUserCan( $action ) {
1094 return $this->userCan( $action, false );
1095 }
1096
1097 /**
1098 * Can $wgUser perform $action on this page?
1099 * @param string $action action that permission needs to be checked for
1100 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
1101 * @return boolean
1102 */
1103 public function userCan( $action, $doExpensiveQueries = true ) {
1104 $fname = 'Title::userCan';
1105 wfProfileIn( $fname );
1106
1107 global $wgUser, $wgNamespaceProtection;
1108
1109 $result = null;
1110 wfRunHooks( 'userCan', array( &$this, &$wgUser, $action, &$result ) );
1111 if ( $result !== null ) {
1112 wfProfileOut( $fname );
1113 return $result;
1114 }
1115
1116 if( NS_SPECIAL == $this->mNamespace ) {
1117 wfProfileOut( $fname );
1118 return false;
1119 }
1120
1121 if ( array_key_exists( $this->mNamespace, $wgNamespaceProtection ) ) {
1122 $nsProt = $wgNamespaceProtection[ $this->mNamespace ];
1123 if ( !is_array($nsProt) ) $nsProt = array($nsProt);
1124 foreach( $nsProt as $right ) {
1125 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1126 wfProfileOut( $fname );
1127 return false;
1128 }
1129 }
1130 }
1131
1132 if( $this->mDbkeyform == '_' ) {
1133 # FIXME: Is this necessary? Shouldn't be allowed anyway...
1134 wfProfileOut( $fname );
1135 return false;
1136 }
1137
1138 # protect css/js subpages of user pages
1139 # XXX: this might be better using restrictions
1140 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
1141 if( $this->isCssJsSubpage()
1142 && !$wgUser->isAllowed('editinterface')
1143 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
1144 wfProfileOut( $fname );
1145 return false;
1146 }
1147
1148 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1149 # We /could/ use the protection level on the source page, but it's fairly ugly
1150 # as we have to establish a precedence hierarchy for pages included by multiple
1151 # cascade-protected pages. So just restrict it to people with 'protect' permission,
1152 # as they could remove the protection anyway.
1153 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1154 # Cascading protection depends on more than this page...
1155 # Several cascading protected pages may include this page...
1156 # Check each cascading level
1157 # This is only for protection restrictions, not for all actions
1158 if( $cascadingSources > 0 && isset($restrictions[$action]) ) {
1159 foreach( $restrictions[$action] as $right ) {
1160 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1161 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1162 wfProfileOut( $fname );
1163 return false;
1164 }
1165 }
1166 }
1167 }
1168
1169 foreach( $this->getRestrictions($action) as $right ) {
1170 // Backwards compatibility, rewrite sysop -> protect
1171 if ( $right == 'sysop' ) {
1172 $right = 'protect';
1173 }
1174 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
1175 wfProfileOut( $fname );
1176 return false;
1177 }
1178 }
1179
1180 if( $action == 'move' &&
1181 !( $this->isMovable() && $wgUser->isAllowed( 'move' ) ) ) {
1182 wfProfileOut( $fname );
1183 return false;
1184 }
1185
1186 if( $action == 'create' ) {
1187 if( ( $this->isTalkPage() && !$wgUser->isAllowed( 'createtalk' ) ) ||
1188 ( !$this->isTalkPage() && !$wgUser->isAllowed( 'createpage' ) ) ) {
1189 wfProfileOut( $fname );
1190 return false;
1191 }
1192 }
1193
1194 wfProfileOut( $fname );
1195 return true;
1196 }
1197
1198 /**
1199 * Can $wgUser edit this page?
1200 * @return boolean
1201 * @deprecated use userCan('edit')
1202 */
1203 public function userCanEdit( $doExpensiveQueries = true ) {
1204 return $this->userCan( 'edit', $doExpensiveQueries );
1205 }
1206
1207 /**
1208 * Can $wgUser create this page?
1209 * @return boolean
1210 * @deprecated use userCan('create')
1211 */
1212 public function userCanCreate( $doExpensiveQueries = true ) {
1213 return $this->userCan( 'create', $doExpensiveQueries );
1214 }
1215
1216 /**
1217 * Can $wgUser move this page?
1218 * @return boolean
1219 * @deprecated use userCan('move')
1220 */
1221 public function userCanMove( $doExpensiveQueries = true ) {
1222 return $this->userCan( 'move', $doExpensiveQueries );
1223 }
1224
1225 /**
1226 * Would anybody with sufficient privileges be able to move this page?
1227 * Some pages just aren't movable.
1228 *
1229 * @return boolean
1230 * @access public
1231 */
1232 function isMovable() {
1233 return Namespace::isMovable( $this->getNamespace() )
1234 && $this->getInterwiki() == '';
1235 }
1236
1237 /**
1238 * Can $wgUser read this page?
1239 * @return boolean
1240 * @fixme fold these checks into userCan()
1241 */
1242 public function userCanRead() {
1243 global $wgUser;
1244
1245 $result = null;
1246 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1247 if ( $result !== null ) {
1248 return $result;
1249 }
1250
1251 if( $wgUser->isAllowed('read') ) {
1252 return true;
1253 } else {
1254 global $wgWhitelistRead;
1255
1256 /**
1257 * Always grant access to the login page.
1258 * Even anons need to be able to log in.
1259 */
1260 if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1261 return true;
1262 }
1263
1264 /** some pages are explicitly allowed */
1265 $name = $this->getPrefixedText();
1266 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
1267 return true;
1268 }
1269
1270 # Compatibility with old settings
1271 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
1272 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
1273 return true;
1274 }
1275 }
1276 }
1277 return false;
1278 }
1279
1280 /**
1281 * Is this a talk page of some sort?
1282 * @return bool
1283 * @access public
1284 */
1285 function isTalkPage() {
1286 return Namespace::isTalk( $this->getNamespace() );
1287 }
1288
1289 /**
1290 * Is this a subpage?
1291 * @return bool
1292 * @access public
1293 */
1294 function isSubpage() {
1295 global $wgNamespacesWithSubpages;
1296
1297 if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) ) {
1298 return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace ] == true );
1299 } else {
1300 return false;
1301 }
1302 }
1303
1304 /**
1305 * Is this a .css or .js subpage of a user page?
1306 * @return bool
1307 * @access public
1308 */
1309 function isCssJsSubpage() {
1310 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.(css|js)$/", $this->mTextform ) );
1311 }
1312 /**
1313 * Is this a *valid* .css or .js subpage of a user page?
1314 * Check that the corresponding skin exists
1315 */
1316 function isValidCssJsSubpage() {
1317 if ( $this->isCssJsSubpage() ) {
1318 $skinNames = Skin::getSkinNames();
1319 return array_key_exists( $this->getSkinFromCssJsSubpage(), $skinNames );
1320 } else {
1321 return false;
1322 }
1323 }
1324 /**
1325 * Trim down a .css or .js subpage title to get the corresponding skin name
1326 */
1327 function getSkinFromCssJsSubpage() {
1328 $subpage = explode( '/', $this->mTextform );
1329 $subpage = $subpage[ count( $subpage ) - 1 ];
1330 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1331 }
1332 /**
1333 * Is this a .css subpage of a user page?
1334 * @return bool
1335 * @access public
1336 */
1337 function isCssSubpage() {
1338 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.css$/", $this->mTextform ) );
1339 }
1340 /**
1341 * Is this a .js subpage of a user page?
1342 * @return bool
1343 * @access public
1344 */
1345 function isJsSubpage() {
1346 return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.js$/", $this->mTextform ) );
1347 }
1348 /**
1349 * Protect css/js subpages of user pages: can $wgUser edit
1350 * this page?
1351 *
1352 * @return boolean
1353 * @todo XXX: this might be better using restrictions
1354 * @access public
1355 */
1356 function userCanEditCssJsSubpage() {
1357 global $wgUser;
1358 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1359 }
1360
1361 /**
1362 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
1363 *
1364 * @return bool If the page is subject to cascading restrictions.
1365 * @access public.
1366 */
1367 function isCascadeProtected() {
1368 list( $sources, $restrictions ) = $this->getCascadeProtectionSources( false );
1369 return ( $sources > 0 );
1370 }
1371
1372 /**
1373 * Cascading protection: Get the source of any cascading restrictions on this page.
1374 *
1375 * @param $get_pages bool Whether or not to retrieve the actual pages that the restrictions have come from.
1376 * @return array( mixed title array, restriction array)
1377 * 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.
1378 * The restriction array is an array of each type, each of which contains an array of unique groups
1379 * @access public
1380 */
1381 function getCascadeProtectionSources( $get_pages = true ) {
1382 global $wgEnableCascadingProtection, $wgRestrictionTypes;
1383
1384 # Define our dimension of restrictions types
1385 $pagerestrictions = array();
1386 foreach( $wgRestrictionTypes as $action )
1387 $pagerestrictions[$action] = array();
1388
1389 if (!$wgEnableCascadingProtection)
1390 return array( false, $pagerestrictions );
1391
1392 if ( isset( $this->mCascadeSources ) && $get_pages ) {
1393 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
1394 } else if ( isset( $this->mHasCascadingRestrictions ) && !$get_pages ) {
1395 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
1396 }
1397
1398 wfProfileIn( __METHOD__ );
1399
1400 $dbr = wfGetDb( DB_SLAVE );
1401
1402 if ( $this->getNamespace() == NS_IMAGE ) {
1403 $tables = array ('imagelinks', 'page_restrictions');
1404 $where_clauses = array(
1405 'il_to' => $this->getDBkey(),
1406 'il_from=pr_page',
1407 'pr_cascade' => 1 );
1408 } else {
1409 $tables = array ('templatelinks', 'page_restrictions');
1410 $where_clauses = array(
1411 'tl_namespace' => $this->getNamespace(),
1412 'tl_title' => $this->getDBkey(),
1413 'tl_from=pr_page',
1414 'pr_cascade' => 1 );
1415 }
1416
1417 if ( $get_pages ) {
1418 $cols = array('pr_page', 'page_namespace', 'page_title', 'pr_expiry', 'pr_type', 'pr_level' );
1419 $where_clauses[] = 'page_id=pr_page';
1420 $tables[] = 'page';
1421 } else {
1422 $cols = array( 'pr_expiry' );
1423 }
1424
1425 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
1426
1427 $sources = $get_pages ? array() : false;
1428 $now = wfTimestampNow();
1429 $purgeExpired = false;
1430
1431 while( $row = $dbr->fetchObject( $res ) ) {
1432 $expiry = Block::decodeExpiry( $row->pr_expiry );
1433 if( $expiry > $now ) {
1434 if ($get_pages) {
1435 $page_id = $row->pr_page;
1436 $page_ns = $row->page_namespace;
1437 $page_title = $row->page_title;
1438 $sources[$page_id] = Title::makeTitle($page_ns, $page_title);
1439 # Add groups needed for each restriction type if its not already there
1440 # Make sure this restriction type still exists
1441 if ( isset($pagerestrictions[$row->pr_type]) && !in_array($row->pr_level, $pagerestrictions[$row->pr_type]) ) {
1442 $pagerestrictions[$row->pr_type][]=$row->pr_level;
1443 }
1444 } else {
1445 $sources = true;
1446 }
1447 } else {
1448 // Trigger lazy purge of expired restrictions from the db
1449 $purgeExpired = true;
1450 }
1451 }
1452 if( $purgeExpired ) {
1453 Title::purgeExpiredRestrictions();
1454 }
1455
1456 wfProfileOut( __METHOD__ );
1457
1458 if ( $get_pages ) {
1459 $this->mCascadeSources = $sources;
1460 $this->mCascadingRestrictions = $pagerestrictions;
1461 } else {
1462 $this->mHasCascadingRestrictions = $sources;
1463 }
1464
1465 return array( $sources, $pagerestrictions );
1466 }
1467
1468 function areRestrictionsCascading() {
1469 if (!$this->mRestrictionsLoaded) {
1470 $this->loadRestrictions();
1471 }
1472
1473 return $this->mCascadeRestriction;
1474 }
1475
1476 /**
1477 * Loads a string into mRestrictions array
1478 * @param resource $res restrictions as an SQL result.
1479 * @access public
1480 */
1481 function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
1482 $dbr = wfGetDb( DB_SLAVE );
1483
1484 $this->mRestrictions['edit'] = array();
1485 $this->mRestrictions['move'] = array();
1486
1487 # Backwards-compatibility: also load the restrictions from the page record (old format).
1488
1489 if ( $oldFashionedRestrictions == NULL ) {
1490 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions', array( 'page_id' => $this->getArticleId() ), __METHOD__ );
1491 }
1492
1493 if ($oldFashionedRestrictions != '') {
1494
1495 foreach( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
1496 $temp = explode( '=', trim( $restrict ) );
1497 if(count($temp) == 1) {
1498 // old old format should be treated as edit/move restriction
1499 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1500 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1501 } else {
1502 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1503 }
1504 }
1505
1506 $this->mOldRestrictions = true;
1507 $this->mCascadeRestriction = false;
1508 $this->mRestrictionsExpiry = Block::decodeExpiry('');
1509
1510 }
1511
1512 if( $dbr->numRows( $res ) ) {
1513 # Current system - load second to make them override.
1514 $now = wfTimestampNow();
1515 $purgeExpired = false;
1516
1517 while ($row = $dbr->fetchObject( $res ) ) {
1518 # Cycle through all the restrictions.
1519
1520 // This code should be refactored, now that it's being used more generally,
1521 // But I don't really see any harm in leaving it in Block for now -werdna
1522 $expiry = Block::decodeExpiry( $row->pr_expiry );
1523
1524 // Only apply the restrictions if they haven't expired!
1525 if ( !$expiry || $expiry > $now ) {
1526 $this->mRestrictionsExpiry = $expiry;
1527 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
1528
1529 $this->mCascadeRestriction |= $row->pr_cascade;
1530 } else {
1531 // Trigger a lazy purge of expired restrictions
1532 $purgeExpired = true;
1533 }
1534 }
1535
1536 if( $purgeExpired ) {
1537 Title::purgeExpiredRestrictions();
1538 }
1539 }
1540
1541 $this->mRestrictionsLoaded = true;
1542 }
1543
1544 function loadRestrictions( $oldFashionedRestrictions = NULL ) {
1545 if( !$this->mRestrictionsLoaded ) {
1546 $dbr = wfGetDB( DB_SLAVE );
1547
1548 $res = $dbr->select( 'page_restrictions', '*',
1549 array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
1550
1551 $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
1552 }
1553 }
1554
1555 /**
1556 * Purge expired restrictions from the page_restrictions table
1557 */
1558 static function purgeExpiredRestrictions() {
1559 $dbw = wfGetDB( DB_MASTER );
1560 $dbw->delete( 'page_restrictions',
1561 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
1562 __METHOD__ );
1563 }
1564
1565 /**
1566 * Accessor/initialisation for mRestrictions
1567 *
1568 * @access public
1569 * @param string $action action that permission needs to be checked for
1570 * @return array the array of groups allowed to edit this article
1571 */
1572 function getRestrictions( $action ) {
1573 if( $this->exists() ) {
1574 if( !$this->mRestrictionsLoaded ) {
1575 $this->loadRestrictions();
1576 }
1577 return isset( $this->mRestrictions[$action] )
1578 ? $this->mRestrictions[$action]
1579 : array();
1580 } else {
1581 return array();
1582 }
1583 }
1584
1585 /**
1586 * Is there a version of this page in the deletion archive?
1587 * @return int the number of archived revisions
1588 * @access public
1589 */
1590 function isDeleted() {
1591 $fname = 'Title::isDeleted';
1592 if ( $this->getNamespace() < 0 ) {
1593 $n = 0;
1594 } else {
1595 $dbr = wfGetDB( DB_SLAVE );
1596 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1597 'ar_title' => $this->getDBkey() ), $fname );
1598 if( $this->getNamespace() == NS_IMAGE ) {
1599 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
1600 array( 'fa_name' => $this->getDBkey() ), $fname );
1601 }
1602 }
1603 return (int)$n;
1604 }
1605
1606 /**
1607 * Get the article ID for this Title from the link cache,
1608 * adding it if necessary
1609 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1610 * for update
1611 * @return int the ID
1612 */
1613 public function getArticleID( $flags = 0 ) {
1614 $linkCache =& LinkCache::singleton();
1615 if ( $flags & GAID_FOR_UPDATE ) {
1616 $oldUpdate = $linkCache->forUpdate( true );
1617 $this->mArticleID = $linkCache->addLinkObj( $this );
1618 $linkCache->forUpdate( $oldUpdate );
1619 } else {
1620 if ( -1 == $this->mArticleID ) {
1621 $this->mArticleID = $linkCache->addLinkObj( $this );
1622 }
1623 }
1624 return $this->mArticleID;
1625 }
1626
1627 function getLatestRevID() {
1628 if ($this->mLatestID !== false)
1629 return $this->mLatestID;
1630
1631 $db = wfGetDB(DB_SLAVE);
1632 return $this->mLatestID = $db->selectField( 'revision',
1633 "max(rev_id)",
1634 array('rev_page' => $this->getArticleID()),
1635 'Title::getLatestRevID' );
1636 }
1637
1638 /**
1639 * This clears some fields in this object, and clears any associated
1640 * keys in the "bad links" section of the link cache.
1641 *
1642 * - This is called from Article::insertNewArticle() to allow
1643 * loading of the new page_id. It's also called from
1644 * Article::doDeleteArticle()
1645 *
1646 * @param int $newid the new Article ID
1647 * @access public
1648 */
1649 function resetArticleID( $newid ) {
1650 $linkCache =& LinkCache::singleton();
1651 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
1652
1653 if ( 0 == $newid ) { $this->mArticleID = -1; }
1654 else { $this->mArticleID = $newid; }
1655 $this->mRestrictionsLoaded = false;
1656 $this->mRestrictions = array();
1657 }
1658
1659 /**
1660 * Updates page_touched for this page; called from LinksUpdate.php
1661 * @return bool true if the update succeded
1662 * @access public
1663 */
1664 function invalidateCache() {
1665 global $wgUseFileCache;
1666
1667 if ( wfReadOnly() ) {
1668 return;
1669 }
1670
1671 $dbw = wfGetDB( DB_MASTER );
1672 $success = $dbw->update( 'page',
1673 array( /* SET */
1674 'page_touched' => $dbw->timestamp()
1675 ), array( /* WHERE */
1676 'page_namespace' => $this->getNamespace() ,
1677 'page_title' => $this->getDBkey()
1678 ), 'Title::invalidateCache'
1679 );
1680
1681 if ($wgUseFileCache) {
1682 $cache = new HTMLFileCache($this);
1683 @unlink($cache->fileCacheName());
1684 }
1685
1686 return $success;
1687 }
1688
1689 /**
1690 * Prefix some arbitrary text with the namespace or interwiki prefix
1691 * of this object
1692 *
1693 * @param string $name the text
1694 * @return string the prefixed text
1695 * @private
1696 */
1697 /* private */ function prefix( $name ) {
1698 $p = '';
1699 if ( '' != $this->mInterwiki ) {
1700 $p = $this->mInterwiki . ':';
1701 }
1702 if ( 0 != $this->mNamespace ) {
1703 $p .= $this->getNsText() . ':';
1704 }
1705 return $p . $name;
1706 }
1707
1708 /**
1709 * Secure and split - main initialisation function for this object
1710 *
1711 * Assumes that mDbkeyform has been set, and is urldecoded
1712 * and uses underscores, but not otherwise munged. This function
1713 * removes illegal characters, splits off the interwiki and
1714 * namespace prefixes, sets the other forms, and canonicalizes
1715 * everything.
1716 * @param bool $isvalid, allows for multiple colons and characters set as illegal
1717 * @return bool true on success
1718 * @private
1719 */
1720 /* private */ function secureAndSplit( $isvalid=true ) {
1721 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1722
1723 # Initialisation
1724 static $rxTc = false;
1725 if( !$rxTc ) {
1726 # % is needed as well
1727 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1728 }
1729
1730 $this->mInterwiki = $this->mFragment = '';
1731 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1732
1733 $dbkey = $this->mDbkeyform;
1734
1735 # Strip Unicode bidi override characters.
1736 # Sometimes they slip into cut-n-pasted page titles, where the
1737 # override chars get included in list displays.
1738 $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
1739 $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
1740
1741 # Clean up whitespace
1742 #
1743 $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
1744 $dbkey = trim( $dbkey, '_' );
1745
1746 if ( '' == $dbkey ) {
1747 return false;
1748 }
1749
1750 if( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
1751 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1752 return false;
1753 }
1754
1755 $this->mDbkeyform = $dbkey;
1756
1757 # Initial colon indicates main namespace rather than specified default
1758 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
1759 if ( ':' == $dbkey{0} ) {
1760 $this->mNamespace = NS_MAIN;
1761 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
1762 }
1763
1764 # Namespace or interwiki prefix
1765 $firstPass = true;
1766 do {
1767 $m = array();
1768 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $dbkey, $m ) ) {
1769 $p = $m[1];
1770 $lowerNs = $wgContLang->lc( $p );
1771 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1772 # Canonical namespace
1773 $dbkey = $m[2];
1774 $this->mNamespace = $ns;
1775 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1776 # Ordinary namespace
1777 $dbkey = $m[2];
1778 $this->mNamespace = $ns;
1779 } elseif( $this->getInterwikiLink( $p ) ) {
1780 if( !$firstPass ) {
1781 # Can't make a local interwiki link to an interwiki link.
1782 # That's just crazy!
1783 return false;
1784 }
1785
1786 # Interwiki link
1787 $dbkey = $m[2];
1788 $this->mInterwiki = $wgContLang->lc( $p );
1789
1790 # Redundant interwiki prefix to the local wiki
1791 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1792 if( $dbkey == '' ) {
1793 # Can't have an empty self-link
1794 return false;
1795 }
1796 $this->mInterwiki = '';
1797 $firstPass = false;
1798 # Do another namespace split...
1799 continue;
1800 }
1801
1802 # If there's an initial colon after the interwiki, that also
1803 # resets the default namespace
1804 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
1805 $this->mNamespace = NS_MAIN;
1806 $dbkey = substr( $dbkey, 1 );
1807 }
1808 }
1809 # If there's no recognized interwiki or namespace,
1810 # then let the colon expression be part of the title.
1811 }
1812 break;
1813 } while( true );
1814
1815 # We already know that some pages won't be in the database!
1816 #
1817 if ( '' != $this->mInterwiki || NS_SPECIAL == $this->mNamespace ) {
1818 $this->mArticleID = 0;
1819 }
1820 $fragment = strstr( $dbkey, '#' );
1821 if ( $isvalid && false !== $fragment ) {
1822 $this->setFragment( $fragment );
1823 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
1824 # remove whitespace again: prevents "Foo_bar_#"
1825 # becoming "Foo_bar_"
1826 $dbkey = preg_replace( '/_*$/', '', $dbkey );
1827 }
1828
1829 # Reject illegal characters.
1830 #
1831 if( $isvalid && preg_match( $rxTc, $dbkey ) ) {
1832 return false;
1833 }
1834
1835 /**
1836 * Pages with "/./" or "/../" appearing in the URLs will
1837 * often be unreachable due to the way web browsers deal
1838 * with 'relative' URLs. Forbid them explicitly.
1839 */
1840 if ( strpos( $dbkey, '.' ) !== false &&
1841 ( $dbkey === '.' || $dbkey === '..' ||
1842 strpos( $dbkey, './' ) === 0 ||
1843 strpos( $dbkey, '../' ) === 0 ||
1844 strpos( $dbkey, '/./' ) !== false ||
1845 strpos( $dbkey, '/../' ) !== false ) )
1846 {
1847 return false;
1848 }
1849
1850 /**
1851 * Magic tilde sequences? Nu-uh!
1852 */
1853 if( strpos( $dbkey, '~~~' ) !== false ) {
1854 return false;
1855 }
1856
1857 /**
1858 * Limit the size of titles to 255 bytes.
1859 * This is typically the size of the underlying database field.
1860 * We make an exception for special pages, which don't need to be stored
1861 * in the database, and may edge over 255 bytes due to subpage syntax
1862 * for long titles, e.g. [[Special:Block/Long name]]
1863 */
1864 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
1865 strlen( $dbkey ) > 512 )
1866 {
1867 return false;
1868 }
1869
1870 /**
1871 * Normally, all wiki links are forced to have
1872 * an initial capital letter so [[foo]] and [[Foo]]
1873 * point to the same place.
1874 *
1875 * Don't force it for interwikis, since the other
1876 * site might be case-sensitive.
1877 */
1878 if( $wgCapitalLinks && $this->mInterwiki == '') {
1879 $dbkey = $wgContLang->ucfirst( $dbkey );
1880 }
1881
1882 /**
1883 * Can't make a link to a namespace alone...
1884 * "empty" local links can only be self-links
1885 * with a fragment identifier.
1886 */
1887 if( $dbkey == '' &&
1888 $this->mInterwiki == '' &&
1889 $this->mNamespace != NS_MAIN ) {
1890 return false;
1891 }
1892
1893 // Any remaining initial :s are illegal.
1894 if ( $dbkey !== '' && ':' == $dbkey{0} ) {
1895 return false;
1896 }
1897
1898 # Fill fields
1899 $this->mDbkeyform = $dbkey;
1900 $this->mUrlform = wfUrlencode( $dbkey );
1901
1902 $this->mTextform = str_replace( '_', ' ', $dbkey );
1903
1904 return true;
1905 }
1906
1907 /**
1908 * Set the fragment for this title
1909 * This is kind of bad, since except for this rarely-used function, Title objects
1910 * are immutable. The reason this is here is because it's better than setting the
1911 * members directly, which is what Linker::formatComment was doing previously.
1912 *
1913 * @param string $fragment text
1914 * @access kind of public
1915 */
1916 function setFragment( $fragment ) {
1917 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1918 }
1919
1920 /**
1921 * Get a Title object associated with the talk page of this article
1922 * @return Title the object for the talk page
1923 * @access public
1924 */
1925 function getTalkPage() {
1926 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1927 }
1928
1929 /**
1930 * Get a title object associated with the subject page of this
1931 * talk page
1932 *
1933 * @return Title the object for the subject page
1934 * @access public
1935 */
1936 function getSubjectPage() {
1937 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1938 }
1939
1940 /**
1941 * Get an array of Title objects linking to this Title
1942 * Also stores the IDs in the link cache.
1943 *
1944 * WARNING: do not use this function on arbitrary user-supplied titles!
1945 * On heavily-used templates it will max out the memory.
1946 *
1947 * @param string $options may be FOR UPDATE
1948 * @return array the Title objects linking here
1949 * @access public
1950 */
1951 function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
1952 $linkCache =& LinkCache::singleton();
1953
1954 if ( $options ) {
1955 $db = wfGetDB( DB_MASTER );
1956 } else {
1957 $db = wfGetDB( DB_SLAVE );
1958 }
1959
1960 $res = $db->select( array( 'page', $table ),
1961 array( 'page_namespace', 'page_title', 'page_id' ),
1962 array(
1963 "{$prefix}_from=page_id",
1964 "{$prefix}_namespace" => $this->getNamespace(),
1965 "{$prefix}_title" => $this->getDbKey() ),
1966 'Title::getLinksTo',
1967 $options );
1968
1969 $retVal = array();
1970 if ( $db->numRows( $res ) ) {
1971 while ( $row = $db->fetchObject( $res ) ) {
1972 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1973 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1974 $retVal[] = $titleObj;
1975 }
1976 }
1977 }
1978 $db->freeResult( $res );
1979 return $retVal;
1980 }
1981
1982 /**
1983 * Get an array of Title objects using this Title as a template
1984 * Also stores the IDs in the link cache.
1985 *
1986 * WARNING: do not use this function on arbitrary user-supplied titles!
1987 * On heavily-used templates it will max out the memory.
1988 *
1989 * @param string $options may be FOR UPDATE
1990 * @return array the Title objects linking here
1991 * @access public
1992 */
1993 function getTemplateLinksTo( $options = '' ) {
1994 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
1995 }
1996
1997 /**
1998 * Get an array of Title objects referring to non-existent articles linked from this page
1999 *
2000 * @param string $options may be FOR UPDATE
2001 * @return array the Title objects
2002 * @access public
2003 */
2004 function getBrokenLinksFrom( $options = '' ) {
2005 if ( $options ) {
2006 $db = wfGetDB( DB_MASTER );
2007 } else {
2008 $db = wfGetDB( DB_SLAVE );
2009 }
2010
2011 $res = $db->safeQuery(
2012 "SELECT pl_namespace, pl_title
2013 FROM !
2014 LEFT JOIN !
2015 ON pl_namespace=page_namespace
2016 AND pl_title=page_title
2017 WHERE pl_from=?
2018 AND page_namespace IS NULL
2019 !",
2020 $db->tableName( 'pagelinks' ),
2021 $db->tableName( 'page' ),
2022 $this->getArticleId(),
2023 $options );
2024
2025 $retVal = array();
2026 if ( $db->numRows( $res ) ) {
2027 while ( $row = $db->fetchObject( $res ) ) {
2028 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2029 }
2030 }
2031 $db->freeResult( $res );
2032 return $retVal;
2033 }
2034
2035
2036 /**
2037 * Get a list of URLs to purge from the Squid cache when this
2038 * page changes
2039 *
2040 * @return array the URLs
2041 * @access public
2042 */
2043 function getSquidURLs() {
2044 global $wgContLang;
2045
2046 $urls = array(
2047 $this->getInternalURL(),
2048 $this->getInternalURL( 'action=history' )
2049 );
2050
2051 // purge variant urls as well
2052 if($wgContLang->hasVariants()){
2053 $variants = $wgContLang->getVariants();
2054 foreach($variants as $vCode){
2055 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
2056 $urls[] = $this->getInternalURL('',$vCode);
2057 }
2058 }
2059
2060 return $urls;
2061 }
2062
2063 function purgeSquid() {
2064 global $wgUseSquid;
2065 if ( $wgUseSquid ) {
2066 $urls = $this->getSquidURLs();
2067 $u = new SquidUpdate( $urls );
2068 $u->doUpdate();
2069 }
2070 }
2071
2072 /**
2073 * Move this page without authentication
2074 * @param Title &$nt the new page Title
2075 * @access public
2076 */
2077 function moveNoAuth( &$nt ) {
2078 return $this->moveTo( $nt, false );
2079 }
2080
2081 /**
2082 * Check whether a given move operation would be valid.
2083 * Returns true if ok, or a message key string for an error message
2084 * if invalid. (Scarrrrry ugly interface this.)
2085 * @param Title &$nt the new title
2086 * @param bool $auth indicates whether $wgUser's permissions
2087 * should be checked
2088 * @return mixed true on success, message name on failure
2089 * @access public
2090 */
2091 function isValidMoveOperation( &$nt, $auth = true ) {
2092 if( !$this or !$nt ) {
2093 return 'badtitletext';
2094 }
2095 if( $this->equals( $nt ) ) {
2096 return 'selfmove';
2097 }
2098 if( !$this->isMovable() || !$nt->isMovable() ) {
2099 return 'immobile_namespace';
2100 }
2101
2102 $oldid = $this->getArticleID();
2103 $newid = $nt->getArticleID();
2104
2105 if ( strlen( $nt->getDBkey() ) < 1 ) {
2106 return 'articleexists';
2107 }
2108 if ( ( '' == $this->getDBkey() ) ||
2109 ( !$oldid ) ||
2110 ( '' == $nt->getDBkey() ) ) {
2111 return 'badarticleerror';
2112 }
2113
2114 if ( $auth && (
2115 !$this->userCan( 'edit' ) || !$nt->userCan( 'edit' ) ||
2116 !$this->userCan( 'move' ) || !$nt->userCan( 'move' ) ) ) {
2117 return 'protectedpage';
2118 }
2119
2120 # The move is allowed only if (1) the target doesn't exist, or
2121 # (2) the target is a redirect to the source, and has no history
2122 # (so we can undo bad moves right after they're done).
2123
2124 if ( 0 != $newid ) { # Target exists; check for validity
2125 if ( ! $this->isValidMoveTarget( $nt ) ) {
2126 return 'articleexists';
2127 }
2128 }
2129 return true;
2130 }
2131
2132 /**
2133 * Move a title to a new location
2134 * @param Title &$nt the new title
2135 * @param bool $auth indicates whether $wgUser's permissions
2136 * should be checked
2137 * @return mixed true on success, message name on failure
2138 * @access public
2139 */
2140 function moveTo( &$nt, $auth = true, $reason = '' ) {
2141 $err = $this->isValidMoveOperation( $nt, $auth );
2142 if( is_string( $err ) ) {
2143 return $err;
2144 }
2145
2146 $pageid = $this->getArticleID();
2147 if( $nt->exists() ) {
2148 $this->moveOverExistingRedirect( $nt, $reason );
2149 $pageCountChange = 0;
2150 } else { # Target didn't exist, do normal move.
2151 $this->moveToNewTitle( $nt, $reason );
2152 $pageCountChange = 1;
2153 }
2154 $redirid = $this->getArticleID();
2155
2156 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
2157 $dbw = wfGetDB( DB_MASTER );
2158 $categorylinks = $dbw->tableName( 'categorylinks' );
2159 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
2160 " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
2161 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
2162 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
2163
2164 # Update watchlists
2165
2166 $oldnamespace = $this->getNamespace() & ~1;
2167 $newnamespace = $nt->getNamespace() & ~1;
2168 $oldtitle = $this->getDBkey();
2169 $newtitle = $nt->getDBkey();
2170
2171 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
2172 WatchedItem::duplicateEntries( $this, $nt );
2173 }
2174
2175 # Update search engine
2176 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
2177 $u->doUpdate();
2178 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
2179 $u->doUpdate();
2180
2181 # Update site_stats
2182 if( $this->isContentPage() && !$nt->isContentPage() ) {
2183 # No longer a content page
2184 # Not viewed, edited, removing
2185 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
2186 } elseif( !$this->isContentPage() && $nt->isContentPage() ) {
2187 # Now a content page
2188 # Not viewed, edited, adding
2189 $u = new SiteStatsUpdate( 0, 1, +1, $pageCountChange );
2190 } elseif( $pageCountChange ) {
2191 # Redirect added
2192 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
2193 } else {
2194 # Nothing special
2195 $u = false;
2196 }
2197 if( $u )
2198 $u->doUpdate();
2199
2200 global $wgUser;
2201 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
2202 return true;
2203 }
2204
2205 /**
2206 * Move page to a title which is at present a redirect to the
2207 * source page
2208 *
2209 * @param Title &$nt the page to move to, which should currently
2210 * be a redirect
2211 * @private
2212 */
2213 function moveOverExistingRedirect( &$nt, $reason = '' ) {
2214 global $wgUseSquid;
2215 $fname = 'Title::moveOverExistingRedirect';
2216 $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
2217
2218 if ( $reason ) {
2219 $comment .= ": $reason";
2220 }
2221
2222 $now = wfTimestampNow();
2223 $newid = $nt->getArticleID();
2224 $oldid = $this->getArticleID();
2225 $dbw = wfGetDB( DB_MASTER );
2226 $linkCache =& LinkCache::singleton();
2227
2228 # Delete the old redirect. We don't save it to history since
2229 # by definition if we've got here it's rather uninteresting.
2230 # We have to remove it so that the next step doesn't trigger
2231 # a conflict on the unique namespace+title index...
2232 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
2233
2234 # Save a null revision in the page's history notifying of the move
2235 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2236 $nullRevId = $nullRevision->insertOn( $dbw );
2237
2238 # Change the name of the target page:
2239 $dbw->update( 'page',
2240 /* SET */ array(
2241 'page_touched' => $dbw->timestamp($now),
2242 'page_namespace' => $nt->getNamespace(),
2243 'page_title' => $nt->getDBkey(),
2244 'page_latest' => $nullRevId,
2245 ),
2246 /* WHERE */ array( 'page_id' => $oldid ),
2247 $fname
2248 );
2249 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2250
2251 # Recreate the redirect, this time in the other direction.
2252 $mwRedir = MagicWord::get( 'redirect' );
2253 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2254 $redirectArticle = new Article( $this );
2255 $newid = $redirectArticle->insertOn( $dbw );
2256 $redirectRevision = new Revision( array(
2257 'page' => $newid,
2258 'comment' => $comment,
2259 'text' => $redirectText ) );
2260 $redirectRevision->insertOn( $dbw );
2261 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2262 $linkCache->clearLink( $this->getPrefixedDBkey() );
2263
2264 # Log the move
2265 $log = new LogPage( 'move' );
2266 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
2267
2268 # Now, we record the link from the redirect to the new title.
2269 # It should have no other outgoing links...
2270 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
2271 $dbw->insert( 'pagelinks',
2272 array(
2273 'pl_from' => $newid,
2274 'pl_namespace' => $nt->getNamespace(),
2275 'pl_title' => $nt->getDbKey() ),
2276 $fname );
2277
2278 # Purge squid
2279 if ( $wgUseSquid ) {
2280 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
2281 $u = new SquidUpdate( $urls );
2282 $u->doUpdate();
2283 }
2284 }
2285
2286 /**
2287 * Move page to non-existing title.
2288 * @param Title &$nt the new Title
2289 * @private
2290 */
2291 function moveToNewTitle( &$nt, $reason = '' ) {
2292 global $wgUseSquid;
2293 $fname = 'MovePageForm::moveToNewTitle';
2294 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
2295 if ( $reason ) {
2296 $comment .= ": $reason";
2297 }
2298
2299 $newid = $nt->getArticleID();
2300 $oldid = $this->getArticleID();
2301 $dbw = wfGetDB( DB_MASTER );
2302 $now = $dbw->timestamp();
2303 $linkCache =& LinkCache::singleton();
2304
2305 # Save a null revision in the page's history notifying of the move
2306 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
2307 $nullRevId = $nullRevision->insertOn( $dbw );
2308
2309 # Rename cur entry
2310 $dbw->update( 'page',
2311 /* SET */ array(
2312 'page_touched' => $now,
2313 'page_namespace' => $nt->getNamespace(),
2314 'page_title' => $nt->getDBkey(),
2315 'page_latest' => $nullRevId,
2316 ),
2317 /* WHERE */ array( 'page_id' => $oldid ),
2318 $fname
2319 );
2320
2321 $linkCache->clearLink( $nt->getPrefixedDBkey() );
2322
2323 # Insert redirect
2324 $mwRedir = MagicWord::get( 'redirect' );
2325 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
2326 $redirectArticle = new Article( $this );
2327 $newid = $redirectArticle->insertOn( $dbw );
2328 $redirectRevision = new Revision( array(
2329 'page' => $newid,
2330 'comment' => $comment,
2331 'text' => $redirectText ) );
2332 $redirectRevision->insertOn( $dbw );
2333 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
2334 $linkCache->clearLink( $this->getPrefixedDBkey() );
2335
2336 # Log the move
2337 $log = new LogPage( 'move' );
2338 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
2339
2340 # Purge caches as per article creation
2341 Article::onArticleCreate( $nt );
2342
2343 # Record the just-created redirect's linking to the page
2344 $dbw->insert( 'pagelinks',
2345 array(
2346 'pl_from' => $newid,
2347 'pl_namespace' => $nt->getNamespace(),
2348 'pl_title' => $nt->getDBkey() ),
2349 $fname );
2350
2351 # Purge old title from squid
2352 # The new title, and links to the new title, are purged in Article::onArticleCreate()
2353 $this->purgeSquid();
2354 }
2355
2356 /**
2357 * Checks if $this can be moved to a given Title
2358 * - Selects for update, so don't call it unless you mean business
2359 *
2360 * @param Title &$nt the new title to check
2361 * @access public
2362 */
2363 function isValidMoveTarget( $nt ) {
2364
2365 $fname = 'Title::isValidMoveTarget';
2366 $dbw = wfGetDB( DB_MASTER );
2367
2368 # Is it a redirect?
2369 $id = $nt->getArticleID();
2370 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
2371 array( 'page_is_redirect','old_text','old_flags' ),
2372 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
2373 $fname, 'FOR UPDATE' );
2374
2375 if ( !$obj || 0 == $obj->page_is_redirect ) {
2376 # Not a redirect
2377 wfDebug( __METHOD__ . ": not a redirect\n" );
2378 return false;
2379 }
2380 $text = Revision::getRevisionText( $obj );
2381
2382 # Does the redirect point to the source?
2383 # Or is it a broken self-redirect, usually caused by namespace collisions?
2384 $m = array();
2385 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
2386 $redirTitle = Title::newFromText( $m[1] );
2387 if( !is_object( $redirTitle ) ||
2388 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
2389 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
2390 wfDebug( __METHOD__ . ": redirect points to other page\n" );
2391 return false;
2392 }
2393 } else {
2394 # Fail safe
2395 wfDebug( __METHOD__ . ": failsafe\n" );
2396 return false;
2397 }
2398
2399 # Does the article have a history?
2400 $row = $dbw->selectRow( array( 'page', 'revision'),
2401 array( 'rev_id' ),
2402 array( 'page_namespace' => $nt->getNamespace(),
2403 'page_title' => $nt->getDBkey(),
2404 'page_id=rev_page AND page_latest != rev_id'
2405 ), $fname, 'FOR UPDATE'
2406 );
2407
2408 # Return true if there was no history
2409 return $row === false;
2410 }
2411
2412 /**
2413 * Get categories to which this Title belongs and return an array of
2414 * categories' names.
2415 *
2416 * @return array an array of parents in the form:
2417 * $parent => $currentarticle
2418 * @access public
2419 */
2420 function getParentCategories() {
2421 global $wgContLang;
2422
2423 $titlekey = $this->getArticleId();
2424 $dbr = wfGetDB( DB_SLAVE );
2425 $categorylinks = $dbr->tableName( 'categorylinks' );
2426
2427 # NEW SQL
2428 $sql = "SELECT * FROM $categorylinks"
2429 ." WHERE cl_from='$titlekey'"
2430 ." AND cl_from <> '0'"
2431 ." ORDER BY cl_sortkey";
2432
2433 $res = $dbr->query ( $sql ) ;
2434
2435 if($dbr->numRows($res) > 0) {
2436 while ( $x = $dbr->fetchObject ( $res ) )
2437 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
2438 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
2439 $dbr->freeResult ( $res ) ;
2440 } else {
2441 $data = '';
2442 }
2443 return $data;
2444 }
2445
2446 /**
2447 * Get a tree of parent categories
2448 * @param array $children an array with the children in the keys, to check for circular refs
2449 * @return array
2450 * @access public
2451 */
2452 function getParentCategoryTree( $children = array() ) {
2453 $parents = $this->getParentCategories();
2454
2455 if($parents != '') {
2456 foreach($parents as $parent => $current) {
2457 if ( array_key_exists( $parent, $children ) ) {
2458 # Circular reference
2459 $stack[$parent] = array();
2460 } else {
2461 $nt = Title::newFromText($parent);
2462 if ( $nt ) {
2463 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
2464 }
2465 }
2466 }
2467 return $stack;
2468 } else {
2469 return array();
2470 }
2471 }
2472
2473
2474 /**
2475 * Get an associative array for selecting this title from
2476 * the "page" table
2477 *
2478 * @return array
2479 * @access public
2480 */
2481 function pageCond() {
2482 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
2483 }
2484
2485 /**
2486 * Get the revision ID of the previous revision
2487 *
2488 * @param integer $revision Revision ID. Get the revision that was before this one.
2489 * @return integer $oldrevision|false
2490 */
2491 function getPreviousRevisionID( $revision ) {
2492 $dbr = wfGetDB( DB_SLAVE );
2493 return $dbr->selectField( 'revision', 'rev_id',
2494 'rev_page=' . intval( $this->getArticleId() ) .
2495 ' AND rev_id<' . intval( $revision ) . ' ORDER BY rev_id DESC' );
2496 }
2497
2498 /**
2499 * Get the revision ID of the next revision
2500 *
2501 * @param integer $revision Revision ID. Get the revision that was after this one.
2502 * @return integer $oldrevision|false
2503 */
2504 function getNextRevisionID( $revision ) {
2505 $dbr = wfGetDB( DB_SLAVE );
2506 return $dbr->selectField( 'revision', 'rev_id',
2507 'rev_page=' . intval( $this->getArticleId() ) .
2508 ' AND rev_id>' . intval( $revision ) . ' ORDER BY rev_id' );
2509 }
2510
2511 /**
2512 * Get the number of revisions between the given revision IDs.
2513 *
2514 * @param integer $old Revision ID.
2515 * @param integer $new Revision ID.
2516 * @return integer Number of revisions between these IDs.
2517 */
2518 function countRevisionsBetween( $old, $new ) {
2519 $dbr = wfGetDB( DB_SLAVE );
2520 return $dbr->selectField( 'revision', 'count(*)',
2521 'rev_page = ' . intval( $this->getArticleId() ) .
2522 ' AND rev_id > ' . intval( $old ) .
2523 ' AND rev_id < ' . intval( $new ) );
2524 }
2525
2526 /**
2527 * Compare with another title.
2528 *
2529 * @param Title $title
2530 * @return bool
2531 */
2532 function equals( $title ) {
2533 // Note: === is necessary for proper matching of number-like titles.
2534 return $this->getInterwiki() === $title->getInterwiki()
2535 && $this->getNamespace() == $title->getNamespace()
2536 && $this->getDbkey() === $title->getDbkey();
2537 }
2538
2539 /**
2540 * Check if page exists
2541 * @return bool
2542 */
2543 function exists() {
2544 return $this->getArticleId() != 0;
2545 }
2546
2547 /**
2548 * Should a link should be displayed as a known link, just based on its title?
2549 *
2550 * Currently, a self-link with a fragment and special pages are in
2551 * this category. Special pages never exist in the database.
2552 */
2553 function isAlwaysKnown() {
2554 return $this->isExternal() || ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
2555 || NS_SPECIAL == $this->mNamespace;
2556 }
2557
2558 /**
2559 * Update page_touched timestamps and send squid purge messages for
2560 * pages linking to this title. May be sent to the job queue depending
2561 * on the number of links. Typically called on create and delete.
2562 */
2563 function touchLinks() {
2564 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
2565 $u->doUpdate();
2566
2567 if ( $this->getNamespace() == NS_CATEGORY ) {
2568 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
2569 $u->doUpdate();
2570 }
2571 }
2572
2573 /**
2574 * Get the last touched timestamp
2575 */
2576 function getTouched() {
2577 $dbr = wfGetDB( DB_SLAVE );
2578 $touched = $dbr->selectField( 'page', 'page_touched',
2579 array(
2580 'page_namespace' => $this->getNamespace(),
2581 'page_title' => $this->getDBkey()
2582 ), __METHOD__
2583 );
2584 return $touched;
2585 }
2586
2587 /**
2588 * Get a cached value from a global cache that is invalidated when this page changes
2589 * @param string $key the key
2590 * @param callback $callback A callback function which generates the value on cache miss
2591 *
2592 * @deprecated use DependencyWrapper
2593 */
2594 function getRelatedCache( $memc, $key, $expiry, $callback, $params = array() ) {
2595 return DependencyWrapper::getValueFromCache( $memc, $key, $expiry, $callback,
2596 $params, new TitleDependency( $this ) );
2597 }
2598
2599 function trackbackURL() {
2600 global $wgTitle, $wgScriptPath, $wgServer;
2601
2602 return "$wgServer$wgScriptPath/trackback.php?article="
2603 . htmlspecialchars(urlencode($wgTitle->getPrefixedDBkey()));
2604 }
2605
2606 function trackbackRDF() {
2607 $url = htmlspecialchars($this->getFullURL());
2608 $title = htmlspecialchars($this->getText());
2609 $tburl = $this->trackbackURL();
2610
2611 return "
2612 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
2613 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
2614 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
2615 <rdf:Description
2616 rdf:about=\"$url\"
2617 dc:identifier=\"$url\"
2618 dc:title=\"$title\"
2619 trackback:ping=\"$tburl\" />
2620 </rdf:RDF>";
2621 }
2622
2623 /**
2624 * Generate strings used for xml 'id' names in monobook tabs
2625 * @return string
2626 */
2627 function getNamespaceKey() {
2628 global $wgContLang;
2629 switch ($this->getNamespace()) {
2630 case NS_MAIN:
2631 case NS_TALK:
2632 return 'nstab-main';
2633 case NS_USER:
2634 case NS_USER_TALK:
2635 return 'nstab-user';
2636 case NS_MEDIA:
2637 return 'nstab-media';
2638 case NS_SPECIAL:
2639 return 'nstab-special';
2640 case NS_PROJECT:
2641 case NS_PROJECT_TALK:
2642 return 'nstab-project';
2643 case NS_IMAGE:
2644 case NS_IMAGE_TALK:
2645 return 'nstab-image';
2646 case NS_MEDIAWIKI:
2647 case NS_MEDIAWIKI_TALK:
2648 return 'nstab-mediawiki';
2649 case NS_TEMPLATE:
2650 case NS_TEMPLATE_TALK:
2651 return 'nstab-template';
2652 case NS_HELP:
2653 case NS_HELP_TALK:
2654 return 'nstab-help';
2655 case NS_CATEGORY:
2656 case NS_CATEGORY_TALK:
2657 return 'nstab-category';
2658 default:
2659 return 'nstab-' . $wgContLang->lc( $this->getSubjectNsText() );
2660 }
2661 }
2662
2663 /**
2664 * Returns true if this title resolves to the named special page
2665 * @param string $name The special page name
2666 * @access public
2667 */
2668 function isSpecial( $name ) {
2669 if ( $this->getNamespace() == NS_SPECIAL ) {
2670 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
2671 if ( $name == $thisName ) {
2672 return true;
2673 }
2674 }
2675 return false;
2676 }
2677
2678 /**
2679 * If the Title refers to a special page alias which is not the local default,
2680 * returns a new Title which points to the local default. Otherwise, returns $this.
2681 */
2682 function fixSpecialName() {
2683 if ( $this->getNamespace() == NS_SPECIAL ) {
2684 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
2685 if ( $canonicalName ) {
2686 $localName = SpecialPage::getLocalNameFor( $canonicalName );
2687 if ( $localName != $this->mDbkeyform ) {
2688 return Title::makeTitle( NS_SPECIAL, $localName );
2689 }
2690 }
2691 }
2692 return $this;
2693 }
2694
2695 /**
2696 * Is this Title in a namespace which contains content?
2697 * In other words, is this a content page, for the purposes of calculating
2698 * statistics, etc?
2699 *
2700 * @return bool
2701 */
2702 public function isContentPage() {
2703 return Namespace::isContent( $this->getNamespace() );
2704 }
2705
2706 }
2707
2708 ?>