3 * Creates a sitemap for the site.
5 * Copyright © 2005, Ævar Arnfjörð Bjarmason, Jens Frank <jeluf@gmx.de> and
6 * Brion Vibber <brion@pobox.com>
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.
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.
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
24 * @ingroup Maintenance
25 * @see http://www.sitemaps.org/
26 * @see http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
29 use MediaWiki\MediaWikiServices
;
30 use Wikimedia\Rdbms\IResultWrapper
;
32 require_once __DIR__
. '/Maintenance.php';
35 * Maintenance script that generates a sitemap for the site.
37 * @ingroup Maintenance
39 class GenerateSitemap
extends Maintenance
{
44 * The maximum amount of urls in a sitemap file
46 * @link http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
53 * The maximum size of a sitemap file
55 * @link http://www.sitemaps.org/faq.php#faq_sitemap_size
62 * The path to prepend to the filename
69 * The URL path to prepend to filenames in the index;
70 * should resolve to the same directory as $fspath.
77 * Whether or not to use compression
84 * Whether or not to include redirection pages
88 public $skipRedirects;
91 * The number of entries to save in each sitemap file
98 * Key => value entries of namespaces and their priorities
102 public $priorities = [];
105 * A one-dimensional array of namespaces in the wiki
109 public $namespaces = [];
112 * When this sitemap batch was generated
119 * A database replica DB object
126 * A resource pointing to the sitemap index file
133 * A resource pointing to a sitemap file
140 * Identifier to use in filenames, default $wgDBname
146 public function __construct() {
147 parent
::__construct();
148 $this->addDescription( 'Creates a sitemap for the site' );
151 'The file system path to save to, e.g. /tmp/sitemap; defaults to current directory',
157 'The URL path corresponding to --fspath, prepended to filenames in the index; '
158 . 'defaults to an empty string',
164 'Compress the sitemap files, can take value yes|no, default yes',
168 $this->addOption( 'skip-redirects', 'Do not include redirecting articles in the sitemap' );
171 'What site identifier to use for the wiki, defaults to $wgDBname',
180 public function execute() {
181 $this->setNamespacePriorities();
182 $this->url_limit
= 50000;
183 $this->size_limit
= ( 2 ** 20 ) * 10;
185 # Create directory if needed
186 $fspath = $this->getOption( 'fspath', getcwd() );
187 if ( !wfMkdirParents( $fspath, null, __METHOD__
) ) {
188 $this->fatalError( "Can not create directory $fspath." );
191 $this->fspath
= realpath( $fspath ) . DIRECTORY_SEPARATOR
;
192 $this->urlpath
= $this->getOption( 'urlpath', "" );
193 if ( $this->urlpath
!== "" && substr( $this->urlpath
, -1 ) !== '/' ) {
194 $this->urlpath
.= '/';
196 $this->identifier
= $this->getOption( 'identifier', wfWikiID() );
197 $this->compress
= $this->getOption( 'compress', 'yes' ) !== 'no';
198 $this->skipRedirects
= $this->hasOption( 'skip-redirects' );
199 $this->dbr
= $this->getDB( DB_REPLICA
);
200 $this->generateNamespaces();
201 $this->timestamp
= wfTimestamp( TS_ISO_8601
, wfTimestampNow() );
202 $this->findex
= fopen( "{$this->fspath}sitemap-index-{$this->identifier}.xml", 'wb' );
206 private function setNamespacePriorities() {
207 global $wgSitemapNamespacesPriorities;
209 // Custom main namespaces
210 $this->priorities
[self
::GS_MAIN
] = '0.5';
211 // Custom talk namesspaces
212 $this->priorities
[self
::GS_TALK
] = '0.1';
213 // MediaWiki standard namespaces
214 $this->priorities
[NS_MAIN
] = '1.0';
215 $this->priorities
[NS_TALK
] = '0.1';
216 $this->priorities
[NS_USER
] = '0.5';
217 $this->priorities
[NS_USER_TALK
] = '0.1';
218 $this->priorities
[NS_PROJECT
] = '0.5';
219 $this->priorities
[NS_PROJECT_TALK
] = '0.1';
220 $this->priorities
[NS_FILE
] = '0.5';
221 $this->priorities
[NS_FILE_TALK
] = '0.1';
222 $this->priorities
[NS_MEDIAWIKI
] = '0.0';
223 $this->priorities
[NS_MEDIAWIKI_TALK
] = '0.1';
224 $this->priorities
[NS_TEMPLATE
] = '0.0';
225 $this->priorities
[NS_TEMPLATE_TALK
] = '0.1';
226 $this->priorities
[NS_HELP
] = '0.5';
227 $this->priorities
[NS_HELP_TALK
] = '0.1';
228 $this->priorities
[NS_CATEGORY
] = '0.5';
229 $this->priorities
[NS_CATEGORY_TALK
] = '0.1';
232 if ( $wgSitemapNamespacesPriorities !== false ) {
234 * @var array $wgSitemapNamespacesPriorities
236 foreach ( $wgSitemapNamespacesPriorities as $namespace => $priority ) {
237 $float = floatval( $priority );
238 if ( $float > 1.0 ) {
240 } elseif ( $float < 0.0 ) {
243 $this->priorities
[$namespace] = $priority;
249 * Generate a one-dimensional array of existing namespaces
251 function generateNamespaces() {
252 // Only generate for specific namespaces if $wgSitemapNamespaces is an array.
253 global $wgSitemapNamespaces;
254 if ( is_array( $wgSitemapNamespaces ) ) {
255 $this->namespaces
= $wgSitemapNamespaces;
260 $res = $this->dbr
->select( 'page',
261 [ 'page_namespace' ],
265 'GROUP BY' => 'page_namespace',
266 'ORDER BY' => 'page_namespace',
270 foreach ( $res as $row ) {
271 $this->namespaces
[] = $row->page_namespace
;
276 * Get the priority of a given namespace
278 * @param int $namespace The namespace to get the priority for
281 function priority( $namespace ) {
282 return $this->priorities
[$namespace] ??
$this->guessPriority( $namespace );
286 * If the namespace isn't listed on the priority list return the
287 * default priority for the namespace, varies depending on whether it's
290 * @param int $namespace The namespace to get the priority for
293 function guessPriority( $namespace ) {
294 return MediaWikiServices
::getInstance()->getNamespaceInfo()->isSubject( $namespace )
295 ?
$this->priorities
[self
::GS_MAIN
]
296 : $this->priorities
[self
::GS_TALK
];
300 * Return a database resolution of all the pages in a given namespace
302 * @param int $namespace Limit the query to this namespace
303 * @return IResultWrapper
305 function getPageRes( $namespace ) {
306 return $this->dbr
->select( 'page',
313 [ 'page_namespace' => $namespace ],
321 public function main() {
322 $contLang = MediaWikiServices
::getInstance()->getContentLanguage();
324 fwrite( $this->findex
, $this->openIndex() );
326 foreach ( $this->namespaces
as $namespace ) {
327 $res = $this->getPageRes( $namespace );
329 $this->generateLimit( $namespace );
330 $length = $this->limit
[0];
333 $fns = $contLang->getFormattedNsText( $namespace );
334 $this->output( "$namespace ($fns)\n" );
335 $skippedRedirects = 0; // Number of redirects skipped for that namespace
336 foreach ( $res as $row ) {
337 if ( $this->skipRedirects
&& $row->page_is_redirect
) {
343 ||
$i === $this->url_limit +
1
344 ||
$length +
$this->limit
[1] +
$this->limit
[2] > $this->size_limit
346 if ( $this->file
!== false ) {
347 $this->write( $this->file
, $this->closeFile() );
348 $this->close( $this->file
);
350 $filename = $this->sitemapFilename( $namespace, $smcount++
);
351 $this->file
= $this->open( $this->fspath
. $filename, 'wb' );
352 $this->write( $this->file
, $this->openFile() );
353 fwrite( $this->findex
, $this->indexEntry( $filename ) );
354 $this->output( "\t$this->fspath$filename\n" );
355 $length = $this->limit
[0];
358 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
359 $date = wfTimestamp( TS_ISO_8601
, $row->page_touched
);
360 $entry = $this->fileEntry( $title->getCanonicalURL(), $date, $this->priority( $namespace ) );
361 $length +
= strlen( $entry );
362 $this->write( $this->file
, $entry );
363 // generate pages for language variants
364 if ( $contLang->hasVariants() ) {
365 $variants = $contLang->getVariants();
366 foreach ( $variants as $vCode ) {
367 if ( $vCode == $contLang->getCode() ) {
368 continue; // we don't want default variant
370 $entry = $this->fileEntry(
371 $title->getCanonicalURL( '', $vCode ),
373 $this->priority( $namespace )
375 $length +
= strlen( $entry );
376 $this->write( $this->file
, $entry );
381 if ( $this->skipRedirects
&& $skippedRedirects > 0 ) {
382 $this->output( " skipped $skippedRedirects redirect(s)\n" );
386 $this->write( $this->file
, $this->closeFile() );
387 $this->close( $this->file
);
390 fwrite( $this->findex
, $this->closeIndex() );
391 fclose( $this->findex
);
395 * gzopen() / fopen() wrapper
397 * @param string $file
398 * @param string $flags
401 function open( $file, $flags ) {
402 $resource = $this->compress ?
gzopen( $file, $flags ) : fopen( $file, $flags );
403 if ( $resource === false ) {
404 throw new MWException( __METHOD__
405 . " error opening file $file with flags $flags. Check permissions?" );
412 * gzwrite() / fwrite() wrapper
414 * @param resource &$handle
417 function write( &$handle, $str ) {
418 if ( $handle === true ||
$handle === false ) {
419 throw new MWException( __METHOD__
. " was passed a boolean as a file handle.\n" );
421 if ( $this->compress
) {
422 gzwrite( $handle, $str );
424 fwrite( $handle, $str );
429 * gzclose() / fclose() wrapper
431 * @param resource &$handle
433 function close( &$handle ) {
434 if ( $this->compress
) {
442 * Get a sitemap filename
444 * @param int $namespace
448 function sitemapFilename( $namespace, $count ) {
449 $ext = $this->compress ?
'.gz' : '';
451 return "sitemap-{$this->identifier}-NS_$namespace-$count.xml$ext";
455 * Return the XML required to open an XML file
460 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
464 * Return the XML schema being used
468 function xmlSchema() {
469 return 'http://www.sitemaps.org/schemas/sitemap/0.9';
473 * Return the XML required to open a sitemap index file
477 function openIndex() {
478 return $this->xmlHead() . '<sitemapindex xmlns="' . $this->xmlSchema() . '">' . "\n";
482 * Return the XML for a single sitemap indexfile entry
484 * @param string $filename The filename of the sitemap file
487 function indexEntry( $filename ) {
488 return "\t<sitemap>\n" .
489 "\t\t<loc>" . wfGetServerUrl( PROTO_CANONICAL
) .
490 ( substr( $this->urlpath
, 0, 1 ) === "/" ?
"" : "/" ) .
491 "{$this->urlpath}$filename</loc>\n" .
492 "\t\t<lastmod>{$this->timestamp}</lastmod>\n" .
497 * Return the XML required to close a sitemap index file
501 function closeIndex() {
502 return "</sitemapindex>\n";
506 * Return the XML required to open a sitemap file
510 function openFile() {
511 return $this->xmlHead() . '<urlset xmlns="' . $this->xmlSchema() . '">' . "\n";
515 * Return the XML for a single sitemap entry
517 * @param string $url An RFC 2396 compliant URL
518 * @param string $date A ISO 8601 date
519 * @param string $priority A priority indicator, 0.0 - 1.0 inclusive with a 0.1 stepsize
522 function fileEntry( $url, $date, $priority ) {
524 // T36666: $url may contain bad characters such as ampersands.
525 "\t\t<loc>" . htmlspecialchars( $url ) . "</loc>\n" .
526 "\t\t<lastmod>$date</lastmod>\n" .
527 "\t\t<priority>$priority</priority>\n" .
532 * Return the XML required to close sitemap file
536 function closeFile() {
537 return "</urlset>\n";
541 * Populate $this->limit
543 * @param int $namespace
545 function generateLimit( $namespace ) {
546 // T19961: make a title with the longest possible URL in this namespace
547 $title = Title
::makeTitle( $namespace, str_repeat( "\u{28B81}", 63 ) . "\u{5583}" );
550 strlen( $this->openFile() ),
551 strlen( $this->fileEntry(
552 $title->getCanonicalURL(),
553 wfTimestamp( TS_ISO_8601
, wfTimestamp() ),
554 $this->priority( $namespace )
556 strlen( $this->closeFile() )
561 $maintClass = GenerateSitemap
::class;
562 require_once RUN_MAINTENANCE_IF_MAIN
;