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