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