3 /***************************************************************************\
4 * SPIP, Systeme de publication pour l'internet *
6 * Copyright (c) 2001-2017 *
7 * Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James *
9 * Ce programme est un logiciel libre distribue sous licence GNU/GPL. *
10 * Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. *
11 \***************************************************************************/
14 * Gestion de l'itérateur DATA
16 * @package SPIP\Core\Iterateur\DATA
19 if (!defined('_ECRIRE_INC_VERSION')) {
23 if (!defined('_DATA_SOURCE_MAX_SIZE')) {
24 define('_DATA_SOURCE_MAX_SIZE', 2 * 1048576);
29 * Créer une boucle sur un itérateur DATA
31 * Annonce au compilateur les "champs" disponibles, c'est à dire
32 * 'cle', 'valeur' et '*' (tout nom possible).
34 * On ne peut effectivement pas connaître à la compilation la structure
35 * des données qui seront obtenues. On indique donc au compilateur que
36 * toute balise utilisée dans la boucle est possiblement un champ
40 * Description de la boucle
42 * Description de la boucle complétée des champs
44 function iterateur_DATA_dist($b) {
45 $b->iterateur
= 'DATA'; # designe la classe d'iterateur
50 '*' => 'ALL' // Champ joker *
53 $b->select
[] = '.valeur';
62 * Pour itérer sur des données quelconques (transformables en tableau)
64 class IterateurDATA
implements Iterator
{
70 protected $tableau = array();
73 * Conditions de filtrage
74 * ie criteres de selection
78 protected $filtre = array();
86 protected $cle = null;
93 protected $valeur = null;
103 * Calcul du total des elements
107 public $total = null;
115 public function __construct($command, $info = array()) {
116 $this->type
= 'DATA';
117 $this->command
= $command;
120 $this->select($command);
128 public function rewind() {
129 reset($this->tableau
);
130 list($this->cle
, $this->valeur
) = each($this->tableau
);
134 * Déclarer les critères exceptions
138 public function exception_des_criteres() {
139 return array('tableau');
143 * Récupérer depuis le cache si possible
148 protected function cache_get($cle) {
152 # utiliser memoization si dispo
153 if (!function_exists('cache_get')) {
157 return cache_get($cle);
161 * Stocker en cache si possible
165 * @param null|mixed $valeur
168 protected function cache_set($cle, $ttl, $valeur = null) {
172 if (is_null($valeur)) {
173 $valeur = $this->tableau
;
175 # utiliser memoization si dispo
176 if (!function_exists('cache_set')) {
180 return cache_set($cle,
187 # conserver le cache 1h de plus que la validite demandee,
188 # pour le cas ou le serveur distant ne reponde plus
192 * Aller chercher les données de la boucle DATA
195 * @param array $command
198 protected function select($command) {
200 // l'iterateur DATA peut etre appele en passant (data:type)
201 // le type se retrouve dans la commande 'from'
202 // dans ce cas la le critere {source}, si present, n'a pas besoin du 1er argument
203 if (isset($this->command
['from'][0])) {
204 if (isset($this->command
['source']) and is_array($this->command
['source'])) {
205 array_unshift($this->command
['source'], $this->command
['sourcemode']);
207 $this->command
['sourcemode'] = $this->command
['from'][0];
210 // cherchons differents moyens de creer le tableau de donnees
211 // les commandes connues pour l'iterateur DATA
212 // sont : {tableau #ARRAY} ; {cle=...} ; {valeur=...}
214 // {source format, [URL], [arg2]...}
215 if (isset($this->command
['source'])
216 and isset($this->command
['sourcemode'])
218 $this->select_source();
221 // Critere {liste X1, X2, X3}
222 if (isset($this->command
['liste'])) {
223 $this->select_liste();
225 if (isset($this->command
['enum'])) {
226 $this->select_enum();
229 // Si a ce stade on n'a pas de table, il y a un bug
230 if (!is_array($this->tableau
)) {
232 spip_log("erreur datasource " . var_export($command, true));
235 // {datapath query.results}
236 // extraire le chemin "query.results" du tableau de donnees
238 and isset($this->command
['datapath'])
239 and is_array($this->command
['datapath'])
241 $this->select_datapath();
245 if ($this->command
['orderby']) {
246 $this->select_orderby();
249 // grouper les resultats {fusion /x/y/z} ;
250 if ($this->command
['groupby']) {
251 $this->select_groupby();
255 #var_dump($this->tableau);
260 * Aller chercher les donnees de la boucle DATA
262 * {source format, [URL], [arg2]...}
264 protected function select_source() {
265 # un peu crado : avant de charger le cache il faut charger
266 # les class indispensables, sinon PHP ne saura pas gerer
267 # l'objet en cache ; cf plugins/icalendar
268 # perf : pas de fonction table_to_array ! (table est deja un array)
269 if (isset($this->command
['sourcemode'])
270 and !in_array($this->command
['sourcemode'], array('table', 'array', 'tableau'))
272 charger_fonction($this->command
['sourcemode'] . '_to_array', 'inc', true);
275 # le premier argument peut etre un array, une URL etc.
276 $src = $this->command
['source'][0];
278 # avons-nous un cache dispo ?
280 if (is_string($src)) {
281 $cle = 'datasource_' . md5($this->command
['sourcemode'] . ':' . var_export($this->command
['source'], true));
284 $cache = $this->cache_get($cle);
285 if (isset($this->command
['datacache'])) {
286 $ttl = intval($this->command
['datacache']);
289 and ($cache['time'] +
(isset($ttl) ?
$ttl : $cache['ttl'])
291 and !(_request('var_mode') === 'recalcul'
292 and include_spip('inc/autoriser')
293 and autoriser('recalcul')
296 $this->tableau
= $cache['data'];
299 # dommage que ca ne soit pas une option de yql_to_array...
300 if ($this->command
['sourcemode'] == 'yql') {
306 if (isset($this->command
['sourcemode'])
307 and in_array($this->command
['sourcemode'],
308 array('table', 'array', 'tableau'))
310 if (is_array($a = $src)
312 and $a = str_replace('"', '"', $a) # fragile!
313 and is_array($a = @unserialize
($a)))
318 if (tester_url_absolue($src)) {
319 include_spip('inc/distant');
320 $u = recuperer_page($src, false, false, _DATA_SOURCE_MAX_SIZE
);
322 throw new Exception("404");
334 if (@is_readable
($src) && @is_file
($src)) {
335 $u = spip_file_get_contents($src);
348 and $g = charger_fonction($this->command
['sourcemode'] . '_to_array', 'inc', true)
350 $args = $this->command
['source'];
352 if (is_array($a = call_user_func_array($g, $args))) {
358 if (!is_array($this->tableau
)) {
362 if (!$this->err
and isset($ttl) and $ttl > 0) {
363 $this->cache_set($cle, $ttl);
366 } catch (Exception
$e) {
367 $e = $e->getMessage();
368 $err = sprintf("[%s, %s] $e",
370 $this->command
['sourcemode']);
371 erreur_squelette(array($err, array()));
376 # en cas d'erreur, utiliser le cache si encore dispo
380 $this->tableau
= $cache['data'];
387 * Retourne un tableau donne depuis un critère liste
389 * Critère `{liste X1, X2, X3}`
391 * @see critere_DATA_liste_dist()
394 protected function select_liste() {
395 # s'il n'y a qu'une valeur dans la liste, sans doute une #BALISE
396 if (!isset($this->command
['liste'][1])) {
397 if (!is_array($this->command
['liste'][0])) {
398 $this->command
['liste'] = explode(',', $this->command
['liste'][0]);
400 $this->command
['liste'] = $this->command
['liste'][0];
403 $this->tableau
= $this->command
['liste'];
407 * Retourne un tableau donne depuis un critere liste
408 * Critere {enum Xmin, Xmax}
411 protected function select_enum() {
412 # s'il n'y a qu'une valeur dans la liste, sans doute une #BALISE
413 if (!isset($this->command
['enum'][1])) {
414 if (!is_array($this->command
['enum'][0])) {
415 $this->command
['enum'] = explode(',', $this->command
['enum'][0]);
417 $this->command
['enum'] = $this->command
['enum'][0];
420 if (count($this->command
['enum']) >= 3) {
421 $enum = range(array_shift($this->command
['enum']), array_shift($this->command
['enum']),
422 array_shift($this->command
['enum']));
424 $enum = range(array_shift($this->command
['enum']), array_shift($this->command
['enum']));
426 $this->tableau
= $enum;
431 * extraire le chemin "query.results" du tableau de donnees
432 * {datapath query.results}
435 protected function select_datapath() {
436 list(, $base) = each($this->command
['datapath']);
437 if (strlen($base = ltrim(trim($base), "/"))) {
438 $this->tableau
= table_valeur($this->tableau
, $base);
439 if (!is_array($this->tableau
)) {
440 $this->tableau
= array();
442 spip_log("datapath '$base' absent");
448 * Ordonner les resultats
452 protected function select_orderby() {
455 foreach ($this->command
['orderby'] as $tri) {
456 // virer le / initial pour les criteres de la forme {par /xx}
457 if (preg_match(',^\.?([/\w]+)( DESC)?$,iS', ltrim($tri, '/'), $r)) {
458 $r = array_pad($r, 3, null);
461 if ($r[1] == 'cle') {
462 if (isset($r[2]) and $r[2]) {
463 krsort($this->tableau
);
465 ksort($this->tableau
);
469 if ($r[1] == 'alea') {
470 $k = array_keys($this->tableau
);
473 foreach ($k as $cle) {
474 $v[$cle] = $this->tableau
[$cle];
479 if ($r[1] == 'valeur') {
481 } # {par valeur/xx/yy} ??
483 $tv = 'table_valeur(%s, ' . var_export($r[1], true) . ')';
486 $a = ' . sprintf($tv, '$aa') . ';
487 $b = ' . sprintf($tv, '$bb') . ';
489 return ($a ' . ((isset($r[2]) and $r[2]) ?
'>' : '<') . ' $b) ? -1 : 1;';
496 uasort($this->tableau
, create_function('$aa,$bb',
505 * Grouper les resultats
509 protected function select_groupby() {
510 // virer le / initial pour les criteres de la forme {fusion /xx}
511 if (strlen($fusion = ltrim($this->command
['groupby'][0], '/'))) {
513 foreach ($this->tableau
as $k => $v) {
514 $val = table_valeur($v, $fusion);
515 if (isset($vu[$val])) {
516 unset($this->tableau
[$k]);
526 * L'iterateur est-il encore valide ?
530 public function valid() {
531 return !is_null($this->cle
);
535 * Retourner la valeur
539 public function current() {
540 return $this->valeur
;
548 public function key() {
553 * Passer a la valeur suivante
557 public function next() {
558 if ($this->valid()) {
559 list($this->cle
, $this->valeur
) = each($this->tableau
);
564 * Compter le nombre total de resultats
568 public function count() {
569 if (is_null($this->total
)) {
570 $this->total
= count($this->tableau
);
578 * Fonctions de transformation donnee => tableau
587 function inc_file_to_array_dist($u) {
588 return preg_split('/\r?\n/', $u);
596 function inc_plugins_to_array_dist() {
597 include_spip('inc/plugin');
599 return liste_chemin_plugin_actifs();
608 function inc_xml_to_array_dist($u) {
609 return @XMLObjectToArray
(new SimpleXmlIterator($u));
616 * @param object $object The object to convert
620 function inc_object_to_array($object) {
621 if (!is_object($object) && !is_array($object)) {
624 if (is_object($object)) {
625 $object = get_object_vars($object);
628 return array_map('inc_object_to_array', $object);
638 function inc_yql_to_array_dist($u) {
639 define('_YQL_ENDPOINT', 'http://query.yahooapis.com/v1/public/yql?&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&q=');
640 $v = recuperer_url($url = _YQL_ENDPOINT
. urlencode($u) . '&format=json');
642 or !$w = json_decode($v['page'], true)
644 throw new Exception('YQL: réponse vide ou mal formée');
646 if (isset($w['error'])) {
647 throw new Exception($w['error']['description']);
650 return inc_object_to_array($w);
659 function inc_sql_to_array_dist($u) {
660 # sortir le connecteur de $u
661 preg_match(',^(?:(\w+):)?(.*)$,S', $u, $v);
662 $serveur = (string)$v[1];
664 if ($s = sql_query($req, $serveur)) {
666 while ($t = sql_fetch($s)) {
682 function inc_json_to_array_dist($u) {
683 if (is_array($json = json_decode($u))
696 function inc_csv_to_array_dist($u) {
697 include_spip('inc/csv');
698 list($entete, $csv) = analyse_csv($u);
699 array_unshift($csv, $entete);
701 include_spip('inc/charsets');
703 foreach ($entete as $k => $v) {
704 if (trim($v) == "") {
706 } // reperer des eventuelles cases vides
707 if (is_numeric($v) and $v < 0) {
709 } // ne pas risquer d'ecraser une cle numerique
710 if (is_numeric($v)) {
712 } // ne pas risquer d'ecraser une cle numerique
713 $v = strtolower(preg_replace(',\W+,', '_', translitteration($v)));
714 foreach ($csv as &$item) {
715 $item[$v] = &$item[$k];
729 function inc_rss_to_array_dist($u) {
730 include_spip('inc/syndic');
731 if (is_array($rss = analyser_backend($u))) {
739 * atom, alias de rss -> tableau
744 function inc_atom_to_array_dist($u) {
745 $g = charger_fonction('rss_to_array', 'inc');
752 * lister des fichiers selon un masque, pour la syntaxe cf php.net/glob
757 function inc_glob_to_array_dist($u) {
759 GLOB_MARK | GLOB_NOSORT | GLOB_BRACE
762 return $a ?
$a : array();
772 function inc_yaml_to_array_dist($u) {
773 include_spip('inc/yaml-mini');
774 if (!function_exists("yaml_decode")) {
775 throw new Exception('YAML: impossible de trouver la fonction yaml_decode');
780 return yaml_decode($u);
785 * pregfiles -> tableau
786 * lister des fichiers a partir d'un dossier de base et selon une regexp.
787 * pour la syntaxe cf la fonction spip preg_files
790 * @param string $regexp
794 function inc_pregfiles_to_array_dist($dir, $regexp = -1, $limit = 10000) {
795 return (array)preg_files($dir, $regexp, $limit);
800 * ls : lister des fichiers selon un masque glob
801 * et renvoyer aussi leurs donnees php.net/stat
806 function inc_ls_to_array_dist($u) {
807 $glob = charger_fonction('glob_to_array', 'inc');
809 foreach ($a as &$v) {
810 $b = (array)@stat
($v);
811 foreach ($b as $k => $ignore) {
812 if (is_numeric($k)) {
816 $b['file'] = basename($v);
829 * @param Object $object
832 function XMLObjectToArray($object) {
833 $xml_array = array();
834 for ($object->rewind(); $object->valid(); $object->next()) {
835 if (array_key_exists($key = $object->key(), $xml_array)) {
836 $key .= '-' . uniqid();
838 $vars = get_object_vars($object->current());
839 if (isset($vars['@attributes'])) {
840 foreach ($vars['@attributes'] as $k => $v) {
841 $xml_array[$key][$k] = $v;
844 if ($object->hasChildren()) {
845 $xml_array[$key][] = XMLObjectToArray(
848 $xml_array[$key][] = strval($object->current());