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