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