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