Make it slightly easier for extensions to hook into page protection.
[mediawiki.git] / maintenance / generateSitemap.php
blob4f6bed5b6a5e770b74589fdb87582dbbbdb01dec
1 <?php
2 /**
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
23 * @file
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';
31 /**
32 * Maintenance script that generates a sitemap for the site.
34 * @ingroup Maintenance
36 class GenerateSitemap extends Maintenance {
37 const GS_MAIN = -2;
38 const GS_TALK = -1;
40 /**
41 * The maximum amount of urls in a sitemap file
43 * @link http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
45 * @var int
47 public $url_limit;
49 /**
50 * The maximum size of a sitemap file
52 * @link http://www.sitemaps.org/faq.php#faq_sitemap_size
54 * @var int
56 public $size_limit;
58 /**
59 * The path to prepend to the filename
61 * @var string
63 public $fspath;
65 /**
66 * The URL path to prepend to filenames in the index; should resolve to the same directory as $fspath
68 * @var string
70 public $urlpath;
72 /**
73 * Whether or not to use compression
75 * @var bool
77 public $compress;
79 /**
80 * Whether or not to include redirection pages
82 * @var bool
84 public $skipRedirects;
86 /**
87 * The number of entries to save in each sitemap file
89 * @var array
91 public $limit = array();
93 /**
94 * Key => value entries of namespaces and their priorities
96 * @var array
98 public $priorities = array();
101 * A one-dimensional array of namespaces in the wiki
103 * @var array
105 public $namespaces = array();
108 * When this sitemap batch was generated
110 * @var string
112 public $timestamp;
115 * A database slave object
117 * @var object
119 public $dbr;
122 * A resource pointing to the sitemap index file
124 * @var resource
126 public $findex;
130 * A resource pointing to a sitemap file
132 * @var resource
134 public $file;
137 * Identifier to use in filenames, default $wgDBname
139 * @var string
141 private $identifier;
144 * Constructor
146 public function __construct() {
147 parent::__construct();
148 $this->mDescription = "Creates a sitemap for the site";
149 $this->addOption( 'fspath', 'The file system path to save to, e.g. /tmp/sitemap; defaults to current directory', false, true );
150 $this->addOption( 'urlpath', 'The URL path corresponding to --fspath, prepended to filenames in the index; defaults to an empty string', false, true );
151 $this->addOption( 'compress', 'Compress the sitemap files, can take value yes|no, default yes', false, true );
152 $this->addOption( 'skip-redirects', 'Do not include redirecting articles in the sitemap' );
153 $this->addOption( 'identifier', 'What site identifier to use for the wiki, defaults to $wgDBname', false, true );
157 * Execute
159 public function execute() {
160 $this->setNamespacePriorities();
161 $this->url_limit = 50000;
162 $this->size_limit = pow( 2, 20 ) * 10;
163 $this->fspath = self::init_path( $this->getOption( 'fspath', getcwd() ) );
164 $this->urlpath = $this->getOption( 'urlpath', "" );
165 if ( $this->urlpath !== "" && substr( $this->urlpath, -1 ) !== '/' ) {
166 $this->urlpath .= '/';
168 $this->identifier = $this->getOption( 'identifier', wfWikiID() );
169 $this->compress = $this->getOption( 'compress', 'yes' ) !== 'no';
170 $this->skipRedirects = $this->getOption( 'skip-redirects', false ) !== false;
171 $this->dbr = wfGetDB( DB_SLAVE );
172 $this->generateNamespaces();
173 $this->timestamp = wfTimestamp( TS_ISO_8601, wfTimestampNow() );
174 $this->findex = fopen( "{$this->fspath}sitemap-index-{$this->identifier}.xml", 'wb' );
175 $this->main();
178 private function setNamespacePriorities() {
179 global $wgSitemapNamespacesPriorities;
181 // Custom main namespaces
182 $this->priorities[self::GS_MAIN] = '0.5';
183 // Custom talk namesspaces
184 $this->priorities[self::GS_TALK] = '0.1';
185 // MediaWiki standard namespaces
186 $this->priorities[NS_MAIN] = '1.0';
187 $this->priorities[NS_TALK] = '0.1';
188 $this->priorities[NS_USER] = '0.5';
189 $this->priorities[NS_USER_TALK] = '0.1';
190 $this->priorities[NS_PROJECT] = '0.5';
191 $this->priorities[NS_PROJECT_TALK] = '0.1';
192 $this->priorities[NS_FILE] = '0.5';
193 $this->priorities[NS_FILE_TALK] = '0.1';
194 $this->priorities[NS_MEDIAWIKI] = '0.0';
195 $this->priorities[NS_MEDIAWIKI_TALK] = '0.1';
196 $this->priorities[NS_TEMPLATE] = '0.0';
197 $this->priorities[NS_TEMPLATE_TALK] = '0.1';
198 $this->priorities[NS_HELP] = '0.5';
199 $this->priorities[NS_HELP_TALK] = '0.1';
200 $this->priorities[NS_CATEGORY] = '0.5';
201 $this->priorities[NS_CATEGORY_TALK] = '0.1';
203 // Custom priorities
204 if ( $wgSitemapNamespacesPriorities !== false ) {
206 * @var $wgSitemapNamespacesPriorities array
208 foreach ( $wgSitemapNamespacesPriorities as $namespace => $priority ) {
209 $float = floatval( $priority );
210 if ( $float > 1.0 ) {
211 $priority = '1.0';
212 } elseif ( $float < 0.0 ) {
213 $priority = '0.0';
215 $this->priorities[$namespace] = $priority;
221 * Create directory if it does not exist and return pathname with a trailing slash
222 * @param $fspath string
223 * @return null|string
225 private static function init_path( $fspath ) {
226 if ( !isset( $fspath ) ) {
227 return null;
229 # Create directory if needed
230 if ( $fspath && !is_dir( $fspath ) ) {
231 wfMkdirParents( $fspath, null, __METHOD__ ) or die( "Can not create directory $fspath.\n" );
234 return realpath( $fspath ) . DIRECTORY_SEPARATOR;
238 * Generate a one-dimensional array of existing namespaces
240 function generateNamespaces() {
241 // Only generate for specific namespaces if $wgSitemapNamespaces is an array.
242 global $wgSitemapNamespaces;
243 if ( is_array( $wgSitemapNamespaces ) ) {
244 $this->namespaces = $wgSitemapNamespaces;
245 return;
248 $res = $this->dbr->select( 'page',
249 array( 'page_namespace' ),
250 array(),
251 __METHOD__,
252 array(
253 'GROUP BY' => 'page_namespace',
254 'ORDER BY' => 'page_namespace',
258 foreach ( $res as $row ) {
259 $this->namespaces[] = $row->page_namespace;
264 * Get the priority of a given namespace
266 * @param $namespace Integer: the namespace to get the priority for
267 * @return String
269 function priority( $namespace ) {
270 return isset( $this->priorities[$namespace] ) ? $this->priorities[$namespace] : $this->guessPriority( $namespace );
274 * If the namespace isn't listed on the priority list return the
275 * default priority for the namespace, varies depending on whether it's
276 * a talkpage or not.
278 * @param $namespace Integer: the namespace to get the priority for
279 * @return String
281 function guessPriority( $namespace ) {
282 return MWNamespace::isSubject( $namespace ) ? $this->priorities[self::GS_MAIN] : $this->priorities[self::GS_TALK];
286 * Return a database resolution of all the pages in a given namespace
288 * @param $namespace Integer: limit the query to this namespace
289 * @return Resource
291 function getPageRes( $namespace ) {
292 return $this->dbr->select( 'page',
293 array(
294 'page_namespace',
295 'page_title',
296 'page_touched',
297 'page_is_redirect'
299 array( 'page_namespace' => $namespace ),
300 __METHOD__
305 * Main loop
307 public function main() {
308 global $wgContLang;
310 fwrite( $this->findex, $this->openIndex() );
312 foreach ( $this->namespaces as $namespace ) {
313 $res = $this->getPageRes( $namespace );
314 $this->file = false;
315 $this->generateLimit( $namespace );
316 $length = $this->limit[0];
317 $i = $smcount = 0;
319 $fns = $wgContLang->getFormattedNsText( $namespace );
320 $this->output( "$namespace ($fns)\n" );
321 $skippedRedirects = 0; // Number of redirects skipped for that namespace
322 foreach ( $res as $row ) {
323 if ( $this->skipRedirects && $row->page_is_redirect ) {
324 $skippedRedirects++;
325 continue;
328 if ( $i++ === 0 || $i === $this->url_limit + 1 || $length + $this->limit[1] + $this->limit[2] > $this->size_limit ) {
329 if ( $this->file !== false ) {
330 $this->write( $this->file, $this->closeFile() );
331 $this->close( $this->file );
333 $filename = $this->sitemapFilename( $namespace, $smcount++ );
334 $this->file = $this->open( $this->fspath . $filename, 'wb' );
335 $this->write( $this->file, $this->openFile() );
336 fwrite( $this->findex, $this->indexEntry( $filename ) );
337 $this->output( "\t$this->fspath$filename\n" );
338 $length = $this->limit[0];
339 $i = 1;
341 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
342 $date = wfTimestamp( TS_ISO_8601, $row->page_touched );
343 $entry = $this->fileEntry( $title->getCanonicalURL(), $date, $this->priority( $namespace ) );
344 $length += strlen( $entry );
345 $this->write( $this->file, $entry );
346 // generate pages for language variants
347 if ( $wgContLang->hasVariants() ) {
348 $variants = $wgContLang->getVariants();
349 foreach ( $variants as $vCode ) {
350 if ( $vCode == $wgContLang->getCode() ) {
351 continue; // we don't want default variant
353 $entry = $this->fileEntry( $title->getCanonicalURL( '', $vCode ), $date, $this->priority( $namespace ) );
354 $length += strlen( $entry );
355 $this->write( $this->file, $entry );
360 if ( $this->skipRedirects && $skippedRedirects > 0 ) {
361 $this->output( " skipped $skippedRedirects redirect(s)\n" );
364 if ( $this->file ) {
365 $this->write( $this->file, $this->closeFile() );
366 $this->close( $this->file );
369 fwrite( $this->findex, $this->closeIndex() );
370 fclose( $this->findex );
374 * gzopen() / fopen() wrapper
376 * @return Resource
378 function open( $file, $flags ) {
379 $resource = $this->compress ? gzopen( $file, $flags ) : fopen( $file, $flags );
380 if ( $resource === false ) {
381 wfDebugDieBacktrace( __METHOD__ . " error opening file $file with flags $flags. Check permissions?" );
383 return $resource;
387 * gzwrite() / fwrite() wrapper
389 function write( &$handle, $str ) {
390 if ( $handle === true || $handle === false ) {
391 wfDebugDieBacktrace( __METHOD__ . " was passed a boolean as a file handle.\n" );
393 if ( $this->compress ) {
394 gzwrite( $handle, $str );
395 } else {
396 fwrite( $handle, $str );
401 * gzclose() / fclose() wrapper
403 function close( &$handle ) {
404 if ( $this->compress ) {
405 gzclose( $handle );
406 } else {
407 fclose( $handle );
412 * Get a sitemap filename
414 * @param $namespace Integer: the namespace
415 * @param $count Integer: the count
416 * @return String
418 function sitemapFilename( $namespace, $count ) {
419 $ext = $this->compress ? '.gz' : '';
420 return "sitemap-{$this->identifier}-NS_$namespace-$count.xml$ext";
424 * Return the XML required to open an XML file
426 * @return string
428 function xmlHead() {
429 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
433 * Return the XML schema being used
435 * @return String
437 function xmlSchema() {
438 return 'http://www.sitemaps.org/schemas/sitemap/0.9';
442 * Return the XML required to open a sitemap index file
444 * @return String
446 function openIndex() {
447 return $this->xmlHead() . '<sitemapindex xmlns="' . $this->xmlSchema() . '">' . "\n";
451 * Return the XML for a single sitemap indexfile entry
453 * @param $filename String: the filename of the sitemap file
454 * @return String
456 function indexEntry( $filename ) {
457 return
458 "\t<sitemap>\n" .
459 "\t\t<loc>{$this->urlpath}$filename</loc>\n" .
460 "\t\t<lastmod>{$this->timestamp}</lastmod>\n" .
461 "\t</sitemap>\n";
465 * Return the XML required to close a sitemap index file
467 * @return String
469 function closeIndex() {
470 return "</sitemapindex>\n";
474 * Return the XML required to open a sitemap file
476 * @return String
478 function openFile() {
479 return $this->xmlHead() . '<urlset xmlns="' . $this->xmlSchema() . '">' . "\n";
483 * Return the XML for a single sitemap entry
485 * @param $url String: an RFC 2396 compliant URL
486 * @param $date String: a ISO 8601 date
487 * @param $priority String: a priority indicator, 0.0 - 1.0 inclusive with a 0.1 stepsize
488 * @return String
490 function fileEntry( $url, $date, $priority ) {
491 return
492 "\t<url>\n" .
493 // bug 34666: $url may contain bad characters such as ampersands.
494 "\t\t<loc>" . htmlspecialchars( $url ) . "</loc>\n" .
495 "\t\t<lastmod>$date</lastmod>\n" .
496 "\t\t<priority>$priority</priority>\n" .
497 "\t</url>\n";
501 * Return the XML required to close sitemap file
503 * @return String
505 function closeFile() {
506 return "</urlset>\n";
510 * Populate $this->limit
512 function generateLimit( $namespace ) {
513 // bug 17961: make a title with the longest possible URL in this namespace
514 $title = Title::makeTitle( $namespace, str_repeat( "\xf0\xa8\xae\x81", 63 ) . "\xe5\x96\x83" );
516 $this->limit = array(
517 strlen( $this->openFile() ),
518 strlen( $this->fileEntry( $title->getCanonicalURL(), wfTimestamp( TS_ISO_8601, wfTimestamp() ), $this->priority( $namespace ) ) ),
519 strlen( $this->closeFile() )
524 $maintClass = "GenerateSitemap";
525 require_once RUN_MAINTENANCE_IF_MAIN;