9e4fc5ccdcc4329d37e3edc9c2e4a38cd045d4f6
[ptitvelo/web/www.git] / www / plugins-dist / sites / inc / syndic.php
1 <?php
2
3 /***************************************************************************\
4 * SPIP, Systeme de publication pour l'internet *
5 * *
6 * Copyright (c) 2001-2013 *
7 * Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James *
8 * *
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 \***************************************************************************/
12
13 if (!defined("_ECRIRE_INC_VERSION")) return;
14
15 // ATTENTION
16 // Cette inclusion charge executer_une_syndication pour compatibilite,
17 // mais cette fonction ne doit plus etre invoquee directement:
18 // il faut passer par cron() pour avoir un verrou portable
19 // Voir un exemple dans action/editer/site
20 include_spip('genie/syndic');
21
22 // prend un fichier backend et retourne un tableau des items lus,
23 // et une chaine en cas d'erreur
24 // http://doc.spip.org/@analyser_backend
25 function analyser_backend($rss, $url_syndic='') {
26 include_spip('inc/texte'); # pour couper()
27
28 $rss = pipeline('pre_syndication', $rss);
29
30 // si true, les URLs de type feedburner sont dereferencees
31 define('_SYNDICATION_DEREFERENCER_URL', false);
32
33 // Echapper les CDATA
34 cdata_echappe($rss, $echappe_cdata);
35
36 // supprimer les commentaires
37 $rss = preg_replace(',<!--.*-->,Ums', '', $rss);
38
39 // simplifier le backend, en supprimant les espaces de nommage type "dc:"
40 $rss = preg_replace(',<(/?)(dc):,i', '<\1', $rss);
41
42 // chercher auteur/lang dans le fil au cas ou les items n'en auraient pas
43 list($header) = preg_split(',<(item|entry)\b,', $rss, 2);
44 if (preg_match_all(
45 ',<(author|creator)\b(.*)</\1>,Uims',
46 $header, $regs, PREG_SET_ORDER)) {
47 $les_auteurs_du_site = array();
48 foreach ($regs as $reg) {
49 $nom = $reg[2];
50 if (preg_match(',<name>(.*)</name>,Uims', $nom, $reg))
51 $nom = $reg[1];
52 $les_auteurs_du_site[] = trim(textebrut(filtrer_entites($nom)));
53 }
54 $les_auteurs_du_site = join(', ', array_unique($les_auteurs_du_site));
55 } else
56 $les_auteurs_du_site = '';
57 if ((preg_match(',<([^>]*xml:)?lang(uage)?'.'>([^<>]+)<,i',
58 $header, $match) AND $l = $match[3])
59 OR ($l = extraire_attribut(extraire_balise($header, 'feed'), 'xml:lang'))
60 )
61 $langue_du_site = $l;
62 // atom
63 elseif (preg_match(',<feed\s[^>]*xml:lang=[\'"]([^<>\'"]+)[\'"],i', $header, $match))
64 $langue_du_site = $match[1];
65
66 // Recuperer les blocs item et entry
67 $items = array_merge(extraire_balises($rss, 'item'), extraire_balises($rss, 'entry'));
68
69
70 //
71 // Analyser chaque <item>...</item> du backend et le transformer en tableau
72 //
73
74 if (!count($items)) return _T('sites:avis_echec_syndication_01');
75
76 foreach ($items as $item) {
77 $data = array();
78
79 // URL (semi-obligatoire, sert de cle)
80
81 // guid n'est un URL que si marque de <guid ispermalink="true"> ;
82 // attention la valeur par defaut est 'true' ce qui oblige a quelque
83 // gymnastique
84 if (preg_match(',<guid.*>[[:space:]]*(https?:[^<]*)</guid>,Uims',
85 $item, $regs) AND preg_match(',^(true|1)?$,i',
86 extraire_attribut($regs[0], 'ispermalink')))
87 $data['url'] = $regs[1];
88 // contourner les redirections feedburner
89 else if (_SYNDICATION_DEREFERENCER_URL
90 AND preg_match(',<feedburner:origLink>(.*)<,Uims',
91 $item, $regs))
92 $data['url'] = $regs[1];
93 // <link>, plus classique
94 else if (preg_match(
95 ',<link[^>]*[[:space:]]rel=["\']?alternate[^>]*>(.*)</link>,Uims',
96 $item, $regs))
97 $data['url'] = $regs[1];
98 else if (preg_match(',<link[^>]*[[:space:]]rel=.alternate[^>]*>,Uims',
99 $item, $regs))
100 $data['url'] = extraire_attribut($regs[0], 'href');
101 else if (preg_match(',<link[^>]*>(.*)</link>,Uims', $item, $regs))
102 $data['url'] = $regs[1];
103 else if (preg_match(',<link[^>]*>,Uims', $item, $regs))
104 $data['url'] = extraire_attribut($regs[0], 'href');
105
106 // Aucun link ni guid, mais une enclosure
107 else if (preg_match(',<enclosure[^>]*>,ims', $item, $regs)
108 AND $url = extraire_attribut($regs[0], 'url'))
109 $data['url'] = $url;
110
111 // pas d'url, c'est genre un compteur...
112 else
113 $data['url'] = '';
114
115 // Titre (semi-obligatoire)
116 if (preg_match(",<title[^>]*>(.*?)</title>,ims",$item,$match))
117 $data['titre'] = $match[1];
118 else if (preg_match(',<link[[:space:]][^>]*>,Uims',$item,$mat)
119 AND $title = extraire_attribut($mat[0], 'title'))
120 $data['titre'] = $title;
121 if (!strlen($data['titre'] = trim($data['titre'])))
122 $data['titre'] = _T('ecrire:info_sans_titre');
123
124 // Date
125 $la_date = '';
126 if (preg_match(',<(published|modified|issued)>([^<]*)<,Uims',
127 $item,$match)) {
128 cdata_echappe_retour($match[2], $echappe_cdata);
129 $la_date = my_strtotime($match[2]);
130 }
131 if (!$la_date AND
132 preg_match(',<(pubdate)>([^<]*)<,Uims',$item, $match)) {
133 cdata_echappe_retour($match[2], $echappe_cdata);
134 $la_date = my_strtotime($match[2]);
135 }
136 if (!$la_date AND
137 preg_match(',<([a-z]+:date)>([^<]*)<,Uims',$item,$match)) {
138 cdata_echappe_retour($match[2], $echappe_cdata);
139 $la_date = my_strtotime($match[2], $echappe_cdata);
140 }
141 if (!$la_date AND
142 preg_match(',<date>([^<]*)<,Uims',$item,$match)) {
143 cdata_echappe_retour($match[1], $echappe_cdata);
144 $la_date = my_strtotime($match[1]);
145 }
146
147 // controle de validite de la date
148 // pour eviter qu'un backend errone passe toujours devant
149 // (note: ca pourrait etre defini site par site, mais ca risque d'etre
150 // plus lourd que vraiment utile)
151 if ($GLOBALS['controler_dates_rss']) {
152 if ($la_date > time() + 48 * 3600)
153 $la_date = time();
154 }
155
156 if ($la_date)
157 $data['date'] = $la_date;
158
159 // Honorer le <lastbuilddate> en forcant la date
160 if (preg_match(',<(lastbuilddate|updated|modified)>([^<>]+)</\1>,i',
161 $item, $regs)
162 AND $lastbuilddate = my_strtotime(trim($regs[2]))
163 // pas dans le futur
164 AND $lastbuilddate < time())
165 $data['lastbuilddate'] = $lastbuilddate;
166
167 // Auteur(s)
168 if (preg_match_all(
169 ',<(author|creator)\b[^>]*>(.*)</\1>,Uims',
170 $item, $regs, PREG_SET_ORDER)) {
171 $auteurs = array();
172 foreach ($regs as $reg) {
173 $nom = $reg[2];
174 if (preg_match(',<name\b[^>]*>(.*)</name>,Uims', $nom, $reg))
175 $nom = $reg[1];
176 // Cas particulier d'un auteur Flickr
177 if (preg_match(',nobody@flickr.com \((.*)\),Uims', $nom, $reg))
178 $nom = $reg[1];
179 $auteurs[] = trim(textebrut(filtrer_entites($nom)));
180 }
181 $data['lesauteurs'] = join(', ', array_unique($auteurs));
182 }
183 else
184 $data['lesauteurs'] = $les_auteurs_du_site;
185
186 // Description
187 if (preg_match(',<(description|summary)\b.*'
188 .'>(.*)</\1\b,Uims',$item,$match)) {
189 $data['descriptif'] = trim($match[2]);
190 }
191 if (preg_match(',<(content)\b.*'
192 .'>(.*)</\1\b,Uims',$item,$match)) {
193 $data['content'] = trim($match[2]);
194 }
195
196 // lang
197 if (preg_match(',<([^>]*xml:)?lang(uage)?'.'>([^<>]+)<,i',
198 $item, $match))
199 $data['lang'] = trim($match[3]);
200 else if ($lang = trim(extraire_attribut($item, 'xml:lang')))
201 $data['lang'] = $lang;
202 else
203 $data['lang'] = trim($langue_du_site);
204
205 // source et url_source (pas trouve d'exemple en ligne !!)
206 # <source url="http://www.truc.net/music/uatsap.mp3" length="19917" />
207 # <source url="http://www.truc.net/rss">Site source</source>
208 if (preg_match(',(<source[^>]*>)(([^<>]+)</source>)?,i',
209 $item, $match)) {
210 $data['source'] = trim($match[3]);
211 $data['url_source'] = str_replace('&amp;', '&',
212 trim(extraire_attribut($match[1], 'url')));
213 }
214
215 // tags
216 # a partir de "<dc:subject>", (del.icio.us)
217 # ou <media:category> (flickr)
218 # ou <itunes:category> (apple)
219 # on cree nos tags microformat <a rel="directory" href="url">titre</a>
220 # http://microformats.org/wiki/rel-directory-fr
221 $tags = array();
222 if (preg_match_all(
223 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*>'
224 .'(.*?)</\1>,ims',
225 $item, $matches, PREG_SET_ORDER))
226 $tags = ajouter_tags($matches, $item); # array()
227 elseif (preg_match_all(
228 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*/>'
229 .',ims',
230 $item, $matches, PREG_SET_ORDER))
231 $tags = ajouter_tags($matches, $item); # array()
232 // Pieces jointes :
233 // chercher <enclosure> au format RSS et les passer en microformat
234 // ou des microformats relEnclosure,
235 // ou encore les media:content
236 if (!afficher_enclosures(join(', ', $tags))) {
237 // on prend toutes les pièces jointes possibles, et on essaie de les rendre uniques.
238 $enclosures = array();
239 # rss 2
240 if (preg_match_all(',<enclosure[[:space:]][^<>]+>,i',
241 $item, $matches, PREG_PATTERN_ORDER)) {
242 $enclosures += array_map('enclosure2microformat', $matches[0]);
243 }
244 # atom
245 if (preg_match_all(',<link\b[^<>]+rel=["\']?enclosure["\']?[^<>]+>,i',
246 $item, $matches, PREG_PATTERN_ORDER)) {
247 $enclosures += array_map('enclosure2microformat', $matches[0]);
248 }
249 # media rss
250 if (preg_match_all(',<media:content\b[^<>]+>,i',
251 $item, $matches, PREG_PATTERN_ORDER)) {
252 $enclosures += array_map('enclosure2microformat', $matches[0]);
253 }
254 $data['enclosures'] = join(', ', array_unique($enclosures));
255 unset($enclosures);
256 }
257 $data['item'] = $item;
258
259 // Nettoyer les donnees et remettre les CDATA en place
260 cdata_echappe_retour($data, $echappe_cdata);
261 cdata_echappe_retour($tags, $echappe_cdata);
262
263 // passer l'url en absolue
264 $data['url'] = url_absolue(filtrer_entites($data['url']), $url_syndic);
265
266 // Trouver les microformats (ecrase les <category> et <dc:subject>)
267 if (preg_match_all(
268 ',<a[[:space:]]([^>]+[[:space:]])?rel=[^>]+>.*</a>,Uims',
269 $data['item'], $regs, PREG_PATTERN_ORDER)) {
270 $tags = $regs[0];
271 }
272 // Cas particulier : tags Connotea sous la forme <a class="postedtag">
273 if (preg_match_all(
274 ',<a[[:space:]][^>]+ class="postedtag"[^>]*>.*</a>,Uims',
275 $data['item'], $regs, PREG_PATTERN_ORDER))
276 $tags = preg_replace(', class="postedtag",i',
277 ' rel="tag"', $regs[0]);
278
279 $data['tags'] = $tags;
280 // enlever le html des titre pour etre homogene avec les autres objets spip
281 $data['titre'] = textebrut($data['titre']);
282
283 $articles[] = $data;
284 }
285
286 return $articles;
287 }
288
289
290 // helas strtotime ne reconnait pas le format W3C
291 // http://www.w3.org/TR/NOTE-datetime
292 // http://doc.spip.org/@my_strtotime
293 function my_strtotime($la_date) {
294
295 // format complet
296 if (preg_match(
297 ',^(\d+-\d+-\d+[T ]\d+:\d+(:\d+)?)(\.\d+)?'
298 .'(Z|([-+]\d{2}):\d+)?$,',
299 $la_date, $match)) {
300 $la_date = str_replace("T", " ", $match[1])." GMT";
301 return strtotime($la_date) - intval($match[5]) * 3600;
302 }
303
304 // YYYY
305 if (preg_match(',^\d{4}$,', $la_date, $match))
306 return strtotime($match[0]."-01-01");
307
308 // YYYY-MM
309 if (preg_match(',^\d{4}-\d{2}$,', $la_date, $match))
310 return strtotime($match[0]."-01");
311
312 // utiliser strtotime en dernier ressort
313 $s = strtotime($la_date);
314 if ($s > 0)
315 return $s;
316
317 // YYYY-MM-DD hh:mm:ss
318 if (preg_match(',^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\b,', $la_date, $match))
319 return strtotime($match[0]);
320
321
322 // erreur
323 spip_log("Impossible de lire le format de date '$la_date'");
324 return false;
325 }
326 // A partir d'un <dc:subject> ou autre essayer de recuperer
327 // le mot et son url ; on cree <a href="url" rel="tag">mot</a>
328 // http://doc.spip.org/@creer_tag
329 function creer_tag($mot,$type,$url) {
330 if (!strlen($mot = trim($mot))) return '';
331 $mot = "<a rel=\"tag\">$mot</a>";
332 if ($url)
333 $mot = inserer_attribut($mot, 'href', $url);
334 if ($type)
335 $mot = inserer_attribut($mot, 'rel', $type);
336 return $mot;
337 }
338
339
340 // http://doc.spip.org/@ajouter_tags
341 function ajouter_tags($matches, $item) {
342 include_spip('inc/filtres');
343 $tags = array();
344 foreach ($matches as $match) {
345 $type = ($match[3] == 'category' OR $match[3] == 'directory')
346 ? 'directory':'tag';
347 $mot = supprimer_tags($match[0]);
348 if (!strlen($mot)
349 AND !strlen($mot = extraire_attribut($match[0], 'label')))
350 break;
351 // rechercher un url
352 if ($url = extraire_attribut($match[0], 'domain')) {
353 // category@domain est la racine d'une url qui se prolonge
354 // avec le contenu text du tag <category> ; mais dans SPIP < 2.0
355 // on donnait category@domain = #URL_RUBRIQUE, et
356 // text = #TITRE_RUBRIQUE ; d'ou l'heuristique suivante sur le slash
357 if (substr($url, -1) == '/')
358 $url .= rawurlencode($mot);
359 }
360 else if ($url = extraire_attribut($match[0], 'resource')
361 OR $url = extraire_attribut($match[0], 'url')
362 )
363 {}
364
365 ## cas particuliers
366 else if (extraire_attribut($match[0], 'scheme') == 'urn:flickr:tags') {
367 foreach(explode(' ', $mot) as $petit)
368 if ($t = creer_tag($petit, $type,
369 'http://www.flickr.com/photos/tags/'.rawurlencode($petit).'/'))
370 $tags[] = $t;
371 $mot = '';
372 }
373 else if (
374 // cas atom1, a faire apres flickr
375 $term = extraire_attribut($match[0], 'term')
376 ) {
377 if ($scheme = extraire_attribut($match[0], 'scheme'))
378 $url = suivre_lien($scheme,$term);
379 else
380 $url = $term;
381 }
382 else {
383 # type delicious.com
384 foreach(explode(' ', $mot) as $petit)
385 if (preg_match(',<rdf\b[^>]*\bresource=["\']([^>]*/'
386 .preg_quote(rawurlencode($petit),',').')["\'],i',
387 $item, $m)) {
388 $mot = '';
389 if ($t = creer_tag($petit, $type, $m[1]))
390 $tags[] = $t;
391 }
392 }
393
394 if ($t = creer_tag($mot, $type, $url))
395 $tags[] = $t;
396 }
397 return $tags;
398 }
399
400
401 // Lit contenu des blocs [[CDATA]] dans un flux
402 // http://doc.spip.org/@cdata_echappe_retour
403 function cdata_echappe(&$rss, &$echappe_cdata) {
404 $echappe_cdata = array();
405 if (preg_match_all(',<!\[CDATA\[(.*)]]>,Uims', $rss,
406 $regs, PREG_SET_ORDER)) {
407 foreach ($regs as $n => $reg) {
408 if (preg_match(',[<>],', $reg[1])) {
409 $echappe_cdata[$n] = $reg[1];
410 $rss = str_replace($reg[0], "@@@SPIP_CDATA$n@@@", $rss);
411 } else
412 $rss = str_replace($reg[0], $reg[1], $rss);
413 }
414 }
415 }
416
417 // Retablit le contenu des blocs [[CDATA]] dans une chaine ou un tableau
418 // http://doc.spip.org/@cdata_echappe_retour
419 function cdata_echappe_retour(&$x, &$echappe_cdata) {
420 if (is_string($x)) {
421 if (strpos($x, '@@@SPIP_CDATA') !== false
422 OR strpos($x, '&lt;') !== false) {
423 $x = filtrer_entites($x);
424 foreach ($echappe_cdata as $n => $e)
425 $x = str_replace("@@@SPIP_CDATA$n@@@", $e, $x);
426 }
427 }
428
429 else if (is_array($x)) {
430 foreach($x as $k => &$v)
431 cdata_echappe_retour($v, $echappe_cdata);
432 }
433 }
434 ?>