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