Use protocol-relative URL for link to MediaWiki.org (as with the footer logo on each...
[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' ) || $this->isSpecial( 'ChangePassword' ) ) {
1673 return $errors;
1674 }
1675
1676 # Time to check the whitelist
1677 global $wgWhitelistRead;
1678
1679 # Only to these checks is there's something to check against
1680 if ( is_array( $wgWhitelistRead ) && count( $wgWhitelistRead ) ) {
1681 # Check for explicit whitelisting
1682 $name = $this->getPrefixedText();
1683 $dbName = $this->getPrefixedDBKey();
1684
1685 // Check with and without underscores
1686 if ( in_array( $name, $wgWhitelistRead, true ) || in_array( $dbName, $wgWhitelistRead, true ) ) {
1687 return $errors;
1688 }
1689
1690 # Old settings might have the title prefixed with
1691 # a colon for main-namespace pages
1692 if ( $this->getNamespace() == NS_MAIN ) {
1693 if ( in_array( ':' . $name, $wgWhitelistRead ) ) {
1694 return $errors;
1695 }
1696 }
1697
1698 # If it's a special page, ditch the subpage bit and check again
1699 if ( $this->isSpecialPage() ) {
1700 $name = $this->getDBkey();
1701 list( $name, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $name );
1702 if ( $name !== false ) {
1703 $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
1704 if ( in_array( $pure, $wgWhitelistRead, true ) ) {
1705 return $errors;
1706 }
1707 }
1708 }
1709 }
1710
1711 $errors[] = $this->missingPermissionError( $action, $short );
1712 return $errors;
1713 }
1714
1715 /**
1716 * Get a description array when the user doesn't have the right to perform
1717 * $action (i.e. when User::isAllowed() returns false)
1718 *
1719 * @param $action String the action to check
1720 * @param $short Boolean short circuit on first error
1721 * @return Array list of errors
1722 */
1723 private function missingPermissionError( $action, $short ) {
1724 // We avoid expensive display logic for quickUserCan's and such
1725 if ( $short ) {
1726 return array( 'badaccess-group0' );
1727 }
1728
1729 $groups = array_map( array( 'User', 'makeGroupLinkWiki' ),
1730 User::getGroupsWithPermission( $action, $this->mNamespace ) );
1731
1732 if ( count( $groups ) ) {
1733 global $wgLang;
1734 return array(
1735 'badaccess-groups',
1736 $wgLang->commaList( $groups ),
1737 count( $groups )
1738 );
1739 } else {
1740 return array( 'badaccess-group0' );
1741 }
1742 }
1743
1744 /**
1745 * Can $user perform $action on this page? This is an internal function,
1746 * which checks ONLY that previously checked by userCan (i.e. it leaves out
1747 * checks on wfReadOnly() and blocks)
1748 *
1749 * @param $action String action that permission needs to be checked for
1750 * @param $user User to check
1751 * @param $doExpensiveQueries Bool Set this to false to avoid doing unnecessary queries.
1752 * @param $short Bool Set this to true to stop after the first permission error.
1753 * @return Array of arrays of the arguments to wfMsg to explain permissions problems.
1754 */
1755 protected function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true, $short = false ) {
1756 wfProfileIn( __METHOD__ );
1757
1758 # Read has special handling
1759 if ( $action == 'read' ) {
1760 $checks = array(
1761 'checkPermissionHooks',
1762 'checkReadPermissions',
1763 );
1764 } else {
1765 $checks = array(
1766 'checkQuickPermissions',
1767 'checkPermissionHooks',
1768 'checkSpecialsAndNSPermissions',
1769 'checkCSSandJSPermissions',
1770 'checkPageRestrictions',
1771 'checkCascadingSourcesRestrictions',
1772 'checkActionPermissions',
1773 'checkUserBlock'
1774 );
1775 }
1776
1777 $errors = array();
1778 while( count( $checks ) > 0 &&
1779 !( $short && count( $errors ) > 0 ) ) {
1780 $method = array_shift( $checks );
1781 $errors = $this->$method( $action, $user, $errors, $doExpensiveQueries, $short );
1782 }
1783
1784 wfProfileOut( __METHOD__ );
1785 return $errors;
1786 }
1787
1788 /**
1789 * Is this title subject to title protection?
1790 * Title protection is the one applied against creation of such title.
1791 *
1792 * @return Mixed An associative array representing any existent title
1793 * protection, or false if there's none.
1794 */
1795 private function getTitleProtection() {
1796 // Can't protect pages in special namespaces
1797 if ( $this->getNamespace() < 0 ) {
1798 return false;
1799 }
1800
1801 // Can't protect pages that exist.
1802 if ( $this->exists() ) {
1803 return false;
1804 }
1805
1806 if ( !isset( $this->mTitleProtection ) ) {
1807 $dbr = wfGetDB( DB_SLAVE );
1808 $res = $dbr->select( 'protected_titles', '*',
1809 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1810 __METHOD__ );
1811
1812 // fetchRow returns false if there are no rows.
1813 $this->mTitleProtection = $dbr->fetchRow( $res );
1814 }
1815 return $this->mTitleProtection;
1816 }
1817
1818 /**
1819 * Update the title protection status
1820 *
1821 * @param $create_perm String Permission required for creation
1822 * @param $reason String Reason for protection
1823 * @param $expiry String Expiry timestamp
1824 * @return boolean true
1825 */
1826 public function updateTitleProtection( $create_perm, $reason, $expiry ) {
1827 global $wgUser, $wgContLang;
1828
1829 if ( $create_perm == implode( ',', $this->getRestrictions( 'create' ) )
1830 && $expiry == $this->mRestrictionsExpiry['create'] ) {
1831 // No change
1832 return true;
1833 }
1834
1835 list ( $namespace, $title ) = array( $this->getNamespace(), $this->getDBkey() );
1836
1837 $dbw = wfGetDB( DB_MASTER );
1838
1839 $encodedExpiry = $dbw->encodeExpiry( $expiry );
1840
1841 $expiry_description = '';
1842 if ( $encodedExpiry != $dbw->getInfinity() ) {
1843 $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ),
1844 $wgContLang->date( $expiry ) , $wgContLang->time( $expiry ) ) . ')';
1845 } else {
1846 $expiry_description .= ' (' . wfMsgForContent( 'protect-expiry-indefinite' ) . ')';
1847 }
1848
1849 # Update protection table
1850 if ( $create_perm != '' ) {
1851 $this->mTitleProtection = array(
1852 'pt_namespace' => $namespace,
1853 'pt_title' => $title,
1854 'pt_create_perm' => $create_perm,
1855 'pt_timestamp' => $dbw->encodeExpiry( wfTimestampNow() ),
1856 'pt_expiry' => $encodedExpiry,
1857 'pt_user' => $wgUser->getId(),
1858 'pt_reason' => $reason,
1859 );
1860 $dbw->replace( 'protected_titles', array( array( 'pt_namespace', 'pt_title' ) ),
1861 $this->mTitleProtection, __METHOD__ );
1862 } else {
1863 $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
1864 'pt_title' => $title ), __METHOD__ );
1865 $this->mTitleProtection = false;
1866 }
1867
1868 # Update the protection log
1869 if ( $dbw->affectedRows() ) {
1870 $log = new LogPage( 'protect' );
1871
1872 if ( $create_perm ) {
1873 $params = array( "[create=$create_perm] $expiry_description", '' );
1874 $log->addEntry( ( isset( $this->mRestrictions['create'] ) && $this->mRestrictions['create'] ) ? 'modify' : 'protect', $this, trim( $reason ), $params );
1875 } else {
1876 $log->addEntry( 'unprotect', $this, $reason );
1877 }
1878 }
1879
1880 return true;
1881 }
1882
1883 /**
1884 * Remove any title protection due to page existing
1885 */
1886 public function deleteTitleProtection() {
1887 $dbw = wfGetDB( DB_MASTER );
1888
1889 $dbw->delete(
1890 'protected_titles',
1891 array( 'pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey() ),
1892 __METHOD__
1893 );
1894 $this->mTitleProtection = false;
1895 }
1896
1897 /**
1898 * Would anybody with sufficient privileges be able to move this page?
1899 * Some pages just aren't movable.
1900 *
1901 * @return Bool TRUE or FALSE
1902 */
1903 public function isMovable() {
1904 if ( !MWNamespace::isMovable( $this->getNamespace() ) || $this->getInterwiki() != '' ) {
1905 // Interwiki title or immovable namespace. Hooks don't get to override here
1906 return false;
1907 }
1908
1909 $result = true;
1910 wfRunHooks( 'TitleIsMovable', array( $this, &$result ) );
1911 return $result;
1912 }
1913
1914 /**
1915 * Is this the mainpage?
1916 * @note Title::newFromText seams to be sufficiently optimized by the title
1917 * cache that we don't need to over-optimize by doing direct comparisons and
1918 * acidentally creating new bugs where $title->equals( Title::newFromText() )
1919 * ends up reporting something differently than $title->isMainPage();
1920 *
1921 * @since 1.18
1922 * @return Bool
1923 */
1924 public function isMainPage() {
1925 return $this->equals( Title::newMainPage() );
1926 }
1927
1928 /**
1929 * Is this a talk page of some sort?
1930 *
1931 * @return Bool
1932 */
1933 public function isTalkPage() {
1934 return MWNamespace::isTalk( $this->getNamespace() );
1935 }
1936
1937 /**
1938 * Is this a subpage?
1939 *
1940 * @return Bool
1941 */
1942 public function isSubpage() {
1943 return MWNamespace::hasSubpages( $this->mNamespace )
1944 ? strpos( $this->getText(), '/' ) !== false
1945 : false;
1946 }
1947
1948 /**
1949 * Returns true if the title is inside the specified namespace.
1950 *
1951 * Please make use of this instead of comparing to getNamespace()
1952 * This function is much more resistant to changes we may make
1953 * to namespaces than code that makes direct comparisons.
1954 * @param $ns The namespace
1955 * @return bool
1956 * @since 1.19
1957 */
1958 public function inNamespace( $ns ) {
1959 return MWNamespace::equals( $this->getNamespace(), $ns );
1960 }
1961
1962 /**
1963 * Returns true if the title is inside one of the specified namespaces.
1964 *
1965 * @param ...$namespaces The namespaces to check for
1966 * @return bool
1967 * @since 1.19
1968 */
1969 public function inNamespaces( /* ... */ ) {
1970 $namespaces = func_get_args();
1971 if ( count( $namespaces ) > 0 && is_array( $namespaces[0] ) ) {
1972 $namespaces = $namespaces[0];
1973 }
1974
1975 foreach ( $namespaces as $ns ) {
1976 if ( $this->inNamespace( $ns ) ) {
1977 return true;
1978 }
1979 }
1980
1981 return false;
1982 }
1983
1984 /**
1985 * Returns true if the title has the same subject namespace as the
1986 * namespace specified.
1987 * For example this method will take NS_USER and return true if namespace
1988 * is either NS_USER or NS_USER_TALK since both of them have NS_USER
1989 * as their subject namespace.
1990 *
1991 * This is MUCH simpler than individually testing for equivilance
1992 * against both NS_USER and NS_USER_TALK, and is also forward compatible.
1993 * @since 1.19
1994 */
1995 public function hasSubjectNamespace( $ns ) {
1996 return MWNamespace::subjectEquals( $this->getNamespace(), $ns );
1997 }
1998
1999 /**
2000 * Does this have subpages? (Warning, usually requires an extra DB query.)
2001 *
2002 * @return Bool
2003 */
2004 public function hasSubpages() {
2005 if ( !MWNamespace::hasSubpages( $this->mNamespace ) ) {
2006 # Duh
2007 return false;
2008 }
2009
2010 # We dynamically add a member variable for the purpose of this method
2011 # alone to cache the result. There's no point in having it hanging
2012 # around uninitialized in every Title object; therefore we only add it
2013 # if needed and don't declare it statically.
2014 if ( isset( $this->mHasSubpages ) ) {
2015 return $this->mHasSubpages;
2016 }
2017
2018 $subpages = $this->getSubpages( 1 );
2019 if ( $subpages instanceof TitleArray ) {
2020 return $this->mHasSubpages = (bool)$subpages->count();
2021 }
2022 return $this->mHasSubpages = false;
2023 }
2024
2025 /**
2026 * Get all subpages of this page.
2027 *
2028 * @param $limit Int maximum number of subpages to fetch; -1 for no limit
2029 * @return mixed TitleArray, or empty array if this page's namespace
2030 * doesn't allow subpages
2031 */
2032 public function getSubpages( $limit = -1 ) {
2033 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
2034 return array();
2035 }
2036
2037 $dbr = wfGetDB( DB_SLAVE );
2038 $conds['page_namespace'] = $this->getNamespace();
2039 $conds[] = 'page_title ' . $dbr->buildLike( $this->getDBkey() . '/', $dbr->anyString() );
2040 $options = array();
2041 if ( $limit > -1 ) {
2042 $options['LIMIT'] = $limit;
2043 }
2044 return $this->mSubpages = TitleArray::newFromResult(
2045 $dbr->select( 'page',
2046 array( 'page_id', 'page_namespace', 'page_title', 'page_is_redirect' ),
2047 $conds,
2048 __METHOD__,
2049 $options
2050 )
2051 );
2052 }
2053
2054 /**
2055 * Does that page contain wikitext, or it is JS, CSS or whatever?
2056 *
2057 * @return Bool
2058 */
2059 public function isWikitextPage() {
2060 $retval = !$this->isCssOrJsPage() && !$this->isCssJsSubpage();
2061 wfRunHooks( 'TitleIsWikitextPage', array( $this, &$retval ) );
2062 return $retval;
2063 }
2064
2065 /**
2066 * Could this page contain custom CSS or JavaScript, based
2067 * on the title?
2068 *
2069 * @return Bool
2070 */
2071 public function isCssOrJsPage() {
2072 $retval = $this->mNamespace == NS_MEDIAWIKI
2073 && preg_match( '!\.(?:css|js)$!u', $this->mTextform ) > 0;
2074 wfRunHooks( 'TitleIsCssOrJsPage', array( $this, &$retval ) );
2075 return $retval;
2076 }
2077
2078 /**
2079 * Is this a .css or .js subpage of a user page?
2080 * @return Bool
2081 */
2082 public function isCssJsSubpage() {
2083 return ( NS_USER == $this->mNamespace and preg_match( "/\\/.*\\.(?:css|js)$/", $this->mTextform ) );
2084 }
2085
2086 /**
2087 * Is this a *valid* .css or .js subpage of a user page?
2088 *
2089 * @return Bool
2090 * @deprecated since 1.17
2091 */
2092 public function isValidCssJsSubpage() {
2093 return $this->isCssJsSubpage();
2094 }
2095
2096 /**
2097 * Trim down a .css or .js subpage title to get the corresponding skin name
2098 *
2099 * @return string containing skin name from .css or .js subpage title
2100 */
2101 public function getSkinFromCssJsSubpage() {
2102 $subpage = explode( '/', $this->mTextform );
2103 $subpage = $subpage[ count( $subpage ) - 1 ];
2104 $lastdot = strrpos( $subpage, '.' );
2105 if ( $lastdot === false )
2106 return $subpage; # Never happens: only called for names ending in '.css' or '.js'
2107 return substr( $subpage, 0, $lastdot );
2108 }
2109
2110 /**
2111 * Is this a .css subpage of a user page?
2112 *
2113 * @return Bool
2114 */
2115 public function isCssSubpage() {
2116 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.css$/", $this->mTextform ) );
2117 }
2118
2119 /**
2120 * Is this a .js subpage of a user page?
2121 *
2122 * @return Bool
2123 */
2124 public function isJsSubpage() {
2125 return ( NS_USER == $this->mNamespace && preg_match( "/\\/.*\\.js$/", $this->mTextform ) );
2126 }
2127
2128 /**
2129 * Protect css subpages of user pages: can $wgUser edit
2130 * this page?
2131 *
2132 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2133 * @return Bool
2134 */
2135 public function userCanEditCssSubpage() {
2136 global $wgUser;
2137 wfDeprecated( __METHOD__ );
2138 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'editusercss' ) )
2139 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2140 }
2141
2142 /**
2143 * Protect js subpages of user pages: can $wgUser edit
2144 * this page?
2145 *
2146 * @deprecated in 1.19; will be removed in 1.20. Use getUserPermissionsErrors() instead.
2147 * @return Bool
2148 */
2149 public function userCanEditJsSubpage() {
2150 global $wgUser;
2151 wfDeprecated( __METHOD__ );
2152 return ( ( $wgUser->isAllowedAll( 'editusercssjs', 'edituserjs' ) )
2153 || preg_match( '/^' . preg_quote( $wgUser->getName(), '/' ) . '\//', $this->mTextform ) );
2154 }
2155
2156 /**
2157 * Cascading protection: Return true if cascading restrictions apply to this page, false if not.
2158 *
2159 * @return Bool If the page is subject to cascading restrictions.
2160 */
2161 public function isCascadeProtected() {
2162 list( $sources, /* $restrictions */ ) = $this->getCascadeProtectionSources( false );
2163 return ( $sources > 0 );
2164 }
2165
2166 /**
2167 * Cascading protection: Get the source of any cascading restrictions on this page.
2168 *
2169 * @param $getPages Bool Whether or not to retrieve the actual pages
2170 * that the restrictions have come from.
2171 * @return Mixed Array of Title objects of the pages from which cascading restrictions
2172 * have come, false for none, or true if such restrictions exist, but $getPages
2173 * was not set. The restriction array is an array of each type, each of which
2174 * contains a array of unique groups.
2175 */
2176 public function getCascadeProtectionSources( $getPages = true ) {
2177 global $wgContLang;
2178 $pagerestrictions = array();
2179
2180 if ( isset( $this->mCascadeSources ) && $getPages ) {
2181 return array( $this->mCascadeSources, $this->mCascadingRestrictions );
2182 } elseif ( isset( $this->mHasCascadingRestrictions ) && !$getPages ) {
2183 return array( $this->mHasCascadingRestrictions, $pagerestrictions );
2184 }
2185
2186 wfProfileIn( __METHOD__ );
2187
2188 $dbr = wfGetDB( DB_SLAVE );
2189
2190 if ( $this->getNamespace() == NS_FILE ) {
2191 $tables = array( 'imagelinks', 'page_restrictions' );
2192 $where_clauses = array(
2193 'il_to' => $this->getDBkey(),
2194 'il_from=pr_page',
2195 'pr_cascade' => 1
2196 );
2197 } else {
2198 $tables = array( 'templatelinks', 'page_restrictions' );
2199 $where_clauses = array(
2200 'tl_namespace' => $this->getNamespace(),
2201 'tl_title' => $this->getDBkey(),
2202 'tl_from=pr_page',
2203 'pr_cascade' => 1
2204 );
2205 }
2206
2207 if ( $getPages ) {
2208 $cols = array( 'pr_page', 'page_namespace', 'page_title',
2209 'pr_expiry', 'pr_type', 'pr_level' );
2210 $where_clauses[] = 'page_id=pr_page';
2211 $tables[] = 'page';
2212 } else {
2213 $cols = array( 'pr_expiry' );
2214 }
2215
2216 $res = $dbr->select( $tables, $cols, $where_clauses, __METHOD__ );
2217
2218 $sources = $getPages ? array() : false;
2219 $now = wfTimestampNow();
2220 $purgeExpired = false;
2221
2222 foreach ( $res as $row ) {
2223 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2224 if ( $expiry > $now ) {
2225 if ( $getPages ) {
2226 $page_id = $row->pr_page;
2227 $page_ns = $row->page_namespace;
2228 $page_title = $row->page_title;
2229 $sources[$page_id] = Title::makeTitle( $page_ns, $page_title );
2230 # Add groups needed for each restriction type if its not already there
2231 # Make sure this restriction type still exists
2232
2233 if ( !isset( $pagerestrictions[$row->pr_type] ) ) {
2234 $pagerestrictions[$row->pr_type] = array();
2235 }
2236
2237 if ( isset( $pagerestrictions[$row->pr_type] ) &&
2238 !in_array( $row->pr_level, $pagerestrictions[$row->pr_type] ) ) {
2239 $pagerestrictions[$row->pr_type][] = $row->pr_level;
2240 }
2241 } else {
2242 $sources = true;
2243 }
2244 } else {
2245 // Trigger lazy purge of expired restrictions from the db
2246 $purgeExpired = true;
2247 }
2248 }
2249 if ( $purgeExpired ) {
2250 Title::purgeExpiredRestrictions();
2251 }
2252
2253 if ( $getPages ) {
2254 $this->mCascadeSources = $sources;
2255 $this->mCascadingRestrictions = $pagerestrictions;
2256 } else {
2257 $this->mHasCascadingRestrictions = $sources;
2258 }
2259
2260 wfProfileOut( __METHOD__ );
2261 return array( $sources, $pagerestrictions );
2262 }
2263
2264 /**
2265 * Returns cascading restrictions for the current article
2266 *
2267 * @return Boolean
2268 */
2269 function areRestrictionsCascading() {
2270 if ( !$this->mRestrictionsLoaded ) {
2271 $this->loadRestrictions();
2272 }
2273
2274 return $this->mCascadeRestriction;
2275 }
2276
2277 /**
2278 * Loads a string into mRestrictions array
2279 *
2280 * @param $res Resource restrictions as an SQL result.
2281 * @param $oldFashionedRestrictions String comma-separated list of page
2282 * restrictions from page table (pre 1.10)
2283 */
2284 private function loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions = null ) {
2285 $rows = array();
2286
2287 foreach ( $res as $row ) {
2288 $rows[] = $row;
2289 }
2290
2291 $this->loadRestrictionsFromRows( $rows, $oldFashionedRestrictions );
2292 }
2293
2294 /**
2295 * Compiles list of active page restrictions from both page table (pre 1.10)
2296 * and page_restrictions table for this existing page.
2297 * Public for usage by LiquidThreads.
2298 *
2299 * @param $rows array of db result objects
2300 * @param $oldFashionedRestrictions string comma-separated list of page
2301 * restrictions from page table (pre 1.10)
2302 */
2303 public function loadRestrictionsFromRows( $rows, $oldFashionedRestrictions = null ) {
2304 global $wgContLang;
2305 $dbr = wfGetDB( DB_SLAVE );
2306
2307 $restrictionTypes = $this->getRestrictionTypes();
2308
2309 foreach ( $restrictionTypes as $type ) {
2310 $this->mRestrictions[$type] = array();
2311 $this->mRestrictionsExpiry[$type] = $wgContLang->formatExpiry( '', TS_MW );
2312 }
2313
2314 $this->mCascadeRestriction = false;
2315
2316 # Backwards-compatibility: also load the restrictions from the page record (old format).
2317
2318 if ( $oldFashionedRestrictions === null ) {
2319 $oldFashionedRestrictions = $dbr->selectField( 'page', 'page_restrictions',
2320 array( 'page_id' => $this->getArticleId() ), __METHOD__ );
2321 }
2322
2323 if ( $oldFashionedRestrictions != '' ) {
2324
2325 foreach ( explode( ':', trim( $oldFashionedRestrictions ) ) as $restrict ) {
2326 $temp = explode( '=', trim( $restrict ) );
2327 if ( count( $temp ) == 1 ) {
2328 // old old format should be treated as edit/move restriction
2329 $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
2330 $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
2331 } else {
2332 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
2333 }
2334 }
2335
2336 $this->mOldRestrictions = true;
2337
2338 }
2339
2340 if ( count( $rows ) ) {
2341 # Current system - load second to make them override.
2342 $now = wfTimestampNow();
2343 $purgeExpired = false;
2344
2345 # Cycle through all the restrictions.
2346 foreach ( $rows as $row ) {
2347
2348 // Don't take care of restrictions types that aren't allowed
2349 if ( !in_array( $row->pr_type, $restrictionTypes ) )
2350 continue;
2351
2352 // This code should be refactored, now that it's being used more generally,
2353 // But I don't really see any harm in leaving it in Block for now -werdna
2354 $expiry = $wgContLang->formatExpiry( $row->pr_expiry, TS_MW );
2355
2356 // Only apply the restrictions if they haven't expired!
2357 if ( !$expiry || $expiry > $now ) {
2358 $this->mRestrictionsExpiry[$row->pr_type] = $expiry;
2359 $this->mRestrictions[$row->pr_type] = explode( ',', trim( $row->pr_level ) );
2360
2361 $this->mCascadeRestriction |= $row->pr_cascade;
2362 } else {
2363 // Trigger a lazy purge of expired restrictions
2364 $purgeExpired = true;
2365 }
2366 }
2367
2368 if ( $purgeExpired ) {
2369 Title::purgeExpiredRestrictions();
2370 }
2371 }
2372
2373 $this->mRestrictionsLoaded = true;
2374 }
2375
2376 /**
2377 * Load restrictions from the page_restrictions table
2378 *
2379 * @param $oldFashionedRestrictions String comma-separated list of page
2380 * restrictions from page table (pre 1.10)
2381 */
2382 public function loadRestrictions( $oldFashionedRestrictions = null ) {
2383 global $wgContLang;
2384 if ( !$this->mRestrictionsLoaded ) {
2385 if ( $this->exists() ) {
2386 $dbr = wfGetDB( DB_SLAVE );
2387
2388 $res = $dbr->select(
2389 'page_restrictions',
2390 '*',
2391 array( 'pr_page' => $this->getArticleId() ),
2392 __METHOD__
2393 );
2394
2395 $this->loadRestrictionsFromResultWrapper( $res, $oldFashionedRestrictions );
2396 } else {
2397 $title_protection = $this->getTitleProtection();
2398
2399 if ( $title_protection ) {
2400 $now = wfTimestampNow();
2401 $expiry = $wgContLang->formatExpiry( $title_protection['pt_expiry'], TS_MW );
2402
2403 if ( !$expiry || $expiry > $now ) {
2404 // Apply the restrictions
2405 $this->mRestrictionsExpiry['create'] = $expiry;
2406 $this->mRestrictions['create'] = explode( ',', trim( $title_protection['pt_create_perm'] ) );
2407 } else { // Get rid of the old restrictions
2408 Title::purgeExpiredRestrictions();
2409 $this->mTitleProtection = false;
2410 }
2411 } else {
2412 $this->mRestrictionsExpiry['create'] = $wgContLang->formatExpiry( '', TS_MW );
2413 }
2414 $this->mRestrictionsLoaded = true;
2415 }
2416 }
2417 }
2418
2419 /**
2420 * Purge expired restrictions from the page_restrictions table
2421 */
2422 static function purgeExpiredRestrictions() {
2423 $dbw = wfGetDB( DB_MASTER );
2424 $dbw->delete(
2425 'page_restrictions',
2426 array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2427 __METHOD__
2428 );
2429
2430 $dbw->delete(
2431 'protected_titles',
2432 array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
2433 __METHOD__
2434 );
2435 }
2436
2437 /**
2438 * Accessor/initialisation for mRestrictions
2439 *
2440 * @param $action String action that permission needs to be checked for
2441 * @return Array of Strings the array of groups allowed to edit this article
2442 */
2443 public function getRestrictions( $action ) {
2444 if ( !$this->mRestrictionsLoaded ) {
2445 $this->loadRestrictions();
2446 }
2447 return isset( $this->mRestrictions[$action] )
2448 ? $this->mRestrictions[$action]
2449 : array();
2450 }
2451
2452 /**
2453 * Get the expiry time for the restriction against a given action
2454 *
2455 * @return String|Bool 14-char timestamp, or 'infinity' if the page is protected forever
2456 * or not protected at all, or false if the action is not recognised.
2457 */
2458 public function getRestrictionExpiry( $action ) {
2459 if ( !$this->mRestrictionsLoaded ) {
2460 $this->loadRestrictions();
2461 }
2462 return isset( $this->mRestrictionsExpiry[$action] ) ? $this->mRestrictionsExpiry[$action] : false;
2463 }
2464
2465 /**
2466 * Is there a version of this page in the deletion archive?
2467 *
2468 * @return Int the number of archived revisions
2469 */
2470 public function isDeleted() {
2471 if ( $this->getNamespace() < 0 ) {
2472 $n = 0;
2473 } else {
2474 $dbr = wfGetDB( DB_SLAVE );
2475
2476 $n = $dbr->selectField( 'archive', 'COUNT(*)',
2477 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2478 __METHOD__
2479 );
2480 if ( $this->getNamespace() == NS_FILE ) {
2481 $n += $dbr->selectField( 'filearchive', 'COUNT(*)',
2482 array( 'fa_name' => $this->getDBkey() ),
2483 __METHOD__
2484 );
2485 }
2486 }
2487 return (int)$n;
2488 }
2489
2490 /**
2491 * Is there a version of this page in the deletion archive?
2492 *
2493 * @return Boolean
2494 */
2495 public function isDeletedQuick() {
2496 if ( $this->getNamespace() < 0 ) {
2497 return false;
2498 }
2499 $dbr = wfGetDB( DB_SLAVE );
2500 $deleted = (bool)$dbr->selectField( 'archive', '1',
2501 array( 'ar_namespace' => $this->getNamespace(), 'ar_title' => $this->getDBkey() ),
2502 __METHOD__
2503 );
2504 if ( !$deleted && $this->getNamespace() == NS_FILE ) {
2505 $deleted = (bool)$dbr->selectField( 'filearchive', '1',
2506 array( 'fa_name' => $this->getDBkey() ),
2507 __METHOD__
2508 );
2509 }
2510 return $deleted;
2511 }
2512
2513 /**
2514 * Get the article ID for this Title from the link cache,
2515 * adding it if necessary
2516 *
2517 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select
2518 * for update
2519 * @return Int the ID
2520 */
2521 public function getArticleID( $flags = 0 ) {
2522 if ( $this->getNamespace() < 0 ) {
2523 return $this->mArticleID = 0;
2524 }
2525 $linkCache = LinkCache::singleton();
2526 if ( $flags & self::GAID_FOR_UPDATE ) {
2527 $oldUpdate = $linkCache->forUpdate( true );
2528 $linkCache->clearLink( $this );
2529 $this->mArticleID = $linkCache->addLinkObj( $this );
2530 $linkCache->forUpdate( $oldUpdate );
2531 } else {
2532 if ( -1 == $this->mArticleID ) {
2533 $this->mArticleID = $linkCache->addLinkObj( $this );
2534 }
2535 }
2536 return $this->mArticleID;
2537 }
2538
2539 /**
2540 * Is this an article that is a redirect page?
2541 * Uses link cache, adding it if necessary
2542 *
2543 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2544 * @return Bool
2545 */
2546 public function isRedirect( $flags = 0 ) {
2547 if ( !is_null( $this->mRedirect ) ) {
2548 return $this->mRedirect;
2549 }
2550 # Calling getArticleID() loads the field from cache as needed
2551 if ( !$this->getArticleID( $flags ) ) {
2552 return $this->mRedirect = false;
2553 }
2554 $linkCache = LinkCache::singleton();
2555 $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
2556
2557 return $this->mRedirect;
2558 }
2559
2560 /**
2561 * What is the length of this page?
2562 * Uses link cache, adding it if necessary
2563 *
2564 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2565 * @return Int
2566 */
2567 public function getLength( $flags = 0 ) {
2568 if ( $this->mLength != -1 ) {
2569 return $this->mLength;
2570 }
2571 # Calling getArticleID() loads the field from cache as needed
2572 if ( !$this->getArticleID( $flags ) ) {
2573 return $this->mLength = 0;
2574 }
2575 $linkCache = LinkCache::singleton();
2576 $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
2577
2578 return $this->mLength;
2579 }
2580
2581 /**
2582 * What is the page_latest field for this page?
2583 *
2584 * @param $flags Int a bit field; may be Title::GAID_FOR_UPDATE to select for update
2585 * @return Int or 0 if the page doesn't exist
2586 */
2587 public function getLatestRevID( $flags = 0 ) {
2588 if ( $this->mLatestID !== false ) {
2589 return intval( $this->mLatestID );
2590 }
2591 # Calling getArticleID() loads the field from cache as needed
2592 if ( !$this->getArticleID( $flags ) ) {
2593 return $this->mLatestID = 0;
2594 }
2595 $linkCache = LinkCache::singleton();
2596 $this->mLatestID = intval( $linkCache->getGoodLinkFieldObj( $this, 'revision' ) );
2597
2598 return $this->mLatestID;
2599 }
2600
2601 /**
2602 * This clears some fields in this object, and clears any associated
2603 * keys in the "bad links" section of the link cache.
2604 *
2605 * - This is called from Article::doEdit() and Article::insertOn() to allow
2606 * loading of the new page_id. It's also called from
2607 * Article::doDeleteArticle()
2608 *
2609 * @param $newid Int the new Article ID
2610 */
2611 public function resetArticleID( $newid ) {
2612 $linkCache = LinkCache::singleton();
2613 $linkCache->clearLink( $this );
2614
2615 if ( $newid === false ) {
2616 $this->mArticleID = -1;
2617 } else {
2618 $this->mArticleID = intval( $newid );
2619 }
2620 $this->mRestrictionsLoaded = false;
2621 $this->mRestrictions = array();
2622 $this->mRedirect = null;
2623 $this->mLength = -1;
2624 $this->mLatestID = false;
2625 }
2626
2627 /**
2628 * Updates page_touched for this page; called from LinksUpdate.php
2629 *
2630 * @return Bool true if the update succeded
2631 */
2632 public function invalidateCache() {
2633 if ( wfReadOnly() ) {
2634 return false;
2635 }
2636 $dbw = wfGetDB( DB_MASTER );
2637 $success = $dbw->update(
2638 'page',
2639 array( 'page_touched' => $dbw->timestamp() ),
2640 $this->pageCond(),
2641 __METHOD__
2642 );
2643 HTMLFileCache::clearFileCache( $this );
2644 return $success;
2645 }
2646
2647 /**
2648 * Prefix some arbitrary text with the namespace or interwiki prefix
2649 * of this object
2650 *
2651 * @param $name String the text
2652 * @return String the prefixed text
2653 * @private
2654 */
2655 private function prefix( $name ) {
2656 $p = '';
2657 if ( $this->mInterwiki != '' ) {
2658 $p = $this->mInterwiki . ':';
2659 }
2660
2661 if ( 0 != $this->mNamespace ) {
2662 $p .= $this->getNsText() . ':';
2663 }
2664 return $p . $name;
2665 }
2666
2667 /**
2668 * Returns a simple regex that will match on characters and sequences invalid in titles.
2669 * Note that this doesn't pick up many things that could be wrong with titles, but that
2670 * replacing this regex with something valid will make many titles valid.
2671 *
2672 * @return String regex string
2673 */
2674 static function getTitleInvalidRegex() {
2675 static $rxTc = false;
2676 if ( !$rxTc ) {
2677 # Matching titles will be held as illegal.
2678 $rxTc = '/' .
2679 # Any character not allowed is forbidden...
2680 '[^' . Title::legalChars() . ']' .
2681 # URL percent encoding sequences interfere with the ability
2682 # to round-trip titles -- you can't link to them consistently.
2683 '|%[0-9A-Fa-f]{2}' .
2684 # XML/HTML character references produce similar issues.
2685 '|&[A-Za-z0-9\x80-\xff]+;' .
2686 '|&#[0-9]+;' .
2687 '|&#x[0-9A-Fa-f]+;' .
2688 '/S';
2689 }
2690
2691 return $rxTc;
2692 }
2693
2694 /**
2695 * Capitalize a text string for a title if it belongs to a namespace that capitalizes
2696 *
2697 * @param $text String containing title to capitalize
2698 * @param $ns int namespace index, defaults to NS_MAIN
2699 * @return String containing capitalized title
2700 */
2701 public static function capitalize( $text, $ns = NS_MAIN ) {
2702 global $wgContLang;
2703
2704 if ( MWNamespace::isCapitalized( $ns ) ) {
2705 return $wgContLang->ucfirst( $text );
2706 } else {
2707 return $text;
2708 }
2709 }
2710
2711 /**
2712 * Secure and split - main initialisation function for this object
2713 *
2714 * Assumes that mDbkeyform has been set, and is urldecoded
2715 * and uses underscores, but not otherwise munged. This function
2716 * removes illegal characters, splits off the interwiki and
2717 * namespace prefixes, sets the other forms, and canonicalizes
2718 * everything.
2719 *
2720 * @return Bool true on success
2721 */
2722 private function secureAndSplit() {
2723 global $wgContLang, $wgLocalInterwiki;
2724
2725 # Initialisation
2726 $this->mInterwiki = $this->mFragment = '';
2727 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
2728
2729 $dbkey = $this->mDbkeyform;
2730
2731 # Strip Unicode bidi override characters.
2732 # Sometimes they slip into cut-n-pasted page titles, where the
2733 # override chars get included in list displays.
2734 $dbkey = preg_replace( '/\xE2\x80[\x8E\x8F\xAA-\xAE]/S', '', $dbkey );
2735
2736 # Clean up whitespace
2737 # Note: use of the /u option on preg_replace here will cause
2738 # input with invalid UTF-8 sequences to be nullified out in PHP 5.2.x,
2739 # conveniently disabling them.
2740 $dbkey = preg_replace( '/[ _\xA0\x{1680}\x{180E}\x{2000}-\x{200A}\x{2028}\x{2029}\x{202F}\x{205F}\x{3000}]+/u', '_', $dbkey );
2741 $dbkey = trim( $dbkey, '_' );
2742
2743 if ( $dbkey == '' ) {
2744 return false;
2745 }
2746
2747 if ( false !== strpos( $dbkey, UTF8_REPLACEMENT ) ) {
2748 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
2749 return false;
2750 }
2751
2752 $this->mDbkeyform = $dbkey;
2753
2754 # Initial colon indicates main namespace rather than specified default
2755 # but should not create invalid {ns,title} pairs such as {0,Project:Foo}
2756 if ( ':' == $dbkey[0] ) {
2757 $this->mNamespace = NS_MAIN;
2758 $dbkey = substr( $dbkey, 1 ); # remove the colon but continue processing
2759 $dbkey = trim( $dbkey, '_' ); # remove any subsequent whitespace
2760 }
2761
2762 # Namespace or interwiki prefix
2763 $firstPass = true;
2764 $prefixRegexp = "/^(.+?)_*:_*(.*)$/S";
2765 do {
2766 $m = array();
2767 if ( preg_match( $prefixRegexp, $dbkey, $m ) ) {
2768 $p = $m[1];
2769 if ( ( $ns = $wgContLang->getNsIndex( $p ) ) !== false ) {
2770 # Ordinary namespace
2771 $dbkey = $m[2];
2772 $this->mNamespace = $ns;
2773 # For Talk:X pages, check if X has a "namespace" prefix
2774 if ( $ns == NS_TALK && preg_match( $prefixRegexp, $dbkey, $x ) ) {
2775 if ( $wgContLang->getNsIndex( $x[1] ) ) {
2776 # Disallow Talk:File:x type titles...
2777 return false;
2778 } elseif ( Interwiki::isValidInterwiki( $x[1] ) ) {
2779 # Disallow Talk:Interwiki:x type titles...
2780 return false;
2781 }
2782 }
2783 } elseif ( Interwiki::isValidInterwiki( $p ) ) {
2784 if ( !$firstPass ) {
2785 # Can't make a local interwiki link to an interwiki link.
2786 # That's just crazy!
2787 return false;
2788 }
2789
2790 # Interwiki link
2791 $dbkey = $m[2];
2792 $this->mInterwiki = $wgContLang->lc( $p );
2793
2794 # Redundant interwiki prefix to the local wiki
2795 if ( $wgLocalInterwiki !== false
2796 && 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) )
2797 {
2798 if ( $dbkey == '' ) {
2799 # Can't have an empty self-link
2800 return false;
2801 }
2802 $this->mInterwiki = '';
2803 $firstPass = false;
2804 # Do another namespace split...
2805 continue;
2806 }
2807
2808 # If there's an initial colon after the interwiki, that also
2809 # resets the default namespace
2810 if ( $dbkey !== '' && $dbkey[0] == ':' ) {
2811 $this->mNamespace = NS_MAIN;
2812 $dbkey = substr( $dbkey, 1 );
2813 }
2814 }
2815 # If there's no recognized interwiki or namespace,
2816 # then let the colon expression be part of the title.
2817 }
2818 break;
2819 } while ( true );
2820
2821 # We already know that some pages won't be in the database!
2822 if ( $this->mInterwiki != '' || NS_SPECIAL == $this->mNamespace ) {
2823 $this->mArticleID = 0;
2824 }
2825 $fragment = strstr( $dbkey, '#' );
2826 if ( false !== $fragment ) {
2827 $this->setFragment( $fragment );
2828 $dbkey = substr( $dbkey, 0, strlen( $dbkey ) - strlen( $fragment ) );
2829 # remove whitespace again: prevents "Foo_bar_#"
2830 # becoming "Foo_bar_"
2831 $dbkey = preg_replace( '/_*$/', '', $dbkey );
2832 }
2833
2834 # Reject illegal characters.
2835 $rxTc = self::getTitleInvalidRegex();
2836 if ( preg_match( $rxTc, $dbkey ) ) {
2837 return false;
2838 }
2839
2840 # Pages with "/./" or "/../" appearing in the URLs will often be un-
2841 # reachable due to the way web browsers deal with 'relative' URLs.
2842 # Also, they conflict with subpage syntax. Forbid them explicitly.
2843 if ( strpos( $dbkey, '.' ) !== false &&
2844 ( $dbkey === '.' || $dbkey === '..' ||
2845 strpos( $dbkey, './' ) === 0 ||
2846 strpos( $dbkey, '../' ) === 0 ||
2847 strpos( $dbkey, '/./' ) !== false ||
2848 strpos( $dbkey, '/../' ) !== false ||
2849 substr( $dbkey, -2 ) == '/.' ||
2850 substr( $dbkey, -3 ) == '/..' ) )
2851 {
2852 return false;
2853 }
2854
2855 # Magic tilde sequences? Nu-uh!
2856 if ( strpos( $dbkey, '~~~' ) !== false ) {
2857 return false;
2858 }
2859
2860 # Limit the size of titles to 255 bytes. This is typically the size of the
2861 # underlying database field. We make an exception for special pages, which
2862 # don't need to be stored in the database, and may edge over 255 bytes due
2863 # to subpage syntax for long titles, e.g. [[Special:Block/Long name]]
2864 if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
2865 strlen( $dbkey ) > 512 )
2866 {
2867 return false;
2868 }
2869
2870 # Normally, all wiki links are forced to have an initial capital letter so [[foo]]
2871 # and [[Foo]] point to the same place. Don't force it for interwikis, since the
2872 # other site might be case-sensitive.
2873 $this->mUserCaseDBKey = $dbkey;
2874 if ( $this->mInterwiki == '' ) {
2875 $dbkey = self::capitalize( $dbkey, $this->mNamespace );
2876 }
2877
2878 # Can't make a link to a namespace alone... "empty" local links can only be
2879 # self-links with a fragment identifier.
2880 if ( $dbkey == '' && $this->mInterwiki == '' && $this->mNamespace != NS_MAIN ) {
2881 return false;
2882 }
2883
2884 // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
2885 // IP names are not allowed for accounts, and can only be referring to
2886 // edits from the IP. Given '::' abbreviations and caps/lowercaps,
2887 // there are numerous ways to present the same IP. Having sp:contribs scan
2888 // them all is silly and having some show the edits and others not is
2889 // inconsistent. Same for talk/userpages. Keep them normalized instead.
2890 $dbkey = ( $this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK )
2891 ? IP::sanitizeIP( $dbkey )
2892 : $dbkey;
2893
2894 // Any remaining initial :s are illegal.
2895 if ( $dbkey !== '' && ':' == $dbkey[0] ) {
2896 return false;
2897 }
2898
2899 # Fill fields
2900 $this->mDbkeyform = $dbkey;
2901 $this->mUrlform = wfUrlencode( $dbkey );
2902
2903 $this->mTextform = str_replace( '_', ' ', $dbkey );
2904
2905 return true;
2906 }
2907
2908 /**
2909 * Set the fragment for this title. Removes the first character from the
2910 * specified fragment before setting, so it assumes you're passing it with
2911 * an initial "#".
2912 *
2913 * Deprecated for public use, use Title::makeTitle() with fragment parameter.
2914 * Still in active use privately.
2915 *
2916 * @param $fragment String text
2917 */
2918 public function setFragment( $fragment ) {
2919 $this->mFragment = str_replace( '_', ' ', substr( $fragment, 1 ) );
2920 }
2921
2922 /**
2923 * Get a Title object associated with the talk page of this article
2924 *
2925 * @return Title the object for the talk page
2926 */
2927 public function getTalkPage() {
2928 return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
2929 }
2930
2931 /**
2932 * Get a title object associated with the subject page of this
2933 * talk page
2934 *
2935 * @return Title the object for the subject page
2936 */
2937 public function getSubjectPage() {
2938 // Is this the same title?
2939 $subjectNS = MWNamespace::getSubject( $this->getNamespace() );
2940 if ( $this->getNamespace() == $subjectNS ) {
2941 return $this;
2942 }
2943 return Title::makeTitle( $subjectNS, $this->getDBkey() );
2944 }
2945
2946 /**
2947 * Get an array of Title objects linking to this Title
2948 * Also stores the IDs in the link cache.
2949 *
2950 * WARNING: do not use this function on arbitrary user-supplied titles!
2951 * On heavily-used templates it will max out the memory.
2952 *
2953 * @param $options Array: may be FOR UPDATE
2954 * @param $table String: table name
2955 * @param $prefix String: fields prefix
2956 * @return Array of Title objects linking here
2957 */
2958 public function getLinksTo( $options = array(), $table = 'pagelinks', $prefix = 'pl' ) {
2959 $linkCache = LinkCache::singleton();
2960
2961 if ( count( $options ) > 0 ) {
2962 $db = wfGetDB( DB_MASTER );
2963 } else {
2964 $db = wfGetDB( DB_SLAVE );
2965 }
2966
2967 $res = $db->select(
2968 array( 'page', $table ),
2969 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect', 'page_latest' ),
2970 array(
2971 "{$prefix}_from=page_id",
2972 "{$prefix}_namespace" => $this->getNamespace(),
2973 "{$prefix}_title" => $this->getDBkey() ),
2974 __METHOD__,
2975 $options
2976 );
2977
2978 $retVal = array();
2979 if ( $db->numRows( $res ) ) {
2980 foreach ( $res as $row ) {
2981 $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title );
2982 if ( $titleObj ) {
2983 $linkCache->addGoodLinkObjFromRow( $titleObj, $row );
2984 $retVal[] = $titleObj;
2985 }
2986 }
2987 }
2988 return $retVal;
2989 }
2990
2991 /**
2992 * Get an array of Title objects using this Title as a template
2993 * Also stores the IDs in the link cache.
2994 *
2995 * WARNING: do not use this function on arbitrary user-supplied titles!
2996 * On heavily-used templates it will max out the memory.
2997 *
2998 * @param $options Array: may be FOR UPDATE
2999 * @return Array of Title the Title objects linking here
3000 */
3001 public function getTemplateLinksTo( $options = array() ) {
3002 return $this->getLinksTo( $options, 'templatelinks', 'tl' );
3003 }
3004
3005 /**
3006 * Get an array of Title objects referring to non-existent articles linked from this page
3007 *
3008 * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
3009 * @return Array of Title the Title objects
3010 */
3011 public function getBrokenLinksFrom() {
3012 if ( $this->getArticleId() == 0 ) {
3013 # All links from article ID 0 are false positives
3014 return array();
3015 }
3016
3017 $dbr = wfGetDB( DB_SLAVE );
3018 $res = $dbr->select(
3019 array( 'page', 'pagelinks' ),
3020 array( 'pl_namespace', 'pl_title' ),
3021 array(
3022 'pl_from' => $this->getArticleId(),
3023 'page_namespace IS NULL'
3024 ),
3025 __METHOD__, array(),
3026 array(
3027 'page' => array(
3028 'LEFT JOIN',
3029 array( 'pl_namespace=page_namespace', 'pl_title=page_title' )
3030 )
3031 )
3032 );
3033
3034 $retVal = array();
3035 foreach ( $res as $row ) {
3036 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
3037 }
3038 return $retVal;
3039 }
3040
3041
3042 /**
3043 * Get a list of URLs to purge from the Squid cache when this
3044 * page changes
3045 *
3046 * @return Array of String the URLs
3047 */
3048 public function getSquidURLs() {
3049 global $wgContLang;
3050
3051 $urls = array(
3052 $this->getInternalURL(),
3053 $this->getInternalURL( 'action=history' )
3054 );
3055
3056 // purge variant urls as well
3057 if ( $wgContLang->hasVariants() ) {
3058 $variants = $wgContLang->getVariants();
3059 foreach ( $variants as $vCode ) {
3060 $urls[] = $this->getInternalURL( '', $vCode );
3061 }
3062 }
3063
3064 return $urls;
3065 }
3066
3067 /**
3068 * Purge all applicable Squid URLs
3069 */
3070 public function purgeSquid() {
3071 global $wgUseSquid;
3072 if ( $wgUseSquid ) {
3073 $urls = $this->getSquidURLs();
3074 $u = new SquidUpdate( $urls );
3075 $u->doUpdate();
3076 }
3077 }
3078
3079 /**
3080 * Move this page without authentication
3081 *
3082 * @param $nt Title the new page Title
3083 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3084 */
3085 public function moveNoAuth( &$nt ) {
3086 return $this->moveTo( $nt, false );
3087 }
3088
3089 /**
3090 * Check whether a given move operation would be valid.
3091 * Returns true if ok, or a getUserPermissionsErrors()-like array otherwise
3092 *
3093 * @param $nt Title the new title
3094 * @param $auth Bool indicates whether $wgUser's permissions
3095 * should be checked
3096 * @param $reason String is the log summary of the move, used for spam checking
3097 * @return Mixed True on success, getUserPermissionsErrors()-like array on failure
3098 */
3099 public function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
3100 global $wgUser;
3101
3102 $errors = array();
3103 if ( !$nt ) {
3104 // Normally we'd add this to $errors, but we'll get
3105 // lots of syntax errors if $nt is not an object
3106 return array( array( 'badtitletext' ) );
3107 }
3108 if ( $this->equals( $nt ) ) {
3109 $errors[] = array( 'selfmove' );
3110 }
3111 if ( !$this->isMovable() ) {
3112 $errors[] = array( 'immobile-source-namespace', $this->getNsText() );
3113 }
3114 if ( $nt->getInterwiki() != '' ) {
3115 $errors[] = array( 'immobile-target-namespace-iw' );
3116 }
3117 if ( !$nt->isMovable() ) {
3118 $errors[] = array( 'immobile-target-namespace', $nt->getNsText() );
3119 }
3120
3121 $oldid = $this->getArticleID();
3122 $newid = $nt->getArticleID();
3123
3124 if ( strlen( $nt->getDBkey() ) < 1 ) {
3125 $errors[] = array( 'articleexists' );
3126 }
3127 if ( ( $this->getDBkey() == '' ) ||
3128 ( !$oldid ) ||
3129 ( $nt->getDBkey() == '' ) ) {
3130 $errors[] = array( 'badarticleerror' );
3131 }
3132
3133 // Image-specific checks
3134 if ( $this->getNamespace() == NS_FILE ) {
3135 $errors = array_merge( $errors, $this->validateFileMoveOperation( $nt ) );
3136 }
3137
3138 if ( $nt->getNamespace() == NS_FILE && $this->getNamespace() != NS_FILE ) {
3139 $errors[] = array( 'nonfile-cannot-move-to-file' );
3140 }
3141
3142 if ( $auth ) {
3143 $errors = wfMergeErrorArrays( $errors,
3144 $this->getUserPermissionsErrors( 'move', $wgUser ),
3145 $this->getUserPermissionsErrors( 'edit', $wgUser ),
3146 $nt->getUserPermissionsErrors( 'move-target', $wgUser ),
3147 $nt->getUserPermissionsErrors( 'edit', $wgUser ) );
3148 }
3149
3150 $match = EditPage::matchSummarySpamRegex( $reason );
3151 if ( $match !== false ) {
3152 // This is kind of lame, won't display nice
3153 $errors[] = array( 'spamprotectiontext' );
3154 }
3155
3156 $err = null;
3157 if ( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err, $reason ) ) ) {
3158 $errors[] = array( 'hookaborted', $err );
3159 }
3160
3161 # The move is allowed only if (1) the target doesn't exist, or
3162 # (2) the target is a redirect to the source, and has no history
3163 # (so we can undo bad moves right after they're done).
3164
3165 if ( 0 != $newid ) { # Target exists; check for validity
3166 if ( !$this->isValidMoveTarget( $nt ) ) {
3167 $errors[] = array( 'articleexists' );
3168 }
3169 } else {
3170 $tp = $nt->getTitleProtection();
3171 $right = ( $tp['pt_create_perm'] == 'sysop' ) ? 'protect' : $tp['pt_create_perm'];
3172 if ( $tp and !$wgUser->isAllowed( $right ) ) {
3173 $errors[] = array( 'cantmove-titleprotected' );
3174 }
3175 }
3176 if ( empty( $errors ) ) {
3177 return true;
3178 }
3179 return $errors;
3180 }
3181
3182 /**
3183 * Check if the requested move target is a valid file move target
3184 * @param Title $nt Target title
3185 * @return array List of errors
3186 */
3187 protected function validateFileMoveOperation( $nt ) {
3188 global $wgUser;
3189
3190 $errors = array();
3191
3192 // wfFindFile( $nt ) / wfLocalFile( $nt ) is not allowed until below
3193
3194 $file = wfLocalFile( $this );
3195 if ( $file->exists() ) {
3196 if ( $nt->getText() != wfStripIllegalFilenameChars( $nt->getText() ) ) {
3197 $errors[] = array( 'imageinvalidfilename' );
3198 }
3199 if ( !File::checkExtensionCompatibility( $file, $nt->getDBkey() ) ) {
3200 $errors[] = array( 'imagetypemismatch' );
3201 }
3202 }
3203
3204 if ( $nt->getNamespace() != NS_FILE ) {
3205 $errors[] = array( 'imagenocrossnamespace' );
3206 // From here we want to do checks on a file object, so if we can't
3207 // create one, we must return.
3208 return $errors;
3209 }
3210
3211 // wfFindFile( $nt ) / wfLocalFile( $nt ) is allowed below here
3212
3213 $destFile = wfLocalFile( $nt );
3214 if ( !$wgUser->isAllowed( 'reupload-shared' ) && !$destFile->exists() && wfFindFile( $nt ) ) {
3215 $errors[] = array( 'file-exists-sharedrepo' );
3216 }
3217
3218 return $errors;
3219 }
3220
3221 /**
3222 * Move a title to a new location
3223 *
3224 * @param $nt Title the new title
3225 * @param $auth Bool indicates whether $wgUser's permissions
3226 * should be checked
3227 * @param $reason String the reason for the move
3228 * @param $createRedirect Bool Whether to create a redirect from the old title to the new title.
3229 * Ignored if the user doesn't have the suppressredirect right.
3230 * @return Mixed true on success, getUserPermissionsErrors()-like array on failure
3231 */
3232 public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
3233 global $wgUser;
3234 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
3235 if ( is_array( $err ) ) {
3236 // Auto-block user's IP if the account was "hard" blocked
3237 $wgUser->spreadAnyEditBlock();
3238 return $err;
3239 }
3240
3241 // If it is a file, move it first.
3242 // It is done before all other moving stuff is done because it's hard to revert.
3243 $dbw = wfGetDB( DB_MASTER );
3244 if ( $this->getNamespace() == NS_FILE ) {
3245 $file = wfLocalFile( $this );
3246 if ( $file->exists() ) {
3247 $status = $file->move( $nt );
3248 if ( !$status->isOk() ) {
3249 return $status->getErrorsArray();
3250 }
3251 }
3252 }
3253 // Clear RepoGroup process cache
3254 RepoGroup::singleton()->clearCache( $this );
3255 RepoGroup::singleton()->clearCache( $nt ); # clear false negative cache
3256
3257 $dbw->begin(); # If $file was a LocalFile, its transaction would have closed our own.
3258 $pageid = $this->getArticleID( self::GAID_FOR_UPDATE );
3259 $protected = $this->isProtected();
3260 $pageCountChange = ( $createRedirect ? 1 : 0 ) - ( $nt->exists() ? 1 : 0 );
3261
3262 // Do the actual move
3263 $err = $this->moveToInternal( $nt, $reason, $createRedirect );
3264 if ( is_array( $err ) ) {
3265 # @todo FIXME: What about the File we have already moved?
3266 $dbw->rollback();
3267 return $err;
3268 }
3269
3270 $redirid = $this->getArticleID();
3271
3272 // Refresh the sortkey for this row. Be careful to avoid resetting
3273 // cl_timestamp, which may disturb time-based lists on some sites.
3274 $prefixes = $dbw->select(
3275 'categorylinks',
3276 array( 'cl_sortkey_prefix', 'cl_to' ),
3277 array( 'cl_from' => $pageid ),
3278 __METHOD__
3279 );
3280 foreach ( $prefixes as $prefixRow ) {
3281 $prefix = $prefixRow->cl_sortkey_prefix;
3282 $catTo = $prefixRow->cl_to;
3283 $dbw->update( 'categorylinks',
3284 array(
3285 'cl_sortkey' => Collation::singleton()->getSortKey(
3286 $nt->getCategorySortkey( $prefix ) ),
3287 'cl_timestamp=cl_timestamp' ),
3288 array(
3289 'cl_from' => $pageid,
3290 'cl_to' => $catTo ),
3291 __METHOD__
3292 );
3293 }
3294
3295 if ( $protected ) {
3296 # Protect the redirect title as the title used to be...
3297 $dbw->insertSelect( 'page_restrictions', 'page_restrictions',
3298 array(
3299 'pr_page' => $redirid,
3300 'pr_type' => 'pr_type',
3301 'pr_level' => 'pr_level',
3302 'pr_cascade' => 'pr_cascade',
3303 'pr_user' => 'pr_user',
3304 'pr_expiry' => 'pr_expiry'
3305 ),
3306 array( 'pr_page' => $pageid ),
3307 __METHOD__,
3308 array( 'IGNORE' )
3309 );
3310 # Update the protection log
3311 $log = new LogPage( 'protect' );
3312 $comment = wfMsgForContent( 'prot_1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
3313 if ( $reason ) {
3314 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3315 }
3316 // @todo FIXME: $params?
3317 $log->addEntry( 'move_prot', $nt, $comment, array( $this->getPrefixedText() ) );
3318 }
3319
3320 # Update watchlists
3321 $oldnamespace = $this->getNamespace() & ~1;
3322 $newnamespace = $nt->getNamespace() & ~1;
3323 $oldtitle = $this->getDBkey();
3324 $newtitle = $nt->getDBkey();
3325
3326 if ( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
3327 WatchedItem::duplicateEntries( $this, $nt );
3328 }
3329
3330 # Update search engine
3331 $u = new SearchUpdate( $pageid, $nt->getPrefixedDBkey() );
3332 $u->doUpdate();
3333 $u = new SearchUpdate( $redirid, $this->getPrefixedDBkey(), '' );
3334 $u->doUpdate();
3335
3336 $dbw->commit();
3337
3338 # Update site_stats
3339 if ( $this->isContentPage() && !$nt->isContentPage() ) {
3340 # No longer a content page
3341 # Not viewed, edited, removing
3342 $u = new SiteStatsUpdate( 0, 1, -1, $pageCountChange );
3343 } elseif ( !$this->isContentPage() && $nt->isContentPage() ) {
3344 # Now a content page
3345 # Not viewed, edited, adding
3346 $u = new SiteStatsUpdate( 0, 1, + 1, $pageCountChange );
3347 } elseif ( $pageCountChange ) {
3348 # Redirect added
3349 $u = new SiteStatsUpdate( 0, 0, 0, 1 );
3350 } else {
3351 # Nothing special
3352 $u = false;
3353 }
3354 if ( $u ) {
3355 $u->doUpdate();
3356 }
3357
3358 # Update message cache for interface messages
3359 if ( $this->getNamespace() == NS_MEDIAWIKI ) {
3360 # @bug 17860: old article can be deleted, if this the case,
3361 # delete it from message cache
3362 if ( $this->getArticleID() === 0 ) {
3363 MessageCache::singleton()->replace( $this->getDBkey(), false );
3364 } else {
3365 $rev = Revision::newFromTitle( $this );
3366 MessageCache::singleton()->replace( $this->getDBkey(), $rev->getText() );
3367 }
3368 }
3369 if ( $nt->getNamespace() == NS_MEDIAWIKI ) {
3370 $rev = Revision::newFromTitle( $nt );
3371 MessageCache::singleton()->replace( $nt->getDBkey(), $rev->getText() );
3372 }
3373
3374 wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
3375 return true;
3376 }
3377
3378 /**
3379 * Move page to a title which is either a redirect to the
3380 * source page or nonexistent
3381 *
3382 * @param $nt Title the page to move to, which should be a redirect or nonexistent
3383 * @param $reason String The reason for the move
3384 * @param $createRedirect Bool Whether to leave a redirect at the old title. Ignored
3385 * if the user doesn't have the suppressredirect right
3386 */
3387 private function moveToInternal( &$nt, $reason = '', $createRedirect = true ) {
3388 global $wgUser, $wgContLang;
3389
3390 if ( $nt->exists() ) {
3391 $moveOverRedirect = true;
3392 $logType = 'move_redir';
3393 } else {
3394 $moveOverRedirect = false;
3395 $logType = 'move';
3396 }
3397
3398 $redirectSuppressed = !$createRedirect && $wgUser->isAllowed( 'suppressredirect' );
3399
3400 $logEntry = new ManualLogEntry( 'move', $logType );
3401 $logEntry->setPerformer( $wgUser );
3402 $logEntry->setTarget( $this );
3403 $logEntry->setComment( $reason );
3404 $logEntry->setParameters( array(
3405 '4::target' => $nt->getPrefixedText(),
3406 '5::noredir' => $redirectSuppressed ? '1': '0',
3407 ) );
3408
3409 $formatter = LogFormatter::newFromEntry( $logEntry );
3410 $formatter->setContext( RequestContext::newExtraneousContext( $this ) );
3411 $comment = $formatter->getPlainActionText();
3412 if ( $reason ) {
3413 $comment .= wfMsgForContent( 'colon-separator' ) . $reason;
3414 }
3415 # Truncate for whole multibyte characters.
3416 $comment = $wgContLang->truncate( $comment, 255 );
3417
3418 $oldid = $this->getArticleID();
3419 $latest = $this->getLatestRevID();
3420
3421 $dbw = wfGetDB( DB_MASTER );
3422
3423 if ( $moveOverRedirect ) {
3424 $rcts = $dbw->timestamp( $nt->getEarliestRevTime() );
3425
3426 $newid = $nt->getArticleID();
3427 $newns = $nt->getNamespace();
3428 $newdbk = $nt->getDBkey();
3429
3430 # Delete the old redirect. We don't save it to history since
3431 # by definition if we've got here it's rather uninteresting.
3432 # We have to remove it so that the next step doesn't trigger
3433 # a conflict on the unique namespace+title index...
3434 $dbw->delete( 'page', array( 'page_id' => $newid ), __METHOD__ );
3435 if ( !$dbw->cascadingDeletes() ) {
3436 $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
3437
3438 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3439 $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
3440 $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
3441 $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
3442 $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
3443 $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
3444 $dbw->delete( 'iwlinks', array( 'iwl_from' => $newid ), __METHOD__ );
3445 $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
3446 $dbw->delete( 'page_props', array( 'pp_page' => $newid ), __METHOD__ );
3447 }
3448 // If the target page was recently created, it may have an entry in recentchanges still
3449 $dbw->delete( 'recentchanges',
3450 array( 'rc_timestamp' => $rcts, 'rc_namespace' => $newns, 'rc_title' => $newdbk, 'rc_new' => 1 ),
3451 __METHOD__
3452 );
3453 }
3454
3455 # Save a null revision in the page's history notifying of the move
3456 $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
3457 if ( !is_object( $nullRevision ) ) {
3458 throw new MWException( 'No valid null revision produced in ' . __METHOD__ );
3459 }
3460 $nullRevId = $nullRevision->insertOn( $dbw );
3461
3462 $now = wfTimestampNow();
3463 # Change the name of the target page:
3464 $dbw->update( 'page',
3465 /* SET */ array(
3466 'page_touched' => $dbw->timestamp( $now ),
3467 'page_namespace' => $nt->getNamespace(),
3468 'page_title' => $nt->getDBkey(),
3469 'page_latest' => $nullRevId,
3470 ),
3471 /* WHERE */ array( 'page_id' => $oldid ),
3472 __METHOD__
3473 );
3474 $nt->resetArticleID( $oldid );
3475
3476 $article = WikiPage::factory( $nt );
3477 wfRunHooks( 'NewRevisionFromEditComplete',
3478 array( $article, $nullRevision, $latest, $wgUser ) );
3479 $article->setCachedLastEditTime( $now );
3480
3481 # Recreate the redirect, this time in the other direction.
3482 if ( $createRedirect || !$wgUser->isAllowed( 'suppressredirect' ) ) {
3483 $mwRedir = MagicWord::get( 'redirect' );
3484 $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
3485 $redirectArticle = WikiPage::factory( $this );
3486 $newid = $redirectArticle->insertOn( $dbw );
3487 if ( $newid ) { // sanity
3488 $redirectRevision = new Revision( array(
3489 'page' => $newid,
3490 'comment' => $comment,
3491 'text' => $redirectText ) );
3492 $redirectRevision->insertOn( $dbw );
3493 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
3494
3495 wfRunHooks( 'NewRevisionFromEditComplete',
3496 array( $redirectArticle, $redirectRevision, false, $wgUser ) );
3497
3498 # Now, we record the link from the redirect to the new title.
3499 # It should have no other outgoing links...
3500 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
3501 $dbw->insert( 'pagelinks',
3502 array(
3503 'pl_from' => $newid,
3504 'pl_namespace' => $nt->getNamespace(),
3505 'pl_title' => $nt->getDBkey() ),
3506 __METHOD__ );
3507 }
3508 } else {
3509 $this->resetArticleID( 0 );
3510 }
3511
3512 # Log the move
3513 $logid = $logEntry->insert();
3514 $logEntry->publish( $logid );
3515
3516 # Purge caches for old and new titles
3517 if ( $moveOverRedirect ) {
3518 # A simple purge is enough when moving over a redirect
3519 $nt->purgeSquid();
3520 } else {
3521 # Purge caches as per article creation, including any pages that link to this title
3522 Article::onArticleCreate( $nt );
3523 }
3524 $this->purgeSquid();
3525 }
3526
3527 /**
3528 * Move this page's subpages to be subpages of $nt
3529 *
3530 * @param $nt Title Move target
3531 * @param $auth bool Whether $wgUser's permissions should be checked
3532 * @param $reason string The reason for the move
3533 * @param $createRedirect bool Whether to create redirects from the old subpages to
3534 * the new ones Ignored if the user doesn't have the 'suppressredirect' right
3535 * @return mixed array with old page titles as keys, and strings (new page titles) or
3536 * arrays (errors) as values, or an error array with numeric indices if no pages
3537 * were moved
3538 */
3539 public function moveSubpages( $nt, $auth = true, $reason = '', $createRedirect = true ) {
3540 global $wgMaximumMovedPages;
3541 // Check permissions
3542 if ( !$this->userCan( 'move-subpages' ) ) {
3543 return array( 'cant-move-subpages' );
3544 }
3545 // Do the source and target namespaces support subpages?
3546 if ( !MWNamespace::hasSubpages( $this->getNamespace() ) ) {
3547 return array( 'namespace-nosubpages',
3548 MWNamespace::getCanonicalName( $this->getNamespace() ) );
3549 }
3550 if ( !MWNamespace::hasSubpages( $nt->getNamespace() ) ) {
3551 return array( 'namespace-nosubpages',
3552 MWNamespace::getCanonicalName( $nt->getNamespace() ) );
3553 }
3554
3555 $subpages = $this->getSubpages( $wgMaximumMovedPages + 1 );
3556 $retval = array();
3557 $count = 0;
3558 foreach ( $subpages as $oldSubpage ) {
3559 $count++;
3560 if ( $count > $wgMaximumMovedPages ) {
3561 $retval[$oldSubpage->getPrefixedTitle()] =
3562 array( 'movepage-max-pages',
3563 $wgMaximumMovedPages );
3564 break;
3565 }
3566
3567 // We don't know whether this function was called before
3568 // or after moving the root page, so check both
3569 // $this and $nt
3570 if ( $oldSubpage->getArticleId() == $this->getArticleId() ||
3571 $oldSubpage->getArticleID() == $nt->getArticleId() )
3572 {
3573 // When moving a page to a subpage of itself,
3574 // don't move it twice
3575 continue;
3576 }
3577 $newPageName = preg_replace(
3578 '#^' . preg_quote( $this->getDBkey(), '#' ) . '#',
3579 StringUtils::escapeRegexReplacement( $nt->getDBkey() ), # bug 21234
3580 $oldSubpage->getDBkey() );
3581 if ( $oldSubpage->isTalkPage() ) {
3582 $newNs = $nt->getTalkPage()->getNamespace();
3583 } else {
3584 $newNs = $nt->getSubjectPage()->getNamespace();
3585 }
3586 # Bug 14385: we need makeTitleSafe because the new page names may
3587 # be longer than 255 characters.
3588 $newSubpage = Title::makeTitleSafe( $newNs, $newPageName );
3589
3590 $success = $oldSubpage->moveTo( $newSubpage, $auth, $reason, $createRedirect );
3591 if ( $success === true ) {
3592 $retval[$oldSubpage->getPrefixedText()] = $newSubpage->getPrefixedText();
3593 } else {
3594 $retval[$oldSubpage->getPrefixedText()] = $success;
3595 }
3596 }
3597 return $retval;
3598 }
3599
3600 /**
3601 * Checks if this page is just a one-rev redirect.
3602 * Adds lock, so don't use just for light purposes.
3603 *
3604 * @return Bool
3605 */
3606 public function isSingleRevRedirect() {
3607 $dbw = wfGetDB( DB_MASTER );
3608 # Is it a redirect?
3609 $row = $dbw->selectRow( 'page',
3610 array( 'page_is_redirect', 'page_latest', 'page_id' ),
3611 $this->pageCond(),
3612 __METHOD__,
3613 array( 'FOR UPDATE' )
3614 );
3615 # Cache some fields we may want
3616 $this->mArticleID = $row ? intval( $row->page_id ) : 0;
3617 $this->mRedirect = $row ? (bool)$row->page_is_redirect : false;
3618 $this->mLatestID = $row ? intval( $row->page_latest ) : false;
3619 if ( !$this->mRedirect ) {
3620 return false;
3621 }
3622 # Does the article have a history?
3623 $row = $dbw->selectField( array( 'page', 'revision' ),
3624 'rev_id',
3625 array( 'page_namespace' => $this->getNamespace(),
3626 'page_title' => $this->getDBkey(),
3627 'page_id=rev_page',
3628 'page_latest != rev_id'
3629 ),
3630 __METHOD__,
3631 array( 'FOR UPDATE' )
3632 );
3633 # Return true if there was no history
3634 return ( $row === false );
3635 }
3636
3637 /**
3638 * Checks if $this can be moved to a given Title
3639 * - Selects for update, so don't call it unless you mean business
3640 *
3641 * @param $nt Title the new title to check
3642 * @return Bool
3643 */
3644 public function isValidMoveTarget( $nt ) {
3645 # Is it an existing file?
3646 if ( $nt->getNamespace() == NS_FILE ) {
3647 $file = wfLocalFile( $nt );
3648 if ( $file->exists() ) {
3649 wfDebug( __METHOD__ . ": file exists\n" );
3650 return false;
3651 }
3652 }
3653 # Is it a redirect with no history?
3654 if ( !$nt->isSingleRevRedirect() ) {
3655 wfDebug( __METHOD__ . ": not a one-rev redirect\n" );
3656 return false;
3657 }
3658 # Get the article text
3659 $rev = Revision::newFromTitle( $nt );
3660 if( !is_object( $rev ) ){
3661 return false;
3662 }
3663 $text = $rev->getText();
3664 # Does the redirect point to the source?
3665 # Or is it a broken self-redirect, usually caused by namespace collisions?
3666 $m = array();
3667 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $text, $m ) ) {
3668 $redirTitle = Title::newFromText( $m[1] );
3669 if ( !is_object( $redirTitle ) ||
3670 ( $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() &&
3671 $redirTitle->getPrefixedDBkey() != $nt->getPrefixedDBkey() ) ) {
3672 wfDebug( __METHOD__ . ": redirect points to other page\n" );
3673 return false;
3674 }
3675 } else {
3676 # Fail safe
3677 wfDebug( __METHOD__ . ": failsafe\n" );
3678 return false;
3679 }
3680 return true;
3681 }
3682
3683 /**
3684 * Can this title be added to a user's watchlist?
3685 *
3686 * @return Bool TRUE or FALSE
3687 */
3688 public function isWatchable() {
3689 return !$this->isExternal() && MWNamespace::isWatchable( $this->getNamespace() );
3690 }
3691
3692 /**
3693 * Get categories to which this Title belongs and return an array of
3694 * categories' names.
3695 *
3696 * @return Array of parents in the form:
3697 * $parent => $currentarticle
3698 */
3699 public function getParentCategories() {
3700 global $wgContLang;
3701
3702 $data = array();
3703
3704 $titleKey = $this->getArticleId();
3705
3706 if ( $titleKey === 0 ) {
3707 return $data;
3708 }
3709
3710 $dbr = wfGetDB( DB_SLAVE );
3711
3712 $res = $dbr->select( 'categorylinks', '*',
3713 array(
3714 'cl_from' => $titleKey,
3715 ),
3716 __METHOD__,
3717 array()
3718 );
3719
3720 if ( $dbr->numRows( $res ) > 0 ) {
3721 foreach ( $res as $row ) {
3722 // $data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$row->cl_to);
3723 $data[$wgContLang->getNSText( NS_CATEGORY ) . ':' . $row->cl_to] = $this->getFullText();
3724 }
3725 }
3726 return $data;
3727 }
3728
3729 /**
3730 * Get a tree of parent categories
3731 *
3732 * @param $children Array with the children in the keys, to check for circular refs
3733 * @return Array Tree of parent categories
3734 */
3735 public function getParentCategoryTree( $children = array() ) {
3736 $stack = array();
3737 $parents = $this->getParentCategories();
3738
3739 if ( $parents ) {
3740 foreach ( $parents as $parent => $current ) {
3741 if ( array_key_exists( $parent, $children ) ) {
3742 # Circular reference
3743 $stack[$parent] = array();
3744 } else {
3745 $nt = Title::newFromText( $parent );
3746 if ( $nt ) {
3747 $stack[$parent] = $nt->getParentCategoryTree( $children + array( $parent => 1 ) );
3748 }
3749 }
3750 }
3751 }
3752
3753 return $stack;
3754 }
3755
3756 /**
3757 * Get an associative array for selecting this title from
3758 * the "page" table
3759 *
3760 * @return Array suitable for the $where parameter of DB::select()
3761 */
3762 public function pageCond() {
3763 if ( $this->mArticleID > 0 ) {
3764 // PK avoids secondary lookups in InnoDB, shouldn't hurt other DBs
3765 return array( 'page_id' => $this->mArticleID );
3766 } else {
3767 return array( 'page_namespace' => $this->mNamespace, 'page_title' => $this->mDbkeyform );
3768 }
3769 }
3770
3771 /**
3772 * Get the revision ID of the previous revision
3773 *
3774 * @param $revId Int Revision ID. Get the revision that was before this one.
3775 * @param $flags Int Title::GAID_FOR_UPDATE
3776 * @return Int|Bool Old revision ID, or FALSE if none exists
3777 */
3778 public function getPreviousRevisionID( $revId, $flags = 0 ) {
3779 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3780 return $db->selectField( 'revision', 'rev_id',
3781 array(
3782 'rev_page' => $this->getArticleId( $flags ),
3783 'rev_id < ' . intval( $revId )
3784 ),
3785 __METHOD__,
3786 array( 'ORDER BY' => 'rev_id DESC' )
3787 );
3788 }
3789
3790 /**
3791 * Get the revision ID of the next revision
3792 *
3793 * @param $revId Int Revision ID. Get the revision that was after this one.
3794 * @param $flags Int Title::GAID_FOR_UPDATE
3795 * @return Int|Bool Next revision ID, or FALSE if none exists
3796 */
3797 public function getNextRevisionID( $revId, $flags = 0 ) {
3798 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3799 return $db->selectField( 'revision', 'rev_id',
3800 array(
3801 'rev_page' => $this->getArticleId( $flags ),
3802 'rev_id > ' . intval( $revId )
3803 ),
3804 __METHOD__,
3805 array( 'ORDER BY' => 'rev_id' )
3806 );
3807 }
3808
3809 /**
3810 * Get the first revision of the page
3811 *
3812 * @param $flags Int Title::GAID_FOR_UPDATE
3813 * @return Revision|Null if page doesn't exist
3814 */
3815 public function getFirstRevision( $flags = 0 ) {
3816 $pageId = $this->getArticleId( $flags );
3817 if ( $pageId ) {
3818 $db = ( $flags & self::GAID_FOR_UPDATE ) ? wfGetDB( DB_MASTER ) : wfGetDB( DB_SLAVE );
3819 $row = $db->selectRow( 'revision', '*',
3820 array( 'rev_page' => $pageId ),
3821 __METHOD__,
3822 array( 'ORDER BY' => 'rev_timestamp ASC', 'LIMIT' => 1 )
3823 );
3824 if ( $row ) {
3825 return new Revision( $row );
3826 }
3827 }
3828 return null;
3829 }
3830
3831 /**
3832 * Get the oldest revision timestamp of this page
3833 *
3834 * @param $flags Int Title::GAID_FOR_UPDATE
3835 * @return String: MW timestamp
3836 */
3837 public function getEarliestRevTime( $flags = 0 ) {
3838 $rev = $this->getFirstRevision( $flags );
3839 return $rev ? $rev->getTimestamp() : null;
3840 }
3841
3842 /**
3843 * Check if this is a new page
3844 *
3845 * @return bool
3846 */
3847 public function isNewPage() {
3848 $dbr = wfGetDB( DB_SLAVE );
3849 return (bool)$dbr->selectField( 'page', 'page_is_new', $this->pageCond(), __METHOD__ );
3850 }
3851
3852 /**
3853 * Get the number of revisions between the given revision.
3854 * Used for diffs and other things that really need it.
3855 *
3856 * @param $old int|Revision Old revision or rev ID (first before range)
3857 * @param $new int|Revision New revision or rev ID (first after range)
3858 * @return Int Number of revisions between these revisions.
3859 */
3860 public function countRevisionsBetween( $old, $new ) {
3861 if ( !( $old instanceof Revision ) ) {
3862 $old = Revision::newFromTitle( $this, (int)$old );
3863 }
3864 if ( !( $new instanceof Revision ) ) {
3865 $new = Revision::newFromTitle( $this, (int)$new );
3866 }
3867 if ( !$old || !$new ) {
3868 return 0; // nothing to compare
3869 }
3870 $dbr = wfGetDB( DB_SLAVE );
3871 return (int)$dbr->selectField( 'revision', 'count(*)',
3872 array(
3873 'rev_page' => $this->getArticleId(),
3874 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3875 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3876 ),
3877 __METHOD__
3878 );
3879 }
3880
3881 /**
3882 * Get the number of authors between the given revision IDs.
3883 * Used for diffs and other things that really need it.
3884 *
3885 * @param $old int|Revision Old revision or rev ID (first before range)
3886 * @param $new int|Revision New revision or rev ID (first after range)
3887 * @param $limit Int Maximum number of authors
3888 * @return Int Number of revision authors between these revisions.
3889 */
3890 public function countAuthorsBetween( $old, $new, $limit ) {
3891 if ( !( $old instanceof Revision ) ) {
3892 $old = Revision::newFromTitle( $this, (int)$old );
3893 }
3894 if ( !( $new instanceof Revision ) ) {
3895 $new = Revision::newFromTitle( $this, (int)$new );
3896 }
3897 if ( !$old || !$new ) {
3898 return 0; // nothing to compare
3899 }
3900 $dbr = wfGetDB( DB_SLAVE );
3901 $res = $dbr->select( 'revision', 'DISTINCT rev_user_text',
3902 array(
3903 'rev_page' => $this->getArticleID(),
3904 'rev_timestamp > ' . $dbr->addQuotes( $dbr->timestamp( $old->getTimestamp() ) ),
3905 'rev_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( $new->getTimestamp() ) )
3906 ), __METHOD__,
3907 array( 'LIMIT' => $limit + 1 ) // add one so caller knows it was truncated
3908 );
3909 return (int)$dbr->numRows( $res );
3910 }
3911
3912 /**
3913 * Compare with another title.
3914 *
3915 * @param $title Title
3916 * @return Bool
3917 */
3918 public function equals( Title $title ) {
3919 // Note: === is necessary for proper matching of number-like titles.
3920 return $this->getInterwiki() === $title->getInterwiki()
3921 && $this->getNamespace() == $title->getNamespace()
3922 && $this->getDBkey() === $title->getDBkey();
3923 }
3924
3925 /**
3926 * Check if this title is a subpage of another title
3927 *
3928 * @param $title Title
3929 * @return Bool
3930 */
3931 public function isSubpageOf( Title $title ) {
3932 return $this->getInterwiki() === $title->getInterwiki()
3933 && $this->getNamespace() == $title->getNamespace()
3934 && strpos( $this->getDBkey(), $title->getDBkey() . '/' ) === 0;
3935 }
3936
3937 /**
3938 * Callback for usort() to do title sorts by (namespace, title)
3939 *
3940 * @param $a Title
3941 * @param $b Title
3942 *
3943 * @return Integer: result of string comparison, or namespace comparison
3944 */
3945 public static function compare( $a, $b ) {
3946 if ( $a->getNamespace() == $b->getNamespace() ) {
3947 return strcmp( $a->getText(), $b->getText() );
3948 } else {
3949 return $a->getNamespace() - $b->getNamespace();
3950 }
3951 }
3952
3953 /**
3954 * Return a string representation of this title
3955 *
3956 * @return String representation of this title
3957 */
3958 public function __toString() {
3959 return $this->getPrefixedText();
3960 }
3961
3962 /**
3963 * Check if page exists. For historical reasons, this function simply
3964 * checks for the existence of the title in the page table, and will
3965 * thus return false for interwiki links, special pages and the like.
3966 * If you want to know if a title can be meaningfully viewed, you should
3967 * probably call the isKnown() method instead.
3968 *
3969 * @return Bool
3970 */
3971 public function exists() {
3972 return $this->getArticleId() != 0;
3973 }
3974
3975 /**
3976 * Should links to this title be shown as potentially viewable (i.e. as
3977 * "bluelinks"), even if there's no record by this title in the page
3978 * table?
3979 *
3980 * This function is semi-deprecated for public use, as well as somewhat
3981 * misleadingly named. You probably just want to call isKnown(), which
3982 * calls this function internally.
3983 *
3984 * (ISSUE: Most of these checks are cheap, but the file existence check
3985 * can potentially be quite expensive. Including it here fixes a lot of
3986 * existing code, but we might want to add an optional parameter to skip
3987 * it and any other expensive checks.)
3988 *
3989 * @return Bool
3990 */
3991 public function isAlwaysKnown() {
3992 if ( $this->mInterwiki != '' ) {
3993 return true; // any interwiki link might be viewable, for all we know
3994 }
3995 switch( $this->mNamespace ) {
3996 case NS_MEDIA:
3997 case NS_FILE:
3998 // file exists, possibly in a foreign repo
3999 return (bool)wfFindFile( $this );
4000 case NS_SPECIAL:
4001 // valid special page
4002 return SpecialPageFactory::exists( $this->getDBkey() );
4003 case NS_MAIN:
4004 // selflink, possibly with fragment
4005 return $this->mDbkeyform == '';
4006 case NS_MEDIAWIKI:
4007 // known system message
4008 return $this->hasSourceText() !== false;
4009 default:
4010 return false;
4011 }
4012 }
4013
4014 /**
4015 * Does this title refer to a page that can (or might) be meaningfully
4016 * viewed? In particular, this function may be used to determine if
4017 * links to the title should be rendered as "bluelinks" (as opposed to
4018 * "redlinks" to non-existent pages).
4019 *
4020 * @return Bool
4021 */
4022 public function isKnown() {
4023 return $this->isAlwaysKnown() || $this->exists();
4024 }
4025
4026 /**
4027 * Does this page have source text?
4028 *
4029 * @return Boolean
4030 */
4031 public function hasSourceText() {
4032 if ( $this->exists() ) {
4033 return true;
4034 }
4035
4036 if ( $this->mNamespace == NS_MEDIAWIKI ) {
4037 // If the page doesn't exist but is a known system message, default
4038 // message content will be displayed, same for language subpages-
4039 // Use always content language to avoid loading hundreds of languages
4040 // to get the link color.
4041 global $wgContLang;
4042 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4043 $message = wfMessage( $name )->inLanguage( $wgContLang )->useDatabase( false );
4044 return $message->exists();
4045 }
4046
4047 return false;
4048 }
4049
4050 /**
4051 * Get the default message text or false if the message doesn't exist
4052 *
4053 * @return String or false
4054 */
4055 public function getDefaultMessageText() {
4056 global $wgContLang;
4057
4058 if ( $this->getNamespace() != NS_MEDIAWIKI ) { // Just in case
4059 return false;
4060 }
4061
4062 list( $name, $lang ) = MessageCache::singleton()->figureMessage( $wgContLang->lcfirst( $this->getText() ) );
4063 $message = wfMessage( $name )->inLanguage( $lang )->useDatabase( false );
4064
4065 if ( $message->exists() ) {
4066 return $message->plain();
4067 } else {
4068 return false;
4069 }
4070 }
4071
4072 /**
4073 * Is this in a namespace that allows actual pages?
4074 *
4075 * @return Bool
4076 * @internal note -- uses hardcoded namespace index instead of constants
4077 */
4078 public function canExist() {
4079 return $this->mNamespace >= 0 && $this->mNamespace != NS_MEDIA;
4080 }
4081
4082 /**
4083 * Update page_touched timestamps and send squid purge messages for
4084 * pages linking to this title. May be sent to the job queue depending
4085 * on the number of links. Typically called on create and delete.
4086 */
4087 public function touchLinks() {
4088 $u = new HTMLCacheUpdate( $this, 'pagelinks' );
4089 $u->doUpdate();
4090
4091 if ( $this->getNamespace() == NS_CATEGORY ) {
4092 $u = new HTMLCacheUpdate( $this, 'categorylinks' );
4093 $u->doUpdate();
4094 }
4095 }
4096
4097 /**
4098 * Get the last touched timestamp
4099 *
4100 * @param $db DatabaseBase: optional db
4101 * @return String last-touched timestamp
4102 */
4103 public function getTouched( $db = null ) {
4104 $db = isset( $db ) ? $db : wfGetDB( DB_SLAVE );
4105 $touched = $db->selectField( 'page', 'page_touched', $this->pageCond(), __METHOD__ );
4106 return $touched;
4107 }
4108
4109 /**
4110 * Get the timestamp when this page was updated since the user last saw it.
4111 *
4112 * @param $user User
4113 * @return String|Null
4114 */
4115 public function getNotificationTimestamp( $user = null ) {
4116 global $wgUser, $wgShowUpdatedMarker;
4117 // Assume current user if none given
4118 if ( !$user ) {
4119 $user = $wgUser;
4120 }
4121 // Check cache first
4122 $uid = $user->getId();
4123 // avoid isset here, as it'll return false for null entries
4124 if ( array_key_exists( $uid, $this->mNotificationTimestamp ) ) {
4125 return $this->mNotificationTimestamp[$uid];
4126 }
4127 if ( !$uid || !$wgShowUpdatedMarker ) {
4128 return $this->mNotificationTimestamp[$uid] = false;
4129 }
4130 // Don't cache too much!
4131 if ( count( $this->mNotificationTimestamp ) >= self::CACHE_MAX ) {
4132 $this->mNotificationTimestamp = array();
4133 }
4134 $dbr = wfGetDB( DB_SLAVE );
4135 $this->mNotificationTimestamp[$uid] = $dbr->selectField( 'watchlist',
4136 'wl_notificationtimestamp',
4137 array( 'wl_namespace' => $this->getNamespace(),
4138 'wl_title' => $this->getDBkey(),
4139 'wl_user' => $user->getId()
4140 ),
4141 __METHOD__
4142 );
4143 return $this->mNotificationTimestamp[$uid];
4144 }
4145
4146 /**
4147 * Generate strings used for xml 'id' names in monobook tabs
4148 *
4149 * @param $prepend string defaults to 'nstab-'
4150 * @return String XML 'id' name
4151 */
4152 public function getNamespaceKey( $prepend = 'nstab-' ) {
4153 global $wgContLang;
4154 // Gets the subject namespace if this title
4155 $namespace = MWNamespace::getSubject( $this->getNamespace() );
4156 // Checks if cononical namespace name exists for namespace
4157 if ( MWNamespace::exists( $this->getNamespace() ) ) {
4158 // Uses canonical namespace name
4159 $namespaceKey = MWNamespace::getCanonicalName( $namespace );
4160 } else {
4161 // Uses text of namespace
4162 $namespaceKey = $this->getSubjectNsText();
4163 }
4164 // Makes namespace key lowercase
4165 $namespaceKey = $wgContLang->lc( $namespaceKey );
4166 // Uses main
4167 if ( $namespaceKey == '' ) {
4168 $namespaceKey = 'main';
4169 }
4170 // Changes file to image for backwards compatibility
4171 if ( $namespaceKey == 'file' ) {
4172 $namespaceKey = 'image';
4173 }
4174 return $prepend . $namespaceKey;
4175 }
4176
4177 /**
4178 * Returns true if this is a special page.
4179 *
4180 * @return boolean
4181 */
4182 public function isSpecialPage() {
4183 return $this->getNamespace() == NS_SPECIAL;
4184 }
4185
4186 /**
4187 * Returns true if this title resolves to the named special page
4188 *
4189 * @param $name String The special page name
4190 * @return boolean
4191 */
4192 public function isSpecial( $name ) {
4193 if ( $this->isSpecialPage() ) {
4194 list( $thisName, /* $subpage */ ) = SpecialPageFactory::resolveAlias( $this->getDBkey() );
4195 if ( $name == $thisName ) {
4196 return true;
4197 }
4198 }
4199 return false;
4200 }
4201
4202 /**
4203 * If the Title refers to a special page alias which is not the local default, resolve
4204 * the alias, and localise the name as necessary. Otherwise, return $this
4205 *
4206 * @return Title
4207 */
4208 public function fixSpecialName() {
4209 if ( $this->isSpecialPage() ) {
4210 list( $canonicalName, $par ) = SpecialPageFactory::resolveAlias( $this->mDbkeyform );
4211 if ( $canonicalName ) {
4212 $localName = SpecialPageFactory::getLocalNameFor( $canonicalName, $par );
4213 if ( $localName != $this->mDbkeyform ) {
4214 return Title::makeTitle( NS_SPECIAL, $localName );
4215 }
4216 }
4217 }
4218 return $this;
4219 }
4220
4221 /**
4222 * Is this Title in a namespace which contains content?
4223 * In other words, is this a content page, for the purposes of calculating
4224 * statistics, etc?
4225 *
4226 * @return Boolean
4227 */
4228 public function isContentPage() {
4229 return MWNamespace::isContent( $this->getNamespace() );
4230 }
4231
4232 /**
4233 * Get all extant redirects to this Title
4234 *
4235 * @param $ns Int|Null Single namespace to consider; NULL to consider all namespaces
4236 * @return Array of Title redirects to this title
4237 */
4238 public function getRedirectsHere( $ns = null ) {
4239 $redirs = array();
4240
4241 $dbr = wfGetDB( DB_SLAVE );
4242 $where = array(
4243 'rd_namespace' => $this->getNamespace(),
4244 'rd_title' => $this->getDBkey(),
4245 'rd_from = page_id'
4246 );
4247 if ( !is_null( $ns ) ) {
4248 $where['page_namespace'] = $ns;
4249 }
4250
4251 $res = $dbr->select(
4252 array( 'redirect', 'page' ),
4253 array( 'page_namespace', 'page_title' ),
4254 $where,
4255 __METHOD__
4256 );
4257
4258 foreach ( $res as $row ) {
4259 $redirs[] = self::newFromRow( $row );
4260 }
4261 return $redirs;
4262 }
4263
4264 /**
4265 * Check if this Title is a valid redirect target
4266 *
4267 * @return Bool
4268 */
4269 public function isValidRedirectTarget() {
4270 global $wgInvalidRedirectTargets;
4271
4272 // invalid redirect targets are stored in a global array, but explicity disallow Userlogout here
4273 if ( $this->isSpecial( 'Userlogout' ) ) {
4274 return false;
4275 }
4276
4277 foreach ( $wgInvalidRedirectTargets as $target ) {
4278 if ( $this->isSpecial( $target ) ) {
4279 return false;
4280 }
4281 }
4282
4283 return true;
4284 }
4285
4286 /**
4287 * Get a backlink cache object
4288 *
4289 * @return BacklinkCache
4290 */
4291 function getBacklinkCache() {
4292 if ( is_null( $this->mBacklinkCache ) ) {
4293 $this->mBacklinkCache = new BacklinkCache( $this );
4294 }
4295 return $this->mBacklinkCache;
4296 }
4297
4298 /**
4299 * Whether the magic words __INDEX__ and __NOINDEX__ function for this page.
4300 *
4301 * @return Boolean
4302 */
4303 public function canUseNoindex() {
4304 global $wgContentNamespaces, $wgExemptFromUserRobotsControl;
4305
4306 $bannedNamespaces = is_null( $wgExemptFromUserRobotsControl )
4307 ? $wgContentNamespaces
4308 : $wgExemptFromUserRobotsControl;
4309
4310 return !in_array( $this->mNamespace, $bannedNamespaces );
4311
4312 }
4313
4314 /**
4315 * Returns restriction types for the current Title
4316 *
4317 * @return array applicable restriction types
4318 */
4319 public function getRestrictionTypes() {
4320 if ( $this->isSpecialPage() ) {
4321 return array();
4322 }
4323
4324 $types = self::getFilteredRestrictionTypes( $this->exists() );
4325
4326 if ( $this->getNamespace() != NS_FILE ) {
4327 # Remove the upload restriction for non-file titles
4328 $types = array_diff( $types, array( 'upload' ) );
4329 }
4330
4331 wfRunHooks( 'TitleGetRestrictionTypes', array( $this, &$types ) );
4332
4333 wfDebug( __METHOD__ . ': applicable restriction types for ' .
4334 $this->getPrefixedText() . ' are ' . implode( ',', $types ) . "\n" );
4335
4336 return $types;
4337 }
4338 /**
4339 * Get a filtered list of all restriction types supported by this wiki.
4340 * @param bool $exists True to get all restriction types that apply to
4341 * titles that do exist, False for all restriction types that apply to
4342 * titles that do not exist
4343 * @return array
4344 */
4345 public static function getFilteredRestrictionTypes( $exists = true ) {
4346 global $wgRestrictionTypes;
4347 $types = $wgRestrictionTypes;
4348 if ( $exists ) {
4349 # Remove the create restriction for existing titles
4350 $types = array_diff( $types, array( 'create' ) );
4351 } else {
4352 # Only the create and upload restrictions apply to non-existing titles
4353 $types = array_intersect( $types, array( 'create', 'upload' ) );
4354 }
4355 return $types;
4356 }
4357
4358 /**
4359 * Returns the raw sort key to be used for categories, with the specified
4360 * prefix. This will be fed to Collation::getSortKey() to get a
4361 * binary sortkey that can be used for actual sorting.
4362 *
4363 * @param $prefix string The prefix to be used, specified using
4364 * {{defaultsort:}} or like [[Category:Foo|prefix]]. Empty for no
4365 * prefix.
4366 * @return string
4367 */
4368 public function getCategorySortkey( $prefix = '' ) {
4369 $unprefixed = $this->getText();
4370
4371 // Anything that uses this hook should only depend
4372 // on the Title object passed in, and should probably
4373 // tell the users to run updateCollations.php --force
4374 // in order to re-sort existing category relations.
4375 wfRunHooks( 'GetDefaultSortkey', array( $this, &$unprefixed ) );
4376 if ( $prefix !== '' ) {
4377 # Separate with a line feed, so the unprefixed part is only used as
4378 # a tiebreaker when two pages have the exact same prefix.
4379 # In UCA, tab is the only character that can sort above LF
4380 # so we strip both of them from the original prefix.
4381 $prefix = strtr( $prefix, "\n\t", ' ' );
4382 return "$prefix\n$unprefixed";
4383 }
4384 return $unprefixed;
4385 }
4386
4387 /**
4388 * Get the language in which the content of this page is written.
4389 * Defaults to $wgContLang, but in certain cases it can be e.g.
4390 * $wgLang (such as special pages, which are in the user language).
4391 *
4392 * @since 1.18
4393 * @return object Language
4394 */
4395 public function getPageLanguage() {
4396 global $wgLang;
4397 if ( $this->isSpecialPage() ) {
4398 // special pages are in the user language
4399 return $wgLang;
4400 } elseif ( $this->isCssOrJsPage() ) {
4401 // css/js should always be LTR and is, in fact, English
4402 return wfGetLangObj( 'en' );
4403 } elseif ( $this->getNamespace() == NS_MEDIAWIKI ) {
4404 // Parse mediawiki messages with correct target language
4405 list( /* $unused */, $lang ) = MessageCache::singleton()->figureMessage( $this->getText() );
4406 return wfGetLangObj( $lang );
4407 }
4408 global $wgContLang;
4409 // If nothing special, it should be in the wiki content language
4410 $pageLang = $wgContLang;
4411 // Hook at the end because we don't want to override the above stuff
4412 wfRunHooks( 'PageContentLanguage', array( $this, &$pageLang, $wgLang ) );
4413 return wfGetLangObj( $pageLang );
4414 }
4415 }