using .append() instead of innerHTML+=. The latter replaces the html and causes all...
[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 URL path to prepend to filenames in the index; should resolve to the same directory as $fspath
61 *
62 * @var string
63 */
64 var $urlpath;
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; defaults to current directory', false, true );
130 $this->addOption( 'urlpath', 'The URL path corresponding to --fspath, prepended to filenames in the index; defaults to an empty string', false, true );
131 $this->addOption( 'compress', 'Compress the sitemap files, can take value yes|no, default yes', false, true );
132 }
133
134 /**
135 * Execute
136 */
137 public function execute() {
138 $this->setNamespacePriorities();
139 $this->url_limit = 50000;
140 $this->size_limit = pow( 2, 20 ) * 10;
141 $this->fspath = self::init_path( $this->getOption( 'fspath', getcwd() ) );
142 $this->urlpath = $this->getOption( 'urlpath', "" );
143 if ( $this->urlpath !== "" && substr( $this->urlpath, -1 ) !== '/' ) {
144 $this->urlpath .= '/';
145 }
146 $this->compress = $this->getOption( 'compress', 'yes' ) !== 'no';
147 $this->dbr = wfGetDB( DB_SLAVE );
148 $this->generateNamespaces();
149 $this->timestamp = wfTimestamp( TS_ISO_8601, wfTimestampNow() );
150 $this->findex = fopen( "{$this->fspath}sitemap-index-" . wfWikiID() . ".xml", 'wb' );
151 $this->main();
152 }
153
154 private function setNamespacePriorities() {
155 // Custom main namespaces
156 $this->priorities[GS_MAIN] = '0.5';
157 // Custom talk namesspaces
158 $this->priorities[GS_TALK] = '0.1';
159 // MediaWiki standard namespaces
160 $this->priorities[NS_MAIN] = '1.0';
161 $this->priorities[NS_TALK] = '0.1';
162 $this->priorities[NS_USER] = '0.5';
163 $this->priorities[NS_USER_TALK] = '0.1';
164 $this->priorities[NS_PROJECT] = '0.5';
165 $this->priorities[NS_PROJECT_TALK] = '0.1';
166 $this->priorities[NS_FILE] = '0.5';
167 $this->priorities[NS_FILE_TALK] = '0.1';
168 $this->priorities[NS_MEDIAWIKI] = '0.0';
169 $this->priorities[NS_MEDIAWIKI_TALK] = '0.1';
170 $this->priorities[NS_TEMPLATE] = '0.0';
171 $this->priorities[NS_TEMPLATE_TALK] = '0.1';
172 $this->priorities[NS_HELP] = '0.5';
173 $this->priorities[NS_HELP_TALK] = '0.1';
174 $this->priorities[NS_CATEGORY] = '0.5';
175 $this->priorities[NS_CATEGORY_TALK] = '0.1';
176 }
177
178 /**
179 * Create directory if it does not exist and return pathname with a trailing slash
180 */
181 private static function init_path( $fspath ) {
182 if ( !isset( $fspath ) ) {
183 return null;
184 }
185 # Create directory if needed
186 if ( $fspath && !is_dir( $fspath ) ) {
187 wfMkdirParents( $fspath ) or die( "Can not create directory $fspath.\n" );
188 }
189
190 return realpath( $fspath ) . DIRECTORY_SEPARATOR ;
191 }
192
193 /**
194 * Generate a one-dimensional array of existing namespaces
195 */
196 function generateNamespaces() {
197 // Only generate for specific namespaces if $wgSitemapNamespaces is an array.
198 global $wgSitemapNamespaces;
199 if ( is_array( $wgSitemapNamespaces ) ) {
200 $this->namespaces = $wgSitemapNamespaces;
201 return;
202 }
203
204 $res = $this->dbr->select( 'page',
205 array( 'page_namespace' ),
206 array(),
207 __METHOD__,
208 array(
209 'GROUP BY' => 'page_namespace',
210 'ORDER BY' => 'page_namespace',
211 )
212 );
213
214 foreach ( $res as $row )
215 $this->namespaces[] = $row->page_namespace;
216 }
217
218 /**
219 * Get the priority of a given namespace
220 *
221 * @param $namespace Integer: the namespace to get the priority for
222 * @return String
223 */
224 function priority( $namespace ) {
225 return isset( $this->priorities[$namespace] ) ? $this->priorities[$namespace] : $this->guessPriority( $namespace );
226 }
227
228 /**
229 * If the namespace isn't listed on the priority list return the
230 * default priority for the namespace, varies depending on whether it's
231 * a talkpage or not.
232 *
233 * @param $namespace Integer: the namespace to get the priority for
234 * @return String
235 */
236 function guessPriority( $namespace ) {
237 return MWNamespace::isMain( $namespace ) ? $this->priorities[GS_MAIN] : $this->priorities[GS_TALK];
238 }
239
240 /**
241 * Return a database resolution of all the pages in a given namespace
242 *
243 * @param $namespace Integer: limit the query to this namespace
244 * @return Resource
245 */
246 function getPageRes( $namespace ) {
247 return $this->dbr->select( 'page',
248 array(
249 'page_namespace',
250 'page_title',
251 'page_touched',
252 ),
253 array( 'page_namespace' => $namespace ),
254 __METHOD__
255 );
256 }
257
258 /**
259 * Main loop
260 */
261 public function main() {
262 global $wgContLang;
263
264 fwrite( $this->findex, $this->openIndex() );
265
266 foreach ( $this->namespaces as $namespace ) {
267 $res = $this->getPageRes( $namespace );
268 $this->file = false;
269 $this->generateLimit( $namespace );
270 $length = $this->limit[0];
271 $i = $smcount = 0;
272
273 $fns = $wgContLang->getFormattedNsText( $namespace );
274 $this->output( "$namespace ($fns)" );
275 foreach ( $res as $row ) {
276 if ( $i++ === 0 || $i === $this->url_limit + 1 || $length + $this->limit[1] + $this->limit[2] > $this->size_limit ) {
277 if ( $this->file !== false ) {
278 $this->write( $this->file, $this->closeFile() );
279 $this->close( $this->file );
280 }
281 $filename = $this->sitemapFilename( $namespace, $smcount++ );
282 $this->file = $this->open( $this->fspath . $filename, 'wb' );
283 $this->write( $this->file, $this->openFile() );
284 fwrite( $this->findex, $this->indexEntry( $filename ) );
285 $this->output( "\t$this->fspath$filename\n" );
286 $length = $this->limit[0];
287 $i = 1;
288 }
289 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
290 $date = wfTimestamp( TS_ISO_8601, $row->page_touched );
291 $entry = $this->fileEntry( $title->getFullURL(), $date, $this->priority( $namespace ) );
292 $length += strlen( $entry );
293 $this->write( $this->file, $entry );
294 // generate pages for language variants
295 if ( $wgContLang->hasVariants() ) {
296 $variants = $wgContLang->getVariants();
297 foreach ( $variants as $vCode ) {
298 if ( $vCode == $wgContLang->getCode() ) continue; // we don't want default variant
299 $entry = $this->fileEntry( $title->getFullURL( '', $vCode ), $date, $this->priority( $namespace ) );
300 $length += strlen( $entry );
301 $this->write( $this->file, $entry );
302 }
303 }
304 }
305 if ( $this->file ) {
306 $this->write( $this->file, $this->closeFile() );
307 $this->close( $this->file );
308 }
309 }
310 fwrite( $this->findex, $this->closeIndex() );
311 fclose( $this->findex );
312 }
313
314 /**
315 * gzopen() / fopen() wrapper
316 *
317 * @return Resource
318 */
319 function open( $file, $flags ) {
320 return $this->compress ? gzopen( $file, $flags ) : fopen( $file, $flags );
321 }
322
323 /**
324 * gzwrite() / fwrite() wrapper
325 */
326 function write( &$handle, $str ) {
327 if ( $this->compress )
328 gzwrite( $handle, $str );
329 else
330 fwrite( $handle, $str );
331 }
332
333 /**
334 * gzclose() / fclose() wrapper
335 */
336 function close( &$handle ) {
337 if ( $this->compress )
338 gzclose( $handle );
339 else
340 fclose( $handle );
341 }
342
343 /**
344 * Get a sitemap filename
345 *
346 * @param $namespace Integer: the namespace
347 * @param $count Integer: the count
348 * @return String
349 */
350 function sitemapFilename( $namespace, $count ) {
351 $ext = $this->compress ? '.gz' : '';
352 return "sitemap-" . wfWikiID() . "-NS_$namespace-$count.xml$ext";
353 }
354
355 /**
356 * Return the XML required to open an XML file
357 *
358 * @return string
359 */
360 function xmlHead() {
361 return '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
362 }
363
364 /**
365 * Return the XML schema being used
366 *
367 * @return String
368 */
369 function xmlSchema() {
370 return 'http://www.sitemaps.org/schemas/sitemap/0.9';
371 }
372
373 /**
374 * Return the XML required to open a sitemap index file
375 *
376 * @return String
377 */
378 function openIndex() {
379 return $this->xmlHead() . '<sitemapindex xmlns="' . $this->xmlSchema() . '">' . "\n";
380 }
381
382 /**
383 * Return the XML for a single sitemap indexfile entry
384 *
385 * @param $filename String: the filename of the sitemap file
386 * @return String
387 */
388 function indexEntry( $filename ) {
389 return
390 "\t<sitemap>\n" .
391 "\t\t<loc>{$this->urlpath}$filename</loc>\n" .
392 "\t\t<lastmod>{$this->timestamp}</lastmod>\n" .
393 "\t</sitemap>\n";
394 }
395
396 /**
397 * Return the XML required to close a sitemap index file
398 *
399 * @return String
400 */
401 function closeIndex() {
402 return "</sitemapindex>\n";
403 }
404
405 /**
406 * Return the XML required to open a sitemap file
407 *
408 * @return String
409 */
410 function openFile() {
411 return $this->xmlHead() . '<urlset xmlns="' . $this->xmlSchema() . '">' . "\n";
412 }
413
414 /**
415 * Return the XML for a single sitemap entry
416 *
417 * @param $url String: an RFC 2396 compliant URL
418 * @param $date String: a ISO 8601 date
419 * @param $priority String: a priority indicator, 0.0 - 1.0 inclusive with a 0.1 stepsize
420 * @return String
421 */
422 function fileEntry( $url, $date, $priority ) {
423 return
424 "\t<url>\n" .
425 "\t\t<loc>$url</loc>\n" .
426 "\t\t<lastmod>$date</lastmod>\n" .
427 "\t\t<priority>$priority</priority>\n" .
428 "\t</url>\n";
429 }
430
431 /**
432 * Return the XML required to close sitemap file
433 *
434 * @return String
435 */
436 function closeFile() {
437 return "</urlset>\n";
438 }
439
440 /**
441 * Populate $this->limit
442 */
443 function generateLimit( $namespace ) {
444 $title = Title::makeTitle( $namespace, str_repeat( "\xf0\xa8\xae\x81", 63 ) . "\xe5\x96\x83" );
445
446 $this->limit = array(
447 strlen( $this->openFile() ),
448 strlen( $this->fileEntry( $title->getFullUrl(), wfTimestamp( TS_ISO_8601, wfTimestamp() ), $this->priority( $namespace ) ) ),
449 strlen( $this->closeFile() )
450 );
451 }
452 }
453
454 $maintClass = "GenerateSitemap";
455 require_once( DO_MAINTENANCE );