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