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