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