Notify.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. <?php
  2. // @requires $_SERVER['SERVER_NAME']
  3. Lib::loadClass('RouteBase');
  4. Lib::loadClass('Przypomnij');
  5. Lib::loadClass('Request');
  6. Lib::loadClass('Route_UserMsgs');
  7. /*
  8. # Nofitication system:
  9. Sends mail by settings `CRM_NOTIFY`:
  10. - who - user login
  11. - when - shedule (once a day, once on houd)
  12. - what - action type
  13. - last_exec_time
  14. */
  15. class Route_Notify extends RouteBase {
  16. public function handleAuth() {
  17. if (!User::logged()) {
  18. throw new HttpException('Unauthorized', 401);
  19. }
  20. }
  21. public function defaultAction() {
  22. SE_Layout::gora();
  23. try {
  24. $this->formUserTableReminder();
  25. } catch (Exception $e) {
  26. SE_Layout::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  27. }
  28. SE_Layout::dol();
  29. }
  30. public function remindersPanelAction() {
  31. $usrLogin = User::getLogin();
  32. SE_Layout::gora();
  33. //SE_Layout::menu();
  34. {// init args
  35. $usrLogin = User::getLogin();
  36. $usrLogin = (isset($_REQUEST['usrLogin']))? V::get('usrLogin', '', $_REQUEST, 'login') : $usrLogin;
  37. if (!$usrLogin) die("Wrong user login!");
  38. $reminders = V::get('reminder', array(), $_REQUEST, 'array');
  39. if (!$reminders) {
  40. $userReminders = $this->getUserReminders($usrLogin);
  41. if (empty($userReminders)) die("Brak zdefiniowanych powiadomień");
  42. foreach ($userReminders as $reminder) { $reminders[] = $reminder['what']; }
  43. }
  44. }
  45. if ('1' == V::get('send', 0, $_POST, 'int')) {
  46. $this->send($usrLogin, $reminders);
  47. }
  48. $urlParts = array();// index.php?_route=Notify&_task=generateUserReminders&usrLogin=magdalena.cichosz&reminder[]=msgs
  49. $urlParts[] = Request::getPathUri();
  50. $urlParts[] = 'index.php?_route=Notify&_task=generateUserReminders';
  51. $urlParts[] = "&usrLogin={$usrLogin}";
  52. foreach ($reminders as $reminderType) {
  53. $urlParts[] = "&reminder[]={$reminderType}";
  54. }
  55. $previewLink = implode('', $urlParts);
  56. $lastSentDate = 'brak';
  57. ?>
  58. <div class="jumbotron">
  59. <div class="container">
  60. <form id="reminderPanelForm" class="form-horizontal" method="POST">
  61. <div class="form-group">
  62. <label class="col-sm-2 control-label">User</label>
  63. <div class="col-sm-10">
  64. <input class="form-control" type="text" name="usrLogin" value="<?php echo $usrLogin; ?>">
  65. </div>
  66. </div>
  67. <?php foreach ($this->getFieldValueLabels('what') as $reminderType => $reminderLabel) : ?>
  68. <?php if ('l_app_all_przypomnij' == $reminderType) continue; ?>
  69. <div class="col-sm-3">
  70. <div class="checkbox">
  71. <label>
  72. <input type="checkbox"
  73. name="reminder[]"
  74. <?php if (in_array($reminderType, $reminders)) : ?>
  75. checked="checked"
  76. <?php endif; ?>
  77. value="<?php echo $reminderType; ?>"> <?php echo $reminderLabel; ?>
  78. </label>
  79. </div>
  80. </div>
  81. <?php endforeach; ?>
  82. <div class="col-sm-offset-2 col-sm-10" style="margin-top:10px;padding-top:10px;border-top:1px solid silver;">
  83. <button class="btn btn-default" onclick="refreshPreview(); return false;">odśwież podgląd</button>
  84. <button class="btn btn-primary" name="send" value="1">wyślij maila</button>
  85. data wysłania ostatniej wiadomości do wybranego użytkownika: <?php echo $lastSentDate; ?>
  86. </div>
  87. </form>
  88. </div>
  89. </div>
  90. <script>
  91. function refreshPreview() {
  92. // $urlParts[] = Request::getPathUri();
  93. // $urlParts[] = 'index.php?_route=Notify&_task=generateUserReminders';
  94. // $urlParts[] = "&usrLogin={$usrLogin}";
  95. // foreach ($reminders as $reminderType) {
  96. // $urlParts[] = "&reminder[]={$reminderType}";
  97. // }
  98. var frm = document.getElementById('reminderPanelForm'),
  99. baseUrl = '<?php echo Request::getPathUri(); ?>',
  100. previewLink = '';
  101. previewLink = baseUrl + 'index.php?_route=Notify&_task=generateUserReminders';
  102. previewLink += '&usrLogin=' + frm['usrLogin'].value;
  103. for (var i in frm['reminder[]']) {
  104. console.log('frm[reminder[]]['+i+']', frm['reminder[]'][i].value, ' checked:', frm['reminder[]'][i].checked);
  105. if (frm['reminder[]'][i].checked) {
  106. previewLink += '&reminder[]=' + frm['reminder[]'][i].value;
  107. }
  108. }
  109. console.log('frm[reminder[]].', frm['reminder[]']);
  110. console.log('frm[reminder[]].value', frm['reminder[]'].value);
  111. console.log('previewLink:', previewLink);
  112. document.getElementById('reminderPreview').src = previewLink;
  113. }
  114. </script>
  115. <div>
  116. <iframe id="reminderPreview" src="<?php echo $previewLink; ?>" style="width:100%;height:500px;max-height:500px;overflow:scroll;border:2px solid silver"></iframe>
  117. </div>
  118. <?php
  119. SE_Layout::dol();
  120. }
  121. public function send($usrLogin, $reminders) {
  122. DBG::_(true, true, "usrLogin", $usrLogin, __CLASS__, __FUNCTION__, __LINE__);
  123. DBG::_(true, true, "reminders", $reminders, __CLASS__, __FUNCTION__, __LINE__);
  124. $user = null;
  125. $pdo = DB::getPDO();
  126. $sth = $pdo->prepare("
  127. select u.ID, u.ADM_ACCOUNT as login, u.EMAIL_LOCAL_ACCOUNT_ADDRESS as aliasy
  128. from ADMIN_USERS u
  129. where u.ADM_ACCOUNT = :usr_login
  130. ");
  131. $sth->bindValue(':usr_login', $usrLogin, PDO::PARAM_STR);
  132. $sth->execute();
  133. $user = $sth->fetch();
  134. if (!$user) throw new Exception("User not found");
  135. if (empty($user['aliasy'])) throw new Exception("Brak lokalnego adresu email");
  136. $aliasy = explode(' ', trim($user['aliasy']));
  137. $mainMail = reset($aliasy);
  138. $pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i";
  139. if (!preg_match($pattern, $mainMail)) throw new Exception("Adres email ma błędny format");
  140. $to = $mainMail;
  141. $headers = "From: " . "noreply@{$_SERVER['SERVER_NAME']}" . "\r\n";
  142. $headers .= "MIME-Version: 1.0\r\n";
  143. $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
  144. $subject = "Powiadomienie - {$_SERVER['SERVER_NAME']}";
  145. ob_start();
  146. $this->generateUserReminders($usrLogin, $reminders);
  147. $message = ob_get_clean();
  148. if (!mail($to, $subject, $message, $headers)) throw new Exception("Nie udało się wysłać powiadomienia");
  149. echo 'Your message has been sent.';
  150. throw new Exception(".EOF TODO");
  151. DBG::_(true, true, "user", $user, __CLASS__, __FUNCTION__, __LINE__);
  152. }
  153. public function generateUserRemindersAction() {
  154. $usrLogin = User::getLogin();
  155. $usrLogin = (isset($_GET['usrLogin']))? V::get('usrLogin', '', $_GET, 'login') : $usrLogin;
  156. if (!$usrLogin) die("Wrong user login!");
  157. $reminders = V::get('reminder', array(), $_GET, 'array');
  158. if (!$reminders) {
  159. $userReminders = $this->getUserReminders($usrLogin);
  160. if (empty($userReminders)) die("Brak zdefiniowanych powiadomień");
  161. foreach ($userReminders as $reminder) { $reminders[] = $reminder['what']; }
  162. }
  163. header('Content-Type: text/html; charset="UTF-8"');
  164. $this->generateUserReminders($usrLogin, $reminders);
  165. }
  166. public function generateUserReminders($usrLogin, $reminders) {
  167. echo '<html>';
  168. echo '<body>';
  169. echo '<div>';
  170. ?>
  171. <h1 style="<?php echo $this->inlineCss('h1'); ?>">Powiadomienia dla <code><?php echo $usrLogin; ?></code></h1>
  172. <?php foreach ($reminders as $reminderType) : ?>
  173. <div style="<?php echo $this->inlineCss('header'); ?>"><strong><?php echo $this->printValue('what', $reminderType); ?></strong></div>
  174. <table rules="all" cellspacing="0" style="border-color:#bbb;" cellpadding="8">
  175. <?php $lp = 0; foreach ($this->getTodoForUserReminder($usrLogin, $reminderType) as $todo) : ?>
  176. <tr>
  177. <td style="<?php echo $this->inlineCss('td.lp'); ?>"><?php echo ++$lp; ?></td>
  178. <td style="<?php echo $this->inlineCss('td.' . $todo['_l_app_class']); ?>">
  179. <span style="<?php echo $this->inlineCss('l_app_date.' . $todo['_l_app_class']); ?>"><?php echo $todo['_l_app_date']; ?></span>
  180. <br><i style="<?php echo $this->inlineCss('l_app.target'); ?>"><?php echo $todo['_l_app']; ?></i>
  181. <?php if (V::get('ID', '', $todo) > 0) : ?>
  182. <br><a href="<?php echo $this->editLink($todo); ?>" target="_blank" style="<?php echo $this->inlineCss('a'); ?>">Edytuj rekord <?php echo $todo['ID']; ?></a>
  183. <?php elseif (V::get('idMsg', '', $todo) > 0) : ?>
  184. <br><a href="<?php echo $this->readMsgLink($todo); ?>" target="_blank" style="<?php echo $this->inlineCss('a'); ?>">Przeczytaj</a>
  185. <?php endif; ?>
  186. </td>
  187. <td style="<?php echo $this->inlineCss('td.info'); ?>"><?php echo $todo['L_APPOITMENT_INFO']; ?></td>
  188. <td style="<?php echo $this->inlineCss('td.record-info'); ?>">
  189. <?php echo $todo['_title']; ?>
  190. </td>
  191. <?php if (V::get('DBG', '', $_GET)) : ?>
  192. <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>
  193. <?php endif; ?>
  194. </tr>
  195. <?php endforeach; ?>
  196. </table>
  197. <?php endforeach; ?>
  198. <?php
  199. echo '</div>';// .container
  200. echo '</body>';
  201. echo '</html>';
  202. }
  203. public function editLink($todo) {
  204. $idTblZasob = 0;
  205. $idRecord = 0;
  206. if ('zasob' == $todo['_task_type']
  207. || 'proces' == $todo['_task_type']
  208. || 'projekt' == $todo['_task_type']
  209. || 'koresp' == $todo['_task_type']
  210. || 'task' == $todo['_task_type']
  211. ) {
  212. $idTblZasob = $todo['_idZasobTable'];
  213. $idRecord = $todo['ID'];
  214. }
  215. if (!$idTblZasob || !$idRecord) return '#';
  216. $urlParts = array();
  217. $urlParts[] = (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']))? $_SERVER['HTTP_X_FORWARDED_PROTO'] : V::get('REQUEST_SCHEME', 'http', $_SERVER);
  218. $urlParts[] = '://';
  219. $urlParts[] = $_SERVER['SERVER_NAME'];
  220. $urlParts[] = $_SERVER['SCRIPT_URL'];
  221. // https://biuro.biall-net.pl/dev-pl/se-master/index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=1466#EDIT/3954
  222. $urlParts[] = "?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$idTblZasob}#EDIT/{$idRecord}";
  223. return implode("", $urlParts);
  224. }
  225. public function readMsgLink($todo) {
  226. $idMsg = 0;
  227. if ('msg' == $todo['_task_type']) {
  228. $idMsg = $todo['idMsg'];
  229. }
  230. if (!$idMsg) return '#' . json_encode($todo);
  231. if (!$idMsg) return '#';
  232. $urlParts = array();
  233. $urlParts[] = Request::getPathUri();
  234. $urlParts[] = 'index.php';
  235. $urlParts[] = "?_route=UserMsgs";
  236. $urlParts[] = "&_task=read";
  237. $urlParts[] = "&usrLogin={$usrLogin}";
  238. $urlParts[] = "&id={$idMsg}";
  239. return implode("", $urlParts);
  240. }
  241. public function inlineCss($cssSelector) {
  242. $baseCss = array();
  243. $baseCss['font-family'] = 'Arial, Helvetica, sans-serif';
  244. $baseCss['font-size'] = 'small';
  245. $baseCss['color'] = '#333';
  246. $customCss = array(
  247. 'h1' => array(),
  248. 'header' => array('background' => '#eee', 'padding' => '4px 10px', 'margin-top' => '6px'),
  249. 'l_app.target' => array('color' => '#999', 'white-space' => 'nowrap'),
  250. 'td.date-base' => array('white-space' => 'nowrap'),
  251. 'td.lp' => array('color' => 'silver'),
  252. 'l_app_date-base' => array('white-space' => 'nowrap'),
  253. 'a' => array('color' => '#337ab7', 'text-decoration' => 'none')
  254. );
  255. $css = $baseCss;
  256. if (array_key_exists($cssSelector, $customCss)) $css = V::extend($css, $customCss[$cssSelector]);
  257. if ('td.date-' == substr($cssSelector, 0, 8)) {
  258. $css = V::extend($css, $customCss['td.date-base']);
  259. $css = V::extend($css, array('color' => $this->getTodoDateCssColor(substr($cssSelector, 3))));
  260. }
  261. if ('l_app_date.date-' == substr($cssSelector, 0, 16)) {
  262. $css = V::extend($css, $customCss['l_app_date-base']);
  263. $css = V::extend($css, array('color' => $this->getTodoDateCssColor(substr($cssSelector, 11))));
  264. }
  265. $inlineCss = array();
  266. foreach ($css as $cssPropName => $cssValue) {
  267. if (true === $cssValue) {
  268. if (!array_key_exists($cssPropName, $baseCss)) continue;
  269. $cssValue = $baseCss[$cssPropName];
  270. }
  271. $inlineCss[] = "{$cssPropName}:{$cssValue}";
  272. }
  273. return implode(";", $inlineCss);
  274. }
  275. public function getTodoDateCssColor($lAppClass) {
  276. $color = '#000';
  277. switch ($lAppClass) {
  278. case 'date-PO_TERMINIE': $color = '#FD4242'; break;
  279. case 'date-DZISIAJ': $color = '#34B934'; break;
  280. case 'date-W_CIAGU_7_DNI': $color = '#C58B1F'; break;
  281. case 'date-PO_7_DNIACH': $color = '#87847D'; break;
  282. }
  283. return $color;
  284. }
  285. public function getTodoForUserReminder($usrLogin, $reminderWhat) {
  286. $listTodo = array();
  287. if ('msgs' == $reminderWhat) {
  288. $routeMsgs = Router::getRoute('UserMsgs');
  289. $routeMsgs->_listLimit = 50;
  290. $msgs = $routeMsgs->getMsgs('unread', $usrLogin);
  291. foreach ($msgs as $idMsg => $msg) {
  292. $todo = array();
  293. $todo['_task_type'] = 'msg';
  294. // [userTargetType] => group
  295. // [userTargetName] => 2948
  296. $todo['_l_app'] = '';
  297. if ('group' == $msg['_raw']->userTargetType) {
  298. $todo['_l_app'] = "do grupy {$msg['_raw']->userTargetName}";
  299. } else if ('user' == $msg['_raw']->userTargetType) {
  300. $todo['_l_app'] = "do {$msg['_raw']->userTargetName}";
  301. }
  302. $todo['idMsg'] = $idMsg;
  303. $todo['_l_app_date'] = substr($msg['_raw']->A_RECORD_CREATE_DATE, 0, 10);
  304. $todo['_l_app_class'] = 'date-PO_TERMINIE';
  305. $todo['L_APPOITMENT_INFO'] = $msg['message'];
  306. // $msg['_raw']->A_STATUS == 'WAITING' => Unread
  307. // $msg['_raw']->A_STATUS == 'NORMAL' => Read
  308. // $msg['_raw']->A_STATUS == 'OFF_SOFT' => Trash
  309. $msgInfo = '<i style="color:silver">' . "Wysłane {$msg['_raw']->A_RECORD_CREATE_DATE} przez {$msg['_raw']->A_RECORD_CREATE_AUTHOR}" . '</i>';
  310. 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>';
  311. $todo['_title'] = $msgInfo;
  312. $listTodo[] = $todo;
  313. }
  314. }
  315. else if ('l_app_projekty' == $reminderWhat) {
  316. $tasks = $this->getPrzypomnijTasks($usrLogin);
  317. foreach ($tasks as $task) {
  318. if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
  319. if ('projekt' != $task['_task_type']) continue;
  320. //$task['DESC'] = $task['A_PROBLEM_DESC'];
  321. $listTodo[] = $task;
  322. }
  323. }
  324. else if ('l_app_koresp' == $reminderWhat) {
  325. $tasks = $this->getPrzypomnijTasks($usrLogin);
  326. foreach ($tasks as $task) {
  327. if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
  328. if ('koresp' != $task['_task_type']) continue;
  329. //$task['DESC'] = $task['A_PROBLEM_DESC'];
  330. $listTodo[] = $task;
  331. }
  332. }
  333. else if ('l_app_zadania' == $reminderWhat) {
  334. $tasks = $this->getPrzypomnijTasks($usrLogin);
  335. foreach ($tasks as $task) {
  336. if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
  337. if ('task' != $task['_task_type']) continue;
  338. //$task['DESC'] = $task['A_PROBLEM_DESC'];
  339. $listTodo[] = $task;
  340. }
  341. }
  342. else if ('l_app_procesy' == $reminderWhat) {
  343. $tasks = $this->getPrzypomnijTasks($usrLogin);
  344. foreach ($tasks as $task) {
  345. if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
  346. if ('proces' != $task['_task_type']) continue;
  347. $listTodo[] = $task;
  348. }
  349. }
  350. else if ('l_app_zasoby' == $reminderWhat) {
  351. $tasks = $this->getPrzypomnijTasks($usrLogin);
  352. foreach ($tasks as $task) {
  353. if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
  354. if ('zasob' != $task['_task_type']) continue;
  355. $listTodo[] = $task;
  356. }
  357. }
  358. return $listTodo;
  359. }
  360. public function getPrzypomnijTasks($usrLogin) {
  361. static $_tasks = array();
  362. if (empty($_tasks)) {
  363. $przypomnij = new Przypomnij();
  364. $przypomnij->setRecurseLimit(3);
  365. $przypomnij->fetchData();
  366. $przypomnij->setFltrUser($usrLogin);
  367. $tasks = $przypomnij->getTasksByDate();
  368. $usrGroupNames = User::getLdapGroupsNames();
  369. foreach ($tasks as $task) {
  370. if (!$task->_show) continue;
  371. if (
  372. $task->A_CLASSIFIED != ''
  373. and !(in_array($task->A_CLASSIFIED, $usrGroupNames))
  374. and $task->A_ADM_COMPANY != ''
  375. and !(in_array($task->A_ADM_COMPANY, $usrGroupNames))
  376. // !($allowedUsers[$task->_l_app]) - to jest bez sensu - wystarczy widocznosc sprawy?
  377. ) {
  378. continue;
  379. }
  380. $task->_l_app_class = $przypomnij->getTaskDateFltrType($task->_l_app_date);
  381. $task->_idZasobTable = $przypomnij->getZasobIdByType($task->_task_type);
  382. $_tasks[] = (array)$task;
  383. }
  384. }
  385. return $_tasks;
  386. }
  387. public function removeUserTableReminder($args) {
  388. $usrLogin = User::getLogin();
  389. $who = V::validate('who', $args, array('type'=>'word', 'equal'=>$usrLogin, 'error_msg_equal'=>"Brak uprawnień do wprowadzania zmian w powiadomieniach innych użytwkoników"));
  390. $what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$this->getFieldValues('what')));
  391. $when = V::validate('when', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$this->getFieldValues('when')));
  392. if ($usrLogin != $who) throw new Exception("Brak uprawnień do wprowadzania zmian w powiadomieniach innych użytwkoników");
  393. $pdo = DB::getPDO();
  394. $sth = $pdo->prepare("
  395. delete from `CRM_NOTIFY`
  396. where `who` = :who
  397. and `what` = :what
  398. and `when` = :when
  399. ");
  400. $sth->bindValue(':who', $usrLogin, PDO::PARAM_STR);
  401. $sth->bindValue(':what', $what, PDO::PARAM_STR);
  402. $sth->bindValue(':when', $when, PDO::PARAM_STR);
  403. $sth->execute();
  404. }
  405. public function formUserTableReminder() {
  406. $usrLogin = User::getLogin();
  407. echo '<div class="container">';
  408. $subTask = V::get('_subTask', '', $_POST);
  409. if ('_add_table_reminder' == $subTask) {
  410. try {
  411. $this->addUserTableReminder($usrLogin, $_POST);
  412. SE_Layout::alert('info', "Dodano powiadomienie");
  413. } catch (PDOException $e) {
  414. if (!empty($e->errorInfo) && !empty($e->errorInfo[1]) && '1062' == $e->errorInfo[1]) {
  415. SE_Layout::alert('warning', "Powiadomienie tego typu zostało już wcześniej dodane");
  416. } else {
  417. SE_Layout::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage() . '<br>' . "Info: " . json_encode($e->errorInfo));
  418. }
  419. } catch (Exception $e) {
  420. SE_Layout::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  421. }
  422. }
  423. else if ('_rm_table_reminder' == $subTask) {
  424. try {
  425. $this->removeUserTableReminder($_POST);
  426. SE_Layout::alert('info', "Usunięto powiadomienie");
  427. } catch (Exception $e) {
  428. SE_Layout::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
  429. }
  430. }
  431. $userReminders = $this->getUserReminders($usrLogin);
  432. ?>
  433. <h1>Powiadomienia dla <code><?php echo $usrLogin; ?></code></h1>
  434. <?php if (empty($userReminders)) : ?>
  435. <?php SE_Layout::alert('warning', "Brak zdefiniowanych powiadomień"); ?>
  436. <?php else : ?>
  437. <table class="table table-hovered">
  438. <thead>
  439. <tr>
  440. <th>rodzaj</th>
  441. <th>jak często</th>
  442. <th>utworzony</th>
  443. <th>ostatnio uruchomiony</th>
  444. <th></th>
  445. </tr>
  446. </thead>
  447. <tbody>
  448. <?php foreach ($userReminders as $reminder) : ?>
  449. <tr>
  450. <td><?php echo $this->printValue('what', $reminder['what']); ?></td>
  451. <td><?php echo $this->printValue('when', $reminder['when']); ?></td>
  452. <td><?php echo $reminder['_created']; ?></td>
  453. <td><?php echo ($reminder['last_exec_time'])? $reminder['last_exec_time'] : '<i>brak danych</i>'; ?></td>
  454. <td>
  455. <form method="post" class="form-inline">
  456. <input type="hidden" name="_subTask" value="_rm_table_reminder">
  457. <input type="hidden" name="who" value="<?php echo $usrLogin; ?>">
  458. <input type="hidden" name="what" value="<?php echo $reminder['what']; ?>">
  459. <input type="hidden" name="when" value="<?php echo $reminder['when']; ?>">
  460. <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>
  461. </form>
  462. </td>
  463. </tr>
  464. <?php endforeach; ?>
  465. </tbody>
  466. </table>
  467. <?php endif; ?>
  468. <hr>
  469. <h4>Dodaj powiadomienia:</h4>
  470. <form method="post" class="form-inline">
  471. <input type="hidden" name="_subTask" value="_add_table_reminder">
  472. <label>rodzaj:</label>
  473. <select type="select" name="what" class="form-control">
  474. <option value="">[ Wybierz ]</option>
  475. <?php foreach ($this->getFieldValueLabels('what') as $value => $label) : ?>
  476. <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
  477. <?php endforeach; ?>
  478. </select>
  479. <label>jak często:</label>
  480. <select type="select" name="when" class="form-control">
  481. <option value="">[ Wybierz ]</option>
  482. <option value="once_a_day">Raz dziennie</option>
  483. </select>
  484. <input type="submit" value="Dodaj" class="btn btn-primary">
  485. </form>
  486. <?php
  487. echo '</div>';// .container
  488. }
  489. public function printValue($fldName, $argValue) {
  490. if ('what' == $fldName || 'when' == $fldName) {
  491. $valueLabels = $this->getFieldValueLabels($fldName);
  492. return V::get($argValue, $argValue, $valueLabels);
  493. }
  494. return $argValue;
  495. }
  496. public function getFieldValueLabels($fldName) {
  497. $valueLabels = array();
  498. if ('what' == $fldName) {
  499. $valueLabels['msgs'] = "wiadomości";
  500. $valueLabels['l_app_projekty'] = "projekty";
  501. $valueLabels['l_app_koresp'] = "korespondencja";
  502. $valueLabels['l_app_zadania'] = "zadania";
  503. $valueLabels['l_app_procesy'] = "procesy";
  504. $valueLabels['l_app_zasoby'] = "zasoby";
  505. $valueLabels['l_app_all_przypomnij'] = "*wszystkie";
  506. } else if ('when' == $fldName) {
  507. $valueLabels['once_a_day'] = "Raz dziennie";
  508. }
  509. return $valueLabels;
  510. }
  511. public function getFieldValues($fldName) {
  512. $valueLabels = $this->getFieldValueLabels($fldName);
  513. return array_keys($valueLabels);
  514. }
  515. public function addUserTableReminder($usrLogin, $args) {
  516. $what_values = $this->getFieldValues('what');
  517. $what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$what_values));
  518. $when_values = $this->getFieldValues('when');
  519. $when = V::validate('when', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$when_values));
  520. $pdo = DB::getPDO();
  521. $sth = $pdo->prepare("
  522. insert into `CRM_NOTIFY` (
  523. `who`,
  524. `what`,
  525. `when`,
  526. `_created`
  527. ) values (
  528. :who,
  529. :what,
  530. :when,
  531. NOW()
  532. )
  533. ");
  534. $bindValues = array();
  535. $bindValues['who'] = array($usrLogin, PDO::PARAM_STR);
  536. $bindValues['what'] = array($what, PDO::PARAM_STR);
  537. $bindValues['when'] = array($when, PDO::PARAM_STR);
  538. $pdo->bindValues($sth, $bindValues);
  539. //DBG::_(true, true, "sql", $pdo->getRawSql($sth), __CLASS__, __FUNCTION__, __LINE__);
  540. // try {
  541. $sth->execute();
  542. // } catch (PDOException $e) {
  543. // throw new Exception("Błąd bazy danych: " . json_encode($e->errorInfo));
  544. // } catch (Exception $e) {
  545. // throw $e;
  546. // }
  547. }
  548. public function getUserReminders($usrLogin) {
  549. $pdo = DB::getPDO();
  550. $sth = $pdo->prepare("
  551. select n.*
  552. from `CRM_NOTIFY` n
  553. where n.`who` = '{$usrLogin}'
  554. ");
  555. $sth->execute();
  556. $reminders = $sth->fetchAll();
  557. return $reminders;
  558. }
  559. public function reinstallAction() {
  560. try {
  561. $force = ('true' == V::get('_force', '', $_GET));
  562. $this->reinstall($force);
  563. } catch (Exception $e) {
  564. echo'<div style="border:1px solid red; background:red; color:#fff;">';
  565. echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
  566. echo'</div>';
  567. }
  568. die('OK');
  569. }
  570. public function reinstallFunctionsAction() {
  571. $this->reinstallFunctions();
  572. die('OK');
  573. }
  574. public function runAction() {
  575. $msgId = V::get('_msgId', 0, $_REQUEST, 'int');
  576. if ($msgId > 0) {
  577. $this->runByMessageId($msgId);
  578. }
  579. $jsonData = new stdClass();
  580. $jsonData->type = 'success';
  581. $jsonData->msg = 'Gotowe';
  582. echo json_encode($jsonData);
  583. exit;
  584. }
  585. public function reinstallFunctions() {
  586. $sqlList = array();
  587. $db = DB::getDB();
  588. if ($db->has_errors()) {
  589. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  590. }
  591. foreach ($sqlList as $sqlName => $sql) {
  592. $res = $db->query($sql);
  593. if ($db->has_errors()) {
  594. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  595. }
  596. }
  597. }
  598. public function testReinstallTable() {
  599. $pdo = DB::getPDO();
  600. if(1){// TEST
  601. $expectedStruct = array();
  602. $expectedStruct['who'] = array('type'=>'varchar', 'max_length'=>20, 'is_nullable'=>false);// `who` varchar(20) -- TODO: NOT NULL
  603. $expectedStruct['when'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `when` varchar(255) NOT NULL
  604. $expectedStruct['what'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `what` varchar(255) NOT NULL
  605. $expectedStruct['last_exec_time'] = array('type'=>'datetime', 'is_nullable'=>true);// `last_exec_time` datetime
  606. $expectedStruct['_created'] = array('type'=>'datetime', 'is_nullable'=>false);// `_created` datetime
  607. $expectedStruct['uniq_key_1'] = array('type'=>'UNIQUE KEY', 'key_fields'=>array('who','when','what'));// UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  608. $expectedStruct['key_who'] = array('type'=>'KEY', 'key_fields'=>array('who'));// KEY `key_who` (`who`)
  609. // $expectedStruct['t1'] = array('type'=>'varchar', 'max_length'=>300, 'default_value'=>null);
  610. // $expectedStruct['t2'] = array('type'=>'int');
  611. // $expectedStruct['t3'] = array('type'=>'int', 'num_precision'=>11, 'default_value'=>null);
  612. // $expectedStruct['t_dec_11_x'] = array('type'=>'decimal', 'num_precision'=>11);
  613. // $expectedStruct['t_dec_11_2'] = array('type'=>'decimal', 'num_precision'=>11, 'num_scale'=>2);
  614. $expectedStruct['t_int'] = array('type'=>'int');
  615. $expectedStruct['t_tinyint'] = array('type'=>'tinyint');
  616. $expectedStruct['t_smallint'] = array('type'=>'smallint');
  617. $expectedStruct['t_mediumint'] = array('type'=>'mediumint');
  618. $expectedStruct['t_bigint'] = array('type'=>'bigint');
  619. $expectedStruct['t_decimal'] = array('type'=>'decimal');
  620. $expectedStruct['t_float'] = array('type'=>'float');
  621. $expectedStruct['t_double'] = array('type'=>'double');
  622. $expectedStruct['t_real'] = array('type'=>'real');
  623. $expectedStruct['t_date'] = array('type'=>'date');
  624. $expectedStruct['t_datetime'] = array('type'=>'datetime');
  625. $expectedStruct['t_timestamp'] = array('type'=>'timestamp');
  626. $expectedStruct['t_time'] = array('type'=>'time');
  627. $expectedStruct['t_year'] = array('type'=>'year');
  628. $expectedStruct['t_char'] = array('type'=>'char');
  629. $expectedStruct['t_varchar'] = array('type'=>'varchar');
  630. $expectedStruct['t_text'] = array('type'=>'text');
  631. $expectedStruct['t_tinytext'] = array('type'=>'tinytext');
  632. $expectedStruct['t_mediumtext'] = array('type'=>'mediumtext');
  633. $expectedStruct['t_longtext'] = array('type'=>'longtext');
  634. $expectedStruct['t_enum'] = array('type'=>'enum', 'values'=>array('v1'));
  635. $expectedStruct['t_set'] = array('type'=>'set', 'values'=>array('v1'));
  636. $expectedStruct['t_bit'] = array('type'=>'bit', 'max_length'=>2);
  637. $expectedStruct['t_boolean'] = array('type'=>'boolean');
  638. $expectedStruct['t_serial'] = array('type'=>'serial');
  639. $expectedStruct['t_binary'] = array('type'=>'binary');
  640. $expectedStruct['t_varbinary'] = array('type'=>'varbinary');
  641. $expectedStruct['t_blob'] = array('type'=>'blob');
  642. $expectedStruct['t_tinyblob'] = array('type'=>'tinyblob');
  643. $expectedStruct['t_mediumblob'] = array('type'=>'mediumblob');
  644. $expectedStruct['t_longblob'] = array('type'=>'longblob');
  645. $expectedStruct['t_geometry'] = array('type'=>'geometry');
  646. $expectedStruct['t_point'] = array('type'=>'point');
  647. $expectedStruct['t_linestring'] = array('type'=>'linestring');
  648. $expectedStruct['t_polygon'] = array('type'=>'polygon');
  649. $expectedStruct['t_multipoint'] = array('type'=>'multipoint');
  650. $expectedStruct['t_multilinestring'] = array('type'=>'multilinestring');
  651. $expectedStruct['t_multipolygon'] = array('type'=>'multipolygon');
  652. $expectedStruct['t_geometrycollection'] = array('type'=>'geometrycollection');
  653. $sqlCreate = $pdo->showCreateStruct('_test_table', $expectedStruct, array('char_encoding'=>'latin2'));
  654. DBG::_(true, true, "fixedEpectedStruct", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
  655. $pdo->assertTableStruct('_test_table', $expectedStruct, array('char_encoding'=>'latin2'));
  656. {// force - drop/create
  657. $pdo->exec("DROP TABLE IF EXISTS _test_table");
  658. $pdo->exec($sqlCreate);
  659. }
  660. }
  661. if(0){// TEST nulls
  662. $sth = $pdo->prepare("DROP TABLE IF EXISTS CRM_NOTIFY");
  663. $sth->execute();
  664. $sth = $pdo->prepare("
  665. CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
  666. `who` varchar(20)
  667. , `when` varchar(255) NOT NULL
  668. , `what` varchar(255) DEFAULT ''
  669. , `t1` varchar(255) NOT NULL -- same as with DEFAULT ''
  670. , `t2` varchar(255) NOT NULL DEFAULT ''
  671. , `t2z` varchar(255) NOT NULL DEFAULT '0'
  672. -- , `t3` varchar(255) NOT NULL DEFAULT NULL -- SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value
  673. , `t4` varchar(255) NULL -- same as with DEFAULT NULL
  674. , `t5` varchar(255) NULL DEFAULT ''
  675. , `t6` varchar(255) NULL DEFAULT NULL
  676. , `i1` int(11) NOT NULL -- same as with DEFAULT 0
  677. , `i2` int(11) NOT NULL DEFAULT 0
  678. -- , `i3` int(11) NOT NULL DEFAULT NULL -- SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value
  679. , `i4` int(11) NULL -- same as with DEFAULT NULL
  680. , `i5` int(11) NULL DEFAULT 0
  681. , `i6` int(11) NULL DEFAULT NULL
  682. , `last_exec_time` datetime DEFAULT NULL
  683. , KEY `who` (`who`)
  684. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  685. ");
  686. $sth->execute();
  687. $sth = $pdo->prepare("insert into CRM_NOTIFY (`last_exec_time`) values (NULL)");
  688. $sth->execute();
  689. // INSERT INTO CRM_NOTIFY (t1, t2, t2z, t4, t5, t6, i1, i2, i4, i5, i6, last_exec_time)
  690. // VALUES ('', '', '0', NULL, '', NULL, 0, 0, NULL, 0, NULL, NULL);
  691. $struct = $pdo->getTableStruct('CRM_NOTIFY');
  692. DBG::_(true, true, "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
  693. DBG::_(true, true, "`t2`: is_null(struct[4]['Default'])=(".is_null($struct[4]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  694. DBG::_(true, true, "`t4`: is_null(struct[6]['Default'])=(".is_null($struct[6]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  695. DBG::_(true, true, "`t5`: is_null(struct[7]['Default'])=(".is_null($struct[7]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  696. DBG::_(true, true, "`t6`: is_null(struct[8]['Default'])=(".is_null($struct[8]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  697. $expectedStruct = array();
  698. $expectedStruct['t1'] = array('type'=>'varchar', 'max_length'=>300, 'default_value'=>null);
  699. //$expectedStruct['t2'] = array('type'=>'int', 'num_precision'=>11, 'default_value'=>null);
  700. $pdo->assertTableStruct('CRM_NOTIFY', $expectedStruct);
  701. }
  702. }
  703. public function reinstall($force = false) {
  704. $sqlList = array();
  705. $pdo = DB::getPDO();
  706. $sqlCreate = <<<EOF_SQL_CREATE
  707. CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
  708. `who` varchar(20) NOT NULL
  709. , `when` varchar(255) NOT NULL
  710. , `what` varchar(255) NOT NULL
  711. , `last_exec_time` datetime DEFAULT NULL
  712. , `_created` datetime NOT NULL
  713. , UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  714. , KEY `key_who` (`who`)
  715. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  716. EOF_SQL_CREATE;
  717. /*
  718. `CRM_NOTIFY`:
  719. - who - user login
  720. - when - shedule (once a day, once on houd)
  721. - what - action type
  722. - last_exec_time
  723. */
  724. if($force){
  725. $pdo->exec("DROP TABLE IF EXISTS CRM_NOTIFY");
  726. $pdo->exec("
  727. CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
  728. `who` varchar(20) NOT NULL
  729. , `when` varchar(255) NOT NULL
  730. , `what` varchar(255) NOT NULL DEFAULT ''
  731. , `last_exec_time` datetime
  732. , KEY `key_who` (`who`)
  733. , UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  734. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  735. ");
  736. }
  737. {// assertTableStruct CRM_NOTIFY
  738. $expectedStruct = array();
  739. $expectedStruct['who'] = array('type'=>'varchar', 'max_length'=>20, 'is_nullable'=>false);// `who` varchar(20) -- TODO: NOT NULL
  740. $expectedStruct['when'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `when` varchar(255) NOT NULL
  741. $expectedStruct['what'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `what` varchar(255) NOT NULL
  742. $expectedStruct['last_exec_time'] = array('type'=>'datetime', 'is_nullable'=>true);// `last_exec_time` datetime
  743. $expectedStruct['_created'] = array('type'=>'datetime', 'is_nullable'=>false);// `_created` datetime
  744. $expectedStruct['uniq_key_1'] = array('type'=>'UNIQUE KEY', 'key_fields'=>array('who','when','what'));// UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  745. $expectedStruct['key_who'] = array('type'=>'KEY', 'key_fields'=>array('who'));// KEY `key_who` (`who`)
  746. DBG::_(true, true, "sqlCreate - raw", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
  747. $sqlCreate = $pdo->showCreateStruct('CRM_NOTIFY', $expectedStruct, array('char_encoding'=>'latin2'));
  748. DBG::_(true, true, "sqlCreate - generated", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
  749. $pdo->assertTableStruct('CRM_NOTIFY', $expectedStruct, array('char_encoding'=>'latin2'));
  750. if(0){// force - drop/create
  751. $pdo->exec("DROP TABLE IF EXISTS CRM_NOTIFY");
  752. $pdo->exec($sqlCreate);
  753. }
  754. }
  755. {// assertTableStruct CRM_NOTIFY_EXEC_LOG
  756. // TODO: create table CRM_NOTIFY_EXEC_LOG with action log
  757. }
  758. //$this->reinstallFunctions();
  759. }
  760. }