BxEventsDb.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) UNA, Inc - https://una.io
  4. * MIT License - https://opensource.org/licenses/MIT
  5. *
  6. * @defgroup Events Events
  7. * @ingroup UnaModules
  8. *
  9. * @{
  10. */
  11. /**
  12. * Groups module database queries
  13. */
  14. class BxEventsDb extends BxBaseModGroupsDb
  15. {
  16. public function __construct(&$oConfig)
  17. {
  18. parent::__construct($oConfig);
  19. }
  20. public function getContentInfoByIntervalId ($iIntervalId)
  21. {
  22. $iContentId = $this->getOne("SELECT `event_id` FROM `bx_events_intervals` WHERE `interval_id` = :interval", array(
  23. 'interval' => $iIntervalId,
  24. ));
  25. if (!$iContentId)
  26. return 0;
  27. return $this->getContentInfoById ($iContentId);
  28. }
  29. public function getContentInfoById ($iContentId, $bForceGet = false)
  30. {
  31. $sQuery = $this->prepare ("SELECT `c`.*, `p`.`account_id`, `p`.`id` AS `profile_id`, `p`.`status` AS `profile_status`, MAX(`i`.`repeat_stop`) AS `repeat_stop` FROM `" . $this->_oConfig->CNF['TABLE_ENTRIES'] . "` AS `c`
  32. INNER JOIN `sys_profiles` AS `p` ON (`p`.`content_id` = `c`.`id` AND `p`.`type` = ?)
  33. LEFT JOIN `bx_events_intervals` as `i` ON (`c`.`id` = `i`.`event_id`)
  34. WHERE `c`.`id` = ?
  35. GROUP BY `c`.`id`", $this->_oConfig->getName(), $iContentId);
  36. return $this->getRow($sQuery);
  37. }
  38. public function deleteIntervalById ($iIntervalId)
  39. {
  40. return $this->query("DELETE FROM `bx_events_intervals` WHERE `interval_id` = :interval", array(
  41. 'interval' => $iIntervalId,
  42. ));
  43. }
  44. public function getIntervals ($iContentId)
  45. {
  46. return $this->getAllWithKey("SELECT * FROM `bx_events_intervals` WHERE `event_id` = :event_id", 'interval_id', array(
  47. 'event_id' => $iContentId,
  48. ));
  49. }
  50. public function getEntriesBy($aParams = [])
  51. {
  52. if(isset($aParams['type']) && !in_array($aParams['type'], ['past']))
  53. return parent::getEntriesBy($aParams);
  54. $CNF = &$this->_oConfig->CNF;
  55. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query', 1 => []]];
  56. $sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";
  57. $sSelectClause = "`" . $CNF['TABLE_ENTRIES'] . "`.*";
  58. switch($aParams['type']) {
  59. case 'past':
  60. if(!empty($aParams['date_from'])) {
  61. $aMethod['params'][1]['date_from'] = (int)$aParams['date_from'];
  62. $sWhereClause .= " AND `" . $CNF['TABLE_ENTRIES'] . "`.`" . $CNF['FIELD_DATE_END'] . "` >= :date_from";
  63. }
  64. $aMethod['params'][1]['date_to'] = !empty($aParams['date_to']) ? (int)$aParams['date_to'] : time();
  65. $sWhereClause .= " AND `" . $CNF['TABLE_ENTRIES'] . "`.`" . $CNF['FIELD_DATE_END'] . "` < :date_to";
  66. break;
  67. }
  68. if(!empty($sOrderClause))
  69. $sOrderClause = 'ORDER BY ' . $sOrderClause;
  70. if(!empty($sLimitClause))
  71. $sLimitClause = 'LIMIT ' . $sLimitClause;
  72. $aMethod['params'][0] = "SELECT " . $sSelectClause . " FROM `" . $CNF['TABLE_ENTRIES'] . "` " . $sJoinClause . " WHERE 1 " . $sWhereClause . " " . $sOrderClause . " " . $sLimitClause;
  73. return call_user_func_array(array($this, $aMethod['name']), $aMethod['params']);
  74. }
  75. public function getEntriesByDate($sDateFrom, $sDateTo, $iEventId = 0, $aSQLPart = array())
  76. {
  77. $CNF = &$this->_oConfig->CNF;
  78. // validate input data
  79. if (false === ($oDateFrom = date_create($sDateFrom, new DateTimeZone('UTC'))))
  80. return array();
  81. if (false === ($oDateTo = date_create($sDateTo, new DateTimeZone('UTC'))))
  82. return array();
  83. if ($oDateFrom > $oDateTo)
  84. return array();
  85. $sModule = $this->_oConfig->getName();
  86. $oMetatags = BxDolMetatags::getObjectInstance($CNF['OBJECT_METATAGS']);
  87. // increase start and end date to cover timezones
  88. $oDateFrom = $oDateFrom->sub(new DateInterval("P1D"));
  89. $oDateTo = $oDateTo->add(new DateInterval("P1D"));
  90. // look throught all days in the interval
  91. $oDateIter = clone($oDateFrom);
  92. $aEntries = array();
  93. while ($oDateIter->format('Y-m-d') != $oDateTo->format('Y-m-d')) {
  94. $oDateMin = date_create($oDateIter->format('Y-m-d') . '00:00:00', new DateTimeZone('UTC'));
  95. $oDateMax = date_create($oDateIter->format('Y-m-d') . '23:59:59', new DateTimeZone('UTC'));
  96. // get all events for the specific day
  97. $oDateMonthBegin = date_create($oDateIter->format('Y-m-01'), new DateTimeZone('UTC'));
  98. $iWeekOfMonth = $oDateIter->format('W') - $oDateMonthBegin->format('W') + 1;
  99. $aBindings = array(
  100. 'timestamp_min' => $oDateMin->getTimestamp(),
  101. 'timestamp_max' => $oDateMax->getTimestamp(),
  102. );
  103. $aBindingsRepeating = array(
  104. 'timestamp_min' => $oDateMin->getTimestamp(),
  105. 'timestamp_max' => $oDateMax->getTimestamp(),
  106. 'year_start' => $oDateFrom->format('Y'),
  107. 'year' => $oDateIter->format('Y'),
  108. 'month' => $oDateIter->format('n'),
  109. 'week_of_month' => $iWeekOfMonth > 0 ? $iWeekOfMonth : $oDateIter->format('W') + 1,
  110. 'day_of_month' => $oDateIter->format('j'),
  111. 'day_of_week' => $oDateIter->format('N'),
  112. );
  113. $sJoin = isset($aSQLPart['join']) ? $aSQLPart['join'] : '';
  114. $sWhere = isset($aSQLPart['where']) ? $aSQLPart['where'] : '';
  115. if ((int)$iEventId) {
  116. $aBindings['event'] = (int)$iEventId;
  117. $aBindingsRepeating['event'] = (int)$iEventId;
  118. $sWhere .= " AND `bx_events_data`.`id` = :event ";
  119. }
  120. // search for regular events
  121. $a = $this->getAllWithKey("SELECT DISTINCT `bx_events_data`.`id`, `bx_events_data`.`event_name` AS `title`, `bx_events_data`.`event_desc` AS `description`,
  122. `bx_events_data`.`threshold` AS `threshold`, `bx_events_data`.`date_start`, `bx_events_data`.`date_end`, `bx_events_data`.`timezone`, `bx_events_data`.`reminder`, 0 AS `repeating`
  123. FROM `bx_events_data` $sJoin
  124. WHERE `bx_events_data`.`status`='active' AND `bx_events_data`.`status_admin`='active' AND `bx_events_data`.`date_start` >= :timestamp_min AND `bx_events_data`.`date_start` <= :timestamp_max $sWhere
  125. ", 'id', $aBindings);
  126. if ($a)
  127. $sWhere .= " AND `bx_events_data`.`id` NOT IN(" . $this->implode_escape(array_keys($a)) . ") ";
  128. $aRepeating = $this->getAllWithKey("SELECT DISTINCT `bx_events_data`.`id`, `bx_events_data`.`event_name` AS `title`, `bx_events_data`.`event_desc` AS `description`, `bx_events_data`.`threshold` AS `threshold`, `bx_events_data`.`date_start`, `bx_events_data`.`date_end`, `bx_events_data`.`timezone`, `bx_events_data`.`reminder`, 1 AS `repeating`
  129. FROM `bx_events_data`
  130. LEFT JOIN `bx_events_intervals` AS `i` ON (
  131. `bx_events_data`.`id` = `i`.`event_id`
  132. AND
  133. `bx_events_data`.`date_start` < :timestamp_max
  134. AND
  135. (0 = `i`.`repeat_stop` OR `i`.`repeat_stop` >= :timestamp_min)
  136. AND (
  137. (0 = `i`.`repeat_year` OR 0 = (:year - :year_start) % `i`.`repeat_year`)
  138. AND
  139. (0 = `i`.`repeat_month` OR :month = `i`.`repeat_month`)
  140. AND
  141. (0 = `i`.`repeat_week_of_month` OR :week_of_month = `i`.`repeat_week_of_month`)
  142. AND
  143. (0 = `i`.`repeat_day_of_month` OR :day_of_month = `i`.`repeat_day_of_month`)
  144. AND
  145. (0 = `i`.`repeat_day_of_week` OR :day_of_week = `i`.`repeat_day_of_week`)
  146. )
  147. ) $sJoin
  148. WHERE `bx_events_data`.`status`='active' AND `bx_events_data`.`status_admin`='active' AND `i`.`interval_id` IS NOT NULL $sWhere
  149. ", 'id', $aBindingsRepeating);
  150. $a = array_merge($aRepeating ? $aRepeating : array(), $a ? $a : array());
  151. // prepare variables for each event
  152. foreach ($a as $k => $r) {
  153. $oDateStart = new DateTime('@' . $r['date_start']);
  154. $oDateEnd = new DateTime('@' . $r['date_end']);
  155. $oDuration = $oDateStart->diff($oDateEnd);
  156. if ($r['repeating']) {
  157. // since repeating interval values are stored in specific timezones then we need to convert it
  158. $oTz = new DateTimeZone($r['timezone'] ? $r['timezone'] : 'UTC');
  159. $sHoursStart = $oDateStart->format('H:i:s');
  160. $iSecondsStart = (clone($oDateStart))->setTimezone($oTz)->format('H') * 3600 + $oDateStart->format('i') * 60 + $oDateStart->format('s');
  161. $iSecondsOffset = $oTz->getOffset($oDateIter);
  162. $sCurrentDay = $oDateIter->format('Y-m-d');
  163. if ($iSecondsOffset > 0 && $iSecondsOffset > $iSecondsStart)
  164. $sCurrentDay = (clone($oDateIter))->sub(new DateInterval("P1D"))->format('Y-m-d');
  165. if ($iSecondsOffset < 0 && -$iSecondsOffset > (86400 - $iSecondsStart))
  166. $sCurrentDay = (clone($oDateIter))->add(new DateInterval("P1D"))->format('Y-m-d');
  167. $oStart = date_create($sCurrentDay . ' ' . $sHoursStart);
  168. $oEnd = $oStart ? clone($oStart) : null;
  169. $oEnd = $oEnd ? $oEnd->add($oDuration) : null;
  170. }
  171. else {
  172. $oStart = $oDateStart;
  173. $oEnd = $oDateEnd;
  174. }
  175. $a[$k]['start'] = $oStart ? $oStart->format('c') : 0;
  176. $a[$k]['end'] = $oEnd ? $oEnd->format('c') : 0;
  177. $a[$k]['start_utc'] = $oDateStart ? $oDateStart->getTimestamp() : 0;
  178. $a[$k]['end_utc'] = $oDateEnd ? $oDateEnd->getTimestamp() : 0;
  179. $a[$k]['url'] = bx_absolute_url(BxDolPermalinks::getInstance()->permalink('page.php?i=' . $this->_oConfig->CNF['URI_VIEW_ENTRY'] . '&id=' . $r['id']));
  180. if(bx_is_api()) {
  181. $a[$k]['url'] = bx_api_get_relative_url($a[$k]['url']);
  182. $a[$k]['location_data'] = $oMetatags->locationGet($r['id']);
  183. $a[$k]['location'] = $oMetatags->locationsString($r['id'], false);
  184. }
  185. else {
  186. if(($oEvent = BxDolProfile::getInstanceByContentAndType($r['id'], $sModule)) !== false)
  187. $a[$k]['extendedProps'] = [
  188. 'class' => 'bx-events-calendar-unit',
  189. 'card' => $oEvent->getUnit()
  190. ];
  191. }
  192. }
  193. // merge with all other events
  194. $aEntries = array_merge($aEntries, $a);
  195. // go to the next day
  196. $oDateIter = $oDateIter->add(new DateInterval("P1D"));
  197. }
  198. return $aEntries;
  199. }
  200. public function checkIn($iProfileId, $iId)
  201. {
  202. $CNF = &$this->_oConfig->CNF;
  203. return $this->query("INSERT INTO `" . $CNF['TABLE_CHECK_IN'] . "` SET `profile_id` = :profile_id, `event_id` = :event_id ON DUPLICATE KEY UPDATE `event_id` = :event_id", [
  204. 'profile_id' => $iProfileId,
  205. 'event_id' => $iId
  206. ]) !== false;
  207. }
  208. public function isCheckedIn($iProfileId, $iId)
  209. {
  210. $CNF = &$this->_oConfig->CNF;
  211. return (int)$this->getOne("SELECT `id` FROM `" . $CNF['TABLE_CHECK_IN'] . "` WHERE `profile_id` = :profile_id AND `event_id` = :event_id LIMIT 1", [
  212. 'profile_id' => $iProfileId,
  213. 'event_id' => $iId
  214. ]) > 0;
  215. }
  216. public function getSessions($aParams = [])
  217. {
  218. $CNF = &$this->_oConfig->CNF;
  219. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  220. $sSelectClause = "`ts`.*";
  221. $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = "";
  222. switch($aParams['sample']) {
  223. case 'id':
  224. $aMethod['name'] = 'getRow';
  225. $aMethod['params'][1] = [
  226. 'id' => $aParams['id']
  227. ];
  228. $sWhereClause = " AND `ts`.`id`=:id";
  229. break;
  230. case 'event_id':
  231. $aMethod['params'][1] = [
  232. 'event_id' => $aParams['event_id']
  233. ];
  234. $sWhereClause = " AND `ts`.`event_id`=:event_id";
  235. $sOrderClause = "`ts`.`" . !empty($aParams['order_by']) ? $aParams['order_by'] : "order" . "` ASC";
  236. break;
  237. }
  238. if(!empty($sOrderClause))
  239. $sOrderClause = 'ORDER BY ' . $sOrderClause;
  240. if(!empty($sLimitClause))
  241. $sLimitClause = 'LIMIT ' . $sLimitClause;
  242. $aMethod['params'][0] = "SELECT " . $sSelectClause . " FROM `" . $CNF['TABLE_SESSIONS'] . "` AS `ts` " . $sJoinClause . " WHERE 1" . $sWhereClause . " " . $sOrderClause . " " . $sLimitClause;
  243. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  244. }
  245. public function getSessionOrderMax($iEventId)
  246. {
  247. $CNF = &$this->_oConfig->CNF;
  248. return (int)$this->getOne("SELECT MAX(`order`) FROM `" . $CNF['TABLE_SESSIONS'] . "` WHERE `event_id`=:event_id", [
  249. 'event_id' => $iEventId
  250. ]);
  251. }
  252. public function deleteSessions($aWhere)
  253. {
  254. $CNF = &$this->_oConfig->CNF;
  255. if(empty($aWhere) || !is_array($aWhere))
  256. return false;
  257. return (int)$this->query("DELETE FROM `" . $CNF['TABLE_SESSIONS'] . "` WHERE " . $this->arrayToSQL($aWhere, ' AND ')) > 0;
  258. }
  259. }
  260. /** @} */