Notify.php 45 KB

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