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