[SPIP] +2.1.12
[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-2011 *
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 > time() + 48 * 3600)
152 $la_date = time();
153 }
154
155 $data['date'] = $la_date;
156
157 // Honorer le <lastbuilddate> en forcant la date
158 if (preg_match(',<(lastbuilddate|updated|modified)>([^<>]+)</\1>,i',
159 $item, $regs)
160 AND $lastbuilddate = my_strtotime(trim($regs[2]))
161 // pas dans le futur
162 AND $lastbuilddate < time())
163 $data['lastbuilddate'] = $lastbuilddate;
164
165 // Auteur(s)
166 if (preg_match_all(
167 ',<(author|creator)>(.*)</\1>,Uims',
168 $item, $regs, PREG_SET_ORDER)) {
169 $auteurs = array();
170 foreach ($regs as $reg) {
171 $nom = $reg[2];
172 if (preg_match(',<name>(.*)</name>,Uims', $nom, $reg))
173 $nom = $reg[1];
174 $auteurs[] = trim(textebrut(filtrer_entites($nom)));
175 }
176 $data['lesauteurs'] = join(', ', array_unique($auteurs));
177 }
178 else
179 $data['lesauteurs'] = $les_auteurs_du_site;
180
181 // Description
182 if (preg_match(',<(description|summary)\b.*'
183 .'>(.*)</\1\b,Uims',$item,$match)) {
184 $data['descriptif'] = trim($match[2]);
185 }
186 if (preg_match(',<(content)\b.*'
187 .'>(.*)</\1\b,Uims',$item,$match)) {
188 $data['content'] = trim($match[2]);
189 }
190
191 // lang
192 if (preg_match(',<([^>]*xml:)?lang(uage)?'.'>([^<>]+)<,i',
193 $item, $match))
194 $data['lang'] = trim($match[3]);
195 else if ($lang = trim(extraire_attribut($item, 'xml:lang')))
196 $data['lang'] = $lang;
197 else
198 $data['lang'] = trim($langue_du_site);
199
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',
204 $item, $match)) {
205 $data['source'] = trim($match[3]);
206 $data['url_source'] = str_replace('&amp;', '&',
207 trim(extraire_attribut($match[1], 'url')));
208 }
209
210 // tags
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
216 $tags = array();
217 if (preg_match_all(
218 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*>'
219 .'(.*?)</\1>,ims',
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))[^>]*/>'
224 .',ims',
225 $item, $matches, PREG_SET_ORDER))
226 $tags = ajouter_tags($matches, $item); # array()
227 // Pieces jointes :
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]));
236 else if (
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]));
241 else if (
242 preg_match_all(',<media:content\b[^<>]+>,i',
243 $item, $matches, PREG_PATTERN_ORDER))
244 $data['enclosures'] = join(', ',
245 array_map('enclosure2microformat', $matches[0]));
246 }
247 $data['item'] = $item;
248
249 // Nettoyer les donnees et remettre les CDATA en place
250 cdata_echappe_retour($data, $echappe_cdata);
251 cdata_echappe_retour($tags, $echappe_cdata);
252
253 // passer l'url en absolue
254 $data['url'] = url_absolue(filtrer_entites($data['url']), $url_syndic);
255
256 // Trouver les microformats (ecrase les <category> et <dc:subject>)
257 if (preg_match_all(
258 ',<a[[:space:]]([^>]+[[:space:]])?rel=[^>]+>.*</a>,Uims',
259 $data['item'], $regs, PREG_PATTERN_ORDER)) {
260 $tags = $regs[0];
261 }
262 // Cas particulier : tags Connotea sous la forme <a class="postedtag">
263 if (preg_match_all(
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]);
268
269 $data['tags'] = $tags;
270 // enlever le html des titre pour etre homogene avec les autres objets spip
271 $data['titre'] = textebrut($data['titre']);
272
273 $articles[] = $data;
274 }
275
276 return $articles;
277 }
278
279
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) {
284
285 // format complet
286 if (preg_match(
287 ',^(\d+-\d+-\d+[T ]\d+:\d+(:\d+)?)(\.\d+)?'
288 .'(Z|([-+]\d{2}):\d+)?$,',
289 $la_date, $match)) {
290 $la_date = str_replace("T", " ", $match[1])." GMT";
291 return strtotime($la_date) - intval($match[5]) * 3600;
292 }
293
294 // YYYY
295 if (preg_match(',^\d{4}$,', $la_date, $match))
296 return strtotime($match[0]."-01-01");
297
298 // YYYY-MM
299 if (preg_match(',^\d{4}-\d{2}$,', $la_date, $match))
300 return strtotime($match[0]."-01");
301
302 // utiliser strtotime en dernier ressort
303 $s = strtotime($la_date);
304 if ($s > 0)
305 return $s;
306
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]);
310
311
312 // erreur
313 spip_log("Impossible de lire le format de date '$la_date'");
314 return false;
315 }
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>";
322 if ($url)
323 $mot = inserer_attribut($mot, 'href', $url);
324 if ($type)
325 $mot = inserer_attribut($mot, 'rel', $type);
326 return $mot;
327 }
328
329
330 // http://doc.spip.org/@ajouter_tags
331 function ajouter_tags($matches, $item) {
332 include_spip('inc/filtres');
333 $tags = array();
334 foreach ($matches as $match) {
335 $type = ($match[3] == 'category' OR $match[3] == 'directory')
336 ? 'directory':'tag';
337 $mot = supprimer_tags($match[0]);
338 if (!strlen($mot)
339 AND !strlen($mot = extraire_attribut($match[0], 'label')))
340 break;
341 // rechercher un url
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);
349 }
350 else if ($url = extraire_attribut($match[0], 'resource')
351 OR $url = extraire_attribut($match[0], 'url')
352 )
353 {}
354
355 ## cas particuliers
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).'/'))
360 $tags[] = $t;
361 $mot = '';
362 }
363 else if (
364 // cas atom1, a faire apres flickr
365 $term = extraire_attribut($match[0], 'term')
366 ) {
367 if ($scheme = extraire_attribut($match[0], 'scheme'))
368 $url = suivre_lien($scheme,$term);
369 else
370 $url = $term;
371 }
372 else {
373 # type delicious.com
374 foreach(explode(' ', $mot) as $petit)
375 if (preg_match(',<rdf\b[^>]*\bresource=["\']([^>]*/'
376 .preg_quote(rawurlencode($petit),',').')["\'],i',
377 $item, $m)) {
378 $mot = '';
379 if ($t = creer_tag($petit, $type, $m[1]))
380 $tags[] = $t;
381 }
382 }
383
384 if ($t = creer_tag($mot, $type, $url))
385 $tags[] = $t;
386 }
387 return $tags;
388 }
389
390
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@@@",
398 $e, $table[$var]);
399 }
400 }
401 ?>