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