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