Respect $wgScriptExtension in SearchEngine::getOpenSearchTemplate() and SearchEngine...
[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 if ( in_array( $action, array( 'read', 'createaccount', 'unblock' ) ) ){
1545 // Edit blocks should not affect reading.
1546 // Account creation blocks handled at userlogin.
1547 // Unblocking handled in SpecialUnblock
1548 } elseif( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ){
1549 // Don't block the user from editing their own talk page unless they've been
1550 // explicitly blocked from that too.
1551 } elseif( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
1552 $block = $user->mBlock;
1553
1554 // This is from OutputPage::blockedPage
1555 // Copied at r23888 by werdna
1556
1557 $id = $user->blockedBy();
1558 $reason = $user->blockedFor();
1559 if ( $reason == '' ) {
1560 $reason = wfMsg( 'blockednoreason' );
1561 }
1562 $ip = wfGetIP();
1563
1564 if ( is_numeric( $id ) ) {
1565 $name = User::whoIs( $id );
1566 } else {
1567 $name = $id;
1568 }
1569
1570 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
1571 $blockid = $block->getId();
1572 $blockExpiry = $user->mBlock->mExpiry;
1573 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $user->mBlock->mTimestamp ), true );
1574 if ( $blockExpiry == 'infinity' ) {
1575 $blockExpiry = wfMessage( 'infiniteblock' );
1576 } else {
1577 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
1578 }
1579
1580 $intended = $user->mBlock->getTarget();
1581
1582 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
1583 $blockid, $blockExpiry, $intended, $blockTimestamp );
1584 }
1585
1586 return $errors;
1587 }
1588
1589 /**
1590 * Can $user perform $action on this page? This is an internal function,
1591 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1592 * checks on wfReadOnly() and blocks)
1593 *
1594 * @param $action String action that permission needs to be checked for
1595 * @param $user User to check
1596 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1597 * @param $short Bool Set this to true to stop after the first permission error.
1598 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1599 */
1600 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1601 wfProfileIn( __METHOD__ );
1602
1603 $errors = array();
1604 $checks = array(
1605 'checkQuickPermissions',
1606 'checkPermissionHooks',
1607 'checkSpecialsAndNSPermissions',
1608 'checkCSSandJSPermissions',
1609 'checkPageRestrictions',
1610 'checkCascadingSourcesRestrictions',
1611 'checkActionPermissions',
1612 'checkUserBlock'
1613 );
1614
1615 while( count( $checks ) > 0 &&
1616 !( $short && count( $errors ) > 0 ) ) {
1617 $method = array_shift( $checks );
1618 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1619 }
1620
1621 wfProfileOut( __METHOD__ );
1622 return $errors;
1623 }
1624
1625 /**
1626 * Is this title subject to title protection?
1627 * Title protection is the one applied against creation of such title.
1628 *
1629 * @return Mixed An associative array representing any existent title
1630 * protection, or false if there's none.
1631 */
1632 private function getTitleProtection() {
1633 // Can't protect pages in special namespaces
1634 if ( $this->getNamespace() < 0 ) {
1635 return false;
1636 }
1637
1638 // Can't protect pages that exist.
1639 if ( $this->exists() ) {
1640 return false;
1641 }
1642
1643 if ( !isset( $this->mTitleProtection ) ) {
1644 $dbr = wfGetDB( DB_SLAVE );
1645 $res = $dbr->select( 'protected_titles', '*',
1646 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1647 __METHOD__ );
1648
1649 // fetchRow returns false if there are no rows.
1650 $this->mTitleProtection = $dbr->fetchRow( $res );
1651 }
1652 return $this->mTitleProtection;
1653 }
1654
1655 /**
1656 * Update the title protection status
1657 *
1658 * @param $create_perm String Permission required for creation
1659 * @param $reason String Reason for protection
1660 * @param $expiry String Expiry timestamp
1661 * @return boolean true
1662 */
1663 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1664 global $wgUser, $wgContLang;
1665
1666 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1667 && $expiry == $this->mRestrictionsExpiry['create'] ) {
1668 // No change
1669 return true;
1670 }
1671
1672 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1673
1674 $dbw = wfGetDB( DB_MASTER );
1675
1676 $encodedExpiry = $dbw->encodeExpiry( $expiry );
1677
1678 $expiry_description = '';
1679 if ( $encodedExpiry != $dbw->getInfinity() ) {
1680 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1681 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1682 } else {
1683 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1684 }
1685
1686 # Update protection table
1687 if ( $create_perm != '' ) {
1688 $this->mTitleProtection = array(
1689 'pt_namespace' => $namespace,
1690 'pt_title' => $title,
1691 'pt_create_perm' => $create_perm,
1692 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1693 'pt_expiry' => $encodedExpiry,
1694 'pt_user' => $wgUser->getId(),
1695 'pt_reason' => $reason,
1696 );
1697 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1698 $this->mTitleProtection, __METHOD__ );
1699 } else {
1700 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1701 'pt_title' => $title ), __METHOD__ );
1702 $this->mTitleProtection = false;
1703 }
1704
1705 # Update the protection log
1706 if ( $dbw->affectedRows() ) {
1707 $log = new LogPage( 'protect' );
1708
1709 if ( $create_perm ) {
1710 $params = array( "[create=$create_perm] $expiry_description", '' );
1711 $log->addEntry( ( isset( $this->mRestrictions['create'] ) && $this->mRestrictions['create'] ) ? 'modify' : 'protect', $this, trim( $reason ), $params );
1712 } else {
1713 $log->addEntry( 'unprotect', $this, $reason );
1714 }
1715 }
1716
1717 return true;
1718 }
1719
1720 /**
1721 * Remove any title protection due to page existing
1722 */
1723 public function deleteTitleProtection() {
1724 $dbw = wfGetDB( DB_MASTER );
1725
1726 $dbw->delete(
1727 'protected_titles',
1728 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1729 __METHOD__
1730 );
1731 $this->mTitleProtection = false;
1732 }
1733
1734 /**
1735 * Would anybody with sufficient privileges be able to move this page?
1736 * Some pages just aren't movable.
1737 *
1738 * @return Bool TRUE or FALSE
1739 */
1740 public function isMovable() {
1741 return MWNamespace::isMovable( $this->getNamespace() ) && $this->getInterwiki() == '';
1742 }
1743
1744 /**
1745 * Can $wgUser read this page?
1746 *
1747 * @return Bool
1748 * @todo fold these checks into userCan()
1749 */
1750 public function userCanRead() {
1751 global $wgUser, $wgGroupPermissions;
1752
1753 static $useShortcut = null;
1754
1755 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
1756 if ( is_null( $useShortcut ) ) {
1757 global $wgRevokePermissions;
1758 $useShortcut = true;
1759 if ( empty( $wgGroupPermissions['*']['read'] ) ) {
1760 # Not a public wiki, so no shortcut
1761 $useShortcut = false;
1762 } elseif ( !empty( $wgRevokePermissions ) ) {
1763 /*
1764 * Iterate through each group with permissions being revoked (key not included since we don't care
1765 * what the group name is), then check if the read permission is being revoked. If it is, then
1766 * we don't use the shortcut below since the user might not be able to read, even though anon
1767 * reading is allowed.
1768 */
1769 foreach ( $wgRevokePermissions as $perms ) {
1770 if ( !empty( $perms['read'] ) ) {
1771 # We might be removing the read right from the user, so no shortcut
1772 $useShortcut = false;
1773 break;
1774 }
1775 }
1776 }
1777 }
1778
1779 $result = null;
1780 wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
1781 if ( $result !== null ) {
1782 return $result;
1783 }
1784
1785 # Shortcut for public wikis, allows skipping quite a bit of code
1786 if ( $useShortcut ) {
1787 return true;
1788 }
1789
1790 if ( $wgUser->isAllowed( 'read' ) ) {
1791 return true;
1792 } else {
1793 global $wgWhitelistRead;
1794
1795 # Always grant access to the login page.
1796 # Even anons need to be able to log in.
1797 if ( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
1798 return true;
1799 }
1800
1801 # Bail out if there isn't whitelist
1802 if ( !is_array( $wgWhitelistRead ) ) {
1803 return false;
1804 }
1805
1806 # Check for explicit whitelisting
1807 $name = $this->getPrefixedText();
1808 $dbName = $this->getPrefixedDBKey();
1809 // Check with and without underscores
1810 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) )
1811 return true;
1812
1813 # Old settings might have the title prefixed with
1814 # a colon for main-namespace pages
1815 if ( $this->getNamespace() == NS_MAIN ) {
1816 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1817 return true;
1818 }
1819 }
1820
1821 # If it's a special page, ditch the subpage bit and check again
1822 if ( $this->getNamespace() == NS_SPECIAL ) {
1823 $name = $this->getDBkey();
1824 list( $name, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $name );
1825 if ( $name === false ) {
1826 # Invalid special page, but we show standard login required message
1827 return false;
1828 }
1829
1830 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1831 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1832 return true;
1833 }
1834 }
1835
1836 }
1837 return false;
1838 }
1839
1840 /**
1841 * Is this the mainpage?
1842 * @note Title::newFromText seams to be sufficiently optimized by the title
1843 * cache that we don't need to over-optimize by doing direct comparisons and
1844 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1845 * ends up reporting something differently than $title->isMainPage();
1846 *
1847 * @return Bool
1848 */
1849 public function isMainPage() {
1850 return $this->equals( Title::newMainPage() );
1851 }
1852
1853 /**
1854 * Is this a talk page of some sort?
1855 *
1856 * @return Bool
1857 */
1858 public function isTalkPage() {
1859 return MWNamespace::isTalk( $this->getNamespace() );
1860 }
1861
1862 /**
1863 * Is this a subpage?
1864 *
1865 * @return Bool
1866 */
1867 public function isSubpage() {
1868 return MWNamespace::hasSubpages( $this->mNamespace )
1869 ? strpos( $this->getText(), '/' ) !== false
1870 : false;
1871 }
1872
1873 /**
1874 * Does this have subpages? (Warning, usually requires an extra DB query.)
1875 *
1876 * @return Bool
1877 */
1878 public function hasSubpages() {
1879 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1880 # Duh
1881 return false;
1882 }
1883
1884 # We dynamically add a member variable for the purpose of this method
1885 # alone to cache the result. There's no point in having it hanging
1886 # around uninitialized in every Title object; therefore we only add it
1887 # if needed and don't declare it statically.
1888 if ( isset( $this->mHasSubpages ) ) {
1889 return $this->mHasSubpages;
1890 }
1891
1892 $subpages = $this->getSubpages( 1 );
1893 if ( $subpages instanceof TitleArray ) {
1894 return $this->mHasSubpages = (bool)$subpages->count();
1895 }
1896 return $this->mHasSubpages = false;
1897 }
1898
1899 /**
1900 * Get all subpages of this page.
1901 *
1902 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
1903 * @return mixed TitleArray, or empty array if this page's namespace
1904 * doesn't allow subpages
1905 */
1906 public function getSubpages( $limit = -1 ) {
1907 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
1908 return array();
1909 }
1910
1911 $dbr = wfGetDB( DB_SLAVE );
1912 $conds['page_namespace'] = $this->getNamespace();
1913 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
1914 $options = array();
1915 if ( $limit > -1 ) {
1916 $options['LIMIT'] = $limit;
1917 }
1918 return $this->mSubpages = TitleArray::newFromResult(
1919 $dbr->select( 'page',
1920 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
1921 $conds,
1922 __METHOD__,
1923 $options
1924 )
1925 );
1926 }
1927
1928 /**
1929 * Could this page contain custom CSS or JavaScript, based
1930 * on the title?
1931 *
1932 * @return Bool
1933 */
1934 public function isCssOrJsPage() {
1935 return $this->mNamespace == NS_MEDIAWIKI
1936 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
1937 }
1938
1939 /**
1940 * Is this a .css or .js subpage of a user page?
1941 * @return Bool
1942 */
1943 public function isCssJsSubpage() {
1944 return ( NS_USER == $this->mNamespace and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
1945 }
1946
1947 /**
1948 * Is this a *valid* .css or .js subpage of a user page?
1949 *
1950 * @return Bool
1951 * @deprecated since 1.17
1952 */
1953 public function isValidCssJsSubpage() {
1954 return $this->isCssJsSubpage();
1955 }
1956
1957 /**
1958 * Trim down a .css or .js subpage title to get the corresponding skin name
1959 *
1960 * @return string containing skin name from .css or .js subpage title
1961 */
1962 public function getSkinFromCssJsSubpage() {
1963 $subpage = explode( '/', $this->mTextform );
1964 $subpage = $subpage[ count( $subpage ) - 1 ];
1965 return( str_replace( array( '.css', '.js' ), array( '', '' ), $subpage ) );
1966 }
1967
1968 /**
1969 * Is this a .css subpage of a user page?
1970 *
1971 * @return Bool
1972 */
1973 public function isCssSubpage() {
1974 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.css$/", $this->mTextform ) );
1975 }
1976
1977 /**
1978 * Is this a .js subpage of a user page?
1979 *
1980 * @return Bool
1981 */
1982 public function isJsSubpage() {
1983 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.js$/", $this->mTextform ) );
1984 }
1985
1986 /**
1987 * Protect css subpages of user pages: can $wgUser edit
1988 * this page?
1989 *
1990 * @return Bool
1991 * @todo XXX: this might be better using restrictions
1992 */
1993 public function userCanEditCssSubpage() {
1994 global $wgUser;
1995 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
1996 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
1997 }
1998
1999 /**
2000 * Protect js subpages of user pages: can $wgUser edit
2001 * this page?
2002 *
2003 * @return Bool
2004 * @todo XXX: this might be better using restrictions
2005 */
2006 public function userCanEditJsSubpage() {
2007 global $wgUser;
2008 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2009 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2010 }
2011
2012 /**
2013 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2014 *
2015 * @return Bool If the page is subject to cascading restrictions.
2016 */
2017 public function isCascadeProtected() {
2018 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2019 return ( $sources > 0 );
2020 }
2021
2022 /**
2023 * Cascading protection: Get the source of any cascading restrictions on this page.
2024 *
2025 * @param $getPages Bool Whether or not to retrieve the actual pages
2026 * that the restrictions have come from.
2027 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2028 * have come, false for none, or true if such restrictions exist, but $getPages
2029 * was not set. The restriction array is an array of each type, each of which
2030 * contains a array of unique groups.
2031 */
2032 public function getCascadeProtectionSources( $getPages = true ) {
2033 global $wgContLang;
2034 $pagerestrictions = array();
2035
2036 if ( isset( $this->mCascadeSources ) && $getPages ) {
2037 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2038 } else if ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2039 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2040 }
2041
2042 wfProfileIn( __METHOD__ );
2043
2044 $dbr = wfGetDB( DB_SLAVE );
2045
2046 if ( $this->getNamespace() == NS_FILE ) {
2047 $tables = array( 'imagelinks', 'page_restrictions' );
2048 $where_clauses = array(
2049 'il_to' => $this->getDBkey(),
2050 'il_from=pr_page',
2051 'pr_cascade' => 1
2052 );
2053 } else {
2054 $tables = array( 'templatelinks', 'page_restrictions' );
2055 $where_clauses = array(
2056 'tl_namespace' => $this->getNamespace(),
2057 'tl_title' => $this->getDBkey(),
2058 'tl_from=pr_page',
2059 'pr_cascade' => 1
2060 );
2061 }
2062
2063 if ( $getPages ) {
2064 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2065 'pr_expiry', 'pr_type', 'pr_level' );
2066 $where_clauses[] = 'page_id=pr_page';
2067 $tables[] = 'page';
2068 } else {
2069 $cols = array( 'pr_expiry' );
2070 }
2071
2072 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2073
2074 $sources = $getPages ? array() : false;
2075 $now = wfTimestampNow();
2076 $purgeExpired = false;
2077
2078 foreach ( $res as $row ) {
2079 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2080 if ( $expiry > $now ) {
2081 if ( $getPages ) {
2082 $page_id = $row->pr_page;
2083 $page_ns = $row->page_namespace;
2084 $page_title = $row->page_title;
2085 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2086 # Add groups needed for each restriction type if its not already there
2087 # Make sure this restriction type still exists
2088
2089 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2090 $pagerestrictions[$row->pr_type] = array();
2091 }
2092
2093 if ( isset( $pagerestrictions[$row->pr_type] ) &&
2094 !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) ) {
2095 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2096 }
2097 } else {
2098 $sources = true;
2099 }
2100 } else {
2101 // Trigger lazy purge of expired restrictions from the db
2102 $purgeExpired = true;
2103 }
2104 }
2105 if ( $purgeExpired ) {
2106 Title::purgeExpiredRestrictions();
2107 }
2108
2109 if ( $getPages ) {
2110 $this->mCascadeSources = $sources;
2111 $this->mCascadingRestrictions = $pagerestrictions;
2112 } else {
2113 $this->mHasCascadingRestrictions = $sources;
2114 }
2115
2116 wfProfileOut( __METHOD__ );
2117 return array( $sources, $pagerestrictions );
2118 }
2119
2120 /**
2121 * Returns cascading restrictions for the current article
2122 *
2123 * @return Boolean
2124 */
2125 function areRestrictionsCascading() {
2126 if ( !$this->mRestrictionsLoaded ) {
2127 $this->loadRestrictions();
2128 }
2129
2130 return $this->mCascadeRestriction;
2131 }
2132
2133 /**
2134 * Loads a string into mRestrictions array
2135 *
2136 * @param $res Resource restrictions as an SQL result.
2137 * @param $oldFashionedRestrictions String comma-separated list of page
2138 * restrictions from page table (pre 1.10)
2139 */
2140 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2141 $rows = array();
2142
2143 foreach ( $res as $row ) {
2144 $rows[] = $row;
2145 }
2146
2147 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2148 }
2149
2150 /**
2151 * Compiles list of active page restrictions from both page table (pre 1.10)
2152 * and page_restrictions table for this existing page.
2153 * Public for usage by LiquidThreads.
2154 *
2155 * @param $rows array of db result objects
2156 * @param $oldFashionedRestrictions string comma-separated list of page
2157 * restrictions from page table (pre 1.10)
2158 */
2159 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2160 global $wgContLang;
2161 $dbr = wfGetDB( DB_SLAVE );
2162
2163 $restrictionTypes = $this->getRestrictionTypes();
2164
2165 foreach ( $restrictionTypes as $type ) {
2166 $this->mRestrictions[$type] = array();
2167 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2168 }
2169
2170 $this->mCascadeRestriction = false;
2171
2172 # Backwards-compatibility: also load the restrictions from the page record (old format).
2173
2174 if ( $oldFashionedRestrictions === null ) {
2175 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2176 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
2177 }
2178
2179 if ( $oldFashionedRestrictions != '' ) {
2180
2181 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2182 $temp = explode( '=', trim( $restrict ) );
2183 if ( count( $temp ) == 1 ) {
2184 // old old format should be treated as edit/move restriction
2185 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2186 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2187 } else {
2188 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
2189 }
2190 }
2191
2192 $this->mOldRestrictions = true;
2193
2194 }
2195
2196 if ( count( $rows ) ) {
2197 # Current system - load second to make them override.
2198 $now = wfTimestampNow();
2199 $purgeExpired = false;
2200
2201 # Cycle through all the restrictions.
2202 foreach ( $rows as $row ) {
2203
2204 // Don't take care of restrictions types that aren't allowed
2205 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2206 continue;
2207
2208 // This code should be refactored, now that it's being used more generally,
2209 // But I don't really see any harm in leaving it in Block for now -werdna
2210 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2211
2212 // Only apply the restrictions if they haven't expired!
2213 if ( !$expiry || $expiry > $now ) {
2214 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2215 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2216
2217 $this->mCascadeRestriction |= $row->pr_cascade;
2218 } else {
2219 // Trigger a lazy purge of expired restrictions
2220 $purgeExpired = true;
2221 }
2222 }
2223
2224 if ( $purgeExpired ) {
2225 Title::purgeExpiredRestrictions();
2226 }
2227 }
2228
2229 $this->mRestrictionsLoaded = true;
2230 }
2231
2232 /**
2233 * Load restrictions from the page_restrictions table
2234 *
2235 * @param $oldFashionedRestrictions String comma-separated list of page
2236 * restrictions from page table (pre 1.10)
2237 */
2238 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2239 global $wgContLang;
2240 if ( !$this->mRestrictionsLoaded ) {
2241 if ( $this->exists() ) {
2242 $dbr = wfGetDB( DB_SLAVE );
2243
2244 $res = $dbr->select(
2245 'page_restrictions',
2246 '*',
2247 array( 'pr_page' => $this->getArticleId() ),
2248 __METHOD__
2249 );
2250
2251 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2252 } else {
2253 $title_protection = $this->getTitleProtection();
2254
2255 if ( $title_protection ) {
2256 $now = wfTimestampNow();
2257 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW );
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'] = $wgContLang->formatExpiry( '', TS_MW );
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 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3101 $pageid = $this->getArticleID( GAID_FOR_UPDATE );
3102 $protected = $this->isProtected();
3103 $pageCountChange = ( $createRedirect ? 1 : 0 ) - ( $nt->exists() ? 1 : 0 );
3104
3105 // Do the actual move
3106 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3107 if ( is_array( $err ) ) {
3108 # FIXME: What about the File we have already moved?
3109 $dbw->rollback();
3110 return $err;
3111 }
3112
3113 $redirid = $this->getArticleID();
3114
3115 // Refresh the sortkey for this row. Be careful to avoid resetting
3116 // cl_timestamp, which may disturb time-based lists on some sites.
3117 $prefixes = $dbw->select(
3118 'categorylinks',
3119 array( 'cl_sortkey_prefix', 'cl_to' ),
3120 array( 'cl_from' => $pageid ),
3121 __METHOD__
3122 );
3123 foreach ( $prefixes as $prefixRow ) {
3124 $prefix = $prefixRow->cl_sortkey_prefix;
3125 $catTo = $prefixRow->cl_to;
3126 $dbw->update( 'categorylinks',
3127 array(
3128 'cl_sortkey' => Collation::singleton()->getSortKey(
3129 $nt->getCategorySortkey( $prefix ) ),
3130 'cl_timestamp=cl_timestamp' ),
3131 array(
3132 'cl_from' => $pageid,
3133 'cl_to' => $catTo ),
3134 __METHOD__
3135 );
3136 }
3137
3138 if ( $protected ) {
3139 # Protect the redirect title as the title used to be...
3140 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3141 array(
3142 'pr_page' => $redirid,
3143 'pr_type' => 'pr_type',
3144 'pr_level' => 'pr_level',
3145 'pr_cascade' => 'pr_cascade',
3146 'pr_user' => 'pr_user',
3147 'pr_expiry' => 'pr_expiry'
3148 ),
3149 array( 'pr_page' => $pageid ),
3150 __METHOD__,
3151 array( 'IGNORE' )
3152 );
3153 # Update the protection log
3154 $log = new LogPage( 'protect' );
3155 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3156 if ( $reason ) {
3157 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3158 }
3159 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) ); // FIXME: $params?
3160 }
3161
3162 # Update watchlists
3163 $oldnamespace = $this->getNamespace() & ~1;
3164 $newnamespace = $nt->getNamespace() & ~1;
3165 $oldtitle = $this->getDBkey();
3166 $newtitle = $nt->getDBkey();
3167
3168 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3169 WatchedItem::duplicateEntries( $this, $nt );
3170 }
3171
3172 # Update search engine
3173 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3174 $u->doUpdate();
3175 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3176 $u->doUpdate();
3177
3178 $dbw->commit();
3179
3180 # Update site_stats
3181 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3182 # No longer a content page
3183 # Not viewed, edited, removing
3184 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3185 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3186 # Now a content page
3187 # Not viewed, edited, adding
3188 $u = new SiteStatsUpdate( 0, 1, + 1, $pageCountChange );
3189 } elseif ( $pageCountChange ) {
3190 # Redirect added
3191 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3192 } else {
3193 # Nothing special
3194 $u = false;
3195 }
3196 if ( $u ) {
3197 $u->doUpdate();
3198 }
3199 # Update message cache for interface messages
3200 if ( $this->getNamespace() == NS_MEDIAWIKI ) {
3201 # @bug 17860: old article can be deleted, if this the case,
3202 # delete it from message cache
3203 if ( $this->getArticleID() === 0 ) {
3204 MessageCache::singleton()->replace( $this->getDBkey(), false );
3205 } else {
3206 $oldarticle = new Article( $this );
3207 MessageCache::singleton()->replace( $this->getDBkey(), $oldarticle->getContent() );
3208 }
3209 }
3210 if ( $nt->getNamespace() == NS_MEDIAWIKI ) {
3211 $newarticle = new Article( $nt );
3212 MessageCache::singleton()->replace( $nt->getDBkey(), $newarticle->getContent() );
3213 }
3214
3215 global $wgUser;
3216 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3217 return true;
3218 }
3219
3220 /**
3221 * Move page to a title which is either a redirect to the
3222 * source page or nonexistent
3223 *
3224 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3225 * @param $reason String The reason for the move
3226 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3227 * if the user doesn't have the suppressredirect right
3228 */
3229 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3230 global $wgUser, $wgContLang;
3231
3232 $moveOverRedirect = $nt->exists();
3233
3234 $commentMsg = ( $moveOverRedirect ? '1movedto2_redir' : '1movedto2' );
3235 $comment = wfMsgForContent( $commentMsg, $this->getPrefixedText(), $nt->getPrefixedText() );
3236
3237 if ( $reason ) {
3238 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3239 }
3240 # Truncate for whole multibyte characters.
3241 $comment = $wgContLang->truncate( $comment, 255 );
3242
3243 $oldid = $this->getArticleID();
3244 $latest = $this->getLatestRevID();
3245
3246 $oldns = $this->getNamespace();
3247 $olddbk = $this->getDBkey();
3248
3249 $dbw = wfGetDB( DB_MASTER );
3250
3251 if ( $moveOverRedirect ) {
3252 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3253
3254 $newid = $nt->getArticleID();
3255 $newns = $nt->getNamespace();
3256 $newdbk = $nt->getDBkey();
3257
3258 # Delete the old redirect. We don't save it to history since
3259 # by definition if we've got here it's rather uninteresting.
3260 # We have to remove it so that the next step doesn't trigger
3261 # a conflict on the unique namespace+title index...
3262 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3263 if ( !$dbw->cascadingDeletes() ) {
3264 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
3265 global $wgUseTrackbacks;
3266 if ( $wgUseTrackbacks ) {
3267 $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
3268 }
3269 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3270 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
3271 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
3272 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
3273 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
3274 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
3275 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
3276 }
3277 // If the target page was recently created, it may have an entry in recentchanges still
3278 $dbw->delete( 'recentchanges',
3279 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3280 __METHOD__
3281 );
3282 }
3283
3284 # Save a null revision in the page's history notifying of the move
3285 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3286 if ( !is_object( $nullRevision ) ) {
3287 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3288 }
3289 $nullRevId = $nullRevision->insertOn( $dbw );
3290
3291 $article = new Article( $this );
3292 wfRunHooks( 'NewRevisionFromEditComplete', array( $article, $nullRevision, $latest, $wgUser ) );
3293
3294 # Change the name of the target page:
3295 $dbw->update( 'page',
3296 /* SET */ array(
3297 'page_touched' => $dbw->timestamp(),
3298 'page_namespace' => $nt->getNamespace(),
3299 'page_title' => $nt->getDBkey(),
3300 'page_latest' => $nullRevId,
3301 ),
3302 /* WHERE */ array( 'page_id' => $oldid ),
3303 __METHOD__
3304 );
3305 $nt->resetArticleID( $oldid );
3306
3307 # Recreate the redirect, this time in the other direction.
3308 if ( $createRedirect || !$wgUser->isAllowed( 'suppressredirect' ) ) {
3309 $mwRedir = MagicWord::get( 'redirect' );
3310 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3311 $redirectArticle = new Article( $this );
3312 $newid = $redirectArticle->insertOn( $dbw );
3313 $redirectRevision = new Revision( array(
3314 'page' => $newid,
3315 'comment' => $comment,
3316 'text' => $redirectText ) );
3317 $redirectRevision->insertOn( $dbw );
3318 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3319
3320 wfRunHooks( 'NewRevisionFromEditComplete', array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3321
3322 # Now, we record the link from the redirect to the new title.
3323 # It should have no other outgoing links...
3324 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3325 $dbw->insert( 'pagelinks',
3326 array(
3327 'pl_from' => $newid,
3328 'pl_namespace' => $nt->getNamespace(),
3329 'pl_title' => $nt->getDBkey() ),
3330 __METHOD__ );
3331 $redirectSuppressed = false;
3332 } else {
3333 // Get rid of old new page entries in Special:NewPages and RC.
3334 // Needs to be before $this->resetArticleID( 0 ).
3335 $dbw->delete( 'recentchanges', array(
3336 'rc_timestamp' => $dbw->timestamp( $this->getEarliestRevTime() ),
3337 'rc_namespace' => $oldns,
3338 'rc_title' => $olddbk,
3339 'rc_new' => 1
3340 ),
3341 __METHOD__
3342 );
3343
3344 $this->resetArticleID( 0 );
3345 $redirectSuppressed = true;
3346 }
3347
3348 # Log the move
3349 $log = new LogPage( 'move' );
3350 $logType = ( $moveOverRedirect ? 'move_redir' : 'move' );
3351 $log->addEntry( $logType, $this, $reason, array( 1 => $nt->getPrefixedText(), 2 => $redirectSuppressed ) );
3352
3353 # Purge caches for old and new titles
3354 if ( $moveOverRedirect ) {
3355 # A simple purge is enough when moving over a redirect
3356 $nt->purgeSquid();
3357 } else {
3358 # Purge caches as per article creation, including any pages that link to this title
3359 Article::onArticleCreate( $nt );
3360 }
3361 $this->purgeSquid();
3362 }
3363
3364 /**
3365 * Move this page's subpages to be subpages of $nt
3366 *
3367 * @param $nt Title Move target
3368 * @param $auth bool Whether $wgUser's permissions should be checked
3369 * @param $reason string The reason for the move
3370 * @param $createRedirect bool Whether to create redirects from the old subpages to
3371 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3372 * @return mixed array with old page titles as keys, and strings (new page titles) or
3373 * arrays (errors) as values, or an error array with numeric indices if no pages
3374 * were moved
3375 */
3376 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3377 global $wgMaximumMovedPages;
3378 // Check permissions
3379 if ( !$this->userCan( 'move-subpages' ) ) {
3380 return array( 'cant-move-subpages' );
3381 }
3382 // Do the source and target namespaces support subpages?
3383 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3384 return array( 'namespace-nosubpages',
3385 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3386 }
3387 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3388 return array( 'namespace-nosubpages',
3389 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3390 }
3391
3392 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3393 $retval = array();
3394 $count = 0;
3395 foreach ( $subpages as $oldSubpage ) {
3396 $count++;
3397 if ( $count > $wgMaximumMovedPages ) {
3398 $retval[$oldSubpage->getPrefixedTitle()] =
3399 array( 'movepage-max-pages',
3400 $wgMaximumMovedPages );
3401 break;
3402 }
3403
3404 // We don't know whether this function was called before
3405 // or after moving the root page, so check both
3406 // $this and $nt
3407 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3408 $oldSubpage->getArticleID() == $nt->getArticleId() )
3409 {
3410 // When moving a page to a subpage of itself,
3411 // don't move it twice
3412 continue;
3413 }
3414 $newPageName = preg_replace(
3415 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3416 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3417 $oldSubpage->getDBkey() );
3418 if ( $oldSubpage->isTalkPage() ) {
3419 $newNs = $nt->getTalkPage()->getNamespace();
3420 } else {
3421 $newNs = $nt->getSubjectPage()->getNamespace();
3422 }
3423 # Bug 14385: we need makeTitleSafe because the new page names may
3424 # be longer than 255 characters.
3425 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3426
3427 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3428 if ( $success === true ) {
3429 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3430 } else {
3431 $retval[$oldSubpage->getPrefixedText()] = $success;
3432 }
3433 }
3434 return $retval;
3435 }
3436
3437 /**
3438 * Checks if this page is just a one-rev redirect.
3439 * Adds lock, so don't use just for light purposes.
3440 *
3441 * @return Bool
3442 */
3443 public function isSingleRevRedirect() {
3444 $dbw = wfGetDB( DB_MASTER );
3445 # Is it a redirect?
3446 $row = $dbw->selectRow( 'page',
3447 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3448 $this->pageCond(),
3449 __METHOD__,
3450 array( 'FOR UPDATE' )
3451 );
3452 # Cache some fields we may want
3453 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3454 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3455 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3456 if ( !$this->mRedirect ) {
3457 return false;
3458 }
3459 # Does the article have a history?
3460 $row = $dbw->selectField( array( 'page', 'revision' ),
3461 'rev_id',
3462 array( 'page_namespace' => $this->getNamespace(),
3463 'page_title' => $this->getDBkey(),
3464 'page_id=rev_page',
3465 'page_latest != rev_id'
3466 ),
3467 __METHOD__,
3468 array( 'FOR UPDATE' )
3469 );
3470 # Return true if there was no history
3471 return ( $row === false );
3472 }
3473
3474 /**
3475 * Checks if $this can be moved to a given Title
3476 * - Selects for update, so don't call it unless you mean business
3477 *
3478 * @param $nt Title the new title to check
3479 * @return Bool
3480 */
3481 public function isValidMoveTarget( $nt ) {
3482 # Is it an existing file?
3483 if ( $nt->getNamespace() == NS_FILE ) {
3484 $file = wfLocalFile( $nt );
3485 if ( $file->exists() ) {
3486 wfDebug( __METHOD__ . ": file exists\n" );
3487 return false;
3488 }
3489 }
3490 # Is it a redirect with no history?
3491 if ( !$nt->isSingleRevRedirect() ) {
3492 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3493 return false;
3494 }
3495 # Get the article text
3496 $rev = Revision::newFromTitle( $nt );
3497 $text = $rev->getText();
3498 # Does the redirect point to the source?
3499 # Or is it a broken self-redirect, usually caused by namespace collisions?
3500 $m = array();
3501 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3502 $redirTitle = Title::newFromText( $m[1] );
3503 if ( !is_object( $redirTitle ) ||
3504 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3505 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3506 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3507 return false;
3508 }
3509 } else {
3510 # Fail safe
3511 wfDebug( __METHOD__ . ": failsafe\n" );
3512 return false;
3513 }
3514 return true;
3515 }
3516
3517 /**
3518 * Can this title be added to a user's watchlist?
3519 *
3520 * @return Bool TRUE or FALSE
3521 */
3522 public function isWatchable() {
3523 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3524 }
3525
3526 /**
3527 * Get categories to which this Title belongs and return an array of
3528 * categories' names.
3529 *
3530 * @return Array of parents in the form:
3531 * $parent => $currentarticle
3532 */
3533 public function getParentCategories() {
3534 global $wgContLang;
3535
3536 $data = array();
3537
3538 $titleKey = $this->getArticleId();
3539
3540 if ( $titleKey === 0 ) {
3541 return $data;
3542 }
3543
3544 $dbr = wfGetDB( DB_SLAVE );
3545
3546 $res = $dbr->select( 'categorylinks', '*',
3547 array(
3548 'cl_from' => $titleKey,
3549 ),
3550 __METHOD__,
3551 array()
3552 );
3553
3554 if ( $dbr->numRows( $res ) > 0 ) {
3555 foreach ( $res as $row ) {
3556 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3557 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3558 }
3559 }
3560 return $data;
3561 }
3562
3563 /**
3564 * Get a tree of parent categories
3565 *
3566 * @param $children Array with the children in the keys, to check for circular refs
3567 * @return Array Tree of parent categories
3568 */
3569 public function getParentCategoryTree( $children = array() ) {
3570 $stack = array();
3571 $parents = $this->getParentCategories();
3572
3573 if ( $parents ) {
3574 foreach ( $parents as $parent => $current ) {
3575 if ( array_key_exists( $parent, $children ) ) {
3576 # Circular reference
3577 $stack[$parent] = array();
3578 } else {
3579 $nt = Title::newFromText( $parent );
3580 if ( $nt ) {
3581 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3582 }
3583 }
3584 }
3585 }
3586
3587 return $stack;
3588 }
3589
3590 /**
3591 * Get an associative array for selecting this title from
3592 * the "page" table
3593 *
3594 * @return Array suitable for the $where parameter of DB::select()
3595 */
3596 public function pageCond() {
3597 if ( $this->mArticleID > 0 ) {
3598 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3599 return array( 'page_id' => $this->mArticleID );
3600 } else {
3601 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3602 }
3603 }
3604
3605 /**
3606 * Get the revision ID of the previous revision
3607 *
3608 * @param $revId Int Revision ID. Get the revision that was before this one.
3609 * @param $flags Int Title::GAID_FOR_UPDATE
3610 * @return Int|Bool Old revision ID, or FALSE if none exists
3611 */
3612 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3613 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3614 return $db->selectField( 'revision', 'rev_id',
3615 array(
3616 'rev_page' => $this->getArticleId( $flags ),
3617 'rev_id < ' . intval( $revId )
3618 ),
3619 __METHOD__,
3620 array( 'ORDER BY' => 'rev_id DESC' )
3621 );
3622 }
3623
3624 /**
3625 * Get the revision ID of the next revision
3626 *
3627 * @param $revId Int Revision ID. Get the revision that was after this one.
3628 * @param $flags Int Title::GAID_FOR_UPDATE
3629 * @return Int|Bool Next revision ID, or FALSE if none exists
3630 */
3631 public function getNextRevisionID( $revId, $flags = 0 ) {
3632 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3633 return $db->selectField( 'revision', 'rev_id',
3634 array(
3635 'rev_page' => $this->getArticleId( $flags ),
3636 'rev_id > ' . intval( $revId )
3637 ),
3638 __METHOD__,
3639 array( 'ORDER BY' => 'rev_id' )
3640 );
3641 }
3642
3643 /**
3644 * Get the first revision of the page
3645 *
3646 * @param $flags Int Title::GAID_FOR_UPDATE
3647 * @return Revision|Null if page doesn't exist
3648 */
3649 public function getFirstRevision( $flags = 0 ) {
3650 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3651 $pageId = $this->getArticleId( $flags );
3652 if ( !$pageId ) {
3653 return null;
3654 }
3655 $row = $db->selectRow( 'revision', '*',
3656 array( 'rev_page' => $pageId ),
3657 __METHOD__,
3658 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3659 );
3660 if ( !$row ) {
3661 return null;
3662 } else {
3663 return new Revision( $row );
3664 }
3665 }
3666
3667 /**
3668 * Check if this is a new page
3669 *
3670 * @return bool
3671 */
3672 public function isNewPage() {
3673 $dbr = wfGetDB( DB_SLAVE );
3674 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3675 }
3676
3677 /**
3678 * Get the oldest revision timestamp of this page
3679 *
3680 * @return String: MW timestamp
3681 */
3682 public function getEarliestRevTime() {
3683 $dbr = wfGetDB( DB_SLAVE );
3684 if ( $this->exists() ) {
3685 $min = $dbr->selectField( 'revision',
3686 'MIN(rev_timestamp)',
3687 array( 'rev_page' => $this->getArticleId() ),
3688 __METHOD__ );
3689 return wfTimestampOrNull( TS_MW, $min );
3690 }
3691 return null;
3692 }
3693
3694 /**
3695 * Get the number of revisions between the given revision IDs.
3696 * Used for diffs and other things that really need it.
3697 *
3698 * @param $old Int Revision ID.
3699 * @param $new Int Revision ID.
3700 * @return Int Number of revisions between these IDs.
3701 */
3702 public function countRevisionsBetween( $old, $new ) {
3703 $dbr = wfGetDB( DB_SLAVE );
3704 return (int)$dbr->selectField( 'revision', 'count(*)', array(
3705 'rev_page' => intval( $this->getArticleId() ),
3706 'rev_id > ' . intval( $old ),
3707 'rev_id < ' . intval( $new )
3708 ), __METHOD__
3709 );
3710 }
3711
3712 /**
3713 * Get the number of authors between the given revision IDs.
3714 * Used for diffs and other things that really need it.
3715 *
3716 * @param $fromRevId Int Revision ID (first before range)
3717 * @param $toRevId Int Revision ID (first after range)
3718 * @param $limit Int Maximum number of authors
3719 * @param $flags Int Title::GAID_FOR_UPDATE
3720 * @return Int
3721 */
3722 public function countAuthorsBetween( $fromRevId, $toRevId, $limit, $flags = 0 ) {
3723 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3724 $res = $db->select( 'revision', 'DISTINCT rev_user_text',
3725 array(
3726 'rev_page' => $this->getArticleID(),
3727 'rev_id > ' . (int)$fromRevId,
3728 'rev_id < ' . (int)$toRevId
3729 ), __METHOD__,
3730 array( 'LIMIT' => $limit )
3731 );
3732 return (int)$db->numRows( $res );
3733 }
3734
3735 /**
3736 * Compare with another title.
3737 *
3738 * @param $title Title
3739 * @return Bool
3740 */
3741 public function equals( Title $title ) {
3742 // Note: === is necessary for proper matching of number-like titles.
3743 return $this->getInterwiki() === $title->getInterwiki()
3744 && $this->getNamespace() == $title->getNamespace()
3745 && $this->getDBkey() === $title->getDBkey();
3746 }
3747
3748 /**
3749 * Callback for usort() to do title sorts by (namespace, title)
3750 *
3751 * @param $a Title
3752 * @param $b Title
3753 *
3754 * @return Integer: result of string comparison, or namespace comparison
3755 */
3756 public static function compare( $a, $b ) {
3757 if ( $a->getNamespace() == $b->getNamespace() ) {
3758 return strcmp( $a->getText(), $b->getText() );
3759 } else {
3760 return $a->getNamespace() - $b->getNamespace();
3761 }
3762 }
3763
3764 /**
3765 * Return a string representation of this title
3766 *
3767 * @return String representation of this title
3768 */
3769 public function __toString() {
3770 return $this->getPrefixedText();
3771 }
3772
3773 /**
3774 * Check if page exists. For historical reasons, this function simply
3775 * checks for the existence of the title in the page table, and will
3776 * thus return false for interwiki links, special pages and the like.
3777 * If you want to know if a title can be meaningfully viewed, you should
3778 * probably call the isKnown() method instead.
3779 *
3780 * @return Bool
3781 */
3782 public function exists() {
3783 return $this->getArticleId() != 0;
3784 }
3785
3786 /**
3787 * Should links to this title be shown as potentially viewable (i.e. as
3788 * "bluelinks"), even if there's no record by this title in the page
3789 * table?
3790 *
3791 * This function is semi-deprecated for public use, as well as somewhat
3792 * misleadingly named. You probably just want to call isKnown(), which
3793 * calls this function internally.
3794 *
3795 * (ISSUE: Most of these checks are cheap, but the file existence check
3796 * can potentially be quite expensive. Including it here fixes a lot of
3797 * existing code, but we might want to add an optional parameter to skip
3798 * it and any other expensive checks.)
3799 *
3800 * @return Bool
3801 */
3802 public function isAlwaysKnown() {
3803 if ( $this->mInterwiki != '' ) {
3804 return true; // any interwiki link might be viewable, for all we know
3805 }
3806 switch( $this->mNamespace ) {
3807 case NS_MEDIA:
3808 case NS_FILE:
3809 // file exists, possibly in a foreign repo
3810 return (bool)wfFindFile( $this );
3811 case NS_SPECIAL:
3812 // valid special page
3813 return SpecialPage::exists( $this->getDBkey() );
3814 case NS_MAIN:
3815 // selflink, possibly with fragment
3816 return $this->mDbkeyform == '';
3817 case NS_MEDIAWIKI:
3818 // known system message
3819 return $this->getDefaultMessageText() !== false;
3820 default:
3821 return false;
3822 }
3823 }
3824
3825 /**
3826 * Does this title refer to a page that can (or might) be meaningfully
3827 * viewed? In particular, this function may be used to determine if
3828 * links to the title should be rendered as "bluelinks" (as opposed to
3829 * "redlinks" to non-existent pages).
3830 *
3831 * @return Bool
3832 */
3833 public function isKnown() {
3834 return $this->isAlwaysKnown() || $this->exists();
3835 }
3836
3837 /**
3838 * Does this page have source text?
3839 *
3840 * @return Boolean
3841 */
3842 public function hasSourceText() {
3843 if ( $this->exists() ) {
3844 return true;
3845 }
3846
3847 if ( $this->mNamespace == NS_MEDIAWIKI ) {
3848 // If the page doesn't exist but is a known system message, default
3849 // message content will be displayed, same for language subpages
3850 return $this->getDefaultMessageText() !== false;
3851 }
3852
3853 return false;
3854 }
3855
3856 /**
3857 * Get the default message text or false if the message doesn't exist
3858 *
3859 * @return String or false
3860 */
3861 public function getDefaultMessageText() {
3862 global $wgContLang;
3863
3864 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
3865 return false;
3866 }
3867
3868 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
3869 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
3870
3871 if ( $message->exists() ) {
3872 return $message->plain();
3873 } else {
3874 return false;
3875 }
3876 }
3877
3878 /**
3879 * Is this in a namespace that allows actual pages?
3880 *
3881 * @return Bool
3882 * @internal note -- uses hardcoded namespace index instead of constants
3883 */
3884 public function canExist() {
3885 return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA;
3886 }
3887
3888 /**
3889 * Update page_touched timestamps and send squid purge messages for
3890 * pages linking to this title. May be sent to the job queue depending
3891 * on the number of links. Typically called on create and delete.
3892 */
3893 public function touchLinks() {
3894 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
3895 $u->doUpdate();
3896
3897 if ( $this->getNamespace() == NS_CATEGORY ) {
3898 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
3899 $u->doUpdate();
3900 }
3901 }
3902
3903 /**
3904 * Get the last touched timestamp
3905 *
3906 * @param $db DatabaseBase: optional db
3907 * @return String last-touched timestamp
3908 */
3909 public function getTouched( $db = null ) {
3910 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
3911 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
3912 return $touched;
3913 }
3914
3915 /**
3916 * Get the timestamp when this page was updated since the user last saw it.
3917 *
3918 * @param $user User
3919 * @return String|Null
3920 */
3921 public function getNotificationTimestamp( $user = null ) {
3922 global $wgUser, $wgShowUpdatedMarker;
3923 // Assume current user if none given
3924 if ( !$user ) {
3925 $user = $wgUser;
3926 }
3927 // Check cache first
3928 $uid = $user->getId();
3929 // avoid isset here, as it'll return false for null entries
3930 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
3931 return $this->mNotificationTimestamp[$uid];
3932 }
3933 if ( !$uid || !$wgShowUpdatedMarker ) {
3934 return $this->mNotificationTimestamp[$uid] = false;
3935 }
3936 // Don't cache too much!
3937 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
3938 $this->mNotificationTimestamp = array();
3939 }
3940 $dbr = wfGetDB( DB_SLAVE );
3941 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
3942 'wl_notificationtimestamp',
3943 array( 'wl_namespace' => $this->getNamespace(),
3944 'wl_title' => $this->getDBkey(),
3945 'wl_user' => $user->getId()
3946 ),
3947 __METHOD__
3948 );
3949 return $this->mNotificationTimestamp[$uid];
3950 }
3951
3952 /**
3953 * Get the trackback URL for this page
3954 *
3955 * @return String Trackback URL
3956 */
3957 public function trackbackURL() {
3958 global $wgScriptPath, $wgServer, $wgScriptExtension;
3959
3960 return "$wgServer$wgScriptPath/trackback$wgScriptExtension?article="
3961 . htmlspecialchars( urlencode( $this->getPrefixedDBkey() ) );
3962 }
3963
3964 /**
3965 * Get the trackback RDF for this page
3966 *
3967 * @return String Trackback RDF
3968 */
3969 public function trackbackRDF() {
3970 $url = htmlspecialchars( $this->getFullURL() );
3971 $title = htmlspecialchars( $this->getText() );
3972 $tburl = $this->trackbackURL();
3973
3974 // Autodiscovery RDF is placed in comments so HTML validator
3975 // won't barf. This is a rather icky workaround, but seems
3976 // frequently used by this kind of RDF thingy.
3977 //
3978 // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
3979 return "<!--
3980 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
3981 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
3982 xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
3983 <rdf:Description
3984 rdf:about=\"$url\"
3985 dc:identifier=\"$url\"
3986 dc:title=\"$title\"
3987 trackback:ping=\"$tburl\" />
3988 </rdf:RDF>
3989 -->";
3990 }
3991
3992 /**
3993 * Generate strings used for xml 'id' names in monobook tabs
3994 *
3995 * @param $prepend string defaults to 'nstab-'
3996 * @return String XML 'id' name
3997 */
3998 public function getNamespaceKey( $prepend = 'nstab-' ) {
3999 global $wgContLang;
4000 // Gets the subject namespace if this title
4001 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4002 // Checks if cononical namespace name exists for namespace
4003 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4004 // Uses canonical namespace name
4005 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4006 } else {
4007 // Uses text of namespace
4008 $namespaceKey = $this->getSubjectNsText();
4009 }
4010 // Makes namespace key lowercase
4011 $namespaceKey = $wgContLang->lc( $namespaceKey );
4012 // Uses main
4013 if ( $namespaceKey == '' ) {
4014 $namespaceKey = 'main';
4015 }
4016 // Changes file to image for backwards compatibility
4017 if ( $namespaceKey == 'file' ) {
4018 $namespaceKey = 'image';
4019 }
4020 return $prepend . $namespaceKey;
4021 }
4022
4023 /**
4024 * Returns true if this is a special page.
4025 *
4026 * @return boolean
4027 */
4028 public function isSpecialPage() {
4029 return $this->getNamespace() == NS_SPECIAL;
4030 }
4031
4032 /**
4033 * Returns true if this title resolves to the named special page
4034 *
4035 * @param $name String The special page name
4036 * @return boolean
4037 */
4038 public function isSpecial( $name ) {
4039 if ( $this->getNamespace() == NS_SPECIAL ) {
4040 list( $thisName, /* $subpage */ ) = SpecialPage::resolveAliasWithSubpage( $this->getDBkey() );
4041 if ( $name == $thisName ) {
4042 return true;
4043 }
4044 }
4045 return false;
4046 }
4047
4048 /**
4049 * If the Title refers to a special page alias which is not the local default, resolve
4050 * the alias, and localise the name as necessary. Otherwise, return $this
4051 *
4052 * @return Title
4053 */
4054 public function fixSpecialName() {
4055 if ( $this->getNamespace() == NS_SPECIAL ) {
4056 $canonicalName = SpecialPage::resolveAlias( $this->mDbkeyform );
4057 if ( $canonicalName ) {
4058 $localName = SpecialPage::getLocalNameFor( $canonicalName );
4059 if ( $localName != $this->mDbkeyform ) {
4060 return Title::makeTitle( NS_SPECIAL, $localName );
4061 }
4062 }
4063 }
4064 return $this;
4065 }
4066
4067 /**
4068 * Is this Title in a namespace which contains content?
4069 * In other words, is this a content page, for the purposes of calculating
4070 * statistics, etc?
4071 *
4072 * @return Boolean
4073 */
4074 public function isContentPage() {
4075 return MWNamespace::isContent( $this->getNamespace() );
4076 }
4077
4078 /**
4079 * Get all extant redirects to this Title
4080 *
4081 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4082 * @return Array of Title redirects to this title
4083 */
4084 public function getRedirectsHere( $ns = null ) {
4085 $redirs = array();
4086
4087 $dbr = wfGetDB( DB_SLAVE );
4088 $where = array(
4089 'rd_namespace' => $this->getNamespace(),
4090 'rd_title' => $this->getDBkey(),
4091 'rd_from = page_id'
4092 );
4093 if ( !is_null( $ns ) ) {
4094 $where['page_namespace'] = $ns;
4095 }
4096
4097 $res = $dbr->select(
4098 array( 'redirect', 'page' ),
4099 array( 'page_namespace', 'page_title' ),
4100 $where,
4101 __METHOD__
4102 );
4103
4104 foreach ( $res as $row ) {
4105 $redirs[] = self::newFromRow( $row );
4106 }
4107 return $redirs;
4108 }
4109
4110 /**
4111 * Check if this Title is a valid redirect target
4112 *
4113 * @return Bool
4114 */
4115 public function isValidRedirectTarget() {
4116 global $wgInvalidRedirectTargets;
4117
4118 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4119 if ( $this->isSpecial( 'Userlogout' ) ) {
4120 return false;
4121 }
4122
4123 foreach ( $wgInvalidRedirectTargets as $target ) {
4124 if ( $this->isSpecial( $target ) ) {
4125 return false;
4126 }
4127 }
4128
4129 return true;
4130 }
4131
4132 /**
4133 * Get a backlink cache object
4134 *
4135 * @return object BacklinkCache
4136 */
4137 function getBacklinkCache() {
4138 if ( is_null( $this->mBacklinkCache ) ) {
4139 $this->mBacklinkCache = new BacklinkCache( $this );
4140 }
4141 return $this->mBacklinkCache;
4142 }
4143
4144 /**
4145 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4146 *
4147 * @return Boolean
4148 */
4149 public function canUseNoindex() {
4150 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4151
4152 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4153 ? $wgContentNamespaces
4154 : $wgExemptFromUserRobotsControl;
4155
4156 return !in_array( $this->mNamespace, $bannedNamespaces );
4157
4158 }
4159
4160 /**
4161 * Returns restriction types for the current Title
4162 *
4163 * @return array applicable restriction types
4164 */
4165 public function getRestrictionTypes() {
4166 if ( $this->getNamespace() == NS_SPECIAL ) {
4167 return array();
4168 }
4169
4170 $types = self::getFilteredRestrictionTypes( $this->exists() );
4171
4172 if ( $this->getNamespace() != NS_FILE ) {
4173 # Remove the upload restriction for non-file titles
4174 $types = array_diff( $types, array( 'upload' ) );
4175 }
4176
4177 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4178
4179 wfDebug( __METHOD__ . ': applicable restriction types for ' .
4180 $this->getPrefixedText() . ' are ' . implode( ',', $types ) . "\n" );
4181
4182 return $types;
4183 }
4184 /**
4185 * Get a filtered list of all restriction types supported by this wiki.
4186 * @param bool $exists True to get all restriction types that apply to
4187 * titles that do exist, False for all restriction types that apply to
4188 * titles that do not exist
4189 * @return array
4190 */
4191 public static function getFilteredRestrictionTypes( $exists = true ) {
4192 global $wgRestrictionTypes;
4193 $types = $wgRestrictionTypes;
4194 if ( $exists ) {
4195 # Remove the create restriction for existing titles
4196 $types = array_diff( $types, array( 'create' ) );
4197 } else {
4198 # Only the create and upload restrictions apply to non-existing titles
4199 $types = array_intersect( $types, array( 'create', 'upload' ) );
4200 }
4201 return $types;
4202 }
4203
4204 /**
4205 * Returns the raw sort key to be used for categories, with the specified
4206 * prefix. This will be fed to Collation::getSortKey() to get a
4207 * binary sortkey that can be used for actual sorting.
4208 *
4209 * @param $prefix string The prefix to be used, specified using
4210 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4211 * prefix.
4212 * @return string
4213 */
4214 public function getCategorySortkey( $prefix = '' ) {
4215 $unprefixed = $this->getText();
4216 if ( $prefix !== '' ) {
4217 # Separate with a line feed, so the unprefixed part is only used as
4218 # a tiebreaker when two pages have the exact same prefix.
4219 # In UCA, tab is the only character that can sort above LF
4220 # so we strip both of them from the original prefix.
4221 $prefix = strtr( $prefix, "\n\t", ' ' );
4222 return "$prefix\n$unprefixed";
4223 }
4224 return $unprefixed;
4225 }
4226 }