fixing getAutoDeleteReason:
[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 ) { #TODO: move to Content class, deprecate here.
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 * Convenience 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 #XXX breaks stuff #TODO: use exception
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 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
2898 assert( $cached !== null ); # assert the assumption that the cache actually knows about this title #TODO: use exception
2899
2900 $this->mLength = intval( $cached );
2901
2902 return $this->mLength;
2903 }
2904
2905 /**
2906 * What is the page_latest field for this page?
2907 *
2908 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2909 * @return Int or 0 if the page doesn't exist
2910 */
2911 public function getLatestRevID( $flags = 0 ) {
2912 if ( $this->mLatestID !== false ) {
2913 return intval( $this->mLatestID );
2914 }
2915 # Calling getArticleID() loads the field from cache as needed
2916 if ( !$this->getArticleID( $flags ) ) {
2917 return $this->mLatestID = 0;
2918 }
2919 $linkCache = LinkCache::singleton();
2920 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
2921 assert( $cached !== null ); # assert the assumption that the cache actually knows about this title #TODO: use exception
2922
2923 $this->mLatestID = intval( $cached );
2924
2925 return $this->mLatestID;
2926 }
2927
2928 /**
2929 * This clears some fields in this object, and clears any associated
2930 * keys in the "bad links" section of the link cache.
2931 *
2932 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
2933 * loading of the new page_id. It's also called from
2934 * WikiPage::doDeleteArticle()
2935 *
2936 * @param $newid Int the new Article ID
2937 */
2938 public function resetArticleID( $newid ) {
2939 $linkCache = LinkCache::singleton();
2940 $linkCache->clearLink( $this );
2941
2942 if ( $newid === false ) {
2943 $this->mArticleID = -1;
2944 } else {
2945 $this->mArticleID = intval( $newid );
2946 }
2947 $this->mRestrictionsLoaded = false;
2948 $this->mRestrictions = array();
2949 $this->mRedirect = null;
2950 $this->mLength = -1;
2951 $this->mLatestID = false;
2952 $this->mEstimateRevisions = null;
2953 }
2954
2955 /**
2956 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2957 *
2958 * @param $text String containing title to capitalize
2959 * @param $ns int namespace index, defaults to NS_MAIN
2960 * @return String containing capitalized title
2961 */
2962 public static function capitalize( $text, $ns = NS_MAIN ) {
2963 global $wgContLang;
2964
2965 if ( MWNamespace::isCapitalized( $ns ) ) {
2966 return $wgContLang->ucfirst( $text );
2967 } else {
2968 return $text;
2969 }
2970 }
2971
2972 /**
2973 * Secure and split - main initialisation function for this object
2974 *
2975 * Assumes that mDbkeyform has been set, and is urldecoded
2976 * and uses underscores, but not otherwise munged. This function
2977 * removes illegal characters, splits off the interwiki and
2978 * namespace prefixes, sets the other forms, and canonicalizes
2979 * everything.
2980 *
2981 * @return Bool true on success
2982 */
2983 private function secureAndSplit() {
2984 global $wgContLang, $wgLocalInterwiki;
2985
2986 # Initialisation
2987 $this->mInterwiki = $this->mFragment = '';
2988 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2989
2990 $dbkey = $this->mDbkeyform;
2991
2992 # Strip Unicode bidi override characters.
2993 # Sometimes they slip into cut-n-pasted page titles, where the
2994 # override chars get included in list displays.
2995 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2996
2997 # Clean up whitespace
2998 # Note: use of the /u option on preg_replace here will cause
2999 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
3000 # conveniently disabling them.
3001 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
3002 $dbkey = trim( $dbkey, '_' );
3003
3004 if ( $dbkey == '' ) {
3005 return false;
3006 }
3007
3008 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
3009 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
3010 return false;
3011 }
3012
3013 $this->mDbkeyform = $dbkey;
3014
3015 # Initial colon indicates main namespace rather than specified default
3016 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
3017 if ( ':' == $dbkey[0] ) {
3018 $this->mNamespace = NS_MAIN;
3019 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
3020 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
3021 }
3022
3023 # Namespace or interwiki prefix
3024 $firstPass = true;
3025 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
3026 do {
3027 $m = array();
3028 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
3029 $p = $m[1];
3030 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
3031 # Ordinary namespace
3032 $dbkey = $m[2];
3033 $this->mNamespace = $ns;
3034 # For Talk:X pages, check if X has a "namespace" prefix
3035 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
3036 if ( $wgContLang->getNsIndex( $x[1] ) ) {
3037 # Disallow Talk:File:x type titles...
3038 return false;
3039 } elseif ( Interwiki::isValidInterwiki( $x[1] ) ) {
3040 # Disallow Talk:Interwiki:x type titles...
3041 return false;
3042 }
3043 }
3044 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
3045 if ( !$firstPass ) {
3046 # Can't make a local interwiki link to an interwiki link.
3047 # That's just crazy!
3048 return false;
3049 }
3050
3051 # Interwiki link
3052 $dbkey = $m[2];
3053 $this->mInterwiki = $wgContLang->lc( $p );
3054
3055 # Redundant interwiki prefix to the local wiki
3056 if ( $wgLocalInterwiki !== false
3057 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
3058 {
3059 if ( $dbkey == '' ) {
3060 # Can't have an empty self-link
3061 return false;
3062 }
3063 $this->mInterwiki = '';
3064 $firstPass = false;
3065 # Do another namespace split...
3066 continue;
3067 }
3068
3069 # If there's an initial colon after the interwiki, that also
3070 # resets the default namespace
3071 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3072 $this->mNamespace = NS_MAIN;
3073 $dbkey = substr( $dbkey, 1 );
3074 }
3075 }
3076 # If there's no recognized interwiki or namespace,
3077 # then let the colon expression be part of the title.
3078 }
3079 break;
3080 } while ( true );
3081
3082 # We already know that some pages won't be in the database!
3083 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
3084 $this->mArticleID = 0;
3085 }
3086 $fragment = strstr( $dbkey, '#' );
3087 if ( false !== $fragment ) {
3088 $this->setFragment( $fragment );
3089 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3090 # remove whitespace again: prevents "Foo_bar_#"
3091 # becoming "Foo_bar_"
3092 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3093 }
3094
3095 # Reject illegal characters.
3096 $rxTc = self::getTitleInvalidRegex();
3097 if ( preg_match( $rxTc, $dbkey ) ) {
3098 return false;
3099 }
3100
3101 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3102 # reachable due to the way web browsers deal with 'relative' URLs.
3103 # Also, they conflict with subpage syntax. Forbid them explicitly.
3104 if ( strpos( $dbkey, '.' ) !== false &&
3105 ( $dbkey === '.' || $dbkey === '..' ||
3106 strpos( $dbkey, './' ) === 0 ||
3107 strpos( $dbkey, '../' ) === 0 ||
3108 strpos( $dbkey, '/./' ) !== false ||
3109 strpos( $dbkey, '/../' ) !== false ||
3110 substr( $dbkey, -2 ) == '/.' ||
3111 substr( $dbkey, -3 ) == '/..' ) )
3112 {
3113 return false;
3114 }
3115
3116 # Magic tilde sequences? Nu-uh!
3117 if ( strpos( $dbkey, '~~~' ) !== false ) {
3118 return false;
3119 }
3120
3121 # Limit the size of titles to 255 bytes. This is typically the size of the
3122 # underlying database field. We make an exception for special pages, which
3123 # don't need to be stored in the database, and may edge over 255 bytes due
3124 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3125 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
3126 strlen( $dbkey ) > 512 )
3127 {
3128 return false;
3129 }
3130
3131 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3132 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3133 # other site might be case-sensitive.
3134 $this->mUserCaseDBKey = $dbkey;
3135 if ( $this->mInterwiki == '' ) {
3136 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
3137 }
3138
3139 # Can't make a link to a namespace alone... "empty" local links can only be
3140 # self-links with a fragment identifier.
3141 if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) {
3142 return false;
3143 }
3144
3145 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3146 // IP names are not allowed for accounts, and can only be referring to
3147 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3148 // there are numerous ways to present the same IP. Having sp:contribs scan
3149 // them all is silly and having some show the edits and others not is
3150 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3151 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK )
3152 ? IP::sanitizeIP( $dbkey )
3153 : $dbkey;
3154
3155 // Any remaining initial :s are illegal.
3156 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3157 return false;
3158 }
3159
3160 # Fill fields
3161 $this->mDbkeyform = $dbkey;
3162 $this->mUrlform = wfUrlencode( $dbkey );
3163
3164 $this->mTextform = str_replace( '_', ' ', $dbkey );
3165
3166 return true;
3167 }
3168
3169 /**
3170 * Get an array of Title objects linking to this Title
3171 * Also stores the IDs in the link cache.
3172 *
3173 * WARNING: do not use this function on arbitrary user-supplied titles!
3174 * On heavily-used templates it will max out the memory.
3175 *
3176 * @param $options Array: may be FOR UPDATE
3177 * @param $table String: table name
3178 * @param $prefix String: fields prefix
3179 * @return Array of Title objects linking here
3180 */
3181 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3182 if ( count( $options ) > 0 ) {
3183 $db = wfGetDB( DB_MASTER );
3184 } else {
3185 $db = wfGetDB( DB_SLAVE );
3186 }
3187
3188 $res = $db->select(
3189 array( 'page', $table ),
3190 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3191 array(
3192 "{$prefix}_from=page_id",
3193 "{$prefix}_namespace" => $this->getNamespace(),
3194 "{$prefix}_title" => $this->getDBkey() ),
3195 __METHOD__,
3196 $options
3197 );
3198
3199 $retVal = array();
3200 if ( $res->numRows() ) {
3201 $linkCache = LinkCache::singleton();
3202 foreach ( $res as $row ) {
3203 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3204 if ( $titleObj ) {
3205 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3206 $retVal[] = $titleObj;
3207 }
3208 }
3209 }
3210 return $retVal;
3211 }
3212
3213 /**
3214 * Get an array of Title objects using this Title as a template
3215 * Also stores the IDs in the link cache.
3216 *
3217 * WARNING: do not use this function on arbitrary user-supplied titles!
3218 * On heavily-used templates it will max out the memory.
3219 *
3220 * @param $options Array: may be FOR UPDATE
3221 * @return Array of Title the Title objects linking here
3222 */
3223 public function getTemplateLinksTo( $options = array() ) {
3224 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3225 }
3226
3227 /**
3228 * Get an array of Title objects linked from this Title
3229 * Also stores the IDs in the link cache.
3230 *
3231 * WARNING: do not use this function on arbitrary user-supplied titles!
3232 * On heavily-used templates it will max out the memory.
3233 *
3234 * @param $options Array: may be FOR UPDATE
3235 * @param $table String: table name
3236 * @param $prefix String: fields prefix
3237 * @return Array of Title objects linking here
3238 */
3239 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3240 $id = $this->getArticleID();
3241
3242 # If the page doesn't exist; there can't be any link from this page
3243 if ( !$id ) {
3244 return array();
3245 }
3246
3247 if ( count( $options ) > 0 ) {
3248 $db = wfGetDB( DB_MASTER );
3249 } else {
3250 $db = wfGetDB( DB_SLAVE );
3251 }
3252
3253 $namespaceFiled = "{$prefix}_namespace";
3254 $titleField = "{$prefix}_title";
3255
3256 $res = $db->select(
3257 array( $table, 'page' ),
3258 array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
3259 array( "{$prefix}_from" => $id ),
3260 __METHOD__,
3261 $options,
3262 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3263 );
3264
3265 $retVal = array();
3266 if ( $res->numRows() ) {
3267 $linkCache = LinkCache::singleton();
3268 foreach ( $res as $row ) {
3269 $titleObj = Title::makeTitle( $row->$namespaceFiled, $row->$titleField );
3270 if ( $titleObj ) {
3271 if ( $row->page_id ) {
3272 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3273 } else {
3274 $linkCache->addBadLinkObj( $titleObj );
3275 }
3276 $retVal[] = $titleObj;
3277 }
3278 }
3279 }
3280 return $retVal;
3281 }
3282
3283 /**
3284 * Get an array of Title objects used on this Title as a template
3285 * Also stores the IDs in the link cache.
3286 *
3287 * WARNING: do not use this function on arbitrary user-supplied titles!
3288 * On heavily-used templates it will max out the memory.
3289 *
3290 * @param $options Array: may be FOR UPDATE
3291 * @return Array of Title the Title objects used here
3292 */
3293 public function getTemplateLinksFrom( $options = array() ) {
3294 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3295 }
3296
3297 /**
3298 * Get an array of Title objects referring to non-existent articles linked from this page
3299 *
3300 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3301 * @return Array of Title the Title objects
3302 */
3303 public function getBrokenLinksFrom() {
3304 if ( $this->getArticleID() == 0 ) {
3305 # All links from article ID 0 are false positives
3306 return array();
3307 }
3308
3309 $dbr = wfGetDB( DB_SLAVE );
3310 $res = $dbr->select(
3311 array( 'page', 'pagelinks' ),
3312 array( 'pl_namespace', 'pl_title' ),
3313 array(
3314 'pl_from' => $this->getArticleID(),
3315 'page_namespace IS NULL'
3316 ),
3317 __METHOD__, array(),
3318 array(
3319 'page' => array(
3320 'LEFT JOIN',
3321 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3322 )
3323 )
3324 );
3325
3326 $retVal = array();
3327 foreach ( $res as $row ) {
3328 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3329 }
3330 return $retVal;
3331 }
3332
3333
3334 /**
3335 * Get a list of URLs to purge from the Squid cache when this
3336 * page changes
3337 *
3338 * @return Array of String the URLs
3339 */
3340 public function getSquidURLs() {
3341 global $wgContLang;
3342
3343 $urls = array(
3344 $this->getInternalURL(),
3345 $this->getInternalURL( 'action=history' )
3346 );
3347
3348 // purge variant urls as well
3349 if ( $wgContLang->hasVariants() ) {
3350 $variants = $wgContLang->getVariants();
3351 foreach ( $variants as $vCode ) {
3352 $urls[] = $this->getInternalURL( '', $vCode );
3353 }
3354 }
3355
3356 return $urls;
3357 }
3358
3359 /**
3360 * Purge all applicable Squid URLs
3361 */
3362 public function purgeSquid() {
3363 global $wgUseSquid;
3364 if ( $wgUseSquid ) {
3365 $urls = $this->getSquidURLs();
3366 $u = new SquidUpdate( $urls );
3367 $u->doUpdate();
3368 }
3369 }
3370
3371 /**
3372 * Move this page without authentication
3373 *
3374 * @param $nt Title the new page Title
3375 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3376 */
3377 public function moveNoAuth( &$nt ) {
3378 return $this->moveTo( $nt, false );
3379 }
3380
3381 /**
3382 * Check whether a given move operation would be valid.
3383 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3384 *
3385 * @param $nt Title the new title
3386 * @param $auth Bool indicates whether $wgUser's permissions
3387 * should be checked
3388 * @param $reason String is the log summary of the move, used for spam checking
3389 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3390 */
3391 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3392 global $wgUser;
3393
3394 $errors = array();
3395 if ( !$nt ) {
3396 // Normally we'd add this to $errors, but we'll get
3397 // lots of syntax errors if $nt is not an object
3398 return array( array( 'badtitletext' ) );
3399 }
3400 if ( $this->equals( $nt ) ) {
3401 $errors[] = array( 'selfmove' );
3402 }
3403 if ( !$this->isMovable() ) {
3404 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3405 }
3406 if ( $nt->getInterwiki() != '' ) {
3407 $errors[] = array( 'immobile-target-namespace-iw' );
3408 }
3409 if ( !$nt->isMovable() ) {
3410 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3411 }
3412
3413 $oldid = $this->getArticleID();
3414 $newid = $nt->getArticleID();
3415
3416 if ( strlen( $nt->getDBkey() ) < 1 ) {
3417 $errors[] = array( 'articleexists' );
3418 }
3419 if ( ( $this->getDBkey() == '' ) ||
3420 ( !$oldid ) ||
3421 ( $nt->getDBkey() == '' ) ) {
3422 $errors[] = array( 'badarticleerror' );
3423 }
3424
3425 // Image-specific checks
3426 if ( $this->getNamespace() == NS_FILE ) {
3427 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3428 }
3429
3430 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3431 $errors[] = array( 'nonfile-cannot-move-to-file' );
3432 }
3433
3434 if ( $auth ) {
3435 $errors = wfMergeErrorArrays( $errors,
3436 $this->getUserPermissionsErrors( 'move', $wgUser ),
3437 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3438 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3439 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3440 }
3441
3442 $match = EditPage::matchSummarySpamRegex( $reason );
3443 if ( $match !== false ) {
3444 // This is kind of lame, won't display nice
3445 $errors[] = array( 'spamprotectiontext' );
3446 }
3447
3448 $err = null;
3449 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3450 $errors[] = array( 'hookaborted', $err );
3451 }
3452
3453 # The move is allowed only if (1) the target doesn't exist, or
3454 # (2) the target is a redirect to the source, and has no history
3455 # (so we can undo bad moves right after they're done).
3456
3457 if ( 0 != $newid ) { # Target exists; check for validity
3458 if ( !$this->isValidMoveTarget( $nt ) ) {
3459 $errors[] = array( 'articleexists' );
3460 }
3461 } else {
3462 $tp = $nt->getTitleProtection();
3463 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3464 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3465 $errors[] = array( 'cantmove-titleprotected' );
3466 }
3467 }
3468 if ( empty( $errors ) ) {
3469 return true;
3470 }
3471 return $errors;
3472 }
3473
3474 /**
3475 * Check if the requested move target is a valid file move target
3476 * @param Title $nt Target title
3477 * @return array List of errors
3478 */
3479 protected function validateFileMoveOperation( $nt ) {
3480 global $wgUser;
3481
3482 $errors = array();
3483
3484 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3485
3486 $file = wfLocalFile( $this );
3487 if ( $file->exists() ) {
3488 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3489 $errors[] = array( 'imageinvalidfilename' );
3490 }
3491 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3492 $errors[] = array( 'imagetypemismatch' );
3493 }
3494 }
3495
3496 if ( $nt->getNamespace() != NS_FILE ) {
3497 $errors[] = array( 'imagenocrossnamespace' );
3498 // From here we want to do checks on a file object, so if we can't
3499 // create one, we must return.
3500 return $errors;
3501 }
3502
3503 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3504
3505 $destFile = wfLocalFile( $nt );
3506 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3507 $errors[] = array( 'file-exists-sharedrepo' );
3508 }
3509
3510 return $errors;
3511 }
3512
3513 /**
3514 * Move a title to a new location
3515 *
3516 * @param $nt Title the new title
3517 * @param $auth Bool indicates whether $wgUser's permissions
3518 * should be checked
3519 * @param $reason String the reason for the move
3520 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3521 * Ignored if the user doesn't have the suppressredirect right.
3522 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3523 */
3524 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3525 global $wgUser;
3526 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3527 if ( is_array( $err ) ) {
3528 // Auto-block user's IP if the account was "hard" blocked
3529 $wgUser->spreadAnyEditBlock();
3530 return $err;
3531 }
3532
3533 // If it is a file, move it first.
3534 // It is done before all other moving stuff is done because it's hard to revert.
3535 $dbw = wfGetDB( DB_MASTER );
3536 if ( $this->getNamespace() == NS_FILE ) {
3537 $file = wfLocalFile( $this );
3538 if ( $file->exists() ) {
3539 $status = $file->move( $nt );
3540 if ( !$status->isOk() ) {
3541 return $status->getErrorsArray();
3542 }
3543 }
3544 // Clear RepoGroup process cache
3545 RepoGroup::singleton()->clearCache( $this );
3546 RepoGroup::singleton()->clearCache( $nt ); # clear false negative cache
3547 }
3548
3549 $dbw->begin( __METHOD__ ); # If $file was a LocalFile, its transaction would have closed our own.
3550 $pageid = $this->getArticleID( self::GAID_FOR_UPDATE );
3551 $protected = $this->isProtected();
3552
3553 // Do the actual move
3554 $this->moveToInternal( $nt, $reason, $createRedirect );
3555
3556 // Refresh the sortkey for this row. Be careful to avoid resetting
3557 // cl_timestamp, which may disturb time-based lists on some sites.
3558 $prefixes = $dbw->select(
3559 'categorylinks',
3560 array( 'cl_sortkey_prefix', 'cl_to' ),
3561 array( 'cl_from' => $pageid ),
3562 __METHOD__
3563 );
3564 foreach ( $prefixes as $prefixRow ) {
3565 $prefix = $prefixRow->cl_sortkey_prefix;
3566 $catTo = $prefixRow->cl_to;
3567 $dbw->update( 'categorylinks',
3568 array(
3569 'cl_sortkey' => Collation::singleton()->getSortKey(
3570 $nt->getCategorySortkey( $prefix ) ),
3571 'cl_timestamp=cl_timestamp' ),
3572 array(
3573 'cl_from' => $pageid,
3574 'cl_to' => $catTo ),
3575 __METHOD__
3576 );
3577 }
3578
3579 $redirid = $this->getArticleID();
3580
3581 if ( $protected ) {
3582 # Protect the redirect title as the title used to be...
3583 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3584 array(
3585 'pr_page' => $redirid,
3586 'pr_type' => 'pr_type',
3587 'pr_level' => 'pr_level',
3588 'pr_cascade' => 'pr_cascade',
3589 'pr_user' => 'pr_user',
3590 'pr_expiry' => 'pr_expiry'
3591 ),
3592 array( 'pr_page' => $pageid ),
3593 __METHOD__,
3594 array( 'IGNORE' )
3595 );
3596 # Update the protection log
3597 $log = new LogPage( 'protect' );
3598 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3599 if ( $reason ) {
3600 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3601 }
3602 // @todo FIXME: $params?
3603 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3604 }
3605
3606 # Update watchlists
3607 $oldnamespace = $this->getNamespace() & ~1;
3608 $newnamespace = $nt->getNamespace() & ~1;
3609 $oldtitle = $this->getDBkey();
3610 $newtitle = $nt->getDBkey();
3611
3612 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3613 WatchedItem::duplicateEntries( $this, $nt );
3614 }
3615
3616 $dbw->commit( __METHOD__ );
3617
3618 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3619 return true;
3620 }
3621
3622 /**
3623 * Move page to a title which is either a redirect to the
3624 * source page or nonexistent
3625 *
3626 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3627 * @param $reason String The reason for the move
3628 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3629 * if the user doesn't have the suppressredirect right
3630 * @throws MWException
3631 */
3632 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3633 global $wgUser, $wgContLang;
3634
3635 if ( $nt->exists() ) {
3636 $moveOverRedirect = true;
3637 $logType = 'move_redir';
3638 } else {
3639 $moveOverRedirect = false;
3640 $logType = 'move';
3641 }
3642
3643 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3644
3645 $logEntry = new ManualLogEntry( 'move', $logType );
3646 $logEntry->setPerformer( $wgUser );
3647 $logEntry->setTarget( $this );
3648 $logEntry->setComment( $reason );
3649 $logEntry->setParameters( array(
3650 '4::target' => $nt->getPrefixedText(),
3651 '5::noredir' => $redirectSuppressed ? '1': '0',
3652 ) );
3653
3654 $formatter = LogFormatter::newFromEntry( $logEntry );
3655 $formatter->setContext( RequestContext::newExtraneousContext( $this ) );
3656 $comment = $formatter->getPlainActionText();
3657 if ( $reason ) {
3658 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3659 }
3660 # Truncate for whole multibyte characters.
3661 $comment = $wgContLang->truncate( $comment, 255 );
3662
3663 $oldid = $this->getArticleID();
3664
3665 $dbw = wfGetDB( DB_MASTER );
3666
3667 $newpage = WikiPage::factory( $nt );
3668
3669 if ( $moveOverRedirect ) {
3670 $newid = $nt->getArticleID();
3671
3672 # Delete the old redirect. We don't save it to history since
3673 # by definition if we've got here it's rather uninteresting.
3674 # We have to remove it so that the next step doesn't trigger
3675 # a conflict on the unique namespace+title index...
3676 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3677
3678 $newpage->doDeleteUpdates( $newid );
3679 }
3680
3681 # Save a null revision in the page's history notifying of the move
3682 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3683 if ( !is_object( $nullRevision ) ) {
3684 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3685 }
3686 $nullRevId = $nullRevision->insertOn( $dbw );
3687
3688 # Change the name of the target page:
3689 $dbw->update( 'page',
3690 /* SET */ array(
3691 'page_namespace' => $nt->getNamespace(),
3692 'page_title' => $nt->getDBkey(),
3693 ),
3694 /* WHERE */ array( 'page_id' => $oldid ),
3695 __METHOD__
3696 );
3697
3698 $this->resetArticleID( 0 );
3699 $nt->resetArticleID( $oldid );
3700
3701 $newpage->updateRevisionOn( $dbw, $nullRevision );
3702
3703 wfRunHooks( 'NewRevisionFromEditComplete',
3704 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3705
3706 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3707
3708 if ( !$moveOverRedirect ) {
3709 WikiPage::onArticleCreate( $nt );
3710 }
3711
3712 # Recreate the redirect, this time in the other direction.
3713 if ( $redirectSuppressed ) {
3714 WikiPage::onArticleDelete( $this );
3715 } else {
3716 $mwRedir = MagicWord::get( 'redirect' );
3717 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3718 $redirectArticle = WikiPage::factory( $this );
3719 $newid = $redirectArticle->insertOn( $dbw );
3720 if ( $newid ) { // sanity
3721 $redirectRevision = new Revision( array(
3722 'page' => $newid,
3723 'comment' => $comment,
3724 'text' => $redirectText ) );
3725 $redirectRevision->insertOn( $dbw );
3726 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3727
3728 wfRunHooks( 'NewRevisionFromEditComplete',
3729 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3730
3731 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3732 }
3733 }
3734
3735 # Log the move
3736 $logid = $logEntry->insert();
3737 $logEntry->publish( $logid );
3738 }
3739
3740 /**
3741 * Move this page's subpages to be subpages of $nt
3742 *
3743 * @param $nt Title Move target
3744 * @param $auth bool Whether $wgUser's permissions should be checked
3745 * @param $reason string The reason for the move
3746 * @param $createRedirect bool Whether to create redirects from the old subpages to
3747 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3748 * @return mixed array with old page titles as keys, and strings (new page titles) or
3749 * arrays (errors) as values, or an error array with numeric indices if no pages
3750 * were moved
3751 */
3752 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3753 global $wgMaximumMovedPages;
3754 // Check permissions
3755 if ( !$this->userCan( 'move-subpages' ) ) {
3756 return array( 'cant-move-subpages' );
3757 }
3758 // Do the source and target namespaces support subpages?
3759 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3760 return array( 'namespace-nosubpages',
3761 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3762 }
3763 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3764 return array( 'namespace-nosubpages',
3765 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3766 }
3767
3768 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3769 $retval = array();
3770 $count = 0;
3771 foreach ( $subpages as $oldSubpage ) {
3772 $count++;
3773 if ( $count > $wgMaximumMovedPages ) {
3774 $retval[$oldSubpage->getPrefixedTitle()] =
3775 array( 'movepage-max-pages',
3776 $wgMaximumMovedPages );
3777 break;
3778 }
3779
3780 // We don't know whether this function was called before
3781 // or after moving the root page, so check both
3782 // $this and $nt
3783 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3784 $oldSubpage->getArticleID() == $nt->getArticleID() )
3785 {
3786 // When moving a page to a subpage of itself,
3787 // don't move it twice
3788 continue;
3789 }
3790 $newPageName = preg_replace(
3791 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3792 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3793 $oldSubpage->getDBkey() );
3794 if ( $oldSubpage->isTalkPage() ) {
3795 $newNs = $nt->getTalkPage()->getNamespace();
3796 } else {
3797 $newNs = $nt->getSubjectPage()->getNamespace();
3798 }
3799 # Bug 14385: we need makeTitleSafe because the new page names may
3800 # be longer than 255 characters.
3801 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3802
3803 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3804 if ( $success === true ) {
3805 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3806 } else {
3807 $retval[$oldSubpage->getPrefixedText()] = $success;
3808 }
3809 }
3810 return $retval;
3811 }
3812
3813 /**
3814 * Checks if this page is just a one-rev redirect.
3815 * Adds lock, so don't use just for light purposes.
3816 *
3817 * @return Bool
3818 */
3819 public function isSingleRevRedirect() {
3820 $dbw = wfGetDB( DB_MASTER );
3821 # Is it a redirect?
3822 $row = $dbw->selectRow( 'page',
3823 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3824 $this->pageCond(),
3825 __METHOD__,
3826 array( 'FOR UPDATE' )
3827 );
3828 # Cache some fields we may want
3829 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3830 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3831 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3832 if ( !$this->mRedirect ) {
3833 return false;
3834 }
3835 # Does the article have a history?
3836 $row = $dbw->selectField( array( 'page', 'revision' ),
3837 'rev_id',
3838 array( 'page_namespace' => $this->getNamespace(),
3839 'page_title' => $this->getDBkey(),
3840 'page_id=rev_page',
3841 'page_latest != rev_id'
3842 ),
3843 __METHOD__,
3844 array( 'FOR UPDATE' )
3845 );
3846 # Return true if there was no history
3847 return ( $row === false );
3848 }
3849
3850 /**
3851 * Checks if $this can be moved to a given Title
3852 * - Selects for update, so don't call it unless you mean business
3853 *
3854 * @param $nt Title the new title to check
3855 * @return Bool
3856 */
3857 public function isValidMoveTarget( $nt ) {
3858 # Is it an existing file?
3859 if ( $nt->getNamespace() == NS_FILE ) {
3860 $file = wfLocalFile( $nt );
3861 if ( $file->exists() ) {
3862 wfDebug( __METHOD__ . ": file exists\n" );
3863 return false;
3864 }
3865 }
3866 # Is it a redirect with no history?
3867 if ( !$nt->isSingleRevRedirect() ) {
3868 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3869 return false;
3870 }
3871 # Get the article text
3872 $rev = Revision::newFromTitle( $nt );
3873 if( !is_object( $rev ) ){
3874 return false;
3875 }
3876 $text = $rev->getText();
3877 # Does the redirect point to the source?
3878 # Or is it a broken self-redirect, usually caused by namespace collisions?
3879 $m = array();
3880 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3881 $redirTitle = Title::newFromText( $m[1] );
3882 if ( !is_object( $redirTitle ) ||
3883 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3884 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3885 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3886 return false;
3887 }
3888 } else {
3889 # Fail safe
3890 wfDebug( __METHOD__ . ": failsafe\n" );
3891 return false;
3892 }
3893 return true;
3894 }
3895
3896 /**
3897 * Get categories to which this Title belongs and return an array of
3898 * categories' names.
3899 *
3900 * @return Array of parents in the form:
3901 * $parent => $currentarticle
3902 */
3903 public function getParentCategories() {
3904 global $wgContLang;
3905
3906 $data = array();
3907
3908 $titleKey = $this->getArticleID();
3909
3910 if ( $titleKey === 0 ) {
3911 return $data;
3912 }
3913
3914 $dbr = wfGetDB( DB_SLAVE );
3915
3916 $res = $dbr->select( 'categorylinks', '*',
3917 array(
3918 'cl_from' => $titleKey,
3919 ),
3920 __METHOD__,
3921 array()
3922 );
3923
3924 if ( $dbr->numRows( $res ) > 0 ) {
3925 foreach ( $res as $row ) {
3926 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3927 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3928 }
3929 }
3930 return $data;
3931 }
3932
3933 /**
3934 * Get a tree of parent categories
3935 *
3936 * @param $children Array with the children in the keys, to check for circular refs
3937 * @return Array Tree of parent categories
3938 */
3939 public function getParentCategoryTree( $children = array() ) {
3940 $stack = array();
3941 $parents = $this->getParentCategories();
3942
3943 if ( $parents ) {
3944 foreach ( $parents as $parent => $current ) {
3945 if ( array_key_exists( $parent, $children ) ) {
3946 # Circular reference
3947 $stack[$parent] = array();
3948 } else {
3949 $nt = Title::newFromText( $parent );
3950 if ( $nt ) {
3951 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3952 }
3953 }
3954 }
3955 }
3956
3957 return $stack;
3958 }
3959
3960 /**
3961 * Get an associative array for selecting this title from
3962 * the "page" table
3963 *
3964 * @return Array suitable for the $where parameter of DB::select()
3965 */
3966 public function pageCond() {
3967 if ( $this->mArticleID > 0 ) {
3968 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3969 return array( 'page_id' => $this->mArticleID );
3970 } else {
3971 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3972 }
3973 }
3974
3975 /**
3976 * Get the revision ID of the previous revision
3977 *
3978 * @param $revId Int Revision ID. Get the revision that was before this one.
3979 * @param $flags Int Title::GAID_FOR_UPDATE
3980 * @return Int|Bool Old revision ID, or FALSE if none exists
3981 */
3982 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3983 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3984 $revId = $db->selectField( 'revision', 'rev_id',
3985 array(
3986 'rev_page' => $this->getArticleID( $flags ),
3987 'rev_id < ' . intval( $revId )
3988 ),
3989 __METHOD__,
3990 array( 'ORDER BY' => 'rev_id DESC' )
3991 );
3992
3993 if ( $revId === false ) {
3994 return false;
3995 } else {
3996 return intval( $revId );
3997 }
3998 }
3999
4000 /**
4001 * Get the revision ID of the next revision
4002 *
4003 * @param $revId Int Revision ID. Get the revision that was after this one.
4004 * @param $flags Int Title::GAID_FOR_UPDATE
4005 * @return Int|Bool Next revision ID, or FALSE if none exists
4006 */
4007 public function getNextRevisionID( $revId, $flags = 0 ) {
4008 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4009 $revId = $db->selectField( 'revision', 'rev_id',
4010 array(
4011 'rev_page' => $this->getArticleID( $flags ),
4012 'rev_id > ' . intval( $revId )
4013 ),
4014 __METHOD__,
4015 array( 'ORDER BY' => 'rev_id' )
4016 );
4017
4018 if ( $revId === false ) {
4019 return false;
4020 } else {
4021 return intval( $revId );
4022 }
4023 }
4024
4025 /**
4026 * Get the first revision of the page
4027 *
4028 * @param $flags Int Title::GAID_FOR_UPDATE
4029 * @return Revision|Null if page doesn't exist
4030 */
4031 public function getFirstRevision( $flags = 0 ) {
4032 $pageId = $this->getArticleID( $flags );
4033 if ( $pageId ) {
4034 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4035 $row = $db->selectRow( 'revision', Revision::selectFields(),
4036 array( 'rev_page' => $pageId ),
4037 __METHOD__,
4038 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4039 );
4040 if ( $row ) {
4041 return new Revision( $row );
4042 }
4043 }
4044 return null;
4045 }
4046
4047 /**
4048 * Get the oldest revision timestamp of this page
4049 *
4050 * @param $flags Int Title::GAID_FOR_UPDATE
4051 * @return String: MW timestamp
4052 */
4053 public function getEarliestRevTime( $flags = 0 ) {
4054 $rev = $this->getFirstRevision( $flags );
4055 return $rev ? $rev->getTimestamp() : null;
4056 }
4057
4058 /**
4059 * Check if this is a new page
4060 *
4061 * @return bool
4062 */
4063 public function isNewPage() {
4064 $dbr = wfGetDB( DB_SLAVE );
4065 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4066 }
4067
4068 /**
4069 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4070 *
4071 * @return bool
4072 */
4073 public function isBigDeletion() {
4074 global $wgDeleteRevisionsLimit;
4075
4076 if ( !$wgDeleteRevisionsLimit ) {
4077 return false;
4078 }
4079
4080 $revCount = $this->estimateRevisionCount();
4081 return $revCount > $wgDeleteRevisionsLimit;
4082 }
4083
4084 /**
4085 * Get the approximate revision count of this page.
4086 *
4087 * @return int
4088 */
4089 public function estimateRevisionCount() {
4090 if ( !$this->exists() ) {
4091 return 0;
4092 }
4093
4094 if ( $this->mEstimateRevisions === null ) {
4095 $dbr = wfGetDB( DB_SLAVE );
4096 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4097 array( 'rev_page' => $this->getArticleID() ), __METHOD__ );
4098 }
4099
4100 return $this->mEstimateRevisions;
4101 }
4102
4103 /**
4104 * Get the number of revisions between the given revision.
4105 * Used for diffs and other things that really need it.
4106 *
4107 * @param $old int|Revision Old revision or rev ID (first before range)
4108 * @param $new int|Revision New revision or rev ID (first after range)
4109 * @return Int Number of revisions between these revisions.
4110 */
4111 public function countRevisionsBetween( $old, $new ) {
4112 if ( !( $old instanceof Revision ) ) {
4113 $old = Revision::newFromTitle( $this, (int)$old );
4114 }
4115 if ( !( $new instanceof Revision ) ) {
4116 $new = Revision::newFromTitle( $this, (int)$new );
4117 }
4118 if ( !$old || !$new ) {
4119 return 0; // nothing to compare
4120 }
4121 $dbr = wfGetDB( DB_SLAVE );
4122 return (int)$dbr->selectField( 'revision', 'count(*)',
4123 array(
4124 'rev_page' => $this->getArticleID(),
4125 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4126 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4127 ),
4128 __METHOD__
4129 );
4130 }
4131
4132 /**
4133 * Get the number of authors between the given revision IDs.
4134 * Used for diffs and other things that really need it.
4135 *
4136 * @param $old int|Revision Old revision or rev ID (first before range)
4137 * @param $new int|Revision New revision or rev ID (first after range)
4138 * @param $limit Int Maximum number of authors
4139 * @return Int Number of revision authors between these revisions.
4140 */
4141 public function countAuthorsBetween( $old, $new, $limit ) {
4142 if ( !( $old instanceof Revision ) ) {
4143 $old = Revision::newFromTitle( $this, (int)$old );
4144 }
4145 if ( !( $new instanceof Revision ) ) {
4146 $new = Revision::newFromTitle( $this, (int)$new );
4147 }
4148 if ( !$old || !$new ) {
4149 return 0; // nothing to compare
4150 }
4151 $dbr = wfGetDB( DB_SLAVE );
4152 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4153 array(
4154 'rev_page' => $this->getArticleID(),
4155 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4156 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4157 ), __METHOD__,
4158 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4159 );
4160 return (int)$dbr->numRows( $res );
4161 }
4162
4163 /**
4164 * Compare with another title.
4165 *
4166 * @param $title Title
4167 * @return Bool
4168 */
4169 public function equals( Title $title ) {
4170 // Note: === is necessary for proper matching of number-like titles.
4171 return $this->getInterwiki() === $title->getInterwiki()
4172 && $this->getNamespace() == $title->getNamespace()
4173 && $this->getDBkey() === $title->getDBkey();
4174 }
4175
4176 /**
4177 * Check if this title is a subpage of another title
4178 *
4179 * @param $title Title
4180 * @return Bool
4181 */
4182 public function isSubpageOf( Title $title ) {
4183 return $this->getInterwiki() === $title->getInterwiki()
4184 && $this->getNamespace() == $title->getNamespace()
4185 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4186 }
4187
4188 /**
4189 * Check if page exists. For historical reasons, this function simply
4190 * checks for the existence of the title in the page table, and will
4191 * thus return false for interwiki links, special pages and the like.
4192 * If you want to know if a title can be meaningfully viewed, you should
4193 * probably call the isKnown() method instead.
4194 *
4195 * @return Bool
4196 */
4197 public function exists() {
4198 return $this->getArticleID() != 0;
4199 }
4200
4201 /**
4202 * Should links to this title be shown as potentially viewable (i.e. as
4203 * "bluelinks"), even if there's no record by this title in the page
4204 * table?
4205 *
4206 * This function is semi-deprecated for public use, as well as somewhat
4207 * misleadingly named. You probably just want to call isKnown(), which
4208 * calls this function internally.
4209 *
4210 * (ISSUE: Most of these checks are cheap, but the file existence check
4211 * can potentially be quite expensive. Including it here fixes a lot of
4212 * existing code, but we might want to add an optional parameter to skip
4213 * it and any other expensive checks.)
4214 *
4215 * @return Bool
4216 */
4217 public function isAlwaysKnown() {
4218 $isKnown = null;
4219
4220 /**
4221 * Allows overriding default behaviour for determining if a page exists.
4222 * If $isKnown is kept as null, regular checks happen. If it's
4223 * a boolean, this value is returned by the isKnown method.
4224 *
4225 * @since 1.20
4226 *
4227 * @param Title $title
4228 * @param boolean|null $isKnown
4229 */
4230 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4231
4232 if ( !is_null( $isKnown ) ) {
4233 return $isKnown;
4234 }
4235
4236 if ( $this->mInterwiki != '' ) {
4237 return true; // any interwiki link might be viewable, for all we know
4238 }
4239
4240 switch( $this->mNamespace ) {
4241 case NS_MEDIA:
4242 case NS_FILE:
4243 // file exists, possibly in a foreign repo
4244 return (bool)wfFindFile( $this );
4245 case NS_SPECIAL:
4246 // valid special page
4247 return SpecialPageFactory::exists( $this->getDBkey() );
4248 case NS_MAIN:
4249 // selflink, possibly with fragment
4250 return $this->mDbkeyform == '';
4251 case NS_MEDIAWIKI:
4252 // known system message
4253 return $this->hasSourceText() !== false;
4254 default:
4255 return false;
4256 }
4257 }
4258
4259 /**
4260 * Does this title refer to a page that can (or might) be meaningfully
4261 * viewed? In particular, this function may be used to determine if
4262 * links to the title should be rendered as "bluelinks" (as opposed to
4263 * "redlinks" to non-existent pages).
4264 * Adding something else to this function will cause inconsistency
4265 * since LinkHolderArray calls isAlwaysKnown() and does its own
4266 * page existence check.
4267 *
4268 * @return Bool
4269 */
4270 public function isKnown() {
4271 return $this->isAlwaysKnown() || $this->exists();
4272 }
4273
4274 /**
4275 * Does this page have source text?
4276 *
4277 * @return Boolean
4278 */
4279 public function hasSourceText() {
4280 if ( $this->exists() ) {
4281 return true;
4282 }
4283
4284 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4285 // If the page doesn't exist but is a known system message, default
4286 // message content will be displayed, same for language subpages-
4287 // Use always content language to avoid loading hundreds of languages
4288 // to get the link color.
4289 global $wgContLang;
4290 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4291 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4292 return $message->exists();
4293 }
4294
4295 return false;
4296 }
4297
4298 /**
4299 * Get the default message text or false if the message doesn't exist
4300 *
4301 * @return String or false
4302 */
4303 public function getDefaultMessageText() {
4304 global $wgContLang;
4305
4306 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4307 return false;
4308 }
4309
4310 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4311 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4312
4313 if ( $message->exists() ) {
4314 return $message->plain();
4315 } else {
4316 return false;
4317 }
4318 }
4319
4320 /**
4321 * Updates page_touched for this page; called from LinksUpdate.php
4322 *
4323 * @return Bool true if the update succeded
4324 */
4325 public function invalidateCache() {
4326 if ( wfReadOnly() ) {
4327 return false;
4328 }
4329 $dbw = wfGetDB( DB_MASTER );
4330 $success = $dbw->update(
4331 'page',
4332 array( 'page_touched' => $dbw->timestamp() ),
4333 $this->pageCond(),
4334 __METHOD__
4335 );
4336 HTMLFileCache::clearFileCache( $this );
4337 return $success;
4338 }
4339
4340 /**
4341 * Update page_touched timestamps and send squid purge messages for
4342 * pages linking to this title. May be sent to the job queue depending
4343 * on the number of links. Typically called on create and delete.
4344 */
4345 public function touchLinks() {
4346 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4347 $u->doUpdate();
4348
4349 if ( $this->getNamespace() == NS_CATEGORY ) {
4350 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4351 $u->doUpdate();
4352 }
4353 }
4354
4355 /**
4356 * Get the last touched timestamp
4357 *
4358 * @param $db DatabaseBase: optional db
4359 * @return String last-touched timestamp
4360 */
4361 public function getTouched( $db = null ) {
4362 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
4363 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4364 return $touched;
4365 }
4366
4367 /**
4368 * Get the timestamp when this page was updated since the user last saw it.
4369 *
4370 * @param $user User
4371 * @return String|Null
4372 */
4373 public function getNotificationTimestamp( $user = null ) {
4374 global $wgUser, $wgShowUpdatedMarker;
4375 // Assume current user if none given
4376 if ( !$user ) {
4377 $user = $wgUser;
4378 }
4379 // Check cache first
4380 $uid = $user->getId();
4381 // avoid isset here, as it'll return false for null entries
4382 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4383 return $this->mNotificationTimestamp[$uid];
4384 }
4385 if ( !$uid || !$wgShowUpdatedMarker ) {
4386 return $this->mNotificationTimestamp[$uid] = false;
4387 }
4388 // Don't cache too much!
4389 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4390 $this->mNotificationTimestamp = array();
4391 }
4392 $dbr = wfGetDB( DB_SLAVE );
4393 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
4394 'wl_notificationtimestamp',
4395 array(
4396 'wl_user' => $user->getId(),
4397 'wl_namespace' => $this->getNamespace(),
4398 'wl_title' => $this->getDBkey(),
4399 ),
4400 __METHOD__
4401 );
4402 return $this->mNotificationTimestamp[$uid];
4403 }
4404
4405 /**
4406 * Generate strings used for xml 'id' names in monobook tabs
4407 *
4408 * @param $prepend string defaults to 'nstab-'
4409 * @return String XML 'id' name
4410 */
4411 public function getNamespaceKey( $prepend = 'nstab-' ) {
4412 global $wgContLang;
4413 // Gets the subject namespace if this title
4414 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4415 // Checks if cononical namespace name exists for namespace
4416 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4417 // Uses canonical namespace name
4418 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4419 } else {
4420 // Uses text of namespace
4421 $namespaceKey = $this->getSubjectNsText();
4422 }
4423 // Makes namespace key lowercase
4424 $namespaceKey = $wgContLang->lc( $namespaceKey );
4425 // Uses main
4426 if ( $namespaceKey == '' ) {
4427 $namespaceKey = 'main';
4428 }
4429 // Changes file to image for backwards compatibility
4430 if ( $namespaceKey == 'file' ) {
4431 $namespaceKey = 'image';
4432 }
4433 return $prepend . $namespaceKey;
4434 }
4435
4436 /**
4437 * Get all extant redirects to this Title
4438 *
4439 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4440 * @return Array of Title redirects to this title
4441 */
4442 public function getRedirectsHere( $ns = null ) {
4443 $redirs = array();
4444
4445 $dbr = wfGetDB( DB_SLAVE );
4446 $where = array(
4447 'rd_namespace' => $this->getNamespace(),
4448 'rd_title' => $this->getDBkey(),
4449 'rd_from = page_id'
4450 );
4451 if ( !is_null( $ns ) ) {
4452 $where['page_namespace'] = $ns;
4453 }
4454
4455 $res = $dbr->select(
4456 array( 'redirect', 'page' ),
4457 array( 'page_namespace', 'page_title' ),
4458 $where,
4459 __METHOD__
4460 );
4461
4462 foreach ( $res as $row ) {
4463 $redirs[] = self::newFromRow( $row );
4464 }
4465 return $redirs;
4466 }
4467
4468 /**
4469 * Check if this Title is a valid redirect target
4470 *
4471 * @return Bool
4472 */
4473 public function isValidRedirectTarget() {
4474 global $wgInvalidRedirectTargets;
4475
4476 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4477 if ( $this->isSpecial( 'Userlogout' ) ) {
4478 return false;
4479 }
4480
4481 foreach ( $wgInvalidRedirectTargets as $target ) {
4482 if ( $this->isSpecial( $target ) ) {
4483 return false;
4484 }
4485 }
4486
4487 return true;
4488 }
4489
4490 /**
4491 * Get a backlink cache object
4492 *
4493 * @return BacklinkCache
4494 */
4495 function getBacklinkCache() {
4496 if ( is_null( $this->mBacklinkCache ) ) {
4497 $this->mBacklinkCache = new BacklinkCache( $this );
4498 }
4499 return $this->mBacklinkCache;
4500 }
4501
4502 /**
4503 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4504 *
4505 * @return Boolean
4506 */
4507 public function canUseNoindex() {
4508 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4509
4510 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4511 ? $wgContentNamespaces
4512 : $wgExemptFromUserRobotsControl;
4513
4514 return !in_array( $this->mNamespace, $bannedNamespaces );
4515
4516 }
4517
4518 /**
4519 * Returns the raw sort key to be used for categories, with the specified
4520 * prefix. This will be fed to Collation::getSortKey() to get a
4521 * binary sortkey that can be used for actual sorting.
4522 *
4523 * @param $prefix string The prefix to be used, specified using
4524 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4525 * prefix.
4526 * @return string
4527 */
4528 public function getCategorySortkey( $prefix = '' ) {
4529 $unprefixed = $this->getText();
4530
4531 // Anything that uses this hook should only depend
4532 // on the Title object passed in, and should probably
4533 // tell the users to run updateCollations.php --force
4534 // in order to re-sort existing category relations.
4535 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4536 if ( $prefix !== '' ) {
4537 # Separate with a line feed, so the unprefixed part is only used as
4538 # a tiebreaker when two pages have the exact same prefix.
4539 # In UCA, tab is the only character that can sort above LF
4540 # so we strip both of them from the original prefix.
4541 $prefix = strtr( $prefix, "\n\t", ' ' );
4542 return "$prefix\n$unprefixed";
4543 }
4544 return $unprefixed;
4545 }
4546
4547 /**
4548 * Get the language in which the content of this page is written.
4549 * Defaults to $wgContLang, but in certain cases it can be e.g.
4550 * $wgLang (such as special pages, which are in the user language).
4551 *
4552 * @since 1.18
4553 * @return Language
4554 */
4555 public function getPageLanguage() {
4556 global $wgLang;
4557 if ( $this->isSpecialPage() ) {
4558 // special pages are in the user language
4559 return $wgLang;
4560 } elseif ( $this->isCssOrJsPage() || $this->isCssJsSubpage() ) {
4561 // css/js should always be LTR and is, in fact, English
4562 return wfGetLangObj( 'en' );
4563 } elseif ( $this->getNamespace() == NS_MEDIAWIKI ) {
4564 // Parse mediawiki messages with correct target language
4565 list( /* $unused */, $lang ) = MessageCache::singleton()->figureMessage( $this->getText() );
4566 return wfGetLangObj( $lang );
4567 }
4568 global $wgContLang;
4569 // If nothing special, it should be in the wiki content language
4570 $pageLang = $wgContLang;
4571 // Hook at the end because we don't want to override the above stuff
4572 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4573 return wfGetLangObj( $pageLang );
4574 }
4575 }