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