Notify.php 39 KB

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