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