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