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