Notify.php 39 KB

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