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