| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161 |
- <?php
- Lib::loadClass('Router');
- Lib::loadClass('RouteBase');
- Lib::loadClass('TypespecialVariable');
- Lib::loadClass('ProcesHelper');
- Lib::loadClass('UsersHelper');
- Lib::loadClass('UI');
- class Route_UserMsgs extends RouteBase {
- var $_listLimit = 20;
- function handleAuth() {
- if (!User::logged()) {
- User::authByRequest();
- }
- if ($postTask = V::get('_postTask', '', $_POST)) {
- $postFunction = "{$postTask}PostTask";
- if (!method_exists($this, $postFunction)) {
- S::saveUserMessage('AlertDangerException', "post task not exists '{$postTask}'");
- } else {
- $this->$postFunction($_POST);
- }
- }
- }
- function defaultAction() { UI::layout([ $this, 'defaultView' ]); }
- function defaultView() {
- $usrLogin = User::getLogin();
- //$this->menu();
- $this->userMsgs($usrLogin);
- }
- function menu() {
- $usrLogin = User::getLogin();
- echo UI::h('ul', [], [
- UI::h('li', [], "TODO: ..."),
- ]);
- }
- 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>
- var DBG = 0;
- var DBG1 = 1;
- function tblMsgsLoadMoreRows(n) {
- var nNode = jQuery(n),
- lastMsgId = nNode.data('last_msg_id'),
- listType = nNode.data('list_type')
- ;
- DBG && console.log("DBG:tblMsgsLoadMoreRows ", { lastMsgId, listType });
- 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('table').children('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
- ;
- DBG && console.log("DBG:tblMsgsLoadMoreRows fetched ", { data });
- 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: ...");
- }
- 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);
- }
- function _printUserMsgsList($listType, $msgsList, $usrLogin) {
- $msgsTotal = count($msgsList);
- $listLimit = $this->_listLimit;
- $lastMsgId = 0;
- $viewMsgList = array_slice($msgsList, 0, $this->_listLimit, $preserve_keys = true);
- if ($msgsTotal > $listLimit) {
- $msgIds = array_slice(array_keys($msgsList), 0, $listLimit);
- $lastMsgId = array_pop($msgIds);
- }
- $actionTask = ($listType == 'inbox')? 'read' : 'view';
- echo UI::h('table', [ 'class' => "tblMsgsList table table-hovered", 'style' => "margin-bottom:0; table-layout:fixed" ], [
- UI::h('thead', [], [
- UI::h('tr', [], [
- UI::h('th', [ 'style' => "width:60px" ], "#"),
- UI::h('th', [], "wiadomość"),
- UI::h('th', [ 'style' => "width:130px" ], "data"),
- ]),
- ]),
- ($msgsTotal > $listLimit)
- ? UI::h('tfoot', [], [
- UI::h('tr', [ 'class' => "active" ], [
- UI::h('td', [ 'colspan' => "3", 'style' => "text-align:center" ], [
- UI::h('button', [
- 'class' => "btn btn-link",
- 'data-last_msg_id' => $lastMsgId,
- 'data-list_type' => $listType,
- 'onclick' => "return tblMsgsLoadMoreRows(this);",
- ], "pobierz starsze wiadomości ..."),
- ]),
- ]),
- ])
- : ''
- ,
- UI::h('tbody', [],
- ($msgsTotal <= 0)
- ? UI::h('tr', [], [
- UI::h('td', [ 'colspan' => "3" ], [
- UI::h('em', [ 'class' => "text-muted", 'style' => "padding-left:60px;" ], "Brak wiadomości"),
- ]),
- ])
- : array_map(function ($msg) use ($actionTask, $usrLogin) {
- $msgLink = ('read' == $actionTask || 'view' == $actionTask)
- ? $this->getLink($actionTask, [ 'id' => $msg['_raw']->ID, 'usrLogin' => $usrLogin ])
- : null
- ;
- $jsOnClick = ($msgLink)
- ? "window.location.href='{$msgLink}'"
- : ''
- ;
- return UI::h('tr', [ 'onclick' => $jsOnClick, 'class' => "tblMsgsListItem " . ($msg['_read'] ? 'active' : '') ], [
- UI::h('td', [], $msg['_raw']->ID),
- UI::h('td', [], [
- UI::h('div', [ 'style' => "overflow:hidden; white-space:nowrap; text-overflow:ellipsis" ], htmlspecialchars($msg['message'])),
- UI::h('div', [ 'class' => "text-muted", 'style' => "font-style:italic"], [
- "od {$msg['_raw']->A_RECORD_CREATE_AUTHOR} do " . $this->getOutMsgTarget($msg['_raw']),
- ]),
- ]),
- UI::h('td', [ 'style' => "white-space:nowrap" ], [
- $msg['_raw']->A_RECORD_CREATE_DATE,
- ($msg['_readDate'])
- ? UI::h('div', [ 'class' => "text-muted", 'style' => "font-style:italic", 'title' => "Przeczytano {$msg['_readDate']}" ], $msg['_readDate'])
- : UI::h('div', [ 'class' => "text-muted", 'style' => "font-style:italic", 'title' => "Wiadomość nie została jeszcze odczytana" ], "nieodczytana")
- ,
- ]),
- ]);
- }, $viewMsgList)
- ),
- ]);
- }
- function getOutMsgTarget($msg) {
- switch ($msg->userTargetType) {
- case 'everyone': return "wszystkich";
- case 'user': return $msg->userTargetName;
- case 'group': return "grupy {$msg->userTargetName}";
- default: return '???';
- }
- }
- function getMsgs($filterType, $usrLogin, $lastMsgId = null, $fromTime = 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");
- }
- if ($lastMsgId > 0) {
- $sqlWhereAddFilter .= "\n and m.`ID`<{$lastMsgId}";
- }
- if (!empty($fromTime)) {
- $sqlWhereAddFilter .= "\n and m.`A_RECORD_CREATE_DATE`>='{$fromTime}'";
- }
- $sqlLimit = $this->_listLimit + 1;
- $sql = "
- select m.*
- from `CRM_UI_MSGS` m
- where m.`uiTargetType` = 'default_db_table_record'
- {$sqlWhereAddFilter}
- order by m.`ID` DESC
- limit {$sqlLimit}
- ";
- return array_map(function ($row) {
- return [
- 'message' => $row['msg'],
- 'type' => $row['msgType'],
- '_raw' => (object)$row,
- '_read' => ('WAITING' != $row['A_STATUS']),
- '_readDate' => $row['actionExecutedTime'],
- ];
- }, DB::getPDO()->fetchAllByKey($sql, 'ID'));
- }
- 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");
- }
- }
- function _create($args, $tableName, $idRow) {
- $toType = V::get('to_type', '', $args);
- $to = V::get('to', '', $args);
- $msg = V::get('msg', '', $args);
- $usrLogin = User::getLogin();
- try {
- $createdId = DB::getPDO()->insert('CRM_UI_MSGS', [
- 'uiTargetType' => "default_db_table_record",
- 'uiTargetName' => "{$tableName}.{$idRow}",
- 'userTargetType' => $toType,
- 'userTargetName' => $to,
- 'msg' => $msg,
- 'A_RECORD_CREATE_DATE' => "NOW()",
- 'A_RECORD_CREATE_AUTHOR' => $usrLogin,
- 'A_STATUS' => "WAITING",
- 'app_className' => "TableMsgs",
- ]);
- } catch (Exception $e) {
- DBG::log($e);
- throw new Exception("Nie udało się zapisać wiadomości.");
- }
- return $createdId;
- }
- 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
- }
- 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);
- }
- 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);
- }
- 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);
- UI::gora();
- UI::menu();
- try {
- $msg = $this->_getMsg($idMsg, $usrLogin);
- $this->_markAsRead($msg);
- $this->viewMsg($msg);
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage() . ' #' . $e->getLine());
- }
- UI::dol();
- }
- 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);
- UI::gora();
- UI::menu();
- try {
- $msg = $this->_getMsg($idMsg, $usrLogin);
- $this->viewMsg($msg);
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage() . ' #' . $e->getLine());
- }
- UI::dol();
- }
- 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);
- // `uiTargetType` enum('default_db_table','default_db_table_record','after_login','everywhere') NOT NULL, // TODO: add namespace, featureID
- // $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;
- }
- function _markAsRead($msg) {
- if ($msg['_read']) return;
- $usrLogin = User::getLogin();
- $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`
- )
- )
- ";
- try {
- DB::getPDO()->execSql($sql);
- } catch (Exception $e) {
- DBG::log($e);
- throw new Exception("Wystąpiły błędy podczas próby zapisu wiadomości: " . $e->getMessage());
- }
- }
- function viewMsg($msg) {
- $usrLogin = User::getLogin();
- $idTable = 0;
- //$rmMsgLink = "{$linkBase}&_task=removeMsg&id={$msg['_raw']->ID}";
- $targetNamespace = (!empty($msg['tblName'])) ? "default_db/{$msg['tblName']}" : ""; // default_db/CRM_LISTA_ZASOBOW
- $idRow = (!empty($msg['idRow'])) ? $msg['idRow'] : "";
- $targetLabel = ($targetNamespace) ? $this->getOutTargetLabel($targetNamespace) : ""; // $tblAcl->getRawLabel()
- echo UI::h('div', [ 'class' => "container" ], [
- UI::h('h3', [], [
- UI::h('i', [ 'class' => "glyphicon glyphicon-envelope" ]),
- " ",
- UI::h('a', [ 'href' => $this->getLink('', [ 'usrLogin' => $usrLogin ]) ], "Wiadomości {$usrLogin}"),
- " » ",
- " Wiadomość nr {$msg['_raw']->ID}",
- ($targetNamespace && $idRow)
- ? UI::h('small', [ 'style' => "display:block; text-align:right" ], [
- UI::h('a', [
- 'style' => "font-size:12px; line-height:15px; vertical-align:text-bottom",
- 'title' => "Edytuj rekord",
- 'href' => "index.php?_route=ViewTableAjax&namespace={$targetNamespace}#EDIT/{$idRow}",
- ], [
- UI::h('i', [ 'class' => "glyphicon glyphicon-pencil" ]),
- " Edytuj rekord {$idRow}",
- ]),
- UI::h('span', [ 'style' => "font-size:12px; line-height:15px; vertical-align:text-bottom" ], " z tabeli "),
- UI::h('a', [
- 'style' => "font-size:12px; line-height:15px; vertical-align:text-bottom",
- 'href' => "index.php?_route=ViewTableAjax&namespace={$targetNamespace}",
- ], $targetLabel),
- " ",
- $this->printMsgDropdownMenu($msg['_raw']),
- ])
- : ''
- ,
- ]),
- ]);
- $this->printWidgetViewMsg($msg);
- }
- function getOutTargetLabel($ns) {
- try {
- $acl = ACL::getAclByNamespace($ns);
- return $acl->getRawLabel();
- } catch (Exception $e) {
- DBG::log($e);
- }
- return $ns;
- }
- function printMsgDropdownMenu($rawMsg) {
- $isRemoved = ('DELETED' === $rawMsg->A_STATUS || 'OFF_HARD' == $rawMsg->A_STATUS);
- return UI::h('div', [ 'class' => "dropdown", 'style' => "display:inline" ], [
- UI::h('button', [ 'class' => "btn btn-xs btn-default dropdown-toggle", 'title' => "Message Menu", 'data-toggle' => "dropdown" ], [
- UI::h('i', [ 'class' => "glyphicon glyphicon-menu-hamburger" ]),
- " Menu",
- ]),
- UI::h('ul', [ 'class' => "dropdown-menu dropdown-menu-right" ], [
- UI::h('li', [], [
- ($isRemoved)
- ? UI::h('form', [ 'method' => "POST" ], [
- UI::h('input', [ 'type' => 'hidden', 'name' => "_postTask", 'value' => "restoreMsg" ]),
- UI::h('input', [ 'type' => 'hidden', 'name' => "id", 'value' => $rawMsg->ID ]),
- UI::h('button', [ 'type' => "submit", 'class' => "btn btn-link" ], [
- UI::h('i', [ 'class' => "glyphicon glyphicon-inbox" ]),
- " Przywróć",
- ]),
- ])
- : UI::h('form', [ 'method' => "POST" ], [
- UI::h('input', [ 'type' => 'hidden', 'name' => "_postTask", 'value' => "removeMsg" ]),
- UI::h('input', [ 'type' => 'hidden', 'name' => "id", 'value' => $rawMsg->ID ]),
- UI::h('button', [ 'type' => "submit", 'class' => "btn btn-link", 'style' => "color:red" ], [
- UI::h('i', [ 'class' => "glyphicon glyphicon-remove" ]),
- " Usuń"
- ]),
- ])
- ,
- ]),
- ]),
- ]);
- }
- function printWidgetViewMsg($msg) {
- $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;
- $sqlIdThread = ($message->idThread > 0)? $message->idThread : $message->id;
- $messageList = array_map(function ($msg) {
- return $this->_convertMessageToJson((object)$msg);
- }, DB::getPDO()->fetchAll("
- select m.*
- from CRM_UI_MSGS m
- where ( m.idThread = :id_thread or m.ID = :id_thread )
- order by m.ID asc
- limit {$sqlLimit}
- ", [
- ':id_thread' => $sqlIdThread
- ]));
- // -- and m.`ID` < {$message->id}
- }
- ?>
- <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
- }
- 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;
- }
- 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?
- $moreMsgs = array_map(function ($item) {
- return (object)$item;
- }, DB::getPDO()->fetchAll("
- select m.*
- from CRM_UI_MSGS m
- where m.idThread = :id_thread
- and m.ID > :id_last_msg
- order by m.ID asc
- limit {$sqlLimit}
- ", [
- ':id_thread' => $idThread,
- ':id_last_msg' => $idLastMsg,
- ]));
- $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);
- }
- 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);
- }
- 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);
- }
- function _reply($uiTargetType, $uiTargetName, $args) {
- $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 = DB::getPDO()->fetchFirst(" select * from CRM_UI_MSGS where ID = :id ", [ ':id' => $newMsg['idReplyTo'] ]);
- if (!$parentMsg) throw new Exception("Nie znaleziono wiadomości");
- $parentMsg = (object)$parentMsg;
- $newMsg['idThread'] = ($parentMsg->idThread > 0)? $parentMsg->idThread : $parentMsg->ID;
- $newMsg['uiTargetType'] = $uiTargetType;// TODO:? $parentMsg->uiTargetType
- $newMsg['uiTargetName'] = $uiTargetName;// TODO:? $parentMsg->uiTargetName
- $insertedId = DB::getPDO()->insert('CRM_UI_MSGS', $newMsg);
- if (!$insertedId) throw new Exception("Nie udało się utworzyć rekordu");
- $msgAdded = DB::getPDO()->fetchFirst(" select * from CRM_UI_MSGS where ID = :id ", [ ':id' => $insertedId ]);
- if (!$msgAdded) throw new Exception("Nie naleziono rekordu nr '{$insertedId}'");
- $msgAdded = (object)$msgAdded;
- $response = new stdClass();
- $response->msg = "Wysłano wiadomość";
- $response->type = 'success';
- $response->record = $this->_convertMessageToJson($msgAdded);
- return $response;
- }
- 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);
- UI::gora();
- UI::menu();
- try {
- $msg = $this->_getMsg($idMsg, $usrLogin);
- $msgsRoute = Router::getRoute('Msgs');
- $msgsRoute->removeTableRecordMsg($idMsg);
- } catch (Exception $e) {
- UI::alert('danger', $e->getMessage() . ' #' . $e->getLine());
- UI::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
- UI::dol();
- }
- function removeMsgPostTask($args) {
- try {
- $id = V::get('id', 0, $args, 'int');
- if ($id <= 0) throw new AlertDangerException("Missing message id!");
- $usrLogin = V::get('usrLogin', User::getLogin(), $_REQUEST, 'word');
- $msg = $this->_getMsg($id, $usrLogin);
- $isRemoved = ('DELETED' === $msg['_raw']->A_STATUS || 'OFF_HARD' == $msg['_raw']->A_STATUS);
- if ($isRemoved) throw new AlertInfoException("Wiadomość nr {$id} została usunięta wcześniej");
- Router::getRoute('Msgs')->removeTableRecordMsg($id);
- throw new AlertInfoException("Usunięto wiadomość nr {$id}"); // TODO: przywróć btn require global post task class
- } catch (Exception $e) {
- DBG::log($e);
- S::saveUserMessage(get_class($e), $e->getMessage());
- }
- }
- function restoreMsgPostTask($args) {
- try {
- $id = V::get('id', 0, $args, 'int');
- if ($id <= 0) throw new AlertDangerException("Missing message id!");
- $usrLogin = V::get('usrLogin', User::getLogin(), $_REQUEST, 'word');
- $msg = $this->_getMsg($id, $usrLogin);
- $isRemoved = ('DELETED' === $msg['_raw']->A_STATUS || 'OFF_HARD' == $msg['_raw']->A_STATUS);
- if (!$isRemoved) throw new AlertInfoException("Wiadomość nr {$id} nie jest usunięta");
- Router::getRoute('Msgs')->restoreTableRecordMsg($id);
- throw new AlertInfoException("Przywrócono wiadomość nr {$id}"); // TODO: przywróć btn require global post task class
- } catch (Exception $e) {
- DBG::log($e);
- S::saveUserMessage(get_class($e), $e->getMessage());
- }
- }
- }
|