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