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