Notify.php 46 KB

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