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