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