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