3 /***************************************************************************\
4 * SPIP, Systeme de publication pour l'internet *
6 * Copyright (c) 2001-2011 *
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[^>]*>(.*)</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']) {
151 if ($la_date > time() +
48 * 3600)
155 $data['date'] = $la_date;
157 // Honorer le <lastbuilddate> en forcant la date
158 if (preg_match(',<(lastbuilddate|updated|modified)>([^<>]+)</\1>,i',
160 AND $lastbuilddate = my_strtotime(trim($regs[2]))
162 AND $lastbuilddate < time())
163 $data['lastbuilddate'] = $lastbuilddate;
167 ',<(author|creator)>(.*)</\1>,Uims',
168 $item, $regs, PREG_SET_ORDER
)) {
170 foreach ($regs as $reg) {
172 if (preg_match(',<name>(.*)</name>,Uims', $nom, $reg))
174 $auteurs[] = trim(textebrut(filtrer_entites($nom)));
176 $data['lesauteurs'] = join(', ', array_unique($auteurs));
179 $data['lesauteurs'] = $les_auteurs_du_site;
182 if (preg_match(',<(description|summary)\b.*'
183 .'>(.*)</\1\b,Uims',$item,$match)) {
184 $data['descriptif'] = trim($match[2]);
186 if (preg_match(',<(content)\b.*'
187 .'>(.*)</\1\b,Uims',$item,$match)) {
188 $data['content'] = trim($match[2]);
192 if (preg_match(',<([^>]*xml:)?lang(uage)?'.'>([^<>]+)<,i',
194 $data['lang'] = trim($match[3]);
195 else if ($lang = trim(extraire_attribut($item, 'xml:lang')))
196 $data['lang'] = $lang;
198 $data['lang'] = trim($langue_du_site);
200 // source et url_source (pas trouve d'exemple en ligne !!)
201 # <source url="http://www.truc.net/music/uatsap.mp3" length="19917" />
202 # <source url="http://www.truc.net/rss">Site source</source>
203 if (preg_match(',(<source[^>]*>)(([^<>]+)</source>)?,i',
205 $data['source'] = trim($match[3]);
206 $data['url_source'] = str_replace('&', '&',
207 trim(extraire_attribut($match[1], 'url')));
211 # a partir de "<dc:subject>", (del.icio.us)
212 # ou <media:category> (flickr)
213 # ou <itunes:category> (apple)
214 # on cree nos tags microformat <a rel="directory" href="url">titre</a>
215 # http://microformats.org/wiki/rel-directory-fr
218 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*>'
220 $item, $matches, PREG_SET_ORDER
))
221 $tags = ajouter_tags($matches, $item); # array()
222 elseif (preg_match_all(
223 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*/>'
225 $item, $matches, PREG_SET_ORDER
))
226 $tags = ajouter_tags($matches, $item); # array()
228 // chercher <enclosure> au format RSS et les passer en microformat
229 // ou des microformats relEnclosure,
230 // ou encore les media:content
231 if (!afficher_enclosures(join(', ', $tags))) {
232 if (preg_match_all(',<enclosure[[:space:]][^<>]+>,i',
233 $item, $matches, PREG_PATTERN_ORDER
))
234 $data['enclosures'] = join(', ',
235 array_map('enclosure2microformat', $matches[0]));
237 preg_match_all(',<link\b[^<>]+rel=["\']?enclosure["\']?[^<>]+>,i',
238 $item, $matches, PREG_PATTERN_ORDER
))
239 $data['enclosures'] = join(', ',
240 array_map('enclosure2microformat', $matches[0]));
242 preg_match_all(',<media:content\b[^<>]+>,i',
243 $item, $matches, PREG_PATTERN_ORDER
))
244 $data['enclosures'] = join(', ',
245 array_map('enclosure2microformat', $matches[0]));
247 $data['item'] = $item;
249 // Nettoyer les donnees et remettre les CDATA en place
250 cdata_echappe_retour($data, $echappe_cdata);
251 cdata_echappe_retour($tags, $echappe_cdata);
253 // passer l'url en absolue
254 $data['url'] = url_absolue(filtrer_entites($data['url']), $url_syndic);
256 // Trouver les microformats (ecrase les <category> et <dc:subject>)
258 ',<a[[:space:]]([^>]+[[:space:]])?rel=[^>]+>.*</a>,Uims',
259 $data['item'], $regs, PREG_PATTERN_ORDER
)) {
262 // Cas particulier : tags Connotea sous la forme <a class="postedtag">
264 ',<a[[:space:]][^>]+ class="postedtag"[^>]*>.*</a>,Uims',
265 $data['item'], $regs, PREG_PATTERN_ORDER
))
266 $tags = preg_replace(', class="postedtag",i',
267 ' rel="tag"', $regs[0]);
269 $data['tags'] = $tags;
270 // enlever le html des titre pour etre homogene avec les autres objets spip
271 $data['titre'] = textebrut($data['titre']);
280 // helas strtotime ne reconnait pas le format W3C
281 // http://www.w3.org/TR/NOTE-datetime
282 // http://doc.spip.org/@my_strtotime
283 function my_strtotime($la_date) {
287 ',^(\d+-\d+-\d+[T ]\d+:\d+(:\d+)?)(\.\d+)?'
288 .'(Z|([-+]\d{2}):\d+)?$,',
290 $la_date = str_replace("T", " ", $match[1])." GMT";
291 return strtotime($la_date) - intval($match[5]) * 3600;
295 if (preg_match(',^\d{4}$,', $la_date, $match))
296 return strtotime($match[0]."-01-01");
299 if (preg_match(',^\d{4}-\d{2}$,', $la_date, $match))
300 return strtotime($match[0]."-01");
302 // utiliser strtotime en dernier ressort
303 $s = strtotime($la_date);
307 // YYYY-MM-DD hh:mm:ss
308 if (preg_match(',^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\b,', $la_date, $match))
309 return strtotime($match[0]);
313 spip_log("Impossible de lire le format de date '$la_date'");
316 // A partir d'un <dc:subject> ou autre essayer de recuperer
317 // le mot et son url ; on cree <a href="url" rel="tag">mot</a>
318 // http://doc.spip.org/@creer_tag
319 function creer_tag($mot,$type,$url) {
320 if (!strlen($mot = trim($mot))) return '';
321 $mot = "<a rel=\"tag\">$mot</a>";
323 $mot = inserer_attribut($mot, 'href', $url);
325 $mot = inserer_attribut($mot, 'rel', $type);
330 // http://doc.spip.org/@ajouter_tags
331 function ajouter_tags($matches, $item) {
332 include_spip('inc/filtres');
334 foreach ($matches as $match) {
335 $type = ($match[3] == 'category' OR $match[3] == 'directory')
337 $mot = supprimer_tags($match[0]);
339 AND !strlen($mot = extraire_attribut($match[0], 'label')))
342 if ($url = extraire_attribut($match[0], 'domain')) {
343 // category@domain est la racine d'une url qui se prolonge
344 // avec le contenu text du tag <category> ; mais dans SPIP < 2.0
345 // on donnait category@domain = #URL_RUBRIQUE, et
346 // text = #TITRE_RUBRIQUE ; d'ou l'heuristique suivante sur le slash
347 if (substr($url, -1) == '/')
348 $url .= rawurlencode($mot);
350 else if ($url = extraire_attribut($match[0], 'resource')
351 OR $url = extraire_attribut($match[0], 'url')
356 else if (extraire_attribut($match[0], 'scheme') == 'urn:flickr:tags') {
357 foreach(explode(' ', $mot) as $petit)
358 if ($t = creer_tag($petit, $type,
359 'http://www.flickr.com/photos/tags/'.rawurlencode($petit).'/'))
364 // cas atom1, a faire apres flickr
365 $term = extraire_attribut($match[0], 'term')
367 if ($scheme = extraire_attribut($match[0], 'scheme'))
368 $url = suivre_lien($scheme,$term);
374 foreach(explode(' ', $mot) as $petit)
375 if (preg_match(',<rdf\b[^>]*\bresource=["\']([^>]*/'
376 .preg_quote(rawurlencode($petit),',').')["\'],i',
379 if ($t = creer_tag($petit, $type, $m[1]))
384 if ($t = creer_tag($mot, $type, $url))
391 // Retablit le contenu des blocs [[CDATA]] dans un tableau
392 // http://doc.spip.org/@cdata_echappe_retour
393 function cdata_echappe_retour(&$table, &$echappe_cdata) {
394 foreach ($table as $var => $val) {
395 $table[$var] = filtrer_entites($table[$var]);
396 foreach ($echappe_cdata as $n => $e)
397 $table[$var] = str_replace("@@@SPIP_CDATA$n@@@",