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