3 /***************************************************************************\
4 * SPIP, Systeme de publication pour l'internet *
6 * Copyright (c) 2001-2014 *
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;
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');
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()
28 $rss = pipeline('pre_syndication', $rss);
30 // si true, les URLs de type feedburner sont dereferencees
31 define('_SYNDICATION_DEREFERENCER_URL', false);
34 $echappe_cdata = array();
35 if (preg_match_all(',<!\[CDATA\[(.*)]]>,Uims', $rss,
36 $regs, PREG_SET_ORDER
)) {
37 foreach ($regs as $n => $reg) {
38 $echappe_cdata[$n] = $reg[1];
39 $rss = str_replace($reg[0], "@@@SPIP_CDATA$n@@@", $rss);
43 // supprimer les commentaires
44 $rss = preg_replace(',<!--.*-->,Ums', '', $rss);
46 // simplifier le backend, en supprimant les espaces de nommage type "dc:"
47 $rss = preg_replace(',<(/?)(dc):,i', '<\1', $rss);
49 // chercher auteur/lang dans le fil au cas ou les items n'en auraient pas
50 list($header) = preg_split(',<(item|entry)\b,', $rss, 2);
52 ',<(author|creator)\b(.*)</\1>,Uims',
53 $header, $regs, PREG_SET_ORDER
)) {
54 $les_auteurs_du_site = array();
55 foreach ($regs as $reg) {
57 if (preg_match(',<name>(.*)</name>,Uims', $nom, $reg))
59 $les_auteurs_du_site[] = trim(textebrut(filtrer_entites($nom)));
61 $les_auteurs_du_site = join(', ', array_unique($les_auteurs_du_site));
63 $les_auteurs_du_site = '';
65 if (preg_match(',<([^>]*xml[:])?lang(uage)?'.'>([^<>]+)<,i', $header, $match))
66 $langue_du_site = $match[3];
68 elseif (preg_match(',<feed\s[^>]*xml:lang=[\'"]([^<>\'"]+)[\'"],i', $header, $match))
69 $langue_du_site = $match[1];
71 // Attention en PCRE 6.7 preg_match_all casse sur un backend avec de gros <content:encoded>
72 $items = preg_split(',<(item|entry)\b.*>,Uims', $rss);
74 foreach ($items as $k=>$item)
75 $items[$k] = preg_replace(',</(item|entry)\b.*>.*$,UimsS', '', $item);
78 // Analyser chaque <item>...</item> du backend et le transformer en tableau
81 if (!count($items)) return _T('avis_echec_syndication_01');
83 foreach ($items as $item) {
86 // URL (semi-obligatoire, sert de cle)
88 // guid n'est un URL que si marque de <guid ispermalink="true"> ;
89 // attention la valeur par defaut est 'true' ce qui oblige a quelque
91 if (preg_match(',<guid.*>[[:space:]]*(https?:[^<]*)</guid>,Uims',
92 $item, $regs) AND preg_match(',^(true|1)?$,i',
93 extraire_attribut($regs[0], 'ispermalink')))
94 $data['url'] = $regs[1];
95 // contourner les redirections feedburner
96 else if (_SYNDICATION_DEREFERENCER_URL
97 AND preg_match(',<feedburner:origLink>(.*)<,Uims',
99 $data['url'] = $regs[1];
100 // <link>, plus classique
102 ',<link[^>]*[[:space:]]rel=["\']?alternate[^>]*>(.*)</link>,Uims',
104 $data['url'] = $regs[1];
105 else if (preg_match(',<link[^>]*[[:space:]]rel=.alternate[^>]*>,Uims',
107 $data['url'] = extraire_attribut($regs[0], 'href');
108 else if (preg_match(',<link[^>]*>\s*([^\s]+)\s*</link>,Uims', $item, $regs))
109 $data['url'] = $regs[1];
110 else if (preg_match(',<link[^>]*>,Uims', $item, $regs))
111 $data['url'] = extraire_attribut($regs[0], 'href');
113 // Aucun link ni guid, mais une enclosure
114 else if (preg_match(',<enclosure[^>]*>,ims', $item, $regs)
115 AND $url = extraire_attribut($regs[0], 'url'))
118 // pas d'url, c'est genre un compteur...
122 // Titre (semi-obligatoire)
123 if (preg_match(",<title[^>]*>(.*?)</title>,ims",$item,$match))
124 $data['titre'] = $match[1];
125 else if (preg_match(',<link[[:space:]][^>]*>,Uims',$item,$mat)
126 AND $title = extraire_attribut($mat[0], 'title'))
127 $data['titre'] = $title;
128 if (!strlen($data['titre'] = trim($data['titre'])))
129 $data['titre'] = _T('ecrire:info_sans_titre');
133 if (preg_match(',<(published|modified|issued)>([^<]*)<,Uims',
135 $la_date = my_strtotime($match[2]);
137 preg_match(',<(pubdate)>([^<]*)<,Uims',$item, $match))
138 $la_date = my_strtotime($match[2]);
140 preg_match(',<([a-z]+:date)>([^<]*)<,Uims',$item,$match))
141 $la_date = my_strtotime($match[2]);
143 preg_match(',<date>([^<]*)<,Uims',$item,$match))
144 $la_date = my_strtotime($match[1]);
146 // controle de validite de la date
147 // pour eviter qu'un backend errone passe toujours devant
148 // (note: ca pourrait etre defini site par site, mais ca risque d'etre
149 // plus lourd que vraiment utile)
150 if ($GLOBALS['controler_dates_rss']) {
152 OR $la_date > time() +
48 * 3600)
156 $data['date'] = $la_date;
158 // Honorer le <lastbuilddate> en forcant la date
159 if (preg_match(',<(lastbuilddate|updated|modified)>([^<>]+)</\1>,i',
161 AND $lastbuilddate = my_strtotime(trim($regs[2]))
163 AND $lastbuilddate < time())
164 $data['lastbuilddate'] = $lastbuilddate;
168 ',<(author|creator)>(.*)</\1>,Uims',
169 $item, $regs, PREG_SET_ORDER
)) {
171 foreach ($regs as $reg) {
173 if (preg_match(',<name>(.*)</name>,Uims', $nom, $reg))
175 $auteurs[] = trim(textebrut(filtrer_entites($nom)));
177 $data['lesauteurs'] = join(', ', array_unique($auteurs));
180 $data['lesauteurs'] = $les_auteurs_du_site;
183 if (preg_match(',<(description|summary)\b.*'
184 .'>(.*)</\1\b,Uims',$item,$match)) {
185 $data['descriptif'] = trim($match[2]);
187 if (preg_match(',<(content)\b.*'
188 .'>(.*)</\1\b,Uims',$item,$match)) {
189 $data['content'] = trim($match[2]);
193 if (preg_match(',<([^>]*xml:)?lang(uage)?'.'>([^<>]+)<,i',
195 $data['lang'] = trim($match[3]);
196 else if ($lang = trim(extraire_attribut($item, 'xml:lang')))
197 $data['lang'] = $lang;
199 $data['lang'] = trim($langue_du_site);
201 // source et url_source (pas trouve d'exemple en ligne !!)
202 # <source url="http://www.truc.net/music/uatsap.mp3" length="19917" />
203 # <source url="http://www.truc.net/rss">Site source</source>
204 if (preg_match(',(<source[^>]*>)(([^<>]+)</source>)?,i',
206 $data['source'] = trim($match[3]);
207 $data['url_source'] = str_replace('&', '&',
208 trim(extraire_attribut($match[1], 'url')));
212 # a partir de "<dc:subject>", (del.icio.us)
213 # ou <media:category> (flickr)
214 # ou <itunes:category> (apple)
215 # on cree nos tags microformat <a rel="directory" href="url">titre</a>
216 # http://microformats.org/wiki/rel-directory-fr
219 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*>'
221 $item, $matches, PREG_SET_ORDER
))
222 $tags = ajouter_tags($matches, $item); # array()
223 elseif (preg_match_all(
224 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*/>'
226 $item, $matches, PREG_SET_ORDER
))
227 $tags = ajouter_tags($matches, $item); # array()
229 // chercher <enclosure> au format RSS et les passer en microformat
230 // ou des microformats relEnclosure,
231 // ou encore les media:content
232 if (!afficher_enclosures(join(', ', $tags))) {
233 if (preg_match_all(',<enclosure[[:space:]][^<>]+>,i',
234 $item, $matches, PREG_PATTERN_ORDER
))
235 $data['enclosures'] = join(', ',
236 array_map('enclosure2microformat', $matches[0]));
238 preg_match_all(',<link\b[^<>]+rel=["\']?enclosure["\']?[^<>]+>,i',
239 $item, $matches, PREG_PATTERN_ORDER
))
240 $data['enclosures'] = join(', ',
241 array_map('enclosure2microformat', $matches[0]));
243 preg_match_all(',<media:content\b[^<>]+>,i',
244 $item, $matches, PREG_PATTERN_ORDER
))
245 $data['enclosures'] = join(', ',
246 array_map('enclosure2microformat', $matches[0]));
248 $data['item'] = $item;
250 // Nettoyer les donnees et remettre les CDATA en place
251 cdata_echappe_retour($data, $echappe_cdata);
252 cdata_echappe_retour($tags, $echappe_cdata);
254 // passer l'url en absolue
255 $data['url'] = url_absolue(filtrer_entites($data['url']), $url_syndic);
257 // Trouver les microformats (ecrase les <category> et <dc:subject>)
259 ',<a[[:space:]]([^>]+[[:space:]])?rel=[^>]+>.*</a>,Uims',
260 $data['item'], $regs, PREG_PATTERN_ORDER
)) {
263 // Cas particulier : tags Connotea sous la forme <a class="postedtag">
265 ',<a[[:space:]][^>]+ class="postedtag"[^>]*>.*</a>,Uims',
266 $data['item'], $regs, PREG_PATTERN_ORDER
))
267 $tags = preg_replace(', class="postedtag",i',
268 ' rel="tag"', $regs[0]);
270 $data['tags'] = $tags;
271 // enlever le html des titre pour etre homogene avec les autres objets spip
272 $data['titre'] = textebrut($data['titre']);
281 // helas strtotime ne reconnait pas le format W3C
282 // http://www.w3.org/TR/NOTE-datetime
283 // http://doc.spip.org/@my_strtotime
284 function my_strtotime($la_date) {
288 ',^(\d+-\d+-\d+[T ]\d+:\d+(:\d+)?)(\.\d+)?'
289 .'(Z|([-+]\d{2}):\d+)?$,',
291 $la_date = str_replace("T", " ", $match[1])." GMT";
292 return strtotime($la_date) - intval($match[5]) * 3600;
296 if (preg_match(',^\d{4}$,', $la_date, $match))
297 return strtotime($match[0]."-01-01");
300 if (preg_match(',^\d{4}-\d{2}$,', $la_date, $match))
301 return strtotime($match[0]."-01");
303 // utiliser strtotime en dernier ressort
304 $s = strtotime($la_date);
308 // YYYY-MM-DD hh:mm:ss
309 if (preg_match(',^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\b,', $la_date, $match))
310 return strtotime($match[0]);
314 spip_log("Impossible de lire le format de date '$la_date'");
317 // A partir d'un <dc:subject> ou autre essayer de recuperer
318 // le mot et son url ; on cree <a href="url" rel="tag">mot</a>
319 // http://doc.spip.org/@creer_tag
320 function creer_tag($mot,$type,$url) {
321 if (!strlen($mot = trim($mot))) return '';
322 $mot = "<a rel=\"tag\">$mot</a>";
324 $mot = inserer_attribut($mot, 'href', $url);
326 $mot = inserer_attribut($mot, 'rel', $type);
331 // http://doc.spip.org/@ajouter_tags
332 function ajouter_tags($matches, $item) {
333 include_spip('inc/filtres');
335 foreach ($matches as $match) {
336 $type = ($match[3] == 'category' OR $match[3] == 'directory')
338 $mot = supprimer_tags($match[0]);
340 AND !strlen($mot = extraire_attribut($match[0], 'label')))
343 if ($url = extraire_attribut($match[0], 'domain')) {
344 // category@domain est la racine d'une url qui se prolonge
345 // avec le contenu text du tag <category> ; mais dans SPIP < 2.0
346 // on donnait category@domain = #URL_RUBRIQUE, et
347 // text = #TITRE_RUBRIQUE ; d'ou l'heuristique suivante sur le slash
348 if (substr($url, -1) == '/')
349 $url .= rawurlencode($mot);
351 else if ($url = extraire_attribut($match[0], 'resource')
352 OR $url = extraire_attribut($match[0], 'url')
357 else if (extraire_attribut($match[0], 'scheme') == 'urn:flickr:tags') {
358 foreach(explode(' ', $mot) as $petit)
359 if ($t = creer_tag($petit, $type,
360 'http://www.flickr.com/photos/tags/'.rawurlencode($petit).'/'))
365 // cas atom1, a faire apres flickr
366 $term = extraire_attribut($match[0], 'term')
368 if ($scheme = extraire_attribut($match[0], 'scheme'))
369 $url = suivre_lien($scheme,$term);
375 foreach(explode(' ', $mot) as $petit)
376 if (preg_match(',<rdf\b[^>]*\bresource=["\']([^>]*/'
377 .preg_quote(rawurlencode($petit),',').')["\'],i',
380 if ($t = creer_tag($petit, $type, $m[1]))
385 if ($t = creer_tag($mot, $type, $url))
392 // Retablit le contenu des blocs [[CDATA]] dans un tableau
393 // http://doc.spip.org/@cdata_echappe_retour
394 function cdata_echappe_retour(&$table, &$echappe_cdata) {
395 foreach ($table as $var => $val) {
396 $table[$var] = filtrer_entites($table[$var]);
397 foreach ($echappe_cdata as $n => $e)
398 $table[$var] = str_replace("@@@SPIP_CDATA$n@@@",