Don't need to set time limit here, already did in setup(), memory_limit still needs...
[mediawiki.git] / maintenance / generateSitemap.php
blob8ca7934123d4aa18fa5abac55f25821f53a3b5cb
1 <?php
2 define( 'GS_MAIN', -2 );
3 define( 'GS_TALK', -1 );
4 /**
5 * Creates a sitemap for the site
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
22 * @ingroup Maintenance
24 * @copyright Copyright © 2005, Ævar Arnfjörð Bjarmason
25 * @copyright Copyright © 2005, Jens Frank <jeluf@gmx.de>
26 * @copyright Copyright © 2005, Brion Vibber <brion@pobox.com>
28 * @see http://www.sitemaps.org/
29 * @see http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
31 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0 or later
34 require_once( dirname(__FILE__) . '/Maintenance.php' );
36 class GenerateSitemap extends Maintenance {
37 /**
38 * The maximum amount of urls in a sitemap file
40 * @link http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
42 * @var int
44 var $url_limit;
46 /**
47 * The maximum size of a sitemap file
49 * @link http://www.sitemaps.org/faq.php#faq_sitemap_size
51 * @var int
53 var $size_limit;
55 /**
56 * The path to prepend to the filename
58 * @var string
60 var $fspath;
62 /**
63 * The path to append to the domain name
65 * @var string
67 var $path;
69 /**
70 * Whether or not to use compression
72 * @var bool
74 var $compress;
76 /**
77 * The number of entries to save in each sitemap file
79 * @var array
81 var $limit = array();
83 /**
84 * Key => value entries of namespaces and their priorities
86 * @var array
88 var $priorities = array();
90 /**
91 * A one-dimensional array of namespaces in the wiki
93 * @var array
95 var $namespaces = array();
97 /**
98 * When this sitemap batch was generated
100 * @var string
102 var $timestamp;
105 * A database slave object
107 * @var object
109 var $dbr;
112 * A resource pointing to the sitemap index file
114 * @var resource
116 var $findex;
120 * A resource pointing to a sitemap file
122 * @var resource
124 var $file;
127 * Constructor
129 public function __construct() {
130 parent::__construct();
131 $this->mDescription = "Creates a sitemap for the site";
132 $this->addOption( 'fspath', 'The file system path to save to, e.g. /tmp/sitemap' .
133 "\n\t\tdefaults to current directory", false, true );
134 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g.\n" .
135 "\t\thttp://en.wikipedia.org. This is sometimes necessary because\n" .
136 "\t\tserver name detection may fail in command line scripts.", false, true );
137 $this->addOption( 'compress', 'Compress the sitemap files, can take value yes|no, default yes', false, true );
141 * Execute
143 public function execute() {
144 global $wgScriptPath;
145 $this->setNamespacePriorities();
146 $this->url_limit = 50000;
147 $this->size_limit = pow( 2, 20 ) * 10;
148 $this->fspath = self::init_path( $this->getOption( 'fspath', getcwd() ) );
149 $this->compress = $this->getOption( 'compress', 'yes' ) !== 'no';
150 $this->dbr = wfGetDB( DB_SLAVE );
151 $this->generateNamespaces();
152 $this->timestamp = wfTimestamp( TS_ISO_8601, wfTimestampNow() );
153 $this->findex = fopen( "{$this->fspath}sitemap-index-" . wfWikiID() . ".xml", 'wb' );
154 $this->main();
157 private function setNamespacePriorities() {
158 // Custom main namespaces
159 $this->priorities[GS_MAIN] = '0.5';
160 // Custom talk namesspaces
161 $this->priorities[GS_TALK] = '0.1';
162 // MediaWiki standard namespaces
163 $this->priorities[NS_MAIN] = '1.0';
164 $this->priorities[NS_TALK] = '0.1';
165 $this->priorities[NS_USER] = '0.5';
166 $this->priorities[NS_USER_TALK] = '0.1';
167 $this->priorities[NS_PROJECT] = '0.5';
168 $this->priorities[NS_PROJECT_TALK] = '0.1';
169 $this->priorities[NS_FILE] = '0.5';
170 $this->priorities[NS_FILE_TALK] = '0.1';
171 $this->priorities[NS_MEDIAWIKI] = '0.0';
172 $this->priorities[NS_MEDIAWIKI_TALK] = '0.1';
173 $this->priorities[NS_TEMPLATE] = '0.0';
174 $this->priorities[NS_TEMPLATE_TALK] = '0.1';
175 $this->priorities[NS_HELP] = '0.5';
176 $this->priorities[NS_HELP_TALK] = '0.1';
177 $this->priorities[NS_CATEGORY] = '0.5';
178 $this->priorities[NS_CATEGORY_TALK] = '0.1';
182 * Create directory if it does not exist and return pathname with a trailing slash
184 private static function init_path( $fspath ) {
185 if( !isset( $fspath ) ) {
186 return null;
188 # Create directory if needed
189 if( $fspath && !is_dir( $fspath ) ) {
190 wfMkdirParents( $fspath ) or die("Can not create directory $fspath.\n");
193 return realpath( $fspath ). DIRECTORY_SEPARATOR ;
197 * Generate a one-dimensional array of existing namespaces
199 function generateNamespaces() {
200 // Only generate for specific namespaces if $wgSitemapNamespaces is an array.
201 global $wgSitemapNamespaces;
202 if( is_array( $wgSitemapNamespaces ) ) {
203 $this->namespaces = $wgSitemapNamespaces;
204 return;
207 $res = $this->dbr->select( 'page',
208 array( 'page_namespace' ),
209 array(),
210 __METHOD__,
211 array(
212 'GROUP BY' => 'page_namespace',
213 'ORDER BY' => 'page_namespace',
217 foreach ( $res as $row )
218 $this->namespaces[] = $row->page_namespace;
222 * Get the priority of a given namespace
224 * @param int $namespace The namespace to get the priority for
226 * @return string
229 function priority( $namespace ) {
230 return isset( $this->priorities[$namespace] ) ? $this->priorities[$namespace] : $this->guessPriority( $namespace );
234 * If the namespace isn't listed on the priority list return the
235 * default priority for the namespace, varies depending on whether it's
236 * a talkpage or not.
238 * @param int $namespace The namespace to get the priority for
240 * @return string
242 function guessPriority( $namespace ) {
243 return MWNamespace::isMain( $namespace ) ? $this->priorities[GS_MAIN] : $this->priorities[GS_TALK];
247 * Return a database resolution of all the pages in a given namespace
249 * @param int $namespace Limit the query to this namespace
251 * @return resource
253 function getPageRes( $namespace ) {
254 return $this->dbr->select( 'page',
255 array(
256 'page_namespace',
257 'page_title',
258 'page_touched',
260 array( 'page_namespace' => $namespace ),
261 __METHOD__
266 * Main loop
268 * @access public
270 function main() {
271 global $wgContLang;
273 fwrite( $this->findex, $this->openIndex() );
275 foreach ( $this->namespaces as $namespace ) {
276 $res = $this->getPageRes( $namespace );
277 $this->file = false;
278 $this->generateLimit( $namespace );
279 $length = $this->limit[0];
280 $i = $smcount = 0;
282 $fns = $wgContLang->getFormattedNsText( $namespace );
283 $this->output( "$namespace ($fns)" );
284 foreach ( $res as $row ) {
285 if ( $i++ === 0 || $i === $this->url_limit + 1 || $length + $this->limit[1] + $this->limit[2] > $this->size_limit ) {
286 if ( $this->file !== false ) {
287 $this->write( $this->file, $this->closeFile() );
288 $this->close( $this->file );
290 $filename = $this->sitemapFilename( $namespace, $smcount++ );
291 $this->file = $this->open( $this->fspath . $filename, 'wb' );
292 $this->write( $this->file, $this->openFile() );
293 fwrite( $this->findex, $this->indexEntry( $filename ) );
294 $this->output( "\t$this->fspath$filename\n" );
295 $length = $this->limit[0];
296 $i = 1;
298 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
299 $date = wfTimestamp( TS_ISO_8601, $row->page_touched );
300 $entry = $this->fileEntry( $title->getFullURL(), $date, $this->priority( $namespace ) );
301 $length += strlen( $entry );
302 $this->write( $this->file, $entry );
303 // generate pages for language variants
304 if($wgContLang->hasVariants()){
305 $variants = $wgContLang->getVariants();
306 foreach($variants as $vCode){
307 if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
308 $entry = $this->fileEntry( $title->getFullURL('',$vCode), $date, $this->priority( $namespace ) );
309 $length += strlen( $entry );
310 $this->write( $this->file, $entry );
314 if ( $this->file ) {
315 $this->write( $this->file, $this->closeFile() );
316 $this->close( $this->file );
319 fwrite( $this->findex, $this->closeIndex() );
320 fclose( $this->findex );
324 * gzopen() / fopen() wrapper
326 * @return resource
328 function open( $file, $flags ) {
329 return $this->compress ? gzopen( $file, $flags ) : fopen( $file, $flags );
333 * gzwrite() / fwrite() wrapper
335 function write( &$handle, $str ) {
336 if ( $this->compress )
337 gzwrite( $handle, $str );
338 else
339 fwrite( $handle, $str );
343 * gzclose() / fclose() wrapper
345 function close( &$handle ) {
346 if ( $this->compress )
347 gzclose( $handle );
348 else
349 fclose( $handle );
353 * Get a sitemap filename
355 * @static
357 * @param int $namespace The namespace
358 * @param int $count The count
360 * @return string
362 function sitemapFilename( $namespace, $count ) {
363 $ext = $this->compress ? '.gz' : '';
364 return "sitemap-".wfWikiID()."-NS_$namespace-$count.xml$ext";
368 * Return the XML required to open an XML file
370 * @static
372 * @return string
374 function xmlHead() {
375 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
379 * Return the XML schema being used
381 * @static
383 * @returns string
385 function xmlSchema() {
386 return 'http://www.sitemaps.org/schemas/sitemap/0.9';
390 * Return the XML required to open a sitemap index file
392 * @return string
394 function openIndex() {
395 return $this->xmlHead() . '<sitemapindex xmlns="' . $this->xmlSchema() . '">' . "\n";
399 * Return the XML for a single sitemap indexfile entry
401 * @static
403 * @param string $filename The filename of the sitemap file
405 * @return string
407 function indexEntry( $filename ) {
408 return
409 "\t<sitemap>\n" .
410 "\t\t<loc>$filename</loc>\n" .
411 "\t\t<lastmod>{$this->timestamp}</lastmod>\n" .
412 "\t</sitemap>\n";
416 * Return the XML required to close a sitemap index file
418 * @static
420 * @return string
422 function closeIndex() {
423 return "</sitemapindex>\n";
427 * Return the XML required to open a sitemap file
429 * @return string
431 function openFile() {
432 return $this->xmlHead() . '<urlset xmlns="' . $this->xmlSchema() . '">' . "\n";
436 * Return the XML for a single sitemap entry
438 * @static
440 * @param string $url An RFC 2396 compliant URL
441 * @param string $date A ISO 8601 date
442 * @param string $priority A priority indicator, 0.0 - 1.0 inclusive with a 0.1 stepsize
444 * @return string
446 function fileEntry( $url, $date, $priority ) {
447 return
448 "\t<url>\n" .
449 "\t\t<loc>$url</loc>\n" .
450 "\t\t<lastmod>$date</lastmod>\n" .
451 "\t\t<priority>$priority</priority>\n" .
452 "\t</url>\n";
456 * Return the XML required to close sitemap file
458 * @static
459 * @return string
461 function closeFile() {
462 return "</urlset>\n";
466 * Populate $this->limit
468 function generateLimit( $namespace ) {
469 $title = Title::makeTitle( $namespace, str_repeat( "\xf0\xa8\xae\x81", 63 ) . "\xe5\x96\x83" );
471 $this->limit = array(
472 strlen( $this->openFile() ),
473 strlen( $this->fileEntry( $title->getFullUrl(), wfTimestamp( TS_ISO_8601, wfTimestamp() ), $this->priority( $namespace ) ) ),
474 strlen( $this->closeFile() )
479 $maintClass = "GenerateSitemap";
480 require_once( DO_MAINTENANCE );