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