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