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