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