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