| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079 |
- <?php
- Lib::loadClass('Router');
- Lib::loadClass('RouteBase');
- Lib::loadClass('TypespecialVariable');
- Lib::loadClass('ProcesHelper');
- Lib::loadClass('UsersHelper');
- class Route_UserMsgs extends RouteBase {
- var $_listLimit = 20;
- public function handleAuth() {
- if (!User::logged()) {
- User::authByRequest();
- }
- }
- public function defaultAction() {
- SE_Layout::gora();
- SE_Layout::menu();
- try {
- $usrLogin = User::getLogin();
- //$this->menu();
- $this->userMsgs($usrLogin);
- } catch (Exception $e) {
- SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
- }
- SE_Layout::dol();
- }
- public function menu() {
- $usrLogin = User::getLogin();
- ?>
- <ul>
- <li>TODO: ...</li>
- </ul>
- <?php
- }
- public function userMsgs($usrLogin) {
- $msgsList = $this->getMsgs('inbox', $usrLogin);
- $totalReadMsgs = 0;
- $totalUnreadMsgs = 0;
- foreach ($msgsList as $ind => $msg) {
- if ($msg['_read']) {
- $totalReadMsgs++;
- } else {
- $totalUnreadMsgs++;
- }
- }
- $sentMsgsList = $this->getMsgs('sent', $usrLogin);
- $removedMsgsList = $this->getMsgs('removed', $usrLogin);
- ?>
- <style type="text/css">
- .tblMsgsListItem { cursor:pointer; }
- </style>
- <div class="container">
- <h3><i class="glyphicon glyphicon-envelope"></i> Wiadomości <code><?php echo $usrLogin; ?></code></h3>
- <div>
- <ul class="nav nav-tabs" role="tablist">
- <!--
- <li>
- <a href="#tbl-msgs-compose"><i class="glyphicon glyphicon-plus"></i> Nowa wiadomość</a>
- </li>
- -->
- <li role="presentation" class="active"><a href="#odebrane" aria-controls="odebrane" role="tab" data-toggle="tab">Odebrane <em>(<?php echo $totalUnreadMsgs; ?>)</em></a></li>
- <li role="presentation"><a href="#wyslane" aria-controls="wyslane" role="tab" data-toggle="tab">Wysłane</em></a></li>
- <li role="presentation"><a href="#kosz" aria-controls="kosz" role="tab" data-toggle="tab">Kosz</em></a></li>
- </ul>
- <div class="tab-content" style="margin-bottom:15px">
- <div role="tabpanel" class="tab-pane active" id="odebrane" style="border-style:none solid solid solid; border-width:1px; border-color:#ddd;">
- <?php $this->_printUserMsgsList('inbox', $msgsList, $usrLogin); ?>
- </div>
- <div role="tabpanel" class="tab-pane" id="wyslane" style="border-style:none solid solid solid; border-width:1px; border-color:#ddd;">
- <?php $this->_printUserMsgsList('sent', $sentMsgsList, $usrLogin); ?>
- </div>
- <div role="tabpanel" class="tab-pane" id="kosz" style="border-style:none solid solid solid; border-width:1px; border-color:#ddd;">
- <?php $this->_printUserMsgsList('removed', $removedMsgsList, $usrLogin); ?>
- </div>
- </div>
- </div>
- <!--
- <div class="panel panel-default" id="tbl-msgs-compose">
- <div class="panel-heading">Wyślij nową wiadomość</div>
- <div class="panel-body">
- <?php if (!empty($arrorsList)) : ?>
- <?php foreach ($arrorsList as $errMsg) : ?>
- <div class="alert alert-danger"><?php echo $errMsg; ?></div>
- <?php endforeach; ?>
- <?php endif; ?>
- <?php $this->_printMsgForm($args); ?>
- </div>
- </div>
- -->
- </div>
- <script>
- function tblMsgsLoadMoreRows(n) {
- var nNode = jQuery(n),
- lastMsgId = nNode.data('last_msg_id'),
- listType = nNode.data('list_type')
- ;
- nNode.blur();
- function tblMsgsSetNoMoreRows(btnLoadMoreNode) {
- btnLoadMoreNode.closest('td').css({color:'silver'}).html('Brak starszych wiadomości');
- }
- if (lastMsgId <= 0) {
- tblMsgsSetNoMoreRows(nNode);
- }
- function tblMsgsAddMsgToList(msg, btnLoadMoreNode, listType) {
- var tbodyNode = btnLoadMoreNode.closest('tfoot').prev('tbody'),
- trNode = jQuery('<tr></tr>'),
- tdIdNode = jQuery('<td></td>'),
- tdMsgNode = jQuery('<td></td>'),
- tdDateNode = jQuery('<td style="white-space:nowrap;"></td>'),
- actionTask = (listType == 'inbox')? 'read' : 'view',
- msgLink = ''
- ;
- trNode.addClass('tblMsgsListItem');
- if (msg['_read']) trNode.addClass('active');
- if ('read' === actionTask || 'view' === actionTask) {
- msgLink = '<?php echo Request::getPathUri() . 'index.php?_route=UserMsgs'; ?>';
- msgLink += '&usrLogin=<?php echo $usrLogin; ?>';
- msgLink += '&id=' + msg['_raw']['ID'];
- msgLink += '&_task=' + actionTask;
- trNode.attr('onclick', "window.location.href='" + msgLink + "'");
- }
- tdIdNode.append(msg['_raw']['ID']);
- tdIdNode.appendTo(trNode);
- tdMsgNode.append('<div style="overflow:hidden; white-space:nowrap; text-overflow:ellipsis;">' + msg['message'] + '</div>');
- msgMetaInfo = 'od ' + msg['_raw']['A_RECORD_CREATE_AUTHOR'] + ' do ';
- if ('everyone' == msg['_raw']['userTargetType']) {
- msgMetaInfo += 'wszystkich';
- } else if ('user' == msg['_raw']['userTargetType']) {
- msgMetaInfo += msg['_raw']['userTargetName'];
- } else if ('group' == msg['_raw']['userTargetType']) {
- msgMetaInfo += 'grupy ' + msg['_raw']['userTargetName'];
- }
- tdMsgNode.append('<div class="text-muted" style="font-style:italic;">' + msgMetaInfo + '</div>');
- tdMsgNode.appendTo(trNode);
- tdDateNode.append(msg['_raw']['A_RECORD_CREATE_DATE']);
- if (msg['_readDate']) {
- tdDateNode.append('<div class="text-muted" style="font-style:italic" title="Przeczytano ' + msg['_readDate'] + '">' + msg['_readDate'] + '</div>');
- } else {
- tdDateNode.append('<div class="text-muted" style="font-style:italic" title="Wiadomość nie została jeszcze odczytana">nieodczytana</div>');
- }
- tdDateNode.appendTo(trNode);
- trNode.hide();
- trNode.appendTo(tbodyNode);
- trNode.show('slow');
- };
- jQuery.ajax({
- data: {},
- dataType: 'json',
- type: "POST",
- url: 'index.php?_route=UserMsgs&_task=loadMoreRows&listType=' + listType + '&lastMsgId=' + lastMsgId + '&usrLogin=<?php echo $usrLogin; ?>'
- })
- .done(function(data, textStatus, jqXHR) {
- var listLimit = <?php echo $this->_listLimit; ?>,
- i = 0,
- lastMsgId = 0,
- hasMore = false
- ;
- if (!data || !data.msgs || !data.keysOrder) {
- jQuery.notify('Wystąpiły błędy podczas pobierania listy wiadomości', 'error');
- return false;
- }
- data.keysOrder.forEach(function(key) {
- if (i < listLimit) {
- lastMsgId = key;
- tblMsgsAddMsgToList(data.msgs[key], nNode, listType);
- } else {
- hasMore = true;
- }
- i++;
- });
- if (!hasMore) {
- tblMsgsSetNoMoreRows(nNode);
- }
- nNode.data('last_msg_id', lastMsgId);
- })
- .fail(function(jqXHR) {
- if (jqXHR.responseJSON) {
- jQuery.notify('Nie udało się pobrać listy wiadomości', 'error');
- }
- else {
- var txt = jqXHR.responseText || 'Nie udało się pobrać listy wiadomości';
- if (jqXHR.status == 404) {
- jQuery.notify(jqXHR.responseText, 'error');
- } else {
- jQuery.notify(jqXHR.responseText, 'warn');
- }
- }
- });
- }
- </script>
- <?php
- //DBG::_(true, true, "_POST", $_POST, __CLASS__, __FUNCTION__, __LINE__);
- //DBG::_(true, true, "tblAcl", $tblAcl, __CLASS__, __FUNCTION__, __LINE__);
- //DBG::_(true, true, "record", $record, __CLASS__, __FUNCTION__, __LINE__);
- //DBG::_(true, true, "msgsList", $msgsList, __CLASS__, __FUNCTION__, __LINE__);
- //throw new Exception("TODO: ...");
- }
- public function loadMoreRowsAction() {
- $usrLogin = V::get('usrLogin', '', $_GET, 'word');
- $lastMsgId = V::get('lastMsgId', 0, $_GET, 'int');
- $listType = V::get('listType', '', $_GET, 'word');
- if (!$usrLogin) throw new HttpException("Wrong param login", 404);
- if ($lastMsgId <= 0) throw new HttpException("Wrong param lastMsgId", 404);
- if (!in_array($listType, array('inbox','sent','removed'))) throw new HttpException("Wrong param listType", 404);
- $resultData = new stdClass();
- $resultData->msgs = $this->getMsgs($listType, $usrLogin, $lastMsgId);
- $resultData->keysOrder = array_keys($resultData->msgs);
- echo json_encode($resultData);
- }
- public function _printUserMsgsList($listType, $msgsList, $usrLogin) {
- $msgsTotal = count($msgsList);
- $listLimit = $this->_listLimit;
- $lastMsgId = 0;
- $actionTask = ($listType == 'inbox')? 'read' : 'view';
- ?>
- <table class="tblMsgsList table table-hovered" style="margin-bottom:0; table-layout:fixed;">
- <thead>
- <tr>
- <th style="width:60px">#</th>
- <th>wiadomość</th>
- <th style="width:130px">data</th>
- </tr>
- </thead>
- <tbody>
- <?php if ($msgsTotal <= 0) : ?>
- <tr>
- <td colspan="3"><em class="text-muted" style="padding-left:60px;">Brak wiadomości</em></td>
- </tr>
- <?php else : ?>
- <?php $i = 0; foreach ($msgsList as $idMsg => $msg) : $i++; if ($i > $listLimit) break; $lastMsgId = $idMsg; ?>
- <?php
- $onClick = '';
- $msgLink = Request::getPathUri() . 'index.php?_route=UserMsgs&id=' . $msg['_raw']->ID;
- $msgLink .= "&usrLogin={$usrLogin}";
- if ('read' == $actionTask || 'view' == $actionTask) {
- $msgLink .= '&_task=' . $actionTask;
- } else {
- $msgLink = null;
- }
- if ($msgLink) {
- $jsOnClick = "window.location.href='{$msgLink}'";
- $onClick = 'onclick="' . $jsOnClick . '"';
- }
- ?>
- <tr <?php echo $onClick; ?>
- class="tblMsgsListItem <?php echo ($msg['_read'])? 'active' : ''; ?>">
- <td><?php echo $msg['_raw']->ID; ?></td>
- <td>
- <div style="overflow:hidden; white-space:nowrap; text-overflow:ellipsis;"><?php echo htmlspecialchars($msg['message']); ?></div>
- <div class="text-muted" style="font-style:italic;">
- od <?php echo $msg['_raw']->A_RECORD_CREATE_AUTHOR; ?> do <?php
- if ('everyone' == $msg['_raw']->userTargetType) {
- echo "wszystkich";
- } else if ('user' == $msg['_raw']->userTargetType) {
- echo "{$msg['_raw']->userTargetName}";
- } else if ('group' == $msg['_raw']->userTargetType) {
- echo "grupy {$msg['_raw']->userTargetName}";
- }
- ?>
- </div>
- </td>
- <td style="white-space:nowrap;">
- <?php echo $msg['_raw']->A_RECORD_CREATE_DATE; ?>
- <?php if ($msg['_readDate']) : ?>
- <div class="text-muted" style="font-style:italic" title="Przeczytano <?php echo $msg['_readDate']; ?>"><?php echo $msg['_readDate']; ?></div>
- <?php else : ?>
- <div class="text-muted" style="font-style:italic" title="Wiadomość nie została jeszcze odczytana">nieodczytana</div>
- <?php endif; ?>
- </td>
- </tr>
- <?php endforeach; ?>
- <?php endif; ?>
- </tbody>
- <tfoot>
- <?php if ($msgsTotal > $listLimit) : ?>
- <tr class="active">
- <td colspan="3" style="text-align:center">
- <button class="btn btn-link"
- data-last_msg_id="<?php echo $lastMsgId; ?>"
- data-list_type="<?php echo $listType; ?>"
- onclick="return tblMsgsLoadMoreRows(this);">pobierz starsze wiadomości ...</button>
- </td>
- </tr>
- <?php endif; ?>
- </tfoot>
- </table>
- <?php
- }
- public function getMsgs($filterType, $usrLogin, $lastMsgId = null) {
- $lastMsgId = (int)$lastMsgId;
- $msgsRoute = Router::getRoute('Msgs');
- $msgsList = array();
- if (empty($usrLogin)) throw new Exception("No user login!");
- $sqlWhereAddFilter = "";
- if ($usrLogin == User::getLogin()) {
- $userGroupIds = User::getGroupsIds();
- } else {
- $userGroup = UsersHelper::getGroupByUserName($usrLogin);
- $userGroupIds = array_keys($userGroup);
- }
- $sqlFilerMsgsForUser = "
- m.`userTargetType` in('everyone')
- or (m.`userTargetType`='user' and m.`userTargetName`='{$usrLogin}')
- or (m.`userTargetType`='group' and m.`userTargetName` in(" . implode(",", $userGroupIds) . "))
- ";
- switch ($filterType) {
- case 'inbox':
- $sqlWhereAddFilter = "
- and ({$sqlFilerMsgsForUser})
- and m.`A_STATUS` in('WAITING', 'NORMAL')
- ";
- break;
- case 'unread':
- $sqlWhereAddFilter = "
- and ({$sqlFilerMsgsForUser})
- and m.`A_STATUS` in('WAITING')
- ";
- break;
- case 'sent':
- $sqlWhereAddFilter = "
- and m.`A_RECORD_CREATE_AUTHOR`='{$usrLogin}'
- and (m.`A_STATUS` in('WAITING', 'NORMAL')
- or (m.`A_STATUS`='OFF_HARD' and m.`A_RECORD_DELETE_AUTHOR`!='{$usrLogin}')
- )
- ";
- break;
- case 'removed':
- $sqlWhereAddFilter = "
- and (m.`A_RECORD_CREATE_AUTHOR`='{$usrLogin}'
- or ({$sqlFilerMsgsForUser})
- )
- and m.`A_STATUS` in('OFF_HARD', 'DELETED')
- ";
- break;
- default: throw new Exception("Unknown filter type");
- }
- $db = DB::getDB();
- $tableName = $db->_($tableName);
- if ($lastMsgId > 0) {
- $sqlWhereAddFilter .= "\n and m.`ID`<{$lastMsgId}";
- }
- $sqlLimit = $this->_listLimit + 1;
- $sql = "select m.*
- from `CRM_UI_MSGS` m
- where m.`uiTargetType`='default_db_table_record'
- -- and m.`uiTargetName`='{$tableName}.{$idRow}'
- {$sqlWhereAddFilter}
- order by m.`ID` DESC
- limit {$sqlLimit}
- ";
- //DBG::_('DBG_MSGS', '>1', "sql", $sql, __CLASS__, __FUNCTION__, __LINE__);
- $db = DB::getDB();
- $res = $db->query($sql);
- while ($r = $db->fetch($res)) {
- $msg['message'] = $r->msg;
- $msg['type'] = $r->msgType;
- $msg['_raw'] = $r;
- $msg['_read'] = ('WAITING' != $r->A_STATUS);
- $msg['_readDate'] = $r->actionExecutedTime;
- $msgsList[$r->ID] = $msg;
- }
- return $msgsList;
- }
- public function _validate($args) {
- $toType = V::get('to_type', '', $args);
- $to = V::get('to', '', $args);
- $msg = V::get('msg', '', $args);
- if (!in_array($toType, array('everyone', 'user', 'group'))) {
- throw new Exception("Niedozwolony typ odbiorcy");
- }
- if (empty($to) && 'everyone' != $toType) {
- throw new Exception("Proszę podać odbiorcę wiadomości");
- }
- if (empty($msg)) {
- throw new Exception("Proszę podać treść wiadomości");
- }
- }
- public function _create($args, $tableName, $idRow) {
- $toType = V::get('to_type', '', $args);
- $to = V::get('to', '', $args);
- $msg = V::get('msg', '', $args);
- $usrLogin = User::getLogin();
- $db = DB::getDB();
- if (!$db) throw new Exception("Brak dazy danych!");
- if ($db->has_errors()) throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
- $item = array();
- $item['`uiTargetType`'] = "'default_db_table_record'";
- $item['`uiTargetName`'] = "'{$tableName}.{$idRow}'";
- $item['`userTargetType`'] = "'{$toType}'";
- $item['`userTargetName`'] = "'{$to}'";
- $item['`msg`'] = "'" . $db->_($msg) . "'";
- $item['`A_RECORD_CREATE_DATE`'] = "NOW()";
- $item['`A_RECORD_CREATE_AUTHOR`'] = "'{$usrLogin}'";
- $item['`A_STATUS`'] = "'WAITING'";
- $item['`app_className`'] = "'TableMsgs'";
- $sql = "insert into `CRM_UI_MSGS` (" . implode(",", array_keys($item)) . ")
- values (" . implode(",", array_values($item)) . ")
- ";
- $res = $db->query($sql);
- if (!$res || $db->has_errors()) throw new Exception("Wystąpiły błędy podczas próby zapisu wiadomości: " . implode("\n<br>", $db->get_errors()));
- $createdId = $db->insert_id();
- if ($createdId <= 0) throw new Exception("Nie udało się zapisać wiadomości.");
- return $createdId;
- }
- public function _printMsgForm($args) {
- $toType = V::get('to_type', '', $args);
- $to = V::get('to', '', $args);
- $msg = V::get('msg', '', $args);
- $listTo = array();
- $listTo['everyone'] = 'Wszyscy';
- $listTo['user'] = 'Użytkownik';
- $listTo['group'] = 'Grupa';
- $toType = (array_key_exists($toType, $listTo))? $toType : 'everyone';
- $typeSpecialGroupId = TypespecialVariable::getInstance(-1, '__ZASOB');
- $typeSpecialUserLogin = TypespecialVariable::getInstance(-1, '__USER_LOGIN');
- $selectedLogin = ('user' == $toType)? $to : '';
- $selectedGroupId = ('group' == $toType)? $to : '';
- ?>
- <form class="form-horizontal" action="" method="post">
- <div class="form-group">
- <label class="col-sm-2 control-label" for="to">Do:</label>
- <div class="col-sm-3">
- <select name="to_type" class="form-control" onChange="return selectTblMsgsToType(this);">
- <?php foreach ($listTo as $type => $typeLabel) : ?>
- <option <?php echo ($type == $toType)? 'selected' : ''; ?>
- value="<?php echo $type; ?>"><?php echo $typeLabel; ?></option>
- <?php endforeach; ?>
- </select>
- </div>
- <div class="col-sm-7">
- <div id="tblMsgsTo-everyone" style="<?php echo ('everyone' == $toType)? '' : 'display:none'; ?>">
- <input name="to-everyone" type="text" class="form-control" disabled>
- </div>
- <div id="tblMsgsTo-group" style="<?php echo ('group' == $toType)? '' : 'display:none'; ?>">
- <?php if ($typeSpecialGroupId) : ?>
- <?php
- $fldName = 'to-group';
- $fldParams = array();
- $fldParams['allowCreate'] = false;
- $fldParams['ajaxDataUrlBase'] = "index.php?_route=TableMsgs&_task=typeSpecialGroupId";
- $fldParams['placeholder'] = 'Grupa...';
- //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
- echo $typeSpecialUserLogin->showFormItem($tblID = -1, $fldName, $selectedGroupId, $fldParams);
- ?>
- <?php else : ?>
- <input name="to-group" type="text" class="form-control" placeholder="Grupa">
- <?php endif; ?>
- </div>
- <div id="tblMsgsTo-user" style="<?php echo ('user' == $toType)? '' : 'display:none'; ?>">
- <?php if ($typeSpecialUserLogin) : ?>
- <?php
- $fldName = 'to-user';
- $fldParams = array();
- $fldParams['allowCreate'] = false;
- $fldParams['ajaxDataUrlBase'] = "index.php?_route=TableMsgs&_task=typeSpecialUserLogin";
- $fldParams['placeholder'] = 'Użytkownik...';
- //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
- echo $typeSpecialUserLogin->showFormItem($tblID = -1, $fldName, $selectedLogin, $fldParams);
- ?>
- <?php else : ?>
- <input name="to-user" type="text" class="form-control" placeholder="Użytkownik">
- <?php endif; ?>
- </div>
- </div>
- </div>
- <div class="form-group">
- <label for="to" class="col-sm-2 control-label">Wiadomość:</label>
- <div class="col-sm-10">
- <textarea name="msg" class="form-control"><?php echo htmlspecialchars($msg); ?></textarea>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-10 col-sm-offset-2">
- <input class="btn btn-primary" type="submit" value="Wyślij">
- </div>
- </div>
- </form>
- <script>
- function selectTblMsgsToType(n) {
- var toTypes = <?php echo json_encode(array_keys($listTo)); ?>,
- selectedType = n.value
- ;
- if (-1 !== toTypes.indexOf(n.value)) {
- toTypes.forEach(function(type) {
- if (type == selectedType) {
- document.getElementById('tblMsgsTo-' + type).style.display = 'block';
- } else {
- document.getElementById('tblMsgsTo-' + type).style.display = 'none';
- }
- });
- }
- }
- </script>
- <?php
- }
- 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);
- }
- public function typeSpecialGroupIdAction() {
- header("Content-type: application/json");
- Lib::loadClass('TypespecialVariable');
- $typeSpecialZasob = TypespecialVariable::getInstance(-1, '__ZASOB');
- if (!$typeSpecialZasob) {
- $jsonData = new stdClass();
- $jsonData->message = "TypeSpecial '__ZASOB' not exists";
- echo json_encode($jsonData);
- exit;
- }
- $query = V::get('q', '', $_REQUEST);
- $rawRows = null;
- $jsonData = array();
- $queryParams = array();
- $queryParams['zasob_type_in'] = array('STANOWISKO', 'PODMIOT', 'DZIAL');
- $rows = $typeSpecialZasob->getValuesWithExports($query, $queryParams);
- DBG::_('DBG_TS', '>1', "rows({$query})", $rows, __CLASS__, __FUNCTION__, __LINE__);
- 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);
- }
- public function readAction() {
- $idMsg = V::get('id', 0, $_GET, 'int');
- $usrLogin = V::get('usrLogin', '', $_REQUEST, 'word');
- if ($idMsg <= 0) throw new HttpException("Wiadomość nie istnieje!", 404);
- if (empty($usrLogin)) throw new HttpException("Błęny user login!", 404);
- SE_Layout::gora();
- SE_Layout::menu();
- try {
- $msg = $this->_getMsg($idMsg, $usrLogin);
- $this->_markAsRead($msg);
- $this->viewMsg($msg);
- } catch (Exception $e) {
- SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
- }
- SE_Layout::dol();
- }
- public function viewAction() {
- $idMsg = V::get('id', 0, $_GET, 'int');
- $usrLogin = V::get('usrLogin', 0, $_REQUEST, 'word');
- if ($idMsg <= 0) throw new HttpException("Wiadomość nie istnieje!", 404);
- if (empty($usrLogin)) throw new HttpException("Błęny user login", 404);
- SE_Layout::gora();
- SE_Layout::menu();
- try {
- $msg = $this->_getMsg($idMsg, $usrLogin);
- $this->viewMsg($msg);
- } catch (Exception $e) {
- SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
- }
- SE_Layout::dol();
- }
- public function _getMsg($idMsg, $usrLogin) {
- $msgsRoute = Router::getRoute('Msgs');
- $msg['_raw'] = $msgsRoute->getMessage($idMsg);
- if (!$msg['_raw']) throw new HttpException("Wiadomość nie istnieje!", 404);
- $msg['usrLogin'] = $usrLogin;
- $msg['message'] = $msg['_raw']->msg;
- $msg['type'] = $msg['_raw']->msgType;
- $msg['_read'] = ('WAITING' != $msg['_raw']->A_STATUS);
- // $msg['_raw']->uiTargetType => default_db_table_record
- // $msg['_raw']->uiTargetName => TEST_PERMS.31
- if ('default_db_table_record' !== $msg['_raw']->uiTargetType) {
- throw new Exception("Parse message target type error!");
- }
- $parts = explode('.', $msg['_raw']->uiTargetName);
- if (2 !== count($parts)) throw new Exception("Parse message target type error!");
- $msg['tblName'] = $parts[0];
- $msg['idRow'] = $parts[1];
- if (!is_numeric($msg['idRow'])) throw new Exception("Parse message target type - id row type error!");
- return $msg;
- }
- public function _markAsRead($msg) {
- if ($msg['_read']) return;
- $usrLogin = User::getLogin();
- $db = DB::getDB();
- if (!$db) throw new Exception("Brak dazy danych!");
- if ($db->has_errors()) throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
- $sql = "update `CRM_UI_MSGS`
- set `A_STATUS`='NORMAL'
- , `A_RECORD_UPDATE_AUTHOR`='{$usrLogin}'
- , `A_RECORD_UPDATE_DATE`=NOW()
- , `actionExecutedTime`=NOW()
- where `ID`='{$msg['_raw']->ID}'
- and `A_STATUS`='WAITING'
- and `A_RECORD_UPDATE_AUTHOR`=''
- and `A_RECORD_UPDATE_DATE` is null
- and (
- ('{$usrLogin}'!=`A_RECORD_CREATE_AUTHOR`)
- or ('{$usrLogin}'=`A_RECORD_CREATE_AUTHOR`
- and 'user'=`userTargetType`
- and '{$usrLogin}'=`userTargetName`
- )
- )
- ";
- $res = $db->query($sql);
- if (!$res || $db->has_errors()) throw new Exception("Wystąpiły błędy podczas próby zapisu wiadomości: " . implode("\n<br>", $db->get_errors()));
- }
- public function viewMsg($msg) {
- $usrLogin = User::getLogin();
- $idTable = 0;
- if (!empty($msg['tblName'])) {
- $tblName = $msg['tblName'];
- $idTable = ProcesHelper::getZasobTableID($tblName);
- if (!$idTable) throw new Exception("Nie udało się odnaleźć nr tabeli '{$tblName}'");
- $idRow = $msg['idRow'];
- if (!$idRow) throw new Exception("Brak numeru powiązanego rekordu!");
- $usrAcl = User::getAcl();
- $tblAcl = $usrAcl->getTableAcl($idTable);
- }
- $linkBase = "index.php?_route=UserMsgs";
- $linkBase .= "&usrLogin={$usrLogin}";
- //$rmMsgLink = "{$linkBase}&_task=removeMsg&id={$msg['_raw']->ID}";
- $backLink = "{$linkBase}";
- ?>
- <div class="container">
- <h3><i class="glyphicon glyphicon-envelope"></i> <a href="<?php echo $backLink; ?>">Wiadomości <?php echo $usrLogin; ?></a>
- » Wiadomość nr <?php echo $msg['_raw']->ID; ?>
- <?php if ($idTable > 0) : ?>
- <!-- <br><small>wiadomość powiązana z rekordem <a href="index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $idTable; ?>#EDIT/<?php echo $idRow; ?>"><?php echo $idRow; ?></a>
- z tabeli <a href="index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $idTable; ?>"><?php echo $tblAcl->getLabel(); ?></a>
- </small>
- -->
- <small style="display:block; text-align:right">
- <a style="font-size:12px; line-height:15px; vertical-align:text-bottom;" title="Edytuj rekord" href="index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $idTable; ?>#EDIT/<?php echo $idRow; ?>"><i class="glyphicon glyphicon-pencil"></i> Edytuj rekord <?php echo $idRow; ?></a>
- <span style="font-size:12px; line-height:15px; vertical-align:text-bottom;">z tabeli</span>
- <a style="font-size:12px; line-height:15px; vertical-align:text-bottom;" href="index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $idTable; ?>"><?php echo $tblAcl->getRawLabel(); ?></a>
- </small>
- <?php endif; ?>
- </h3>
- </div>
- <?php $this->printWidgetViewMsg($msg); ?>
- <?php
- }
- public function printWidgetViewMsg($msg) {
- $messageList = array();
- $uiTargetName = $msg['_raw']->uiTargetName;
- $uiTargetType = $msg['_raw']->uiTargetType;
- $replyLink = "index.php?_route=UserMsgs&_task=reply&uiTargetName={$uiTargetName}&uiTargetType={$uiTargetType}";
- $markAsReadLink = "index.php?_route=UserMsgs&_task=markAsRead";
- $message = $this->_convertMessageToJson($msg['_raw']);
- {//if ($message->idThread > 0) {
- $sqlLimit = 100;
- $ds = DB::getDataSource();
- $sqlIdThread = ($message->idThread > 0)? $message->idThread : $message->id;
- $sql = "
- select m.*
- from `CRM_UI_MSGS` m
- where (m.`idThread` = {$sqlIdThread} or m.`ID` = {$sqlIdThread})
- -- and m.`ID` < {$message->id}
- order by m.`ID` asc
- limit {$sqlLimit}
- ";
- $moreMsgs = $ds->getListByQuery($sql);
- foreach ($moreMsgs as $msg) $messageList[] = $this->_convertMessageToJson($msg);
- }
- //$messageList[] = $message;
- ?>
- <link rel="stylesheet" href="./stuff/widget-select.css">
- <style type="text/css">
- .user_avatar {
- display:block;
- width:40px;
- height:40px;
- margin:0 auto 10px auto;
- padding:0;
- border:1px solid #ddd;
- line-height: 38px;
- font-size:16px;
- text-align:center;
- vertical-align:middle;
- color:#aaa;
- }
- </style>
- <div id="widget-msg-tree" style="max-width:1000px; margin:0 auto;"></div>
- <script src="stuff/vendors.js"></script>
- <script src="stuff/bundle.se_route_user_msgs.js"></script>
- <script>
- var testNewRecordCounter = 0;
- jQuery("#widget-msg-tree").MsgThread({
- usrLogin: '<?php echo User::getLogin(); ?>',
- idThread: <?php echo $message->idThread; ?>,
- msgs: <?php echo json_encode($messageList); ?>,
- fetchMessages: (function() {
- var _msgsXhr = null;
- return function(reqData, callback) {
- if (_msgsXhr && _msgsXhr.state() === 'pending') {
- _msgsXhr.abort();
- _msgsXhr = null;
- }
- _msgsXhr = $.ajax({
- url: 'index.php?_route=UserMsgs&_task=getMessagesById&idThread=<?php echo $message->idThread; ?>',
- data: reqData,
- dataType: 'json'
- });
- _msgsXhr.done(function(data, textStatus, jqXHR) {
- if (data && data.msgs && data.msgs.length > 0) {
- callback(null, {msgs: data.msgs});
- } else {
- callback(null, {msgs: []});//"Error no data!");
- }
- });
- _msgsXhr.fail(function() {
- callback(null, {options: []});//"Error no data!");
- });
- _msgsXhr.always(function() {
- _msgsXhr = null;
- });
- };
- })(),
- fetchOptionsForGroup: (function() {
- var _groupXhr = null;
- return function(input, callback) {
- if (_groupXhr && _groupXhr.state() === 'pending') {
- _groupXhr.abort();
- _groupXhr = null;
- }
- _groupXhr = $.ajax({
- url: 'index.php?_route=UserMsgs&_task=typeSpecialGroupId&q=' + input,
- dataType: 'json'
- });
- _groupXhr.done(function(data, textStatus, jqXHR) {
- if (data && data.length > 0) {
- var options = [];
- data.forEach(function(item) {
- options.push({value: item.id, label: item.name});
- });
- callback(null, {options: options});
- } else {
- callback(null, {options: []});//"Error no data!");
- }
- });
- _groupXhr.fail(function() {
- callback(null, {options: []});//"Error no data!");
- });
- _groupXhr.always(function() {
- _groupXhr = null;
- });
- };
- })(),
- fetchOptionsForUser: (function() {
- var _userXhr = null;
- return function(input, callback) {
- if (_userXhr && _userXhr.state() === 'pending') {
- _userXhr.abort();
- _userXhr = null;
- }
- _userXhr = $.ajax({
- url: 'index.php?_route=UserMsgs&_task=typeSpecialUserLogin&q=' + input,
- dataType: 'json'
- });
- _userXhr.done(function(data, textStatus, jqXHR) {
- if (data && data.length > 0) {
- var options = [];
- data.forEach(function(item) {
- options.push({value: item.id, label: item.name});
- });
- callback(null, {options: options});
- } else {
- callback(null, {options: []});//"Error no data!");
- }
- });
- _userXhr.fail(function() {
- callback(null, {options: []});//"Error no data!");
- });
- _userXhr.always(function() {
- _userXhr = null;
- });
- };
- })(),
- saveReply: function(data, callback) {
- //console.log('#widget-msg-tree/MsgThread::saveReply: data:', data, 'callback', callback);
- $.ajax({
- url: '<?php echo $replyLink; ?>',
- method: 'POST',
- data: data,
- dataType: 'json'
- })
- .done(function(data, textStatus, jqXHR) {
- var returnData = {message: '', type: 'danger'};
- if (data && data.record) {
- returnData.msg = data.msg || 'Wysłano wiadomość';
- returnData.record = data.record;
- returnData.type = 'success';
- } else if (data.validateErrors) {
- returnData.msg = data.msg || 'Wystąpiły błędy w formularzu';
- returnData.type = 'warning';
- returnData.validateErrors = data.validateErrors;
- } else {
- returnData.msg = data.msg || 'Nie udało się wysłać wiadomości!';
- returnData.type = 'danger';
- }
- callback(null, returnData);
- })
- .fail(function() {
- callback(null, {message: 'Nie udało się wysłać wiadomości!', type: 'danger'});
- });
- },
- markAsRead: function(idMsg, callback) {
- //console.log('#widget-msg-tree/MsgThread::markAsRead: idMsg:', idMsg);
- $.ajax({
- url: '<?php echo $markAsReadLink; ?>&idMsg=' + idMsg,
- method: 'GET',
- dataType: 'json'
- })
- .done(function(data, textStatus, jqXHR) {
- var returnData = {message: '', type: 'danger'};
- if (data && data.record) {
- returnData.msg = data.msg || 'Oznaczono wiadomość jako odczytaną';
- returnData.record = data.record;
- returnData.type = 'success';
- } else {
- returnData.msg = data.msg || 'Nie udało się oznaczyć wiadomości jako odczytanej!';
- returnData.type = 'danger';
- }
- callback(null, returnData);
- })
- .fail(function() {
- callback(null, {message: 'Nie udało się oznaczyć wiadomości jako odczytanej!', type: 'danger'});
- });
- },
- dbg: false
- });
- // jQuery("#widget-msg-tree").on('change', function(e, data) {
- // console.log('#widget-msg-tree/MsgThread::onChange: data:', data);
- // });
- </script>
- <?php
- }
- public function _convertMessageToJson($rawMsg) {
- /* $msg = {_raw: {A_RECORD_CREATE_AUTHOR: "plabudda",
- A_RECORD_CREATE_DATE: "2015-10-26 12:20:05",
- A_RECORD_DELETE_AUTHOR: "",
- A_RECORD_DELETE_DATE: null,
- A_RECORD_UPDATE_AUTHOR: "plabudda",
- A_RECORD_UPDATE_DATE: "2015-11-02 12:44:59",
- A_STATUS: "NORMAL",
- ID: "67",
- actionExecutedTime: "2015-11-02 12:44:59",
- actionNotes: "",
- app_className: "TableMsgs",
- msg: "test Y",
- msgType: "info",
- uiTargetName: "TEST_PERMS.31",
- uiTargetType: "default_db_table_record",
- userTargetName: "plabudda",
- userTargetType: "user"}
- _read: true,
- idRow: "31",
- message: "test Y",
- tblName: "TEST_PERMS",
- type: "info",
- usrLogin: "plabudda"} */
- $usrLogin = User::getLogin();
- $message = new stdClass();
- $message->id = $rawMsg->ID;
- $message->idThread = $rawMsg->idThread;// TODO: ID_THREAD
- $message->idReplyTo = $rawMsg->idReplyTo;// TODO: ID_REPLY_TO
- $message->message = $rawMsg->msg;
- $message->type = $rawMsg->msgType;
- $message->to = $rawMsg->userTargetName;
- $message->toType = $rawMsg->userTargetType;
- $message->author = $rawMsg->A_RECORD_CREATE_AUTHOR;
- $message->created = $rawMsg->A_RECORD_CREATE_DATE;
- $message->_read = ('WAITING' != $rawMsg->A_STATUS);
- $message->_readByUser = ('WAITING' != $rawMsg->A_STATUS);
- if ('WAITING' == $rawMsg->A_STATUS
- && $usrLogin == $rawMsg->A_RECORD_CREATE_AUTHOR) {
- if ('user' == $rawMsg->userTargetType
- && $usrLogin == $rawMsg->userTargetName) {
- $message->_readByUser = false;
- } else {
- $message->_readByUser = true;
- }
- }
- if ($message->_read) {
- if (!empty($rawMsg->A_RECORD_UPDATE_DATE)) $message->_readDate = $rawMsg->A_RECORD_UPDATE_DATE;
- if (!empty($rawMsg->A_RECORD_UPDATE_AUTHOR)) $message->_readBy = $rawMsg->A_RECORD_UPDATE_AUTHOR;
- }
- return $message;
- }
- public function getMessagesByIdAction() {
- try {
- $idThread = V::get('idThread', '', $_GET, 'int');
- $idLastMsg = V::get('idLastMsg', '', $_GET, 'int');
- if ($idThread <= 0) throw new Exception("Wrong param id!");
- $sqlLimit = 10;// TODO: 100?
- $ds = DB::getDataSource();
- $sql = "
- select m.*
- from `CRM_UI_MSGS` m
- where m.`idThread` = {$idThread}
- and m.`ID` > {$idLastMsg}
- order by m.`ID` asc
- limit {$sqlLimit}
- ";
- $moreMsgs = $ds->getListByQuery($sql);
- $response = new stdClass();
- $response->msg = "Nowe wiadomości";
- $response->type = 'success';
- $response->msgs = array();
- foreach ($moreMsgs as $msg) {
- $response->msgs[] = $this->_convertMessageToJson($msg);
- }
- } catch (Exception $e) {
- $response = new stdClass();
- $response->msg = "Wystąpiły błędy: " . $e->getMessage();
- $response->type = 'danger';
- }
- echo json_encode($response);
- }
- public function replyAction() {
- try {
- $uiTargetType = V::get('uiTargetType', '', $_GET);
- $uiTargetName = V::get('uiTargetName', '', $_GET);
- $response = $this->_reply($uiTargetType, $uiTargetName, $_POST);
- } catch (Exception $e) {
- $response = new stdClass();
- $response->msg = "Wystąpiły błędy: " . $e->getMessage();
- $response->type = 'danger';
- }
- echo json_encode($response);
- }
- public function markAsReadAction() {
- $usrLogin = User::getLogin();
- try {
- $idMsg = V::get('idMsg', '', $_GET, 'int');
- $msg = $this->_getMsg($idMsg, $usrLogin);
- $this->_markAsRead($msg);
- $response = new stdClass();
- //$response->msg = "";
- $response->type = "success";
- $msg = $this->_getMsg($idMsg, $usrLogin);
- $response->record = $this->_convertMessageToJson($msg['_raw']);
- } catch (Exception $e) {
- $response = new stdClass();
- $response->msg = "Wystąpiły błędy: " . $e->getMessage();
- $response->type = 'danger';
- }
- echo json_encode($response);
- }
- public function _reply($uiTargetType, $uiTargetName, $args) {
- $ds = DB::getDataSource();
- $newMsg = array();
- $newMsg['idReplyTo'] = V::get('idReplyTo', '', $args, 'int');
- $newMsg['msg'] = V::get('message', '', $args);
- $newMsg['msgType'] = V::get('msgType', 'info', $args);
- $newMsg['userTargetType'] = V::get('toType', '', $args);
- $newMsg['userTargetName'] = V::get('to', '', $args);
- $newMsg['A_RECORD_CREATE_DATE'] = 'NOW()';
- $newMsg['A_RECORD_CREATE_AUTHOR'] = User::getLogin();
- $newMsg['app_className'] = 'TableMsgs';
- //DBG::_(true, true, "newMsg", $newMsg, __CLASS__, __FUNCTION__, __LINE__);
- if ($newMsg['idReplyTo'] <= 0) throw new Exception("Wrong id reply to msg");
- $parentMsg = $ds->getById('CRM_UI_MSGS', $newMsg['idReplyTo']);
- if (!$parentMsg) throw new Exception("Nie znaleziono wiadomości");
- $newMsg['idThread'] = ($parentMsg->idThread > 0)? $parentMsg->idThread : $parentMsg->ID;
- $newMsg['uiTargetType'] = $uiTargetType;// TODO:? $parentMsg->uiTargetType
- $newMsg['uiTargetName'] = $uiTargetName;// TODO:? $parentMsg->uiTargetName
- $insertedId = $ds->insert('CRM_UI_MSGS', $newMsg);
- if (!$insertedId) throw new Exception("Nie udało się utworzyć rekordu");
- $msgAdded = $ds->getById('CRM_UI_MSGS', $insertedId);
- $response = new stdClass();
- $response->msg = "Wysłano wiadomość";
- $response->type = 'success';
- $response->record = $this->_convertMessageToJson($msgAdded);
- return $response;
- }
- public function removeMsgAction() {
- $idMsg = V::get('id', 0, $_GET, 'int');
- $usrLogin = V::get('usrLogin', 0, $_REQUEST, 'word');
- if ($idMsg <= 0) throw new HttpException("Wiadomość nie istnieje!", 404);
- if (empty($usrLogin)) throw new HttpException("Błęny user login", 404);
- SE_Layout::gora();
- SE_Layout::menu();
- try {
- $msg = $this->_getMsg($idMsg, $usrLogin);
- $msgsRoute = Router::getRoute('Msgs');
- $msgsRoute->removeTableRecordMsg($idMsg);
- } catch (Exception $e) {
- SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
- SE_Layout::dol();
- exit;
- }
- ?>
- <div class="container">
- <div class="alert alert-success">
- Wiadomość została usunięta <a class="btn btn-xs btn-default" href="index.php?_route=UserMsgs&usrLogin=<?php echo $usrLogin; ?>">wróć</a>
- </div>
- </div>
- <?php
- SE_Layout::dol();
- }
- }
|