UserNotification.class.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * Define a usernotification.
  4. * @author Valentin CARRUESCO
  5. * @category Plugin
  6. * @license copyright
  7. */
  8. class UserNotification extends Entity{
  9. public $id,$notification,$user,$read;
  10. protected $TABLE_NAME = 'user_notification';
  11. public $fields =
  12. array(
  13. 'id' => 'key',
  14. 'notification' => 'int',
  15. 'user' => 'string',
  16. 'read' => 'boolean'
  17. );
  18. public $joins = array(
  19. 'notification' => 'Notification'
  20. );
  21. public static function byUser($myUser,$options = array()){
  22. require_once(__DIR__.SLASH.'Notification.class.php');
  23. $options = array_merge(array(
  24. 'limit' => 100,
  25. 'unread' => false,
  26. 'types' => array()
  27. ),$options);
  28. //Création des user_notification absentes pour les notification pinned
  29. $pinnedNotifications = "SELECT n.* FROM `notification` n LEFT JOIN `user_notification` un ON un.notification = n.id AND un.user=? WHERE n.pinned=1 AND un.id IS NULL";
  30. foreach(Notification::staticQuery($pinnedNotifications,array($myUser->login),true) as $pinneds){
  31. $userNotification = new UserNotification();
  32. $userNotification->notification = $pinneds->id;
  33. $userNotification->user = $myUser->login;
  34. $userNotification->read = 0;
  35. $userNotification->save();
  36. }
  37. //récuperation des user_notifications
  38. $query = 'SELECT *, un.id as id FROM {{table}} un LEFT JOIN '.Notification::tableName().' n ON un.notification=n.id
  39. WHERE un.user=? AND (n.start<? OR n.start IS NULL) AND (n.end>? OR n.end IS NULL) '.($options['unread']===true ? 'AND (un.read = 0)' : '');
  40. if(count($options['types'])!=0) $query .= ' and n.type IN ("'.implode('","',$options['types']).'")';
  41. $query .= ' ORDER BY n.created DESC LIMIT '.$options['limit'];
  42. return UserNotification::staticQuery($query,array($myUser->login,time(),time()));
  43. }
  44. public static function get_unreads_count($myUser,$key=null) {
  45. require_once(__DIR__.SLASH.'Notification.class.php');
  46. $query = 'SELECT COUNT(*) unread, n.type FROM {{table}} un INNER JOIN '.Notification::tableName().' n ON un.notification=n.id WHERE un.user=? AND (n.start<? OR n.start IS NULL) AND (n.end>? OR n.end IS NULL) AND (un.read = 0) GROUP BY n.type';
  47. $unreads = array();
  48. foreach (UserNotification::staticQuery($query, array($myUser->login,time(),time())) as $unread)
  49. $unreads['detailled'][$unread['type']] = $unread['unread'];
  50. $unreads['total'] = isset($unreads['detailled']) ? array_sum($unreads['detailled']) : 0;
  51. $unreads['compact'] = $unreads['total'] > 5 ? '5+' : $unreads['total'];
  52. return isset($key) && isset($unreads[$key]) ? $unreads[$key] : $unreads;
  53. }
  54. }
  55. ?>