Notify.php 34 KB

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