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