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