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