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