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