Notify.php 45 KB

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