Notify.php 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. <?php
  2. // @requires $_SERVER['SERVER_NAME']
  3. Lib::loadClass('RouteBase');
  4. Lib::loadClass('Przypomnij');
  5. Lib::loadClass('Request');
  6. Lib::loadClass('TypespecialVariable');
  7. Lib::loadClass('UI');
  8. Lib::loadClass('Router');
  9. Lib::loadClass('DBG');
  10. /*
  11. # Nofitication System:
  12. ## INSTALL - Nofitication System: index.php?_route=Notify&_task=reinstall&_force=true
  13. Sends mail by settings `CRM_NOTIFY`:
  14. - who - user login
  15. - when - shedule (once a day, once on houd)
  16. - what - action type
  17. - last_exec_time
  18. TODO: add after_action for Msgs to user/group
  19. TODO: add after_action for Tasks with special params:
  20. - Owner - notify after Worker change satus (100% done)
  21. - Worker - notify after Owner set him as a Worker to task
  22. */
  23. class Route_Notify extends RouteBase {
  24. public function handleAuth() {
  25. if (!User::logged()) {
  26. User::authByRequest();
  27. }
  28. }
  29. public function defaultAction() {
  30. UI::gora();
  31. UI::menu();
  32. try {
  33. $usrLogin = User::getLogin();
  34. $this->formUserTableReminder($usrLogin);
  35. } catch (Exception $e) {
  36. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  37. }
  38. UI::dol();
  39. }
  40. public function remindersPanelAction() {
  41. $usrLogin = User::getLogin();
  42. UI::gora();
  43. //UI::menu();
  44. {// init args
  45. $usrLogin = User::getLogin();
  46. $usrLogin = (isset($_REQUEST['usrLogin']))? V::get('usrLogin', '', $_REQUEST, 'login') : $usrLogin;
  47. if (!$usrLogin) die("Wrong user login!");
  48. $notifyTypeList = V::get('reminder', array(), $_REQUEST, 'array');
  49. if (!$notifyTypeList) {
  50. $userNotifyList = $this->getUserNotifyList($usrLogin);
  51. if (empty($userNotifyList)) die("Brak zdefiniowanych powiadomień");
  52. foreach ($userNotifyList as $notify) { $notifyTypeList[] = $notify['what']; }
  53. }
  54. }
  55. if ('1' == V::get('send', 0, $_POST, 'int')) {
  56. UI::alert('warning', "TODO: fix send, mark as sent");
  57. //$this->send($usrLogin, $notifyTypeList);
  58. //$this->markAsSent($usrLogin, $notifyTypeList);
  59. }
  60. $previewLink = $this->getLink('generateUserReminders', [
  61. 'usrLogin' => $usrLogin,
  62. 'reminder' => array_values($notifyTypeList),
  63. ]);
  64. $generateBaseLink = $this->getLink('generateUserReminders');
  65. $lastSentDate = 'brak';// TODO: getLastSendData($usrLogin);
  66. $typeSpecialUserLogin = TypespecialVariable::getInstance(-1, '__USER_LOGIN');
  67. ?>
  68. <div class="jumbotron">
  69. <div class="container">
  70. <form id="reminderPanelForm" class="form-horizontal" method="POST">
  71. <div class="form-group">
  72. <label class="col-sm-2 control-label">User</label>
  73. <div class="col-sm-10">
  74. <?php if ($typeSpecialUserLogin) : ?>
  75. <?php
  76. $fldName = 'usrLogin';
  77. $fldParams = array();
  78. $fldParams['allowCreate'] = false;
  79. $fldParams['ajaxDataUrlBase'] = "index.php?_route=Notify&_task=typeSpecialUserLogin";
  80. $fldParams['placeholder'] = 'Szukaj...';
  81. //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
  82. echo $typeSpecialUserLogin->showFormItem($tblID = -1, $fldName, $usrLogin, $fldParams);
  83. ?>
  84. <?php else : ?>
  85. <input class="form-control" type="text" name="usrLogin" value="<?php echo $usrLogin; ?>">
  86. <?php endif; ?>
  87. </div>
  88. </div>
  89. <?php foreach ($this->getFieldValueLabels('what') as $reminderType => $reminderLabel) : ?>
  90. <?php if ('l_app_all_przypomnij' == $reminderType) continue; ?>
  91. <div class="col-sm-3">
  92. <div class="checkbox">
  93. <label>
  94. <input type="checkbox"
  95. name="reminder[]"
  96. <?php if (in_array($reminderType, $notifyTypeList)) : ?>
  97. checked="checked"
  98. <?php endif; ?>
  99. value="<?php echo $reminderType; ?>"> <?php echo $reminderLabel; ?>
  100. </label>
  101. </div>
  102. </div>
  103. <?php endforeach; ?>
  104. <div class="col-sm-offset-2 col-sm-10" style="margin-top:10px;padding-top:10px;border-top:1px solid silver;">
  105. <button class="btn btn-default" onclick="refreshPreview(); return false;">odśwież podgląd</button>
  106. <button class="btn btn-primary" name="send" value="1">wyślij maila</button>
  107. data wysłania ostatniej wiadomości do wybranego użytkownika: <?php echo $lastSentDate; ?>
  108. </div>
  109. </form>
  110. </div>
  111. </div>
  112. <?php
  113. echo UI::h('script', [], "
  114. function refreshPreview() {
  115. var frm = document.getElementById('reminderPanelForm'),
  116. previewLink = '';
  117. previewLink = '{$generateBaseLink}' + '&usrLogin=' + frm['usrLogin'].value;
  118. for (var i in frm['reminder[]']) {
  119. // console.log('frm[reminder[]]['+i+']', frm['reminder[]'][i].value, ' checked:', frm['reminder[]'][i].checked);
  120. if (frm['reminder[]'][i].checked) {
  121. previewLink += '&reminder[]=' + frm['reminder[]'][i].value;
  122. }
  123. }
  124. // console.log('frm[reminder[]].', frm['reminder[]']);
  125. // console.log('frm[reminder[]].value', frm['reminder[]'].value);
  126. // console.log('previewLink:', previewLink);
  127. document.getElementById('reminderPreview').src = previewLink;
  128. }
  129. ");
  130. echo UI::h('div', [], [
  131. UI::h('iframe', [
  132. 'id' => "reminderPreview",
  133. 'src' => $previewLink,
  134. 'style' => "width:100%;height:500px;max-height:500px;overflow:scroll;border:2px solid silver"
  135. ]),
  136. ]);
  137. UI::dol();
  138. }
  139. public function typeSpecialUserLoginAction() {
  140. header("Content-type: application/json");
  141. $typeSpecialUserId = TypespecialVariable::getInstance(-1, '__USER_LOGIN');
  142. if (!$typeSpecialUserId) {
  143. $jsonData = new stdClass();
  144. $jsonData->message = "TypeSpecial '__USER_LOGIN' not exists";
  145. echo json_encode($jsonData);
  146. exit;
  147. }
  148. $query = V::get('q', '', $_REQUEST);
  149. $rawRows = null;
  150. $jsonData = array();
  151. $queryParams = array();
  152. $rows = $typeSpecialUserId->getValuesWithExports($query, $queryParams);
  153. foreach ($rows as $kID => $vItem) {
  154. $itemJson = new stdClass();
  155. $itemJson->id = $vItem->id;
  156. $itemJson->name = $vItem->param_out;
  157. if (!empty($vItem->exports)) {
  158. $itemJson->exports = $vItem->exports;
  159. }
  160. $jsonData[] = $itemJson;
  161. }
  162. echo json_encode($jsonData);
  163. }
  164. /**
  165. * @param $userReminders {'once_a_day' => {$type => $last_exec_time}, 'immediately' => {$type => $last_exec_time}}
  166. */
  167. public function sendUserReminders($who, $userReminders, $forceMail = null) {
  168. // DBG::_('DBG_NTF', '>1', "reminders.1", $userReminders, __CLASS__, __FUNCTION__, __LINE__);
  169. // remove duplicates
  170. if (!empty($userReminders['once_a_day']) && !empty($userReminders['immediately'])) {
  171. foreach ($userReminders['once_a_day'] as $what => $last_exec) {
  172. if (array_key_exists($what, $userReminders['immediately'])) {
  173. // DBG::_('DBG_NTF', '>2', "skip immediately '{$what}' for '{$who}'", $userReminders['immediately'][$what], __CLASS__, __FUNCTION__, __LINE__);
  174. unset($userReminders['immediately'][$what]);
  175. }
  176. }
  177. if (empty($userReminders['immediately'])) unset($userReminders['immediately']);
  178. }
  179. // DBG::_('DBG_NTF', '>1', "reminders.2", $userReminders, __CLASS__, __FUNCTION__, __LINE__);
  180. foreach ($userReminders as $when => $listWhat) {
  181. if (!empty($listWhat)) {
  182. $reminders = array_keys($listWhat);
  183. echo "<p>Sending to {$who} reminders [" . implode(",", $reminders) . "] at '{$when}'</p>" . "\n";
  184. $this->send($who, $listWhat, $when, $forceMail);
  185. $this->markAsSent($who, $listWhat, $when);
  186. }
  187. }
  188. }
  189. /**
  190. * @param $reminders array( )
  191. * @param $when 'once_a_day', 'immediately'
  192. */
  193. public function send($usrLogin, $reminders, $when = null, $forceMail = null) {
  194. DBG::_('DBG_NTF', '>1', "usrLogin", $usrLogin, __CLASS__, __FUNCTION__, __LINE__);
  195. DBG::_('DBG_NTF', '>1', "reminders(when: {$when})", $reminders, __CLASS__, __FUNCTION__, __LINE__);
  196. $mainMail = $this->getUserMainMail($usrLogin);
  197. $msgNote = '';
  198. if (!empty($forceMail)) {
  199. $mainMail = $forceMail;
  200. if (empty($user['aliasy'])) $msgNote .= 'ERROR: Brak lokalnego adresu email' . "\n\n";
  201. }
  202. $pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i";
  203. if (!preg_match($pattern, $mainMail)) throw new Exception("Adres email ma błędny format");
  204. $usrReminders = $this->getUserReminders($usrLogin, $reminders, $when);
  205. if (empty($usrReminders)) {
  206. DBG::_('DBG_NTF', '>0', "Skip usr({$usrLogin}) - no remindres", $usrReminders, __CLASS__, __FUNCTION__, __LINE__);
  207. return;
  208. }
  209. $to = $mainMail;
  210. $headers = "From: " . "noreply@{$_SERVER['SERVER_NAME']}" . "\r\n";
  211. $headers .= "MIME-Version: 1.0\r\n";
  212. $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
  213. if (null == $when || 'once_a_day' == $when) {
  214. $subject = "Powiadomienia dla {$usrLogin} - " . date("Y-m-d") . " - {$_SERVER['SERVER_NAME']}";
  215. } else {
  216. $subject = "Nowe powiadomienia dla {$usrLogin} - {$_SERVER['SERVER_NAME']}";
  217. }
  218. ob_start();
  219. $this->viewUserReminders($usrReminders, $usrLogin);
  220. echo "\n\n<br><br>\nWiadomość została wygenerowana automatycznie." . "\n\n";
  221. {
  222. $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE";
  223. if ('biuro.biall-net.pl' == $_SERVER['SERVER_NAME']) $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE/version-git";
  224. $notifyLink = "{$baseUrl}/index.php?_route=Notify";
  225. echo "<br><br>\nPowiadomienia można ustawić na: <a href=\"{$notifyLink}\">{$notifyLink}</a>." . "\n\n";
  226. }
  227. $message = ob_get_clean();
  228. trigger_error("send msg to {$to} ({$usrLogin}) when='{$when}'", E_USER_NOTICE);
  229. if (!mail($to, $subject, $message, $headers)) {
  230. trigger_error("Cannot send msg to {$to} ({$usrLogin}) when='{$when}'", E_USER_WARNING);
  231. throw new Exception("Nie udało się wysłać powiadomienia");
  232. }
  233. }
  234. public function getUserMainMail($usrLogin) {
  235. $sqlUserLogin = DB::getPDO()->quote($usrLogin);
  236. $sql = "
  237. select u.ID, u.ADM_ACCOUNT as login, u.EMAIL_LOCAL_ACCOUNT_ADDRESS as aliasy
  238. from ADMIN_USERS u
  239. where u.ADM_ACCOUNT = {$sqlUserLogin}
  240. ";
  241. $user = DB::getPDO()->fetchFirst($sql);
  242. if (!$user) throw new Exception("User not found");
  243. if (empty($user['aliasy'])) throw new Exception("Brak lokalnego adresu email");
  244. $aliasy = explode(' ', trim($user['aliasy']));
  245. return reset($aliasy);
  246. }
  247. public function markAsSent($usrLogin, $reminders, $when) {
  248. // $sqlReminderTypes = "'" . implode("','", $notifyTypeList) . "'";
  249. $sqlReminderTypes = "'" . implode("','", array_keys($reminders)) . "'";
  250. $sth = DB::getPDO()->prepare("
  251. update CRM_NOTIFY
  252. set `last_exec_time` = NOW()
  253. where `who` = :login
  254. and `when` = :when
  255. and `what` in({$sqlReminderTypes})
  256. ");
  257. $sth->bindValue(':login', $usrLogin, PDO::PARAM_STR);
  258. $sth->bindValue(':when', $when, PDO::PARAM_STR);
  259. $sth->execute();
  260. }
  261. public function generateUserRemindersAction() {
  262. $usrLogin = User::getLogin();
  263. $usrLogin = (isset($_GET['usrLogin']))? V::get('usrLogin', '', $_GET, 'login') : $usrLogin;
  264. if (!$usrLogin) die("Wrong user login!");
  265. $notifyTypeList = V::get('reminder', array(), $_GET, 'array');
  266. if (!$notifyTypeList) {
  267. $userNotifyList = $this->getUserNotifyList($usrLogin);
  268. if (empty($userNotifyList)) die("Brak zdefiniowanych powiadomień");
  269. foreach ($userNotifyList as $notify) { $notifyTypeList[] = $notify['what']; }
  270. }
  271. header('Content-Type: text/html; charset="UTF-8"');
  272. $usrReminders = $this->getAllUserReminders($usrLogin, $notifyTypeList);
  273. $this->viewUserReminders($usrReminders, $usrLogin);
  274. }
  275. /**
  276. * @param $reminders - array( $notifyType )
  277. */
  278. public function getAllUserReminders($usrLogin, $notifyTypeList) {
  279. $usrReminders = array();
  280. foreach ($notifyTypeList as $notifyType) {
  281. $listTodo = $this->getTodoForUserReminder($usrLogin, $notifyType);
  282. if (!empty($listTodo)) $usrReminders[$notifyType] = $listTodo;
  283. }
  284. return $usrReminders;
  285. }
  286. /**
  287. * @param $reminders - array( $notifyType => $lastExecTime )
  288. */
  289. public function getUserReminders($usrLogin, $reminders, $when = null) {
  290. $usrReminders = array();
  291. foreach ($reminders as $notifyType => $lastExecTime) {
  292. $fetchFromTime = (null == $when || 'once_a_day' == $when)? null : $lastExecTime;
  293. $listTodo = $this->getTodoForUserReminder($usrLogin, $notifyType, $fetchFromTime);
  294. if (!empty($listTodo)) $usrReminders[$notifyType] = $listTodo;
  295. }
  296. return $usrReminders;
  297. }
  298. public function viewUserReminders($usrReminders, $usrLogin) {
  299. echo '<html>';
  300. echo '<body>';
  301. echo '<div>';
  302. ?>
  303. <h1 style="<?php echo $this->inlineCss('h1'); ?>">Powiadomienia dla <code><?php echo $usrLogin; ?></code></h1>
  304. <?php foreach ($usrReminders as $reminderType => $listTodo) : ?>
  305. <div style="<?php echo $this->inlineCss('header'); ?>"><strong><?php echo $this->printValue('what', $reminderType); ?></strong></div>
  306. <table rules="all" cellspacing="0" style="border-color:#bbb;" cellpadding="8">
  307. <?php $lp = 0; foreach ($listTodo as $todo) : ?>
  308. <tr>
  309. <td style="<?php echo $this->inlineCss('td.lp'); ?>"><?php echo ++$lp; ?></td>
  310. <td style="<?php echo $this->inlineCss('td.' . $todo['_l_app_class']); ?>">
  311. <span style="<?php echo $this->inlineCss('l_app_date.' . $todo['_l_app_class']); ?>"><?php echo $todo['_l_app_date']; ?></span>
  312. <br><i style="<?php echo $this->inlineCss('l_app.target'); ?>"><?php echo $todo['_l_app']; ?></i>
  313. <?php if (V::get('ID', '', $todo) > 0) : ?>
  314. <br><a href="<?php echo $this->editLink($todo); ?>" target="_blank" style="<?php echo $this->inlineCss('a'); ?>">Edytuj rekord <?php echo $todo['ID']; ?></a>
  315. <?php elseif (V::get('idMsg', '', $todo) > 0) : ?>
  316. <br><a href="<?php echo $this->readMsgLink($usrLogin, $todo); ?>" target="_blank" style="<?php echo $this->inlineCss('a'); ?>">Przeczytaj</a>
  317. <?php endif; ?>
  318. </td>
  319. <td style="<?php echo $this->inlineCss('td.info'); ?>"><?php echo $todo['L_APPOITMENT_INFO']; ?></td>
  320. <td style="<?php echo $this->inlineCss('td.record-info'); ?>">
  321. <?php echo $todo['_title']; ?>
  322. </td>
  323. <?php if (V::get('DBG', '', $_GET)) : ?>
  324. <td style="<?php echo $this->inlineCss('td.record-desc'); ?>"><pre style="border:1px solid red;max-height:80px;overflow:scroll"><?php print_r($todo); ?></pre></td>
  325. <?php endif; ?>
  326. </tr>
  327. <?php endforeach; ?>
  328. </table>
  329. <?php endforeach; ?>
  330. <?php
  331. echo '</div>';// .container
  332. echo '</body>';
  333. echo '</html>';
  334. }
  335. public function editLink($todo) {
  336. $idTblZasob = 0;
  337. $idRecord = 0;
  338. if ('zasob' == $todo['_task_type']
  339. || 'proces' == $todo['_task_type']
  340. || 'projekt' == $todo['_task_type']
  341. || 'koresp' == $todo['_task_type']
  342. || 'task' == $todo['_task_type']
  343. ) {
  344. $idTblZasob = $todo['_idZasobTable'];
  345. $idRecord = $todo['ID'];
  346. }
  347. if (!$idTblZasob || !$idRecord) return '#';
  348. return Router::getRoute('ViewTableajax')->getLink('', [
  349. 'namespace' => ACL::getNamespaceFromId($idTblZasob),
  350. ]) . "#EDIT/{$idRecord}";
  351. }
  352. public function readMsgLink($usrLogin, $todo) {
  353. $idMsg = 0;
  354. if ('msg' == $todo['_task_type']) {
  355. $idMsg = $todo['idMsg'];
  356. }
  357. if (!$idMsg) return '#' . json_encode($todo);
  358. if (!$idMsg) return '#';
  359. return Router::getRoute('UserMsgs')->getLink('read', [ 'usrLogin' => $usrLogin, 'id' => $idMsg ]);
  360. }
  361. public function inlineCss($cssSelector) {
  362. $baseCss = array();
  363. $baseCss['font-family'] = 'Arial, Helvetica, sans-serif';
  364. $baseCss['font-size'] = 'small';
  365. $baseCss['color'] = '#333';
  366. $customCss = array(
  367. 'h1' => array(),
  368. 'header' => array('background' => '#eee', 'padding' => '4px 10px', 'margin-top' => '6px'),
  369. 'l_app.target' => array('color' => '#999', 'white-space' => 'nowrap'),
  370. 'td.date-base' => array('white-space' => 'nowrap'),
  371. 'td.lp' => array('color' => 'silver'),
  372. 'l_app_date-base' => array('white-space' => 'nowrap'),
  373. 'a' => array('color' => '#337ab7', 'text-decoration' => 'none')
  374. );
  375. $css = $baseCss;
  376. if (array_key_exists($cssSelector, $customCss)) $css = V::extend($css, $customCss[$cssSelector]);
  377. if ('td.date-' == substr($cssSelector, 0, 8)) {
  378. $css = V::extend($css, $customCss['td.date-base']);
  379. $css = V::extend($css, array('color' => $this->getTodoDateCssColor(substr($cssSelector, 3))));
  380. }
  381. if ('l_app_date.date-' == substr($cssSelector, 0, 16)) {
  382. $css = V::extend($css, $customCss['l_app_date-base']);
  383. $css = V::extend($css, array('color' => $this->getTodoDateCssColor(substr($cssSelector, 11))));
  384. }
  385. $inlineCss = array();
  386. foreach ($css as $cssPropName => $cssValue) {
  387. if (true === $cssValue) {
  388. if (!array_key_exists($cssPropName, $baseCss)) continue;
  389. $cssValue = $baseCss[$cssPropName];
  390. }
  391. $inlineCss[] = "{$cssPropName}:{$cssValue}";
  392. }
  393. return implode(";", $inlineCss);
  394. }
  395. public function getTodoDateCssColor($lAppClass) {
  396. $color = '#000';
  397. switch ($lAppClass) {
  398. case 'date-PO_TERMINIE': $color = '#FD4242'; break;
  399. case 'date-DZISIAJ': $color = '#34B934'; break;
  400. case 'date-W_CIAGU_7_DNI': $color = '#C58B1F'; break;
  401. case 'date-PO_7_DNIACH': $color = '#87847D'; break;
  402. }
  403. return $color;
  404. }
  405. public function getTodoForUserReminder($usrLogin, $reminderWhat, $lastExecTime = null) {
  406. $listTodo = array();
  407. if ('msgs' == $reminderWhat) {
  408. $routeMsgs = Router::getRoute('UserMsgs');
  409. $routeMsgs->_listLimit = 50;
  410. $msgs = $routeMsgs->getMsgs('unread', $usrLogin, $lastMsgId = null, $lastExecTime);
  411. foreach ($msgs as $idMsg => $msg) {
  412. $todo = array();
  413. $todo['_task_type'] = 'msg';
  414. // [userTargetType] => group
  415. // [userTargetName] => 2948
  416. $todo['_l_app'] = '';
  417. if ('group' == $msg['_raw']->userTargetType) {
  418. $todo['_l_app'] = "do grupy {$msg['_raw']->userTargetName}";
  419. } else if ('user' == $msg['_raw']->userTargetType) {
  420. $todo['_l_app'] = "do {$msg['_raw']->userTargetName}";
  421. }
  422. $todo['idMsg'] = $idMsg;
  423. $todo['_l_app_date'] = substr($msg['_raw']->A_RECORD_CREATE_DATE, 0, 10);
  424. $todo['_l_app_class'] = 'date-PO_TERMINIE';
  425. $todo['L_APPOITMENT_INFO'] = $msg['message'];
  426. // $msg['_raw']->A_STATUS == 'WAITING' => Unread
  427. // $msg['_raw']->A_STATUS == 'NORMAL' => Read
  428. // $msg['_raw']->A_STATUS == 'OFF_SOFT' => Trash
  429. $msgInfo = '<i style="color:silver">' . "Wysłane {$msg['_raw']->A_RECORD_CREATE_DATE} przez {$msg['_raw']->A_RECORD_CREATE_AUTHOR}" . '</i>';
  430. if ('NORMAL' == $msg['_raw']->A_STATUS) $msgInfo .= '<br><i style="color:silver">' . "Przeczytane {$msg['_raw']->A_RECORD_UPDATE_DATE} przez {$msg['_raw']->A_RECORD_UPDATE_AUTHOR}" . '</i>';
  431. $todo['_title'] = $msgInfo;
  432. $listTodo[] = $todo;
  433. }
  434. }
  435. else if ('l_app_projekty' == $reminderWhat) {
  436. $tasks = $this->getPrzypomnijTasks($usrLogin);
  437. foreach ($tasks as $task) {
  438. if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
  439. if ('projekt' != $task['_task_type']) continue;
  440. //$task['DESC'] = $task['A_PROBLEM_DESC'];
  441. if (!$this->filterTaskByTime($task, $lastExecTime)) continue;
  442. $listTodo[] = $task;
  443. }
  444. }
  445. else if ('l_app_koresp' == $reminderWhat) {
  446. $tasks = $this->getPrzypomnijTasks($usrLogin);
  447. foreach ($tasks as $task) {
  448. if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
  449. if ('koresp' != $task['_task_type']) continue;
  450. //$task['DESC'] = $task['A_PROBLEM_DESC'];
  451. if (!$this->filterTaskByTime($task, $lastExecTime)) continue;
  452. $listTodo[] = $task;
  453. }
  454. }
  455. else if ('l_app_zadania' == $reminderWhat) {
  456. $tasks = $this->getPrzypomnijTasks($usrLogin);
  457. foreach ($tasks as $task) {
  458. if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
  459. if ('task' != $task['_task_type']) continue;
  460. //$task['DESC'] = $task['A_PROBLEM_DESC'];
  461. if (!$this->filterTaskByTime($task, $lastExecTime)) continue;
  462. $listTodo[] = $task;
  463. }
  464. }
  465. else if ('l_app_procesy' == $reminderWhat) {
  466. $tasks = $this->getPrzypomnijTasks($usrLogin);
  467. foreach ($tasks as $task) {
  468. if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
  469. if ('proces' != $task['_task_type']) continue;
  470. if (!$this->filterTaskByTime($task, $lastExecTime)) continue;
  471. $listTodo[] = $task;
  472. }
  473. }
  474. else if ('l_app_zasoby' == $reminderWhat) {
  475. $tasks = $this->getPrzypomnijTasks($usrLogin);
  476. foreach ($tasks as $task) {
  477. if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
  478. if ('zasob' != $task['_task_type']) continue;
  479. if (!$this->filterTaskByTime($task, $lastExecTime)) continue;
  480. $listTodo[] = $task;
  481. }
  482. }
  483. return $listTodo;
  484. }
  485. public function filterTaskByTime($task, $lastExecTime) {
  486. if (null == $lastExecTime) return true;
  487. if (empty($task['A_RECORD_CREATE_DATE'])) return true;
  488. if ($task['A_RECORD_CREATE_DATE'] >= $lastExecTime) return true;
  489. if (empty($task['A_RECORD_UPDATE_DATE'])) {
  490. DBG::_('DBG_NTF', '>1', "skip task by lastExecTime({$lastExecTime}) - empty update date", $task, __CLASS__, __FUNCTION__, __LINE__);
  491. return false;
  492. } else if ($task['A_RECORD_UPDATE_DATE'] < $lastExecTime) {
  493. DBG::_('DBG_NTF', '>1', "skip task by lastExecTime({$lastExecTime}) - old update date", $task, __CLASS__, __FUNCTION__, __LINE__);
  494. return false;
  495. }
  496. return true;
  497. }
  498. public function getPrzypomnijTasks($usrLogin) {
  499. static $_tasks = array();
  500. if (empty($_tasks[$usrLogin])) {
  501. $_tasks[$usrLogin] = array();
  502. $przypomnij = new Przypomnij();
  503. $przypomnij->setRecurseLimit(3);
  504. $przypomnij->fetchData($usrLogin);
  505. $przypomnij->setFltrUser($usrLogin);
  506. $tasks = $przypomnij->getTasksByDate();
  507. {
  508. $usrGroupNames = array();
  509. //$usrGroupNames = User::getLdapGroupsNames();
  510. Lib::loadClass('UsersLdapHelper');
  511. $ldapGroups = UsersLdapHelper::getUserGroups($usrLogin, 3);
  512. foreach ($ldapGroups as $kID => $vLDAPGroup) {
  513. $usrGroupNames[$kID] = $vLDAPGroup->cn;
  514. }
  515. }
  516. foreach ($tasks as $task) {
  517. if (!$task->_show) continue;
  518. if (
  519. $task->A_CLASSIFIED != ''
  520. && !(in_array($task->A_CLASSIFIED, $usrGroupNames))
  521. && $task->A_ADM_COMPANY != ''
  522. && !(in_array($task->A_ADM_COMPANY, $usrGroupNames))
  523. // !($allowedUsers[$task->_l_app]) - to jest bez sensu - wystarczy widocznosc sprawy?
  524. ) {
  525. continue;
  526. }
  527. $task->_l_app_class = $przypomnij->getTaskDateFltrType($task->_l_app_date);
  528. $task->_idZasobTable = $przypomnij->getZasobIdByType($task->_task_type);
  529. $_tasks[$usrLogin][] = (array)$task;
  530. }
  531. }
  532. return $_tasks[$usrLogin];
  533. }
  534. public function removeUserTableReminder($args) {
  535. $usrLogin = User::getLogin();
  536. $who = V::validate('who', $args, array('type'=>'login', 'equal'=>$usrLogin, 'error_msg_equal'=>"Brak uprawnień do wprowadzania zmian w powiadomieniach innych użytwkoników"));
  537. $what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$this->getFieldValues('what')));
  538. $when = V::validate('when', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$this->getFieldValues('when')));
  539. if ($usrLogin != $who) throw new Exception("Brak uprawnień do wprowadzania zmian w powiadomieniach innych użytwkoników");
  540. $pdo = DB::getPDO();
  541. $sth = $pdo->prepare("
  542. delete from `CRM_NOTIFY`
  543. where `who` = :who
  544. and `what` = :what
  545. and `when` = :when
  546. ");
  547. $sth->bindValue(':who', $usrLogin, PDO::PARAM_STR);
  548. $sth->bindValue(':what', $what, PDO::PARAM_STR);
  549. $sth->bindValue(':when', $when, PDO::PARAM_STR);
  550. $sth->execute();
  551. }
  552. public function formUserTableReminder($usrLogin) {
  553. echo '<div class="container">';
  554. $subTask = V::get('_subTask', '', $_POST);
  555. if ('_add_table_reminder' == $subTask) {
  556. try {
  557. $this->addUserTableReminder($usrLogin, $_POST);
  558. UI::alert('info', "Dodano powiadomienie");
  559. } catch (PDOException $e) {
  560. if (!empty($e->errorInfo) && !empty($e->errorInfo[1]) && '1062' == $e->errorInfo[1]) {
  561. UI::alert('warning', "Powiadomienie tego typu zostało już wcześniej dodane");
  562. } else {
  563. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage() . '<br>' . "Info: " . json_encode($e->errorInfo));
  564. }
  565. } catch (Exception $e) {
  566. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  567. }
  568. }
  569. else if ('_rm_table_reminder' == $subTask) {
  570. try {
  571. $this->removeUserTableReminder($_POST);
  572. UI::alert('info', "Usunięto powiadomienie");
  573. } catch (Exception $e) {
  574. UI::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  575. }
  576. }
  577. $userNotifyList = $this->getUserNotifyList($usrLogin);
  578. $userMail = $this->getUserMainMail($usrLogin);
  579. $whatLabelsForOnceADay = $this->getFieldValueLabels('what', $userNotifyList, $when = 'once_a_day');
  580. $whatLabelsForImmediately = $this->getFieldValueLabels('what', $userNotifyList, $when = 'immediately');
  581. echo UI::h('h1', [], "Powiadomienia dla <code>{$usrLogin}</code>");
  582. echo UI::h('p', [ 'style' => "font-style:italic" ], [
  583. "Będą wysyłane na adres: {$userMail}. ",
  584. UI::h('a', [
  585. 'href' => $this->getLink('generateUserReminders', [
  586. 'usrLogin' => $usrLogin,
  587. ])
  588. ], 'podgląd'),
  589. ]);
  590. if (empty($userNotifyList)) {
  591. UI::alert('warning', "Brak zdefiniowanych powiadomień");
  592. } else {
  593. $this__printValue = [$this, 'printValue'];
  594. UI::table([ // <table class="table table-hover">
  595. 'disable_lp' => true,
  596. '@class' => 'table table-hover',
  597. 'cell_padding' => 8,
  598. 'rows' => array_map(function ($notify) use ($usrLogin, $this__printValue) {
  599. return [
  600. 'rodzaj' => $this__printValue('what', $notify['what']),
  601. 'jak często' => $this__printValue('when', $notify['when']),
  602. 'utworzony' => $notify['_created'],
  603. 'ostatnio uruchomiony' => $notify['last_exec_time'] ? $notify['last_exec_time'] : '<i>brak danych</i>',
  604. '#' => UI::h('form', [ 'method' => "post", 'class' => "form-inline" ], [
  605. UI::h('input', [ 'type' => "hidden", 'name' => "_subTask", 'value' => "_rm_table_reminder" ]),
  606. UI::h('input', [ 'type' => "hidden", 'name' => "who", 'value' => $usrLogin ]),
  607. UI::h('input', [ 'type' => "hidden", 'name' => "what", 'value' => $notify['what'] ]),
  608. UI::h('input', [ 'type' => "hidden", 'name' => "when", 'value' => $notify['when'] ]),
  609. UI::h('button', [
  610. 'class' => "btn btn-link btn-xs",
  611. 'onclick' => "return confirm('Czy usunąć powiadomienie?')",
  612. 'type' => "submit"
  613. ], '<i class="glyphicon glyphicon-remove" style="color:red;opacity:0.4;"></i>'),
  614. ]),
  615. ];
  616. }, $userNotifyList)
  617. ]);
  618. }
  619. ?>
  620. <?php if (!empty($whatLabelsForOnceADay)) : ?>
  621. <hr>
  622. <h4>Dodaj powiadomienia wysyłane raz dziennie:</h4>
  623. <form method="post" class="form-inline">
  624. <input type="hidden" name="_subTask" value="_add_table_reminder">
  625. <input type="hidden" name="when" value="once_a_day">
  626. <label>rodzaj:</label>
  627. <select type="select" name="what" class="form-control">
  628. <option value="">[ Wybierz ]</option>
  629. <?php foreach ($whatLabelsForOnceADay as $value => $label) : ?>
  630. <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
  631. <?php endforeach; ?>
  632. </select>
  633. <input type="submit" value="Dodaj" class="btn btn-primary">
  634. </form>
  635. <?php endif; ?>
  636. <?php if (!empty($whatLabelsForImmediately)) : ?>
  637. <hr>
  638. <h4>Dodaj powiadomienia wysyłane na bieżąco:</h4>
  639. <form method="post" class="form-inline">
  640. <input type="hidden" name="_subTask" value="_add_table_reminder">
  641. <input type="hidden" name="when" value="immediately">
  642. <label>rodzaj:</label>
  643. <select type="select" name="what" class="form-control">
  644. <option value="">[ Wybierz ]</option>
  645. <?php foreach ($whatLabelsForImmediately as $value => $label) : ?>
  646. <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
  647. <?php endforeach; ?>
  648. </select>
  649. <input type="submit" value="Dodaj" class="btn btn-primary">
  650. </form>
  651. <?php endif; ?>
  652. <?php
  653. echo '</div>';// .container
  654. }
  655. public function printValue($fldName, $argValue) {
  656. if ('what' == $fldName || 'when' == $fldName) {
  657. $valueLabels = $this->getFieldValueLabels($fldName);
  658. return V::get($argValue, $argValue, $valueLabels);
  659. }
  660. return $argValue;
  661. }
  662. public function getAllPrzypomnijTypes() {
  663. $allPrzypomnijTypes = array();
  664. $allPrzypomnijTypes[] = 'msgs';
  665. $allPrzypomnijTypes[] = 'l_app_projekty';
  666. $allPrzypomnijTypes[] = 'l_app_koresp';
  667. $allPrzypomnijTypes[] = 'l_app_zadania';
  668. $allPrzypomnijTypes[] = 'l_app_procesy';
  669. $allPrzypomnijTypes[] = 'l_app_zasoby';
  670. return $allPrzypomnijTypes;
  671. }
  672. public function getFieldValueLabels($fldName, $userNotifyList = null, $when = null) {
  673. $valueLabels = array();
  674. if ('what' == $fldName) {
  675. if (null == $userNotifyList) $userNotifyList = array();
  676. if ('once_a_day' == $when) {
  677. $valueLabels['msgs'] = "wiadomości";
  678. $valueLabels['l_app_projekty'] = "projekty";
  679. $valueLabels['l_app_koresp'] = "korespondencja";
  680. $valueLabels['l_app_zadania'] = "zadania";
  681. $valueLabels['l_app_procesy'] = "procesy";
  682. $valueLabels['l_app_zasoby'] = "zasoby";
  683. $valueLabels['l_app_all_przypomnij'] = "*wszystkie";
  684. if (!empty($userNotifyList)) {// filter out existing notify
  685. foreach ($userNotifyList as $notify) {
  686. if ($when == $notify['when'] && array_key_exists($notify['what'], $valueLabels)) {
  687. unset($valueLabels[$notify['what']]);
  688. }
  689. }
  690. if (1 == count($valueLabels) && !empty($valueLabels['l_app_all_przypomnij'])) {
  691. unset($valueLabels['l_app_all_przypomnij']);
  692. }
  693. }
  694. } else if ('immediately' == $when) {
  695. $valueLabels['msgs'] = "wiadomości";
  696. $valueLabels['l_app_zadania'] = "zadania";
  697. if (!empty($userNotifyList)) {// filter out existing notify
  698. foreach ($userNotifyList as $notify) {
  699. if ($when == $notify['when'] && array_key_exists($notify['what'], $valueLabels)) {
  700. unset($valueLabels[$notify['what']]);
  701. }
  702. }
  703. }
  704. } else {
  705. $valueLabels['msgs'] = "wiadomości";
  706. $valueLabels['l_app_projekty'] = "projekty";
  707. $valueLabels['l_app_koresp'] = "korespondencja";
  708. $valueLabels['l_app_zadania'] = "zadania";
  709. $valueLabels['l_app_procesy'] = "procesy";
  710. $valueLabels['l_app_zasoby'] = "zasoby";
  711. $valueLabels['l_app_all_przypomnij'] = "*wszystkie";
  712. }
  713. } else if ('when' == $fldName) {
  714. $valueLabels['once_a_day'] = "Raz dziennie";
  715. $valueLabels['immediately'] = "Na bieżąco";
  716. }
  717. return $valueLabels;
  718. }
  719. public function getFieldValues($fldName) {
  720. $valueLabels = $this->getFieldValueLabels($fldName);
  721. return array_keys($valueLabels);
  722. }
  723. public function addUserTableReminder($usrLogin, $args) {
  724. $what_values = $this->getFieldValues('what');
  725. $what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$what_values));
  726. $when_values = $this->getFieldValues('when');
  727. $when = V::validate('when', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$when_values));
  728. $pdo = DB::getPDO();
  729. if ('l_app_all_przypomnij' == $what) {
  730. $types = $this->getAllPrzypomnijTypes();
  731. $sqlValues = array();
  732. $sqlWho = $pdo->quote($usrLogin, PDO::PARAM_STR);
  733. $sqlWhen = $pdo->quote($when, PDO::PARAM_STR);
  734. foreach ($types as $type) {
  735. $sqlWhat = $pdo->quote($type, PDO::PARAM_STR);
  736. $sqlValues[] = "( {$sqlWho}, {$sqlWhat}, {$sqlWhen}, NOW() )";
  737. }
  738. $sqlValues = implode(", ", $sqlValues);
  739. $pdo->execSql("
  740. insert ignore into `CRM_NOTIFY` (
  741. `who`,
  742. `what`,
  743. `when`,
  744. `_created`
  745. ) values {$sqlValues}
  746. ");
  747. } else {
  748. $sth = $pdo->prepare("
  749. insert into `CRM_NOTIFY` (
  750. `who`,
  751. `what`,
  752. `when`,
  753. `_created`
  754. ) values (
  755. :who,
  756. :what,
  757. :when,
  758. NOW()
  759. )
  760. ");
  761. $bindValues = array();
  762. $bindValues['who'] = array($usrLogin, PDO::PARAM_STR);
  763. $bindValues['what'] = array($what, PDO::PARAM_STR);
  764. $bindValues['when'] = array($when, PDO::PARAM_STR);
  765. $pdo->bindValues($sth, $bindValues);
  766. // try {
  767. $sth->execute();
  768. // } catch (PDOException $e) {
  769. // throw new Exception("Błąd bazy danych: " . json_encode($e->errorInfo));
  770. // } catch (Exception $e) {
  771. // throw $e;
  772. // }
  773. }
  774. }
  775. public function getUserNotifyList($usrLogin) {
  776. return DB::getPDO()->fetchAll("
  777. select n.*
  778. from `CRM_NOTIFY` n
  779. where n.`who` = '{$usrLogin}'
  780. ");
  781. }
  782. public function getTodoList($limit = 10, $whenTypes = array()) {
  783. $pdo = DB::getPDO();
  784. if (empty($whenTypes)) throw new Exception("when types not set in getTodoList");
  785. {
  786. $sqlWhenFltr = array();
  787. if (in_array('once_a_day', $whenTypes)) {
  788. $sqlWhenFltr[] = "
  789. (
  790. n.`when` = 'once_a_day' and (
  791. n.last_exec_time is null
  792. or DATE(n.last_exec_time) < CURDATE()
  793. )
  794. )
  795. ";
  796. }
  797. if (in_array('immediately', $whenTypes)) {
  798. $sqlWhenFltr[] = "( n.`when` = 'immediately' )";
  799. }
  800. if (empty($sqlWhenFltr)) throw new Exception("when types not allowed in getTodoList");
  801. $sqlWhenFltr = "( " . implode(" or ", $sqlWhenFltr) . " )";
  802. }
  803. $sth = $pdo->prepare("
  804. select u.ADM_ACCOUNT
  805. from ADMIN_USERS u
  806. join CRM_NOTIFY n on(n.`who` = u.ADM_ACCOUNT and {$sqlWhenFltr})
  807. where u.A_STATUS = 'NORMAL'
  808. and u.EMPLOYEE_TYPE = 'Pracownik'
  809. and n.`who` is not null
  810. group by u.ADM_ACCOUNT
  811. order by n.last_exec_time asc
  812. limit :limit
  813. ");
  814. $sth->bindValue(':limit', $limit, PDO::PARAM_INT);
  815. $sth->execute();
  816. $rawUsers = $sth->fetchAll();
  817. if (empty($rawUsers)) return array();
  818. $sqlUsers = array(); foreach ($rawUsers as $row) { $sqlUsers[] = $pdo->quote($row['ADM_ACCOUNT'], PDO::PARAM_STR); }
  819. $sqlUsers = implode(", ", $sqlUsers);
  820. $sth = $pdo->prepare("
  821. select n.`who`, n.`when`, n.`what`
  822. , UNIX_TIMESTAMP(n.last_exec_time) as last_exec_time
  823. , IF(n.`when` = 'immediately'
  824. , (select UNIX_TIMESTAMP(MAX(i.last_exec_time))
  825. from CRM_NOTIFY i
  826. where i.`who` = n.`who`
  827. and i.`what` = n.`what`
  828. -- and i.`when` = 'once_a_day'
  829. -- limit 1
  830. )
  831. , null
  832. ) as _last_exec_time_fix_for_immediately
  833. from CRM_NOTIFY n
  834. where n.`who` in({$sqlUsers})
  835. and {$sqlWhenFltr}
  836. order by n.last_exec_time asc
  837. ");
  838. $sth->execute();
  839. $rawReminders = $sth->fetchAll();
  840. $reminders = array();
  841. $timeToday = mktime(0, 0, 0, date('n'), date('j'), date('Y'));
  842. //$timeTomorrow = mktime(0, 0, 0, date('n'), date('j') + 1, date('Y'));
  843. DBG::_('DBG_NTF', '>1', "rawReminders (today:{$timeToday})", $rawReminders, __CLASS__, __FUNCTION__, __LINE__);
  844. foreach ($rawReminders as $row) {
  845. $who = $row['who'];
  846. $when = $row['when'];
  847. $what = $row['what'];
  848. $last_exec_time = $row['last_exec_time'];
  849. $last_exec_time_fix_for_immediately = $row['_last_exec_time_fix_for_immediately'];
  850. if ('once_a_day' == $when) {
  851. if ($last_exec_time >= $timeToday) {
  852. DBG::_('DBG_NTF', '>1', "skip {$last_exec_time} for '{$what}' at '{$when}'", $row, __CLASS__, __FUNCTION__, __LINE__);
  853. continue;
  854. } else {
  855. //DBG::_(true, true, "TODO: else {$last_exec_time} >= {$timeToday}", $row, __CLASS__, __FUNCTION__, __LINE__);
  856. }
  857. } else if ('immediately' == $when) {
  858. //DBG::_(true, true, "TODO: else {$last_exec_time} >= {$timeToday}", $row, __CLASS__, __FUNCTION__, __LINE__);
  859. } else {
  860. DBG::_('DBG_NTF', '>0', "TODO: unimplemented when = '{$when}'", $row, __CLASS__, __FUNCTION__, __LINE__);
  861. continue;
  862. }
  863. $last_date = ($last_exec_time)? date("Y-m-d H:i:s", $last_exec_time) : null;
  864. if (!isset($reminders[$who])) $reminders[$who] = array();
  865. if (!isset($reminders[$who][$when])) $reminders[$who][$when] = array();
  866. $reminders[$who][$when][$what] = $last_date;
  867. if ('immediately' == $when && null !== $last_exec_time_fix_for_immediately && $last_exec_time_fix_for_immediately > $last_exec_time) {
  868. $reminders[$who][$when][$what] = date("Y-m-d H:i:s", $last_exec_time_fix_for_immediately);
  869. }
  870. }
  871. return $reminders;
  872. }
  873. public function reinstallAction() {
  874. try {
  875. $force = ('true' == V::get('_force', '', $_GET));
  876. $this->reinstall($force);
  877. } catch (Exception $e) {
  878. echo'<div style="border:1px solid red; background:red; color:#fff;">';
  879. echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
  880. echo'</div>';
  881. }
  882. die('OK');
  883. }
  884. public function reinstallFunctionsAction() {
  885. $this->reinstallFunctions();
  886. die('OK');
  887. }
  888. public function runAction() {
  889. $msgId = V::get('_msgId', 0, $_REQUEST, 'int');
  890. if ($msgId > 0) {
  891. $this->runByMessageId($msgId);
  892. }
  893. $jsonData = new stdClass();
  894. $jsonData->type = 'success';
  895. $jsonData->msg = 'Gotowe';
  896. echo json_encode($jsonData);
  897. exit;
  898. }
  899. public function reinstallFunctions() {
  900. $sqlList = array();
  901. $db = DB::getDB();
  902. if ($db->has_errors()) {
  903. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  904. }
  905. foreach ($sqlList as $sqlName => $sql) {
  906. $res = $db->query($sql);
  907. if ($db->has_errors()) {
  908. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  909. }
  910. }
  911. }
  912. public function testReinstallTable() {
  913. $pdo = DB::getPDO();
  914. if(1){// TEST
  915. $expectedStruct = array();
  916. $expectedStruct['who'] = array('type'=>'varchar', 'max_length'=>20, 'is_nullable'=>false);// `who` varchar(20) -- TODO: NOT NULL
  917. $expectedStruct['when'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `when` varchar(255) NOT NULL
  918. $expectedStruct['what'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `what` varchar(255) NOT NULL
  919. $expectedStruct['last_exec_time'] = array('type'=>'datetime', 'is_nullable'=>true);// `last_exec_time` datetime
  920. $expectedStruct['_created'] = array('type'=>'datetime', 'is_nullable'=>false);// `_created` datetime
  921. $expectedStruct['uniq_key_1'] = array('type'=>'UNIQUE KEY', 'key_fields'=>array('who','when','what'));// UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  922. $expectedStruct['key_who'] = array('type'=>'KEY', 'key_fields'=>array('who'));// KEY `key_who` (`who`)
  923. // $expectedStruct['t1'] = array('type'=>'varchar', 'max_length'=>300, 'default_value'=>null);
  924. // $expectedStruct['t2'] = array('type'=>'int');
  925. // $expectedStruct['t3'] = array('type'=>'int', 'num_precision'=>11, 'default_value'=>null);
  926. // $expectedStruct['t_dec_11_x'] = array('type'=>'decimal', 'num_precision'=>11);
  927. // $expectedStruct['t_dec_11_2'] = array('type'=>'decimal', 'num_precision'=>11, 'num_scale'=>2);
  928. $expectedStruct['t_int'] = array('type'=>'int');
  929. $expectedStruct['t_tinyint'] = array('type'=>'tinyint');
  930. $expectedStruct['t_smallint'] = array('type'=>'smallint');
  931. $expectedStruct['t_mediumint'] = array('type'=>'mediumint');
  932. $expectedStruct['t_bigint'] = array('type'=>'bigint');
  933. $expectedStruct['t_decimal'] = array('type'=>'decimal');
  934. $expectedStruct['t_float'] = array('type'=>'float');
  935. $expectedStruct['t_double'] = array('type'=>'double');
  936. $expectedStruct['t_real'] = array('type'=>'real');
  937. $expectedStruct['t_date'] = array('type'=>'date');
  938. $expectedStruct['t_datetime'] = array('type'=>'datetime');
  939. $expectedStruct['t_timestamp'] = array('type'=>'timestamp');
  940. $expectedStruct['t_time'] = array('type'=>'time');
  941. $expectedStruct['t_year'] = array('type'=>'year');
  942. $expectedStruct['t_char'] = array('type'=>'char');
  943. $expectedStruct['t_varchar'] = array('type'=>'varchar');
  944. $expectedStruct['t_text'] = array('type'=>'text');
  945. $expectedStruct['t_tinytext'] = array('type'=>'tinytext');
  946. $expectedStruct['t_mediumtext'] = array('type'=>'mediumtext');
  947. $expectedStruct['t_longtext'] = array('type'=>'longtext');
  948. $expectedStruct['t_enum'] = array('type'=>'enum', 'values'=>array('v1'));
  949. $expectedStruct['t_set'] = array('type'=>'set', 'values'=>array('v1'));
  950. $expectedStruct['t_bit'] = array('type'=>'bit', 'max_length'=>2);
  951. $expectedStruct['t_boolean'] = array('type'=>'boolean');
  952. $expectedStruct['t_serial'] = array('type'=>'serial');
  953. $expectedStruct['t_binary'] = array('type'=>'binary');
  954. $expectedStruct['t_varbinary'] = array('type'=>'varbinary');
  955. $expectedStruct['t_blob'] = array('type'=>'blob');
  956. $expectedStruct['t_tinyblob'] = array('type'=>'tinyblob');
  957. $expectedStruct['t_mediumblob'] = array('type'=>'mediumblob');
  958. $expectedStruct['t_longblob'] = array('type'=>'longblob');
  959. $expectedStruct['t_geometry'] = array('type'=>'geometry');
  960. $expectedStruct['t_point'] = array('type'=>'point');
  961. $expectedStruct['t_linestring'] = array('type'=>'linestring');
  962. $expectedStruct['t_polygon'] = array('type'=>'polygon');
  963. $expectedStruct['t_multipoint'] = array('type'=>'multipoint');
  964. $expectedStruct['t_multilinestring'] = array('type'=>'multilinestring');
  965. $expectedStruct['t_multipolygon'] = array('type'=>'multipolygon');
  966. $expectedStruct['t_geometrycollection'] = array('type'=>'geometrycollection');
  967. $sqlCreate = $pdo->showCreateStruct('_test_table', $expectedStruct, array('char_encoding'=>'latin2'));
  968. DBG::_(true, true, "fixedEpectedStruct", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
  969. $pdo->assertTableStruct('_test_table', $expectedStruct, array('char_encoding'=>'latin2'));
  970. {// force - drop/create
  971. $pdo->exec("DROP TABLE IF EXISTS _test_table");
  972. $pdo->exec($sqlCreate);
  973. }
  974. }
  975. if(0){// TEST nulls
  976. $sth = $pdo->prepare("DROP TABLE IF EXISTS CRM_NOTIFY");
  977. $sth->execute();
  978. $sth = $pdo->prepare("
  979. CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
  980. `who` varchar(20)
  981. , `when` varchar(255) NOT NULL
  982. , `what` varchar(255) DEFAULT ''
  983. , `t1` varchar(255) NOT NULL -- same as with DEFAULT ''
  984. , `t2` varchar(255) NOT NULL DEFAULT ''
  985. , `t2z` varchar(255) NOT NULL DEFAULT '0'
  986. -- , `t3` varchar(255) NOT NULL DEFAULT NULL -- SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value
  987. , `t4` varchar(255) NULL -- same as with DEFAULT NULL
  988. , `t5` varchar(255) NULL DEFAULT ''
  989. , `t6` varchar(255) NULL DEFAULT NULL
  990. , `i1` int(11) NOT NULL -- same as with DEFAULT 0
  991. , `i2` int(11) NOT NULL DEFAULT 0
  992. -- , `i3` int(11) NOT NULL DEFAULT NULL -- SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value
  993. , `i4` int(11) NULL -- same as with DEFAULT NULL
  994. , `i5` int(11) NULL DEFAULT 0
  995. , `i6` int(11) NULL DEFAULT NULL
  996. , `last_exec_time` datetime DEFAULT NULL
  997. , KEY `who` (`who`)
  998. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  999. ");
  1000. $sth->execute();
  1001. $sth = $pdo->prepare("insert into CRM_NOTIFY (`last_exec_time`) values (NULL)");
  1002. $sth->execute();
  1003. // INSERT INTO CRM_NOTIFY (t1, t2, t2z, t4, t5, t6, i1, i2, i4, i5, i6, last_exec_time)
  1004. // VALUES ('', '', '0', NULL, '', NULL, 0, 0, NULL, 0, NULL, NULL);
  1005. $struct = $pdo->getTableStruct('CRM_NOTIFY');
  1006. DBG::_(true, true, "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
  1007. DBG::_(true, true, "`t2`: is_null(struct[4]['Default'])=(".is_null($struct[4]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  1008. DBG::_(true, true, "`t4`: is_null(struct[6]['Default'])=(".is_null($struct[6]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  1009. DBG::_(true, true, "`t5`: is_null(struct[7]['Default'])=(".is_null($struct[7]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  1010. DBG::_(true, true, "`t6`: is_null(struct[8]['Default'])=(".is_null($struct[8]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  1011. $expectedStruct = array();
  1012. $expectedStruct['t1'] = array('type'=>'varchar', 'max_length'=>300, 'default_value'=>null);
  1013. //$expectedStruct['t2'] = array('type'=>'int', 'num_precision'=>11, 'default_value'=>null);
  1014. $pdo->assertTableStruct('CRM_NOTIFY', $expectedStruct);
  1015. }
  1016. }
  1017. public function reinstall($force = false) {
  1018. $sqlList = array();
  1019. $pdo = DB::getPDO();
  1020. $sqlCreate = "
  1021. CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
  1022. `who` varchar(20) NOT NULL
  1023. , `when` varchar(255) NOT NULL
  1024. , `what` varchar(255) NOT NULL
  1025. , `last_exec_time` datetime DEFAULT NULL
  1026. , `_created` datetime NOT NULL
  1027. , UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  1028. , KEY `key_who` (`who`)
  1029. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  1030. ";
  1031. /*
  1032. `CRM_NOTIFY`:
  1033. - who - user login
  1034. - when - shedule (once a day, once on houd)
  1035. - what - action type
  1036. - last_exec_time
  1037. */
  1038. if ($force) $pdo->exec("DROP TABLE IF EXISTS CRM_NOTIFY");
  1039. $pdo->exec($sqlCreate);
  1040. if(0){// TODO: assertTableStruct CRM_NOTIFY
  1041. $expectedStruct = array();
  1042. $expectedStruct['who'] = array('type'=>'varchar', 'max_length'=>20, 'is_nullable'=>false);// `who` varchar(20) -- TODO: NOT NULL
  1043. $expectedStruct['when'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `when` varchar(255) NOT NULL
  1044. $expectedStruct['what'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `what` varchar(255) NOT NULL
  1045. $expectedStruct['last_exec_time'] = array('type'=>'datetime', 'is_nullable'=>true);// `last_exec_time` datetime
  1046. $expectedStruct['_created'] = array('type'=>'datetime', 'is_nullable'=>false);// `_created` datetime
  1047. $expectedStruct['uniq_key_1'] = array('type'=>'UNIQUE KEY', 'key_fields'=>array('who','when','what'));// UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  1048. $expectedStruct['key_who'] = array('type'=>'KEY', 'key_fields'=>array('who'));// KEY `key_who` (`who`)
  1049. DBG::_(true, true, "sqlCreate - raw", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
  1050. $sqlCreate = $pdo->showCreateStruct('CRM_NOTIFY', $expectedStruct, array('char_encoding'=>'latin2'));
  1051. DBG::_(true, true, "sqlCreate - generated", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
  1052. $pdo->assertTableStruct('CRM_NOTIFY', $expectedStruct, array('char_encoding'=>'latin2'));
  1053. if(0){// force - drop/create
  1054. $pdo->exec("DROP TABLE IF EXISTS CRM_NOTIFY");
  1055. $pdo->exec($sqlCreate);
  1056. }
  1057. }
  1058. {// assertTableStruct CRM_NOTIFY_EXEC_LOG
  1059. // TODO: create table CRM_NOTIFY_EXEC_LOG with action log
  1060. }
  1061. //$this->reinstallFunctions();
  1062. }
  1063. }