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