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