Notify.php 38 KB

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