Revert DatabaseBase::tablePrefix() part of r79272: doesn't seem to be really necessar...
[mediawiki.git] / maintenance / generateSitemap.php
blob84c3d6a4fe5cfe235797fb226a09d4d17c75e533
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( dirname( __FILE__ ) . '/Maintenance.php' );
31 class GenerateSitemap extends Maintenance {
32 const GS_MAIN = -2;
33 const GS_TALK = -1;
35 /**
36 * The maximum amount of urls in a sitemap file
38 * @link http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
40 * @var int
42 var $url_limit;
44 /**
45 * The maximum size of a sitemap file
47 * @link http://www.sitemaps.org/faq.php#faq_sitemap_size
49 * @var int
51 var $size_limit;
53 /**
54 * The path to prepend to the filename
56 * @var string
58 var $fspath;
60 /**
61 * The URL path to prepend to filenames in the index; should resolve to the same directory as $fspath
63 * @var string
65 var $urlpath;
67 /**
68 * Whether or not to use compression
70 * @var bool
72 var $compress;
74 /**
75 * The number of entries to save in each sitemap file
77 * @var array
79 var $limit = array();
81 /**
82 * Key => value entries of namespaces and their priorities
84 * @var array
86 var $priorities = array();
88 /**
89 * A one-dimensional array of namespaces in the wiki
91 * @var array
93 var $namespaces = array();
95 /**
96 * When this sitemap batch was generated
98 * @var string
100 var $timestamp;
103 * A database slave object
105 * @var object
107 var $dbr;
110 * A resource pointing to the sitemap index file
112 * @var resource
114 var $findex;
118 * A resource pointing to a sitemap file
120 * @var resource
122 var $file;
125 * Identifier to use in filenames, default $wgDBname
127 * @var string
129 private $identifier;
132 * Constructor
134 public function __construct() {
135 parent::__construct();
136 $this->mDescription = "Creates a sitemap for the site";
137 $this->addOption( 'fspath', 'The file system path to save to, e.g. /tmp/sitemap; defaults to current directory', false, true );
138 $this->addOption( 'urlpath', 'The URL path corresponding to --fspath, prepended to filenames in the index; defaults to an empty string', false, true );
139 $this->addOption( 'compress', 'Compress the sitemap files, can take value yes|no, default yes', false, true );
140 $this->addOption( 'identifier', 'What site identifier to use for the wiki, defaults to $wgDBname', false, true );
144 * Execute
146 public function execute() {
147 $this->setNamespacePriorities();
148 $this->url_limit = 50000;
149 $this->size_limit = pow( 2, 20 ) * 10;
150 $this->fspath = self::init_path( $this->getOption( 'fspath', getcwd() ) );
151 $this->urlpath = $this->getOption( 'urlpath', "" );
152 if ( $this->urlpath !== "" && substr( $this->urlpath, -1 ) !== '/' ) {
153 $this->urlpath .= '/';
155 $this->identifier = $this->getOption( 'identifier', wfWikiID() );
156 $this->compress = $this->getOption( 'compress', 'yes' ) !== 'no';
157 $this->dbr = wfGetDB( DB_SLAVE );
158 $this->generateNamespaces();
159 $this->timestamp = wfTimestamp( TS_ISO_8601, wfTimestampNow() );
160 $this->findex = fopen( "{$this->fspath}sitemap-index-{$this->identifier}.xml", 'wb' );
161 $this->main();
164 private function setNamespacePriorities() {
165 // Custom main namespaces
166 $this->priorities[self::GS_MAIN] = '0.5';
167 // Custom talk namesspaces
168 $this->priorities[self::GS_TALK] = '0.1';
169 // MediaWiki standard namespaces
170 $this->priorities[NS_MAIN] = '1.0';
171 $this->priorities[NS_TALK] = '0.1';
172 $this->priorities[NS_USER] = '0.5';
173 $this->priorities[NS_USER_TALK] = '0.1';
174 $this->priorities[NS_PROJECT] = '0.5';
175 $this->priorities[NS_PROJECT_TALK] = '0.1';
176 $this->priorities[NS_FILE] = '0.5';
177 $this->priorities[NS_FILE_TALK] = '0.1';
178 $this->priorities[NS_MEDIAWIKI] = '0.0';
179 $this->priorities[NS_MEDIAWIKI_TALK] = '0.1';
180 $this->priorities[NS_TEMPLATE] = '0.0';
181 $this->priorities[NS_TEMPLATE_TALK] = '0.1';
182 $this->priorities[NS_HELP] = '0.5';
183 $this->priorities[NS_HELP_TALK] = '0.1';
184 $this->priorities[NS_CATEGORY] = '0.5';
185 $this->priorities[NS_CATEGORY_TALK] = '0.1';
189 * Create directory if it does not exist and return pathname with a trailing slash
191 private static function init_path( $fspath ) {
192 if ( !isset( $fspath ) ) {
193 return null;
195 # Create directory if needed
196 if ( $fspath && !is_dir( $fspath ) ) {
197 wfMkdirParents( $fspath ) or die( "Can not create directory $fspath.\n" );
200 return realpath( $fspath ) . DIRECTORY_SEPARATOR ;
204 * Generate a one-dimensional array of existing namespaces
206 function generateNamespaces() {
207 // Only generate for specific namespaces if $wgSitemapNamespaces is an array.
208 global $wgSitemapNamespaces;
209 if ( is_array( $wgSitemapNamespaces ) ) {
210 $this->namespaces = $wgSitemapNamespaces;
211 return;
214 $res = $this->dbr->select( 'page',
215 array( 'page_namespace' ),
216 array(),
217 __METHOD__,
218 array(
219 'GROUP BY' => 'page_namespace',
220 'ORDER BY' => 'page_namespace',
224 foreach ( $res as $row )
225 $this->namespaces[] = $row->page_namespace;
229 * Get the priority of a given namespace
231 * @param $namespace Integer: the namespace to get the priority for
232 * @return String
234 function priority( $namespace ) {
235 return isset( $this->priorities[$namespace] ) ? $this->priorities[$namespace] : $this->guessPriority( $namespace );
239 * If the namespace isn't listed on the priority list return the
240 * default priority for the namespace, varies depending on whether it's
241 * a talkpage or not.
243 * @param $namespace Integer: the namespace to get the priority for
244 * @return String
246 function guessPriority( $namespace ) {
247 return MWNamespace::isMain( $namespace ) ? $this->priorities[self::GS_MAIN] : $this->priorities[self::GS_TALK];
251 * Return a database resolution of all the pages in a given namespace
253 * @param $namespace Integer: limit the query to this namespace
254 * @return Resource
256 function getPageRes( $namespace ) {
257 return $this->dbr->select( 'page',
258 array(
259 'page_namespace',
260 'page_title',
261 'page_touched',
263 array( 'page_namespace' => $namespace ),
264 __METHOD__
269 * Main loop
271 public function main() {
272 global $wgContLang;
274 fwrite( $this->findex, $this->openIndex() );
276 foreach ( $this->namespaces as $namespace ) {
277 $res = $this->getPageRes( $namespace );
278 $this->file = false;
279 $this->generateLimit( $namespace );
280 $length = $this->limit[0];
281 $i = $smcount = 0;
283 $fns = $wgContLang->getFormattedNsText( $namespace );
284 $this->output( "$namespace ($fns)\n" );
285 foreach ( $res as $row ) {
286 if ( $i++ === 0 || $i === $this->url_limit + 1 || $length + $this->limit[1] + $this->limit[2] > $this->size_limit ) {
287 if ( $this->file !== false ) {
288 $this->write( $this->file, $this->closeFile() );
289 $this->close( $this->file );
291 $filename = $this->sitemapFilename( $namespace, $smcount++ );
292 $this->file = $this->open( $this->fspath . $filename, 'wb' );
293 $this->write( $this->file, $this->openFile() );
294 fwrite( $this->findex, $this->indexEntry( $filename ) );
295 $this->output( "\t$this->fspath$filename\n" );
296 $length = $this->limit[0];
297 $i = 1;
299 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
300 $date = wfTimestamp( TS_ISO_8601, $row->page_touched );
301 $entry = $this->fileEntry( $title->getFullURL(), $date, $this->priority( $namespace ) );
302 $length += strlen( $entry );
303 $this->write( $this->file, $entry );
304 // generate pages for language variants
305 if ( $wgContLang->hasVariants() ) {
306 $variants = $wgContLang->getVariants();
307 foreach ( $variants as $vCode ) {
308 if ( $vCode == $wgContLang->getCode() ) continue; // we don't want default variant
309 $entry = $this->fileEntry( $title->getFullURL( '', $vCode ), $date, $this->priority( $namespace ) );
310 $length += strlen( $entry );
311 $this->write( $this->file, $entry );
315 if ( $this->file ) {
316 $this->write( $this->file, $this->closeFile() );
317 $this->close( $this->file );
320 fwrite( $this->findex, $this->closeIndex() );
321 fclose( $this->findex );
325 * gzopen() / fopen() wrapper
327 * @return Resource
329 function open( $file, $flags ) {
330 return $this->compress ? gzopen( $file, $flags ) : fopen( $file, $flags );
334 * gzwrite() / fwrite() wrapper
336 function write( &$handle, $str ) {
337 if ( $this->compress )
338 gzwrite( $handle, $str );
339 else
340 fwrite( $handle, $str );
344 * gzclose() / fclose() wrapper
346 function close( &$handle ) {
347 if ( $this->compress )
348 gzclose( $handle );
349 else
350 fclose( $handle );
354 * Get a sitemap filename
356 * @param $namespace Integer: the namespace
357 * @param $count Integer: the count
358 * @return String
360 function sitemapFilename( $namespace, $count ) {
361 $ext = $this->compress ? '.gz' : '';
362 return "sitemap-{$this->identifier}-NS_$namespace-$count.xml$ext";
366 * Return the XML required to open an XML file
368 * @return string
370 function xmlHead() {
371 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
375 * Return the XML schema being used
377 * @return String
379 function xmlSchema() {
380 return 'http://www.sitemaps.org/schemas/sitemap/0.9';
384 * Return the XML required to open a sitemap index file
386 * @return String
388 function openIndex() {
389 return $this->xmlHead() . '<sitemapindex xmlns="' . $this->xmlSchema() . '">' . "\n";
393 * Return the XML for a single sitemap indexfile entry
395 * @param $filename String: the filename of the sitemap file
396 * @return String
398 function indexEntry( $filename ) {
399 return
400 "\t<sitemap>\n" .
401 "\t\t<loc>{$this->urlpath}$filename</loc>\n" .
402 "\t\t<lastmod>{$this->timestamp}</lastmod>\n" .
403 "\t</sitemap>\n";
407 * Return the XML required to close a sitemap index file
409 * @return String
411 function closeIndex() {
412 return "</sitemapindex>\n";
416 * Return the XML required to open a sitemap file
418 * @return String
420 function openFile() {
421 return $this->xmlHead() . '<urlset xmlns="' . $this->xmlSchema() . '">' . "\n";
425 * Return the XML for a single sitemap entry
427 * @param $url String: an RFC 2396 compliant URL
428 * @param $date String: a ISO 8601 date
429 * @param $priority String: a priority indicator, 0.0 - 1.0 inclusive with a 0.1 stepsize
430 * @return String
432 function fileEntry( $url, $date, $priority ) {
433 return
434 "\t<url>\n" .
435 "\t\t<loc>$url</loc>\n" .
436 "\t\t<lastmod>$date</lastmod>\n" .
437 "\t\t<priority>$priority</priority>\n" .
438 "\t</url>\n";
442 * Return the XML required to close sitemap file
444 * @return String
446 function closeFile() {
447 return "</urlset>\n";
451 * Populate $this->limit
453 function generateLimit( $namespace ) {
454 // bug 17961: make a title with the longest possible URL in this namespace
455 $title = Title::makeTitle( $namespace, str_repeat( "\xf0\xa8\xae\x81", 63 ) . "\xe5\x96\x83" );
457 $this->limit = array(
458 strlen( $this->openFile() ),
459 strlen( $this->fileEntry( $title->getFullUrl(), wfTimestamp( TS_ISO_8601, wfTimestamp() ), $this->priority( $namespace ) ) ),
460 strlen( $this->closeFile() )
465 $maintClass = "GenerateSitemap";
466 require_once( RUN_MAINTENANCE_IF_MAIN );