5e0960dfa1e807b14a0f91f77d02ff48e21aa885
[lhc/web/www.git] / www / plugins-dist / sites / inc / syndic.php
1 <?php
2
3 /***************************************************************************\
4 * SPIP, Systeme de publication pour l'internet *
5 * *
6 * Copyright (c) 2001-2020 *
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 /**
14 * Gestion de syndication (RSS,...)
15 *
16 * @package SPIP\Sites\Syndication
17 **/
18
19 if (!defined("_ECRIRE_INC_VERSION")) {
20 return;
21 }
22
23 // ATTENTION
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');
29
30
31 /**
32 * Analyse un texte de backend
33 *
34 * @param string $rss
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
41 **/
42 function analyser_backend($rss, $url_syndic = '') {
43 include_spip('inc/texte'); # pour couper()
44
45 $rss = pipeline('pre_syndication', $rss);
46
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);
50 }
51
52 // Echapper les CDATA
53 cdata_echappe($rss, $echappe_cdata);
54
55 // supprimer les commentaires
56 $rss = preg_replace(',<!--.*-->,Ums', '', $rss);
57
58 // simplifier le backend, en supprimant les espaces de nommage type "dc:"
59 $rss = preg_replace(',<(/?)(dc):,i', '<\1', $rss);
60
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);
63 if (preg_match_all(
64 ',<(author|creator)\b(.*)</\1>,Uims',
65 $header, $regs, PREG_SET_ORDER)) {
66 $les_auteurs_du_site = array();
67 foreach ($regs as $reg) {
68 $nom = $reg[2];
69 if (preg_match(',<name>(.*)</name>,Uims', $nom, $reg)) {
70 $nom = $reg[1];
71 }
72 $les_auteurs_du_site[] = trim(textebrut(filtrer_entites($nom)));
73 }
74 $les_auteurs_du_site = join(', ', array_unique($les_auteurs_du_site));
75 } else {
76 $les_auteurs_du_site = '';
77 }
78
79 $langue_du_site = '';
80
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'))
84 ) {
85 $langue_du_site = $l;
86 } // atom
87 elseif (preg_match(',<feed\s[^>]*xml:lang=[\'"]([^<>\'"]+)[\'"],i', $header, $match)) {
88 $langue_du_site = $match[1];
89 }
90
91 // Recuperer les blocs item et entry
92 $items = array_merge(extraire_balises($rss, 'item'), extraire_balises($rss, 'entry'));
93
94
95 //
96 // Analyser chaque <item>...</item> du backend et le transformer en tableau
97 //
98
99 if (!count($items)) {
100 return _T('sites:avis_echec_syndication_01');
101 }
102
103 if (!defined('_SYNDICATION_MAX_ITEMS')) define('_SYNDICATION_MAX_ITEMS',1000);
104 $nb_items = 0;
105 foreach ($items as $item) {
106 $data = array();
107 if ($nb_items++>_SYNDICATION_MAX_ITEMS){
108 break;
109 }
110
111 // URL (semi-obligatoire, sert de cle)
112
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
115 // gymnastique
116 if (preg_match(',<guid.*>[[:space:]]*(https?:[^<]*)</guid>,Uims',
117 $item, $regs) and preg_match(',^(true|1)?$,i',
118 extraire_attribut($regs[0], 'ispermalink'))
119 ) {
120 $data['url'] = $regs[1];
121 } // contourner les redirections feedburner
122 else {
123 if (_SYNDICATION_DEREFERENCER_URL
124 and preg_match(',<feedburner:origLink>(.*)<,Uims',
125 $item, $regs)
126 ) {
127 $data['url'] = $regs[1];
128 } // <link>, plus classique
129 else {
130 if (preg_match(
131 ',<link[^>]*[[:space:]]rel=["\']?alternate[^>]*>(.*)</link>,Uims',
132 $item, $regs)) {
133 $data['url'] = trim($regs[1]);
134 // c'est pas impossible d'avoir l'URL dans un href quand meme :)
135 if (empty($data['url'])){
136 $data['url'] = extraire_attribut($regs[0], 'href');
137 }
138 } else {
139 if (preg_match(',<link[^>]*[[:space:]]rel=.alternate[^>]*>,Uims',
140 $item, $regs)) {
141 $data['url'] = extraire_attribut($regs[0], 'href');
142 } else {
143 if (preg_match(',<link[^>]*>\s*([^\s]+)\s*</link>,Uims', $item, $regs)) {
144 $data['url'] = $regs[1];
145 } else {
146 if (preg_match(',<link[^>]*>,Uims', $item, $regs)) {
147 $data['url'] = extraire_attribut($regs[0], 'href');
148 } // Aucun link ni guid, mais une enclosure
149 else {
150 if (preg_match(',<enclosure[^>]*>,ims', $item, $regs)
151 and $url = extraire_attribut($regs[0], 'url')
152 ) {
153 $data['url'] = $url;
154 } // pas d'url, c'est genre un compteur...
155 else {
156 $data['url'] = '';
157 }
158 }
159 }
160 }
161 }
162 }
163 }
164
165 // Titre (semi-obligatoire)
166 if (preg_match(",<title[^>]*>(.*?)</title>,ims", $item, $match)) {
167 $data['titre'] = $match[1];
168 } else {
169 if (preg_match(',<link[[:space:]][^>]*>,Uims', $item, $mat)
170 and $title = extraire_attribut($mat[0], 'title')
171 ) {
172 $data['titre'] = $title;
173 }
174 }
175 if (!strlen($data['titre'] = trim($data['titre']))) {
176 $data['titre'] = _T('ecrire:info_sans_titre');
177 }
178
179 // Date
180 $la_date = '';
181 if (preg_match(',<(published|modified|issued)>([^<]*)<,Uims',
182 $item, $match)) {
183 cdata_echappe_retour($match[2], $echappe_cdata);
184 $la_date = my_strtotime($match[2], $langue_du_site);
185 }
186 if (!$la_date and
187 preg_match(',<(pubdate)>([^<]*)<,Uims', $item, $match)
188 ) {
189 cdata_echappe_retour($match[2], $echappe_cdata);
190 $la_date = my_strtotime($match[2], $langue_du_site);
191 }
192 if (!$la_date and
193 preg_match(',<([a-z]+:date)>([^<]*)<,Uims', $item, $match)
194 ) {
195 cdata_echappe_retour($match[2], $echappe_cdata);
196 $la_date = my_strtotime($match[2], $langue_du_site);
197 }
198 if (!$la_date and
199 preg_match(',<date>([^<]*)<,Uims', $item, $match)
200 ) {
201 cdata_echappe_retour($match[1], $echappe_cdata);
202 $la_date = my_strtotime($match[1], $langue_du_site);
203 }
204
205 // controle de validite de la date
206 // pour eviter qu'un backend errone passe toujours devant
207 // (note: ca pourrait etre defini site par site, mais ca risque d'etre
208 // plus lourd que vraiment utile)
209 if ($GLOBALS['controler_dates_rss']) {
210 if (!$la_date
211 or $la_date > time() + 48 * 3600
212 ) {
213 $la_date = time();
214 }
215 }
216
217 if ($la_date) {
218 $data['date'] = $la_date;
219 }
220
221 // Honorer le <lastbuilddate> en forcant la date
222 if (preg_match(',<(lastbuilddate|updated|modified)>([^<>]+)</\1>,i',
223 $item, $regs)
224 and $lastbuilddate = my_strtotime(trim($regs[2]), $langue_du_site)
225 // pas dans le futur
226 and $lastbuilddate < time()
227 ) {
228 $data['lastbuilddate'] = $lastbuilddate;
229 }
230
231 // Auteur(s)
232 if (preg_match_all(
233 ',<(author|creator)\b[^>]*>(.*)</\1>,Uims',
234 $item, $regs, PREG_SET_ORDER)) {
235 $auteurs = array();
236 foreach ($regs as $reg) {
237 $nom = $reg[2];
238 if (preg_match(',<name\b[^>]*>(.*)</name>,Uims', $nom, $reg)) {
239 $nom = $reg[1];
240 }
241 // Cas particulier d'un auteur Flickr
242 if (preg_match(',nobody@flickr.com \((.*)\),Uims', $nom, $reg)) {
243 $nom = $reg[1];
244 }
245 $auteurs[] = trim(textebrut(filtrer_entites($nom)));
246 }
247 $data['lesauteurs'] = join(', ', array_unique($auteurs));
248 } else {
249 $data['lesauteurs'] = $les_auteurs_du_site;
250 }
251
252 // Description
253 if (preg_match(',<(description|summary)\b.*'
254 . '>(.*)</\1\b,Uims', $item, $match)) {
255 $data['descriptif'] = trim($match[2]);
256 }
257 if (preg_match(',<(content)\b.*'
258 . '>(.*)</\1\b,Uims', $item, $match)) {
259 $data['content'] = trim($match[2]);
260 }
261
262 // lang
263 if (preg_match(',<([^>]*xml:)?lang(uage)?' . '>([^<>]+)<,i',
264 $item, $match)) {
265 $data['lang'] = trim($match[3]);
266 } else {
267 if ($lang = trim(extraire_attribut($item, 'xml:lang'))) {
268 $data['lang'] = $lang;
269 } else {
270 $data['lang'] = trim($langue_du_site);
271 }
272 }
273
274 // source et url_source (pas trouve d'exemple en ligne !!)
275 # <source url="http://www.truc.net/music/uatsap.mp3" length="19917" />
276 # <source url="http://www.truc.net/rss">Site source</source>
277 if (preg_match(',(<source[^>]*>)(([^<>]+)</source>)?,i',
278 $item, $match)) {
279 $data['source'] = trim($match[3]);
280 $data['url_source'] = str_replace('&amp;', '&',
281 trim(extraire_attribut($match[1], 'url')));
282 }
283
284 // GitHub : Identification du commit
285 if (preg_match(',<id>[^/]+/(\w+)</id>,Uims', $item, $regs)) {
286 $data['id_commit'] = $regs[1];
287 }
288
289 // tags
290 # a partir de "<dc:subject>", (del.icio.us)
291 # ou <media:category> (flickr)
292 # ou <itunes:category> (apple)
293 # on cree nos tags microformat <a rel="directory" href="url">titre</a>
294 # http://microformats.org/wiki/rel-directory-fr
295 $tags = array();
296 if (preg_match_all(
297 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*>'
298 . '(.*?)</\1>,ims',
299 $item, $matches, PREG_SET_ORDER)) {
300 $tags = ajouter_tags($matches, $item);
301 } # array()
302 elseif (preg_match_all(
303 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*/>'
304 . ',ims',
305 $item, $matches, PREG_SET_ORDER)) {
306 $tags = ajouter_tags($matches, $item);
307 } # array()
308 // Pieces jointes :
309 // chercher <enclosure> au format RSS et les passer en microformat
310 // ou des microformats relEnclosure,
311 // ou encore les media:content
312 if (!afficher_enclosures(join(', ', $tags))) {
313 // on prend toutes les pièces jointes possibles, et on essaie de les rendre uniques.
314 $enclosures = array();
315 # rss 2
316 if (preg_match_all(',<enclosure[[:space:]][^<>]+>,i',
317 $item, $matches, PREG_PATTERN_ORDER)) {
318 $enclosures += array_map('enclosure2microformat', $matches[0]);
319 }
320 # atom
321 if (preg_match_all(',<link\b[^<>]+rel=["\']?enclosure["\']?[^<>]+>,i',
322 $item, $matches, PREG_PATTERN_ORDER)) {
323 $enclosures += array_map('enclosure2microformat', $matches[0]);
324 }
325 # media rss
326 if (preg_match_all(',<media:content\b[^<>]+>,i',
327 $item, $matches, PREG_PATTERN_ORDER)) {
328 $enclosures += array_map('enclosure2microformat', $matches[0]);
329 }
330 $data['enclosures'] = join(', ', array_unique($enclosures));
331 unset($enclosures);
332 }
333 $data['item'] = $item;
334
335 // Nettoyer les donnees et remettre les CDATA en place
336 cdata_echappe_retour($data, $echappe_cdata);
337 cdata_echappe_retour($tags, $echappe_cdata);
338
339 // passer l'url en absolue
340 $data['url'] = url_absolue(filtrer_entites($data['url']), $url_syndic);
341
342 // si on demande un dereferencement de l'URL, il faut verifier que ce n'est pas une redirection
343 if (_SYNDICATION_DEREFERENCER_URL) {
344 $target = $data['url'];
345 include_spip("inc/distant");
346 for ($i = 0; $i < 10; $i++) {
347 // 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
348 $res = recuperer_lapage($target, false, "GET", 4096);
349 if (!$res) {
350 break;
351 } // c'est pas bon signe car on a pas trouve l'URL...
352 if (is_array($res)) {
353 break;
354 } // on a trouve la page, donc on a l'URL finale
355 $target = $res; // c'est une redirection, on la suit pour voir ou elle mene
356 }
357 // ici $target est l'URL finale de la page
358 $data['url'] = $target;
359 }
360
361 // Trouver les microformats (ecrase les <category> et <dc:subject>)
362 if (preg_match_all(
363 ',<a[[:space:]]([^>]+[[:space:]])?rel=[^>]+>.*</a>,Uims',
364 $data['item'], $regs, PREG_PATTERN_ORDER)) {
365 $tags = $regs[0];
366 }
367 // Cas particulier : tags Connotea sous la forme <a class="postedtag">
368 if (preg_match_all(
369 ',<a[[:space:]][^>]+ class="postedtag"[^>]*>.*</a>,Uims',
370 $data['item'], $regs, PREG_PATTERN_ORDER)) {
371 $tags = preg_replace(', class="postedtag",i',
372 ' rel="tag"', $regs[0]);
373 }
374
375 $data['tags'] = $tags;
376 // enlever le html des titre pour etre homogene avec les autres objets spip
377 $data['titre'] = textebrut($data['titre']);
378
379 $articles[] = $data;
380 }
381
382 return $articles;
383 }
384
385
386 /**
387 * Strtotime même avec le format W3C !
388 *
389 * Car hélàs, strtotime ne le reconnait pas tout seul !
390 *
391 * @link http://www.w3.org/TR/NOTE-datetime Format datetime du W3C
392 *
393 * @param string $la_date
394 * Date à parser
395 * @return int
396 * Timestamp
397 **/
398 function my_strtotime($la_date, $lang = null) {
399 // format complet
400 if (preg_match(
401 ',^(\d+-\d+-\d+[T ]\d+:\d+(:\d+)?)(\.\d+)?'
402 . '(Z|([-+]\d{2}):\d+)?$,',
403 $la_date, $match)) {
404 $match = array_pad($match, 6, null);
405 $la_date = str_replace("T", " ", $match[1]) . " GMT";
406
407 return strtotime($la_date) - intval($match[5]) * 3600;
408 }
409
410 // YYYY
411 if (preg_match(',^\d{4}$,', $la_date, $match)) {
412 return strtotime($match[0] . "-01-01");
413 }
414
415 // YYYY-MM
416 if (preg_match(',^\d{4}-\d{2}$,', $la_date, $match)) {
417 return strtotime($match[0] . "-01");
418 }
419
420 // YYYY-MM-DD hh:mm:ss
421 if (preg_match(',^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\b,', $la_date, $match)) {
422 return strtotime($match[0]);
423 }
424
425 // utiliser strtotime en dernier ressort
426 // en nettoyant le jour qui prefixe parfois la date, suivi d'une virgule
427 // et les UT qui sont en fait des UTC
428 $la_date_c = preg_replace("/^\w+,\s*/ms", "", $la_date);
429 $la_date_c = preg_replace("/UT\s*$/ms", "UTC", $la_date_c);
430 if ($s = strtotime($la_date)
431 or $s = strtotime($la_date_c)
432 ) {
433 return $s;
434 }
435
436 // essayons de voir si le nom du mois est dans la langue du flux et remplacons le
437 // par la version anglaise avant de faire strtotime
438 if ($lang) {
439 // "fr-fr"
440 list($lang) = explode("-", $lang);
441 static $months = null;
442 if (!isset($months[$lang])) {
443 $prev_lang = $GLOBALS['spip_lang'];
444 changer_langue($lang);
445 foreach (range(1, 12) as $m) {
446 $s = _T("date_mois_$m");
447 $months[$lang][$s] = date("M", strtotime("2013-$m-01"));
448 $s = _T("date_mois_" . $m . "_abbr");
449 $months[$lang][$s] = date("M", strtotime("2013-$m-01"));
450 $months[$lang][trim($s, ".")] = date("M", strtotime("2013-$m-01"));
451 }
452 changer_langue($prev_lang);
453 }
454 spip_log($la_date_c, "dbgs");
455 foreach ($months[$lang] as $loc => $en) {
456 if (stripos($la_date_c, $loc) !== false) {
457 $s = str_ireplace($loc, $en, $la_date_c);
458 if ($s = strtotime($s)) {
459 return $s;
460 }
461 }
462 }
463 }
464
465 // erreur
466 spip_log("Impossible de lire le format de date '$la_date'");
467
468 return false;
469 }
470
471 // A partir d'un <dc:subject> ou autre essayer de recuperer
472 // le mot et son url ; on cree <a href="url" rel="tag">mot</a>
473 // https://code.spip.net/@creer_tag
474 function creer_tag($mot, $type, $url) {
475 if (!strlen($mot = trim($mot))) {
476 return '';
477 }
478 $mot = "<a rel=\"tag\">$mot</a>";
479 if ($url) {
480 $mot = inserer_attribut($mot, 'href', $url);
481 }
482 if ($type) {
483 $mot = inserer_attribut($mot, 'rel', $type);
484 }
485
486 return $mot;
487 }
488
489
490 // https://code.spip.net/@ajouter_tags
491 function ajouter_tags($matches, $item) {
492 include_spip('inc/filtres');
493 $tags = array();
494 foreach ($matches as $match) {
495 $type = ($match[3] == 'category' or $match[3] == 'directory')
496 ? 'directory' : 'tag';
497 $mot = supprimer_tags($match[0]);
498 if (!strlen($mot)
499 and !strlen($mot = extraire_attribut($match[0], 'label'))
500 ) {
501 break;
502 }
503 // rechercher un url
504 if ($url = extraire_attribut($match[0], 'domain')) {
505 // category@domain est la racine d'une url qui se prolonge
506 // avec le contenu text du tag <category> ; mais dans SPIP < 2.0
507 // on donnait category@domain = #URL_RUBRIQUE, et
508 // text = #TITRE_RUBRIQUE ; d'ou l'heuristique suivante sur le slash
509 if (substr($url, -1) == '/') {
510 $url .= rawurlencode($mot);
511 }
512 } else {
513 if ($url = extraire_attribut($match[0], 'resource')
514 or $url = extraire_attribut($match[0], 'url')
515 ) {
516 } ## cas particuliers
517 else {
518 if (extraire_attribut($match[0], 'scheme') == 'urn:flickr:tags') {
519 foreach (explode(' ', $mot) as $petit) {
520 if ($t = creer_tag($petit, $type,
521 'http://www.flickr.com/photos/tags/' . rawurlencode($petit) . '/')
522 ) {
523 $tags[] = $t;
524 }
525 }
526 $mot = '';
527 } else {
528 if (
529 // cas atom1, a faire apres flickr
530 $term = extraire_attribut($match[0], 'term')
531 ) {
532 if ($scheme = extraire_attribut($match[0], 'scheme')) {
533 $url = suivre_lien($scheme, $term);
534 } else {
535 $url = $term;
536 }
537 } else {
538 # type delicious.com
539 foreach (explode(' ', $mot) as $petit) {
540 if (preg_match(',<rdf\b[^>]*\bresource=["\']([^>]*/'
541 . preg_quote(rawurlencode($petit), ',') . ')["\'],i',
542 $item, $m)) {
543 $mot = '';
544 if ($t = creer_tag($petit, $type, $m[1])) {
545 $tags[] = $t;
546 }
547 }
548 }
549 }
550 }
551 }
552 }
553
554 if ($t = creer_tag($mot, $type, $url)) {
555 $tags[] = $t;
556 }
557 }
558
559 return $tags;
560 }
561
562
563 // Lit contenu des blocs [[CDATA]] dans un flux
564 // https://code.spip.net/@cdata_echappe_retour
565 function cdata_echappe(&$rss, &$echappe_cdata) {
566 $echappe_cdata = array();
567 if (preg_match_all(',<!\[CDATA\[(.*)]]>,Uims', $rss,
568 $regs, PREG_SET_ORDER)) {
569 foreach ($regs as $n => $reg) {
570 if (strpos($reg[1],'<')!==false
571 or strpos($reg[1],'>')!==false) {
572 // verifier que la chaine est encore dans le flux, car on peut avoir X fois la meme
573 // inutile de (sur)peupler le tableau avec des substitutions identiques
574 if (strpos($rss,$reg[0])!==false){
575 $echappe_cdata["@@@SPIP_CDATA$n@@@"] = $reg[1];
576 $rss = str_replace($reg[0], "@@@SPIP_CDATA$n@@@", $rss);
577 }
578 } else {
579 $rss = str_replace($reg[0], $reg[1], $rss);
580 }
581 }
582 }
583 }
584
585 // Retablit le contenu des blocs [[CDATA]] dans une chaine ou un tableau
586 // https://code.spip.net/@cdata_echappe_retour
587 function cdata_echappe_retour(&$x, &$echappe_cdata) {
588 if (is_string($x)) {
589 if (strpos($x, '&lt;') !== false){
590 $x = filtrer_entites($x);
591 }
592 if (strpos($x, '@@@SPIP_CDATA') !== false){
593 $x = str_replace( array_keys($echappe_cdata), array_values($echappe_cdata), $x);
594 }
595 } else {
596 if (is_array($x)) {
597 foreach ($x as $k => &$v) {
598 cdata_echappe_retour($v, $echappe_cdata);
599 }
600 }
601 }
602 }