UserMsgs.php 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157
  1. <?php
  2. Lib::loadClass('Router');
  3. Lib::loadClass('RouteBase');
  4. Lib::loadClass('TypespecialVariable');
  5. Lib::loadClass('ProcesHelper');
  6. Lib::loadClass('UsersHelper');
  7. Lib::loadClass('UI');
  8. class Route_UserMsgs extends RouteBase {
  9. var $_listLimit = 20;
  10. function handleAuth() {
  11. if (!User::logged()) {
  12. User::authByRequest();
  13. }
  14. if ($postTask = V::get('_postTask', '', $_POST)) {
  15. $postFunction = "{$postTask}PostTask";
  16. if (!method_exists($this, $postFunction)) {
  17. S::saveUserMessage('AlertDangerException', "post task not exists '{$postTask}'");
  18. } else {
  19. $this->$postFunction($_POST);
  20. }
  21. }
  22. }
  23. function defaultAction() { UI::layout([ $this, 'defaultView' ]); }
  24. function defaultView() {
  25. $usrLogin = User::getLogin();
  26. //$this->menu();
  27. $this->userMsgs($usrLogin);
  28. }
  29. function menu() {
  30. $usrLogin = User::getLogin();
  31. echo UI::h('ul', [], [
  32. UI::h('li', [], "TODO: ..."),
  33. ]);
  34. }
  35. function userMsgs($usrLogin) {
  36. $msgsList = $this->getMsgs('inbox', $usrLogin);
  37. $totalReadMsgs = 0;
  38. $totalUnreadMsgs = 0;
  39. foreach ($msgsList as $ind => $msg) {
  40. if ($msg['_read']) {
  41. $totalReadMsgs++;
  42. } else {
  43. $totalUnreadMsgs++;
  44. }
  45. }
  46. $sentMsgsList = $this->getMsgs('sent', $usrLogin);
  47. $removedMsgsList = $this->getMsgs('removed', $usrLogin);
  48. ?>
  49. <style type="text/css">
  50. .tblMsgsListItem { cursor:pointer; }
  51. </style>
  52. <div class="container">
  53. <h3><i class="glyphicon glyphicon-envelope"></i> Wiadomości <code><?php echo $usrLogin; ?></code></h3>
  54. <div>
  55. <ul class="nav nav-tabs" role="tablist">
  56. <!--
  57. <li>
  58. <a href="#tbl-msgs-compose"><i class="glyphicon glyphicon-plus"></i> Nowa wiadomość</a>
  59. </li>
  60. -->
  61. <li role="presentation" class="active"><a href="#odebrane" aria-controls="odebrane" role="tab" data-toggle="tab">Odebrane <em>(<?php echo $totalUnreadMsgs; ?>)</em></a></li>
  62. <li role="presentation"><a href="#wyslane" aria-controls="wyslane" role="tab" data-toggle="tab">Wysłane</em></a></li>
  63. <li role="presentation"><a href="#kosz" aria-controls="kosz" role="tab" data-toggle="tab">Kosz</em></a></li>
  64. </ul>
  65. <div class="tab-content" style="margin-bottom:15px">
  66. <div role="tabpanel" class="tab-pane active" id="odebrane" style="border-style:none solid solid solid; border-width:1px; border-color:#ddd;">
  67. <?php $this->_printUserMsgsList('inbox', $msgsList, $usrLogin); ?>
  68. </div>
  69. <div role="tabpanel" class="tab-pane" id="wyslane" style="border-style:none solid solid solid; border-width:1px; border-color:#ddd;">
  70. <?php $this->_printUserMsgsList('sent', $sentMsgsList, $usrLogin); ?>
  71. </div>
  72. <div role="tabpanel" class="tab-pane" id="kosz" style="border-style:none solid solid solid; border-width:1px; border-color:#ddd;">
  73. <?php $this->_printUserMsgsList('removed', $removedMsgsList, $usrLogin); ?>
  74. </div>
  75. </div>
  76. </div>
  77. <!--
  78. <div class="panel panel-default" id="tbl-msgs-compose">
  79. <div class="panel-heading">Wyślij nową wiadomość</div>
  80. <div class="panel-body">
  81. <?php if (!empty($arrorsList)) : ?>
  82. <?php foreach ($arrorsList as $errMsg) : ?>
  83. <div class="alert alert-danger"><?php echo $errMsg; ?></div>
  84. <?php endforeach; ?>
  85. <?php endif; ?>
  86. <?php $this->_printMsgForm($args); ?>
  87. </div>
  88. </div>
  89. -->
  90. </div>
  91. <script>
  92. var DBG = 0;
  93. var DBG1 = 1;
  94. function tblMsgsLoadMoreRows(n) {
  95. var nNode = jQuery(n),
  96. lastMsgId = nNode.data('last_msg_id'),
  97. listType = nNode.data('list_type')
  98. ;
  99. DBG && console.log("DBG:tblMsgsLoadMoreRows ", { lastMsgId, listType });
  100. nNode.blur();
  101. function tblMsgsSetNoMoreRows(btnLoadMoreNode) {
  102. btnLoadMoreNode.closest('td').css({color:'silver'}).html('Brak starszych wiadomości');
  103. }
  104. if (lastMsgId <= 0) {
  105. tblMsgsSetNoMoreRows(nNode);
  106. }
  107. function tblMsgsAddMsgToList(msg, btnLoadMoreNode, listType) {
  108. var tbodyNode = btnLoadMoreNode.closest('table').children('tbody'),
  109. trNode = jQuery('<tr></tr>'),
  110. tdIdNode = jQuery('<td></td>'),
  111. tdMsgNode = jQuery('<td></td>'),
  112. tdDateNode = jQuery('<td style="white-space:nowrap;"></td>'),
  113. actionTask = (listType == 'inbox')? 'read' : 'view',
  114. msgLink = ''
  115. ;
  116. trNode.addClass('tblMsgsListItem');
  117. if (msg['_read']) trNode.addClass('active');
  118. if ('read' === actionTask || 'view' === actionTask) {
  119. msgLink = '<?php echo Request::getPathUri() . 'index.php?_route=UserMsgs'; ?>';
  120. msgLink += '&usrLogin=<?php echo $usrLogin; ?>';
  121. msgLink += '&id=' + msg['_raw']['ID'];
  122. msgLink += '&_task=' + actionTask;
  123. trNode.attr('onclick', "window.location.href='" + msgLink + "'");
  124. }
  125. tdIdNode.append(msg['_raw']['ID']);
  126. tdIdNode.appendTo(trNode);
  127. tdMsgNode.append('<div style="overflow:hidden; white-space:nowrap; text-overflow:ellipsis;">' + msg['message'] + '</div>');
  128. msgMetaInfo = 'od ' + msg['_raw']['A_RECORD_CREATE_AUTHOR'] + ' do ';
  129. if ('everyone' == msg['_raw']['userTargetType']) {
  130. msgMetaInfo += 'wszystkich';
  131. } else if ('user' == msg['_raw']['userTargetType']) {
  132. msgMetaInfo += msg['_raw']['userTargetName'];
  133. } else if ('group' == msg['_raw']['userTargetType']) {
  134. msgMetaInfo += 'grupy ' + msg['_raw']['userTargetName'];
  135. }
  136. tdMsgNode.append('<div class="text-muted" style="font-style:italic;">' + msgMetaInfo + '</div>');
  137. tdMsgNode.appendTo(trNode);
  138. tdDateNode.append(msg['_raw']['A_RECORD_CREATE_DATE']);
  139. if (msg['_readDate']) {
  140. tdDateNode.append('<div class="text-muted" style="font-style:italic" title="Przeczytano ' + msg['_readDate'] + '">' + msg['_readDate'] + '</div>');
  141. } else {
  142. tdDateNode.append('<div class="text-muted" style="font-style:italic" title="Wiadomość nie została jeszcze odczytana">nieodczytana</div>');
  143. }
  144. tdDateNode.appendTo(trNode);
  145. trNode.hide();
  146. trNode.appendTo(tbodyNode);
  147. trNode.show('slow');
  148. };
  149. jQuery.ajax({
  150. data: {},
  151. dataType: 'json',
  152. type: "POST",
  153. url: 'index.php?_route=UserMsgs&_task=loadMoreRows&listType=' + listType + '&lastMsgId=' + lastMsgId + '&usrLogin=<?php echo $usrLogin; ?>'
  154. })
  155. .done(function(data, textStatus, jqXHR) {
  156. var listLimit = <?php echo $this->_listLimit; ?>,
  157. i = 0,
  158. lastMsgId = 0,
  159. hasMore = false
  160. ;
  161. DBG && console.log("DBG:tblMsgsLoadMoreRows fetched ", { data });
  162. if (!data || !data.msgs || !data.keysOrder) {
  163. jQuery.notify('Wystąpiły błędy podczas pobierania listy wiadomości', 'error');
  164. return false;
  165. }
  166. data.keysOrder.forEach(function(key) {
  167. if (i < listLimit) {
  168. lastMsgId = key;
  169. tblMsgsAddMsgToList(data.msgs[key], nNode, listType);
  170. } else {
  171. hasMore = true;
  172. }
  173. i++;
  174. });
  175. if (!hasMore) {
  176. tblMsgsSetNoMoreRows(nNode);
  177. }
  178. nNode.data('last_msg_id', lastMsgId);
  179. })
  180. .fail(function(jqXHR) {
  181. if (jqXHR.responseJSON) {
  182. jQuery.notify('Nie udało się pobrać listy wiadomości', 'error');
  183. }
  184. else {
  185. var txt = jqXHR.responseText || 'Nie udało się pobrać listy wiadomości';
  186. if (jqXHR.status == 404) {
  187. jQuery.notify(jqXHR.responseText, 'error');
  188. } else {
  189. jQuery.notify(jqXHR.responseText, 'warn');
  190. }
  191. }
  192. });
  193. }
  194. </script>
  195. <?php
  196. //DBG::_(true, true, "_POST", $_POST, __CLASS__, __FUNCTION__, __LINE__);
  197. //DBG::_(true, true, "tblAcl", $tblAcl, __CLASS__, __FUNCTION__, __LINE__);
  198. //DBG::_(true, true, "record", $record, __CLASS__, __FUNCTION__, __LINE__);
  199. //DBG::_(true, true, "msgsList", $msgsList, __CLASS__, __FUNCTION__, __LINE__);
  200. //throw new Exception("TODO: ...");
  201. }
  202. function loadMoreRowsAction() {
  203. $usrLogin = V::get('usrLogin', '', $_GET, 'word');
  204. $lastMsgId = V::get('lastMsgId', 0, $_GET, 'int');
  205. $listType = V::get('listType', '', $_GET, 'word');
  206. if (!$usrLogin) throw new HttpException("Wrong param login", 404);
  207. if ($lastMsgId <= 0) throw new HttpException("Wrong param lastMsgId", 404);
  208. if (!in_array($listType, array('inbox','sent','removed'))) throw new HttpException("Wrong param listType", 404);
  209. $resultData = new stdClass();
  210. $resultData->msgs = $this->getMsgs($listType, $usrLogin, $lastMsgId);
  211. $resultData->keysOrder = array_keys($resultData->msgs);
  212. echo json_encode($resultData);
  213. }
  214. function _printUserMsgsList($listType, $msgsList, $usrLogin) {
  215. $msgsTotal = count($msgsList);
  216. $listLimit = $this->_listLimit;
  217. $lastMsgId = 0;
  218. $viewMsgList = array_slice($msgsList, 0, $this->_listLimit, $preserve_keys = true);
  219. if ($msgsTotal > $listLimit) {
  220. $msgIds = array_slice(array_keys($msgsList), 0, $listLimit);
  221. $lastMsgId = array_pop($msgIds);
  222. }
  223. $actionTask = ($listType == 'inbox')? 'read' : 'view';
  224. echo UI::h('table', [ 'class' => "tblMsgsList table table-hovered", 'style' => "margin-bottom:0; table-layout:fixed" ], [
  225. UI::h('thead', [], [
  226. UI::h('tr', [], [
  227. UI::h('th', [ 'style' => "width:60px" ], "#"),
  228. UI::h('th', [], "wiadomość"),
  229. UI::h('th', [ 'style' => "width:130px" ], "data"),
  230. ]),
  231. ]),
  232. ($msgsTotal > $listLimit)
  233. ? UI::h('tfoot', [], [
  234. UI::h('tr', [ 'class' => "active" ], [
  235. UI::h('td', [ 'colspan' => "3", 'style' => "text-align:center" ], [
  236. UI::h('button', [
  237. 'class' => "btn btn-link",
  238. 'data-last_msg_id' => $lastMsgId,
  239. 'data-list_type' => $listType,
  240. 'onclick' => "return tblMsgsLoadMoreRows(this);",
  241. ], "pobierz starsze wiadomości ..."),
  242. ]),
  243. ]),
  244. ])
  245. : ''
  246. ,
  247. UI::h('tbody', [],
  248. ($msgsTotal <= 0)
  249. ? UI::h('tr', [], [
  250. UI::h('td', [ 'colspan' => "3" ], [
  251. UI::h('em', [ 'class' => "text-muted", 'style' => "padding-left:60px;" ], "Brak wiadomości"),
  252. ]),
  253. ])
  254. : array_map(function ($msg) use ($actionTask, $usrLogin) {
  255. $msgLink = ('read' == $actionTask || 'view' == $actionTask)
  256. ? $this->getLink($actionTask, [ 'id' => $msg['_raw']->ID, 'usrLogin' => $usrLogin ])
  257. : null
  258. ;
  259. $jsOnClick = ($msgLink)
  260. ? "window.location.href='{$msgLink}'"
  261. : ''
  262. ;
  263. return UI::h('tr', [ 'onclick' => $jsOnClick, 'class' => "tblMsgsListItem " . ($msg['_read'] ? 'active' : '') ], [
  264. UI::h('td', [], $msg['_raw']->ID),
  265. UI::h('td', [], [
  266. UI::h('div', [ 'style' => "overflow:hidden; white-space:nowrap; text-overflow:ellipsis" ], htmlspecialchars($msg['message'])),
  267. UI::h('div', [ 'class' => "text-muted", 'style' => "font-style:italic"], [
  268. "od {$msg['_raw']->A_RECORD_CREATE_AUTHOR} do " . $this->getOutMsgTarget($msg['_raw']),
  269. ]),
  270. ]),
  271. UI::h('td', [ 'style' => "white-space:nowrap" ], [
  272. $msg['_raw']->A_RECORD_CREATE_DATE,
  273. ($msg['_readDate'])
  274. ? UI::h('div', [ 'class' => "text-muted", 'style' => "font-style:italic", 'title' => "Przeczytano {$msg['_readDate']}" ], $msg['_readDate'])
  275. : UI::h('div', [ 'class' => "text-muted", 'style' => "font-style:italic", 'title' => "Wiadomość nie została jeszcze odczytana" ], "nieodczytana")
  276. ,
  277. ]),
  278. ]);
  279. }, $viewMsgList)
  280. ),
  281. ]);
  282. }
  283. function getOutMsgTarget($msg) {
  284. switch ($msg->userTargetType) {
  285. case 'everyone': return "wszystkich";
  286. case 'user': return $msg->userTargetName;
  287. case 'group': return "grupy {$msg->userTargetName}";
  288. default: return '???';
  289. }
  290. }
  291. function getMsgs($filterType, $usrLogin, $lastMsgId = null, $fromTime = null) {
  292. $lastMsgId = (int)$lastMsgId;
  293. $msgsRoute = Router::getRoute('Msgs');
  294. $msgsList = array();
  295. if (empty($usrLogin)) throw new Exception("No user login!");
  296. $sqlWhereAddFilter = "";
  297. if ($usrLogin == User::getLogin()) {
  298. $userGroupIds = User::getGroupsIds();
  299. } else {
  300. $userGroup = UsersHelper::getGroupByUserName($usrLogin);
  301. $userGroupIds = array_keys($userGroup);
  302. }
  303. $sqlFilerMsgsForUser = "
  304. m.`userTargetType` in('everyone')
  305. or (m.`userTargetType`='user' and m.`userTargetName`='{$usrLogin}')
  306. or (m.`userTargetType`='group' and m.`userTargetName` in(" . implode(",", $userGroupIds) . "))
  307. ";
  308. switch ($filterType) {
  309. case 'inbox':
  310. $sqlWhereAddFilter = "
  311. and ({$sqlFilerMsgsForUser})
  312. and m.`A_STATUS` in('WAITING', 'NORMAL')
  313. ";
  314. break;
  315. case 'unread':
  316. $sqlWhereAddFilter = "
  317. and ({$sqlFilerMsgsForUser})
  318. and m.`A_STATUS` in('WAITING')
  319. ";
  320. break;
  321. case 'sent':
  322. $sqlWhereAddFilter = "
  323. and m.`A_RECORD_CREATE_AUTHOR`='{$usrLogin}'
  324. and (m.`A_STATUS` in('WAITING', 'NORMAL')
  325. or (m.`A_STATUS`='OFF_HARD' and m.`A_RECORD_DELETE_AUTHOR`!='{$usrLogin}')
  326. )
  327. ";
  328. break;
  329. case 'removed':
  330. $sqlWhereAddFilter = "
  331. and (m.`A_RECORD_CREATE_AUTHOR`='{$usrLogin}'
  332. or ({$sqlFilerMsgsForUser})
  333. )
  334. and m.`A_STATUS` in('OFF_HARD', 'DELETED')
  335. ";
  336. break;
  337. default: throw new Exception("Unknown filter type");
  338. }
  339. if ($lastMsgId > 0) {
  340. $sqlWhereAddFilter .= "\n and m.`ID`<{$lastMsgId}";
  341. }
  342. if (!empty($fromTime)) {
  343. $sqlWhereAddFilter .= "\n and m.`A_RECORD_CREATE_DATE`>='{$fromTime}'";
  344. }
  345. $sqlLimit = $this->_listLimit + 1;
  346. $sql = "
  347. select m.*
  348. from `CRM_UI_MSGS` m
  349. where m.`uiTargetType` = 'default_db_table_record'
  350. {$sqlWhereAddFilter}
  351. order by m.`ID` DESC
  352. limit {$sqlLimit}
  353. ";
  354. return array_map(function ($row) {
  355. return [
  356. 'message' => $row['msg'],
  357. 'type' => $row['msgType'],
  358. '_raw' => (object)$row,
  359. '_read' => ('WAITING' != $row['A_STATUS']),
  360. '_readDate' => $row['actionExecutedTime'],
  361. ];
  362. }, DB::getPDO()->fetchAllByKey($sql, 'ID'));
  363. }
  364. function _validate($args) {
  365. $toType = V::get('to_type', '', $args);
  366. $to = V::get('to', '', $args);
  367. $msg = V::get('msg', '', $args);
  368. if (!in_array($toType, array('everyone', 'user', 'group'))) {
  369. throw new Exception("Niedozwolony typ odbiorcy");
  370. }
  371. if (empty($to) && 'everyone' != $toType) {
  372. throw new Exception("Proszę podać odbiorcę wiadomości");
  373. }
  374. if (empty($msg)) {
  375. throw new Exception("Proszę podać treść wiadomości");
  376. }
  377. }
  378. function _create($args, $tableName, $idRow) {
  379. $toType = V::get('to_type', '', $args);
  380. $to = V::get('to', '', $args);
  381. $msg = V::get('msg', '', $args);
  382. $usrLogin = User::getLogin();
  383. try {
  384. $createdId = DB::getPDO()->insert('CRM_UI_MSGS', [
  385. 'uiTargetType' => "default_db_table_record",
  386. 'uiTargetName' => "{$tableName}.{$idRow}",
  387. 'userTargetType' => $toType,
  388. 'userTargetName' => $to,
  389. 'msg' => $msg,
  390. 'A_RECORD_CREATE_DATE' => "NOW()",
  391. 'A_RECORD_CREATE_AUTHOR' => $usrLogin,
  392. 'A_STATUS' => "WAITING",
  393. 'app_className' => "TableMsgs",
  394. ]);
  395. } catch (Exception $e) {
  396. DBG::log($e);
  397. throw new Exception("Nie udało się zapisać wiadomości.");
  398. }
  399. return $createdId;
  400. }
  401. function _printMsgForm($args) {
  402. $toType = V::get('to_type', '', $args);
  403. $to = V::get('to', '', $args);
  404. $msg = V::get('msg', '', $args);
  405. $listTo = array();
  406. $listTo['everyone'] = 'Wszyscy';
  407. $listTo['user'] = 'Użytkownik';
  408. $listTo['group'] = 'Grupa';
  409. $toType = (array_key_exists($toType, $listTo))? $toType : 'everyone';
  410. $typeSpecialGroupId = TypespecialVariable::getInstance(-1, '__ZASOB');
  411. $typeSpecialUserLogin = TypespecialVariable::getInstance(-1, '__USER_LOGIN');
  412. $selectedLogin = ('user' == $toType)? $to : '';
  413. $selectedGroupId = ('group' == $toType)? $to : '';
  414. ?>
  415. <form class="form-horizontal" action="" method="post">
  416. <div class="form-group">
  417. <label class="col-sm-2 control-label" for="to">Do:</label>
  418. <div class="col-sm-3">
  419. <select name="to_type" class="form-control" onChange="return selectTblMsgsToType(this);">
  420. <?php foreach ($listTo as $type => $typeLabel) : ?>
  421. <option <?php echo ($type == $toType)? 'selected' : ''; ?>
  422. value="<?php echo $type; ?>"><?php echo $typeLabel; ?></option>
  423. <?php endforeach; ?>
  424. </select>
  425. </div>
  426. <div class="col-sm-7">
  427. <div id="tblMsgsTo-everyone" style="<?php echo ('everyone' == $toType)? '' : 'display:none'; ?>">
  428. <input name="to-everyone" type="text" class="form-control" disabled>
  429. </div>
  430. <div id="tblMsgsTo-group" style="<?php echo ('group' == $toType)? '' : 'display:none'; ?>">
  431. <?php if ($typeSpecialGroupId) : ?>
  432. <?php
  433. $fldName = 'to-group';
  434. $fldParams = array();
  435. $fldParams['allowCreate'] = false;
  436. $fldParams['ajaxDataUrlBase'] = "index.php?_route=TableMsgs&_task=typeSpecialGroupId";
  437. $fldParams['placeholder'] = 'Grupa...';
  438. //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
  439. echo $typeSpecialUserLogin->showFormItem($tblID = -1, $fldName, $selectedGroupId, $fldParams);
  440. ?>
  441. <?php else : ?>
  442. <input name="to-group" type="text" class="form-control" placeholder="Grupa">
  443. <?php endif; ?>
  444. </div>
  445. <div id="tblMsgsTo-user" style="<?php echo ('user' == $toType)? '' : 'display:none'; ?>">
  446. <?php if ($typeSpecialUserLogin) : ?>
  447. <?php
  448. $fldName = 'to-user';
  449. $fldParams = array();
  450. $fldParams['allowCreate'] = false;
  451. $fldParams['ajaxDataUrlBase'] = "index.php?_route=TableMsgs&_task=typeSpecialUserLogin";
  452. $fldParams['placeholder'] = 'Użytkownik...';
  453. //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
  454. echo $typeSpecialUserLogin->showFormItem($tblID = -1, $fldName, $selectedLogin, $fldParams);
  455. ?>
  456. <?php else : ?>
  457. <input name="to-user" type="text" class="form-control" placeholder="Użytkownik">
  458. <?php endif; ?>
  459. </div>
  460. </div>
  461. </div>
  462. <div class="form-group">
  463. <label for="to" class="col-sm-2 control-label">Wiadomość:</label>
  464. <div class="col-sm-10">
  465. <textarea name="msg" class="form-control"><?php echo htmlspecialchars($msg); ?></textarea>
  466. </div>
  467. </div>
  468. <div class="form-group">
  469. <div class="col-sm-10 col-sm-offset-2">
  470. <input class="btn btn-primary" type="submit" value="Wyślij">
  471. </div>
  472. </div>
  473. </form>
  474. <script>
  475. function selectTblMsgsToType(n) {
  476. var toTypes = <?php echo json_encode(array_keys($listTo)); ?>,
  477. selectedType = n.value
  478. ;
  479. if (-1 !== toTypes.indexOf(n.value)) {
  480. toTypes.forEach(function(type) {
  481. if (type == selectedType) {
  482. document.getElementById('tblMsgsTo-' + type).style.display = 'block';
  483. } else {
  484. document.getElementById('tblMsgsTo-' + type).style.display = 'none';
  485. }
  486. });
  487. }
  488. }
  489. </script>
  490. <?php
  491. }
  492. function typeSpecialUserLoginAction() {
  493. header("Content-type: application/json");
  494. $typeSpecialUserId = TypespecialVariable::getInstance(-1, '__USER_LOGIN');
  495. if (!$typeSpecialUserId) {
  496. $jsonData = new stdClass();
  497. $jsonData->message = "TypeSpecial '__USER_LOGIN' not exists";
  498. echo json_encode($jsonData);
  499. exit;
  500. }
  501. $query = V::get('q', '', $_REQUEST);
  502. $rawRows = null;
  503. $jsonData = array();
  504. $queryParams = array();
  505. $rows = $typeSpecialUserId->getValuesWithExports($query, $queryParams);
  506. foreach ($rows as $kID => $vItem) {
  507. $itemJson = new stdClass();
  508. $itemJson->id = $vItem->id;
  509. $itemJson->name = $vItem->param_out;
  510. if (!empty($vItem->exports)) {
  511. $itemJson->exports = $vItem->exports;
  512. }
  513. $jsonData[] = $itemJson;
  514. }
  515. echo json_encode($jsonData);
  516. }
  517. function typeSpecialGroupIdAction() {
  518. header("Content-type: application/json");
  519. Lib::loadClass('TypespecialVariable');
  520. $typeSpecialZasob = TypespecialVariable::getInstance(-1, '__ZASOB');
  521. if (!$typeSpecialZasob) {
  522. $jsonData = new stdClass();
  523. $jsonData->message = "TypeSpecial '__ZASOB' not exists";
  524. echo json_encode($jsonData);
  525. exit;
  526. }
  527. $query = V::get('q', '', $_REQUEST);
  528. $rawRows = null;
  529. $jsonData = array();
  530. $queryParams = array();
  531. $queryParams['zasob_type_in'] = array('STANOWISKO', 'PODMIOT', 'DZIAL');
  532. $rows = $typeSpecialZasob->getValuesWithExports($query, $queryParams);
  533. DBG::_('DBG_TS', '>1', "rows({$query})", $rows, __CLASS__, __FUNCTION__, __LINE__);
  534. foreach ($rows as $kID => $vItem) {
  535. $itemJson = new stdClass();
  536. $itemJson->id = $vItem->id;
  537. $itemJson->name = $vItem->param_out;
  538. if (!empty($vItem->exports)) {
  539. $itemJson->exports = $vItem->exports;
  540. }
  541. $jsonData[] = $itemJson;
  542. }
  543. echo json_encode($jsonData);
  544. }
  545. function readAction() {
  546. $idMsg = V::get('id', 0, $_GET, 'int');
  547. $usrLogin = V::get('usrLogin', '', $_REQUEST, 'word');
  548. if ($idMsg <= 0) throw new HttpException("Wiadomość nie istnieje!", 404);
  549. if (empty($usrLogin)) throw new HttpException("Błęny user login!", 404);
  550. SE_Layout::gora();
  551. SE_Layout::menu();
  552. try {
  553. $msg = $this->_getMsg($idMsg, $usrLogin);
  554. $this->_markAsRead($msg);
  555. $this->viewMsg($msg);
  556. } catch (Exception $e) {
  557. SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
  558. }
  559. SE_Layout::dol();
  560. }
  561. function viewAction() {
  562. $idMsg = V::get('id', 0, $_GET, 'int');
  563. $usrLogin = V::get('usrLogin', 0, $_REQUEST, 'word');
  564. if ($idMsg <= 0) throw new HttpException("Wiadomość nie istnieje!", 404);
  565. if (empty($usrLogin)) throw new HttpException("Błęny user login", 404);
  566. SE_Layout::gora();
  567. SE_Layout::menu();
  568. try {
  569. $msg = $this->_getMsg($idMsg, $usrLogin);
  570. $this->viewMsg($msg);
  571. } catch (Exception $e) {
  572. SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
  573. }
  574. SE_Layout::dol();
  575. }
  576. function _getMsg($idMsg, $usrLogin) {
  577. $msgsRoute = Router::getRoute('Msgs');
  578. $msg['_raw'] = $msgsRoute->getMessage($idMsg);
  579. if (!$msg['_raw']) throw new HttpException("Wiadomość nie istnieje!", 404);
  580. $msg['usrLogin'] = $usrLogin;
  581. $msg['message'] = $msg['_raw']->msg;
  582. $msg['type'] = $msg['_raw']->msgType;
  583. $msg['_read'] = ('WAITING' != $msg['_raw']->A_STATUS);
  584. // `uiTargetType` enum('default_db_table','default_db_table_record','after_login','everywhere') NOT NULL, // TODO: add namespace, featureID
  585. // $msg['_raw']->uiTargetType => default_db_table_record
  586. // $msg['_raw']->uiTargetName => TEST_PERMS.31
  587. if ('default_db_table_record' !== $msg['_raw']->uiTargetType) {
  588. throw new Exception("Parse message target type error!");
  589. }
  590. $parts = explode('.', $msg['_raw']->uiTargetName);
  591. if (2 !== count($parts)) throw new Exception("Parse message target type error!");
  592. $msg['tblName'] = $parts[0];
  593. $msg['idRow'] = $parts[1];
  594. if (!is_numeric($msg['idRow'])) throw new Exception("Parse message target type - id row type error!");
  595. return $msg;
  596. }
  597. function _markAsRead($msg) {
  598. if ($msg['_read']) return;
  599. $usrLogin = User::getLogin();
  600. $sql = "
  601. update `CRM_UI_MSGS`
  602. set `A_STATUS` = 'NORMAL'
  603. , `A_RECORD_UPDATE_AUTHOR` = '{$usrLogin}'
  604. , `A_RECORD_UPDATE_DATE` = NOW()
  605. , `actionExecutedTime` = NOW()
  606. where `ID`='{$msg['_raw']->ID}'
  607. and `A_STATUS` = 'WAITING'
  608. and `A_RECORD_UPDATE_AUTHOR` = ''
  609. and `A_RECORD_UPDATE_DATE` is null
  610. and (
  611. ('{$usrLogin}' != `A_RECORD_CREATE_AUTHOR`)
  612. or ('{$usrLogin}' = `A_RECORD_CREATE_AUTHOR`
  613. and 'user' = `userTargetType`
  614. and '{$usrLogin}' = `userTargetName`
  615. )
  616. )
  617. ";
  618. try {
  619. DB::getPDO()->execSql($sql);
  620. } catch (Exception $e) {
  621. DBG::log($e);
  622. throw new Exception("Wystąpiły błędy podczas próby zapisu wiadomości: " . $e->getMessage());
  623. }
  624. }
  625. function viewMsg($msg) {
  626. $usrLogin = User::getLogin();
  627. $idTable = 0;
  628. //$rmMsgLink = "{$linkBase}&_task=removeMsg&id={$msg['_raw']->ID}";
  629. $targetNamespace = (!empty($msg['tblName'])) ? "default_db/{$msg['tblName']}" : ""; // default_db/CRM_LISTA_ZASOBOW
  630. $idRow = (!empty($msg['idRow'])) ? $msg['idRow'] : "";
  631. $targetLabel = ($targetNamespace) ? $this->getOutTargetLabel($targetNamespace) : ""; // $tblAcl->getRawLabel()
  632. echo UI::h('div', [ 'class' => "container" ], [
  633. UI::h('h3', [], [
  634. UI::h('i', [ 'class' => "glyphicon glyphicon-envelope" ]),
  635. " ",
  636. UI::h('a', [ 'href' => $this->getLink('', [ 'usrLogin' => $usrLogin ]) ], "Wiadomości {$usrLogin}"),
  637. " &raquo; ",
  638. " Wiadomość nr {$msg['_raw']->ID}",
  639. ($targetNamespace && $idRow)
  640. ? UI::h('small', [ 'style' => "display:block; text-align:right" ], [
  641. UI::h('a', [
  642. 'style' => "font-size:12px; line-height:15px; vertical-align:text-bottom",
  643. 'title' => "Edytuj rekord",
  644. 'href' => "index.php?_route=ViewTableAjax&namespace={$targetNamespace}#EDIT/{$idRow}",
  645. ], [
  646. UI::h('i', [ 'class' => "glyphicon glyphicon-pencil" ]),
  647. " Edytuj rekord {$idRow}",
  648. ]),
  649. UI::h('span', [ 'style' => "font-size:12px; line-height:15px; vertical-align:text-bottom" ], " z tabeli "),
  650. UI::h('a', [
  651. 'style' => "font-size:12px; line-height:15px; vertical-align:text-bottom",
  652. 'href' => "index.php?_route=ViewTableAjax&namespace={$targetNamespace}",
  653. ], $targetLabel),
  654. " ",
  655. $this->printMsgDropdownMenu($msg['_raw']),
  656. ])
  657. : ''
  658. ,
  659. ]),
  660. ]);
  661. $this->printWidgetViewMsg($msg);
  662. }
  663. function getOutTargetLabel($ns) {
  664. try {
  665. $acl = ACL::getAclByNamespace($ns);
  666. return $acl->getRawLabel();
  667. } catch (Exception $e) {
  668. DBG::log($e);
  669. }
  670. return $ns;
  671. }
  672. function printMsgDropdownMenu($rawMsg) {
  673. $isRemoved = ('DELETED' === $rawMsg->A_STATUS || 'OFF_HARD' == $rawMsg->A_STATUS);
  674. return UI::h('div', [ 'class' => "dropdown", 'style' => "display:inline" ], [
  675. UI::h('button', [ 'class' => "btn btn-xs btn-default dropdown-toggle", 'title' => "Message Menu", 'data-toggle' => "dropdown" ], [
  676. UI::h('i', [ 'class' => "glyphicon glyphicon-menu-hamburger" ]),
  677. " Menu",
  678. ]),
  679. UI::h('ul', [ 'class' => "dropdown-menu dropdown-menu-right" ], [
  680. UI::h('li', [], [
  681. ($isRemoved)
  682. ? UI::h('form', [ 'method' => "POST" ], [
  683. UI::h('input', [ 'type' => 'hidden', 'name' => "_postTask", 'value' => "restoreMsg" ]),
  684. UI::h('input', [ 'type' => 'hidden', 'name' => "id", 'value' => $rawMsg->ID ]),
  685. UI::h('button', [ 'type' => "submit", 'class' => "btn btn-link" ], [
  686. UI::h('i', [ 'class' => "glyphicon glyphicon-inbox" ]),
  687. " Przywróć",
  688. ]),
  689. ])
  690. : UI::h('form', [ 'method' => "POST" ], [
  691. UI::h('input', [ 'type' => 'hidden', 'name' => "_postTask", 'value' => "removeMsg" ]),
  692. UI::h('input', [ 'type' => 'hidden', 'name' => "id", 'value' => $rawMsg->ID ]),
  693. UI::h('button', [ 'type' => "submit", 'class' => "btn btn-link", 'style' => "color:red" ], [
  694. UI::h('i', [ 'class' => "glyphicon glyphicon-remove" ]),
  695. " Usuń"
  696. ]),
  697. ])
  698. ,
  699. ]),
  700. ]),
  701. ]);
  702. }
  703. function printWidgetViewMsg($msg) {
  704. $messageList = array();
  705. $uiTargetName = $msg['_raw']->uiTargetName;
  706. $uiTargetType = $msg['_raw']->uiTargetType;
  707. $replyLink = "index.php?_route=UserMsgs&_task=reply&uiTargetName={$uiTargetName}&uiTargetType={$uiTargetType}";
  708. $markAsReadLink = "index.php?_route=UserMsgs&_task=markAsRead";
  709. $message = $this->_convertMessageToJson($msg['_raw']);
  710. {//if ($message->idThread > 0) {
  711. $sqlLimit = 100;
  712. $ds = DB::getDataSource();
  713. $sqlIdThread = ($message->idThread > 0)? $message->idThread : $message->id;
  714. $sql = "
  715. select m.*
  716. from `CRM_UI_MSGS` m
  717. where (m.`idThread` = {$sqlIdThread} or m.`ID` = {$sqlIdThread})
  718. -- and m.`ID` < {$message->id}
  719. order by m.`ID` asc
  720. limit {$sqlLimit}
  721. ";
  722. $moreMsgs = $ds->getListByQuery($sql);
  723. foreach ($moreMsgs as $msg) $messageList[] = $this->_convertMessageToJson($msg);
  724. }
  725. //$messageList[] = $message;
  726. ?>
  727. <link rel="stylesheet" href="./stuff/widget-select.css">
  728. <style type="text/css">
  729. .user_avatar {
  730. display:block;
  731. width:40px;
  732. height:40px;
  733. margin:0 auto 10px auto;
  734. padding:0;
  735. border:1px solid #ddd;
  736. line-height: 38px;
  737. font-size:16px;
  738. text-align:center;
  739. vertical-align:middle;
  740. color:#aaa;
  741. }
  742. </style>
  743. <div id="widget-msg-tree" style="max-width:1000px; margin:0 auto;"></div>
  744. <script src="stuff/vendors.js"></script>
  745. <script src="stuff/bundle.se_route_user_msgs.js"></script>
  746. <script>
  747. var testNewRecordCounter = 0;
  748. jQuery("#widget-msg-tree").MsgThread({
  749. usrLogin: '<?php echo User::getLogin(); ?>',
  750. idThread: <?php echo $message->idThread; ?>,
  751. msgs: <?php echo json_encode($messageList); ?>,
  752. fetchMessages: (function() {
  753. var _msgsXhr = null;
  754. return function(reqData, callback) {
  755. if (_msgsXhr && _msgsXhr.state() === 'pending') {
  756. _msgsXhr.abort();
  757. _msgsXhr = null;
  758. }
  759. _msgsXhr = $.ajax({
  760. url: 'index.php?_route=UserMsgs&_task=getMessagesById&idThread=<?php echo $message->idThread; ?>',
  761. data: reqData,
  762. dataType: 'json'
  763. });
  764. _msgsXhr.done(function(data, textStatus, jqXHR) {
  765. if (data && data.msgs && data.msgs.length > 0) {
  766. callback(null, {msgs: data.msgs});
  767. } else {
  768. callback(null, {msgs: []});//"Error no data!");
  769. }
  770. });
  771. _msgsXhr.fail(function() {
  772. callback(null, {options: []});//"Error no data!");
  773. });
  774. _msgsXhr.always(function() {
  775. _msgsXhr = null;
  776. });
  777. };
  778. })(),
  779. fetchOptionsForGroup: (function() {
  780. var _groupXhr = null;
  781. return function(input, callback) {
  782. if (_groupXhr && _groupXhr.state() === 'pending') {
  783. _groupXhr.abort();
  784. _groupXhr = null;
  785. }
  786. _groupXhr = $.ajax({
  787. url: 'index.php?_route=UserMsgs&_task=typeSpecialGroupId&q=' + input,
  788. dataType: 'json'
  789. });
  790. _groupXhr.done(function(data, textStatus, jqXHR) {
  791. if (data && data.length > 0) {
  792. var options = [];
  793. data.forEach(function(item) {
  794. options.push({value: item.id, label: item.name});
  795. });
  796. callback(null, {options: options});
  797. } else {
  798. callback(null, {options: []});//"Error no data!");
  799. }
  800. });
  801. _groupXhr.fail(function() {
  802. callback(null, {options: []});//"Error no data!");
  803. });
  804. _groupXhr.always(function() {
  805. _groupXhr = null;
  806. });
  807. };
  808. })(),
  809. fetchOptionsForUser: (function() {
  810. var _userXhr = null;
  811. return function(input, callback) {
  812. if (_userXhr && _userXhr.state() === 'pending') {
  813. _userXhr.abort();
  814. _userXhr = null;
  815. }
  816. _userXhr = $.ajax({
  817. url: 'index.php?_route=UserMsgs&_task=typeSpecialUserLogin&q=' + input,
  818. dataType: 'json'
  819. });
  820. _userXhr.done(function(data, textStatus, jqXHR) {
  821. if (data && data.length > 0) {
  822. var options = [];
  823. data.forEach(function(item) {
  824. options.push({value: item.id, label: item.name});
  825. });
  826. callback(null, {options: options});
  827. } else {
  828. callback(null, {options: []});//"Error no data!");
  829. }
  830. });
  831. _userXhr.fail(function() {
  832. callback(null, {options: []});//"Error no data!");
  833. });
  834. _userXhr.always(function() {
  835. _userXhr = null;
  836. });
  837. };
  838. })(),
  839. saveReply: function(data, callback) {
  840. //console.log('#widget-msg-tree/MsgThread::saveReply: data:', data, 'callback', callback);
  841. $.ajax({
  842. url: '<?php echo $replyLink; ?>',
  843. method: 'POST',
  844. data: data,
  845. dataType: 'json'
  846. })
  847. .done(function(data, textStatus, jqXHR) {
  848. var returnData = {message: '', type: 'danger'};
  849. if (data && data.record) {
  850. returnData.msg = data.msg || 'Wysłano wiadomość';
  851. returnData.record = data.record;
  852. returnData.type = 'success';
  853. } else if (data.validateErrors) {
  854. returnData.msg = data.msg || 'Wystąpiły błędy w formularzu';
  855. returnData.type = 'warning';
  856. returnData.validateErrors = data.validateErrors;
  857. } else {
  858. returnData.msg = data.msg || 'Nie udało się wysłać wiadomości!';
  859. returnData.type = 'danger';
  860. }
  861. callback(null, returnData);
  862. })
  863. .fail(function() {
  864. callback(null, {message: 'Nie udało się wysłać wiadomości!', type: 'danger'});
  865. });
  866. },
  867. markAsRead: function(idMsg, callback) {
  868. //console.log('#widget-msg-tree/MsgThread::markAsRead: idMsg:', idMsg);
  869. $.ajax({
  870. url: '<?php echo $markAsReadLink; ?>&idMsg=' + idMsg,
  871. method: 'GET',
  872. dataType: 'json'
  873. })
  874. .done(function(data, textStatus, jqXHR) {
  875. var returnData = {message: '', type: 'danger'};
  876. if (data && data.record) {
  877. returnData.msg = data.msg || 'Oznaczono wiadomość jako odczytaną';
  878. returnData.record = data.record;
  879. returnData.type = 'success';
  880. } else {
  881. returnData.msg = data.msg || 'Nie udało się oznaczyć wiadomości jako odczytanej!';
  882. returnData.type = 'danger';
  883. }
  884. callback(null, returnData);
  885. })
  886. .fail(function() {
  887. callback(null, {message: 'Nie udało się oznaczyć wiadomości jako odczytanej!', type: 'danger'});
  888. });
  889. },
  890. dbg: false
  891. });
  892. // jQuery("#widget-msg-tree").on('change', function(e, data) {
  893. // console.log('#widget-msg-tree/MsgThread::onChange: data:', data);
  894. // });
  895. </script>
  896. <?php
  897. }
  898. function _convertMessageToJson($rawMsg) {
  899. /* $msg = {_raw: {A_RECORD_CREATE_AUTHOR: "plabudda",
  900. A_RECORD_CREATE_DATE: "2015-10-26 12:20:05",
  901. A_RECORD_DELETE_AUTHOR: "",
  902. A_RECORD_DELETE_DATE: null,
  903. A_RECORD_UPDATE_AUTHOR: "plabudda",
  904. A_RECORD_UPDATE_DATE: "2015-11-02 12:44:59",
  905. A_STATUS: "NORMAL",
  906. ID: "67",
  907. actionExecutedTime: "2015-11-02 12:44:59",
  908. actionNotes: "",
  909. app_className: "TableMsgs",
  910. msg: "test Y",
  911. msgType: "info",
  912. uiTargetName: "TEST_PERMS.31",
  913. uiTargetType: "default_db_table_record",
  914. userTargetName: "plabudda",
  915. userTargetType: "user"}
  916. _read: true,
  917. idRow: "31",
  918. message: "test Y",
  919. tblName: "TEST_PERMS",
  920. type: "info",
  921. usrLogin: "plabudda"} */
  922. $usrLogin = User::getLogin();
  923. $message = new stdClass();
  924. $message->id = $rawMsg->ID;
  925. $message->idThread = $rawMsg->idThread;// TODO: ID_THREAD
  926. $message->idReplyTo = $rawMsg->idReplyTo;// TODO: ID_REPLY_TO
  927. $message->message = $rawMsg->msg;
  928. $message->type = $rawMsg->msgType;
  929. $message->to = $rawMsg->userTargetName;
  930. $message->toType = $rawMsg->userTargetType;
  931. $message->author = $rawMsg->A_RECORD_CREATE_AUTHOR;
  932. $message->created = $rawMsg->A_RECORD_CREATE_DATE;
  933. $message->_read = ('WAITING' != $rawMsg->A_STATUS);
  934. $message->_readByUser = ('WAITING' != $rawMsg->A_STATUS);
  935. if ('WAITING' == $rawMsg->A_STATUS
  936. && $usrLogin == $rawMsg->A_RECORD_CREATE_AUTHOR) {
  937. if ('user' == $rawMsg->userTargetType
  938. && $usrLogin == $rawMsg->userTargetName) {
  939. $message->_readByUser = false;
  940. } else {
  941. $message->_readByUser = true;
  942. }
  943. }
  944. if ($message->_read) {
  945. if (!empty($rawMsg->A_RECORD_UPDATE_DATE)) $message->_readDate = $rawMsg->A_RECORD_UPDATE_DATE;
  946. if (!empty($rawMsg->A_RECORD_UPDATE_AUTHOR)) $message->_readBy = $rawMsg->A_RECORD_UPDATE_AUTHOR;
  947. }
  948. return $message;
  949. }
  950. function getMessagesByIdAction() {
  951. try {
  952. $idThread = V::get('idThread', '', $_GET, 'int');
  953. $idLastMsg = V::get('idLastMsg', '', $_GET, 'int');
  954. if ($idThread <= 0) throw new Exception("Wrong param id!");
  955. $sqlLimit = 10;// TODO: 100?
  956. $ds = DB::getDataSource();
  957. $sql = "
  958. select m.*
  959. from `CRM_UI_MSGS` m
  960. where m.`idThread` = {$idThread}
  961. and m.`ID` > {$idLastMsg}
  962. order by m.`ID` asc
  963. limit {$sqlLimit}
  964. ";
  965. $moreMsgs = $ds->getListByQuery($sql);
  966. $response = new stdClass();
  967. $response->msg = "Nowe wiadomości";
  968. $response->type = 'success';
  969. $response->msgs = array();
  970. foreach ($moreMsgs as $msg) {
  971. $response->msgs[] = $this->_convertMessageToJson($msg);
  972. }
  973. } catch (Exception $e) {
  974. $response = new stdClass();
  975. $response->msg = "Wystąpiły błędy: " . $e->getMessage();
  976. $response->type = 'danger';
  977. }
  978. echo json_encode($response);
  979. }
  980. function replyAction() {
  981. try {
  982. $uiTargetType = V::get('uiTargetType', '', $_GET);
  983. $uiTargetName = V::get('uiTargetName', '', $_GET);
  984. $response = $this->_reply($uiTargetType, $uiTargetName, $_POST);
  985. } catch (Exception $e) {
  986. $response = new stdClass();
  987. $response->msg = "Wystąpiły błędy: " . $e->getMessage();
  988. $response->type = 'danger';
  989. }
  990. echo json_encode($response);
  991. }
  992. function markAsReadAction() {
  993. $usrLogin = User::getLogin();
  994. try {
  995. $idMsg = V::get('idMsg', '', $_GET, 'int');
  996. $msg = $this->_getMsg($idMsg, $usrLogin);
  997. $this->_markAsRead($msg);
  998. $response = new stdClass();
  999. //$response->msg = "";
  1000. $response->type = "success";
  1001. $msg = $this->_getMsg($idMsg, $usrLogin);
  1002. $response->record = $this->_convertMessageToJson($msg['_raw']);
  1003. } catch (Exception $e) {
  1004. $response = new stdClass();
  1005. $response->msg = "Wystąpiły błędy: " . $e->getMessage();
  1006. $response->type = 'danger';
  1007. }
  1008. echo json_encode($response);
  1009. }
  1010. function _reply($uiTargetType, $uiTargetName, $args) {
  1011. $ds = DB::getDataSource();
  1012. $newMsg = array();
  1013. $newMsg['idReplyTo'] = V::get('idReplyTo', '', $args, 'int');
  1014. $newMsg['msg'] = V::get('message', '', $args);
  1015. $newMsg['msgType'] = V::get('msgType', 'info', $args);
  1016. $newMsg['userTargetType'] = V::get('toType', '', $args);
  1017. $newMsg['userTargetName'] = V::get('to', '', $args);
  1018. $newMsg['A_RECORD_CREATE_DATE'] = 'NOW()';
  1019. $newMsg['A_RECORD_CREATE_AUTHOR'] = User::getLogin();
  1020. $newMsg['app_className'] = 'TableMsgs';
  1021. //DBG::_(true, true, "newMsg", $newMsg, __CLASS__, __FUNCTION__, __LINE__);
  1022. if ($newMsg['idReplyTo'] <= 0) throw new Exception("Wrong id reply to msg");
  1023. $parentMsg = $ds->getById('CRM_UI_MSGS', $newMsg['idReplyTo']);
  1024. if (!$parentMsg) throw new Exception("Nie znaleziono wiadomości");
  1025. $newMsg['idThread'] = ($parentMsg->idThread > 0)? $parentMsg->idThread : $parentMsg->ID;
  1026. $newMsg['uiTargetType'] = $uiTargetType;// TODO:? $parentMsg->uiTargetType
  1027. $newMsg['uiTargetName'] = $uiTargetName;// TODO:? $parentMsg->uiTargetName
  1028. $insertedId = $ds->insert('CRM_UI_MSGS', $newMsg);
  1029. if (!$insertedId) throw new Exception("Nie udało się utworzyć rekordu");
  1030. $msgAdded = $ds->getById('CRM_UI_MSGS', $insertedId);
  1031. $response = new stdClass();
  1032. $response->msg = "Wysłano wiadomość";
  1033. $response->type = 'success';
  1034. $response->record = $this->_convertMessageToJson($msgAdded);
  1035. return $response;
  1036. }
  1037. function removeMsgAction() {
  1038. $idMsg = V::get('id', 0, $_GET, 'int');
  1039. $usrLogin = V::get('usrLogin', 0, $_REQUEST, 'word');
  1040. if ($idMsg <= 0) throw new HttpException("Wiadomość nie istnieje!", 404);
  1041. if (empty($usrLogin)) throw new HttpException("Błęny user login", 404);
  1042. SE_Layout::gora();
  1043. SE_Layout::menu();
  1044. try {
  1045. $msg = $this->_getMsg($idMsg, $usrLogin);
  1046. $msgsRoute = Router::getRoute('Msgs');
  1047. $msgsRoute->removeTableRecordMsg($idMsg);
  1048. } catch (Exception $e) {
  1049. SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
  1050. SE_Layout::dol();
  1051. exit;
  1052. }
  1053. ?>
  1054. <div class="container">
  1055. <div class="alert alert-success">
  1056. Wiadomość została usunięta <a class="btn btn-xs btn-default" href="index.php?_route=UserMsgs&usrLogin=<?php echo $usrLogin; ?>">wróć</a>
  1057. </div>
  1058. </div>
  1059. <?php
  1060. SE_Layout::dol();
  1061. }
  1062. function removeMsgPostTask($args) {
  1063. try {
  1064. $id = V::get('id', 0, $args, 'int');
  1065. if ($id <= 0) throw new AlertDangerException("Missing message id!");
  1066. $usrLogin = V::get('usrLogin', User::getLogin(), $_REQUEST, 'word');
  1067. $msg = $this->_getMsg($id, $usrLogin);
  1068. $isRemoved = ('DELETED' === $msg['_raw']->A_STATUS || 'OFF_HARD' == $msg['_raw']->A_STATUS);
  1069. if ($isRemoved) throw new AlertInfoException("Wiadomość nr {$id} została usunięta wcześniej");
  1070. Router::getRoute('Msgs')->removeTableRecordMsg($id);
  1071. throw new AlertInfoException("Usunięto wiadomość nr {$id}"); // TODO: przywróć btn require global post task class
  1072. } catch (Exception $e) {
  1073. DBG::log($e);
  1074. S::saveUserMessage(get_class($e), $e->getMessage());
  1075. }
  1076. }
  1077. function restoreMsgPostTask($args) {
  1078. try {
  1079. $id = V::get('id', 0, $args, 'int');
  1080. if ($id <= 0) throw new AlertDangerException("Missing message id!");
  1081. $usrLogin = V::get('usrLogin', User::getLogin(), $_REQUEST, 'word');
  1082. $msg = $this->_getMsg($id, $usrLogin);
  1083. $isRemoved = ('DELETED' === $msg['_raw']->A_STATUS || 'OFF_HARD' == $msg['_raw']->A_STATUS);
  1084. if (!$isRemoved) throw new AlertInfoException("Wiadomość nr {$id} nie jest usunięta");
  1085. Router::getRoute('Msgs')->restoreTableRecordMsg($id);
  1086. throw new AlertInfoException("Przywrócono wiadomość nr {$id}"); // TODO: przywróć btn require global post task class
  1087. } catch (Exception $e) {
  1088. DBG::log($e);
  1089. S::saveUserMessage(get_class($e), $e->getMessage());
  1090. }
  1091. }
  1092. }