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