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