139b6bae9de4334f3b71f471241848cc085a5c0e
[Packages/TYPO3.CMS.git] / typo3 / mod / tools / em / class.em_xmlhandler.php
1 <?php
2 /* **************************************************************
3 * Copyright notice
4 *
5 * (c) 2006 Karsten Dambekalns <karsten@typo3.org>
6 * All rights reserved
7 *
8 * This script is part of the TYPO3 project. The TYPO3 project is
9 * free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * The GNU General Public License can be found at
15 * http://www.gnu.org/copyleft/gpl.html.
16 * A copy is found in the textfile GPL.txt and important notices to the license
17 * from the author is found in LICENSE.txt distributed with these scripts.
18 *
19 *
20 * This script is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
24 *
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
27
28 /**
29 * XML handling class for the TYPO3 Extension Manager.
30 *
31 * It contains methods for handling the XML files involved with the EM,
32 * such as the list of extension mirrors and the list of available extensions.
33 *
34 * @author Karsten Dambekalns <karsten@typo3.org>
35 * @package TYPO3
36 * @subpackage EM
37 */
38 class SC_mod_tools_em_xmlhandler {
39 /**
40 * Holds the parsed XML from extensions.xml.gz
41 * @see parseExtensionsXML()
42 *
43 * @var array
44 */
45 var $emObj;
46 var $extXMLResult = array();
47 var $extensionsXML = array();
48 var $reviewStates = null;
49 var $useUnchecked = false;
50 var $useObsolete = false;
51
52 /**
53 * Reduces the entries in $this->extensionsXML to the latest version per extension and removes entries not matching the search parameter
54 *
55 * @param string $search The list of extensions is reduced to entries matching this. If empty, the full list is returned.
56 * @param boolean $latest If true, only the latest version is kept in the list
57 * @return [type] ...
58 */
59 function searchExtensionsXML($search, $owner='', $order = '', $allExt = false, $allVer = false, $offset = 0, $limit = 500) {
60 $where = '1=1';
61 if ($search) {
62 $where .= ' AND extkey LIKE \'%'.$GLOBALS['TYPO3_DB']->quoteStr($GLOBALS['TYPO3_DB']->escapeStrForLike($search, 'cache_extensions'), 'cache_extensions').'%\'';
63 }
64 if ($owner) {
65 $where .= ' AND ownerusername='.$GLOBALS['TYPO3_DB']->fullQuoteStr($owner, 'cache_extensions');
66 }
67 if(!(strlen($owner) || $this->useUnchecked || $allExt)) {
68 $where .= ' AND reviewstate>0';
69 }
70 if(!($this->useObsolete || $allExt)) {
71 $where .= ' AND state!=5'; // 5 == obsolete
72 }
73 switch ($order) {
74 case 'author_company':
75 $forder = 'authorname, authorcompany';
76 break;
77 case 'state':
78 $forder = 'state';
79 break;
80 case 'cat':
81 default:
82 $forder = 'category';
83 break;
84 }
85 $order = $forder.', title';
86 if (!$allVer) {
87 if ($this->useUnchecked) {
88 $where .= ' AND lastversion>0';
89 } else {
90 $where .= ' AND lastreviewedversion>0';
91 }
92 }
93 $this->catArr = array();
94 $idx = 0;
95 foreach ($this->emObj->defaultCategories['cat'] as $catKey => $tmp) {
96 $this->catArr[$idx] = $catKey;
97 $idx++;
98 }
99 $this->stateArr = array();
100 $idx = 0;
101 foreach ($this->emObj->states as $state => $tmp) {
102 $this->stateArr[$idx] = $state;
103 $idx++;
104 }
105
106 // Fetch count
107 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('count(*) as cnt', 'cache_extensions', $where);
108 $row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
109 $this->matchingCount = $row['cnt'];
110 $GLOBALS['TYPO3_DB']->sql_free_result($res);
111
112 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'cache_extensions', $where, '', $order, $offset.','.$limit);
113 $this->extensionsXML = array();
114 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
115 $row['category'] = $this->catArr[$row['category']];
116 $row['state'] = $this->stateArr[$row['state']];
117
118 if (!is_array($this->extensionsXML[$row['extkey']])) {
119 $this->extensionsXML[$row['extkey']] = array();
120 $this->extensionsXML[$row['extkey']]['downloadcounter'] = $row['alldownloadcounter'];
121 }
122 if (!is_array($this->extensionsXML[$row['extkey']]['versions'])) {
123 $this->extensionsXML[$row['extkey']]['versions'] = array();
124 }
125 $row['dependencies'] = unserialize($row['dependencies']);
126 $this->extensionsXML[$row['extkey']]['versions'][$row['version']] = $row;
127 }
128 $GLOBALS['TYPO3_DB']->sql_free_result($res);
129 }
130
131 function countExtensions() {
132 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('extkey', 'cache_extensions', '1=1', 'extkey');
133 $cnt = $GLOBALS['TYPO3_DB']->sql_num_rows($res);
134 $GLOBALS['TYPO3_DB']->sql_free_result($res);
135 return $cnt;
136 }
137
138 /**
139 * Loads the pre-parsed extension list
140 *
141 * @return boolean true on success, false on error
142 */
143 function loadExtensionsXML() {
144 $this->searchExtensionsXML('', '', '', true);
145 }
146
147 /**
148 * Frees the pre-parsed extension list
149 *
150 * @return void
151 */
152 function freeExtensionsXML() {
153 unset($this->extensionsXML);
154 $this->extensionsXML = array();
155 }
156
157 /**
158 * Removes all extension with a certain state from the list
159 *
160 * @param array &$extensions The "versions" subpart of the extension list
161 * @return void
162 */
163 function removeObsolete(&$extensions) {
164 if($this->useObsolete) return;
165
166 reset($extensions);
167 while (list($version, $data) = each($extensions)) {
168 if($data['state']=='obsolete')
169 unset($extensions[$version]);
170 }
171 }
172
173 /**
174 + * Returns the reviewstate of a specific extension-key/version
175 *
176 * @param string $extKey
177 * @param string $version: ...
178 * @return integer Review state, if none is set 0 is returned as default.
179 */
180 function getReviewState($extKey, $version) {
181 $where = 'extkey='.$GLOBALS['TYPO3_DB']->fullQuoteStr($extKey, 'cache_extensions').' AND version='.$GLOBALS['TYPO3_DB']->fullQuoteStr($version, 'cache_extensions');
182 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('reviewstate', 'cache_extensions', $where);
183 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
184 return $row['reviewstate'];
185 }
186 $GLOBALS['TYPO3_DB']->sql_free_result($res);
187 return 0;
188 }
189
190 /**
191 * Removes all extension versions from $extensions that have a reviewstate<1, unless explicitly allowed
192 *
193 * @param array &$extensions The "versions" subpart of the extension list
194 * @return void
195 */
196 function checkReviewState(&$extensions) {
197 if ($this->useUnchecked) return;
198
199 reset($extensions);
200 while (list($version, $data) = each($extensions)) {
201 if($data['reviewstate']<1)
202 unset($extensions[$version]);
203 }
204 }
205
206 /**
207 * Removes all extension versions from the list of available extensions that have a reviewstate<1, unless explicitly allowed
208 *
209 * @return void
210 */
211 function checkReviewStateGlobal() {
212 if($this->useUnchecked) return;
213
214 reset($this->extensionsXML);
215 while (list($extkey, $data) = each($this->extensionsXML)) {
216 while (list($version, $vdata) = each($data['versions'])) {
217 if($vdata['reviewstate']<1) unset($this->extensionsXML[$extkey]['versions'][$version]);
218 }
219 if(!count($this->extensionsXML[$extkey]['versions'])) unset($this->extensionsXML[$extkey]);
220 }
221 }
222
223
224 /**
225 * ***************PARSING METHODS***********************
226 */
227 /**
228 * Enter description here...
229 *
230 * @param unknown_type $parser
231 * @param unknown_type $name
232 * @param unknown_type $attrs
233 * @return [type] ...
234 */
235 function startElement($parser, $name, $attrs) {
236 switch($name) {
237 case 'extensions':
238 break;
239 case 'extension':
240 $this->currentExt = $attrs['extensionkey'];
241 break;
242 case 'version':
243 $this->currentVersion = $attrs['version'];
244 $this->extXMLResult[$this->currentExt]['versions'][$this->currentVersion] = array();
245 break;
246 default:
247 $this->currentTag = $name;
248 }
249 }
250
251 /**
252 * Enter description here...
253 *
254 * @param unknown_type $parser
255 * @param unknown_type $name
256 * @return [type] ...
257 */
258 function endElement($parser, $name) {
259 switch($name) {
260 case 'extension':
261 unset($this->currentExt);
262 break;
263 case 'version':
264 unset($this->currentVersion);
265 break;
266 default:
267 unset($this->currentTag);
268 }
269 }
270
271 /**
272 * Enter description here...
273 *
274 * @param unknown_type $parser
275 * @param unknown_type $data
276 * @return [type] ...
277 */
278 function characterData($parser, $data) {
279 if(isset($this->currentTag)) {
280 if(!isset($this->currentVersion) && $this->currentTag == 'downloadcounter') {
281 $this->extXMLResult[$this->currentExt]['downloadcounter'] = trim($data);
282 } elseif($this->currentTag == 'dependencies') {
283 $data = @unserialize($data);
284 if(is_array($data)) {
285 $dep = array();
286 foreach($data as $v) {
287 $dep[$v['kind']][$v['extensionKey']] = $v['versionRange'];
288 }
289 $this->extXMLResult[$this->currentExt]['versions'][$this->currentVersion]['dependencies'] = $dep;
290 }
291 } elseif($this->currentTag == 'reviewstate') {
292 $this->reviewStates[$this->currentExt][$this->currentVersion] = (int)trim($data);
293 $this->extXMLResult[$this->currentExt]['versions'][$this->currentVersion]['reviewstate'] = (int)trim($data);
294 } else {
295 $this->extXMLResult[$this->currentExt]['versions'][$this->currentVersion][$this->currentTag] .= trim($data);
296 }
297 }
298 }
299
300 /**
301 * Parses content of mirrors.xml into a suitable array
302 *
303 * @param string XML data file to parse
304 * @return string HTLML output informing about result
305 */
306 function parseExtensionsXML($filename) {
307
308 $parser = xml_parser_create();
309 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
310 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
311 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'utf-8');
312 xml_set_element_handler($parser, array(&$this,'startElement'), array(&$this,'endElement'));
313 xml_set_character_data_handler($parser, array(&$this,'characterData'));
314
315 $fp = gzopen($filename, 'rb');
316 if (!$fp) {
317 $content.= 'Error opening XML extension file "'.$filename.'"';
318 return $content;
319 }
320 $string = gzread($fp, 0xffff); // Read 64KB
321
322 $this->revCatArr = array();
323 $idx = 0;
324 foreach ($this->emObj->defaultCategories['cat'] as $catKey => $tmp) {
325 $this->revCatArr[$catKey] = $idx++;
326 }
327
328 $this->revStateArr = array();
329 $idx = 0;
330 foreach ($this->emObj->states as $state => $tmp) {
331 $this->revStateArr[$state] = $idx++;
332 }
333
334 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_extensions', '1=1');
335
336 $extcount = 0;
337 @ini_set('pcre.backtrack_limit', 500000);
338 do {
339 if (preg_match('/.*(<extension\s+extensionkey="[^"]+">.*<\/extension>)/suU', $string, $match)) {
340 // Parse content:
341 if (!xml_parse($parser, $match[0], 0)) {
342 $content.= 'Error in XML parser while decoding extensions XML file. Line '.xml_get_current_line_number($parser).': '.xml_error_string(xml_get_error_code($parser));
343 $error = true;
344 break;
345 }
346 $this->storeXMLResult();
347 $this->extXMLResult = array();
348 $extcount++;
349 $string = substr($string, strlen($match[0]));
350 } elseif(function_exists('preg_last_error') && preg_last_error()) {
351 $errorcodes = array(
352 0 => 'PREG_NO_ERROR',
353 1 => 'PREG_INTERNAL_ERROR',
354 2 => 'PREG_BACKTRACK_LIMIT_ERROR',
355 3 => 'PREG_RECURSION_LIMIT_ERROR',
356 4 => 'PREG_BAD_UTF8_ERROR'
357 );
358 $content.= 'Error in regular expression matching, code: '.$errorcodes[preg_last_error()].'<br />See <a href="http://www.php.net/manual/en/function.preg-last-error.php" target="_blank">http://www.php.net/manual/en/function.preg-last-error.php</a>';
359 $error = true;
360 break;
361 } else {
362 if(gzeof($fp)) break; // Nothing more can be read
363 $string .= gzread($fp, 0xffff); // Read another 64KB
364 }
365 } while (true);
366
367 xml_parser_free($parser);
368 gzclose($fp);
369
370 if(!$error) {
371 $content.= '<p>The extensions list has been updated and now contains '.$extcount.' extension entries.</p>';
372 }
373
374 return $content;
375 }
376
377 function storeXMLResult() {
378 foreach ($this->extXMLResult as $extkey => $extArr) {
379 $max = -1;
380 $maxrev = -1;
381 $last = '';
382 $lastrev = '';
383 $usecat = '';
384 $usetitle = '';
385 $usestate = '';
386 $useauthorcompany = '';
387 $useauthorname = '';
388 $verArr = array();
389 foreach ($extArr['versions'] as $version => $vArr) {
390 $iv = $this->emObj->makeVersion($version, 'int');
391 if ($vArr['title']&&!$usetitle) {
392 $usetitle = $vArr['title'];
393 }
394 if ($vArr['state']&&!$usestate) {
395 $usestate = $vArr['state'];
396 }
397 if ($vArr['authorcompany']&&!$useauthorcompany) {
398 $useauthorcompany = $vArr['authorcompany'];
399 }
400 if ($vArr['authorname']&&!$useauthorname) {
401 $useauthorname = $vArr['authorname'];
402 }
403 $verArr[$version] = $iv;
404 if ($iv>$max) {
405 $max = $iv;
406 $last = $version;
407 if ($vArr['title']) {
408 $usetitle = $vArr['title'];
409 }
410 if ($vArr['state']) {
411 $usestate = $vArr['state'];
412 }
413 if ($vArr['authorcompany']) {
414 $useauthorcompany = $vArr['authorcompany'];
415 }
416 if ($vArr['authorname']) {
417 $useauthorname = $vArr['authorname'];
418 }
419 $usecat = $vArr['category'];
420 }
421 if ($vArr['reviewstate'] && ($iv>$maxrev)) {
422 $maxrev = $iv;
423 $lastrev = $version;
424 }
425 }
426 if (!strlen($usecat)) {
427 $usecat = 4; // Extensions without a category end up in "misc"
428 } else {
429 if (isset($this->revCatArr[$usecat])) {
430 $usecat = $this->revCatArr[$usecat];
431 } else {
432 $usecat = 4; // Extensions without a category end up in "misc"
433 }
434 }
435 if (isset($this->revStateArr[$usestate])) {
436 $usestate = $this->revCatArr[$usestate];
437 } else {
438 $usestate = 999; // Extensions without a category end up in "misc"
439 }
440 foreach ($extArr['versions'] as $version => $vArr) {
441 $vArr['version'] = $version;
442 $vArr['intversion'] = $verArr[$version];
443 $vArr['extkey'] = $extkey;
444 $vArr['alldownloadcounter'] = $extArr['downloadcounter'];
445 $vArr['dependencies'] = serialize($vArr['dependencies']);
446 $vArr['category'] = $usecat;
447 $vArr['title'] = $usetitle;
448 if ($version==$last) {
449 $vArr['lastversion'] = 1;
450 }
451 if ($version==$lastrev) {
452 $vArr['lastreviewedversion'] = 1;
453 }
454 $vArr['state'] = isset($this->revStateArr[$vArr['state']])?$this->revStateArr[$vArr['state']]:$usestate; // 999 = not set category
455 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_extensions', $vArr);
456 }
457 }
458 }
459
460 /**
461 * Parses content of mirrors.xml into a suitable array
462 *
463 * @param string $string: XML data to parse
464 * @return string HTLML output informing about result
465 */
466 function parseMirrorsXML($string) {
467 global $TYPO3_CONF_VARS;
468
469 // Create parser:
470 $parser = xml_parser_create();
471 $vals = array();
472 $index = array();
473
474 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
475 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
476
477 if ((double)phpversion()>=5) {
478 $preg_result = array();
479 preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/',substr($string,0,200),$preg_result);
480 $theCharset = $preg_result[1] ? $preg_result[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ? $TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
481 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, $theCharset); // us-ascii / utf-8 / iso-8859-1
482 }
483
484 // Parse content:
485 xml_parse_into_struct($parser, $string, $vals, $index);
486
487 // If error, return error message:
488 if (xml_get_error_code($parser)) {
489 $line = xml_get_current_line_number($parser);
490 $error = xml_error_string(xml_get_error_code($parser));
491 xml_parser_free($parser);
492 return 'Error in XML parser while decoding mirrors XML file. Line '.$line.': '.$error;
493 } else {
494 // Init vars:
495 $stack = array(array());
496 $stacktop = 0;
497 $mirrornumber = 0;
498 $current=array();
499 $tagName = '';
500 $documentTag = '';
501
502 // Traverse the parsed XML structure:
503 foreach($vals as $val) {
504
505 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
506 $tagName = ($val['tag']=='mirror' && $val['type']=='open') ? '__plh' : $val['tag'];
507 if (!$documentTag) $documentTag = $tagName;
508
509 // Setting tag-values, manage stack:
510 switch($val['type']) {
511 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
512 $current[$tagName] = array(); // Setting blank place holder
513 $stack[$stacktop++] = $current;
514 $current = array();
515 break;
516 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
517 $oldCurrent = $current;
518 $current = $stack[--$stacktop];
519 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
520 if($tagName=='mirror') {
521 unset($current['__plh']);
522 $current[$oldCurrent['host']] = $oldCurrent;
523 } else {
524 $current[key($current)] = $oldCurrent;
525 }
526 unset($oldCurrent);
527 break;
528 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
529 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
530 break;
531 }
532 }
533 return $current[$tagName];
534 }
535 }
536
537 /**
538 * Parses content of *-l10n.xml into a suitable array
539 *
540 * @param string $string: XML data to parse
541 * @return array Array representation of XML data
542 */
543 function parseL10nXML($string) {
544 // Create parser:
545 $parser = xml_parser_create();
546 $vals = array();
547 $index = array();
548
549 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
550 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
551
552 // Parse content:
553 xml_parse_into_struct($parser, $string, $vals, $index);
554
555 // If error, return error message:
556 if (xml_get_error_code($parser)) {
557 $line = xml_get_current_line_number($parser);
558 $error = xml_error_string(xml_get_error_code($parser));
559 debug($error);
560 xml_parser_free($parser);
561 return 'Error in XML parser while decoding l10n XML file. Line '.$line.': '.$error;
562 } else {
563 // Init vars:
564 $stack = array(array());
565 $stacktop = 0;
566 $mirrornumber = 0;
567 $current=array();
568 $tagName = '';
569 $documentTag = '';
570
571 // Traverse the parsed XML structure:
572 foreach($vals as $val) {
573
574 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
575 $tagName = ($val['tag']=='languagepack' && $val['type']=='open') ? $val['attributes']['language'] : $val['tag'];
576 if (!$documentTag) $documentTag = $tagName;
577
578 // Setting tag-values, manage stack:
579 switch($val['type']) {
580 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
581 $current[$tagName] = array(); // Setting blank place holder
582 $stack[$stacktop++] = $current;
583 $current = array();
584 break;
585 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
586 $oldCurrent = $current;
587 $current = $stack[--$stacktop];
588 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
589 $current[key($current)] = $oldCurrent;
590 unset($oldCurrent);
591 break;
592 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
593 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
594 break;
595 }
596 }
597 return $current[$tagName];
598 }
599 }
600 }
601 ?>