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