PageRenderTime 57ms CodeModel.GetById 4ms RepoModel.GetById 0ms app.codeStats 0ms

/plugins-dist/sites/inc/syndic.php

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