[SPIP][PLUGINS] v3.0-->v3.2
[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-2016 *
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'] = $regs[1];
134 } else {
135 if (preg_match(',<link[^>]*[[:space:]]rel=.alternate[^>]*>,Uims',
136 $item, $regs)) {
137 $data['url'] = extraire_attribut($regs[0], 'href');
138 } else {
139 if (preg_match(',<link[^>]*>\s*([^\s]+)\s*</link>,Uims', $item, $regs)) {
140 $data['url'] = $regs[1];
141 } else {
142 if (preg_match(',<link[^>]*>,Uims', $item, $regs)) {
143 $data['url'] = extraire_attribut($regs[0], 'href');
144 } // Aucun link ni guid, mais une enclosure
145 else {
146 if (preg_match(',<enclosure[^>]*>,ims', $item, $regs)
147 and $url = extraire_attribut($regs[0], 'url')
148 ) {
149 $data['url'] = $url;
150 } // pas d'url, c'est genre un compteur...
151 else {
152 $data['url'] = '';
153 }
154 }
155 }
156 }
157 }
158 }
159 }
160
161 // Titre (semi-obligatoire)
162 if (preg_match(",<title[^>]*>(.*?)</title>,ims", $item, $match)) {
163 $data['titre'] = $match[1];
164 } else {
165 if (preg_match(',<link[[:space:]][^>]*>,Uims', $item, $mat)
166 and $title = extraire_attribut($mat[0], 'title')
167 ) {
168 $data['titre'] = $title;
169 }
170 }
171 if (!strlen($data['titre'] = trim($data['titre']))) {
172 $data['titre'] = _T('ecrire:info_sans_titre');
173 }
174
175 // Date
176 $la_date = '';
177 if (preg_match(',<(published|modified|issued)>([^<]*)<,Uims',
178 $item, $match)) {
179 cdata_echappe_retour($match[2], $echappe_cdata);
180 $la_date = my_strtotime($match[2], $langue_du_site);
181 }
182 if (!$la_date and
183 preg_match(',<(pubdate)>([^<]*)<,Uims', $item, $match)
184 ) {
185 cdata_echappe_retour($match[2], $echappe_cdata);
186 $la_date = my_strtotime($match[2], $langue_du_site);
187 }
188 if (!$la_date and
189 preg_match(',<([a-z]+:date)>([^<]*)<,Uims', $item, $match)
190 ) {
191 cdata_echappe_retour($match[2], $echappe_cdata);
192 $la_date = my_strtotime($match[2], $langue_du_site);
193 }
194 if (!$la_date and
195 preg_match(',<date>([^<]*)<,Uims', $item, $match)
196 ) {
197 cdata_echappe_retour($match[1], $echappe_cdata);
198 $la_date = my_strtotime($match[1], $langue_du_site);
199 }
200
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']) {
206 if (!$la_date
207 or $la_date > time() + 48 * 3600
208 ) {
209 $la_date = time();
210 }
211 }
212
213 if ($la_date) {
214 $data['date'] = $la_date;
215 }
216
217 // Honorer le <lastbuilddate> en forcant la date
218 if (preg_match(',<(lastbuilddate|updated|modified)>([^<>]+)</\1>,i',
219 $item, $regs)
220 and $lastbuilddate = my_strtotime(trim($regs[2]), $langue_du_site)
221 // pas dans le futur
222 and $lastbuilddate < time()
223 ) {
224 $data['lastbuilddate'] = $lastbuilddate;
225 }
226
227 // Auteur(s)
228 if (preg_match_all(
229 ',<(author|creator)\b[^>]*>(.*)</\1>,Uims',
230 $item, $regs, PREG_SET_ORDER)) {
231 $auteurs = array();
232 foreach ($regs as $reg) {
233 $nom = $reg[2];
234 if (preg_match(',<name\b[^>]*>(.*)</name>,Uims', $nom, $reg)) {
235 $nom = $reg[1];
236 }
237 // Cas particulier d'un auteur Flickr
238 if (preg_match(',nobody@flickr.com \((.*)\),Uims', $nom, $reg)) {
239 $nom = $reg[1];
240 }
241 $auteurs[] = trim(textebrut(filtrer_entites($nom)));
242 }
243 $data['lesauteurs'] = join(', ', array_unique($auteurs));
244 } else {
245 $data['lesauteurs'] = $les_auteurs_du_site;
246 }
247
248 // Description
249 if (preg_match(',<(description|summary)\b.*'
250 . '>(.*)</\1\b,Uims', $item, $match)) {
251 $data['descriptif'] = trim($match[2]);
252 }
253 if (preg_match(',<(content)\b.*'
254 . '>(.*)</\1\b,Uims', $item, $match)) {
255 $data['content'] = trim($match[2]);
256 }
257
258 // lang
259 if (preg_match(',<([^>]*xml:)?lang(uage)?' . '>([^<>]+)<,i',
260 $item, $match)) {
261 $data['lang'] = trim($match[3]);
262 } else {
263 if ($lang = trim(extraire_attribut($item, 'xml:lang'))) {
264 $data['lang'] = $lang;
265 } else {
266 $data['lang'] = trim($langue_du_site);
267 }
268 }
269
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',
274 $item, $match)) {
275 $data['source'] = trim($match[3]);
276 $data['url_source'] = str_replace('&amp;', '&',
277 trim(extraire_attribut($match[1], 'url')));
278 }
279
280 // tags
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
286 $tags = array();
287 if (preg_match_all(
288 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*>'
289 . '(.*?)</\1>,ims',
290 $item, $matches, PREG_SET_ORDER)) {
291 $tags = ajouter_tags($matches, $item);
292 } # array()
293 elseif (preg_match_all(
294 ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*/>'
295 . ',ims',
296 $item, $matches, PREG_SET_ORDER)) {
297 $tags = ajouter_tags($matches, $item);
298 } # array()
299 // Pieces jointes :
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();
306 # rss 2
307 if (preg_match_all(',<enclosure[[:space:]][^<>]+>,i',
308 $item, $matches, PREG_PATTERN_ORDER)) {
309 $enclosures += array_map('enclosure2microformat', $matches[0]);
310 }
311 # atom
312 if (preg_match_all(',<link\b[^<>]+rel=["\']?enclosure["\']?[^<>]+>,i',
313 $item, $matches, PREG_PATTERN_ORDER)) {
314 $enclosures += array_map('enclosure2microformat', $matches[0]);
315 }
316 # media rss
317 if (preg_match_all(',<media:content\b[^<>]+>,i',
318 $item, $matches, PREG_PATTERN_ORDER)) {
319 $enclosures += array_map('enclosure2microformat', $matches[0]);
320 }
321 $data['enclosures'] = join(', ', array_unique($enclosures));
322 unset($enclosures);
323 }
324 $data['item'] = $item;
325
326 // Nettoyer les donnees et remettre les CDATA en place
327 cdata_echappe_retour($data, $echappe_cdata);
328 cdata_echappe_retour($tags, $echappe_cdata);
329
330 // passer l'url en absolue
331 $data['url'] = url_absolue(filtrer_entites($data['url']), $url_syndic);
332
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);
340 if (!$res) {
341 break;
342 } // c'est pas bon signe car on a pas trouve l'URL...
343 if (is_array($res)) {
344 break;
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
347 }
348 // ici $target est l'URL finale de la page
349 $data['url'] = $target;
350 }
351
352 // Trouver les microformats (ecrase les <category> et <dc:subject>)
353 if (preg_match_all(
354 ',<a[[:space:]]([^>]+[[:space:]])?rel=[^>]+>.*</a>,Uims',
355 $data['item'], $regs, PREG_PATTERN_ORDER)) {
356 $tags = $regs[0];
357 }
358 // Cas particulier : tags Connotea sous la forme <a class="postedtag">
359 if (preg_match_all(
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]);
364 }
365
366 $data['tags'] = $tags;
367 // enlever le html des titre pour etre homogene avec les autres objets spip
368 $data['titre'] = textebrut($data['titre']);
369
370 $articles[] = $data;
371 }
372
373 return $articles;
374 }
375
376
377 /**
378 * Strtotime même avec le format W3C !
379 *
380 * Car hélàs, strtotime ne le reconnait pas tout seul !
381 *
382 * @link http://www.w3.org/TR/NOTE-datetime Format datetime du W3C
383 *
384 * @param string $la_date
385 * Date à parser
386 * @return int
387 * Timestamp
388 **/
389 function my_strtotime($la_date, $lang = null) {
390 // format complet
391 if (preg_match(
392 ',^(\d+-\d+-\d+[T ]\d+:\d+(:\d+)?)(\.\d+)?'
393 . '(Z|([-+]\d{2}):\d+)?$,',
394 $la_date, $match)) {
395 $match = array_pad($match, 6, null);
396 $la_date = str_replace("T", " ", $match[1]) . " GMT";
397
398 return strtotime($la_date) - intval($match[5]) * 3600;
399 }
400
401 // YYYY
402 if (preg_match(',^\d{4}$,', $la_date, $match)) {
403 return strtotime($match[0] . "-01-01");
404 }
405
406 // YYYY-MM
407 if (preg_match(',^\d{4}-\d{2}$,', $la_date, $match)) {
408 return strtotime($match[0] . "-01");
409 }
410
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]);
414 }
415
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)
423 ) {
424 return $s;
425 }
426
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
429 if ($lang) {
430 // "fr-fr"
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"));
442 }
443 changer_langue($prev_lang);
444 }
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)) {
450 return $s;
451 }
452 }
453 }
454 }
455
456 // erreur
457 spip_log("Impossible de lire le format de date '$la_date'");
458
459 return false;
460 }
461
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))) {
467 return '';
468 }
469 $mot = "<a rel=\"tag\">$mot</a>";
470 if ($url) {
471 $mot = inserer_attribut($mot, 'href', $url);
472 }
473 if ($type) {
474 $mot = inserer_attribut($mot, 'rel', $type);
475 }
476
477 return $mot;
478 }
479
480
481 // https://code.spip.net/@ajouter_tags
482 function ajouter_tags($matches, $item) {
483 include_spip('inc/filtres');
484 $tags = array();
485 foreach ($matches as $match) {
486 $type = ($match[3] == 'category' or $match[3] == 'directory')
487 ? 'directory' : 'tag';
488 $mot = supprimer_tags($match[0]);
489 if (!strlen($mot)
490 and !strlen($mot = extraire_attribut($match[0], 'label'))
491 ) {
492 break;
493 }
494 // rechercher un url
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);
502 }
503 } else {
504 if ($url = extraire_attribut($match[0], 'resource')
505 or $url = extraire_attribut($match[0], 'url')
506 ) {
507 } ## cas particuliers
508 else {
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) . '/')
513 ) {
514 $tags[] = $t;
515 }
516 }
517 $mot = '';
518 } else {
519 if (
520 // cas atom1, a faire apres flickr
521 $term = extraire_attribut($match[0], 'term')
522 ) {
523 if ($scheme = extraire_attribut($match[0], 'scheme')) {
524 $url = suivre_lien($scheme, $term);
525 } else {
526 $url = $term;
527 }
528 } else {
529 # type delicious.com
530 foreach (explode(' ', $mot) as $petit) {
531 if (preg_match(',<rdf\b[^>]*\bresource=["\']([^>]*/'
532 . preg_quote(rawurlencode($petit), ',') . ')["\'],i',
533 $item, $m)) {
534 $mot = '';
535 if ($t = creer_tag($petit, $type, $m[1])) {
536 $tags[] = $t;
537 }
538 }
539 }
540 }
541 }
542 }
543 }
544
545 if ($t = creer_tag($mot, $type, $url)) {
546 $tags[] = $t;
547 }
548 }
549
550 return $tags;
551 }
552
553
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);
568 }
569 } else {
570 $rss = str_replace($reg[0], $reg[1], $rss);
571 }
572 }
573 }
574 }
575
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) {
579 if (is_string($x)) {
580 if (strpos($x, '&lt;') !== false){
581 $x = filtrer_entites($x);
582 }
583 if (strpos($x, '@@@SPIP_CDATA') !== false){
584 $x = str_replace( array_keys($echappe_cdata), array_values($echappe_cdata), $x);
585 }
586 } else {
587 if (is_array($x)) {
588 foreach ($x as $k => &$v) {
589 cdata_echappe_retour($v, $echappe_cdata);
590 }
591 }
592 }
593 }