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