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