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