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