1
0

BxTasksDb.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  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. * @defgroup Tasks Tasks
  6. * @ingroup UnaModules
  7. *
  8. * @{
  9. */
  10. /*
  11. * Module database queries
  12. */
  13. class BxTasksDb extends BxBaseModTextDb
  14. {
  15. protected $_aSqlMarkers;
  16. public function __construct(&$oConfig)
  17. {
  18. parent::__construct($oConfig);
  19. $this->_aSqlMarkers = [
  20. 'logged_pid' => bx_get_logged_profile_id()
  21. ];
  22. }
  23. public function getExportTimeFields()
  24. {
  25. return $this->getFields('bx_tasks_time_track');
  26. }
  27. public function getContexts($aParams = [])
  28. {
  29. $CNF = &$this->_oConfig->CNF;
  30. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  31. $sSelectClause = '`tc`.*';
  32. $sJoinClause = $sWhereClause = $sOrderClause = '';
  33. if(!empty($aParams))
  34. switch($aParams['sample']) {
  35. case 'id':
  36. $aMethod['name'] = 'getRow';
  37. $aMethod['params'][1] = [
  38. 'id' => $aParams['id']
  39. ];
  40. $sWhereClause = "AND `tc`.`id` = :id";
  41. break;
  42. }
  43. if(!empty($sOrderClause))
  44. $sOrderClause = "ORDER BY " . $sOrderClause;
  45. $aMethod['params'][0] = "SELECT
  46. " . $sSelectClause . "
  47. FROM `" . $CNF['TABLE_CONTEXTS'] . "` AS `tc` " . $sJoinClause . "
  48. WHERE 1 " . $sWhereClause . " " . $sOrderClause;
  49. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  50. }
  51. public function getContextRepository($iId)
  52. {
  53. $aContext = $this->getContexts([
  54. 'sample' => 'id',
  55. 'id' => $iId
  56. ]);
  57. return $aContext && is_array($aContext) ? $aContext : false;
  58. }
  59. public function getLists ($iContextId = 0)
  60. {
  61. $CNF = &$this->_oConfig->CNF;
  62. return $this->getAll("SELECT * FROM `" . $CNF['TABLE_LISTS'] . "` WHERE `context_id` = :context_id", [
  63. 'context_id' => $iContextId
  64. ]);
  65. }
  66. public function getList ($iId = 0)
  67. {
  68. $CNF = &$this->_oConfig->CNF;
  69. return $this->getRow("SELECT * FROM `" . $CNF['TABLE_LISTS'] . "` WHERE `id` = :id", [
  70. 'id' => $iId
  71. ]);
  72. }
  73. public function deleteList ($iId = 0)
  74. {
  75. $CNF = &$this->_oConfig->CNF;
  76. if($this->query("DELETE FROM `" . $CNF['TABLE_ENTRIES'] . "` WHERE `" . $CNF['FIELD_TASKLIST'] . "`=:id", ['id' => $iId]) === false)
  77. return false;
  78. return (int)$this->query("DELETE FROM `" . $CNF['TABLE_LISTS'] . "` WHERE `id`=:id", [
  79. 'id' => $iId
  80. ]) > 0;
  81. }
  82. public function getTasks ($iContextId = 0, $iListId = false, $aParams = [])
  83. {
  84. $CNF = &$this->_oConfig->CNF;
  85. $aBindings = [];
  86. $sSelectClause = "`te`.*";
  87. $sJoinClause = $sWhereClause = "";
  88. if(($sField = $CNF['FIELD_ALLOW_VIEW_TO']) && $iContextId) {
  89. $aBindings[$sField] = -$iContextId;
  90. $sWhereClause .= " AND `te`.`" . $sField . "` = :" . $sField;
  91. }
  92. if(($sField = $CNF['FIELD_TASKLIST']) && $iListId !== false) {
  93. $aBindings[$sField] = $iListId;
  94. $sWhereClause .= " AND `te`.`" . $sField . "` = :" . $sField;
  95. }
  96. if(($iFilter = (int)($aParams['filter'] ?? 0)) && ($aFilter = $this->getFilterById($iFilter))) {
  97. if(($aFltJoin = $aFilter['conditions']['join'] ?? false) && ($sFltJoin = $this->_getSqlJoinFrom($aFltJoin)) != '')
  98. $sJoinClause .= " " . $sFltJoin;
  99. if(($aFltWhere = $aFilter['conditions']['where'] ?? false) && ($sFltWhere = $this->_getSqlWhereFrom($aFltWhere)) != '')
  100. $sWhereClause .= " AND " . $sFltWhere;
  101. }
  102. if(($iProfileId = $aParams['for_profile'] ?? false)) {
  103. $aBindings['profile_id'] = (int)$iProfileId;
  104. $sJoinClause .= " LEFT JOIN `" . $CNF['TABLE_ASSIGNMENTS'] . "` AS `tafp` ON `te`.`id`=`tafp`.`content`";
  105. $sWhereClause .= " AND (`te`.`" . $CNF['FIELD_AUTHOR'] . "`=:profile_id OR `tafp`.`initiator`=:profile_id)";
  106. }
  107. if(($oCf = BxDolContentFilter::getInstance()) && $oCf->isEnabled())
  108. $sWhereClause .= $oCf->getSQLParts('te', $CNF['FIELD_CF']);
  109. if(($aParams['with_stats'] ?? false)) {
  110. $sSelectClause .= $this->prepareAsString(", (SELECT SUM(`value`) FROM `" . $CNF['TABLE_TIME_TRACK'] . "` WHERE `object_id`=`te`.`id` AND `author_id`=?) AS `time`, `tt`.`sum` AS `time_total`", bx_get_logged_profile_id());
  111. $sJoinClause .= " LEFT JOIN `" . $CNF['TABLE_TIME'] . "` AS `tt` ON `te`.`id`=`tt`.`object_id`";
  112. }
  113. return $this->getAll("SELECT DISTINCT " . $sSelectClause . " FROM `" . $CNF['TABLE_ENTRIES'] . "` AS `te`" . $sJoinClause . " WHERE 1" . $sWhereClause, $aBindings);
  114. }
  115. public function getEntriesByDate($sDateFrom, $sDateTo, $aSQLPart = array())
  116. {
  117. // validate input data
  118. if (false === ($oDateFrom = date_create($sDateFrom, new DateTimeZone('UTC'))))
  119. return array();
  120. if (false === ($oDateTo = date_create($sDateTo, new DateTimeZone('UTC'))))
  121. return array();
  122. if ($oDateFrom > $oDateTo)
  123. return array();
  124. // increase start and end date to cover timezones
  125. $oDateFrom = $oDateFrom->sub(new DateInterval("P1D"));
  126. $oDateTo = $oDateTo->add(new DateInterval("P1D"));
  127. // look throught all days in the interval
  128. $oDateIter = clone($oDateFrom);
  129. $aEntries = array();
  130. while ($oDateIter->format('Y-m-d') != $oDateTo->format('Y-m-d')) {
  131. $oDateMin = date_create($oDateIter->format('Y-m-d') . '00:00:00', new DateTimeZone('UTC'));
  132. $oDateMax = date_create($oDateIter->format('Y-m-d') . '23:59:59', new DateTimeZone('UTC'));
  133. // get all events for the specific day
  134. $oDateMonthBegin = date_create($oDateIter->format('Y-m-01'), new DateTimeZone('UTC'));
  135. $iWeekOfMonth = $oDateIter->format('W') - $oDateMonthBegin->format('W') + 1;
  136. $aBindings = array(
  137. 'timestamp_min' => $oDateMin->getTimestamp(),
  138. 'timestamp_max' => $oDateMax->getTimestamp(),
  139. );
  140. $sWhere = isset($aSQLPart['where']) ? $aSQLPart['where'] : '';
  141. $a = $this->getAll("SELECT DISTINCT `bx_tasks_tasks`.`id`, `bx_tasks_tasks`.`title` AS `title`, `bx_tasks_tasks`.`due_date`
  142. FROM `bx_tasks_tasks`
  143. WHERE (`bx_tasks_tasks`.`due_date` >= :timestamp_min AND `bx_tasks_tasks`.`due_date` <= :timestamp_max ) $sWhere
  144. ", $aBindings);
  145. // prepare variables for each event
  146. $sCurrentDay = $oDateIter->format('Y-m-d');
  147. foreach ($a as $k => $r) {
  148. $oDateStart = new DateTime();
  149. $oDateStart->setTimestamp($r['due_date']);
  150. $oDateStart->setTimezone(new DateTimeZone('UTC'));
  151. $oDateEnd = new DateTime();
  152. $oDateEnd->setTimestamp($r['due_date']);
  153. $oDateEnd->setTimezone(new DateTimeZone('UTC'));
  154. $oDuration = $oDateStart->diff($oDateEnd);
  155. $sHoursStart = $oDateStart->format('H:i:s');
  156. $oStart = date_create($sCurrentDay . ' ' . $sHoursStart, new DateTimeZone('UTC'));
  157. $oEnd = $oStart ? clone($oStart) : null;
  158. $oEnd = $oEnd ? $oEnd->add($oDuration) : null;
  159. $a[$k]['start'] = $oStart ? $oStart->format('Y-m-d') : 0;
  160. $a[$k]['start_utc'] = $oStart ? $oStart->getTimestamp() : 0;
  161. $a[$k]['url'] = bx_absolute_url(BxDolPermalinks::getInstance()->permalink('page.php?i=' . $this->_oConfig->CNF['URI_VIEW_ENTRY'] . '&id=' . $r['id']));
  162. }
  163. // merge with all other events
  164. $aEntries = array_merge($aEntries, $a);
  165. // go to the next day
  166. $oDateIter = $oDateIter->add(new DateInterval("P1D"));
  167. }
  168. return $aEntries;
  169. }
  170. public function expireEntries()
  171. {
  172. $CNF = $this->_oConfig->CNF;
  173. $aResult = $this->getColumn("SELECT `id` FROM `" . $CNF['TABLE_ENTRIES'] . "` WHERE `" . $CNF['FIELD_DUE_DATE'] . "` < UNIX_TIMESTAMP() AND `" . $CNF['FIELD_EXPIRED'] . "` = '0'");
  174. if(empty($aResult) || !is_array($aResult))
  175. return false;
  176. return count($aResult) == (int)$this->query("UPDATE `" . $CNF['TABLE_ENTRIES'] . "` SET `" . $CNF['FIELD_EXPIRED'] . "` = '1' WHERE `id` IN (" . $this->implode_escape($aResult) . ")") ? $aResult : false;
  177. }
  178. public function getContextId($iContentId)
  179. {
  180. $CNF = $this->_oConfig->CNF;
  181. $aData = $this->getContentInfoById($iContentId);
  182. if($aData && is_array($aData) && ($iValue = (int)($aData[$CNF['FIELD_ALLOW_VIEW_TO']] ?? 0)) < 0)
  183. return abs($iValue);
  184. return 0;
  185. }
  186. public function getContextsIdsByType($sType, $iProfileId)
  187. {
  188. $CNF = $this->_oConfig->CNF;
  189. //--- Add own tasks
  190. $sQuery = '(SELECT `tp`.`id` FROM `' . $CNF['TABLE_ENTRIES'] . '` AS `tt` INNER JOIN `sys_profiles` AS `tp` ON ABS(`tt`.`allow_view_to`)=`tp`.`id` AND `tp`.`type`=:type WHERE `tt`.`author`=:author GROUP BY `tp`.`id`)';
  191. //--- Add assigned tasks
  192. $oAssignments = BxDolConnection::getObjectInstance($CNF['OBJECT_CONNECTION']);
  193. $aSql = $oAssignments->getConnectedContentAsSQLParts('tt', 'id', $iProfileId);
  194. if($aSql && ($sJoin = $aSql['join'] ?? false))
  195. $sQuery .= ' UNION (SELECT `tp`.`id` FROM `' . $CNF['TABLE_ENTRIES'] . '` AS `tt` INNER JOIN `sys_profiles` AS `tp` ON ABS(`tt`.`allow_view_to`)=`tp`.`id` AND `tp`.`type`=:type ' . $sJoin . ' WHERE 1)';
  196. return $this->getColumn($sQuery, [
  197. 'type' => $sType,
  198. 'author' => $iProfileId
  199. ]);
  200. }
  201. public function getFilters($aParams = [])
  202. {
  203. $CNF = &$this->_oConfig->CNF;
  204. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  205. $sSelectClause = '`tf`.*';
  206. $sJoinClause = $sWhereClause = '';
  207. $sOrderClause = '`tf`.`added` ASC, `tf`.`permanent` ASC';
  208. if(!empty($aParams))
  209. switch($aParams['sample']) {
  210. case 'id':
  211. $aMethod['name'] = 'getRow';
  212. $aMethod['params'][1] = [
  213. 'id' => $aParams['id']
  214. ];
  215. $sWhereClause = "AND `tf`.`id` = :id";
  216. break;
  217. case 'temporary':
  218. $aMethod['name'] = 'getRow';
  219. $sWhereClause .= " AND `tf`.`permanent` = '0'";
  220. if(($iContextId = $aParams['context_id'] ?? false) !== false) {
  221. $aMethod['params'][1]['context_id'] = $iContextId;
  222. $sWhereClause .= " AND `tf`.`context_id` = :context_id";
  223. }
  224. if(($iAuthor = $aParams['author'] ?? false) !== false) {
  225. $aMethod['params'][1]['author'] = $iAuthor;
  226. $sWhereClause .= " AND `tf`.`author` = :author";
  227. }
  228. break;
  229. case 'author':
  230. $aMethod['params'][1] = [
  231. 'author' => $aParams['author']
  232. ];
  233. $sWhereClause = "AND `tf`.`author` = :author";
  234. if(isset($aParams['active']) && $aParams['active'] === true)
  235. $sWhereClause .= " AND `tf`.`active` <> '0'";
  236. break;
  237. case 'active':
  238. $sWhereClause .= " AND `tf`.`active` <> '0'";
  239. if(($iContextId = $aParams['context_id'] ?? false) !== false) {
  240. $aMethod['params'][1]['context_id'] = $iContextId;
  241. $sWhereClause .= " AND `tf`.`context_id` = :context_id";
  242. }
  243. if(($iAuthor = $aParams['author'] ?? false) !== false) {
  244. $aMethod['params'][1]['author'] = $iAuthor;
  245. $sWhereClause .= " AND `tf`.`author` = :author";
  246. }
  247. if(($iPermanent = $aParams['permanent'] ?? false) !== false) {
  248. $aMethod['params'][1]['permanent'] = $iPermanent;
  249. $sWhereClause .= " AND `tf`.`permanent` = :permanent";
  250. }
  251. break;
  252. }
  253. if(!empty($sOrderClause))
  254. $sOrderClause = "ORDER BY " . $sOrderClause;
  255. $aMethod['params'][0] = "SELECT
  256. " . $sSelectClause . "
  257. FROM `" . $CNF['TABLE_FILTERS'] . "` AS `tf` " . $sJoinClause . "
  258. WHERE 1 " . $sWhereClause . " " . $sOrderClause;
  259. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  260. }
  261. public function getFilterById($iId)
  262. {
  263. $aFilter = $this->getFilters(['sample' => 'id', 'id' => $iId]);
  264. if(!$aFilter || !is_array($aFilter))
  265. return false;
  266. if(($sK = 'conditions') && $aFilter[$sK])
  267. $aFilter[$sK] = json_decode($aFilter[$sK], true);
  268. return $aFilter;
  269. }
  270. public function cleanFilters($iContextId, $iAuthor, $iLifetime = 3600)
  271. {
  272. $CNF = &$this->_oConfig->CNF;
  273. $this->query("DELETE FROM `" . $CNF['TABLE_FILTERS'] . "` WHERE `context_id` = :context_id AND `author` = :author AND UNIX_TIMESTAMP() - `added` > :lifetime AND `permanent` = '0'", [
  274. 'context_id' => $iContextId,
  275. 'author' => $iAuthor,
  276. 'lifetime' => $iLifetime
  277. ]);
  278. }
  279. public function getTemporaryFilterId($iContextId, $iAuthorId)
  280. {
  281. $aFilter = $this->getFilters([
  282. 'sample' => 'temporary',
  283. 'context_id' => $iContextId,
  284. 'author' => $iAuthorId
  285. ]);
  286. return $aFilter && is_array($aFilter) ? $aFilter['id'] : 0;
  287. }
  288. public function getTimeTracks($aParams = [])
  289. {
  290. $CNF = &$this->_oConfig->CNF;
  291. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  292. $sSelectClause = '`ttt`.*';
  293. $sJoinClause = $sWhereClause = $sOrderClause = '';
  294. if(!empty($aParams))
  295. switch($aParams['sample']) {
  296. case 'id':
  297. $aMethod['name'] = 'getRow';
  298. $aMethod['params'][1] = [
  299. 'id' => $aParams['id']
  300. ];
  301. $sWhereClause = "AND `ttt`.`id` = :id";
  302. break;
  303. case 'assignees':
  304. $aMethod['name'] = 'getColumn';
  305. $sSelectClause = 'DISTINCT `ttt`.`author_id`';
  306. break;
  307. }
  308. if(!empty($sOrderClause))
  309. $sOrderClause = "ORDER BY " . $sOrderClause;
  310. $aMethod['params'][0] = "SELECT
  311. " . $sSelectClause . "
  312. FROM `" . $CNF['TABLE_TIME_TRACK'] . "` AS `ttt` " . $sJoinClause . "
  313. WHERE 1 " . $sWhereClause . " " . $sOrderClause;
  314. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  315. }
  316. public function insertTimeTrack($aParamsSet)
  317. {
  318. $CNF = &$this->_oConfig->CNF;
  319. if(empty($aParamsSet))
  320. return false;
  321. return $this->query("INSERT INTO `" . $CNF['TABLE_TIME_TRACK'] . "` SET " . $this->arrayToSQL($aParamsSet)) ? $this->lastId() : false;
  322. }
  323. public function getTimers($aParams = [])
  324. {
  325. $CNF = &$this->_oConfig->CNF;
  326. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  327. $sSelectClause = '`tt`.*';
  328. $sJoinClause = $sWhereClause = $sOrderClause = '';
  329. if(!empty($aParams))
  330. switch($aParams['sample']) {
  331. case 'id':
  332. $aMethod['name'] = 'getRow';
  333. $aMethod['params'][1] = [
  334. 'id' => $aParams['id']
  335. ];
  336. $sWhereClause = "AND `tt`.`id` = :id";
  337. break;
  338. case 'content_profile_ids':
  339. $aMethod['name'] = 'getRow';
  340. $aMethod['params'][1] = [
  341. 'content_id' => $aParams['content_id'],
  342. 'profile_id' => $aParams['profile_id']
  343. ];
  344. $sWhereClause = "AND `tt`.`content_id` = :content_id AND `tt`.`profile_id` = :profile_id";
  345. break;
  346. case 'profile_id':
  347. $aMethod['params'][1] = [
  348. 'profile_id' => $aParams['profile_id']
  349. ];
  350. $sWhereClause = "AND `tt`.`profile_id` = :profile_id";
  351. if(isset($aParams['active']) && $aParams['active'] === true) {
  352. $aMethod['name'] = 'getRow';
  353. $sWhereClause .= " AND `tt`.`started` <> '0'";
  354. }
  355. break;
  356. }
  357. if(!empty($sOrderClause))
  358. $sOrderClause = "ORDER BY " . $sOrderClause;
  359. $aMethod['params'][0] = "SELECT
  360. " . $sSelectClause . "
  361. FROM `" . $CNF['TABLE_TIMERS'] . "` AS `tt` " . $sJoinClause . "
  362. WHERE 1 " . $sWhereClause . " " . $sOrderClause;
  363. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  364. }
  365. public function isTimerStarted($iObjectId, $iAuthorId)
  366. {
  367. $aTimer = $this->getTimers([
  368. 'sample' => 'content_profile_ids',
  369. 'content_id' => $iObjectId,
  370. 'profile_id' => $iAuthorId
  371. ]);
  372. return ($aTimer['started'] ?? 0) != 0;
  373. }
  374. public function insertTimer($aParamsSet)
  375. {
  376. $CNF = &$this->_oConfig->CNF;
  377. if(empty($aParamsSet))
  378. return false;
  379. return $this->query("INSERT INTO `" . $CNF['TABLE_TIMERS'] . "` SET " . $this->arrayToSQL($aParamsSet)) ? $this->lastId() : false;
  380. }
  381. public function updateTimer($aParamsSet, $aParamsWhere)
  382. {
  383. $CNF = &$this->_oConfig->CNF;
  384. if(empty($aParamsSet) || empty($aParamsWhere))
  385. return false;
  386. return $this->query("UPDATE `" . $CNF['TABLE_TIMERS'] . "` SET " . $this->arrayToSQL($aParamsSet) . " WHERE " . $this->arrayToSQL($aParamsWhere, " AND "));
  387. }
  388. public function deleteTimer($aParamsWhere)
  389. {
  390. $CNF = &$this->_oConfig->CNF;
  391. if(empty($aParamsWhere))
  392. return false;
  393. return $this->query("DELETE FROM `" . $CNF['TABLE_TIMERS'] . "` WHERE " . $this->arrayToSQL($aParamsWhere, " AND "));
  394. }
  395. public function getBudgetTracks($aParams = [])
  396. {
  397. $CNF = &$this->_oConfig->CNF;
  398. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  399. $sSelectClause = '`tbt`.*';
  400. $sJoinClause = $sWhereClause = $sOrderClause = '';
  401. if(!empty($aParams))
  402. switch($aParams['sample']) {
  403. case 'id':
  404. $aMethod['name'] = 'getRow';
  405. $aMethod['params'][1] = [
  406. 'id' => $aParams['id']
  407. ];
  408. $sWhereClause = "AND `tbt`.`id` = :id";
  409. break;
  410. }
  411. if(!empty($sOrderClause))
  412. $sOrderClause = "ORDER BY " . $sOrderClause;
  413. $aMethod['params'][0] = "SELECT
  414. " . $sSelectClause . "
  415. FROM `" . $CNF['TABLE_BUDGET_TRACK'] . "` AS `tbt` " . $sJoinClause . "
  416. WHERE 1 " . $sWhereClause . " " . $sOrderClause;
  417. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  418. }
  419. public function getBudget($aParams = [])
  420. {
  421. $CNF = &$this->_oConfig->CNF;
  422. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  423. $sSelectClause = '`tb`.*';
  424. $sJoinClause = $sWhereClause = $sOrderClause = '';
  425. if(!empty($aParams))
  426. switch($aParams['sample']) {
  427. case 'id':
  428. $aMethod['name'] = 'getRow';
  429. $aMethod['params'][1] = [
  430. 'id' => $aParams['id']
  431. ];
  432. $sWhereClause = "AND `tb`.`id` = :id";
  433. break;
  434. case 'context_id':
  435. $aMethod['name'] = 'getRow';
  436. $aMethod['params'][1] = [
  437. 'context_id' => $aParams['context_id']
  438. ];
  439. $sWhereClause = "AND `tb`.`context_id` = :context_id";
  440. break;
  441. }
  442. if(!empty($sOrderClause))
  443. $sOrderClause = "ORDER BY " . $sOrderClause;
  444. $aMethod['params'][0] = "SELECT
  445. " . $sSelectClause . "
  446. FROM `" . $CNF['TABLE_BUDGET'] . "` AS `tb` " . $sJoinClause . "
  447. WHERE 1 " . $sWhereClause . " " . $sOrderClause;
  448. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  449. }
  450. public function isBudgetByContext($iContextId)
  451. {
  452. $aBudget = $this->getBudget([
  453. 'sample' => 'context_id',
  454. 'context_id' => $iContextId
  455. ]);
  456. return $aBudget && is_array($aBudget);
  457. }
  458. public function insertBudget($iContextId, $iValueTotal = 0, $iValueSpent = 0)
  459. {
  460. $CNF = &$this->_oConfig->CNF;
  461. return $this->query("INSERT INTO `" . $CNF['TABLE_BUDGET'] . "` (`context_id`, `value_total`, `value_spent`) VALUES (:context_id, :value_total, :value_spent) ON DUPLICATE KEY UPDATE `value_total`=`value_total`+:value_total, `value_spent`=`value_spent`+:value_spent", [
  462. 'context_id' => $iContextId,
  463. 'value_total' => $iValueTotal,
  464. 'value_spent' => $iValueSpent
  465. ]) !== false;
  466. }
  467. public function updateBudgetTotal($iContextId, $iValue)
  468. {
  469. return $this->updateBudgetValue('total', $iContextId, $iValue);
  470. }
  471. public function updateBudgetSpent($iContextId, $iValue)
  472. {
  473. return $this->updateBudgetValue('spent', $iContextId, $iValue);
  474. }
  475. public function updateBudgetValue($sField, $iContextId, $iValue)
  476. {
  477. $CNF = &$this->_oConfig->CNF;
  478. return $this->query("UPDATE `" . $CNF['TABLE_BUDGET'] . "` SET `value_" . $sField . "` = `value_" . $sField . "` + :value WHERE `context_id` = :context_id", [
  479. 'context_id' => $iContextId,
  480. 'value' => $iValue,
  481. ]) !== false;
  482. }
  483. public function getPreLists($aParams = [])
  484. {
  485. $CNF = &$this->_oConfig->CNF;
  486. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  487. $sSelectClause = '`tpl`.*';
  488. $sJoinClause = $sWhereClause = $sOrderClause = '';
  489. if(!empty($aParams))
  490. switch($aParams['sample']) {
  491. case 'name':
  492. $aMethod['name'] = 'getRow';
  493. $aMethod['params'][1] = [
  494. 'name' => $aParams['name']
  495. ];
  496. $sWhereClause = "AND `tpl`.`name` = :name";
  497. break;
  498. }
  499. if(!empty($sOrderClause))
  500. $sOrderClause = "ORDER BY " . $sOrderClause;
  501. $aMethod['params'][0] = "SELECT
  502. " . $sSelectClause . "
  503. FROM `" . $CNF['TABLE_PRE_LISTS'] . "` AS `tpl` " . $sJoinClause . "
  504. WHERE 1 " . $sWhereClause . " " . $sOrderClause;
  505. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  506. }
  507. public function getPreValues($aParams = [])
  508. {
  509. $CNF = &$this->_oConfig->CNF;
  510. $aMethod = ['name' => 'getAll', 'params' => [0 => 'query']];
  511. $sSelectClause = '`tpv`.*';
  512. $sJoinClause = $sWhereClause = $sOrderClause = '';
  513. if(!empty($aParams))
  514. switch($aParams['sample']) {
  515. case 'value_to_use':
  516. $aMethod['name'] = 'getOne';
  517. $aMethod['params'][1] = [
  518. 'context_id' => $aParams['context_id'],
  519. 'list' => $aParams['list']
  520. ];
  521. $sSelectClause = "IF(ISNULL(MAX(`tpv`.`value`)), 0, MAX(`tpv`.`value`)) + 1";
  522. $sWhereClause = "AND `tpv`.`context_id` = :context_id AND `tpv`.`list` = :list";
  523. break;
  524. case 'id':
  525. $aMethod['name'] = 'getRow';
  526. $aMethod['params'][1] = [
  527. 'id' => $aParams['id']
  528. ];
  529. $sWhereClause = "AND `tpv`.`id` = :id";
  530. break;
  531. case 'context_list_value':
  532. $aMethod['name'] = 'getRow';
  533. $aMethod['params'][1] = [
  534. 'context_id' => $aParams['context_id'],
  535. 'list' => $aParams['list'],
  536. 'value' => $aParams['value']
  537. ];
  538. $sWhereClause = "AND `tpv`.`context_id` = :context_id AND `tpv`.`list` = :list AND `tpv`.`value` = :value";
  539. break;
  540. case 'context_list':
  541. $aMethod['name'] = 'getAllWithKey';
  542. $aMethod['params'][1] = 'value';
  543. $aMethod['params'][2] = [
  544. 'context_id' => $aParams['context_id'],
  545. 'list' => $aParams['list']
  546. ];
  547. $sWhereClause = "AND `tpv`.`context_id` = :context_id AND `tpv`.`list` = :list";
  548. if(($iActive = $aParams['active'] ?? false) !== false) {
  549. $aMethod['params'][2]['active'] = (int)$iActive;
  550. $sWhereClause .= " AND `tpv`.`active` = :active";
  551. }
  552. $sOrderClause = "`tpv`.`order` ASC";
  553. break;
  554. }
  555. if(!empty($sOrderClause))
  556. $sOrderClause = "ORDER BY " . $sOrderClause;
  557. $aMethod['params'][0] = "SELECT
  558. " . $sSelectClause . "
  559. FROM `" . $CNF['TABLE_PRE_VALUES'] . "` AS `tpv` " . $sJoinClause . "
  560. WHERE 1 " . $sWhereClause . " " . $sOrderClause;
  561. return call_user_func_array([$this, $aMethod['name']], $aMethod['params']);
  562. }
  563. /**
  564. * Legend:
  565. * grp - group
  566. * cnd - condition
  567. * cnds - conditions
  568. *
  569. * t - table
  570. * f - field
  571. * o - operation
  572. * v - value
  573. * j - joining type (INNER, LEFT)
  574. *
  575. * Addons:
  576. * +a - alias, like ta - table alias
  577. * +j - join, like tj - table join or fj - field join
  578. * +m - main, like tm - table main or fm - field main
  579. */
  580. protected function _getSqlJoinFrom($aCnd)
  581. {
  582. return $this->_getSqlClauseFrom('join', $aCnd);
  583. }
  584. protected function _getSqlJoinFromGroup($aGrp)
  585. {
  586. $sResult = "";
  587. if(empty($aGrp['cnds']) || !is_array($aGrp['cnds']))
  588. return $sResult;
  589. $sOprGrp = " ";
  590. foreach($aGrp['cnds'] as $aCnd)
  591. if(($sResultCnd = $this->_getSqlJoinFromCondition($aCnd)) != '')
  592. $sResult .= $sOprGrp . $sResultCnd;
  593. return trim($sResult, $sOprGrp);
  594. }
  595. protected function _getSqlJoinFromCondition($aCnd)
  596. {
  597. $sResult = "";
  598. if(!$this->_isJoinCondition($aCnd))
  599. return $sResult;
  600. $sFldJ = "`" . ($aCnd['taj'] ?? $aCnd['tj']) . "`.`" . $aCnd['fj'] . "`";
  601. $sFldM = "`" . $aCnd['fm'] . "`";
  602. if(($sTblAlsM = $aCnd['tam'] ?? ($aCnd['tm'] ?? false)))
  603. $sFldM = "`" . $sTblAlsM . "`." . $sFldM;
  604. return $aCnd['j'] . " JOIN `" . $aCnd['tj'] . "`" . (($sTblAlsJ = $aCnd['taj'] ?? false) ? " AS `" . $sTblAlsJ . "`" : "") . " ON (" . $sFldM . " = " . $sFldJ . ")";
  605. }
  606. protected function _getSqlWhereFrom($aCnd)
  607. {
  608. return $this->_getSqlClauseFrom('where', $aCnd);
  609. }
  610. protected function _getSqlWhereFromGroup($aGrp)
  611. {
  612. $sResult = "";
  613. if(!isset($aGrp['o'], $aGrp['cnds']) || empty($aGrp['cnds']) || !is_array($aGrp['cnds']))
  614. return $sResult;
  615. $sOprGrp = " " . $aGrp['o'] . " ";
  616. foreach($aGrp['cnds'] as $aCnd)
  617. if(($sResultCnd = $this->_getSqlWhereFrom($aCnd)) != '')
  618. $sResult .= $sOprGrp . $sResultCnd;
  619. if(($sResult = trim($sResult, $sOprGrp)) != '')
  620. $sResult = "(" . $sResult . ")";
  621. return $sResult;
  622. }
  623. protected function _getSqlWhereFromCondition($aCnd)
  624. {
  625. $sResult = "";
  626. if(!$this->_isWhereCondition($aCnd))
  627. return $sResult;
  628. if(($sMethod = '_getSqlWhereFromCondition' . bx_gen_method_name($aCnd['f'])) && method_exists($this, $sMethod)) {
  629. $mixedResult = $this->$sMethod($aCnd);
  630. if(!$this->_isWhereCondition($mixedResult))
  631. return $mixedResult;
  632. $aCnd = $mixedResult;
  633. }
  634. $sFld = "`" . $aCnd['f'] . "`";
  635. if(($sTbl = $aCnd['t'] ?? ''))
  636. $sFld = "`" . $sTbl . "`." . $sFld;
  637. switch($aCnd['o']) {
  638. case 'IN':
  639. if(empty($aCnd['v']) || !is_array($aCnd['v']))
  640. break;
  641. $sResult .= $sFld . " IN (" . $this->implode_escape($aCnd['v']) . ")";
  642. break;
  643. case 'NOT IN':
  644. if(empty($aCnd['v']) || !is_array($aCnd['v']))
  645. break;
  646. $sResult .= $sFld . " NOT IN (" . $this->implode_escape($aCnd['v']) . ")";
  647. break;
  648. case 'LIKE':
  649. $sResult .= $sFld . " LIKE " . $this->escape('%' . $aCnd['v'] . '%');
  650. break;
  651. default:
  652. $sResult .= $sFld . " " . $aCnd['o'] . " " . $this->escape($aCnd['v']);
  653. }
  654. return $sResult;
  655. }
  656. protected function _isJoinCondition($mixedCnd)
  657. {
  658. return is_array($mixedCnd) && isset($mixedCnd['j'], $mixedCnd['tj'], $mixedCnd['fj'], $mixedCnd['fm']);
  659. }
  660. protected function _isWhereCondition($mixedCnd)
  661. {
  662. return is_array($mixedCnd) && isset($mixedCnd['f'], $mixedCnd['v'], $mixedCnd['o']);
  663. }
  664. protected function _getSqlClauseFrom($sType, $aCnd)
  665. {
  666. $sMethod = '';
  667. if(($aCnd['grp'] ?? false) === true)
  668. $sMethod = 'Group';
  669. else if(($aCnd['cnd'] ?? false) === true)
  670. $sMethod = 'Condition';
  671. if(!$sMethod || !method_exists($this, ($sMethod = '_getSql' . bx_gen_method_name($sType) . 'From' . $sMethod)))
  672. return '';
  673. $sResult = $this->$sMethod($aCnd);
  674. if($sResult && $this->_aSqlMarkers)
  675. $sResult = bx_replace_markers($sResult, $this->_aSqlMarkers);
  676. return $sResult;
  677. }
  678. }
  679. /** @} */