MediaWiki REL1_35
generateSitemap.php
Go to the documentation of this file.
1<?php
32
33require_once __DIR__ . '/Maintenance.php';
34
41 private const GS_MAIN = -2;
42 private const GS_TALK = -1;
43
51 public $url_limit;
52
61
67 public $fspath;
68
75 public $urlpath;
76
82 public $compress;
83
90
96 public $limit = [];
97
103 public $priorities = [];
104
110 public $namespaces = [];
111
118
124 public $dbr;
125
131 public $findex;
132
138 public $file;
139
145 private $identifier;
146
147 public function __construct() {
148 parent::__construct();
149 $this->addDescription( 'Creates a sitemap for the site' );
150 $this->addOption(
151 'fspath',
152 'The file system path to save to, e.g. /tmp/sitemap; defaults to current directory',
153 false,
154 true
155 );
156 $this->addOption(
157 'urlpath',
158 'The URL path corresponding to --fspath, prepended to filenames in the index; '
159 . 'defaults to an empty string',
160 false,
161 true
162 );
163 $this->addOption(
164 'compress',
165 'Compress the sitemap files, can take value yes|no, default yes',
166 false,
167 true
168 );
169 $this->addOption( 'skip-redirects', 'Do not include redirecting articles in the sitemap' );
170 $this->addOption(
171 'identifier',
172 'What site identifier to use for the wiki, defaults to $wgDBname',
173 false,
174 true
175 );
176 }
177
181 public function execute() {
182 $this->setNamespacePriorities();
183 $this->url_limit = 50000;
184 $this->size_limit = ( 2 ** 20 ) * 10;
185
186 # Create directory if needed
187 $fspath = $this->getOption( 'fspath', getcwd() );
188 if ( !wfMkdirParents( $fspath, null, __METHOD__ ) ) {
189 $this->fatalError( "Can not create directory $fspath." );
190 }
191
192 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
193 $this->fspath = realpath( $fspath ) . DIRECTORY_SEPARATOR;
194 $this->urlpath = $this->getOption( 'urlpath', "" );
195 if ( $this->urlpath !== "" && substr( $this->urlpath, -1 ) !== '/' ) {
196 $this->urlpath .= '/';
197 }
198 $this->identifier = $this->getOption( 'identifier', $dbDomain );
199 $this->compress = $this->getOption( 'compress', 'yes' ) !== 'no';
200 $this->skipRedirects = $this->hasOption( 'skip-redirects' );
201 $this->dbr = $this->getDB( DB_REPLICA );
202 $this->generateNamespaces();
203 $this->timestamp = wfTimestamp( TS_ISO_8601, wfTimestampNow() );
204 $encIdentifier = rawurlencode( $this->identifier );
205 $this->findex = fopen( "{$this->fspath}sitemap-index-{$encIdentifier}.xml", 'wb' );
206 $this->main();
207 }
208
209 private function setNamespacePriorities() {
211
212 // Custom main namespaces
213 $this->priorities[self::GS_MAIN] = '0.5';
214 // Custom talk namesspaces
215 $this->priorities[self::GS_TALK] = '0.1';
216 // MediaWiki standard namespaces
217 $this->priorities[NS_MAIN] = '1.0';
218 $this->priorities[NS_TALK] = '0.1';
219 $this->priorities[NS_USER] = '0.5';
220 $this->priorities[NS_USER_TALK] = '0.1';
221 $this->priorities[NS_PROJECT] = '0.5';
222 $this->priorities[NS_PROJECT_TALK] = '0.1';
223 $this->priorities[NS_FILE] = '0.5';
224 $this->priorities[NS_FILE_TALK] = '0.1';
225 $this->priorities[NS_MEDIAWIKI] = '0.0';
226 $this->priorities[NS_MEDIAWIKI_TALK] = '0.1';
227 $this->priorities[NS_TEMPLATE] = '0.0';
228 $this->priorities[NS_TEMPLATE_TALK] = '0.1';
229 $this->priorities[NS_HELP] = '0.5';
230 $this->priorities[NS_HELP_TALK] = '0.1';
231 $this->priorities[NS_CATEGORY] = '0.5';
232 $this->priorities[NS_CATEGORY_TALK] = '0.1';
233
234 // Custom priorities
235 if ( $wgSitemapNamespacesPriorities !== false ) {
239 foreach ( $wgSitemapNamespacesPriorities as $namespace => $priority ) {
240 $float = floatval( $priority );
241 if ( $float > 1.0 ) {
242 $priority = '1.0';
243 } elseif ( $float < 0.0 ) {
244 $priority = '0.0';
245 }
246 $this->priorities[$namespace] = $priority;
247 }
248 }
249 }
250
254 private function generateNamespaces() {
255 // Only generate for specific namespaces if $wgSitemapNamespaces is an array.
257 if ( is_array( $wgSitemapNamespaces ) ) {
258 $this->namespaces = $wgSitemapNamespaces;
259
260 return;
261 }
262
263 $res = $this->dbr->select( 'page',
264 [ 'page_namespace' ],
265 [],
266 __METHOD__,
267 [
268 'GROUP BY' => 'page_namespace',
269 'ORDER BY' => 'page_namespace',
270 ]
271 );
272
273 foreach ( $res as $row ) {
274 $this->namespaces[] = $row->page_namespace;
275 }
276 }
277
284 private function priority( $namespace ) {
285 return $this->priorities[$namespace] ?? $this->guessPriority( $namespace );
286 }
287
296 private function guessPriority( $namespace ) {
297 return MediaWikiServices::getInstance()->getNamespaceInfo()->isSubject( $namespace )
298 ? $this->priorities[self::GS_MAIN]
299 : $this->priorities[self::GS_TALK];
300 }
301
308 private function getPageRes( $namespace ) {
309 return $this->dbr->select( 'page',
310 [
311 'page_namespace',
312 'page_title',
313 'page_touched',
314 'page_is_redirect'
315 ],
316 [ 'page_namespace' => $namespace ],
317 __METHOD__
318 );
319 }
320
324 public function main() {
325 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
326
327 fwrite( $this->findex, $this->openIndex() );
328
329 foreach ( $this->namespaces as $namespace ) {
330 $res = $this->getPageRes( $namespace );
331 $this->file = false;
332 $this->generateLimit( $namespace );
333 $length = $this->limit[0];
334 $i = $smcount = 0;
335
336 $fns = $contLang->getFormattedNsText( $namespace );
337 $this->output( "$namespace ($fns)\n" );
338 $skippedRedirects = 0; // Number of redirects skipped for that namespace
339 foreach ( $res as $row ) {
340 if ( $this->skipRedirects && $row->page_is_redirect ) {
341 $skippedRedirects++;
342 continue;
343 }
344
345 if ( $i++ === 0
346 || $i === $this->url_limit + 1
347 || $length + $this->limit[1] + $this->limit[2] > $this->size_limit
348 ) {
349 if ( $this->file !== false ) {
350 $this->write( $this->file, $this->closeFile() );
351 $this->close( $this->file );
352 }
353 $filename = $this->sitemapFilename( $namespace, $smcount++ );
354 $this->file = $this->open( $this->fspath . $filename, 'wb' );
355 $this->write( $this->file, $this->openFile() );
356 fwrite( $this->findex, $this->indexEntry( $filename ) );
357 $this->output( "\t$this->fspath$filename\n" );
358 $length = $this->limit[0];
359 $i = 1;
360 }
361 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
362 $date = wfTimestamp( TS_ISO_8601, $row->page_touched );
363 $entry = $this->fileEntry( $title->getCanonicalURL(), $date, $this->priority( $namespace ) );
364 $length += strlen( $entry );
365 $this->write( $this->file, $entry );
366 // generate pages for language variants
367 if ( $contLang->hasVariants() ) {
368 $variants = $contLang->getVariants();
369 foreach ( $variants as $vCode ) {
370 if ( $vCode == $contLang->getCode() ) {
371 continue; // we don't want default variant
372 }
373 $entry = $this->fileEntry(
374 $title->getCanonicalURL( '', $vCode ),
375 $date,
376 $this->priority( $namespace )
377 );
378 $length += strlen( $entry );
379 $this->write( $this->file, $entry );
380 }
381 }
382 }
383
384 if ( $this->skipRedirects && $skippedRedirects > 0 ) {
385 $this->output( " skipped $skippedRedirects redirect(s)\n" );
386 }
387
388 if ( $this->file ) {
389 $this->write( $this->file, $this->closeFile() );
390 $this->close( $this->file );
391 }
392 }
393 fwrite( $this->findex, $this->closeIndex() );
394 fclose( $this->findex );
395 }
396
404 private function open( $file, $flags ) {
405 $resource = $this->compress ? gzopen( $file, $flags ) : fopen( $file, $flags );
406 if ( $resource === false ) {
407 throw new MWException( __METHOD__
408 . " error opening file $file with flags $flags. Check permissions?" );
409 }
410
411 return $resource;
412 }
413
420 private function write( &$handle, $str ) {
421 if ( $handle === true || $handle === false ) {
422 throw new MWException( __METHOD__ . " was passed a boolean as a file handle.\n" );
423 }
424 if ( $this->compress ) {
425 gzwrite( $handle, $str );
426 } else {
427 fwrite( $handle, $str );
428 }
429 }
430
436 private function close( &$handle ) {
437 if ( $this->compress ) {
438 gzclose( $handle );
439 } else {
440 fclose( $handle );
441 }
442 }
443
451 private function sitemapFilename( $namespace, $count ) {
452 $ext = $this->compress ? '.gz' : '';
453
454 return "sitemap-{$this->identifier}-NS_$namespace-$count.xml$ext";
455 }
456
462 private function xmlHead() {
463 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
464 }
465
471 private function xmlSchema() {
472 return 'http://www.sitemaps.org/schemas/sitemap/0.9';
473 }
474
480 private function openIndex() {
481 return $this->xmlHead() . '<sitemapindex xmlns="' . $this->xmlSchema() . '">' . "\n";
482 }
483
490 private function indexEntry( $filename ) {
491 return "\t<sitemap>\n" .
492 "\t\t<loc>" . wfGetServerUrl( PROTO_CANONICAL ) .
493 ( substr( $this->urlpath, 0, 1 ) === "/" ? "" : "/" ) .
494 "{$this->urlpath}$filename</loc>\n" .
495 "\t\t<lastmod>{$this->timestamp}</lastmod>\n" .
496 "\t</sitemap>\n";
497 }
498
504 private function closeIndex() {
505 return "</sitemapindex>\n";
506 }
507
513 private function openFile() {
514 return $this->xmlHead() . '<urlset xmlns="' . $this->xmlSchema() . '">' . "\n";
515 }
516
525 private function fileEntry( $url, $date, $priority ) {
526 return "\t<url>\n" .
527 // T36666: $url may contain bad characters such as ampersands.
528 "\t\t<loc>" . htmlspecialchars( $url ) . "</loc>\n" .
529 "\t\t<lastmod>$date</lastmod>\n" .
530 "\t\t<priority>$priority</priority>\n" .
531 "\t</url>\n";
532 }
533
539 private function closeFile() {
540 return "</urlset>\n";
541 }
542
548 private function generateLimit( $namespace ) {
549 // T19961: make a title with the longest possible URL in this namespace
550 $title = Title::makeTitle( $namespace, str_repeat( "\u{28B81}", 63 ) . "\u{5583}" );
551
552 $this->limit = [
553 strlen( $this->openFile() ),
554 strlen( $this->fileEntry(
555 $title->getCanonicalURL(),
556 wfTimestamp( TS_ISO_8601, wfTimestamp() ),
557 $this->priority( $namespace )
558 ) ),
559 strlen( $this->closeFile() )
560 ];
561 }
562}
563
564$maintClass = GenerateSitemap::class;
565require_once RUN_MAINTENANCE_IF_MAIN;
getDB()
$wgSitemapNamespaces
Array of namespaces to generate a Google sitemap for when the maintenance/generateSitemap....
$wgSitemapNamespacesPriorities
Custom namespace priorities for sitemaps.
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.
const RUN_MAINTENANCE_IF_MAIN
Maintenance script that generates a sitemap for the site.
generateLimit( $namespace)
Populate $this->limit.
string $timestamp
When this sitemap batch was generated.
xmlSchema()
Return the XML schema being used.
indexEntry( $filename)
Return the XML for a single sitemap indexfile entry.
close(&$handle)
gzclose() / fclose() wrapper
IDatabase $dbr
A database replica DB object.
generateNamespaces()
Generate a one-dimensional array of existing namespaces.
closeFile()
Return the XML required to close sitemap file.
string $identifier
Identifier to use in filenames, default $wgDBname.
string $fspath
The path to prepend to the filename.
closeIndex()
Return the XML required to close a sitemap index file.
write(&$handle, $str)
gzwrite() / fwrite() wrapper
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.
open( $file, $flags)
gzopen() / fopen() wrapper
int $size_limit
The maximum size of a sitemap file.
xmlHead()
Return the XML required to open an XML file.
getPageRes( $namespace)
Return a database resolution of all the pages in a given namespace.
priority( $namespace)
Get the priority of a given namespace.
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.
guessPriority( $namespace)
If the namespace isn't listed on the priority list return the default priority for the namespace,...
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.
fileEntry( $url, $date, $priority)
Return the XML for a single sitemap entry.
openFile()
Return the XML required to open a sitemap file.
sitemapFilename( $namespace, $count)
Get a sitemap filename.
openIndex()
Return the XML required to open a sitemap index file.
MediaWiki exception.
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.
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.
MediaWikiServices is the service locator for the application scope of MediaWiki.
const PROTO_CANONICAL
Definition Defines.php:213
const NS_HELP
Definition Defines.php:82
const NS_USER
Definition Defines.php:72
const NS_FILE
Definition Defines.php:76
const NS_MEDIAWIKI_TALK
Definition Defines.php:79
const NS_MAIN
Definition Defines.php:70
const NS_PROJECT_TALK
Definition Defines.php:75
const NS_MEDIAWIKI
Definition Defines.php:78
const NS_TEMPLATE
Definition Defines.php:80
const NS_FILE_TALK
Definition Defines.php:77
const NS_HELP_TALK
Definition Defines.php:83
const NS_CATEGORY_TALK
Definition Defines.php:85
const NS_TALK
Definition Defines.php:71
const NS_USER_TALK
Definition Defines.php:73
const NS_PROJECT
Definition Defines.php:74
const NS_CATEGORY
Definition Defines.php:84
const NS_TEMPLATE_TALK
Definition Defines.php:81
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
Result wrapper for grabbing data queried from an IDatabase object.
const DB_REPLICA
Definition defines.php:25
if(!is_readable( $file)) $ext
Definition router.php:48