Notify.php 38 KB

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