Feed.class.php 10 KB

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