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