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