Notify.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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. $sqlUsers = array(); foreach ($rawUsers as $row) { $sqlUsers[] = $pdo->quote($row['ADM_ACCOUNT'], PDO::PARAM_STR); }
  707. $sqlUsers = implode(", ", $sqlUsers);
  708. $sth = $pdo->prepare("
  709. select n.`who`, n.`when`, n.`what`, UNIX_TIMESTAMP(n.last_exec_time) as last_exec_time
  710. from CRM_NOTIFY n
  711. where n.`who` in({$sqlUsers})
  712. and {$sqlWhenFltr}
  713. ");
  714. $sth->execute();
  715. $rawReminders = $sth->fetchAll();
  716. $reminders = array();
  717. $timeToday = mktime(0, 0, 0, date('n'), date('j'), date('Y'));
  718. //$timeTomorrow = mktime(0, 0, 0, date('n'), date('j') + 1, date('Y'));
  719. DBG::_('DBG_NTF', '>1', "rawReminders (today:{$timeToday})", $rawReminders, __CLASS__, __FUNCTION__, __LINE__);
  720. foreach ($rawReminders as $row) {
  721. $user = $row['who'];
  722. $when = $row['when'];
  723. $what = $row['what'];
  724. $last_exec_time = $row['last_exec_time'];
  725. if ('once_a_day' == $when) {
  726. if ($last_exec_time >= $timeToday) {
  727. DBG::_('DBG_NTF', '>1', "skip {$last_exec_time} for {$what} at {$when}", $row, __CLASS__, __FUNCTION__, __LINE__);
  728. continue;
  729. } else {
  730. //DBG::_(true, true, "TODO: else {$last_exec_time} >= {$timeToday}", $row, __CLASS__, __FUNCTION__, __LINE__);
  731. }
  732. } else {
  733. DBG::_('DBG_NTF', '>0', "TODO: unimplemented when = '{$when}'", $row, __CLASS__, __FUNCTION__, __LINE__);
  734. continue;
  735. }
  736. $last_date = ($last_exec_time)? date("Y-m-d H:i:s", $last_exec_time) : null;
  737. if (!isset($reminders[$user])) $reminders[$user] = array();
  738. if (!isset($reminders[$user][$when])) $reminders[$user][$when] = array();
  739. $reminders[$user][$when][$what] = $last_date;
  740. }
  741. return $reminders;
  742. }
  743. public function reinstallAction() {
  744. try {
  745. $force = ('true' == V::get('_force', '', $_GET));
  746. $this->reinstall($force);
  747. } catch (Exception $e) {
  748. echo'<div style="border:1px solid red; background:red; color:#fff;">';
  749. echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
  750. echo'</div>';
  751. }
  752. die('OK');
  753. }
  754. public function reinstallFunctionsAction() {
  755. $this->reinstallFunctions();
  756. die('OK');
  757. }
  758. public function runAction() {
  759. $msgId = V::get('_msgId', 0, $_REQUEST, 'int');
  760. if ($msgId > 0) {
  761. $this->runByMessageId($msgId);
  762. }
  763. $jsonData = new stdClass();
  764. $jsonData->type = 'success';
  765. $jsonData->msg = 'Gotowe';
  766. echo json_encode($jsonData);
  767. exit;
  768. }
  769. public function reinstallFunctions() {
  770. $sqlList = array();
  771. $db = DB::getDB();
  772. if ($db->has_errors()) {
  773. throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  774. }
  775. foreach ($sqlList as $sqlName => $sql) {
  776. $res = $db->query($sql);
  777. if ($db->has_errors()) {
  778. throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
  779. }
  780. }
  781. }
  782. public function testReinstallTable() {
  783. $pdo = DB::getPDO();
  784. if(1){// TEST
  785. $expectedStruct = array();
  786. $expectedStruct['who'] = array('type'=>'varchar', 'max_length'=>20, 'is_nullable'=>false);// `who` varchar(20) -- TODO: NOT NULL
  787. $expectedStruct['when'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `when` varchar(255) NOT NULL
  788. $expectedStruct['what'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `what` varchar(255) NOT NULL
  789. $expectedStruct['last_exec_time'] = array('type'=>'datetime', 'is_nullable'=>true);// `last_exec_time` datetime
  790. $expectedStruct['_created'] = array('type'=>'datetime', 'is_nullable'=>false);// `_created` datetime
  791. $expectedStruct['uniq_key_1'] = array('type'=>'UNIQUE KEY', 'key_fields'=>array('who','when','what'));// UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  792. $expectedStruct['key_who'] = array('type'=>'KEY', 'key_fields'=>array('who'));// KEY `key_who` (`who`)
  793. // $expectedStruct['t1'] = array('type'=>'varchar', 'max_length'=>300, 'default_value'=>null);
  794. // $expectedStruct['t2'] = array('type'=>'int');
  795. // $expectedStruct['t3'] = array('type'=>'int', 'num_precision'=>11, 'default_value'=>null);
  796. // $expectedStruct['t_dec_11_x'] = array('type'=>'decimal', 'num_precision'=>11);
  797. // $expectedStruct['t_dec_11_2'] = array('type'=>'decimal', 'num_precision'=>11, 'num_scale'=>2);
  798. $expectedStruct['t_int'] = array('type'=>'int');
  799. $expectedStruct['t_tinyint'] = array('type'=>'tinyint');
  800. $expectedStruct['t_smallint'] = array('type'=>'smallint');
  801. $expectedStruct['t_mediumint'] = array('type'=>'mediumint');
  802. $expectedStruct['t_bigint'] = array('type'=>'bigint');
  803. $expectedStruct['t_decimal'] = array('type'=>'decimal');
  804. $expectedStruct['t_float'] = array('type'=>'float');
  805. $expectedStruct['t_double'] = array('type'=>'double');
  806. $expectedStruct['t_real'] = array('type'=>'real');
  807. $expectedStruct['t_date'] = array('type'=>'date');
  808. $expectedStruct['t_datetime'] = array('type'=>'datetime');
  809. $expectedStruct['t_timestamp'] = array('type'=>'timestamp');
  810. $expectedStruct['t_time'] = array('type'=>'time');
  811. $expectedStruct['t_year'] = array('type'=>'year');
  812. $expectedStruct['t_char'] = array('type'=>'char');
  813. $expectedStruct['t_varchar'] = array('type'=>'varchar');
  814. $expectedStruct['t_text'] = array('type'=>'text');
  815. $expectedStruct['t_tinytext'] = array('type'=>'tinytext');
  816. $expectedStruct['t_mediumtext'] = array('type'=>'mediumtext');
  817. $expectedStruct['t_longtext'] = array('type'=>'longtext');
  818. $expectedStruct['t_enum'] = array('type'=>'enum', 'values'=>array('v1'));
  819. $expectedStruct['t_set'] = array('type'=>'set', 'values'=>array('v1'));
  820. $expectedStruct['t_bit'] = array('type'=>'bit', 'max_length'=>2);
  821. $expectedStruct['t_boolean'] = array('type'=>'boolean');
  822. $expectedStruct['t_serial'] = array('type'=>'serial');
  823. $expectedStruct['t_binary'] = array('type'=>'binary');
  824. $expectedStruct['t_varbinary'] = array('type'=>'varbinary');
  825. $expectedStruct['t_blob'] = array('type'=>'blob');
  826. $expectedStruct['t_tinyblob'] = array('type'=>'tinyblob');
  827. $expectedStruct['t_mediumblob'] = array('type'=>'mediumblob');
  828. $expectedStruct['t_longblob'] = array('type'=>'longblob');
  829. $expectedStruct['t_geometry'] = array('type'=>'geometry');
  830. $expectedStruct['t_point'] = array('type'=>'point');
  831. $expectedStruct['t_linestring'] = array('type'=>'linestring');
  832. $expectedStruct['t_polygon'] = array('type'=>'polygon');
  833. $expectedStruct['t_multipoint'] = array('type'=>'multipoint');
  834. $expectedStruct['t_multilinestring'] = array('type'=>'multilinestring');
  835. $expectedStruct['t_multipolygon'] = array('type'=>'multipolygon');
  836. $expectedStruct['t_geometrycollection'] = array('type'=>'geometrycollection');
  837. $sqlCreate = $pdo->showCreateStruct('_test_table', $expectedStruct, array('char_encoding'=>'latin2'));
  838. DBG::_(true, true, "fixedEpectedStruct", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
  839. $pdo->assertTableStruct('_test_table', $expectedStruct, array('char_encoding'=>'latin2'));
  840. {// force - drop/create
  841. $pdo->exec("DROP TABLE IF EXISTS _test_table");
  842. $pdo->exec($sqlCreate);
  843. }
  844. }
  845. if(0){// TEST nulls
  846. $sth = $pdo->prepare("DROP TABLE IF EXISTS CRM_NOTIFY");
  847. $sth->execute();
  848. $sth = $pdo->prepare("
  849. CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
  850. `who` varchar(20)
  851. , `when` varchar(255) NOT NULL
  852. , `what` varchar(255) DEFAULT ''
  853. , `t1` varchar(255) NOT NULL -- same as with DEFAULT ''
  854. , `t2` varchar(255) NOT NULL DEFAULT ''
  855. , `t2z` varchar(255) NOT NULL DEFAULT '0'
  856. -- , `t3` varchar(255) NOT NULL DEFAULT NULL -- SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value
  857. , `t4` varchar(255) NULL -- same as with DEFAULT NULL
  858. , `t5` varchar(255) NULL DEFAULT ''
  859. , `t6` varchar(255) NULL DEFAULT NULL
  860. , `i1` int(11) NOT NULL -- same as with DEFAULT 0
  861. , `i2` int(11) NOT NULL DEFAULT 0
  862. -- , `i3` int(11) NOT NULL DEFAULT NULL -- SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value
  863. , `i4` int(11) NULL -- same as with DEFAULT NULL
  864. , `i5` int(11) NULL DEFAULT 0
  865. , `i6` int(11) NULL DEFAULT NULL
  866. , `last_exec_time` datetime DEFAULT NULL
  867. , KEY `who` (`who`)
  868. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  869. ");
  870. $sth->execute();
  871. $sth = $pdo->prepare("insert into CRM_NOTIFY (`last_exec_time`) values (NULL)");
  872. $sth->execute();
  873. // INSERT INTO CRM_NOTIFY (t1, t2, t2z, t4, t5, t6, i1, i2, i4, i5, i6, last_exec_time)
  874. // VALUES ('', '', '0', NULL, '', NULL, 0, 0, NULL, 0, NULL, NULL);
  875. $struct = $pdo->getTableStruct('CRM_NOTIFY');
  876. DBG::_(true, true, "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
  877. DBG::_(true, true, "`t2`: is_null(struct[4]['Default'])=(".is_null($struct[4]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  878. DBG::_(true, true, "`t4`: is_null(struct[6]['Default'])=(".is_null($struct[6]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  879. DBG::_(true, true, "`t5`: is_null(struct[7]['Default'])=(".is_null($struct[7]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  880. DBG::_(true, true, "`t6`: is_null(struct[8]['Default'])=(".is_null($struct[8]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
  881. $expectedStruct = array();
  882. $expectedStruct['t1'] = array('type'=>'varchar', 'max_length'=>300, 'default_value'=>null);
  883. //$expectedStruct['t2'] = array('type'=>'int', 'num_precision'=>11, 'default_value'=>null);
  884. $pdo->assertTableStruct('CRM_NOTIFY', $expectedStruct);
  885. }
  886. }
  887. public function reinstall($force = false) {
  888. $sqlList = array();
  889. $pdo = DB::getPDO();
  890. $sqlCreate = <<<EOF_SQL_CREATE
  891. CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
  892. `who` varchar(20) NOT NULL
  893. , `when` varchar(255) NOT NULL
  894. , `what` varchar(255) NOT NULL
  895. , `last_exec_time` datetime DEFAULT NULL
  896. , `_created` datetime NOT NULL
  897. , UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  898. , KEY `key_who` (`who`)
  899. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  900. EOF_SQL_CREATE;
  901. /*
  902. `CRM_NOTIFY`:
  903. - who - user login
  904. - when - shedule (once a day, once on houd)
  905. - what - action type
  906. - last_exec_time
  907. */
  908. if($force){
  909. $pdo->exec("DROP TABLE IF EXISTS CRM_NOTIFY");
  910. $pdo->exec("
  911. CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
  912. `who` varchar(20) NOT NULL
  913. , `when` varchar(255) NOT NULL
  914. , `what` varchar(255) NOT NULL DEFAULT ''
  915. , `last_exec_time` datetime
  916. , KEY `key_who` (`who`)
  917. , UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  918. ) ENGINE=MyISAM DEFAULT CHARSET=latin2
  919. ");
  920. }
  921. {// assertTableStruct CRM_NOTIFY
  922. $expectedStruct = array();
  923. $expectedStruct['who'] = array('type'=>'varchar', 'max_length'=>20, 'is_nullable'=>false);// `who` varchar(20) -- TODO: NOT NULL
  924. $expectedStruct['when'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `when` varchar(255) NOT NULL
  925. $expectedStruct['what'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `what` varchar(255) NOT NULL
  926. $expectedStruct['last_exec_time'] = array('type'=>'datetime', 'is_nullable'=>true);// `last_exec_time` datetime
  927. $expectedStruct['_created'] = array('type'=>'datetime', 'is_nullable'=>false);// `_created` datetime
  928. $expectedStruct['uniq_key_1'] = array('type'=>'UNIQUE KEY', 'key_fields'=>array('who','when','what'));// UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
  929. $expectedStruct['key_who'] = array('type'=>'KEY', 'key_fields'=>array('who'));// KEY `key_who` (`who`)
  930. DBG::_(true, true, "sqlCreate - raw", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
  931. $sqlCreate = $pdo->showCreateStruct('CRM_NOTIFY', $expectedStruct, array('char_encoding'=>'latin2'));
  932. DBG::_(true, true, "sqlCreate - generated", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
  933. $pdo->assertTableStruct('CRM_NOTIFY', $expectedStruct, array('char_encoding'=>'latin2'));
  934. if(0){// force - drop/create
  935. $pdo->exec("DROP TABLE IF EXISTS CRM_NOTIFY");
  936. $pdo->exec($sqlCreate);
  937. }
  938. }
  939. {// assertTableStruct CRM_NOTIFY_EXEC_LOG
  940. // TODO: create table CRM_NOTIFY_EXEC_LOG with action log
  941. }
  942. //$this->reinstallFunctions();
  943. }
  944. }