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