3 /***************************************************************************\
4 * SPIP, Systeme de publication pour l'internet *
6 * Copyright (c) 2001-2016 *
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 \***************************************************************************/
14 * Gestion de syndication (RSS,...)
16 * @package SPIP\Sites\Syndication
19 if (!defined("_ECRIRE_INC_VERSION")) {
24 // Cette inclusion charge executer_une_syndication pour compatibilite,
25 // mais cette fonction ne doit plus etre invoquee directement:
26 // il faut passer par cron() pour avoir un verrou portable
27 // Voir un exemple dans action/editer/site
28 include_spip('genie/syndic');
32 * Analyse un texte de backend
35 * Texte du fichier de backend
36 * @param string $url_syndic
37 * URL du site d'où à été extrait le texte
38 * @return array|string
39 * - array : tableau des items lus,
40 * - string : texte d'erreur
42 function analyser_backend($rss, $url_syndic = '') {
43 include_spip('inc/texte'); # pour couper()
45 $rss = pipeline('pre_syndication', $rss);
47 if (!defined('_SYNDICATION_DEREFERENCER_URL')) {
48 /** si true, les URLs de type feedburner sont déréférencées */
49 define('_SYNDICATION_DEREFERENCER_URL', false);
53 cdata_echappe($rss, $echappe_cdata);
55 // supprimer les commentaires
56 $rss = preg_replace(',<!--.*-->,Ums', '', $rss);
58 // simplifier le backend, en supprimant les espaces de nommage type "dc:"
59 $rss = preg_replace(',<(/?)(dc):,i', '<\1', $rss);
61 // chercher auteur/lang dans le fil au cas ou les items n'en auraient pas
62 list($header) = preg_split(',<(item|entry)\b,', $rss, 2);
64 ',<(author|creator)\b(.*)</\1>,Uims',
65 $header, $regs, PREG_SET_ORDER
)) {
66 $les_auteurs_du_site = array();
67 foreach ($regs as $reg) {
69 if (preg_match(',<name>(.*)</name>,Uims', $nom, $reg)) {
72 $les_auteurs_du_site[] = trim(textebrut(filtrer_entites($nom)));
74 $les_auteurs_du_site = join(', ', array_unique($les_auteurs_du_site));
76 $les_auteurs_du_site = '';
81 if ((preg_match(',<([^>]*xml:)?lang(uage)?' . '>([^<>]+)<,i',
82 $header, $match) and $l = $match[3])
83 or ($l = extraire_attribut(extraire_balise($header, 'feed'), 'xml:lang'))
87 elseif (preg_match(',<feed\s[^>]*xml:lang=[\'"]([^<>\'"]+)[\'"],i', $header, $match)) {
88 $langue_du_site = $match[1];
91 // Recuperer les blocs item et entry
92 $items = array_merge(extraire_balises($rss, 'item'), extraire_balises($rss, 'entry'));
96 // Analyser chaque <item>...</item> du backend et le transformer en tableau
100 return _T('sites:avis_echec_syndication_01');
103 if (!defined('_SYNDICATION_MAX_ITEMS')) define('_SYNDICATION_MAX_ITEMS',1000);
105 foreach ($items as $item) {
107 if ($nb_items++
>_SYNDICATION_MAX_ITEMS
){
111 // URL (semi-obligatoire, sert de cle)
113 // guid n'est un URL que si marque de <guid ispermalink="true"> ;
114 // attention la valeur par defaut est 'true' ce qui oblige a quelque
116 if (preg_match(',<guid.*>[[:space:]]*(https?:[^<]*)</guid>,Uims',
117 $item, $regs) and preg_match(',^(true|1)?$,i',
118 extraire_attribut($regs[0], 'ispermalink'))
120 $data['url'] = $regs[1];
121 } // contourner les redirections feedburner
123 if (_SYNDICATION_DEREFERENCER_URL
124 and preg_match(',<feedburner:origLink>(.*)<,Uims',
127 $data['url'] = $regs[1];
128 } // <link>, plus classique
131 ',<link[^>]*[[:space:]]rel=["\']?alternate[^>]*>(.*)</link>,Uims',
133 $data['url'] = $regs[1];
135 if (preg_match(',<link[^>]*[[:space:]]rel=.alternate[^>]*>,Uims',
137 $data['url'] = extraire_attribut($regs[0], 'href');
139 if (preg_match(',<link[^>]*>\s*([^\s]+)\s*</link>,Uims', $item, $regs)) {
140 $data['url'] = $regs[1];
142 if (preg_match(',<link[^>]*>,Uims', $item, $regs)) {
143 $data['url'] = extraire_attribut($regs[0], 'href');
144 } // Aucun link ni guid, mais une enclosure
146 if (preg_match(',<enclosure[^>]*>,ims', $item, $regs)
147 and $url = extraire_attribut($regs[0], 'url')
150 } // pas d'url, c'est genre un compteur...
161 // Titre (semi-obligatoire)
162 if (preg_match(",<title[^>]*>(.*?)</title>,ims", $item, $match)) {
163 $data['titre'] = $match[1];
165 if (preg_match(',<link[[:space:]][^>]*>,Uims', $item, $mat)
166 and $title = extraire_attribut($mat[0], 'title')
168 $data['titre'] = $title;
171 if (!strlen($data['titre'] = trim($data['titre']))) {
172 $data['titre'] = _T('ecrire:info_sans_titre');
177 if (preg_match(',<(published|modified|issued)>([^<]*)<,Uims',
179 cdata_echappe_retour($match[2], $echappe_cdata);
180 $la_date = my_strtotime($match[2], $langue_du_site);
183 preg_match(',<(pubdate)>([^<]*)<,Uims', $item, $match)
185 cdata_echappe_retour($match[2], $echappe_cdata);
186 $la_date = my_strtotime($match[2], $langue_du_site);
189 preg_match(',<([a-z]+:date)>([^<]*)<,Uims', $item, $match)
191 cdata_echappe_retour($match[2], $echappe_cdata);
192 $la_date = my_strtotime($match[2], $langue_du_site);
195 preg_match(',<date>([^<]*)<,Uims', $item, $match)
197 cdata_echappe_retour($match[1], $echappe_cdata);
198 $la_date = my_strtotime($match[1], $langue_du_site);
201 // controle de validite de la date
202 // pour eviter qu'un backend errone passe toujours devant
203 // (note: ca pourrait etre defini site par site, mais ca risque d'etre
204 // plus lourd que vraiment utile)
205 if ($GLOBALS['controler_dates_rss']) {
207 or $la_date > time() +
48 * 3600
214 $data['date'] = $la_date;
217 // Honorer le <lastbuilddate> en forcant la date
218 if (preg_match(',<(lastbuilddate|updated|modified)>([^<>]+)</\1>,i',
220 and $lastbuilddate = my_strtotime(trim($regs[2]), $langue_du_site)
222 and $lastbuilddate < time()
224 $data['lastbuilddate'] = $lastbuilddate;
229 ',<(author|creator)\b[^>]*>(.*)</\1>,Uims',
230 $item, $regs, PREG_SET_ORDER
)) {
232 foreach ($regs as $reg) {
234 if (preg_match(',<name\b[^>]*>(.*)</name>,Uims', $nom, $reg)) {
237 // Cas particulier d'un auteur Flickr
238 if (preg_match(',nobody@flickr.com \((.*)\),Uims', $nom, $reg)) {
241 $auteurs[] = trim(textebrut(filtrer_entites($nom)));
243 $data['lesauteurs'] = join(', ', array_unique($auteurs));
245 $data['lesauteurs'] = $les_auteurs_du_site;
249 if (preg_match(',<(description|summary)\b.*'
250 . '>(.*)</\1\b,Uims', $item, $match)) {
251 $data['descriptif'] = trim($match[2]);
253 if (preg_match(',<(content)\b.*'
254 . '>(.*)</\1\b,Uims', $item, $match)) {
255 $data['content'] = trim($match[2]);
259 if (preg_match(',<([^>]*xml:)?lang(uage)?' . '>([^<>]+)<,i',
261 $data['lang'] = trim($match[3]);
263 if ($lang = trim(extraire_attribut($item, 'xml:lang'))) {
264 $data['lang'] = $lang;
266 $data['lang'] = trim($langue_du_site);
270 // source et url_source (pas trouve d'exemple en ligne !!)
271 # <source url="http://www.truc.net/music/uatsap.mp3" length="19917" />
272 # <source url="http://www.truc.net/rss">Site source</source>
273 if (preg_match(',(<source[^>]*>)(([^<>]+)</source>)?,i',
275 $data['source'] = trim($match[3]);
276 $data['url_source'] = str_replace('&', '&',
277 trim(extraire_attribut($match[1], 'url')));
281 # a partir de "<dc:subject>", (del.icio.us)
282 # ou <media:category> (flickr)
283 # ou <itunes:category> (apple)
284 # on cree nos tags microformat <a rel="directory" href="url">titre</a>
285 # http://microformats.org/wiki/rel-directory-fr
288 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*>'
290 $item, $matches, PREG_SET_ORDER
)) {
291 $tags = ajouter_tags($matches, $item);
293 elseif (preg_match_all(
294 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*/>'
296 $item, $matches, PREG_SET_ORDER
)) {
297 $tags = ajouter_tags($matches, $item);
300 // chercher <enclosure> au format RSS et les passer en microformat
301 // ou des microformats relEnclosure,
302 // ou encore les media:content
303 if (!afficher_enclosures(join(', ', $tags))) {
304 // on prend toutes les pièces jointes possibles, et on essaie de les rendre uniques.
305 $enclosures = array();
307 if (preg_match_all(',<enclosure[[:space:]][^<>]+>,i',
308 $item, $matches, PREG_PATTERN_ORDER
)) {
309 $enclosures +
= array_map('enclosure2microformat', $matches[0]);
312 if (preg_match_all(',<link\b[^<>]+rel=["\']?enclosure["\']?[^<>]+>,i',
313 $item, $matches, PREG_PATTERN_ORDER
)) {
314 $enclosures +
= array_map('enclosure2microformat', $matches[0]);
317 if (preg_match_all(',<media:content\b[^<>]+>,i',
318 $item, $matches, PREG_PATTERN_ORDER
)) {
319 $enclosures +
= array_map('enclosure2microformat', $matches[0]);
321 $data['enclosures'] = join(', ', array_unique($enclosures));
324 $data['item'] = $item;
326 // Nettoyer les donnees et remettre les CDATA en place
327 cdata_echappe_retour($data, $echappe_cdata);
328 cdata_echappe_retour($tags, $echappe_cdata);
330 // passer l'url en absolue
331 $data['url'] = url_absolue(filtrer_entites($data['url']), $url_syndic);
333 // si on demande un dereferencement de l'URL, il faut verifier que ce n'est pas une redirection
334 if (_SYNDICATION_DEREFERENCER_URL
) {
335 $target = $data['url'];
336 include_spip("inc/distant");
337 for ($i = 0; $i < 10; $i++
) {
338 // on fait un GET et pas un HEAD car les vieux SPIP ne repondent pas la redirection avec un HEAD (honte) sur un article virtuel
339 $res = recuperer_lapage($target, false, "GET", 4096);
342 } // c'est pas bon signe car on a pas trouve l'URL...
343 if (is_array($res)) {
345 } // on a trouve la page, donc on a l'URL finale
346 $target = $res; // c'est une redirection, on la suit pour voir ou elle mene
348 // ici $target est l'URL finale de la page
349 $data['url'] = $target;
352 // Trouver les microformats (ecrase les <category> et <dc:subject>)
354 ',<a[[:space:]]([^>]+[[:space:]])?rel=[^>]+>.*</a>,Uims',
355 $data['item'], $regs, PREG_PATTERN_ORDER
)) {
358 // Cas particulier : tags Connotea sous la forme <a class="postedtag">
360 ',<a[[:space:]][^>]+ class="postedtag"[^>]*>.*</a>,Uims',
361 $data['item'], $regs, PREG_PATTERN_ORDER
)) {
362 $tags = preg_replace(', class="postedtag",i',
363 ' rel="tag"', $regs[0]);
366 $data['tags'] = $tags;
367 // enlever le html des titre pour etre homogene avec les autres objets spip
368 $data['titre'] = textebrut($data['titre']);
378 * Strtotime même avec le format W3C !
380 * Car hélàs, strtotime ne le reconnait pas tout seul !
382 * @link http://www.w3.org/TR/NOTE-datetime Format datetime du W3C
384 * @param string $la_date
389 function my_strtotime($la_date, $lang = null) {
392 ',^(\d+-\d+-\d+[T ]\d+:\d+(:\d+)?)(\.\d+)?'
393 . '(Z|([-+]\d{2}):\d+)?$,',
395 $match = array_pad($match, 6, null);
396 $la_date = str_replace("T", " ", $match[1]) . " GMT";
398 return strtotime($la_date) - intval($match[5]) * 3600;
402 if (preg_match(',^\d{4}$,', $la_date, $match)) {
403 return strtotime($match[0] . "-01-01");
407 if (preg_match(',^\d{4}-\d{2}$,', $la_date, $match)) {
408 return strtotime($match[0] . "-01");
411 // YYYY-MM-DD hh:mm:ss
412 if (preg_match(',^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\b,', $la_date, $match)) {
413 return strtotime($match[0]);
416 // utiliser strtotime en dernier ressort
417 // en nettoyant le jour qui prefixe parfois la date, suivi d'une virgule
418 // et les UT qui sont en fait des UTC
419 $la_date_c = preg_replace("/^\w+,\s*/ms", "", $la_date);
420 $la_date_c = preg_replace("/UT\s*$/ms", "UTC", $la_date_c);
421 if ($s = strtotime($la_date)
422 or $s = strtotime($la_date_c)
427 // essayons de voir si le nom du mois est dans la langue du flux et remplacons le
428 // par la version anglaise avant de faire strtotime
431 list($lang) = explode("-", $lang);
432 static $months = null;
433 if (!isset($months[$lang])) {
434 $prev_lang = $GLOBALS['spip_lang'];
435 changer_langue($lang);
436 foreach (range(1, 12) as $m) {
437 $s = _T("date_mois_$m");
438 $months[$lang][$s] = date("M", strtotime("2013-$m-01"));
439 $s = _T("date_mois_" . $m . "_abbr");
440 $months[$lang][$s] = date("M", strtotime("2013-$m-01"));
441 $months[$lang][trim($s, ".")] = date("M", strtotime("2013-$m-01"));
443 changer_langue($prev_lang);
445 spip_log($la_date_c, "dbgs");
446 foreach ($months[$lang] as $loc => $en) {
447 if (stripos($la_date_c, $loc) !== false) {
448 $s = str_ireplace($loc, $en, $la_date_c);
449 if ($s = strtotime($s)) {
457 spip_log("Impossible de lire le format de date '$la_date'");
462 // A partir d'un <dc:subject> ou autre essayer de recuperer
463 // le mot et son url ; on cree <a href="url" rel="tag">mot</a>
464 // https://code.spip.net/@creer_tag
465 function creer_tag($mot, $type, $url) {
466 if (!strlen($mot = trim($mot))) {
469 $mot = "<a rel=\"tag\">$mot</a>";
471 $mot = inserer_attribut($mot, 'href', $url);
474 $mot = inserer_attribut($mot, 'rel', $type);
481 // https://code.spip.net/@ajouter_tags
482 function ajouter_tags($matches, $item) {
483 include_spip('inc/filtres');
485 foreach ($matches as $match) {
486 $type = ($match[3] == 'category' or $match[3] == 'directory')
487 ?
'directory' : 'tag';
488 $mot = supprimer_tags($match[0]);
490 and !strlen($mot = extraire_attribut($match[0], 'label'))
495 if ($url = extraire_attribut($match[0], 'domain')) {
496 // category@domain est la racine d'une url qui se prolonge
497 // avec le contenu text du tag <category> ; mais dans SPIP < 2.0
498 // on donnait category@domain = #URL_RUBRIQUE, et
499 // text = #TITRE_RUBRIQUE ; d'ou l'heuristique suivante sur le slash
500 if (substr($url, -1) == '/') {
501 $url .= rawurlencode($mot);
504 if ($url = extraire_attribut($match[0], 'resource')
505 or $url = extraire_attribut($match[0], 'url')
507 } ## cas particuliers
509 if (extraire_attribut($match[0], 'scheme') == 'urn:flickr:tags') {
510 foreach (explode(' ', $mot) as $petit) {
511 if ($t = creer_tag($petit, $type,
512 'http://www.flickr.com/photos/tags/' . rawurlencode($petit) . '/')
520 // cas atom1, a faire apres flickr
521 $term = extraire_attribut($match[0], 'term')
523 if ($scheme = extraire_attribut($match[0], 'scheme')) {
524 $url = suivre_lien($scheme, $term);
530 foreach (explode(' ', $mot) as $petit) {
531 if (preg_match(',<rdf\b[^>]*\bresource=["\']([^>]*/'
532 . preg_quote(rawurlencode($petit), ',') . ')["\'],i',
535 if ($t = creer_tag($petit, $type, $m[1])) {
545 if ($t = creer_tag($mot, $type, $url)) {
554 // Lit contenu des blocs [[CDATA]] dans un flux
555 // https://code.spip.net/@cdata_echappe_retour
556 function cdata_echappe(&$rss, &$echappe_cdata) {
557 $echappe_cdata = array();
558 if (preg_match_all(',<!\[CDATA\[(.*)]]>,Uims', $rss,
559 $regs, PREG_SET_ORDER
)) {
560 foreach ($regs as $n => $reg) {
561 if (strpos($reg[1],'<')!==false
562 or strpos($reg[1],'>')!==false) {
563 // verifier que la chaine est encore dans le flux, car on peut avoir X fois la meme
564 // inutile de (sur)peupler le tableau avec des substitutions identiques
565 if (strpos($rss,$reg[0])!==false){
566 $echappe_cdata["@@@SPIP_CDATA$n@@@"] = $reg[1];
567 $rss = str_replace($reg[0], "@@@SPIP_CDATA$n@@@", $rss);
570 $rss = str_replace($reg[0], $reg[1], $rss);
576 // Retablit le contenu des blocs [[CDATA]] dans une chaine ou un tableau
577 // https://code.spip.net/@cdata_echappe_retour
578 function cdata_echappe_retour(&$x, &$echappe_cdata) {
580 if (strpos($x, '<') !== false){
581 $x = filtrer_entites($x);
583 if (strpos($x, '@@@SPIP_CDATA') !== false){
584 $x = str_replace( array_keys($echappe_cdata), array_values($echappe_cdata), $x);
588 foreach ($x as $k => &$v) {
589 cdata_echappe_retour($v, $echappe_cdata);