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