API: BREAKING CHANGE: (bug 28541) Output of binary ICU sortkeys is broken. Change...
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * See title.txt
4 * @file
5 */
6
7 /**
8 * @deprecated This used to be a define, but was moved to
9 * Title::GAID_FOR_UPDATE in 1.17. This will probably be removed in 1.18
10 */
11 define( 'GAID_FOR_UPDATE', Title::GAID_FOR_UPDATE );
12
13 /**
14 * Represents a title within MediaWiki.
15 * Optionally may contain an interwiki designation or namespace.
16 * @note This class can fetch various kinds of data from the database;
17 * however, it does so inefficiently.
18 *
19 * @internal documentation reviewed 15 Mar 2010
20 */
21 class Title {
22 /** @name Static cache variables */
23 // @{
24 static private $titleCache = array();
25 // @}
26
27 /**
28 * Title::newFromText maintains a cache to avoid expensive re-normalization of
29 * commonly used titles. On a batch operation this can become a memory leak
30 * if not bounded. After hitting this many titles reset the cache.
31 */
32 const CACHE_MAX = 1000;
33
34 /**
35 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
36 * to use the master DB
37 */
38 const GAID_FOR_UPDATE = 1;
39
40
41 /**
42 * @name Private member variables
43 * Please use the accessor functions instead.
44 * @private
45 */
46 // @{
47
48 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
49 var $mUrlform = ''; // /< URL-encoded form of the main part
50 var $mDbkeyform = ''; // /< Main part with underscores
51 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
52 var $mNamespace = NS_MAIN; // /< Namespace index, i.e. one of the NS_xxxx constants
53 var $mInterwiki = ''; // /< Interwiki prefix (or null string)
54 var $mFragment; // /< Title fragment (i.e. the bit after the #)
55 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
56 var $mLatestID = false; // /< ID of most recent revision
57 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
58 var $mOldRestrictions = false;
59 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
60 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
61 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
62 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
63 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
64 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
65 var $mPrefixedText; ///< Text form including namespace/interwiki, initialised on demand
66 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
67 # Don't change the following default, NS_MAIN is hardcoded in several
68 # places. See bug 696.
69 var $mDefaultNamespace = NS_MAIN; // /< Namespace index when there is no namespace
70 # Zero except in {{transclusion}} tags
71 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
72 var $mLength = -1; // /< The page length, 0 for special pages
73 var $mRedirect = null; // /< Is the article at this title a redirect?
74 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
75 var $mBacklinkCache = null; // /< Cache of links to this title
76 // @}
77
78
79 /**
80 * Constructor
81 * @private
82 */
83 /* private */ function __construct() { }
84
85 /**
86 * Create a new Title from a prefixed DB key
87 *
88 * @param $key String the database key, which has underscores
89 * instead of spaces, possibly including namespace and
90 * interwiki prefixes
91 * @return Title, or NULL on an error
92 */
93 public static function newFromDBkey( $key ) {
94 $t = new Title();
95 $t->mDbkeyform = $key;
96 if ( $t->secureAndSplit() ) {
97 return $t;
98 } else {
99 return null;
100 }
101 }
102
103 /**
104 * Create a new Title from text, such as what one would find in a link. De-
105 * codes any HTML entities in the text.
106 *
107 * @param $text String the link text; spaces, prefixes, and an
108 * initial ':' indicating the main namespace are accepted.
109 * @param $defaultNamespace Int the namespace to use if none is speci-
110 * fied by a prefix. If you want to force a specific namespace even if
111 * $text might begin with a namespace prefix, use makeTitle() or
112 * makeTitleSafe().
113 * @return Title, 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 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
133 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
134
135 $t = new Title();
136 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
137 $t->mDefaultNamespace = $defaultNamespace;
138
139 static $cachedcount = 0 ;
140 if ( $t->secureAndSplit() ) {
141 if ( $defaultNamespace == NS_MAIN ) {
142 if ( $cachedcount >= self::CACHE_MAX ) {
143 # Avoid memory leaks on mass operations...
144 Title::$titleCache = array();
145 $cachedcount = 0;
146 }
147 $cachedcount++;
148 Title::$titleCache[$text] =& $t;
149 }
150 return $t;
151 } else {
152 $ret = null;
153 return $ret;
154 }
155 }
156
157 /**
158 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
159 *
160 * Example of wrong and broken code:
161 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
162 *
163 * Example of right code:
164 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
165 *
166 * Create a new Title from URL-encoded text. Ensures that
167 * the given title's length does not exceed the maximum.
168 *
169 * @param $url String the title, as might be taken from a URL
170 * @return Title the new object, or NULL on an error
171 */
172 public static function newFromURL( $url ) {
173 global $wgLegalTitleChars;
174 $t = new Title();
175
176 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
177 # but some URLs used it as a space replacement and they still come
178 # from some external search tools.
179 if ( strpos( $wgLegalTitleChars, '+' ) === false ) {
180 $url = str_replace( '+', ' ', $url );
181 }
182
183 $t->mDbkeyform = str_replace( ' ', '_', $url );
184 if ( $t->secureAndSplit() ) {
185 return $t;
186 } else {
187 return null;
188 }
189 }
190
191 /**
192 * Create a new Title from an article ID
193 *
194 * @param $id Int the page_id corresponding to the Title to create
195 * @param $flags Int use Title::GAID_FOR_UPDATE to use master
196 * @return Title the new object, or NULL on an error
197 */
198 public static function newFromID( $id, $flags = 0 ) {
199 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
200 $row = $db->selectRow( 'page', '*', array( 'page_id' => $id ), __METHOD__ );
201 if ( $row !== false ) {
202 $title = Title::newFromRow( $row );
203 } else {
204 $title = null;
205 }
206 return $title;
207 }
208
209 /**
210 * Make an array of titles from an array of IDs
211 *
212 * @param $ids Array of Int Array of IDs
213 * @return Array of Titles
214 */
215 public static function newFromIDs( $ids ) {
216 if ( !count( $ids ) ) {
217 return array();
218 }
219 $dbr = wfGetDB( DB_SLAVE );
220
221 $res = $dbr->select(
222 'page',
223 array(
224 'page_namespace', 'page_title', 'page_id',
225 'page_len', 'page_is_redirect', 'page_latest',
226 ),
227 array( 'page_id' => $ids ),
228 __METHOD__
229 );
230
231 $titles = array();
232 foreach ( $res as $row ) {
233 $titles[] = Title::newFromRow( $row );
234 }
235 return $titles;
236 }
237
238 /**
239 * Make a Title object from a DB row
240 *
241 * @param $row Object database row (needs at least page_title,page_namespace)
242 * @return Title corresponding Title
243 */
244 public static function newFromRow( $row ) {
245 $t = self::makeTitle( $row->page_namespace, $row->page_title );
246
247 $t->mArticleID = isset( $row->page_id ) ? intval( $row->page_id ) : -1;
248 $t->mLength = isset( $row->page_len ) ? intval( $row->page_len ) : -1;
249 $t->mRedirect = isset( $row->page_is_redirect ) ? (bool)$row->page_is_redirect : null;
250 $t->mLatestID = isset( $row->page_latest ) ? intval( $row->page_latest ) : false;
251
252 return $t;
253 }
254
255 /**
256 * Create a new Title from a namespace index and a DB key.
257 * It's assumed that $ns and $title are *valid*, for instance when
258 * they came directly from the database or a special page name.
259 * For convenience, spaces are converted to underscores so that
260 * eg user_text fields can be used directly.
261 *
262 * @param $ns Int the namespace of the article
263 * @param $title String the unprefixed database key form
264 * @param $fragment String the link fragment (after the "#")
265 * @param $interwiki String the interwiki prefix
266 * @return Title the new object
267 */
268 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
269 $t = new Title();
270 $t->mInterwiki = $interwiki;
271 $t->mFragment = $fragment;
272 $t->mNamespace = $ns = intval( $ns );
273 $t->mDbkeyform = str_replace( ' ', '_', $title );
274 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
275 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
276 $t->mTextform = str_replace( '_', ' ', $title );
277 return $t;
278 }
279
280 /**
281 * Create a new Title from a namespace index and a DB key.
282 * The parameters will be checked for validity, which is a bit slower
283 * than makeTitle() but safer for user-provided data.
284 *
285 * @param $ns Int the namespace of the article
286 * @param $title String database key form
287 * @param $fragment String the link fragment (after the "#")
288 * @param $interwiki String interwiki prefix
289 * @return Title the new object, or NULL on an error
290 */
291 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
292 $t = new Title();
293 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki );
294 if ( $t->secureAndSplit() ) {
295 return $t;
296 } else {
297 return null;
298 }
299 }
300
301 /**
302 * Create a new Title for the Main Page
303 *
304 * @return Title the new object
305 */
306 public static function newMainPage() {
307 $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
308 // Don't give fatal errors if the message is broken
309 if ( !$title ) {
310 $title = Title::newFromText( 'Main Page' );
311 }
312 return $title;
313 }
314
315 /**
316 * Extract a redirect destination from a string and return the
317 * Title, or null if the text doesn't contain a valid redirect
318 * This will only return the very next target, useful for
319 * the redirect table and other checks that don't need full recursion
320 *
321 * @param $text String: Text with possible redirect
322 * @return Title: The corresponding Title
323 */
324 public static function newFromRedirect( $text ) {
325 return self::newFromRedirectInternal( $text );
326 }
327
328 /**
329 * Extract a redirect destination from a string and return the
330 * Title, or null if the text doesn't contain a valid redirect
331 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
332 * in order to provide (hopefully) the Title of the final destination instead of another redirect
333 *
334 * @param $text String Text with possible redirect
335 * @return Title
336 */
337 public static function newFromRedirectRecurse( $text ) {
338 $titles = self::newFromRedirectArray( $text );
339 return $titles ? array_pop( $titles ) : null;
340 }
341
342 /**
343 * Extract a redirect destination from a string and return an
344 * array of Titles, or null if the text doesn't contain a valid redirect
345 * The last element in the array is the final destination after all redirects
346 * have been resolved (up to $wgMaxRedirects times)
347 *
348 * @param $text String Text with possible redirect
349 * @return Array of Titles, with the destination last
350 */
351 public static function newFromRedirectArray( $text ) {
352 global $wgMaxRedirects;
353 $title = self::newFromRedirectInternal( $text );
354 if ( is_null( $title ) ) {
355 return null;
356 }
357 // recursive check to follow double redirects
358 $recurse = $wgMaxRedirects;
359 $titles = array( $title );
360 while ( --$recurse > 0 ) {
361 if ( $title->isRedirect() ) {
362 $article = new Article( $title, 0 );
363 $newtitle = $article->getRedirectTarget();
364 } else {
365 break;
366 }
367 // Redirects to some special pages are not permitted
368 if ( $newtitle instanceOf Title && $newtitle->isValidRedirectTarget() ) {
369 // the new title passes the checks, so make that our current title so that further recursion can be checked
370 $title = $newtitle;
371 $titles[] = $newtitle;
372 } else {
373 break;
374 }
375 }
376 return $titles;
377 }
378
379 /**
380 * Really extract the redirect destination
381 * Do not call this function directly, use one of the newFromRedirect* functions above
382 *
383 * @param $text String Text with possible redirect
384 * @return Title
385 */
386 protected static function newFromRedirectInternal( $text ) {
387 global $wgMaxRedirects;
388 if ( $wgMaxRedirects < 1 ) {
389 //redirects are disabled, so quit early
390 return null;
391 }
392 $redir = MagicWord::get( 'redirect' );
393 $text = trim( $text );
394 if ( $redir->matchStartAndRemove( $text ) ) {
395 // Extract the first link and see if it's usable
396 // Ensure that it really does come directly after #REDIRECT
397 // Some older redirects included a colon, so don't freak about that!
398 $m = array();
399 if ( preg_match( '!^\s*:?\s*\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
400 // Strip preceding colon used to "escape" categories, etc.
401 // and URL-decode links
402 if ( strpos( $m[1], '%' ) !== false ) {
403 // Match behavior of inline link parsing here;
404 $m[1] = rawurldecode( ltrim( $m[1], ':' ) );
405 }
406 $title = Title::newFromText( $m[1] );
407 // If the title is a redirect to bad special pages or is invalid, return null
408 if ( !$title instanceof Title || !$title->isValidRedirectTarget() ) {
409 return null;
410 }
411 return $title;
412 }
413 }
414 return null;
415 }
416
417 # ----------------------------------------------------------------------------
418 # Static functions
419 # ----------------------------------------------------------------------------
420
421 /**
422 * Get the prefixed DB key associated with an ID
423 *
424 * @param $id Int the page_id of the article
425 * @return Title an object representing the article, or NULL if no such article was found
426 */
427 public static function nameOf( $id ) {
428 $dbr = wfGetDB( DB_SLAVE );
429
430 $s = $dbr->selectRow(
431 'page',
432 array( 'page_namespace', 'page_title' ),
433 array( 'page_id' => $id ),
434 __METHOD__
435 );
436 if ( $s === false ) {
437 return null;
438 }
439
440 $n = self::makeName( $s->page_namespace, $s->page_title );
441 return $n;
442 }
443
444 /**
445 * Get a regex character class describing the legal characters in a link
446 *
447 * @return String the list of characters, not delimited
448 */
449 public static function legalChars() {
450 global $wgLegalTitleChars;
451 return $wgLegalTitleChars;
452 }
453
454 /**
455 * Get a string representation of a title suitable for
456 * including in a search index
457 *
458 * @param $ns Int a namespace index
459 * @param $title String text-form main part
460 * @return String a stripped-down title string ready for the search index
461 */
462 public static function indexTitle( $ns, $title ) {
463 global $wgContLang;
464
465 $lc = SearchEngine::legalSearchChars() . '&#;';
466 $t = $wgContLang->normalizeForSearch( $title );
467 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
468 $t = $wgContLang->lc( $t );
469
470 # Handle 's, s'
471 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
472 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
473
474 $t = preg_replace( "/\\s+/", ' ', $t );
475
476 if ( $ns == NS_FILE ) {
477 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
478 }
479 return trim( $t );
480 }
481
482 /**
483 * Make a prefixed DB key from a DB key and a namespace index
484 *
485 * @param $ns Int numerical representation of the namespace
486 * @param $title String the DB key form the title
487 * @param $fragment String The link fragment (after the "#")
488 * @param $interwiki String The interwiki prefix
489 * @return String the prefixed form of the title
490 */
491 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
492 global $wgContLang;
493
494 $namespace = $wgContLang->getNsText( $ns );
495 $name = $namespace == '' ? $title : "$namespace:$title";
496 if ( strval( $interwiki ) != '' ) {
497 $name = "$interwiki:$name";
498 }
499 if ( strval( $fragment ) != '' ) {
500 $name .= '#' . $fragment;
501 }
502 return $name;
503 }
504
505 /**
506 * Determine whether the object refers to a page within
507 * this project.
508 *
509 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
510 */
511 public function isLocal() {
512 if ( $this->mInterwiki != '' ) {
513 return Interwiki::fetch( $this->mInterwiki )->isLocal();
514 } else {
515 return true;
516 }
517 }
518
519 /**
520 * Determine whether the object refers to a page within
521 * this project and is transcludable.
522 *
523 * @return Bool TRUE if this is transcludable
524 */
525 public function isTrans() {
526 if ( $this->mInterwiki == '' ) {
527 return false;
528 }
529
530 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
531 }
532
533 /**
534 * Returns the DB name of the distant wiki which owns the object.
535 *
536 * @return String the DB name
537 */
538 public function getTransWikiID() {
539 if ( $this->mInterwiki == '' ) {
540 return false;
541 }
542
543 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
544 }
545
546 /**
547 * Escape a text fragment, say from a link, for a URL
548 *
549 * @param $fragment string containing a URL or link fragment (after the "#")
550 * @return String: escaped string
551 */
552 static function escapeFragmentForURL( $fragment ) {
553 # Note that we don't urlencode the fragment. urlencoded Unicode
554 # fragments appear not to work in IE (at least up to 7) or in at least
555 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
556 # to care if they aren't encoded.
557 return Sanitizer::escapeId( $fragment, 'noninitial' );
558 }
559
560 # ----------------------------------------------------------------------------
561 # Other stuff
562 # ----------------------------------------------------------------------------
563
564 /** Simple accessors */
565 /**
566 * Get the text form (spaces not underscores) of the main part
567 *
568 * @return String Main part of the title
569 */
570 public function getText() { return $this->mTextform; }
571
572 /**
573 * Get the URL-encoded form of the main part
574 *
575 * @return String Main part of the title, URL-encoded
576 */
577 public function getPartialURL() { return $this->mUrlform; }
578
579 /**
580 * Get the main part with underscores
581 *
582 * @return String: Main part of the title, with underscores
583 */
584 public function getDBkey() { return $this->mDbkeyform; }
585
586 /**
587 * Get the namespace index, i.e. one of the NS_xxxx constants.
588 *
589 * @return Integer: Namespace index
590 */
591 public function getNamespace() { return $this->mNamespace; }
592
593 /**
594 * Get the namespace text
595 *
596 * @return String: Namespace text
597 */
598 public function getNsText() {
599 global $wgContLang;
600
601 if ( $this->mInterwiki != '' ) {
602 // This probably shouldn't even happen. ohh man, oh yuck.
603 // But for interwiki transclusion it sometimes does.
604 // Shit. Shit shit shit.
605 //
606 // Use the canonical namespaces if possible to try to
607 // resolve a foreign namespace.
608 if ( MWNamespace::exists( $this->mNamespace ) ) {
609 return MWNamespace::getCanonicalName( $this->mNamespace );
610 }
611 }
612
613 if ( $wgContLang->needsGenderDistinction() &&
614 MWNamespace::hasGenderDistinction( $this->mNamespace ) ) {
615 $gender = GenderCache::singleton()->getGenderOf( $this->getText(), __METHOD__ );
616 return $wgContLang->getGenderNsText( $this->mNamespace, $gender );
617 }
618
619 return $wgContLang->getNsText( $this->mNamespace );
620 }
621
622 /**
623 * Get the DB key with the initial letter case as specified by the user
624 *
625 * @return String DB key
626 */
627 function getUserCaseDBKey() {
628 return $this->mUserCaseDBKey;
629 }
630
631 /**
632 * Get the namespace text of the subject (rather than talk) page
633 *
634 * @return String Namespace text
635 */
636 public function getSubjectNsText() {
637 global $wgContLang;
638 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
639 }
640
641 /**
642 * Get the namespace text of the talk page
643 *
644 * @return String Namespace text
645 */
646 public function getTalkNsText() {
647 global $wgContLang;
648 return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
649 }
650
651 /**
652 * Could this title have a corresponding talk page?
653 *
654 * @return Bool TRUE or FALSE
655 */
656 public function canTalk() {
657 return( MWNamespace::canTalk( $this->mNamespace ) );
658 }
659
660 /**
661 * Get the interwiki prefix (or null string)
662 *
663 * @return String Interwiki prefix
664 */
665 public function getInterwiki() { return $this->mInterwiki; }
666
667 /**
668 * Get the Title fragment (i.e.\ the bit after the #) in text form
669 *
670 * @return String Title fragment
671 */
672 public function getFragment() { return $this->mFragment; }
673
674 /**
675 * Get the fragment in URL form, including the "#" character if there is one
676 * @return String Fragment in URL form
677 */
678 public function getFragmentForURL() {
679 if ( $this->mFragment == '' ) {
680 return '';
681 } else {
682 return '#' . Title::escapeFragmentForURL( $this->mFragment );
683 }
684 }
685
686 /**
687 * Get the default namespace index, for when there is no namespace
688 *
689 * @return Int Default namespace index
690 */
691 public function getDefaultNamespace() { return $this->mDefaultNamespace; }
692
693 /**
694 * Get title for search index
695 *
696 * @return String a stripped-down title string ready for the
697 * search index
698 */
699 public function getIndexTitle() {
700 return Title::indexTitle( $this->mNamespace, $this->mTextform );
701 }
702
703 /**
704 * Get the prefixed database key form
705 *
706 * @return String the prefixed title, with underscores and
707 * any interwiki and namespace prefixes
708 */
709 public function getPrefixedDBkey() {
710 $s = $this->prefix( $this->mDbkeyform );
711 $s = str_replace( ' ', '_', $s );
712 return $s;
713 }
714
715 /**
716 * Get the prefixed title with spaces.
717 * This is the form usually used for display
718 *
719 * @return String the prefixed title, with spaces
720 */
721 public function getPrefixedText() {
722 if ( empty( $this->mPrefixedText ) ) { // FIXME: bad usage of empty() ?
723 $s = $this->prefix( $this->mTextform );
724 $s = str_replace( '_', ' ', $s );
725 $this->mPrefixedText = $s;
726 }
727 return $this->mPrefixedText;
728 }
729
730 /**
731 * Get the prefixed title with spaces, plus any fragment
732 * (part beginning with '#')
733 *
734 * @return String the prefixed title, with spaces and the fragment, including '#'
735 */
736 public function getFullText() {
737 $text = $this->getPrefixedText();
738 if ( $this->mFragment != '' ) {
739 $text .= '#' . $this->mFragment;
740 }
741 return $text;
742 }
743
744 /**
745 * Get the base name, i.e. the leftmost parts before the /
746 *
747 * @return String Base name
748 */
749 public function getBaseText() {
750 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
751 return $this->getText();
752 }
753
754 $parts = explode( '/', $this->getText() );
755 # Don't discard the real title if there's no subpage involved
756 if ( count( $parts ) > 1 ) {
757 unset( $parts[count( $parts ) - 1] );
758 }
759 return implode( '/', $parts );
760 }
761
762 /**
763 * Get the lowest-level subpage name, i.e. the rightmost part after /
764 *
765 * @return String Subpage name
766 */
767 public function getSubpageText() {
768 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
769 return( $this->mTextform );
770 }
771 $parts = explode( '/', $this->mTextform );
772 return( $parts[count( $parts ) - 1] );
773 }
774
775 /**
776 * Get a URL-encoded form of the subpage text
777 *
778 * @return String URL-encoded subpage name
779 */
780 public function getSubpageUrlForm() {
781 $text = $this->getSubpageText();
782 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
783 return( $text );
784 }
785
786 /**
787 * Get a URL-encoded title (not an actual URL) including interwiki
788 *
789 * @return String the URL-encoded form
790 */
791 public function getPrefixedURL() {
792 $s = $this->prefix( $this->mDbkeyform );
793 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
794 return $s;
795 }
796
797 /**
798 * Get a real URL referring to this title, with interwiki link and
799 * fragment
800 *
801 * @param $query \twotypes{\string,\array} an optional query string, not used for interwiki
802 * links. Can be specified as an associative array as well, e.g.,
803 * array( 'action' => 'edit' ) (keys and values will be URL-escaped).
804 * @param $variant String language variant of url (for sr, zh..)
805 * @return String the URL
806 */
807 public function getFullURL( $query = '', $variant = false ) {
808 global $wgServer, $wgRequest;
809
810 if ( is_array( $query ) ) {
811 $query = wfArrayToCGI( $query );
812 }
813
814 $interwiki = Interwiki::fetch( $this->mInterwiki );
815 if ( !$interwiki ) {
816 $url = $this->getLocalURL( $query, $variant );
817
818 // Ugly quick hack to avoid duplicate prefixes (bug 4571 etc)
819 // Correct fix would be to move the prepending elsewhere.
820 if ( $wgRequest->getVal( 'action' ) != 'render' ) {
821 $url = $wgServer . $url;
822 }
823 } else {
824 $baseUrl = $interwiki->getURL();
825
826 $namespace = wfUrlencode( $this->getNsText() );
827 if ( $namespace != '' ) {
828 # Can this actually happen? Interwikis shouldn't be parsed.
829 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
830 $namespace .= ':';
831 }
832 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
833 $url = wfAppendQuery( $url, $query );
834 }
835
836 # Finally, add the fragment.
837 $url .= $this->getFragmentForURL();
838
839 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
840 return $url;
841 }
842
843 /**
844 * Get a URL with no fragment or server name. If this page is generated
845 * with action=render, $wgServer is prepended.
846 *
847 * @param $query Mixed: an optional query string; if not specified,
848 * $wgArticlePath will be used. Can be specified as an associative array
849 * as well, e.g., array( 'action' => 'edit' ) (keys and values will be
850 * URL-escaped).
851 * @param $variant String language variant of url (for sr, zh..)
852 * @return String the URL
853 */
854 public function getLocalURL( $query = '', $variant = false ) {
855 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
856 global $wgVariantArticlePath, $wgContLang;
857
858 if ( is_array( $query ) ) {
859 $query = wfArrayToCGI( $query );
860 }
861
862 if ( $this->isExternal() ) {
863 $url = $this->getFullURL();
864 if ( $query ) {
865 // This is currently only used for edit section links in the
866 // context of interwiki transclusion. In theory we should
867 // append the query to the end of any existing query string,
868 // but interwiki transclusion is already broken in that case.
869 $url .= "?$query";
870 }
871 } else {
872 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
873 if ( $query == '' ) {
874 if ( $variant != false && $wgContLang->hasVariants() ) {
875 if ( !$wgVariantArticlePath ) {
876 $variantArticlePath = "$wgScript?title=$1&variant=$2"; // default
877 } else {
878 $variantArticlePath = $wgVariantArticlePath;
879 }
880 $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
881 $url = str_replace( '$1', $dbkey, $url );
882 } else {
883 $url = str_replace( '$1', $dbkey, $wgArticlePath );
884 }
885 } else {
886 global $wgActionPaths;
887 $url = false;
888 $matches = array();
889 if ( !empty( $wgActionPaths ) &&
890 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
891 {
892 $action = urldecode( $matches[2] );
893 if ( isset( $wgActionPaths[$action] ) ) {
894 $query = $matches[1];
895 if ( isset( $matches[4] ) ) {
896 $query .= $matches[4];
897 }
898 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
899 if ( $query != '' ) {
900 $url = wfAppendQuery( $url, $query );
901 }
902 }
903 }
904 if ( $url === false ) {
905 if ( $query == '-' ) {
906 $query = '';
907 }
908 $url = "{$wgScript}?title={$dbkey}&{$query}";
909 }
910 }
911
912 // FIXME: this causes breakage in various places when we
913 // actually expected a local URL and end up with dupe prefixes.
914 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
915 $url = $wgServer . $url;
916 }
917 }
918 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
919 return $url;
920 }
921
922 /**
923 * Get a URL that's the simplest URL that will be valid to link, locally,
924 * to the current Title. It includes the fragment, but does not include
925 * the server unless action=render is used (or the link is external). If
926 * there's a fragment but the prefixed text is empty, we just return a link
927 * to the fragment.
928 *
929 * The result obviously should not be URL-escaped, but does need to be
930 * HTML-escaped if it's being output in HTML.
931 *
932 * @param $query Array of Strings An associative array of key => value pairs for the
933 * query string. Keys and values will be escaped.
934 * @param $variant String language variant of URL (for sr, zh..). Ignored
935 * for external links. Default is "false" (same variant as current page,
936 * for anonymous users).
937 * @return String the URL
938 */
939 public function getLinkUrl( $query = array(), $variant = false ) {
940 wfProfileIn( __METHOD__ );
941 if ( $this->isExternal() ) {
942 $ret = $this->getFullURL( $query );
943 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
944 $ret = $this->getFragmentForURL();
945 } else {
946 $ret = $this->getLocalURL( $query, $variant ) . $this->getFragmentForURL();
947 }
948 wfProfileOut( __METHOD__ );
949 return $ret;
950 }
951
952 /**
953 * Get an HTML-escaped version of the URL form, suitable for
954 * using in a link, without a server name or fragment
955 *
956 * @param $query String an optional query string
957 * @return String the URL
958 */
959 public function escapeLocalURL( $query = '' ) {
960 return htmlspecialchars( $this->getLocalURL( $query ) );
961 }
962
963 /**
964 * Get an HTML-escaped version of the URL form, suitable for
965 * using in a link, including the server name and fragment
966 *
967 * @param $query String an optional query string
968 * @return String the URL
969 */
970 public function escapeFullURL( $query = '' ) {
971 return htmlspecialchars( $this->getFullURL( $query ) );
972 }
973
974 /**
975 * Get the URL form for an internal link.
976 * - Used in various Squid-related code, in case we have a different
977 * internal hostname for the server from the exposed one.
978 *
979 * @param $query String an optional query string
980 * @param $variant String language variant of url (for sr, zh..)
981 * @return String the URL
982 */
983 public function getInternalURL( $query = '', $variant = false ) {
984 global $wgInternalServer, $wgServer;
985 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
986 $url = $server . $this->getLocalURL( $query, $variant );
987 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
988 return $url;
989 }
990
991 /**
992 * Get the edit URL for this Title
993 *
994 * @return String the URL, or a null string if this is an
995 * interwiki link
996 */
997 public function getEditURL() {
998 if ( $this->mInterwiki != '' ) {
999 return '';
1000 }
1001 $s = $this->getLocalURL( 'action=edit' );
1002
1003 return $s;
1004 }
1005
1006 /**
1007 * Get the HTML-escaped displayable text form.
1008 * Used for the title field in <a> tags.
1009 *
1010 * @return String the text, including any prefixes
1011 */
1012 public function getEscapedText() {
1013 return htmlspecialchars( $this->getPrefixedText() );
1014 }
1015
1016 /**
1017 * Is this Title interwiki?
1018 *
1019 * @return Bool
1020 */
1021 public function isExternal() {
1022 return ( $this->mInterwiki != '' );
1023 }
1024
1025 /**
1026 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1027 *
1028 * @param $action String Action to check (default: edit)
1029 * @return Bool
1030 */
1031 public function isSemiProtected( $action = 'edit' ) {
1032 if ( $this->exists() ) {
1033 $restrictions = $this->getRestrictions( $action );
1034 if ( count( $restrictions ) > 0 ) {
1035 foreach ( $restrictions as $restriction ) {
1036 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1037 return false;
1038 }
1039 }
1040 } else {
1041 # Not protected
1042 return false;
1043 }
1044 return true;
1045 } else {
1046 # If it doesn't exist, it can't be protected
1047 return false;
1048 }
1049 }
1050
1051 /**
1052 * Does the title correspond to a protected article?
1053 *
1054 * @param $action String the action the page is protected from,
1055 * by default checks all actions.
1056 * @return Bool
1057 */
1058 public function isProtected( $action = '' ) {
1059 global $wgRestrictionLevels;
1060
1061 $restrictionTypes = $this->getRestrictionTypes();
1062
1063 # Special pages have inherent protection
1064 if( $this->getNamespace() == NS_SPECIAL ) {
1065 return true;
1066 }
1067
1068 # Check regular protection levels
1069 foreach ( $restrictionTypes as $type ) {
1070 if ( $action == $type || $action == '' ) {
1071 $r = $this->getRestrictions( $type );
1072 foreach ( $wgRestrictionLevels as $level ) {
1073 if ( in_array( $level, $r ) && $level != '' ) {
1074 return true;
1075 }
1076 }
1077 }
1078 }
1079
1080 return false;
1081 }
1082
1083 /**
1084 * Is this a conversion table for the LanguageConverter?
1085 *
1086 * @return Bool
1087 */
1088 public function isConversionTable() {
1089 if(
1090 $this->getNamespace() == NS_MEDIAWIKI &&
1091 strpos( $this->getText(), 'Conversiontable' ) !== false
1092 )
1093 {
1094 return true;
1095 }
1096
1097 return false;
1098 }
1099
1100 /**
1101 * Is $wgUser watching this page?
1102 *
1103 * @return Bool
1104 */
1105 public function userIsWatching() {
1106 global $wgUser;
1107
1108 if ( is_null( $this->mWatched ) ) {
1109 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1110 $this->mWatched = false;
1111 } else {
1112 $this->mWatched = $wgUser->isWatched( $this );
1113 }
1114 }
1115 return $this->mWatched;
1116 }
1117
1118 /**
1119 * Can $wgUser perform $action on this page?
1120 * This skips potentially expensive cascading permission checks
1121 * as well as avoids expensive error formatting
1122 *
1123 * Suitable for use for nonessential UI controls in common cases, but
1124 * _not_ for functional access control.
1125 *
1126 * May provide false positives, but should never provide a false negative.
1127 *
1128 * @param $action String action that permission needs to be checked for
1129 * @return Bool
1130 */
1131 public function quickUserCan( $action ) {
1132 return $this->userCan( $action, false );
1133 }
1134
1135 /**
1136 * Determines if $user is unable to edit this page because it has been protected
1137 * by $wgNamespaceProtection.
1138 *
1139 * @param $user User object, $wgUser will be used if not passed
1140 * @return Bool
1141 */
1142 public function isNamespaceProtected( User $user = null ) {
1143 global $wgNamespaceProtection;
1144
1145 if ( $user === null ) {
1146 global $wgUser;
1147 $user = $wgUser;
1148 }
1149
1150 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
1151 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
1152 if ( $right != '' && !$user->isAllowed( $right ) ) {
1153 return true;
1154 }
1155 }
1156 }
1157 return false;
1158 }
1159
1160 /**
1161 * Can $wgUser perform $action on this page?
1162 *
1163 * @param $action String action that permission needs to be checked for
1164 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1165 * @return Bool
1166 */
1167 public function userCan( $action, $doExpensiveQueries = true ) {
1168 global $wgUser;
1169 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1170 }
1171
1172 /**
1173 * Can $user perform $action on this page?
1174 *
1175 * FIXME: This *does not* check throttles (User::pingLimiter()).
1176 *
1177 * @param $action String action that permission needs to be checked for
1178 * @param $user User to check
1179 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1180 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1181 * @return Array of arguments to wfMsg to explain permissions problems.
1182 */
1183 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1184 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1185
1186 // Remove the errors being ignored.
1187 foreach ( $errors as $index => $error ) {
1188 $error_key = is_array( $error ) ? $error[0] : $error;
1189
1190 if ( in_array( $error_key, $ignoreErrors ) ) {
1191 unset( $errors[$index] );
1192 }
1193 }
1194
1195 return $errors;
1196 }
1197
1198 /**
1199 * Permissions checks that fail most often, and which are easiest to test.
1200 *
1201 * @param $action String the action to check
1202 * @param $user User user to check
1203 * @param $errors Array list of current errors
1204 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1205 * @param $short Boolean short circuit on first error
1206 *
1207 * @return Array list of errors
1208 */
1209 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1210 if ( $action == 'create' ) {
1211 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1212 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1213 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1214 }
1215 } elseif ( $action == 'move' ) {
1216 if ( !$user->isAllowed( 'move-rootuserpages' )
1217 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1218 // Show user page-specific message only if the user can move other pages
1219 $errors[] = array( 'cant-move-user-page' );
1220 }
1221
1222 // Check if user is allowed to move files if it's a file
1223 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1224 $errors[] = array( 'movenotallowedfile' );
1225 }
1226
1227 if ( !$user->isAllowed( 'move' ) ) {
1228 // User can't move anything
1229 global $wgGroupPermissions;
1230 $userCanMove = false;
1231 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1232 $userCanMove = $wgGroupPermissions['user']['move'];
1233 }
1234 $autoconfirmedCanMove = false;
1235 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1236 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1237 }
1238 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1239 // custom message if logged-in users without any special rights can move
1240 $errors[] = array( 'movenologintext' );
1241 } else {
1242 $errors[] = array( 'movenotallowed' );
1243 }
1244 }
1245 } elseif ( $action == 'move-target' ) {
1246 if ( !$user->isAllowed( 'move' ) ) {
1247 // User can't move anything
1248 $errors[] = array( 'movenotallowed' );
1249 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1250 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1251 // Show user page-specific message only if the user can move other pages
1252 $errors[] = array( 'cant-move-to-user-page' );
1253 }
1254 } elseif ( !$user->isAllowed( $action ) ) {
1255 // We avoid expensive display logic for quickUserCan's and such
1256 $groups = false;
1257 if ( !$short ) {
1258 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1259 User::getGroupsWithPermission( $action ) );
1260 }
1261
1262 if ( $groups ) {
1263 global $wgLang;
1264 $return = array(
1265 'badaccess-groups',
1266 $wgLang->commaList( $groups ),
1267 count( $groups )
1268 );
1269 } else {
1270 $return = array( 'badaccess-group0' );
1271 }
1272 $errors[] = $return;
1273 }
1274
1275 return $errors;
1276 }
1277
1278 /**
1279 * Add the resulting error code to the errors array
1280 *
1281 * @param $errors Array list of current errors
1282 * @param $result Mixed result of errors
1283 *
1284 * @return Array list of errors
1285 */
1286 private function resultToError( $errors, $result ) {
1287 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1288 // A single array representing an error
1289 $errors[] = $result;
1290 } else if ( is_array( $result ) && is_array( $result[0] ) ) {
1291 // A nested array representing multiple errors
1292 $errors = array_merge( $errors, $result );
1293 } else if ( $result !== '' && is_string( $result ) ) {
1294 // A string representing a message-id
1295 $errors[] = array( $result );
1296 } else if ( $result === false ) {
1297 // a generic "We don't want them to do that"
1298 $errors[] = array( 'badaccess-group0' );
1299 }
1300 return $errors;
1301 }
1302
1303 /**
1304 * Check various permission hooks
1305 *
1306 * @param $action String the action to check
1307 * @param $user User user to check
1308 * @param $errors Array list of current errors
1309 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1310 * @param $short Boolean short circuit on first error
1311 *
1312 * @return Array list of errors
1313 */
1314 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1315 // Use getUserPermissionsErrors instead
1316 $result = '';
1317 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1318 return $result ? array() : array( array( 'badaccess-group0' ) );
1319 }
1320 // Check getUserPermissionsErrors hook
1321 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1322 $errors = $this->resultToError( $errors, $result );
1323 }
1324 // Check getUserPermissionsErrorsExpensive hook
1325 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1326 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1327 $errors = $this->resultToError( $errors, $result );
1328 }
1329
1330 return $errors;
1331 }
1332
1333 /**
1334 * Check permissions on special pages & namespaces
1335 *
1336 * @param $action String the action to check
1337 * @param $user User user to check
1338 * @param $errors Array list of current errors
1339 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1340 * @param $short Boolean short circuit on first error
1341 *
1342 * @return Array list of errors
1343 */
1344 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1345 # Only 'createaccount' and 'execute' can be performed on
1346 # special pages, which don't actually exist in the DB.
1347 $specialOKActions = array( 'createaccount', 'execute' );
1348 if ( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions ) ) {
1349 $errors[] = array( 'ns-specialprotected' );
1350 }
1351
1352 # Check $wgNamespaceProtection for restricted namespaces
1353 if ( $this->isNamespaceProtected( $user ) ) {
1354 $ns = $this->mNamespace == NS_MAIN ?
1355 wfMsg( 'nstab-main' ) : $this->getNsText();
1356 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
1357 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1358 }
1359
1360 return $errors;
1361 }
1362
1363 /**
1364 * Check CSS/JS sub-page permissions
1365 *
1366 * @param $action String the action to check
1367 * @param $user User user to check
1368 * @param $errors Array list of current errors
1369 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1370 * @param $short Boolean short circuit on first error
1371 *
1372 * @return Array list of errors
1373 */
1374 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1375 # Protect css/js subpages of user pages
1376 # XXX: this might be better using restrictions
1377 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1378 # and $this->userCanEditJsSubpage() from working
1379 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1380 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1381 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
1382 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1383 $errors[] = array( 'customcssjsprotected' );
1384 } else if ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1385 $errors[] = array( 'customcssjsprotected' );
1386 }
1387 }
1388
1389 return $errors;
1390 }
1391
1392 /**
1393 * Check against page_restrictions table requirements on this
1394 * page. The user must possess all required rights for this
1395 * action.
1396 *
1397 * @param $action String the action to check
1398 * @param $user User user to check
1399 * @param $errors Array list of current errors
1400 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1401 * @param $short Boolean short circuit on first error
1402 *
1403 * @return Array list of errors
1404 */
1405 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1406 foreach ( $this->getRestrictions( $action ) as $right ) {
1407 // Backwards compatibility, rewrite sysop -> protect
1408 if ( $right == 'sysop' ) {
1409 $right = 'protect';
1410 }
1411 if ( $right != '' && !$user->isAllowed( $right ) ) {
1412 // Users with 'editprotected' permission can edit protected pages
1413 if ( $action == 'edit' && $user->isAllowed( 'editprotected' ) ) {
1414 // Users with 'editprotected' permission cannot edit protected pages
1415 // with cascading option turned on.
1416 if ( $this->mCascadeRestriction ) {
1417 $errors[] = array( 'protectedpagetext', $right );
1418 }
1419 } else {
1420 $errors[] = array( 'protectedpagetext', $right );
1421 }
1422 }
1423 }
1424
1425 return $errors;
1426 }
1427
1428 /**
1429 * Check restrictions on cascading pages.
1430 *
1431 * @param $action String the action to check
1432 * @param $user User to check
1433 * @param $errors Array list of current errors
1434 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1435 * @param $short Boolean short circuit on first error
1436 *
1437 * @return Array list of errors
1438 */
1439 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1440 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1441 # We /could/ use the protection level on the source page, but it's
1442 # fairly ugly as we have to establish a precedence hierarchy for pages
1443 # included by multiple cascade-protected pages. So just restrict
1444 # it to people with 'protect' permission, as they could remove the
1445 # protection anyway.
1446 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1447 # Cascading protection depends on more than this page...
1448 # Several cascading protected pages may include this page...
1449 # Check each cascading level
1450 # This is only for protection restrictions, not for all actions
1451 if ( isset( $restrictions[$action] ) ) {
1452 foreach ( $restrictions[$action] as $right ) {
1453 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1454 if ( $right != '' && !$user->isAllowed( $right ) ) {
1455 $pages = '';
1456 foreach ( $cascadingSources as $page )
1457 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1458 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1459 }
1460 }
1461 }
1462 }
1463
1464 return $errors;
1465 }
1466
1467 /**
1468 * Check action permissions not already checked in checkQuickPermissions
1469 *
1470 * @param $action String the action to check
1471 * @param $user User to check
1472 * @param $errors Array list of current errors
1473 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1474 * @param $short Boolean short circuit on first error
1475 *
1476 * @return Array list of errors
1477 */
1478 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1479 if ( $action == 'protect' ) {
1480 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1481 // If they can't edit, they shouldn't protect.
1482 $errors[] = array( 'protect-cantedit' );
1483 }
1484 } elseif ( $action == 'create' ) {
1485 $title_protection = $this->getTitleProtection();
1486 if( $title_protection ) {
1487 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1488 $title_protection['pt_create_perm'] = 'protect'; // B/C
1489 }
1490 if( $title_protection['pt_create_perm'] == '' || !$user->isAllowed( $title_protection['pt_create_perm'] ) ) {
1491 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1492 }
1493 }
1494 } elseif ( $action == 'move' ) {
1495 // Check for immobile pages
1496 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1497 // Specific message for this case
1498 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1499 } elseif ( !$this->isMovable() ) {
1500 // Less specific message for rarer cases
1501 $errors[] = array( 'immobile-page' );
1502 }
1503 } elseif ( $action == 'move-target' ) {
1504 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1505 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1506 } elseif ( !$this->isMovable() ) {
1507 $errors[] = array( 'immobile-target-page' );
1508 }
1509 }
1510 return $errors;
1511 }
1512
1513 /**
1514 * Check that the user isn't blocked from editting.
1515 *
1516 * @param $action String the action to check
1517 * @param $user User to check
1518 * @param $errors Array list of current errors
1519 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1520 * @param $short Boolean short circuit on first error
1521 *
1522 * @return Array list of errors
1523 */
1524 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1525 if( $short && count( $errors ) > 0 ) {
1526 return $errors;
1527 }
1528
1529 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1530
1531 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1532 $errors[] = array( 'confirmedittext' );
1533 }
1534
1535 if ( in_array( $action, array( 'read', 'createaccount', 'unblock' ) ) ){
1536 // Edit blocks should not affect reading.
1537 // Account creation blocks handled at userlogin.
1538 // Unblocking handled in SpecialUnblock
1539 } elseif( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ){
1540 // Don't block the user from editing their own talk page unless they've been
1541 // explicitly blocked from that too.
1542 } elseif( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
1543 $block = $user->mBlock;
1544
1545 // This is from OutputPage::blockedPage
1546 // Copied at r23888 by werdna
1547
1548 $id = $user->blockedBy();
1549 $reason = $user->blockedFor();
1550 if ( $reason == '' ) {
1551 $reason = wfMsg( 'blockednoreason' );
1552 }
1553 $ip = wfGetIP();
1554
1555 if ( is_numeric( $id ) ) {
1556 $name = User::whoIs( $id );
1557 } else {
1558 $name = $id;
1559 }
1560
1561 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1562 $blockid = $block->getId();
1563 $blockExpiry = $user->mBlock->mExpiry;
1564 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1565 if ( $blockExpiry == 'infinity' ) {
1566 $blockExpiry = wfMessage( 'infiniteblock' )->text();
1567 } else {
1568 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1569 }
1570
1571 $intended = strval( $user->mBlock->getTarget() );
1572
1573 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1574 $blockid, $blockExpiry, $intended, $blockTimestamp );
1575 }
1576
1577 return $errors;
1578 }
1579
1580 /**
1581 * Can $user perform $action on this page? This is an internal function,
1582 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1583 * checks on wfReadOnly() and blocks)
1584 *
1585 * @param $action String action that permission needs to be checked for
1586 * @param $user User to check
1587 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1588 * @param $short Bool Set this to true to stop after the first permission error.
1589 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1590 */
1591 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1592 wfProfileIn( __METHOD__ );
1593
1594 $errors = array();
1595 $checks = array(
1596 'checkQuickPermissions',
1597 'checkPermissionHooks',
1598 'checkSpecialsAndNSPermissions',
1599 'checkCSSandJSPermissions',
1600 'checkPageRestrictions',
1601 'checkCascadingSourcesRestrictions',
1602 'checkActionPermissions',
1603 'checkUserBlock'
1604 );
1605
1606 while( count( $checks ) > 0 &&
1607 !( $short && count( $errors ) > 0 ) ) {
1608 $method = array_shift( $checks );
1609 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1610 }
1611
1612 wfProfileOut( __METHOD__ );
1613 return $errors;
1614 }
1615
1616 /**
1617 * Is this title subject to title protection?
1618 * Title protection is the one applied against creation of such title.
1619 *
1620 * @return Mixed An associative array representing any existent title
1621 * protection, or false if there's none.
1622 */
1623 private function getTitleProtection() {
1624 // Can't protect pages in special namespaces
1625 if ( $this->getNamespace() < 0 ) {
1626 return false;
1627 }
1628
1629 // Can't protect pages that exist.
1630 if ( $this->exists() ) {
1631 return false;
1632 }
1633
1634 if ( !isset( $this->mTitleProtection ) ) {
1635 $dbr = wfGetDB( DB_SLAVE );
1636 $res = $dbr->select( 'protected_titles', '*',
1637 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1638 __METHOD__ );
1639
1640 // fetchRow returns false if there are no rows.
1641 $this->mTitleProtection = $dbr->fetchRow( $res );
1642 }
1643 return $this->mTitleProtection;
1644 }
1645
1646 /**
1647 * Update the title protection status
1648 *
1649 * @param $create_perm String Permission required for creation
1650 * @param $reason String Reason for protection
1651 * @param $expiry String Expiry timestamp
1652 * @return boolean true
1653 */
1654 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1655 global $wgUser, $wgContLang;
1656
1657 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1658 && $expiry == $this->mRestrictionsExpiry['create'] ) {
1659 // No change
1660 return true;
1661 }
1662
1663 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1664
1665 $dbw = wfGetDB( DB_MASTER );
1666
1667 $encodedExpiry = $dbw->encodeExpiry( $expiry );
1668
1669 $expiry_description = '';
1670 if ( $encodedExpiry != $dbw->getInfinity() ) {
1671 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1672 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1673 } else {
1674 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1675 }
1676
1677 # Update protection table
1678 if ( $create_perm != '' ) {
1679 $this->mTitleProtection = array(
1680 'pt_namespace' => $namespace,
1681 'pt_title' => $title,
1682 'pt_create_perm' => $create_perm,
1683 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1684 'pt_expiry' => $encodedExpiry,
1685 'pt_user' => $wgUser->getId(),
1686 'pt_reason' => $reason,
1687 );
1688 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1689 $this->mTitleProtection, __METHOD__ );
1690 } else {
1691 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1692 'pt_title' => $title ), __METHOD__ );
1693 $this->mTitleProtection = false;
1694 }
1695
1696 # Update the protection log
1697 if ( $dbw->affectedRows() ) {
1698 $log = new LogPage( 'protect' );
1699
1700 if ( $create_perm ) {
1701 $params = array( "[create=$create_perm] $expiry_description", '' );
1702 $log->addEntry( ( isset( $this->mRestrictions['create'] ) && $this->mRestrictions['create'] ) ? 'modify' : 'protect', $this, trim( $reason ), $params );
1703 } else {
1704 $log->addEntry( 'unprotect', $this, $reason );
1705 }
1706 }
1707
1708 return true;
1709 }
1710
1711 /**
1712 * Remove any title protection due to page existing
1713 */
1714 public function deleteTitleProtection() {
1715 $dbw = wfGetDB( DB_MASTER );
1716
1717 $dbw->delete(
1718 'protected_titles',
1719 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1720 __METHOD__
1721 );
1722 $this->mTitleProtection = false;
1723 }
1724
1725 /**
1726 * Would anybody with sufficient privileges be able to move this page?
1727 * Some pages just aren't movable.
1728 *
1729 * @return Bool TRUE or FALSE
1730 */
1731 public function isMovable() {
1732 return MWNamespace::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1733 }
1734
1735 /**
1736 * Can $wgUser read this page?
1737 *
1738 * @return Bool
1739 * @todo fold these checks into userCan()
1740 */
1741 public function userCanRead() {
1742 global $wgUser, $wgGroupPermissions;
1743
1744 static $useShortcut = null;
1745
1746 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1747 if ( is_null( $useShortcut ) ) {
1748 global $wgRevokePermissions;
1749 $useShortcut = true;
1750 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1751 # Not a public wiki, so no shortcut
1752 $useShortcut = false;
1753 } elseif ( !empty( $wgRevokePermissions ) ) {
1754 /*
1755 * Iterate through each group with permissions being revoked (key not included since we don't care
1756 * what the group name is), then check if the read permission is being revoked. If it is, then
1757 * we don't use the shortcut below since the user might not be able to read, even though anon
1758 * reading is allowed.
1759 */
1760 foreach ( $wgRevokePermissions as $perms ) {
1761 if ( !empty( $perms['read'] ) ) {
1762 # We might be removing the read right from the user, so no shortcut
1763 $useShortcut = false;
1764 break;
1765 }
1766 }
1767 }
1768 }
1769
1770 $result = null;
1771 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1772 if ( $result !== null ) {
1773 return $result;
1774 }
1775
1776 # Shortcut for public wikis, allows skipping quite a bit of code
1777 if ( $useShortcut ) {
1778 return true;
1779 }
1780
1781 if ( $wgUser->isAllowed( 'read' ) ) {
1782 return true;
1783 } else {
1784 global $wgWhitelistRead;
1785
1786 # Always grant access to the login page.
1787 # Even anons need to be able to log in.
1788 if ( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1789 return true;
1790 }
1791
1792 # Bail out if there isn't whitelist
1793 if ( !is_array( $wgWhitelistRead ) ) {
1794 return false;
1795 }
1796
1797 # Check for explicit whitelisting
1798 $name = $this->getPrefixedText();
1799 $dbName = $this->getPrefixedDBKey();
1800 // Check with and without underscores
1801 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) )
1802 return true;
1803
1804 # Old settings might have the title prefixed with
1805 # a colon for main-namespace pages
1806 if ( $this->getNamespace() == NS_MAIN ) {
1807 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1808 return true;
1809 }
1810 }
1811
1812 # If it's a special page, ditch the subpage bit and check again
1813 if ( $this->getNamespace() == NS_SPECIAL ) {
1814 $name = $this->getDBkey();
1815 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
1816 if ( $name === false ) {
1817 # Invalid special page, but we show standard login required message
1818 return false;
1819 }
1820
1821 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1822 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1823 return true;
1824 }
1825 }
1826
1827 }
1828 return false;
1829 }
1830
1831 /**
1832 * Is this the mainpage?
1833 * @note Title::newFromText seams to be sufficiently optimized by the title
1834 * cache that we don't need to over-optimize by doing direct comparisons and
1835 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1836 * ends up reporting something differently than $title->isMainPage();
1837 *
1838 * @return Bool
1839 */
1840 public function isMainPage() {
1841 return $this->equals( Title::newMainPage() );
1842 }
1843
1844 /**
1845 * Is this a talk page of some sort?
1846 *
1847 * @return Bool
1848 */
1849 public function isTalkPage() {
1850 return MWNamespace::isTalk( $this->getNamespace() );
1851 }
1852
1853 /**
1854 * Is this a subpage?
1855 *
1856 * @return Bool
1857 */
1858 public function isSubpage() {
1859 return MWNamespace::hasSubpages( $this->mNamespace )
1860 ? strpos( $this->getText(), '/' ) !== false
1861 : false;
1862 }
1863
1864 /**
1865 * Does this have subpages? (Warning, usually requires an extra DB query.)
1866 *
1867 * @return Bool
1868 */
1869 public function hasSubpages() {
1870 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1871 # Duh
1872 return false;
1873 }
1874
1875 # We dynamically add a member variable for the purpose of this method
1876 # alone to cache the result. There's no point in having it hanging
1877 # around uninitialized in every Title object; therefore we only add it
1878 # if needed and don't declare it statically.
1879 if ( isset( $this->mHasSubpages ) ) {
1880 return $this->mHasSubpages;
1881 }
1882
1883 $subpages = $this->getSubpages( 1 );
1884 if ( $subpages instanceof TitleArray ) {
1885 return $this->mHasSubpages = (bool)$subpages->count();
1886 }
1887 return $this->mHasSubpages = false;
1888 }
1889
1890 /**
1891 * Get all subpages of this page.
1892 *
1893 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
1894 * @return mixed TitleArray, or empty array if this page's namespace
1895 * doesn't allow subpages
1896 */
1897 public function getSubpages( $limit = -1 ) {
1898 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
1899 return array();
1900 }
1901
1902 $dbr = wfGetDB( DB_SLAVE );
1903 $conds['page_namespace'] = $this->getNamespace();
1904 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1905 $options = array();
1906 if ( $limit > -1 ) {
1907 $options['LIMIT'] = $limit;
1908 }
1909 return $this->mSubpages = TitleArray::newFromResult(
1910 $dbr->select( 'page',
1911 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1912 $conds,
1913 __METHOD__,
1914 $options
1915 )
1916 );
1917 }
1918
1919 /**
1920 * Could this page contain custom CSS or JavaScript, based
1921 * on the title?
1922 *
1923 * @return Bool
1924 */
1925 public function isCssOrJsPage() {
1926 return $this->mNamespace == NS_MEDIAWIKI
1927 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1928 }
1929
1930 /**
1931 * Is this a .css or .js subpage of a user page?
1932 * @return Bool
1933 */
1934 public function isCssJsSubpage() {
1935 return ( NS_USER == $this->mNamespace and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1936 }
1937
1938 /**
1939 * Is this a *valid* .css or .js subpage of a user page?
1940 *
1941 * @return Bool
1942 * @deprecated since 1.17
1943 */
1944 public function isValidCssJsSubpage() {
1945 return $this->isCssJsSubpage();
1946 }
1947
1948 /**
1949 * Trim down a .css or .js subpage title to get the corresponding skin name
1950 *
1951 * @return string containing skin name from .css or .js subpage title
1952 */
1953 public function getSkinFromCssJsSubpage() {
1954 $subpage = explode( '/', $this->mTextform );
1955 $subpage = $subpage[ count( $subpage ) - 1 ];
1956 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1957 }
1958
1959 /**
1960 * Is this a .css subpage of a user page?
1961 *
1962 * @return Bool
1963 */
1964 public function isCssSubpage() {
1965 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.css$/", $this->mTextform ) );
1966 }
1967
1968 /**
1969 * Is this a .js subpage of a user page?
1970 *
1971 * @return Bool
1972 */
1973 public function isJsSubpage() {
1974 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.js$/", $this->mTextform ) );
1975 }
1976
1977 /**
1978 * Protect css subpages of user pages: can $wgUser edit
1979 * this page?
1980 *
1981 * @return Bool
1982 * @todo XXX: this might be better using restrictions
1983 */
1984 public function userCanEditCssSubpage() {
1985 global $wgUser;
1986 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
1987 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
1988 }
1989
1990 /**
1991 * Protect js subpages of user pages: can $wgUser edit
1992 * this page?
1993 *
1994 * @return Bool
1995 * @todo XXX: this might be better using restrictions
1996 */
1997 public function userCanEditJsSubpage() {
1998 global $wgUser;
1999 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2000 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2001 }
2002
2003 /**
2004 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2005 *
2006 * @return Bool If the page is subject to cascading restrictions.
2007 */
2008 public function isCascadeProtected() {
2009 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2010 return ( $sources > 0 );
2011 }
2012
2013 /**
2014 * Cascading protection: Get the source of any cascading restrictions on this page.
2015 *
2016 * @param $getPages Bool Whether or not to retrieve the actual pages
2017 * that the restrictions have come from.
2018 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2019 * have come, false for none, or true if such restrictions exist, but $getPages
2020 * was not set. The restriction array is an array of each type, each of which
2021 * contains a array of unique groups.
2022 */
2023 public function getCascadeProtectionSources( $getPages = true ) {
2024 global $wgContLang;
2025 $pagerestrictions = array();
2026
2027 if ( isset( $this->mCascadeSources ) && $getPages ) {
2028 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2029 } else if ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2030 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2031 }
2032
2033 wfProfileIn( __METHOD__ );
2034
2035 $dbr = wfGetDB( DB_SLAVE );
2036
2037 if ( $this->getNamespace() == NS_FILE ) {
2038 $tables = array( 'imagelinks', 'page_restrictions' );
2039 $where_clauses = array(
2040 'il_to' => $this->getDBkey(),
2041 'il_from=pr_page',
2042 'pr_cascade' => 1
2043 );
2044 } else {
2045 $tables = array( 'templatelinks', 'page_restrictions' );
2046 $where_clauses = array(
2047 'tl_namespace' => $this->getNamespace(),
2048 'tl_title' => $this->getDBkey(),
2049 'tl_from=pr_page',
2050 'pr_cascade' => 1
2051 );
2052 }
2053
2054 if ( $getPages ) {
2055 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2056 'pr_expiry', 'pr_type', 'pr_level' );
2057 $where_clauses[] = 'page_id=pr_page';
2058 $tables[] = 'page';
2059 } else {
2060 $cols = array( 'pr_expiry' );
2061 }
2062
2063 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2064
2065 $sources = $getPages ? array() : false;
2066 $now = wfTimestampNow();
2067 $purgeExpired = false;
2068
2069 foreach ( $res as $row ) {
2070 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2071 if ( $expiry > $now ) {
2072 if ( $getPages ) {
2073 $page_id = $row->pr_page;
2074 $page_ns = $row->page_namespace;
2075 $page_title = $row->page_title;
2076 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2077 # Add groups needed for each restriction type if its not already there
2078 # Make sure this restriction type still exists
2079
2080 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2081 $pagerestrictions[$row->pr_type] = array();
2082 }
2083
2084 if ( isset( $pagerestrictions[$row->pr_type] ) &&
2085 !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) ) {
2086 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2087 }
2088 } else {
2089 $sources = true;
2090 }
2091 } else {
2092 // Trigger lazy purge of expired restrictions from the db
2093 $purgeExpired = true;
2094 }
2095 }
2096 if ( $purgeExpired ) {
2097 Title::purgeExpiredRestrictions();
2098 }
2099
2100 if ( $getPages ) {
2101 $this->mCascadeSources = $sources;
2102 $this->mCascadingRestrictions = $pagerestrictions;
2103 } else {
2104 $this->mHasCascadingRestrictions = $sources;
2105 }
2106
2107 wfProfileOut( __METHOD__ );
2108 return array( $sources, $pagerestrictions );
2109 }
2110
2111 /**
2112 * Returns cascading restrictions for the current article
2113 *
2114 * @return Boolean
2115 */
2116 function areRestrictionsCascading() {
2117 if ( !$this->mRestrictionsLoaded ) {
2118 $this->loadRestrictions();
2119 }
2120
2121 return $this->mCascadeRestriction;
2122 }
2123
2124 /**
2125 * Loads a string into mRestrictions array
2126 *
2127 * @param $res Resource restrictions as an SQL result.
2128 * @param $oldFashionedRestrictions String comma-separated list of page
2129 * restrictions from page table (pre 1.10)
2130 */
2131 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2132 $rows = array();
2133
2134 foreach ( $res as $row ) {
2135 $rows[] = $row;
2136 }
2137
2138 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2139 }
2140
2141 /**
2142 * Compiles list of active page restrictions from both page table (pre 1.10)
2143 * and page_restrictions table for this existing page.
2144 * Public for usage by LiquidThreads.
2145 *
2146 * @param $rows array of db result objects
2147 * @param $oldFashionedRestrictions string comma-separated list of page
2148 * restrictions from page table (pre 1.10)
2149 */
2150 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2151 global $wgContLang;
2152 $dbr = wfGetDB( DB_SLAVE );
2153
2154 $restrictionTypes = $this->getRestrictionTypes();
2155
2156 foreach ( $restrictionTypes as $type ) {
2157 $this->mRestrictions[$type] = array();
2158 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2159 }
2160
2161 $this->mCascadeRestriction = false;
2162
2163 # Backwards-compatibility: also load the restrictions from the page record (old format).
2164
2165 if ( $oldFashionedRestrictions === null ) {
2166 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2167 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
2168 }
2169
2170 if ( $oldFashionedRestrictions != '' ) {
2171
2172 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2173 $temp = explode( '=', trim( $restrict ) );
2174 if ( count( $temp ) == 1 ) {
2175 // old old format should be treated as edit/move restriction
2176 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2177 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2178 } else {
2179 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
2180 }
2181 }
2182
2183 $this->mOldRestrictions = true;
2184
2185 }
2186
2187 if ( count( $rows ) ) {
2188 # Current system - load second to make them override.
2189 $now = wfTimestampNow();
2190 $purgeExpired = false;
2191
2192 # Cycle through all the restrictions.
2193 foreach ( $rows as $row ) {
2194
2195 // Don't take care of restrictions types that aren't allowed
2196 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2197 continue;
2198
2199 // This code should be refactored, now that it's being used more generally,
2200 // But I don't really see any harm in leaving it in Block for now -werdna
2201 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2202
2203 // Only apply the restrictions if they haven't expired!
2204 if ( !$expiry || $expiry > $now ) {
2205 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2206 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2207
2208 $this->mCascadeRestriction |= $row->pr_cascade;
2209 } else {
2210 // Trigger a lazy purge of expired restrictions
2211 $purgeExpired = true;
2212 }
2213 }
2214
2215 if ( $purgeExpired ) {
2216 Title::purgeExpiredRestrictions();
2217 }
2218 }
2219
2220 $this->mRestrictionsLoaded = true;
2221 }
2222
2223 /**
2224 * Load restrictions from the page_restrictions table
2225 *
2226 * @param $oldFashionedRestrictions String comma-separated list of page
2227 * restrictions from page table (pre 1.10)
2228 */
2229 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2230 global $wgContLang;
2231 if ( !$this->mRestrictionsLoaded ) {
2232 if ( $this->exists() ) {
2233 $dbr = wfGetDB( DB_SLAVE );
2234
2235 $res = $dbr->select(
2236 'page_restrictions',
2237 '*',
2238 array( 'pr_page' => $this->getArticleId() ),
2239 __METHOD__
2240 );
2241
2242 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2243 } else {
2244 $title_protection = $this->getTitleProtection();
2245
2246 if ( $title_protection ) {
2247 $now = wfTimestampNow();
2248 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW );
2249
2250 if ( !$expiry || $expiry > $now ) {
2251 // Apply the restrictions
2252 $this->mRestrictionsExpiry['create'] = $expiry;
2253 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2254 } else { // Get rid of the old restrictions
2255 Title::purgeExpiredRestrictions();
2256 $this->mTitleProtection = false;
2257 }
2258 } else {
2259 $this->mRestrictionsExpiry['create'] = $wgContLang->formatExpiry( '', TS_MW );
2260 }
2261 $this->mRestrictionsLoaded = true;
2262 }
2263 }
2264 }
2265
2266 /**
2267 * Purge expired restrictions from the page_restrictions table
2268 */
2269 static function purgeExpiredRestrictions() {
2270 $dbw = wfGetDB( DB_MASTER );
2271 $dbw->delete(
2272 'page_restrictions',
2273 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2274 __METHOD__
2275 );
2276
2277 $dbw->delete(
2278 'protected_titles',
2279 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2280 __METHOD__
2281 );
2282 }
2283
2284 /**
2285 * Accessor/initialisation for mRestrictions
2286 *
2287 * @param $action String action that permission needs to be checked for
2288 * @return Array of Strings the array of groups allowed to edit this article
2289 */
2290 public function getRestrictions( $action ) {
2291 if ( !$this->mRestrictionsLoaded ) {
2292 $this->loadRestrictions();
2293 }
2294 return isset( $this->mRestrictions[$action] )
2295 ? $this->mRestrictions[$action]
2296 : array();
2297 }
2298
2299 /**
2300 * Get the expiry time for the restriction against a given action
2301 *
2302 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2303 * or not protected at all, or false if the action is not recognised.
2304 */
2305 public function getRestrictionExpiry( $action ) {
2306 if ( !$this->mRestrictionsLoaded ) {
2307 $this->loadRestrictions();
2308 }
2309 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2310 }
2311
2312 /**
2313 * Is there a version of this page in the deletion archive?
2314 *
2315 * @return Int the number of archived revisions
2316 */
2317 public function isDeleted() {
2318 if ( $this->getNamespace() < 0 ) {
2319 $n = 0;
2320 } else {
2321 $dbr = wfGetDB( DB_SLAVE );
2322 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2323 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2324 __METHOD__
2325 );
2326 if ( $this->getNamespace() == NS_FILE ) {
2327 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2328 array( 'fa_name' => $this->getDBkey() ),
2329 __METHOD__
2330 );
2331 }
2332 }
2333 return (int)$n;
2334 }
2335
2336 /**
2337 * Is there a version of this page in the deletion archive?
2338 *
2339 * @return Boolean
2340 */
2341 public function isDeletedQuick() {
2342 if ( $this->getNamespace() < 0 ) {
2343 return false;
2344 }
2345 $dbr = wfGetDB( DB_SLAVE );
2346 $deleted = (bool)$dbr->selectField( 'archive', '1',
2347 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2348 __METHOD__
2349 );
2350 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
2351 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2352 array( 'fa_name' => $this->getDBkey() ),
2353 __METHOD__
2354 );
2355 }
2356 return $deleted;
2357 }
2358
2359 /**
2360 * Get the article ID for this Title from the link cache,
2361 * adding it if necessary
2362 *
2363 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2364 * for update
2365 * @return Int the ID
2366 */
2367 public function getArticleID( $flags = 0 ) {
2368 if ( $this->getNamespace() < 0 ) {
2369 return $this->mArticleID = 0;
2370 }
2371 $linkCache = LinkCache::singleton();
2372 if ( $flags & self::GAID_FOR_UPDATE ) {
2373 $oldUpdate = $linkCache->forUpdate( true );
2374 $linkCache->clearLink( $this );
2375 $this->mArticleID = $linkCache->addLinkObj( $this );
2376 $linkCache->forUpdate( $oldUpdate );
2377 } else {
2378 if ( -1 == $this->mArticleID ) {
2379 $this->mArticleID = $linkCache->addLinkObj( $this );
2380 }
2381 }
2382 return $this->mArticleID;
2383 }
2384
2385 /**
2386 * Is this an article that is a redirect page?
2387 * Uses link cache, adding it if necessary
2388 *
2389 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2390 * @return Bool
2391 */
2392 public function isRedirect( $flags = 0 ) {
2393 if ( !is_null( $this->mRedirect ) ) {
2394 return $this->mRedirect;
2395 }
2396 # Calling getArticleID() loads the field from cache as needed
2397 if ( !$this->getArticleID( $flags ) ) {
2398 return $this->mRedirect = false;
2399 }
2400 $linkCache = LinkCache::singleton();
2401 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2402
2403 return $this->mRedirect;
2404 }
2405
2406 /**
2407 * What is the length of this page?
2408 * Uses link cache, adding it if necessary
2409 *
2410 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2411 * @return Int
2412 */
2413 public function getLength( $flags = 0 ) {
2414 if ( $this->mLength != -1 ) {
2415 return $this->mLength;
2416 }
2417 # Calling getArticleID() loads the field from cache as needed
2418 if ( !$this->getArticleID( $flags ) ) {
2419 return $this->mLength = 0;
2420 }
2421 $linkCache = LinkCache::singleton();
2422 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2423
2424 return $this->mLength;
2425 }
2426
2427 /**
2428 * What is the page_latest field for this page?
2429 *
2430 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2431 * @return Int or 0 if the page doesn't exist
2432 */
2433 public function getLatestRevID( $flags = 0 ) {
2434 if ( $this->mLatestID !== false ) {
2435 return intval( $this->mLatestID );
2436 }
2437 # Calling getArticleID() loads the field from cache as needed
2438 if ( !$this->getArticleID( $flags ) ) {
2439 return $this->mLatestID = 0;
2440 }
2441 $linkCache = LinkCache::singleton();
2442 $this->mLatestID = intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2443
2444 return $this->mLatestID;
2445 }
2446
2447 /**
2448 * This clears some fields in this object, and clears any associated
2449 * keys in the "bad links" section of the link cache.
2450 *
2451 * - This is called from Article::doEdit() and Article::insertOn() to allow
2452 * loading of the new page_id. It's also called from
2453 * Article::doDeleteArticle()
2454 *
2455 * @param $newid Int the new Article ID
2456 */
2457 public function resetArticleID( $newid ) {
2458 $linkCache = LinkCache::singleton();
2459 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2460
2461 if ( $newid === false ) {
2462 $this->mArticleID = -1;
2463 } else {
2464 $this->mArticleID = intval( $newid );
2465 }
2466 $this->mRestrictionsLoaded = false;
2467 $this->mRestrictions = array();
2468 $this->mRedirect = null;
2469 $this->mLength = -1;
2470 $this->mLatestID = false;
2471 }
2472
2473 /**
2474 * Updates page_touched for this page; called from LinksUpdate.php
2475 *
2476 * @return Bool true if the update succeded
2477 */
2478 public function invalidateCache() {
2479 if ( wfReadOnly() ) {
2480 return;
2481 }
2482 $dbw = wfGetDB( DB_MASTER );
2483 $success = $dbw->update(
2484 'page',
2485 array( 'page_touched' => $dbw->timestamp() ),
2486 $this->pageCond(),
2487 __METHOD__
2488 );
2489 HTMLFileCache::clearFileCache( $this );
2490 return $success;
2491 }
2492
2493 /**
2494 * Prefix some arbitrary text with the namespace or interwiki prefix
2495 * of this object
2496 *
2497 * @param $name String the text
2498 * @return String the prefixed text
2499 * @private
2500 */
2501 /* private */ function prefix( $name ) {
2502 $p = '';
2503 if ( $this->mInterwiki != '' ) {
2504 $p = $this->mInterwiki . ':';
2505 }
2506
2507 if ( 0 != $this->mNamespace ) {
2508 $p .= $this->getNsText() . ':';
2509 }
2510 return $p . $name;
2511 }
2512
2513 /**
2514 * Returns a simple regex that will match on characters and sequences invalid in titles.
2515 * Note that this doesn't pick up many things that could be wrong with titles, but that
2516 * replacing this regex with something valid will make many titles valid.
2517 *
2518 * @return String regex string
2519 */
2520 static function getTitleInvalidRegex() {
2521 static $rxTc = false;
2522 if ( !$rxTc ) {
2523 # Matching titles will be held as illegal.
2524 $rxTc = '/' .
2525 # Any character not allowed is forbidden...
2526 '[^' . Title::legalChars() . ']' .
2527 # URL percent encoding sequences interfere with the ability
2528 # to round-trip titles -- you can't link to them consistently.
2529 '|%[0-9A-Fa-f]{2}' .
2530 # XML/HTML character references produce similar issues.
2531 '|&[A-Za-z0-9\x80-\xff]+;' .
2532 '|&#[0-9]+;' .
2533 '|&#x[0-9A-Fa-f]+;' .
2534 '/S';
2535 }
2536
2537 return $rxTc;
2538 }
2539
2540 /**
2541 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2542 *
2543 * @param $text String containing title to capitalize
2544 * @param $ns int namespace index, defaults to NS_MAIN
2545 * @return String containing capitalized title
2546 */
2547 public static function capitalize( $text, $ns = NS_MAIN ) {
2548 global $wgContLang;
2549
2550 if ( MWNamespace::isCapitalized( $ns ) ) {
2551 return $wgContLang->ucfirst( $text );
2552 } else {
2553 return $text;
2554 }
2555 }
2556
2557 /**
2558 * Secure and split - main initialisation function for this object
2559 *
2560 * Assumes that mDbkeyform has been set, and is urldecoded
2561 * and uses underscores, but not otherwise munged. This function
2562 * removes illegal characters, splits off the interwiki and
2563 * namespace prefixes, sets the other forms, and canonicalizes
2564 * everything.
2565 *
2566 * @return Bool true on success
2567 */
2568 private function secureAndSplit() {
2569 global $wgContLang, $wgLocalInterwiki;
2570
2571 # Initialisation
2572 $this->mInterwiki = $this->mFragment = '';
2573 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2574
2575 $dbkey = $this->mDbkeyform;
2576
2577 # Strip Unicode bidi override characters.
2578 # Sometimes they slip into cut-n-pasted page titles, where the
2579 # override chars get included in list displays.
2580 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2581
2582 # Clean up whitespace
2583 # Note: use of the /u option on preg_replace here will cause
2584 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2585 # conveniently disabling them.
2586 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2587 $dbkey = trim( $dbkey, '_' );
2588
2589 if ( $dbkey == '' ) {
2590 return false;
2591 }
2592
2593 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2594 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2595 return false;
2596 }
2597
2598 $this->mDbkeyform = $dbkey;
2599
2600 # Initial colon indicates main namespace rather than specified default
2601 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2602 if ( ':' == $dbkey { 0 } ) {
2603 $this->mNamespace = NS_MAIN;
2604 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2605 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2606 }
2607
2608 # Namespace or interwiki prefix
2609 $firstPass = true;
2610 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2611 do {
2612 $m = array();
2613 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2614 $p = $m[1];
2615 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2616 # Ordinary namespace
2617 $dbkey = $m[2];
2618 $this->mNamespace = $ns;
2619 # For Talk:X pages, check if X has a "namespace" prefix
2620 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2621 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2622 # Disallow Talk:File:x type titles...
2623 return false;
2624 } else if ( Interwiki::isValidInterwiki( $x[1] ) ) {
2625 # Disallow Talk:Interwiki:x type titles...
2626 return false;
2627 }
2628 }
2629 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
2630 if ( !$firstPass ) {
2631 # Can't make a local interwiki link to an interwiki link.
2632 # That's just crazy!
2633 return false;
2634 }
2635
2636 # Interwiki link
2637 $dbkey = $m[2];
2638 $this->mInterwiki = $wgContLang->lc( $p );
2639
2640 # Redundant interwiki prefix to the local wiki
2641 if ( $wgLocalInterwiki !== false
2642 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
2643 {
2644 if ( $dbkey == '' ) {
2645 # Can't have an empty self-link
2646 return false;
2647 }
2648 $this->mInterwiki = '';
2649 $firstPass = false;
2650 # Do another namespace split...
2651 continue;
2652 }
2653
2654 # If there's an initial colon after the interwiki, that also
2655 # resets the default namespace
2656 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2657 $this->mNamespace = NS_MAIN;
2658 $dbkey = substr( $dbkey, 1 );
2659 }
2660 }
2661 # If there's no recognized interwiki or namespace,
2662 # then let the colon expression be part of the title.
2663 }
2664 break;
2665 } while ( true );
2666
2667 # We already know that some pages won't be in the database!
2668 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
2669 $this->mArticleID = 0;
2670 }
2671 $fragment = strstr( $dbkey, '#' );
2672 if ( false !== $fragment ) {
2673 $this->setFragment( $fragment );
2674 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2675 # remove whitespace again: prevents "Foo_bar_#"
2676 # becoming "Foo_bar_"
2677 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2678 }
2679
2680 # Reject illegal characters.
2681 $rxTc = self::getTitleInvalidRegex();
2682 if ( preg_match( $rxTc, $dbkey ) ) {
2683 return false;
2684 }
2685
2686 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2687 # reachable due to the way web browsers deal with 'relative' URLs.
2688 # Also, they conflict with subpage syntax. Forbid them explicitly.
2689 if ( strpos( $dbkey, '.' ) !== false &&
2690 ( $dbkey === '.' || $dbkey === '..' ||
2691 strpos( $dbkey, './' ) === 0 ||
2692 strpos( $dbkey, '../' ) === 0 ||
2693 strpos( $dbkey, '/./' ) !== false ||
2694 strpos( $dbkey, '/../' ) !== false ||
2695 substr( $dbkey, -2 ) == '/.' ||
2696 substr( $dbkey, -3 ) == '/..' ) )
2697 {
2698 return false;
2699 }
2700
2701 # Magic tilde sequences? Nu-uh!
2702 if ( strpos( $dbkey, '~~~' ) !== false ) {
2703 return false;
2704 }
2705
2706 # Limit the size of titles to 255 bytes. This is typically the size of the
2707 # underlying database field. We make an exception for special pages, which
2708 # don't need to be stored in the database, and may edge over 255 bytes due
2709 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2710 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2711 strlen( $dbkey ) > 512 )
2712 {
2713 return false;
2714 }
2715
2716 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2717 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2718 # other site might be case-sensitive.
2719 $this->mUserCaseDBKey = $dbkey;
2720 if ( $this->mInterwiki == '' ) {
2721 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
2722 }
2723
2724 # Can't make a link to a namespace alone... "empty" local links can only be
2725 # self-links with a fragment identifier.
2726 if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) {
2727 return false;
2728 }
2729
2730 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2731 // IP names are not allowed for accounts, and can only be referring to
2732 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2733 // there are numerous ways to present the same IP. Having sp:contribs scan
2734 // them all is silly and having some show the edits and others not is
2735 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2736 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK )
2737 ? IP::sanitizeIP( $dbkey )
2738 : $dbkey;
2739
2740 // Any remaining initial :s are illegal.
2741 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2742 return false;
2743 }
2744
2745 # Fill fields
2746 $this->mDbkeyform = $dbkey;
2747 $this->mUrlform = wfUrlencode( $dbkey );
2748
2749 $this->mTextform = str_replace( '_', ' ', $dbkey );
2750
2751 return true;
2752 }
2753
2754 /**
2755 * Set the fragment for this title. Removes the first character from the
2756 * specified fragment before setting, so it assumes you're passing it with
2757 * an initial "#".
2758 *
2759 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2760 * Still in active use privately.
2761 *
2762 * @param $fragment String text
2763 */
2764 public function setFragment( $fragment ) {
2765 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2766 }
2767
2768 /**
2769 * Get a Title object associated with the talk page of this article
2770 *
2771 * @return Title the object for the talk page
2772 */
2773 public function getTalkPage() {
2774 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2775 }
2776
2777 /**
2778 * Get a title object associated with the subject page of this
2779 * talk page
2780 *
2781 * @return Title the object for the subject page
2782 */
2783 public function getSubjectPage() {
2784 // Is this the same title?
2785 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2786 if ( $this->getNamespace() == $subjectNS ) {
2787 return $this;
2788 }
2789 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2790 }
2791
2792 /**
2793 * Get an array of Title objects linking to this Title
2794 * Also stores the IDs in the link cache.
2795 *
2796 * WARNING: do not use this function on arbitrary user-supplied titles!
2797 * On heavily-used templates it will max out the memory.
2798 *
2799 * @param $options Array: may be FOR UPDATE
2800 * @param $table String: table name
2801 * @param $prefix String: fields prefix
2802 * @return Array of Title objects linking here
2803 */
2804 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2805 $linkCache = LinkCache::singleton();
2806
2807 if ( count( $options ) > 0 ) {
2808 $db = wfGetDB( DB_MASTER );
2809 } else {
2810 $db = wfGetDB( DB_SLAVE );
2811 }
2812
2813 $res = $db->select(
2814 array( 'page', $table ),
2815 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2816 array(
2817 "{$prefix}_from=page_id",
2818 "{$prefix}_namespace" => $this->getNamespace(),
2819 "{$prefix}_title" => $this->getDBkey() ),
2820 __METHOD__,
2821 $options
2822 );
2823
2824 $retVal = array();
2825 if ( $db->numRows( $res ) ) {
2826 foreach ( $res as $row ) {
2827 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
2828 if ( $titleObj ) {
2829 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect, $row->page_latest );
2830 $retVal[] = $titleObj;
2831 }
2832 }
2833 }
2834 return $retVal;
2835 }
2836
2837 /**
2838 * Get an array of Title objects using this Title as a template
2839 * Also stores the IDs in the link cache.
2840 *
2841 * WARNING: do not use this function on arbitrary user-supplied titles!
2842 * On heavily-used templates it will max out the memory.
2843 *
2844 * @param $options Array: may be FOR UPDATE
2845 * @return Array of Title the Title objects linking here
2846 */
2847 public function getTemplateLinksTo( $options = array() ) {
2848 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2849 }
2850
2851 /**
2852 * Get an array of Title objects referring to non-existent articles linked from this page
2853 *
2854 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2855 * @return Array of Title the Title objects
2856 */
2857 public function getBrokenLinksFrom() {
2858 if ( $this->getArticleId() == 0 ) {
2859 # All links from article ID 0 are false positives
2860 return array();
2861 }
2862
2863 $dbr = wfGetDB( DB_SLAVE );
2864 $res = $dbr->select(
2865 array( 'page', 'pagelinks' ),
2866 array( 'pl_namespace', 'pl_title' ),
2867 array(
2868 'pl_from' => $this->getArticleId(),
2869 'page_namespace IS NULL'
2870 ),
2871 __METHOD__, array(),
2872 array(
2873 'page' => array(
2874 'LEFT JOIN',
2875 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2876 )
2877 )
2878 );
2879
2880 $retVal = array();
2881 foreach ( $res as $row ) {
2882 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2883 }
2884 return $retVal;
2885 }
2886
2887
2888 /**
2889 * Get a list of URLs to purge from the Squid cache when this
2890 * page changes
2891 *
2892 * @return Array of String the URLs
2893 */
2894 public function getSquidURLs() {
2895 global $wgContLang;
2896
2897 $urls = array(
2898 $this->getInternalURL(),
2899 $this->getInternalURL( 'action=history' )
2900 );
2901
2902 // purge variant urls as well
2903 if ( $wgContLang->hasVariants() ) {
2904 $variants = $wgContLang->getVariants();
2905 foreach ( $variants as $vCode ) {
2906 $urls[] = $this->getInternalURL( '', $vCode );
2907 }
2908 }
2909
2910 return $urls;
2911 }
2912
2913 /**
2914 * Purge all applicable Squid URLs
2915 */
2916 public function purgeSquid() {
2917 global $wgUseSquid;
2918 if ( $wgUseSquid ) {
2919 $urls = $this->getSquidURLs();
2920 $u = new SquidUpdate( $urls );
2921 $u->doUpdate();
2922 }
2923 }
2924
2925 /**
2926 * Move this page without authentication
2927 *
2928 * @param $nt Title the new page Title
2929 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
2930 */
2931 public function moveNoAuth( &$nt ) {
2932 return $this->moveTo( $nt, false );
2933 }
2934
2935 /**
2936 * Check whether a given move operation would be valid.
2937 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2938 *
2939 * @param $nt Title the new title
2940 * @param $auth Bool indicates whether $wgUser's permissions
2941 * should be checked
2942 * @param $reason String is the log summary of the move, used for spam checking
2943 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
2944 */
2945 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2946 global $wgUser;
2947
2948 $errors = array();
2949 if ( !$nt ) {
2950 // Normally we'd add this to $errors, but we'll get
2951 // lots of syntax errors if $nt is not an object
2952 return array( array( 'badtitletext' ) );
2953 }
2954 if ( $this->equals( $nt ) ) {
2955 $errors[] = array( 'selfmove' );
2956 }
2957 if ( !$this->isMovable() ) {
2958 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2959 }
2960 if ( $nt->getInterwiki() != '' ) {
2961 $errors[] = array( 'immobile-target-namespace-iw' );
2962 }
2963 if ( !$nt->isMovable() ) {
2964 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
2965 }
2966
2967 $oldid = $this->getArticleID();
2968 $newid = $nt->getArticleID();
2969
2970 if ( strlen( $nt->getDBkey() ) < 1 ) {
2971 $errors[] = array( 'articleexists' );
2972 }
2973 if ( ( $this->getDBkey() == '' ) ||
2974 ( !$oldid ) ||
2975 ( $nt->getDBkey() == '' ) ) {
2976 $errors[] = array( 'badarticleerror' );
2977 }
2978
2979 // Image-specific checks
2980 if ( $this->getNamespace() == NS_FILE ) {
2981 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
2982 }
2983
2984 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
2985 $errors[] = array( 'nonfile-cannot-move-to-file' );
2986 }
2987
2988 if ( $auth ) {
2989 $errors = wfMergeErrorArrays( $errors,
2990 $this->getUserPermissionsErrors( 'move', $wgUser ),
2991 $this->getUserPermissionsErrors( 'edit', $wgUser ),
2992 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
2993 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
2994 }
2995
2996 $match = EditPage::matchSummarySpamRegex( $reason );
2997 if ( $match !== false ) {
2998 // This is kind of lame, won't display nice
2999 $errors[] = array( 'spamprotectiontext' );
3000 }
3001
3002 $err = null;
3003 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3004 $errors[] = array( 'hookaborted', $err );
3005 }
3006
3007 # The move is allowed only if (1) the target doesn't exist, or
3008 # (2) the target is a redirect to the source, and has no history
3009 # (so we can undo bad moves right after they're done).
3010
3011 if ( 0 != $newid ) { # Target exists; check for validity
3012 if ( !$this->isValidMoveTarget( $nt ) ) {
3013 $errors[] = array( 'articleexists' );
3014 }
3015 } else {
3016 $tp = $nt->getTitleProtection();
3017 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3018 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3019 $errors[] = array( 'cantmove-titleprotected' );
3020 }
3021 }
3022 if ( empty( $errors ) ) {
3023 return true;
3024 }
3025 return $errors;
3026 }
3027
3028 /**
3029 * Check if the requested move target is a valid file move target
3030 * @param Title $nt Target title
3031 * @return array List of errors
3032 */
3033 protected function validateFileMoveOperation( $nt ) {
3034 global $wgUser;
3035
3036 $errors = array();
3037
3038 if ( $nt->getNamespace() != NS_FILE ) {
3039 $errors[] = array( 'imagenocrossnamespace' );
3040 }
3041
3042 $file = wfLocalFile( $this );
3043 if ( $file->exists() ) {
3044 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3045 $errors[] = array( 'imageinvalidfilename' );
3046 }
3047 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3048 $errors[] = array( 'imagetypemismatch' );
3049 }
3050 }
3051
3052 $destFile = wfLocalFile( $nt );
3053 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3054 $errors[] = array( 'file-exists-sharedrepo' );
3055 }
3056
3057 return $errors;
3058 }
3059
3060 /**
3061 * Move a title to a new location
3062 *
3063 * @param $nt Title the new title
3064 * @param $auth Bool indicates whether $wgUser's permissions
3065 * should be checked
3066 * @param $reason String the reason for the move
3067 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3068 * Ignored if the user doesn't have the suppressredirect right.
3069 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3070 */
3071 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3072 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3073 if ( is_array( $err ) ) {
3074 return $err;
3075 }
3076
3077 // If it is a file, move it first. It is done before all other moving stuff is
3078 // done because it's hard to revert
3079 $dbw = wfGetDB( DB_MASTER );
3080 if ( $this->getNamespace() == NS_FILE ) {
3081 $file = wfLocalFile( $this );
3082 if ( $file->exists() ) {
3083 $status = $file->move( $nt );
3084 if ( !$status->isOk() ) {
3085 return $status->getErrorsArray();
3086 }
3087 }
3088 }
3089
3090 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3091 $pageid = $this->getArticleID( GAID_FOR_UPDATE );
3092 $protected = $this->isProtected();
3093 $pageCountChange = ( $createRedirect ? 1 : 0 ) - ( $nt->exists() ? 1 : 0 );
3094
3095 // Do the actual move
3096 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3097 if ( is_array( $err ) ) {
3098 # FIXME: What about the File we have already moved?
3099 $dbw->rollback();
3100 return $err;
3101 }
3102
3103 $redirid = $this->getArticleID();
3104
3105 // Refresh the sortkey for this row. Be careful to avoid resetting
3106 // cl_timestamp, which may disturb time-based lists on some sites.
3107 $prefixes = $dbw->select(
3108 'categorylinks',
3109 array( 'cl_sortkey_prefix', 'cl_to' ),
3110 array( 'cl_from' => $pageid ),
3111 __METHOD__
3112 );
3113 foreach ( $prefixes as $prefixRow ) {
3114 $prefix = $prefixRow->cl_sortkey_prefix;
3115 $catTo = $prefixRow->cl_to;
3116 $dbw->update( 'categorylinks',
3117 array(
3118 'cl_sortkey' => Collation::singleton()->getSortKey(
3119 $nt->getCategorySortkey( $prefix ) ),
3120 'cl_timestamp=cl_timestamp' ),
3121 array(
3122 'cl_from' => $pageid,
3123 'cl_to' => $catTo ),
3124 __METHOD__
3125 );
3126 }
3127
3128 if ( $protected ) {
3129 # Protect the redirect title as the title used to be...
3130 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3131 array(
3132 'pr_page' => $redirid,
3133 'pr_type' => 'pr_type',
3134 'pr_level' => 'pr_level',
3135 'pr_cascade' => 'pr_cascade',
3136 'pr_user' => 'pr_user',
3137 'pr_expiry' => 'pr_expiry'
3138 ),
3139 array( 'pr_page' => $pageid ),
3140 __METHOD__,
3141 array( 'IGNORE' )
3142 );
3143 # Update the protection log
3144 $log = new LogPage( 'protect' );
3145 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3146 if ( $reason ) {
3147 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3148 }
3149 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) ); // FIXME: $params?
3150 }
3151
3152 # Update watchlists
3153 $oldnamespace = $this->getNamespace() & ~1;
3154 $newnamespace = $nt->getNamespace() & ~1;
3155 $oldtitle = $this->getDBkey();
3156 $newtitle = $nt->getDBkey();
3157
3158 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3159 WatchedItem::duplicateEntries( $this, $nt );
3160 }
3161
3162 # Update search engine
3163 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3164 $u->doUpdate();
3165 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3166 $u->doUpdate();
3167
3168 $dbw->commit();
3169
3170 # Update site_stats
3171 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3172 # No longer a content page
3173 # Not viewed, edited, removing
3174 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3175 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3176 # Now a content page
3177 # Not viewed, edited, adding
3178 $u = new SiteStatsUpdate( 0, 1, + 1, $pageCountChange );
3179 } elseif ( $pageCountChange ) {
3180 # Redirect added
3181 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3182 } else {
3183 # Nothing special
3184 $u = false;
3185 }
3186 if ( $u ) {
3187 $u->doUpdate();
3188 }
3189 # Update message cache for interface messages
3190 if ( $this->getNamespace() == NS_MEDIAWIKI ) {
3191 # @bug 17860: old article can be deleted, if this the case,
3192 # delete it from message cache
3193 if ( $this->getArticleID() === 0 ) {
3194 MessageCache::singleton()->replace( $this->getDBkey(), false );
3195 } else {
3196 $oldarticle = new Article( $this );
3197 MessageCache::singleton()->replace( $this->getDBkey(), $oldarticle->getContent() );
3198 }
3199 }
3200 if ( $nt->getNamespace() == NS_MEDIAWIKI ) {
3201 $newarticle = new Article( $nt );
3202 MessageCache::singleton()->replace( $nt->getDBkey(), $newarticle->getContent() );
3203 }
3204
3205 global $wgUser;
3206 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3207 return true;
3208 }
3209
3210 /**
3211 * Move page to a title which is either a redirect to the
3212 * source page or nonexistent
3213 *
3214 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3215 * @param $reason String The reason for the move
3216 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3217 * if the user doesn't have the suppressredirect right
3218 */
3219 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3220 global $wgUser, $wgContLang;
3221
3222 $moveOverRedirect = $nt->exists();
3223
3224 $commentMsg = ( $moveOverRedirect ? '1movedto2_redir' : '1movedto2' );
3225 $comment = wfMsgForContent( $commentMsg, $this->getPrefixedText(), $nt->getPrefixedText() );
3226
3227 if ( $reason ) {
3228 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3229 }
3230 # Truncate for whole multibyte characters.
3231 $comment = $wgContLang->truncate( $comment, 255 );
3232
3233 $oldid = $this->getArticleID();
3234 $latest = $this->getLatestRevID();
3235
3236 $oldns = $this->getNamespace();
3237 $olddbk = $this->getDBkey();
3238
3239 $dbw = wfGetDB( DB_MASTER );
3240
3241 if ( $moveOverRedirect ) {
3242 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3243
3244 $newid = $nt->getArticleID();
3245 $newns = $nt->getNamespace();
3246 $newdbk = $nt->getDBkey();
3247
3248 # Delete the old redirect. We don't save it to history since
3249 # by definition if we've got here it's rather uninteresting.
3250 # We have to remove it so that the next step doesn't trigger
3251 # a conflict on the unique namespace+title index...
3252 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3253 if ( !$dbw->cascadingDeletes() ) {
3254 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
3255 global $wgUseTrackbacks;
3256 if ( $wgUseTrackbacks ) {
3257 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
3258 }
3259 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3260 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
3261 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
3262 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
3263 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
3264 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
3265 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
3266 }
3267 // If the target page was recently created, it may have an entry in recentchanges still
3268 $dbw->delete( 'recentchanges',
3269 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3270 __METHOD__
3271 );
3272 }
3273
3274 # Save a null revision in the page's history notifying of the move
3275 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3276 if ( !is_object( $nullRevision ) ) {
3277 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3278 }
3279 $nullRevId = $nullRevision->insertOn( $dbw );
3280
3281 $article = new Article( $this );
3282 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3283
3284 # Change the name of the target page:
3285 $dbw->update( 'page',
3286 /* SET */ array(
3287 'page_touched' => $dbw->timestamp(),
3288 'page_namespace' => $nt->getNamespace(),
3289 'page_title' => $nt->getDBkey(),
3290 'page_latest' => $nullRevId,
3291 ),
3292 /* WHERE */ array( 'page_id' => $oldid ),
3293 __METHOD__
3294 );
3295 $nt->resetArticleID( $oldid );
3296
3297 # Recreate the redirect, this time in the other direction.
3298 if ( $createRedirect || !$wgUser->isAllowed( 'suppressredirect' ) ) {
3299 $mwRedir = MagicWord::get( 'redirect' );
3300 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3301 $redirectArticle = new Article( $this );
3302 $newid = $redirectArticle->insertOn( $dbw );
3303 $redirectRevision = new Revision( array(
3304 'page' => $newid,
3305 'comment' => $comment,
3306 'text' => $redirectText ) );
3307 $redirectRevision->insertOn( $dbw );
3308 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3309
3310 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3311
3312 # Now, we record the link from the redirect to the new title.
3313 # It should have no other outgoing links...
3314 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3315 $dbw->insert( 'pagelinks',
3316 array(
3317 'pl_from' => $newid,
3318 'pl_namespace' => $nt->getNamespace(),
3319 'pl_title' => $nt->getDBkey() ),
3320 __METHOD__ );
3321 $redirectSuppressed = false;
3322 } else {
3323 // Get rid of old new page entries in Special:NewPages and RC.
3324 // Needs to be before $this->resetArticleID( 0 ).
3325 $dbw->delete( 'recentchanges', array(
3326 'rc_timestamp' => $dbw->timestamp( $this->getEarliestRevTime() ),
3327 'rc_namespace' => $oldns,
3328 'rc_title' => $olddbk,
3329 'rc_new' => 1
3330 ),
3331 __METHOD__
3332 );
3333
3334 $this->resetArticleID( 0 );
3335 $redirectSuppressed = true;
3336 }
3337
3338 # Log the move
3339 $log = new LogPage( 'move' );
3340 $logType = ( $moveOverRedirect ? 'move_redir' : 'move' );
3341 $log->addEntry( $logType, $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3342
3343 # Purge caches for old and new titles
3344 if ( $moveOverRedirect ) {
3345 # A simple purge is enough when moving over a redirect
3346 $nt->purgeSquid();
3347 } else {
3348 # Purge caches as per article creation, including any pages that link to this title
3349 Article::onArticleCreate( $nt );
3350 }
3351 $this->purgeSquid();
3352 }
3353
3354 /**
3355 * Move this page's subpages to be subpages of $nt
3356 *
3357 * @param $nt Title Move target
3358 * @param $auth bool Whether $wgUser's permissions should be checked
3359 * @param $reason string The reason for the move
3360 * @param $createRedirect bool Whether to create redirects from the old subpages to
3361 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3362 * @return mixed array with old page titles as keys, and strings (new page titles) or
3363 * arrays (errors) as values, or an error array with numeric indices if no pages
3364 * were moved
3365 */
3366 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3367 global $wgMaximumMovedPages;
3368 // Check permissions
3369 if ( !$this->userCan( 'move-subpages' ) ) {
3370 return array( 'cant-move-subpages' );
3371 }
3372 // Do the source and target namespaces support subpages?
3373 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3374 return array( 'namespace-nosubpages',
3375 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3376 }
3377 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3378 return array( 'namespace-nosubpages',
3379 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3380 }
3381
3382 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3383 $retval = array();
3384 $count = 0;
3385 foreach ( $subpages as $oldSubpage ) {
3386 $count++;
3387 if ( $count > $wgMaximumMovedPages ) {
3388 $retval[$oldSubpage->getPrefixedTitle()] =
3389 array( 'movepage-max-pages',
3390 $wgMaximumMovedPages );
3391 break;
3392 }
3393
3394 // We don't know whether this function was called before
3395 // or after moving the root page, so check both
3396 // $this and $nt
3397 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3398 $oldSubpage->getArticleID() == $nt->getArticleId() )
3399 {
3400 // When moving a page to a subpage of itself,
3401 // don't move it twice
3402 continue;
3403 }
3404 $newPageName = preg_replace(
3405 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3406 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3407 $oldSubpage->getDBkey() );
3408 if ( $oldSubpage->isTalkPage() ) {
3409 $newNs = $nt->getTalkPage()->getNamespace();
3410 } else {
3411 $newNs = $nt->getSubjectPage()->getNamespace();
3412 }
3413 # Bug 14385: we need makeTitleSafe because the new page names may
3414 # be longer than 255 characters.
3415 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3416
3417 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3418 if ( $success === true ) {
3419 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3420 } else {
3421 $retval[$oldSubpage->getPrefixedText()] = $success;
3422 }
3423 }
3424 return $retval;
3425 }
3426
3427 /**
3428 * Checks if this page is just a one-rev redirect.
3429 * Adds lock, so don't use just for light purposes.
3430 *
3431 * @return Bool
3432 */
3433 public function isSingleRevRedirect() {
3434 $dbw = wfGetDB( DB_MASTER );
3435 # Is it a redirect?
3436 $row = $dbw->selectRow( 'page',
3437 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3438 $this->pageCond(),
3439 __METHOD__,
3440 array( 'FOR UPDATE' )
3441 );
3442 # Cache some fields we may want
3443 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3444 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3445 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3446 if ( !$this->mRedirect ) {
3447 return false;
3448 }
3449 # Does the article have a history?
3450 $row = $dbw->selectField( array( 'page', 'revision' ),
3451 'rev_id',
3452 array( 'page_namespace' => $this->getNamespace(),
3453 'page_title' => $this->getDBkey(),
3454 'page_id=rev_page',
3455 'page_latest != rev_id'
3456 ),
3457 __METHOD__,
3458 array( 'FOR UPDATE' )
3459 );
3460 # Return true if there was no history
3461 return ( $row === false );
3462 }
3463
3464 /**
3465 * Checks if $this can be moved to a given Title
3466 * - Selects for update, so don't call it unless you mean business
3467 *
3468 * @param $nt Title the new title to check
3469 * @return Bool
3470 */
3471 public function isValidMoveTarget( $nt ) {
3472 # Is it an existing file?
3473 if ( $nt->getNamespace() == NS_FILE ) {
3474 $file = wfLocalFile( $nt );
3475 if ( $file->exists() ) {
3476 wfDebug( __METHOD__ . ": file exists\n" );
3477 return false;
3478 }
3479 }
3480 # Is it a redirect with no history?
3481 if ( !$nt->isSingleRevRedirect() ) {
3482 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3483 return false;
3484 }
3485 # Get the article text
3486 $rev = Revision::newFromTitle( $nt );
3487 $text = $rev->getText();
3488 # Does the redirect point to the source?
3489 # Or is it a broken self-redirect, usually caused by namespace collisions?
3490 $m = array();
3491 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3492 $redirTitle = Title::newFromText( $m[1] );
3493 if ( !is_object( $redirTitle ) ||
3494 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3495 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3496 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3497 return false;
3498 }
3499 } else {
3500 # Fail safe
3501 wfDebug( __METHOD__ . ": failsafe\n" );
3502 return false;
3503 }
3504 return true;
3505 }
3506
3507 /**
3508 * Can this title be added to a user's watchlist?
3509 *
3510 * @return Bool TRUE or FALSE
3511 */
3512 public function isWatchable() {
3513 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3514 }
3515
3516 /**
3517 * Get categories to which this Title belongs and return an array of
3518 * categories' names.
3519 *
3520 * @return Array of parents in the form:
3521 * $parent => $currentarticle
3522 */
3523 public function getParentCategories() {
3524 global $wgContLang;
3525
3526 $data = array();
3527
3528 $titleKey = $this->getArticleId();
3529
3530 if ( $titleKey === 0 ) {
3531 return $data;
3532 }
3533
3534 $dbr = wfGetDB( DB_SLAVE );
3535
3536 $res = $dbr->select( 'categorylinks', '*',
3537 array(
3538 'cl_from' => $titleKey,
3539 ),
3540 __METHOD__,
3541 array()
3542 );
3543
3544 if ( $dbr->numRows( $res ) > 0 ) {
3545 foreach ( $res as $row ) {
3546 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3547 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3548 }
3549 }
3550 return $data;
3551 }
3552
3553 /**
3554 * Get a tree of parent categories
3555 *
3556 * @param $children Array with the children in the keys, to check for circular refs
3557 * @return Array Tree of parent categories
3558 */
3559 public function getParentCategoryTree( $children = array() ) {
3560 $stack = array();
3561 $parents = $this->getParentCategories();
3562
3563 if ( $parents ) {
3564 foreach ( $parents as $parent => $current ) {
3565 if ( array_key_exists( $parent, $children ) ) {
3566 # Circular reference
3567 $stack[$parent] = array();
3568 } else {
3569 $nt = Title::newFromText( $parent );
3570 if ( $nt ) {
3571 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3572 }
3573 }
3574 }
3575 }
3576
3577 return $stack;
3578 }
3579
3580 /**
3581 * Get an associative array for selecting this title from
3582 * the "page" table
3583 *
3584 * @return Array suitable for the $where parameter of DB::select()
3585 */
3586 public function pageCond() {
3587 if ( $this->mArticleID > 0 ) {
3588 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3589 return array( 'page_id' => $this->mArticleID );
3590 } else {
3591 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3592 }
3593 }
3594
3595 /**
3596 * Get the revision ID of the previous revision
3597 *
3598 * @param $revId Int Revision ID. Get the revision that was before this one.
3599 * @param $flags Int Title::GAID_FOR_UPDATE
3600 * @return Int|Bool Old revision ID, or FALSE if none exists
3601 */
3602 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3603 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3604 return $db->selectField( 'revision', 'rev_id',
3605 array(
3606 'rev_page' => $this->getArticleId( $flags ),
3607 'rev_id < ' . intval( $revId )
3608 ),
3609 __METHOD__,
3610 array( 'ORDER BY' => 'rev_id DESC' )
3611 );
3612 }
3613
3614 /**
3615 * Get the revision ID of the next revision
3616 *
3617 * @param $revId Int Revision ID. Get the revision that was after this one.
3618 * @param $flags Int Title::GAID_FOR_UPDATE
3619 * @return Int|Bool Next revision ID, or FALSE if none exists
3620 */
3621 public function getNextRevisionID( $revId, $flags = 0 ) {
3622 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3623 return $db->selectField( 'revision', 'rev_id',
3624 array(
3625 'rev_page' => $this->getArticleId( $flags ),
3626 'rev_id > ' . intval( $revId )
3627 ),
3628 __METHOD__,
3629 array( 'ORDER BY' => 'rev_id' )
3630 );
3631 }
3632
3633 /**
3634 * Get the first revision of the page
3635 *
3636 * @param $flags Int Title::GAID_FOR_UPDATE
3637 * @return Revision|Null if page doesn't exist
3638 */
3639 public function getFirstRevision( $flags = 0 ) {
3640 $pageId = $this->getArticleId( $flags );
3641 if ( $pageId ) {
3642 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3643 $row = $db->selectRow( 'revision', '*',
3644 array( 'rev_page' => $pageId ),
3645 __METHOD__,
3646 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3647 );
3648 if ( $row ) {
3649 return new Revision( $row );
3650 }
3651 }
3652 return null;
3653 }
3654
3655 /**
3656 * Get the oldest revision timestamp of this page
3657 *
3658 * @param $flags Int Title::GAID_FOR_UPDATE
3659 * @return String: MW timestamp
3660 */
3661 public function getEarliestRevTime( $flags = 0 ) {
3662 $rev = $this->getFirstRevision( $flags );
3663 return $rev ? $rev->getTimestamp() : null;
3664 }
3665
3666 /**
3667 * Check if this is a new page
3668 *
3669 * @return bool
3670 */
3671 public function isNewPage() {
3672 $dbr = wfGetDB( DB_SLAVE );
3673 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3674 }
3675
3676 /**
3677 * Get the number of revisions between the given revision.
3678 * Used for diffs and other things that really need it.
3679 *
3680 * @param $old int|Revision Old revision or rev ID (first before range)
3681 * @param $new int|Revision New revision or rev ID (first after range)
3682 * @return Int Number of revisions between these revisions.
3683 */
3684 public function countRevisionsBetween( $old, $new ) {
3685 if ( !( $old instanceof Revision ) ) {
3686 $old = Revision::newFromTitle( $this, (int)$old );
3687 }
3688 if ( !( $new instanceof Revision ) ) {
3689 $new = Revision::newFromTitle( $this, (int)$new );
3690 }
3691 if ( !$old || !$new ) {
3692 return 0; // nothing to compare
3693 }
3694 $dbr = wfGetDB( DB_SLAVE );
3695 return (int)$dbr->selectField( 'revision', 'count(*)',
3696 array(
3697 'rev_page' => $this->getArticleId(),
3698 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3699 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3700 ),
3701 __METHOD__
3702 );
3703 }
3704
3705 /**
3706 * Get the number of authors between the given revision IDs.
3707 * Used for diffs and other things that really need it.
3708 *
3709 * @param $old int|Revision Old revision or rev ID (first before range)
3710 * @param $new int|Revision New revision or rev ID (first after range)
3711 * @param $limit Int Maximum number of authors
3712 * @return Int Number of revision authors between these revisions.
3713 */
3714 public function countAuthorsBetween( $old, $new, $limit ) {
3715 if ( !( $old instanceof Revision ) ) {
3716 $old = Revision::newFromTitle( $this, (int)$old );
3717 }
3718 if ( !( $new instanceof Revision ) ) {
3719 $new = Revision::newFromTitle( $this, (int)$new );
3720 }
3721 if ( !$old || !$new ) {
3722 return 0; // nothing to compare
3723 }
3724 $dbr = wfGetDB( DB_SLAVE );
3725 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
3726 array(
3727 'rev_page' => $this->getArticleID(),
3728 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3729 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3730 ), __METHOD__,
3731 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
3732 );
3733 return (int)$dbr->numRows( $res );
3734 }
3735
3736 /**
3737 * Compare with another title.
3738 *
3739 * @param $title Title
3740 * @return Bool
3741 */
3742 public function equals( Title $title ) {
3743 // Note: === is necessary for proper matching of number-like titles.
3744 return $this->getInterwiki() === $title->getInterwiki()
3745 && $this->getNamespace() == $title->getNamespace()
3746 && $this->getDBkey() === $title->getDBkey();
3747 }
3748
3749 /**
3750 * Callback for usort() to do title sorts by (namespace, title)
3751 *
3752 * @param $a Title
3753 * @param $b Title
3754 *
3755 * @return Integer: result of string comparison, or namespace comparison
3756 */
3757 public static function compare( $a, $b ) {
3758 if ( $a->getNamespace() == $b->getNamespace() ) {
3759 return strcmp( $a->getText(), $b->getText() );
3760 } else {
3761 return $a->getNamespace() - $b->getNamespace();
3762 }
3763 }
3764
3765 /**
3766 * Return a string representation of this title
3767 *
3768 * @return String representation of this title
3769 */
3770 public function __toString() {
3771 return $this->getPrefixedText();
3772 }
3773
3774 /**
3775 * Check if page exists. For historical reasons, this function simply
3776 * checks for the existence of the title in the page table, and will
3777 * thus return false for interwiki links, special pages and the like.
3778 * If you want to know if a title can be meaningfully viewed, you should
3779 * probably call the isKnown() method instead.
3780 *
3781 * @return Bool
3782 */
3783 public function exists() {
3784 return $this->getArticleId() != 0;
3785 }
3786
3787 /**
3788 * Should links to this title be shown as potentially viewable (i.e. as
3789 * "bluelinks"), even if there's no record by this title in the page
3790 * table?
3791 *
3792 * This function is semi-deprecated for public use, as well as somewhat
3793 * misleadingly named. You probably just want to call isKnown(), which
3794 * calls this function internally.
3795 *
3796 * (ISSUE: Most of these checks are cheap, but the file existence check
3797 * can potentially be quite expensive. Including it here fixes a lot of
3798 * existing code, but we might want to add an optional parameter to skip
3799 * it and any other expensive checks.)
3800 *
3801 * @return Bool
3802 */
3803 public function isAlwaysKnown() {
3804 if ( $this->mInterwiki != '' ) {
3805 return true; // any interwiki link might be viewable, for all we know
3806 }
3807 switch( $this->mNamespace ) {
3808 case NS_MEDIA:
3809 case NS_FILE:
3810 // file exists, possibly in a foreign repo
3811 return (bool)wfFindFile( $this );
3812 case NS_SPECIAL:
3813 // valid special page
3814 return SpecialPageFactory::exists( $this->getDBkey() );
3815 case NS_MAIN:
3816 // selflink, possibly with fragment
3817 return $this->mDbkeyform == '';
3818 case NS_MEDIAWIKI:
3819 // known system message
3820 return $this->getDefaultMessageText() !== false;
3821 default:
3822 return false;
3823 }
3824 }
3825
3826 /**
3827 * Does this title refer to a page that can (or might) be meaningfully
3828 * viewed? In particular, this function may be used to determine if
3829 * links to the title should be rendered as "bluelinks" (as opposed to
3830 * "redlinks" to non-existent pages).
3831 *
3832 * @return Bool
3833 */
3834 public function isKnown() {
3835 return $this->isAlwaysKnown() || $this->exists();
3836 }
3837
3838 /**
3839 * Does this page have source text?
3840 *
3841 * @return Boolean
3842 */
3843 public function hasSourceText() {
3844 if ( $this->exists() ) {
3845 return true;
3846 }
3847
3848 if ( $this->mNamespace == NS_MEDIAWIKI ) {
3849 // If the page doesn't exist but is a known system message, default
3850 // message content will be displayed, same for language subpages
3851 return $this->getDefaultMessageText() !== false;
3852 }
3853
3854 return false;
3855 }
3856
3857 /**
3858 * Get the default message text or false if the message doesn't exist
3859 *
3860 * @return String or false
3861 */
3862 public function getDefaultMessageText() {
3863 global $wgContLang;
3864
3865 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
3866 return false;
3867 }
3868
3869 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
3870 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
3871
3872 if ( $message->exists() ) {
3873 return $message->plain();
3874 } else {
3875 return false;
3876 }
3877 }
3878
3879 /**
3880 * Is this in a namespace that allows actual pages?
3881 *
3882 * @return Bool
3883 * @internal note -- uses hardcoded namespace index instead of constants
3884 */
3885 public function canExist() {
3886 return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA;
3887 }
3888
3889 /**
3890 * Update page_touched timestamps and send squid purge messages for
3891 * pages linking to this title. May be sent to the job queue depending
3892 * on the number of links. Typically called on create and delete.
3893 */
3894 public function touchLinks() {
3895 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3896 $u->doUpdate();
3897
3898 if ( $this->getNamespace() == NS_CATEGORY ) {
3899 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3900 $u->doUpdate();
3901 }
3902 }
3903
3904 /**
3905 * Get the last touched timestamp
3906 *
3907 * @param $db DatabaseBase: optional db
3908 * @return String last-touched timestamp
3909 */
3910 public function getTouched( $db = null ) {
3911 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
3912 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
3913 return $touched;
3914 }
3915
3916 /**
3917 * Get the timestamp when this page was updated since the user last saw it.
3918 *
3919 * @param $user User
3920 * @return String|Null
3921 */
3922 public function getNotificationTimestamp( $user = null ) {
3923 global $wgUser, $wgShowUpdatedMarker;
3924 // Assume current user if none given
3925 if ( !$user ) {
3926 $user = $wgUser;
3927 }
3928 // Check cache first
3929 $uid = $user->getId();
3930 // avoid isset here, as it'll return false for null entries
3931 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
3932 return $this->mNotificationTimestamp[$uid];
3933 }
3934 if ( !$uid || !$wgShowUpdatedMarker ) {
3935 return $this->mNotificationTimestamp[$uid] = false;
3936 }
3937 // Don't cache too much!
3938 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
3939 $this->mNotificationTimestamp = array();
3940 }
3941 $dbr = wfGetDB( DB_SLAVE );
3942 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
3943 'wl_notificationtimestamp',
3944 array( 'wl_namespace' => $this->getNamespace(),
3945 'wl_title' => $this->getDBkey(),
3946 'wl_user' => $user->getId()
3947 ),
3948 __METHOD__
3949 );
3950 return $this->mNotificationTimestamp[$uid];
3951 }
3952
3953 /**
3954 * Get the trackback URL for this page
3955 *
3956 * @return String Trackback URL
3957 */
3958 public function trackbackURL() {
3959 global $wgScriptPath, $wgServer, $wgScriptExtension;
3960
3961 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3962 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3963 }
3964
3965 /**
3966 * Get the trackback RDF for this page
3967 *
3968 * @return String Trackback RDF
3969 */
3970 public function trackbackRDF() {
3971 $url = htmlspecialchars( $this->getFullURL() );
3972 $title = htmlspecialchars( $this->getText() );
3973 $tburl = $this->trackbackURL();
3974
3975 // Autodiscovery RDF is placed in comments so HTML validator
3976 // won't barf. This is a rather icky workaround, but seems
3977 // frequently used by this kind of RDF thingy.
3978 //
3979 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3980 return "<!--
3981 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3982 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3983 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3984 <rdf:Description
3985 rdf:about=\"$url\"
3986 dc:identifier=\"$url\"
3987 dc:title=\"$title\"
3988 trackback:ping=\"$tburl\" />
3989 </rdf:RDF>
3990 -->";
3991 }
3992
3993 /**
3994 * Generate strings used for xml 'id' names in monobook tabs
3995 *
3996 * @param $prepend string defaults to 'nstab-'
3997 * @return String XML 'id' name
3998 */
3999 public function getNamespaceKey( $prepend = 'nstab-' ) {
4000 global $wgContLang;
4001 // Gets the subject namespace if this title
4002 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4003 // Checks if cononical namespace name exists for namespace
4004 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4005 // Uses canonical namespace name
4006 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4007 } else {
4008 // Uses text of namespace
4009 $namespaceKey = $this->getSubjectNsText();
4010 }
4011 // Makes namespace key lowercase
4012 $namespaceKey = $wgContLang->lc( $namespaceKey );
4013 // Uses main
4014 if ( $namespaceKey == '' ) {
4015 $namespaceKey = 'main';
4016 }
4017 // Changes file to image for backwards compatibility
4018 if ( $namespaceKey == 'file' ) {
4019 $namespaceKey = 'image';
4020 }
4021 return $prepend . $namespaceKey;
4022 }
4023
4024 /**
4025 * Returns true if this is a special page.
4026 *
4027 * @return boolean
4028 */
4029 public function isSpecialPage() {
4030 return $this->getNamespace() == NS_SPECIAL;
4031 }
4032
4033 /**
4034 * Returns true if this title resolves to the named special page
4035 *
4036 * @param $name String The special page name
4037 * @return boolean
4038 */
4039 public function isSpecial( $name ) {
4040 if ( $this->getNamespace() == NS_SPECIAL ) {
4041 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
4042 if ( $name == $thisName ) {
4043 return true;
4044 }
4045 }
4046 return false;
4047 }
4048
4049 /**
4050 * If the Title refers to a special page alias which is not the local default, resolve
4051 * the alias, and localise the name as necessary. Otherwise, return $this
4052 *
4053 * @return Title
4054 */
4055 public function fixSpecialName() {
4056 if ( $this->getNamespace() == NS_SPECIAL ) {
4057 list( $canonicalName, /*...*/ ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
4058 if ( $canonicalName ) {
4059 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName );
4060 if ( $localName != $this->mDbkeyform ) {
4061 return Title::makeTitle( NS_SPECIAL, $localName );
4062 }
4063 }
4064 }
4065 return $this;
4066 }
4067
4068 /**
4069 * Is this Title in a namespace which contains content?
4070 * In other words, is this a content page, for the purposes of calculating
4071 * statistics, etc?
4072 *
4073 * @return Boolean
4074 */
4075 public function isContentPage() {
4076 return MWNamespace::isContent( $this->getNamespace() );
4077 }
4078
4079 /**
4080 * Get all extant redirects to this Title
4081 *
4082 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4083 * @return Array of Title redirects to this title
4084 */
4085 public function getRedirectsHere( $ns = null ) {
4086 $redirs = array();
4087
4088 $dbr = wfGetDB( DB_SLAVE );
4089 $where = array(
4090 'rd_namespace' => $this->getNamespace(),
4091 'rd_title' => $this->getDBkey(),
4092 'rd_from = page_id'
4093 );
4094 if ( !is_null( $ns ) ) {
4095 $where['page_namespace'] = $ns;
4096 }
4097
4098 $res = $dbr->select(
4099 array( 'redirect', 'page' ),
4100 array( 'page_namespace', 'page_title' ),
4101 $where,
4102 __METHOD__
4103 );
4104
4105 foreach ( $res as $row ) {
4106 $redirs[] = self::newFromRow( $row );
4107 }
4108 return $redirs;
4109 }
4110
4111 /**
4112 * Check if this Title is a valid redirect target
4113 *
4114 * @return Bool
4115 */
4116 public function isValidRedirectTarget() {
4117 global $wgInvalidRedirectTargets;
4118
4119 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4120 if ( $this->isSpecial( 'Userlogout' ) ) {
4121 return false;
4122 }
4123
4124 foreach ( $wgInvalidRedirectTargets as $target ) {
4125 if ( $this->isSpecial( $target ) ) {
4126 return false;
4127 }
4128 }
4129
4130 return true;
4131 }
4132
4133 /**
4134 * Get a backlink cache object
4135 *
4136 * @return object BacklinkCache
4137 */
4138 function getBacklinkCache() {
4139 if ( is_null( $this->mBacklinkCache ) ) {
4140 $this->mBacklinkCache = new BacklinkCache( $this );
4141 }
4142 return $this->mBacklinkCache;
4143 }
4144
4145 /**
4146 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4147 *
4148 * @return Boolean
4149 */
4150 public function canUseNoindex() {
4151 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4152
4153 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4154 ? $wgContentNamespaces
4155 : $wgExemptFromUserRobotsControl;
4156
4157 return !in_array( $this->mNamespace, $bannedNamespaces );
4158
4159 }
4160
4161 /**
4162 * Returns restriction types for the current Title
4163 *
4164 * @return array applicable restriction types
4165 */
4166 public function getRestrictionTypes() {
4167 if ( $this->getNamespace() == NS_SPECIAL ) {
4168 return array();
4169 }
4170
4171 $types = self::getFilteredRestrictionTypes( $this->exists() );
4172
4173 if ( $this->getNamespace() != NS_FILE ) {
4174 # Remove the upload restriction for non-file titles
4175 $types = array_diff( $types, array( 'upload' ) );
4176 }
4177
4178 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4179
4180 wfDebug( __METHOD__ . ': applicable restriction types for ' .
4181 $this->getPrefixedText() . ' are ' . implode( ',', $types ) . "\n" );
4182
4183 return $types;
4184 }
4185 /**
4186 * Get a filtered list of all restriction types supported by this wiki.
4187 * @param bool $exists True to get all restriction types that apply to
4188 * titles that do exist, False for all restriction types that apply to
4189 * titles that do not exist
4190 * @return array
4191 */
4192 public static function getFilteredRestrictionTypes( $exists = true ) {
4193 global $wgRestrictionTypes;
4194 $types = $wgRestrictionTypes;
4195 if ( $exists ) {
4196 # Remove the create restriction for existing titles
4197 $types = array_diff( $types, array( 'create' ) );
4198 } else {
4199 # Only the create and upload restrictions apply to non-existing titles
4200 $types = array_intersect( $types, array( 'create', 'upload' ) );
4201 }
4202 return $types;
4203 }
4204
4205 /**
4206 * Returns the raw sort key to be used for categories, with the specified
4207 * prefix. This will be fed to Collation::getSortKey() to get a
4208 * binary sortkey that can be used for actual sorting.
4209 *
4210 * @param $prefix string The prefix to be used, specified using
4211 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4212 * prefix.
4213 * @return string
4214 */
4215 public function getCategorySortkey( $prefix = '' ) {
4216 $unprefixed = $this->getText();
4217 if ( $prefix !== '' ) {
4218 # Separate with a line feed, so the unprefixed part is only used as
4219 # a tiebreaker when two pages have the exact same prefix.
4220 # In UCA, tab is the only character that can sort above LF
4221 # so we strip both of them from the original prefix.
4222 $prefix = strtr( $prefix, "\n\t", ' ' );
4223 return "$prefix\n$unprefixed";
4224 }
4225 return $unprefixed;
4226 }
4227 }
4228
4229 /**
4230 * A BadTitle is generated in MediaWiki::parseTitle() if the title is invalid; the
4231 * software uses this to display an error page. Internally it's basically a Title
4232 * for an empty special page
4233 */
4234 class BadTitle extends Title {
4235 public function __construct(){
4236 $this->mTextform = '';
4237 $this->mUrlform = '';
4238 $this->mDbkeyform = '';
4239 $this->mNamespace = NS_SPECIAL; // Stops talk page link, etc, being shown
4240 }
4241
4242 public function exists(){
4243 return false;
4244 }
4245
4246 public function getPrefixedText(){
4247 return '';
4248 }
4249
4250 public function getText(){
4251 return '';
4252 }
4253
4254 public function getPrefixedURL(){
4255 return '';
4256 }
4257
4258 public function getPrefixedDBKey(){
4259 return '';
4260 }
4261 }