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