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