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