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