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