| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141 |
- <?php
- // @requires $_SERVER['SERVER_NAME']
- Lib::loadClass('RouteBase');
- Lib::loadClass('Przypomnij');
- Lib::loadClass('Request');
- Lib::loadClass('TypespecialVariable');
- Lib::loadClass('Route_UserMsgs');
- /*
- # Nofitication System:
- ## INSTALL - Nofitication System: index.php?_route=Notify&_task=reinstall&_force=true
- Sends mail by settings `CRM_NOTIFY`:
- - who - user login
- - when - shedule (once a day, once on houd)
- - what - action type
- - last_exec_time
- TODO: add after_action for Msgs to user/group
- TODO: add after_action for Tasks with special params:
- - Owner - notify after Worker change satus (100% done)
- - Worker - notify after Owner set him as a Worker to task
- */
- class Route_Notify extends RouteBase {
- public function handleAuth() {
- if (!User::logged()) {
- User::authByRequest();
- }
- }
- public function defaultAction() {
- SE_Layout::gora();
- SE_Layout::menu();
- try {
- $usrLogin = User::getLogin();
- $this->formUserTableReminder($usrLogin);
- } catch (Exception $e) {
- SE_Layout::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- SE_Layout::dol();
- }
- public function remindersPanelAction() {
- $usrLogin = User::getLogin();
- SE_Layout::gora();
- //SE_Layout::menu();
- {// init args
- $usrLogin = User::getLogin();
- $usrLogin = (isset($_REQUEST['usrLogin']))? V::get('usrLogin', '', $_REQUEST, 'login') : $usrLogin;
- if (!$usrLogin) die("Wrong user login!");
- $notifyTypeList = V::get('reminder', array(), $_REQUEST, 'array');
- if (!$notifyTypeList) {
- $userNotifyList = $this->getUserNotifyList($usrLogin);
- if (empty($userNotifyList)) die("Brak zdefiniowanych powiadomień");
- foreach ($userNotifyList as $notify) { $notifyTypeList[] = $notify['what']; }
- }
- }
- if ('1' == V::get('send', 0, $_POST, 'int')) {
- SE_Layout::alert('warning', "TODO: fix send, mark as sent");
- //$this->send($usrLogin, $notifyTypeList);
- //$this->markAsSent($usrLogin, $notifyTypeList);
- }
- $urlParts = array();// index.php?_route=Notify&_task=generateUserReminders&usrLogin=magdalena.cichosz&reminder[]=msgs
- $urlQuery = array('_route' => "Notify"
- , '_task' => 'generateUserReminders'
- , 'usrLogin' => $usrLogin
- , 'reminder' => array_values($notifyTypeList));
- $previewLink = Request::getUriDirName() . "/index.php?" . http_build_query($urlQuery);
- $lastSentDate = 'brak';// TODO: getLastSendData($usrLogin);
- $typeSpecialUserLogin = TypespecialVariable::getInstance(-1, '__USER_LOGIN');
- ?>
- <div class="jumbotron">
- <div class="container">
- <form id="reminderPanelForm" class="form-horizontal" method="POST">
- <div class="form-group">
- <label class="col-sm-2 control-label">User</label>
- <div class="col-sm-10">
- <?php if ($typeSpecialUserLogin) : ?>
- <?php
- $fldName = 'usrLogin';
- $fldParams = array();
- $fldParams['allowCreate'] = false;
- $fldParams['ajaxDataUrlBase'] = "index.php?_route=Notify&_task=typeSpecialUserLogin";
- $fldParams['placeholder'] = 'Szukaj...';
- //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
- echo $typeSpecialUserLogin->showFormItem($tblID = -1, $fldName, $usrLogin, $fldParams);
- ?>
- <?php else : ?>
- <input class="form-control" type="text" name="usrLogin" value="<?php echo $usrLogin; ?>">
- <?php endif; ?>
- </div>
- </div>
- <?php foreach ($this->getFieldValueLabels('what') as $reminderType => $reminderLabel) : ?>
- <?php if ('l_app_all_przypomnij' == $reminderType) continue; ?>
- <div class="col-sm-3">
- <div class="checkbox">
- <label>
- <input type="checkbox"
- name="reminder[]"
- <?php if (in_array($reminderType, $notifyTypeList)) : ?>
- checked="checked"
- <?php endif; ?>
- value="<?php echo $reminderType; ?>"> <?php echo $reminderLabel; ?>
- </label>
- </div>
- </div>
- <?php endforeach; ?>
- <div class="col-sm-offset-2 col-sm-10" style="margin-top:10px;padding-top:10px;border-top:1px solid silver;">
- <button class="btn btn-default" onclick="refreshPreview(); return false;">odśwież podgląd</button>
- <button class="btn btn-primary" name="send" value="1">wyślij maila</button>
- data wysłania ostatniej wiadomości do wybranego użytkownika: <?php echo $lastSentDate; ?>
- </div>
- </form>
- </div>
- </div>
- <script>
- function refreshPreview() {
- var frm = document.getElementById('reminderPanelForm'),
- baseUrl = '<?php echo Request::getUriDirName(); ?>',
- previewLink = '';
- previewLink = baseUrl + '/index.php?_route=Notify&_task=generateUserReminders';
- previewLink += '&usrLogin=' + frm['usrLogin'].value;
- for (var i in frm['reminder[]']) {
- console.log('frm[reminder[]]['+i+']', frm['reminder[]'][i].value, ' checked:', frm['reminder[]'][i].checked);
- if (frm['reminder[]'][i].checked) {
- previewLink += '&reminder[]=' + frm['reminder[]'][i].value;
- }
- }
- console.log('frm[reminder[]].', frm['reminder[]']);
- console.log('frm[reminder[]].value', frm['reminder[]'].value);
- console.log('previewLink:', previewLink);
- document.getElementById('reminderPreview').src = previewLink;
- }
- </script>
- <div>
- <iframe id="reminderPreview" src="<?php echo $previewLink; ?>" style="width:100%;height:500px;max-height:500px;overflow:scroll;border:2px solid silver"></iframe>
- </div>
- <?php
- SE_Layout::dol();
- }
- public function typeSpecialUserLoginAction() {
- header("Content-type: application/json");
- $typeSpecialUserId = TypespecialVariable::getInstance(-1, '__USER_LOGIN');
- if (!$typeSpecialUserId) {
- $jsonData = new stdClass();
- $jsonData->message = "TypeSpecial '__USER_LOGIN' not exists";
- echo json_encode($jsonData);
- exit;
- }
- $query = V::get('q', '', $_REQUEST);
- $rawRows = null;
- $jsonData = array();
- $queryParams = array();
- $rows = $typeSpecialUserId->getValuesWithExports($query, $queryParams);
- foreach ($rows as $kID => $vItem) {
- $itemJson = new stdClass();
- $itemJson->id = $vItem->id;
- $itemJson->name = $vItem->param_out;
- if (!empty($vItem->exports)) {
- $itemJson->exports = $vItem->exports;
- }
- $jsonData[] = $itemJson;
- }
- echo json_encode($jsonData);
- }
- /**
- * @param $userReminders {'once_a_day' => {$type => $last_exec_time}, 'immediately' => {$type => $last_exec_time}}
- */
- public function sendUserReminders($who, $userReminders, $forceMail = null) {
- DBG::_('DBG_NTF', '>1', "reminders.1", $userReminders, __CLASS__, __FUNCTION__, __LINE__);
- // remove duplicates
- if (!empty($userReminders['once_a_day']) && !empty($userReminders['immediately'])) {
- foreach ($userReminders['once_a_day'] as $what => $last_exec) {
- if (array_key_exists($what, $userReminders['immediately'])) {
- DBG::_('DBG_NTF', '>2', "skip immediately '{$what}' for '{$who}'", $userReminders['immediately'][$what], __CLASS__, __FUNCTION__, __LINE__);
- unset($userReminders['immediately'][$what]);
- }
- }
- if (empty($userReminders['immediately'])) unset($userReminders['immediately']);
- }
- DBG::_('DBG_NTF', '>1', "reminders.2", $userReminders, __CLASS__, __FUNCTION__, __LINE__);
- foreach ($userReminders as $when => $listWhat) {
- if (!empty($listWhat)) {
- $reminders = array_keys($listWhat);
- echo "<p>Sending to {$who} reminders [" . implode(",", $reminders) . "] at '{$when}'</p>" . "\n";
- $this->send($who, $listWhat, $when, $forceMail);
- $this->markAsSent($who, $listWhat, $when);
- }
- }
- }
- /**
- * @param $reminders array( )
- * @param $when 'once_a_day', 'immediately'
- */
- public function send($usrLogin, $reminders, $when = null, $forceMail = null) {
- DBG::_('DBG_NTF', '>1', "usrLogin", $usrLogin, __CLASS__, __FUNCTION__, __LINE__);
- DBG::_('DBG_NTF', '>1', "reminders(when: {$when})", $reminders, __CLASS__, __FUNCTION__, __LINE__);
- $mainMail = $this->getUserMainMail($usrLogin);
- $msgNote = '';
- if (!empty($forceMail)) {
- $mainMail = $forceMail;
- if (empty($user['aliasy'])) $msgNote .= 'ERROR: Brak lokalnego adresu email' . "\n\n";
- }
- $pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i";
- if (!preg_match($pattern, $mainMail)) throw new Exception("Adres email ma błędny format");
- $usrReminders = $this->getUserReminders($usrLogin, $reminders, $when);
- if (empty($usrReminders)) {
- DBG::_('DBG_NTF', '>0', "Skip usr({$usrLogin}) - no remindres", $usrReminders, __CLASS__, __FUNCTION__, __LINE__);
- return;
- }
- $to = $mainMail;
- $headers = "From: " . "noreply@{$_SERVER['SERVER_NAME']}" . "\r\n";
- $headers .= "MIME-Version: 1.0\r\n";
- $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
- if (null == $when || 'once_a_day' == $when) {
- $subject = "Powiadomienia dla {$usrLogin} - " . date("Y-m-d") . " - {$_SERVER['SERVER_NAME']}";
- } else {
- $subject = "Nowe powiadomienia dla {$usrLogin} - {$_SERVER['SERVER_NAME']}";
- }
- ob_start();
- $this->viewUserReminders($usrReminders, $usrLogin);
- echo "\n\n<br><br>\nWiadomość została wygenerowana automatycznie." . "\n\n";
- {
- $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE";
- if ('biuro.biall-net.pl' == $_SERVER['SERVER_NAME']) $baseUrl = "https://{$_SERVER['SERVER_NAME']}/SE/version-git";
- $notifyLink = "{$baseUrl}/index.php?_route=Notify";
- echo "<br><br>\nPowiadomienia można ustawić na: <a href=\"{$notifyLink}\">{$notifyLink}</a>." . "\n\n";
- }
- $message = ob_get_clean();
- trigger_error("send msg to {$to} ({$usrLogin}) when='{$when}'", E_USER_NOTICE);
- if (!mail($to, $subject, $message, $headers)) {
- trigger_error("Cannot send msg to {$to} ({$usrLogin}) when='{$when}'", E_USER_WARNING);
- throw new Exception("Nie udało się wysłać powiadomienia");
- }
- }
- public function getUserMainMail($usrLogin) {
- $user = null;
- $sth = DB::getPDO()->prepare("
- select u.ID, u.ADM_ACCOUNT as login, u.EMAIL_LOCAL_ACCOUNT_ADDRESS as aliasy
- from ADMIN_USERS u
- where u.ADM_ACCOUNT = :usr_login
- ");
- $sth->bindValue(':usr_login', $usrLogin, PDO::PARAM_STR);
- $sth->execute();
- $user = $sth->fetch();
- if (!$user) throw new Exception("User not found");
- if (empty($user['aliasy'])) throw new Exception("Brak lokalnego adresu email");
- $aliasy = explode(' ', trim($user['aliasy']));
- return reset($aliasy);
- }
- public function markAsSent($usrLogin, $reminders, $when) {
- // $sqlReminderTypes = "'" . implode("','", $notifyTypeList) . "'";
- $sqlReminderTypes = "'" . implode("','", array_keys($reminders)) . "'";
- $sth = DB::getPDO()->prepare("
- update CRM_NOTIFY
- set `last_exec_time` = NOW()
- where `who` = :login
- and `when` = :when
- and `what` in({$sqlReminderTypes})
- ");
- $sth->bindValue(':login', $usrLogin, PDO::PARAM_STR);
- $sth->bindValue(':when', $when, PDO::PARAM_STR);
- $sth->execute();
- }
- public function generateUserRemindersAction() {
- $usrLogin = User::getLogin();
- $usrLogin = (isset($_GET['usrLogin']))? V::get('usrLogin', '', $_GET, 'login') : $usrLogin;
- if (!$usrLogin) die("Wrong user login!");
- $notifyTypeList = V::get('reminder', array(), $_GET, 'array');
- if (!$notifyTypeList) {
- $userNotifyList = $this->getUserNotifyList($usrLogin);
- if (empty($userNotifyList)) die("Brak zdefiniowanych powiadomień");
- foreach ($userNotifyList as $notify) { $notifyTypeList[] = $notify['what']; }
- }
- header('Content-Type: text/html; charset="UTF-8"');
- $usrReminders = $this->getAllUserReminders($usrLogin, $notifyTypeList);
- $this->viewUserReminders($usrReminders, $usrLogin);
- }
- /**
- * @param $reminders - array( $notifyType )
- */
- public function getAllUserReminders($usrLogin, $notifyTypeList) {
- $usrReminders = array();
- foreach ($notifyTypeList as $notifyType) {
- $listTodo = $this->getTodoForUserReminder($usrLogin, $notifyType);
- if (!empty($listTodo)) $usrReminders[$notifyType] = $listTodo;
- }
- return $usrReminders;
- }
- /**
- * @param $reminders - array( $notifyType => $lastExecTime )
- */
- public function getUserReminders($usrLogin, $reminders, $when = null) {
- $usrReminders = array();
- foreach ($reminders as $notifyType => $lastExecTime) {
- $fetchFromTime = (null == $when || 'once_a_day' == $when)? null : $lastExecTime;
- $listTodo = $this->getTodoForUserReminder($usrLogin, $notifyType, $fetchFromTime);
- if (!empty($listTodo)) $usrReminders[$notifyType] = $listTodo;
- }
- return $usrReminders;
- }
- public function viewUserReminders($usrReminders, $usrLogin) {
- echo '<html>';
- echo '<body>';
- echo '<div>';
- ?>
- <h1 style="<?php echo $this->inlineCss('h1'); ?>">Powiadomienia dla <code><?php echo $usrLogin; ?></code></h1>
- <?php foreach ($usrReminders as $reminderType => $listTodo) : ?>
- <div style="<?php echo $this->inlineCss('header'); ?>"><strong><?php echo $this->printValue('what', $reminderType); ?></strong></div>
- <table rules="all" cellspacing="0" style="border-color:#bbb;" cellpadding="8">
- <?php $lp = 0; foreach ($listTodo as $todo) : ?>
- <tr>
- <td style="<?php echo $this->inlineCss('td.lp'); ?>"><?php echo ++$lp; ?></td>
- <td style="<?php echo $this->inlineCss('td.' . $todo['_l_app_class']); ?>">
- <span style="<?php echo $this->inlineCss('l_app_date.' . $todo['_l_app_class']); ?>"><?php echo $todo['_l_app_date']; ?></span>
- <br><i style="<?php echo $this->inlineCss('l_app.target'); ?>"><?php echo $todo['_l_app']; ?></i>
- <?php if (V::get('ID', '', $todo) > 0) : ?>
- <br><a href="<?php echo $this->editLink($todo); ?>" target="_blank" style="<?php echo $this->inlineCss('a'); ?>">Edytuj rekord <?php echo $todo['ID']; ?></a>
- <?php elseif (V::get('idMsg', '', $todo) > 0) : ?>
- <br><a href="<?php echo $this->readMsgLink($usrLogin, $todo); ?>" target="_blank" style="<?php echo $this->inlineCss('a'); ?>">Przeczytaj</a>
- <?php endif; ?>
- </td>
- <td style="<?php echo $this->inlineCss('td.info'); ?>"><?php echo $todo['L_APPOITMENT_INFO']; ?></td>
- <td style="<?php echo $this->inlineCss('td.record-info'); ?>">
- <?php echo $todo['_title']; ?>
- </td>
- <?php if (V::get('DBG', '', $_GET)) : ?>
- <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>
- <?php endif; ?>
- </tr>
- <?php endforeach; ?>
- </table>
- <?php endforeach; ?>
- <?php
- echo '</div>';// .container
- echo '</body>';
- echo '</html>';
- }
- public function editLink($todo) {
- $idTblZasob = 0;
- $idRecord = 0;
- if ('zasob' == $todo['_task_type']
- || 'proces' == $todo['_task_type']
- || 'projekt' == $todo['_task_type']
- || 'koresp' == $todo['_task_type']
- || 'task' == $todo['_task_type']
- ) {
- $idTblZasob = $todo['_idZasobTable'];
- $idRecord = $todo['ID'];
- }
- if (!$idTblZasob || !$idRecord) return '#';
- $urlQuery = array('MENU_INIT' => "VIEWTABLE_AJAX"
- , 'ZASOB_ID' => $idTblZasob);
- return Request::getUriDirName() . "/index.php?" . http_build_query($urlQuery) . "#EDIT/{$idRecord}";
- }
- public function readMsgLink($usrLogin, $todo) {
- $idMsg = 0;
- if ('msg' == $todo['_task_type']) {
- $idMsg = $todo['idMsg'];
- }
- if (!$idMsg) return '#' . json_encode($todo);
- if (!$idMsg) return '#';
- $urlQuery = array('_route' => "UserMsgs"
- , '_task' => 'read'
- , 'usrLogin' => $usrLogin
- , 'id' => $idMsg);
- return Request::getUriDirName() . "/index.php?" . http_build_query($urlQuery);
- }
- public function inlineCss($cssSelector) {
- $baseCss = array();
- $baseCss['font-family'] = 'Arial, Helvetica, sans-serif';
- $baseCss['font-size'] = 'small';
- $baseCss['color'] = '#333';
- $customCss = array(
- 'h1' => array(),
- 'header' => array('background' => '#eee', 'padding' => '4px 10px', 'margin-top' => '6px'),
- 'l_app.target' => array('color' => '#999', 'white-space' => 'nowrap'),
- 'td.date-base' => array('white-space' => 'nowrap'),
- 'td.lp' => array('color' => 'silver'),
- 'l_app_date-base' => array('white-space' => 'nowrap'),
- 'a' => array('color' => '#337ab7', 'text-decoration' => 'none')
- );
- $css = $baseCss;
- if (array_key_exists($cssSelector, $customCss)) $css = V::extend($css, $customCss[$cssSelector]);
- if ('td.date-' == substr($cssSelector, 0, 8)) {
- $css = V::extend($css, $customCss['td.date-base']);
- $css = V::extend($css, array('color' => $this->getTodoDateCssColor(substr($cssSelector, 3))));
- }
- if ('l_app_date.date-' == substr($cssSelector, 0, 16)) {
- $css = V::extend($css, $customCss['l_app_date-base']);
- $css = V::extend($css, array('color' => $this->getTodoDateCssColor(substr($cssSelector, 11))));
- }
- $inlineCss = array();
- foreach ($css as $cssPropName => $cssValue) {
- if (true === $cssValue) {
- if (!array_key_exists($cssPropName, $baseCss)) continue;
- $cssValue = $baseCss[$cssPropName];
- }
- $inlineCss[] = "{$cssPropName}:{$cssValue}";
- }
- return implode(";", $inlineCss);
- }
- public function getTodoDateCssColor($lAppClass) {
- $color = '#000';
- switch ($lAppClass) {
- case 'date-PO_TERMINIE': $color = '#FD4242'; break;
- case 'date-DZISIAJ': $color = '#34B934'; break;
- case 'date-W_CIAGU_7_DNI': $color = '#C58B1F'; break;
- case 'date-PO_7_DNIACH': $color = '#87847D'; break;
- }
- return $color;
- }
- public function getTodoForUserReminder($usrLogin, $reminderWhat, $lastExecTime = null) {
- $listTodo = array();
- if ('msgs' == $reminderWhat) {
- $routeMsgs = Router::getRoute('UserMsgs');
- $routeMsgs->_listLimit = 50;
- $msgs = $routeMsgs->getMsgs('unread', $usrLogin, $lastMsgId = null, $lastExecTime);
- foreach ($msgs as $idMsg => $msg) {
- $todo = array();
- $todo['_task_type'] = 'msg';
- // [userTargetType] => group
- // [userTargetName] => 2948
- $todo['_l_app'] = '';
- if ('group' == $msg['_raw']->userTargetType) {
- $todo['_l_app'] = "do grupy {$msg['_raw']->userTargetName}";
- } else if ('user' == $msg['_raw']->userTargetType) {
- $todo['_l_app'] = "do {$msg['_raw']->userTargetName}";
- }
- $todo['idMsg'] = $idMsg;
- $todo['_l_app_date'] = substr($msg['_raw']->A_RECORD_CREATE_DATE, 0, 10);
- $todo['_l_app_class'] = 'date-PO_TERMINIE';
- $todo['L_APPOITMENT_INFO'] = $msg['message'];
- // $msg['_raw']->A_STATUS == 'WAITING' => Unread
- // $msg['_raw']->A_STATUS == 'NORMAL' => Read
- // $msg['_raw']->A_STATUS == 'OFF_SOFT' => Trash
- $msgInfo = '<i style="color:silver">' . "Wysłane {$msg['_raw']->A_RECORD_CREATE_DATE} przez {$msg['_raw']->A_RECORD_CREATE_AUTHOR}" . '</i>';
- 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>';
- $todo['_title'] = $msgInfo;
- $listTodo[] = $todo;
- }
- }
- else if ('l_app_projekty' == $reminderWhat) {
- $tasks = $this->getPrzypomnijTasks($usrLogin);
- foreach ($tasks as $task) {
- if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
- if ('projekt' != $task['_task_type']) continue;
- //$task['DESC'] = $task['A_PROBLEM_DESC'];
- if (!$this->filterTaskByTime($task, $lastExecTime)) continue;
- $listTodo[] = $task;
- }
- }
- else if ('l_app_koresp' == $reminderWhat) {
- $tasks = $this->getPrzypomnijTasks($usrLogin);
- foreach ($tasks as $task) {
- if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
- if ('koresp' != $task['_task_type']) continue;
- //$task['DESC'] = $task['A_PROBLEM_DESC'];
- if (!$this->filterTaskByTime($task, $lastExecTime)) continue;
- $listTodo[] = $task;
- }
- }
- else if ('l_app_zadania' == $reminderWhat) {
- $tasks = $this->getPrzypomnijTasks($usrLogin);
- foreach ($tasks as $task) {
- if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
- if ('task' != $task['_task_type']) continue;
- //$task['DESC'] = $task['A_PROBLEM_DESC'];
- if (!$this->filterTaskByTime($task, $lastExecTime)) continue;
- $listTodo[] = $task;
- }
- }
- else if ('l_app_procesy' == $reminderWhat) {
- $tasks = $this->getPrzypomnijTasks($usrLogin);
- foreach ($tasks as $task) {
- if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
- if ('proces' != $task['_task_type']) continue;
- if (!$this->filterTaskByTime($task, $lastExecTime)) continue;
- $listTodo[] = $task;
- }
- }
- else if ('l_app_zasoby' == $reminderWhat) {
- $tasks = $this->getPrzypomnijTasks($usrLogin);
- foreach ($tasks as $task) {
- if (empty($task['_l_app_date']) || '0000-00-00' == $task['_l_app_date']) continue;
- if ('zasob' != $task['_task_type']) continue;
- if (!$this->filterTaskByTime($task, $lastExecTime)) continue;
- $listTodo[] = $task;
- }
- }
- return $listTodo;
- }
- public function filterTaskByTime($task, $lastExecTime) {
- if (null == $lastExecTime) return true;
- if (empty($task['A_RECORD_CREATE_DATE'])) return true;
- if ($task['A_RECORD_CREATE_DATE'] >= $lastExecTime) return true;
- if (empty($task['A_RECORD_UPDATE_DATE'])) {
- DBG::_('DBG_NTF', '>1', "skip task by lastExecTime({$lastExecTime}) - empty update date", $task, __CLASS__, __FUNCTION__, __LINE__);
- return false;
- } else if ($task['A_RECORD_UPDATE_DATE'] < $lastExecTime) {
- DBG::_('DBG_NTF', '>1', "skip task by lastExecTime({$lastExecTime}) - old update date", $task, __CLASS__, __FUNCTION__, __LINE__);
- return false;
- }
- return true;
- }
- public function getPrzypomnijTasks($usrLogin) {
- static $_tasks = array();
- if (empty($_tasks[$usrLogin])) {
- $_tasks[$usrLogin] = array();
- $przypomnij = new Przypomnij();
- $przypomnij->setRecurseLimit(3);
- $przypomnij->fetchData($usrLogin);
- $przypomnij->setFltrUser($usrLogin);
- $tasks = $przypomnij->getTasksByDate();
- {
- $usrGroupNames = array();
- //$usrGroupNames = User::getLdapGroupsNames();
- Lib::loadClass('UsersLdapHelper');
- $ldapGroups = UsersLdapHelper::getUserGroups($usrLogin, 3);
- foreach ($ldapGroups as $kID => $vLDAPGroup) {
- $usrGroupNames[$kID] = $vLDAPGroup->cn;
- }
- }
- foreach ($tasks as $task) {
- if (!$task->_show) continue;
- if (
- $task->A_CLASSIFIED != ''
- and !(in_array($task->A_CLASSIFIED, $usrGroupNames))
- and $task->A_ADM_COMPANY != ''
- and !(in_array($task->A_ADM_COMPANY, $usrGroupNames))
- // !($allowedUsers[$task->_l_app]) - to jest bez sensu - wystarczy widocznosc sprawy?
- ) {
- continue;
- }
- $task->_l_app_class = $przypomnij->getTaskDateFltrType($task->_l_app_date);
- $task->_idZasobTable = $przypomnij->getZasobIdByType($task->_task_type);
- $_tasks[$usrLogin][] = (array)$task;
- }
- }
- return $_tasks[$usrLogin];
- }
- public function removeUserTableReminder($args) {
- $usrLogin = User::getLogin();
- $who = V::validate('who', $args, array('type'=>'word', 'equal'=>$usrLogin, 'error_msg_equal'=>"Brak uprawnień do wprowadzania zmian w powiadomieniach innych użytwkoników"));
- $what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$this->getFieldValues('what')));
- $when = V::validate('when', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$this->getFieldValues('when')));
- if ($usrLogin != $who) throw new Exception("Brak uprawnień do wprowadzania zmian w powiadomieniach innych użytwkoników");
- $pdo = DB::getPDO();
- $sth = $pdo->prepare("
- delete from `CRM_NOTIFY`
- where `who` = :who
- and `what` = :what
- and `when` = :when
- ");
- $sth->bindValue(':who', $usrLogin, PDO::PARAM_STR);
- $sth->bindValue(':what', $what, PDO::PARAM_STR);
- $sth->bindValue(':when', $when, PDO::PARAM_STR);
- $sth->execute();
- }
- public function formUserTableReminder($usrLogin) {
- echo '<div class="container">';
- $subTask = V::get('_subTask', '', $_POST);
- if ('_add_table_reminder' == $subTask) {
- try {
- $this->addUserTableReminder($usrLogin, $_POST);
- SE_Layout::alert('info', "Dodano powiadomienie");
- } catch (PDOException $e) {
- if (!empty($e->errorInfo) && !empty($e->errorInfo[1]) && '1062' == $e->errorInfo[1]) {
- SE_Layout::alert('warning', "Powiadomienie tego typu zostało już wcześniej dodane");
- } else {
- SE_Layout::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage() . '<br>' . "Info: " . json_encode($e->errorInfo));
- }
- } catch (Exception $e) {
- SE_Layout::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- }
- else if ('_rm_table_reminder' == $subTask) {
- try {
- $this->removeUserTableReminder($_POST);
- SE_Layout::alert('info', "Usunięto powiadomienie");
- } catch (Exception $e) {
- SE_Layout::alert('danger', "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage());
- }
- }
- $userNotifyList = $this->getUserNotifyList($usrLogin);
- $userMail = $this->getUserMainMail($usrLogin);
- $whatLabelsForOnceADay = $this->getFieldValueLabels('what', $userNotifyList, $when = 'once_a_day');
- $whatLabelsForImmediately = $this->getFieldValueLabels('what', $userNotifyList, $when = 'immediately');
- ?>
- <h1>Powiadomienia dla <code><?php echo $usrLogin; ?></code></h1>
- <p><i>Będą wysyłane na adres: <?php echo $userMail; ?></i></p>
- <?php if (empty($userNotifyList)) : ?>
- <?php SE_Layout::alert('warning', "Brak zdefiniowanych powiadomień"); ?>
- <?php else : ?>
- <table class="table table-hovered">
- <thead>
- <tr>
- <th>rodzaj</th>
- <th>jak często</th>
- <th>utworzony</th>
- <th>ostatnio uruchomiony</th>
- <th></th>
- </tr>
- </thead>
- <tbody>
- <?php foreach ($userNotifyList as $notify) : ?>
- <tr>
- <td><?php echo $this->printValue('what', $notify['what']); ?></td>
- <td><?php echo $this->printValue('when', $notify['when']); ?></td>
- <td><?php echo $notify['_created']; ?></td>
- <td><?php echo ($notify['last_exec_time'])? $notify['last_exec_time'] : '<i>brak danych</i>'; ?></td>
- <td>
- <form method="post" class="form-inline">
- <input type="hidden" name="_subTask" value="_rm_table_reminder">
- <input type="hidden" name="who" value="<?php echo $usrLogin; ?>">
- <input type="hidden" name="what" value="<?php echo $notify['what']; ?>">
- <input type="hidden" name="when" value="<?php echo $notify['when']; ?>">
- <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>
- </form>
- </td>
- </tr>
- <?php endforeach; ?>
- </tbody>
- </table>
- <?php endif; ?>
- <?php if (!empty($whatLabelsForOnceADay)) : ?>
- <hr>
- <h4>Dodaj powiadomienia wysyłane raz dziennie:</h4>
- <form method="post" class="form-inline">
- <input type="hidden" name="_subTask" value="_add_table_reminder">
- <input type="hidden" name="when" value="once_a_day">
- <label>rodzaj:</label>
- <select type="select" name="what" class="form-control">
- <option value="">[ Wybierz ]</option>
- <?php foreach ($whatLabelsForOnceADay as $value => $label) : ?>
- <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
- <?php endforeach; ?>
- </select>
- <input type="submit" value="Dodaj" class="btn btn-primary">
- </form>
- <?php endif; ?>
- <?php if (!empty($whatLabelsForImmediately)) : ?>
- <hr>
- <h4>Dodaj powiadomienia wysyłane na bieżąco:</h4>
- <form method="post" class="form-inline">
- <input type="hidden" name="_subTask" value="_add_table_reminder">
- <input type="hidden" name="when" value="immediately">
- <label>rodzaj:</label>
- <select type="select" name="what" class="form-control">
- <option value="">[ Wybierz ]</option>
- <?php foreach ($whatLabelsForImmediately as $value => $label) : ?>
- <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
- <?php endforeach; ?>
- </select>
- <input type="submit" value="Dodaj" class="btn btn-primary">
- </form>
- <?php endif; ?>
- <?php
- echo '</div>';// .container
- }
- public function printValue($fldName, $argValue) {
- if ('what' == $fldName || 'when' == $fldName) {
- $valueLabels = $this->getFieldValueLabels($fldName);
- return V::get($argValue, $argValue, $valueLabels);
- }
- return $argValue;
- }
- public function getAllPrzypomnijTypes() {
- $allPrzypomnijTypes = array();
- $allPrzypomnijTypes[] = 'msgs';
- $allPrzypomnijTypes[] = 'l_app_projekty';
- $allPrzypomnijTypes[] = 'l_app_koresp';
- $allPrzypomnijTypes[] = 'l_app_zadania';
- $allPrzypomnijTypes[] = 'l_app_procesy';
- $allPrzypomnijTypes[] = 'l_app_zasoby';
- return $allPrzypomnijTypes;
- }
- public function getFieldValueLabels($fldName, $userNotifyList = null, $when = null) {
- $valueLabels = array();
- if ('what' == $fldName) {
- if (null == $userNotifyList) $userNotifyList = array();
- if ('once_a_day' == $when) {
- $valueLabels['msgs'] = "wiadomości";
- $valueLabels['l_app_projekty'] = "projekty";
- $valueLabels['l_app_koresp'] = "korespondencja";
- $valueLabels['l_app_zadania'] = "zadania";
- $valueLabels['l_app_procesy'] = "procesy";
- $valueLabels['l_app_zasoby'] = "zasoby";
- $valueLabels['l_app_all_przypomnij'] = "*wszystkie";
- if (!empty($userNotifyList)) {// filter out existing notify
- foreach ($userNotifyList as $notify) {
- if ($when == $notify['when'] && array_key_exists($notify['what'], $valueLabels)) {
- unset($valueLabels[$notify['what']]);
- }
- }
- if (1 == count($valueLabels) && !empty($valueLabels['l_app_all_przypomnij'])) {
- unset($valueLabels['l_app_all_przypomnij']);
- }
- }
- } else if ('immediately' == $when) {
- $valueLabels['msgs'] = "wiadomości";
- $valueLabels['l_app_zadania'] = "zadania";
- if (!empty($userNotifyList)) {// filter out existing notify
- foreach ($userNotifyList as $notify) {
- if ($when == $notify['when'] && array_key_exists($notify['what'], $valueLabels)) {
- unset($valueLabels[$notify['what']]);
- }
- }
- }
- } else {
- $valueLabels['msgs'] = "wiadomości";
- $valueLabels['l_app_projekty'] = "projekty";
- $valueLabels['l_app_koresp'] = "korespondencja";
- $valueLabels['l_app_zadania'] = "zadania";
- $valueLabels['l_app_procesy'] = "procesy";
- $valueLabels['l_app_zasoby'] = "zasoby";
- $valueLabels['l_app_all_przypomnij'] = "*wszystkie";
- }
- } else if ('when' == $fldName) {
- $valueLabels['once_a_day'] = "Raz dziennie";
- $valueLabels['immediately'] = "Na bieżąco";
- }
- return $valueLabels;
- }
- public function getFieldValues($fldName) {
- $valueLabels = $this->getFieldValueLabels($fldName);
- return array_keys($valueLabels);
- }
- public function addUserTableReminder($usrLogin, $args) {
- $what_values = $this->getFieldValues('what');
- $what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$what_values));
- $when_values = $this->getFieldValues('when');
- $when = V::validate('when', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$when_values));
- $pdo = DB::getPDO();
- if ('l_app_all_przypomnij' == $what) {
- $types = $this->getAllPrzypomnijTypes();
- $sqlValues = array();
- $sqlWho = $pdo->quote($usrLogin, PDO::PARAM_STR);
- $sqlWhen = $pdo->quote($when, PDO::PARAM_STR);
- foreach ($types as $type) {
- $sqlWhat = $pdo->quote($type, PDO::PARAM_STR);
- $sqlValues[] = "( {$sqlWho}, {$sqlWhat}, {$sqlWhen}, NOW() )";
- }
- $sqlValues = implode(", ", $sqlValues);
- $pdo->exec("
- insert ignore into `CRM_NOTIFY` (
- `who`,
- `what`,
- `when`,
- `_created`
- ) values {$sqlValues}
- ");
- } else {
- $sth = $pdo->prepare("
- insert into `CRM_NOTIFY` (
- `who`,
- `what`,
- `when`,
- `_created`
- ) values (
- :who,
- :what,
- :when,
- NOW()
- )
- ");
- $bindValues = array();
- $bindValues['who'] = array($usrLogin, PDO::PARAM_STR);
- $bindValues['what'] = array($what, PDO::PARAM_STR);
- $bindValues['when'] = array($when, PDO::PARAM_STR);
- $pdo->bindValues($sth, $bindValues);
- // try {
- $sth->execute();
- // } catch (PDOException $e) {
- // throw new Exception("Błąd bazy danych: " . json_encode($e->errorInfo));
- // } catch (Exception $e) {
- // throw $e;
- // }
- }
- }
- public function getUserNotifyList($usrLogin) {
- $sth = DB::getPDO()->prepare("
- select n.*
- from `CRM_NOTIFY` n
- where n.`who` = '{$usrLogin}'
- ");
- $sth->execute();
- $notifyTypeList = $sth->fetchAll();
- return $notifyTypeList;
- }
- public function getTodoList($limit = 10, $whenTypes = array()) {
- $pdo = DB::getPDO();
- if (empty($whenTypes)) throw new Exception("when types not set in getTodoList");
- {
- $sqlWhenFltr = array();
- if (in_array('once_a_day', $whenTypes)) {
- $sqlWhenFltr[] = "
- (
- n.`when` = 'once_a_day' and (
- n.last_exec_time is null
- or DATE(n.last_exec_time) < CURDATE()
- )
- )
- ";
- }
- if (in_array('immediately', $whenTypes)) {
- $sqlWhenFltr[] = "( n.`when` = 'immediately' )";
- }
- if (empty($sqlWhenFltr)) throw new Exception("when types not allowed in getTodoList");
- $sqlWhenFltr = "( " . implode(" or ", $sqlWhenFltr) . " )";
- }
- $sth = $pdo->prepare("
- select u.ADM_ACCOUNT
- from ADMIN_USERS u
- join CRM_NOTIFY n on(n.`who` = u.ADM_ACCOUNT and {$sqlWhenFltr})
- where u.A_STATUS = 'NORMAL'
- and u.EMPLOYEE_TYPE = 'Pracownik'
- and n.`who` is not null
- group by u.ADM_ACCOUNT
- order by n.last_exec_time asc
- limit :limit
- ");
- $sth->bindValue(':limit', $limit, PDO::PARAM_INT);
- $sth->execute();
- $rawUsers = $sth->fetchAll();
- if (empty($rawUsers)) return array();
- $sqlUsers = array(); foreach ($rawUsers as $row) { $sqlUsers[] = $pdo->quote($row['ADM_ACCOUNT'], PDO::PARAM_STR); }
- $sqlUsers = implode(", ", $sqlUsers);
- $sth = $pdo->prepare("
- select n.`who`, n.`when`, n.`what`
- , UNIX_TIMESTAMP(n.last_exec_time) as last_exec_time
- , IF(n.`when` = 'immediately'
- , (select UNIX_TIMESTAMP(MAX(i.last_exec_time))
- from CRM_NOTIFY i
- where i.`who` = n.`who`
- and i.`what` = n.`what`
- -- and i.`when` = 'once_a_day'
- -- limit 1
- )
- , null
- ) as _last_exec_time_fix_for_immediately
- from CRM_NOTIFY n
- where n.`who` in({$sqlUsers})
- and {$sqlWhenFltr}
- order by n.last_exec_time asc
- ");
- $sth->execute();
- $rawReminders = $sth->fetchAll();
- $reminders = array();
- $timeToday = mktime(0, 0, 0, date('n'), date('j'), date('Y'));
- //$timeTomorrow = mktime(0, 0, 0, date('n'), date('j') + 1, date('Y'));
- DBG::_('DBG_NTF', '>1', "rawReminders (today:{$timeToday})", $rawReminders, __CLASS__, __FUNCTION__, __LINE__);
- foreach ($rawReminders as $row) {
- $who = $row['who'];
- $when = $row['when'];
- $what = $row['what'];
- $last_exec_time = $row['last_exec_time'];
- $last_exec_time_fix_for_immediately = $row['_last_exec_time_fix_for_immediately'];
- if ('once_a_day' == $when) {
- if ($last_exec_time >= $timeToday) {
- DBG::_('DBG_NTF', '>1', "skip {$last_exec_time} for '{$what}' at '{$when}'", $row, __CLASS__, __FUNCTION__, __LINE__);
- continue;
- } else {
- //DBG::_(true, true, "TODO: else {$last_exec_time} >= {$timeToday}", $row, __CLASS__, __FUNCTION__, __LINE__);
- }
- } else if ('immediately' == $when) {
- //DBG::_(true, true, "TODO: else {$last_exec_time} >= {$timeToday}", $row, __CLASS__, __FUNCTION__, __LINE__);
- } else {
- DBG::_('DBG_NTF', '>0', "TODO: unimplemented when = '{$when}'", $row, __CLASS__, __FUNCTION__, __LINE__);
- continue;
- }
- $last_date = ($last_exec_time)? date("Y-m-d H:i:s", $last_exec_time) : null;
- if (!isset($reminders[$who])) $reminders[$who] = array();
- if (!isset($reminders[$who][$when])) $reminders[$who][$when] = array();
- $reminders[$who][$when][$what] = $last_date;
- if ('immediately' == $when && null !== $last_exec_time_fix_for_immediately && $last_exec_time_fix_for_immediately > $last_exec_time) {
- $reminders[$who][$when][$what] = date("Y-m-d H:i:s", $last_exec_time_fix_for_immediately);
- }
- }
- return $reminders;
- }
- public function reinstallAction() {
- try {
- $force = ('true' == V::get('_force', '', $_GET));
- $this->reinstall($force);
- } catch (Exception $e) {
- echo'<div style="border:1px solid red; background:red; color:#fff;">';
- echo "Error #" . $e->getCode() . "|" . $e->getLine() . ": " . $e->getMessage();
- echo'</div>';
- }
- die('OK');
- }
- public function reinstallFunctionsAction() {
- $this->reinstallFunctions();
- die('OK');
- }
- public function runAction() {
- $msgId = V::get('_msgId', 0, $_REQUEST, 'int');
- if ($msgId > 0) {
- $this->runByMessageId($msgId);
- }
- $jsonData = new stdClass();
- $jsonData->type = 'success';
- $jsonData->msg = 'Gotowe';
- echo json_encode($jsonData);
- exit;
- }
- public function reinstallFunctions() {
- $sqlList = array();
- $db = DB::getDB();
- if ($db->has_errors()) {
- throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
- }
- foreach ($sqlList as $sqlName => $sql) {
- $res = $db->query($sql);
- if ($db->has_errors()) {
- throw new Exception("DB Errors at sql '{$sqlName}': " . implode("\n<br>", $db->get_errors()));
- }
- }
- }
- public function testReinstallTable() {
- $pdo = DB::getPDO();
- if(1){// TEST
- $expectedStruct = array();
- $expectedStruct['who'] = array('type'=>'varchar', 'max_length'=>20, 'is_nullable'=>false);// `who` varchar(20) -- TODO: NOT NULL
- $expectedStruct['when'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `when` varchar(255) NOT NULL
- $expectedStruct['what'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `what` varchar(255) NOT NULL
- $expectedStruct['last_exec_time'] = array('type'=>'datetime', 'is_nullable'=>true);// `last_exec_time` datetime
- $expectedStruct['_created'] = array('type'=>'datetime', 'is_nullable'=>false);// `_created` datetime
- $expectedStruct['uniq_key_1'] = array('type'=>'UNIQUE KEY', 'key_fields'=>array('who','when','what'));// UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
- $expectedStruct['key_who'] = array('type'=>'KEY', 'key_fields'=>array('who'));// KEY `key_who` (`who`)
- // $expectedStruct['t1'] = array('type'=>'varchar', 'max_length'=>300, 'default_value'=>null);
- // $expectedStruct['t2'] = array('type'=>'int');
- // $expectedStruct['t3'] = array('type'=>'int', 'num_precision'=>11, 'default_value'=>null);
- // $expectedStruct['t_dec_11_x'] = array('type'=>'decimal', 'num_precision'=>11);
- // $expectedStruct['t_dec_11_2'] = array('type'=>'decimal', 'num_precision'=>11, 'num_scale'=>2);
- $expectedStruct['t_int'] = array('type'=>'int');
- $expectedStruct['t_tinyint'] = array('type'=>'tinyint');
- $expectedStruct['t_smallint'] = array('type'=>'smallint');
- $expectedStruct['t_mediumint'] = array('type'=>'mediumint');
- $expectedStruct['t_bigint'] = array('type'=>'bigint');
- $expectedStruct['t_decimal'] = array('type'=>'decimal');
- $expectedStruct['t_float'] = array('type'=>'float');
- $expectedStruct['t_double'] = array('type'=>'double');
- $expectedStruct['t_real'] = array('type'=>'real');
- $expectedStruct['t_date'] = array('type'=>'date');
- $expectedStruct['t_datetime'] = array('type'=>'datetime');
- $expectedStruct['t_timestamp'] = array('type'=>'timestamp');
- $expectedStruct['t_time'] = array('type'=>'time');
- $expectedStruct['t_year'] = array('type'=>'year');
- $expectedStruct['t_char'] = array('type'=>'char');
- $expectedStruct['t_varchar'] = array('type'=>'varchar');
- $expectedStruct['t_text'] = array('type'=>'text');
- $expectedStruct['t_tinytext'] = array('type'=>'tinytext');
- $expectedStruct['t_mediumtext'] = array('type'=>'mediumtext');
- $expectedStruct['t_longtext'] = array('type'=>'longtext');
- $expectedStruct['t_enum'] = array('type'=>'enum', 'values'=>array('v1'));
- $expectedStruct['t_set'] = array('type'=>'set', 'values'=>array('v1'));
- $expectedStruct['t_bit'] = array('type'=>'bit', 'max_length'=>2);
- $expectedStruct['t_boolean'] = array('type'=>'boolean');
- $expectedStruct['t_serial'] = array('type'=>'serial');
- $expectedStruct['t_binary'] = array('type'=>'binary');
- $expectedStruct['t_varbinary'] = array('type'=>'varbinary');
- $expectedStruct['t_blob'] = array('type'=>'blob');
- $expectedStruct['t_tinyblob'] = array('type'=>'tinyblob');
- $expectedStruct['t_mediumblob'] = array('type'=>'mediumblob');
- $expectedStruct['t_longblob'] = array('type'=>'longblob');
- $expectedStruct['t_geometry'] = array('type'=>'geometry');
- $expectedStruct['t_point'] = array('type'=>'point');
- $expectedStruct['t_linestring'] = array('type'=>'linestring');
- $expectedStruct['t_polygon'] = array('type'=>'polygon');
- $expectedStruct['t_multipoint'] = array('type'=>'multipoint');
- $expectedStruct['t_multilinestring'] = array('type'=>'multilinestring');
- $expectedStruct['t_multipolygon'] = array('type'=>'multipolygon');
- $expectedStruct['t_geometrycollection'] = array('type'=>'geometrycollection');
- $sqlCreate = $pdo->showCreateStruct('_test_table', $expectedStruct, array('char_encoding'=>'latin2'));
- DBG::_(true, true, "fixedEpectedStruct", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
- $pdo->assertTableStruct('_test_table', $expectedStruct, array('char_encoding'=>'latin2'));
- {// force - drop/create
- $pdo->exec("DROP TABLE IF EXISTS _test_table");
- $pdo->exec($sqlCreate);
- }
- }
- if(0){// TEST nulls
- $sth = $pdo->prepare("DROP TABLE IF EXISTS CRM_NOTIFY");
- $sth->execute();
- $sth = $pdo->prepare("
- CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
- `who` varchar(20)
- , `when` varchar(255) NOT NULL
- , `what` varchar(255) DEFAULT ''
- , `t1` varchar(255) NOT NULL -- same as with DEFAULT ''
- , `t2` varchar(255) NOT NULL DEFAULT ''
- , `t2z` varchar(255) NOT NULL DEFAULT '0'
- -- , `t3` varchar(255) NOT NULL DEFAULT NULL -- SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value
- , `t4` varchar(255) NULL -- same as with DEFAULT NULL
- , `t5` varchar(255) NULL DEFAULT ''
- , `t6` varchar(255) NULL DEFAULT NULL
- , `i1` int(11) NOT NULL -- same as with DEFAULT 0
- , `i2` int(11) NOT NULL DEFAULT 0
- -- , `i3` int(11) NOT NULL DEFAULT NULL -- SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value
- , `i4` int(11) NULL -- same as with DEFAULT NULL
- , `i5` int(11) NULL DEFAULT 0
- , `i6` int(11) NULL DEFAULT NULL
- , `last_exec_time` datetime DEFAULT NULL
- , KEY `who` (`who`)
- ) ENGINE=MyISAM DEFAULT CHARSET=latin2
- ");
- $sth->execute();
- $sth = $pdo->prepare("insert into CRM_NOTIFY (`last_exec_time`) values (NULL)");
- $sth->execute();
- // INSERT INTO CRM_NOTIFY (t1, t2, t2z, t4, t5, t6, i1, i2, i4, i5, i6, last_exec_time)
- // VALUES ('', '', '0', NULL, '', NULL, 0, 0, NULL, 0, NULL, NULL);
- $struct = $pdo->getTableStruct('CRM_NOTIFY');
- DBG::_(true, true, "struct", $struct, __CLASS__, __FUNCTION__, __LINE__);
- DBG::_(true, true, "`t2`: is_null(struct[4]['Default'])=(".is_null($struct[4]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
- DBG::_(true, true, "`t4`: is_null(struct[6]['Default'])=(".is_null($struct[6]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
- DBG::_(true, true, "`t5`: is_null(struct[7]['Default'])=(".is_null($struct[7]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
- DBG::_(true, true, "`t6`: is_null(struct[8]['Default'])=(".is_null($struct[8]['Default']).")", null, __CLASS__, __FUNCTION__, __LINE__);
- $expectedStruct = array();
- $expectedStruct['t1'] = array('type'=>'varchar', 'max_length'=>300, 'default_value'=>null);
- //$expectedStruct['t2'] = array('type'=>'int', 'num_precision'=>11, 'default_value'=>null);
- $pdo->assertTableStruct('CRM_NOTIFY', $expectedStruct);
- }
- }
- public function reinstall($force = false) {
- $sqlList = array();
- $pdo = DB::getPDO();
- $sqlCreate = <<<EOF_SQL_CREATE
- CREATE TABLE IF NOT EXISTS CRM_NOTIFY (
- `who` varchar(20) NOT NULL
- , `when` varchar(255) NOT NULL
- , `what` varchar(255) NOT NULL
- , `last_exec_time` datetime DEFAULT NULL
- , `_created` datetime NOT NULL
- , UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
- , KEY `key_who` (`who`)
- ) ENGINE=MyISAM DEFAULT CHARSET=latin2
- EOF_SQL_CREATE;
- /*
- `CRM_NOTIFY`:
- - who - user login
- - when - shedule (once a day, once on houd)
- - what - action type
- - last_exec_time
- */
- if ($force) $pdo->exec("DROP TABLE IF EXISTS CRM_NOTIFY");
- $pdo->exec($sqlCreate);
- if(0){// TODO: assertTableStruct CRM_NOTIFY
- $expectedStruct = array();
- $expectedStruct['who'] = array('type'=>'varchar', 'max_length'=>20, 'is_nullable'=>false);// `who` varchar(20) -- TODO: NOT NULL
- $expectedStruct['when'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `when` varchar(255) NOT NULL
- $expectedStruct['what'] = array('type'=>'varchar', 'max_length'=>255, 'is_nullable'=>false);// `what` varchar(255) NOT NULL
- $expectedStruct['last_exec_time'] = array('type'=>'datetime', 'is_nullable'=>true);// `last_exec_time` datetime
- $expectedStruct['_created'] = array('type'=>'datetime', 'is_nullable'=>false);// `_created` datetime
- $expectedStruct['uniq_key_1'] = array('type'=>'UNIQUE KEY', 'key_fields'=>array('who','when','what'));// UNIQUE KEY `uniq_key_1` (`who`,`when`,`what`)
- $expectedStruct['key_who'] = array('type'=>'KEY', 'key_fields'=>array('who'));// KEY `key_who` (`who`)
- DBG::_(true, true, "sqlCreate - raw", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
- $sqlCreate = $pdo->showCreateStruct('CRM_NOTIFY', $expectedStruct, array('char_encoding'=>'latin2'));
- DBG::_(true, true, "sqlCreate - generated", $sqlCreate, __CLASS__, __FUNCTION__, __LINE__);
- $pdo->assertTableStruct('CRM_NOTIFY', $expectedStruct, array('char_encoding'=>'latin2'));
- if(0){// force - drop/create
- $pdo->exec("DROP TABLE IF EXISTS CRM_NOTIFY");
- $pdo->exec($sqlCreate);
- }
- }
- {// assertTableStruct CRM_NOTIFY_EXEC_LOG
- // TODO: create table CRM_NOTIFY_EXEC_LOG with action log
- }
- //$this->reinstallFunctions();
- }
- }
|