Notify.php 45 KB

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