Feed.class.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. <?php
  2. /*
  3. @nom: Feed
  4. @auteur: Idleman (idleman@idleman.fr)
  5. @description: Classe de gestion des flux RSS/ATOM
  6. */
  7. class Feed extends MysqlEntity{
  8. protected $id,$name,$url,$events=array(),$description,$website,$folder,$lastupdate;
  9. protected $TABLE_NAME = 'feed';
  10. protected $CLASS_NAME = 'Feed';
  11. protected $object_fields =
  12. array(
  13. 'id'=>'key',
  14. 'name'=>'string',
  15. 'description'=>'longstring',
  16. 'website'=>'longstring',
  17. 'url'=>'longstring',
  18. 'lastupdate'=>'string',
  19. 'folder'=>'integer'
  20. );
  21. protected $object_fields_index =
  22. array(
  23. 'folder'=>'index'
  24. );
  25. protected $error = '';
  26. function __construct($name=null,$url=null){
  27. $this->name = $name;
  28. $this->url = $url;
  29. parent::__construct();
  30. }
  31. /** @TODO: ne faire qu'un seul chargement avec SimplePie et récupérer les
  32. même informations. Mettre le chargement en cache au moins d'une méthode
  33. loadLeed() qui ne chargera qu'une seule fois. Voire même en déclenchement
  34. retardé, au dernier moment. */
  35. function getInfos(){
  36. $xml = @simplexml_load_file($this->url);
  37. if($xml!=false){
  38. $this->name = array_shift ($xml->xpath('channel/title'));
  39. $this->description = array_shift ($xml->xpath('channel/description'));
  40. $this->website = array_shift ($xml->xpath('channel/link'));
  41. }
  42. }
  43. function getError() { return $this->error; }
  44. /*@TODO: fournir un extrait quand il 'y a pas de description. De même pour les médias.
  45. @TODO: SimplePie remplace "é" par "&eacute;", il ne devrait pas le faire.
  46. J'ai testé set_stupidly_fast(true) sans succès.
  47. Il encadre les descriptions avec <div>, absents dans le source du flux.
  48. @TODO: la vérification de doublon est sous la responsabilité de l'appelant.
  49. Il serait peut-être utile de faire une méthode add() qui vérifie, plante si
  50. nécessaire, et appelle parse(). Impossible de vérifier dans parse() même
  51. car elle est appelée aussi pour autre chose que l'ajout.
  52. */
  53. function parse($syncId,&$nbEvents =0, $enableCache=true, $forceFeed=false){
  54. $nbEvents = 0;
  55. assert('is_int($syncId) && $syncId>0');
  56. if (empty($this->id) || 0 == $this->id) {
  57. /* Le flux ne dispose pas pas d'id !. Ça arrive si on appelle
  58. parse() sans avoir appelé save() pour un nouveau flux.
  59. @TODO: un create() pour un nouveau flux ? */
  60. $msg = 'Empty or null id for a feed! '
  61. .'See '.__FILE__.' on line '.__LINE__;
  62. error_log($msg, E_USER_ERROR);
  63. die($msg); // Arrêt, sinon création événements sans flux associé.
  64. }
  65. $feed = new SimplePie();
  66. $feed->enable_cache($enableCache);
  67. $feed->force_feed($forceFeed);
  68. $feed->set_feed_url($this->url);
  69. $feed->set_useragent('Mozilla/4.0 Leed (LightFeed Agrgegator) '.VERSION_NAME.' by idleman http://projet.idleman.fr/leed');
  70. if (!$feed->init()) {
  71. $this->error = $feed->error;
  72. $this->lastupdate = $_SERVER['REQUEST_TIME'];
  73. $this->save();
  74. return false;
  75. }
  76. $feed->handle_content_type(); // UTF-8 par défaut pour SimplePie
  77. if($this->name=='') $this->name = $feed->get_title();
  78. if($this->name=='') $this->name = $this->url;
  79. $this->website = $feed->get_link();
  80. $this->description = $feed->get_description();
  81. $items = $feed->get_items();
  82. $eventManager = new Event();
  83. $events = array();
  84. $iEvents = 0;
  85. foreach($items as $item){
  86. // Ne retient que les 100 premiers éléments de flux.
  87. if ($iEvents++>=100) break;
  88. // Si le guid existe déjà, on évite de le reparcourir.
  89. $alreadyParsed = $eventManager->load(array('guid'=>$item->get_id(), 'feed'=>$this->id));
  90. if (isset($alreadyParsed)&&($alreadyParsed!=false)) {
  91. $events[]=$alreadyParsed->getId();
  92. continue;
  93. }
  94. // Initialisation des informations de l'événement (élt. de flux)
  95. $event = new Event();
  96. $event->setSyncId($syncId);
  97. $event->setGuid($item->get_id());
  98. $event->setTitle($item->get_title());
  99. $event->setPubdate($item->get_date());
  100. $event->setCreator(
  101. ''==$item->get_author()
  102. ? ''
  103. : $item->get_author()->name
  104. );
  105. $event->setLink($item->get_permalink());
  106. $event->setFeed($this->id);
  107. $event->setUnread(1); // inexistant, donc non-lu
  108. //Gestion de la balise enclosure pour les podcasts et autre cochonneries :)
  109. $enclosure = $item->get_enclosure();
  110. if($enclosure!=null && $enclosure->link!=''){
  111. $enclosureName = substr(
  112. $enclosure->link,
  113. strrpos($enclosure->link, '/')+1,
  114. strlen($enclosure->link)
  115. );
  116. $enclosureArgs = strpos($enclosureName, '?');
  117. if($enclosureArgs!==false)
  118. $enclosureName = substr($enclosureName,0,$enclosureArgs);
  119. $enclosureFormat = isset($enclosure->handler)
  120. ? $enclosure->handler
  121. : substr($enclosureName, strrpos($enclosureName,'.')+1);
  122. $enclosure ='<div class="enclosure"><h1>Fichier média :</h1><a href="'.$enclosure->link.'"> '.$enclosureName.'</a> <span>(Format '.strtoupper($enclosureFormat).', '.Functions::convertFileSize($enclosure->length).')</span></div>';
  123. }else{
  124. $enclosure = '';
  125. }
  126. $event->setContent($item->get_content().$enclosure);
  127. $event->setDescription($item->get_description().$enclosure);
  128. if(trim($event->getDescription())=='')
  129. $event->setDescription(
  130. substr($event->getContent(),0,300)
  131. .'…<br><a href="'.$event->getLink()
  132. .'">Lire la suite de l\'article</a>'
  133. );
  134. if(trim($event->getContent())=='')
  135. $event->setContent($event->getDescription());
  136. $event->setCategory($item->get_category());
  137. $event->save();
  138. $nbEvents++;
  139. }
  140. $listid = "";
  141. foreach($events as $item){
  142. $listid.=','.$item;
  143. }
  144. $query='UPDATE `'.MYSQL_PREFIX.'event` SET syncId='.$syncId.' WHERE id in (0'.$listid.');';
  145. $myQuery = $this->customQuery($query);
  146. $this->lastupdate = $_SERVER['REQUEST_TIME'];
  147. $this->save();
  148. return true;
  149. }
  150. function removeOldEvents($maxEvent, $currentSyncId){
  151. if ($maxEvent<=0) return;
  152. $eventManager = new Event();
  153. $nbLines = $eventManager->rowCount(array(
  154. 'feed'=>$this->id,
  155. 'unread'=>0,
  156. 'favorite'=>0,
  157. ));
  158. $limit = $nbLines - $maxEvent;
  159. if ($limit<=0) return;
  160. $tableEvent = '`'.MYSQL_PREFIX."event`";
  161. $query = "
  162. DELETE FROM {$tableEvent} WHERE feed={$this->id} AND favorite!=1 AND unread!=1 AND syncId!={$currentSyncId} ORDER BY pubDate ASC LIMIT {$limit}
  163. ";
  164. ///@TODO: escape the variables inside mysql
  165. $this->customExecute($query);
  166. }
  167. function setId($id){
  168. $this->id = $id;
  169. }
  170. function getDescription(){
  171. return $this->description;
  172. }
  173. function setDescription($description){
  174. $this->description = $description;
  175. }
  176. function getWebSite(){
  177. return $this->website;
  178. }
  179. function setWebSite($website){
  180. $this->website = $website;
  181. }
  182. function getId(){
  183. return $this->id;
  184. }
  185. function getUrl(){
  186. return $this->url;
  187. }
  188. function setUrl($url){
  189. $this->url = $url;
  190. }
  191. function getName(){
  192. return (trim($this->name)!='' ? $this->name:$this->url);
  193. }
  194. function setName($name){
  195. $this->name = $name;
  196. }
  197. function getEvents($start=0,$limit=10000,$order,$columns='*'){
  198. $eventManager = new Event();
  199. $events = $eventManager->loadAllOnlyColumn($columns,array('feed'=>$this->getId()),$order,$start.','.$limit);
  200. return $events;
  201. }
  202. function countUnreadEvents(){
  203. $unreads = array();
  204. $results = Feed::customQuery("SELECT COUNT(".MYSQL_PREFIX."event.id), ".MYSQL_PREFIX."event.feed FROM ".MYSQL_PREFIX."event WHERE ".MYSQL_PREFIX."event.unread = 1 GROUP BY ".MYSQL_PREFIX."event.feed") ;
  205. if($results!=false){
  206. while($item = mysql_fetch_array($results)){
  207. $unreads[$item[1]] = $item[0];
  208. }
  209. }
  210. return $unreads;
  211. }
  212. function getFeedsPerFolder(){
  213. $feedsFolderMap = array();
  214. $feedsIdMap = array();
  215. $results = Feed::customQuery("SELECT ".MYSQL_PREFIX."feed.name AS name, ".MYSQL_PREFIX."feed.id AS id, ".MYSQL_PREFIX."feed.url AS url, ".MYSQL_PREFIX."folder.id AS folder FROM ".MYSQL_PREFIX."feed INNER JOIN ".MYSQL_PREFIX."folder ON ( ".MYSQL_PREFIX."feed.folder = ".MYSQL_PREFIX."folder.id ) ORDER BY ".MYSQL_PREFIX."feed.name ;");
  216. if($results!=false){
  217. while($item = mysql_fetch_array($results)){
  218. $name = $item['name'];
  219. $feedsIdMap[$item['id']]['name'] = $name;
  220. $feedsFolderMap[$item['folder']][$item['id']]['id'] = $item['id'];
  221. $feedsFolderMap[$item['folder']][$item['id']]['name'] = $name;
  222. $feedsFolderMap[$item['folder']][$item['id']]['url'] = $item['url'];
  223. }
  224. }
  225. $feeds['folderMap'] = $feedsFolderMap;
  226. $feeds['idMap'] = $feedsIdMap;
  227. return $feeds;
  228. }
  229. function getFolder(){
  230. return $this->folder;
  231. }
  232. function setFolder($folder){
  233. $this->folder = $folder;
  234. }
  235. function getLastupdate(){
  236. return $this->lastUpdate;
  237. }
  238. function setLastupdate($lastupdate){
  239. $this->lastupdate = $lastupdate;
  240. }
  241. /** @returns vrai si l'url n'est pas déjà connue .*/
  242. function notRegistered() {
  243. return $this->rowCount(array('url' => $this->url)) == 0;
  244. }
  245. }
  246. ?>