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