MediaWiki master
generateSitemap.php
Go to the documentation of this file.
1<?php
35
36// @codeCoverageIgnoreStart
37require_once __DIR__ . '/Maintenance.php';
38// @codeCoverageIgnoreEnd
39
46 private const GS_MAIN = -2;
47 private const GS_TALK = -1;
48
56 public $url_limit;
57
66
72 public $fspath;
73
80 public $urlpath;
81
87 public $compress;
88
95
101 public $limit = [];
102
108 public $priorities = [];
109
115 public $namespaces = [];
116
123
129 public $dbr;
130
136 public $findex;
137
143 public $file;
144
150 private $identifier;
151
152 public function __construct() {
153 parent::__construct();
154 $this->addDescription( 'Creates a sitemap for the site' );
155 $this->addOption(
156 'fspath',
157 'The file system path to save to, e.g. /tmp/sitemap; defaults to current directory',
158 false,
159 true
160 );
161 $this->addOption(
162 'urlpath',
163 'The URL path corresponding to --fspath, prepended to filenames in the index; '
164 . 'defaults to an empty string',
165 false,
166 true
167 );
168 $this->addOption(
169 'compress',
170 'Compress the sitemap files, can take value yes|no, default yes',
171 false,
172 true
173 );
174 $this->addOption( 'skip-redirects', 'Do not include redirecting articles in the sitemap' );
175 $this->addOption(
176 'identifier',
177 'What site identifier to use for the wiki, defaults to $wgDBname',
178 false,
179 true
180 );
181 $this->addOption(
182 'namespaces',
183 'Only include pages in these namespaces in the sitemap, ' .
184 'defaults to the value of wgSitemapNamespaces if not defined.',
185 false, true, false, true
186 );
187 }
188
192 public function execute() {
193 $this->setNamespacePriorities();
194 $this->url_limit = 50000;
195 $this->size_limit = ( 2 ** 20 ) * 10;
196
197 # Create directory if needed
198 $fspath = $this->getOption( 'fspath', getcwd() );
199 if ( !wfMkdirParents( $fspath, null, __METHOD__ ) ) {
200 $this->fatalError( "Can not create directory $fspath." );
201 }
202
203 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
204 $this->fspath = realpath( $fspath ) . DIRECTORY_SEPARATOR;
205 $this->urlpath = $this->getOption( 'urlpath', "" );
206 if ( $this->urlpath !== "" && substr( $this->urlpath, -1 ) !== '/' ) {
207 $this->urlpath .= '/';
208 }
209 $this->identifier = $this->getOption( 'identifier', $dbDomain );
210 $this->compress = $this->getOption( 'compress', 'yes' ) !== 'no';
211 $this->skipRedirects = $this->hasOption( 'skip-redirects' );
212 $this->dbr = $this->getReplicaDB();
213 $this->generateNamespaces();
214 $this->timestamp = wfTimestamp( TS_ISO_8601, wfTimestampNow() );
215 $encIdentifier = rawurlencode( $this->identifier );
216 $this->findex = fopen( "{$this->fspath}sitemap-index-{$encIdentifier}.xml", 'wb' );
217 $this->main();
218 }
219
220 private function setNamespacePriorities() {
221 $sitemapNamespacesPriorities = $this->getConfig()->get( MainConfigNames::SitemapNamespacesPriorities );
222
223 // Custom main namespaces
224 $this->priorities[self::GS_MAIN] = '0.5';
225 // Custom talk namespaces
226 $this->priorities[self::GS_TALK] = '0.1';
227 // MediaWiki standard namespaces
228 $this->priorities[NS_MAIN] = '1.0';
229 $this->priorities[NS_TALK] = '0.1';
230 $this->priorities[NS_USER] = '0.5';
231 $this->priorities[NS_USER_TALK] = '0.1';
232 $this->priorities[NS_PROJECT] = '0.5';
233 $this->priorities[NS_PROJECT_TALK] = '0.1';
234 $this->priorities[NS_FILE] = '0.5';
235 $this->priorities[NS_FILE_TALK] = '0.1';
236 $this->priorities[NS_MEDIAWIKI] = '0.0';
237 $this->priorities[NS_MEDIAWIKI_TALK] = '0.1';
238 $this->priorities[NS_TEMPLATE] = '0.0';
239 $this->priorities[NS_TEMPLATE_TALK] = '0.1';
240 $this->priorities[NS_HELP] = '0.5';
241 $this->priorities[NS_HELP_TALK] = '0.1';
242 $this->priorities[NS_CATEGORY] = '0.5';
243 $this->priorities[NS_CATEGORY_TALK] = '0.1';
244
245 // Custom priorities
246 if ( $sitemapNamespacesPriorities !== false ) {
250 foreach ( $sitemapNamespacesPriorities as $namespace => $priority ) {
251 $float = floatval( $priority );
252 if ( $float > 1.0 ) {
253 $priority = '1.0';
254 } elseif ( $float < 0.0 ) {
255 $priority = '0.0';
256 }
257 $this->priorities[$namespace] = $priority;
258 }
259 }
260 }
261
265 private function generateNamespaces() {
266 // Use the namespaces passed in via command line arguments if they are set.
267 $sitemapNamespacesFromConfig = $this->getOption( 'namespaces' );
268 if ( is_array( $sitemapNamespacesFromConfig ) && count( $sitemapNamespacesFromConfig ) > 0 ) {
269 $this->namespaces = $sitemapNamespacesFromConfig;
270
271 return;
272 }
273
274 // Only generate for specific namespaces if $wgSitemapNamespaces is an array.
275 $sitemapNamespaces = $this->getConfig()->get( MainConfigNames::SitemapNamespaces );
276 if ( is_array( $sitemapNamespaces ) ) {
277 $this->namespaces = $sitemapNamespaces;
278
279 return;
280 }
281
282 $res = $this->dbr->newSelectQueryBuilder()
283 ->select( [ 'page_namespace' ] )
284 ->from( 'page' )
285 ->groupBy( 'page_namespace' )
286 ->orderBy( 'page_namespace' )
287 ->caller( __METHOD__ )->fetchResultSet();
288
289 foreach ( $res as $row ) {
290 $this->namespaces[] = $row->page_namespace;
291 }
292 }
293
300 private function priority( $namespace ) {
301 return $this->priorities[$namespace] ?? $this->guessPriority( $namespace );
302 }
303
312 private function guessPriority( $namespace ) {
313 return $this->getServiceContainer()->getNamespaceInfo()->isSubject( $namespace )
314 ? $this->priorities[self::GS_MAIN]
315 : $this->priorities[self::GS_TALK];
316 }
317
324 private function getPageRes( $namespace ) {
325 return $this->dbr->newSelectQueryBuilder()
326 ->select( [ 'page_namespace', 'page_title', 'page_touched', 'page_is_redirect', 'pp_propname' ] )
327 ->from( 'page' )
328 ->leftJoin( 'page_props', null, [ 'page_id = pp_page', 'pp_propname' => 'noindex' ] )
329 ->where( [ 'page_namespace' => $namespace ] )
330 ->caller( __METHOD__ )->fetchResultSet();
331 }
332
336 public function main() {
337 $services = $this->getServiceContainer();
338 $contLang = $services->getContentLanguage();
339 $langConverter = $services->getLanguageConverterFactory()->getLanguageConverter( $contLang );
340 $serverUrl = $services->getUrlUtils()->getServer( PROTO_CANONICAL ) ?? '';
341
342 fwrite( $this->findex, $this->openIndex() );
343
344 foreach ( $this->namespaces as $namespace ) {
345 $res = $this->getPageRes( $namespace );
346 $this->file = false;
347 $this->generateLimit( $namespace );
348 $length = $this->limit[0];
349 $i = $smcount = 0;
350
351 $fns = $contLang->getFormattedNsText( $namespace );
352 $this->output( "$namespace ($fns)\n" );
353 $skippedRedirects = 0; // Number of redirects skipped for that namespace
354 $skippedNoindex = 0; // Number of pages with __NOINDEX__ switch for that NS
355 foreach ( $res as $row ) {
356 if ( $row->pp_propname === 'noindex' ) {
357 $skippedNoindex++;
358 continue;
359 }
360
361 if ( $this->skipRedirects && $row->page_is_redirect ) {
362 $skippedRedirects++;
363 continue;
364 }
365
366 if ( $i++ === 0
367 || $i === $this->url_limit + 1
368 || $length + $this->limit[1] + $this->limit[2] > $this->size_limit
369 ) {
370 if ( $this->file !== false ) {
371 $this->write( $this->file, $this->closeFile() );
372 $this->close( $this->file );
373 }
374 $filename = $this->sitemapFilename( $namespace, $smcount++ );
375 $this->file = $this->open( $this->fspath . $filename, 'wb' );
376 $this->write( $this->file, $this->openFile() );
377 fwrite( $this->findex, $this->indexEntry( $filename, $serverUrl ) );
378 $this->output( "\t$this->fspath$filename\n" );
379 $length = $this->limit[0];
380 $i = 1;
381 }
382 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
383 $date = wfTimestamp( TS_ISO_8601, $row->page_touched );
384 $entry = $this->fileEntry( $title->getCanonicalURL(), $date, $this->priority( $namespace ) );
385 $length += strlen( $entry );
386 $this->write( $this->file, $entry );
387 // generate pages for language variants
388 if ( $langConverter->hasVariants() ) {
389 $variants = $langConverter->getVariants();
390 foreach ( $variants as $vCode ) {
391 if ( $vCode == $contLang->getCode() ) {
392 continue; // we don't want default variant
393 }
394 $entry = $this->fileEntry(
395 $title->getCanonicalURL( [ 'variant' => $vCode ] ),
396 $date,
397 $this->priority( $namespace )
398 );
399 $length += strlen( $entry );
400 $this->write( $this->file, $entry );
401 }
402 }
403 }
404
405 if ( $skippedNoindex > 0 ) {
406 $this->output( " skipped $skippedNoindex page(s) with __NOINDEX__ switch\n" );
407 }
408
409 if ( $this->skipRedirects && $skippedRedirects > 0 ) {
410 $this->output( " skipped $skippedRedirects redirect(s)\n" );
411 }
412
413 if ( $this->file ) {
414 $this->write( $this->file, $this->closeFile() );
415 $this->close( $this->file );
416 }
417 }
418 fwrite( $this->findex, $this->closeIndex() );
419 fclose( $this->findex );
420 }
421
429 private function open( $file, $flags ) {
430 $resource = $this->compress ? gzopen( $file, $flags ) : fopen( $file, $flags );
431 if ( $resource === false ) {
432 throw new RuntimeException( __METHOD__
433 . " error opening file $file with flags $flags. Check permissions?" );
434 }
435
436 return $resource;
437 }
438
445 private function write( &$handle, $str ) {
446 if ( $handle === true || $handle === false ) {
447 throw new InvalidArgumentException( __METHOD__ . " was passed a boolean as a file handle.\n" );
448 }
449 if ( $this->compress ) {
450 gzwrite( $handle, $str );
451 } else {
452 fwrite( $handle, $str );
453 }
454 }
455
461 private function close( &$handle ) {
462 if ( $this->compress ) {
463 gzclose( $handle );
464 } else {
465 fclose( $handle );
466 }
467 }
468
476 private function sitemapFilename( $namespace, $count ) {
477 $ext = $this->compress ? '.gz' : '';
478
479 return "sitemap-{$this->identifier}-NS_$namespace-$count.xml$ext";
480 }
481
487 private function xmlHead() {
488 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
489 }
490
496 private function xmlSchema() {
497 return 'http://www.sitemaps.org/schemas/sitemap/0.9';
498 }
499
505 private function openIndex() {
506 return $this->xmlHead() . '<sitemapindex xmlns="' . $this->xmlSchema() . '">' . "\n";
507 }
508
516 private function indexEntry( $filename, $serverUrl ) {
517 return "\t<sitemap>\n" .
518 "\t\t<loc>" . $serverUrl .
519 ( substr( $this->urlpath, 0, 1 ) === "/" ? "" : "/" ) .
520 "{$this->urlpath}$filename</loc>\n" .
521 "\t\t<lastmod>{$this->timestamp}</lastmod>\n" .
522 "\t</sitemap>\n";
523 }
524
530 private function closeIndex() {
531 return "</sitemapindex>\n";
532 }
533
539 private function openFile() {
540 return $this->xmlHead() . '<urlset xmlns="' . $this->xmlSchema() . '">' . "\n";
541 }
542
551 private function fileEntry( $url, $date, $priority ) {
552 return "\t<url>\n" .
553 // T36666: $url may contain bad characters such as ampersands.
554 "\t\t<loc>" . htmlspecialchars( $url ) . "</loc>\n" .
555 "\t\t<lastmod>$date</lastmod>\n" .
556 "\t\t<priority>$priority</priority>\n" .
557 "\t</url>\n";
558 }
559
565 private function closeFile() {
566 return "</urlset>\n";
567 }
568
574 private function generateLimit( $namespace ) {
575 // T19961: make a title with the longest possible URL in this namespace
576 $title = Title::makeTitle( $namespace, str_repeat( "\u{28B81}", 63 ) . "\u{5583}" );
577
578 $this->limit = [
579 strlen( $this->openFile() ),
580 strlen( $this->fileEntry(
581 $title->getCanonicalURL(),
582 wfTimestamp( TS_ISO_8601, wfTimestamp() ),
583 $this->priority( $namespace )
584 ) ),
585 strlen( $this->closeFile() )
586 ];
587 }
588}
589
590// @codeCoverageIgnoreStart
591$maintClass = GenerateSitemap::class;
592require_once RUN_MAINTENANCE_IF_MAIN;
593// @codeCoverageIgnoreEnd
const PROTO_CANONICAL
Definition Defines.php:216
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.
__construct()
Default constructor.
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.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
output( $out, $channel=null)
Throw some output to the user.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
hasOption( $name)
Checks to see if a particular option was set.
getOption( $name, $default=null)
Get an option, or return the default.
getServiceContainer()
Returns the main service container.
addDescription( $text)
Set the description text.
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.