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