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