3 /***************************************************************************\
4 * SPIP, Systeme de publication pour l'internet *
6 * Copyright (c) 2001-2012 *
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 \***************************************************************************/
13 if (!defined('_ECRIRE_INC_VERSION')) return;
18 * creer une boucle sur un iterateur DATA
19 * annonce au compilo les "champs" disponibles
24 function iterateur_DATA_dist($b) {
25 $b->iterateur
= 'DATA'; # designe la classe d'iterateur
30 '*' => 'ALL' // Champ joker *
33 $b->select
[] = '.valeur';
39 * IterateurDATA pour iterer sur des donnees
41 class IterateurDATA
implements Iterator
{
46 protected $tableau = array();
49 * Conditions de filtrage
50 * ie criteres de selection
53 protected $filtre = array();
60 protected $cle = null;
66 protected $valeur = null;
76 * Calcul du total des elements
88 public function __construct($command, $info=array()) {
90 $this->command
= $command;
93 $this->select($command);
100 public function rewind() {
101 reset($this->tableau
);
102 list($this->cle
, $this->valeur
) = each($this->tableau
);
106 * Declarer les criteres exceptions
109 public function exception_des_criteres() {
110 return array('tableau');
114 * Recuperer depuis le cache si possible
118 protected function cache_get($cle) {
120 # utiliser memoization si dispo
121 include_spip('inc/memoization');
122 if (!function_exists('cache_get')) return;
123 return cache_get($cle);
127 * Srtocker en cache si possible
132 protected function cache_set($cle, $ttl, $valeur = null) {
134 if (is_null($valeur)) {
135 $valeur = $this->tableau
;
137 # utiliser memoization si dispo
138 include_spip('inc/memoization');
139 if (!function_exists('cache_set')) return;
140 return cache_set($cle,
147 # conserver le cache 1h deplus que la validite demandee,
148 # pour le cas ou le serveur distant ne repond plus
152 * Aller chercher les donnees de la boucle DATA
158 protected function select($command) {
160 // l'iterateur DATA peut etre appele en passant (data:type)
161 // le type se retrouve dans la commande 'from'
162 // dans ce cas la le critere {source}, si present, n'a pas besoin du 1er argument
163 if (isset($this->command
['from'][0])) {
164 if (isset($this->command
['source']) and is_array($this->command
['source'])) {
165 array_unshift($this->command
['source'], $this->command
['sourcemode']);
167 $this->command
['sourcemode'] = $this->command
['from'][0];
170 // cherchons defferents moyens de creer le tableau de donnees
171 // les commandes connues pour l'iterateur DATA
172 // sont : {tableau #ARRAY} ; {cle=...} ; {valeur=...}
174 // {source format, [URL], [arg2]...}
175 if (isset($this->command
['source'])
176 AND isset($this->command
['sourcemode'])) {
177 $this->select_source();
180 // Critere {liste X1, X2, X3}
181 if (isset($this->command
['liste'])) {
182 $this->select_liste();
184 if (isset($this->command
['enum'])) {
185 $this->select_enum();
188 // Si a ce stade on n'a pas de table, il y a un bug
189 if (!is_array($this->tableau
)) {
191 spip_log("erreur datasource ".var_export($command,true));
194 // {datapath query.results}
195 // extraire le chemin "query.results" du tableau de donnees
197 AND isset($this->command
['datapath'])
198 AND is_array($this->command
['datapath'])) {
199 $this->select_datapath();
203 if ($this->command
['orderby']) {
204 $this->select_orderby();
207 // grouper les resultats {fusion /x/y/z} ;
208 if ($this->command
['groupby']) {
209 $this->select_groupby();
213 #var_dump($this->tableau);
218 * Aller chercher les donnees de la boucle DATA
220 * {source format, [URL], [arg2]...}
222 protected function select_source() {
223 # un peu crado : avant de charger le cache il faut charger
224 # les class indispensables, sinon PHP ne saura pas gerer
225 # l'objet en cache ; cf plugins/icalendar
226 # perf : pas de fonction table_to_array ! (table est deja un array)
227 if (isset($this->command
['sourcemode'])
228 AND !in_array($this->command
['sourcemode'],array('table', 'array', 'tableau')))
229 charger_fonction($this->command
['sourcemode'] . '_to_array', 'inc', true);
231 # le premier argument peut etre un array, une URL etc.
232 $src = $this->command
['source'][0];
234 # avons-nous un cache dispo ?
237 $cle = 'datasource_'.md5($this->command
['sourcemode'].':'.var_export($this->command
['source'],true));
239 $cache = $this->cache_get($cle);
240 if (isset($this->command
['datacache']))
241 $ttl = intval($this->command
['datacache']);
243 AND ($cache['time'] +
(isset($ttl) ?
$ttl : $cache['ttl'])
245 AND !(_request('var_mode') === 'recalcul'
246 AND include_spip('inc/autoriser')
247 AND autoriser('recalcul')
249 $this->tableau
= $cache['data'];
252 # dommage que ca ne soit pas une option de yql_to_array...
253 if ($this->command
['sourcemode'] == 'yql')
254 if (!isset($ttl)) $ttl = 3600;
256 if (isset($this->command
['sourcemode'])
257 AND in_array($this->command
['sourcemode'],
258 array('table', 'array', 'tableau'))
260 if (is_array($a = $src)
262 AND $a = str_replace('"', '"', $a) # fragile!
263 AND is_array($a = @unserialize
($a)))
268 if (preg_match(',^https?://,', $src)) {
269 include_spip('inc/distant');
270 $u = recuperer_page($src);
272 throw new Exception("404");
273 if (!isset($ttl)) $ttl = 24*3600;
274 } else if (@is_dir
($src)) {
276 if (!isset($ttl)) $ttl = 10;
277 } else if (@is_readable
($src) && @is_file
($src)) {
278 $u = spip_file_get_contents($src);
279 if (!isset($ttl)) $ttl = 10;
282 if (!isset($ttl)) $ttl = 10;
285 AND $g = charger_fonction($this->command
['sourcemode'] . '_to_array', 'inc', true)) {
286 $args = $this->command
['source'];
288 if (is_array($a = call_user_func_array($g,$args))) {
294 if (!is_array($this->tableau
))
297 if (!$this->err
AND isset($ttl) and $ttl>0)
298 $this->cache_set($cle, $ttl);
301 catch (Exception
$e) {
302 $e = $e->getMessage();
303 $err = sprintf("[%s, %s] $e",
305 $this->command
['sourcemode']);
306 erreur_squelette(array($err, array()));
310 # en cas d'erreur, utiliser le cache si encore dispo
313 $this->tableau
= $cache['data'];
320 * Retourne un tableau donne depuis un critere liste
321 * Critere {liste X1, X2, X3}
324 protected function select_liste() {
325 # s'il n'y a qu'une valeur dans la liste, sans doute une #BALISE
326 if (!isset($this->command
['liste'][1])) {
327 if (!is_array($this->command
['liste'][0])) {
328 $this->command
['liste'] = explode(',', $this->command
['liste'][0]);
330 $this->command
['liste'] = $this->command
['liste'][0];
333 $this->tableau
= $this->command
['liste'];
337 * Retourne un tableau donne depuis un critere liste
338 * Critere {enum Xmin, Xmax}
341 protected function select_enum() {
342 # s'il n'y a qu'une valeur dans la liste, sans doute une #BALISE
343 if (!isset($this->command
['enum'][1])) {
344 if (!is_array($this->command
['enum'][0])) {
345 $this->command
['enum'] = explode(',', $this->command
['enum'][0]);
347 $this->command
['enum'] = $this->command
['enum'][0];
350 if (count($this->command
['enum'])>=3)
351 $enum = range(array_shift($this->command
['enum']),array_shift($this->command
['enum']),array_shift($this->command
['enum']));
353 $enum = range(array_shift($this->command
['enum']),array_shift($this->command
['enum']));
354 $this->tableau
= $enum;
359 * extraire le chemin "query.results" du tableau de donnees
360 * {datapath query.results}
363 protected function select_datapath() {
364 list(,$base) = each($this->command
['datapath']);
365 if (strlen($base = ltrim(trim($base),"/"))) {
366 $this->tableau
= table_valeur($this->tableau
, $base);
367 if (!is_array($this->tableau
)) {
368 $this->tableau
= array();
370 spip_log("datapath '$base' absent");
376 * Ordonner les resultats
380 protected function select_orderby() {
383 foreach($this->command
['orderby'] as $tri) {
384 // virer le / initial pour les criteres de la forme {par /xx}
385 if (preg_match(',^\.?([/\w]+)( DESC)?$,iS', ltrim($tri, '/'), $r)) {
388 if (isset($r2) and $r[2])
389 krsort($this->tableau
);
391 ksort($this->tableau
);
394 else if ($r[1] == 'alea') {
395 $k = array_keys($this->tableau
);
399 $v[$cle] = $this->tableau
[$cle];
404 if ($r[1] == 'valeur')
406 # {par valeur/xx/yy} ??
408 $tv = 'table_valeur(%s, '.var_export($r[1],true).')';
410 $a = '.sprintf($tv,'$aa').';
411 $b = '.sprintf($tv,'$bb').';
413 return ($a ' . ($r[2] ?
'>' : '<').' $b) ? -1 : 1;';
419 uasort($this->tableau
, create_function('$aa,$bb',
428 * Grouper les resurltats
432 protected function select_groupby() {
433 // virer le / initial pour les criteres de la forme {fusion /xx}
434 if (strlen($fusion = ltrim($this->command
['groupby'][0], '/'))) {
436 foreach($this->tableau
as $k => $v) {
437 $val = table_valeur($v, $fusion);
438 if (isset($vu[$val]))
439 unset($this->tableau
[$k]);
448 * L'iterateur est-il encore valide ?
451 public function valid(){
452 return !is_null($this->cle
);
456 * Retourner la valeur
459 public function current() {
460 return $this->valeur
;
467 public function key() {
472 * Passer a la valeur suivante
475 public function next(){
477 list($this->cle
, $this->valeur
) = each($this->tableau
);
481 * Compter le nombre total de resultats
484 public function count() {
485 if (is_null($this->total
))
486 $this->total
= count($this->tableau
);
492 * Fonctions de transformation donnee => tableau
501 function inc_file_to_array_dist($u) {
502 return preg_split('/\r?\n/', $u);
509 function inc_plugins_to_array_dist() {
510 include_spip('inc/plugin');
511 return liste_chemin_plugin_actifs();
519 function inc_xml_to_array_dist($u) {
520 return @ObjectToArray
(new SimpleXmlIterator($u));
529 function inc_yql_to_array_dist($u) {
530 define('_YQL_ENDPOINT', 'http://query.yahooapis.com/v1/public/yql?&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&q=');
531 $v = recuperer_page($url = _YQL_ENDPOINT
.urlencode($u).'&format=json');
532 $w = json_decode($v);
534 throw new Exception('YQL: réponse vide ou mal formée');
545 function inc_sql_to_array_dist($u) {
546 # sortir le connecteur de $u
547 preg_match(',^(?:(\w+):)?(.*)$,S', $u, $v);
548 $serveur = (string) $v[1];
550 if ($s = sql_query($req, $serveur)) {
552 while ($t = sql_fetch($s))
564 function inc_json_to_array_dist($u) {
565 if (is_array($json = json_decode($u))
567 return (array) $json;
575 function inc_csv_to_array_dist($u) {
576 include_spip('inc/csv');
577 list($entete,$csv) = analyse_csv($u);
578 array_unshift($csv,$entete);
580 include_spip('inc/charsets');
581 foreach ($entete as $k => $v) {
582 $v = strtolower(preg_replace(',\W+,', '_', translitteration($v)));
583 foreach ($csv as &$item)
584 $item[$v] = &$item[$k];
594 function inc_rss_to_array_dist($u) {
595 include_spip('inc/syndic');
596 if (is_array($rss = analyser_backend($u)))
602 * atom, alias de rss -> tableau
606 function inc_atom_to_array_dist($u) {
607 $g = charger_fonction('rss_to_array', 'inc');
613 * lister des fichiers selon un masque, pour la syntaxe cf php.net/glob
617 function inc_glob_to_array_dist($u) {
618 return (array) glob($u,
619 GLOB_MARK | GLOB_NOSORT | GLOB_BRACE
624 * pregfiles -> tableau
625 * lister des fichiers a partir d'un dossier de base et selon une regexp.
626 * pour la syntaxe cf la fonction spip preg_files
628 * @param string $regexp
632 function inc_pregfiles_to_array_dist($dir, $regexp=-1, $limit=10000) {
633 return (array) preg_files($dir, $regexp, $limit);
638 * ls : lister des fichiers selon un masque glob
639 * et renvoyer aussi leurs donnees php.net/stat
643 function inc_ls_to_array_dist($u) {
644 $glob = charger_fonction('glob_to_array', 'inc');
646 foreach ($a as &$v) {
647 $b = (array) @stat
($v);
648 foreach ($b as $k => $ignore)
649 if (is_numeric($k)) unset($b[$k]);
650 $b['file'] = basename($v);
661 * @param Object $object
664 function ObjectToArray($object){
665 $xml_array = array();
666 for( $object->rewind(); $object->valid(); $object->next() ) {
667 if(array_key_exists($key = $object->key(), $xml_array)){
668 $key .= '-'.uniqid();
670 $vars = get_object_vars($object->current());
671 if (isset($vars['@attributes']))
672 foreach($vars['@attributes'] as $k => $v)
673 $xml_array[$key][$k] = $v;
674 if($object->hasChildren()){
675 $xml_array[$key][] = ObjectToArray(
679 $xml_array[$key][] = strval($object->current());