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