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