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