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