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