Notify.php 46 KB

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