coding style tweaks
[lhc/web/wiklou.git] / maintenance / generateSitemap.php
1 <?php
2 define( 'GS_MAIN', -2 );
3 define( 'GS_TALK', -1 );
4 /**
5 * Creates a sitemap for the site
6 *
7 * Copyright © 2005, Ævar Arnfjörð Bjarmason, Jens Frank <jeluf@gmx.de> and
8 * Brion Vibber <brion@pobox.com>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 *
25 * @file
26 * @ingroup Maintenance
27 * @see http://www.sitemaps.org/
28 * @see http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
29 */
30
31 require_once( dirname( __FILE__ ) . '/Maintenance.php' );
32
33 class GenerateSitemap extends Maintenance {
34 /**
35 * The maximum amount of urls in a sitemap file
36 *
37 * @link http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd
38 *
39 * @var int
40 */
41 var $url_limit;
42
43 /**
44 * The maximum size of a sitemap file
45 *
46 * @link http://www.sitemaps.org/faq.php#faq_sitemap_size
47 *
48 * @var int
49 */
50 var $size_limit;
51
52 /**
53 * The path to prepend to the filename
54 *
55 * @var string
56 */
57 var $fspath;
58
59 /**
60 * The path to append to the domain name
61 *
62 * @var string
63 */
64 var $path;
65
66 /**
67 * Whether or not to use compression
68 *
69 * @var bool
70 */
71 var $compress;
72
73 /**
74 * The number of entries to save in each sitemap file
75 *
76 * @var array
77 */
78 var $limit = array();
79
80 /**
81 * Key => value entries of namespaces and their priorities
82 *
83 * @var array
84 */
85 var $priorities = array();
86
87 /**
88 * A one-dimensional array of namespaces in the wiki
89 *
90 * @var array
91 */
92 var $namespaces = array();
93
94 /**
95 * When this sitemap batch was generated
96 *
97 * @var string
98 */
99 var $timestamp;
100
101 /**
102 * A database slave object
103 *
104 * @var object
105 */
106 var $dbr;
107
108 /**
109 * A resource pointing to the sitemap index file
110 *
111 * @var resource
112 */
113 var $findex;
114
115
116 /**
117 * A resource pointing to a sitemap file
118 *
119 * @var resource
120 */
121 var $file;
122
123 /**
124 * Constructor
125 */
126 public function __construct() {
127 parent::__construct();
128 $this->mDescription = "Creates a sitemap for the site";
129 $this->addOption( 'fspath', 'The file system path to save to, e.g. /tmp/sitemap' .
130 "\n\t\tdefaults to current directory", false, true );
131 $this->addOption( 'server', "The protocol and server name to use in URLs, e.g.\n" .
132 "\t\thttp://en.wikipedia.org. This is sometimes necessary because\n" .
133 "\t\tserver name detection may fail in command line scripts.", false, true );
134 $this->addOption( 'compress', 'Compress the sitemap files, can take value yes|no, default yes', false, true );
135 }
136
137 /**
138 * Execute
139 */
140 public function execute() {
141 $this->setNamespacePriorities();
142 $this->url_limit = 50000;
143 $this->size_limit = pow( 2, 20 ) * 10;
144 $this->fspath = self::init_path( $this->getOption( 'fspath', getcwd() ) );
145 $this->compress = $this->getOption( 'compress', 'yes' ) !== 'no';
146 $this->dbr = wfGetDB( DB_SLAVE );
147 $this->generateNamespaces();
148 $this->timestamp = wfTimestamp( TS_ISO_8601, wfTimestampNow() );
149 $this->findex = fopen( "{$this->fspath}sitemap-index-" . wfWikiID() . ".xml", 'wb' );
150 $this->main();
151 }
152
153 private function setNamespacePriorities() {
154 // Custom main namespaces
155 $this->priorities[GS_MAIN] = '0.5';
156 // Custom talk namesspaces
157 $this->priorities[GS_TALK] = '0.1';
158 // MediaWiki standard namespaces
159 $this->priorities[NS_MAIN] = '1.0';
160 $this->priorities[NS_TALK] = '0.1';
161 $this->priorities[NS_USER] = '0.5';
162 $this->priorities[NS_USER_TALK] = '0.1';
163 $this->priorities[NS_PROJECT] = '0.5';
164 $this->priorities[NS_PROJECT_TALK] = '0.1';
165 $this->priorities[NS_FILE] = '0.5';
166 $this->priorities[NS_FILE_TALK] = '0.1';
167 $this->priorities[NS_MEDIAWIKI] = '0.0';
168 $this->priorities[NS_MEDIAWIKI_TALK] = '0.1';
169 $this->priorities[NS_TEMPLATE] = '0.0';
170 $this->priorities[NS_TEMPLATE_TALK] = '0.1';
171 $this->priorities[NS_HELP] = '0.5';
172 $this->priorities[NS_HELP_TALK] = '0.1';
173 $this->priorities[NS_CATEGORY] = '0.5';
174 $this->priorities[NS_CATEGORY_TALK] = '0.1';
175 }
176
177 /**
178 * Create directory if it does not exist and return pathname with a trailing slash
179 */
180 private static function init_path( $fspath ) {
181 if ( !isset( $fspath ) ) {
182 return null;
183 }
184 # Create directory if needed
185 if ( $fspath && !is_dir( $fspath ) ) {
186 wfMkdirParents( $fspath ) or die( "Can not create directory $fspath.\n" );
187 }
188
189 return realpath( $fspath ) . DIRECTORY_SEPARATOR ;
190 }
191
192 /**
193 * Generate a one-dimensional array of existing namespaces
194 */
195 function generateNamespaces() {
196 // Only generate for specific namespaces if $wgSitemapNamespaces is an array.
197 global $wgSitemapNamespaces;
198 if ( is_array( $wgSitemapNamespaces ) ) {
199 $this->namespaces = $wgSitemapNamespaces;
200 return;
201 }
202
203 $res = $this->dbr->select( 'page',
204 array( 'page_namespace' ),
205 array(),
206 __METHOD__,
207 array(
208 'GROUP BY' => 'page_namespace',
209 'ORDER BY' => 'page_namespace',
210 )
211 );
212
213 foreach ( $res as $row )
214 $this->namespaces[] = $row->page_namespace;
215 }
216
217 /**
218 * Get the priority of a given namespace
219 *
220 * @param $namespace Integer: the namespace to get the priority for
221 * @return String
222 */
223 function priority( $namespace ) {
224 return isset( $this->priorities[$namespace] ) ? $this->priorities[$namespace] : $this->guessPriority( $namespace );
225 }
226
227 /**
228 * If the namespace isn't listed on the priority list return the
229 * default priority for the namespace, varies depending on whether it's
230 * a talkpage or not.
231 *
232 * @param $namespace Integer: the namespace to get the priority for
233 * @return String
234 */
235 function guessPriority( $namespace ) {
236 return MWNamespace::isMain( $namespace ) ? $this->priorities[GS_MAIN] : $this->priorities[GS_TALK];
237 }
238
239 /**
240 * Return a database resolution of all the pages in a given namespace
241 *
242 * @param $namespace Integer: limit the query to this namespace
243 * @return Resource
244 */
245 function getPageRes( $namespace ) {
246 return $this->dbr->select( 'page',
247 array(
248 'page_namespace',
249 'page_title',
250 'page_touched',
251 ),
252 array( 'page_namespace' => $namespace ),
253 __METHOD__
254 );
255 }
256
257 /**
258 * Main loop
259 */
260 public function main() {
261 global $wgContLang;
262
263 fwrite( $this->findex, $this->openIndex() );
264
265 foreach ( $this->namespaces as $namespace ) {
266 $res = $this->getPageRes( $namespace );
267 $this->file = false;
268 $this->generateLimit( $namespace );
269 $length = $this->limit[0];
270 $i = $smcount = 0;
271
272 $fns = $wgContLang->getFormattedNsText( $namespace );
273 $this->output( "$namespace ($fns)" );
274 foreach ( $res as $row ) {
275 if ( $i++ === 0 || $i === $this->url_limit + 1 || $length + $this->limit[1] + $this->limit[2] > $this->size_limit ) {
276 if ( $this->file !== false ) {
277 $this->write( $this->file, $this->closeFile() );
278 $this->close( $this->file );
279 }
280 $filename = $this->sitemapFilename( $namespace, $smcount++ );
281 $this->file = $this->open( $this->fspath . $filename, 'wb' );
282 $this->write( $this->file, $this->openFile() );
283 fwrite( $this->findex, $this->indexEntry( $filename ) );
284 $this->output( "\t$this->fspath$filename\n" );
285 $length = $this->limit[0];
286 $i = 1;
287 }
288 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
289 $date = wfTimestamp( TS_ISO_8601, $row->page_touched );
290 $entry = $this->fileEntry( $title->getFullURL(), $date, $this->priority( $namespace ) );
291 $length += strlen( $entry );
292 $this->write( $this->file, $entry );
293 // generate pages for language variants
294 if ( $wgContLang->hasVariants() ) {
295 $variants = $wgContLang->getVariants();
296 foreach ( $variants as $vCode ) {
297 if ( $vCode == $wgContLang->getCode() ) continue; // we don't want default variant
298 $entry = $this->fileEntry( $title->getFullURL( '', $vCode ), $date, $this->priority( $namespace ) );
299 $length += strlen( $entry );
300 $this->write( $this->file, $entry );
301 }
302 }
303 }
304 if ( $this->file ) {
305 $this->write( $this->file, $this->closeFile() );
306 $this->close( $this->file );
307 }
308 }
309 fwrite( $this->findex, $this->closeIndex() );
310 fclose( $this->findex );
311 }
312
313 /**
314 * gzopen() / fopen() wrapper
315 *
316 * @return Resource
317 */
318 function open( $file, $flags ) {
319 return $this->compress ? gzopen( $file, $flags ) : fopen( $file, $flags );
320 }
321
322 /**
323 * gzwrite() / fwrite() wrapper
324 */
325 function write( &$handle, $str ) {
326 if ( $this->compress )
327 gzwrite( $handle, $str );
328 else
329 fwrite( $handle, $str );
330 }
331
332 /**
333 * gzclose() / fclose() wrapper
334 */
335 function close( &$handle ) {
336 if ( $this->compress )
337 gzclose( $handle );
338 else
339 fclose( $handle );
340 }
341
342 /**
343 * Get a sitemap filename
344 *
345 * @param $namespace Integer: the namespace
346 * @param $count Integer: the count
347 * @return String
348 */
349 function sitemapFilename( $namespace, $count ) {
350 $ext = $this->compress ? '.gz' : '';
351 return "sitemap-" . wfWikiID() . "-NS_$namespace-$count.xml$ext";
352 }
353
354 /**
355 * Return the XML required to open an XML file
356 *
357 * @return string
358 */
359 function xmlHead() {
360 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
361 }
362
363 /**
364 * Return the XML schema being used
365 *
366 * @return String
367 */
368 function xmlSchema() {
369 return 'http://www.sitemaps.org/schemas/sitemap/0.9';
370 }
371
372 /**
373 * Return the XML required to open a sitemap index file
374 *
375 * @return String
376 */
377 function openIndex() {
378 return $this->xmlHead() . '<sitemapindex xmlns="' . $this->xmlSchema() . '">' . "\n";
379 }
380
381 /**
382 * Return the XML for a single sitemap indexfile entry
383 *
384 * @param $filename String: the filename of the sitemap file
385 * @return String
386 */
387 function indexEntry( $filename ) {
388 return
389 "\t<sitemap>\n" .
390 "\t\t<loc>$filename</loc>\n" .
391 "\t\t<lastmod>{$this->timestamp}</lastmod>\n" .
392 "\t</sitemap>\n";
393 }
394
395 /**
396 * Return the XML required to close a sitemap index file
397 *
398 * @return String
399 */
400 function closeIndex() {
401 return "</sitemapindex>\n";
402 }
403
404 /**
405 * Return the XML required to open a sitemap file
406 *
407 * @return String
408 */
409 function openFile() {
410 return $this->xmlHead() . '<urlset xmlns="' . $this->xmlSchema() . '">' . "\n";
411 }
412
413 /**
414 * Return the XML for a single sitemap entry
415 *
416 * @param $url String: an RFC 2396 compliant URL
417 * @param $date String: a ISO 8601 date
418 * @param $priority String: a priority indicator, 0.0 - 1.0 inclusive with a 0.1 stepsize
419 * @return String
420 */
421 function fileEntry( $url, $date, $priority ) {
422 return
423 "\t<url>\n" .
424 "\t\t<loc>$url</loc>\n" .
425 "\t\t<lastmod>$date</lastmod>\n" .
426 "\t\t<priority>$priority</priority>\n" .
427 "\t</url>\n";
428 }
429
430 /**
431 * Return the XML required to close sitemap file
432 *
433 * @return String
434 */
435 function closeFile() {
436 return "</urlset>\n";
437 }
438
439 /**
440 * Populate $this->limit
441 */
442 function generateLimit( $namespace ) {
443 $title = Title::makeTitle( $namespace, str_repeat( "\xf0\xa8\xae\x81", 63 ) . "\xe5\x96\x83" );
444
445 $this->limit = array(
446 strlen( $this->openFile() ),
447 strlen( $this->fileEntry( $title->getFullUrl(), wfTimestamp( TS_ISO_8601, wfTimestamp() ), $this->priority( $namespace ) ) ),
448 strlen( $this->closeFile() )
449 );
450 }
451 }
452
453 $maintClass = "GenerateSitemap";
454 require_once( DO_MAINTENANCE );