Merge "Fix "UTPage" creation in tests"
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * Representation of a title within %MediaWiki.
4 *
5 * See title.txt
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 */
24
25 /**
26 * Represents a title within MediaWiki.
27 * Optionally may contain an interwiki designation or namespace.
28 * @note This class can fetch various kinds of data from the database;
29 * however, it does so inefficiently.
30 * @note Consider using a TitleValue object instead. TitleValue is more lightweight
31 * and does not rely on global state or the database.
32 *
33 * @internal documentation reviewed 15 Mar 2010
34 */
35 class Title {
36 /** @var MapCacheLRU */
37 static private $titleCache = null;
38
39 /**
40 * Title::newFromText maintains a cache to avoid expensive re-normalization of
41 * commonly used titles. On a batch operation this can become a memory leak
42 * if not bounded. After hitting this many titles reset the cache.
43 */
44 const CACHE_MAX = 1000;
45
46 /**
47 * Used to be GAID_FOR_UPDATE define. Used with getArticleID() and friends
48 * to use the master DB
49 */
50 const GAID_FOR_UPDATE = 1;
51
52 /**
53 * @name Private member variables
54 * Please use the accessor functions instead.
55 * @private
56 */
57 // @{
58
59 var $mTextform = ''; // /< Text form (spaces not underscores) of the main part
60 var $mUrlform = ''; // /< URL-encoded form of the main part
61 var $mDbkeyform = ''; // /< Main part with underscores
62 var $mUserCaseDBKey; // /< DB key with the initial letter in the case specified by the user
63 var $mNamespace = NS_MAIN; // /< Namespace index, i.e. one of the NS_xxxx constants
64 var $mInterwiki = ''; // /< Interwiki prefix
65 var $mFragment = ''; // /< Title fragment (i.e. the bit after the #)
66 var $mArticleID = -1; // /< Article ID, fetched from the link cache on demand
67 var $mLatestID = false; // /< ID of most recent revision
68 var $mContentModel = false; // /< ID of the page's content model, i.e. one of the CONTENT_MODEL_XXX constants
69 private $mEstimateRevisions; // /< Estimated number of revisions; null of not loaded
70 var $mRestrictions = array(); // /< Array of groups allowed to edit this article
71 var $mOldRestrictions = false;
72 var $mCascadeRestriction; ///< Cascade restrictions on this page to included templates and images?
73 var $mCascadingRestrictions; // Caching the results of getCascadeProtectionSources
74 var $mRestrictionsExpiry = array(); ///< When do the restrictions on this page expire?
75 var $mHasCascadingRestrictions; ///< Are cascading restrictions in effect on this page?
76 var $mCascadeSources; ///< Where are the cascading restrictions coming from on this page?
77 var $mRestrictionsLoaded = false; ///< Boolean for initialisation on demand
78 var $mPrefixedText = null; ///< Text form including namespace/interwiki, initialised on demand
79 var $mTitleProtection; ///< Cached value for getTitleProtection (create protection)
80 # Don't change the following default, NS_MAIN is hardcoded in several
81 # places. See bug 696.
82 # Zero except in {{transclusion}} tags
83 var $mDefaultNamespace = NS_MAIN; // /< Namespace index when there is no namespace
84 var $mWatched = null; // /< Is $wgUser watching this page? null if unfilled, accessed through userIsWatching()
85 var $mLength = -1; // /< The page length, 0 for special pages
86 var $mRedirect = null; // /< Is the article at this title a redirect?
87 var $mNotificationTimestamp = array(); // /< Associative array of user ID -> timestamp/false
88 var $mHasSubpage; // /< Whether a page has any subpages
89 private $mPageLanguage = false; // /< The (string) language code of the page's language and content code.
90 private $mTitleValue = null; // /< A corresponding TitleValue object
91 // @}
92
93 /**
94 * B/C kludge: provide a TitleParser for use by Title.
95 * Ideally, Title would have no methods that need this.
96 * Avoid usage of this singleton by using TitleValue
97 * and the associated services when possible.
98 *
99 * @return TitleParser
100 */
101 private static function getTitleParser() {
102 global $wgContLang, $wgLocalInterwikis;
103
104 static $titleCodec = null;
105 static $titleCodecFingerprint = null;
106
107 // $wgContLang and $wgLocalInterwikis may change (especially while testing),
108 // make sure we are using the right one. To detect changes over the course
109 // of a request, we remember a fingerprint of the config used to create the
110 // codec singleton, and re-create it if the fingerprint doesn't match.
111 $fingerprint = spl_object_hash( $wgContLang ) . '|' . join( '+', $wgLocalInterwikis );
112
113 if ( $fingerprint !== $titleCodecFingerprint ) {
114 $titleCodec = null;
115 }
116
117 if ( !$titleCodec ) {
118 $titleCodec = new MediaWikiTitleCodec( $wgContLang, GenderCache::singleton(), $wgLocalInterwikis );
119 $titleCodecFingerprint = $fingerprint;
120 }
121
122 return $titleCodec;
123 }
124
125 /**
126 * B/C kludge: provide a TitleParser for use by Title.
127 * Ideally, Title would have no methods that need this.
128 * Avoid usage of this singleton by using TitleValue
129 * and the associated services when possible.
130 *
131 * @return TitleFormatter
132 */
133 private static function getTitleFormatter() {
134 //NOTE: we know that getTitleParser() returns a MediaWikiTitleCodec,
135 // which implements TitleFormatter.
136 return self::getTitleParser();
137 }
138
139 /**
140 * Constructor
141 */
142 /*protected*/ function __construct() { }
143
144 /**
145 * Create a new Title from a prefixed DB key
146 *
147 * @param string $key the database key, which has underscores
148 * instead of spaces, possibly including namespace and
149 * interwiki prefixes
150 * @return Title, or NULL on an error
151 */
152 public static function newFromDBkey( $key ) {
153 $t = new Title();
154 $t->mDbkeyform = $key;
155 if ( $t->secureAndSplit() ) {
156 return $t;
157 } else {
158 return null;
159 }
160 }
161
162 /**
163 * Create a new Title from a TitleValue
164 *
165 * @param TitleValue $titleValue, assumed to be safe.
166 *
167 * @return Title
168 */
169 public static function newFromTitleValue( TitleValue $titleValue ) {
170 return self::makeTitle(
171 $titleValue->getNamespace(),
172 $titleValue->getText(),
173 $titleValue->getFragment() );
174 }
175
176 /**
177 * Create a new Title from text, such as what one would find in a link. De-
178 * codes any HTML entities in the text.
179 *
180 * @param string $text the link text; spaces, prefixes, and an
181 * initial ':' indicating the main namespace are accepted.
182 * @param int $defaultNamespace the namespace to use if none is specified
183 * by a prefix. If you want to force a specific namespace even if
184 * $text might begin with a namespace prefix, use makeTitle() or
185 * makeTitleSafe().
186 * @throws MWException
187 * @return Title|null - Title or null on an error.
188 */
189 public static function newFromText( $text, $defaultNamespace = NS_MAIN ) {
190 if ( is_object( $text ) ) {
191 throw new MWException( 'Title::newFromText given an object' );
192 }
193
194 $cache = self::getTitleCache();
195
196 /**
197 * Wiki pages often contain multiple links to the same page.
198 * Title normalization and parsing can become expensive on
199 * pages with many links, so we can save a little time by
200 * caching them.
201 *
202 * In theory these are value objects and won't get changed...
203 */
204 if ( $defaultNamespace == NS_MAIN && $cache->has( $text ) ) {
205 return $cache->get( $text );
206 }
207
208 # Convert things like &eacute; &#257; or &#x3017; into normalized (bug 14952) text
209 $filteredText = Sanitizer::decodeCharReferencesAndNormalize( $text );
210
211 $t = new Title();
212 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
213 $t->mDefaultNamespace = intval( $defaultNamespace );
214
215 if ( $t->secureAndSplit() ) {
216 if ( $defaultNamespace == NS_MAIN ) {
217 $cache->set( $text, $t );
218 }
219 return $t;
220 } else {
221 $ret = null;
222 return $ret;
223 }
224 }
225
226 /**
227 * THIS IS NOT THE FUNCTION YOU WANT. Use Title::newFromText().
228 *
229 * Example of wrong and broken code:
230 * $title = Title::newFromURL( $wgRequest->getVal( 'title' ) );
231 *
232 * Example of right code:
233 * $title = Title::newFromText( $wgRequest->getVal( 'title' ) );
234 *
235 * Create a new Title from URL-encoded text. Ensures that
236 * the given title's length does not exceed the maximum.
237 *
238 * @param string $url the title, as might be taken from a URL
239 * @return Title the new object, or NULL on an error
240 */
241 public static function newFromURL( $url ) {
242 $t = new Title();
243
244 # For compatibility with old buggy URLs. "+" is usually not valid in titles,
245 # but some URLs used it as a space replacement and they still come
246 # from some external search tools.
247 if ( strpos( self::legalChars(), '+' ) === false ) {
248 $url = str_replace( '+', ' ', $url );
249 }
250
251 $t->mDbkeyform = str_replace( ' ', '_', $url );
252 if ( $t->secureAndSplit() ) {
253 return $t;
254 } else {
255 return null;
256 }
257 }
258
259 /**
260 * @return MapCacheLRU
261 */
262 private static function getTitleCache() {
263 if ( self::$titleCache == null ) {
264 self::$titleCache = new MapCacheLRU( self::CACHE_MAX );
265 }
266 return self::$titleCache;
267 }
268
269 /**
270 * Returns a list of fields that are to be selected for initializing Title objects or LinkCache entries.
271 * Uses $wgContentHandlerUseDB to determine whether to include page_content_model.
272 *
273 * @return array
274 */
275 protected static function getSelectFields() {
276 global $wgContentHandlerUseDB;
277
278 $fields = array(
279 'page_namespace', 'page_title', 'page_id',
280 'page_len', 'page_is_redirect', 'page_latest',
281 );
282
283 if ( $wgContentHandlerUseDB ) {
284 $fields[] = 'page_content_model';
285 }
286
287 return $fields;
288 }
289
290 /**
291 * Create a new Title from an article ID
292 *
293 * @param int $id the page_id corresponding to the Title to create
294 * @param int $flags use Title::GAID_FOR_UPDATE to use master
295 * @return Title|null the new object, or NULL on an error
296 */
297 public static function newFromID( $id, $flags = 0 ) {
298 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
299 $row = $db->selectRow(
300 'page',
301 self::getSelectFields(),
302 array( 'page_id' => $id ),
303 __METHOD__
304 );
305 if ( $row !== false ) {
306 $title = Title::newFromRow( $row );
307 } else {
308 $title = null;
309 }
310 return $title;
311 }
312
313 /**
314 * Make an array of titles from an array of IDs
315 *
316 * @param array $ids of Int Array of IDs
317 * @return Array of Titles
318 */
319 public static function newFromIDs( $ids ) {
320 if ( !count( $ids ) ) {
321 return array();
322 }
323 $dbr = wfGetDB( DB_SLAVE );
324
325 $res = $dbr->select(
326 'page',
327 self::getSelectFields(),
328 array( 'page_id' => $ids ),
329 __METHOD__
330 );
331
332 $titles = array();
333 foreach ( $res as $row ) {
334 $titles[] = Title::newFromRow( $row );
335 }
336 return $titles;
337 }
338
339 /**
340 * Make a Title object from a DB row
341 *
342 * @param stdClass $row Object database row (needs at least page_title,page_namespace)
343 * @return Title corresponding Title
344 */
345 public static function newFromRow( $row ) {
346 $t = self::makeTitle( $row->page_namespace, $row->page_title );
347 $t->loadFromRow( $row );
348 return $t;
349 }
350
351 /**
352 * Load Title object fields from a DB row.
353 * If false is given, the title will be treated as non-existing.
354 *
355 * @param $row stdClass|bool database row
356 */
357 public function loadFromRow( $row ) {
358 if ( $row ) { // page found
359 if ( isset( $row->page_id ) ) {
360 $this->mArticleID = (int)$row->page_id;
361 }
362 if ( isset( $row->page_len ) ) {
363 $this->mLength = (int)$row->page_len;
364 }
365 if ( isset( $row->page_is_redirect ) ) {
366 $this->mRedirect = (bool)$row->page_is_redirect;
367 }
368 if ( isset( $row->page_latest ) ) {
369 $this->mLatestID = (int)$row->page_latest;
370 }
371 if ( isset( $row->page_content_model ) ) {
372 $this->mContentModel = strval( $row->page_content_model );
373 } else {
374 $this->mContentModel = false; # initialized lazily in getContentModel()
375 }
376 } else { // page not found
377 $this->mArticleID = 0;
378 $this->mLength = 0;
379 $this->mRedirect = false;
380 $this->mLatestID = 0;
381 $this->mContentModel = false; # initialized lazily in getContentModel()
382 }
383 }
384
385 /**
386 * Create a new Title from a namespace index and a DB key.
387 * It's assumed that $ns and $title are *valid*, for instance when
388 * they came directly from the database or a special page name.
389 * For convenience, spaces are converted to underscores so that
390 * eg user_text fields can be used directly.
391 *
392 * @param int $ns the namespace of the article
393 * @param string $title the unprefixed database key form
394 * @param string $fragment the link fragment (after the "#")
395 * @param string $interwiki the interwiki prefix
396 * @return Title the new object
397 */
398 public static function &makeTitle( $ns, $title, $fragment = '', $interwiki = '' ) {
399 $t = new Title();
400 $t->mInterwiki = $interwiki;
401 $t->mFragment = $fragment;
402 $t->mNamespace = $ns = intval( $ns );
403 $t->mDbkeyform = str_replace( ' ', '_', $title );
404 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
405 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
406 $t->mTextform = str_replace( '_', ' ', $title );
407 $t->mContentModel = false; # initialized lazily in getContentModel()
408 return $t;
409 }
410
411 /**
412 * Create a new Title from a namespace index and a DB key.
413 * The parameters will be checked for validity, which is a bit slower
414 * than makeTitle() but safer for user-provided data.
415 *
416 * @param int $ns the namespace of the article
417 * @param string $title database key form
418 * @param string $fragment the link fragment (after the "#")
419 * @param string $interwiki interwiki prefix
420 * @return Title the new object, or NULL on an error
421 */
422 public static function makeTitleSafe( $ns, $title, $fragment = '', $interwiki = '' ) {
423 if ( !MWNamespace::exists( $ns ) ) {
424 return null;
425 }
426
427 $t = new Title();
428 $t->mDbkeyform = Title::makeName( $ns, $title, $fragment, $interwiki );
429 if ( $t->secureAndSplit() ) {
430 return $t;
431 } else {
432 return null;
433 }
434 }
435
436 /**
437 * Create a new Title for the Main Page
438 *
439 * @return Title the new object
440 */
441 public static function newMainPage() {
442 $title = Title::newFromText( wfMessage( 'mainpage' )->inContentLanguage()->text() );
443 // Don't give fatal errors if the message is broken
444 if ( !$title ) {
445 $title = Title::newFromText( 'Main Page' );
446 }
447 return $title;
448 }
449
450 /**
451 * Extract a redirect destination from a string and return the
452 * Title, or null if the text doesn't contain a valid redirect
453 * This will only return the very next target, useful for
454 * the redirect table and other checks that don't need full recursion
455 *
456 * @param string $text Text with possible redirect
457 * @return Title: The corresponding Title
458 * @deprecated since 1.21, use Content::getRedirectTarget instead.
459 */
460 public static function newFromRedirect( $text ) {
461 ContentHandler::deprecated( __METHOD__, '1.21' );
462
463 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
464 return $content->getRedirectTarget();
465 }
466
467 /**
468 * Extract a redirect destination from a string and return the
469 * Title, or null if the text doesn't contain a valid redirect
470 * This will recurse down $wgMaxRedirects times or until a non-redirect target is hit
471 * in order to provide (hopefully) the Title of the final destination instead of another redirect
472 *
473 * @param string $text Text with possible redirect
474 * @return Title
475 * @deprecated since 1.21, use Content::getUltimateRedirectTarget instead.
476 */
477 public static function newFromRedirectRecurse( $text ) {
478 ContentHandler::deprecated( __METHOD__, '1.21' );
479
480 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
481 return $content->getUltimateRedirectTarget();
482 }
483
484 /**
485 * Extract a redirect destination from a string and return an
486 * array of Titles, or null if the text doesn't contain a valid redirect
487 * The last element in the array is the final destination after all redirects
488 * have been resolved (up to $wgMaxRedirects times)
489 *
490 * @param string $text Text with possible redirect
491 * @return Array of Titles, with the destination last
492 * @deprecated since 1.21, use Content::getRedirectChain instead.
493 */
494 public static function newFromRedirectArray( $text ) {
495 ContentHandler::deprecated( __METHOD__, '1.21' );
496
497 $content = ContentHandler::makeContent( $text, null, CONTENT_MODEL_WIKITEXT );
498 return $content->getRedirectChain();
499 }
500
501 /**
502 * Get the prefixed DB key associated with an ID
503 *
504 * @param int $id the page_id of the article
505 * @return Title an object representing the article, or NULL if no such article was found
506 */
507 public static function nameOf( $id ) {
508 $dbr = wfGetDB( DB_SLAVE );
509
510 $s = $dbr->selectRow(
511 'page',
512 array( 'page_namespace', 'page_title' ),
513 array( 'page_id' => $id ),
514 __METHOD__
515 );
516 if ( $s === false ) {
517 return null;
518 }
519
520 $n = self::makeName( $s->page_namespace, $s->page_title );
521 return $n;
522 }
523
524 /**
525 * Get a regex character class describing the legal characters in a link
526 *
527 * @return String the list of characters, not delimited
528 */
529 public static function legalChars() {
530 global $wgLegalTitleChars;
531 return $wgLegalTitleChars;
532 }
533
534 /**
535 * Returns a simple regex that will match on characters and sequences invalid in titles.
536 * Note that this doesn't pick up many things that could be wrong with titles, but that
537 * replacing this regex with something valid will make many titles valid.
538 *
539 * @todo: move this into MediaWikiTitleCodec
540 *
541 * @return String regex string
542 */
543 static function getTitleInvalidRegex() {
544 static $rxTc = false;
545 if ( !$rxTc ) {
546 # Matching titles will be held as illegal.
547 $rxTc = '/' .
548 # Any character not allowed is forbidden...
549 '[^' . self::legalChars() . ']' .
550 # URL percent encoding sequences interfere with the ability
551 # to round-trip titles -- you can't link to them consistently.
552 '|%[0-9A-Fa-f]{2}' .
553 # XML/HTML character references produce similar issues.
554 '|&[A-Za-z0-9\x80-\xff]+;' .
555 '|&#[0-9]+;' .
556 '|&#x[0-9A-Fa-f]+;' .
557 '/S';
558 }
559
560 return $rxTc;
561 }
562
563 /**
564 * Utility method for converting a character sequence from bytes to Unicode.
565 *
566 * Primary usecase being converting $wgLegalTitleChars to a sequence usable in
567 * javascript, as PHP uses UTF-8 bytes where javascript uses Unicode code units.
568 *
569 * @param string $byteClass
570 * @return string
571 */
572 public static function convertByteClassToUnicodeClass( $byteClass ) {
573 $length = strlen( $byteClass );
574 // Input token queue
575 $x0 = $x1 = $x2 = '';
576 // Decoded queue
577 $d0 = $d1 = $d2 = '';
578 // Decoded integer codepoints
579 $ord0 = $ord1 = $ord2 = 0;
580 // Re-encoded queue
581 $r0 = $r1 = $r2 = '';
582 // Output
583 $out = '';
584 // Flags
585 $allowUnicode = false;
586 for ( $pos = 0; $pos < $length; $pos++ ) {
587 // Shift the queues down
588 $x2 = $x1;
589 $x1 = $x0;
590 $d2 = $d1;
591 $d1 = $d0;
592 $ord2 = $ord1;
593 $ord1 = $ord0;
594 $r2 = $r1;
595 $r1 = $r0;
596 // Load the current input token and decoded values
597 $inChar = $byteClass[$pos];
598 if ( $inChar == '\\' ) {
599 if ( preg_match( '/x([0-9a-fA-F]{2})/A', $byteClass, $m, 0, $pos + 1 ) ) {
600 $x0 = $inChar . $m[0];
601 $d0 = chr( hexdec( $m[1] ) );
602 $pos += strlen( $m[0] );
603 } elseif ( preg_match( '/[0-7]{3}/A', $byteClass, $m, 0, $pos + 1 ) ) {
604 $x0 = $inChar . $m[0];
605 $d0 = chr( octdec( $m[0] ) );
606 $pos += strlen( $m[0] );
607 } elseif ( $pos + 1 >= $length ) {
608 $x0 = $d0 = '\\';
609 } else {
610 $d0 = $byteClass[$pos + 1];
611 $x0 = $inChar . $d0;
612 $pos += 1;
613 }
614 } else {
615 $x0 = $d0 = $inChar;
616 }
617 $ord0 = ord( $d0 );
618 // Load the current re-encoded value
619 if ( $ord0 < 32 || $ord0 == 0x7f ) {
620 $r0 = sprintf( '\x%02x', $ord0 );
621 } elseif ( $ord0 >= 0x80 ) {
622 // Allow unicode if a single high-bit character appears
623 $r0 = sprintf( '\x%02x', $ord0 );
624 $allowUnicode = true;
625 } elseif ( strpos( '-\\[]^', $d0 ) !== false ) {
626 $r0 = '\\' . $d0;
627 } else {
628 $r0 = $d0;
629 }
630 // Do the output
631 if ( $x0 !== '' && $x1 === '-' && $x2 !== '' ) {
632 // Range
633 if ( $ord2 > $ord0 ) {
634 // Empty range
635 } elseif ( $ord0 >= 0x80 ) {
636 // Unicode range
637 $allowUnicode = true;
638 if ( $ord2 < 0x80 ) {
639 // Keep the non-unicode section of the range
640 $out .= "$r2-\\x7F";
641 }
642 } else {
643 // Normal range
644 $out .= "$r2-$r0";
645 }
646 // Reset state to the initial value
647 $x0 = $x1 = $d0 = $d1 = $r0 = $r1 = '';
648 } elseif ( $ord2 < 0x80 ) {
649 // ASCII character
650 $out .= $r2;
651 }
652 }
653 if ( $ord1 < 0x80 ) {
654 $out .= $r1;
655 }
656 if ( $ord0 < 0x80 ) {
657 $out .= $r0;
658 }
659 if ( $allowUnicode ) {
660 $out .= '\u0080-\uFFFF';
661 }
662 return $out;
663 }
664
665 /**
666 * Make a prefixed DB key from a DB key and a namespace index
667 *
668 * @param int $ns numerical representation of the namespace
669 * @param string $title the DB key form the title
670 * @param string $fragment The link fragment (after the "#")
671 * @param string $interwiki The interwiki prefix
672 * @return String the prefixed form of the title
673 */
674 public static function makeName( $ns, $title, $fragment = '', $interwiki = '' ) {
675 global $wgContLang;
676
677 $namespace = $wgContLang->getNsText( $ns );
678 $name = $namespace == '' ? $title : "$namespace:$title";
679 if ( strval( $interwiki ) != '' ) {
680 $name = "$interwiki:$name";
681 }
682 if ( strval( $fragment ) != '' ) {
683 $name .= '#' . $fragment;
684 }
685 return $name;
686 }
687
688 /**
689 * Escape a text fragment, say from a link, for a URL
690 *
691 * @param string $fragment containing a URL or link fragment (after the "#")
692 * @return String: escaped string
693 */
694 static function escapeFragmentForURL( $fragment ) {
695 # Note that we don't urlencode the fragment. urlencoded Unicode
696 # fragments appear not to work in IE (at least up to 7) or in at least
697 # one version of Opera 9.x. The W3C validator, for one, doesn't seem
698 # to care if they aren't encoded.
699 return Sanitizer::escapeId( $fragment, 'noninitial' );
700 }
701
702 /**
703 * Callback for usort() to do title sorts by (namespace, title)
704 *
705 * @param $a Title
706 * @param $b Title
707 *
708 * @return Integer: result of string comparison, or namespace comparison
709 */
710 public static function compare( $a, $b ) {
711 if ( $a->getNamespace() == $b->getNamespace() ) {
712 return strcmp( $a->getText(), $b->getText() );
713 } else {
714 return $a->getNamespace() - $b->getNamespace();
715 }
716 }
717
718 /**
719 * Determine whether the object refers to a page within
720 * this project.
721 *
722 * @return Bool TRUE if this is an in-project interwiki link or a wikilink, FALSE otherwise
723 */
724 public function isLocal() {
725 if ( $this->isExternal() ) {
726 $iw = Interwiki::fetch( $this->mInterwiki );
727 if ( $iw ) {
728 return $iw->isLocal();
729 }
730 }
731 return true;
732 }
733
734 /**
735 * Is this Title interwiki?
736 *
737 * @return Bool
738 */
739 public function isExternal() {
740 return $this->mInterwiki !== '';
741 }
742
743 /**
744 * Get the interwiki prefix
745 *
746 * Use Title::isExternal to check if a interwiki is set
747 *
748 * @return String Interwiki prefix
749 */
750 public function getInterwiki() {
751 return $this->mInterwiki;
752 }
753
754 /**
755 * Determine whether the object refers to a page within
756 * this project and is transcludable.
757 *
758 * @return Bool TRUE if this is transcludable
759 */
760 public function isTrans() {
761 if ( !$this->isExternal() ) {
762 return false;
763 }
764
765 return Interwiki::fetch( $this->mInterwiki )->isTranscludable();
766 }
767
768 /**
769 * Returns the DB name of the distant wiki which owns the object.
770 *
771 * @return String the DB name
772 */
773 public function getTransWikiID() {
774 if ( !$this->isExternal() ) {
775 return false;
776 }
777
778 return Interwiki::fetch( $this->mInterwiki )->getWikiID();
779 }
780
781 /**
782 * Get a TitleValue object representing this Title.
783 *
784 * @note: Not all valid Titles have a corresponding valid TitleValue
785 * (e.g. TitleValues cannot represent page-local links that have a
786 * fragment but no title text).
787 *
788 * @return TitleValue|null
789 */
790 public function getTitleValue() {
791 if ( $this->mTitleValue === null ) {
792 try {
793 $this->mTitleValue = new TitleValue(
794 $this->getNamespace(),
795 $this->getDBkey(),
796 $this->getFragment() );
797 } catch ( InvalidArgumentException $ex ) {
798 wfDebug( __METHOD__ . ': Can\'t create a TitleValue for [[' .
799 $this->getPrefixedText() . ']]: ' . $ex->getMessage() . "\n" );
800 }
801 }
802
803 return $this->mTitleValue;
804 }
805
806 /**
807 * Get the text form (spaces not underscores) of the main part
808 *
809 * @return String Main part of the title
810 */
811 public function getText() {
812 return $this->mTextform;
813 }
814
815 /**
816 * Get the URL-encoded form of the main part
817 *
818 * @return String Main part of the title, URL-encoded
819 */
820 public function getPartialURL() {
821 return $this->mUrlform;
822 }
823
824 /**
825 * Get the main part with underscores
826 *
827 * @return String: Main part of the title, with underscores
828 */
829 public function getDBkey() {
830 return $this->mDbkeyform;
831 }
832
833 /**
834 * Get the DB key with the initial letter case as specified by the user
835 *
836 * @return String DB key
837 */
838 function getUserCaseDBKey() {
839 if ( !is_null( $this->mUserCaseDBKey ) ) {
840 return $this->mUserCaseDBKey;
841 } else {
842 // If created via makeTitle(), $this->mUserCaseDBKey is not set.
843 return $this->mDbkeyform;
844 }
845 }
846
847 /**
848 * Get the namespace index, i.e. one of the NS_xxxx constants.
849 *
850 * @return Integer: Namespace index
851 */
852 public function getNamespace() {
853 return $this->mNamespace;
854 }
855
856 /**
857 * Get the page's content model id, see the CONTENT_MODEL_XXX constants.
858 *
859 * @throws MWException
860 * @return String: Content model id
861 */
862 public function getContentModel() {
863 if ( !$this->mContentModel ) {
864 $linkCache = LinkCache::singleton();
865 $this->mContentModel = $linkCache->getGoodLinkFieldObj( $this, 'model' );
866 }
867
868 if ( !$this->mContentModel ) {
869 $this->mContentModel = ContentHandler::getDefaultModelFor( $this );
870 }
871
872 if ( !$this->mContentModel ) {
873 throw new MWException( 'Failed to determine content model!' );
874 }
875
876 return $this->mContentModel;
877 }
878
879 /**
880 * Convenience method for checking a title's content model name
881 *
882 * @param string $id The content model ID (use the CONTENT_MODEL_XXX constants).
883 * @return Boolean true if $this->getContentModel() == $id
884 */
885 public function hasContentModel( $id ) {
886 return $this->getContentModel() == $id;
887 }
888
889 /**
890 * Get the namespace text
891 *
892 * @return String: Namespace text
893 */
894 public function getNsText() {
895 if ( $this->isExternal() ) {
896 // This probably shouldn't even happen. ohh man, oh yuck.
897 // But for interwiki transclusion it sometimes does.
898 // Shit. Shit shit shit.
899 //
900 // Use the canonical namespaces if possible to try to
901 // resolve a foreign namespace.
902 if ( MWNamespace::exists( $this->mNamespace ) ) {
903 return MWNamespace::getCanonicalName( $this->mNamespace );
904 }
905 }
906
907 try {
908 $formatter = $this->getTitleFormatter();
909 return $formatter->getNamespaceName( $this->mNamespace, $this->mDbkeyform );
910 } catch ( InvalidArgumentException $ex ) {
911 wfDebug( __METHOD__ . ': ' . $ex->getMessage() . "\n" );
912 return false;
913 }
914 }
915
916 /**
917 * Get the namespace text of the subject (rather than talk) page
918 *
919 * @return String Namespace text
920 */
921 public function getSubjectNsText() {
922 global $wgContLang;
923 return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
924 }
925
926 /**
927 * Get the namespace text of the talk page
928 *
929 * @return String Namespace text
930 */
931 public function getTalkNsText() {
932 global $wgContLang;
933 return $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) );
934 }
935
936 /**
937 * Could this title have a corresponding talk page?
938 *
939 * @return Bool TRUE or FALSE
940 */
941 public function canTalk() {
942 return MWNamespace::canTalk( $this->mNamespace );
943 }
944
945 /**
946 * Is this in a namespace that allows actual pages?
947 *
948 * @return Bool
949 * @internal note -- uses hardcoded namespace index instead of constants
950 */
951 public function canExist() {
952 return $this->mNamespace >= NS_MAIN;
953 }
954
955 /**
956 * Can this title be added to a user's watchlist?
957 *
958 * @return Bool TRUE or FALSE
959 */
960 public function isWatchable() {
961 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
962 }
963
964 /**
965 * Returns true if this is a special page.
966 *
967 * @return boolean
968 */
969 public function isSpecialPage() {
970 return $this->getNamespace() == NS_SPECIAL;
971 }
972
973 /**
974 * Returns true if this title resolves to the named special page
975 *
976 * @param string $name The special page name
977 * @return boolean
978 */
979 public function isSpecial( $name ) {
980 if ( $this->isSpecialPage() ) {
981 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
982 if ( $name == $thisName ) {
983 return true;
984 }
985 }
986 return false;
987 }
988
989 /**
990 * If the Title refers to a special page alias which is not the local default, resolve
991 * the alias, and localise the name as necessary. Otherwise, return $this
992 *
993 * @return Title
994 */
995 public function fixSpecialName() {
996 if ( $this->isSpecialPage() ) {
997 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
998 if ( $canonicalName ) {
999 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
1000 if ( $localName != $this->mDbkeyform ) {
1001 return Title::makeTitle( NS_SPECIAL, $localName );
1002 }
1003 }
1004 }
1005 return $this;
1006 }
1007
1008 /**
1009 * Returns true if the title is inside the specified namespace.
1010 *
1011 * Please make use of this instead of comparing to getNamespace()
1012 * This function is much more resistant to changes we may make
1013 * to namespaces than code that makes direct comparisons.
1014 * @param int $ns The namespace
1015 * @return bool
1016 * @since 1.19
1017 */
1018 public function inNamespace( $ns ) {
1019 return MWNamespace::equals( $this->getNamespace(), $ns );
1020 }
1021
1022 /**
1023 * Returns true if the title is inside one of the specified namespaces.
1024 *
1025 * @param ...$namespaces The namespaces to check for
1026 * @return bool
1027 * @since 1.19
1028 */
1029 public function inNamespaces( /* ... */ ) {
1030 $namespaces = func_get_args();
1031 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1032 $namespaces = $namespaces[0];
1033 }
1034
1035 foreach ( $namespaces as $ns ) {
1036 if ( $this->inNamespace( $ns ) ) {
1037 return true;
1038 }
1039 }
1040
1041 return false;
1042 }
1043
1044 /**
1045 * Returns true if the title has the same subject namespace as the
1046 * namespace specified.
1047 * For example this method will take NS_USER and return true if namespace
1048 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1049 * as their subject namespace.
1050 *
1051 * This is MUCH simpler than individually testing for equivalence
1052 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1053 * @since 1.19
1054 * @param $ns int
1055 * @return bool
1056 */
1057 public function hasSubjectNamespace( $ns ) {
1058 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
1059 }
1060
1061 /**
1062 * Is this Title in a namespace which contains content?
1063 * In other words, is this a content page, for the purposes of calculating
1064 * statistics, etc?
1065 *
1066 * @return Boolean
1067 */
1068 public function isContentPage() {
1069 return MWNamespace::isContent( $this->getNamespace() );
1070 }
1071
1072 /**
1073 * Would anybody with sufficient privileges be able to move this page?
1074 * Some pages just aren't movable.
1075 *
1076 * @return Bool TRUE or FALSE
1077 */
1078 public function isMovable() {
1079 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->isExternal() ) {
1080 // Interwiki title or immovable namespace. Hooks don't get to override here
1081 return false;
1082 }
1083
1084 $result = true;
1085 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
1086 return $result;
1087 }
1088
1089 /**
1090 * Is this the mainpage?
1091 * @note Title::newFromText seems to be sufficiently optimized by the title
1092 * cache that we don't need to over-optimize by doing direct comparisons and
1093 * accidentally creating new bugs where $title->equals( Title::newFromText() )
1094 * ends up reporting something differently than $title->isMainPage();
1095 *
1096 * @since 1.18
1097 * @return Bool
1098 */
1099 public function isMainPage() {
1100 return $this->equals( Title::newMainPage() );
1101 }
1102
1103 /**
1104 * Is this a subpage?
1105 *
1106 * @return Bool
1107 */
1108 public function isSubpage() {
1109 return MWNamespace::hasSubpages( $this->mNamespace )
1110 ? strpos( $this->getText(), '/' ) !== false
1111 : false;
1112 }
1113
1114 /**
1115 * Is this a conversion table for the LanguageConverter?
1116 *
1117 * @return Bool
1118 */
1119 public function isConversionTable() {
1120 // @todo ConversionTable should become a separate content model.
1121
1122 return $this->getNamespace() == NS_MEDIAWIKI &&
1123 strpos( $this->getText(), 'Conversiontable/' ) === 0;
1124 }
1125
1126 /**
1127 * Does that page contain wikitext, or it is JS, CSS or whatever?
1128 *
1129 * @return Bool
1130 */
1131 public function isWikitextPage() {
1132 return $this->hasContentModel( CONTENT_MODEL_WIKITEXT );
1133 }
1134
1135 /**
1136 * Could this page contain custom CSS or JavaScript for the global UI.
1137 * This is generally true for pages in the MediaWiki namespace having CONTENT_MODEL_CSS
1138 * or CONTENT_MODEL_JAVASCRIPT.
1139 *
1140 * This method does *not* return true for per-user JS/CSS. Use isCssJsSubpage() for that!
1141 *
1142 * Note that this method should not return true for pages that contain and show "inactive" CSS or JS.
1143 *
1144 * @return Bool
1145 */
1146 public function isCssOrJsPage() {
1147 $isCssOrJsPage = NS_MEDIAWIKI == $this->mNamespace
1148 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1149 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1150
1151 #NOTE: this hook is also called in ContentHandler::getDefaultModel. It's called here again to make sure
1152 # hook functions can force this method to return true even outside the mediawiki namespace.
1153
1154 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$isCssOrJsPage ) );
1155
1156 return $isCssOrJsPage;
1157 }
1158
1159 /**
1160 * Is this a .css or .js subpage of a user page?
1161 * @return Bool
1162 */
1163 public function isCssJsSubpage() {
1164 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1165 && ( $this->hasContentModel( CONTENT_MODEL_CSS )
1166 || $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) ) );
1167 }
1168
1169 /**
1170 * Trim down a .css or .js subpage title to get the corresponding skin name
1171 *
1172 * @return string containing skin name from .css or .js subpage title
1173 */
1174 public function getSkinFromCssJsSubpage() {
1175 $subpage = explode( '/', $this->mTextform );
1176 $subpage = $subpage[count( $subpage ) - 1];
1177 $lastdot = strrpos( $subpage, '.' );
1178 if ( $lastdot === false ) {
1179 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
1180 }
1181 return substr( $subpage, 0, $lastdot );
1182 }
1183
1184 /**
1185 * Is this a .css subpage of a user page?
1186 *
1187 * @return Bool
1188 */
1189 public function isCssSubpage() {
1190 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1191 && $this->hasContentModel( CONTENT_MODEL_CSS ) );
1192 }
1193
1194 /**
1195 * Is this a .js subpage of a user page?
1196 *
1197 * @return Bool
1198 */
1199 public function isJsSubpage() {
1200 return ( NS_USER == $this->mNamespace && $this->isSubpage()
1201 && $this->hasContentModel( CONTENT_MODEL_JAVASCRIPT ) );
1202 }
1203
1204 /**
1205 * Is this a talk page of some sort?
1206 *
1207 * @return Bool
1208 */
1209 public function isTalkPage() {
1210 return MWNamespace::isTalk( $this->getNamespace() );
1211 }
1212
1213 /**
1214 * Get a Title object associated with the talk page of this article
1215 *
1216 * @return Title the object for the talk page
1217 */
1218 public function getTalkPage() {
1219 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1220 }
1221
1222 /**
1223 * Get a title object associated with the subject page of this
1224 * talk page
1225 *
1226 * @return Title the object for the subject page
1227 */
1228 public function getSubjectPage() {
1229 // Is this the same title?
1230 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
1231 if ( $this->getNamespace() == $subjectNS ) {
1232 return $this;
1233 }
1234 return Title::makeTitle( $subjectNS, $this->getDBkey() );
1235 }
1236
1237 /**
1238 * Get the default namespace index, for when there is no namespace
1239 *
1240 * @return Int Default namespace index
1241 */
1242 public function getDefaultNamespace() {
1243 return $this->mDefaultNamespace;
1244 }
1245
1246 /**
1247 * Get the Title fragment (i.e.\ the bit after the #) in text form
1248 *
1249 * Use Title::hasFragment to check for a fragment
1250 *
1251 * @return String Title fragment
1252 */
1253 public function getFragment() {
1254 return $this->mFragment;
1255 }
1256
1257 /**
1258 * Check if a Title fragment is set
1259 *
1260 * @return bool
1261 * @since 1.23
1262 */
1263 public function hasFragment() {
1264 return $this->mFragment !== '';
1265 }
1266
1267 /**
1268 * Get the fragment in URL form, including the "#" character if there is one
1269 * @return String Fragment in URL form
1270 */
1271 public function getFragmentForURL() {
1272 if ( !$this->hasFragment() ) {
1273 return '';
1274 } else {
1275 return '#' . Title::escapeFragmentForURL( $this->getFragment() );
1276 }
1277 }
1278
1279 /**
1280 * Set the fragment for this title. Removes the first character from the
1281 * specified fragment before setting, so it assumes you're passing it with
1282 * an initial "#".
1283 *
1284 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
1285 * Still in active use privately.
1286 *
1287 * @param string $fragment text
1288 */
1289 public function setFragment( $fragment ) {
1290 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
1291 }
1292
1293 /**
1294 * Prefix some arbitrary text with the namespace or interwiki prefix
1295 * of this object
1296 *
1297 * @param string $name the text
1298 * @return String the prefixed text
1299 * @private
1300 */
1301 private function prefix( $name ) {
1302 $p = '';
1303 if ( $this->isExternal() ) {
1304 $p = $this->mInterwiki . ':';
1305 }
1306
1307 if ( 0 != $this->mNamespace ) {
1308 $p .= $this->getNsText() . ':';
1309 }
1310 return $p . $name;
1311 }
1312
1313 /**
1314 * Get the prefixed database key form
1315 *
1316 * @return String the prefixed title, with underscores and
1317 * any interwiki and namespace prefixes
1318 */
1319 public function getPrefixedDBkey() {
1320 $s = $this->prefix( $this->mDbkeyform );
1321 $s = str_replace( ' ', '_', $s );
1322 return $s;
1323 }
1324
1325 /**
1326 * Get the prefixed title with spaces.
1327 * This is the form usually used for display
1328 *
1329 * @return String the prefixed title, with spaces
1330 */
1331 public function getPrefixedText() {
1332 if ( $this->mPrefixedText === null ) {
1333 $s = $this->prefix( $this->mTextform );
1334 $s = str_replace( '_', ' ', $s );
1335 $this->mPrefixedText = $s;
1336 }
1337 return $this->mPrefixedText;
1338 }
1339
1340 /**
1341 * Return a string representation of this title
1342 *
1343 * @return String representation of this title
1344 */
1345 public function __toString() {
1346 return $this->getPrefixedText();
1347 }
1348
1349 /**
1350 * Get the prefixed title with spaces, plus any fragment
1351 * (part beginning with '#')
1352 *
1353 * @return String the prefixed title, with spaces and the fragment, including '#'
1354 */
1355 public function getFullText() {
1356 $text = $this->getPrefixedText();
1357 if ( $this->hasFragment() ) {
1358 $text .= '#' . $this->getFragment();
1359 }
1360 return $text;
1361 }
1362
1363 /**
1364 * Get the root page name text without a namespace, i.e. the leftmost part before any slashes
1365 *
1366 * @par Example:
1367 * @code
1368 * Title::newFromText('User:Foo/Bar/Baz')->getRootText();
1369 * # returns: 'Foo'
1370 * @endcode
1371 *
1372 * @return String Root name
1373 * @since 1.20
1374 */
1375 public function getRootText() {
1376 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1377 return $this->getText();
1378 }
1379
1380 return strtok( $this->getText(), '/' );
1381 }
1382
1383 /**
1384 * Get the root page name title, i.e. the leftmost part before any slashes
1385 *
1386 * @par Example:
1387 * @code
1388 * Title::newFromText('User:Foo/Bar/Baz')->getRootTitle();
1389 * # returns: Title{User:Foo}
1390 * @endcode
1391 *
1392 * @return Title Root title
1393 * @since 1.20
1394 */
1395 public function getRootTitle() {
1396 return Title::makeTitle( $this->getNamespace(), $this->getRootText() );
1397 }
1398
1399 /**
1400 * Get the base page name without a namespace, i.e. the part before the subpage name
1401 *
1402 * @par Example:
1403 * @code
1404 * Title::newFromText('User:Foo/Bar/Baz')->getBaseText();
1405 * # returns: 'Foo/Bar'
1406 * @endcode
1407 *
1408 * @return String Base name
1409 */
1410 public function getBaseText() {
1411 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1412 return $this->getText();
1413 }
1414
1415 $parts = explode( '/', $this->getText() );
1416 # Don't discard the real title if there's no subpage involved
1417 if ( count( $parts ) > 1 ) {
1418 unset( $parts[count( $parts ) - 1] );
1419 }
1420 return implode( '/', $parts );
1421 }
1422
1423 /**
1424 * Get the base page name title, i.e. the part before the subpage name
1425 *
1426 * @par Example:
1427 * @code
1428 * Title::newFromText('User:Foo/Bar/Baz')->getBaseTitle();
1429 * # returns: Title{User:Foo/Bar}
1430 * @endcode
1431 *
1432 * @return Title Base title
1433 * @since 1.20
1434 */
1435 public function getBaseTitle() {
1436 return Title::makeTitle( $this->getNamespace(), $this->getBaseText() );
1437 }
1438
1439 /**
1440 * Get the lowest-level subpage name, i.e. the rightmost part after any slashes
1441 *
1442 * @par Example:
1443 * @code
1444 * Title::newFromText('User:Foo/Bar/Baz')->getSubpageText();
1445 * # returns: "Baz"
1446 * @endcode
1447 *
1448 * @return String Subpage name
1449 */
1450 public function getSubpageText() {
1451 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
1452 return $this->mTextform;
1453 }
1454 $parts = explode( '/', $this->mTextform );
1455 return $parts[count( $parts ) - 1];
1456 }
1457
1458 /**
1459 * Get the title for a subpage of the current page
1460 *
1461 * @par Example:
1462 * @code
1463 * Title::newFromText('User:Foo/Bar/Baz')->getSubpage("Asdf");
1464 * # returns: Title{User:Foo/Bar/Baz/Asdf}
1465 * @endcode
1466 *
1467 * @param string $text The subpage name to add to the title
1468 * @return Title Subpage title
1469 * @since 1.20
1470 */
1471 public function getSubpage( $text ) {
1472 return Title::makeTitleSafe( $this->getNamespace(), $this->getText() . '/' . $text );
1473 }
1474
1475 /**
1476 * Get the HTML-escaped displayable text form.
1477 * Used for the title field in <a> tags.
1478 *
1479 * @return String the text, including any prefixes
1480 * @deprecated since 1.19
1481 */
1482 public function getEscapedText() {
1483 wfDeprecated( __METHOD__, '1.19' );
1484 return htmlspecialchars( $this->getPrefixedText() );
1485 }
1486
1487 /**
1488 * Get a URL-encoded form of the subpage text
1489 *
1490 * @return String URL-encoded subpage name
1491 */
1492 public function getSubpageUrlForm() {
1493 $text = $this->getSubpageText();
1494 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1495 return $text;
1496 }
1497
1498 /**
1499 * Get a URL-encoded title (not an actual URL) including interwiki
1500 *
1501 * @return String the URL-encoded form
1502 */
1503 public function getPrefixedURL() {
1504 $s = $this->prefix( $this->mDbkeyform );
1505 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1506 return $s;
1507 }
1508
1509 /**
1510 * Helper to fix up the get{Canonical,Full,Link,Local,Internal}URL args
1511 * get{Canonical,Full,Link,Local,Internal}URL methods accepted an optional
1512 * second argument named variant. This was deprecated in favor
1513 * of passing an array of option with a "variant" key
1514 * Once $query2 is removed for good, this helper can be dropped
1515 * and the wfArrayToCgi moved to getLocalURL();
1516 *
1517 * @since 1.19 (r105919)
1518 * @param $query
1519 * @param $query2 bool
1520 * @return String
1521 */
1522 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1523 if ( $query2 !== false ) {
1524 wfDeprecated( "Title::get{Canonical,Full,Link,Local,Internal}URL " .
1525 "method called with a second parameter is deprecated. Add your " .
1526 "parameter to an array passed as the first parameter.", "1.19" );
1527 }
1528 if ( is_array( $query ) ) {
1529 $query = wfArrayToCgi( $query );
1530 }
1531 if ( $query2 ) {
1532 if ( is_string( $query2 ) ) {
1533 // $query2 is a string, we will consider this to be
1534 // a deprecated $variant argument and add it to the query
1535 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1536 } else {
1537 $query2 = wfArrayToCgi( $query2 );
1538 }
1539 // If we have $query content add a & to it first
1540 if ( $query ) {
1541 $query .= '&';
1542 }
1543 // Now append the queries together
1544 $query .= $query2;
1545 }
1546 return $query;
1547 }
1548
1549 /**
1550 * Get a real URL referring to this title, with interwiki link and
1551 * fragment
1552 *
1553 * @see self::getLocalURL for the arguments.
1554 * @see wfExpandUrl
1555 * @param $query
1556 * @param $query2 bool
1557 * @param $proto Protocol type to use in URL
1558 * @return String the URL
1559 */
1560 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1561 $query = self::fixUrlQueryArgs( $query, $query2 );
1562
1563 # Hand off all the decisions on urls to getLocalURL
1564 $url = $this->getLocalURL( $query );
1565
1566 # Expand the url to make it a full url. Note that getLocalURL has the
1567 # potential to output full urls for a variety of reasons, so we use
1568 # wfExpandUrl instead of simply prepending $wgServer
1569 $url = wfExpandUrl( $url, $proto );
1570
1571 # Finally, add the fragment.
1572 $url .= $this->getFragmentForURL();
1573
1574 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1575 return $url;
1576 }
1577
1578 /**
1579 * Get a URL with no fragment or server name (relative URL) from a Title object.
1580 * If this page is generated with action=render, however,
1581 * $wgServer is prepended to make an absolute URL.
1582 *
1583 * @see self::getFullURL to always get an absolute URL.
1584 * @see self::newFromText to produce a Title object.
1585 *
1586 * @param string|array $query an optional query string,
1587 * not used for interwiki links. Can be specified as an associative array as well,
1588 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1589 * Some query patterns will trigger various shorturl path replacements.
1590 * @param $query2 Mixed: An optional secondary query array. This one MUST
1591 * be an array. If a string is passed it will be interpreted as a deprecated
1592 * variant argument and urlencoded into a variant= argument.
1593 * This second query argument will be added to the $query
1594 * The second parameter is deprecated since 1.19. Pass it as a key,value
1595 * pair in the first parameter array instead.
1596 *
1597 * @return String of the URL.
1598 */
1599 public function getLocalURL( $query = '', $query2 = false ) {
1600 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1601
1602 $query = self::fixUrlQueryArgs( $query, $query2 );
1603
1604 $interwiki = Interwiki::fetch( $this->mInterwiki );
1605 if ( $interwiki ) {
1606 $namespace = $this->getNsText();
1607 if ( $namespace != '' ) {
1608 # Can this actually happen? Interwikis shouldn't be parsed.
1609 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1610 $namespace .= ':';
1611 }
1612 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1613 $url = wfAppendQuery( $url, $query );
1614 } else {
1615 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1616 if ( $query == '' ) {
1617 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1618 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1619 } else {
1620 global $wgVariantArticlePath, $wgActionPaths, $wgContLang;
1621 $url = false;
1622 $matches = array();
1623
1624 if ( !empty( $wgActionPaths )
1625 && preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches )
1626 ) {
1627 $action = urldecode( $matches[2] );
1628 if ( isset( $wgActionPaths[$action] ) ) {
1629 $query = $matches[1];
1630 if ( isset( $matches[4] ) ) {
1631 $query .= $matches[4];
1632 }
1633 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1634 if ( $query != '' ) {
1635 $url = wfAppendQuery( $url, $query );
1636 }
1637 }
1638 }
1639
1640 if ( $url === false
1641 && $wgVariantArticlePath
1642 && $wgContLang->getCode() === $this->getPageLanguage()->getCode()
1643 && $this->getPageLanguage()->hasVariants()
1644 && preg_match( '/^variant=([^&]*)$/', $query, $matches )
1645 ) {
1646 $variant = urldecode( $matches[1] );
1647 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1648 // Only do the variant replacement if the given variant is a valid
1649 // variant for the page's language.
1650 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1651 $url = str_replace( '$1', $dbkey, $url );
1652 }
1653 }
1654
1655 if ( $url === false ) {
1656 if ( $query == '-' ) {
1657 $query = '';
1658 }
1659 $url = "{$wgScript}?title={$dbkey}&{$query}";
1660 }
1661 }
1662
1663 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1664
1665 // @todo FIXME: This causes breakage in various places when we
1666 // actually expected a local URL and end up with dupe prefixes.
1667 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1668 $url = $wgServer . $url;
1669 }
1670 }
1671 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1672 return $url;
1673 }
1674
1675 /**
1676 * Get a URL that's the simplest URL that will be valid to link, locally,
1677 * to the current Title. It includes the fragment, but does not include
1678 * the server unless action=render is used (or the link is external). If
1679 * there's a fragment but the prefixed text is empty, we just return a link
1680 * to the fragment.
1681 *
1682 * The result obviously should not be URL-escaped, but does need to be
1683 * HTML-escaped if it's being output in HTML.
1684 *
1685 * @param $query
1686 * @param $query2 bool
1687 * @param $proto Protocol to use; setting this will cause a full URL to be used
1688 * @see self::getLocalURL for the arguments.
1689 * @return String the URL
1690 */
1691 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1692 wfProfileIn( __METHOD__ );
1693 if ( $this->isExternal() || $proto !== PROTO_RELATIVE ) {
1694 $ret = $this->getFullURL( $query, $query2, $proto );
1695 } elseif ( $this->getPrefixedText() === '' && $this->hasFragment() ) {
1696 $ret = $this->getFragmentForURL();
1697 } else {
1698 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1699 }
1700 wfProfileOut( __METHOD__ );
1701 return $ret;
1702 }
1703
1704 /**
1705 * Get an HTML-escaped version of the URL form, suitable for
1706 * using in a link, without a server name or fragment
1707 *
1708 * @see self::getLocalURL for the arguments.
1709 * @param $query string
1710 * @param $query2 bool|string
1711 * @return String the URL
1712 * @deprecated since 1.19
1713 */
1714 public function escapeLocalURL( $query = '', $query2 = false ) {
1715 wfDeprecated( __METHOD__, '1.19' );
1716 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1717 }
1718
1719 /**
1720 * Get an HTML-escaped version of the URL form, suitable for
1721 * using in a link, including the server name and fragment
1722 *
1723 * @see self::getLocalURL for the arguments.
1724 * @return String the URL
1725 * @deprecated since 1.19
1726 */
1727 public function escapeFullURL( $query = '', $query2 = false ) {
1728 wfDeprecated( __METHOD__, '1.19' );
1729 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1730 }
1731
1732 /**
1733 * Get the URL form for an internal link.
1734 * - Used in various Squid-related code, in case we have a different
1735 * internal hostname for the server from the exposed one.
1736 *
1737 * This uses $wgInternalServer to qualify the path, or $wgServer
1738 * if $wgInternalServer is not set. If the server variable used is
1739 * protocol-relative, the URL will be expanded to http://
1740 *
1741 * @see self::getLocalURL for the arguments.
1742 * @return String the URL
1743 */
1744 public function getInternalURL( $query = '', $query2 = false ) {
1745 global $wgInternalServer, $wgServer;
1746 $query = self::fixUrlQueryArgs( $query, $query2 );
1747 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1748 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1749 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1750 return $url;
1751 }
1752
1753 /**
1754 * Get the URL for a canonical link, for use in things like IRC and
1755 * e-mail notifications. Uses $wgCanonicalServer and the
1756 * GetCanonicalURL hook.
1757 *
1758 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1759 *
1760 * @see self::getLocalURL for the arguments.
1761 * @return string The URL
1762 * @since 1.18
1763 */
1764 public function getCanonicalURL( $query = '', $query2 = false ) {
1765 $query = self::fixUrlQueryArgs( $query, $query2 );
1766 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1767 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1768 return $url;
1769 }
1770
1771 /**
1772 * HTML-escaped version of getCanonicalURL()
1773 *
1774 * @see self::getLocalURL for the arguments.
1775 * @since 1.18
1776 * @return string
1777 * @deprecated since 1.19
1778 */
1779 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1780 wfDeprecated( __METHOD__, '1.19' );
1781 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1782 }
1783
1784 /**
1785 * Get the edit URL for this Title
1786 *
1787 * @return String the URL, or a null string if this is an
1788 * interwiki link
1789 */
1790 public function getEditURL() {
1791 if ( $this->isExternal() ) {
1792 return '';
1793 }
1794 $s = $this->getLocalURL( 'action=edit' );
1795
1796 return $s;
1797 }
1798
1799 /**
1800 * Is $wgUser watching this page?
1801 *
1802 * @deprecated since 1.20; use User::isWatched() instead.
1803 * @return Bool
1804 */
1805 public function userIsWatching() {
1806 global $wgUser;
1807
1808 if ( is_null( $this->mWatched ) ) {
1809 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1810 $this->mWatched = false;
1811 } else {
1812 $this->mWatched = $wgUser->isWatched( $this );
1813 }
1814 }
1815 return $this->mWatched;
1816 }
1817
1818 /**
1819 * Can $wgUser read this page?
1820 *
1821 * @deprecated since 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1822 * @return Bool
1823 */
1824 public function userCanRead() {
1825 wfDeprecated( __METHOD__, '1.19' );
1826 return $this->userCan( 'read' );
1827 }
1828
1829 /**
1830 * Can $user perform $action on this page?
1831 * This skips potentially expensive cascading permission checks
1832 * as well as avoids expensive error formatting
1833 *
1834 * Suitable for use for nonessential UI controls in common cases, but
1835 * _not_ for functional access control.
1836 *
1837 * May provide false positives, but should never provide a false negative.
1838 *
1839 * @param string $action action that permission needs to be checked for
1840 * @param $user User to check (since 1.19); $wgUser will be used if not
1841 * provided.
1842 * @return Bool
1843 */
1844 public function quickUserCan( $action, $user = null ) {
1845 return $this->userCan( $action, $user, false );
1846 }
1847
1848 /**
1849 * Can $user perform $action on this page?
1850 *
1851 * @param string $action action that permission needs to be checked for
1852 * @param $user User to check (since 1.19); $wgUser will be used if not
1853 * provided.
1854 * @param bool $doExpensiveQueries Set this to false to avoid doing
1855 * unnecessary queries.
1856 * @return Bool
1857 */
1858 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1859 if ( !$user instanceof User ) {
1860 global $wgUser;
1861 $user = $wgUser;
1862 }
1863 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1864 }
1865
1866 /**
1867 * Can $user perform $action on this page?
1868 *
1869 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1870 *
1871 * @param string $action action that permission needs to be checked for
1872 * @param $user User to check
1873 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary
1874 * queries by skipping checks for cascading protections and user blocks.
1875 * @param array $ignoreErrors of Strings Set this to a list of message keys
1876 * whose corresponding errors may be ignored.
1877 * @return Array of arguments to wfMessage to explain permissions problems.
1878 */
1879 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1880 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1881
1882 // Remove the errors being ignored.
1883 foreach ( $errors as $index => $error ) {
1884 $error_key = is_array( $error ) ? $error[0] : $error;
1885
1886 if ( in_array( $error_key, $ignoreErrors ) ) {
1887 unset( $errors[$index] );
1888 }
1889 }
1890
1891 return $errors;
1892 }
1893
1894 /**
1895 * Permissions checks that fail most often, and which are easiest to test.
1896 *
1897 * @param string $action the action to check
1898 * @param $user User user to check
1899 * @param array $errors list of current errors
1900 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1901 * @param $short Boolean short circuit on first error
1902 *
1903 * @return Array list of errors
1904 */
1905 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1906 if ( !wfRunHooks( 'TitleQuickPermissions', array( $this, $user, $action, &$errors, $doExpensiveQueries, $short ) ) ) {
1907 return $errors;
1908 }
1909
1910 if ( $action == 'create' ) {
1911 if (
1912 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1913 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1914 ) {
1915 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1916 }
1917 } elseif ( $action == 'move' ) {
1918 if ( !$user->isAllowed( 'move-rootuserpages' )
1919 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1920 // Show user page-specific message only if the user can move other pages
1921 $errors[] = array( 'cant-move-user-page' );
1922 }
1923
1924 // Check if user is allowed to move files if it's a file
1925 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1926 $errors[] = array( 'movenotallowedfile' );
1927 }
1928
1929 if ( !$user->isAllowed( 'move' ) ) {
1930 // User can't move anything
1931 $userCanMove = User::groupHasPermission( 'user', 'move' );
1932 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
1933 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1934 // custom message if logged-in users without any special rights can move
1935 $errors[] = array( 'movenologintext' );
1936 } else {
1937 $errors[] = array( 'movenotallowed' );
1938 }
1939 }
1940 } elseif ( $action == 'move-target' ) {
1941 if ( !$user->isAllowed( 'move' ) ) {
1942 // User can't move anything
1943 $errors[] = array( 'movenotallowed' );
1944 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1945 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1946 // Show user page-specific message only if the user can move other pages
1947 $errors[] = array( 'cant-move-to-user-page' );
1948 }
1949 } elseif ( !$user->isAllowed( $action ) ) {
1950 $errors[] = $this->missingPermissionError( $action, $short );
1951 }
1952
1953 return $errors;
1954 }
1955
1956 /**
1957 * Add the resulting error code to the errors array
1958 *
1959 * @param array $errors list of current errors
1960 * @param $result Mixed result of errors
1961 *
1962 * @return Array list of errors
1963 */
1964 private function resultToError( $errors, $result ) {
1965 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1966 // A single array representing an error
1967 $errors[] = $result;
1968 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1969 // A nested array representing multiple errors
1970 $errors = array_merge( $errors, $result );
1971 } elseif ( $result !== '' && is_string( $result ) ) {
1972 // A string representing a message-id
1973 $errors[] = array( $result );
1974 } elseif ( $result === false ) {
1975 // a generic "We don't want them to do that"
1976 $errors[] = array( 'badaccess-group0' );
1977 }
1978 return $errors;
1979 }
1980
1981 /**
1982 * Check various permission hooks
1983 *
1984 * @param string $action the action to check
1985 * @param $user User user to check
1986 * @param array $errors list of current errors
1987 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1988 * @param $short Boolean short circuit on first error
1989 *
1990 * @return Array list of errors
1991 */
1992 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1993 // Use getUserPermissionsErrors instead
1994 $result = '';
1995 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1996 return $result ? array() : array( array( 'badaccess-group0' ) );
1997 }
1998 // Check getUserPermissionsErrors hook
1999 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
2000 $errors = $this->resultToError( $errors, $result );
2001 }
2002 // Check getUserPermissionsErrorsExpensive hook
2003 if (
2004 $doExpensiveQueries
2005 && !( $short && count( $errors ) > 0 )
2006 && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
2007 ) {
2008 $errors = $this->resultToError( $errors, $result );
2009 }
2010
2011 return $errors;
2012 }
2013
2014 /**
2015 * Check permissions on special pages & namespaces
2016 *
2017 * @param string $action the action to check
2018 * @param $user User user to check
2019 * @param array $errors list of current errors
2020 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2021 * @param $short Boolean short circuit on first error
2022 *
2023 * @return Array list of errors
2024 */
2025 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2026 # Only 'createaccount' can be performed on special pages,
2027 # which don't actually exist in the DB.
2028 if ( NS_SPECIAL == $this->mNamespace && $action !== 'createaccount' ) {
2029 $errors[] = array( 'ns-specialprotected' );
2030 }
2031
2032 # Check $wgNamespaceProtection for restricted namespaces
2033 if ( $this->isNamespaceProtected( $user ) ) {
2034 $ns = $this->mNamespace == NS_MAIN ?
2035 wfMessage( 'nstab-main' )->text() : $this->getNsText();
2036 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
2037 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
2038 }
2039
2040 return $errors;
2041 }
2042
2043 /**
2044 * Check CSS/JS sub-page permissions
2045 *
2046 * @param string $action the action to check
2047 * @param $user User user to check
2048 * @param array $errors list of current errors
2049 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2050 * @param $short Boolean short circuit on first error
2051 *
2052 * @return Array list of errors
2053 */
2054 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2055 # Protect css/js subpages of user pages
2056 # XXX: this might be better using restrictions
2057 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
2058 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' ) ) {
2059 if ( preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
2060 if ( $this->isCssSubpage() && !$user->isAllowedAny( 'editmyusercss', 'editusercss' ) ) {
2061 $errors[] = array( 'mycustomcssprotected' );
2062 } elseif ( $this->isJsSubpage() && !$user->isAllowedAny( 'editmyuserjs', 'edituserjs' ) ) {
2063 $errors[] = array( 'mycustomjsprotected' );
2064 }
2065 } else {
2066 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
2067 $errors[] = array( 'customcssprotected' );
2068 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
2069 $errors[] = array( 'customjsprotected' );
2070 }
2071 }
2072 }
2073
2074 return $errors;
2075 }
2076
2077 /**
2078 * Check against page_restrictions table requirements on this
2079 * page. The user must possess all required rights for this
2080 * action.
2081 *
2082 * @param string $action the action to check
2083 * @param $user User user to check
2084 * @param array $errors list of current errors
2085 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2086 * @param $short Boolean short circuit on first error
2087 *
2088 * @return Array list of errors
2089 */
2090 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2091 foreach ( $this->getRestrictions( $action ) as $right ) {
2092 // Backwards compatibility, rewrite sysop -> editprotected
2093 if ( $right == 'sysop' ) {
2094 $right = 'editprotected';
2095 }
2096 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2097 if ( $right == 'autoconfirmed' ) {
2098 $right = 'editsemiprotected';
2099 }
2100 if ( $right == '' ) {
2101 continue;
2102 }
2103 if ( !$user->isAllowed( $right ) ) {
2104 $errors[] = array( 'protectedpagetext', $right );
2105 } elseif ( $this->mCascadeRestriction && !$user->isAllowed( 'protect' ) ) {
2106 $errors[] = array( 'protectedpagetext', 'protect' );
2107 }
2108 }
2109
2110 return $errors;
2111 }
2112
2113 /**
2114 * Check restrictions on cascading pages.
2115 *
2116 * @param string $action the action to check
2117 * @param $user User to check
2118 * @param array $errors list of current errors
2119 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2120 * @param $short Boolean short circuit on first error
2121 *
2122 * @return Array list of errors
2123 */
2124 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2125 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
2126 # We /could/ use the protection level on the source page, but it's
2127 # fairly ugly as we have to establish a precedence hierarchy for pages
2128 # included by multiple cascade-protected pages. So just restrict
2129 # it to people with 'protect' permission, as they could remove the
2130 # protection anyway.
2131 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
2132 # Cascading protection depends on more than this page...
2133 # Several cascading protected pages may include this page...
2134 # Check each cascading level
2135 # This is only for protection restrictions, not for all actions
2136 if ( isset( $restrictions[$action] ) ) {
2137 foreach ( $restrictions[$action] as $right ) {
2138 // Backwards compatibility, rewrite sysop -> editprotected
2139 if ( $right == 'sysop' ) {
2140 $right = 'editprotected';
2141 }
2142 // Backwards compatibility, rewrite autoconfirmed -> editsemiprotected
2143 if ( $right == 'autoconfirmed' ) {
2144 $right = 'editsemiprotected';
2145 }
2146 if ( $right != '' && !$user->isAllowedAll( 'protect', $right ) ) {
2147 $pages = '';
2148 foreach ( $cascadingSources as $page ) {
2149 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
2150 }
2151 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
2152 }
2153 }
2154 }
2155 }
2156
2157 return $errors;
2158 }
2159
2160 /**
2161 * Check action permissions not already checked in checkQuickPermissions
2162 *
2163 * @param string $action the action to check
2164 * @param $user User to check
2165 * @param array $errors list of current errors
2166 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2167 * @param $short Boolean short circuit on first error
2168 *
2169 * @return Array list of errors
2170 */
2171 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2172 global $wgDeleteRevisionsLimit, $wgLang;
2173
2174 if ( $action == 'protect' ) {
2175 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
2176 // If they can't edit, they shouldn't protect.
2177 $errors[] = array( 'protect-cantedit' );
2178 }
2179 } elseif ( $action == 'create' ) {
2180 $title_protection = $this->getTitleProtection();
2181 if ( $title_protection ) {
2182 if ( $title_protection['pt_create_perm'] == 'sysop' ) {
2183 $title_protection['pt_create_perm'] = 'editprotected'; // B/C
2184 }
2185 if ( $title_protection['pt_create_perm'] == 'autoconfirmed' ) {
2186 $title_protection['pt_create_perm'] = 'editsemiprotected'; // B/C
2187 }
2188 if ( $title_protection['pt_create_perm'] == ''
2189 || !$user->isAllowed( $title_protection['pt_create_perm'] )
2190 ) {
2191 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
2192 }
2193 }
2194 } elseif ( $action == 'move' ) {
2195 // Check for immobile pages
2196 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2197 // Specific message for this case
2198 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
2199 } elseif ( !$this->isMovable() ) {
2200 // Less specific message for rarer cases
2201 $errors[] = array( 'immobile-source-page' );
2202 }
2203 } elseif ( $action == 'move-target' ) {
2204 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2205 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2206 } elseif ( !$this->isMovable() ) {
2207 $errors[] = array( 'immobile-target-page' );
2208 }
2209 } elseif ( $action == 'delete' ) {
2210 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
2211 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion()
2212 ) {
2213 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2214 }
2215 }
2216 return $errors;
2217 }
2218
2219 /**
2220 * Check that the user isn't blocked from editing.
2221 *
2222 * @param string $action the action to check
2223 * @param $user User to check
2224 * @param array $errors list of current errors
2225 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2226 * @param $short Boolean short circuit on first error
2227 *
2228 * @return Array list of errors
2229 */
2230 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2231 // Account creation blocks handled at userlogin.
2232 // Unblocking handled in SpecialUnblock
2233 if ( !$doExpensiveQueries || in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2234 return $errors;
2235 }
2236
2237 global $wgEmailConfirmToEdit;
2238
2239 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2240 $errors[] = array( 'confirmedittext' );
2241 }
2242
2243 if ( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2244 // Don't block the user from editing their own talk page unless they've been
2245 // explicitly blocked from that too.
2246 } elseif ( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
2247 // @todo FIXME: Pass the relevant context into this function.
2248 $errors[] = $user->getBlock()->getPermissionsError( RequestContext::getMain() );
2249 }
2250
2251 return $errors;
2252 }
2253
2254 /**
2255 * Check that the user is allowed to read this page.
2256 *
2257 * @param string $action the action to check
2258 * @param $user User to check
2259 * @param array $errors list of current errors
2260 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2261 * @param $short Boolean short circuit on first error
2262 *
2263 * @return Array list of errors
2264 */
2265 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2266 global $wgWhitelistRead, $wgWhitelistReadRegexp;
2267
2268 $whitelisted = false;
2269 if ( User::isEveryoneAllowed( 'read' ) ) {
2270 # Shortcut for public wikis, allows skipping quite a bit of code
2271 $whitelisted = true;
2272 } elseif ( $user->isAllowed( 'read' ) ) {
2273 # If the user is allowed to read pages, he is allowed to read all pages
2274 $whitelisted = true;
2275 } elseif ( $this->isSpecial( 'Userlogin' )
2276 || $this->isSpecial( 'ChangePassword' )
2277 || $this->isSpecial( 'PasswordReset' )
2278 ) {
2279 # Always grant access to the login page.
2280 # Even anons need to be able to log in.
2281 $whitelisted = true;
2282 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2283 # Time to check the whitelist
2284 # Only do these checks is there's something to check against
2285 $name = $this->getPrefixedText();
2286 $dbName = $this->getPrefixedDBkey();
2287
2288 // Check for explicit whitelisting with and without underscores
2289 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2290 $whitelisted = true;
2291 } elseif ( $this->getNamespace() == NS_MAIN ) {
2292 # Old settings might have the title prefixed with
2293 # a colon for main-namespace pages
2294 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2295 $whitelisted = true;
2296 }
2297 } elseif ( $this->isSpecialPage() ) {
2298 # If it's a special page, ditch the subpage bit and check again
2299 $name = $this->getDBkey();
2300 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2301 if ( $name ) {
2302 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2303 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2304 $whitelisted = true;
2305 }
2306 }
2307 }
2308 }
2309
2310 if ( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2311 $name = $this->getPrefixedText();
2312 // Check for regex whitelisting
2313 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2314 if ( preg_match( $listItem, $name ) ) {
2315 $whitelisted = true;
2316 break;
2317 }
2318 }
2319 }
2320
2321 if ( !$whitelisted ) {
2322 # If the title is not whitelisted, give extensions a chance to do so...
2323 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2324 if ( !$whitelisted ) {
2325 $errors[] = $this->missingPermissionError( $action, $short );
2326 }
2327 }
2328
2329 return $errors;
2330 }
2331
2332 /**
2333 * Get a description array when the user doesn't have the right to perform
2334 * $action (i.e. when User::isAllowed() returns false)
2335 *
2336 * @param string $action the action to check
2337 * @param $short Boolean short circuit on first error
2338 * @return Array list of errors
2339 */
2340 private function missingPermissionError( $action, $short ) {
2341 // We avoid expensive display logic for quickUserCan's and such
2342 if ( $short ) {
2343 return array( 'badaccess-group0' );
2344 }
2345
2346 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2347 User::getGroupsWithPermission( $action ) );
2348
2349 if ( count( $groups ) ) {
2350 global $wgLang;
2351 return array(
2352 'badaccess-groups',
2353 $wgLang->commaList( $groups ),
2354 count( $groups )
2355 );
2356 } else {
2357 return array( 'badaccess-group0' );
2358 }
2359 }
2360
2361 /**
2362 * Can $user perform $action on this page? This is an internal function,
2363 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2364 * checks on wfReadOnly() and blocks)
2365 *
2366 * @param string $action action that permission needs to be checked for
2367 * @param $user User to check
2368 * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
2369 * @param bool $short Set this to true to stop after the first permission error.
2370 * @return Array of arrays of the arguments to wfMessage to explain permissions problems.
2371 */
2372 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2373 wfProfileIn( __METHOD__ );
2374
2375 # Read has special handling
2376 if ( $action == 'read' ) {
2377 $checks = array(
2378 'checkPermissionHooks',
2379 'checkReadPermissions',
2380 );
2381 } else {
2382 $checks = array(
2383 'checkQuickPermissions',
2384 'checkPermissionHooks',
2385 'checkSpecialsAndNSPermissions',
2386 'checkCSSandJSPermissions',
2387 'checkPageRestrictions',
2388 'checkCascadingSourcesRestrictions',
2389 'checkActionPermissions',
2390 'checkUserBlock'
2391 );
2392 }
2393
2394 $errors = array();
2395 while ( count( $checks ) > 0 &&
2396 !( $short && count( $errors ) > 0 ) ) {
2397 $method = array_shift( $checks );
2398 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2399 }
2400
2401 wfProfileOut( __METHOD__ );
2402 return $errors;
2403 }
2404
2405 /**
2406 * Get a filtered list of all restriction types supported by this wiki.
2407 * @param bool $exists True to get all restriction types that apply to
2408 * titles that do exist, False for all restriction types that apply to
2409 * titles that do not exist
2410 * @return array
2411 */
2412 public static function getFilteredRestrictionTypes( $exists = true ) {
2413 global $wgRestrictionTypes;
2414 $types = $wgRestrictionTypes;
2415 if ( $exists ) {
2416 # Remove the create restriction for existing titles
2417 $types = array_diff( $types, array( 'create' ) );
2418 } else {
2419 # Only the create and upload restrictions apply to non-existing titles
2420 $types = array_intersect( $types, array( 'create', 'upload' ) );
2421 }
2422 return $types;
2423 }
2424
2425 /**
2426 * Returns restriction types for the current Title
2427 *
2428 * @return array applicable restriction types
2429 */
2430 public function getRestrictionTypes() {
2431 if ( $this->isSpecialPage() ) {
2432 return array();
2433 }
2434
2435 $types = self::getFilteredRestrictionTypes( $this->exists() );
2436
2437 if ( $this->getNamespace() != NS_FILE ) {
2438 # Remove the upload restriction for non-file titles
2439 $types = array_diff( $types, array( 'upload' ) );
2440 }
2441
2442 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2443
2444 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2445 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2446
2447 return $types;
2448 }
2449
2450 /**
2451 * Is this title subject to title protection?
2452 * Title protection is the one applied against creation of such title.
2453 *
2454 * @return Mixed An associative array representing any existent title
2455 * protection, or false if there's none.
2456 */
2457 private function getTitleProtection() {
2458 // Can't protect pages in special namespaces
2459 if ( $this->getNamespace() < 0 ) {
2460 return false;
2461 }
2462
2463 // Can't protect pages that exist.
2464 if ( $this->exists() ) {
2465 return false;
2466 }
2467
2468 if ( !isset( $this->mTitleProtection ) ) {
2469 $dbr = wfGetDB( DB_SLAVE );
2470 $res = $dbr->select(
2471 'protected_titles',
2472 array( 'pt_user', 'pt_reason', 'pt_expiry', 'pt_create_perm' ),
2473 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2474 __METHOD__
2475 );
2476
2477 // fetchRow returns false if there are no rows.
2478 $this->mTitleProtection = $dbr->fetchRow( $res );
2479 }
2480 return $this->mTitleProtection;
2481 }
2482
2483 /**
2484 * Update the title protection status
2485 *
2486 * @deprecated since 1.19; use WikiPage::doUpdateRestrictions() instead.
2487 * @param $create_perm String Permission required for creation
2488 * @param string $reason Reason for protection
2489 * @param string $expiry Expiry timestamp
2490 * @return boolean true
2491 */
2492 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2493 wfDeprecated( __METHOD__, '1.19' );
2494
2495 global $wgUser;
2496
2497 $limit = array( 'create' => $create_perm );
2498 $expiry = array( 'create' => $expiry );
2499
2500 $page = WikiPage::factory( $this );
2501 $cascade = false;
2502 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $wgUser );
2503
2504 return $status->isOK();
2505 }
2506
2507 /**
2508 * Remove any title protection due to page existing
2509 */
2510 public function deleteTitleProtection() {
2511 $dbw = wfGetDB( DB_MASTER );
2512
2513 $dbw->delete(
2514 'protected_titles',
2515 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2516 __METHOD__
2517 );
2518 $this->mTitleProtection = false;
2519 }
2520
2521 /**
2522 * Is this page "semi-protected" - the *only* protection levels are listed
2523 * in $wgSemiprotectedRestrictionLevels?
2524 *
2525 * @param string $action Action to check (default: edit)
2526 * @return Bool
2527 */
2528 public function isSemiProtected( $action = 'edit' ) {
2529 global $wgSemiprotectedRestrictionLevels;
2530
2531 $restrictions = $this->getRestrictions( $action );
2532 $semi = $wgSemiprotectedRestrictionLevels;
2533 if ( !$restrictions || !$semi ) {
2534 // Not protected, or all protection is full protection
2535 return false;
2536 }
2537
2538 // Remap autoconfirmed to editsemiprotected for BC
2539 foreach ( array_keys( $semi, 'autoconfirmed' ) as $key ) {
2540 $semi[$key] = 'editsemiprotected';
2541 }
2542 foreach ( array_keys( $restrictions, 'autoconfirmed' ) as $key ) {
2543 $restrictions[$key] = 'editsemiprotected';
2544 }
2545
2546 return !array_diff( $restrictions, $semi );
2547 }
2548
2549 /**
2550 * Does the title correspond to a protected article?
2551 *
2552 * @param string $action the action the page is protected from,
2553 * by default checks all actions.
2554 * @return Bool
2555 */
2556 public function isProtected( $action = '' ) {
2557 global $wgRestrictionLevels;
2558
2559 $restrictionTypes = $this->getRestrictionTypes();
2560
2561 # Special pages have inherent protection
2562 if ( $this->isSpecialPage() ) {
2563 return true;
2564 }
2565
2566 # Check regular protection levels
2567 foreach ( $restrictionTypes as $type ) {
2568 if ( $action == $type || $action == '' ) {
2569 $r = $this->getRestrictions( $type );
2570 foreach ( $wgRestrictionLevels as $level ) {
2571 if ( in_array( $level, $r ) && $level != '' ) {
2572 return true;
2573 }
2574 }
2575 }
2576 }
2577
2578 return false;
2579 }
2580
2581 /**
2582 * Determines if $user is unable to edit this page because it has been protected
2583 * by $wgNamespaceProtection.
2584 *
2585 * @param $user User object to check permissions
2586 * @return Bool
2587 */
2588 public function isNamespaceProtected( User $user ) {
2589 global $wgNamespaceProtection;
2590
2591 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2592 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2593 if ( $right != '' && !$user->isAllowed( $right ) ) {
2594 return true;
2595 }
2596 }
2597 }
2598 return false;
2599 }
2600
2601 /**
2602 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2603 *
2604 * @return Bool If the page is subject to cascading restrictions.
2605 */
2606 public function isCascadeProtected() {
2607 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2608 return ( $sources > 0 );
2609 }
2610
2611 /**
2612 * Determines whether cascading protection sources have already been loaded from
2613 * the database.
2614 *
2615 * @param bool $getPages True to check if the pages are loaded, or false to check
2616 * if the status is loaded.
2617 * @return bool Whether or not the specified information has been loaded
2618 * @since 1.23
2619 */
2620 public function areCascadeProtectionSourcesLoaded( $getPages = true ) {
2621 return $getPages ? isset( $this->mCascadeSources ) : isset( $this->mHasCascadingRestrictions );
2622 }
2623
2624 /**
2625 * Cascading protection: Get the source of any cascading restrictions on this page.
2626 *
2627 * @param bool $getPages Whether or not to retrieve the actual pages
2628 * that the restrictions have come from.
2629 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2630 * have come, false for none, or true if such restrictions exist, but $getPages
2631 * was not set. The restriction array is an array of each type, each of which
2632 * contains a array of unique groups.
2633 */
2634 public function getCascadeProtectionSources( $getPages = true ) {
2635 global $wgContLang;
2636 $pagerestrictions = array();
2637
2638 if ( isset( $this->mCascadeSources ) && $getPages ) {
2639 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2640 } elseif ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2641 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2642 }
2643
2644 wfProfileIn( __METHOD__ );
2645
2646 $dbr = wfGetDB( DB_SLAVE );
2647
2648 if ( $this->getNamespace() == NS_FILE ) {
2649 $tables = array( 'imagelinks', 'page_restrictions' );
2650 $where_clauses = array(
2651 'il_to' => $this->getDBkey(),
2652 'il_from=pr_page',
2653 'pr_cascade' => 1
2654 );
2655 } else {
2656 $tables = array( 'templatelinks', 'page_restrictions' );
2657 $where_clauses = array(
2658 'tl_namespace' => $this->getNamespace(),
2659 'tl_title' => $this->getDBkey(),
2660 'tl_from=pr_page',
2661 'pr_cascade' => 1
2662 );
2663 }
2664
2665 if ( $getPages ) {
2666 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2667 'pr_expiry', 'pr_type', 'pr_level' );
2668 $where_clauses[] = 'page_id=pr_page';
2669 $tables[] = 'page';
2670 } else {
2671 $cols = array( 'pr_expiry' );
2672 }
2673
2674 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2675
2676 $sources = $getPages ? array() : false;
2677 $now = wfTimestampNow();
2678 $purgeExpired = false;
2679
2680 foreach ( $res as $row ) {
2681 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2682 if ( $expiry > $now ) {
2683 if ( $getPages ) {
2684 $page_id = $row->pr_page;
2685 $page_ns = $row->page_namespace;
2686 $page_title = $row->page_title;
2687 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2688 # Add groups needed for each restriction type if its not already there
2689 # Make sure this restriction type still exists
2690
2691 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2692 $pagerestrictions[$row->pr_type] = array();
2693 }
2694
2695 if (
2696 isset( $pagerestrictions[$row->pr_type] )
2697 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2698 ) {
2699 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2700 }
2701 } else {
2702 $sources = true;
2703 }
2704 } else {
2705 // Trigger lazy purge of expired restrictions from the db
2706 $purgeExpired = true;
2707 }
2708 }
2709 if ( $purgeExpired ) {
2710 Title::purgeExpiredRestrictions();
2711 }
2712
2713 if ( $getPages ) {
2714 $this->mCascadeSources = $sources;
2715 $this->mCascadingRestrictions = $pagerestrictions;
2716 } else {
2717 $this->mHasCascadingRestrictions = $sources;
2718 }
2719
2720 wfProfileOut( __METHOD__ );
2721 return array( $sources, $pagerestrictions );
2722 }
2723
2724 /**
2725 * Accessor for mRestrictionsLoaded
2726 *
2727 * @return bool Whether or not the page's restrictions have already been
2728 * loaded from the database
2729 * @since 1.23
2730 */
2731 public function areRestrictionsLoaded() {
2732 return $this->mRestrictionsLoaded;
2733 }
2734
2735 /**
2736 * Accessor/initialisation for mRestrictions
2737 *
2738 * @param string $action action that permission needs to be checked for
2739 * @return Array of Strings the array of groups allowed to edit this article
2740 */
2741 public function getRestrictions( $action ) {
2742 if ( !$this->mRestrictionsLoaded ) {
2743 $this->loadRestrictions();
2744 }
2745 return isset( $this->mRestrictions[$action] )
2746 ? $this->mRestrictions[$action]
2747 : array();
2748 }
2749
2750 /**
2751 * Accessor/initialisation for mRestrictions
2752 *
2753 * @return Array of Arrays of Strings the first level indexed by
2754 * action, the second level containing the names of the groups
2755 * allowed to perform each action
2756 * @since 1.23
2757 */
2758 public function getAllRestrictions() {
2759 if ( !$this->mRestrictionsLoaded ) {
2760 $this->loadRestrictions();
2761 }
2762 return $this->mRestrictions;
2763 }
2764
2765 /**
2766 * Get the expiry time for the restriction against a given action
2767 *
2768 * @param $action
2769 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2770 * or not protected at all, or false if the action is not recognised.
2771 */
2772 public function getRestrictionExpiry( $action ) {
2773 if ( !$this->mRestrictionsLoaded ) {
2774 $this->loadRestrictions();
2775 }
2776 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2777 }
2778
2779 /**
2780 * Returns cascading restrictions for the current article
2781 *
2782 * @return Boolean
2783 */
2784 function areRestrictionsCascading() {
2785 if ( !$this->mRestrictionsLoaded ) {
2786 $this->loadRestrictions();
2787 }
2788
2789 return $this->mCascadeRestriction;
2790 }
2791
2792 /**
2793 * Loads a string into mRestrictions array
2794 *
2795 * @param $res Resource restrictions as an SQL result.
2796 * @param string $oldFashionedRestrictions comma-separated list of page
2797 * restrictions from page table (pre 1.10)
2798 */
2799 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2800 $rows = array();
2801
2802 foreach ( $res as $row ) {
2803 $rows[] = $row;
2804 }
2805
2806 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2807 }
2808
2809 /**
2810 * Compiles list of active page restrictions from both page table (pre 1.10)
2811 * and page_restrictions table for this existing page.
2812 * Public for usage by LiquidThreads.
2813 *
2814 * @param array $rows of db result objects
2815 * @param string $oldFashionedRestrictions comma-separated list of page
2816 * restrictions from page table (pre 1.10)
2817 */
2818 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2819 global $wgContLang;
2820 $dbr = wfGetDB( DB_SLAVE );
2821
2822 $restrictionTypes = $this->getRestrictionTypes();
2823
2824 foreach ( $restrictionTypes as $type ) {
2825 $this->mRestrictions[$type] = array();
2826 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2827 }
2828
2829 $this->mCascadeRestriction = false;
2830
2831 # Backwards-compatibility: also load the restrictions from the page record (old format).
2832
2833 if ( $oldFashionedRestrictions === null ) {
2834 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2835 array( 'page_id' => $this->getArticleID() ), __METHOD__ );
2836 }
2837
2838 if ( $oldFashionedRestrictions != '' ) {
2839
2840 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2841 $temp = explode( '=', trim( $restrict ) );
2842 if ( count( $temp ) == 1 ) {
2843 // old old format should be treated as edit/move restriction
2844 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2845 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2846 } else {
2847 $restriction = trim( $temp[1] );
2848 if ( $restriction != '' ) { //some old entries are empty
2849 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2850 }
2851 }
2852 }
2853
2854 $this->mOldRestrictions = true;
2855
2856 }
2857
2858 if ( count( $rows ) ) {
2859 # Current system - load second to make them override.
2860 $now = wfTimestampNow();
2861 $purgeExpired = false;
2862
2863 # Cycle through all the restrictions.
2864 foreach ( $rows as $row ) {
2865
2866 // Don't take care of restrictions types that aren't allowed
2867 if ( !in_array( $row->pr_type, $restrictionTypes ) ) {
2868 continue;
2869 }
2870
2871 // This code should be refactored, now that it's being used more generally,
2872 // But I don't really see any harm in leaving it in Block for now -werdna
2873 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2874
2875 // Only apply the restrictions if they haven't expired!
2876 if ( !$expiry || $expiry > $now ) {
2877 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2878 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2879
2880 $this->mCascadeRestriction |= $row->pr_cascade;
2881 } else {
2882 // Trigger a lazy purge of expired restrictions
2883 $purgeExpired = true;
2884 }
2885 }
2886
2887 if ( $purgeExpired ) {
2888 Title::purgeExpiredRestrictions();
2889 }
2890 }
2891
2892 $this->mRestrictionsLoaded = true;
2893 }
2894
2895 /**
2896 * Load restrictions from the page_restrictions table
2897 *
2898 * @param string $oldFashionedRestrictions comma-separated list of page
2899 * restrictions from page table (pre 1.10)
2900 */
2901 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2902 global $wgContLang;
2903 if ( !$this->mRestrictionsLoaded ) {
2904 if ( $this->exists() ) {
2905 $dbr = wfGetDB( DB_SLAVE );
2906
2907 $res = $dbr->select(
2908 'page_restrictions',
2909 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2910 array( 'pr_page' => $this->getArticleID() ),
2911 __METHOD__
2912 );
2913
2914 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2915 } else {
2916 $title_protection = $this->getTitleProtection();
2917
2918 if ( $title_protection ) {
2919 $now = wfTimestampNow();
2920 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW );
2921
2922 if ( !$expiry || $expiry > $now ) {
2923 // Apply the restrictions
2924 $this->mRestrictionsExpiry['create'] = $expiry;
2925 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2926 } else { // Get rid of the old restrictions
2927 Title::purgeExpiredRestrictions();
2928 $this->mTitleProtection = false;
2929 }
2930 } else {
2931 $this->mRestrictionsExpiry['create'] = $wgContLang->formatExpiry( '', TS_MW );
2932 }
2933 $this->mRestrictionsLoaded = true;
2934 }
2935 }
2936 }
2937
2938 /**
2939 * Flush the protection cache in this object and force reload from the database.
2940 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2941 */
2942 public function flushRestrictions() {
2943 $this->mRestrictionsLoaded = false;
2944 $this->mTitleProtection = null;
2945 }
2946
2947 /**
2948 * Purge expired restrictions from the page_restrictions table
2949 */
2950 static function purgeExpiredRestrictions() {
2951 if ( wfReadOnly() ) {
2952 return;
2953 }
2954
2955 $method = __METHOD__;
2956 $dbw = wfGetDB( DB_MASTER );
2957 $dbw->onTransactionIdle( function() use ( $dbw, $method ) {
2958 $dbw->delete(
2959 'page_restrictions',
2960 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2961 $method
2962 );
2963 $dbw->delete(
2964 'protected_titles',
2965 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2966 $method
2967 );
2968 } );
2969 }
2970
2971 /**
2972 * Does this have subpages? (Warning, usually requires an extra DB query.)
2973 *
2974 * @return Bool
2975 */
2976 public function hasSubpages() {
2977 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
2978 # Duh
2979 return false;
2980 }
2981
2982 # We dynamically add a member variable for the purpose of this method
2983 # alone to cache the result. There's no point in having it hanging
2984 # around uninitialized in every Title object; therefore we only add it
2985 # if needed and don't declare it statically.
2986 if ( !isset( $this->mHasSubpages ) ) {
2987 $this->mHasSubpages = false;
2988 $subpages = $this->getSubpages( 1 );
2989 if ( $subpages instanceof TitleArray ) {
2990 $this->mHasSubpages = (bool)$subpages->count();
2991 }
2992 }
2993
2994 return $this->mHasSubpages;
2995 }
2996
2997 /**
2998 * Get all subpages of this page.
2999 *
3000 * @param int $limit maximum number of subpages to fetch; -1 for no limit
3001 * @return mixed TitleArray, or empty array if this page's namespace
3002 * doesn't allow subpages
3003 */
3004 public function getSubpages( $limit = -1 ) {
3005 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3006 return array();
3007 }
3008
3009 $dbr = wfGetDB( DB_SLAVE );
3010 $conds['page_namespace'] = $this->getNamespace();
3011 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
3012 $options = array();
3013 if ( $limit > -1 ) {
3014 $options['LIMIT'] = $limit;
3015 }
3016 $this->mSubpages = TitleArray::newFromResult(
3017 $dbr->select( 'page',
3018 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
3019 $conds,
3020 __METHOD__,
3021 $options
3022 )
3023 );
3024 return $this->mSubpages;
3025 }
3026
3027 /**
3028 * Is there a version of this page in the deletion archive?
3029 *
3030 * @return Int the number of archived revisions
3031 */
3032 public function isDeleted() {
3033 if ( $this->getNamespace() < 0 ) {
3034 $n = 0;
3035 } else {
3036 $dbr = wfGetDB( DB_SLAVE );
3037
3038 $n = $dbr->selectField( 'archive', 'COUNT(*)',
3039 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3040 __METHOD__
3041 );
3042 if ( $this->getNamespace() == NS_FILE ) {
3043 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
3044 array( 'fa_name' => $this->getDBkey() ),
3045 __METHOD__
3046 );
3047 }
3048 }
3049 return (int)$n;
3050 }
3051
3052 /**
3053 * Is there a version of this page in the deletion archive?
3054 *
3055 * @return Boolean
3056 */
3057 public function isDeletedQuick() {
3058 if ( $this->getNamespace() < 0 ) {
3059 return false;
3060 }
3061 $dbr = wfGetDB( DB_SLAVE );
3062 $deleted = (bool)$dbr->selectField( 'archive', '1',
3063 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
3064 __METHOD__
3065 );
3066 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
3067 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
3068 array( 'fa_name' => $this->getDBkey() ),
3069 __METHOD__
3070 );
3071 }
3072 return $deleted;
3073 }
3074
3075 /**
3076 * Get the article ID for this Title from the link cache,
3077 * adding it if necessary
3078 *
3079 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select
3080 * for update
3081 * @return Int the ID
3082 */
3083 public function getArticleID( $flags = 0 ) {
3084 if ( $this->getNamespace() < 0 ) {
3085 $this->mArticleID = 0;
3086 return $this->mArticleID;
3087 }
3088 $linkCache = LinkCache::singleton();
3089 if ( $flags & self::GAID_FOR_UPDATE ) {
3090 $oldUpdate = $linkCache->forUpdate( true );
3091 $linkCache->clearLink( $this );
3092 $this->mArticleID = $linkCache->addLinkObj( $this );
3093 $linkCache->forUpdate( $oldUpdate );
3094 } else {
3095 if ( -1 == $this->mArticleID ) {
3096 $this->mArticleID = $linkCache->addLinkObj( $this );
3097 }
3098 }
3099 return $this->mArticleID;
3100 }
3101
3102 /**
3103 * Is this an article that is a redirect page?
3104 * Uses link cache, adding it if necessary
3105 *
3106 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update
3107 * @return Bool
3108 */
3109 public function isRedirect( $flags = 0 ) {
3110 if ( !is_null( $this->mRedirect ) ) {
3111 return $this->mRedirect;
3112 }
3113 # Calling getArticleID() loads the field from cache as needed
3114 if ( !$this->getArticleID( $flags ) ) {
3115 $this->mRedirect = false;
3116 return $this->mRedirect;
3117 }
3118
3119 $linkCache = LinkCache::singleton();
3120 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
3121 if ( $cached === null ) {
3122 # Trust LinkCache's state over our own
3123 # LinkCache is telling us that the page doesn't exist, despite there being cached
3124 # data relating to an existing page in $this->mArticleID. Updaters should clear
3125 # LinkCache as appropriate, or use $flags = Title::GAID_FOR_UPDATE. If that flag is
3126 # set, then LinkCache will definitely be up to date here, since getArticleID() forces
3127 # LinkCache to refresh its data from the master.
3128 $this->mRedirect = false;
3129 return $this->mRedirect;
3130 }
3131
3132 $this->mRedirect = (bool)$cached;
3133
3134 return $this->mRedirect;
3135 }
3136
3137 /**
3138 * What is the length of this page?
3139 * Uses link cache, adding it if necessary
3140 *
3141 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update
3142 * @return Int
3143 */
3144 public function getLength( $flags = 0 ) {
3145 if ( $this->mLength != -1 ) {
3146 return $this->mLength;
3147 }
3148 # Calling getArticleID() loads the field from cache as needed
3149 if ( !$this->getArticleID( $flags ) ) {
3150 $this->mLength = 0;
3151 return $this->mLength;
3152 }
3153 $linkCache = LinkCache::singleton();
3154 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
3155 if ( $cached === null ) {
3156 # Trust LinkCache's state over our own, as for isRedirect()
3157 $this->mLength = 0;
3158 return $this->mLength;
3159 }
3160
3161 $this->mLength = intval( $cached );
3162
3163 return $this->mLength;
3164 }
3165
3166 /**
3167 * What is the page_latest field for this page?
3168 *
3169 * @param int $flags a bit field; may be Title::GAID_FOR_UPDATE to select for update
3170 * @return Int or 0 if the page doesn't exist
3171 */
3172 public function getLatestRevID( $flags = 0 ) {
3173 if ( !( $flags & Title::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3174 return intval( $this->mLatestID );
3175 }
3176 # Calling getArticleID() loads the field from cache as needed
3177 if ( !$this->getArticleID( $flags ) ) {
3178 $this->mLatestID = 0;
3179 return $this->mLatestID;
3180 }
3181 $linkCache = LinkCache::singleton();
3182 $linkCache->addLinkObj( $this );
3183 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3184 if ( $cached === null ) {
3185 # Trust LinkCache's state over our own, as for isRedirect()
3186 $this->mLatestID = 0;
3187 return $this->mLatestID;
3188 }
3189
3190 $this->mLatestID = intval( $cached );
3191
3192 return $this->mLatestID;
3193 }
3194
3195 /**
3196 * This clears some fields in this object, and clears any associated
3197 * keys in the "bad links" section of the link cache.
3198 *
3199 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3200 * loading of the new page_id. It's also called from
3201 * WikiPage::doDeleteArticleReal()
3202 *
3203 * @param int $newid the new Article ID
3204 */
3205 public function resetArticleID( $newid ) {
3206 $linkCache = LinkCache::singleton();
3207 $linkCache->clearLink( $this );
3208
3209 if ( $newid === false ) {
3210 $this->mArticleID = -1;
3211 } else {
3212 $this->mArticleID = intval( $newid );
3213 }
3214 $this->mRestrictionsLoaded = false;
3215 $this->mRestrictions = array();
3216 $this->mRedirect = null;
3217 $this->mLength = -1;
3218 $this->mLatestID = false;
3219 $this->mContentModel = false;
3220 $this->mEstimateRevisions = null;
3221 $this->mPageLanguage = false;
3222 }
3223
3224 /**
3225 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3226 *
3227 * @param string $text containing title to capitalize
3228 * @param int $ns namespace index, defaults to NS_MAIN
3229 * @return String containing capitalized title
3230 */
3231 public static function capitalize( $text, $ns = NS_MAIN ) {
3232 global $wgContLang;
3233
3234 if ( MWNamespace::isCapitalized( $ns ) ) {
3235 return $wgContLang->ucfirst( $text );
3236 } else {
3237 return $text;
3238 }
3239 }
3240
3241 /**
3242 * Secure and split - main initialisation function for this object
3243 *
3244 * Assumes that mDbkeyform has been set, and is urldecoded
3245 * and uses underscores, but not otherwise munged. This function
3246 * removes illegal characters, splits off the interwiki and
3247 * namespace prefixes, sets the other forms, and canonicalizes
3248 * everything.
3249 *
3250 * @return Bool true on success
3251 */
3252 private function secureAndSplit() {
3253 # Initialisation
3254 $this->mInterwiki = '';
3255 $this->mFragment = '';
3256 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
3257
3258 $dbkey = $this->mDbkeyform;
3259
3260 try {
3261 // @note: splitTitleString() is a temporary hack to allow MediaWikiTitleCodec to share
3262 // the parsing code with Title, while avoiding massive refactoring.
3263 // @todo: get rid of secureAndSplit, refactor parsing code.
3264 $parser = $this->getTitleParser();
3265 $parts = $parser->splitTitleString( $dbkey, $this->getDefaultNamespace() );
3266 } catch ( MalformedTitleException $ex ) {
3267 return false;
3268 }
3269
3270 # Fill fields
3271 $this->setFragment( '#' . $parts['fragment'] );
3272 $this->mInterwiki = $parts['interwiki'];
3273 $this->mNamespace = $parts['namespace'];
3274 $this->mUserCaseDBKey = $parts['user_case_dbkey'];
3275
3276 $this->mDbkeyform = $parts['dbkey'];
3277 $this->mUrlform = wfUrlencode( $this->mDbkeyform );
3278 $this->mTextform = str_replace( '_', ' ', $this->mDbkeyform );
3279
3280 # We already know that some pages won't be in the database!
3281 if ( $this->isExternal() || $this->mNamespace == NS_SPECIAL ) {
3282 $this->mArticleID = 0;
3283 }
3284
3285 return true;
3286 }
3287
3288 /**
3289 * Get an array of Title objects linking to this Title
3290 * Also stores the IDs in the link cache.
3291 *
3292 * WARNING: do not use this function on arbitrary user-supplied titles!
3293 * On heavily-used templates it will max out the memory.
3294 *
3295 * @param array $options may be FOR UPDATE
3296 * @param string $table table name
3297 * @param string $prefix fields prefix
3298 * @return Array of Title objects linking here
3299 */
3300 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3301 if ( count( $options ) > 0 ) {
3302 $db = wfGetDB( DB_MASTER );
3303 } else {
3304 $db = wfGetDB( DB_SLAVE );
3305 }
3306
3307 $res = $db->select(
3308 array( 'page', $table ),
3309 self::getSelectFields(),
3310 array(
3311 "{$prefix}_from=page_id",
3312 "{$prefix}_namespace" => $this->getNamespace(),
3313 "{$prefix}_title" => $this->getDBkey() ),
3314 __METHOD__,
3315 $options
3316 );
3317
3318 $retVal = array();
3319 if ( $res->numRows() ) {
3320 $linkCache = LinkCache::singleton();
3321 foreach ( $res as $row ) {
3322 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3323 if ( $titleObj ) {
3324 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3325 $retVal[] = $titleObj;
3326 }
3327 }
3328 }
3329 return $retVal;
3330 }
3331
3332 /**
3333 * Get an array of Title objects using this Title as a template
3334 * Also stores the IDs in the link cache.
3335 *
3336 * WARNING: do not use this function on arbitrary user-supplied titles!
3337 * On heavily-used templates it will max out the memory.
3338 *
3339 * @param array $options may be FOR UPDATE
3340 * @return Array of Title the Title objects linking here
3341 */
3342 public function getTemplateLinksTo( $options = array() ) {
3343 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3344 }
3345
3346 /**
3347 * Get an array of Title objects linked from this Title
3348 * Also stores the IDs in the link cache.
3349 *
3350 * WARNING: do not use this function on arbitrary user-supplied titles!
3351 * On heavily-used templates it will max out the memory.
3352 *
3353 * @param array $options may be FOR UPDATE
3354 * @param string $table table name
3355 * @param string $prefix fields prefix
3356 * @return Array of Title objects linking here
3357 */
3358 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3359 global $wgContentHandlerUseDB;
3360
3361 $id = $this->getArticleID();
3362
3363 # If the page doesn't exist; there can't be any link from this page
3364 if ( !$id ) {
3365 return array();
3366 }
3367
3368 if ( count( $options ) > 0 ) {
3369 $db = wfGetDB( DB_MASTER );
3370 } else {
3371 $db = wfGetDB( DB_SLAVE );
3372 }
3373
3374 $namespaceFiled = "{$prefix}_namespace";
3375 $titleField = "{$prefix}_title";
3376
3377 $fields = array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' );
3378 if ( $wgContentHandlerUseDB ) {
3379 $fields[] = 'page_content_model';
3380 }
3381
3382 $res = $db->select(
3383 array( $table, 'page' ),
3384 $fields,
3385 array( "{$prefix}_from" => $id ),
3386 __METHOD__,
3387 $options,
3388 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3389 );
3390
3391 $retVal = array();
3392 if ( $res->numRows() ) {
3393 $linkCache = LinkCache::singleton();
3394 foreach ( $res as $row ) {
3395 $titleObj = Title::makeTitle( $row->$namespaceFiled, $row->$titleField );
3396 if ( $titleObj ) {
3397 if ( $row->page_id ) {
3398 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3399 } else {
3400 $linkCache->addBadLinkObj( $titleObj );
3401 }
3402 $retVal[] = $titleObj;
3403 }
3404 }
3405 }
3406 return $retVal;
3407 }
3408
3409 /**
3410 * Get an array of Title objects used on this Title as a template
3411 * Also stores the IDs in the link cache.
3412 *
3413 * WARNING: do not use this function on arbitrary user-supplied titles!
3414 * On heavily-used templates it will max out the memory.
3415 *
3416 * @param array $options may be FOR UPDATE
3417 * @return Array of Title the Title objects used here
3418 */
3419 public function getTemplateLinksFrom( $options = array() ) {
3420 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3421 }
3422
3423 /**
3424 * Get an array of Title objects referring to non-existent articles linked from this page
3425 *
3426 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3427 * @return Array of Title the Title objects
3428 */
3429 public function getBrokenLinksFrom() {
3430 if ( $this->getArticleID() == 0 ) {
3431 # All links from article ID 0 are false positives
3432 return array();
3433 }
3434
3435 $dbr = wfGetDB( DB_SLAVE );
3436 $res = $dbr->select(
3437 array( 'page', 'pagelinks' ),
3438 array( 'pl_namespace', 'pl_title' ),
3439 array(
3440 'pl_from' => $this->getArticleID(),
3441 'page_namespace IS NULL'
3442 ),
3443 __METHOD__, array(),
3444 array(
3445 'page' => array(
3446 'LEFT JOIN',
3447 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3448 )
3449 )
3450 );
3451
3452 $retVal = array();
3453 foreach ( $res as $row ) {
3454 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3455 }
3456 return $retVal;
3457 }
3458
3459 /**
3460 * Get a list of URLs to purge from the Squid cache when this
3461 * page changes
3462 *
3463 * @return Array of String the URLs
3464 */
3465 public function getSquidURLs() {
3466 $urls = array(
3467 $this->getInternalURL(),
3468 $this->getInternalURL( 'action=history' )
3469 );
3470
3471 $pageLang = $this->getPageLanguage();
3472 if ( $pageLang->hasVariants() ) {
3473 $variants = $pageLang->getVariants();
3474 foreach ( $variants as $vCode ) {
3475 $urls[] = $this->getInternalURL( '', $vCode );
3476 }
3477 }
3478
3479 // If we are looking at a css/js user subpage, purge the action=raw.
3480 if ( $this->isJsSubpage() ) {
3481 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/javascript' );
3482 } elseif ( $this->isCssSubpage() ) {
3483 $urls[] = $this->getInternalUrl( 'action=raw&ctype=text/css' );
3484 }
3485
3486 wfRunHooks( 'TitleSquidURLs', array( $this, &$urls ) );
3487 return $urls;
3488 }
3489
3490 /**
3491 * Purge all applicable Squid URLs
3492 */
3493 public function purgeSquid() {
3494 global $wgUseSquid;
3495 if ( $wgUseSquid ) {
3496 $urls = $this->getSquidURLs();
3497 $u = new SquidUpdate( $urls );
3498 $u->doUpdate();
3499 }
3500 }
3501
3502 /**
3503 * Move this page without authentication
3504 *
3505 * @param $nt Title the new page Title
3506 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3507 */
3508 public function moveNoAuth( &$nt ) {
3509 return $this->moveTo( $nt, false );
3510 }
3511
3512 /**
3513 * Check whether a given move operation would be valid.
3514 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3515 *
3516 * @param $nt Title the new title
3517 * @param bool $auth indicates whether $wgUser's permissions
3518 * should be checked
3519 * @param string $reason is the log summary of the move, used for spam checking
3520 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3521 */
3522 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3523 global $wgUser, $wgContentHandlerUseDB;
3524
3525 $errors = array();
3526 if ( !$nt ) {
3527 // Normally we'd add this to $errors, but we'll get
3528 // lots of syntax errors if $nt is not an object
3529 return array( array( 'badtitletext' ) );
3530 }
3531 if ( $this->equals( $nt ) ) {
3532 $errors[] = array( 'selfmove' );
3533 }
3534 if ( !$this->isMovable() ) {
3535 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3536 }
3537 if ( $nt->isExternal() ) {
3538 $errors[] = array( 'immobile-target-namespace-iw' );
3539 }
3540 if ( !$nt->isMovable() ) {
3541 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3542 }
3543
3544 $oldid = $this->getArticleID();
3545 $newid = $nt->getArticleID();
3546
3547 if ( strlen( $nt->getDBkey() ) < 1 ) {
3548 $errors[] = array( 'articleexists' );
3549 }
3550 if (
3551 ( $this->getDBkey() == '' ) ||
3552 ( !$oldid ) ||
3553 ( $nt->getDBkey() == '' )
3554 ) {
3555 $errors[] = array( 'badarticleerror' );
3556 }
3557
3558 // Content model checks
3559 if ( !$wgContentHandlerUseDB &&
3560 $this->getContentModel() !== $nt->getContentModel() ) {
3561 // can't move a page if that would change the page's content model
3562 $errors[] = array(
3563 'bad-target-model',
3564 ContentHandler::getLocalizedName( $this->getContentModel() ),
3565 ContentHandler::getLocalizedName( $nt->getContentModel() )
3566 );
3567 }
3568
3569 // Image-specific checks
3570 if ( $this->getNamespace() == NS_FILE ) {
3571 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3572 }
3573
3574 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3575 $errors[] = array( 'nonfile-cannot-move-to-file' );
3576 }
3577
3578 if ( $auth ) {
3579 $errors = wfMergeErrorArrays( $errors,
3580 $this->getUserPermissionsErrors( 'move', $wgUser ),
3581 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3582 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3583 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3584 }
3585
3586 $match = EditPage::matchSummarySpamRegex( $reason );
3587 if ( $match !== false ) {
3588 // This is kind of lame, won't display nice
3589 $errors[] = array( 'spamprotectiontext' );
3590 }
3591
3592 $err = null;
3593 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3594 $errors[] = array( 'hookaborted', $err );
3595 }
3596
3597 # The move is allowed only if (1) the target doesn't exist, or
3598 # (2) the target is a redirect to the source, and has no history
3599 # (so we can undo bad moves right after they're done).
3600
3601 if ( 0 != $newid ) { # Target exists; check for validity
3602 if ( !$this->isValidMoveTarget( $nt ) ) {
3603 $errors[] = array( 'articleexists' );
3604 }
3605 } else {
3606 $tp = $nt->getTitleProtection();
3607 $right = $tp['pt_create_perm'];
3608 if ( $right == 'sysop' ) {
3609 $right = 'editprotected'; // B/C
3610 }
3611 if ( $right == 'autoconfirmed' ) {
3612 $right = 'editsemiprotected'; // B/C
3613 }
3614 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3615 $errors[] = array( 'cantmove-titleprotected' );
3616 }
3617 }
3618 if ( empty( $errors ) ) {
3619 return true;
3620 }
3621 return $errors;
3622 }
3623
3624 /**
3625 * Check if the requested move target is a valid file move target
3626 * @param Title $nt Target title
3627 * @return array List of errors
3628 */
3629 protected function validateFileMoveOperation( $nt ) {
3630 global $wgUser;
3631
3632 $errors = array();
3633
3634 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3635
3636 $file = wfLocalFile( $this );
3637 if ( $file->exists() ) {
3638 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3639 $errors[] = array( 'imageinvalidfilename' );
3640 }
3641 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3642 $errors[] = array( 'imagetypemismatch' );
3643 }
3644 }
3645
3646 if ( $nt->getNamespace() != NS_FILE ) {
3647 $errors[] = array( 'imagenocrossnamespace' );
3648 // From here we want to do checks on a file object, so if we can't
3649 // create one, we must return.
3650 return $errors;
3651 }
3652
3653 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3654
3655 $destFile = wfLocalFile( $nt );
3656 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3657 $errors[] = array( 'file-exists-sharedrepo' );
3658 }
3659
3660 return $errors;
3661 }
3662
3663 /**
3664 * Move a title to a new location
3665 *
3666 * @param $nt Title the new title
3667 * @param bool $auth indicates whether $wgUser's permissions
3668 * should be checked
3669 * @param string $reason the reason for the move
3670 * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
3671 * Ignored if the user doesn't have the suppressredirect right.
3672 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3673 */
3674 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3675 global $wgUser;
3676 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3677 if ( is_array( $err ) ) {
3678 // Auto-block user's IP if the account was "hard" blocked
3679 $wgUser->spreadAnyEditBlock();
3680 return $err;
3681 }
3682 // Check suppressredirect permission
3683 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3684 $createRedirect = true;
3685 }
3686
3687 wfRunHooks( 'TitleMove', array( $this, $nt, $wgUser ) );
3688
3689 // If it is a file, move it first.
3690 // It is done before all other moving stuff is done because it's hard to revert.
3691 $dbw = wfGetDB( DB_MASTER );
3692 if ( $this->getNamespace() == NS_FILE ) {
3693 $file = wfLocalFile( $this );
3694 if ( $file->exists() ) {
3695 $status = $file->move( $nt );
3696 if ( !$status->isOk() ) {
3697 return $status->getErrorsArray();
3698 }
3699 }
3700 // Clear RepoGroup process cache
3701 RepoGroup::singleton()->clearCache( $this );
3702 RepoGroup::singleton()->clearCache( $nt ); # clear false negative cache
3703 }
3704
3705 $dbw->begin( __METHOD__ ); # If $file was a LocalFile, its transaction would have closed our own.
3706 $pageid = $this->getArticleID( self::GAID_FOR_UPDATE );
3707 $protected = $this->isProtected();
3708
3709 // Do the actual move
3710 $this->moveToInternal( $nt, $reason, $createRedirect );
3711
3712 // Refresh the sortkey for this row. Be careful to avoid resetting
3713 // cl_timestamp, which may disturb time-based lists on some sites.
3714 $prefixes = $dbw->select(
3715 'categorylinks',
3716 array( 'cl_sortkey_prefix', 'cl_to' ),
3717 array( 'cl_from' => $pageid ),
3718 __METHOD__
3719 );
3720 foreach ( $prefixes as $prefixRow ) {
3721 $prefix = $prefixRow->cl_sortkey_prefix;
3722 $catTo = $prefixRow->cl_to;
3723 $dbw->update( 'categorylinks',
3724 array(
3725 'cl_sortkey' => Collation::singleton()->getSortKey(
3726 $nt->getCategorySortkey( $prefix ) ),
3727 'cl_timestamp=cl_timestamp' ),
3728 array(
3729 'cl_from' => $pageid,
3730 'cl_to' => $catTo ),
3731 __METHOD__
3732 );
3733 }
3734
3735 $redirid = $this->getArticleID();
3736
3737 if ( $protected ) {
3738 # Protect the redirect title as the title used to be...
3739 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3740 array(
3741 'pr_page' => $redirid,
3742 'pr_type' => 'pr_type',
3743 'pr_level' => 'pr_level',
3744 'pr_cascade' => 'pr_cascade',
3745 'pr_user' => 'pr_user',
3746 'pr_expiry' => 'pr_expiry'
3747 ),
3748 array( 'pr_page' => $pageid ),
3749 __METHOD__,
3750 array( 'IGNORE' )
3751 );
3752 # Update the protection log
3753 $log = new LogPage( 'protect' );
3754 $comment = wfMessage(
3755 'prot_1movedto2',
3756 $this->getPrefixedText(),
3757 $nt->getPrefixedText()
3758 )->inContentLanguage()->text();
3759 if ( $reason ) {
3760 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3761 }
3762 // @todo FIXME: $params?
3763 $logId = $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ), $wgUser );
3764
3765 // reread inserted pr_ids for log relation
3766 $insertedPrIds = $dbw->select(
3767 'page_restrictions',
3768 'pr_id',
3769 array( 'pr_page' => $redirid ),
3770 __METHOD__
3771 );
3772 $logRelationsValues = array();
3773 foreach ( $insertedPrIds as $prid ) {
3774 $logRelationsValues[] = $prid->pr_id;
3775 }
3776 $log->addRelations( 'pr_id', $logRelationsValues, $logId );
3777 }
3778
3779 # Update watchlists
3780 $oldnamespace = MWNamespace::getSubject( $this->getNamespace() );
3781 $newnamespace = MWNamespace::getSubject( $nt->getNamespace() );
3782 $oldtitle = $this->getDBkey();
3783 $newtitle = $nt->getDBkey();
3784
3785 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3786 WatchedItem::duplicateEntries( $this, $nt );
3787 }
3788
3789 $dbw->commit( __METHOD__ );
3790
3791 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid, $reason ) );
3792 return true;
3793 }
3794
3795 /**
3796 * Move page to a title which is either a redirect to the
3797 * source page or nonexistent
3798 *
3799 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3800 * @param string $reason The reason for the move
3801 * @param bool $createRedirect Whether to leave a redirect at the old title. Does not check
3802 * if the user has the suppressredirect right
3803 * @throws MWException
3804 */
3805 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3806 global $wgUser, $wgContLang;
3807
3808 if ( $nt->exists() ) {
3809 $moveOverRedirect = true;
3810 $logType = 'move_redir';
3811 } else {
3812 $moveOverRedirect = false;
3813 $logType = 'move';
3814 }
3815
3816 if ( $createRedirect ) {
3817 $contentHandler = ContentHandler::getForTitle( $this );
3818 $redirectContent = $contentHandler->makeRedirectContent( $nt,
3819 wfMessage( 'move-redirect-text' )->inContentLanguage()->plain() );
3820
3821 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
3822 } else {
3823 $redirectContent = null;
3824 }
3825
3826 $logEntry = new ManualLogEntry( 'move', $logType );
3827 $logEntry->setPerformer( $wgUser );
3828 $logEntry->setTarget( $this );
3829 $logEntry->setComment( $reason );
3830 $logEntry->setParameters( array(
3831 '4::target' => $nt->getPrefixedText(),
3832 '5::noredir' => $redirectContent ? '0': '1',
3833 ) );
3834
3835 $formatter = LogFormatter::newFromEntry( $logEntry );
3836 $formatter->setContext( RequestContext::newExtraneousContext( $this ) );
3837 $comment = $formatter->getPlainActionText();
3838 if ( $reason ) {
3839 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3840 }
3841 # Truncate for whole multibyte characters.
3842 $comment = $wgContLang->truncate( $comment, 255 );
3843
3844 $oldid = $this->getArticleID();
3845
3846 $dbw = wfGetDB( DB_MASTER );
3847
3848 $newpage = WikiPage::factory( $nt );
3849
3850 if ( $moveOverRedirect ) {
3851 $newid = $nt->getArticleID();
3852 $newcontent = $newpage->getContent();
3853
3854 # Delete the old redirect. We don't save it to history since
3855 # by definition if we've got here it's rather uninteresting.
3856 # We have to remove it so that the next step doesn't trigger
3857 # a conflict on the unique namespace+title index...
3858 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3859
3860 $newpage->doDeleteUpdates( $newid, $newcontent );
3861 }
3862
3863 # Save a null revision in the page's history notifying of the move
3864 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3865 if ( !is_object( $nullRevision ) ) {
3866 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3867 }
3868
3869 $nullRevision->insertOn( $dbw );
3870
3871 # Change the name of the target page:
3872 $dbw->update( 'page',
3873 /* SET */ array(
3874 'page_namespace' => $nt->getNamespace(),
3875 'page_title' => $nt->getDBkey(),
3876 ),
3877 /* WHERE */ array( 'page_id' => $oldid ),
3878 __METHOD__
3879 );
3880
3881 // clean up the old title before reset article id - bug 45348
3882 if ( !$redirectContent ) {
3883 WikiPage::onArticleDelete( $this );
3884 }
3885
3886 $this->resetArticleID( 0 ); // 0 == non existing
3887 $nt->resetArticleID( $oldid );
3888 $newpage->loadPageData( WikiPage::READ_LOCKING ); // bug 46397
3889
3890 $newpage->updateRevisionOn( $dbw, $nullRevision );
3891
3892 wfRunHooks( 'NewRevisionFromEditComplete',
3893 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3894
3895 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3896
3897 if ( !$moveOverRedirect ) {
3898 WikiPage::onArticleCreate( $nt );
3899 }
3900
3901 # Recreate the redirect, this time in the other direction.
3902 if ( $redirectContent ) {
3903 $redirectArticle = WikiPage::factory( $this );
3904 $redirectArticle->loadFromRow( false, WikiPage::READ_LOCKING ); // bug 46397
3905 $newid = $redirectArticle->insertOn( $dbw );
3906 if ( $newid ) { // sanity
3907 $this->resetArticleID( $newid );
3908 $redirectRevision = new Revision( array(
3909 'title' => $this, // for determining the default content model
3910 'page' => $newid,
3911 'comment' => $comment,
3912 'content' => $redirectContent ) );
3913 $redirectRevision->insertOn( $dbw );
3914 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3915
3916 wfRunHooks( 'NewRevisionFromEditComplete',
3917 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3918
3919 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3920 }
3921 }
3922
3923 # Log the move
3924 $logid = $logEntry->insert();
3925 $logEntry->publish( $logid );
3926 }
3927
3928 /**
3929 * Move this page's subpages to be subpages of $nt
3930 *
3931 * @param $nt Title Move target
3932 * @param bool $auth Whether $wgUser's permissions should be checked
3933 * @param string $reason The reason for the move
3934 * @param bool $createRedirect Whether to create redirects from the old subpages to
3935 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3936 * @return mixed array with old page titles as keys, and strings (new page titles) or
3937 * arrays (errors) as values, or an error array with numeric indices if no pages
3938 * were moved
3939 */
3940 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3941 global $wgMaximumMovedPages;
3942 // Check permissions
3943 if ( !$this->userCan( 'move-subpages' ) ) {
3944 return array( 'cant-move-subpages' );
3945 }
3946 // Do the source and target namespaces support subpages?
3947 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3948 return array( 'namespace-nosubpages',
3949 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3950 }
3951 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3952 return array( 'namespace-nosubpages',
3953 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3954 }
3955
3956 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3957 $retval = array();
3958 $count = 0;
3959 foreach ( $subpages as $oldSubpage ) {
3960 $count++;
3961 if ( $count > $wgMaximumMovedPages ) {
3962 $retval[$oldSubpage->getPrefixedText()] =
3963 array( 'movepage-max-pages',
3964 $wgMaximumMovedPages );
3965 break;
3966 }
3967
3968 // We don't know whether this function was called before
3969 // or after moving the root page, so check both
3970 // $this and $nt
3971 if ( $oldSubpage->getArticleID() == $this->getArticleID()
3972 || $oldSubpage->getArticleID() == $nt->getArticleID()
3973 ) {
3974 // When moving a page to a subpage of itself,
3975 // don't move it twice
3976 continue;
3977 }
3978 $newPageName = preg_replace(
3979 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3980 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3981 $oldSubpage->getDBkey() );
3982 if ( $oldSubpage->isTalkPage() ) {
3983 $newNs = $nt->getTalkPage()->getNamespace();
3984 } else {
3985 $newNs = $nt->getSubjectPage()->getNamespace();
3986 }
3987 # Bug 14385: we need makeTitleSafe because the new page names may
3988 # be longer than 255 characters.
3989 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3990
3991 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3992 if ( $success === true ) {
3993 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3994 } else {
3995 $retval[$oldSubpage->getPrefixedText()] = $success;
3996 }
3997 }
3998 return $retval;
3999 }
4000
4001 /**
4002 * Checks if this page is just a one-rev redirect.
4003 * Adds lock, so don't use just for light purposes.
4004 *
4005 * @return Bool
4006 */
4007 public function isSingleRevRedirect() {
4008 global $wgContentHandlerUseDB;
4009
4010 $dbw = wfGetDB( DB_MASTER );
4011
4012 # Is it a redirect?
4013 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
4014 if ( $wgContentHandlerUseDB ) {
4015 $fields[] = 'page_content_model';
4016 }
4017
4018 $row = $dbw->selectRow( 'page',
4019 $fields,
4020 $this->pageCond(),
4021 __METHOD__,
4022 array( 'FOR UPDATE' )
4023 );
4024 # Cache some fields we may want
4025 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
4026 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
4027 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
4028 $this->mContentModel = $row && isset( $row->page_content_model ) ? strval( $row->page_content_model ) : false;
4029 if ( !$this->mRedirect ) {
4030 return false;
4031 }
4032 # Does the article have a history?
4033 $row = $dbw->selectField( array( 'page', 'revision' ),
4034 'rev_id',
4035 array( 'page_namespace' => $this->getNamespace(),
4036 'page_title' => $this->getDBkey(),
4037 'page_id=rev_page',
4038 'page_latest != rev_id'
4039 ),
4040 __METHOD__,
4041 array( 'FOR UPDATE' )
4042 );
4043 # Return true if there was no history
4044 return ( $row === false );
4045 }
4046
4047 /**
4048 * Checks if $this can be moved to a given Title
4049 * - Selects for update, so don't call it unless you mean business
4050 *
4051 * @param $nt Title the new title to check
4052 * @return Bool
4053 */
4054 public function isValidMoveTarget( $nt ) {
4055 # Is it an existing file?
4056 if ( $nt->getNamespace() == NS_FILE ) {
4057 $file = wfLocalFile( $nt );
4058 if ( $file->exists() ) {
4059 wfDebug( __METHOD__ . ": file exists\n" );
4060 return false;
4061 }
4062 }
4063 # Is it a redirect with no history?
4064 if ( !$nt->isSingleRevRedirect() ) {
4065 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
4066 return false;
4067 }
4068 # Get the article text
4069 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
4070 if ( !is_object( $rev ) ) {
4071 return false;
4072 }
4073 $content = $rev->getContent();
4074 # Does the redirect point to the source?
4075 # Or is it a broken self-redirect, usually caused by namespace collisions?
4076 $redirTitle = $content ? $content->getRedirectTarget() : null;
4077
4078 if ( $redirTitle ) {
4079 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4080 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4081 wfDebug( __METHOD__ . ": redirect points to other page\n" );
4082 return false;
4083 } else {
4084 return true;
4085 }
4086 } else {
4087 # Fail safe (not a redirect after all. strange.)
4088 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4089 " is a redirect, but it doesn't contain a valid redirect.\n" );
4090 return false;
4091 }
4092 }
4093
4094 /**
4095 * Get categories to which this Title belongs and return an array of
4096 * categories' names.
4097 *
4098 * @return Array of parents in the form:
4099 * $parent => $currentarticle
4100 */
4101 public function getParentCategories() {
4102 global $wgContLang;
4103
4104 $data = array();
4105
4106 $titleKey = $this->getArticleID();
4107
4108 if ( $titleKey === 0 ) {
4109 return $data;
4110 }
4111
4112 $dbr = wfGetDB( DB_SLAVE );
4113
4114 $res = $dbr->select(
4115 'categorylinks',
4116 'cl_to',
4117 array( 'cl_from' => $titleKey ),
4118 __METHOD__
4119 );
4120
4121 if ( $res->numRows() > 0 ) {
4122 foreach ( $res as $row ) {
4123 // $data[] = Title::newFromText($wgContLang->getNsText ( NS_CATEGORY ).':'.$row->cl_to);
4124 $data[$wgContLang->getNsText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
4125 }
4126 }
4127 return $data;
4128 }
4129
4130 /**
4131 * Get a tree of parent categories
4132 *
4133 * @param array $children with the children in the keys, to check for circular refs
4134 * @return Array Tree of parent categories
4135 */
4136 public function getParentCategoryTree( $children = array() ) {
4137 $stack = array();
4138 $parents = $this->getParentCategories();
4139
4140 if ( $parents ) {
4141 foreach ( $parents as $parent => $current ) {
4142 if ( array_key_exists( $parent, $children ) ) {
4143 # Circular reference
4144 $stack[$parent] = array();
4145 } else {
4146 $nt = Title::newFromText( $parent );
4147 if ( $nt ) {
4148 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
4149 }
4150 }
4151 }
4152 }
4153
4154 return $stack;
4155 }
4156
4157 /**
4158 * Get an associative array for selecting this title from
4159 * the "page" table
4160 *
4161 * @return Array suitable for the $where parameter of DB::select()
4162 */
4163 public function pageCond() {
4164 if ( $this->mArticleID > 0 ) {
4165 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4166 return array( 'page_id' => $this->mArticleID );
4167 } else {
4168 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
4169 }
4170 }
4171
4172 /**
4173 * Get the revision ID of the previous revision
4174 *
4175 * @param int $revId Revision ID. Get the revision that was before this one.
4176 * @param int $flags Title::GAID_FOR_UPDATE
4177 * @return Int|Bool Old revision ID, or FALSE if none exists
4178 */
4179 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4180 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4181 $revId = $db->selectField( 'revision', 'rev_id',
4182 array(
4183 'rev_page' => $this->getArticleID( $flags ),
4184 'rev_id < ' . intval( $revId )
4185 ),
4186 __METHOD__,
4187 array( 'ORDER BY' => 'rev_id DESC' )
4188 );
4189
4190 if ( $revId === false ) {
4191 return false;
4192 } else {
4193 return intval( $revId );
4194 }
4195 }
4196
4197 /**
4198 * Get the revision ID of the next revision
4199 *
4200 * @param int $revId Revision ID. Get the revision that was after this one.
4201 * @param int $flags Title::GAID_FOR_UPDATE
4202 * @return Int|Bool Next revision ID, or FALSE if none exists
4203 */
4204 public function getNextRevisionID( $revId, $flags = 0 ) {
4205 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4206 $revId = $db->selectField( 'revision', 'rev_id',
4207 array(
4208 'rev_page' => $this->getArticleID( $flags ),
4209 'rev_id > ' . intval( $revId )
4210 ),
4211 __METHOD__,
4212 array( 'ORDER BY' => 'rev_id' )
4213 );
4214
4215 if ( $revId === false ) {
4216 return false;
4217 } else {
4218 return intval( $revId );
4219 }
4220 }
4221
4222 /**
4223 * Get the first revision of the page
4224 *
4225 * @param int $flags Title::GAID_FOR_UPDATE
4226 * @return Revision|Null if page doesn't exist
4227 */
4228 public function getFirstRevision( $flags = 0 ) {
4229 $pageId = $this->getArticleID( $flags );
4230 if ( $pageId ) {
4231 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4232 $row = $db->selectRow( 'revision', Revision::selectFields(),
4233 array( 'rev_page' => $pageId ),
4234 __METHOD__,
4235 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4236 );
4237 if ( $row ) {
4238 return new Revision( $row );
4239 }
4240 }
4241 return null;
4242 }
4243
4244 /**
4245 * Get the oldest revision timestamp of this page
4246 *
4247 * @param int $flags Title::GAID_FOR_UPDATE
4248 * @return String: MW timestamp
4249 */
4250 public function getEarliestRevTime( $flags = 0 ) {
4251 $rev = $this->getFirstRevision( $flags );
4252 return $rev ? $rev->getTimestamp() : null;
4253 }
4254
4255 /**
4256 * Check if this is a new page
4257 *
4258 * @return bool
4259 */
4260 public function isNewPage() {
4261 $dbr = wfGetDB( DB_SLAVE );
4262 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4263 }
4264
4265 /**
4266 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4267 *
4268 * @return bool
4269 */
4270 public function isBigDeletion() {
4271 global $wgDeleteRevisionsLimit;
4272
4273 if ( !$wgDeleteRevisionsLimit ) {
4274 return false;
4275 }
4276
4277 $revCount = $this->estimateRevisionCount();
4278 return $revCount > $wgDeleteRevisionsLimit;
4279 }
4280
4281 /**
4282 * Get the approximate revision count of this page.
4283 *
4284 * @return int
4285 */
4286 public function estimateRevisionCount() {
4287 if ( !$this->exists() ) {
4288 return 0;
4289 }
4290
4291 if ( $this->mEstimateRevisions === null ) {
4292 $dbr = wfGetDB( DB_SLAVE );
4293 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4294 array( 'rev_page' => $this->getArticleID() ), __METHOD__ );
4295 }
4296
4297 return $this->mEstimateRevisions;
4298 }
4299
4300 /**
4301 * Get the number of revisions between the given revision.
4302 * Used for diffs and other things that really need it.
4303 *
4304 * @param int|Revision $old Old revision or rev ID (first before range)
4305 * @param int|Revision $new New revision or rev ID (first after range)
4306 * @param int|null $max Limit of Revisions to count, will be incremented to detect truncations
4307 * @return Int Number of revisions between these revisions.
4308 */
4309 public function countRevisionsBetween( $old, $new, $max = null ) {
4310 if ( !( $old instanceof Revision ) ) {
4311 $old = Revision::newFromTitle( $this, (int)$old );
4312 }
4313 if ( !( $new instanceof Revision ) ) {
4314 $new = Revision::newFromTitle( $this, (int)$new );
4315 }
4316 if ( !$old || !$new ) {
4317 return 0; // nothing to compare
4318 }
4319 $dbr = wfGetDB( DB_SLAVE );
4320 $conds = array(
4321 'rev_page' => $this->getArticleID(),
4322 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4323 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4324 );
4325 if ( $max !== null ) {
4326 $res = $dbr->select( 'revision', '1',
4327 $conds,
4328 __METHOD__,
4329 array( 'LIMIT' => $max + 1 ) // extra to detect truncation
4330 );
4331 return $res->numRows();
4332 } else {
4333 return (int)$dbr->selectField( 'revision', 'count(*)', $conds, __METHOD__ );
4334 }
4335 }
4336
4337 /**
4338 * Get the authors between the given revisions or revision IDs.
4339 * Used for diffs and other things that really need it.
4340 *
4341 * @since 1.23
4342 *
4343 * @param int|Revision $old Old revision or rev ID (first before range by default)
4344 * @param int|Revision $new New revision or rev ID (first after range by default)
4345 * @param int $limit Maximum number of authors
4346 * @param string|array $options (Optional): Single option, or an array of options:
4347 * 'include_old' Include $old in the range; $new is excluded.
4348 * 'include_new' Include $new in the range; $old is excluded.
4349 * 'include_both' Include both $old and $new in the range.
4350 * Unknown option values are ignored.
4351 * @return array|null Names of revision authors in the range; null if not both revisions exist
4352 */
4353 public function getAuthorsBetween( $old, $new, $limit, $options = array() ) {
4354 if ( !( $old instanceof Revision ) ) {
4355 $old = Revision::newFromTitle( $this, (int)$old );
4356 }
4357 if ( !( $new instanceof Revision ) ) {
4358 $new = Revision::newFromTitle( $this, (int)$new );
4359 }
4360 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4361 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4362 // in the sanity check below?
4363 if ( !$old || !$new ) {
4364 return null; // nothing to compare
4365 }
4366 $authors = array();
4367 $old_cmp = '>';
4368 $new_cmp = '<';
4369 $options = (array)$options;
4370 if ( in_array( 'include_old', $options ) ) {
4371 $old_cmp = '>=';
4372 }
4373 if ( in_array( 'include_new', $options ) ) {
4374 $new_cmp = '<=';
4375 }
4376 if ( in_array( 'include_both', $options ) ) {
4377 $old_cmp = '>=';
4378 $new_cmp = '<=';
4379 }
4380 // No DB query needed if $old and $new are the same or successive revisions:
4381 if ( $old->getId() === $new->getId() ) {
4382 return ( $old_cmp === '>' && $new_cmp === '<' ) ? array() : array( $old->getRawUserText() );
4383 } elseif ( $old->getId() === $new->getParentId() ) {
4384 if ( $old_cmp === '>=' && $new_cmp === '<=' ) {
4385 $authors[] = $old->getRawUserText();
4386 if ( $old->getRawUserText() != $new->getRawUserText() ) {
4387 $authors[] = $new->getRawUserText();
4388 }
4389 } elseif ( $old_cmp === '>=' ) {
4390 $authors[] = $old->getRawUserText();
4391 } elseif ( $new_cmp === '<=' ) {
4392 $authors[] = $new->getRawUserText();
4393 }
4394 return $authors;
4395 }
4396 $dbr = wfGetDB( DB_SLAVE );
4397 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4398 array(
4399 'rev_page' => $this->getArticleID(),
4400 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4401 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4402 ), __METHOD__,
4403 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4404 );
4405 foreach ( $res as $row ) {
4406 $authors[] = $row->rev_user_text;
4407 }
4408 return $authors;
4409 }
4410
4411 /**
4412 * Get the number of authors between the given revisions or revision IDs.
4413 * Used for diffs and other things that really need it.
4414 *
4415 * @param int|Revision $old Old revision or rev ID (first before range by default)
4416 * @param int|Revision $new New revision or rev ID (first after range by default)
4417 * @param int $limit Maximum number of authors
4418 * @param string|array $options (Optional): Single option, or an array of options:
4419 * 'include_old' Include $old in the range; $new is excluded.
4420 * 'include_new' Include $new in the range; $old is excluded.
4421 * 'include_both' Include both $old and $new in the range.
4422 * Unknown option values are ignored.
4423 * @return int Number of revision authors in the range; zero if not both revisions exist
4424 */
4425 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4426 $authors = $this->getAuthorsBetween( $old, $new, $limit, $options );
4427 return $authors ? count( $authors ) : 0;
4428 }
4429
4430 /**
4431 * Compare with another title.
4432 *
4433 * @param $title Title
4434 * @return Bool
4435 */
4436 public function equals( Title $title ) {
4437 // Note: === is necessary for proper matching of number-like titles.
4438 return $this->getInterwiki() === $title->getInterwiki()
4439 && $this->getNamespace() == $title->getNamespace()
4440 && $this->getDBkey() === $title->getDBkey();
4441 }
4442
4443 /**
4444 * Check if this title is a subpage of another title
4445 *
4446 * @param $title Title
4447 * @return Bool
4448 */
4449 public function isSubpageOf( Title $title ) {
4450 return $this->getInterwiki() === $title->getInterwiki()
4451 && $this->getNamespace() == $title->getNamespace()
4452 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4453 }
4454
4455 /**
4456 * Check if page exists. For historical reasons, this function simply
4457 * checks for the existence of the title in the page table, and will
4458 * thus return false for interwiki links, special pages and the like.
4459 * If you want to know if a title can be meaningfully viewed, you should
4460 * probably call the isKnown() method instead.
4461 *
4462 * @return Bool
4463 */
4464 public function exists() {
4465 return $this->getArticleID() != 0;
4466 }
4467
4468 /**
4469 * Should links to this title be shown as potentially viewable (i.e. as
4470 * "bluelinks"), even if there's no record by this title in the page
4471 * table?
4472 *
4473 * This function is semi-deprecated for public use, as well as somewhat
4474 * misleadingly named. You probably just want to call isKnown(), which
4475 * calls this function internally.
4476 *
4477 * (ISSUE: Most of these checks are cheap, but the file existence check
4478 * can potentially be quite expensive. Including it here fixes a lot of
4479 * existing code, but we might want to add an optional parameter to skip
4480 * it and any other expensive checks.)
4481 *
4482 * @return Bool
4483 */
4484 public function isAlwaysKnown() {
4485 $isKnown = null;
4486
4487 /**
4488 * Allows overriding default behavior for determining if a page exists.
4489 * If $isKnown is kept as null, regular checks happen. If it's
4490 * a boolean, this value is returned by the isKnown method.
4491 *
4492 * @since 1.20
4493 *
4494 * @param Title $title
4495 * @param boolean|null $isKnown
4496 */
4497 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4498
4499 if ( !is_null( $isKnown ) ) {
4500 return $isKnown;
4501 }
4502
4503 if ( $this->isExternal() ) {
4504 return true; // any interwiki link might be viewable, for all we know
4505 }
4506
4507 switch ( $this->mNamespace ) {
4508 case NS_MEDIA:
4509 case NS_FILE:
4510 // file exists, possibly in a foreign repo
4511 return (bool)wfFindFile( $this );
4512 case NS_SPECIAL:
4513 // valid special page
4514 return SpecialPageFactory::exists( $this->getDBkey() );
4515 case NS_MAIN:
4516 // selflink, possibly with fragment
4517 return $this->mDbkeyform == '';
4518 case NS_MEDIAWIKI:
4519 // known system message
4520 return $this->hasSourceText() !== false;
4521 default:
4522 return false;
4523 }
4524 }
4525
4526 /**
4527 * Does this title refer to a page that can (or might) be meaningfully
4528 * viewed? In particular, this function may be used to determine if
4529 * links to the title should be rendered as "bluelinks" (as opposed to
4530 * "redlinks" to non-existent pages).
4531 * Adding something else to this function will cause inconsistency
4532 * since LinkHolderArray calls isAlwaysKnown() and does its own
4533 * page existence check.
4534 *
4535 * @return Bool
4536 */
4537 public function isKnown() {
4538 return $this->isAlwaysKnown() || $this->exists();
4539 }
4540
4541 /**
4542 * Does this page have source text?
4543 *
4544 * @return Boolean
4545 */
4546 public function hasSourceText() {
4547 if ( $this->exists() ) {
4548 return true;
4549 }
4550
4551 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4552 // If the page doesn't exist but is a known system message, default
4553 // message content will be displayed, same for language subpages-
4554 // Use always content language to avoid loading hundreds of languages
4555 // to get the link color.
4556 global $wgContLang;
4557 list( $name, ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4558 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4559 return $message->exists();
4560 }
4561
4562 return false;
4563 }
4564
4565 /**
4566 * Get the default message text or false if the message doesn't exist
4567 *
4568 * @return String or false
4569 */
4570 public function getDefaultMessageText() {
4571 global $wgContLang;
4572
4573 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4574 return false;
4575 }
4576
4577 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4578 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4579
4580 if ( $message->exists() ) {
4581 return $message->plain();
4582 } else {
4583 return false;
4584 }
4585 }
4586
4587 /**
4588 * Updates page_touched for this page; called from LinksUpdate.php
4589 *
4590 * @return Bool true if the update succeeded
4591 */
4592 public function invalidateCache() {
4593 if ( wfReadOnly() ) {
4594 return false;
4595 }
4596
4597 $method = __METHOD__;
4598 $dbw = wfGetDB( DB_MASTER );
4599 $conds = $this->pageCond();
4600 $dbw->onTransactionIdle( function() use ( $dbw, $conds, $method ) {
4601 $dbw->update(
4602 'page',
4603 array( 'page_touched' => $dbw->timestamp() ),
4604 $conds,
4605 $method
4606 );
4607 } );
4608
4609 return true;
4610 }
4611
4612 /**
4613 * Update page_touched timestamps and send squid purge messages for
4614 * pages linking to this title. May be sent to the job queue depending
4615 * on the number of links. Typically called on create and delete.
4616 */
4617 public function touchLinks() {
4618 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4619 $u->doUpdate();
4620
4621 if ( $this->getNamespace() == NS_CATEGORY ) {
4622 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4623 $u->doUpdate();
4624 }
4625 }
4626
4627 /**
4628 * Get the last touched timestamp
4629 *
4630 * @param $db DatabaseBase: optional db
4631 * @return String last-touched timestamp
4632 */
4633 public function getTouched( $db = null ) {
4634 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
4635 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4636 return $touched;
4637 }
4638
4639 /**
4640 * Get the timestamp when this page was updated since the user last saw it.
4641 *
4642 * @param $user User
4643 * @return String|Null
4644 */
4645 public function getNotificationTimestamp( $user = null ) {
4646 global $wgUser, $wgShowUpdatedMarker;
4647 // Assume current user if none given
4648 if ( !$user ) {
4649 $user = $wgUser;
4650 }
4651 // Check cache first
4652 $uid = $user->getId();
4653 // avoid isset here, as it'll return false for null entries
4654 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4655 return $this->mNotificationTimestamp[$uid];
4656 }
4657 if ( !$uid || !$wgShowUpdatedMarker || !$user->isAllowed( 'viewmywatchlist' ) ) {
4658 $this->mNotificationTimestamp[$uid] = false;
4659 return $this->mNotificationTimestamp[$uid];
4660 }
4661 // Don't cache too much!
4662 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4663 $this->mNotificationTimestamp = array();
4664 }
4665 $dbr = wfGetDB( DB_SLAVE );
4666 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
4667 'wl_notificationtimestamp',
4668 array(
4669 'wl_user' => $user->getId(),
4670 'wl_namespace' => $this->getNamespace(),
4671 'wl_title' => $this->getDBkey(),
4672 ),
4673 __METHOD__
4674 );
4675 return $this->mNotificationTimestamp[$uid];
4676 }
4677
4678 /**
4679 * Generate strings used for xml 'id' names in monobook tabs
4680 *
4681 * @param string $prepend defaults to 'nstab-'
4682 * @return String XML 'id' name
4683 */
4684 public function getNamespaceKey( $prepend = 'nstab-' ) {
4685 global $wgContLang;
4686 // Gets the subject namespace if this title
4687 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4688 // Checks if canonical namespace name exists for namespace
4689 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4690 // Uses canonical namespace name
4691 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4692 } else {
4693 // Uses text of namespace
4694 $namespaceKey = $this->getSubjectNsText();
4695 }
4696 // Makes namespace key lowercase
4697 $namespaceKey = $wgContLang->lc( $namespaceKey );
4698 // Uses main
4699 if ( $namespaceKey == '' ) {
4700 $namespaceKey = 'main';
4701 }
4702 // Changes file to image for backwards compatibility
4703 if ( $namespaceKey == 'file' ) {
4704 $namespaceKey = 'image';
4705 }
4706 return $prepend . $namespaceKey;
4707 }
4708
4709 /**
4710 * Get all extant redirects to this Title
4711 *
4712 * @param int|Null $ns Single namespace to consider; NULL to consider all namespaces
4713 * @return Title[] Array of Title redirects to this title
4714 */
4715 public function getRedirectsHere( $ns = null ) {
4716 $redirs = array();
4717
4718 $dbr = wfGetDB( DB_SLAVE );
4719 $where = array(
4720 'rd_namespace' => $this->getNamespace(),
4721 'rd_title' => $this->getDBkey(),
4722 'rd_from = page_id'
4723 );
4724 if ( $this->isExternal() ) {
4725 $where['rd_interwiki'] = $this->getInterwiki();
4726 } else {
4727 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4728 }
4729 if ( !is_null( $ns ) ) {
4730 $where['page_namespace'] = $ns;
4731 }
4732
4733 $res = $dbr->select(
4734 array( 'redirect', 'page' ),
4735 array( 'page_namespace', 'page_title' ),
4736 $where,
4737 __METHOD__
4738 );
4739
4740 foreach ( $res as $row ) {
4741 $redirs[] = self::newFromRow( $row );
4742 }
4743 return $redirs;
4744 }
4745
4746 /**
4747 * Check if this Title is a valid redirect target
4748 *
4749 * @return Bool
4750 */
4751 public function isValidRedirectTarget() {
4752 global $wgInvalidRedirectTargets;
4753
4754 // invalid redirect targets are stored in a global array, but explicitly disallow Userlogout here
4755 if ( $this->isSpecial( 'Userlogout' ) ) {
4756 return false;
4757 }
4758
4759 foreach ( $wgInvalidRedirectTargets as $target ) {
4760 if ( $this->isSpecial( $target ) ) {
4761 return false;
4762 }
4763 }
4764
4765 return true;
4766 }
4767
4768 /**
4769 * Get a backlink cache object
4770 *
4771 * @return BacklinkCache
4772 */
4773 public function getBacklinkCache() {
4774 return BacklinkCache::get( $this );
4775 }
4776
4777 /**
4778 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4779 *
4780 * @return Boolean
4781 */
4782 public function canUseNoindex() {
4783 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4784
4785 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4786 ? $wgContentNamespaces
4787 : $wgExemptFromUserRobotsControl;
4788
4789 return !in_array( $this->mNamespace, $bannedNamespaces );
4790
4791 }
4792
4793 /**
4794 * Returns the raw sort key to be used for categories, with the specified
4795 * prefix. This will be fed to Collation::getSortKey() to get a
4796 * binary sortkey that can be used for actual sorting.
4797 *
4798 * @param string $prefix The prefix to be used, specified using
4799 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4800 * prefix.
4801 * @return string
4802 */
4803 public function getCategorySortkey( $prefix = '' ) {
4804 $unprefixed = $this->getText();
4805
4806 // Anything that uses this hook should only depend
4807 // on the Title object passed in, and should probably
4808 // tell the users to run updateCollations.php --force
4809 // in order to re-sort existing category relations.
4810 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4811 if ( $prefix !== '' ) {
4812 # Separate with a line feed, so the unprefixed part is only used as
4813 # a tiebreaker when two pages have the exact same prefix.
4814 # In UCA, tab is the only character that can sort above LF
4815 # so we strip both of them from the original prefix.
4816 $prefix = strtr( $prefix, "\n\t", ' ' );
4817 return "$prefix\n$unprefixed";
4818 }
4819 return $unprefixed;
4820 }
4821
4822 /**
4823 * Get the language in which the content of this page is written in
4824 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4825 * e.g. $wgLang (such as special pages, which are in the user language).
4826 *
4827 * @since 1.18
4828 * @return Language
4829 */
4830 public function getPageLanguage() {
4831 global $wgLang, $wgLanguageCode;
4832 wfProfileIn( __METHOD__ );
4833 if ( $this->isSpecialPage() ) {
4834 // special pages are in the user language
4835 wfProfileOut( __METHOD__ );
4836 return $wgLang;
4837 }
4838
4839 if ( !$this->mPageLanguage || $this->mPageLanguage[1] !== $wgLanguageCode ) {
4840 // Note that this may depend on user settings, so the cache should be only per-request.
4841 // NOTE: ContentHandler::getPageLanguage() may need to load the content to determine the page language!
4842 // Checking $wgLanguageCode hasn't changed for the benefit of unit tests.
4843 $contentHandler = ContentHandler::getForTitle( $this );
4844 $langObj = wfGetLangObj( $contentHandler->getPageLanguage( $this ) );
4845 $this->mPageLanguage = array( $langObj->getCode(), $wgLanguageCode );
4846 } else {
4847 $langObj = wfGetLangObj( $this->mPageLanguage[0] );
4848 }
4849 wfProfileOut( __METHOD__ );
4850 return $langObj;
4851 }
4852
4853 /**
4854 * Get the language in which the content of this page is written when
4855 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4856 * e.g. $wgLang (such as special pages, which are in the user language).
4857 *
4858 * @since 1.20
4859 * @return Language
4860 */
4861 public function getPageViewLanguage() {
4862 global $wgLang;
4863
4864 if ( $this->isSpecialPage() ) {
4865 // If the user chooses a variant, the content is actually
4866 // in a language whose code is the variant code.
4867 $variant = $wgLang->getPreferredVariant();
4868 if ( $wgLang->getCode() !== $variant ) {
4869 return Language::factory( $variant );
4870 }
4871
4872 return $wgLang;
4873 }
4874
4875 //NOTE: can't be cached persistently, depends on user settings
4876 //NOTE: ContentHandler::getPageViewLanguage() may need to load the content to determine the page language!
4877 $contentHandler = ContentHandler::getForTitle( $this );
4878 $pageLang = $contentHandler->getPageViewLanguage( $this );
4879 return $pageLang;
4880 }
4881
4882 /**
4883 * Get a list of rendered edit notices for this page.
4884 *
4885 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4886 * they will already be wrapped in paragraphs.
4887 *
4888 * @since 1.21
4889 * @param int $oldid Revision ID that's being edited
4890 * @return Array
4891 */
4892 public function getEditNotices( $oldid = 0 ) {
4893 $notices = array();
4894
4895 # Optional notices on a per-namespace and per-page basis
4896 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4897 $editnotice_ns_message = wfMessage( $editnotice_ns );
4898 if ( $editnotice_ns_message->exists() ) {
4899 $notices[$editnotice_ns] = $editnotice_ns_message->parseAsBlock();
4900 }
4901 if ( MWNamespace::hasSubpages( $this->getNamespace() ) ) {
4902 $parts = explode( '/', $this->getDBkey() );
4903 $editnotice_base = $editnotice_ns;
4904 while ( count( $parts ) > 0 ) {
4905 $editnotice_base .= '-' . array_shift( $parts );
4906 $editnotice_base_msg = wfMessage( $editnotice_base );
4907 if ( $editnotice_base_msg->exists() ) {
4908 $notices[$editnotice_base] = $editnotice_base_msg->parseAsBlock();
4909 }
4910 }
4911 } else {
4912 # Even if there are no subpages in namespace, we still don't want / in MW ns.
4913 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
4914 $editnoticeMsg = wfMessage( $editnoticeText );
4915 if ( $editnoticeMsg->exists() ) {
4916 $notices[$editnoticeText] = $editnoticeMsg->parseAsBlock();
4917 }
4918 }
4919
4920 wfRunHooks( 'TitleGetEditNotices', array( $this, $oldid, &$notices ) );
4921 return $notices;
4922 }
4923 }