MediaWiki master
generateSitemap.php
Go to the documentation of this file.
1<?php
34
35require_once __DIR__ . '/Maintenance.php';
36
43 private const GS_MAIN = -2;
44 private const GS_TALK = -1;
45
53 public $url_limit;
54
63
69 public $fspath;
70
77 public $urlpath;
78
84 public $compress;
85
92
98 public $limit = [];
99
105 public $priorities = [];
106
112 public $namespaces = [];
113
120
126 public $dbr;
127
133 public $findex;
134
140 public $file;
141
147 private $identifier;
148
149 public function __construct() {
150 parent::__construct();
151 $this->addDescription( 'Creates a sitemap for the site' );
152 $this->addOption(
153 'fspath',
154 'The file system path to save to, e.g. /tmp/sitemap; defaults to current directory',
155 false,
156 true
157 );
158 $this->addOption(
159 'urlpath',
160 'The URL path corresponding to --fspath, prepended to filenames in the index; '
161 . 'defaults to an empty string',
162 false,
163 true
164 );
165 $this->addOption(
166 'compress',
167 'Compress the sitemap files, can take value yes|no, default yes',
168 false,
169 true
170 );
171 $this->addOption( 'skip-redirects', 'Do not include redirecting articles in the sitemap' );
172 $this->addOption(
173 'identifier',
174 'What site identifier to use for the wiki, defaults to $wgDBname',
175 false,
176 true
177 );
178 $this->addOption(
179 'namespaces',
180 'Only include pages in these namespaces in the sitemap, ' .
181 'defaults to the value of wgSitemapNamespaces if not defined.',
182 false, true, false, true
183 );
184 }
185
189 public function execute() {
190 $this->setNamespacePriorities();
191 $this->url_limit = 50000;
192 $this->size_limit = ( 2 ** 20 ) * 10;
193
194 # Create directory if needed
195 $fspath = $this->getOption( 'fspath', getcwd() );
196 if ( !wfMkdirParents( $fspath, null, __METHOD__ ) ) {
197 $this->fatalError( "Can not create directory $fspath." );
198 }
199
200 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
201 $this->fspath = realpath( $fspath ) . DIRECTORY_SEPARATOR;
202 $this->urlpath = $this->getOption( 'urlpath', "" );
203 if ( $this->urlpath !== "" && substr( $this->urlpath, -1 ) !== '/' ) {
204 $this->urlpath .= '/';
205 }
206 $this->identifier = $this->getOption( 'identifier', $dbDomain );
207 $this->compress = $this->getOption( 'compress', 'yes' ) !== 'no';
208 $this->skipRedirects = $this->hasOption( 'skip-redirects' );
209 $this->dbr = $this->getReplicaDB();
210 $this->generateNamespaces();
211 $this->timestamp = wfTimestamp( TS_ISO_8601, wfTimestampNow() );
212 $encIdentifier = rawurlencode( $this->identifier );
213 $this->findex = fopen( "{$this->fspath}sitemap-index-{$encIdentifier}.xml", 'wb' );
214 $this->main();
215 }
216
217 private function setNamespacePriorities() {
218 $sitemapNamespacesPriorities = $this->getConfig()->get( MainConfigNames::SitemapNamespacesPriorities );
219
220 // Custom main namespaces
221 $this->priorities[self::GS_MAIN] = '0.5';
222 // Custom talk namespaces
223 $this->priorities[self::GS_TALK] = '0.1';
224 // MediaWiki standard namespaces
225 $this->priorities[NS_MAIN] = '1.0';
226 $this->priorities[NS_TALK] = '0.1';
227 $this->priorities[NS_USER] = '0.5';
228 $this->priorities[NS_USER_TALK] = '0.1';
229 $this->priorities[NS_PROJECT] = '0.5';
230 $this->priorities[NS_PROJECT_TALK] = '0.1';
231 $this->priorities[NS_FILE] = '0.5';
232 $this->priorities[NS_FILE_TALK] = '0.1';
233 $this->priorities[NS_MEDIAWIKI] = '0.0';
234 $this->priorities[NS_MEDIAWIKI_TALK] = '0.1';
235 $this->priorities[NS_TEMPLATE] = '0.0';
236 $this->priorities[NS_TEMPLATE_TALK] = '0.1';
237 $this->priorities[NS_HELP] = '0.5';
238 $this->priorities[NS_HELP_TALK] = '0.1';
239 $this->priorities[NS_CATEGORY] = '0.5';
240 $this->priorities[NS_CATEGORY_TALK] = '0.1';
241
242 // Custom priorities
243 if ( $sitemapNamespacesPriorities !== false ) {
247 foreach ( $sitemapNamespacesPriorities as $namespace => $priority ) {
248 $float = floatval( $priority );
249 if ( $float > 1.0 ) {
250 $priority = '1.0';
251 } elseif ( $float < 0.0 ) {
252 $priority = '0.0';
253 }
254 $this->priorities[$namespace] = $priority;
255 }
256 }
257 }
258
262 private function generateNamespaces() {
263 // Use the namespaces passed in via command line arguments if they are set.
264 $sitemapNamespacesFromConfig = $this->getOption( 'namespaces' );
265 if ( is_array( $sitemapNamespacesFromConfig ) && count( $sitemapNamespacesFromConfig ) > 0 ) {
266 $this->namespaces = $sitemapNamespacesFromConfig;
267
268 return;
269 }
270
271 // Only generate for specific namespaces if $wgSitemapNamespaces is an array.
272 $sitemapNamespaces = $this->getConfig()->get( MainConfigNames::SitemapNamespaces );
273 if ( is_array( $sitemapNamespaces ) ) {
274 $this->namespaces = $sitemapNamespaces;
275
276 return;
277 }
278
279 $res = $this->dbr->newSelectQueryBuilder()
280 ->select( [ 'page_namespace' ] )
281 ->from( 'page' )
282 ->groupBy( 'page_namespace' )
283 ->orderBy( 'page_namespace' )
284 ->caller( __METHOD__ )->fetchResultSet();
285
286 foreach ( $res as $row ) {
287 $this->namespaces[] = $row->page_namespace;
288 }
289 }
290
297 private function priority( $namespace ) {
298 return $this->priorities[$namespace] ?? $this->guessPriority( $namespace );
299 }
300
309 private function guessPriority( $namespace ) {
310 return $this->getServiceContainer()->getNamespaceInfo()->isSubject( $namespace )
311 ? $this->priorities[self::GS_MAIN]
312 : $this->priorities[self::GS_TALK];
313 }
314
321 private function getPageRes( $namespace ) {
322 return $this->dbr->newSelectQueryBuilder()
323 ->select( [ 'page_namespace', 'page_title', 'page_touched', 'page_is_redirect', 'pp_propname' ] )
324 ->from( 'page' )
325 ->leftJoin( 'page_props', null, [ 'page_id = pp_page', 'pp_propname' => 'noindex' ] )
326 ->where( [ 'page_namespace' => $namespace ] )
327 ->caller( __METHOD__ )->fetchResultSet();
328 }
329
333 public function main() {
334 $services = $this->getServiceContainer();
335 $contLang = $services->getContentLanguage();
336 $langConverter = $services->getLanguageConverterFactory()->getLanguageConverter( $contLang );
337
338 fwrite( $this->findex, $this->openIndex() );
339
340 foreach ( $this->namespaces as $namespace ) {
341 $res = $this->getPageRes( $namespace );
342 $this->file = false;
343 $this->generateLimit( $namespace );
344 $length = $this->limit[0];
345 $i = $smcount = 0;
346
347 $fns = $contLang->getFormattedNsText( $namespace );
348 $this->output( "$namespace ($fns)\n" );
349 $skippedRedirects = 0; // Number of redirects skipped for that namespace
350 $skippedNoindex = 0; // Number of pages with __NOINDEX__ switch for that NS
351 foreach ( $res as $row ) {
352 if ( $row->pp_propname === 'noindex' ) {
353 $skippedNoindex++;
354 continue;
355 }
356
357 if ( $this->skipRedirects && $row->page_is_redirect ) {
358 $skippedRedirects++;
359 continue;
360 }
361
362 if ( $i++ === 0
363 || $i === $this->url_limit + 1
364 || $length + $this->limit[1] + $this->limit[2] > $this->size_limit
365 ) {
366 if ( $this->file !== false ) {
367 $this->write( $this->file, $this->closeFile() );
368 $this->close( $this->file );
369 }
370 $filename = $this->sitemapFilename( $namespace, $smcount++ );
371 $this->file = $this->open( $this->fspath . $filename, 'wb' );
372 $this->write( $this->file, $this->openFile() );
373 fwrite( $this->findex, $this->indexEntry( $filename ) );
374 $this->output( "\t$this->fspath$filename\n" );
375 $length = $this->limit[0];
376 $i = 1;
377 }
378 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
379 $date = wfTimestamp( TS_ISO_8601, $row->page_touched );
380 $entry = $this->fileEntry( $title->getCanonicalURL(), $date, $this->priority( $namespace ) );
381 $length += strlen( $entry );
382 $this->write( $this->file, $entry );
383 // generate pages for language variants
384 if ( $langConverter->hasVariants() ) {
385 $variants = $langConverter->getVariants();
386 foreach ( $variants as $vCode ) {
387 if ( $vCode == $contLang->getCode() ) {
388 continue; // we don't want default variant
389 }
390 $entry = $this->fileEntry(
391 $title->getCanonicalURL( [ 'variant' => $vCode ] ),
392 $date,
393 $this->priority( $namespace )
394 );
395 $length += strlen( $entry );
396 $this->write( $this->file, $entry );
397 }
398 }
399 }
400
401 if ( $skippedNoindex > 0 ) {
402 $this->output( " skipped $skippedNoindex page(s) with __NOINDEX__ switch\n" );
403 }
404
405 if ( $this->skipRedirects && $skippedRedirects > 0 ) {
406 $this->output( " skipped $skippedRedirects redirect(s)\n" );
407 }
408
409 if ( $this->file ) {
410 $this->write( $this->file, $this->closeFile() );
411 $this->close( $this->file );
412 }
413 }
414 fwrite( $this->findex, $this->closeIndex() );
415 fclose( $this->findex );
416 }
417
425 private function open( $file, $flags ) {
426 $resource = $this->compress ? gzopen( $file, $flags ) : fopen( $file, $flags );
427 if ( $resource === false ) {
428 throw new RuntimeException( __METHOD__
429 . " error opening file $file with flags $flags. Check permissions?" );
430 }
431
432 return $resource;
433 }
434
441 private function write( &$handle, $str ) {
442 if ( $handle === true || $handle === false ) {
443 throw new InvalidArgumentException( __METHOD__ . " was passed a boolean as a file handle.\n" );
444 }
445 if ( $this->compress ) {
446 gzwrite( $handle, $str );
447 } else {
448 fwrite( $handle, $str );
449 }
450 }
451
457 private function close( &$handle ) {
458 if ( $this->compress ) {
459 gzclose( $handle );
460 } else {
461 fclose( $handle );
462 }
463 }
464
472 private function sitemapFilename( $namespace, $count ) {
473 $ext = $this->compress ? '.gz' : '';
474
475 return "sitemap-{$this->identifier}-NS_$namespace-$count.xml$ext";
476 }
477
483 private function xmlHead() {
484 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
485 }
486
492 private function xmlSchema() {
493 return 'http://www.sitemaps.org/schemas/sitemap/0.9';
494 }
495
501 private function openIndex() {
502 return $this->xmlHead() . '<sitemapindex xmlns="' . $this->xmlSchema() . '">' . "\n";
503 }
504
511 private function indexEntry( $filename ) {
512 return "\t<sitemap>\n" .
513 "\t\t<loc>" . wfGetServerUrl( PROTO_CANONICAL ) .
514 ( substr( $this->urlpath, 0, 1 ) === "/" ? "" : "/" ) .
515 "{$this->urlpath}$filename</loc>\n" .
516 "\t\t<lastmod>{$this->timestamp}</lastmod>\n" .
517 "\t</sitemap>\n";
518 }
519
525 private function closeIndex() {
526 return "</sitemapindex>\n";
527 }
528
534 private function openFile() {
535 return $this->xmlHead() . '<urlset xmlns="' . $this->xmlSchema() . '">' . "\n";
536 }
537
546 private function fileEntry( $url, $date, $priority ) {
547 return "\t<url>\n" .
548 // T36666: $url may contain bad characters such as ampersands.
549 "\t\t<loc>" . htmlspecialchars( $url ) . "</loc>\n" .
550 "\t\t<lastmod>$date</lastmod>\n" .
551 "\t\t<priority>$priority</priority>\n" .
552 "\t</url>\n";
553 }
554
560 private function closeFile() {
561 return "</urlset>\n";
562 }
563
569 private function generateLimit( $namespace ) {
570 // T19961: make a title with the longest possible URL in this namespace
571 $title = Title::makeTitle( $namespace, str_repeat( "\u{28B81}", 63 ) . "\u{5583}" );
572
573 $this->limit = [
574 strlen( $this->openFile() ),
575 strlen( $this->fileEntry(
576 $title->getCanonicalURL(),
577 wfTimestamp( TS_ISO_8601, wfTimestamp() ),
578 $this->priority( $namespace )
579 ) ),
580 strlen( $this->closeFile() )
581 ];
582 }
583}
584
585$maintClass = GenerateSitemap::class;
586require_once RUN_MAINTENANCE_IF_MAIN;
const PROTO_CANONICAL
Definition Defines.php:208
const NS_HELP
Definition Defines.php:76
const NS_USER
Definition Defines.php:66
const NS_FILE
Definition Defines.php:70
const NS_MEDIAWIKI_TALK
Definition Defines.php:73
const NS_MAIN
Definition Defines.php:64
const NS_PROJECT_TALK
Definition Defines.php:69
const NS_MEDIAWIKI
Definition Defines.php:72
const NS_TEMPLATE
Definition Defines.php:74
const NS_FILE_TALK
Definition Defines.php:71
const NS_HELP_TALK
Definition Defines.php:77
const NS_CATEGORY_TALK
Definition Defines.php:79
const NS_TALK
Definition Defines.php:65
const NS_USER_TALK
Definition Defines.php:67
const NS_PROJECT
Definition Defines.php:68
const NS_CATEGORY
Definition Defines.php:78
const NS_TEMPLATE_TALK
Definition Defines.php:75
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfGetServerUrl( $proto)
Get the wiki's "server", i.e.
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.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
output( $out, $channel=null)
Throw some output to the user.
hasOption( $name)
Checks to see if a particular option was set.
getServiceContainer()
Returns the main service container.
addDescription( $text)
Set the description text.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
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
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:36
Result wrapper for grabbing data queried from an IDatabase object.