Merge "Make ApiEditPage use Article::newFromWikiPage() and add user to context"
[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 */
1301 public function getEscapedText() {
1302 wfDeprecated( __METHOD__, '1.19' );
1303 return htmlspecialchars( $this->getPrefixedText() );
1304 }
1305
1306 /**
1307 * Get a URL-encoded form of the subpage text
1308 *
1309 * @return String URL-encoded subpage name
1310 */
1311 public function getSubpageUrlForm() {
1312 $text = $this->getSubpageText();
1313 $text = wfUrlencode( str_replace( ' ', '_', $text ) );
1314 return( $text );
1315 }
1316
1317 /**
1318 * Get a URL-encoded title (not an actual URL) including interwiki
1319 *
1320 * @return String the URL-encoded form
1321 */
1322 public function getPrefixedURL() {
1323 $s = $this->prefix( $this->mDbkeyform );
1324 $s = wfUrlencode( str_replace( ' ', '_', $s ) );
1325 return $s;
1326 }
1327
1328 /**
1329 * Helper to fix up the get{Local,Full,Link,Canonical}URL args
1330 * get{Canonical,Full,Link,Local}URL methods accepted an optional
1331 * second argument named variant. This was deprecated in favor
1332 * of passing an array of option with a "variant" key
1333 * Once $query2 is removed for good, this helper can be dropped
1334 * andthe wfArrayToCgi moved to getLocalURL();
1335 *
1336 * @since 1.19 (r105919)
1337 * @param $query
1338 * @param $query2 bool
1339 * @return String
1340 */
1341 private static function fixUrlQueryArgs( $query, $query2 = false ) {
1342 if( $query2 !== false ) {
1343 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" );
1344 }
1345 if ( is_array( $query ) ) {
1346 $query = wfArrayToCgi( $query );
1347 }
1348 if ( $query2 ) {
1349 if ( is_string( $query2 ) ) {
1350 // $query2 is a string, we will consider this to be
1351 // a deprecated $variant argument and add it to the query
1352 $query2 = wfArrayToCgi( array( 'variant' => $query2 ) );
1353 } else {
1354 $query2 = wfArrayToCgi( $query2 );
1355 }
1356 // If we have $query content add a & to it first
1357 if ( $query ) {
1358 $query .= '&';
1359 }
1360 // Now append the queries together
1361 $query .= $query2;
1362 }
1363 return $query;
1364 }
1365
1366 /**
1367 * Get a real URL referring to this title, with interwiki link and
1368 * fragment
1369 *
1370 * See getLocalURL for the arguments.
1371 *
1372 * @see self::getLocalURL
1373 * @see wfExpandUrl
1374 * @param $query
1375 * @param $query2 bool
1376 * @param $proto Protocol type to use in URL
1377 * @return String the URL
1378 */
1379 public function getFullURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1380 $query = self::fixUrlQueryArgs( $query, $query2 );
1381
1382 # Hand off all the decisions on urls to getLocalURL
1383 $url = $this->getLocalURL( $query );
1384
1385 # Expand the url to make it a full url. Note that getLocalURL has the
1386 # potential to output full urls for a variety of reasons, so we use
1387 # wfExpandUrl instead of simply prepending $wgServer
1388 $url = wfExpandUrl( $url, $proto );
1389
1390 # Finally, add the fragment.
1391 $url .= $this->getFragmentForURL();
1392
1393 wfRunHooks( 'GetFullURL', array( &$this, &$url, $query ) );
1394 return $url;
1395 }
1396
1397 /**
1398 * Get a URL with no fragment or server name. If this page is generated
1399 * with action=render, $wgServer is prepended.
1400 *
1401
1402 * @param $query string|array an optional query string,
1403 * not used for interwiki links. Can be specified as an associative array as well,
1404 * e.g., array( 'action' => 'edit' ) (keys and values will be URL-escaped).
1405 * Some query patterns will trigger various shorturl path replacements.
1406 * @param $query2 Mixed: An optional secondary query array. This one MUST
1407 * be an array. If a string is passed it will be interpreted as a deprecated
1408 * variant argument and urlencoded into a variant= argument.
1409 * This second query argument will be added to the $query
1410 * The second parameter is deprecated since 1.19. Pass it as a key,value
1411 * pair in the first parameter array instead.
1412 *
1413 * @return String the URL
1414 */
1415 public function getLocalURL( $query = '', $query2 = false ) {
1416 global $wgArticlePath, $wgScript, $wgServer, $wgRequest;
1417
1418 $query = self::fixUrlQueryArgs( $query, $query2 );
1419
1420 $interwiki = Interwiki::fetch( $this->mInterwiki );
1421 if ( $interwiki ) {
1422 $namespace = $this->getNsText();
1423 if ( $namespace != '' ) {
1424 # Can this actually happen? Interwikis shouldn't be parsed.
1425 # Yes! It can in interwiki transclusion. But... it probably shouldn't.
1426 $namespace .= ':';
1427 }
1428 $url = $interwiki->getURL( $namespace . $this->getDBkey() );
1429 $url = wfAppendQuery( $url, $query );
1430 } else {
1431 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
1432 if ( $query == '' ) {
1433 $url = str_replace( '$1', $dbkey, $wgArticlePath );
1434 wfRunHooks( 'GetLocalURL::Article', array( &$this, &$url ) );
1435 } else {
1436 global $wgVariantArticlePath, $wgActionPaths;
1437 $url = false;
1438 $matches = array();
1439
1440 if ( !empty( $wgActionPaths ) &&
1441 preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) )
1442 {
1443 $action = urldecode( $matches[2] );
1444 if ( isset( $wgActionPaths[$action] ) ) {
1445 $query = $matches[1];
1446 if ( isset( $matches[4] ) ) {
1447 $query .= $matches[4];
1448 }
1449 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
1450 if ( $query != '' ) {
1451 $url = wfAppendQuery( $url, $query );
1452 }
1453 }
1454 }
1455
1456 if ( $url === false &&
1457 $wgVariantArticlePath &&
1458 $this->getPageLanguage()->hasVariants() &&
1459 preg_match( '/^variant=([^&]*)$/', $query, $matches ) )
1460 {
1461 $variant = urldecode( $matches[1] );
1462 if ( $this->getPageLanguage()->hasVariant( $variant ) ) {
1463 // Only do the variant replacement if the given variant is a valid
1464 // variant for the page's language.
1465 $url = str_replace( '$2', urlencode( $variant ), $wgVariantArticlePath );
1466 $url = str_replace( '$1', $dbkey, $url );
1467 }
1468 }
1469
1470 if ( $url === false ) {
1471 if ( $query == '-' ) {
1472 $query = '';
1473 }
1474 $url = "{$wgScript}?title={$dbkey}&{$query}";
1475 }
1476 }
1477
1478 wfRunHooks( 'GetLocalURL::Internal', array( &$this, &$url, $query ) );
1479
1480 // @todo FIXME: This causes breakage in various places when we
1481 // actually expected a local URL and end up with dupe prefixes.
1482 if ( $wgRequest->getVal( 'action' ) == 'render' ) {
1483 $url = $wgServer . $url;
1484 }
1485 }
1486 wfRunHooks( 'GetLocalURL', array( &$this, &$url, $query ) );
1487 return $url;
1488 }
1489
1490 /**
1491 * Get a URL that's the simplest URL that will be valid to link, locally,
1492 * to the current Title. It includes the fragment, but does not include
1493 * the server unless action=render is used (or the link is external). If
1494 * there's a fragment but the prefixed text is empty, we just return a link
1495 * to the fragment.
1496 *
1497 * The result obviously should not be URL-escaped, but does need to be
1498 * HTML-escaped if it's being output in HTML.
1499 *
1500 * See getLocalURL for the arguments.
1501 *
1502 * @param $query
1503 * @param $query2 bool
1504 * @param $proto Protocol to use; setting this will cause a full URL to be used
1505 * @see self::getLocalURL
1506 * @return String the URL
1507 */
1508 public function getLinkURL( $query = '', $query2 = false, $proto = PROTO_RELATIVE ) {
1509 wfProfileIn( __METHOD__ );
1510 if ( $this->isExternal() || $proto !== PROTO_RELATIVE ) {
1511 $ret = $this->getFullURL( $query, $query2, $proto );
1512 } elseif ( $this->getPrefixedText() === '' && $this->getFragment() !== '' ) {
1513 $ret = $this->getFragmentForURL();
1514 } else {
1515 $ret = $this->getLocalURL( $query, $query2 ) . $this->getFragmentForURL();
1516 }
1517 wfProfileOut( __METHOD__ );
1518 return $ret;
1519 }
1520
1521 /**
1522 * Get an HTML-escaped version of the URL form, suitable for
1523 * using in a link, without a server name or fragment
1524 *
1525 * See getLocalURL for the arguments.
1526 *
1527 * @see self::getLocalURL
1528 * @param $query string
1529 * @param $query2 bool|string
1530 * @return String the URL
1531 */
1532 public function escapeLocalURL( $query = '', $query2 = false ) {
1533 wfDeprecated( __METHOD__, '1.19' );
1534 return htmlspecialchars( $this->getLocalURL( $query, $query2 ) );
1535 }
1536
1537 /**
1538 * Get an HTML-escaped version of the URL form, suitable for
1539 * using in a link, including the server name and fragment
1540 *
1541 * See getLocalURL for the arguments.
1542 *
1543 * @see self::getLocalURL
1544 * @return String the URL
1545 */
1546 public function escapeFullURL( $query = '', $query2 = false ) {
1547 wfDeprecated( __METHOD__, '1.19' );
1548 return htmlspecialchars( $this->getFullURL( $query, $query2 ) );
1549 }
1550
1551 /**
1552 * Get the URL form for an internal link.
1553 * - Used in various Squid-related code, in case we have a different
1554 * internal hostname for the server from the exposed one.
1555 *
1556 * This uses $wgInternalServer to qualify the path, or $wgServer
1557 * if $wgInternalServer is not set. If the server variable used is
1558 * protocol-relative, the URL will be expanded to http://
1559 *
1560 * See getLocalURL for the arguments.
1561 *
1562 * @see self::getLocalURL
1563 * @return String the URL
1564 */
1565 public function getInternalURL( $query = '', $query2 = false ) {
1566 global $wgInternalServer, $wgServer;
1567 $query = self::fixUrlQueryArgs( $query, $query2 );
1568 $server = $wgInternalServer !== false ? $wgInternalServer : $wgServer;
1569 $url = wfExpandUrl( $server . $this->getLocalURL( $query ), PROTO_HTTP );
1570 wfRunHooks( 'GetInternalURL', array( &$this, &$url, $query ) );
1571 return $url;
1572 }
1573
1574 /**
1575 * Get the URL for a canonical link, for use in things like IRC and
1576 * e-mail notifications. Uses $wgCanonicalServer and the
1577 * GetCanonicalURL hook.
1578 *
1579 * NOTE: Unlike getInternalURL(), the canonical URL includes the fragment
1580 *
1581 * See getLocalURL for the arguments.
1582 *
1583 * @see self::getLocalURL
1584 * @return string The URL
1585 * @since 1.18
1586 */
1587 public function getCanonicalURL( $query = '', $query2 = false ) {
1588 $query = self::fixUrlQueryArgs( $query, $query2 );
1589 $url = wfExpandUrl( $this->getLocalURL( $query ) . $this->getFragmentForURL(), PROTO_CANONICAL );
1590 wfRunHooks( 'GetCanonicalURL', array( &$this, &$url, $query ) );
1591 return $url;
1592 }
1593
1594 /**
1595 * HTML-escaped version of getCanonicalURL()
1596 *
1597 * See getLocalURL for the arguments.
1598 *
1599 * @see self::getLocalURL
1600 * @since 1.18
1601 * @return string
1602 */
1603 public function escapeCanonicalURL( $query = '', $query2 = false ) {
1604 wfDeprecated( __METHOD__, '1.19' );
1605 return htmlspecialchars( $this->getCanonicalURL( $query, $query2 ) );
1606 }
1607
1608 /**
1609 * Get the edit URL for this Title
1610 *
1611 * @return String the URL, or a null string if this is an
1612 * interwiki link
1613 */
1614 public function getEditURL() {
1615 if ( $this->mInterwiki != '' ) {
1616 return '';
1617 }
1618 $s = $this->getLocalURL( 'action=edit' );
1619
1620 return $s;
1621 }
1622
1623 /**
1624 * Is $wgUser watching this page?
1625 *
1626 * @deprecated in 1.20; use User::isWatched() instead.
1627 * @return Bool
1628 */
1629 public function userIsWatching() {
1630 global $wgUser;
1631
1632 if ( is_null( $this->mWatched ) ) {
1633 if ( NS_SPECIAL == $this->mNamespace || !$wgUser->isLoggedIn() ) {
1634 $this->mWatched = false;
1635 } else {
1636 $this->mWatched = $wgUser->isWatched( $this );
1637 }
1638 }
1639 return $this->mWatched;
1640 }
1641
1642 /**
1643 * Can $wgUser read this page?
1644 *
1645 * @deprecated in 1.19; use userCan(), quickUserCan() or getUserPermissionsErrors() instead
1646 * @return Bool
1647 * @todo fold these checks into userCan()
1648 */
1649 public function userCanRead() {
1650 wfDeprecated( __METHOD__, '1.19' );
1651 return $this->userCan( 'read' );
1652 }
1653
1654 /**
1655 * Can $user perform $action on this page?
1656 * This skips potentially expensive cascading permission checks
1657 * as well as avoids expensive error formatting
1658 *
1659 * Suitable for use for nonessential UI controls in common cases, but
1660 * _not_ for functional access control.
1661 *
1662 * May provide false positives, but should never provide a false negative.
1663 *
1664 * @param $action String action that permission needs to be checked for
1665 * @param $user User to check (since 1.19); $wgUser will be used if not
1666 * provided.
1667 * @return Bool
1668 */
1669 public function quickUserCan( $action, $user = null ) {
1670 return $this->userCan( $action, $user, false );
1671 }
1672
1673 /**
1674 * Can $user perform $action on this page?
1675 *
1676 * @param $action String action that permission needs to be checked for
1677 * @param $user User to check (since 1.19); $wgUser will be used if not
1678 * provided.
1679 * @param $doExpensiveQueries Bool Set this to false to avoid doing
1680 * unnecessary queries.
1681 * @return Bool
1682 */
1683 public function userCan( $action, $user = null, $doExpensiveQueries = true ) {
1684 if ( !$user instanceof User ) {
1685 global $wgUser;
1686 $user = $wgUser;
1687 }
1688 return !count( $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries, true ) );
1689 }
1690
1691 /**
1692 * Can $user perform $action on this page?
1693 *
1694 * @todo FIXME: This *does not* check throttles (User::pingLimiter()).
1695 *
1696 * @param $action String action that permission needs to be checked for
1697 * @param $user User to check
1698 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary
1699 * queries by skipping checks for cascading protections and user blocks.
1700 * @param $ignoreErrors Array of Strings Set this to a list of message keys
1701 * whose corresponding errors may be ignored.
1702 * @return Array of arguments to wfMessage to explain permissions problems.
1703 */
1704 public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true, $ignoreErrors = array() ) {
1705 $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
1706
1707 // Remove the errors being ignored.
1708 foreach ( $errors as $index => $error ) {
1709 $error_key = is_array( $error ) ? $error[0] : $error;
1710
1711 if ( in_array( $error_key, $ignoreErrors ) ) {
1712 unset( $errors[$index] );
1713 }
1714 }
1715
1716 return $errors;
1717 }
1718
1719 /**
1720 * Permissions checks that fail most often, and which are easiest to test.
1721 *
1722 * @param $action String the action to check
1723 * @param $user User user to check
1724 * @param $errors Array list of current errors
1725 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1726 * @param $short Boolean short circuit on first error
1727 *
1728 * @return Array list of errors
1729 */
1730 private function checkQuickPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1731 if ( $action == 'create' ) {
1732 if (
1733 ( $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
1734 ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) )
1735 ) {
1736 $errors[] = $user->isAnon() ? array( 'nocreatetext' ) : array( 'nocreate-loggedin' );
1737 }
1738 } elseif ( $action == 'move' ) {
1739 if ( !$user->isAllowed( 'move-rootuserpages' )
1740 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1741 // Show user page-specific message only if the user can move other pages
1742 $errors[] = array( 'cant-move-user-page' );
1743 }
1744
1745 // Check if user is allowed to move files if it's a file
1746 if ( $this->mNamespace == NS_FILE && !$user->isAllowed( 'movefile' ) ) {
1747 $errors[] = array( 'movenotallowedfile' );
1748 }
1749
1750 if ( !$user->isAllowed( 'move' ) ) {
1751 // User can't move anything
1752 $userCanMove = User::groupHasPermission( 'user', 'move' );
1753 $autoconfirmedCanMove = User::groupHasPermission( 'autoconfirmed', 'move' );
1754 if ( $user->isAnon() && ( $userCanMove || $autoconfirmedCanMove ) ) {
1755 // custom message if logged-in users without any special rights can move
1756 $errors[] = array( 'movenologintext' );
1757 } else {
1758 $errors[] = array( 'movenotallowed' );
1759 }
1760 }
1761 } elseif ( $action == 'move-target' ) {
1762 if ( !$user->isAllowed( 'move' ) ) {
1763 // User can't move anything
1764 $errors[] = array( 'movenotallowed' );
1765 } elseif ( !$user->isAllowed( 'move-rootuserpages' )
1766 && $this->mNamespace == NS_USER && !$this->isSubpage() ) {
1767 // Show user page-specific message only if the user can move other pages
1768 $errors[] = array( 'cant-move-to-user-page' );
1769 }
1770 } elseif ( !$user->isAllowed( $action ) ) {
1771 $errors[] = $this->missingPermissionError( $action, $short );
1772 }
1773
1774 return $errors;
1775 }
1776
1777 /**
1778 * Add the resulting error code to the errors array
1779 *
1780 * @param $errors Array list of current errors
1781 * @param $result Mixed result of errors
1782 *
1783 * @return Array list of errors
1784 */
1785 private function resultToError( $errors, $result ) {
1786 if ( is_array( $result ) && count( $result ) && !is_array( $result[0] ) ) {
1787 // A single array representing an error
1788 $errors[] = $result;
1789 } elseif ( is_array( $result ) && is_array( $result[0] ) ) {
1790 // A nested array representing multiple errors
1791 $errors = array_merge( $errors, $result );
1792 } elseif ( $result !== '' && is_string( $result ) ) {
1793 // A string representing a message-id
1794 $errors[] = array( $result );
1795 } elseif ( $result === false ) {
1796 // a generic "We don't want them to do that"
1797 $errors[] = array( 'badaccess-group0' );
1798 }
1799 return $errors;
1800 }
1801
1802 /**
1803 * Check various permission hooks
1804 *
1805 * @param $action String the action to check
1806 * @param $user User user to check
1807 * @param $errors Array list of current errors
1808 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1809 * @param $short Boolean short circuit on first error
1810 *
1811 * @return Array list of errors
1812 */
1813 private function checkPermissionHooks( $action, $user, $errors, $doExpensiveQueries, $short ) {
1814 // Use getUserPermissionsErrors instead
1815 $result = '';
1816 if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
1817 return $result ? array() : array( array( 'badaccess-group0' ) );
1818 }
1819 // Check getUserPermissionsErrors hook
1820 if ( !wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
1821 $errors = $this->resultToError( $errors, $result );
1822 }
1823 // Check getUserPermissionsErrorsExpensive hook
1824 if (
1825 $doExpensiveQueries
1826 && !( $short && count( $errors ) > 0 )
1827 && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) )
1828 ) {
1829 $errors = $this->resultToError( $errors, $result );
1830 }
1831
1832 return $errors;
1833 }
1834
1835 /**
1836 * Check permissions on special pages & namespaces
1837 *
1838 * @param $action String the action to check
1839 * @param $user User user to check
1840 * @param $errors Array list of current errors
1841 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1842 * @param $short Boolean short circuit on first error
1843 *
1844 * @return Array list of errors
1845 */
1846 private function checkSpecialsAndNSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1847 # Only 'createaccount' can be performed on special pages,
1848 # which don't actually exist in the DB.
1849 if ( NS_SPECIAL == $this->mNamespace && $action !== 'createaccount' ) {
1850 $errors[] = array( 'ns-specialprotected' );
1851 }
1852
1853 # Check $wgNamespaceProtection for restricted namespaces
1854 if ( $this->isNamespaceProtected( $user ) ) {
1855 $ns = $this->mNamespace == NS_MAIN ?
1856 wfMessage( 'nstab-main' )->text() : $this->getNsText();
1857 $errors[] = $this->mNamespace == NS_MEDIAWIKI ?
1858 array( 'protectedinterface' ) : array( 'namespaceprotected', $ns );
1859 }
1860
1861 return $errors;
1862 }
1863
1864 /**
1865 * Check CSS/JS sub-page permissions
1866 *
1867 * @param $action String the action to check
1868 * @param $user User user to check
1869 * @param $errors Array list of current errors
1870 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1871 * @param $short Boolean short circuit on first error
1872 *
1873 * @return Array list of errors
1874 */
1875 private function checkCSSandJSPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1876 # Protect css/js subpages of user pages
1877 # XXX: this might be better using restrictions
1878 # XXX: right 'editusercssjs' is deprecated, for backward compatibility only
1879 if ( $action != 'patrol' && !$user->isAllowed( 'editusercssjs' )
1880 && !preg_match( '/^' . preg_quote( $user->getName(), '/' ) . '\//', $this->mTextform ) ) {
1881 if ( $this->isCssSubpage() && !$user->isAllowed( 'editusercss' ) ) {
1882 $errors[] = array( 'customcssprotected' );
1883 } elseif ( $this->isJsSubpage() && !$user->isAllowed( 'edituserjs' ) ) {
1884 $errors[] = array( 'customjsprotected' );
1885 }
1886 }
1887
1888 return $errors;
1889 }
1890
1891 /**
1892 * Check against page_restrictions table requirements on this
1893 * page. The user must possess all required rights for this
1894 * action.
1895 *
1896 * @param $action String the action to check
1897 * @param $user User user to check
1898 * @param $errors Array list of current errors
1899 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1900 * @param $short Boolean short circuit on first error
1901 *
1902 * @return Array list of errors
1903 */
1904 private function checkPageRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1905 foreach ( $this->getRestrictions( $action ) as $right ) {
1906 // Backwards compatibility, rewrite sysop -> protect
1907 if ( $right == 'sysop' ) {
1908 $right = 'protect';
1909 }
1910 if ( $right != '' && !$user->isAllowed( $right ) ) {
1911 // Users with 'editprotected' permission can edit protected pages
1912 // without cascading option turned on.
1913 if ( $action != 'edit' || !$user->isAllowed( 'editprotected' )
1914 || $this->mCascadeRestriction )
1915 {
1916 $errors[] = array( 'protectedpagetext', $right );
1917 }
1918 }
1919 }
1920
1921 return $errors;
1922 }
1923
1924 /**
1925 * Check restrictions on cascading pages.
1926 *
1927 * @param $action String the action to check
1928 * @param $user User to check
1929 * @param $errors Array list of current errors
1930 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1931 * @param $short Boolean short circuit on first error
1932 *
1933 * @return Array list of errors
1934 */
1935 private function checkCascadingSourcesRestrictions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1936 if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
1937 # We /could/ use the protection level on the source page, but it's
1938 # fairly ugly as we have to establish a precedence hierarchy for pages
1939 # included by multiple cascade-protected pages. So just restrict
1940 # it to people with 'protect' permission, as they could remove the
1941 # protection anyway.
1942 list( $cascadingSources, $restrictions ) = $this->getCascadeProtectionSources();
1943 # Cascading protection depends on more than this page...
1944 # Several cascading protected pages may include this page...
1945 # Check each cascading level
1946 # This is only for protection restrictions, not for all actions
1947 if ( isset( $restrictions[$action] ) ) {
1948 foreach ( $restrictions[$action] as $right ) {
1949 $right = ( $right == 'sysop' ) ? 'protect' : $right;
1950 if ( $right != '' && !$user->isAllowed( $right ) ) {
1951 $pages = '';
1952 foreach ( $cascadingSources as $page )
1953 $pages .= '* [[:' . $page->getPrefixedText() . "]]\n";
1954 $errors[] = array( 'cascadeprotected', count( $cascadingSources ), $pages );
1955 }
1956 }
1957 }
1958 }
1959
1960 return $errors;
1961 }
1962
1963 /**
1964 * Check action permissions not already checked in checkQuickPermissions
1965 *
1966 * @param $action String the action to check
1967 * @param $user User to check
1968 * @param $errors Array list of current errors
1969 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
1970 * @param $short Boolean short circuit on first error
1971 *
1972 * @return Array list of errors
1973 */
1974 private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
1975 global $wgDeleteRevisionsLimit, $wgLang;
1976
1977 if ( $action == 'protect' ) {
1978 if ( count( $this->getUserPermissionsErrorsInternal( 'edit', $user, $doExpensiveQueries, true ) ) ) {
1979 // If they can't edit, they shouldn't protect.
1980 $errors[] = array( 'protect-cantedit' );
1981 }
1982 } elseif ( $action == 'create' ) {
1983 $title_protection = $this->getTitleProtection();
1984 if( $title_protection ) {
1985 if( $title_protection['pt_create_perm'] == 'sysop' ) {
1986 $title_protection['pt_create_perm'] = 'protect'; // B/C
1987 }
1988 if( $title_protection['pt_create_perm'] == '' ||
1989 !$user->isAllowed( $title_protection['pt_create_perm'] ) )
1990 {
1991 $errors[] = array( 'titleprotected', User::whoIs( $title_protection['pt_user'] ), $title_protection['pt_reason'] );
1992 }
1993 }
1994 } elseif ( $action == 'move' ) {
1995 // Check for immobile pages
1996 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
1997 // Specific message for this case
1998 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
1999 } elseif ( !$this->isMovable() ) {
2000 // Less specific message for rarer cases
2001 $errors[] = array( 'immobile-source-page' );
2002 }
2003 } elseif ( $action == 'move-target' ) {
2004 if ( !MWNamespace::isMovable( $this->mNamespace ) ) {
2005 $errors[] = array( 'immobile-target-namespace', $this->getNsText() );
2006 } elseif ( !$this->isMovable() ) {
2007 $errors[] = array( 'immobile-target-page' );
2008 }
2009 } elseif ( $action == 'delete' ) {
2010 if ( $doExpensiveQueries && $wgDeleteRevisionsLimit
2011 && !$this->userCan( 'bigdelete', $user ) && $this->isBigDeletion() )
2012 {
2013 $errors[] = array( 'delete-toobig', $wgLang->formatNum( $wgDeleteRevisionsLimit ) );
2014 }
2015 }
2016 return $errors;
2017 }
2018
2019 /**
2020 * Check that the user isn't blocked from editting.
2021 *
2022 * @param $action String the action to check
2023 * @param $user User to check
2024 * @param $errors Array list of current errors
2025 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2026 * @param $short Boolean short circuit on first error
2027 *
2028 * @return Array list of errors
2029 */
2030 private function checkUserBlock( $action, $user, $errors, $doExpensiveQueries, $short ) {
2031 // Account creation blocks handled at userlogin.
2032 // Unblocking handled in SpecialUnblock
2033 if( !$doExpensiveQueries || in_array( $action, array( 'createaccount', 'unblock' ) ) ) {
2034 return $errors;
2035 }
2036
2037 global $wgContLang, $wgLang, $wgEmailConfirmToEdit;
2038
2039 if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
2040 $errors[] = array( 'confirmedittext' );
2041 }
2042
2043 if ( ( $action == 'edit' || $action == 'create' ) && !$user->isBlockedFrom( $this ) ) {
2044 // Don't block the user from editing their own talk page unless they've been
2045 // explicitly blocked from that too.
2046 } elseif( $user->isBlocked() && $user->mBlock->prevents( $action ) !== false ) {
2047 $block = $user->getBlock();
2048
2049 // This is from OutputPage::blockedPage
2050 // Copied at r23888 by werdna
2051
2052 $id = $user->blockedBy();
2053 $reason = $user->blockedFor();
2054 if ( $reason == '' ) {
2055 $reason = wfMessage( 'blockednoreason' )->text();
2056 }
2057 $ip = $user->getRequest()->getIP();
2058
2059 if ( is_numeric( $id ) ) {
2060 $name = User::whoIs( $id );
2061 } else {
2062 $name = $id;
2063 }
2064
2065 $link = '[[' . $wgContLang->getNsText( NS_USER ) . ":{$name}|{$name}]]";
2066 $blockid = $block->getId();
2067 $blockExpiry = $block->getExpiry();
2068 $blockTimestamp = $wgLang->timeanddate( wfTimestamp( TS_MW, $block->mTimestamp ), true );
2069 if ( $blockExpiry == 'infinity' ) {
2070 $blockExpiry = wfMessage( 'infiniteblock' )->text();
2071 } else {
2072 $blockExpiry = $wgLang->timeanddate( wfTimestamp( TS_MW, $blockExpiry ), true );
2073 }
2074
2075 $intended = strval( $block->getTarget() );
2076
2077 $errors[] = array( ( $block->mAuto ? 'autoblockedtext' : 'blockedtext' ), $link, $reason, $ip, $name,
2078 $blockid, $blockExpiry, $intended, $blockTimestamp );
2079 }
2080
2081 return $errors;
2082 }
2083
2084 /**
2085 * Check that the user is allowed to read this page.
2086 *
2087 * @param $action String the action to check
2088 * @param $user User to check
2089 * @param $errors Array list of current errors
2090 * @param $doExpensiveQueries Boolean whether or not to perform expensive queries
2091 * @param $short Boolean short circuit on first error
2092 *
2093 * @return Array list of errors
2094 */
2095 private function checkReadPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
2096 global $wgWhitelistRead, $wgWhitelistReadRegexp, $wgRevokePermissions;
2097 static $useShortcut = null;
2098
2099 # Initialize the $useShortcut boolean, to determine if we can skip quite a bit of code below
2100 if ( is_null( $useShortcut ) ) {
2101 $useShortcut = true;
2102 if ( !User::groupHasPermission( '*', 'read' ) ) {
2103 # Not a public wiki, so no shortcut
2104 $useShortcut = false;
2105 } elseif ( !empty( $wgRevokePermissions ) ) {
2106 /**
2107 * Iterate through each group with permissions being revoked (key not included since we don't care
2108 * what the group name is), then check if the read permission is being revoked. If it is, then
2109 * we don't use the shortcut below since the user might not be able to read, even though anon
2110 * reading is allowed.
2111 */
2112 foreach ( $wgRevokePermissions as $perms ) {
2113 if ( !empty( $perms['read'] ) ) {
2114 # We might be removing the read right from the user, so no shortcut
2115 $useShortcut = false;
2116 break;
2117 }
2118 }
2119 }
2120 }
2121
2122 $whitelisted = false;
2123 if ( $useShortcut ) {
2124 # Shortcut for public wikis, allows skipping quite a bit of code
2125 $whitelisted = true;
2126 } elseif ( $user->isAllowed( 'read' ) ) {
2127 # If the user is allowed to read pages, he is allowed to read all pages
2128 $whitelisted = true;
2129 } elseif ( $this->isSpecial( 'Userlogin' )
2130 || $this->isSpecial( 'ChangePassword' )
2131 || $this->isSpecial( 'PasswordReset' )
2132 ) {
2133 # Always grant access to the login page.
2134 # Even anons need to be able to log in.
2135 $whitelisted = true;
2136 } elseif ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
2137 # Time to check the whitelist
2138 # Only do these checks is there's something to check against
2139 $name = $this->getPrefixedText();
2140 $dbName = $this->getPrefixedDBKey();
2141
2142 // Check for explicit whitelisting with and without underscores
2143 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
2144 $whitelisted = true;
2145 } elseif ( $this->getNamespace() == NS_MAIN ) {
2146 # Old settings might have the title prefixed with
2147 # a colon for main-namespace pages
2148 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
2149 $whitelisted = true;
2150 }
2151 } elseif ( $this->isSpecialPage() ) {
2152 # If it's a special page, ditch the subpage bit and check again
2153 $name = $this->getDBkey();
2154 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
2155 if ( $name ) {
2156 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
2157 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
2158 $whitelisted = true;
2159 }
2160 }
2161 }
2162 }
2163
2164 if( !$whitelisted && is_array( $wgWhitelistReadRegexp ) && !empty( $wgWhitelistReadRegexp ) ) {
2165 $name = $this->getPrefixedText();
2166 // Check for regex whitelisting
2167 foreach ( $wgWhitelistReadRegexp as $listItem ) {
2168 if ( preg_match( $listItem, $name ) ) {
2169 $whitelisted = true;
2170 break;
2171 }
2172 }
2173 }
2174
2175 if ( !$whitelisted ) {
2176 # If the title is not whitelisted, give extensions a chance to do so...
2177 wfRunHooks( 'TitleReadWhitelist', array( $this, $user, &$whitelisted ) );
2178 if ( !$whitelisted ) {
2179 $errors[] = $this->missingPermissionError( $action, $short );
2180 }
2181 }
2182
2183 return $errors;
2184 }
2185
2186 /**
2187 * Get a description array when the user doesn't have the right to perform
2188 * $action (i.e. when User::isAllowed() returns false)
2189 *
2190 * @param $action String the action to check
2191 * @param $short Boolean short circuit on first error
2192 * @return Array list of errors
2193 */
2194 private function missingPermissionError( $action, $short ) {
2195 // We avoid expensive display logic for quickUserCan's and such
2196 if ( $short ) {
2197 return array( 'badaccess-group0' );
2198 }
2199
2200 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
2201 User::getGroupsWithPermission( $action ) );
2202
2203 if ( count( $groups ) ) {
2204 global $wgLang;
2205 return array(
2206 'badaccess-groups',
2207 $wgLang->commaList( $groups ),
2208 count( $groups )
2209 );
2210 } else {
2211 return array( 'badaccess-group0' );
2212 }
2213 }
2214
2215 /**
2216 * Can $user perform $action on this page? This is an internal function,
2217 * which checks ONLY that previously checked by userCan (i.e. it leaves out
2218 * checks on wfReadOnly() and blocks)
2219 *
2220 * @param $action String action that permission needs to be checked for
2221 * @param $user User to check
2222 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
2223 * @param $short Bool Set this to true to stop after the first permission error.
2224 * @return Array of arrays of the arguments to wfMessage to explain permissions problems.
2225 */
2226 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
2227 wfProfileIn( __METHOD__ );
2228
2229 # Read has special handling
2230 if ( $action == 'read' ) {
2231 $checks = array(
2232 'checkPermissionHooks',
2233 'checkReadPermissions',
2234 );
2235 } else {
2236 $checks = array(
2237 'checkQuickPermissions',
2238 'checkPermissionHooks',
2239 'checkSpecialsAndNSPermissions',
2240 'checkCSSandJSPermissions',
2241 'checkPageRestrictions',
2242 'checkCascadingSourcesRestrictions',
2243 'checkActionPermissions',
2244 'checkUserBlock'
2245 );
2246 }
2247
2248 $errors = array();
2249 while( count( $checks ) > 0 &&
2250 !( $short && count( $errors ) > 0 ) ) {
2251 $method = array_shift( $checks );
2252 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
2253 }
2254
2255 wfProfileOut( __METHOD__ );
2256 return $errors;
2257 }
2258
2259 /**
2260 * Protect css subpages of user pages: can $wgUser edit
2261 * this page?
2262 *
2263 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2264 * @return Bool
2265 */
2266 public function userCanEditCssSubpage() {
2267 global $wgUser;
2268 wfDeprecated( __METHOD__, '1.19' );
2269 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2270 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2271 }
2272
2273 /**
2274 * Protect js subpages of user pages: can $wgUser edit
2275 * this page?
2276 *
2277 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2278 * @return Bool
2279 */
2280 public function userCanEditJsSubpage() {
2281 global $wgUser;
2282 wfDeprecated( __METHOD__, '1.19' );
2283 return (
2284 ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2285 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform )
2286 );
2287 }
2288
2289 /**
2290 * Get a filtered list of all restriction types supported by this wiki.
2291 * @param bool $exists True to get all restriction types that apply to
2292 * titles that do exist, False for all restriction types that apply to
2293 * titles that do not exist
2294 * @return array
2295 */
2296 public static function getFilteredRestrictionTypes( $exists = true ) {
2297 global $wgRestrictionTypes;
2298 $types = $wgRestrictionTypes;
2299 if ( $exists ) {
2300 # Remove the create restriction for existing titles
2301 $types = array_diff( $types, array( 'create' ) );
2302 } else {
2303 # Only the create and upload restrictions apply to non-existing titles
2304 $types = array_intersect( $types, array( 'create', 'upload' ) );
2305 }
2306 return $types;
2307 }
2308
2309 /**
2310 * Returns restriction types for the current Title
2311 *
2312 * @return array applicable restriction types
2313 */
2314 public function getRestrictionTypes() {
2315 if ( $this->isSpecialPage() ) {
2316 return array();
2317 }
2318
2319 $types = self::getFilteredRestrictionTypes( $this->exists() );
2320
2321 if ( $this->getNamespace() != NS_FILE ) {
2322 # Remove the upload restriction for non-file titles
2323 $types = array_diff( $types, array( 'upload' ) );
2324 }
2325
2326 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
2327
2328 wfDebug( __METHOD__ . ': applicable restrictions to [[' .
2329 $this->getPrefixedText() . ']] are {' . implode( ',', $types ) . "}\n" );
2330
2331 return $types;
2332 }
2333
2334 /**
2335 * Is this title subject to title protection?
2336 * Title protection is the one applied against creation of such title.
2337 *
2338 * @return Mixed An associative array representing any existent title
2339 * protection, or false if there's none.
2340 */
2341 private function getTitleProtection() {
2342 // Can't protect pages in special namespaces
2343 if ( $this->getNamespace() < 0 ) {
2344 return false;
2345 }
2346
2347 // Can't protect pages that exist.
2348 if ( $this->exists() ) {
2349 return false;
2350 }
2351
2352 if ( !isset( $this->mTitleProtection ) ) {
2353 $dbr = wfGetDB( DB_SLAVE );
2354 $res = $dbr->select(
2355 'protected_titles',
2356 array( 'pt_user', 'pt_reason', 'pt_expiry', 'pt_create_perm' ),
2357 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2358 __METHOD__
2359 );
2360
2361 // fetchRow returns false if there are no rows.
2362 $this->mTitleProtection = $dbr->fetchRow( $res );
2363 }
2364 return $this->mTitleProtection;
2365 }
2366
2367 /**
2368 * Update the title protection status
2369 *
2370 * @deprecated in 1.19; will be removed in 1.20. Use WikiPage::doUpdateRestrictions() instead.
2371 * @param $create_perm String Permission required for creation
2372 * @param $reason String Reason for protection
2373 * @param $expiry String Expiry timestamp
2374 * @return boolean true
2375 */
2376 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
2377 wfDeprecated( __METHOD__, '1.19' );
2378
2379 global $wgUser;
2380
2381 $limit = array( 'create' => $create_perm );
2382 $expiry = array( 'create' => $expiry );
2383
2384 $page = WikiPage::factory( $this );
2385 $cascade = false;
2386 $status = $page->doUpdateRestrictions( $limit, $expiry, $cascade, $reason, $wgUser );
2387
2388 return $status->isOK();
2389 }
2390
2391 /**
2392 * Remove any title protection due to page existing
2393 */
2394 public function deleteTitleProtection() {
2395 $dbw = wfGetDB( DB_MASTER );
2396
2397 $dbw->delete(
2398 'protected_titles',
2399 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
2400 __METHOD__
2401 );
2402 $this->mTitleProtection = false;
2403 }
2404
2405 /**
2406 * Is this page "semi-protected" - the *only* protection is autoconfirm?
2407 *
2408 * @param $action String Action to check (default: edit)
2409 * @return Bool
2410 */
2411 public function isSemiProtected( $action = 'edit' ) {
2412 if ( $this->exists() ) {
2413 $restrictions = $this->getRestrictions( $action );
2414 if ( count( $restrictions ) > 0 ) {
2415 foreach ( $restrictions as $restriction ) {
2416 if ( strtolower( $restriction ) != 'autoconfirmed' ) {
2417 return false;
2418 }
2419 }
2420 } else {
2421 # Not protected
2422 return false;
2423 }
2424 return true;
2425 } else {
2426 # If it doesn't exist, it can't be protected
2427 return false;
2428 }
2429 }
2430
2431 /**
2432 * Does the title correspond to a protected article?
2433 *
2434 * @param $action String the action the page is protected from,
2435 * by default checks all actions.
2436 * @return Bool
2437 */
2438 public function isProtected( $action = '' ) {
2439 global $wgRestrictionLevels;
2440
2441 $restrictionTypes = $this->getRestrictionTypes();
2442
2443 # Special pages have inherent protection
2444 if( $this->isSpecialPage() ) {
2445 return true;
2446 }
2447
2448 # Check regular protection levels
2449 foreach ( $restrictionTypes as $type ) {
2450 if ( $action == $type || $action == '' ) {
2451 $r = $this->getRestrictions( $type );
2452 foreach ( $wgRestrictionLevels as $level ) {
2453 if ( in_array( $level, $r ) && $level != '' ) {
2454 return true;
2455 }
2456 }
2457 }
2458 }
2459
2460 return false;
2461 }
2462
2463 /**
2464 * Determines if $user is unable to edit this page because it has been protected
2465 * by $wgNamespaceProtection.
2466 *
2467 * @param $user User object to check permissions
2468 * @return Bool
2469 */
2470 public function isNamespaceProtected( User $user ) {
2471 global $wgNamespaceProtection;
2472
2473 if ( isset( $wgNamespaceProtection[$this->mNamespace] ) ) {
2474 foreach ( (array)$wgNamespaceProtection[$this->mNamespace] as $right ) {
2475 if ( $right != '' && !$user->isAllowed( $right ) ) {
2476 return true;
2477 }
2478 }
2479 }
2480 return false;
2481 }
2482
2483 /**
2484 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2485 *
2486 * @return Bool If the page is subject to cascading restrictions.
2487 */
2488 public function isCascadeProtected() {
2489 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2490 return ( $sources > 0 );
2491 }
2492
2493 /**
2494 * Cascading protection: Get the source of any cascading restrictions on this page.
2495 *
2496 * @param $getPages Bool Whether or not to retrieve the actual pages
2497 * that the restrictions have come from.
2498 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2499 * have come, false for none, or true if such restrictions exist, but $getPages
2500 * was not set. The restriction array is an array of each type, each of which
2501 * contains a array of unique groups.
2502 */
2503 public function getCascadeProtectionSources( $getPages = true ) {
2504 global $wgContLang;
2505 $pagerestrictions = array();
2506
2507 if ( isset( $this->mCascadeSources ) && $getPages ) {
2508 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2509 } elseif ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2510 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2511 }
2512
2513 wfProfileIn( __METHOD__ );
2514
2515 $dbr = wfGetDB( DB_SLAVE );
2516
2517 if ( $this->getNamespace() == NS_FILE ) {
2518 $tables = array( 'imagelinks', 'page_restrictions' );
2519 $where_clauses = array(
2520 'il_to' => $this->getDBkey(),
2521 'il_from=pr_page',
2522 'pr_cascade' => 1
2523 );
2524 } else {
2525 $tables = array( 'templatelinks', 'page_restrictions' );
2526 $where_clauses = array(
2527 'tl_namespace' => $this->getNamespace(),
2528 'tl_title' => $this->getDBkey(),
2529 'tl_from=pr_page',
2530 'pr_cascade' => 1
2531 );
2532 }
2533
2534 if ( $getPages ) {
2535 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2536 'pr_expiry', 'pr_type', 'pr_level' );
2537 $where_clauses[] = 'page_id=pr_page';
2538 $tables[] = 'page';
2539 } else {
2540 $cols = array( 'pr_expiry' );
2541 }
2542
2543 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2544
2545 $sources = $getPages ? array() : false;
2546 $now = wfTimestampNow();
2547 $purgeExpired = false;
2548
2549 foreach ( $res as $row ) {
2550 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2551 if ( $expiry > $now ) {
2552 if ( $getPages ) {
2553 $page_id = $row->pr_page;
2554 $page_ns = $row->page_namespace;
2555 $page_title = $row->page_title;
2556 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2557 # Add groups needed for each restriction type if its not already there
2558 # Make sure this restriction type still exists
2559
2560 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2561 $pagerestrictions[$row->pr_type] = array();
2562 }
2563
2564 if (
2565 isset( $pagerestrictions[$row->pr_type] )
2566 && !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] )
2567 ) {
2568 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2569 }
2570 } else {
2571 $sources = true;
2572 }
2573 } else {
2574 // Trigger lazy purge of expired restrictions from the db
2575 $purgeExpired = true;
2576 }
2577 }
2578 if ( $purgeExpired ) {
2579 Title::purgeExpiredRestrictions();
2580 }
2581
2582 if ( $getPages ) {
2583 $this->mCascadeSources = $sources;
2584 $this->mCascadingRestrictions = $pagerestrictions;
2585 } else {
2586 $this->mHasCascadingRestrictions = $sources;
2587 }
2588
2589 wfProfileOut( __METHOD__ );
2590 return array( $sources, $pagerestrictions );
2591 }
2592
2593 /**
2594 * Accessor/initialisation for mRestrictions
2595 *
2596 * @param $action String action that permission needs to be checked for
2597 * @return Array of Strings the array of groups allowed to edit this article
2598 */
2599 public function getRestrictions( $action ) {
2600 if ( !$this->mRestrictionsLoaded ) {
2601 $this->loadRestrictions();
2602 }
2603 return isset( $this->mRestrictions[$action] )
2604 ? $this->mRestrictions[$action]
2605 : array();
2606 }
2607
2608 /**
2609 * Get the expiry time for the restriction against a given action
2610 *
2611 * @param $action
2612 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2613 * or not protected at all, or false if the action is not recognised.
2614 */
2615 public function getRestrictionExpiry( $action ) {
2616 if ( !$this->mRestrictionsLoaded ) {
2617 $this->loadRestrictions();
2618 }
2619 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2620 }
2621
2622 /**
2623 * Returns cascading restrictions for the current article
2624 *
2625 * @return Boolean
2626 */
2627 function areRestrictionsCascading() {
2628 if ( !$this->mRestrictionsLoaded ) {
2629 $this->loadRestrictions();
2630 }
2631
2632 return $this->mCascadeRestriction;
2633 }
2634
2635 /**
2636 * Loads a string into mRestrictions array
2637 *
2638 * @param $res Resource restrictions as an SQL result.
2639 * @param $oldFashionedRestrictions String comma-separated list of page
2640 * restrictions from page table (pre 1.10)
2641 */
2642 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2643 $rows = array();
2644
2645 foreach ( $res as $row ) {
2646 $rows[] = $row;
2647 }
2648
2649 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2650 }
2651
2652 /**
2653 * Compiles list of active page restrictions from both page table (pre 1.10)
2654 * and page_restrictions table for this existing page.
2655 * Public for usage by LiquidThreads.
2656 *
2657 * @param $rows array of db result objects
2658 * @param $oldFashionedRestrictions string comma-separated list of page
2659 * restrictions from page table (pre 1.10)
2660 */
2661 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2662 global $wgContLang;
2663 $dbr = wfGetDB( DB_SLAVE );
2664
2665 $restrictionTypes = $this->getRestrictionTypes();
2666
2667 foreach ( $restrictionTypes as $type ) {
2668 $this->mRestrictions[$type] = array();
2669 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2670 }
2671
2672 $this->mCascadeRestriction = false;
2673
2674 # Backwards-compatibility: also load the restrictions from the page record (old format).
2675
2676 if ( $oldFashionedRestrictions === null ) {
2677 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2678 array( 'page_id' => $this->getArticleID() ), __METHOD__ );
2679 }
2680
2681 if ( $oldFashionedRestrictions != '' ) {
2682
2683 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2684 $temp = explode( '=', trim( $restrict ) );
2685 if ( count( $temp ) == 1 ) {
2686 // old old format should be treated as edit/move restriction
2687 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2688 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2689 } else {
2690 $restriction = trim( $temp[1] );
2691 if( $restriction != '' ) { //some old entries are empty
2692 $this->mRestrictions[$temp[0]] = explode( ',', $restriction );
2693 }
2694 }
2695 }
2696
2697 $this->mOldRestrictions = true;
2698
2699 }
2700
2701 if ( count( $rows ) ) {
2702 # Current system - load second to make them override.
2703 $now = wfTimestampNow();
2704 $purgeExpired = false;
2705
2706 # Cycle through all the restrictions.
2707 foreach ( $rows as $row ) {
2708
2709 // Don't take care of restrictions types that aren't allowed
2710 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2711 continue;
2712
2713 // This code should be refactored, now that it's being used more generally,
2714 // But I don't really see any harm in leaving it in Block for now -werdna
2715 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2716
2717 // Only apply the restrictions if they haven't expired!
2718 if ( !$expiry || $expiry > $now ) {
2719 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2720 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2721
2722 $this->mCascadeRestriction |= $row->pr_cascade;
2723 } else {
2724 // Trigger a lazy purge of expired restrictions
2725 $purgeExpired = true;
2726 }
2727 }
2728
2729 if ( $purgeExpired ) {
2730 Title::purgeExpiredRestrictions();
2731 }
2732 }
2733
2734 $this->mRestrictionsLoaded = true;
2735 }
2736
2737 /**
2738 * Load restrictions from the page_restrictions table
2739 *
2740 * @param $oldFashionedRestrictions String comma-separated list of page
2741 * restrictions from page table (pre 1.10)
2742 */
2743 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2744 global $wgContLang;
2745 if ( !$this->mRestrictionsLoaded ) {
2746 if ( $this->exists() ) {
2747 $dbr = wfGetDB( DB_SLAVE );
2748
2749 $res = $dbr->select(
2750 'page_restrictions',
2751 array( 'pr_type', 'pr_expiry', 'pr_level', 'pr_cascade' ),
2752 array( 'pr_page' => $this->getArticleID() ),
2753 __METHOD__
2754 );
2755
2756 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2757 } else {
2758 $title_protection = $this->getTitleProtection();
2759
2760 if ( $title_protection ) {
2761 $now = wfTimestampNow();
2762 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW );
2763
2764 if ( !$expiry || $expiry > $now ) {
2765 // Apply the restrictions
2766 $this->mRestrictionsExpiry['create'] = $expiry;
2767 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2768 } else { // Get rid of the old restrictions
2769 Title::purgeExpiredRestrictions();
2770 $this->mTitleProtection = false;
2771 }
2772 } else {
2773 $this->mRestrictionsExpiry['create'] = $wgContLang->formatExpiry( '', TS_MW );
2774 }
2775 $this->mRestrictionsLoaded = true;
2776 }
2777 }
2778 }
2779
2780 /**
2781 * Flush the protection cache in this object and force reload from the database.
2782 * This is used when updating protection from WikiPage::doUpdateRestrictions().
2783 */
2784 public function flushRestrictions() {
2785 $this->mRestrictionsLoaded = false;
2786 $this->mTitleProtection = null;
2787 }
2788
2789 /**
2790 * Purge expired restrictions from the page_restrictions table
2791 */
2792 static function purgeExpiredRestrictions() {
2793 if ( wfReadOnly() ) {
2794 return;
2795 }
2796
2797 $dbw = wfGetDB( DB_MASTER );
2798 $dbw->delete(
2799 'page_restrictions',
2800 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2801 __METHOD__
2802 );
2803
2804 $dbw->delete(
2805 'protected_titles',
2806 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2807 __METHOD__
2808 );
2809 }
2810
2811 /**
2812 * Does this have subpages? (Warning, usually requires an extra DB query.)
2813 *
2814 * @return Bool
2815 */
2816 public function hasSubpages() {
2817 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
2818 # Duh
2819 return false;
2820 }
2821
2822 # We dynamically add a member variable for the purpose of this method
2823 # alone to cache the result. There's no point in having it hanging
2824 # around uninitialized in every Title object; therefore we only add it
2825 # if needed and don't declare it statically.
2826 if ( isset( $this->mHasSubpages ) ) {
2827 return $this->mHasSubpages;
2828 }
2829
2830 $subpages = $this->getSubpages( 1 );
2831 if ( $subpages instanceof TitleArray ) {
2832 return $this->mHasSubpages = (bool)$subpages->count();
2833 }
2834 return $this->mHasSubpages = false;
2835 }
2836
2837 /**
2838 * Get all subpages of this page.
2839 *
2840 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2841 * @return mixed TitleArray, or empty array if this page's namespace
2842 * doesn't allow subpages
2843 */
2844 public function getSubpages( $limit = -1 ) {
2845 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
2846 return array();
2847 }
2848
2849 $dbr = wfGetDB( DB_SLAVE );
2850 $conds['page_namespace'] = $this->getNamespace();
2851 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2852 $options = array();
2853 if ( $limit > -1 ) {
2854 $options['LIMIT'] = $limit;
2855 }
2856 return $this->mSubpages = TitleArray::newFromResult(
2857 $dbr->select( 'page',
2858 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2859 $conds,
2860 __METHOD__,
2861 $options
2862 )
2863 );
2864 }
2865
2866 /**
2867 * Is there a version of this page in the deletion archive?
2868 *
2869 * @return Int the number of archived revisions
2870 */
2871 public function isDeleted() {
2872 if ( $this->getNamespace() < 0 ) {
2873 $n = 0;
2874 } else {
2875 $dbr = wfGetDB( DB_SLAVE );
2876
2877 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2878 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2879 __METHOD__
2880 );
2881 if ( $this->getNamespace() == NS_FILE ) {
2882 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2883 array( 'fa_name' => $this->getDBkey() ),
2884 __METHOD__
2885 );
2886 }
2887 }
2888 return (int)$n;
2889 }
2890
2891 /**
2892 * Is there a version of this page in the deletion archive?
2893 *
2894 * @return Boolean
2895 */
2896 public function isDeletedQuick() {
2897 if ( $this->getNamespace() < 0 ) {
2898 return false;
2899 }
2900 $dbr = wfGetDB( DB_SLAVE );
2901 $deleted = (bool)$dbr->selectField( 'archive', '1',
2902 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2903 __METHOD__
2904 );
2905 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
2906 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2907 array( 'fa_name' => $this->getDBkey() ),
2908 __METHOD__
2909 );
2910 }
2911 return $deleted;
2912 }
2913
2914 /**
2915 * Get the article ID for this Title from the link cache,
2916 * adding it if necessary
2917 *
2918 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2919 * for update
2920 * @return Int the ID
2921 */
2922 public function getArticleID( $flags = 0 ) {
2923 if ( $this->getNamespace() < 0 ) {
2924 return $this->mArticleID = 0;
2925 }
2926 $linkCache = LinkCache::singleton();
2927 if ( $flags & self::GAID_FOR_UPDATE ) {
2928 $oldUpdate = $linkCache->forUpdate( true );
2929 $linkCache->clearLink( $this );
2930 $this->mArticleID = $linkCache->addLinkObj( $this );
2931 $linkCache->forUpdate( $oldUpdate );
2932 } else {
2933 if ( -1 == $this->mArticleID ) {
2934 $this->mArticleID = $linkCache->addLinkObj( $this );
2935 }
2936 }
2937 return $this->mArticleID;
2938 }
2939
2940 /**
2941 * Is this an article that is a redirect page?
2942 * Uses link cache, adding it if necessary
2943 *
2944 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2945 * @return Bool
2946 */
2947 public function isRedirect( $flags = 0 ) {
2948 if ( !( $flags & Title::GAID_FOR_UPDATE ) && !is_null( $this->mRedirect ) ) {
2949 return $this->mRedirect;
2950 }
2951
2952 if ( !$this->getArticleID( $flags ) ) {
2953 return $this->mRedirect = false;
2954 }
2955
2956 $linkCache = LinkCache::singleton();
2957 $linkCache->addLinkObj( $this );
2958 $cached = $linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2959
2960 if ( $cached === null ) {
2961 // Should not happen
2962 throw new MWException( "LinkCache doesn't know redirect status of this title: " . $this->getPrefixedDBkey() );
2963 }
2964
2965 $this->mRedirect = (bool)$cached;
2966
2967 return $this->mRedirect;
2968 }
2969
2970 /**
2971 * What is the length of this page?
2972 * Uses link cache, adding it if necessary
2973 *
2974 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2975 * @return Int
2976 */
2977 public function getLength( $flags = 0 ) {
2978 if ( !( $flags & Title::GAID_FOR_UPDATE ) && $this->mLength != -1 ) {
2979 return $this->mLength;
2980 }
2981
2982 if ( !$this->getArticleID( $flags ) ) {
2983 return $this->mLength = 0;
2984 }
2985
2986 $linkCache = LinkCache::singleton();
2987 $linkCache->addLinkObj( $this );
2988 $cached = $linkCache->getGoodLinkFieldObj( $this, 'length' );
2989
2990 if ( $cached === null ) {
2991 // Should not happen
2992 throw new MWException( "LinkCache doesn't know redirect status of this title: " . $this->getPrefixedDBkey() );
2993 }
2994
2995 $this->mLength = intval( $cached );
2996
2997 return $this->mLength;
2998 }
2999
3000 /**
3001 * What is the page_latest field for this page?
3002 *
3003 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
3004 * @throws MWException
3005 * @return Int or 0 if the page doesn't exist
3006 */
3007 public function getLatestRevID( $flags = 0 ) {
3008 if ( !( $flags & Title::GAID_FOR_UPDATE ) && $this->mLatestID !== false ) {
3009 return intval( $this->mLatestID );
3010 }
3011
3012 if ( !$this->getArticleID( $flags ) ) {
3013 return $this->mLatestID = 0;
3014 }
3015
3016 $linkCache = LinkCache::singleton();
3017 $linkCache->addLinkObj( $this );
3018 $cached = $linkCache->getGoodLinkFieldObj( $this, 'revision' );
3019
3020 if ( $cached === null ) {
3021 // Should not happen
3022 throw new MWException( "LinkCache doesn't know latest revision ID of this title: " . $this->getPrefixedDBkey() );
3023 }
3024
3025 $this->mLatestID = intval( $cached );
3026
3027 return $this->mLatestID;
3028 }
3029
3030 /**
3031 * This clears some fields in this object, and clears any associated
3032 * keys in the "bad links" section of the link cache.
3033 *
3034 * - This is called from WikiPage::doEdit() and WikiPage::insertOn() to allow
3035 * loading of the new page_id. It's also called from
3036 * WikiPage::doDeleteArticleReal()
3037 *
3038 * @param $newid Int the new Article ID
3039 */
3040 public function resetArticleID( $newid ) {
3041 $linkCache = LinkCache::singleton();
3042 $linkCache->clearLink( $this );
3043
3044 if ( $newid === false ) {
3045 $this->mArticleID = -1;
3046 } else {
3047 $this->mArticleID = intval( $newid );
3048 }
3049 $this->mRestrictionsLoaded = false;
3050 $this->mRestrictions = array();
3051 $this->mRedirect = null;
3052 $this->mLength = -1;
3053 $this->mLatestID = false;
3054 $this->mContentModel = false;
3055 $this->mEstimateRevisions = null;
3056 }
3057
3058 /**
3059 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
3060 *
3061 * @param $text String containing title to capitalize
3062 * @param $ns int namespace index, defaults to NS_MAIN
3063 * @return String containing capitalized title
3064 */
3065 public static function capitalize( $text, $ns = NS_MAIN ) {
3066 global $wgContLang;
3067
3068 if ( MWNamespace::isCapitalized( $ns ) ) {
3069 return $wgContLang->ucfirst( $text );
3070 } else {
3071 return $text;
3072 }
3073 }
3074
3075 /**
3076 * Secure and split - main initialisation function for this object
3077 *
3078 * Assumes that mDbkeyform has been set, and is urldecoded
3079 * and uses underscores, but not otherwise munged. This function
3080 * removes illegal characters, splits off the interwiki and
3081 * namespace prefixes, sets the other forms, and canonicalizes
3082 * everything.
3083 *
3084 * @return Bool true on success
3085 */
3086 private function secureAndSplit() {
3087 global $wgContLang, $wgLocalInterwiki;
3088
3089 # Initialisation
3090 $this->mInterwiki = $this->mFragment = '';
3091 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
3092
3093 $dbkey = $this->mDbkeyform;
3094
3095 # Strip Unicode bidi override characters.
3096 # Sometimes they slip into cut-n-pasted page titles, where the
3097 # override chars get included in list displays.
3098 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
3099
3100 # Clean up whitespace
3101 # Note: use of the /u option on preg_replace here will cause
3102 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
3103 # conveniently disabling them.
3104 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
3105 $dbkey = trim( $dbkey, '_' );
3106
3107 if ( $dbkey == '' ) {
3108 return false;
3109 }
3110
3111 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
3112 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
3113 return false;
3114 }
3115
3116 $this->mDbkeyform = $dbkey;
3117
3118 # Initial colon indicates main namespace rather than specified default
3119 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
3120 if ( ':' == $dbkey[0] ) {
3121 $this->mNamespace = NS_MAIN;
3122 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
3123 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
3124 }
3125
3126 # Namespace or interwiki prefix
3127 $firstPass = true;
3128 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
3129 do {
3130 $m = array();
3131 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
3132 $p = $m[1];
3133 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
3134 # Ordinary namespace
3135 $dbkey = $m[2];
3136 $this->mNamespace = $ns;
3137 # For Talk:X pages, check if X has a "namespace" prefix
3138 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
3139 if ( $wgContLang->getNsIndex( $x[1] ) ) {
3140 # Disallow Talk:File:x type titles...
3141 return false;
3142 } elseif ( Interwiki::isValidInterwiki( $x[1] ) ) {
3143 # Disallow Talk:Interwiki:x type titles...
3144 return false;
3145 }
3146 }
3147 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
3148 if ( !$firstPass ) {
3149 # Can't make a local interwiki link to an interwiki link.
3150 # That's just crazy!
3151 return false;
3152 }
3153
3154 # Interwiki link
3155 $dbkey = $m[2];
3156 $this->mInterwiki = $wgContLang->lc( $p );
3157
3158 # Redundant interwiki prefix to the local wiki
3159 if ( $wgLocalInterwiki !== false
3160 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
3161 {
3162 if ( $dbkey == '' ) {
3163 # Can't have an empty self-link
3164 return false;
3165 }
3166 $this->mInterwiki = '';
3167 $firstPass = false;
3168 # Do another namespace split...
3169 continue;
3170 }
3171
3172 # If there's an initial colon after the interwiki, that also
3173 # resets the default namespace
3174 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
3175 $this->mNamespace = NS_MAIN;
3176 $dbkey = substr( $dbkey, 1 );
3177 }
3178 }
3179 # If there's no recognized interwiki or namespace,
3180 # then let the colon expression be part of the title.
3181 }
3182 break;
3183 } while ( true );
3184
3185 # We already know that some pages won't be in the database!
3186 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
3187 $this->mArticleID = 0;
3188 }
3189 $fragment = strstr( $dbkey, '#' );
3190 if ( false !== $fragment ) {
3191 $this->setFragment( $fragment );
3192 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
3193 # remove whitespace again: prevents "Foo_bar_#"
3194 # becoming "Foo_bar_"
3195 $dbkey = preg_replace( '/_*$/', '', $dbkey );
3196 }
3197
3198 # Reject illegal characters.
3199 $rxTc = self::getTitleInvalidRegex();
3200 if ( preg_match( $rxTc, $dbkey ) ) {
3201 return false;
3202 }
3203
3204 # Pages with "/./" or "/../" appearing in the URLs will often be un-
3205 # reachable due to the way web browsers deal with 'relative' URLs.
3206 # Also, they conflict with subpage syntax. Forbid them explicitly.
3207 if (
3208 strpos( $dbkey, '.' ) !== false &&
3209 (
3210 $dbkey === '.' || $dbkey === '..' ||
3211 strpos( $dbkey, './' ) === 0 ||
3212 strpos( $dbkey, '../' ) === 0 ||
3213 strpos( $dbkey, '/./' ) !== false ||
3214 strpos( $dbkey, '/../' ) !== false ||
3215 substr( $dbkey, -2 ) == '/.' ||
3216 substr( $dbkey, -3 ) == '/..'
3217 )
3218 ) {
3219 return false;
3220 }
3221
3222 # Magic tilde sequences? Nu-uh!
3223 if ( strpos( $dbkey, '~~~' ) !== false ) {
3224 return false;
3225 }
3226
3227 # Limit the size of titles to 255 bytes. This is typically the size of the
3228 # underlying database field. We make an exception for special pages, which
3229 # don't need to be stored in the database, and may edge over 255 bytes due
3230 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
3231 if (
3232 ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 )
3233 || strlen( $dbkey ) > 512
3234 ) {
3235 return false;
3236 }
3237
3238 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
3239 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
3240 # other site might be case-sensitive.
3241 $this->mUserCaseDBKey = $dbkey;
3242 if ( $this->mInterwiki == '' ) {
3243 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
3244 }
3245
3246 # Can't make a link to a namespace alone... "empty" local links can only be
3247 # self-links with a fragment identifier.
3248 if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) {
3249 return false;
3250 }
3251
3252 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
3253 // IP names are not allowed for accounts, and can only be referring to
3254 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
3255 // there are numerous ways to present the same IP. Having sp:contribs scan
3256 // them all is silly and having some show the edits and others not is
3257 // inconsistent. Same for talk/userpages. Keep them normalized instead.
3258 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK )
3259 ? IP::sanitizeIP( $dbkey )
3260 : $dbkey;
3261
3262 // Any remaining initial :s are illegal.
3263 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
3264 return false;
3265 }
3266
3267 # Fill fields
3268 $this->mDbkeyform = $dbkey;
3269 $this->mUrlform = wfUrlencode( $dbkey );
3270
3271 $this->mTextform = str_replace( '_', ' ', $dbkey );
3272
3273 return true;
3274 }
3275
3276 /**
3277 * Get an array of Title objects linking to this Title
3278 * Also stores the IDs in the link cache.
3279 *
3280 * WARNING: do not use this function on arbitrary user-supplied titles!
3281 * On heavily-used templates it will max out the memory.
3282 *
3283 * @param $options Array: may be FOR UPDATE
3284 * @param $table String: table name
3285 * @param $prefix String: fields prefix
3286 * @return Array of Title objects linking here
3287 */
3288 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3289 if ( count( $options ) > 0 ) {
3290 $db = wfGetDB( DB_MASTER );
3291 } else {
3292 $db = wfGetDB( DB_SLAVE );
3293 }
3294
3295 $res = $db->select(
3296 array( 'page', $table ),
3297 self::getSelectFields(),
3298 array(
3299 "{$prefix}_from=page_id",
3300 "{$prefix}_namespace" => $this->getNamespace(),
3301 "{$prefix}_title" => $this->getDBkey() ),
3302 __METHOD__,
3303 $options
3304 );
3305
3306 $retVal = array();
3307 if ( $res->numRows() ) {
3308 $linkCache = LinkCache::singleton();
3309 foreach ( $res as $row ) {
3310 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
3311 if ( $titleObj ) {
3312 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3313 $retVal[] = $titleObj;
3314 }
3315 }
3316 }
3317 return $retVal;
3318 }
3319
3320 /**
3321 * Get an array of Title objects using this Title as a template
3322 * Also stores the IDs in the link cache.
3323 *
3324 * WARNING: do not use this function on arbitrary user-supplied titles!
3325 * On heavily-used templates it will max out the memory.
3326 *
3327 * @param $options Array: may be FOR UPDATE
3328 * @return Array of Title the Title objects linking here
3329 */
3330 public function getTemplateLinksTo( $options = array() ) {
3331 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3332 }
3333
3334 /**
3335 * Get an array of Title objects linked from this Title
3336 * Also stores the IDs in the link cache.
3337 *
3338 * WARNING: do not use this function on arbitrary user-supplied titles!
3339 * On heavily-used templates it will max out the memory.
3340 *
3341 * @param $options Array: may be FOR UPDATE
3342 * @param $table String: table name
3343 * @param $prefix String: fields prefix
3344 * @return Array of Title objects linking here
3345 */
3346 public function getLinksFrom( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
3347 global $wgContentHandlerUseDB;
3348
3349 $id = $this->getArticleID();
3350
3351 # If the page doesn't exist; there can't be any link from this page
3352 if ( !$id ) {
3353 return array();
3354 }
3355
3356 if ( count( $options ) > 0 ) {
3357 $db = wfGetDB( DB_MASTER );
3358 } else {
3359 $db = wfGetDB( DB_SLAVE );
3360 }
3361
3362 $namespaceFiled = "{$prefix}_namespace";
3363 $titleField = "{$prefix}_title";
3364
3365 $fields = array( $namespaceFiled, $titleField, 'page_id', 'page_len', 'page_is_redirect', 'page_latest' );
3366 if ( $wgContentHandlerUseDB ) $fields[] = 'page_content_model';
3367
3368 $res = $db->select(
3369 array( $table, 'page' ),
3370 $fields,
3371 array( "{$prefix}_from" => $id ),
3372 __METHOD__,
3373 $options,
3374 array( 'page' => array( 'LEFT JOIN', array( "page_namespace=$namespaceFiled", "page_title=$titleField" ) ) )
3375 );
3376
3377 $retVal = array();
3378 if ( $res->numRows() ) {
3379 $linkCache = LinkCache::singleton();
3380 foreach ( $res as $row ) {
3381 $titleObj = Title::makeTitle( $row->$namespaceFiled, $row->$titleField );
3382 if ( $titleObj ) {
3383 if ( $row->page_id ) {
3384 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
3385 } else {
3386 $linkCache->addBadLinkObj( $titleObj );
3387 }
3388 $retVal[] = $titleObj;
3389 }
3390 }
3391 }
3392 return $retVal;
3393 }
3394
3395 /**
3396 * Get an array of Title objects used on this Title as a template
3397 * Also stores the IDs in the link cache.
3398 *
3399 * WARNING: do not use this function on arbitrary user-supplied titles!
3400 * On heavily-used templates it will max out the memory.
3401 *
3402 * @param $options Array: may be FOR UPDATE
3403 * @return Array of Title the Title objects used here
3404 */
3405 public function getTemplateLinksFrom( $options = array() ) {
3406 return $this->getLinksFrom( $options, 'templatelinks', 'tl' );
3407 }
3408
3409 /**
3410 * Get an array of Title objects referring to non-existent articles linked from this page
3411 *
3412 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3413 * @return Array of Title the Title objects
3414 */
3415 public function getBrokenLinksFrom() {
3416 if ( $this->getArticleID() == 0 ) {
3417 # All links from article ID 0 are false positives
3418 return array();
3419 }
3420
3421 $dbr = wfGetDB( DB_SLAVE );
3422 $res = $dbr->select(
3423 array( 'page', 'pagelinks' ),
3424 array( 'pl_namespace', 'pl_title' ),
3425 array(
3426 'pl_from' => $this->getArticleID(),
3427 'page_namespace IS NULL'
3428 ),
3429 __METHOD__, array(),
3430 array(
3431 'page' => array(
3432 'LEFT JOIN',
3433 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3434 )
3435 )
3436 );
3437
3438 $retVal = array();
3439 foreach ( $res as $row ) {
3440 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3441 }
3442 return $retVal;
3443 }
3444
3445
3446 /**
3447 * Get a list of URLs to purge from the Squid cache when this
3448 * page changes
3449 *
3450 * @return Array of String the URLs
3451 */
3452 public function getSquidURLs() {
3453 $urls = array(
3454 $this->getInternalURL(),
3455 $this->getInternalURL( 'action=history' )
3456 );
3457
3458 $pageLang = $this->getPageLanguage();
3459 if ( $pageLang->hasVariants() ) {
3460 $variants = $pageLang->getVariants();
3461 foreach ( $variants as $vCode ) {
3462 $urls[] = $this->getInternalURL( '', $vCode );
3463 }
3464 }
3465
3466 return $urls;
3467 }
3468
3469 /**
3470 * Purge all applicable Squid URLs
3471 */
3472 public function purgeSquid() {
3473 global $wgUseSquid;
3474 if ( $wgUseSquid ) {
3475 $urls = $this->getSquidURLs();
3476 $u = new SquidUpdate( $urls );
3477 $u->doUpdate();
3478 }
3479 }
3480
3481 /**
3482 * Move this page without authentication
3483 *
3484 * @param $nt Title the new page Title
3485 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3486 */
3487 public function moveNoAuth( &$nt ) {
3488 return $this->moveTo( $nt, false );
3489 }
3490
3491 /**
3492 * Check whether a given move operation would be valid.
3493 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3494 *
3495 * @param $nt Title the new title
3496 * @param $auth Bool indicates whether $wgUser's permissions
3497 * should be checked
3498 * @param $reason String is the log summary of the move, used for spam checking
3499 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3500 */
3501 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3502 global $wgUser, $wgContentHandlerUseDB;
3503
3504 $errors = array();
3505 if ( !$nt ) {
3506 // Normally we'd add this to $errors, but we'll get
3507 // lots of syntax errors if $nt is not an object
3508 return array( array( 'badtitletext' ) );
3509 }
3510 if ( $this->equals( $nt ) ) {
3511 $errors[] = array( 'selfmove' );
3512 }
3513 if ( !$this->isMovable() ) {
3514 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3515 }
3516 if ( $nt->getInterwiki() != '' ) {
3517 $errors[] = array( 'immobile-target-namespace-iw' );
3518 }
3519 if ( !$nt->isMovable() ) {
3520 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3521 }
3522
3523 $oldid = $this->getArticleID();
3524 $newid = $nt->getArticleID();
3525
3526 if ( strlen( $nt->getDBkey() ) < 1 ) {
3527 $errors[] = array( 'articleexists' );
3528 }
3529 if (
3530 ( $this->getDBkey() == '' ) ||
3531 ( !$oldid ) ||
3532 ( $nt->getDBkey() == '' )
3533 ) {
3534 $errors[] = array( 'badarticleerror' );
3535 }
3536
3537 // Content model checks
3538 if ( !$wgContentHandlerUseDB &&
3539 $this->getContentModel() !== $nt->getContentModel() ) {
3540 // can't move a page if that would change the page's content model
3541 $errors[] = array(
3542 'bad-target-model',
3543 ContentHandler::getLocalizedName( $this->getContentModel() ),
3544 ContentHandler::getLocalizedName( $nt->getContentModel() )
3545 );
3546 }
3547
3548 // Image-specific checks
3549 if ( $this->getNamespace() == NS_FILE ) {
3550 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3551 }
3552
3553 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3554 $errors[] = array( 'nonfile-cannot-move-to-file' );
3555 }
3556
3557 if ( $auth ) {
3558 $errors = wfMergeErrorArrays( $errors,
3559 $this->getUserPermissionsErrors( 'move', $wgUser ),
3560 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3561 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3562 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3563 }
3564
3565 $match = EditPage::matchSummarySpamRegex( $reason );
3566 if ( $match !== false ) {
3567 // This is kind of lame, won't display nice
3568 $errors[] = array( 'spamprotectiontext' );
3569 }
3570
3571 $err = null;
3572 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3573 $errors[] = array( 'hookaborted', $err );
3574 }
3575
3576 # The move is allowed only if (1) the target doesn't exist, or
3577 # (2) the target is a redirect to the source, and has no history
3578 # (so we can undo bad moves right after they're done).
3579
3580 if ( 0 != $newid ) { # Target exists; check for validity
3581 if ( !$this->isValidMoveTarget( $nt ) ) {
3582 $errors[] = array( 'articleexists' );
3583 }
3584 } else {
3585 $tp = $nt->getTitleProtection();
3586 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3587 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3588 $errors[] = array( 'cantmove-titleprotected' );
3589 }
3590 }
3591 if ( empty( $errors ) ) {
3592 return true;
3593 }
3594 return $errors;
3595 }
3596
3597 /**
3598 * Check if the requested move target is a valid file move target
3599 * @param Title $nt Target title
3600 * @return array List of errors
3601 */
3602 protected function validateFileMoveOperation( $nt ) {
3603 global $wgUser;
3604
3605 $errors = array();
3606
3607 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3608
3609 $file = wfLocalFile( $this );
3610 if ( $file->exists() ) {
3611 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3612 $errors[] = array( 'imageinvalidfilename' );
3613 }
3614 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3615 $errors[] = array( 'imagetypemismatch' );
3616 }
3617 }
3618
3619 if ( $nt->getNamespace() != NS_FILE ) {
3620 $errors[] = array( 'imagenocrossnamespace' );
3621 // From here we want to do checks on a file object, so if we can't
3622 // create one, we must return.
3623 return $errors;
3624 }
3625
3626 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3627
3628 $destFile = wfLocalFile( $nt );
3629 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3630 $errors[] = array( 'file-exists-sharedrepo' );
3631 }
3632
3633 return $errors;
3634 }
3635
3636 /**
3637 * Move a title to a new location
3638 *
3639 * @param $nt Title the new title
3640 * @param $auth Bool indicates whether $wgUser's permissions
3641 * should be checked
3642 * @param $reason String the reason for the move
3643 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3644 * Ignored if the user doesn't have the suppressredirect right.
3645 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3646 */
3647 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3648 global $wgUser;
3649 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3650 if ( is_array( $err ) ) {
3651 // Auto-block user's IP if the account was "hard" blocked
3652 $wgUser->spreadAnyEditBlock();
3653 return $err;
3654 }
3655 // Check suppressredirect permission
3656 if ( $auth && !$wgUser->isAllowed( 'suppressredirect' ) ) {
3657 $createRedirect = true;
3658 }
3659
3660 // If it is a file, move it first.
3661 // It is done before all other moving stuff is done because it's hard to revert.
3662 $dbw = wfGetDB( DB_MASTER );
3663 if ( $this->getNamespace() == NS_FILE ) {
3664 $file = wfLocalFile( $this );
3665 if ( $file->exists() ) {
3666 $status = $file->move( $nt );
3667 if ( !$status->isOk() ) {
3668 return $status->getErrorsArray();
3669 }
3670 }
3671 // Clear RepoGroup process cache
3672 RepoGroup::singleton()->clearCache( $this );
3673 RepoGroup::singleton()->clearCache( $nt ); # clear false negative cache
3674 }
3675
3676 $dbw->begin( __METHOD__ ); # If $file was a LocalFile, its transaction would have closed our own.
3677 $pageid = $this->getArticleID( self::GAID_FOR_UPDATE );
3678 $protected = $this->isProtected();
3679
3680 // Do the actual move
3681 $this->moveToInternal( $nt, $reason, $createRedirect );
3682
3683 // Refresh the sortkey for this row. Be careful to avoid resetting
3684 // cl_timestamp, which may disturb time-based lists on some sites.
3685 $prefixes = $dbw->select(
3686 'categorylinks',
3687 array( 'cl_sortkey_prefix', 'cl_to' ),
3688 array( 'cl_from' => $pageid ),
3689 __METHOD__
3690 );
3691 foreach ( $prefixes as $prefixRow ) {
3692 $prefix = $prefixRow->cl_sortkey_prefix;
3693 $catTo = $prefixRow->cl_to;
3694 $dbw->update( 'categorylinks',
3695 array(
3696 'cl_sortkey' => Collation::singleton()->getSortKey(
3697 $nt->getCategorySortkey( $prefix ) ),
3698 'cl_timestamp=cl_timestamp' ),
3699 array(
3700 'cl_from' => $pageid,
3701 'cl_to' => $catTo ),
3702 __METHOD__
3703 );
3704 }
3705
3706 $redirid = $this->getArticleID();
3707
3708 if ( $protected ) {
3709 # Protect the redirect title as the title used to be...
3710 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3711 array(
3712 'pr_page' => $redirid,
3713 'pr_type' => 'pr_type',
3714 'pr_level' => 'pr_level',
3715 'pr_cascade' => 'pr_cascade',
3716 'pr_user' => 'pr_user',
3717 'pr_expiry' => 'pr_expiry'
3718 ),
3719 array( 'pr_page' => $pageid ),
3720 __METHOD__,
3721 array( 'IGNORE' )
3722 );
3723 # Update the protection log
3724 $log = new LogPage( 'protect' );
3725 $comment = wfMessage(
3726 'prot_1movedto2',
3727 $this->getPrefixedText(),
3728 $nt->getPrefixedText()
3729 )->inContentLanguage()->text();
3730 if ( $reason ) {
3731 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3732 }
3733 // @todo FIXME: $params?
3734 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3735 }
3736
3737 # Update watchlists
3738 $oldnamespace = MWNamespace::getSubject( $this->getNamespace() );
3739 $newnamespace = MWNamespace::getSubject( $nt->getNamespace() );
3740 $oldtitle = $this->getDBkey();
3741 $newtitle = $nt->getDBkey();
3742
3743 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3744 WatchedItem::duplicateEntries( $this, $nt );
3745 }
3746
3747 $dbw->commit( __METHOD__ );
3748
3749 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3750 return true;
3751 }
3752
3753 /**
3754 * Move page to a title which is either a redirect to the
3755 * source page or nonexistent
3756 *
3757 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3758 * @param $reason String The reason for the move
3759 * @param $createRedirect Bool Whether to leave a redirect at the old title. Does not check
3760 * if the user has the suppressredirect right
3761 * @throws MWException
3762 */
3763 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3764 global $wgUser, $wgContLang;
3765
3766 if ( $nt->exists() ) {
3767 $moveOverRedirect = true;
3768 $logType = 'move_redir';
3769 } else {
3770 $moveOverRedirect = false;
3771 $logType = 'move';
3772 }
3773
3774 if ( $createRedirect ) {
3775 $contentHandler = ContentHandler::getForTitle( $this );
3776 $redirectContent = $contentHandler->makeRedirectContent( $nt );
3777
3778 // NOTE: If this page's content model does not support redirects, $redirectContent will be null.
3779 } else {
3780 $redirectContent = null;
3781 }
3782
3783 $logEntry = new ManualLogEntry( 'move', $logType );
3784 $logEntry->setPerformer( $wgUser );
3785 $logEntry->setTarget( $this );
3786 $logEntry->setComment( $reason );
3787 $logEntry->setParameters( array(
3788 '4::target' => $nt->getPrefixedText(),
3789 '5::noredir' => $redirectContent ? '0': '1',
3790 ) );
3791
3792 $formatter = LogFormatter::newFromEntry( $logEntry );
3793 $formatter->setContext( RequestContext::newExtraneousContext( $this ) );
3794 $comment = $formatter->getPlainActionText();
3795 if ( $reason ) {
3796 $comment .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $reason;
3797 }
3798 # Truncate for whole multibyte characters.
3799 $comment = $wgContLang->truncate( $comment, 255 );
3800
3801 $oldid = $this->getArticleID();
3802
3803 $dbw = wfGetDB( DB_MASTER );
3804
3805 $newpage = WikiPage::factory( $nt );
3806
3807 if ( $moveOverRedirect ) {
3808 $newid = $nt->getArticleID();
3809
3810 # Delete the old redirect. We don't save it to history since
3811 # by definition if we've got here it's rather uninteresting.
3812 # We have to remove it so that the next step doesn't trigger
3813 # a conflict on the unique namespace+title index...
3814 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3815
3816 $newpage->doDeleteUpdates( $newid );
3817 }
3818
3819 # Save a null revision in the page's history notifying of the move
3820 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3821 if ( !is_object( $nullRevision ) ) {
3822 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3823 }
3824
3825 $nullRevision->insertOn( $dbw );
3826
3827 # Change the name of the target page:
3828 $dbw->update( 'page',
3829 /* SET */ array(
3830 'page_namespace' => $nt->getNamespace(),
3831 'page_title' => $nt->getDBkey(),
3832 ),
3833 /* WHERE */ array( 'page_id' => $oldid ),
3834 __METHOD__
3835 );
3836
3837 $this->resetArticleID( 0 );
3838 $nt->resetArticleID( $oldid );
3839
3840 $newpage->updateRevisionOn( $dbw, $nullRevision );
3841
3842 wfRunHooks( 'NewRevisionFromEditComplete',
3843 array( $newpage, $nullRevision, $nullRevision->getParentId(), $wgUser ) );
3844
3845 $newpage->doEditUpdates( $nullRevision, $wgUser, array( 'changed' => false ) );
3846
3847 if ( !$moveOverRedirect ) {
3848 WikiPage::onArticleCreate( $nt );
3849 }
3850
3851 # Recreate the redirect, this time in the other direction.
3852 if ( !$redirectContent ) {
3853 WikiPage::onArticleDelete( $this );
3854 } else {
3855 $redirectArticle = WikiPage::factory( $this );
3856 $newid = $redirectArticle->insertOn( $dbw );
3857 if ( $newid ) { // sanity
3858 $redirectRevision = new Revision( array(
3859 'title' => $this, // for determining the default content model
3860 'page' => $newid,
3861 'comment' => $comment,
3862 'content' => $redirectContent ) );
3863 $redirectRevision->insertOn( $dbw );
3864 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3865
3866 wfRunHooks( 'NewRevisionFromEditComplete',
3867 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3868
3869 $redirectArticle->doEditUpdates( $redirectRevision, $wgUser, array( 'created' => true ) );
3870 }
3871 }
3872
3873 # Log the move
3874 $logid = $logEntry->insert();
3875 $logEntry->publish( $logid );
3876 }
3877
3878 /**
3879 * Move this page's subpages to be subpages of $nt
3880 *
3881 * @param $nt Title Move target
3882 * @param $auth bool Whether $wgUser's permissions should be checked
3883 * @param $reason string The reason for the move
3884 * @param $createRedirect bool Whether to create redirects from the old subpages to
3885 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3886 * @return mixed array with old page titles as keys, and strings (new page titles) or
3887 * arrays (errors) as values, or an error array with numeric indices if no pages
3888 * were moved
3889 */
3890 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3891 global $wgMaximumMovedPages;
3892 // Check permissions
3893 if ( !$this->userCan( 'move-subpages' ) ) {
3894 return array( 'cant-move-subpages' );
3895 }
3896 // Do the source and target namespaces support subpages?
3897 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3898 return array( 'namespace-nosubpages',
3899 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3900 }
3901 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3902 return array( 'namespace-nosubpages',
3903 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3904 }
3905
3906 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3907 $retval = array();
3908 $count = 0;
3909 foreach ( $subpages as $oldSubpage ) {
3910 $count++;
3911 if ( $count > $wgMaximumMovedPages ) {
3912 $retval[$oldSubpage->getPrefixedTitle()] =
3913 array( 'movepage-max-pages',
3914 $wgMaximumMovedPages );
3915 break;
3916 }
3917
3918 // We don't know whether this function was called before
3919 // or after moving the root page, so check both
3920 // $this and $nt
3921 if ( $oldSubpage->getArticleID() == $this->getArticleID() ||
3922 $oldSubpage->getArticleID() == $nt->getArticleID() )
3923 {
3924 // When moving a page to a subpage of itself,
3925 // don't move it twice
3926 continue;
3927 }
3928 $newPageName = preg_replace(
3929 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3930 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3931 $oldSubpage->getDBkey() );
3932 if ( $oldSubpage->isTalkPage() ) {
3933 $newNs = $nt->getTalkPage()->getNamespace();
3934 } else {
3935 $newNs = $nt->getSubjectPage()->getNamespace();
3936 }
3937 # Bug 14385: we need makeTitleSafe because the new page names may
3938 # be longer than 255 characters.
3939 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3940
3941 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3942 if ( $success === true ) {
3943 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3944 } else {
3945 $retval[$oldSubpage->getPrefixedText()] = $success;
3946 }
3947 }
3948 return $retval;
3949 }
3950
3951 /**
3952 * Checks if this page is just a one-rev redirect.
3953 * Adds lock, so don't use just for light purposes.
3954 *
3955 * @return Bool
3956 */
3957 public function isSingleRevRedirect() {
3958 global $wgContentHandlerUseDB;
3959
3960 $dbw = wfGetDB( DB_MASTER );
3961
3962 # Is it a redirect?
3963 $fields = array( 'page_is_redirect', 'page_latest', 'page_id' );
3964 if ( $wgContentHandlerUseDB ) $fields[] = 'page_content_model';
3965
3966 $row = $dbw->selectRow( 'page',
3967 $fields,
3968 $this->pageCond(),
3969 __METHOD__,
3970 array( 'FOR UPDATE' )
3971 );
3972 # Cache some fields we may want
3973 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3974 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3975 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3976 $this->mContentModel = $row && isset( $row->page_content_model ) ? strval( $row->page_content_model ) : false;
3977 if ( !$this->mRedirect ) {
3978 return false;
3979 }
3980 # Does the article have a history?
3981 $row = $dbw->selectField( array( 'page', 'revision' ),
3982 'rev_id',
3983 array( 'page_namespace' => $this->getNamespace(),
3984 'page_title' => $this->getDBkey(),
3985 'page_id=rev_page',
3986 'page_latest != rev_id'
3987 ),
3988 __METHOD__,
3989 array( 'FOR UPDATE' )
3990 );
3991 # Return true if there was no history
3992 return ( $row === false );
3993 }
3994
3995 /**
3996 * Checks if $this can be moved to a given Title
3997 * - Selects for update, so don't call it unless you mean business
3998 *
3999 * @param $nt Title the new title to check
4000 * @return Bool
4001 */
4002 public function isValidMoveTarget( $nt ) {
4003 # Is it an existing file?
4004 if ( $nt->getNamespace() == NS_FILE ) {
4005 $file = wfLocalFile( $nt );
4006 if ( $file->exists() ) {
4007 wfDebug( __METHOD__ . ": file exists\n" );
4008 return false;
4009 }
4010 }
4011 # Is it a redirect with no history?
4012 if ( !$nt->isSingleRevRedirect() ) {
4013 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
4014 return false;
4015 }
4016 # Get the article text
4017 $rev = Revision::newFromTitle( $nt, false, Revision::READ_LATEST );
4018 if( !is_object( $rev ) ) {
4019 return false;
4020 }
4021 $content = $rev->getContent();
4022 # Does the redirect point to the source?
4023 # Or is it a broken self-redirect, usually caused by namespace collisions?
4024 $redirTitle = $content ? $content->getRedirectTarget() : null;
4025
4026 if ( $redirTitle ) {
4027 if ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
4028 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) {
4029 wfDebug( __METHOD__ . ": redirect points to other page\n" );
4030 return false;
4031 } else {
4032 return true;
4033 }
4034 } else {
4035 # Fail safe (not a redirect after all. strange.)
4036 wfDebug( __METHOD__ . ": failsafe: database sais " . $nt->getPrefixedDBkey() .
4037 " is a redirect, but it doesn't contain a valid redirect.\n" );
4038 return false;
4039 }
4040 }
4041
4042 /**
4043 * Get categories to which this Title belongs and return an array of
4044 * categories' names.
4045 *
4046 * @return Array of parents in the form:
4047 * $parent => $currentarticle
4048 */
4049 public function getParentCategories() {
4050 global $wgContLang;
4051
4052 $data = array();
4053
4054 $titleKey = $this->getArticleID();
4055
4056 if ( $titleKey === 0 ) {
4057 return $data;
4058 }
4059
4060 $dbr = wfGetDB( DB_SLAVE );
4061
4062 $res = $dbr->select(
4063 'categorylinks',
4064 'cl_to',
4065 array( 'cl_from' => $titleKey ),
4066 __METHOD__
4067 );
4068
4069 if ( $res->numRows() > 0 ) {
4070 foreach ( $res as $row ) {
4071 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
4072 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
4073 }
4074 }
4075 return $data;
4076 }
4077
4078 /**
4079 * Get a tree of parent categories
4080 *
4081 * @param $children Array with the children in the keys, to check for circular refs
4082 * @return Array Tree of parent categories
4083 */
4084 public function getParentCategoryTree( $children = array() ) {
4085 $stack = array();
4086 $parents = $this->getParentCategories();
4087
4088 if ( $parents ) {
4089 foreach ( $parents as $parent => $current ) {
4090 if ( array_key_exists( $parent, $children ) ) {
4091 # Circular reference
4092 $stack[$parent] = array();
4093 } else {
4094 $nt = Title::newFromText( $parent );
4095 if ( $nt ) {
4096 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
4097 }
4098 }
4099 }
4100 }
4101
4102 return $stack;
4103 }
4104
4105 /**
4106 * Get an associative array for selecting this title from
4107 * the "page" table
4108 *
4109 * @return Array suitable for the $where parameter of DB::select()
4110 */
4111 public function pageCond() {
4112 if ( $this->mArticleID > 0 ) {
4113 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
4114 return array( 'page_id' => $this->mArticleID );
4115 } else {
4116 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
4117 }
4118 }
4119
4120 /**
4121 * Get the revision ID of the previous revision
4122 *
4123 * @param $revId Int Revision ID. Get the revision that was before this one.
4124 * @param $flags Int Title::GAID_FOR_UPDATE
4125 * @return Int|Bool Old revision ID, or FALSE if none exists
4126 */
4127 public function getPreviousRevisionID( $revId, $flags = 0 ) {
4128 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4129 $revId = $db->selectField( 'revision', 'rev_id',
4130 array(
4131 'rev_page' => $this->getArticleID( $flags ),
4132 'rev_id < ' . intval( $revId )
4133 ),
4134 __METHOD__,
4135 array( 'ORDER BY' => 'rev_id DESC' )
4136 );
4137
4138 if ( $revId === false ) {
4139 return false;
4140 } else {
4141 return intval( $revId );
4142 }
4143 }
4144
4145 /**
4146 * Get the revision ID of the next revision
4147 *
4148 * @param $revId Int Revision ID. Get the revision that was after this one.
4149 * @param $flags Int Title::GAID_FOR_UPDATE
4150 * @return Int|Bool Next revision ID, or FALSE if none exists
4151 */
4152 public function getNextRevisionID( $revId, $flags = 0 ) {
4153 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4154 $revId = $db->selectField( 'revision', 'rev_id',
4155 array(
4156 'rev_page' => $this->getArticleID( $flags ),
4157 'rev_id > ' . intval( $revId )
4158 ),
4159 __METHOD__,
4160 array( 'ORDER BY' => 'rev_id' )
4161 );
4162
4163 if ( $revId === false ) {
4164 return false;
4165 } else {
4166 return intval( $revId );
4167 }
4168 }
4169
4170 /**
4171 * Get the first revision of the page
4172 *
4173 * @param $flags Int Title::GAID_FOR_UPDATE
4174 * @return Revision|Null if page doesn't exist
4175 */
4176 public function getFirstRevision( $flags = 0 ) {
4177 $pageId = $this->getArticleID( $flags );
4178 if ( $pageId ) {
4179 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
4180 $row = $db->selectRow( 'revision', Revision::selectFields(),
4181 array( 'rev_page' => $pageId ),
4182 __METHOD__,
4183 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
4184 );
4185 if ( $row ) {
4186 return new Revision( $row );
4187 }
4188 }
4189 return null;
4190 }
4191
4192 /**
4193 * Get the oldest revision timestamp of this page
4194 *
4195 * @param $flags Int Title::GAID_FOR_UPDATE
4196 * @return String: MW timestamp
4197 */
4198 public function getEarliestRevTime( $flags = 0 ) {
4199 $rev = $this->getFirstRevision( $flags );
4200 return $rev ? $rev->getTimestamp() : null;
4201 }
4202
4203 /**
4204 * Check if this is a new page
4205 *
4206 * @return bool
4207 */
4208 public function isNewPage() {
4209 $dbr = wfGetDB( DB_SLAVE );
4210 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
4211 }
4212
4213 /**
4214 * Check whether the number of revisions of this page surpasses $wgDeleteRevisionsLimit
4215 *
4216 * @return bool
4217 */
4218 public function isBigDeletion() {
4219 global $wgDeleteRevisionsLimit;
4220
4221 if ( !$wgDeleteRevisionsLimit ) {
4222 return false;
4223 }
4224
4225 $revCount = $this->estimateRevisionCount();
4226 return $revCount > $wgDeleteRevisionsLimit;
4227 }
4228
4229 /**
4230 * Get the approximate revision count of this page.
4231 *
4232 * @return int
4233 */
4234 public function estimateRevisionCount() {
4235 if ( !$this->exists() ) {
4236 return 0;
4237 }
4238
4239 if ( $this->mEstimateRevisions === null ) {
4240 $dbr = wfGetDB( DB_SLAVE );
4241 $this->mEstimateRevisions = $dbr->estimateRowCount( 'revision', '*',
4242 array( 'rev_page' => $this->getArticleID() ), __METHOD__ );
4243 }
4244
4245 return $this->mEstimateRevisions;
4246 }
4247
4248 /**
4249 * Get the number of revisions between the given revision.
4250 * Used for diffs and other things that really need it.
4251 *
4252 * @param $old int|Revision Old revision or rev ID (first before range)
4253 * @param $new int|Revision New revision or rev ID (first after range)
4254 * @return Int Number of revisions between these revisions.
4255 */
4256 public function countRevisionsBetween( $old, $new ) {
4257 if ( !( $old instanceof Revision ) ) {
4258 $old = Revision::newFromTitle( $this, (int)$old );
4259 }
4260 if ( !( $new instanceof Revision ) ) {
4261 $new = Revision::newFromTitle( $this, (int)$new );
4262 }
4263 if ( !$old || !$new ) {
4264 return 0; // nothing to compare
4265 }
4266 $dbr = wfGetDB( DB_SLAVE );
4267 return (int)$dbr->selectField( 'revision', 'count(*)',
4268 array(
4269 'rev_page' => $this->getArticleID(),
4270 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4271 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4272 ),
4273 __METHOD__
4274 );
4275 }
4276
4277 /**
4278 * Get the number of authors between the given revisions or revision IDs.
4279 * Used for diffs and other things that really need it.
4280 *
4281 * @param $old int|Revision Old revision or rev ID (first before range by default)
4282 * @param $new int|Revision New revision or rev ID (first after range by default)
4283 * @param $limit int Maximum number of authors
4284 * @param $options string|array (Optional): Single option, or an array of options:
4285 * 'include_old' Include $old in the range; $new is excluded.
4286 * 'include_new' Include $new in the range; $old is excluded.
4287 * 'include_both' Include both $old and $new in the range.
4288 * Unknown option values are ignored.
4289 * @return int Number of revision authors in the range; zero if not both revisions exist
4290 */
4291 public function countAuthorsBetween( $old, $new, $limit, $options = array() ) {
4292 if ( !( $old instanceof Revision ) ) {
4293 $old = Revision::newFromTitle( $this, (int)$old );
4294 }
4295 if ( !( $new instanceof Revision ) ) {
4296 $new = Revision::newFromTitle( $this, (int)$new );
4297 }
4298 // XXX: what if Revision objects are passed in, but they don't refer to this title?
4299 // Add $old->getPage() != $new->getPage() || $old->getPage() != $this->getArticleID()
4300 // in the sanity check below?
4301 if ( !$old || !$new ) {
4302 return 0; // nothing to compare
4303 }
4304 $old_cmp = '>';
4305 $new_cmp = '<';
4306 $options = (array)$options;
4307 if ( in_array( 'include_old', $options ) ) {
4308 $old_cmp = '>=';
4309 }
4310 if ( in_array( 'include_new', $options ) ) {
4311 $new_cmp = '<=';
4312 }
4313 if ( in_array( 'include_both', $options ) ) {
4314 $old_cmp = '>=';
4315 $new_cmp = '<=';
4316 }
4317 // No DB query needed if $old and $new are the same or successive revisions:
4318 if ( $old->getId() === $new->getId() ) {
4319 return ( $old_cmp === '>' && $new_cmp === '<' ) ? 0 : 1;
4320 } else if ( $old->getId() === $new->getParentId() ) {
4321 if ( $old_cmp === '>' || $new_cmp === '<' ) {
4322 return ( $old_cmp === '>' && $new_cmp === '<' ) ? 0 : 1;
4323 }
4324 return ( $old->getRawUserText() === $new->getRawUserText() ) ? 1 : 2;
4325 }
4326 $dbr = wfGetDB( DB_SLAVE );
4327 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
4328 array(
4329 'rev_page' => $this->getArticleID(),
4330 "rev_timestamp $old_cmp " . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
4331 "rev_timestamp $new_cmp " . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
4332 ), __METHOD__,
4333 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
4334 );
4335 return (int)$dbr->numRows( $res );
4336 }
4337
4338 /**
4339 * Compare with another title.
4340 *
4341 * @param $title Title
4342 * @return Bool
4343 */
4344 public function equals( Title $title ) {
4345 // Note: === is necessary for proper matching of number-like titles.
4346 return $this->getInterwiki() === $title->getInterwiki()
4347 && $this->getNamespace() == $title->getNamespace()
4348 && $this->getDBkey() === $title->getDBkey();
4349 }
4350
4351 /**
4352 * Check if this title is a subpage of another title
4353 *
4354 * @param $title Title
4355 * @return Bool
4356 */
4357 public function isSubpageOf( Title $title ) {
4358 return $this->getInterwiki() === $title->getInterwiki()
4359 && $this->getNamespace() == $title->getNamespace()
4360 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
4361 }
4362
4363 /**
4364 * Check if page exists. For historical reasons, this function simply
4365 * checks for the existence of the title in the page table, and will
4366 * thus return false for interwiki links, special pages and the like.
4367 * If you want to know if a title can be meaningfully viewed, you should
4368 * probably call the isKnown() method instead.
4369 *
4370 * @return Bool
4371 */
4372 public function exists() {
4373 return $this->getArticleID() != 0;
4374 }
4375
4376 /**
4377 * Should links to this title be shown as potentially viewable (i.e. as
4378 * "bluelinks"), even if there's no record by this title in the page
4379 * table?
4380 *
4381 * This function is semi-deprecated for public use, as well as somewhat
4382 * misleadingly named. You probably just want to call isKnown(), which
4383 * calls this function internally.
4384 *
4385 * (ISSUE: Most of these checks are cheap, but the file existence check
4386 * can potentially be quite expensive. Including it here fixes a lot of
4387 * existing code, but we might want to add an optional parameter to skip
4388 * it and any other expensive checks.)
4389 *
4390 * @return Bool
4391 */
4392 public function isAlwaysKnown() {
4393 $isKnown = null;
4394
4395 /**
4396 * Allows overriding default behaviour for determining if a page exists.
4397 * If $isKnown is kept as null, regular checks happen. If it's
4398 * a boolean, this value is returned by the isKnown method.
4399 *
4400 * @since 1.20
4401 *
4402 * @param Title $title
4403 * @param boolean|null $isKnown
4404 */
4405 wfRunHooks( 'TitleIsAlwaysKnown', array( $this, &$isKnown ) );
4406
4407 if ( !is_null( $isKnown ) ) {
4408 return $isKnown;
4409 }
4410
4411 if ( $this->mInterwiki != '' ) {
4412 return true; // any interwiki link might be viewable, for all we know
4413 }
4414
4415 switch( $this->mNamespace ) {
4416 case NS_MEDIA:
4417 case NS_FILE:
4418 // file exists, possibly in a foreign repo
4419 return (bool)wfFindFile( $this );
4420 case NS_SPECIAL:
4421 // valid special page
4422 return SpecialPageFactory::exists( $this->getDBkey() );
4423 case NS_MAIN:
4424 // selflink, possibly with fragment
4425 return $this->mDbkeyform == '';
4426 case NS_MEDIAWIKI:
4427 // known system message
4428 return $this->hasSourceText() !== false;
4429 default:
4430 return false;
4431 }
4432 }
4433
4434 /**
4435 * Does this title refer to a page that can (or might) be meaningfully
4436 * viewed? In particular, this function may be used to determine if
4437 * links to the title should be rendered as "bluelinks" (as opposed to
4438 * "redlinks" to non-existent pages).
4439 * Adding something else to this function will cause inconsistency
4440 * since LinkHolderArray calls isAlwaysKnown() and does its own
4441 * page existence check.
4442 *
4443 * @return Bool
4444 */
4445 public function isKnown() {
4446 return $this->isAlwaysKnown() || $this->exists();
4447 }
4448
4449 /**
4450 * Does this page have source text?
4451 *
4452 * @return Boolean
4453 */
4454 public function hasSourceText() {
4455 if ( $this->exists() ) {
4456 return true;
4457 }
4458
4459 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4460 // If the page doesn't exist but is a known system message, default
4461 // message content will be displayed, same for language subpages-
4462 // Use always content language to avoid loading hundreds of languages
4463 // to get the link color.
4464 global $wgContLang;
4465 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4466 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4467 return $message->exists();
4468 }
4469
4470 return false;
4471 }
4472
4473 /**
4474 * Get the default message text or false if the message doesn't exist
4475 *
4476 * @return String or false
4477 */
4478 public function getDefaultMessageText() {
4479 global $wgContLang;
4480
4481 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4482 return false;
4483 }
4484
4485 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4486 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4487
4488 if ( $message->exists() ) {
4489 return $message->plain();
4490 } else {
4491 return false;
4492 }
4493 }
4494
4495 /**
4496 * Updates page_touched for this page; called from LinksUpdate.php
4497 *
4498 * @return Bool true if the update succeded
4499 */
4500 public function invalidateCache() {
4501 global $wgMemc;
4502 if ( wfReadOnly() ) {
4503 return false;
4504 }
4505 $dbw = wfGetDB( DB_MASTER );
4506 $success = $dbw->update(
4507 'page',
4508 array( 'page_touched' => $dbw->timestamp() ),
4509 $this->pageCond(),
4510 __METHOD__
4511 );
4512 HTMLFileCache::clearFileCache( $this );
4513
4514 // Clear page info.
4515 $revision = WikiPage::factory( $this )->getRevision();
4516 if( $revision !== null ) {
4517 $memcKey = wfMemcKey( 'infoaction', $this->getPrefixedText(), $revision->getId() );
4518 $success = $success && $wgMemc->delete( $memcKey );
4519 }
4520
4521 return $success;
4522 }
4523
4524 /**
4525 * Update page_touched timestamps and send squid purge messages for
4526 * pages linking to this title. May be sent to the job queue depending
4527 * on the number of links. Typically called on create and delete.
4528 */
4529 public function touchLinks() {
4530 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4531 $u->doUpdate();
4532
4533 if ( $this->getNamespace() == NS_CATEGORY ) {
4534 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4535 $u->doUpdate();
4536 }
4537 }
4538
4539 /**
4540 * Get the last touched timestamp
4541 *
4542 * @param $db DatabaseBase: optional db
4543 * @return String last-touched timestamp
4544 */
4545 public function getTouched( $db = null ) {
4546 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
4547 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4548 return $touched;
4549 }
4550
4551 /**
4552 * Get the timestamp when this page was updated since the user last saw it.
4553 *
4554 * @param $user User
4555 * @return String|Null
4556 */
4557 public function getNotificationTimestamp( $user = null ) {
4558 global $wgUser, $wgShowUpdatedMarker;
4559 // Assume current user if none given
4560 if ( !$user ) {
4561 $user = $wgUser;
4562 }
4563 // Check cache first
4564 $uid = $user->getId();
4565 // avoid isset here, as it'll return false for null entries
4566 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4567 return $this->mNotificationTimestamp[$uid];
4568 }
4569 if ( !$uid || !$wgShowUpdatedMarker ) {
4570 return $this->mNotificationTimestamp[$uid] = false;
4571 }
4572 // Don't cache too much!
4573 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4574 $this->mNotificationTimestamp = array();
4575 }
4576 $dbr = wfGetDB( DB_SLAVE );
4577 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
4578 'wl_notificationtimestamp',
4579 array(
4580 'wl_user' => $user->getId(),
4581 'wl_namespace' => $this->getNamespace(),
4582 'wl_title' => $this->getDBkey(),
4583 ),
4584 __METHOD__
4585 );
4586 return $this->mNotificationTimestamp[$uid];
4587 }
4588
4589 /**
4590 * Generate strings used for xml 'id' names in monobook tabs
4591 *
4592 * @param $prepend string defaults to 'nstab-'
4593 * @return String XML 'id' name
4594 */
4595 public function getNamespaceKey( $prepend = 'nstab-' ) {
4596 global $wgContLang;
4597 // Gets the subject namespace if this title
4598 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4599 // Checks if cononical namespace name exists for namespace
4600 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4601 // Uses canonical namespace name
4602 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4603 } else {
4604 // Uses text of namespace
4605 $namespaceKey = $this->getSubjectNsText();
4606 }
4607 // Makes namespace key lowercase
4608 $namespaceKey = $wgContLang->lc( $namespaceKey );
4609 // Uses main
4610 if ( $namespaceKey == '' ) {
4611 $namespaceKey = 'main';
4612 }
4613 // Changes file to image for backwards compatibility
4614 if ( $namespaceKey == 'file' ) {
4615 $namespaceKey = 'image';
4616 }
4617 return $prepend . $namespaceKey;
4618 }
4619
4620 /**
4621 * Get all extant redirects to this Title
4622 *
4623 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4624 * @return Array of Title redirects to this title
4625 */
4626 public function getRedirectsHere( $ns = null ) {
4627 $redirs = array();
4628
4629 $dbr = wfGetDB( DB_SLAVE );
4630 $where = array(
4631 'rd_namespace' => $this->getNamespace(),
4632 'rd_title' => $this->getDBkey(),
4633 'rd_from = page_id'
4634 );
4635 if ( $this->isExternal() ) {
4636 $where['rd_interwiki'] = $this->getInterwiki();
4637 } else {
4638 $where[] = 'rd_interwiki = ' . $dbr->addQuotes( '' ) . ' OR rd_interwiki IS NULL';
4639 }
4640 if ( !is_null( $ns ) ) {
4641 $where['page_namespace'] = $ns;
4642 }
4643
4644 $res = $dbr->select(
4645 array( 'redirect', 'page' ),
4646 array( 'page_namespace', 'page_title' ),
4647 $where,
4648 __METHOD__
4649 );
4650
4651 foreach ( $res as $row ) {
4652 $redirs[] = self::newFromRow( $row );
4653 }
4654 return $redirs;
4655 }
4656
4657 /**
4658 * Check if this Title is a valid redirect target
4659 *
4660 * @return Bool
4661 */
4662 public function isValidRedirectTarget() {
4663 global $wgInvalidRedirectTargets;
4664
4665 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4666 if ( $this->isSpecial( 'Userlogout' ) ) {
4667 return false;
4668 }
4669
4670 foreach ( $wgInvalidRedirectTargets as $target ) {
4671 if ( $this->isSpecial( $target ) ) {
4672 return false;
4673 }
4674 }
4675
4676 return true;
4677 }
4678
4679 /**
4680 * Get a backlink cache object
4681 *
4682 * @return BacklinkCache
4683 */
4684 public function getBacklinkCache() {
4685 return BacklinkCache::get( $this );
4686 }
4687
4688 /**
4689 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4690 *
4691 * @return Boolean
4692 */
4693 public function canUseNoindex() {
4694 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4695
4696 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4697 ? $wgContentNamespaces
4698 : $wgExemptFromUserRobotsControl;
4699
4700 return !in_array( $this->mNamespace, $bannedNamespaces );
4701
4702 }
4703
4704 /**
4705 * Returns the raw sort key to be used for categories, with the specified
4706 * prefix. This will be fed to Collation::getSortKey() to get a
4707 * binary sortkey that can be used for actual sorting.
4708 *
4709 * @param $prefix string The prefix to be used, specified using
4710 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4711 * prefix.
4712 * @return string
4713 */
4714 public function getCategorySortkey( $prefix = '' ) {
4715 $unprefixed = $this->getText();
4716
4717 // Anything that uses this hook should only depend
4718 // on the Title object passed in, and should probably
4719 // tell the users to run updateCollations.php --force
4720 // in order to re-sort existing category relations.
4721 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4722 if ( $prefix !== '' ) {
4723 # Separate with a line feed, so the unprefixed part is only used as
4724 # a tiebreaker when two pages have the exact same prefix.
4725 # In UCA, tab is the only character that can sort above LF
4726 # so we strip both of them from the original prefix.
4727 $prefix = strtr( $prefix, "\n\t", ' ' );
4728 return "$prefix\n$unprefixed";
4729 }
4730 return $unprefixed;
4731 }
4732
4733 /**
4734 * Get the language in which the content of this page is written in
4735 * wikitext. Defaults to $wgContLang, but in certain cases it can be
4736 * e.g. $wgLang (such as special pages, which are in the user language).
4737 *
4738 * @since 1.18
4739 * @return Language
4740 */
4741 public function getPageLanguage() {
4742 global $wgLang;
4743 if ( $this->isSpecialPage() ) {
4744 // special pages are in the user language
4745 return $wgLang;
4746 }
4747
4748 //TODO: use the LinkCache to cache this! Note that this may depend on user settings, so the cache should be only per-request.
4749 //NOTE: ContentHandler::getPageLanguage() may need to load the content to determine the page language!
4750 $contentHandler = ContentHandler::getForTitle( $this );
4751 $pageLang = $contentHandler->getPageLanguage( $this );
4752
4753 return wfGetLangObj( $pageLang );
4754 }
4755
4756 /**
4757 * Get the language in which the content of this page is written when
4758 * viewed by user. Defaults to $wgContLang, but in certain cases it can be
4759 * e.g. $wgLang (such as special pages, which are in the user language).
4760 *
4761 * @since 1.20
4762 * @return Language
4763 */
4764 public function getPageViewLanguage() {
4765 global $wgLang;
4766
4767 if ( $this->isSpecialPage() ) {
4768 // If the user chooses a variant, the content is actually
4769 // in a language whose code is the variant code.
4770 $variant = $wgLang->getPreferredVariant();
4771 if ( $wgLang->getCode() !== $variant ) {
4772 return Language::factory( $variant );
4773 }
4774
4775 return $wgLang;
4776 }
4777
4778 //NOTE: can't be cached persistently, depends on user settings
4779 //NOTE: ContentHandler::getPageViewLanguage() may need to load the content to determine the page language!
4780 $contentHandler = ContentHandler::getForTitle( $this );
4781 $pageLang = $contentHandler->getPageViewLanguage( $this );
4782 return $pageLang;
4783 }
4784
4785 /**
4786 * Get a list of rendered edit notices for this page.
4787 *
4788 * Array is keyed by the original message key, and values are rendered using parseAsBlock, so
4789 * they will already be wrapped in paragraphs.
4790 *
4791 * @since 1.21
4792 * @return Array
4793 */
4794 public function getEditNotices() {
4795 $notices = array();
4796
4797 # Optional notices on a per-namespace and per-page basis
4798 $editnotice_ns = 'editnotice-' . $this->getNamespace();
4799 $editnotice_ns_message = wfMessage( $editnotice_ns );
4800 if ( $editnotice_ns_message->exists() ) {
4801 $notices[$editnotice_ns] = $editnotice_ns_message->parseAsBlock();
4802 }
4803 if ( MWNamespace::hasSubpages( $this->getNamespace() ) ) {
4804 $parts = explode( '/', $this->getDBkey() );
4805 $editnotice_base = $editnotice_ns;
4806 while ( count( $parts ) > 0 ) {
4807 $editnotice_base .= '-' . array_shift( $parts );
4808 $editnotice_base_msg = wfMessage( $editnotice_base );
4809 if ( $editnotice_base_msg->exists() ) {
4810 $notices[$editnotice_base] = $editnotice_base_msg->parseAsBlock();
4811 }
4812 }
4813 } else {
4814 # Even if there are no subpages in namespace, we still don't want / in MW ns.
4815 $editnoticeText = $editnotice_ns . '-' . str_replace( '/', '-', $this->getDBkey() );
4816 $editnoticeMsg = wfMessage( $editnoticeText );
4817 if ( $editnoticeMsg->exists() ) {
4818 $notices[$editnoticeText] = $editnoticeMsg->parseAsBlock();
4819 }
4820 }
4821 return $notices;
4822 }
4823 }