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