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