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