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