Merge "Allow additional interwiki prefixes on local interwiki links"
[lhc/web/wiklou.git] / maintenance / generateSitemap.php
1 <?php
2 /**
3 * Creates a sitemap for the site.
4 *
5 * Copyright © 2005, Ævar Arnfjörð Bjarmason, Jens Frank <jeluf@gmx.de> and
6 * Brion Vibber <brion@pobox.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Maintenance
25 * @see http://www.sitemaps.org/
26 * @see http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
27 */
28
29 require_once __DIR__ . '/Maintenance.php';
30
31 /**
32 * Maintenance script that generates a sitemap for the site.
33 *
34 * @ingroup Maintenance
35 */
36 class GenerateSitemap extends Maintenance {
37 const GS_MAIN = -2;
38 const GS_TALK = -1;
39
40 /**
41 * The maximum amount of urls in a sitemap file
42 *
43 * @link http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
44 *
45 * @var int
46 */
47 public $url_limit;
48
49 /**
50 * The maximum size of a sitemap file
51 *
52 * @link http://www.sitemaps.org/faq.php#faq_sitemap_size
53 *
54 * @var int
55 */
56 public $size_limit;
57
58 /**
59 * The path to prepend to the filename
60 *
61 * @var string
62 */
63 public $fspath;
64
65 /**
66 * The URL path to prepend to filenames in the index; should resolve to the same directory as $fspath
67 *
68 * @var string
69 */
70 public $urlpath;
71
72 /**
73 * Whether or not to use compression
74 *
75 * @var bool
76 */
77 public $compress;
78
79 /**
80 * Whether or not to include redirection pages
81 *
82 * @var bool
83 */
84 public $skipRedirects;
85
86 /**
87 * The number of entries to save in each sitemap file
88 *
89 * @var array
90 */
91 public $limit = array();
92
93 /**
94 * Key => value entries of namespaces and their priorities
95 *
96 * @var array
97 */
98 public $priorities = array();
99
100 /**
101 * A one-dimensional array of namespaces in the wiki
102 *
103 * @var array
104 */
105 public $namespaces = array();
106
107 /**
108 * When this sitemap batch was generated
109 *
110 * @var string
111 */
112 public $timestamp;
113
114 /**
115 * A database slave object
116 *
117 * @var object
118 */
119 public $dbr;
120
121 /**
122 * A resource pointing to the sitemap index file
123 *
124 * @var resource
125 */
126 public $findex;
127
128 /**
129 * A resource pointing to a sitemap file
130 *
131 * @var resource
132 */
133 public $file;
134
135 /**
136 * Identifier to use in filenames, default $wgDBname
137 *
138 * @var string
139 */
140 private $identifier;
141
142 /**
143 * Constructor
144 */
145 public function __construct() {
146 parent::__construct();
147 $this->mDescription = "Creates a sitemap for the site";
148 $this->addOption( 'fspath', 'The file system path to save to, e.g. /tmp/sitemap; defaults to current directory', false, true );
149 $this->addOption( 'urlpath', 'The URL path corresponding to --fspath, prepended to filenames in the index; defaults to an empty string', false, true );
150 $this->addOption( 'compress', 'Compress the sitemap files, can take value yes|no, default yes', false, true );
151 $this->addOption( 'skip-redirects', 'Do not include redirecting articles in the sitemap' );
152 $this->addOption( 'identifier', 'What site identifier to use for the wiki, defaults to $wgDBname', false, true );
153 }
154
155 /**
156 * Execute
157 */
158 public function execute() {
159 $this->setNamespacePriorities();
160 $this->url_limit = 50000;
161 $this->size_limit = pow( 2, 20 ) * 10;
162 $this->fspath = self::init_path( $this->getOption( 'fspath', getcwd() ) );
163 $this->urlpath = $this->getOption( 'urlpath', "" );
164 if ( $this->urlpath !== "" && substr( $this->urlpath, -1 ) !== '/' ) {
165 $this->urlpath .= '/';
166 }
167 $this->identifier = $this->getOption( 'identifier', wfWikiID() );
168 $this->compress = $this->getOption( 'compress', 'yes' ) !== 'no';
169 $this->skipRedirects = $this->getOption( 'skip-redirects', false ) !== false;
170 $this->dbr = wfGetDB( DB_SLAVE );
171 $this->generateNamespaces();
172 $this->timestamp = wfTimestamp( TS_ISO_8601, wfTimestampNow() );
173 $this->findex = fopen( "{$this->fspath}sitemap-index-{$this->identifier}.xml", 'wb' );
174 $this->main();
175 }
176
177 private function setNamespacePriorities() {
178 global $wgSitemapNamespacesPriorities;
179
180 // Custom main namespaces
181 $this->priorities[self::GS_MAIN] = '0.5';
182 // Custom talk namesspaces
183 $this->priorities[self::GS_TALK] = '0.1';
184 // MediaWiki standard namespaces
185 $this->priorities[NS_MAIN] = '1.0';
186 $this->priorities[NS_TALK] = '0.1';
187 $this->priorities[NS_USER] = '0.5';
188 $this->priorities[NS_USER_TALK] = '0.1';
189 $this->priorities[NS_PROJECT] = '0.5';
190 $this->priorities[NS_PROJECT_TALK] = '0.1';
191 $this->priorities[NS_FILE] = '0.5';
192 $this->priorities[NS_FILE_TALK] = '0.1';
193 $this->priorities[NS_MEDIAWIKI] = '0.0';
194 $this->priorities[NS_MEDIAWIKI_TALK] = '0.1';
195 $this->priorities[NS_TEMPLATE] = '0.0';
196 $this->priorities[NS_TEMPLATE_TALK] = '0.1';
197 $this->priorities[NS_HELP] = '0.5';
198 $this->priorities[NS_HELP_TALK] = '0.1';
199 $this->priorities[NS_CATEGORY] = '0.5';
200 $this->priorities[NS_CATEGORY_TALK] = '0.1';
201
202 // Custom priorities
203 if ( $wgSitemapNamespacesPriorities !== false ) {
204 /**
205 * @var $wgSitemapNamespacesPriorities array
206 */
207 foreach ( $wgSitemapNamespacesPriorities as $namespace => $priority ) {
208 $float = floatval( $priority );
209 if ( $float > 1.0 ) {
210 $priority = '1.0';
211 } elseif ( $float < 0.0 ) {
212 $priority = '0.0';
213 }
214 $this->priorities[$namespace] = $priority;
215 }
216 }
217 }
218
219 /**
220 * Create directory if it does not exist and return pathname with a trailing slash
221 * @param string $fspath
222 * @return null|string
223 */
224 private static function init_path( $fspath ) {
225 if ( !isset( $fspath ) ) {
226 return null;
227 }
228 # Create directory if needed
229 if ( $fspath && !is_dir( $fspath ) ) {
230 wfMkdirParents( $fspath, null, __METHOD__ ) or die( "Can not create directory $fspath.\n" );
231 }
232
233 return realpath( $fspath ) . DIRECTORY_SEPARATOR;
234 }
235
236 /**
237 * Generate a one-dimensional array of existing namespaces
238 */
239 function generateNamespaces() {
240 // Only generate for specific namespaces if $wgSitemapNamespaces is an array.
241 global $wgSitemapNamespaces;
242 if ( is_array( $wgSitemapNamespaces ) ) {
243 $this->namespaces = $wgSitemapNamespaces;
244 return;
245 }
246
247 $res = $this->dbr->select( 'page',
248 array( 'page_namespace' ),
249 array(),
250 __METHOD__,
251 array(
252 'GROUP BY' => 'page_namespace',
253 'ORDER BY' => 'page_namespace',
254 )
255 );
256
257 foreach ( $res as $row ) {
258 $this->namespaces[] = $row->page_namespace;
259 }
260 }
261
262 /**
263 * Get the priority of a given namespace
264 *
265 * @param int $namespace The namespace to get the priority for
266 * @return string
267 */
268 function priority( $namespace ) {
269 return isset( $this->priorities[$namespace] ) ? $this->priorities[$namespace] : $this->guessPriority( $namespace );
270 }
271
272 /**
273 * If the namespace isn't listed on the priority list return the
274 * default priority for the namespace, varies depending on whether it's
275 * a talkpage or not.
276 *
277 * @param int $namespace The namespace to get the priority for
278 * @return string
279 */
280 function guessPriority( $namespace ) {
281 return MWNamespace::isSubject( $namespace ) ? $this->priorities[self::GS_MAIN] : $this->priorities[self::GS_TALK];
282 }
283
284 /**
285 * Return a database resolution of all the pages in a given namespace
286 *
287 * @param int $namespace Limit the query to this namespace
288 * @return Resource
289 */
290 function getPageRes( $namespace ) {
291 return $this->dbr->select( 'page',
292 array(
293 'page_namespace',
294 'page_title',
295 'page_touched',
296 'page_is_redirect'
297 ),
298 array( 'page_namespace' => $namespace ),
299 __METHOD__
300 );
301 }
302
303 /**
304 * Main loop
305 */
306 public function main() {
307 global $wgContLang;
308
309 fwrite( $this->findex, $this->openIndex() );
310
311 foreach ( $this->namespaces as $namespace ) {
312 $res = $this->getPageRes( $namespace );
313 $this->file = false;
314 $this->generateLimit( $namespace );
315 $length = $this->limit[0];
316 $i = $smcount = 0;
317
318 $fns = $wgContLang->getFormattedNsText( $namespace );
319 $this->output( "$namespace ($fns)\n" );
320 $skippedRedirects = 0; // Number of redirects skipped for that namespace
321 foreach ( $res as $row ) {
322 if ( $this->skipRedirects && $row->page_is_redirect ) {
323 $skippedRedirects++;
324 continue;
325 }
326
327 if ( $i++ === 0 || $i === $this->url_limit + 1 || $length + $this->limit[1] + $this->limit[2] > $this->size_limit ) {
328 if ( $this->file !== false ) {
329 $this->write( $this->file, $this->closeFile() );
330 $this->close( $this->file );
331 }
332 $filename = $this->sitemapFilename( $namespace, $smcount++ );
333 $this->file = $this->open( $this->fspath . $filename, 'wb' );
334 $this->write( $this->file, $this->openFile() );
335 fwrite( $this->findex, $this->indexEntry( $filename ) );
336 $this->output( "\t$this->fspath$filename\n" );
337 $length = $this->limit[0];
338 $i = 1;
339 }
340 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
341 $date = wfTimestamp( TS_ISO_8601, $row->page_touched );
342 $entry = $this->fileEntry( $title->getCanonicalURL(), $date, $this->priority( $namespace ) );
343 $length += strlen( $entry );
344 $this->write( $this->file, $entry );
345 // generate pages for language variants
346 if ( $wgContLang->hasVariants() ) {
347 $variants = $wgContLang->getVariants();
348 foreach ( $variants as $vCode ) {
349 if ( $vCode == $wgContLang->getCode() ) {
350 continue; // we don't want default variant
351 }
352 $entry = $this->fileEntry( $title->getCanonicalURL( '', $vCode ), $date, $this->priority( $namespace ) );
353 $length += strlen( $entry );
354 $this->write( $this->file, $entry );
355 }
356 }
357 }
358
359 if ( $this->skipRedirects && $skippedRedirects > 0 ) {
360 $this->output( " skipped $skippedRedirects redirect(s)\n" );
361 }
362
363 if ( $this->file ) {
364 $this->write( $this->file, $this->closeFile() );
365 $this->close( $this->file );
366 }
367 }
368 fwrite( $this->findex, $this->closeIndex() );
369 fclose( $this->findex );
370 }
371
372 /**
373 * gzopen() / fopen() wrapper
374 *
375 * @param string $file
376 * @param string $flags
377 * @return resource
378 */
379 function open( $file, $flags ) {
380 $resource = $this->compress ? gzopen( $file, $flags ) : fopen( $file, $flags );
381 if ( $resource === false ) {
382 throw new MWException( __METHOD__ . " error opening file $file with flags $flags. Check permissions?" );
383 }
384 return $resource;
385 }
386
387 /**
388 * gzwrite() / fwrite() wrapper
389 *
390 * @param resource $handle
391 * @param string $str
392 */
393 function write( &$handle, $str ) {
394 if ( $handle === true || $handle === false ) {
395 throw new MWException( __METHOD__ . " was passed a boolean as a file handle.\n" );
396 }
397 if ( $this->compress ) {
398 gzwrite( $handle, $str );
399 } else {
400 fwrite( $handle, $str );
401 }
402 }
403
404 /**
405 * gzclose() / fclose() wrapper
406 *
407 * @param resource $handle
408 */
409 function close( &$handle ) {
410 if ( $this->compress ) {
411 gzclose( $handle );
412 } else {
413 fclose( $handle );
414 }
415 }
416
417 /**
418 * Get a sitemap filename
419 *
420 * @param int $namespace The namespace
421 * @param int $count The count
422 * @return string
423 */
424 function sitemapFilename( $namespace, $count ) {
425 $ext = $this->compress ? '.gz' : '';
426 return "sitemap-{$this->identifier}-NS_$namespace-$count.xml$ext";
427 }
428
429 /**
430 * Return the XML required to open an XML file
431 *
432 * @return string
433 */
434 function xmlHead() {
435 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
436 }
437
438 /**
439 * Return the XML schema being used
440 *
441 * @return string
442 */
443 function xmlSchema() {
444 return 'http://www.sitemaps.org/schemas/sitemap/0.9';
445 }
446
447 /**
448 * Return the XML required to open a sitemap index file
449 *
450 * @return string
451 */
452 function openIndex() {
453 return $this->xmlHead() . '<sitemapindex xmlns="' . $this->xmlSchema() . '">' . "\n";
454 }
455
456 /**
457 * Return the XML for a single sitemap indexfile entry
458 *
459 * @param string $filename The filename of the sitemap file
460 * @return string
461 */
462 function indexEntry( $filename ) {
463 return
464 "\t<sitemap>\n" .
465 "\t\t<loc>{$this->urlpath}$filename</loc>\n" .
466 "\t\t<lastmod>{$this->timestamp}</lastmod>\n" .
467 "\t</sitemap>\n";
468 }
469
470 /**
471 * Return the XML required to close a sitemap index file
472 *
473 * @return string
474 */
475 function closeIndex() {
476 return "</sitemapindex>\n";
477 }
478
479 /**
480 * Return the XML required to open a sitemap file
481 *
482 * @return string
483 */
484 function openFile() {
485 return $this->xmlHead() . '<urlset xmlns="' . $this->xmlSchema() . '">' . "\n";
486 }
487
488 /**
489 * Return the XML for a single sitemap entry
490 *
491 * @param string $url An RFC 2396 compliant URL
492 * @param string $date A ISO 8601 date
493 * @param string $priority A priority indicator, 0.0 - 1.0 inclusive with a 0.1 stepsize
494 * @return string
495 */
496 function fileEntry( $url, $date, $priority ) {
497 return
498 "\t<url>\n" .
499 // bug 34666: $url may contain bad characters such as ampersands.
500 "\t\t<loc>" . htmlspecialchars( $url ) . "</loc>\n" .
501 "\t\t<lastmod>$date</lastmod>\n" .
502 "\t\t<priority>$priority</priority>\n" .
503 "\t</url>\n";
504 }
505
506 /**
507 * Return the XML required to close sitemap file
508 *
509 * @return string
510 */
511 function closeFile() {
512 return "</urlset>\n";
513 }
514
515 /**
516 * Populate $this->limit
517 *
518 * @param int $namespace
519 */
520 function generateLimit( $namespace ) {
521 // bug 17961: make a title with the longest possible URL in this namespace
522 $title = Title::makeTitle( $namespace, str_repeat( "\xf0\xa8\xae\x81", 63 ) . "\xe5\x96\x83" );
523
524 $this->limit = array(
525 strlen( $this->openFile() ),
526 strlen( $this->fileEntry( $title->getCanonicalURL(), wfTimestamp( TS_ISO_8601, wfTimestamp() ), $this->priority( $namespace ) ) ),
527 strlen( $this->closeFile() )
528 );
529 }
530 }
531
532 $maintClass = "GenerateSitemap";
533 require_once RUN_MAINTENANCE_IF_MAIN;