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