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