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