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