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