Notify.php 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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)) {
  519. $przypomnij = new Przypomnij();
  520. $przypomnij->setRecurseLimit(3);
  521. $przypomnij->fetchData($usrLogin);
  522. $przypomnij->setFltrUser($usrLogin);
  523. $tasks = $przypomnij->getTasksByDate();
  524. {
  525. $usrGroupNames = array();
  526. //$usrGroupNames = User::getLdapGroupsNames();
  527. Lib::loadClass('UsersLdapHelper');
  528. $ldapGroups = UsersLdapHelper::getUserGroups($usrLogin, 3);
  529. foreach ($ldapGroups as $kID => $vLDAPGroup) {
  530. $usrGroupNames[$kID] = $vLDAPGroup->cn;
  531. }
  532. }
  533. foreach ($tasks as $task) {
  534. if (!$task->_show) continue;
  535. if (
  536. $task->A_CLASSIFIED != ''
  537. and !(in_array($task->A_CLASSIFIED, $usrGroupNames))
  538. and $task->A_ADM_COMPANY != ''
  539. and !(in_array($task->A_ADM_COMPANY, $usrGroupNames))
  540. // !($allowedUsers[$task->_l_app]) - to jest bez sensu - wystarczy widocznosc sprawy?
  541. ) {
  542. continue;
  543. }
  544. $task->_l_app_class = $przypomnij->getTaskDateFltrType($task->_l_app_date);
  545. $task->_idZasobTable = $przypomnij->getZasobIdByType($task->_task_type);
  546. $_tasks[] = (array)$task;
  547. }
  548. }
  549. return $_tasks;
  550. }
  551. public function removeUserTableReminder($args) {
  552. $usrLogin = User::getLogin();
  553. $who = V::validate('who', $args, array('type'=>'word', 'equal'=>$usrLogin, 'error_msg_equal'=>"Brak uprawnień do wprowadzania zmian w powiadomieniach innych użytwkoników"));
  554. $what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$this->getFieldValues('what')));
  555. $when = V::validate('when', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$this->getFieldValues('when')));
  556. if ($usrLogin != $who) throw new Exception("Brak uprawnień do wprowadzania zmian w powiadomieniach innych użytwkoników");
  557. $pdo = DB::getPDO();
  558. $sth = $pdo->prepare("
  559. delete from `CRM_NOTIFY`
  560. where `who` = :who
  561. and `what` = :what
  562. and `when` = :when
  563. ");
  564. $sth->bindValue(':who', $usrLogin, PDO::PARAM_STR);
  565. $sth->bindValue(':what', $what, PDO::PARAM_STR);
  566. $sth->bindValue(':when', $when, PDO::PARAM_STR);
  567. $sth->execute();
  568. }
  569. public function formUserTableReminder($usrLogin) {
  570. echo '<div class="container">';
  571. $subTask = V::get('_subTask', '', $_POST);
  572. if ('_add_table_reminder' == $subTask) {
  573. try {
  574. $this->addUserTableReminder($usrLogin, $_POST);
  575. SE_Layout::alert('info', "Dodano powiadomienie");
  576. } catch (PDOException $e) {
  577. if (!empty($e->errorInfo) && !empty($e->errorInfo[1]) && '1062' == $e->errorInfo[1]) {
  578. SE_Layout::alert('warning', "Powiadomienie tego typu zostało już wcześniej dodane");
  579. } else {
  580. SE_Layout::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage() . '<br>' . "Info: " . json_encode($e->errorInfo));
  581. }
  582. } catch (Exception $e) {
  583. SE_Layout::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  584. }
  585. }
  586. else if ('_rm_table_reminder' == $subTask) {
  587. try {
  588. $this->removeUserTableReminder($_POST);
  589. SE_Layout::alert('info', "Usunięto powiadomienie");
  590. } catch (Exception $e) {
  591. SE_Layout::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  592. }
  593. }
  594. $userNotifyList = $this->getUserNotifyList($usrLogin);
  595. $userMail = $this->getUserMainMail($usrLogin);
  596. $whatLabelsForOnceADay = $this->getFieldValueLabels('what', $userNotifyList, $when = 'once_a_day');
  597. $whatLabelsForImmediately = $this->getFieldValueLabels('what', $userNotifyList, $when = 'immediately');
  598. ?>
  599. <h1>Powiadomienia dla <code><?php echo $usrLogin; ?></code></h1>
  600. <p><i>Będą wysyłane na adres: <?php echo $userMail; ?></i></p>
  601. <?php if (empty($userNotifyList)) : ?>
  602. <?php SE_Layout::alert('warning', "Brak zdefiniowanych powiadomień"); ?>
  603. <?php else : ?>
  604. <table class="table table-hovered">
  605. <thead>
  606. <tr>
  607. <th>rodzaj</th>
  608. <th>jak często</th>
  609. <th>utworzony</th>
  610. <th>ostatnio uruchomiony</th>
  611. <th></th>
  612. </tr>
  613. </thead>
  614. <tbody>
  615. <?php foreach ($userNotifyList as $notify) : ?>
  616. <tr>
  617. <td><?php echo $this->printValue('what', $notify['what']); ?></td>
  618. <td><?php echo $this->printValue('when', $notify['when']); ?></td>
  619. <td><?php echo $notify['_created']; ?></td>
  620. <td><?php echo ($notify['last_exec_time'])? $notify['last_exec_time'] : '<i>brak danych</i>'; ?></td>
  621. <td>
  622. <form method="post" class="form-inline">
  623. <input type="hidden" name="_subTask" value="_rm_table_reminder">
  624. <input type="hidden" name="who" value="<?php echo $usrLogin; ?>">
  625. <input type="hidden" name="what" value="<?php echo $notify['what']; ?>">
  626. <input type="hidden" name="when" value="<?php echo $notify['when']; ?>">
  627. <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>
  628. </form>
  629. </td>
  630. </tr>
  631. <?php endforeach; ?>
  632. </tbody>
  633. </table>
  634. <?php endif; ?>
  635. <?php if (!empty($whatLabelsForOnceADay)) : ?>
  636. <hr>
  637. <h4>Dodaj powiadomienia wysyłane raz dziennie:</h4>
  638. <form method="post" class="form-inline">
  639. <input type="hidden" name="_subTask" value="_add_table_reminder">
  640. <input type="hidden" name="when" value="once_a_day">
  641. <label>rodzaj:</label>
  642. <select type="select" name="what" class="form-control">
  643. <option value="">[ Wybierz ]</option>
  644. <?php foreach ($whatLabelsForOnceADay as $value => $label) : ?>
  645. <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
  646. <?php endforeach; ?>
  647. </select>
  648. <input type="submit" value="Dodaj" class="btn btn-primary">
  649. </form>
  650. <?php endif; ?>
  651. <?php if (!empty($whatLabelsForImmediately)) : ?>
  652. <hr>
  653. <h4>Dodaj powiadomienia wysyłane na bieżąco:</h4>
  654. <form method="post" class="form-inline">
  655. <input type="hidden" name="_subTask" value="_add_table_reminder">
  656. <input type="hidden" name="when" value="immediately">
  657. <label>rodzaj:</label>
  658. <select type="select" name="what" class="form-control">
  659. <option value="">[ Wybierz ]</option>
  660. <?php foreach ($whatLabelsForImmediately as $value => $label) : ?>
  661. <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
  662. <?php endforeach; ?>
  663. </select>
  664. <input type="submit" value="Dodaj" class="btn btn-primary">
  665. </form>
  666. <?php endif; ?>
  667. <?php
  668. echo '</div>';// .container
  669. }
  670. public function printValue($fldName, $argValue) {
  671. if ('what' == $fldName || 'when' == $fldName) {
  672. $valueLabels = $this->getFieldValueLabels($fldName);
  673. return V::get($argValue, $argValue, $valueLabels);
  674. }
  675. return $argValue;
  676. }
  677. public function getAllPrzypomnijTypes() {
  678. $allPrzypomnijTypes = array();
  679. $allPrzypomnijTypes[] = 'msgs';
  680. $allPrzypomnijTypes[] = 'l_app_projekty';
  681. $allPrzypomnijTypes[] = 'l_app_koresp';
  682. $allPrzypomnijTypes[] = 'l_app_zadania';
  683. $allPrzypomnijTypes[] = 'l_app_procesy';
  684. $allPrzypomnijTypes[] = 'l_app_zasoby';
  685. return $allPrzypomnijTypes;
  686. }
  687. public function getFieldValueLabels($fldName, $userNotifyList = null, $when = null) {
  688. $valueLabels = array();
  689. if ('what' == $fldName) {
  690. if (null == $userNotifyList) $userNotifyList = array();
  691. if ('once_a_day' == $when) {
  692. $valueLabels['msgs'] = "wiadomości";
  693. $valueLabels['l_app_projekty'] = "projekty";
  694. $valueLabels['l_app_koresp'] = "korespondencja";
  695. $valueLabels['l_app_zadania'] = "zadania";
  696. $valueLabels['l_app_procesy'] = "procesy";
  697. $valueLabels['l_app_zasoby'] = "zasoby";
  698. $valueLabels['l_app_all_przypomnij'] = "*wszystkie";
  699. if (!empty($userNotifyList)) {// filter out existing notify
  700. foreach ($userNotifyList as $notify) {
  701. if ($when == $notify['when'] && array_key_exists($notify['what'], $valueLabels)) {
  702. unset($valueLabels[$notify['what']]);
  703. }
  704. }
  705. if (1 == count($valueLabels) && !empty($valueLabels['l_app_all_przypomnij'])) {
  706. unset($valueLabels['l_app_all_przypomnij']);
  707. }
  708. }
  709. } else if ('immediately' == $when) {
  710. $valueLabels['msgs'] = "wiadomości";
  711. $valueLabels['l_app_zadania'] = "zadania";
  712. if (!empty($userNotifyList)) {// filter out existing notify
  713. foreach ($userNotifyList as $notify) {
  714. if ($when == $notify['when'] && array_key_exists($notify['what'], $valueLabels)) {
  715. unset($valueLabels[$notify['what']]);
  716. }
  717. }
  718. }
  719. } else {
  720. $valueLabels['msgs'] = "wiadomości";
  721. $valueLabels['l_app_projekty'] = "projekty";
  722. $valueLabels['l_app_koresp'] = "korespondencja";
  723. $valueLabels['l_app_zadania'] = "zadania";
  724. $valueLabels['l_app_procesy'] = "procesy";
  725. $valueLabels['l_app_zasoby'] = "zasoby";
  726. $valueLabels['l_app_all_przypomnij'] = "*wszystkie";
  727. }
  728. } else if ('when' == $fldName) {
  729. $valueLabels['once_a_day'] = "Raz dziennie";
  730. $valueLabels['immediately'] = "Na bieżąco";
  731. }
  732. return $valueLabels;
  733. }
  734. public function getFieldValues($fldName) {
  735. $valueLabels = $this->getFieldValueLabels($fldName);
  736. return array_keys($valueLabels);
  737. }
  738. public function addUserTableReminder($usrLogin, $args) {
  739. $what_values = $this->getFieldValues('what');
  740. $what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$what_values));
  741. $when_values = $this->getFieldValues('when');
  742. $when = V::validate('when', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$when_values));
  743. $pdo = DB::getPDO();
  744. if ('l_app_all_przypomnij' == $what) {
  745. $types = $this->getAllPrzypomnijTypes();
  746. $sqlValues = array();
  747. $sqlWho = $pdo->quote($usrLogin, PDO::PARAM_STR);
  748. $sqlWhen = $pdo->quote($when, PDO::PARAM_STR);
  749. foreach ($types as $type) {
  750. $sqlWhat = $pdo->quote($type, PDO::PARAM_STR);
  751. $sqlValues[] = "( {$sqlWho}, {$sqlWhat}, {$sqlWhen}, NOW() )";
  752. }
  753. $sqlValues = implode(", ", $sqlValues);
  754. $pdo->exec("
  755. insert ignore into `CRM_NOTIFY` (
  756. `who`,
  757. `what`,
  758. `when`,
  759. `_created`
  760. ) values {$sqlValues}
  761. ");
  762. } else {
  763. $sth = $pdo->prepare("
  764. insert into `CRM_NOTIFY` (
  765. `who`,
  766. `what`,
  767. `when`,
  768. `_created`
  769. ) values (
  770. :who,
  771. :what,
  772. :when,
  773. NOW()
  774. )
  775. ");
  776. $bindValues = array();
  777. $bindValues['who'] = array($usrLogin, PDO::PARAM_STR);
  778. $bindValues['what'] = array($what, PDO::PARAM_STR);
  779. $bindValues['when'] = array($when, PDO::PARAM_STR);
  780. $pdo->bindValues($sth, $bindValues);
  781. // try {
  782. $sth->execute();
  783. // } catch (PDOException $e) {
  784. // throw new Exception("Błąd bazy danych: " . json_encode($e->errorInfo));
  785. // } catch (Exception $e) {
  786. // throw $e;
  787. // }
  788. }
  789. }
  790. public function getUserNotifyList($usrLogin) {
  791. $sth = DB::getPDO()->prepare("
  792. select n.*
  793. from `CRM_NOTIFY` n
  794. where n.`who` = '{$usrLogin}'
  795. ");
  796. $sth->execute();
  797. $notifyTypeList = $sth->fetchAll();
  798. return $notifyTypeList;
  799. }
  800. public function getTodoList($limit = 10, $whenTypes = array()) {
  801. $pdo = DB::getPDO();
  802. if (empty($whenTypes)) throw new Exception("when types not set in getTodoList");
  803. {
  804. $sqlWhenFltr = array();
  805. if (in_array('once_a_day', $whenTypes)) {
  806. $sqlWhenFltr[] = "
  807. (
  808. n.`when` = 'once_a_day' and (
  809. n.last_exec_time is null
  810. or DATE(n.last_exec_time) < CURDATE()
  811. )
  812. )
  813. ";
  814. }
  815. if (in_array('immediately', $whenTypes)) {
  816. $sqlWhenFltr[] = "( n.`when` = 'immediately' )";
  817. }
  818. if (empty($sqlWhenFltr)) throw new Exception("when types not allowed in getTodoList");
  819. $sqlWhenFltr = "( " . implode(" or ", $sqlWhenFltr) . " )";
  820. }
  821. $sth = $pdo->prepare("
  822. select u.ADM_ACCOUNT
  823. from ADMIN_USERS u
  824. join CRM_NOTIFY n on(n.`who` = u.ADM_ACCOUNT and {$sqlWhenFltr})
  825. where u.A_STATUS = 'NORMAL'
  826. and u.EMPLOYEE_TYPE = 'Pracownik'
  827. and n.`who` is not null
  828. group by u.ADM_ACCOUNT
  829. order by n.last_exec_time asc
  830. limit :limit
  831. ");
  832. $sth->bindValue(':limit', $limit, PDO::PARAM_INT);
  833. $sth->execute();
  834. $rawUsers = $sth->fetchAll();
  835. if (empty($rawUsers)) return array();
  836. $sqlUsers = array(); foreach ($rawUsers as $row) { $sqlUsers[] = $pdo->quote($row['ADM_ACCOUNT'], PDO::PARAM_STR); }
  837. $sqlUsers = implode(", ", $sqlUsers);
  838. $sth = $pdo->prepare("
  839. select n.`who`, n.`when`, n.`what`
  840. , UNIX_TIMESTAMP(n.last_exec_time) as last_exec_time
  841. , IF(n.`when` = 'immediately'
  842. , (select UNIX_TIMESTAMP(MAX(i.last_exec_time))
  843. from CRM_NOTIFY i
  844. where i.`who` = n.`who`
  845. and i.`what` = n.`what`
  846. -- and i.`when` = 'once_a_day'
  847. -- limit 1
  848. )
  849. , null
  850. ) as _last_exec_time_fix_for_immediately
  851. from CRM_NOTIFY n
  852. where n.`who` in({$sqlUsers})
  853. and {$sqlWhenFltr}
  854. order by n.last_exec_time asc
  855. ");
  856. $sth->execute();
  857. $rawReminders = $sth->fetchAll();
  858. $reminders = array();
  859. $timeToday = mktime(0, 0, 0, date('n'), date('j'), date('Y'));
  860. //$timeTomorrow = mktime(0, 0, 0, date('n'), date('j') + 1, date('Y'));
  861. DBG::_('DBG_NTF', '>1', "rawReminders (today:{$timeToday})", $rawReminders, __CLASS__, __FUNCTION__, __LINE__);
  862. foreach ($rawReminders as $row) {
  863. $who = $row['who'];
  864. $when = $row['when'];
  865. $what = $row['what'];
  866. $last_exec_time = $row['last_exec_time'];
  867. $last_exec_time_fix_for_immediately = $row['_last_exec_time_fix_for_immediately'];
  868. if ('once_a_day' == $when) {
  869. if ($last_exec_time >= $timeToday) {
  870. DBG::_('DBG_NTF', '>1', "skip {$last_exec_time} for '{$what}' at '{$when}'", $row, __CLASS__, __FUNCTION__, __LINE__);
  871. continue;
  872. } else {
  873. //DBG::_(true, true, "TODO: else {$last_exec_time} >= {$timeToday}", $row, __CLASS__, __FUNCTION__, __LINE__);
  874. }
  875. } else if ('immediately' == $when) {
  876. //DBG::_(true, true, "TODO: else {$last_exec_time} >= {$timeToday}", $row, __CLASS__, __FUNCTION__, __LINE__);
  877. } else {
  878. DBG::_('DBG_NTF', '>0', "TODO: unimplemented when = '{$when}'", $row, __CLASS__, __FUNCTION__, __LINE__);
  879. continue;
  880. }
  881. $last_date = ($last_exec_time)? date("Y-m-d H:i:s", $last_exec_time) : null;
  882. if (!isset($reminders[$who])) $reminders[$who] = array();
  883. if (!isset($reminders[$who][$when])) $reminders[$who][$when] = array();
  884. $reminders[$who][$when][$what] = $last_date;
  885. if ('immediately' == $when && null !== $last_exec_time_fix_for_immediately && $last_exec_time_fix_for_immediately > $last_exec_time) {
  886. $reminders[$who][$when][$what] = date("Y-m-d H:i:s", $last_exec_time_fix_for_immediately);
  887. }
  888. }
  889. return $reminders;
  890. }
  891. public function reinstallAction() {
  892. try {
  893. $force = ('true' == V::get('_force', '', $_GET));
  894. $this->reinstall($force);
  895. } catch (Exception $e) {
  896. echo'<div style="border:1px solid red; background:red; color:#fff;">';
  897. echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
  898. echo'</div>';
  899. }
  900. die('OK');
  901. }
  902. public function reinstallFunctionsAction() {
  903. $this->reinstallFunctions();
  904. die('OK');
  905. }
  906. public function runAction() {
  907. $msgId = V::get('_msgId', 0, $_REQUEST, 'int');
  908. if ($msgId > 0) {
  909. $this->runByMessageId($msgId);
  910. }
  911. $jsonData = new stdClass();
  912. $jsonData->type = 'success';
  913. $jsonData->msg = 'Gotowe';
  914. echo json_encode($jsonData);
  915. exit;
  916. }
  917. public function reinstallFunctions() {
  918. $sqlList = array();
  919. $db = DB::getDB();
  920. if ($db->has_errors()) {
  921. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  922. }
  923. foreach ($sqlList as $sqlName => $sql) {
  924. $res = $db->query($sql);
  925. if ($db->has_errors()) {
  926. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  927. }
  928. }
  929. }
  930. public function testReinstallTable() {
  931. $pdo = DB::getPDO();
  932. if(1){// TEST
  933. $expectedStruct = array();
  934. $expectedStruct['who'] = array('type'=>'varchar', 'max_length'=>20, 'is_nullable'=>false);// `who` varchar(20) -- TODO: NOT NULL
  935. $expectedStruct['when'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `when` varchar(255) NOT NULL
  936. $expectedStruct['what'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `what` varchar(255) NOT NULL
  937. $expectedStruct['last_exec_time'] = array('type'=>'datetime', 'is_nullable'=>true);// `last_exec_time` datetime
  938. $expectedStruct['_created'] = array('type'=>'datetime', 'is_nullable'=>false);// `_created` datetime
  939. $expectedStruct['uniq_key_1'] = array('type'=>'UNIQUE KEY', 'key_fields'=>array('who','when','what'));// UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  940. $expectedStruct['key_who'] = array('type'=>'KEY', 'key_fields'=>array('who'));// KEY `key_who` (`who`)
  941. // $expectedStruct['t1'] = array('type'=>'varchar', 'max_length'=>300, 'default_value'=>null);
  942. // $expectedStruct['t2'] = array('type'=>'int');
  943. // $expectedStruct['t3'] = array('type'=>'int', 'num_precision'=>11, 'default_value'=>null);
  944. // $expectedStruct['t_dec_11_x'] = array('type'=>'decimal', 'num_precision'=>11);
  945. // $expectedStruct['t_dec_11_2'] = array('type'=>'decimal', 'num_precision'=>11, 'num_scale'=>2);
  946. $expectedStruct['t_int'] = array('type'=>'int');
  947. $expectedStruct['t_tinyint'] = array('type'=>'tinyint');
  948. $expectedStruct['t_smallint'] = array('type'=>'smallint');
  949. $expectedStruct['t_mediumint'] = array('type'=>'mediumint');
  950. $expectedStruct['t_bigint'] = array('type'=>'bigint');
  951. $expectedStruct['t_decimal'] = array('type'=>'decimal');
  952. $expectedStruct['t_float'] = array('type'=>'float');
  953. $expectedStruct['t_double'] = array('type'=>'double');
  954. $expectedStruct['t_real'] = array('type'=>'real');
  955. $expectedStruct['t_date'] = array('type'=>'date');
  956. $expectedStruct['t_datetime'] = array('type'=>'datetime');
  957. $expectedStruct['t_timestamp'] = array('type'=>'timestamp');
  958. $expectedStruct['t_time'] = array('type'=>'time');
  959. $expectedStruct['t_year'] = array('type'=>'year');
  960. $expectedStruct['t_char'] = array('type'=>'char');
  961. $expectedStruct['t_varchar'] = array('type'=>'varchar');
  962. $expectedStruct['t_text'] = array('type'=>'text');
  963. $expectedStruct['t_tinytext'] = array('type'=>'tinytext');
  964. $expectedStruct['t_mediumtext'] = array('type'=>'mediumtext');
  965. $expectedStruct['t_longtext'] = array('type'=>'longtext');
  966. $expectedStruct['t_enum'] = array('type'=>'enum', 'values'=>array('v1'));
  967. $expectedStruct['t_set'] = array('type'=>'set', 'values'=>array('v1'));
  968. $expectedStruct['t_bit'] = array('type'=>'bit', 'max_length'=>2);
  969. $expectedStruct['t_boolean'] = array('type'=>'boolean');
  970. $expectedStruct['t_serial'] = array('type'=>'serial');
  971. $expectedStruct['t_binary'] = array('type'=>'binary');
  972. $expectedStruct['t_varbinary'] = array('type'=>'varbinary');
  973. $expectedStruct['t_blob'] = array('type'=>'blob');
  974. $expectedStruct['t_tinyblob'] = array('type'=>'tinyblob');
  975. $expectedStruct['t_mediumblob'] = array('type'=>'mediumblob');
  976. $expectedStruct['t_longblob'] = array('type'=>'longblob');
  977. $expectedStruct['t_geometry'] = array('type'=>'geometry');
  978. $expectedStruct['t_point'] = array('type'=>'point');
  979. $expectedStruct['t_linestring'] = array('type'=>'linestring');
  980. $expectedStruct['t_polygon'] = array('type'=>'polygon');
  981. $expectedStruct['t_multipoint'] = array('type'=>'multipoint');
  982. $expectedStruct['t_multilinestring'] = array('type'=>'multilinestring');
  983. $expectedStruct['t_multipolygon'] = array('type'=>'multipolygon');
  984. $expectedStruct['t_geometrycollection'] = array('type'=>'geometrycollection');
  985. $sqlCreate = $pdo->showCreateStruct('_test_table', $expectedStruct, array('char_encoding'=>'latin2'));
  986. DBG::_(true, true, "fixedEpectedStruct", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
  987. $pdo->assertTableStruct('_test_table', $expectedStruct, array('char_encoding'=>'latin2'));
  988. {// force - drop/create
  989. $pdo->exec("DROP TABLE IF EXISTS _test_table");
  990. $pdo->exec($sqlCreate);
  991. }
  992. }
  993. if(0){// TEST nulls
  994. $sth = $pdo->prepare("DROP TABLE IF EXISTS CRM_NOTIFY");
  995. $sth->execute();
  996. $sth = $pdo->prepare("
  997. CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
  998. `who` varchar(20)
  999. , `when` varchar(255) NOT NULL
  1000. , `what` varchar(255) DEFAULT ''
  1001. , `t1` varchar(255) NOT NULL -- same as with DEFAULT ''
  1002. , `t2` varchar(255) NOT NULL DEFAULT ''
  1003. , `t2z` varchar(255) NOT NULL DEFAULT '0'
  1004. -- , `t3` varchar(255) NOT NULL DEFAULT NULL -- SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value
  1005. , `t4` varchar(255) NULL -- same as with DEFAULT NULL
  1006. , `t5` varchar(255) NULL DEFAULT ''
  1007. , `t6` varchar(255) NULL DEFAULT NULL
  1008. , `i1` int(11) NOT NULL -- same as with DEFAULT 0
  1009. , `i2` int(11) NOT NULL DEFAULT 0
  1010. -- , `i3` int(11) NOT NULL DEFAULT NULL -- SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value
  1011. , `i4` int(11) NULL -- same as with DEFAULT NULL
  1012. , `i5` int(11) NULL DEFAULT 0
  1013. , `i6` int(11) NULL DEFAULT NULL
  1014. , `last_exec_time` datetime DEFAULT NULL
  1015. , KEY `who` (`who`)
  1016. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  1017. ");
  1018. $sth->execute();
  1019. $sth = $pdo->prepare("insert into CRM_NOTIFY (`last_exec_time`) values (NULL)");
  1020. $sth->execute();
  1021. // INSERT INTO CRM_NOTIFY (t1, t2, t2z, t4, t5, t6, i1, i2, i4, i5, i6, last_exec_time)
  1022. // VALUES ('', '', '0', NULL, '', NULL, 0, 0, NULL, 0, NULL, NULL);
  1023. $struct = $pdo->getTableStruct('CRM_NOTIFY');
  1024. DBG::_(true, true, "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
  1025. DBG::_(true, true, "`t2`: is_null(struct[4]['Default'])=(".is_null($struct[4]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  1026. DBG::_(true, true, "`t4`: is_null(struct[6]['Default'])=(".is_null($struct[6]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  1027. DBG::_(true, true, "`t5`: is_null(struct[7]['Default'])=(".is_null($struct[7]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  1028. DBG::_(true, true, "`t6`: is_null(struct[8]['Default'])=(".is_null($struct[8]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  1029. $expectedStruct = array();
  1030. $expectedStruct['t1'] = array('type'=>'varchar', 'max_length'=>300, 'default_value'=>null);
  1031. //$expectedStruct['t2'] = array('type'=>'int', 'num_precision'=>11, 'default_value'=>null);
  1032. $pdo->assertTableStruct('CRM_NOTIFY', $expectedStruct);
  1033. }
  1034. }
  1035. public function reinstall($force = false) {
  1036. $sqlList = array();
  1037. $pdo = DB::getPDO();
  1038. $sqlCreate = <<<EOF_SQL_CREATE
  1039. CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
  1040. `who` varchar(20) NOT NULL
  1041. , `when` varchar(255) NOT NULL
  1042. , `what` varchar(255) NOT NULL
  1043. , `last_exec_time` datetime DEFAULT NULL
  1044. , `_created` datetime NOT NULL
  1045. , UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  1046. , KEY `key_who` (`who`)
  1047. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  1048. EOF_SQL_CREATE;
  1049. /*
  1050. `CRM_NOTIFY`:
  1051. - who - user login
  1052. - when - shedule (once a day, once on houd)
  1053. - what - action type
  1054. - last_exec_time
  1055. */
  1056. if($force){
  1057. $pdo->exec("DROP TABLE IF EXISTS CRM_NOTIFY");
  1058. $pdo->exec("
  1059. CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
  1060. `who` varchar(20) NOT NULL
  1061. , `when` varchar(255) NOT NULL
  1062. , `what` varchar(255) NOT NULL DEFAULT ''
  1063. , `last_exec_time` datetime
  1064. , KEY `key_who` (`who`)
  1065. , UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  1066. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  1067. ");
  1068. }
  1069. {// assertTableStruct CRM_NOTIFY
  1070. $expectedStruct = array();
  1071. $expectedStruct['who'] = array('type'=>'varchar', 'max_length'=>20, 'is_nullable'=>false);// `who` varchar(20) -- TODO: NOT NULL
  1072. $expectedStruct['when'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `when` varchar(255) NOT NULL
  1073. $expectedStruct['what'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `what` varchar(255) NOT NULL
  1074. $expectedStruct['last_exec_time'] = array('type'=>'datetime', 'is_nullable'=>true);// `last_exec_time` datetime
  1075. $expectedStruct['_created'] = array('type'=>'datetime', 'is_nullable'=>false);// `_created` datetime
  1076. $expectedStruct['uniq_key_1'] = array('type'=>'UNIQUE KEY', 'key_fields'=>array('who','when','what'));// UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  1077. $expectedStruct['key_who'] = array('type'=>'KEY', 'key_fields'=>array('who'));// KEY `key_who` (`who`)
  1078. DBG::_(true, true, "sqlCreate - raw", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
  1079. $sqlCreate = $pdo->showCreateStruct('CRM_NOTIFY', $expectedStruct, array('char_encoding'=>'latin2'));
  1080. DBG::_(true, true, "sqlCreate - generated", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
  1081. $pdo->assertTableStruct('CRM_NOTIFY', $expectedStruct, array('char_encoding'=>'latin2'));
  1082. if(0){// force - drop/create
  1083. $pdo->exec("DROP TABLE IF EXISTS CRM_NOTIFY");
  1084. $pdo->exec($sqlCreate);
  1085. }
  1086. }
  1087. {// assertTableStruct CRM_NOTIFY_EXEC_LOG
  1088. // TODO: create table CRM_NOTIFY_EXEC_LOG with action log
  1089. }
  1090. //$this->reinstallFunctions();
  1091. }
  1092. }