3 * Creates a sitemap for the site.
5 * Copyright © 2005, Ævar Arnfjörð Bjarmason, Jens Frank <jeluf@gmx.de> and
6 * Brooke Vibber <bvibber@wikimedia.org>
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\MainConfigNames
;
30 use MediaWiki\Title\Title
;
31 use MediaWiki\WikiMap\WikiMap
;
32 use Wikimedia\Rdbms\IDatabase
;
33 use Wikimedia\Rdbms\IResultWrapper
;
35 // @codeCoverageIgnoreStart
36 require_once __DIR__
. '/Maintenance.php';
37 // @codeCoverageIgnoreEnd
40 * Maintenance script that generates a sitemap for the site.
42 * @ingroup Maintenance
44 class GenerateSitemap
extends Maintenance
{
45 private const GS_MAIN
= -2;
46 private const GS_TALK
= -1;
49 * The maximum amount of urls in a sitemap file
51 * @link http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
58 * The maximum size of a sitemap file
60 * @link http://www.sitemaps.org/faq.php#faq_sitemap_size
67 * The path to prepend to the filename
74 * The URL path to prepend to filenames in the index;
75 * should resolve to the same directory as $fspath.
82 * Whether or not to use compression
89 * Whether or not to include redirection pages
93 public $skipRedirects;
96 * The number of entries to save in each sitemap file
103 * Key => value entries of namespaces and their priorities
107 public $priorities = [];
110 * A one-dimensional array of namespaces in the wiki
114 public $namespaces = [];
117 * When this sitemap batch was generated
124 * A database replica DB object
131 * A resource pointing to the sitemap index file
138 * A resource pointing to a sitemap file
140 * @var resource|false
145 * Identifier to use in filenames, default $wgDBname
151 public function __construct() {
152 parent
::__construct();
153 $this->addDescription( 'Creates a sitemap for the site' );
156 'The file system path to save to, e.g. /tmp/sitemap; defaults to current directory',
162 'The URL path corresponding to --fspath, prepended to filenames in the index; '
163 . 'defaults to an empty string',
169 'Compress the sitemap files, can take value yes|no, default yes',
173 $this->addOption( 'skip-redirects', 'Do not include redirecting articles in the sitemap' );
176 'What site identifier to use for the wiki, defaults to $wgDBname',
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
191 public function execute() {
192 $this->setNamespacePriorities();
193 $this->url_limit
= 50000;
194 $this->size_limit
= ( 2 ** 20 ) * 10;
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." );
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
.= '/';
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' );
219 private function setNamespacePriorities() {
220 $sitemapNamespacesPriorities = $this->getConfig()->get( MainConfigNames
::SitemapNamespacesPriorities
);
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';
245 if ( $sitemapNamespacesPriorities !== false ) {
247 * @var array $sitemapNamespacesPriorities
249 foreach ( $sitemapNamespacesPriorities as $namespace => $priority ) {
250 $float = floatval( $priority );
251 if ( $float > 1.0 ) {
253 } elseif ( $float < 0.0 ) {
256 $this->priorities
[$namespace] = $priority;
262 * Generate a one-dimensional array of existing namespaces
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;
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;
281 $res = $this->dbr
->newSelectQueryBuilder()
282 ->select( [ 'page_namespace' ] )
284 ->groupBy( 'page_namespace' )
285 ->orderBy( 'page_namespace' )
286 ->caller( __METHOD__
)->fetchResultSet();
288 foreach ( $res as $row ) {
289 $this->namespaces
[] = $row->page_namespace
;
294 * Get the priority of a given namespace
296 * @param int $namespace The namespace to get the priority for
299 private function priority( $namespace ) {
300 return $this->priorities
[$namespace] ??
$this->guessPriority( $namespace );
304 * If the namespace isn't listed on the priority list return the
305 * default priority for the namespace, varies depending on whether it's
308 * @param int $namespace The namespace to get the priority for
311 private function guessPriority( $namespace ) {
312 return $this->getServiceContainer()->getNamespaceInfo()->isSubject( $namespace )
313 ?
$this->priorities
[self
::GS_MAIN
]
314 : $this->priorities
[self
::GS_TALK
];
318 * Return a database resolution of all the pages in a given namespace
320 * @param int $namespace Limit the query to this namespace
321 * @return IResultWrapper
323 private function getPageRes( $namespace ) {
324 return $this->dbr
->newSelectQueryBuilder()
325 ->select( [ 'page_namespace', 'page_title', 'page_touched', 'page_is_redirect', 'pp_propname' ] )
327 ->leftJoin( 'page_props', null, [ 'page_id = pp_page', 'pp_propname' => 'noindex' ] )
328 ->where( [ 'page_namespace' => $namespace ] )
329 ->caller( __METHOD__
)->fetchResultSet();
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
) ??
'';
341 fwrite( $this->findex
, $this->openIndex() );
343 foreach ( $this->namespaces
as $namespace ) {
344 $res = $this->getPageRes( $namespace );
346 $this->generateLimit( $namespace );
347 $length = $this->limit
[0];
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' ) {
360 if ( $this->skipRedirects
&& $row->page_is_redirect
) {
366 ||
$i === $this->url_limit +
1
367 ||
$length +
$this->limit
[1] +
$this->limit
[2] > $this->size_limit
369 if ( $this->file
!== false ) {
370 $this->write( $this->file
, $this->closeFile() );
371 $this->close( $this->file
);
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];
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
393 $entry = $this->fileEntry(
394 $title->getCanonicalURL( [ 'variant' => $vCode ] ),
396 $this->priority( $namespace )
398 $length +
= strlen( $entry );
399 $this->write( $this->file
, $entry );
404 if ( $skippedNoindex > 0 ) {
405 $this->output( " skipped $skippedNoindex page(s) with __NOINDEX__ switch\n" );
408 if ( $this->skipRedirects
&& $skippedRedirects > 0 ) {
409 $this->output( " skipped $skippedRedirects redirect(s)\n" );
413 $this->write( $this->file
, $this->closeFile() );
414 $this->close( $this->file
);
417 fwrite( $this->findex
, $this->closeIndex() );
418 fclose( $this->findex
);
422 * gzopen() / fopen() wrapper
424 * @param string $file
425 * @param string $flags
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?" );
439 * gzwrite() / fwrite() wrapper
441 * @param resource &$handle
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" );
448 if ( $this->compress
) {
449 gzwrite( $handle, $str );
451 fwrite( $handle, $str );
456 * gzclose() / fclose() wrapper
458 * @param resource &$handle
460 private function close( &$handle ) {
461 if ( $this->compress
) {
469 * Get a sitemap filename
471 * @param int $namespace
475 private function sitemapFilename( $namespace, $count ) {
476 $ext = $this->compress ?
'.gz' : '';
478 return "sitemap-{$this->identifier}-NS_$namespace-$count.xml$ext";
482 * Return the XML required to open an XML file
486 private function xmlHead() {
487 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
491 * Return the XML schema being used
495 private function xmlSchema() {
496 return 'http://www.sitemaps.org/schemas/sitemap/0.9';
500 * Return the XML required to open a sitemap index file
504 private function openIndex() {
505 return $this->xmlHead() . '<sitemapindex xmlns="' . $this->xmlSchema() . '">' . "\n";
509 * Return the XML for a single sitemap indexfile entry
511 * @param string $filename The filename of the sitemap file
512 * @param string $serverUrl Current server url
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" .
525 * Return the XML required to close a sitemap index file
529 private function closeIndex() {
530 return "</sitemapindex>\n";
534 * Return the XML required to open a sitemap file
538 private function openFile() {
539 return $this->xmlHead() . '<urlset xmlns="' . $this->xmlSchema() . '">' . "\n";
543 * Return the XML for a single sitemap entry
545 * @param string $url An RFC 2396 compliant URL
546 * @param string $date A ISO 8601 date
547 * @param string $priority A priority indicator, 0.0 - 1.0 inclusive with a 0.1 stepsize
550 private function fileEntry( $url, $date, $priority ) {
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" .
560 * Return the XML required to close sitemap file
564 private function closeFile() {
565 return "</urlset>\n";
569 * Populate $this->limit
571 * @param int $namespace
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}" );
578 strlen( $this->openFile() ),
579 strlen( $this->fileEntry(
580 $title->getCanonicalURL(),
581 wfTimestamp( TS_ISO_8601
, wfTimestamp() ),
582 $this->priority( $namespace )
584 strlen( $this->closeFile() )
589 // @codeCoverageIgnoreStart
590 $maintClass = GenerateSitemap
::class;
591 require_once RUN_MAINTENANCE_IF_MAIN
;
592 // @codeCoverageIgnoreEnd