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