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