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 require_once __DIR__
. '/Maintenance.php';
32 * Maintenance script that generates a sitemap for the site.
34 * @ingroup Maintenance
36 class GenerateSitemap
extends Maintenance
{
41 * The maximum amount of urls in a sitemap file
43 * @link http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
50 * The maximum size of a sitemap file
52 * @link http://www.sitemaps.org/faq.php#faq_sitemap_size
59 * The path to prepend to the filename
66 * The URL path to prepend to filenames in the index;
67 * should resolve to the same directory as $fspath.
74 * Whether or not to use compression
81 * Whether or not to include redirection pages
85 public $skipRedirects;
88 * The number of entries to save in each sitemap file
95 * Key => value entries of namespaces and their priorities
99 public $priorities = [];
102 * A one-dimensional array of namespaces in the wiki
106 public $namespaces = [];
109 * When this sitemap batch was generated
116 * A database replica DB object
123 * A resource pointing to the sitemap index file
130 * A resource pointing to a sitemap file
137 * Identifier to use in filenames, default $wgDBname
143 public function __construct() {
144 parent
::__construct();
145 $this->addDescription( 'Creates a sitemap for the site' );
148 'The file system path to save to, e.g. /tmp/sitemap; defaults to current directory',
154 'The URL path corresponding to --fspath, prepended to filenames in the index; '
155 . 'defaults to an empty string',
161 'Compress the sitemap files, can take value yes|no, default yes',
165 $this->addOption( 'skip-redirects', 'Do not include redirecting articles in the sitemap' );
168 'What site identifier to use for the wiki, defaults to $wgDBname',
177 public function execute() {
178 $this->setNamespacePriorities();
179 $this->url_limit
= 50000;
180 $this->size_limit
= ( 2 ** 20 ) * 10;
182 # Create directory if needed
183 $fspath = $this->getOption( 'fspath', getcwd() );
184 if ( !wfMkdirParents( $fspath, null, __METHOD__
) ) {
185 $this->fatalError( "Can not create directory $fspath." );
188 $this->fspath
= realpath( $fspath ) . DIRECTORY_SEPARATOR
;
189 $this->urlpath
= $this->getOption( 'urlpath', "" );
190 if ( $this->urlpath
!== "" && substr( $this->urlpath
, -1 ) !== '/' ) {
191 $this->urlpath
.= '/';
193 $this->identifier
= $this->getOption( 'identifier', wfWikiID() );
194 $this->compress
= $this->getOption( 'compress', 'yes' ) !== 'no';
195 $this->skipRedirects
= $this->hasOption( 'skip-redirects' );
196 $this->dbr
= $this->getDB( DB_REPLICA
);
197 $this->generateNamespaces();
198 $this->timestamp
= wfTimestamp( TS_ISO_8601
, wfTimestampNow() );
199 $this->findex
= fopen( "{$this->fspath}sitemap-index-{$this->identifier}.xml", 'wb' );
203 private function setNamespacePriorities() {
204 global $wgSitemapNamespacesPriorities;
206 // Custom main namespaces
207 $this->priorities
[self
::GS_MAIN
] = '0.5';
208 // Custom talk namesspaces
209 $this->priorities
[self
::GS_TALK
] = '0.1';
210 // MediaWiki standard namespaces
211 $this->priorities
[NS_MAIN
] = '1.0';
212 $this->priorities
[NS_TALK
] = '0.1';
213 $this->priorities
[NS_USER
] = '0.5';
214 $this->priorities
[NS_USER_TALK
] = '0.1';
215 $this->priorities
[NS_PROJECT
] = '0.5';
216 $this->priorities
[NS_PROJECT_TALK
] = '0.1';
217 $this->priorities
[NS_FILE
] = '0.5';
218 $this->priorities
[NS_FILE_TALK
] = '0.1';
219 $this->priorities
[NS_MEDIAWIKI
] = '0.0';
220 $this->priorities
[NS_MEDIAWIKI_TALK
] = '0.1';
221 $this->priorities
[NS_TEMPLATE
] = '0.0';
222 $this->priorities
[NS_TEMPLATE_TALK
] = '0.1';
223 $this->priorities
[NS_HELP
] = '0.5';
224 $this->priorities
[NS_HELP_TALK
] = '0.1';
225 $this->priorities
[NS_CATEGORY
] = '0.5';
226 $this->priorities
[NS_CATEGORY_TALK
] = '0.1';
229 if ( $wgSitemapNamespacesPriorities !== false ) {
231 * @var $wgSitemapNamespacesPriorities array
233 foreach ( $wgSitemapNamespacesPriorities as $namespace => $priority ) {
234 $float = floatval( $priority );
235 if ( $float > 1.0 ) {
237 } elseif ( $float < 0.0 ) {
240 $this->priorities
[$namespace] = $priority;
246 * Generate a one-dimensional array of existing namespaces
248 function generateNamespaces() {
249 // Only generate for specific namespaces if $wgSitemapNamespaces is an array.
250 global $wgSitemapNamespaces;
251 if ( is_array( $wgSitemapNamespaces ) ) {
252 $this->namespaces
= $wgSitemapNamespaces;
257 $res = $this->dbr
->select( 'page',
258 [ 'page_namespace' ],
262 'GROUP BY' => 'page_namespace',
263 'ORDER BY' => 'page_namespace',
267 foreach ( $res as $row ) {
268 $this->namespaces
[] = $row->page_namespace
;
273 * Get the priority of a given namespace
275 * @param int $namespace The namespace to get the priority for
278 function priority( $namespace ) {
279 return $this->priorities
[$namespace] ??
$this->guessPriority( $namespace );
283 * If the namespace isn't listed on the priority list return the
284 * default priority for the namespace, varies depending on whether it's
287 * @param int $namespace The namespace to get the priority for
290 function guessPriority( $namespace ) {
291 return MWNamespace
::isSubject( $namespace )
292 ?
$this->priorities
[self
::GS_MAIN
]
293 : $this->priorities
[self
::GS_TALK
];
297 * Return a database resolution of all the pages in a given namespace
299 * @param int $namespace Limit the query to this namespace
302 function getPageRes( $namespace ) {
303 return $this->dbr
->select( 'page',
310 [ 'page_namespace' => $namespace ],
318 public function main() {
321 fwrite( $this->findex
, $this->openIndex() );
323 foreach ( $this->namespaces
as $namespace ) {
324 $res = $this->getPageRes( $namespace );
326 $this->generateLimit( $namespace );
327 $length = $this->limit
[0];
330 $fns = $wgContLang->getFormattedNsText( $namespace );
331 $this->output( "$namespace ($fns)\n" );
332 $skippedRedirects = 0; // Number of redirects skipped for that namespace
333 foreach ( $res as $row ) {
334 if ( $this->skipRedirects
&& $row->page_is_redirect
) {
340 ||
$i === $this->url_limit +
1
341 ||
$length +
$this->limit
[1] +
$this->limit
[2] > $this->size_limit
343 if ( $this->file
!== false ) {
344 $this->write( $this->file
, $this->closeFile() );
345 $this->close( $this->file
);
347 $filename = $this->sitemapFilename( $namespace, $smcount++
);
348 $this->file
= $this->open( $this->fspath
. $filename, 'wb' );
349 $this->write( $this->file
, $this->openFile() );
350 fwrite( $this->findex
, $this->indexEntry( $filename ) );
351 $this->output( "\t$this->fspath$filename\n" );
352 $length = $this->limit
[0];
355 $title = Title
::makeTitle( $row->page_namespace
, $row->page_title
);
356 $date = wfTimestamp( TS_ISO_8601
, $row->page_touched
);
357 $entry = $this->fileEntry( $title->getCanonicalURL(), $date, $this->priority( $namespace ) );
358 $length +
= strlen( $entry );
359 $this->write( $this->file
, $entry );
360 // generate pages for language variants
361 if ( $wgContLang->hasVariants() ) {
362 $variants = $wgContLang->getVariants();
363 foreach ( $variants as $vCode ) {
364 if ( $vCode == $wgContLang->getCode() ) {
365 continue; // we don't want default variant
367 $entry = $this->fileEntry(
368 $title->getCanonicalURL( '', $vCode ),
370 $this->priority( $namespace )
372 $length +
= strlen( $entry );
373 $this->write( $this->file
, $entry );
378 if ( $this->skipRedirects
&& $skippedRedirects > 0 ) {
379 $this->output( " skipped $skippedRedirects redirect(s)\n" );
383 $this->write( $this->file
, $this->closeFile() );
384 $this->close( $this->file
);
387 fwrite( $this->findex
, $this->closeIndex() );
388 fclose( $this->findex
);
392 * gzopen() / fopen() wrapper
394 * @param string $file
395 * @param string $flags
398 function open( $file, $flags ) {
399 $resource = $this->compress ?
gzopen( $file, $flags ) : fopen( $file, $flags );
400 if ( $resource === false ) {
401 throw new MWException( __METHOD__
402 . " error opening file $file with flags $flags. Check permissions?" );
409 * gzwrite() / fwrite() wrapper
411 * @param resource &$handle
414 function write( &$handle, $str ) {
415 if ( $handle === true ||
$handle === false ) {
416 throw new MWException( __METHOD__
. " was passed a boolean as a file handle.\n" );
418 if ( $this->compress
) {
419 gzwrite( $handle, $str );
421 fwrite( $handle, $str );
426 * gzclose() / fclose() wrapper
428 * @param resource &$handle
430 function close( &$handle ) {
431 if ( $this->compress
) {
439 * Get a sitemap filename
441 * @param int $namespace
445 function sitemapFilename( $namespace, $count ) {
446 $ext = $this->compress ?
'.gz' : '';
448 return "sitemap-{$this->identifier}-NS_$namespace-$count.xml$ext";
452 * Return the XML required to open an XML file
457 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
461 * Return the XML schema being used
465 function xmlSchema() {
466 return 'http://www.sitemaps.org/schemas/sitemap/0.9';
470 * Return the XML required to open a sitemap index file
474 function openIndex() {
475 return $this->xmlHead() . '<sitemapindex xmlns="' . $this->xmlSchema() . '">' . "\n";
479 * Return the XML for a single sitemap indexfile entry
481 * @param string $filename The filename of the sitemap file
484 function indexEntry( $filename ) {
485 return "\t<sitemap>\n" .
486 "\t\t<loc>{$this->urlpath}$filename</loc>\n" .
487 "\t\t<lastmod>{$this->timestamp}</lastmod>\n" .
492 * Return the XML required to close a sitemap index file
496 function closeIndex() {
497 return "</sitemapindex>\n";
501 * Return the XML required to open a sitemap file
505 function openFile() {
506 return $this->xmlHead() . '<urlset xmlns="' . $this->xmlSchema() . '">' . "\n";
510 * Return the XML for a single sitemap entry
512 * @param string $url An RFC 2396 compliant URL
513 * @param string $date A ISO 8601 date
514 * @param string $priority A priority indicator, 0.0 - 1.0 inclusive with a 0.1 stepsize
517 function fileEntry( $url, $date, $priority ) {
519 // T36666: $url may contain bad characters such as ampersands.
520 "\t\t<loc>" . htmlspecialchars( $url ) . "</loc>\n" .
521 "\t\t<lastmod>$date</lastmod>\n" .
522 "\t\t<priority>$priority</priority>\n" .
527 * Return the XML required to close sitemap file
531 function closeFile() {
532 return "</urlset>\n";
536 * Populate $this->limit
538 * @param int $namespace
540 function generateLimit( $namespace ) {
541 // T19961: make a title with the longest possible URL in this namespace
542 $title = Title
::makeTitle( $namespace, str_repeat( "\u{28B81}", 63 ) . "\u{5583}" );
545 strlen( $this->openFile() ),
546 strlen( $this->fileEntry(
547 $title->getCanonicalURL(),
548 wfTimestamp( TS_ISO_8601
, wfTimestamp() ),
549 $this->priority( $namespace )
551 strlen( $this->closeFile() )
556 $maintClass = GenerateSitemap
::class;
557 require_once RUN_MAINTENANCE_IF_MAIN
;