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