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