[SPIP] ~2.1.12 -->2.1.25
[velocampus/web/www.git] / www / ecrire / inc / syndic.php
1 <?php
2
3 /***************************************************************************\
4 * SPIP, Systeme de publication pour l'internet *
5 * *
6 * Copyright (c) 2001-2014 *
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 $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);
40 }
41 }
42
43 // supprimer les commentaires
44 $rss = preg_replace(',<!--.*-->,Ums', '', $rss);
45
46 // simplifier le backend, en supprimant les espaces de nommage type "dc:"
47 $rss = preg_replace(',<(/?)(dc):,i', '<\1', $rss);
48
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);
51 if (preg_match_all(
52 ',<(author|creator)\b(.*)</\1>,Uims',
53 $header, $regs, PREG_SET_ORDER)) {
54 $les_auteurs_du_site = array();
55 foreach ($regs as $reg) {
56 $nom = $reg[2];
57 if (preg_match(',<name>(.*)</name>,Uims', $nom, $reg))
58 $nom = $reg[1];
59 $les_auteurs_du_site[] = trim(textebrut(filtrer_entites($nom)));
60 }
61 $les_auteurs_du_site = join(', ', array_unique($les_auteurs_du_site));
62 } else
63 $les_auteurs_du_site = '';
64
65 if (preg_match(',<([^>]*xml[:])?lang(uage)?'.'>([^<>]+)<,i', $header, $match))
66 $langue_du_site = $match[3];
67 // atom
68 elseif (preg_match(',<feed\s[^>]*xml:lang=[\'"]([^<>\'"]+)[\'"],i', $header, $match))
69 $langue_du_site = $match[1];
70
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);
73 array_shift($items);
74 foreach ($items as $k=>$item)
75 $items[$k] = preg_replace(',</(item|entry)\b.*>.*$,UimsS', '', $item);
76
77 //
78 // Analyser chaque <item>...</item> du backend et le transformer en tableau
79 //
80
81 if (!count($items)) return _T('avis_echec_syndication_01');
82
83 foreach ($items as $item) {
84 $data = array();
85
86 // URL (semi-obligatoire, sert de cle)
87
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
90 // gymnastique
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',
98 $item, $regs))
99 $data['url'] = $regs[1];
100 // <link>, plus classique
101 else if (preg_match(
102 ',<link[^>]*[[:space:]]rel=["\']?alternate[^>]*>(.*)</link>,Uims',
103 $item, $regs))
104 $data['url'] = $regs[1];
105 else if (preg_match(',<link[^>]*[[:space:]]rel=.alternate[^>]*>,Uims',
106 $item, $regs))
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');
112
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'))
116 $data['url'] = $url;
117
118 // pas d'url, c'est genre un compteur...
119 else
120 $data['url'] = '';
121
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');
130
131 // Date
132 $la_date = '';
133 if (preg_match(',<(published|modified|issued)>([^<]*)<,Uims',
134 $item,$match))
135 $la_date = my_strtotime($match[2]);
136 if (!$la_date AND
137 preg_match(',<(pubdate)>([^<]*)<,Uims',$item, $match))
138 $la_date = my_strtotime($match[2]);
139 if (!$la_date AND
140 preg_match(',<([a-z]+:date)>([^<]*)<,Uims',$item,$match))
141 $la_date = my_strtotime($match[2]);
142 if (!$la_date AND
143 preg_match(',<date>([^<]*)<,Uims',$item,$match))
144 $la_date = my_strtotime($match[1]);
145
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
152 OR $la_date > time() + 48 * 3600)
153 $la_date = time();
154 }
155
156 $data['date'] = $la_date;
157
158 // Honorer le <lastbuilddate> en forcant la date
159 if (preg_match(',<(lastbuilddate|updated|modified)>([^<>]+)</\1>,i',
160 $item, $regs)
161 AND $lastbuilddate = my_strtotime(trim($regs[2]))
162 // pas dans le futur
163 AND $lastbuilddate < time())
164 $data['lastbuilddate'] = $lastbuilddate;
165
166 // Auteur(s)
167 if (preg_match_all(
168 ',<(author|creator)>(.*)</\1>,Uims',
169 $item, $regs, PREG_SET_ORDER)) {
170 $auteurs = array();
171 foreach ($regs as $reg) {
172 $nom = $reg[2];
173 if (preg_match(',<name>(.*)</name>,Uims', $nom, $reg))
174 $nom = $reg[1];
175 $auteurs[] = trim(textebrut(filtrer_entites($nom)));
176 }
177 $data['lesauteurs'] = join(', ', array_unique($auteurs));
178 }
179 else
180 $data['lesauteurs'] = $les_auteurs_du_site;
181
182 // Description
183 if (preg_match(',<(description|summary)\b.*'
184 .'>(.*)</\1\b,Uims',$item,$match)) {
185 $data['descriptif'] = trim($match[2]);
186 }
187 if (preg_match(',<(content)\b.*'
188 .'>(.*)</\1\b,Uims',$item,$match)) {
189 $data['content'] = trim($match[2]);
190 }
191
192 // lang
193 if (preg_match(',<([^>]*xml:)?lang(uage)?'.'>([^<>]+)<,i',
194 $item, $match))
195 $data['lang'] = trim($match[3]);
196 else if ($lang = trim(extraire_attribut($item, 'xml:lang')))
197 $data['lang'] = $lang;
198 else
199 $data['lang'] = trim($langue_du_site);
200
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',
205 $item, $match)) {
206 $data['source'] = trim($match[3]);
207 $data['url_source'] = str_replace('&amp;', '&',
208 trim(extraire_attribut($match[1], 'url')));
209 }
210
211 // tags
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
217 $tags = array();
218 if (preg_match_all(
219 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*>'
220 .'(.*?)</\1>,ims',
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))[^>]*/>'
225 .',ims',
226 $item, $matches, PREG_SET_ORDER))
227 $tags = ajouter_tags($matches, $item); # array()
228 // Pieces jointes :
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]));
237 else if (
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]));
242 else if (
243 preg_match_all(',<media:content\b[^<>]+>,i',
244 $item, $matches, PREG_PATTERN_ORDER))
245 $data['enclosures'] = join(', ',
246 array_map('enclosure2microformat', $matches[0]));
247 }
248 $data['item'] = $item;
249
250 // Nettoyer les donnees et remettre les CDATA en place
251 cdata_echappe_retour($data, $echappe_cdata);
252 cdata_echappe_retour($tags, $echappe_cdata);
253
254 // passer l'url en absolue
255 $data['url'] = url_absolue(filtrer_entites($data['url']), $url_syndic);
256
257 // Trouver les microformats (ecrase les <category> et <dc:subject>)
258 if (preg_match_all(
259 ',<a[[:space:]]([^>]+[[:space:]])?rel=[^>]+>.*</a>,Uims',
260 $data['item'], $regs, PREG_PATTERN_ORDER)) {
261 $tags = $regs[0];
262 }
263 // Cas particulier : tags Connotea sous la forme <a class="postedtag">
264 if (preg_match_all(
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]);
269
270 $data['tags'] = $tags;
271 // enlever le html des titre pour etre homogene avec les autres objets spip
272 $data['titre'] = textebrut($data['titre']);
273
274 $articles[] = $data;
275 }
276
277 return $articles;
278 }
279
280
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) {
285
286 // format complet
287 if (preg_match(
288 ',^(\d+-\d+-\d+[T ]\d+:\d+(:\d+)?)(\.\d+)?'
289 .'(Z|([-+]\d{2}):\d+)?$,',
290 $la_date, $match)) {
291 $la_date = str_replace("T", " ", $match[1])." GMT";
292 return strtotime($la_date) - intval($match[5]) * 3600;
293 }
294
295 // YYYY
296 if (preg_match(',^\d{4}$,', $la_date, $match))
297 return strtotime($match[0]."-01-01");
298
299 // YYYY-MM
300 if (preg_match(',^\d{4}-\d{2}$,', $la_date, $match))
301 return strtotime($match[0]."-01");
302
303 // utiliser strtotime en dernier ressort
304 $s = strtotime($la_date);
305 if ($s > 0)
306 return $s;
307
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]);
311
312
313 // erreur
314 spip_log("Impossible de lire le format de date '$la_date'");
315 return false;
316 }
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>";
323 if ($url)
324 $mot = inserer_attribut($mot, 'href', $url);
325 if ($type)
326 $mot = inserer_attribut($mot, 'rel', $type);
327 return $mot;
328 }
329
330
331 // http://doc.spip.org/@ajouter_tags
332 function ajouter_tags($matches, $item) {
333 include_spip('inc/filtres');
334 $tags = array();
335 foreach ($matches as $match) {
336 $type = ($match[3] == 'category' OR $match[3] == 'directory')
337 ? 'directory':'tag';
338 $mot = supprimer_tags($match[0]);
339 if (!strlen($mot)
340 AND !strlen($mot = extraire_attribut($match[0], 'label')))
341 break;
342 // rechercher un url
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);
350 }
351 else if ($url = extraire_attribut($match[0], 'resource')
352 OR $url = extraire_attribut($match[0], 'url')
353 )
354 {}
355
356 ## cas particuliers
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).'/'))
361 $tags[] = $t;
362 $mot = '';
363 }
364 else if (
365 // cas atom1, a faire apres flickr
366 $term = extraire_attribut($match[0], 'term')
367 ) {
368 if ($scheme = extraire_attribut($match[0], 'scheme'))
369 $url = suivre_lien($scheme,$term);
370 else
371 $url = $term;
372 }
373 else {
374 # type delicious.com
375 foreach(explode(' ', $mot) as $petit)
376 if (preg_match(',<rdf\b[^>]*\bresource=["\']([^>]*/'
377 .preg_quote(rawurlencode($petit),',').')["\'],i',
378 $item, $m)) {
379 $mot = '';
380 if ($t = creer_tag($petit, $type, $m[1]))
381 $tags[] = $t;
382 }
383 }
384
385 if ($t = creer_tag($mot, $type, $url))
386 $tags[] = $t;
387 }
388 return $tags;
389 }
390
391
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@@@",
399 $e, $table[$var]);
400 }
401 }
402 ?>