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