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