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