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