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