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