2 /* **************************************************************
5 * (c) 2006-2009 Karsten Dambekalns <karsten@typo3.org>
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.
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.
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.
25 * This copyright notice MUST APPEAR in all copies of the script!
26 ***************************************************************/
29 * XML handling class for the TYPO3 Extension Manager.
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.
34 * @author Karsten Dambekalns <karsten@typo3.org>
38 class SC_mod_tools_em_xmlhandler
{
41 * Enxtension Manager module
43 * @var SC_mod_tools_em_index
48 * Holds the parsed XML from extensions.xml.gz
49 * @see parseExtensionsXML()
53 var $extXMLResult = array();
54 var $extensionsXML = array();
55 var $reviewStates = null;
56 var $useUnchecked = false;
57 var $useObsolete = false;
60 * Reduces the entries in $this->extensionsXML to the latest version per extension and removes entries not matching the search parameter
62 * @param string $search The list of extensions is reduced to entries matching this. If empty, the full list is returned.
63 * @param string $owner If set only extensions of that user are fetched
64 * @param string $order A field to order the result by
65 * @param boolean $allExt If set also unreviewed and obsolete extensions are shown
66 * @param boolean $allVer If set returns all version of an extension, otherwise only the last
67 * @param integer $offset Offset to return result from (goes into LIMIT clause)
68 * @param integer $limit Maximum number of entries to return (goes into LIMIT clause)
69 * @param boolean $exactMatch If set search is done for exact matches of extension keys only
72 function searchExtensionsXML($search, $owner='', $order='', $allExt=false, $allVer=false, $offset=0, $limit=500, $exactMatch=false) {
74 if ($search && $exactMatch) {
75 $where.= ' AND extkey=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($search, 'cache_extensions');
77 $where.= ' AND extkey LIKE \'%'.$GLOBALS['TYPO3_DB']->quoteStr($GLOBALS['TYPO3_DB']->escapeStrForLike($search, 'cache_extensions'), 'cache_extensions').'%\'';
80 $where.= ' AND ownerusername='.$GLOBALS['TYPO3_DB']->fullQuoteStr($owner, 'cache_extensions');
82 if (strlen($owner) ||
$this->useUnchecked ||
$allExt) {
83 // show extensions without review or that have passed review
84 $where.= ' AND reviewstate >= 0';
86 // only display extensions that have passed review
87 $where.= ' AND reviewstate > 0';
89 if (!$this->useObsolete
&& !$allExt) {
90 $where.= ' AND state!=5'; // 5 == obsolete
93 case 'author_company':
94 $forder = 'authorname, authorcompany';
101 $forder = 'category';
104 $order = $forder.', title';
106 if ($this->useUnchecked
) {
107 $where .= ' AND lastversion>0';
109 $where .= ' AND lastreviewedversion>0';
112 $this->catArr
= array();
114 foreach ($this->emObj
->defaultCategories
['cat'] as $catKey => $tmp) {
115 $this->catArr
[$idx] = $catKey;
118 $this->stateArr
= array();
120 foreach ($this->emObj
->states
as $state => $tmp) {
121 $this->stateArr
[$idx] = $state;
126 $count = $GLOBALS['TYPO3_DB']->exec_SELECTcountRows('*', 'cache_extensions', $where);
127 $this->matchingCount
= $count;
129 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'cache_extensions', $where, '', $order, $offset.','.$limit);
130 $this->extensionsXML
= array();
131 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
132 $row['category'] = $this->catArr
[$row['category']];
133 $row['state'] = $this->stateArr
[$row['state']];
135 if (!is_array($this->extensionsXML
[$row['extkey']])) {
136 $this->extensionsXML
[$row['extkey']] = array();
137 $this->extensionsXML
[$row['extkey']]['downloadcounter'] = $row['alldownloadcounter'];
139 if (!is_array($this->extensionsXML
[$row['extkey']]['versions'])) {
140 $this->extensionsXML
[$row['extkey']]['versions'] = array();
142 $row['dependencies'] = unserialize($row['dependencies']);
143 $this->extensionsXML
[$row['extkey']]['versions'][$row['version']] = $row;
145 $GLOBALS['TYPO3_DB']->sql_free_result($res);
149 * Reduces the entries in $this->extensionsXML to the latest version per extension and removes entries not matching the search parameter
150 * The extension key has to be a valid one as search is done for exact matches only.
152 * @param string $search The list of extensions is reduced to entries with exactely this extension key. If empty, the full list is returned.
153 * @param string $owner If set only extensions of that user are fetched
154 * @param string $order A field to order the result by
155 * @param boolean $allExt If set also unreviewed and obsolete extensions are shown
156 * @param boolean $allVer If set returns all version of an extension, otherwise only the last
157 * @param integer $offset Offset to return result from (goes into LIMIT clause)
158 * @param integer $limit Maximum number of entries to return (goes into LIMIT clause)
161 function searchExtensionsXMLExact($search, $owner='', $order='', $allExt=false, $allVer=false, $offset=0, $limit=500) {
162 $this->searchExtensionsXML($search, $owner, $order, $allExt, $allVer, $offset, $limit, true);
165 function countExtensions() {
166 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('extkey', 'cache_extensions', '1=1', 'extkey');
167 $cnt = $GLOBALS['TYPO3_DB']->sql_num_rows($res);
168 $GLOBALS['TYPO3_DB']->sql_free_result($res);
173 * Loads the pre-parsed extension list
175 * @return boolean true on success, false on error
177 function loadExtensionsXML() {
178 $this->searchExtensionsXML('', '', '', true);
182 * Frees the pre-parsed extension list
186 function freeExtensionsXML() {
187 unset($this->extensionsXML
);
188 $this->extensionsXML
= array();
192 * Removes all extension with a certain state from the list
194 * @param array &$extensions The "versions" subpart of the extension list
197 function removeObsolete(&$extensions) {
198 if($this->useObsolete
) return;
201 while (list($version, $data) = each($extensions)) {
202 if($data['state']=='obsolete')
203 unset($extensions[$version]);
208 * Returns the reviewstate of a specific extension-key/version
210 * @param string $extKey
211 * @param string $version: ...
212 * @return integer Review state, if none is set 0 is returned as default.
214 function getReviewState($extKey, $version) {
215 $where = 'extkey='.$GLOBALS['TYPO3_DB']->fullQuoteStr($extKey, 'cache_extensions').' AND version='.$GLOBALS['TYPO3_DB']->fullQuoteStr($version, 'cache_extensions');
216 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('reviewstate', 'cache_extensions', $where);
217 if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
218 return $row['reviewstate'];
220 $GLOBALS['TYPO3_DB']->sql_free_result($res);
225 * Removes all extension versions from $extensions that have a reviewstate<1, unless explicitly allowed
227 * @param array &$extensions The "versions" subpart of the extension list
230 function checkReviewState(&$extensions) {
231 if ($this->useUnchecked
) return;
234 while (list($version, $data) = each($extensions)) {
235 if($data['reviewstate']<1)
236 unset($extensions[$version]);
241 * Removes all extension versions from the list of available extensions that have a reviewstate<1, unless explicitly allowed
245 function checkReviewStateGlobal() {
246 if($this->useUnchecked
) return;
248 reset($this->extensionsXML
);
249 while (list($extkey, $data) = each($this->extensionsXML
)) {
250 while (list($version, $vdata) = each($data['versions'])) {
251 if($vdata['reviewstate']<1) unset($this->extensionsXML
[$extkey]['versions'][$version]);
253 if(!count($this->extensionsXML
[$extkey]['versions'])) unset($this->extensionsXML
[$extkey]);
259 * ***************PARSING METHODS***********************
262 * Enter description here...
264 * @param unknown_type $parser
265 * @param unknown_type $name
266 * @param unknown_type $attrs
269 function startElement($parser, $name, $attrs) {
274 $this->currentExt
= $attrs['extensionkey'];
277 $this->currentVersion
= $attrs['version'];
278 $this->extXMLResult
[$this->currentExt
]['versions'][$this->currentVersion
] = array();
281 $this->currentTag
= $name;
286 * Enter description here...
288 * @param unknown_type $parser
289 * @param unknown_type $name
292 function endElement($parser, $name) {
295 unset($this->currentExt
);
298 unset($this->currentVersion
);
301 unset($this->currentTag
);
306 * Enter description here...
308 * @param unknown_type $parser
309 * @param unknown_type $data
312 function characterData($parser, $data) {
313 if(isset($this->currentTag
)) {
314 if(!isset($this->currentVersion
) && $this->currentTag
== 'downloadcounter') {
315 $this->extXMLResult
[$this->currentExt
]['downloadcounter'] = trim($data);
316 } elseif($this->currentTag
== 'dependencies') {
317 $data = @unserialize
($data);
318 if(is_array($data)) {
320 foreach($data as $v) {
321 $dep[$v['kind']][$v['extensionKey']] = $v['versionRange'];
323 $this->extXMLResult
[$this->currentExt
]['versions'][$this->currentVersion
]['dependencies'] = $dep;
325 } elseif($this->currentTag
== 'reviewstate') {
326 $this->reviewStates
[$this->currentExt
][$this->currentVersion
] = (int)trim($data);
327 $this->extXMLResult
[$this->currentExt
]['versions'][$this->currentVersion
]['reviewstate'] = (int)trim($data);
329 $this->extXMLResult
[$this->currentExt
]['versions'][$this->currentVersion
][$this->currentTag
] .= trim($data);
335 * Parses content of mirrors.xml into a suitable array
337 * @param string XML data file to parse
338 * @return string HTLML output informing about result
340 function parseExtensionsXML($filename) {
342 $parser = xml_parser_create();
343 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
344 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
345 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING
, 'utf-8');
346 xml_set_element_handler($parser, array(&$this,'startElement'), array(&$this,'endElement'));
347 xml_set_character_data_handler($parser, array(&$this,'characterData'));
349 $fp = gzopen($filename, 'rb');
351 $content.= 'Error opening XML extension file "'.$filename.'"';
354 $string = gzread($fp, 0xffff); // Read 64KB
356 $this->revCatArr
= array();
358 foreach ($this->emObj
->defaultCategories
['cat'] as $catKey => $tmp) {
359 $this->revCatArr
[$catKey] = $idx++
;
362 $this->revStateArr
= array();
364 foreach ($this->emObj
->states
as $state => $tmp) {
365 $this->revStateArr
[$state] = $idx++
;
368 $GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_extensions', '1=1');
371 @ini_set
('pcre.backtrack_limit', 500000);
373 if (preg_match('/.*(<extension\s+extensionkey="[^"]+">.*<\/extension>)/suU', $string, $match)) {
375 if (!xml_parse($parser, $match[0], 0)) {
376 $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));
380 $this->storeXMLResult();
381 $this->extXMLResult
= array();
383 $string = substr($string, strlen($match[0]));
384 } elseif(function_exists('preg_last_error') && preg_last_error()) {
386 0 => 'PREG_NO_ERROR',
387 1 => 'PREG_INTERNAL_ERROR',
388 2 => 'PREG_BACKTRACK_LIMIT_ERROR',
389 3 => 'PREG_RECURSION_LIMIT_ERROR',
390 4 => 'PREG_BAD_UTF8_ERROR'
392 $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>';
396 if(gzeof($fp)) break; // Nothing more can be read
397 $string .= gzread($fp, 0xffff); // Read another 64KB
401 xml_parser_free($parser);
405 $content.= '<p>The extensions list has been updated and now contains '.$extcount.' extension entries.</p>';
411 function storeXMLResult() {
412 foreach ($this->extXMLResult
as $extkey => $extArr) {
420 $useauthorcompany = '';
423 foreach ($extArr['versions'] as $version => $vArr) {
424 $iv = $this->emObj
->makeVersion($version, 'int');
425 if ($vArr['title']&&!$usetitle) {
426 $usetitle = $vArr['title'];
428 if ($vArr['state']&&!$usestate) {
429 $usestate = $vArr['state'];
431 if ($vArr['authorcompany']&&!$useauthorcompany) {
432 $useauthorcompany = $vArr['authorcompany'];
434 if ($vArr['authorname']&&!$useauthorname) {
435 $useauthorname = $vArr['authorname'];
437 $verArr[$version] = $iv;
441 if ($vArr['title']) {
442 $usetitle = $vArr['title'];
444 if ($vArr['state']) {
445 $usestate = $vArr['state'];
447 if ($vArr['authorcompany']) {
448 $useauthorcompany = $vArr['authorcompany'];
450 if ($vArr['authorname']) {
451 $useauthorname = $vArr['authorname'];
453 $usecat = $vArr['category'];
455 if ($vArr['reviewstate'] && ($iv>$maxrev)) {
460 if (!strlen($usecat)) {
461 $usecat = 4; // Extensions without a category end up in "misc"
463 if (isset($this->revCatArr
[$usecat])) {
464 $usecat = $this->revCatArr
[$usecat];
466 $usecat = 4; // Extensions without a category end up in "misc"
469 if (isset($this->revStateArr
[$usestate])) {
470 $usestate = $this->revCatArr
[$usestate];
472 $usestate = 999; // Extensions without a category end up in "misc"
474 foreach ($extArr['versions'] as $version => $vArr) {
475 $vArr['version'] = $version;
476 $vArr['intversion'] = $verArr[$version];
477 $vArr['extkey'] = $extkey;
478 $vArr['alldownloadcounter'] = $extArr['downloadcounter'];
479 $vArr['dependencies'] = serialize($vArr['dependencies']);
480 $vArr['category'] = $usecat;
481 $vArr['title'] = $usetitle;
482 if ($version==$last) {
483 $vArr['lastversion'] = 1;
485 if ($version==$lastrev) {
486 $vArr['lastreviewedversion'] = 1;
488 $vArr['state'] = isset($this->revStateArr
[$vArr['state']])?
$this->revStateArr
[$vArr['state']]:$usestate; // 999 = not set category
489 $GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_extensions', $vArr);
495 * Parses content of mirrors.xml into a suitable array
497 * @param string $string: XML data to parse
498 * @return string HTLML output informing about result
500 function parseMirrorsXML($string) {
501 global $TYPO3_CONF_VARS;
504 $parser = xml_parser_create();
508 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
509 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
511 $preg_result = array();
512 preg_match('/^[[:space:]]*<\?xml[^>]*encoding[[:space:]]*=[[:space:]]*"([^"]*)"/',substr($string,0,200),$preg_result);
513 $theCharset = $preg_result[1] ?
$preg_result[1] : ($TYPO3_CONF_VARS['BE']['forceCharset'] ?
$TYPO3_CONF_VARS['BE']['forceCharset'] : 'iso-8859-1');
514 xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING
, $theCharset); // us-ascii / utf-8 / iso-8859-1
517 xml_parse_into_struct($parser, $string, $vals, $index);
519 // If error, return error message:
520 if (xml_get_error_code($parser)) {
521 $line = xml_get_current_line_number($parser);
522 $error = xml_error_string(xml_get_error_code($parser));
523 xml_parser_free($parser);
524 return 'Error in XML parser while decoding mirrors XML file. Line '.$line.': '.$error;
527 $stack = array(array());
534 // Traverse the parsed XML structure:
535 foreach($vals as $val) {
537 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
538 $tagName = ($val['tag']=='mirror' && $val['type']=='open') ?
'__plh' : $val['tag'];
539 if (!$documentTag) $documentTag = $tagName;
541 // Setting tag-values, manage stack:
542 switch($val['type']) {
543 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
544 $current[$tagName] = array(); // Setting blank place holder
545 $stack[$stacktop++
] = $current;
548 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
549 $oldCurrent = $current;
550 $current = $stack[--$stacktop];
551 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
552 if($tagName=='mirror') {
553 unset($current['__plh']);
554 $current[$oldCurrent['host']] = $oldCurrent;
556 $current[key($current)] = $oldCurrent;
560 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
561 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
565 return $current[$tagName];
570 * Parses content of *-l10n.xml into a suitable array
572 * @param string $string: XML data to parse
573 * @return array Array representation of XML data
575 function parseL10nXML($string) {
577 $parser = xml_parser_create();
581 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING
, 0);
582 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE
, 0);
585 xml_parse_into_struct($parser, $string, $vals, $index);
587 // If error, return error message:
588 if (xml_get_error_code($parser)) {
589 $line = xml_get_current_line_number($parser);
590 $error = xml_error_string(xml_get_error_code($parser));
592 xml_parser_free($parser);
593 return 'Error in XML parser while decoding l10n XML file. Line '.$line.': '.$error;
596 $stack = array(array());
603 // Traverse the parsed XML structure:
604 foreach($vals as $val) {
606 // First, process the tag-name (which is used in both cases, whether "complete" or "close")
607 $tagName = ($val['tag']=='languagepack' && $val['type']=='open') ?
$val['attributes']['language'] : $val['tag'];
608 if (!$documentTag) $documentTag = $tagName;
610 // Setting tag-values, manage stack:
611 switch($val['type']) {
612 case 'open': // If open tag it means there is an array stored in sub-elements. Therefore increase the stackpointer and reset the accumulation array:
613 $current[$tagName] = array(); // Setting blank place holder
614 $stack[$stacktop++
] = $current;
617 case 'close': // If the tag is "close" then it is an array which is closing and we decrease the stack pointer.
618 $oldCurrent = $current;
619 $current = $stack[--$stacktop];
620 end($current); // Going to the end of array to get placeholder key, key($current), and fill in array next:
621 $current[key($current)] = $oldCurrent;
624 case 'complete': // If "complete", then it's a value. If the attribute "base64" is set, then decode the value, otherwise just set it.
625 $current[$tagName] = (string)$val['value']; // Had to cast it as a string - otherwise it would be evaluate false if tested with isset()!!
629 return $current[$tagName];