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