2204e601514a0923775b104c8a2237404de34654
[lhc/web/wiklou.git] / includes / Title.php
1 <?php
2 /**
3 * See title.txt
4 *
5 * @package MediaWiki
6 */
7
8 require_once( 'normal/UtfNormal.php' );
9
10 $wgTitleInterwikiCache = array();
11 define ( 'GAID_FOR_UPDATE', 1 );
12
13 # Title::newFromTitle maintains a cache to avoid
14 # expensive re-normalization of commonly used titles.
15 # On a batch operation this can become a memory leak
16 # if not bounded. After hitting this many titles,
17 # reset the cache.
18 define( 'MW_TITLECACHE_MAX', 1000 );
19
20 /**
21 * Title class
22 * - Represents a title, which may contain an interwiki designation or namespace
23 * - Can fetch various kinds of data from the database, albeit inefficiently.
24 *
25 * @package MediaWiki
26 */
27 class Title {
28 /**
29 * All member variables should be considered private
30 * Please use the accessor functions
31 */
32
33 /**#@+
34 * @access private
35 */
36
37 var $mTextform; # Text form (spaces not underscores) of the main part
38 var $mUrlform; # URL-encoded form of the main part
39 var $mDbkeyform; # Main part with underscores
40 var $mNamespace; # Namespace index, i.e. one of the NS_xxxx constants
41 var $mInterwiki; # Interwiki prefix (or null string)
42 var $mFragment; # Title fragment (i.e. the bit after the #)
43 var $mArticleID; # Article ID, fetched from the link cache on demand
44 var $mRestrictions; # Array of groups allowed to edit this article
45 # Only null or "sysop" are supported
46 var $mRestrictionsLoaded; # Boolean for initialisation on demand
47 var $mPrefixedText; # Text form including namespace/interwiki, initialised on demand
48 var $mDefaultNamespace; # Namespace index when there is no namespace
49 # Zero except in {{transclusion}} tags
50 var $mWatched; # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
51 /**#@-*/
52
53
54 /**
55 * Constructor
56 * @access private
57 */
58 /* private */ function Title() {
59 $this->mInterwiki = $this->mUrlform =
60 $this->mTextform = $this->mDbkeyform = '';
61 $this->mArticleID = -1;
62 $this->mNamespace = NS_MAIN;
63 $this->mRestrictionsLoaded = false;
64 $this->mRestrictions = array();
65 # Dont change the following, NS_MAIN is hardcoded in several place
66 # See bug #696
67 $this->mDefaultNamespace = NS_MAIN;
68 $this->mWatched = NULL;
69 }
70
71 /**
72 * Create a new Title from a prefixed DB key
73 * @param string $key The database key, which has underscores
74 * instead of spaces, possibly including namespace and
75 * interwiki prefixes
76 * @return Title the new object, or NULL on an error
77 * @static
78 * @access public
79 */
80 /* static */ function newFromDBkey( $key ) {
81 $t = new Title();
82 $t->mDbkeyform = $key;
83 if( $t->secureAndSplit() )
84 return $t;
85 else
86 return NULL;
87 }
88
89 /**
90 * Create a new Title from text, such as what one would
91 * find in a link. Decodes any HTML entities in the text.
92 *
93 * @param string $text the link text; spaces, prefixes,
94 * and an initial ':' indicating the main namespace
95 * are accepted
96 * @param int $defaultNamespace the namespace to use if
97 * none is specified by a prefix
98 * @return Title the new object, or NULL on an error
99 * @static
100 * @access public
101 */
102 function &newFromText( $text, $defaultNamespace = NS_MAIN ) {
103 $fname = 'Title::newFromText';
104 wfProfileIn( $fname );
105
106 if( is_object( $text ) ) {
107 wfDebugDieBacktrace( 'Title::newFromText given an object' );
108 }
109
110 /**
111 * Wiki pages often contain multiple links to the same page.
112 * Title normalization and parsing can become expensive on
113 * pages with many links, so we can save a little time by
114 * caching them.
115 *
116 * In theory these are value objects and won't get changed...
117 */
118 static $titleCache = array();
119 if( $defaultNamespace == NS_MAIN && isset( $titleCache[$text] ) ) {
120 wfProfileOut( $fname );
121 return $titleCache[$text];
122 }
123
124 /**
125 * Convert things like &eacute; into real text...
126 */
127 global $wgInputEncoding;
128 $filteredText = do_html_entity_decode( $text, ENT_COMPAT, $wgInputEncoding );
129
130 /**
131 * Convert things like &#257; or &#x3017; into real text...
132 * WARNING: Not friendly to internal links on a latin-1 wiki.
133 */
134 $filteredText = wfMungeToUtf8( $filteredText );
135
136 # What was this for? TS 2004-03-03
137 # $text = urldecode( $text );
138
139 $t =& new Title();
140 $t->mDbkeyform = str_replace( ' ', '_', $filteredText );
141 $t->mDefaultNamespace = $defaultNamespace;
142
143 if( $t->secureAndSplit() ) {
144 if( $defaultNamespace == NS_MAIN ) {
145 if( count( $titleCache ) >= MW_TITLECACHE_MAX ) {
146 # Avoid memory leaks on mass operations...
147 $titleCache = array();
148 }
149 $titleCache[$text] =& $t;
150 }
151 wfProfileOut( $fname );
152 return $t;
153 } else {
154 wfProfileOut( $fname );
155 return NULL;
156 }
157 }
158
159 /**
160 * Create a new Title from URL-encoded text. Ensures that
161 * the given title's length does not exceed the maximum.
162 * @param string $url the title, as might be taken from a URL
163 * @return Title the new object, or NULL on an error
164 * @static
165 * @access public
166 */
167 function newFromURL( $url ) {
168 global $wgLang, $wgServer;
169 $t = new Title();
170
171 # For compatibility with old buggy URLs. "+" is not valid in titles,
172 # but some URLs used it as a space replacement and they still come
173 # from some external search tools.
174 $s = str_replace( '+', ' ', $url );
175
176 $t->mDbkeyform = str_replace( ' ', '_', $s );
177 if( $t->secureAndSplit() ) {
178 return $t;
179 } else {
180 return NULL;
181 }
182 }
183
184 /**
185 * Create a new Title from an article ID
186 *
187 * @todo This is inefficiently implemented, the page row is requested
188 * but not used for anything else
189 *
190 * @param int $id the page_id corresponding to the Title to create
191 * @return Title the new object, or NULL on an error
192 * @access public
193 * @static
194 */
195 function newFromID( $id ) {
196 $fname = 'Title::newFromID';
197 $dbr =& wfGetDB( DB_SLAVE );
198 $row = $dbr->selectRow( 'page', array( 'page_namespace', 'page_title' ),
199 array( 'page_id' => $id ), $fname );
200 if ( $row !== false ) {
201 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
202 } else {
203 $title = NULL;
204 }
205 return $title;
206 }
207
208 /**
209 * Create a new Title from a namespace index and a DB key.
210 * It's assumed that $ns and $title are *valid*, for instance when
211 * they came directly from the database or a special page name.
212 * For convenience, spaces are converted to underscores so that
213 * eg user_text fields can be used directly.
214 *
215 * @param int $ns the namespace of the article
216 * @param string $title the unprefixed database key form
217 * @return Title the new object
218 * @static
219 * @access public
220 */
221 function &makeTitle( $ns, $title ) {
222 $t =& new Title();
223 $t->mInterwiki = '';
224 $t->mFragment = '';
225 $t->mNamespace = IntVal( $ns );
226 $t->mDbkeyform = str_replace( ' ', '_', $title );
227 $t->mArticleID = ( $ns >= 0 ) ? -1 : 0;
228 $t->mUrlform = wfUrlencode( $t->mDbkeyform );
229 $t->mTextform = str_replace( '_', ' ', $title );
230 return $t;
231 }
232
233 /**
234 * Create a new Title frrom a namespace index and a DB key.
235 * The parameters will be checked for validity, which is a bit slower
236 * than makeTitle() but safer for user-provided data.
237 *
238 * @param int $ns the namespace of the article
239 * @param string $title the database key form
240 * @return Title the new object, or NULL on an error
241 * @static
242 * @access public
243 */
244 function makeTitleSafe( $ns, $title ) {
245 $t = new Title();
246 $t->mDbkeyform = Title::makeName( $ns, $title );
247 if( $t->secureAndSplit() ) {
248 return $t;
249 } else {
250 return NULL;
251 }
252 }
253
254 /**
255 * Create a new Title for the Main Page
256 *
257 * @static
258 * @return Title the new object
259 * @access public
260 */
261 function newMainPage() {
262 return Title::newFromText( wfMsgForContent( 'mainpage' ) );
263 }
264
265 /**
266 * Create a new Title for a redirect
267 * @param string $text the redirect title text
268 * @return Title the new object, or NULL if the text is not a
269 * valid redirect
270 * @static
271 * @access public
272 */
273 function newFromRedirect( $text ) {
274 global $wgMwRedir;
275 $rt = NULL;
276 if ( $wgMwRedir->matchStart( $text ) ) {
277 if ( preg_match( '/\[{2}(.*?)(?:\||\]{2})/', $text, $m ) ) {
278 # categories are escaped using : for example one can enter:
279 # #REDIRECT [[:Category:Music]]. Need to remove it.
280 if ( substr($m[1],0,1) == ':') {
281 # We don't want to keep the ':'
282 $m[1] = substr( $m[1], 1 );
283 }
284
285 $rt = Title::newFromText( $m[1] );
286 # Disallow redirects to Special:Userlogout
287 if ( !is_null($rt) && $rt->getNamespace() == NS_SPECIAL && preg_match( '/^Userlogout/i', $rt->getText() ) ) {
288 $rt = NULL;
289 }
290 }
291 }
292 return $rt;
293 }
294
295 #----------------------------------------------------------------------------
296 # Static functions
297 #----------------------------------------------------------------------------
298
299 /**
300 * Get the prefixed DB key associated with an ID
301 * @param int $id the page_id of the article
302 * @return Title an object representing the article, or NULL
303 * if no such article was found
304 * @static
305 * @access public
306 */
307 function nameOf( $id ) {
308 $fname = 'Title::nameOf';
309 $dbr =& wfGetDB( DB_SLAVE );
310
311 $s = $dbr->selectRow( 'page', array( 'page_namespace','page_title' ), array( 'page_id' => $id ), $fname );
312 if ( $s === false ) { return NULL; }
313
314 $n = Title::makeName( $s->page_namespace, $s->page_title );
315 return $n;
316 }
317
318 /**
319 * Get a regex character class describing the legal characters in a link
320 * @return string the list of characters, not delimited
321 * @static
322 * @access public
323 */
324 /* static */ function legalChars() {
325 # Missing characters:
326 # * []|# Needed for link syntax
327 # * % and + are corrupted by Apache when they appear in the path
328 #
329 # % seems to work though
330 #
331 # The problem with % is that URLs are double-unescaped: once by Apache's
332 # path conversion code, and again by PHP. So %253F, for example, becomes "?".
333 # Our code does not double-escape to compensate for this, indeed double escaping
334 # would break if the double-escaped title was passed in the query string
335 # rather than the path. This is a minor security issue because articles can be
336 # created such that they are hard to view or edit. -- TS
337 #
338 # Theoretically 0x80-0x9F of ISO 8859-1 should be disallowed, but
339 # this breaks interlanguage links
340
341 $set = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF";
342 return $set;
343 }
344
345 /**
346 * Get a string representation of a title suitable for
347 * including in a search index
348 *
349 * @param int $ns a namespace index
350 * @param string $title text-form main part
351 * @return string a stripped-down title string ready for the
352 * search index
353 */
354 /* static */ function indexTitle( $ns, $title ) {
355 global $wgDBminWordLen, $wgContLang;
356 require_once( 'SearchEngine.php' );
357
358 $lc = SearchEngine::legalSearchChars() . '&#;';
359 $t = $wgContLang->stripForSearch( $title );
360 $t = preg_replace( "/[^{$lc}]+/", ' ', $t );
361 $t = strtolower( $t );
362
363 # Handle 's, s'
364 $t = preg_replace( "/([{$lc}]+)'s( |$)/", "\\1 \\1's ", $t );
365 $t = preg_replace( "/([{$lc}]+)s'( |$)/", "\\1s ", $t );
366
367 $t = preg_replace( "/\\s+/", ' ', $t );
368
369 if ( $ns == NS_IMAGE ) {
370 $t = preg_replace( "/ (png|gif|jpg|jpeg|ogg)$/", "", $t );
371 }
372 return trim( $t );
373 }
374
375 /*
376 * Make a prefixed DB key from a DB key and a namespace index
377 * @param int $ns numerical representation of the namespace
378 * @param string $title the DB key form the title
379 * @return string the prefixed form of the title
380 */
381 /* static */ function makeName( $ns, $title ) {
382 global $wgContLang;
383
384 $n = $wgContLang->getNsText( $ns );
385 return $n == '' ? $title : "$n:$title";
386 }
387
388 /**
389 * Returns the URL associated with an interwiki prefix
390 * @param string $key the interwiki prefix (e.g. "MeatBall")
391 * @return the associated URL, containing "$1", which should be
392 * replaced by an article title
393 * @static (arguably)
394 * @access public
395 */
396 function getInterwikiLink( $key ) {
397 global $wgMemc, $wgDBname, $wgInterwikiExpiry, $wgTitleInterwikiCache;
398 $fname = 'Title::getInterwikiLink';
399
400 wfProfileIn( $fname );
401
402 $k = $wgDBname.':interwiki:'.$key;
403 if( array_key_exists( $k, $wgTitleInterwikiCache ) ) {
404 wfProfileOut( $fname );
405 return $wgTitleInterwikiCache[$k]->iw_url;
406 }
407
408 $s = $wgMemc->get( $k );
409 # Ignore old keys with no iw_local
410 if( $s && isset( $s->iw_local ) ) {
411 $wgTitleInterwikiCache[$k] = $s;
412 wfProfileOut( $fname );
413 return $s->iw_url;
414 }
415
416 $dbr =& wfGetDB( DB_SLAVE );
417 $res = $dbr->select( 'interwiki',
418 array( 'iw_url', 'iw_local' ),
419 array( 'iw_prefix' => $key ), $fname );
420 if( !$res ) {
421 wfProfileOut( $fname );
422 return '';
423 }
424
425 $s = $dbr->fetchObject( $res );
426 if( !$s ) {
427 # Cache non-existence: create a blank object and save it to memcached
428 $s = (object)false;
429 $s->iw_url = '';
430 $s->iw_local = 0;
431 }
432 $wgMemc->set( $k, $s, $wgInterwikiExpiry );
433 $wgTitleInterwikiCache[$k] = $s;
434
435 wfProfileOut( $fname );
436 return $s->iw_url;
437 }
438
439 /**
440 * Determine whether the object refers to a page within
441 * this project.
442 *
443 * @return bool TRUE if this is an in-project interwiki link
444 * or a wikilink, FALSE otherwise
445 * @access public
446 */
447 function isLocal() {
448 global $wgTitleInterwikiCache, $wgDBname;
449
450 if ( $this->mInterwiki != '' ) {
451 # Make sure key is loaded into cache
452 $this->getInterwikiLink( $this->mInterwiki );
453 $k = $wgDBname.':interwiki:' . $this->mInterwiki;
454 return (bool)($wgTitleInterwikiCache[$k]->iw_local);
455 } else {
456 return true;
457 }
458 }
459
460 /**
461 * Update the page_touched field for an array of title objects
462 * @todo Inefficient unless the IDs are already loaded into the
463 * link cache
464 * @param array $titles an array of Title objects to be touched
465 * @param string $timestamp the timestamp to use instead of the
466 * default current time
467 * @static
468 * @access public
469 */
470 function touchArray( $titles, $timestamp = '' ) {
471 if ( count( $titles ) == 0 ) {
472 return;
473 }
474 $dbw =& wfGetDB( DB_MASTER );
475 if ( $timestamp == '' ) {
476 $timestamp = $dbw->timestamp();
477 }
478 $page = $dbw->tableName( 'page' );
479 $sql = "UPDATE $page SET page_touched='{$timestamp}' WHERE page_id IN (";
480 $first = true;
481
482 foreach ( $titles as $title ) {
483 if ( ! $first ) {
484 $sql .= ',';
485 }
486 $first = false;
487 $sql .= $title->getArticleID();
488 }
489 $sql .= ')';
490 if ( ! $first ) {
491 $dbw->query( $sql, 'Title::touchArray' );
492 }
493 }
494
495 #----------------------------------------------------------------------------
496 # Other stuff
497 #----------------------------------------------------------------------------
498
499 /** Simple accessors */
500 /**
501 * Get the text form (spaces not underscores) of the main part
502 * @return string
503 * @access public
504 */
505 function getText() { return $this->mTextform; }
506 /**
507 * Get the URL-encoded form of the main part
508 * @return string
509 * @access public
510 */
511 function getPartialURL() { return $this->mUrlform; }
512 /**
513 * Get the main part with underscores
514 * @return string
515 * @access public
516 */
517 function getDBkey() { return $this->mDbkeyform; }
518 /**
519 * Get the namespace index, i.e. one of the NS_xxxx constants
520 * @return int
521 * @access public
522 */
523 function getNamespace() { return $this->mNamespace; }
524 /**
525 * Get the interwiki prefix (or null string)
526 * @return string
527 * @access public
528 */
529 function getInterwiki() { return $this->mInterwiki; }
530 /**
531 * Get the Title fragment (i.e. the bit after the #)
532 * @return string
533 * @access public
534 */
535 function getFragment() { return $this->mFragment; }
536 /**
537 * Get the default namespace index, for when there is no namespace
538 * @return int
539 * @access public
540 */
541 function getDefaultNamespace() { return $this->mDefaultNamespace; }
542
543 /**
544 * Get title for search index
545 * @return string a stripped-down title string ready for the
546 * search index
547 */
548 function getIndexTitle() {
549 return Title::indexTitle( $this->mNamespace, $this->mTextform );
550 }
551
552 /**
553 * Get the prefixed database key form
554 * @return string the prefixed title, with underscores and
555 * any interwiki and namespace prefixes
556 * @access public
557 */
558 function getPrefixedDBkey() {
559 $s = $this->prefix( $this->mDbkeyform );
560 $s = str_replace( ' ', '_', $s );
561 return $s;
562 }
563
564 /**
565 * Get the prefixed title with spaces.
566 * This is the form usually used for display
567 * @return string the prefixed title, with spaces
568 * @access public
569 */
570 function getPrefixedText() {
571 global $wgContLang;
572 if ( empty( $this->mPrefixedText ) ) {
573 $s = $this->prefix( $this->mTextform );
574 $s = str_replace( '_', ' ', $s );
575 $this->mPrefixedText = $s;
576 }
577 return $this->mPrefixedText;
578 }
579
580 /**
581 * Get the prefixed title with spaces, plus any fragment
582 * (part beginning with '#')
583 * @return string the prefixed title, with spaces and
584 * the fragment, including '#'
585 * @access public
586 */
587 function getFullText() {
588 global $wgContLang;
589 $text = $this->getPrefixedText();
590 if( '' != $this->mFragment ) {
591 $text .= '#' . $this->mFragment;
592 }
593 return $text;
594 }
595
596 /**
597 * Get a URL-encoded title (not an actual URL) including interwiki
598 * @return string the URL-encoded form
599 * @access public
600 */
601 function getPrefixedURL() {
602 $s = $this->prefix( $this->mDbkeyform );
603 $s = str_replace( ' ', '_', $s );
604
605 $s = wfUrlencode ( $s ) ;
606
607 # Cleaning up URL to make it look nice -- is this safe?
608 $s = str_replace( '%28', '(', $s );
609 $s = str_replace( '%29', ')', $s );
610
611 return $s;
612 }
613
614 /**
615 * Get a real URL referring to this title, with interwiki link and
616 * fragment
617 *
618 * @param string $query an optional query string, not used
619 * for interwiki links
620 * @return string the URL
621 * @access public
622 */
623 function getFullURL( $query = '' ) {
624 global $wgContLang, $wgServer, $wgScript, $wgMakeDumpLinks, $wgArticlePath;
625
626 if ( '' == $this->mInterwiki ) {
627 return $wgServer . $this->getLocalUrl( $query );
628 } elseif ( $wgMakeDumpLinks && $wgContLang->getLanguageName( $this->mInterwiki ) ) {
629 $baseUrl = str_replace( '$1', "../../{$this->mInterwiki}/$1", $wgArticlePath );
630 $baseUrl = str_replace( '$1', $this->getHashedDirectory() . '/$1', $baseUrl );
631 } else {
632 $baseUrl = $this->getInterwikiLink( $this->mInterwiki );
633 }
634
635 $namespace = $wgContLang->getNsText( $this->mNamespace );
636 if ( '' != $namespace ) {
637 # Can this actually happen? Interwikis shouldn't be parsed.
638 $namepace .= ':';
639 }
640 $url = str_replace( '$1', $namespace . $this->mUrlform, $baseUrl );
641 if( $query != '' ) {
642 if( false === strpos( $url, '?' ) ) {
643 $url .= '?';
644 } else {
645 $url .= '&';
646 }
647 $url .= $query;
648 }
649 if ( '' != $this->mFragment ) {
650 $url .= '#' . $this->mFragment;
651 }
652 return $url;
653 }
654
655 /**
656 * Get a relative directory for putting an HTML version of this article into
657 */
658 function getHashedDirectory() {
659 global $wgMakeDumpLinks, $wgInputEncoding;
660 $dbkey = $this->getDBkey();
661
662 # Split into characters
663 if ( $wgInputEncoding == 'UTF-8' ) {
664 preg_match_all( '/./us', $dbkey, $m );
665 } else {
666 preg_match_all( '/./s', $dbkey, $m );
667 }
668 $chars = $m[0];
669 $length = count( $chars );
670 $dir = '';
671
672 for ( $i = 0; $i < $wgMakeDumpLinks; $i++ ) {
673 if ( $i ) {
674 $dir .= '/';
675 }
676 if ( $i >= $length ) {
677 $dir .= '_';
678 } elseif ( ord( $chars[$i] ) > 32 ) {
679 $dir .= strtolower( $chars[$i] );
680 } else {
681 $dir .= sprintf( "%02X", ord( $chars[$i] ) );
682 }
683 }
684 return $dir;
685 }
686
687 function getHashedFilename() {
688 $dbkey = $this->getPrefixedDBkey();
689 $mainPage = Title::newMainPage();
690 if ( $mainPage->getPrefixedDBkey() == $dbkey ) {
691 return 'index.html';
692 }
693
694 $dir = $this->getHashedDirectory();
695
696 # Replace illegal charcters for Windows paths with underscores
697 $friendlyName = strtr( $dbkey, '/\\*?"<>|~', '_________' );
698
699 # Work out lower case form. We assume we're on a system with case-insensitive
700 # filenames, so unless the case is of a special form, we have to disambiguate
701 $lowerCase = $this->prefix( ucfirst( strtolower( $this->getDBkey() ) ) );
702
703 # Make it mostly unique
704 if ( $lowerCase != $friendlyName ) {
705 $friendlyName .= '_' . substr(md5( $dbkey ), 0, 4);
706 }
707 # Handle colon specially because by replacing it with tilde
708 # Thus we reduce the number of paths with hashes appended
709 $friendlyName = str_replace( ':', '~', $friendlyName );
710 return "$dir/$friendlyName.html";
711 }
712
713 /**
714 * Get a URL with no fragment or server name
715 * @param string $query an optional query string; if not specified,
716 * $wgArticlePath will be used.
717 * @return string the URL
718 * @access public
719 */
720 function getLocalURL( $query = '' ) {
721 global $wgLang, $wgArticlePath, $wgScript, $wgMakeDumpLinks;
722
723 if ( $this->isExternal() ) {
724 return $this->getFullURL();
725 }
726
727 $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
728 if ( $wgMakeDumpLinks ) {
729 $url = str_replace( '$1', wfUrlencode( $this->getHashedFilename() ), $wgArticlePath );
730 } elseif ( $query == '' ) {
731 $url = str_replace( '$1', $dbkey, $wgArticlePath );
732 } else {
733 if( preg_match( '/^(.*&|)action=([^&]*)(&(.*)|)$/', $query, $matches ) ) {
734 global $wgActionPaths;
735 $action = urldecode( $matches[2] );
736 if( isset( $wgActionPaths[$action] ) ) {
737 $query = $matches[1];
738 if( isset( $matches[4] ) ) $query .= $matches[4];
739 $url = str_replace( '$1', $dbkey, $wgActionPaths[$action] );
740 if( $query != '' ) $url .= '?' . $query;
741 return $url;
742 }
743 }
744 if ( $query == '-' ) {
745 $query = '';
746 }
747 $url = "{$wgScript}?title={$dbkey}&{$query}";
748 }
749 return $url;
750 }
751
752 /**
753 * Get an HTML-escaped version of the URL form, suitable for
754 * using in a link, without a server name or fragment
755 * @param string $query an optional query string
756 * @return string the URL
757 * @access public
758 */
759 function escapeLocalURL( $query = '' ) {
760 return htmlspecialchars( $this->getLocalURL( $query ) );
761 }
762
763 /**
764 * Get an HTML-escaped version of the URL form, suitable for
765 * using in a link, including the server name and fragment
766 *
767 * @return string the URL
768 * @param string $query an optional query string
769 * @access public
770 */
771 function escapeFullURL( $query = '' ) {
772 return htmlspecialchars( $this->getFullURL( $query ) );
773 }
774
775 /**
776 * Get the URL form for an internal link.
777 * - Used in various Squid-related code, in case we have a different
778 * internal hostname for the server from the exposed one.
779 *
780 * @param string $query an optional query string
781 * @return string the URL
782 * @access public
783 */
784 function getInternalURL( $query = '' ) {
785 global $wgInternalServer;
786 return $wgInternalServer . $this->getLocalURL( $query );
787 }
788
789 /**
790 * Get the edit URL for this Title
791 * @return string the URL, or a null string if this is an
792 * interwiki link
793 * @access public
794 */
795 function getEditURL() {
796 global $wgServer, $wgScript;
797
798 if ( '' != $this->mInterwiki ) { return ''; }
799 $s = $this->getLocalURL( 'action=edit' );
800
801 return $s;
802 }
803
804 /**
805 * Get the HTML-escaped displayable text form.
806 * Used for the title field in <a> tags.
807 * @return string the text, including any prefixes
808 * @access public
809 */
810 function getEscapedText() {
811 return htmlspecialchars( $this->getPrefixedText() );
812 }
813
814 /**
815 * Is this Title interwiki?
816 * @return boolean
817 * @access public
818 */
819 function isExternal() { return ( '' != $this->mInterwiki ); }
820
821 /**
822 * Does the title correspond to a protected article?
823 * @param string $what the action the page is protected from,
824 * by default checks move and edit
825 * @return boolean
826 * @access public
827 */
828 function isProtected($action = '') {
829 if ( -1 == $this->mNamespace ) { return true; }
830 if($action == 'edit' || $action == '') {
831 $a = $this->getRestrictions("edit");
832 if ( in_array( 'sysop', $a ) ) { return true; }
833 }
834 if($action == 'move' || $action == '') {
835 $a = $this->getRestrictions("move");
836 if ( in_array( 'sysop', $a ) ) { return true; }
837 }
838 return false;
839 }
840
841 /**
842 * Is $wgUser is watching this page?
843 * @return boolean
844 * @access public
845 */
846 function userIsWatching() {
847 global $wgUser;
848
849 if ( is_null( $this->mWatched ) ) {
850 if ( -1 == $this->mNamespace || 0 == $wgUser->getID()) {
851 $this->mWatched = false;
852 } else {
853 $this->mWatched = $wgUser->isWatched( $this );
854 }
855 }
856 return $this->mWatched;
857 }
858
859 /**
860 * Is $wgUser perform $action this page?
861 * @param string $action action that permission needs to be checked for
862 * @return boolean
863 * @access private
864 */
865 function userCan($action) {
866 $fname = 'Title::userCanEdit';
867 wfProfileIn( $fname );
868
869 global $wgUser;
870 if( NS_SPECIAL == $this->mNamespace ) {
871 wfProfileOut( $fname );
872 return false;
873 }
874 if( NS_MEDIAWIKI == $this->mNamespace &&
875 !$wgUser->isAllowed('editinterface') ) {
876 wfProfileOut( $fname );
877 return false;
878 }
879 if( $this->mDbkeyform == '_' ) {
880 # FIXME: Is this necessary? Shouldn't be allowed anyway...
881 wfProfileOut( $fname );
882 return false;
883 }
884
885 # protect global styles and js
886 if ( NS_MEDIAWIKI == $this->mNamespace
887 && preg_match("/\\.(css|js)$/", $this->mTextform )
888 && !$wgUser->isAllowed('editinterface') ) {
889 wfProfileOut( $fname );
890 return false;
891 }
892
893 # protect css/js subpages of user pages
894 # XXX: this might be better using restrictions
895 # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
896 if( NS_USER == $this->mNamespace
897 && preg_match("/\\.(css|js)$/", $this->mTextform )
898 && !$wgUser->isAllowed('editinterface')
899 && !preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) ) {
900 wfProfileOut( $fname );
901 return false;
902 }
903
904 foreach( $this->getRestrictions($action) as $right ) {
905 // Backwards compatibility, rewrite sysop -> protect
906 if ( $right == 'sysop' ) {
907 $right = 'protect';
908 }
909 if( '' != $right && !$wgUser->isAllowed( $right ) ) {
910 wfProfileOut( $fname );
911 return false;
912 }
913 }
914
915 if( $action == 'move' && !$this->isMovable() ) {
916 wfProfileOut( $fname );
917 return false;
918 }
919
920 wfProfileOut( $fname );
921 return true;
922 }
923
924 /**
925 * Can $wgUser edit this page?
926 * @return boolean
927 * @access public
928 */
929 function userCanEdit() {
930 return $this->userCan('edit');
931 }
932
933 /**
934 * Can $wgUser move this page?
935 * @return boolean
936 * @access public
937 */
938 function userCanMove() {
939 return $this->userCan('move');
940 }
941
942 /**
943 * Would anybody with sufficient privileges be able to move this page?
944 * Some pages just aren't movable.
945 *
946 * @return boolean
947 * @access public
948 */
949 function isMovable() {
950 return Namespace::isMovable( $this->getNamespace() )
951 && $this->getInterwiki() == '';
952 }
953
954 /**
955 * Can $wgUser read this page?
956 * @return boolean
957 * @access public
958 */
959 function userCanRead() {
960 global $wgUser;
961
962 if( $wgUser->isAllowed('read') ) {
963 return true;
964 } else {
965 global $wgWhitelistRead;
966
967 /** If anon users can create an account,
968 they need to reach the login page first! */
969 if( $wgUser->isAllowed( 'createaccount' )
970 && $this->mId == NS_SPECIAL
971 && $this->getText() == 'Userlogin' ) {
972 return true;
973 }
974
975 /** some pages are explicitly allowed */
976 $name = $this->getPrefixedText();
977 if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead ) ) {
978 return true;
979 }
980
981 # Compatibility with old settings
982 if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
983 if( in_array( ':' . $name, $wgWhitelistRead ) ) {
984 return true;
985 }
986 }
987 }
988 return false;
989 }
990
991 /**
992 * Is this a talk page of some sort?
993 * @return bool
994 * @access public
995 */
996 function isTalkPage() {
997 return Namespace::isTalk( $this->getNamespace() );
998 }
999
1000 /**
1001 * Is this a .css or .js subpage of a user page?
1002 * @return bool
1003 * @access public
1004 */
1005 function isCssJsSubpage() {
1006 return ( NS_USER == $this->mNamespace and preg_match("/\\.(css|js)$/", $this->mTextform ) );
1007 }
1008 /**
1009 * Is this a .css subpage of a user page?
1010 * @return bool
1011 * @access public
1012 */
1013 function isCssSubpage() {
1014 return ( NS_USER == $this->mNamespace and preg_match("/\\.css$/", $this->mTextform ) );
1015 }
1016 /**
1017 * Is this a .js subpage of a user page?
1018 * @return bool
1019 * @access public
1020 */
1021 function isJsSubpage() {
1022 return ( NS_USER == $this->mNamespace and preg_match("/\\.js$/", $this->mTextform ) );
1023 }
1024 /**
1025 * Protect css/js subpages of user pages: can $wgUser edit
1026 * this page?
1027 *
1028 * @return boolean
1029 * @todo XXX: this might be better using restrictions
1030 * @access public
1031 */
1032 function userCanEditCssJsSubpage() {
1033 global $wgUser;
1034 return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
1035 }
1036
1037 /**
1038 * Loads a string into mRestrictions array
1039 * @param string $res restrictions in string format
1040 * @access public
1041 */
1042 function loadRestrictions( $res ) {
1043 foreach( explode( ':', trim( $res ) ) as $restrict ) {
1044 $temp = explode( '=', trim( $restrict ) );
1045 if(count($temp) == 1) {
1046 // old format should be treated as edit/move restriction
1047 $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
1048 $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
1049 } else {
1050 $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
1051 }
1052 }
1053 $this->mRestrictionsLoaded = true;
1054 }
1055
1056 /**
1057 * Accessor/initialisation for mRestrictions
1058 * @param string $action action that permission needs to be checked for
1059 * @return array the array of groups allowed to edit this article
1060 * @access public
1061 */
1062 function getRestrictions($action) {
1063 $id = $this->getArticleID();
1064 if ( 0 == $id ) { return array(); }
1065
1066 if ( ! $this->mRestrictionsLoaded ) {
1067 $dbr =& wfGetDB( DB_SLAVE );
1068 $res = $dbr->selectField( 'page', 'page_restrictions', 'page_id='.$id );
1069 $this->loadRestrictions( $res );
1070 }
1071 if( isset( $this->mRestrictions[$action] ) ) {
1072 return $this->mRestrictions[$action];
1073 }
1074 return array();
1075 }
1076
1077 /**
1078 * Is there a version of this page in the deletion archive?
1079 * @return int the number of archived revisions
1080 * @access public
1081 */
1082 function isDeleted() {
1083 $fname = 'Title::isDeleted';
1084 $dbr =& wfGetDB( DB_SLAVE );
1085 $n = $dbr->selectField( 'archive', 'COUNT(*)', array( 'ar_namespace' => $this->getNamespace(),
1086 'ar_title' => $this->getDBkey() ), $fname );
1087 return (int)$n;
1088 }
1089
1090 /**
1091 * Get the article ID for this Title from the link cache,
1092 * adding it if necessary
1093 * @param int $flags a bit field; may be GAID_FOR_UPDATE to select
1094 * for update
1095 * @return int the ID
1096 * @access public
1097 */
1098 function getArticleID( $flags = 0 ) {
1099 global $wgLinkCache;
1100
1101 if ( $flags & GAID_FOR_UPDATE ) {
1102 $oldUpdate = $wgLinkCache->forUpdate( true );
1103 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1104 $wgLinkCache->forUpdate( $oldUpdate );
1105 } else {
1106 if ( -1 == $this->mArticleID ) {
1107 $this->mArticleID = $wgLinkCache->addLinkObj( $this );
1108 }
1109 }
1110 return $this->mArticleID;
1111 }
1112
1113 /**
1114 * This clears some fields in this object, and clears any associated
1115 * keys in the "bad links" section of $wgLinkCache.
1116 *
1117 * - This is called from Article::insertNewArticle() to allow
1118 * loading of the new page_id. It's also called from
1119 * Article::doDeleteArticle()
1120 *
1121 * @param int $newid the new Article ID
1122 * @access public
1123 */
1124 function resetArticleID( $newid ) {
1125 global $wgLinkCache;
1126 $wgLinkCache->clearBadLink( $this->getPrefixedDBkey() );
1127
1128 if ( 0 == $newid ) { $this->mArticleID = -1; }
1129 else { $this->mArticleID = $newid; }
1130 $this->mRestrictionsLoaded = false;
1131 $this->mRestrictions = array();
1132 }
1133
1134 /**
1135 * Updates page_touched for this page; called from LinksUpdate.php
1136 * @return bool true if the update succeded
1137 * @access public
1138 */
1139 function invalidateCache() {
1140 if ( wfReadOnly() ) {
1141 return;
1142 }
1143
1144 $now = wfTimestampNow();
1145 $dbw =& wfGetDB( DB_MASTER );
1146 $success = $dbw->update( 'page',
1147 array( /* SET */
1148 'page_touched' => $dbw->timestamp()
1149 ), array( /* WHERE */
1150 'page_namespace' => $this->getNamespace() ,
1151 'page_title' => $this->getDBkey()
1152 ), 'Title::invalidateCache'
1153 );
1154 return $success;
1155 }
1156
1157 /**
1158 * Prefix some arbitrary text with the namespace or interwiki prefix
1159 * of this object
1160 *
1161 * @param string $name the text
1162 * @return string the prefixed text
1163 * @access private
1164 */
1165 /* private */ function prefix( $name ) {
1166 global $wgContLang;
1167
1168 $p = '';
1169 if ( '' != $this->mInterwiki ) {
1170 $p = $this->mInterwiki . ':';
1171 }
1172 if ( 0 != $this->mNamespace ) {
1173 $p .= $wgContLang->getNsText( $this->mNamespace ) . ':';
1174 }
1175 return $p . $name;
1176 }
1177
1178 /**
1179 * Secure and split - main initialisation function for this object
1180 *
1181 * Assumes that mDbkeyform has been set, and is urldecoded
1182 * and uses underscores, but not otherwise munged. This function
1183 * removes illegal characters, splits off the interwiki and
1184 * namespace prefixes, sets the other forms, and canonicalizes
1185 * everything.
1186 * @return bool true on success
1187 * @access private
1188 */
1189 /* private */ function secureAndSplit() {
1190 global $wgContLang, $wgLocalInterwiki, $wgCapitalLinks;
1191 $fname = 'Title::secureAndSplit';
1192 wfProfileIn( $fname );
1193
1194 # Initialisation
1195 static $rxTc = false;
1196 if( !$rxTc ) {
1197 # % is needed as well
1198 $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
1199 }
1200
1201 $this->mInterwiki = $this->mFragment = '';
1202 $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
1203
1204 # Clean up whitespace
1205 #
1206 $t = preg_replace( '/[ _]+/', '_', $this->mDbkeyform );
1207 $t = trim( $t, '_' );
1208
1209 if ( '' == $t ) {
1210 wfProfileOut( $fname );
1211 return false;
1212 }
1213
1214 if( false !== strpos( $t, UTF8_REPLACEMENT ) ) {
1215 # Contained illegal UTF-8 sequences or forbidden Unicode chars.
1216 wfProfileOut( $fname );
1217 return false;
1218 }
1219
1220 $this->mDbkeyform = $t;
1221
1222 # Initial colon indicating main namespace
1223 if ( ':' == $t{0} ) {
1224 $r = substr( $t, 1 );
1225 $this->mNamespace = NS_MAIN;
1226 } else {
1227 # Namespace or interwiki prefix
1228 $firstPass = true;
1229 do {
1230 if ( preg_match( "/^(.+?)_*:_*(.*)$/S", $t, $m ) ) {
1231 $p = $m[1];
1232 $lowerNs = strtolower( $p );
1233 if ( $ns = Namespace::getCanonicalIndex( $lowerNs ) ) {
1234 # Canonical namespace
1235 $t = $m[2];
1236 $this->mNamespace = $ns;
1237 } elseif ( $ns = $wgContLang->getNsIndex( $lowerNs )) {
1238 # Ordinary namespace
1239 $t = $m[2];
1240 $this->mNamespace = $ns;
1241 } elseif( $this->getInterwikiLink( $p ) ) {
1242 if( !$firstPass ) {
1243 # Can't make a local interwiki link to an interwiki link.
1244 # That's just crazy!
1245 wfProfileOut( $fname );
1246 return false;
1247 }
1248
1249 # Interwiki link
1250 $t = $m[2];
1251 $this->mInterwiki = $p;
1252
1253 # Redundant interwiki prefix to the local wiki
1254 if ( 0 == strcasecmp( $this->mInterwiki, $wgLocalInterwiki ) ) {
1255 if( $t == '' ) {
1256 # Can't have an empty self-link
1257 wfProfileOut( $fname );
1258 return false;
1259 }
1260 $this->mInterwiki = '';
1261 $firstPass = false;
1262 # Do another namespace split...
1263 continue;
1264 }
1265 }
1266 # If there's no recognized interwiki or namespace,
1267 # then let the colon expression be part of the title.
1268 }
1269 break;
1270 } while( true );
1271 $r = $t;
1272 }
1273
1274 # We already know that some pages won't be in the database!
1275 #
1276 if ( '' != $this->mInterwiki || -1 == $this->mNamespace ) {
1277 $this->mArticleID = 0;
1278 }
1279 $f = strstr( $r, '#' );
1280 if ( false !== $f ) {
1281 $this->mFragment = substr( $f, 1 );
1282 $r = substr( $r, 0, strlen( $r ) - strlen( $f ) );
1283 # remove whitespace again: prevents "Foo_bar_#"
1284 # becoming "Foo_bar_"
1285 $r = preg_replace( '/_*$/', '', $r );
1286 }
1287
1288 # Reject illegal characters.
1289 #
1290 if( preg_match( $rxTc, $r ) ) {
1291 wfProfileOut( $fname );
1292 return false;
1293 }
1294
1295 /**
1296 * Pages with "/./" or "/../" appearing in the URLs will
1297 * often be unreachable due to the way web browsers deal
1298 * with 'relative' URLs. Forbid them explicitly.
1299 */
1300 if ( strpos( $r, '.' ) !== false &&
1301 ( $r === '.' || $r === '..' ||
1302 strpos( $r, './' ) === 0 ||
1303 strpos( $r, '../' ) === 0 ||
1304 strpos( $r, '/./' ) !== false ||
1305 strpos( $r, '/../' ) !== false ) )
1306 {
1307 wfProfileOut( $fname );
1308 return false;
1309 }
1310
1311 # We shouldn't need to query the DB for the size.
1312 #$maxSize = $dbr->textFieldSize( 'page', 'page_title' );
1313 if ( strlen( $r ) > 255 ) {
1314 wfProfileOut( $fname );
1315 return false;
1316 }
1317
1318 /**
1319 * Normally, all wiki links are forced to have
1320 * an initial capital letter so [[foo]] and [[Foo]]
1321 * point to the same place.
1322 *
1323 * Don't force it for interwikis, since the other
1324 * site might be case-sensitive.
1325 */
1326 if( $wgCapitalLinks && $this->mInterwiki == '') {
1327 $t = $wgContLang->ucfirst( $r );
1328 } else {
1329 $t = $r;
1330 }
1331
1332 /**
1333 * Can't make a link to a namespace alone...
1334 * "empty" local links can only be self-links
1335 * with a fragment identifier.
1336 */
1337 if( $t == '' &&
1338 $this->mInterwiki == '' &&
1339 $this->mNamespace != NS_MAIN ) {
1340 wfProfileOut( $fname );
1341 return false;
1342 }
1343
1344 # Fill fields
1345 $this->mDbkeyform = $t;
1346 $this->mUrlform = wfUrlencode( $t );
1347
1348 $this->mTextform = str_replace( '_', ' ', $t );
1349
1350 wfProfileOut( $fname );
1351 return true;
1352 }
1353
1354 /**
1355 * Get a Title object associated with the talk page of this article
1356 * @return Title the object for the talk page
1357 * @access public
1358 */
1359 function getTalkPage() {
1360 return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
1361 }
1362
1363 /**
1364 * Get a title object associated with the subject page of this
1365 * talk page
1366 *
1367 * @return Title the object for the subject page
1368 * @access public
1369 */
1370 function getSubjectPage() {
1371 return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
1372 }
1373
1374 /**
1375 * Get an array of Title objects linking to this Title
1376 * Also stores the IDs in the link cache.
1377 *
1378 * @param string $options may be FOR UPDATE
1379 * @return array the Title objects linking here
1380 * @access public
1381 */
1382 function getLinksTo( $options = '' ) {
1383 global $wgLinkCache;
1384 $id = $this->getArticleID();
1385
1386 if ( $options ) {
1387 $db =& wfGetDB( DB_MASTER );
1388 } else {
1389 $db =& wfGetDB( DB_SLAVE );
1390 }
1391
1392 $res = $db->select( array( 'page', 'pagelinks' ),
1393 array( 'page_namespace', 'page_title', 'page_id' ),
1394 array(
1395 'pl_from=page_id',
1396 'pl_namespace' => $this->getNamespace(),
1397 'pl_title' => $this->getDbKey() ),
1398 'Title::getLinksTo',
1399 $options );
1400
1401 $retVal = array();
1402 if ( $db->numRows( $res ) ) {
1403 while ( $row = $db->fetchObject( $res ) ) {
1404 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1405 $wgLinkCache->addGoodLinkObj( $row->page_id, $titleObj );
1406 $retVal[] = $titleObj;
1407 }
1408 }
1409 }
1410 $db->freeResult( $res );
1411 return $retVal;
1412 }
1413
1414 /**
1415 * Get an array of Title objects referring to non-existent articles linked from this page
1416 *
1417 * @param string $options may be FOR UPDATE
1418 * @return array the Title objects
1419 * @access public
1420 */
1421 function getBrokenLinksFrom( $options = '' ) {
1422 global $wgLinkCache;
1423
1424 if ( $options ) {
1425 $db =& wfGetDB( DB_MASTER );
1426 } else {
1427 $db =& wfGetDB( DB_SLAVE );
1428 }
1429
1430 $res = $db->safeQuery(
1431 "SELECT pl_namespace, pl_title
1432 FROM !
1433 LEFT JOIN !
1434 ON pl_namespace=page_namespace
1435 AND pl_title=page_title
1436 WHERE pl_from=?
1437 AND page_namespace IS NULL
1438 !",
1439 $db->tableName( 'pagelinks' ),
1440 $db->tableName( 'page' ),
1441 $this->getArticleId(),
1442 $options );
1443
1444 $retVal = array();
1445 if ( $db->numRows( $res ) ) {
1446 while ( $row = $db->fetchObject( $res ) ) {
1447 $retVal[] = Title::makeTitle( $row->pl_namespace, $row->pl_title );
1448 }
1449 }
1450 $db->freeResult( $res );
1451 return $retVal;
1452 }
1453
1454
1455 /**
1456 * Get a list of URLs to purge from the Squid cache when this
1457 * page changes
1458 *
1459 * @return array the URLs
1460 * @access public
1461 */
1462 function getSquidURLs() {
1463 return array(
1464 $this->getInternalURL(),
1465 $this->getInternalURL( 'action=history' )
1466 );
1467 }
1468
1469 /**
1470 * Move this page without authentication
1471 * @param Title &$nt the new page Title
1472 * @access public
1473 */
1474 function moveNoAuth( &$nt ) {
1475 return $this->moveTo( $nt, false );
1476 }
1477
1478 /**
1479 * Check whether a given move operation would be valid.
1480 * Returns true if ok, or a message key string for an error message
1481 * if invalid. (Scarrrrry ugly interface this.)
1482 * @param Title &$nt the new title
1483 * @param bool $auth indicates whether $wgUser's permissions
1484 * should be checked
1485 * @return mixed true on success, message name on failure
1486 * @access public
1487 */
1488 function isValidMoveOperation( &$nt, $auth = true, $reason = '' ) {
1489 global $wgUser;
1490 if( !$this or !$nt ) {
1491 return 'badtitletext';
1492 }
1493 if( $this->equals( $nt ) ) {
1494 return 'selfmove';
1495 }
1496 if( !$this->isMovable() || !$nt->isMovable() ) {
1497 return 'immobile_namespace';
1498 }
1499
1500 $fname = 'Title::move';
1501 $oldid = $this->getArticleID();
1502 $newid = $nt->getArticleID();
1503
1504 if ( strlen( $nt->getDBkey() ) < 1 ) {
1505 return 'articleexists';
1506 }
1507 if ( ( '' == $this->getDBkey() ) ||
1508 ( !$oldid ) ||
1509 ( '' == $nt->getDBkey() ) ) {
1510 return 'badarticleerror';
1511 }
1512
1513 if ( $auth && (
1514 !$this->userCanEdit() || !$nt->userCanEdit() ||
1515 !$this->userCanMove() || !$nt->userCanMove() ) ) {
1516 return 'protectedpage';
1517 }
1518
1519 # The move is allowed only if (1) the target doesn't exist, or
1520 # (2) the target is a redirect to the source, and has no history
1521 # (so we can undo bad moves right after they're done).
1522
1523 if ( 0 != $newid ) { # Target exists; check for validity
1524 if ( ! $this->isValidMoveTarget( $nt ) ) {
1525 return 'articleexists';
1526 }
1527 }
1528 return true;
1529 }
1530
1531 /**
1532 * Move a title to a new location
1533 * @param Title &$nt the new title
1534 * @param bool $auth indicates whether $wgUser's permissions
1535 * should be checked
1536 * @return mixed true on success, message name on failure
1537 * @access public
1538 */
1539 function moveTo( &$nt, $auth = true, $reason = '' ) {
1540 $err = $this->isValidMoveOperation( $nt, $auth, $reason );
1541 if( is_string( $err ) ) {
1542 return $err;
1543 }
1544 if( $nt->exists() ) {
1545 $this->moveOverExistingRedirect( $nt, $reason );
1546 } else { # Target didn't exist, do normal move.
1547 $this->moveToNewTitle( $nt, $newid, $reason );
1548 }
1549
1550 # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
1551
1552 $dbw =& wfGetDB( DB_MASTER );
1553 $categorylinks = $dbw->tableName( 'categorylinks' );
1554 $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
1555 " WHERE cl_from=" . $dbw->addQuotes( $this->getArticleID() ) .
1556 " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
1557 $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
1558
1559 # Update watchlists
1560
1561 $oldnamespace = $this->getNamespace() & ~1;
1562 $newnamespace = $nt->getNamespace() & ~1;
1563 $oldtitle = $this->getDBkey();
1564 $newtitle = $nt->getDBkey();
1565
1566 if( $oldnamespace != $newnamespace || $oldtitle != $newtitle ) {
1567 WatchedItem::duplicateEntries( $this, $nt );
1568 }
1569
1570 # Update search engine
1571 $u = new SearchUpdate( $oldid, $nt->getPrefixedDBkey() );
1572 $u->doUpdate();
1573 $u = new SearchUpdate( $newid, $this->getPrefixedDBkey(), '' );
1574 $u->doUpdate();
1575
1576 wfRunHooks( 'TitleMoveComplete', array(&$this, &$nt, &$wgUser, $oldid, $newid) );
1577 return true;
1578 }
1579
1580 /**
1581 * Move page to a title which is at present a redirect to the
1582 * source page
1583 *
1584 * @param Title &$nt the page to move to, which should currently
1585 * be a redirect
1586 * @access private
1587 */
1588 function moveOverExistingRedirect( &$nt, $reason = '' ) {
1589 global $wgUser, $wgLinkCache, $wgUseSquid, $wgMwRedir;
1590 $fname = 'Title::moveOverExistingRedirect';
1591 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1592
1593 if ( $reason ) {
1594 $comment .= ": $reason";
1595 }
1596
1597 $now = wfTimestampNow();
1598 $rand = wfRandom();
1599 $newid = $nt->getArticleID();
1600 $oldid = $this->getArticleID();
1601 $dbw =& wfGetDB( DB_MASTER );
1602 $links = $dbw->tableName( 'links' );
1603
1604 # Delete the old redirect. We don't save it to history since
1605 # by definition if we've got here it's rather uninteresting.
1606 # We have to remove it so that the next step doesn't trigger
1607 # a conflict on the unique namespace+title index...
1608 $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
1609
1610 # Save a null revision in the page's history notifying of the move
1611 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1612 wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1613 true );
1614 $nullRevId = $nullRevision->insertOn( $dbw );
1615
1616 # Change the name of the target page:
1617 $dbw->update( 'page',
1618 /* SET */ array(
1619 'page_touched' => $dbw->timestamp($now),
1620 'page_namespace' => $nt->getNamespace(),
1621 'page_title' => $nt->getDBkey(),
1622 'page_latest' => $nullRevId,
1623 ),
1624 /* WHERE */ array( 'page_id' => $oldid ),
1625 $fname
1626 );
1627 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1628
1629 # Recreate the redirect, this time in the other direction.
1630 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1631 $redirectArticle = new Article( $this );
1632 $newid = $redirectArticle->insertOn( $dbw );
1633 $redirectRevision = new Revision( array(
1634 'page' => $newid,
1635 'comment' => $comment,
1636 'text' => $redirectText ) );
1637 $revid = $redirectRevision->insertOn( $dbw );
1638 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1639 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1640
1641 # Log the move
1642 $log = new LogPage( 'move' );
1643 $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
1644
1645 # Now, we record the link from the redirect to the new title.
1646 # It should have no other outgoing links...
1647 $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
1648 $dbw->insert( 'pagelinks',
1649 array(
1650 'pl_from' => $newid,
1651 'pl_namespace' => $this->getNamespace(),
1652 'pl_title' => $this->getDbKey() ),
1653 $fname );
1654
1655 # Clear linkscc
1656 LinkCache::linksccClearLinksTo( $this );
1657 LinkCache::linksccClearLinksTo( $nt );
1658
1659 # Purge squid
1660 if ( $wgUseSquid ) {
1661 $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
1662 $u = new SquidUpdate( $urls );
1663 $u->doUpdate();
1664 }
1665 }
1666
1667 /**
1668 * Move page to non-existing title.
1669 * @param Title &$nt the new Title
1670 * @param int &$newid set to be the new article ID
1671 * @access private
1672 */
1673 function moveToNewTitle( &$nt, &$newid, $reason = '' ) {
1674 global $wgUser, $wgLinkCache, $wgUseSquid;
1675 global $wgMwRedir;
1676 $fname = 'MovePageForm::moveToNewTitle';
1677 $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
1678 if ( $reason ) {
1679 $comment .= ": $reason";
1680 }
1681
1682 $newid = $nt->getArticleID();
1683 $oldid = $this->getArticleID();
1684 $dbw =& wfGetDB( DB_MASTER );
1685 $now = $dbw->timestamp();
1686 wfSeedRandom();
1687 $rand = wfRandom();
1688
1689 # Save a null revision in the page's history notifying of the move
1690 $nullRevision = Revision::newNullRevision( $dbw, $oldid,
1691 wfMsg( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() ),
1692 true );
1693 $nullRevId = $nullRevision->insertOn( $dbw );
1694
1695 # Rename cur entry
1696 $dbw->update( 'page',
1697 /* SET */ array(
1698 'page_touched' => $now,
1699 'page_namespace' => $nt->getNamespace(),
1700 'page_title' => $nt->getDBkey(),
1701 'page_latest' => $nullRevId,
1702 ),
1703 /* WHERE */ array( 'page_id' => $oldid ),
1704 $fname
1705 );
1706
1707 $wgLinkCache->clearLink( $nt->getPrefixedDBkey() );
1708
1709 # Insert redirect
1710 $redirectText = $wgMwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
1711 $redirectArticle = new Article( $this );
1712 $newid = $redirectArticle->insertOn( $dbw );
1713 $redirectRevision = new Revision( array(
1714 'page' => $newid,
1715 'comment' => $comment,
1716 'text' => $redirectText ) );
1717 $revid = $redirectRevision->insertOn( $dbw );
1718 $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
1719 $wgLinkCache->clearLink( $this->getPrefixedDBkey() );
1720
1721 # Log the move
1722 $log = new LogPage( 'move' );
1723 $log->addEntry( 'move', $this, $reason, array( 1 => $nt->getPrefixedText()) );
1724
1725 # Purge squid and linkscc as per article creation
1726 Article::onArticleCreate( $nt );
1727
1728 # Record the just-created redirect's linking to the page
1729 $dbw->insert( 'pagelinks',
1730 array(
1731 'pl_from' => $newid,
1732 'pl_namespace' => $this->getNamespace(),
1733 'pl_title' => $this->getTitle() ),
1734 $fname );
1735
1736 # Non-existent target may have had broken links to it; these must
1737 # now be touched to update link coloring.
1738 $nt->touchLinks();
1739
1740 # Purge old title from squid
1741 # The new title, and links to the new title, are purged in Article::onArticleCreate()
1742 $titles = $nt->getLinksTo();
1743 if ( $wgUseSquid ) {
1744 $urls = $this->getSquidURLs();
1745 foreach ( $titles as $linkTitle ) {
1746 $urls[] = $linkTitle->getInternalURL();
1747 }
1748 $u = new SquidUpdate( $urls );
1749 $u->doUpdate();
1750 }
1751 }
1752
1753 /**
1754 * Checks if $this can be moved to a given Title
1755 * - Selects for update, so don't call it unless you mean business
1756 *
1757 * @param Title &$nt the new title to check
1758 * @access public
1759 */
1760 function isValidMoveTarget( $nt ) {
1761
1762 $fname = 'Title::isValidMoveTarget';
1763 $dbw =& wfGetDB( DB_MASTER );
1764
1765 # Is it a redirect?
1766 $id = $nt->getArticleID();
1767 $obj = $dbw->selectRow( array( 'page', 'revision', 'text'),
1768 array( 'page_is_redirect','old_text' ),
1769 array( 'page_id' => $id, 'page_latest=rev_id', 'rev_text_id=old_id' ),
1770 $fname, 'FOR UPDATE' );
1771
1772 if ( !$obj || 0 == $obj->page_is_redirect ) {
1773 # Not a redirect
1774 return false;
1775 }
1776
1777 # Does the redirect point to the source?
1778 if ( preg_match( "/\\[\\[\\s*([^\\]\\|]*)]]/", $obj->old_text, $m ) ) {
1779 $redirTitle = Title::newFromText( $m[1] );
1780 if( !is_object( $redirTitle ) ||
1781 $redirTitle->getPrefixedDBkey() != $this->getPrefixedDBkey() ) {
1782 return false;
1783 }
1784 }
1785
1786 # Does the article have a history?
1787 $row = $dbw->selectRow( array( 'page', 'revision'),
1788 array( 'rev_id' ),
1789 array( 'page_namespace' => $nt->getNamespace(),
1790 'page_title' => $nt->getDBkey(),
1791 'page_id=rev_page AND page_latest != rev_id'
1792 ), $fname, 'FOR UPDATE'
1793 );
1794
1795 # Return true if there was no history
1796 return $row === false;
1797 }
1798
1799 /**
1800 * Create a redirect; fails if the title already exists; does
1801 * not notify RC
1802 *
1803 * @param Title $dest the destination of the redirect
1804 * @param string $comment the comment string describing the move
1805 * @return bool true on success
1806 * @access public
1807 */
1808 function createRedirect( $dest, $comment ) {
1809 global $wgUser;
1810 if ( $this->getArticleID() ) {
1811 return false;
1812 }
1813
1814 $fname = 'Title::createRedirect';
1815 $dbw =& wfGetDB( DB_MASTER );
1816
1817 $article = new Article( $this );
1818 $newid = $article->insertOn( $dbw );
1819 $revision = new Revision( array(
1820 'page' => $newid,
1821 'comment' => $comment,
1822 'text' => "#REDIRECT [[" . $dest->getPrefixedText() . "]]\n",
1823 ) );
1824 $revisionId = $revision->insertOn( $dbw );
1825 $article->updateRevisionOn( $dbw, $revision, 0 );
1826
1827 # Link table
1828 $dbw->insert( 'pagelinks',
1829 array(
1830 'pl_from' => $newid,
1831 'pl_namespace' => $dest->getNamespace(),
1832 'pl_title' => $dest->getDbKey()
1833 ), $fname
1834 );
1835
1836 Article::onArticleCreate( $this );
1837 return true;
1838 }
1839
1840 /**
1841 * Get categories to which this Title belongs and return an array of
1842 * categories' names.
1843 *
1844 * @return array an array of parents in the form:
1845 * $parent => $currentarticle
1846 * @access public
1847 */
1848 function getParentCategories() {
1849 global $wgContLang,$wgUser;
1850
1851 $titlekey = $this->getArticleId();
1852 $sk =& $wgUser->getSkin();
1853 $parents = array();
1854 $dbr =& wfGetDB( DB_SLAVE );
1855 $categorylinks = $dbr->tableName( 'categorylinks' );
1856
1857 # NEW SQL
1858 $sql = "SELECT * FROM $categorylinks"
1859 ." WHERE cl_from='$titlekey'"
1860 ." AND cl_from <> '0'"
1861 ." ORDER BY cl_sortkey";
1862
1863 $res = $dbr->query ( $sql ) ;
1864
1865 if($dbr->numRows($res) > 0) {
1866 while ( $x = $dbr->fetchObject ( $res ) )
1867 //$data[] = Title::newFromText($wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to);
1868 $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
1869 $dbr->freeResult ( $res ) ;
1870 } else {
1871 $data = '';
1872 }
1873 return $data;
1874 }
1875
1876 /**
1877 * Get a tree of parent categories
1878 * @param array $children an array with the children in the keys, to check for circular refs
1879 * @return array
1880 * @access public
1881 */
1882 function getParentCategoryTree( $children = array() ) {
1883 $parents = $this->getParentCategories();
1884
1885 if($parents != '') {
1886 foreach($parents as $parent => $current)
1887 {
1888 if ( array_key_exists( $parent, $children ) ) {
1889 # Circular reference
1890 $stack[$parent] = array();
1891 } else {
1892 $nt = Title::newFromText($parent);
1893 $stack[$parent] = $nt->getParentCategoryTree( $children + array($parent => 1) );
1894 }
1895 }
1896 return $stack;
1897 } else {
1898 return array();
1899 }
1900 }
1901
1902
1903 /**
1904 * Get an associative array for selecting this title from
1905 * the "cur" table
1906 *
1907 * @return array
1908 * @access public
1909 */
1910 function curCond() {
1911 wfDebugDieBacktrace( 'curCond called' );
1912 return array( 'cur_namespace' => $this->mNamespace, 'cur_title' => $this->mDbkeyform );
1913 }
1914
1915 /**
1916 * Get an associative array for selecting this title from the
1917 * "old" table
1918 *
1919 * @return array
1920 * @access public
1921 */
1922 function oldCond() {
1923 wfDebugDieBacktrace( 'oldCond called' );
1924 return array( 'old_namespace' => $this->mNamespace, 'old_title' => $this->mDbkeyform );
1925 }
1926
1927 /**
1928 * Get the revision ID of the previous revision
1929 *
1930 * @param integer $revision Revision ID. Get the revision that was before this one.
1931 * @return interger $oldrevision|false
1932 */
1933 function getPreviousRevisionID( $revision ) {
1934 $dbr =& wfGetDB( DB_SLAVE );
1935 return $dbr->selectField( 'revision', 'rev_id',
1936 'rev_page=' . IntVal( $this->getArticleId() ) .
1937 ' AND rev_id<' . IntVal( $revision ) . ' ORDER BY rev_id DESC' );
1938 }
1939
1940 /**
1941 * Get the revision ID of the next revision
1942 *
1943 * @param integer $revision Revision ID. Get the revision that was after this one.
1944 * @return interger $oldrevision|false
1945 */
1946 function getNextRevisionID( $revision ) {
1947 $dbr =& wfGetDB( DB_SLAVE );
1948 return $dbr->selectField( 'revision', 'rev_id',
1949 'rev_page=' . IntVal( $this->getArticleId() ) .
1950 ' AND rev_id>' . IntVal( $revision ) . ' ORDER BY rev_id' );
1951 }
1952
1953 /**
1954 * Compare with another title.
1955 *
1956 * @param Title $title
1957 * @return bool
1958 */
1959 function equals( &$title ) {
1960 return $this->getInterwiki() == $title->getInterwiki()
1961 && $this->getNamespace() == $title->getNamespace()
1962 && $this->getDbkey() == $title->getDbkey();
1963 }
1964
1965 /**
1966 * Check if page exists
1967 * @return bool
1968 */
1969 function exists() {
1970 return $this->getArticleId() != 0;
1971 }
1972
1973 /**
1974 * Should a link should be displayed as a known link, just based on its title?
1975 *
1976 * Currently, a self-link with a fragment, special pages and image pages are in
1977 * this category. Special pages never exist in the database. Some images do not
1978 * have description pages in the database, but the description page contains
1979 * useful history information that the user may want to link to.
1980 *
1981 */
1982 function isAlwaysKnown() {
1983 return ( 0 == $this->mNamespace && "" == $this->mDbkeyform )
1984 || NS_SPECIAL == $this->mNamespace || NS_IMAGE == $this->mNamespace;
1985 }
1986
1987 /**
1988 * Update page_touched timestamps on pages linking to this title.
1989 * In principal, this could be backgrounded and could also do squid
1990 * purging.
1991 */
1992 function touchLinks() {
1993 $fname = 'Title::touchLinks';
1994
1995 $dbw =& wfGetDB( DB_MASTER );
1996
1997 $res = $dbw->select( 'pagelinks',
1998 array( 'pl_from' ),
1999 array(
2000 'pl_namespace' => $this->getNamespace(),
2001 'pl_title' => $this->getDbKey() ),
2002 $fname );
2003 if ( 0 == $dbw->numRows( $res ) ) {
2004 return;
2005 }
2006
2007 $arr = array();
2008 $toucharr = array();
2009 while( $row = $dbw->fetchObject( $res ) ) {
2010 $toucharr[] = $row->pl_from;
2011 }
2012
2013 $dbw->update( 'page', /* SET */ array( 'page_touched' => $dbw->timestamp() ),
2014 /* WHERE */ array( 'page_id' => $toucharr ),$fname);
2015 }
2016 }
2017 ?>