PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/spip/ecrire/inc/syndic.php

https://github.com/eyeswebcrea/espace-couture-sittler.fr
PHP | 401 lines | 264 code | 50 blank | 87 comment | 74 complexity | d22a056ff9aa77eb349fb3d15e2795b3 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-3.0
  1. <?php
  2. /***************************************************************************\
  3. * SPIP, Systeme de publication pour l'internet *
  4. * *
  5. * Copyright (c) 2001-2011 *
  6. * Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James *
  7. * *
  8. * Ce programme est un logiciel libre distribue sous licence GNU/GPL. *
  9. * Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. *
  10. \***************************************************************************/
  11. if (!defined('_ECRIRE_INC_VERSION')) return;
  12. // ATTENTION
  13. // Cette inclusion charge executer_une_syndication pour compatibilite,
  14. // mais cette fonction ne doit plus etre invoquee directement:
  15. // il faut passer par cron() pour avoir un verrou portable
  16. // Voir un exemple dans action/editer/site
  17. include_spip('genie/syndic');
  18. // prend un fichier backend et retourne un tableau des items lus,
  19. // et une chaine en cas d'erreur
  20. // http://doc.spip.org/@analyser_backend
  21. function analyser_backend($rss, $url_syndic='') {
  22. include_spip('inc/texte'); # pour couper()
  23. $rss = pipeline('pre_syndication', $rss);
  24. // si true, les URLs de type feedburner sont dereferencees
  25. define('_SYNDICATION_DEREFERENCER_URL', false);
  26. // Echapper les CDATA
  27. $echappe_cdata = array();
  28. if (preg_match_all(',<!\[CDATA\[(.*)]]>,Uims', $rss,
  29. $regs, PREG_SET_ORDER)) {
  30. foreach ($regs as $n => $reg) {
  31. $echappe_cdata[$n] = $reg[1];
  32. $rss = str_replace($reg[0], "@@@SPIP_CDATA$n@@@", $rss);
  33. }
  34. }
  35. // supprimer les commentaires
  36. $rss = preg_replace(',<!--.*-->,Ums', '', $rss);
  37. // simplifier le backend, en supprimant les espaces de nommage type "dc:"
  38. $rss = preg_replace(',<(/?)(dc):,i', '<\1', $rss);
  39. // chercher auteur/lang dans le fil au cas ou les items n'en auraient pas
  40. list($header) = preg_split(',<(item|entry)\b,', $rss, 2);
  41. if (preg_match_all(
  42. ',<(author|creator)\b(.*)</\1>,Uims',
  43. $header, $regs, PREG_SET_ORDER)) {
  44. $les_auteurs_du_site = array();
  45. foreach ($regs as $reg) {
  46. $nom = $reg[2];
  47. if (preg_match(',<name>(.*)</name>,Uims', $nom, $reg))
  48. $nom = $reg[1];
  49. $les_auteurs_du_site[] = trim(textebrut(filtrer_entites($nom)));
  50. }
  51. $les_auteurs_du_site = join(', ', array_unique($les_auteurs_du_site));
  52. } else
  53. $les_auteurs_du_site = '';
  54. if (preg_match(',<([^>]*xml[:])?lang(uage)?'.'>([^<>]+)<,i', $header, $match))
  55. $langue_du_site = $match[3];
  56. // atom
  57. elseif (preg_match(',<feed\s[^>]*xml:lang=[\'"]([^<>\'"]+)[\'"],i', $header, $match))
  58. $langue_du_site = $match[1];
  59. // Attention en PCRE 6.7 preg_match_all casse sur un backend avec de gros <content:encoded>
  60. $items = preg_split(',<(item|entry)\b.*>,Uims', $rss);
  61. array_shift($items);
  62. foreach ($items as $k=>$item)
  63. $items[$k] = preg_replace(',</(item|entry)\b.*>.*$,UimsS', '', $item);
  64. //
  65. // Analyser chaque <item>...</item> du backend et le transformer en tableau
  66. //
  67. if (!count($items)) return _T('avis_echec_syndication_01');
  68. foreach ($items as $item) {
  69. $data = array();
  70. // URL (semi-obligatoire, sert de cle)
  71. // guid n'est un URL que si marque de <guid ispermalink="true"> ;
  72. // attention la valeur par defaut est 'true' ce qui oblige a quelque
  73. // gymnastique
  74. if (preg_match(',<guid.*>[[:space:]]*(https?:[^<]*)</guid>,Uims',
  75. $item, $regs) AND preg_match(',^(true|1)?$,i',
  76. extraire_attribut($regs[0], 'ispermalink')))
  77. $data['url'] = $regs[1];
  78. // contourner les redirections feedburner
  79. else if (_SYNDICATION_DEREFERENCER_URL
  80. AND preg_match(',<feedburner:origLink>(.*)<,Uims',
  81. $item, $regs))
  82. $data['url'] = $regs[1];
  83. // <link>, plus classique
  84. else if (preg_match(
  85. ',<link[^>]*[[:space:]]rel=["\']?alternate[^>]*>(.*)</link>,Uims',
  86. $item, $regs))
  87. $data['url'] = $regs[1];
  88. else if (preg_match(',<link[^>]*[[:space:]]rel=.alternate[^>]*>,Uims',
  89. $item, $regs))
  90. $data['url'] = extraire_attribut($regs[0], 'href');
  91. else if (preg_match(',<link[^>]*>(.*)</link>,Uims', $item, $regs))
  92. $data['url'] = $regs[1];
  93. else if (preg_match(',<link[^>]*>,Uims', $item, $regs))
  94. $data['url'] = extraire_attribut($regs[0], 'href');
  95. // Aucun link ni guid, mais une enclosure
  96. else if (preg_match(',<enclosure[^>]*>,ims', $item, $regs)
  97. AND $url = extraire_attribut($regs[0], 'url'))
  98. $data['url'] = $url;
  99. // pas d'url, c'est genre un compteur...
  100. else
  101. $data['url'] = '';
  102. // Titre (semi-obligatoire)
  103. if (preg_match(",<title[^>]*>(.*?)</title>,ims",$item,$match))
  104. $data['titre'] = $match[1];
  105. else if (preg_match(',<link[[:space:]][^>]*>,Uims',$item,$mat)
  106. AND $title = extraire_attribut($mat[0], 'title'))
  107. $data['titre'] = $title;
  108. if (!strlen($data['titre'] = trim($data['titre'])))
  109. $data['titre'] = _T('ecrire:info_sans_titre');
  110. // Date
  111. $la_date = '';
  112. if (preg_match(',<(published|modified|issued)>([^<]*)<,Uims',
  113. $item,$match))
  114. $la_date = my_strtotime($match[2]);
  115. if (!$la_date AND
  116. preg_match(',<(pubdate)>([^<]*)<,Uims',$item, $match))
  117. $la_date = my_strtotime($match[2]);
  118. if (!$la_date AND
  119. preg_match(',<([a-z]+:date)>([^<]*)<,Uims',$item,$match))
  120. $la_date = my_strtotime($match[2]);
  121. if (!$la_date AND
  122. preg_match(',<date>([^<]*)<,Uims',$item,$match))
  123. $la_date = my_strtotime($match[1]);
  124. // controle de validite de la date
  125. // pour eviter qu'un backend errone passe toujours devant
  126. // (note: ca pourrait etre defini site par site, mais ca risque d'etre
  127. // plus lourd que vraiment utile)
  128. if ($GLOBALS['controler_dates_rss']) {
  129. if ($la_date > time() + 48 * 3600)
  130. $la_date = time();
  131. }
  132. $data['date'] = $la_date;
  133. // Honorer le <lastbuilddate> en forcant la date
  134. if (preg_match(',<(lastbuilddate|updated|modified)>([^<>]+)</\1>,i',
  135. $item, $regs)
  136. AND $lastbuilddate = my_strtotime(trim($regs[2]))
  137. // pas dans le futur
  138. AND $lastbuilddate < time())
  139. $data['lastbuilddate'] = $lastbuilddate;
  140. // Auteur(s)
  141. if (preg_match_all(
  142. ',<(author|creator)>(.*)</\1>,Uims',
  143. $item, $regs, PREG_SET_ORDER)) {
  144. $auteurs = array();
  145. foreach ($regs as $reg) {
  146. $nom = $reg[2];
  147. if (preg_match(',<name>(.*)</name>,Uims', $nom, $reg))
  148. $nom = $reg[1];
  149. $auteurs[] = trim(textebrut(filtrer_entites($nom)));
  150. }
  151. $data['lesauteurs'] = join(', ', array_unique($auteurs));
  152. }
  153. else
  154. $data['lesauteurs'] = $les_auteurs_du_site;
  155. // Description
  156. if (preg_match(',<(description|summary)\b.*'
  157. .'>(.*)</\1\b,Uims',$item,$match)) {
  158. $data['descriptif'] = trim($match[2]);
  159. }
  160. if (preg_match(',<(content)\b.*'
  161. .'>(.*)</\1\b,Uims',$item,$match)) {
  162. $data['content'] = trim($match[2]);
  163. }
  164. // lang
  165. if (preg_match(',<([^>]*xml:)?lang(uage)?'.'>([^<>]+)<,i',
  166. $item, $match))
  167. $data['lang'] = trim($match[3]);
  168. else if ($lang = trim(extraire_attribut($item, 'xml:lang')))
  169. $data['lang'] = $lang;
  170. else
  171. $data['lang'] = trim($langue_du_site);
  172. // source et url_source (pas trouve d'exemple en ligne !!)
  173. # <source url="http://www.truc.net/music/uatsap.mp3" length="19917" />
  174. # <source url="http://www.truc.net/rss">Site source</source>
  175. if (preg_match(',(<source[^>]*>)(([^<>]+)</source>)?,i',
  176. $item, $match)) {
  177. $data['source'] = trim($match[3]);
  178. $data['url_source'] = str_replace('&amp;', '&',
  179. trim(extraire_attribut($match[1], 'url')));
  180. }
  181. // tags
  182. # a partir de "<dc:subject>", (del.icio.us)
  183. # ou <media:category> (flickr)
  184. # ou <itunes:category> (apple)
  185. # on cree nos tags microformat <a rel="directory" href="url">titre</a>
  186. # http://microformats.org/wiki/rel-directory-fr
  187. $tags = array();
  188. if (preg_match_all(
  189. ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*>'
  190. .'(.*?)</\1>,ims',
  191. $item, $matches, PREG_SET_ORDER))
  192. $tags = ajouter_tags($matches, $item); # array()
  193. elseif (preg_match_all(
  194. ',<(([a-z]+:)?(subject|category|directory|keywords?|tags?|type))[^>]*/>'
  195. .',ims',
  196. $item, $matches, PREG_SET_ORDER))
  197. $tags = ajouter_tags($matches, $item); # array()
  198. // Pieces jointes :
  199. // chercher <enclosure> au format RSS et les passer en microformat
  200. // ou des microformats relEnclosure,
  201. // ou encore les media:content
  202. if (!afficher_enclosures(join(', ', $tags))) {
  203. if (preg_match_all(',<enclosure[[:space:]][^<>]+>,i',
  204. $item, $matches, PREG_PATTERN_ORDER))
  205. $data['enclosures'] = join(', ',
  206. array_map('enclosure2microformat', $matches[0]));
  207. else if (
  208. preg_match_all(',<link\b[^<>]+rel=["\']?enclosure["\']?[^<>]+>,i',
  209. $item, $matches, PREG_PATTERN_ORDER))
  210. $data['enclosures'] = join(', ',
  211. array_map('enclosure2microformat', $matches[0]));
  212. else if (
  213. preg_match_all(',<media:content\b[^<>]+>,i',
  214. $item, $matches, PREG_PATTERN_ORDER))
  215. $data['enclosures'] = join(', ',
  216. array_map('enclosure2microformat', $matches[0]));
  217. }
  218. $data['item'] = $item;
  219. // Nettoyer les donnees et remettre les CDATA en place
  220. cdata_echappe_retour($data, $echappe_cdata);
  221. cdata_echappe_retour($tags, $echappe_cdata);
  222. // passer l'url en absolue
  223. $data['url'] = url_absolue(filtrer_entites($data['url']), $url_syndic);
  224. // Trouver les microformats (ecrase les <category> et <dc:subject>)
  225. if (preg_match_all(
  226. ',<a[[:space:]]([^>]+[[:space:]])?rel=[^>]+>.*</a>,Uims',
  227. $data['item'], $regs, PREG_PATTERN_ORDER)) {
  228. $tags = $regs[0];
  229. }
  230. // Cas particulier : tags Connotea sous la forme <a class="postedtag">
  231. if (preg_match_all(
  232. ',<a[[:space:]][^>]+ class="postedtag"[^>]*>.*</a>,Uims',
  233. $data['item'], $regs, PREG_PATTERN_ORDER))
  234. $tags = preg_replace(', class="postedtag",i',
  235. ' rel="tag"', $regs[0]);
  236. $data['tags'] = $tags;
  237. // enlever le html des titre pour etre homogene avec les autres objets spip
  238. $data['titre'] = textebrut($data['titre']);
  239. $articles[] = $data;
  240. }
  241. return $articles;
  242. }
  243. // helas strtotime ne reconnait pas le format W3C
  244. // http://www.w3.org/TR/NOTE-datetime
  245. // http://doc.spip.org/@my_strtotime
  246. function my_strtotime($la_date) {
  247. // format complet
  248. if (preg_match(
  249. ',^(\d+-\d+-\d+[T ]\d+:\d+(:\d+)?)(\.\d+)?'
  250. .'(Z|([-+]\d{2}):\d+)?$,',
  251. $la_date, $match)) {
  252. $la_date = str_replace("T", " ", $match[1])." GMT";
  253. return strtotime($la_date) - intval($match[5]) * 3600;
  254. }
  255. // YYYY
  256. if (preg_match(',^\d{4}$,', $la_date, $match))
  257. return strtotime($match[0]."-01-01");
  258. // YYYY-MM
  259. if (preg_match(',^\d{4}-\d{2}$,', $la_date, $match))
  260. return strtotime($match[0]."-01");
  261. // utiliser strtotime en dernier ressort
  262. $s = strtotime($la_date);
  263. if ($s > 0)
  264. return $s;
  265. // YYYY-MM-DD hh:mm:ss
  266. if (preg_match(',^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\b,', $la_date, $match))
  267. return strtotime($match[0]);
  268. // erreur
  269. spip_log("Impossible de lire le format de date '$la_date'");
  270. return false;
  271. }
  272. // A partir d'un <dc:subject> ou autre essayer de recuperer
  273. // le mot et son url ; on cree <a href="url" rel="tag">mot</a>
  274. // http://doc.spip.org/@creer_tag
  275. function creer_tag($mot,$type,$url) {
  276. if (!strlen($mot = trim($mot))) return '';
  277. $mot = "<a rel=\"tag\">$mot</a>";
  278. if ($url)
  279. $mot = inserer_attribut($mot, 'href', $url);
  280. if ($type)
  281. $mot = inserer_attribut($mot, 'rel', $type);
  282. return $mot;
  283. }
  284. // http://doc.spip.org/@ajouter_tags
  285. function ajouter_tags($matches, $item) {
  286. include_spip('inc/filtres');
  287. $tags = array();
  288. foreach ($matches as $match) {
  289. $type = ($match[3] == 'category' OR $match[3] == 'directory')
  290. ? 'directory':'tag';
  291. $mot = supprimer_tags($match[0]);
  292. if (!strlen($mot)
  293. AND !strlen($mot = extraire_attribut($match[0], 'label')))
  294. break;
  295. // rechercher un url
  296. if ($url = extraire_attribut($match[0], 'domain')) {
  297. // category@domain est la racine d'une url qui se prolonge
  298. // avec le contenu text du tag <category> ; mais dans SPIP < 2.0
  299. // on donnait category@domain = #URL_RUBRIQUE, et
  300. // text = #TITRE_RUBRIQUE ; d'ou l'heuristique suivante sur le slash
  301. if (substr($url, -1) == '/')
  302. $url .= rawurlencode($mot);
  303. }
  304. else if ($url = extraire_attribut($match[0], 'resource')
  305. OR $url = extraire_attribut($match[0], 'url')
  306. )
  307. {}
  308. ## cas particuliers
  309. else if (extraire_attribut($match[0], 'scheme') == 'urn:flickr:tags') {
  310. foreach(explode(' ', $mot) as $petit)
  311. if ($t = creer_tag($petit, $type,
  312. 'http://www.flickr.com/photos/tags/'.rawurlencode($petit).'/'))
  313. $tags[] = $t;
  314. $mot = '';
  315. }
  316. else if (
  317. // cas atom1, a faire apres flickr
  318. $term = extraire_attribut($match[0], 'term')
  319. ) {
  320. if ($scheme = extraire_attribut($match[0], 'scheme'))
  321. $url = suivre_lien($scheme,$term);
  322. else
  323. $url = $term;
  324. }
  325. else {
  326. # type delicious.com
  327. foreach(explode(' ', $mot) as $petit)
  328. if (preg_match(',<rdf\b[^>]*\bresource=["\']([^>]*/'
  329. .preg_quote(rawurlencode($petit),',').')["\'],i',
  330. $item, $m)) {
  331. $mot = '';
  332. if ($t = creer_tag($petit, $type, $m[1]))
  333. $tags[] = $t;
  334. }
  335. }
  336. if ($t = creer_tag($mot, $type, $url))
  337. $tags[] = $t;
  338. }
  339. return $tags;
  340. }
  341. // Retablit le contenu des blocs [[CDATA]] dans un tableau
  342. // http://doc.spip.org/@cdata_echappe_retour
  343. function cdata_echappe_retour(&$table, &$echappe_cdata) {
  344. foreach ($table as $var => $val) {
  345. $table[$var] = filtrer_entites($table[$var]);
  346. foreach ($echappe_cdata as $n => $e)
  347. $table[$var] = str_replace("@@@SPIP_CDATA$n@@@",
  348. $e, $table[$var]);
  349. }
  350. }
  351. ?>