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