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