MediaWiki 1.43.1
generateSitemap.php
Go to the documentation of this file.
1<?php
34
35// @codeCoverageIgnoreStart
36require_once __DIR__ . '/Maintenance.php';
37// @codeCoverageIgnoreEnd
38
44class GenerateSitemap extends Maintenance {
45 private const GS_MAIN = -2;
46 private const GS_TALK = -1;
47
55 public $url_limit;
56
65
71 public $fspath;
72
79 public $urlpath;
80
86 public $compress;
87
94
100 public $limit = [];
101
107 public $priorities = [];
108
114 public $namespaces = [];
115
122
128 public $dbr;
129
135 public $findex;
136
142 public $file;
143
149 private $identifier;
150
151 public function __construct() {
152 parent::__construct();
153 $this->addDescription( 'Creates a sitemap for the site' );
154 $this->addOption(
155 'fspath',
156 'The file system path to save to, e.g. /tmp/sitemap; defaults to current directory',
157 false,
158 true
159 );
160 $this->addOption(
161 'urlpath',
162 'The URL path corresponding to --fspath, prepended to filenames in the index; '
163 . 'defaults to an empty string',
164 false,
165 true
166 );
167 $this->addOption(
168 'compress',
169 'Compress the sitemap files, can take value yes|no, default yes',
170 false,
171 true
172 );
173 $this->addOption( 'skip-redirects', 'Do not include redirecting articles in the sitemap' );
174 $this->addOption(
175 'identifier',
176 'What site identifier to use for the wiki, defaults to $wgDBname',
177 false,
178 true
179 );
180 $this->addOption(
181 'namespaces',
182 'Only include pages in these namespaces in the sitemap, ' .
183 'defaults to the value of wgSitemapNamespaces if not defined.',
184 false, true, false, true
185 );
186 }
187
191 public function execute() {
192 $this->setNamespacePriorities();
193 $this->url_limit = 50000;
194 $this->size_limit = ( 2 ** 20 ) * 10;
195
196 # Create directory if needed
197 $fspath = $this->getOption( 'fspath', getcwd() );
198 if ( !wfMkdirParents( $fspath, null, __METHOD__ ) ) {
199 $this->fatalError( "Can not create directory $fspath." );
200 }
201
202 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
203 $this->fspath = realpath( $fspath ) . DIRECTORY_SEPARATOR;
204 $this->urlpath = $this->getOption( 'urlpath', "" );
205 if ( $this->urlpath !== "" && substr( $this->urlpath, -1 ) !== '/' ) {
206 $this->urlpath .= '/';
207 }
208 $this->identifier = $this->getOption( 'identifier', $dbDomain );
209 $this->compress = $this->getOption( 'compress', 'yes' ) !== 'no';
210 $this->skipRedirects = $this->hasOption( 'skip-redirects' );
211 $this->dbr = $this->getReplicaDB();
212 $this->generateNamespaces();
213 $this->timestamp = wfTimestamp( TS_ISO_8601, wfTimestampNow() );
214 $encIdentifier = rawurlencode( $this->identifier );
215 $this->findex = fopen( "{$this->fspath}sitemap-index-{$encIdentifier}.xml", 'wb' );
216 $this->main();
217 }
218
219 private function setNamespacePriorities() {
220 $sitemapNamespacesPriorities = $this->getConfig()->get( MainConfigNames::SitemapNamespacesPriorities );
221
222 // Custom main namespaces
223 $this->priorities[self::GS_MAIN] = '0.5';
224 // Custom talk namespaces
225 $this->priorities[self::GS_TALK] = '0.1';
226 // MediaWiki standard namespaces
227 $this->priorities[NS_MAIN] = '1.0';
228 $this->priorities[NS_TALK] = '0.1';
229 $this->priorities[NS_USER] = '0.5';
230 $this->priorities[NS_USER_TALK] = '0.1';
231 $this->priorities[NS_PROJECT] = '0.5';
232 $this->priorities[NS_PROJECT_TALK] = '0.1';
233 $this->priorities[NS_FILE] = '0.5';
234 $this->priorities[NS_FILE_TALK] = '0.1';
235 $this->priorities[NS_MEDIAWIKI] = '0.0';
236 $this->priorities[NS_MEDIAWIKI_TALK] = '0.1';
237 $this->priorities[NS_TEMPLATE] = '0.0';
238 $this->priorities[NS_TEMPLATE_TALK] = '0.1';
239 $this->priorities[NS_HELP] = '0.5';
240 $this->priorities[NS_HELP_TALK] = '0.1';
241 $this->priorities[NS_CATEGORY] = '0.5';
242 $this->priorities[NS_CATEGORY_TALK] = '0.1';
243
244 // Custom priorities
245 if ( $sitemapNamespacesPriorities !== false ) {
249 foreach ( $sitemapNamespacesPriorities as $namespace => $priority ) {
250 $float = floatval( $priority );
251 if ( $float > 1.0 ) {
252 $priority = '1.0';
253 } elseif ( $float < 0.0 ) {
254 $priority = '0.0';
255 }
256 $this->priorities[$namespace] = $priority;
257 }
258 }
259 }
260
264 private function generateNamespaces() {
265 // Use the namespaces passed in via command line arguments if they are set.
266 $sitemapNamespacesFromConfig = $this->getOption( 'namespaces' );
267 if ( is_array( $sitemapNamespacesFromConfig ) && count( $sitemapNamespacesFromConfig ) > 0 ) {
268 $this->namespaces = $sitemapNamespacesFromConfig;
269
270 return;
271 }
272
273 // Only generate for specific namespaces if $wgSitemapNamespaces is an array.
274 $sitemapNamespaces = $this->getConfig()->get( MainConfigNames::SitemapNamespaces );
275 if ( is_array( $sitemapNamespaces ) ) {
276 $this->namespaces = $sitemapNamespaces;
277
278 return;
279 }
280
281 $res = $this->dbr->newSelectQueryBuilder()
282 ->select( [ 'page_namespace' ] )
283 ->from( 'page' )
284 ->groupBy( 'page_namespace' )
285 ->orderBy( 'page_namespace' )
286 ->caller( __METHOD__ )->fetchResultSet();
287
288 foreach ( $res as $row ) {
289 $this->namespaces[] = $row->page_namespace;
290 }
291 }
292
299 private function priority( $namespace ) {
300 return $this->priorities[$namespace] ?? $this->guessPriority( $namespace );
301 }
302
311 private function guessPriority( $namespace ) {
312 return $this->getServiceContainer()->getNamespaceInfo()->isSubject( $namespace )
313 ? $this->priorities[self::GS_MAIN]
314 : $this->priorities[self::GS_TALK];
315 }
316
323 private function getPageRes( $namespace ) {
324 return $this->dbr->newSelectQueryBuilder()
325 ->select( [ 'page_namespace', 'page_title', 'page_touched', 'page_is_redirect', 'pp_propname' ] )
326 ->from( 'page' )
327 ->leftJoin( 'page_props', null, [ 'page_id = pp_page', 'pp_propname' => 'noindex' ] )
328 ->where( [ 'page_namespace' => $namespace ] )
329 ->caller( __METHOD__ )->fetchResultSet();
330 }
331
335 public function main() {
336 $services = $this->getServiceContainer();
337 $contLang = $services->getContentLanguage();
338 $langConverter = $services->getLanguageConverterFactory()->getLanguageConverter( $contLang );
339 $serverUrl = $services->getUrlUtils()->getServer( PROTO_CANONICAL ) ?? '';
340
341 fwrite( $this->findex, $this->openIndex() );
342
343 foreach ( $this->namespaces as $namespace ) {
344 $res = $this->getPageRes( $namespace );
345 $this->file = false;
346 $this->generateLimit( $namespace );
347 $length = $this->limit[0];
348 $i = $smcount = 0;
349
350 $fns = $contLang->getFormattedNsText( $namespace );
351 $this->output( "$namespace ($fns)\n" );
352 $skippedRedirects = 0; // Number of redirects skipped for that namespace
353 $skippedNoindex = 0; // Number of pages with __NOINDEX__ switch for that NS
354 foreach ( $res as $row ) {
355 if ( $row->pp_propname === 'noindex' ) {
356 $skippedNoindex++;
357 continue;
358 }
359
360 if ( $this->skipRedirects && $row->page_is_redirect ) {
361 $skippedRedirects++;
362 continue;
363 }
364
365 if ( $i++ === 0
366 || $i === $this->url_limit + 1
367 || $length + $this->limit[1] + $this->limit[2] > $this->size_limit
368 ) {
369 if ( $this->file !== false ) {
370 $this->write( $this->file, $this->closeFile() );
371 $this->close( $this->file );
372 }
373 $filename = $this->sitemapFilename( $namespace, $smcount++ );
374 $this->file = $this->open( $this->fspath . $filename, 'wb' );
375 $this->write( $this->file, $this->openFile() );
376 fwrite( $this->findex, $this->indexEntry( $filename, $serverUrl ) );
377 $this->output( "\t$this->fspath$filename\n" );
378 $length = $this->limit[0];
379 $i = 1;
380 }
381 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
382 $date = wfTimestamp( TS_ISO_8601, $row->page_touched );
383 $entry = $this->fileEntry( $title->getCanonicalURL(), $date, $this->priority( $namespace ) );
384 $length += strlen( $entry );
385 $this->write( $this->file, $entry );
386 // generate pages for language variants
387 if ( $langConverter->hasVariants() ) {
388 $variants = $langConverter->getVariants();
389 foreach ( $variants as $vCode ) {
390 if ( $vCode == $contLang->getCode() ) {
391 continue; // we don't want default variant
392 }
393 $entry = $this->fileEntry(
394 $title->getCanonicalURL( [ 'variant' => $vCode ] ),
395 $date,
396 $this->priority( $namespace )
397 );
398 $length += strlen( $entry );
399 $this->write( $this->file, $entry );
400 }
401 }
402 }
403
404 if ( $skippedNoindex > 0 ) {
405 $this->output( " skipped $skippedNoindex page(s) with __NOINDEX__ switch\n" );
406 }
407
408 if ( $this->skipRedirects && $skippedRedirects > 0 ) {
409 $this->output( " skipped $skippedRedirects redirect(s)\n" );
410 }
411
412 if ( $this->file ) {
413 $this->write( $this->file, $this->closeFile() );
414 $this->close( $this->file );
415 }
416 }
417 fwrite( $this->findex, $this->closeIndex() );
418 fclose( $this->findex );
419 }
420
428 private function open( $file, $flags ) {
429 $resource = $this->compress ? gzopen( $file, $flags ) : fopen( $file, $flags );
430 if ( $resource === false ) {
431 throw new RuntimeException( __METHOD__
432 . " error opening file $file with flags $flags. Check permissions?" );
433 }
434
435 return $resource;
436 }
437
444 private function write( &$handle, $str ) {
445 if ( $handle === true || $handle === false ) {
446 throw new InvalidArgumentException( __METHOD__ . " was passed a boolean as a file handle.\n" );
447 }
448 if ( $this->compress ) {
449 gzwrite( $handle, $str );
450 } else {
451 fwrite( $handle, $str );
452 }
453 }
454
460 private function close( &$handle ) {
461 if ( $this->compress ) {
462 gzclose( $handle );
463 } else {
464 fclose( $handle );
465 }
466 }
467
475 private function sitemapFilename( $namespace, $count ) {
476 $ext = $this->compress ? '.gz' : '';
477
478 return "sitemap-{$this->identifier}-NS_$namespace-$count.xml$ext";
479 }
480
486 private function xmlHead() {
487 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
488 }
489
495 private function xmlSchema() {
496 return 'http://www.sitemaps.org/schemas/sitemap/0.9';
497 }
498
504 private function openIndex() {
505 return $this->xmlHead() . '<sitemapindex xmlns="' . $this->xmlSchema() . '">' . "\n";
506 }
507
515 private function indexEntry( $filename, $serverUrl ) {
516 return "\t<sitemap>\n" .
517 "\t\t<loc>" . $serverUrl .
518 ( substr( $this->urlpath, 0, 1 ) === "/" ? "" : "/" ) .
519 "{$this->urlpath}$filename</loc>\n" .
520 "\t\t<lastmod>{$this->timestamp}</lastmod>\n" .
521 "\t</sitemap>\n";
522 }
523
529 private function closeIndex() {
530 return "</sitemapindex>\n";
531 }
532
538 private function openFile() {
539 return $this->xmlHead() . '<urlset xmlns="' . $this->xmlSchema() . '">' . "\n";
540 }
541
550 private function fileEntry( $url, $date, $priority ) {
551 return "\t<url>\n" .
552 // T36666: $url may contain bad characters such as ampersands.
553 "\t\t<loc>" . htmlspecialchars( $url ) . "</loc>\n" .
554 "\t\t<lastmod>$date</lastmod>\n" .
555 "\t\t<priority>$priority</priority>\n" .
556 "\t</url>\n";
557 }
558
564 private function closeFile() {
565 return "</urlset>\n";
566 }
567
573 private function generateLimit( $namespace ) {
574 // T19961: make a title with the longest possible URL in this namespace
575 $title = Title::makeTitle( $namespace, str_repeat( "\u{28B81}", 63 ) . "\u{5583}" );
576
577 $this->limit = [
578 strlen( $this->openFile() ),
579 strlen( $this->fileEntry(
580 $title->getCanonicalURL(),
581 wfTimestamp( TS_ISO_8601, wfTimestamp() ),
582 $this->priority( $namespace )
583 ) ),
584 strlen( $this->closeFile() )
585 ];
586 }
587}
588
589// @codeCoverageIgnoreStart
590$maintClass = GenerateSitemap::class;
591require_once RUN_MAINTENANCE_IF_MAIN;
592// @codeCoverageIgnoreEnd
const PROTO_CANONICAL
Definition Defines.php:210
const NS_HELP
Definition Defines.php:77
const NS_USER
Definition Defines.php:67
const NS_FILE
Definition Defines.php:71
const NS_MEDIAWIKI_TALK
Definition Defines.php:74
const NS_MAIN
Definition Defines.php:65
const NS_PROJECT_TALK
Definition Defines.php:70
const NS_MEDIAWIKI
Definition Defines.php:73
const NS_TEMPLATE
Definition Defines.php:75
const NS_FILE_TALK
Definition Defines.php:72
const NS_HELP_TALK
Definition Defines.php:78
const NS_CATEGORY_TALK
Definition Defines.php:80
const NS_TALK
Definition Defines.php:66
const NS_USER_TALK
Definition Defines.php:68
const NS_PROJECT
Definition Defines.php:69
const NS_CATEGORY
Definition Defines.php:79
const NS_TEMPLATE_TALK
Definition Defines.php:76
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfMkdirParents( $dir, $mode=null, $caller=null)
Make directory, and make all parent directories if they don't exist.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Maintenance script that generates a sitemap for the site.
string $timestamp
When this sitemap batch was generated.
IDatabase $dbr
A database replica DB object.
string $fspath
The path to prepend to the filename.
array $priorities
Key => value entries of namespaces and their priorities.
bool $skipRedirects
Whether or not to include redirection pages.
array $limit
The number of entries to save in each sitemap file.
int $size_limit
The maximum size of a sitemap file.
bool $compress
Whether or not to use compression.
array $namespaces
A one-dimensional array of namespaces in the wiki.
string $urlpath
The URL path to prepend to filenames in the index; should resolve to the same directory as $fspath.
resource $findex
A resource pointing to the sitemap index file.
int $url_limit
The maximum amount of urls in a sitemap file.
resource false $file
A resource pointing to a sitemap file.
A class containing constants representing the names of configuration variables.
Represents a title within MediaWiki.
Definition Title.php:78
Tools for dealing with other locally-hosted wikis.
Definition WikiMap.php:31
Interface to a relational database.
Definition IDatabase.php:48
Result wrapper for grabbing data queried from an IDatabase object.