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