Last few svn property fixes
[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;
994 $url = $wgInternalServer . $this->getLocalURL( $query, $variant );
995 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
996 return $url;
997 }
998
999 /**
1000 * Get the edit URL for this Title
1001 *
1002 * @return String the URL, or a null string if this is an
1003 * interwiki link
1004 */
1005 public function getEditURL() {
1006 if ( $this->mInterwiki != '' ) {
1007 return '';
1008 }
1009 $s = $this->getLocalURL( 'action=edit' );
1010
1011 return $s;
1012 }
1013
1014 /**
1015 * Get the HTML-escaped displayable text form.
1016 * Used for the title field in <a> tags.
1017 *
1018 * @return String the text, including any prefixes
1019 */
1020 public function getEscapedText() {
1021 return htmlspecialchars( $this->getPrefixedText() );
1022 }
1023
1024 /**
1025 * Is this Title interwiki?
1026 *
1027 * @return Bool
1028 */
1029 public function isExternal() {
1030 return ( $this->mInterwiki != '' );
1031 }
1032
1033 /**
1034 * Is this page "semi-protected" - the *only* protection is autoconfirm?
1035 *
1036 * @param $action String Action to check (default: edit)
1037 * @return Bool
1038 */
1039 public function isSemiProtected( $action = 'edit' ) {
1040 if ( $this->exists() ) {
1041 $restrictions = $this->getRestrictions( $action );
1042 if ( count( $restrictions ) > 0 ) {
1043 foreach ( $restrictions as $restriction ) {
1044 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
1045 return false;
1046 }
1047 }
1048 } else {
1049 # Not protected
1050 return false;
1051 }
1052 return true;
1053 } else {
1054 # If it doesn't exist, it can't be protected
1055 return false;
1056 }
1057 }
1058
1059 /**
1060 * Does the title correspond to a protected article?
1061 *
1062 * @param $action String the action the page is protected from,
1063 * by default checks all actions.
1064 * @return Bool
1065 */
1066 public function isProtected( $action = '' ) {
1067 global $wgRestrictionLevels;
1068
1069 $restrictionTypes = $this->getRestrictionTypes();
1070
1071 # Special pages have inherent protection
1072 if( $this->getNamespace() == NS_SPECIAL ) {
1073 return true;
1074 }
1075
1076 # Check regular protection levels
1077 foreach ( $restrictionTypes as $type ) {
1078 if ( $action == $type || $action == '' ) {
1079 $r = $this->getRestrictions( $type );
1080 foreach ( $wgRestrictionLevels as $level ) {
1081 if ( in_array( $level, $r ) && $level != '' ) {
1082 return true;
1083 }
1084 }
1085 }
1086 }
1087
1088 return false;
1089 }
1090
1091 /**
1092 * Is this a conversion table for the LanguageConverter?
1093 *
1094 * @return Bool
1095 */
1096 public function isConversionTable() {
1097 if(
1098 $this->getNamespace() == NS_MEDIAWIKI &&
1099 strpos( $this->getText(), 'Conversiontable' ) !== false
1100 )
1101 {
1102 return true;
1103 }
1104
1105 return false;
1106 }
1107
1108 /**
1109 * Is $wgUser watching this page?
1110 *
1111 * @return Bool
1112 */
1113 public function userIsWatching() {
1114 global $wgUser;
1115
1116 if ( is_null( $this->mWatched ) ) {
1117 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1118 $this->mWatched = false;
1119 } else {
1120 $this->mWatched = $wgUser->isWatched( $this );
1121 }
1122 }
1123 return $this->mWatched;
1124 }
1125
1126 /**
1127 * Can $wgUser perform $action on this page?
1128 * This skips potentially expensive cascading permission checks
1129 * as well as avoids expensive error formatting
1130 *
1131 * Suitable for use for nonessential UI controls in common cases, but
1132 * _not_ for functional access control.
1133 *
1134 * May provide false positives, but should never provide a false negative.
1135 *
1136 * @param $action String action that permission needs to be checked for
1137 * @return Bool
1138 */
1139 public function quickUserCan( $action ) {
1140 return $this->userCan( $action, false );
1141 }
1142
1143 /**
1144 * Determines if $user is unable to edit this page because it has been protected
1145 * by $wgNamespaceProtection.
1146 *
1147 * @param $user User object, $wgUser will be used if not passed
1148 * @return Bool
1149 */
1150 public function isNamespaceProtected( User $user = null ) {
1151 global $wgNamespaceProtection;
1152
1153 if ( $user === null ) {
1154 global $wgUser;
1155 $user = $wgUser;
1156 }
1157
1158 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
1159 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
1160 if ( $right != '' && !$user->isAllowed( $right ) ) {
1161 return true;
1162 }
1163 }
1164 }
1165 return false;
1166 }
1167
1168 /**
1169 * Can $wgUser perform $action on this page?
1170 *
1171 * @param $action String action that permission needs to be checked for
1172 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1173 * @return Bool
1174 */
1175 public function userCan( $action, $doExpensiveQueries = true ) {
1176 global $wgUser;
1177 return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries, true ) === array() );
1178 }
1179
1180 /**
1181 * Can $user perform $action on this page?
1182 *
1183 * FIXME: This *does not* check throttles (User::pingLimiter()).
1184 *
1185 * @param $action String action that permission needs to be checked for
1186 * @param $user User to check
1187 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1188 * @param $ignoreErrors Array of Strings Set this to a list of message keys whose corresponding errors may be ignored.
1189 * @return Array of arguments to wfMsg to explain permissions problems.
1190 */
1191 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1192 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1193
1194 // Remove the errors being ignored.
1195 foreach ( $errors as $index => $error ) {
1196 $error_key = is_array( $error ) ? $error[0] : $error;
1197
1198 if ( in_array( $error_key, $ignoreErrors ) ) {
1199 unset( $errors[$index] );
1200 }
1201 }
1202
1203 return $errors;
1204 }
1205
1206 /**
1207 * Permissions checks that fail most often, and which are easiest to test.
1208 *
1209 * @param $action String the action to check
1210 * @param $user User user to check
1211 * @param $errors Array list of current errors
1212 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1213 * @param $short Boolean short circuit on first error
1214 *
1215 * @return Array list of errors
1216 */
1217 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1218 if ( $action == 'create' ) {
1219 if ( ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1220 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
1221 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1222 }
1223 } elseif ( $action == 'move' ) {
1224 if ( !$user->isAllowed( 'move-rootuserpages' )
1225 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1226 // Show user page-specific message only if the user can move other pages
1227 $errors[] = array( 'cant-move-user-page' );
1228 }
1229
1230 // Check if user is allowed to move files if it's a file
1231 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1232 $errors[] = array( 'movenotallowedfile' );
1233 }
1234
1235 if ( !$user->isAllowed( 'move' ) ) {
1236 // User can't move anything
1237 global $wgGroupPermissions;
1238 $userCanMove = false;
1239 if ( isset( $wgGroupPermissions['user']['move'] ) ) {
1240 $userCanMove = $wgGroupPermissions['user']['move'];
1241 }
1242 $autoconfirmedCanMove = false;
1243 if ( isset( $wgGroupPermissions['autoconfirmed']['move'] ) ) {
1244 $autoconfirmedCanMove = $wgGroupPermissions['autoconfirmed']['move'];
1245 }
1246 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1247 // custom message if logged-in users without any special rights can move
1248 $errors[] = array( 'movenologintext' );
1249 } else {
1250 $errors[] = array( 'movenotallowed' );
1251 }
1252 }
1253 } elseif ( $action == 'move-target' ) {
1254 if ( !$user->isAllowed( 'move' ) ) {
1255 // User can't move anything
1256 $errors[] = array( 'movenotallowed' );
1257 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1258 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1259 // Show user page-specific message only if the user can move other pages
1260 $errors[] = array( 'cant-move-to-user-page' );
1261 }
1262 } elseif ( !$user->isAllowed( $action ) ) {
1263 // We avoid expensive display logic for quickUserCan's and such
1264 $groups = false;
1265 if ( !$short ) {
1266 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1267 User::getGroupsWithPermission( $action ) );
1268 }
1269
1270 if ( $groups ) {
1271 global $wgLang;
1272 $return = array(
1273 'badaccess-groups',
1274 $wgLang->commaList( $groups ),
1275 count( $groups )
1276 );
1277 } else {
1278 $return = array( 'badaccess-group0' );
1279 }
1280 $errors[] = $return;
1281 }
1282
1283 return $errors;
1284 }
1285
1286 /**
1287 * Add the resulting error code to the errors array
1288 *
1289 * @param $errors Array list of current errors
1290 * @param $result Mixed result of errors
1291 *
1292 * @return Array list of errors
1293 */
1294 private function resultToError( $errors, $result ) {
1295 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1296 // A single array representing an error
1297 $errors[] = $result;
1298 } else if ( is_array( $result ) && is_array( $result[0] ) ) {
1299 // A nested array representing multiple errors
1300 $errors = array_merge( $errors, $result );
1301 } else if ( $result !== '' && is_string( $result ) ) {
1302 // A string representing a message-id
1303 $errors[] = array( $result );
1304 } else if ( $result === false ) {
1305 // a generic "We don't want them to do that"
1306 $errors[] = array( 'badaccess-group0' );
1307 }
1308 return $errors;
1309 }
1310
1311 /**
1312 * Check various permission hooks
1313 *
1314 * @param $action String the action to check
1315 * @param $user User user to check
1316 * @param $errors Array list of current errors
1317 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1318 * @param $short Boolean short circuit on first error
1319 *
1320 * @return Array list of errors
1321 */
1322 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1323 // Use getUserPermissionsErrors instead
1324 $result = '';
1325 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1326 return $result ? array() : array( array( 'badaccess-group0' ) );
1327 }
1328 // Check getUserPermissionsErrors hook
1329 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1330 $errors = $this->resultToError( $errors, $result );
1331 }
1332 // Check getUserPermissionsErrorsExpensive hook
1333 if ( $doExpensiveQueries && !( $short && count( $errors ) > 0 ) &&
1334 !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
1335 $errors = $this->resultToError( $errors, $result );
1336 }
1337
1338 return $errors;
1339 }
1340
1341 /**
1342 * Check permissions on special pages & namespaces
1343 *
1344 * @param $action String the action to check
1345 * @param $user User user to check
1346 * @param $errors Array list of current errors
1347 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1348 * @param $short Boolean short circuit on first error
1349 *
1350 * @return Array list of errors
1351 */
1352 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1353 # Only 'createaccount' and 'execute' can be performed on
1354 # special pages, which don't actually exist in the DB.
1355 $specialOKActions = array( 'createaccount', 'execute' );
1356 if ( NS_SPECIAL == $this->mNamespace && !in_array( $action, $specialOKActions ) ) {
1357 $errors[] = array( 'ns-specialprotected' );
1358 }
1359
1360 # Check $wgNamespaceProtection for restricted namespaces
1361 if ( $this->isNamespaceProtected( $user ) ) {
1362 $ns = $this->mNamespace == NS_MAIN ?
1363 wfMsg( 'nstab-main' ) : $this->getNsText();
1364 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
1365 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1366 }
1367
1368 return $errors;
1369 }
1370
1371 /**
1372 * Check CSS/JS sub-page permissions
1373 *
1374 * @param $action String the action to check
1375 * @param $user User user to check
1376 * @param $errors Array list of current errors
1377 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1378 * @param $short Boolean short circuit on first error
1379 *
1380 * @return Array list of errors
1381 */
1382 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1383 # Protect css/js subpages of user pages
1384 # XXX: this might be better using restrictions
1385 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssSubpage()
1386 # and $this->userCanEditJsSubpage() from working
1387 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1388 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1389 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
1390 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1391 $errors[] = array( 'customcssjsprotected' );
1392 } else if ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1393 $errors[] = array( 'customcssjsprotected' );
1394 }
1395 }
1396
1397 return $errors;
1398 }
1399
1400 /**
1401 * Check against page_restrictions table requirements on this
1402 * page. The user must possess all required rights for this
1403 * action.
1404 *
1405 * @param $action String the action to check
1406 * @param $user User user to check
1407 * @param $errors Array list of current errors
1408 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1409 * @param $short Boolean short circuit on first error
1410 *
1411 * @return Array list of errors
1412 */
1413 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1414 foreach ( $this->getRestrictions( $action ) as $right ) {
1415 // Backwards compatibility, rewrite sysop -> protect
1416 if ( $right == 'sysop' ) {
1417 $right = 'protect';
1418 }
1419 if ( $right != '' && !$user->isAllowed( $right ) ) {
1420 // Users with 'editprotected' permission can edit protected pages
1421 if ( $action == 'edit' && $user->isAllowed( 'editprotected' ) ) {
1422 // Users with 'editprotected' permission cannot edit protected pages
1423 // with cascading option turned on.
1424 if ( $this->mCascadeRestriction ) {
1425 $errors[] = array( 'protectedpagetext', $right );
1426 }
1427 } else {
1428 $errors[] = array( 'protectedpagetext', $right );
1429 }
1430 }
1431 }
1432
1433 return $errors;
1434 }
1435
1436 /**
1437 * Check restrictions on cascading pages.
1438 *
1439 * @param $action String the action to check
1440 * @param $user User to check
1441 * @param $errors Array list of current errors
1442 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1443 * @param $short Boolean short circuit on first error
1444 *
1445 * @return Array list of errors
1446 */
1447 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1448 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1449 # We /could/ use the protection level on the source page, but it's
1450 # fairly ugly as we have to establish a precedence hierarchy for pages
1451 # included by multiple cascade-protected pages. So just restrict
1452 # it to people with 'protect' permission, as they could remove the
1453 # protection anyway.
1454 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1455 # Cascading protection depends on more than this page...
1456 # Several cascading protected pages may include this page...
1457 # Check each cascading level
1458 # This is only for protection restrictions, not for all actions
1459 if ( isset( $restrictions[$action] ) ) {
1460 foreach ( $restrictions[$action] as $right ) {
1461 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1462 if ( $right != '' && !$user->isAllowed( $right ) ) {
1463 $pages = '';
1464 foreach ( $cascadingSources as $page )
1465 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1466 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1467 }
1468 }
1469 }
1470 }
1471
1472 return $errors;
1473 }
1474
1475 /**
1476 * Check action permissions not already checked in checkQuickPermissions
1477 *
1478 * @param $action String the action to check
1479 * @param $user User to check
1480 * @param $errors Array list of current errors
1481 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1482 * @param $short Boolean short circuit on first error
1483 *
1484 * @return Array list of errors
1485 */
1486 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1487 if ( $action == 'protect' ) {
1488 if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
1489 // If they can't edit, they shouldn't protect.
1490 $errors[] = array( 'protect-cantedit' );
1491 }
1492 } elseif ( $action == 'create' ) {
1493 $title_protection = $this->getTitleProtection();
1494 if( $title_protection ) {
1495 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1496 $title_protection['pt_create_perm'] = 'protect'; // B/C
1497 }
1498 if( $title_protection['pt_create_perm'] == '' || !$user->isAllowed( $title_protection['pt_create_perm'] ) ) {
1499 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1500 }
1501 }
1502 } elseif ( $action == 'move' ) {
1503 // Check for immobile pages
1504 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1505 // Specific message for this case
1506 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1507 } elseif ( !$this->isMovable() ) {
1508 // Less specific message for rarer cases
1509 $errors[] = array( 'immobile-page' );
1510 }
1511 } elseif ( $action == 'move-target' ) {
1512 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1513 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
1514 } elseif ( !$this->isMovable() ) {
1515 $errors[] = array( 'immobile-target-page' );
1516 }
1517 }
1518 return $errors;
1519 }
1520
1521 /**
1522 * Check that the user isn't blocked from editting.
1523 *
1524 * @param $action String the action to check
1525 * @param $user User to check
1526 * @param $errors Array list of current errors
1527 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1528 * @param $short Boolean short circuit on first error
1529 *
1530 * @return Array list of errors
1531 */
1532 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
1533 if( $short && count( $errors ) > 0 ) {
1534 return $errors;
1535 }
1536
1537 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
1538
1539 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() && $action != 'createaccount' ) {
1540 $errors[] = array( 'confirmedittext' );
1541 }
1542
1543 // Edit blocks should not affect reading. Account creation blocks handled at userlogin.
1544 if ( $action != 'read' && $action != 'createaccount' && $user->isBlockedFrom( $this ) ) {
1545 $block = $user->mBlock;
1546
1547 // This is from OutputPage::blockedPage
1548 // Copied at r23888 by werdna
1549
1550 $id = $user->blockedBy();
1551 $reason = $user->blockedFor();
1552 if ( $reason == '' ) {
1553 $reason = wfMsg( 'blockednoreason' );
1554 }
1555 $ip = wfGetIP();
1556
1557 if ( is_numeric( $id ) ) {
1558 $name = User::whoIs( $id );
1559 } else {
1560 $name = $id;
1561 }
1562
1563 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1564 $blockid = $block->mId;
1565 $blockExpiry = $user->mBlock->mExpiry;
1566 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1567 if ( $blockExpiry == 'infinity' ) {
1568 // Entry in database (table ipblocks) is 'infinity' but 'ipboptions' uses 'infinite' or 'indefinite'
1569 $scBlockExpiryOptions = wfMsg( 'ipboptions' );
1570
1571 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
1572 if ( !strpos( $option, ':' ) )
1573 continue;
1574
1575 list( $show, $value ) = explode( ':', $option );
1576
1577 if ( $value == 'infinite' || $value == 'indefinite' ) {
1578 $blockExpiry = $show;
1579 break;
1580 }
1581 }
1582 } else {
1583 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1584 }
1585
1586 $intended = $user->mBlock->mAddress;
1587
1588 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1589 $blockid, $blockExpiry, $intended, $blockTimestamp );
1590 }
1591
1592 return $errors;
1593 }
1594
1595 /**
1596 * Can $user perform $action on this page? This is an internal function,
1597 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1598 * checks on wfReadOnly() and blocks)
1599 *
1600 * @param $action String action that permission needs to be checked for
1601 * @param $user User to check
1602 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1603 * @param $short Bool Set this to true to stop after the first permission error.
1604 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1605 */
1606 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1607 wfProfileIn( __METHOD__ );
1608
1609 $errors = array();
1610 $checks = array(
1611 'checkQuickPermissions',
1612 'checkPermissionHooks',
1613 'checkSpecialsAndNSPermissions',
1614 'checkCSSandJSPermissions',
1615 'checkPageRestrictions',
1616 'checkCascadingSourcesRestrictions',
1617 'checkActionPermissions',
1618 'checkUserBlock'
1619 );
1620
1621 while( count( $checks ) > 0 &&
1622 !( $short && count( $errors ) > 0 ) ) {
1623 $method = array_shift( $checks );
1624 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1625 }
1626
1627 wfProfileOut( __METHOD__ );
1628 return $errors;
1629 }
1630
1631 /**
1632 * Is this title subject to title protection?
1633 * Title protection is the one applied against creation of such title.
1634 *
1635 * @return Mixed An associative array representing any existent title
1636 * protection, or false if there's none.
1637 */
1638 private function getTitleProtection() {
1639 // Can't protect pages in special namespaces
1640 if ( $this->getNamespace() < 0 ) {
1641 return false;
1642 }
1643
1644 // Can't protect pages that exist.
1645 if ( $this->exists() ) {
1646 return false;
1647 }
1648
1649 if ( !isset( $this->mTitleProtection ) ) {
1650 $dbr = wfGetDB( DB_SLAVE );
1651 $res = $dbr->select( 'protected_titles', '*',
1652 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1653 __METHOD__ );
1654
1655 // fetchRow returns false if there are no rows.
1656 $this->mTitleProtection = $dbr->fetchRow( $res );
1657 }
1658 return $this->mTitleProtection;
1659 }
1660
1661 /**
1662 * Update the title protection status
1663 *
1664 * @param $create_perm String Permission required for creation
1665 * @param $reason String Reason for protection
1666 * @param $expiry String Expiry timestamp
1667 * @return boolean true
1668 */
1669 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1670 global $wgUser, $wgContLang;
1671
1672 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1673 && $expiry == $this->mRestrictionsExpiry['create'] ) {
1674 // No change
1675 return true;
1676 }
1677
1678 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1679
1680 $dbw = wfGetDB( DB_MASTER );
1681
1682 $encodedExpiry = Block::encodeExpiry( $expiry, $dbw );
1683
1684 $expiry_description = '';
1685 if ( $encodedExpiry != 'infinity' ) {
1686 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1687 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1688 } else {
1689 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1690 }
1691
1692 # Update protection table
1693 if ( $create_perm != '' ) {
1694 $this->mTitleProtection = array(
1695 'pt_namespace' => $namespace,
1696 'pt_title' => $title,
1697 'pt_create_perm' => $create_perm,
1698 'pt_timestamp' => Block::encodeExpiry( wfTimestampNow(), $dbw ),
1699 'pt_expiry' => $encodedExpiry,
1700 'pt_user' => $wgUser->getId(),
1701 'pt_reason' => $reason,
1702 );
1703 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1704 $this->mTitleProtection, __METHOD__ );
1705 } else {
1706 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1707 'pt_title' => $title ), __METHOD__ );
1708 $this->mTitleProtection = false;
1709 }
1710
1711 # Update the protection log
1712 if ( $dbw->affectedRows() ) {
1713 $log = new LogPage( 'protect' );
1714
1715 if ( $create_perm ) {
1716 $params = array( "[create=$create_perm] $expiry_description", '' );
1717 $log->addEntry( ( isset( $this->mRestrictions['create'] ) && $this->mRestrictions['create'] ) ? 'modify' : 'protect', $this, trim( $reason ), $params );
1718 } else {
1719 $log->addEntry( 'unprotect', $this, $reason );
1720 }
1721 }
1722
1723 return true;
1724 }
1725
1726 /**
1727 * Remove any title protection due to page existing
1728 */
1729 public function deleteTitleProtection() {
1730 $dbw = wfGetDB( DB_MASTER );
1731
1732 $dbw->delete(
1733 'protected_titles',
1734 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1735 __METHOD__
1736 );
1737 $this->mTitleProtection = false;
1738 }
1739
1740 /**
1741 * Would anybody with sufficient privileges be able to move this page?
1742 * Some pages just aren't movable.
1743 *
1744 * @return Bool TRUE or FALSE
1745 */
1746 public function isMovable() {
1747 return MWNamespace::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1748 }
1749
1750 /**
1751 * Can $wgUser read this page?
1752 *
1753 * @return Bool
1754 * @todo fold these checks into userCan()
1755 */
1756 public function userCanRead() {
1757 global $wgUser, $wgGroupPermissions;
1758
1759 static $useShortcut = null;
1760
1761 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1762 if ( is_null( $useShortcut ) ) {
1763 global $wgRevokePermissions;
1764 $useShortcut = true;
1765 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1766 # Not a public wiki, so no shortcut
1767 $useShortcut = false;
1768 } elseif ( !empty( $wgRevokePermissions ) ) {
1769 /*
1770 * Iterate through each group with permissions being revoked (key not included since we don't care
1771 * what the group name is), then check if the read permission is being revoked. If it is, then
1772 * we don't use the shortcut below since the user might not be able to read, even though anon
1773 * reading is allowed.
1774 */
1775 foreach ( $wgRevokePermissions as $perms ) {
1776 if ( !empty( $perms['read'] ) ) {
1777 # We might be removing the read right from the user, so no shortcut
1778 $useShortcut = false;
1779 break;
1780 }
1781 }
1782 }
1783 }
1784
1785 $result = null;
1786 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1787 if ( $result !== null ) {
1788 return $result;
1789 }
1790
1791 # Shortcut for public wikis, allows skipping quite a bit of code
1792 if ( $useShortcut ) {
1793 return true;
1794 }
1795
1796 if ( $wgUser->isAllowed( 'read' ) ) {
1797 return true;
1798 } else {
1799 global $wgWhitelistRead;
1800
1801 # Always grant access to the login page.
1802 # Even anons need to be able to log in.
1803 if ( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1804 return true;
1805 }
1806
1807 # Bail out if there isn't whitelist
1808 if ( !is_array( $wgWhitelistRead ) ) {
1809 return false;
1810 }
1811
1812 # Check for explicit whitelisting
1813 $name = $this->getPrefixedText();
1814 $dbName = $this->getPrefixedDBKey();
1815 // Check with and without underscores
1816 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) )
1817 return true;
1818
1819 # Old settings might have the title prefixed with
1820 # a colon for main-namespace pages
1821 if ( $this->getNamespace() == NS_MAIN ) {
1822 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1823 return true;
1824 }
1825 }
1826
1827 # If it's a special page, ditch the subpage bit and check again
1828 if ( $this->getNamespace() == NS_SPECIAL ) {
1829 $name = $this->getDBkey();
1830 list( $name, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $name );
1831 if ( $name === false ) {
1832 # Invalid special page, but we show standard login required message
1833 return false;
1834 }
1835
1836 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1837 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1838 return true;
1839 }
1840 }
1841
1842 }
1843 return false;
1844 }
1845
1846 /**
1847 * Is this the mainpage?
1848 * @note Title::newFromText seams to be sufficiently optimized by the title
1849 * cache that we don't need to over-optimize by doing direct comparisons and
1850 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1851 * ends up reporting something differently than $title->isMainPage();
1852 *
1853 * @return Bool
1854 */
1855 public function isMainPage() {
1856 return $this->equals( Title::newMainPage() );
1857 }
1858
1859 /**
1860 * Is this a talk page of some sort?
1861 *
1862 * @return Bool
1863 */
1864 public function isTalkPage() {
1865 return MWNamespace::isTalk( $this->getNamespace() );
1866 }
1867
1868 /**
1869 * Is this a subpage?
1870 *
1871 * @return Bool
1872 */
1873 public function isSubpage() {
1874 return MWNamespace::hasSubpages( $this->mNamespace )
1875 ? strpos( $this->getText(), '/' ) !== false
1876 : false;
1877 }
1878
1879 /**
1880 * Does this have subpages? (Warning, usually requires an extra DB query.)
1881 *
1882 * @return Bool
1883 */
1884 public function hasSubpages() {
1885 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1886 # Duh
1887 return false;
1888 }
1889
1890 # We dynamically add a member variable for the purpose of this method
1891 # alone to cache the result. There's no point in having it hanging
1892 # around uninitialized in every Title object; therefore we only add it
1893 # if needed and don't declare it statically.
1894 if ( isset( $this->mHasSubpages ) ) {
1895 return $this->mHasSubpages;
1896 }
1897
1898 $subpages = $this->getSubpages( 1 );
1899 if ( $subpages instanceof TitleArray ) {
1900 return $this->mHasSubpages = (bool)$subpages->count();
1901 }
1902 return $this->mHasSubpages = false;
1903 }
1904
1905 /**
1906 * Get all subpages of this page.
1907 *
1908 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
1909 * @return mixed TitleArray, or empty array if this page's namespace
1910 * doesn't allow subpages
1911 */
1912 public function getSubpages( $limit = -1 ) {
1913 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
1914 return array();
1915 }
1916
1917 $dbr = wfGetDB( DB_SLAVE );
1918 $conds['page_namespace'] = $this->getNamespace();
1919 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1920 $options = array();
1921 if ( $limit > -1 ) {
1922 $options['LIMIT'] = $limit;
1923 }
1924 return $this->mSubpages = TitleArray::newFromResult(
1925 $dbr->select( 'page',
1926 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1927 $conds,
1928 __METHOD__,
1929 $options
1930 )
1931 );
1932 }
1933
1934 /**
1935 * Could this page contain custom CSS or JavaScript, based
1936 * on the title?
1937 *
1938 * @return Bool
1939 */
1940 public function isCssOrJsPage() {
1941 return $this->mNamespace == NS_MEDIAWIKI
1942 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1943 }
1944
1945 /**
1946 * Is this a .css or .js subpage of a user page?
1947 * @return Bool
1948 */
1949 public function isCssJsSubpage() {
1950 return ( NS_USER == $this->mNamespace and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1951 }
1952
1953 /**
1954 * Is this a *valid* .css or .js subpage of a user page?
1955 *
1956 * @return Bool
1957 * @deprecated @since 1.17
1958 */
1959 public function isValidCssJsSubpage() {
1960 return $this->isCssJsSubpage();
1961 }
1962
1963 /**
1964 * Trim down a .css or .js subpage title to get the corresponding skin name
1965 *
1966 * @return string containing skin name from .css or .js subpage title
1967 */
1968 public function getSkinFromCssJsSubpage() {
1969 $subpage = explode( '/', $this->mTextform );
1970 $subpage = $subpage[ count( $subpage ) - 1 ];
1971 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1972 }
1973
1974 /**
1975 * Is this a .css subpage of a user page?
1976 *
1977 * @return Bool
1978 */
1979 public function isCssSubpage() {
1980 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.css$/", $this->mTextform ) );
1981 }
1982
1983 /**
1984 * Is this a .js subpage of a user page?
1985 *
1986 * @return Bool
1987 */
1988 public function isJsSubpage() {
1989 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.js$/", $this->mTextform ) );
1990 }
1991
1992 /**
1993 * Protect css subpages of user pages: can $wgUser edit
1994 * this page?
1995 *
1996 * @return Bool
1997 * @todo XXX: this might be better using restrictions
1998 */
1999 public function userCanEditCssSubpage() {
2000 global $wgUser;
2001 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'editusercss' ) )
2002 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2003 }
2004
2005 /**
2006 * Protect js subpages of user pages: can $wgUser edit
2007 * this page?
2008 *
2009 * @return Bool
2010 * @todo XXX: this might be better using restrictions
2011 */
2012 public function userCanEditJsSubpage() {
2013 global $wgUser;
2014 return ( ( $wgUser->isAllowed( 'editusercssjs' ) && $wgUser->isAllowed( 'edituserjs' ) )
2015 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2016 }
2017
2018 /**
2019 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2020 *
2021 * @return Bool If the page is subject to cascading restrictions.
2022 */
2023 public function isCascadeProtected() {
2024 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2025 return ( $sources > 0 );
2026 }
2027
2028 /**
2029 * Cascading protection: Get the source of any cascading restrictions on this page.
2030 *
2031 * @param $getPages Bool Whether or not to retrieve the actual pages
2032 * that the restrictions have come from.
2033 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2034 * have come, false for none, or true if such restrictions exist, but $getPages
2035 * was not set. The restriction array is an array of each type, each of which
2036 * contains a array of unique groups.
2037 */
2038 public function getCascadeProtectionSources( $getPages = true ) {
2039 $pagerestrictions = array();
2040
2041 if ( isset( $this->mCascadeSources ) && $getPages ) {
2042 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2043 } else if ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2044 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2045 }
2046
2047 wfProfileIn( __METHOD__ );
2048
2049 $dbr = wfGetDB( DB_SLAVE );
2050
2051 if ( $this->getNamespace() == NS_FILE ) {
2052 $tables = array( 'imagelinks', 'page_restrictions' );
2053 $where_clauses = array(
2054 'il_to' => $this->getDBkey(),
2055 'il_from=pr_page',
2056 'pr_cascade' => 1
2057 );
2058 } else {
2059 $tables = array( 'templatelinks', 'page_restrictions' );
2060 $where_clauses = array(
2061 'tl_namespace' => $this->getNamespace(),
2062 'tl_title' => $this->getDBkey(),
2063 'tl_from=pr_page',
2064 'pr_cascade' => 1
2065 );
2066 }
2067
2068 if ( $getPages ) {
2069 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2070 'pr_expiry', 'pr_type', 'pr_level' );
2071 $where_clauses[] = 'page_id=pr_page';
2072 $tables[] = 'page';
2073 } else {
2074 $cols = array( 'pr_expiry' );
2075 }
2076
2077 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2078
2079 $sources = $getPages ? array() : false;
2080 $now = wfTimestampNow();
2081 $purgeExpired = false;
2082
2083 foreach ( $res as $row ) {
2084 $expiry = Block::decodeExpiry( $row->pr_expiry );
2085 if ( $expiry > $now ) {
2086 if ( $getPages ) {
2087 $page_id = $row->pr_page;
2088 $page_ns = $row->page_namespace;
2089 $page_title = $row->page_title;
2090 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2091 # Add groups needed for each restriction type if its not already there
2092 # Make sure this restriction type still exists
2093
2094 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2095 $pagerestrictions[$row->pr_type] = array();
2096 }
2097
2098 if ( isset( $pagerestrictions[$row->pr_type] ) &&
2099 !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) ) {
2100 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2101 }
2102 } else {
2103 $sources = true;
2104 }
2105 } else {
2106 // Trigger lazy purge of expired restrictions from the db
2107 $purgeExpired = true;
2108 }
2109 }
2110 if ( $purgeExpired ) {
2111 Title::purgeExpiredRestrictions();
2112 }
2113
2114 if ( $getPages ) {
2115 $this->mCascadeSources = $sources;
2116 $this->mCascadingRestrictions = $pagerestrictions;
2117 } else {
2118 $this->mHasCascadingRestrictions = $sources;
2119 }
2120
2121 wfProfileOut( __METHOD__ );
2122 return array( $sources, $pagerestrictions );
2123 }
2124
2125 /**
2126 * Returns cascading restrictions for the current article
2127 *
2128 * @return Boolean
2129 */
2130 function areRestrictionsCascading() {
2131 if ( !$this->mRestrictionsLoaded ) {
2132 $this->loadRestrictions();
2133 }
2134
2135 return $this->mCascadeRestriction;
2136 }
2137
2138 /**
2139 * Loads a string into mRestrictions array
2140 *
2141 * @param $res Resource restrictions as an SQL result.
2142 * @param $oldFashionedRestrictions String comma-separated list of page
2143 * restrictions from page table (pre 1.10)
2144 */
2145 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2146 $rows = array();
2147
2148 foreach ( $res as $row ) {
2149 $rows[] = $row;
2150 }
2151
2152 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2153 }
2154
2155 /**
2156 * Compiles list of active page restrictions from both page table (pre 1.10)
2157 * and page_restrictions table for this existing page.
2158 * Public for usage by LiquidThreads.
2159 *
2160 * @param $rows array of db result objects
2161 * @param $oldFashionedRestrictions string comma-separated list of page
2162 * restrictions from page table (pre 1.10)
2163 */
2164 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2165 $dbr = wfGetDB( DB_SLAVE );
2166
2167 $restrictionTypes = $this->getRestrictionTypes();
2168
2169 foreach ( $restrictionTypes as $type ) {
2170 $this->mRestrictions[$type] = array();
2171 $this->mRestrictionsExpiry[$type] = Block::decodeExpiry( '' );
2172 }
2173
2174 $this->mCascadeRestriction = false;
2175
2176 # Backwards-compatibility: also load the restrictions from the page record (old format).
2177
2178 if ( $oldFashionedRestrictions === null ) {
2179 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2180 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
2181 }
2182
2183 if ( $oldFashionedRestrictions != '' ) {
2184
2185 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2186 $temp = explode( '=', trim( $restrict ) );
2187 if ( count( $temp ) == 1 ) {
2188 // old old format should be treated as edit/move restriction
2189 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2190 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2191 } else {
2192 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
2193 }
2194 }
2195
2196 $this->mOldRestrictions = true;
2197
2198 }
2199
2200 if ( count( $rows ) ) {
2201 # Current system - load second to make them override.
2202 $now = wfTimestampNow();
2203 $purgeExpired = false;
2204
2205 # Cycle through all the restrictions.
2206 foreach ( $rows as $row ) {
2207
2208 // Don't take care of restrictions types that aren't allowed
2209 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2210 continue;
2211
2212 // This code should be refactored, now that it's being used more generally,
2213 // But I don't really see any harm in leaving it in Block for now -werdna
2214 $expiry = Block::decodeExpiry( $row->pr_expiry );
2215
2216 // Only apply the restrictions if they haven't expired!
2217 if ( !$expiry || $expiry > $now ) {
2218 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2219 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2220
2221 $this->mCascadeRestriction |= $row->pr_cascade;
2222 } else {
2223 // Trigger a lazy purge of expired restrictions
2224 $purgeExpired = true;
2225 }
2226 }
2227
2228 if ( $purgeExpired ) {
2229 Title::purgeExpiredRestrictions();
2230 }
2231 }
2232
2233 $this->mRestrictionsLoaded = true;
2234 }
2235
2236 /**
2237 * Load restrictions from the page_restrictions table
2238 *
2239 * @param $oldFashionedRestrictions String comma-separated list of page
2240 * restrictions from page table (pre 1.10)
2241 */
2242 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2243 if ( !$this->mRestrictionsLoaded ) {
2244 if ( $this->exists() ) {
2245 $dbr = wfGetDB( DB_SLAVE );
2246
2247 $res = $dbr->select( 'page_restrictions', '*',
2248 array( 'pr_page' => $this->getArticleId() ), __METHOD__ );
2249
2250 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2251 } else {
2252 $title_protection = $this->getTitleProtection();
2253
2254 if ( $title_protection ) {
2255 $now = wfTimestampNow();
2256 $expiry = Block::decodeExpiry( $title_protection['pt_expiry'] );
2257
2258 if ( !$expiry || $expiry > $now ) {
2259 // Apply the restrictions
2260 $this->mRestrictionsExpiry['create'] = $expiry;
2261 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2262 } else { // Get rid of the old restrictions
2263 Title::purgeExpiredRestrictions();
2264 $this->mTitleProtection = false;
2265 }
2266 } else {
2267 $this->mRestrictionsExpiry['create'] = Block::decodeExpiry( '' );
2268 }
2269 $this->mRestrictionsLoaded = true;
2270 }
2271 }
2272 }
2273
2274 /**
2275 * Purge expired restrictions from the page_restrictions table
2276 */
2277 static function purgeExpiredRestrictions() {
2278 $dbw = wfGetDB( DB_MASTER );
2279 $dbw->delete(
2280 'page_restrictions',
2281 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2282 __METHOD__
2283 );
2284
2285 $dbw->delete(
2286 'protected_titles',
2287 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2288 __METHOD__
2289 );
2290 }
2291
2292 /**
2293 * Accessor/initialisation for mRestrictions
2294 *
2295 * @param $action String action that permission needs to be checked for
2296 * @return Array of Strings the array of groups allowed to edit this article
2297 */
2298 public function getRestrictions( $action ) {
2299 if ( !$this->mRestrictionsLoaded ) {
2300 $this->loadRestrictions();
2301 }
2302 return isset( $this->mRestrictions[$action] )
2303 ? $this->mRestrictions[$action]
2304 : array();
2305 }
2306
2307 /**
2308 * Get the expiry time for the restriction against a given action
2309 *
2310 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2311 * or not protected at all, or false if the action is not recognised.
2312 */
2313 public function getRestrictionExpiry( $action ) {
2314 if ( !$this->mRestrictionsLoaded ) {
2315 $this->loadRestrictions();
2316 }
2317 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2318 }
2319
2320 /**
2321 * Is there a version of this page in the deletion archive?
2322 *
2323 * @return Int the number of archived revisions
2324 */
2325 public function isDeleted() {
2326 if ( $this->getNamespace() < 0 ) {
2327 $n = 0;
2328 } else {
2329 $dbr = wfGetDB( DB_SLAVE );
2330 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2331 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2332 __METHOD__
2333 );
2334 if ( $this->getNamespace() == NS_FILE ) {
2335 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2336 array( 'fa_name' => $this->getDBkey() ),
2337 __METHOD__
2338 );
2339 }
2340 }
2341 return (int)$n;
2342 }
2343
2344 /**
2345 * Is there a version of this page in the deletion archive?
2346 *
2347 * @return Boolean
2348 */
2349 public function isDeletedQuick() {
2350 if ( $this->getNamespace() < 0 ) {
2351 return false;
2352 }
2353 $dbr = wfGetDB( DB_SLAVE );
2354 $deleted = (bool)$dbr->selectField( 'archive', '1',
2355 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2356 __METHOD__
2357 );
2358 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
2359 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2360 array( 'fa_name' => $this->getDBkey() ),
2361 __METHOD__
2362 );
2363 }
2364 return $deleted;
2365 }
2366
2367 /**
2368 * Get the article ID for this Title from the link cache,
2369 * adding it if necessary
2370 *
2371 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2372 * for update
2373 * @return Int the ID
2374 */
2375 public function getArticleID( $flags = 0 ) {
2376 if ( $this->getNamespace() < 0 ) {
2377 return $this->mArticleID = 0;
2378 }
2379 $linkCache = LinkCache::singleton();
2380 if ( $flags & self::GAID_FOR_UPDATE ) {
2381 $oldUpdate = $linkCache->forUpdate( true );
2382 $linkCache->clearLink( $this );
2383 $this->mArticleID = $linkCache->addLinkObj( $this );
2384 $linkCache->forUpdate( $oldUpdate );
2385 } else {
2386 if ( -1 == $this->mArticleID ) {
2387 $this->mArticleID = $linkCache->addLinkObj( $this );
2388 }
2389 }
2390 return $this->mArticleID;
2391 }
2392
2393 /**
2394 * Is this an article that is a redirect page?
2395 * Uses link cache, adding it if necessary
2396 *
2397 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2398 * @return Bool
2399 */
2400 public function isRedirect( $flags = 0 ) {
2401 if ( !is_null( $this->mRedirect ) ) {
2402 return $this->mRedirect;
2403 }
2404 # Calling getArticleID() loads the field from cache as needed
2405 if ( !$this->getArticleID( $flags ) ) {
2406 return $this->mRedirect = false;
2407 }
2408 $linkCache = LinkCache::singleton();
2409 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2410
2411 return $this->mRedirect;
2412 }
2413
2414 /**
2415 * What is the length of this page?
2416 * Uses link cache, adding it if necessary
2417 *
2418 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2419 * @return Int
2420 */
2421 public function getLength( $flags = 0 ) {
2422 if ( $this->mLength != -1 ) {
2423 return $this->mLength;
2424 }
2425 # Calling getArticleID() loads the field from cache as needed
2426 if ( !$this->getArticleID( $flags ) ) {
2427 return $this->mLength = 0;
2428 }
2429 $linkCache = LinkCache::singleton();
2430 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2431
2432 return $this->mLength;
2433 }
2434
2435 /**
2436 * What is the page_latest field for this page?
2437 *
2438 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2439 * @return Int or 0 if the page doesn't exist
2440 */
2441 public function getLatestRevID( $flags = 0 ) {
2442 if ( $this->mLatestID !== false ) {
2443 return intval( $this->mLatestID );
2444 }
2445 # Calling getArticleID() loads the field from cache as needed
2446 if ( !$this->getArticleID( $flags ) ) {
2447 return $this->mLatestID = 0;
2448 }
2449 $linkCache = LinkCache::singleton();
2450 $this->mLatestID = intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2451
2452 return $this->mLatestID;
2453 }
2454
2455 /**
2456 * This clears some fields in this object, and clears any associated
2457 * keys in the "bad links" section of the link cache.
2458 *
2459 * - This is called from Article::doEdit() and Article::insertOn() to allow
2460 * loading of the new page_id. It's also called from
2461 * Article::doDeleteArticle()
2462 *
2463 * @param $newid Int the new Article ID
2464 */
2465 public function resetArticleID( $newid ) {
2466 $linkCache = LinkCache::singleton();
2467 $linkCache->clearBadLink( $this->getPrefixedDBkey() );
2468
2469 if ( $newid === false ) {
2470 $this->mArticleID = -1;
2471 } else {
2472 $this->mArticleID = intval( $newid );
2473 }
2474 $this->mRestrictionsLoaded = false;
2475 $this->mRestrictions = array();
2476 $this->mRedirect = null;
2477 $this->mLength = -1;
2478 $this->mLatestID = false;
2479 }
2480
2481 /**
2482 * Updates page_touched for this page; called from LinksUpdate.php
2483 *
2484 * @return Bool true if the update succeded
2485 */
2486 public function invalidateCache() {
2487 if ( wfReadOnly() ) {
2488 return;
2489 }
2490 $dbw = wfGetDB( DB_MASTER );
2491 $success = $dbw->update(
2492 'page',
2493 array( 'page_touched' => $dbw->timestamp() ),
2494 $this->pageCond(),
2495 __METHOD__
2496 );
2497 HTMLFileCache::clearFileCache( $this );
2498 return $success;
2499 }
2500
2501 /**
2502 * Prefix some arbitrary text with the namespace or interwiki prefix
2503 * of this object
2504 *
2505 * @param $name String the text
2506 * @return String the prefixed text
2507 * @private
2508 */
2509 /* private */ function prefix( $name ) {
2510 $p = '';
2511 if ( $this->mInterwiki != '' ) {
2512 $p = $this->mInterwiki . ':';
2513 }
2514
2515 if ( 0 != $this->mNamespace ) {
2516 $p .= $this->getNsText() . ':';
2517 }
2518 return $p . $name;
2519 }
2520
2521 /**
2522 * Returns a simple regex that will match on characters and sequences invalid in titles.
2523 * Note that this doesn't pick up many things that could be wrong with titles, but that
2524 * replacing this regex with something valid will make many titles valid.
2525 *
2526 * @return String regex string
2527 */
2528 static function getTitleInvalidRegex() {
2529 static $rxTc = false;
2530 if ( !$rxTc ) {
2531 # Matching titles will be held as illegal.
2532 $rxTc = '/' .
2533 # Any character not allowed is forbidden...
2534 '[^' . Title::legalChars() . ']' .
2535 # URL percent encoding sequences interfere with the ability
2536 # to round-trip titles -- you can't link to them consistently.
2537 '|%[0-9A-Fa-f]{2}' .
2538 # XML/HTML character references produce similar issues.
2539 '|&[A-Za-z0-9\x80-\xff]+;' .
2540 '|&#[0-9]+;' .
2541 '|&#x[0-9A-Fa-f]+;' .
2542 '/S';
2543 }
2544
2545 return $rxTc;
2546 }
2547
2548 /**
2549 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2550 *
2551 * @param $text String containing title to capitalize
2552 * @param $ns int namespace index, defaults to NS_MAIN
2553 * @return String containing capitalized title
2554 */
2555 public static function capitalize( $text, $ns = NS_MAIN ) {
2556 global $wgContLang;
2557
2558 if ( MWNamespace::isCapitalized( $ns ) ) {
2559 return $wgContLang->ucfirst( $text );
2560 } else {
2561 return $text;
2562 }
2563 }
2564
2565 /**
2566 * Secure and split - main initialisation function for this object
2567 *
2568 * Assumes that mDbkeyform has been set, and is urldecoded
2569 * and uses underscores, but not otherwise munged. This function
2570 * removes illegal characters, splits off the interwiki and
2571 * namespace prefixes, sets the other forms, and canonicalizes
2572 * everything.
2573 *
2574 * @return Bool true on success
2575 */
2576 private function secureAndSplit() {
2577 global $wgContLang, $wgLocalInterwiki;
2578
2579 # Initialisation
2580 $rxTc = self::getTitleInvalidRegex();
2581
2582 $this->mInterwiki = $this->mFragment = '';
2583 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2584
2585 $dbkey = $this->mDbkeyform;
2586
2587 # Strip Unicode bidi override characters.
2588 # Sometimes they slip into cut-n-pasted page titles, where the
2589 # override chars get included in list displays.
2590 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2591
2592 # Clean up whitespace
2593 # Note: use of the /u option on preg_replace here will cause
2594 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2595 # conveniently disabling them.
2596 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2597 $dbkey = trim( $dbkey, '_' );
2598
2599 if ( $dbkey == '' ) {
2600 return false;
2601 }
2602
2603 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2604 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2605 return false;
2606 }
2607
2608 $this->mDbkeyform = $dbkey;
2609
2610 # Initial colon indicates main namespace rather than specified default
2611 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2612 if ( ':' == $dbkey { 0 } ) {
2613 $this->mNamespace = NS_MAIN;
2614 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2615 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2616 }
2617
2618 # Namespace or interwiki prefix
2619 $firstPass = true;
2620 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2621 do {
2622 $m = array();
2623 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2624 $p = $m[1];
2625 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2626 # Ordinary namespace
2627 $dbkey = $m[2];
2628 $this->mNamespace = $ns;
2629 # For Talk:X pages, check if X has a "namespace" prefix
2630 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2631 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2632 # Disallow Talk:File:x type titles...
2633 return false;
2634 } else if ( Interwiki::isValidInterwiki( $x[1] ) ) {
2635 # Disallow Talk:Interwiki:x type titles...
2636 return false;
2637 }
2638 }
2639 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
2640 if ( !$firstPass ) {
2641 # Can't make a local interwiki link to an interwiki link.
2642 # That's just crazy!
2643 return false;
2644 }
2645
2646 # Interwiki link
2647 $dbkey = $m[2];
2648 $this->mInterwiki = $wgContLang->lc( $p );
2649
2650 # Redundant interwiki prefix to the local wiki
2651 if ( $wgLocalInterwiki !== false
2652 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
2653 {
2654 if ( $dbkey == '' ) {
2655 # Can't have an empty self-link
2656 return false;
2657 }
2658 $this->mInterwiki = '';
2659 $firstPass = false;
2660 # Do another namespace split...
2661 continue;
2662 }
2663
2664 # If there's an initial colon after the interwiki, that also
2665 # resets the default namespace
2666 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2667 $this->mNamespace = NS_MAIN;
2668 $dbkey = substr( $dbkey, 1 );
2669 }
2670 }
2671 # If there's no recognized interwiki or namespace,
2672 # then let the colon expression be part of the title.
2673 }
2674 break;
2675 } while ( true );
2676
2677 # We already know that some pages won't be in the database!
2678 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
2679 $this->mArticleID = 0;
2680 }
2681 $fragment = strstr( $dbkey, '#' );
2682 if ( false !== $fragment ) {
2683 $this->setFragment( preg_replace( '/^#_*/', '#', $fragment ) );
2684 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2685 # remove whitespace again: prevents "Foo_bar_#"
2686 # becoming "Foo_bar_"
2687 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2688 }
2689
2690 # Reject illegal characters.
2691 if ( preg_match( $rxTc, $dbkey ) ) {
2692 return false;
2693 }
2694
2695 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2696 # reachable due to the way web browsers deal with 'relative' URLs.
2697 # Also, they conflict with subpage syntax. Forbid them explicitly.
2698 if ( strpos( $dbkey, '.' ) !== false &&
2699 ( $dbkey === '.' || $dbkey === '..' ||
2700 strpos( $dbkey, './' ) === 0 ||
2701 strpos( $dbkey, '../' ) === 0 ||
2702 strpos( $dbkey, '/./' ) !== false ||
2703 strpos( $dbkey, '/../' ) !== false ||
2704 substr( $dbkey, -2 ) == '/.' ||
2705 substr( $dbkey, -3 ) == '/..' ) )
2706 {
2707 return false;
2708 }
2709
2710 # Magic tilde sequences? Nu-uh!
2711 if ( strpos( $dbkey, '~~~' ) !== false ) {
2712 return false;
2713 }
2714
2715 # Limit the size of titles to 255 bytes. This is typically the size of the
2716 # underlying database field. We make an exception for special pages, which
2717 # don't need to be stored in the database, and may edge over 255 bytes due
2718 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2719 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2720 strlen( $dbkey ) > 512 )
2721 {
2722 return false;
2723 }
2724
2725 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2726 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2727 # other site might be case-sensitive.
2728 $this->mUserCaseDBKey = $dbkey;
2729 if ( $this->mInterwiki == '' ) {
2730 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
2731 }
2732
2733 # Can't make a link to a namespace alone... "empty" local links can only be
2734 # self-links with a fragment identifier.
2735 if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) {
2736 return false;
2737 }
2738
2739 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2740 // IP names are not allowed for accounts, and can only be referring to
2741 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2742 // there are numerous ways to present the same IP. Having sp:contribs scan
2743 // them all is silly and having some show the edits and others not is
2744 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2745 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK )
2746 ? IP::sanitizeIP( $dbkey )
2747 : $dbkey;
2748
2749 // Any remaining initial :s are illegal.
2750 if ( $dbkey !== '' && ':' == $dbkey { 0 } ) {
2751 return false;
2752 }
2753
2754 # Fill fields
2755 $this->mDbkeyform = $dbkey;
2756 $this->mUrlform = wfUrlencode( $dbkey );
2757
2758 $this->mTextform = str_replace( '_', ' ', $dbkey );
2759
2760 return true;
2761 }
2762
2763 /**
2764 * Set the fragment for this title. Removes the first character from the
2765 * specified fragment before setting, so it assumes you're passing it with
2766 * an initial "#".
2767 *
2768 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2769 * Still in active use privately.
2770 *
2771 * @param $fragment String text
2772 */
2773 public function setFragment( $fragment ) {
2774 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2775 }
2776
2777 /**
2778 * Get a Title object associated with the talk page of this article
2779 *
2780 * @return Title the object for the talk page
2781 */
2782 public function getTalkPage() {
2783 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2784 }
2785
2786 /**
2787 * Get a title object associated with the subject page of this
2788 * talk page
2789 *
2790 * @return Title the object for the subject page
2791 */
2792 public function getSubjectPage() {
2793 // Is this the same title?
2794 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2795 if ( $this->getNamespace() == $subjectNS ) {
2796 return $this;
2797 }
2798 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2799 }
2800
2801 /**
2802 * Get an array of Title objects linking to this Title
2803 * Also stores the IDs in the link cache.
2804 *
2805 * WARNING: do not use this function on arbitrary user-supplied titles!
2806 * On heavily-used templates it will max out the memory.
2807 *
2808 * @param $options Array: may be FOR UPDATE
2809 * @param $table String: table name
2810 * @param $prefix String: fields prefix
2811 * @return Array of Title objects linking here
2812 */
2813 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2814 $linkCache = LinkCache::singleton();
2815
2816 if ( count( $options ) > 0 ) {
2817 $db = wfGetDB( DB_MASTER );
2818 } else {
2819 $db = wfGetDB( DB_SLAVE );
2820 }
2821
2822 $res = $db->select(
2823 array( 'page', $table ),
2824 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2825 array(
2826 "{$prefix}_from=page_id",
2827 "{$prefix}_namespace" => $this->getNamespace(),
2828 "{$prefix}_title" => $this->getDBkey() ),
2829 __METHOD__,
2830 $options
2831 );
2832
2833 $retVal = array();
2834 if ( $db->numRows( $res ) ) {
2835 foreach ( $res as $row ) {
2836 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
2837 if ( $titleObj ) {
2838 $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect, $row->page_latest );
2839 $retVal[] = $titleObj;
2840 }
2841 }
2842 }
2843 return $retVal;
2844 }
2845
2846 /**
2847 * Get an array of Title objects using this Title as a template
2848 * Also stores the IDs in the link cache.
2849 *
2850 * WARNING: do not use this function on arbitrary user-supplied titles!
2851 * On heavily-used templates it will max out the memory.
2852 *
2853 * @param $options Array: may be FOR UPDATE
2854 * @return Array of Title the Title objects linking here
2855 */
2856 public function getTemplateLinksTo( $options = array() ) {
2857 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
2858 }
2859
2860 /**
2861 * Get an array of Title objects referring to non-existent articles linked from this page
2862 *
2863 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
2864 * @return Array of Title the Title objects
2865 */
2866 public function getBrokenLinksFrom() {
2867 if ( $this->getArticleId() == 0 ) {
2868 # All links from article ID 0 are false positives
2869 return array();
2870 }
2871
2872 $dbr = wfGetDB( DB_SLAVE );
2873 $res = $dbr->select(
2874 array( 'page', 'pagelinks' ),
2875 array( 'pl_namespace', 'pl_title' ),
2876 array(
2877 'pl_from' => $this->getArticleId(),
2878 'page_namespace IS NULL'
2879 ),
2880 __METHOD__, array(),
2881 array(
2882 'page' => array(
2883 'LEFT JOIN',
2884 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
2885 )
2886 )
2887 );
2888
2889 $retVal = array();
2890 foreach ( $res as $row ) {
2891 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
2892 }
2893 return $retVal;
2894 }
2895
2896
2897 /**
2898 * Get a list of URLs to purge from the Squid cache when this
2899 * page changes
2900 *
2901 * @return Array of String the URLs
2902 */
2903 public function getSquidURLs() {
2904 global $wgContLang;
2905
2906 $urls = array(
2907 $this->getInternalURL(),
2908 $this->getInternalURL( 'action=history' )
2909 );
2910
2911 // purge variant urls as well
2912 if ( $wgContLang->hasVariants() ) {
2913 $variants = $wgContLang->getVariants();
2914 foreach ( $variants as $vCode ) {
2915 $urls[] = $this->getInternalURL( '', $vCode );
2916 }
2917 }
2918
2919 return $urls;
2920 }
2921
2922 /**
2923 * Purge all applicable Squid URLs
2924 */
2925 public function purgeSquid() {
2926 global $wgUseSquid;
2927 if ( $wgUseSquid ) {
2928 $urls = $this->getSquidURLs();
2929 $u = new SquidUpdate( $urls );
2930 $u->doUpdate();
2931 }
2932 }
2933
2934 /**
2935 * Move this page without authentication
2936 *
2937 * @param $nt Title the new page Title
2938 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
2939 */
2940 public function moveNoAuth( &$nt ) {
2941 return $this->moveTo( $nt, false );
2942 }
2943
2944 /**
2945 * Check whether a given move operation would be valid.
2946 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
2947 *
2948 * @param $nt Title the new title
2949 * @param $auth Bool indicates whether $wgUser's permissions
2950 * should be checked
2951 * @param $reason String is the log summary of the move, used for spam checking
2952 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
2953 */
2954 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
2955 global $wgUser;
2956
2957 $errors = array();
2958 if ( !$nt ) {
2959 // Normally we'd add this to $errors, but we'll get
2960 // lots of syntax errors if $nt is not an object
2961 return array( array( 'badtitletext' ) );
2962 }
2963 if ( $this->equals( $nt ) ) {
2964 $errors[] = array( 'selfmove' );
2965 }
2966 if ( !$this->isMovable() ) {
2967 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2968 }
2969 if ( $nt->getInterwiki() != '' ) {
2970 $errors[] = array( 'immobile-target-namespace-iw' );
2971 }
2972 if ( !$nt->isMovable() ) {
2973 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
2974 }
2975
2976 $oldid = $this->getArticleID();
2977 $newid = $nt->getArticleID();
2978
2979 if ( strlen( $nt->getDBkey() ) < 1 ) {
2980 $errors[] = array( 'articleexists' );
2981 }
2982 if ( ( $this->getDBkey() == '' ) ||
2983 ( !$oldid ) ||
2984 ( $nt->getDBkey() == '' ) ) {
2985 $errors[] = array( 'badarticleerror' );
2986 }
2987
2988 // Image-specific checks
2989 if ( $this->getNamespace() == NS_FILE ) {
2990 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
2991 }
2992
2993 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
2994 $errors[] = array( 'nonfile-cannot-move-to-file' );
2995 }
2996
2997 if ( $auth ) {
2998 $errors = wfMergeErrorArrays( $errors,
2999 $this->getUserPermissionsErrors( 'move', $wgUser ),
3000 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3001 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3002 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3003 }
3004
3005 $match = EditPage::matchSummarySpamRegex( $reason );
3006 if ( $match !== false ) {
3007 // This is kind of lame, won't display nice
3008 $errors[] = array( 'spamprotectiontext' );
3009 }
3010
3011 $err = null;
3012 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3013 $errors[] = array( 'hookaborted', $err );
3014 }
3015
3016 # The move is allowed only if (1) the target doesn't exist, or
3017 # (2) the target is a redirect to the source, and has no history
3018 # (so we can undo bad moves right after they're done).
3019
3020 if ( 0 != $newid ) { # Target exists; check for validity
3021 if ( !$this->isValidMoveTarget( $nt ) ) {
3022 $errors[] = array( 'articleexists' );
3023 }
3024 } else {
3025 $tp = $nt->getTitleProtection();
3026 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3027 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3028 $errors[] = array( 'cantmove-titleprotected' );
3029 }
3030 }
3031 if ( empty( $errors ) ) {
3032 return true;
3033 }
3034 return $errors;
3035 }
3036
3037 /**
3038 * Check if the requested move target is a valid file move target
3039 * @param Title $nt Target title
3040 * @return array List of errors
3041 */
3042 protected function validateFileMoveOperation( $nt ) {
3043 global $wgUser;
3044
3045 $errors = array();
3046
3047 if ( $nt->getNamespace() != NS_FILE ) {
3048 $errors[] = array( 'imagenocrossnamespace' );
3049 }
3050
3051 $file = wfLocalFile( $this );
3052 if ( $file->exists() ) {
3053 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3054 $errors[] = array( 'imageinvalidfilename' );
3055 }
3056 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3057 $errors[] = array( 'imagetypemismatch' );
3058 }
3059 }
3060
3061 $destFile = wfLocalFile( $nt );
3062 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destfile->exists() && wfFindFile( $nt ) ) {
3063 $errors[] = array( 'file-exists-sharedrepo' );
3064 }
3065
3066 return $errors;
3067 }
3068
3069 /**
3070 * Move a title to a new location
3071 *
3072 * @param $nt Title the new title
3073 * @param $auth Bool indicates whether $wgUser's permissions
3074 * should be checked
3075 * @param $reason String the reason for the move
3076 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3077 * Ignored if the user doesn't have the suppressredirect right.
3078 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3079 */
3080 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3081 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3082 if ( is_array( $err ) ) {
3083 return $err;
3084 }
3085
3086 // If it is a file, move it first. It is done before all other moving stuff is
3087 // done because it's hard to revert
3088 $dbw = wfGetDB( DB_MASTER );
3089 if ( $this->getNamespace() == NS_FILE ) {
3090 $file = wfLocalFile( $this );
3091 if ( $file->exists() ) {
3092 $status = $file->move( $nt );
3093 if ( !$status->isOk() ) {
3094 return $status->getErrorsArray();
3095 }
3096 }
3097 }
3098
3099 $pageid = $this->getArticleID();
3100 $protected = $this->isProtected();
3101 $pageCountChange = ( $createRedirect ? 1 : 0 ) - ( $nt->exists() ? 1 : 0 );
3102
3103 // Do the actual move
3104 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3105 if ( is_array( $err ) ) {
3106 return $err;
3107 }
3108
3109 $redirid = $this->getArticleID();
3110
3111 // Refresh the sortkey for this row. Be careful to avoid resetting
3112 // cl_timestamp, which may disturb time-based lists on some sites.
3113 $prefix = $dbw->selectField(
3114 'categorylinks',
3115 'cl_sortkey_prefix',
3116 array( 'cl_from' => $pageid ),
3117 __METHOD__
3118 );
3119 $dbw->update( 'categorylinks',
3120 array(
3121 'cl_sortkey' => Collation::singleton()->getSortKey(
3122 $nt->getCategorySortkey( $prefix ) ),
3123 'cl_timestamp=cl_timestamp' ),
3124 array( 'cl_from' => $pageid ),
3125 __METHOD__ );
3126
3127 if ( $protected ) {
3128 # Protect the redirect title as the title used to be...
3129 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3130 array(
3131 'pr_page' => $redirid,
3132 'pr_type' => 'pr_type',
3133 'pr_level' => 'pr_level',
3134 'pr_cascade' => 'pr_cascade',
3135 'pr_user' => 'pr_user',
3136 'pr_expiry' => 'pr_expiry'
3137 ),
3138 array( 'pr_page' => $pageid ),
3139 __METHOD__,
3140 array( 'IGNORE' )
3141 );
3142 # Update the protection log
3143 $log = new LogPage( 'protect' );
3144 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3145 if ( $reason ) {
3146 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3147 }
3148 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) ); // FIXME: $params?
3149 }
3150
3151 # Update watchlists
3152 $oldnamespace = $this->getNamespace() & ~1;
3153 $newnamespace = $nt->getNamespace() & ~1;
3154 $oldtitle = $this->getDBkey();
3155 $newtitle = $nt->getDBkey();
3156
3157 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3158 WatchedItem::duplicateEntries( $this, $nt );
3159 }
3160
3161 # Update search engine
3162 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3163 $u->doUpdate();
3164 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3165 $u->doUpdate();
3166
3167 # Update site_stats
3168 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3169 # No longer a content page
3170 # Not viewed, edited, removing
3171 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3172 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3173 # Now a content page
3174 # Not viewed, edited, adding
3175 $u = new SiteStatsUpdate( 0, 1, + 1, $pageCountChange );
3176 } elseif ( $pageCountChange ) {
3177 # Redirect added
3178 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3179 } else {
3180 # Nothing special
3181 $u = false;
3182 }
3183 if ( $u ) {
3184 $u->doUpdate();
3185 }
3186 # Update message cache for interface messages
3187 if ( $this->getNamespace() == NS_MEDIAWIKI ) {
3188 # @bug 17860: old article can be deleted, if this the case,
3189 # delete it from message cache
3190 if ( $this->getArticleID() === 0 ) {
3191 MessageCache::singleton()->replace( $this->getDBkey(), false );
3192 } else {
3193 $oldarticle = new Article( $this );
3194 MessageCache::singleton()->replace( $this->getDBkey(), $oldarticle->getContent() );
3195 }
3196 }
3197 if ( $nt->getNamespace() == NS_MEDIAWIKI ) {
3198 $newarticle = new Article( $nt );
3199 MessageCache::singleton()->replace( $nt->getDBkey(), $newarticle->getContent() );
3200 }
3201
3202 global $wgUser;
3203 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3204 return true;
3205 }
3206
3207 /**
3208 * Move page to a title which is either a redirect to the
3209 * source page or nonexistent
3210 *
3211 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3212 * @param $reason String The reason for the move
3213 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3214 * if the user doesn't have the suppressredirect right
3215 */
3216 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3217 global $wgUser, $wgContLang;
3218
3219 $moveOverRedirect = $nt->exists();
3220
3221 $commentMsg = ( $moveOverRedirect ? '1movedto2_redir' : '1movedto2' );
3222 $comment = wfMsgForContent( $commentMsg, $this->getPrefixedText(), $nt->getPrefixedText() );
3223
3224 if ( $reason ) {
3225 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3226 }
3227 # Truncate for whole multibyte characters. +5 bytes for ellipsis
3228 $comment = $wgContLang->truncate( $comment, 250 );
3229
3230 $oldid = $this->getArticleID();
3231 $latest = $this->getLatestRevID();
3232
3233 $dbw = wfGetDB( DB_MASTER );
3234
3235 if ( $moveOverRedirect ) {
3236 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3237
3238 $newid = $nt->getArticleID();
3239 $newns = $nt->getNamespace();
3240 $newdbk = $nt->getDBkey();
3241
3242 # Delete the old redirect. We don't save it to history since
3243 # by definition if we've got here it's rather uninteresting.
3244 # We have to remove it so that the next step doesn't trigger
3245 # a conflict on the unique namespace+title index...
3246 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3247 if ( !$dbw->cascadingDeletes() ) {
3248 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
3249 global $wgUseTrackbacks;
3250 if ( $wgUseTrackbacks ) {
3251 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
3252 }
3253 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3254 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
3255 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
3256 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
3257 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
3258 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
3259 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
3260 }
3261 // If the target page was recently created, it may have an entry in recentchanges still
3262 $dbw->delete( 'recentchanges',
3263 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3264 __METHOD__
3265 );
3266 }
3267
3268 # Save a null revision in the page's history notifying of the move
3269 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3270 if ( !is_object( $nullRevision ) ) {
3271 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3272 }
3273 $nullRevId = $nullRevision->insertOn( $dbw );
3274
3275 $article = new Article( $this );
3276 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3277
3278 # Change the name of the target page:
3279 $dbw->update( 'page',
3280 /* SET */ array(
3281 'page_touched' => $dbw->timestamp(),
3282 'page_namespace' => $nt->getNamespace(),
3283 'page_title' => $nt->getDBkey(),
3284 'page_latest' => $nullRevId,
3285 ),
3286 /* WHERE */ array( 'page_id' => $oldid ),
3287 __METHOD__
3288 );
3289 $nt->resetArticleID( $oldid );
3290
3291 # Recreate the redirect, this time in the other direction.
3292 if ( $createRedirect || !$wgUser->isAllowed( 'suppressredirect' ) ) {
3293 $mwRedir = MagicWord::get( 'redirect' );
3294 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3295 $redirectArticle = new Article( $this );
3296 $newid = $redirectArticle->insertOn( $dbw );
3297 $redirectRevision = new Revision( array(
3298 'page' => $newid,
3299 'comment' => $comment,
3300 'text' => $redirectText ) );
3301 $redirectRevision->insertOn( $dbw );
3302 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3303
3304 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3305
3306 # Now, we record the link from the redirect to the new title.
3307 # It should have no other outgoing links...
3308 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3309 $dbw->insert( 'pagelinks',
3310 array(
3311 'pl_from' => $newid,
3312 'pl_namespace' => $nt->getNamespace(),
3313 'pl_title' => $nt->getDBkey() ),
3314 __METHOD__ );
3315 $redirectSuppressed = false;
3316 } else {
3317 $this->resetArticleID( 0 );
3318 $redirectSuppressed = true;
3319 }
3320
3321 # Log the move
3322 $log = new LogPage( 'move' );
3323 $logType = ( $moveOverRedirect ? 'move_redir' : 'move' );
3324 $log->addEntry( $logType, $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3325
3326 # Purge caches for old and new titles
3327 if ( $moveOverRedirect ) {
3328 # A simple purge is enough when moving over a redirect
3329 $nt->purgeSquid();
3330 } else {
3331 # Purge caches as per article creation, including any pages that link to this title
3332 Article::onArticleCreate( $nt );
3333 }
3334 $this->purgeSquid();
3335 }
3336
3337 /**
3338 * Move this page's subpages to be subpages of $nt
3339 *
3340 * @param $nt Title Move target
3341 * @param $auth bool Whether $wgUser's permissions should be checked
3342 * @param $reason string The reason for the move
3343 * @param $createRedirect bool Whether to create redirects from the old subpages to
3344 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3345 * @return mixed array with old page titles as keys, and strings (new page titles) or
3346 * arrays (errors) as values, or an error array with numeric indices if no pages
3347 * were moved
3348 */
3349 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3350 global $wgMaximumMovedPages;
3351 // Check permissions
3352 if ( !$this->userCan( 'move-subpages' ) ) {
3353 return array( 'cant-move-subpages' );
3354 }
3355 // Do the source and target namespaces support subpages?
3356 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3357 return array( 'namespace-nosubpages',
3358 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3359 }
3360 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3361 return array( 'namespace-nosubpages',
3362 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3363 }
3364
3365 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3366 $retval = array();
3367 $count = 0;
3368 foreach ( $subpages as $oldSubpage ) {
3369 $count++;
3370 if ( $count > $wgMaximumMovedPages ) {
3371 $retval[$oldSubpage->getPrefixedTitle()] =
3372 array( 'movepage-max-pages',
3373 $wgMaximumMovedPages );
3374 break;
3375 }
3376
3377 // We don't know whether this function was called before
3378 // or after moving the root page, so check both
3379 // $this and $nt
3380 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3381 $oldSubpage->getArticleID() == $nt->getArticleId() )
3382 {
3383 // When moving a page to a subpage of itself,
3384 // don't move it twice
3385 continue;
3386 }
3387 $newPageName = preg_replace(
3388 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3389 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3390 $oldSubpage->getDBkey() );
3391 if ( $oldSubpage->isTalkPage() ) {
3392 $newNs = $nt->getTalkPage()->getNamespace();
3393 } else {
3394 $newNs = $nt->getSubjectPage()->getNamespace();
3395 }
3396 # Bug 14385: we need makeTitleSafe because the new page names may
3397 # be longer than 255 characters.
3398 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3399
3400 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3401 if ( $success === true ) {
3402 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3403 } else {
3404 $retval[$oldSubpage->getPrefixedText()] = $success;
3405 }
3406 }
3407 return $retval;
3408 }
3409
3410 /**
3411 * Checks if this page is just a one-rev redirect.
3412 * Adds lock, so don't use just for light purposes.
3413 *
3414 * @return Bool
3415 */
3416 public function isSingleRevRedirect() {
3417 $dbw = wfGetDB( DB_MASTER );
3418 # Is it a redirect?
3419 $row = $dbw->selectRow( 'page',
3420 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3421 $this->pageCond(),
3422 __METHOD__,
3423 array( 'FOR UPDATE' )
3424 );
3425 # Cache some fields we may want
3426 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3427 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3428 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3429 if ( !$this->mRedirect ) {
3430 return false;
3431 }
3432 # Does the article have a history?
3433 $row = $dbw->selectField( array( 'page', 'revision' ),
3434 'rev_id',
3435 array( 'page_namespace' => $this->getNamespace(),
3436 'page_title' => $this->getDBkey(),
3437 'page_id=rev_page',
3438 'page_latest != rev_id'
3439 ),
3440 __METHOD__,
3441 array( 'FOR UPDATE' )
3442 );
3443 # Return true if there was no history
3444 return ( $row === false );
3445 }
3446
3447 /**
3448 * Checks if $this can be moved to a given Title
3449 * - Selects for update, so don't call it unless you mean business
3450 *
3451 * @param $nt Title the new title to check
3452 * @return Bool
3453 */
3454 public function isValidMoveTarget( $nt ) {
3455 # Is it an existing file?
3456 if ( $nt->getNamespace() == NS_FILE ) {
3457 $file = wfLocalFile( $nt );
3458 if ( $file->exists() ) {
3459 wfDebug( __METHOD__ . ": file exists\n" );
3460 return false;
3461 }
3462 }
3463 # Is it a redirect with no history?
3464 if ( !$nt->isSingleRevRedirect() ) {
3465 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3466 return false;
3467 }
3468 # Get the article text
3469 $rev = Revision::newFromTitle( $nt );
3470 $text = $rev->getText();
3471 # Does the redirect point to the source?
3472 # Or is it a broken self-redirect, usually caused by namespace collisions?
3473 $m = array();
3474 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3475 $redirTitle = Title::newFromText( $m[1] );
3476 if ( !is_object( $redirTitle ) ||
3477 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3478 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3479 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3480 return false;
3481 }
3482 } else {
3483 # Fail safe
3484 wfDebug( __METHOD__ . ": failsafe\n" );
3485 return false;
3486 }
3487 return true;
3488 }
3489
3490 /**
3491 * Can this title be added to a user's watchlist?
3492 *
3493 * @return Bool TRUE or FALSE
3494 */
3495 public function isWatchable() {
3496 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3497 }
3498
3499 /**
3500 * Get categories to which this Title belongs and return an array of
3501 * categories' names.
3502 *
3503 * @return Array of parents in the form:
3504 * $parent => $currentarticle
3505 */
3506 public function getParentCategories() {
3507 global $wgContLang;
3508
3509 $data = array();
3510
3511 $titleKey = $this->getArticleId();
3512
3513 if ( $titleKey === 0 ) {
3514 return $data;
3515 }
3516
3517 $dbr = wfGetDB( DB_SLAVE );
3518
3519 $res = $dbr->select( 'categorylinks', '*',
3520 array(
3521 'cl_from' => $titleKey,
3522 ),
3523 __METHOD__,
3524 array()
3525 );
3526
3527 if ( $dbr->numRows( $res ) > 0 ) {
3528 foreach ( $res as $row ) {
3529 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3530 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3531 }
3532 }
3533 return $data;
3534 }
3535
3536 /**
3537 * Get a tree of parent categories
3538 *
3539 * @param $children Array with the children in the keys, to check for circular refs
3540 * @return Array Tree of parent categories
3541 */
3542 public function getParentCategoryTree( $children = array() ) {
3543 $stack = array();
3544 $parents = $this->getParentCategories();
3545
3546 if ( $parents ) {
3547 foreach ( $parents as $parent => $current ) {
3548 if ( array_key_exists( $parent, $children ) ) {
3549 # Circular reference
3550 $stack[$parent] = array();
3551 } else {
3552 $nt = Title::newFromText( $parent );
3553 if ( $nt ) {
3554 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3555 }
3556 }
3557 }
3558 }
3559
3560 return $stack;
3561 }
3562
3563 /**
3564 * Get an associative array for selecting this title from
3565 * the "page" table
3566 *
3567 * @return Array suitable for the $where parameter of DB::select()
3568 */
3569 public function pageCond() {
3570 if ( $this->mArticleID > 0 ) {
3571 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3572 return array( 'page_id' => $this->mArticleID );
3573 } else {
3574 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3575 }
3576 }
3577
3578 /**
3579 * Get the revision ID of the previous revision
3580 *
3581 * @param $revId Int Revision ID. Get the revision that was before this one.
3582 * @param $flags Int Title::GAID_FOR_UPDATE
3583 * @return Int|Bool Old revision ID, or FALSE if none exists
3584 */
3585 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3586 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3587 return $db->selectField( 'revision', 'rev_id',
3588 array(
3589 'rev_page' => $this->getArticleId( $flags ),
3590 'rev_id < ' . intval( $revId )
3591 ),
3592 __METHOD__,
3593 array( 'ORDER BY' => 'rev_id DESC' )
3594 );
3595 }
3596
3597 /**
3598 * Get the revision ID of the next revision
3599 *
3600 * @param $revId Int Revision ID. Get the revision that was after this one.
3601 * @param $flags Int Title::GAID_FOR_UPDATE
3602 * @return Int|Bool Next revision ID, or FALSE if none exists
3603 */
3604 public function getNextRevisionID( $revId, $flags = 0 ) {
3605 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3606 return $db->selectField( 'revision', 'rev_id',
3607 array(
3608 'rev_page' => $this->getArticleId( $flags ),
3609 'rev_id > ' . intval( $revId )
3610 ),
3611 __METHOD__,
3612 array( 'ORDER BY' => 'rev_id' )
3613 );
3614 }
3615
3616 /**
3617 * Get the first revision of the page
3618 *
3619 * @param $flags Int Title::GAID_FOR_UPDATE
3620 * @return Revision|Null if page doesn't exist
3621 */
3622 public function getFirstRevision( $flags = 0 ) {
3623 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3624 $pageId = $this->getArticleId( $flags );
3625 if ( !$pageId ) {
3626 return null;
3627 }
3628 $row = $db->selectRow( 'revision', '*',
3629 array( 'rev_page' => $pageId ),
3630 __METHOD__,
3631 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3632 );
3633 if ( !$row ) {
3634 return null;
3635 } else {
3636 return new Revision( $row );
3637 }
3638 }
3639
3640 /**
3641 * Check if this is a new page
3642 *
3643 * @return bool
3644 */
3645 public function isNewPage() {
3646 $dbr = wfGetDB( DB_SLAVE );
3647 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3648 }
3649
3650 /**
3651 * Get the oldest revision timestamp of this page
3652 *
3653 * @return String: MW timestamp
3654 */
3655 public function getEarliestRevTime() {
3656 $dbr = wfGetDB( DB_SLAVE );
3657 if ( $this->exists() ) {
3658 $min = $dbr->selectField( 'revision',
3659 'MIN(rev_timestamp)',
3660 array( 'rev_page' => $this->getArticleId() ),
3661 __METHOD__ );
3662 return wfTimestampOrNull( TS_MW, $min );
3663 }
3664 return null;
3665 }
3666
3667 /**
3668 * Get the number of revisions between the given revision IDs.
3669 * Used for diffs and other things that really need it.
3670 *
3671 * @param $old Int Revision ID.
3672 * @param $new Int Revision ID.
3673 * @return Int Number of revisions between these IDs.
3674 */
3675 public function countRevisionsBetween( $old, $new ) {
3676 $dbr = wfGetDB( DB_SLAVE );
3677 return (int)$dbr->selectField( 'revision', 'count(*)', array(
3678 'rev_page' => intval( $this->getArticleId() ),
3679 'rev_id > ' . intval( $old ),
3680 'rev_id < ' . intval( $new )
3681 ), __METHOD__
3682 );
3683 }
3684
3685 /**
3686 * Get the number of authors between the given revision IDs.
3687 * Used for diffs and other things that really need it.
3688 *
3689 * @param $fromRevId Int Revision ID (first before range)
3690 * @param $toRevId Int Revision ID (first after range)
3691 * @param $limit Int Maximum number of authors
3692 * @param $flags Int Title::GAID_FOR_UPDATE
3693 * @return Int
3694 */
3695 public function countAuthorsBetween( $fromRevId, $toRevId, $limit, $flags = 0 ) {
3696 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3697 $res = $db->select( 'revision', 'DISTINCT rev_user_text',
3698 array(
3699 'rev_page' => $this->getArticleID(),
3700 'rev_id > ' . (int)$fromRevId,
3701 'rev_id < ' . (int)$toRevId
3702 ), __METHOD__,
3703 array( 'LIMIT' => $limit )
3704 );
3705 return (int)$db->numRows( $res );
3706 }
3707
3708 /**
3709 * Compare with another title.
3710 *
3711 * @param $title Title
3712 * @return Bool
3713 */
3714 public function equals( Title $title ) {
3715 // Note: === is necessary for proper matching of number-like titles.
3716 return $this->getInterwiki() === $title->getInterwiki()
3717 && $this->getNamespace() == $title->getNamespace()
3718 && $this->getDBkey() === $title->getDBkey();
3719 }
3720
3721 /**
3722 * Callback for usort() to do title sorts by (namespace, title)
3723 *
3724 * @param $a Title
3725 * @param $b Title
3726 *
3727 * @return Integer: result of string comparison, or namespace comparison
3728 */
3729 public static function compare( $a, $b ) {
3730 if ( $a->getNamespace() == $b->getNamespace() ) {
3731 return strcmp( $a->getText(), $b->getText() );
3732 } else {
3733 return $a->getNamespace() - $b->getNamespace();
3734 }
3735 }
3736
3737 /**
3738 * Return a string representation of this title
3739 *
3740 * @return String representation of this title
3741 */
3742 public function __toString() {
3743 return $this->getPrefixedText();
3744 }
3745
3746 /**
3747 * Check if page exists. For historical reasons, this function simply
3748 * checks for the existence of the title in the page table, and will
3749 * thus return false for interwiki links, special pages and the like.
3750 * If you want to know if a title can be meaningfully viewed, you should
3751 * probably call the isKnown() method instead.
3752 *
3753 * @return Bool
3754 */
3755 public function exists() {
3756 return $this->getArticleId() != 0;
3757 }
3758
3759 /**
3760 * Should links to this title be shown as potentially viewable (i.e. as
3761 * "bluelinks"), even if there's no record by this title in the page
3762 * table?
3763 *
3764 * This function is semi-deprecated for public use, as well as somewhat
3765 * misleadingly named. You probably just want to call isKnown(), which
3766 * calls this function internally.
3767 *
3768 * (ISSUE: Most of these checks are cheap, but the file existence check
3769 * can potentially be quite expensive. Including it here fixes a lot of
3770 * existing code, but we might want to add an optional parameter to skip
3771 * it and any other expensive checks.)
3772 *
3773 * @return Bool
3774 */
3775 public function isAlwaysKnown() {
3776 if ( $this->mInterwiki != '' ) {
3777 return true; // any interwiki link might be viewable, for all we know
3778 }
3779 switch( $this->mNamespace ) {
3780 case NS_MEDIA:
3781 case NS_FILE:
3782 // file exists, possibly in a foreign repo
3783 return (bool)wfFindFile( $this );
3784 case NS_SPECIAL:
3785 // valid special page
3786 return SpecialPage::exists( $this->getDBkey() );
3787 case NS_MAIN:
3788 // selflink, possibly with fragment
3789 return $this->mDbkeyform == '';
3790 case NS_MEDIAWIKI:
3791 // known system message
3792 return $this->getDefaultMessageText() !== false;
3793 default:
3794 return false;
3795 }
3796 }
3797
3798 /**
3799 * Does this title refer to a page that can (or might) be meaningfully
3800 * viewed? In particular, this function may be used to determine if
3801 * links to the title should be rendered as "bluelinks" (as opposed to
3802 * "redlinks" to non-existent pages).
3803 *
3804 * @return Bool
3805 */
3806 public function isKnown() {
3807 return $this->isAlwaysKnown() || $this->exists();
3808 }
3809
3810 /**
3811 * Does this page have source text?
3812 *
3813 * @return Boolean
3814 */
3815 public function hasSourceText() {
3816 if ( $this->exists() ) {
3817 return true;
3818 }
3819
3820 if ( $this->mNamespace == NS_MEDIAWIKI ) {
3821 // If the page doesn't exist but is a known system message, default
3822 // message content will be displayed, same for language subpages
3823 return $this->getDefaultMessageText() !== false;
3824 }
3825
3826 return false;
3827 }
3828
3829 /**
3830 * Get the default message text or false if the message doesn't exist
3831 *
3832 * @return String or false
3833 */
3834 public function getDefaultMessageText() {
3835 global $wgContLang;
3836
3837 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
3838 return false;
3839 }
3840
3841 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
3842 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
3843
3844 if ( $message->exists() ) {
3845 return $message->plain();
3846 } else {
3847 return false;
3848 }
3849 }
3850
3851 /**
3852 * Is this in a namespace that allows actual pages?
3853 *
3854 * @return Bool
3855 * @internal note -- uses hardcoded namespace index instead of constants
3856 */
3857 public function canExist() {
3858 return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA;
3859 }
3860
3861 /**
3862 * Update page_touched timestamps and send squid purge messages for
3863 * pages linking to this title. May be sent to the job queue depending
3864 * on the number of links. Typically called on create and delete.
3865 */
3866 public function touchLinks() {
3867 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3868 $u->doUpdate();
3869
3870 if ( $this->getNamespace() == NS_CATEGORY ) {
3871 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3872 $u->doUpdate();
3873 }
3874 }
3875
3876 /**
3877 * Get the last touched timestamp
3878 *
3879 * @param $db DatabaseBase: optional db
3880 * @return String last-touched timestamp
3881 */
3882 public function getTouched( $db = null ) {
3883 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
3884 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
3885 return $touched;
3886 }
3887
3888 /**
3889 * Get the timestamp when this page was updated since the user last saw it.
3890 *
3891 * @param $user User
3892 * @return String|Null
3893 */
3894 public function getNotificationTimestamp( $user = null ) {
3895 global $wgUser, $wgShowUpdatedMarker;
3896 // Assume current user if none given
3897 if ( !$user ) {
3898 $user = $wgUser;
3899 }
3900 // Check cache first
3901 $uid = $user->getId();
3902 // avoid isset here, as it'll return false for null entries
3903 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
3904 return $this->mNotificationTimestamp[$uid];
3905 }
3906 if ( !$uid || !$wgShowUpdatedMarker ) {
3907 return $this->mNotificationTimestamp[$uid] = false;
3908 }
3909 // Don't cache too much!
3910 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
3911 $this->mNotificationTimestamp = array();
3912 }
3913 $dbr = wfGetDB( DB_SLAVE );
3914 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
3915 'wl_notificationtimestamp',
3916 array( 'wl_namespace' => $this->getNamespace(),
3917 'wl_title' => $this->getDBkey(),
3918 'wl_user' => $user->getId()
3919 ),
3920 __METHOD__
3921 );
3922 return $this->mNotificationTimestamp[$uid];
3923 }
3924
3925 /**
3926 * Get the trackback URL for this page
3927 *
3928 * @return String Trackback URL
3929 */
3930 public function trackbackURL() {
3931 global $wgScriptPath, $wgServer, $wgScriptExtension;
3932
3933 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3934 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3935 }
3936
3937 /**
3938 * Get the trackback RDF for this page
3939 *
3940 * @return String Trackback RDF
3941 */
3942 public function trackbackRDF() {
3943 $url = htmlspecialchars( $this->getFullURL() );
3944 $title = htmlspecialchars( $this->getText() );
3945 $tburl = $this->trackbackURL();
3946
3947 // Autodiscovery RDF is placed in comments so HTML validator
3948 // won't barf. This is a rather icky workaround, but seems
3949 // frequently used by this kind of RDF thingy.
3950 //
3951 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3952 return "<!--
3953 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3954 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3955 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3956 <rdf:Description
3957 rdf:about=\"$url\"
3958 dc:identifier=\"$url\"
3959 dc:title=\"$title\"
3960 trackback:ping=\"$tburl\" />
3961 </rdf:RDF>
3962 -->";
3963 }
3964
3965 /**
3966 * Generate strings used for xml 'id' names in monobook tabs
3967 *
3968 * @param $prepend string defaults to 'nstab-'
3969 * @return String XML 'id' name
3970 */
3971 public function getNamespaceKey( $prepend = 'nstab-' ) {
3972 global $wgContLang;
3973 // Gets the subject namespace if this title
3974 $namespace = MWNamespace::getSubject( $this->getNamespace() );
3975 // Checks if cononical namespace name exists for namespace
3976 if ( MWNamespace::exists( $this->getNamespace() ) ) {
3977 // Uses canonical namespace name
3978 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
3979 } else {
3980 // Uses text of namespace
3981 $namespaceKey = $this->getSubjectNsText();
3982 }
3983 // Makes namespace key lowercase
3984 $namespaceKey = $wgContLang->lc( $namespaceKey );
3985 // Uses main
3986 if ( $namespaceKey == '' ) {
3987 $namespaceKey = 'main';
3988 }
3989 // Changes file to image for backwards compatibility
3990 if ( $namespaceKey == 'file' ) {
3991 $namespaceKey = 'image';
3992 }
3993 return $prepend . $namespaceKey;
3994 }
3995
3996 /**
3997 * Returns true if this is a special page.
3998 *
3999 * @return boolean
4000 */
4001 public function isSpecialPage() {
4002 return $this->getNamespace() == NS_SPECIAL;
4003 }
4004
4005 /**
4006 * Returns true if this title resolves to the named special page
4007 *
4008 * @param $name String The special page name
4009 * @return boolean
4010 */
4011 public function isSpecial( $name ) {
4012 if ( $this->getNamespace() == NS_SPECIAL ) {
4013 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
4014 if ( $name == $thisName ) {
4015 return true;
4016 }
4017 }
4018 return false;
4019 }
4020
4021 /**
4022 * If the Title refers to a special page alias which is not the local default, resolve
4023 * the alias, and localise the name as necessary. Otherwise, return $this
4024 *
4025 * @return Title
4026 */
4027 public function fixSpecialName() {
4028 if ( $this->getNamespace() == NS_SPECIAL ) {
4029 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
4030 if ( $canonicalName ) {
4031 $localName = SpecialPage::getLocalNameFor( $canonicalName );
4032 if ( $localName != $this->mDbkeyform ) {
4033 return Title::makeTitle( NS_SPECIAL, $localName );
4034 }
4035 }
4036 }
4037 return $this;
4038 }
4039
4040 /**
4041 * Is this Title in a namespace which contains content?
4042 * In other words, is this a content page, for the purposes of calculating
4043 * statistics, etc?
4044 *
4045 * @return Boolean
4046 */
4047 public function isContentPage() {
4048 return MWNamespace::isContent( $this->getNamespace() );
4049 }
4050
4051 /**
4052 * Get all extant redirects to this Title
4053 *
4054 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4055 * @return Array of Title redirects to this title
4056 */
4057 public function getRedirectsHere( $ns = null ) {
4058 $redirs = array();
4059
4060 $dbr = wfGetDB( DB_SLAVE );
4061 $where = array(
4062 'rd_namespace' => $this->getNamespace(),
4063 'rd_title' => $this->getDBkey(),
4064 'rd_from = page_id'
4065 );
4066 if ( !is_null( $ns ) ) {
4067 $where['page_namespace'] = $ns;
4068 }
4069
4070 $res = $dbr->select(
4071 array( 'redirect', 'page' ),
4072 array( 'page_namespace', 'page_title' ),
4073 $where,
4074 __METHOD__
4075 );
4076
4077 foreach ( $res as $row ) {
4078 $redirs[] = self::newFromRow( $row );
4079 }
4080 return $redirs;
4081 }
4082
4083 /**
4084 * Check if this Title is a valid redirect target
4085 *
4086 * @return Bool
4087 */
4088 public function isValidRedirectTarget() {
4089 global $wgInvalidRedirectTargets;
4090
4091 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4092 if ( $this->isSpecial( 'Userlogout' ) ) {
4093 return false;
4094 }
4095
4096 foreach ( $wgInvalidRedirectTargets as $target ) {
4097 if ( $this->isSpecial( $target ) ) {
4098 return false;
4099 }
4100 }
4101
4102 return true;
4103 }
4104
4105 /**
4106 * Get a backlink cache object
4107 *
4108 * @return object BacklinkCache
4109 */
4110 function getBacklinkCache() {
4111 if ( is_null( $this->mBacklinkCache ) ) {
4112 $this->mBacklinkCache = new BacklinkCache( $this );
4113 }
4114 return $this->mBacklinkCache;
4115 }
4116
4117 /**
4118 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4119 *
4120 * @return Boolean
4121 */
4122 public function canUseNoindex() {
4123 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4124
4125 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4126 ? $wgContentNamespaces
4127 : $wgExemptFromUserRobotsControl;
4128
4129 return !in_array( $this->mNamespace, $bannedNamespaces );
4130
4131 }
4132
4133 /**
4134 * Returns restriction types for the current Title
4135 *
4136 * @return array applicable restriction types
4137 */
4138 public function getRestrictionTypes() {
4139 if ( $this->getNamespace() == NS_SPECIAL ) {
4140 return array();
4141 }
4142
4143 $types = self::getFilteredRestrictionTypes( $this->exists() );
4144
4145 if ( $this->getNamespace() != NS_FILE ) {
4146 # Remove the upload restriction for non-file titles
4147 $types = array_diff( $types, array( 'upload' ) );
4148 }
4149
4150 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4151
4152 wfDebug( __METHOD__ . ': applicable restriction types for ' .
4153 $this->getPrefixedText() . ' are ' . implode( ',', $types ) . "\n" );
4154
4155 return $types;
4156 }
4157 /**
4158 * Get a filtered list of all restriction types supported by this wiki.
4159 * @param bool $exists True to get all restriction types that apply to
4160 * titles that do exist, False for all restriction types that apply to
4161 * titles that do not exist
4162 * @return array
4163 */
4164 public static function getFilteredRestrictionTypes( $exists = true ) {
4165 global $wgRestrictionTypes;
4166 $types = $wgRestrictionTypes;
4167 if ( $exists ) {
4168 # Remove the create restriction for existing titles
4169 $types = array_diff( $types, array( 'create' ) );
4170 } else {
4171 # Only the create and upload restrictions apply to non-existing titles
4172 $types = array_intersect( $types, array( 'create', 'upload' ) );
4173 }
4174 return $types;
4175 }
4176
4177 /**
4178 * Returns the raw sort key to be used for categories, with the specified
4179 * prefix. This will be fed to Collation::getSortKey() to get a
4180 * binary sortkey that can be used for actual sorting.
4181 *
4182 * @param $prefix string The prefix to be used, specified using
4183 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4184 * prefix.
4185 * @return string
4186 */
4187 public function getCategorySortkey( $prefix = '' ) {
4188 $unprefixed = $this->getText();
4189 if ( $prefix !== '' ) {
4190 # Separate with a line feed, so the unprefixed part is only used as
4191 # a tiebreaker when two pages have the exact same prefix.
4192 # In UCA, tab is the only character that can sort above LF
4193 # so we strip both of them from the original prefix.
4194 $prefix = strtr( $prefix, "\n\t", ' ' );
4195 return "$prefix\n$unprefixed";
4196 }
4197 return $unprefixed;
4198 }
4199 }