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