UserMsgs.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. <?php
  2. Lib::loadClass('Router');
  3. Lib::loadClass('RouteBase');
  4. Lib::loadClass('TypespecialVariable');
  5. Lib::loadClass('ProcesHelper');
  6. class Route_UserMsgs extends RouteBase {
  7. var $_listLimit = 20;
  8. public function handleAuth() {
  9. if (!User::logged()) {
  10. User::authByRequest();
  11. }
  12. }
  13. public function defaultAction() {
  14. SE_Layout::gora();
  15. SE_Layout::menu();
  16. try {
  17. $usrLogin = User::getLogin();
  18. //$this->menu();
  19. $this->userMsgs($usrLogin);
  20. } catch (Exception $e) {
  21. SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
  22. }
  23. SE_Layout::dol();
  24. }
  25. public function menu() {
  26. $usrLogin = User::getLogin();
  27. ?>
  28. <ul>
  29. <li>TODO: ...</li>
  30. </ul>
  31. <?php
  32. }
  33. public function userMsgs($usrLogin) {
  34. $msgsList = $this->getMsgs('inbox', $usrLogin);
  35. $totalReadMsgs = 0;
  36. $totalUnreadMsgs = 0;
  37. foreach ($msgsList as $ind => $msg) {
  38. if ($msg['_read']) {
  39. $totalReadMsgs++;
  40. } else {
  41. $totalUnreadMsgs++;
  42. }
  43. }
  44. $sentMsgsList = $this->getMsgs('sent', $usrLogin);
  45. $removedMsgsList = $this->getMsgs('removed', $usrLogin);
  46. ?>
  47. <style type="text/css">
  48. .tblMsgsListItem { cursor:pointer; }
  49. </style>
  50. <div class="container">
  51. <h3><i class="glyphicon glyphicon-envelope"></i> Wiadomości <code><?php echo $usrLogin; ?></code></h3>
  52. <div>
  53. <ul class="nav nav-tabs" role="tablist">
  54. <!--
  55. <li>
  56. <a href="#tbl-msgs-compose"><i class="glyphicon glyphicon-plus"></i> Nowa wiadomość</a>
  57. </li>
  58. -->
  59. <li role="presentation" class="active"><a href="#odebrane" aria-controls="odebrane" role="tab" data-toggle="tab">Odebrane <em>(<?php echo $totalUnreadMsgs; ?>)</em></a></li>
  60. <li role="presentation"><a href="#wyslane" aria-controls="wyslane" role="tab" data-toggle="tab">Wysłane</em></a></li>
  61. <li role="presentation"><a href="#kosz" aria-controls="kosz" role="tab" data-toggle="tab">Kosz</em></a></li>
  62. </ul>
  63. <div class="tab-content" style="margin-bottom:15px">
  64. <div role="tabpanel" class="tab-pane active" id="odebrane" style="border-style:none solid solid solid; border-width:1px; border-color:#ddd;">
  65. <?php $this->_printUserMsgsList('inbox', $msgsList, $usrLogin); ?>
  66. </div>
  67. <div role="tabpanel" class="tab-pane" id="wyslane" style="border-style:none solid solid solid; border-width:1px; border-color:#ddd;">
  68. <?php $this->_printUserMsgsList('sent', $sentMsgsList, $usrLogin); ?>
  69. </div>
  70. <div role="tabpanel" class="tab-pane" id="kosz" style="border-style:none solid solid solid; border-width:1px; border-color:#ddd;">
  71. <?php $this->_printUserMsgsList('removed', $removedMsgsList, $usrLogin); ?>
  72. </div>
  73. </div>
  74. </div>
  75. <!--
  76. <div class="panel panel-default" id="tbl-msgs-compose">
  77. <div class="panel-heading">Wyślij nową wiadomość</div>
  78. <div class="panel-body">
  79. <?php if (!empty($arrorsList)) : ?>
  80. <?php foreach ($arrorsList as $errMsg) : ?>
  81. <div class="alert alert-danger"><?php echo $errMsg; ?></div>
  82. <?php endforeach; ?>
  83. <?php endif; ?>
  84. <?php $this->_printMsgForm($args); ?>
  85. </div>
  86. </div>
  87. -->
  88. </div>
  89. <script>
  90. function tblMsgsLoadMoreRows(n) {
  91. var nNode = jQuery(n),
  92. lastMsgId = nNode.data('last_msg_id'),
  93. listType = nNode.data('list_type')
  94. ;
  95. nNode.blur();
  96. function tblMsgsSetNoMoreRows(btnLoadMoreNode) {
  97. btnLoadMoreNode.closest('td').css({color:'silver'}).html('Brak starszych wiadomości');
  98. }
  99. if (lastMsgId <= 0) {
  100. tblMsgsSetNoMoreRows(nNode);
  101. }
  102. function tblMsgsAddMsgToList(msg, btnLoadMoreNode, listType) {
  103. var tbodyNode = btnLoadMoreNode.closest('tfoot').prev('tbody'),
  104. trNode = jQuery('<tr></tr>'),
  105. tdIdNode = jQuery('<td></td>'),
  106. tdMsgNode = jQuery('<td></td>'),
  107. tdDateNode = jQuery('<td style="white-space:nowrap;"></td>'),
  108. actionTask = (listType == 'inbox')? 'read' : 'view',
  109. msgLink = ''
  110. ;
  111. trNode.addClass('tblMsgsListItem');
  112. if (msg['_read']) trNode.addClass('active');
  113. if ('read' === actionTask || 'view' === actionTask) {
  114. msgLink = '<?php echo Request::getPathUri() . 'index.php?_route=UserMsgs'; ?>';
  115. msgLink += '&usrLogin=<?php echo $usrLogin; ?>';
  116. msgLink += '&id=' + msg['_raw']['ID'];
  117. msgLink += '&_task=' + actionTask;
  118. trNode.attr('onclick', "window.location.href='" + msgLink + "'");
  119. }
  120. tdIdNode.append(msg['_raw']['ID']);
  121. tdIdNode.appendTo(trNode);
  122. tdMsgNode.append('<div style="overflow:hidden; white-space:nowrap; text-overflow:ellipsis;">' + msg['message'] + '</div>');
  123. msgMetaInfo = 'od ' + msg['_raw']['A_RECORD_CREATE_AUTHOR'] + ' do ';
  124. if ('everyone' == msg['_raw']['userTargetType']) {
  125. msgMetaInfo += 'wszystkich';
  126. } else if ('user' == msg['_raw']['userTargetType']) {
  127. msgMetaInfo += msg['_raw']['userTargetName'];
  128. } else if ('group' == msg['_raw']['userTargetType']) {
  129. msgMetaInfo += 'grupy ' + msg['_raw']['userTargetName'];
  130. }
  131. tdMsgNode.append('<div class="text-muted" style="font-style:italic;">' + msgMetaInfo + '</div>');
  132. tdMsgNode.appendTo(trNode);
  133. tdDateNode.append(msg['_raw']['A_RECORD_CREATE_DATE']);
  134. if (msg['_readDate']) {
  135. tdDateNode.append('<div class="text-muted" style="font-style:italic" title="Przeczytano ' + msg['_readDate'] + '">' + msg['_readDate'] + '</div>');
  136. } else {
  137. tdDateNode.append('<div class="text-muted" style="font-style:italic" title="Wiadomość nie została jeszcze odczytana">nieodczytana</div>');
  138. }
  139. tdDateNode.appendTo(trNode);
  140. trNode.hide();
  141. trNode.appendTo(tbodyNode);
  142. trNode.show('slow');
  143. };
  144. jQuery.ajax({
  145. data: {},
  146. dataType: 'json',
  147. type: "POST",
  148. url: 'index.php?_route=UserMsgs&_task=loadMoreRows&listType=' + listType + '&lastMsgId=' + lastMsgId + '&usrLogin=<?php echo $usrLogin; ?>'
  149. })
  150. .done(function(data, textStatus, jqXHR) {
  151. var listLimit = <?php echo $this->_listLimit; ?>,
  152. i = 0,
  153. lastMsgId = 0,
  154. hasMore = false
  155. ;
  156. if (!data || !data.msgs || !data.keysOrder) {
  157. jQuery.notify('Wystąpiły błędy podczas pobierania listy wiadomości', 'error');
  158. return false;
  159. }
  160. data.keysOrder.forEach(function(key) {
  161. if (i < listLimit) {
  162. lastMsgId = key;
  163. tblMsgsAddMsgToList(data.msgs[key], nNode, listType);
  164. } else {
  165. hasMore = true;
  166. }
  167. i++;
  168. });
  169. if (!hasMore) {
  170. tblMsgsSetNoMoreRows(nNode);
  171. }
  172. nNode.data('last_msg_id', lastMsgId);
  173. })
  174. .fail(function(jqXHR) {
  175. if (jqXHR.responseJSON) {
  176. jQuery.notify('Nie udało się pobrać listy wiadomości', 'error');
  177. }
  178. else {
  179. var txt = jqXHR.responseText || 'Nie udało się pobrać listy wiadomości';
  180. if (jqXHR.status == 404) {
  181. jQuery.notify(jqXHR.responseText, 'error');
  182. } else {
  183. jQuery.notify(jqXHR.responseText, 'warn');
  184. }
  185. }
  186. });
  187. }
  188. </script>
  189. <?php
  190. //DBG::_(true, true, "_POST", $_POST, __CLASS__, __FUNCTION__, __LINE__);
  191. //DBG::_(true, true, "tblAcl", $tblAcl, __CLASS__, __FUNCTION__, __LINE__);
  192. //DBG::_(true, true, "record", $record, __CLASS__, __FUNCTION__, __LINE__);
  193. //DBG::_(true, true, "msgsList", $msgsList, __CLASS__, __FUNCTION__, __LINE__);
  194. //throw new Exception("TODO: ...");
  195. }
  196. public function loadMoreRowsAction() {
  197. $usrLogin = V::get('usrLogin', '', $_GET, 'word');
  198. $lastMsgId = V::get('lastMsgId', 0, $_GET, 'int');
  199. $listType = V::get('listType', '', $_GET, 'word');
  200. if (!$usrLogin) throw new HttpException("Wrong param login", 404);
  201. if ($lastMsgId <= 0) throw new HttpException("Wrong param lastMsgId", 404);
  202. if (!in_array($listType, array('inbox','sent','removed'))) throw new HttpException("Wrong param listType", 404);
  203. $resultData = new stdClass();
  204. $resultData->msgs = $this->getMsgs($listType, $usrLogin, $lastMsgId);
  205. $resultData->keysOrder = array_keys($resultData->msgs);
  206. echo json_encode($resultData);
  207. }
  208. public function _printUserMsgsList($listType, $msgsList, $usrLogin) {
  209. $msgsTotal = count($msgsList);
  210. $listLimit = $this->_listLimit;
  211. $lastMsgId = 0;
  212. $actionTask = ($listType == 'inbox')? 'read' : 'view';
  213. ?>
  214. <table class="tblMsgsList table table-hovered" style="margin-bottom:0; table-layout:fixed;">
  215. <thead>
  216. <tr>
  217. <th style="width:60px">#</th>
  218. <th>wiadomość</th>
  219. <th style="width:130px">data</th>
  220. </tr>
  221. </thead>
  222. <tbody>
  223. <?php if ($msgsTotal <= 0) : ?>
  224. <tr>
  225. <td colspan="3"><em class="text-muted" style="padding-left:60px;">Brak wiadomości</em></td>
  226. </tr>
  227. <?php else : ?>
  228. <?php $i = 0; foreach ($msgsList as $idMsg => $msg) : $i++; if ($i > $listLimit) break; $lastMsgId = $idMsg; ?>
  229. <?php
  230. $onClick = '';
  231. $msgLink = Request::getPathUri() . 'index.php?_route=UserMsgs&id=' . $msg['_raw']->ID;
  232. $msgLink .= "&usrLogin={$usrLogin}";
  233. if ('read' == $actionTask || 'view' == $actionTask) {
  234. $msgLink .= '&_task=' . $actionTask;
  235. } else {
  236. $msgLink = null;
  237. }
  238. if ($msgLink) {
  239. $jsOnClick = "window.location.href='{$msgLink}'";
  240. $onClick = 'onclick="' . $jsOnClick . '"';
  241. }
  242. ?>
  243. <tr <?php echo $onClick; ?>
  244. class="tblMsgsListItem <?php echo ($msg['_read'])? 'active' : ''; ?>">
  245. <td><?php echo $msg['_raw']->ID; ?></td>
  246. <td>
  247. <div style="overflow:hidden; white-space:nowrap; text-overflow:ellipsis;"><?php echo htmlspecialchars($msg['message']); ?></div>
  248. <div class="text-muted" style="font-style:italic;">
  249. od <?php echo $msg['_raw']->A_RECORD_CREATE_AUTHOR; ?> do <?php
  250. if ('everyone' == $msg['_raw']->userTargetType) {
  251. echo "wszystkich";
  252. } else if ('user' == $msg['_raw']->userTargetType) {
  253. echo "{$msg['_raw']->userTargetName}";
  254. } else if ('group' == $msg['_raw']->userTargetType) {
  255. echo "grupy {$msg['_raw']->userTargetName}";
  256. }
  257. ?>
  258. </div>
  259. </td>
  260. <td style="white-space:nowrap;">
  261. <?php echo $msg['_raw']->A_RECORD_CREATE_DATE; ?>
  262. <?php if ($msg['_readDate']) : ?>
  263. <div class="text-muted" style="font-style:italic" title="Przeczytano <?php echo $msg['_readDate']; ?>"><?php echo $msg['_readDate']; ?></div>
  264. <?php else : ?>
  265. <div class="text-muted" style="font-style:italic" title="Wiadomość nie została jeszcze odczytana">nieodczytana</div>
  266. <?php endif; ?>
  267. </td>
  268. </tr>
  269. <?php endforeach; ?>
  270. <?php endif; ?>
  271. </tbody>
  272. <tfoot>
  273. <?php if ($msgsTotal > $listLimit) : ?>
  274. <tr class="active">
  275. <td colspan="3" style="text-align:center">
  276. <button class="btn btn-link"
  277. data-last_msg_id="<?php echo $lastMsgId; ?>"
  278. data-list_type="<?php echo $listType; ?>"
  279. onclick="return tblMsgsLoadMoreRows(this);">pobierz starsze wiadomości ...</button>
  280. </td>
  281. </tr>
  282. <?php endif; ?>
  283. </tfoot>
  284. </table>
  285. <?php
  286. }
  287. public function getMsgs($filterType, $usrLogin, $lastMsgId = null) {
  288. $lastMsgId = (int)$lastMsgId;
  289. $msgsRoute = Router::getRoute('Msgs');
  290. $msgsList = array();
  291. if (empty($usrLogin)) throw new Exception("No user login!");
  292. $sqlWhereAddFilter = "";
  293. {// TODO: fetch groups ids for another user - $usrLogin
  294. $usrLogin = User::getLogin();
  295. $userGroupIds = User::getGroupsIds();
  296. }
  297. $sqlFilerMsgsForUser = "
  298. m.`userTargetType` in('everyone')
  299. or (m.`userTargetType`='user' and m.`userTargetName`='{$usrLogin}')
  300. or (m.`userTargetType`='group' and m.`userTargetName` in(" . implode(",", $userGroupIds) . "))
  301. ";
  302. switch ($filterType) {
  303. case 'inbox':
  304. $sqlWhereAddFilter = "
  305. and ({$sqlFilerMsgsForUser})
  306. and m.`A_STATUS` in('WAITING', 'NORMAL')
  307. ";
  308. break;
  309. case 'unread':
  310. $sqlWhereAddFilter = "
  311. and ({$sqlFilerMsgsForUser})
  312. and m.`A_STATUS` in('WAITING')
  313. ";
  314. break;
  315. case 'sent':
  316. $sqlWhereAddFilter = "
  317. and m.`A_RECORD_CREATE_AUTHOR`='{$usrLogin}'
  318. and (m.`A_STATUS` in('WAITING', 'NORMAL')
  319. or (m.`A_STATUS`='OFF_HARD' and m.`A_RECORD_DELETE_AUTHOR`!='{$usrLogin}')
  320. )
  321. ";
  322. break;
  323. case 'removed':
  324. $sqlWhereAddFilter = "
  325. and (m.`A_RECORD_CREATE_AUTHOR`='{$usrLogin}'
  326. or ({$sqlFilerMsgsForUser})
  327. )
  328. and m.`A_STATUS` in('OFF_HARD', 'DELETED')
  329. ";
  330. break;
  331. default: throw new Exception("Unknown filter type");
  332. }
  333. $db = DB::getDB();
  334. $tableName = $db->_($tableName);
  335. if ($lastMsgId > 0) {
  336. $sqlWhereAddFilter .= "\n and m.`ID`<{$lastMsgId}";
  337. }
  338. $sqlLimit = $this->_listLimit + 1;
  339. $sql = "select m.*
  340. from `CRM_UI_MSGS` m
  341. where m.`uiTargetType`='default_db_table_record'
  342. -- and m.`uiTargetName`='{$tableName}.{$idRow}'
  343. {$sqlWhereAddFilter}
  344. order by m.`ID` DESC
  345. limit {$sqlLimit}
  346. ";
  347. //DBG::_('DBG_MSGS', '>1', "sql", $sql, __CLASS__, __FUNCTION__, __LINE__);
  348. $db = DB::getDB();
  349. $res = $db->query($sql);
  350. while ($r = $db->fetch($res)) {
  351. $msg['message'] = $r->msg;
  352. $msg['type'] = $r->msgType;
  353. $msg['_raw'] = $r;
  354. $msg['_read'] = ('WAITING' != $r->A_STATUS);
  355. $msg['_readDate'] = $r->actionExecutedTime;
  356. $msgsList[$r->ID] = $msg;
  357. }
  358. return $msgsList;
  359. }
  360. public function _validate($args) {
  361. $toType = V::get('to_type', '', $args);
  362. $to = V::get('to', '', $args);
  363. $msg = V::get('msg', '', $args);
  364. if (!in_array($toType, array('everyone', 'user', 'group'))) {
  365. throw new Exception("Niedozwolony typ odbiorcy");
  366. }
  367. if (empty($to) && 'everyone' != $toType) {
  368. throw new Exception("Proszę podać odbiorcę wiadomości");
  369. }
  370. if (empty($msg)) {
  371. throw new Exception("Proszę podać treść wiadomości");
  372. }
  373. }
  374. public function _create($args, $tableName, $idRow) {
  375. $toType = V::get('to_type', '', $args);
  376. $to = V::get('to', '', $args);
  377. $msg = V::get('msg', '', $args);
  378. $usrLogin = User::getLogin();
  379. $db = DB::getDB();
  380. if (!$db) throw new Exception("Brak dazy danych!");
  381. if ($db->has_errors()) throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  382. $item = array();
  383. $item['`uiTargetType`'] = "'default_db_table_record'";
  384. $item['`uiTargetName`'] = "'{$tableName}.{$idRow}'";
  385. $item['`userTargetType`'] = "'{$toType}'";
  386. $item['`userTargetName`'] = "'{$to}'";
  387. $item['`msg`'] = "'" . $db->_($msg) . "'";
  388. $item['`A_RECORD_CREATE_DATE`'] = "NOW()";
  389. $item['`A_RECORD_CREATE_AUTHOR`'] = "'{$usrLogin}'";
  390. $item['`A_STATUS`'] = "'WAITING'";
  391. $item['`app_className`'] = "'TableMsgs'";
  392. $sql = "insert into `CRM_UI_MSGS` (" . implode(",", array_keys($item)) . ")
  393. values (" . implode(",", array_values($item)) . ")
  394. ";
  395. $res = $db->query($sql);
  396. 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()));
  397. $createdId = $db->insert_id();
  398. if ($createdId <= 0) throw new Exception("Nie udało się zapisać wiadomości.");
  399. return $createdId;
  400. }
  401. public 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. public 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. public 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. public 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. public 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. public 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. // $msg['_raw']->uiTargetType => default_db_table_record
  585. // $msg['_raw']->uiTargetName => TEST_PERMS.31
  586. if ('default_db_table_record' !== $msg['_raw']->uiTargetType) {
  587. throw new Exception("Parse message target type error!");
  588. }
  589. $parts = explode('.', $msg['_raw']->uiTargetName);
  590. if (2 !== count($parts)) throw new Exception("Parse message target type error!");
  591. $msg['tblName'] = $parts[0];
  592. $msg['idRow'] = $parts[1];
  593. if (!is_numeric($msg['idRow'])) throw new Exception("Parse message target type - id row type error!");
  594. return $msg;
  595. }
  596. public function _markAsRead($msg) {
  597. if ($msg['_read']) return;
  598. $usrLogin = User::getLogin();
  599. $db = DB::getDB();
  600. if (!$db) throw new Exception("Brak dazy danych!");
  601. if ($db->has_errors()) throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  602. $sql = "update `CRM_UI_MSGS`
  603. set `A_STATUS`='NORMAL'
  604. , `A_RECORD_UPDATE_AUTHOR`='{$usrLogin}'
  605. , `A_RECORD_UPDATE_DATE`=NOW()
  606. , `actionExecutedTime`=NOW()
  607. where `ID`='{$msg['_raw']->ID}'
  608. and `A_STATUS`='WAITING'
  609. and `A_RECORD_UPDATE_AUTHOR`=''
  610. and `A_RECORD_UPDATE_DATE` is null
  611. and (
  612. ('{$usrLogin}'!=`A_RECORD_CREATE_AUTHOR`)
  613. or ('{$usrLogin}'=`A_RECORD_CREATE_AUTHOR`
  614. and 'user'=`userTargetType`
  615. and '{$usrLogin}'=`userTargetName`
  616. )
  617. )
  618. ";
  619. $res = $db->query($sql);
  620. 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()));
  621. }
  622. public function viewMsg($msg) {
  623. $usrLogin = User::getLogin();
  624. $idTable = 0;
  625. if (!empty($msg['tblName'])) {
  626. $tblName = $msg['tblName'];
  627. $idTable = ProcesHelper::getZasobTableID($tblName);
  628. if (!$idTable) throw new Exception("Nie udało się odnaleźć nr tabeli '{$tblName}'");
  629. $idRow = $msg['idRow'];
  630. if (!$idRow) throw new Exception("Brak numeru powiązanego rekordu!");
  631. $usrAcl = User::getAcl();
  632. $tblAcl = $usrAcl->getTableAcl($idTable);
  633. }
  634. $linkBase = "index.php?_route=UserMsgs";
  635. $linkBase .= "&usrLogin={$usrLogin}";
  636. //$rmMsgLink = "{$linkBase}&_task=removeMsg&id={$msg['_raw']->ID}";
  637. $backLink = "{$linkBase}";
  638. ?>
  639. <div class="container">
  640. <h3><i class="glyphicon glyphicon-envelope"></i> <a href="<?php echo $backLink; ?>">Wiadomości <?php echo $usrLogin; ?></a>
  641. &raquo; Wiadomość nr <?php echo $msg['_raw']->ID; ?>
  642. <?php if ($idTable > 0) : ?>
  643. <!-- <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>
  644. z tabeli <a href="index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $idTable; ?>"><?php echo $tblAcl->getLabel(); ?></a>
  645. </small>
  646. -->
  647. <small style="display:block; text-align:right">
  648. <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>
  649. <span style="font-size:12px; line-height:15px; vertical-align:text-bottom;">z tabeli</span>
  650. <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>
  651. </small>
  652. <?php endif; ?>
  653. </h3>
  654. </div>
  655. <?php $this->printWidgetViewMsg($msg); ?>
  656. <?php
  657. }
  658. public function printWidgetViewMsg($msg) {
  659. $messageList = array();
  660. $uiTargetName = $msg['_raw']->uiTargetName;
  661. $uiTargetType = $msg['_raw']->uiTargetType;
  662. $replyLink = "index.php?_route=UserMsgs&_task=reply&uiTargetName={$uiTargetName}&uiTargetType={$uiTargetType}";
  663. $markAsReadLink = "index.php?_route=UserMsgs&_task=markAsRead";
  664. $message = $this->_convertMessageToJson($msg['_raw']);
  665. {//if ($message->idThread > 0) {
  666. $sqlLimit = 100;
  667. $ds = DB::getDataSource();
  668. $sqlIdThread = ($message->idThread > 0)? $message->idThread : $message->id;
  669. $sql = "
  670. select m.*
  671. from `CRM_UI_MSGS` m
  672. where (m.`idThread` = {$sqlIdThread} or m.`ID` = {$sqlIdThread})
  673. -- and m.`ID` < {$message->id}
  674. order by m.`ID` asc
  675. limit {$sqlLimit}
  676. ";
  677. $moreMsgs = $ds->getListByQuery($sql);
  678. foreach ($moreMsgs as $msg) $messageList[] = $this->_convertMessageToJson($msg);
  679. }
  680. //$messageList[] = $message;
  681. ?>
  682. <link rel="stylesheet" href="./stuff/widget-select.css">
  683. <style type="text/css">
  684. .user_avatar {
  685. display:block;
  686. width:40px;
  687. height:40px;
  688. margin:0 auto 10px auto;
  689. padding:0;
  690. border:1px solid #ddd;
  691. line-height: 38px;
  692. font-size:16px;
  693. text-align:center;
  694. vertical-align:middle;
  695. color:#aaa;
  696. }
  697. </style>
  698. <div id="widget-msg-tree" style="max-width:1000px; margin:0 auto;"></div>
  699. <script src="stuff/vendors.js"></script>
  700. <script src="stuff/bundle.se_route_user_msgs.js"></script>
  701. <script>
  702. var testNewRecordCounter = 0;
  703. jQuery("#widget-msg-tree").MsgThread({
  704. usrLogin: '<?php echo User::getLogin(); ?>',
  705. idThread: <?php echo $message->idThread; ?>,
  706. msgs: <?php echo json_encode($messageList); ?>,
  707. fetchMessages: (function() {
  708. var _msgsXhr = null;
  709. return function(reqData, callback) {
  710. if (_msgsXhr && _msgsXhr.state() === 'pending') {
  711. _msgsXhr.abort();
  712. _msgsXhr = null;
  713. }
  714. _msgsXhr = $.ajax({
  715. url: 'index.php?_route=UserMsgs&_task=getMessagesById&idThread=<?php echo $message->idThread; ?>',
  716. data: reqData,
  717. dataType: 'json'
  718. });
  719. _msgsXhr.done(function(data, textStatus, jqXHR) {
  720. if (data && data.msgs && data.msgs.length > 0) {
  721. callback(null, {msgs: data.msgs});
  722. } else {
  723. callback(null, {msgs: []});//"Error no data!");
  724. }
  725. });
  726. _msgsXhr.fail(function() {
  727. callback(null, {options: []});//"Error no data!");
  728. });
  729. _msgsXhr.always(function() {
  730. _msgsXhr = null;
  731. });
  732. };
  733. })(),
  734. fetchOptionsForGroup: (function() {
  735. var _groupXhr = null;
  736. return function(input, callback) {
  737. if (_groupXhr && _groupXhr.state() === 'pending') {
  738. _groupXhr.abort();
  739. _groupXhr = null;
  740. }
  741. _groupXhr = $.ajax({
  742. url: 'index.php?_route=UserMsgs&_task=typeSpecialGroupId&q=' + input,
  743. dataType: 'json'
  744. });
  745. _groupXhr.done(function(data, textStatus, jqXHR) {
  746. if (data && data.length > 0) {
  747. var options = [];
  748. data.forEach(function(item) {
  749. options.push({value: item.id, label: item.name});
  750. });
  751. callback(null, {options: options});
  752. } else {
  753. callback(null, {options: []});//"Error no data!");
  754. }
  755. });
  756. _groupXhr.fail(function() {
  757. callback(null, {options: []});//"Error no data!");
  758. });
  759. _groupXhr.always(function() {
  760. _groupXhr = null;
  761. });
  762. };
  763. })(),
  764. fetchOptionsForUser: (function() {
  765. var _userXhr = null;
  766. return function(input, callback) {
  767. if (_userXhr && _userXhr.state() === 'pending') {
  768. _userXhr.abort();
  769. _userXhr = null;
  770. }
  771. _userXhr = $.ajax({
  772. url: 'index.php?_route=UserMsgs&_task=typeSpecialUserLogin&q=' + input,
  773. dataType: 'json'
  774. });
  775. _userXhr.done(function(data, textStatus, jqXHR) {
  776. if (data && data.length > 0) {
  777. var options = [];
  778. data.forEach(function(item) {
  779. options.push({value: item.id, label: item.name});
  780. });
  781. callback(null, {options: options});
  782. } else {
  783. callback(null, {options: []});//"Error no data!");
  784. }
  785. });
  786. _userXhr.fail(function() {
  787. callback(null, {options: []});//"Error no data!");
  788. });
  789. _userXhr.always(function() {
  790. _userXhr = null;
  791. });
  792. };
  793. })(),
  794. saveReply: function(data, callback) {
  795. //console.log('#widget-msg-tree/MsgThread::saveReply: data:', data, 'callback', callback);
  796. $.ajax({
  797. url: '<?php echo $replyLink; ?>',
  798. method: 'POST',
  799. data: data,
  800. dataType: 'json'
  801. })
  802. .done(function(data, textStatus, jqXHR) {
  803. var returnData = {message: '', type: 'danger'};
  804. if (data && data.record) {
  805. returnData.msg = data.msg || 'Wysłano wiadomość';
  806. returnData.record = data.record;
  807. returnData.type = 'success';
  808. } else if (data.validateErrors) {
  809. returnData.msg = data.msg || 'Wystąpiły błędy w formularzu';
  810. returnData.type = 'warning';
  811. returnData.validateErrors = data.validateErrors;
  812. } else {
  813. returnData.msg = data.msg || 'Nie udało się wysłać wiadomości!';
  814. returnData.type = 'danger';
  815. }
  816. callback(null, returnData);
  817. })
  818. .fail(function() {
  819. callback(null, {message: 'Nie udało się wysłać wiadomości!', type: 'danger'});
  820. });
  821. },
  822. markAsRead: function(idMsg, callback) {
  823. //console.log('#widget-msg-tree/MsgThread::markAsRead: idMsg:', idMsg);
  824. $.ajax({
  825. url: '<?php echo $markAsReadLink; ?>&idMsg=' + idMsg,
  826. method: 'GET',
  827. dataType: 'json'
  828. })
  829. .done(function(data, textStatus, jqXHR) {
  830. var returnData = {message: '', type: 'danger'};
  831. if (data && data.record) {
  832. returnData.msg = data.msg || 'Oznaczono wiadomość jako odczytaną';
  833. returnData.record = data.record;
  834. returnData.type = 'success';
  835. } else {
  836. returnData.msg = data.msg || 'Nie udało się oznaczyć wiadomości jako odczytanej!';
  837. returnData.type = 'danger';
  838. }
  839. callback(null, returnData);
  840. })
  841. .fail(function() {
  842. callback(null, {message: 'Nie udało się oznaczyć wiadomości jako odczytanej!', type: 'danger'});
  843. });
  844. },
  845. dbg: false
  846. });
  847. // jQuery("#widget-msg-tree").on('change', function(e, data) {
  848. // console.log('#widget-msg-tree/MsgThread::onChange: data:', data);
  849. // });
  850. </script>
  851. <?php
  852. }
  853. public function _convertMessageToJson($rawMsg) {
  854. /* $msg = {_raw: {A_RECORD_CREATE_AUTHOR: "plabudda",
  855. A_RECORD_CREATE_DATE: "2015-10-26 12:20:05",
  856. A_RECORD_DELETE_AUTHOR: "",
  857. A_RECORD_DELETE_DATE: null,
  858. A_RECORD_UPDATE_AUTHOR: "plabudda",
  859. A_RECORD_UPDATE_DATE: "2015-11-02 12:44:59",
  860. A_STATUS: "NORMAL",
  861. ID: "67",
  862. actionExecutedTime: "2015-11-02 12:44:59",
  863. actionNotes: "",
  864. app_className: "TableMsgs",
  865. msg: "test Y",
  866. msgType: "info",
  867. uiTargetName: "TEST_PERMS.31",
  868. uiTargetType: "default_db_table_record",
  869. userTargetName: "plabudda",
  870. userTargetType: "user"}
  871. _read: true,
  872. idRow: "31",
  873. message: "test Y",
  874. tblName: "TEST_PERMS",
  875. type: "info",
  876. usrLogin: "plabudda"} */
  877. $usrLogin = User::getLogin();
  878. $message = new stdClass();
  879. $message->id = $rawMsg->ID;
  880. $message->idThread = $rawMsg->idThread;// TODO: ID_THREAD
  881. $message->idReplyTo = $rawMsg->idReplyTo;// TODO: ID_REPLY_TO
  882. $message->message = $rawMsg->msg;
  883. $message->type = $rawMsg->msgType;
  884. $message->to = $rawMsg->userTargetName;
  885. $message->toType = $rawMsg->userTargetType;
  886. $message->author = $rawMsg->A_RECORD_CREATE_AUTHOR;
  887. $message->created = $rawMsg->A_RECORD_CREATE_DATE;
  888. $message->_read = ('WAITING' != $rawMsg->A_STATUS);
  889. $message->_readByUser = ('WAITING' != $rawMsg->A_STATUS);
  890. if ('WAITING' == $rawMsg->A_STATUS
  891. && $usrLogin == $rawMsg->A_RECORD_CREATE_AUTHOR) {
  892. if ('user' == $rawMsg->userTargetType
  893. && $usrLogin == $rawMsg->userTargetName) {
  894. $message->_readByUser = false;
  895. } else {
  896. $message->_readByUser = true;
  897. }
  898. }
  899. if ($message->_read) {
  900. if (!empty($rawMsg->A_RECORD_UPDATE_DATE)) $message->_readDate = $rawMsg->A_RECORD_UPDATE_DATE;
  901. if (!empty($rawMsg->A_RECORD_UPDATE_AUTHOR)) $message->_readBy = $rawMsg->A_RECORD_UPDATE_AUTHOR;
  902. }
  903. return $message;
  904. }
  905. public function getMessagesByIdAction() {
  906. try {
  907. $idThread = V::get('idThread', '', $_GET, 'int');
  908. $idLastMsg = V::get('idLastMsg', '', $_GET, 'int');
  909. if ($idThread <= 0) throw new Exception("Wrong param id!");
  910. $sqlLimit = 10;// TODO: 100?
  911. $ds = DB::getDataSource();
  912. $sql = "
  913. select m.*
  914. from `CRM_UI_MSGS` m
  915. where m.`idThread` = {$idThread}
  916. and m.`ID` > {$idLastMsg}
  917. order by m.`ID` asc
  918. limit {$sqlLimit}
  919. ";
  920. $moreMsgs = $ds->getListByQuery($sql);
  921. $response = new stdClass();
  922. $response->msg = "Nowe wiadomości";
  923. $response->type = 'success';
  924. $response->msgs = array();
  925. foreach ($moreMsgs as $msg) {
  926. $response->msgs[] = $this->_convertMessageToJson($msg);
  927. }
  928. } catch (Exception $e) {
  929. $response = new stdClass();
  930. $response->msg = "Wystąpiły błędy: " . $e->getMessage();
  931. $response->type = 'danger';
  932. }
  933. echo json_encode($response);
  934. }
  935. public function replyAction() {
  936. try {
  937. $uiTargetType = V::get('uiTargetType', '', $_GET);
  938. $uiTargetName = V::get('uiTargetName', '', $_GET);
  939. $response = $this->_reply($uiTargetType, $uiTargetName, $_POST);
  940. } catch (Exception $e) {
  941. $response = new stdClass();
  942. $response->msg = "Wystąpiły błędy: " . $e->getMessage();
  943. $response->type = 'danger';
  944. }
  945. echo json_encode($response);
  946. }
  947. public function markAsReadAction() {
  948. $usrLogin = User::getLogin();
  949. try {
  950. $idMsg = V::get('idMsg', '', $_GET, 'int');
  951. $msg = $this->_getMsg($idMsg, $usrLogin);
  952. $this->_markAsRead($msg);
  953. $response = new stdClass();
  954. //$response->msg = "";
  955. $response->type = "success";
  956. $msg = $this->_getMsg($idMsg, $usrLogin);
  957. $response->record = $this->_convertMessageToJson($msg['_raw']);
  958. } catch (Exception $e) {
  959. $response = new stdClass();
  960. $response->msg = "Wystąpiły błędy: " . $e->getMessage();
  961. $response->type = 'danger';
  962. }
  963. echo json_encode($response);
  964. }
  965. public function _reply($uiTargetType, $uiTargetName, $args) {
  966. $ds = DB::getDataSource();
  967. $newMsg = array();
  968. $newMsg['idReplyTo'] = V::get('idReplyTo', '', $args, 'int');
  969. $newMsg['msg'] = V::get('message', '', $args);
  970. $newMsg['msgType'] = V::get('msgType', 'info', $args);
  971. $newMsg['userTargetType'] = V::get('toType', '', $args);
  972. $newMsg['userTargetName'] = V::get('to', '', $args);
  973. $newMsg['A_RECORD_CREATE_DATE'] = 'NOW()';
  974. $newMsg['A_RECORD_CREATE_AUTHOR'] = User::getLogin();
  975. $newMsg['app_className'] = 'TableMsgs';
  976. //DBG::_(true, true, "newMsg", $newMsg, __CLASS__, __FUNCTION__, __LINE__);
  977. if ($newMsg['idReplyTo'] <= 0) throw new Exception("Wrong id reply to msg");
  978. $parentMsg = $ds->getById('CRM_UI_MSGS', $newMsg['idReplyTo']);
  979. if (!$parentMsg) throw new Exception("Nie znaleziono wiadomości");
  980. $newMsg['idThread'] = ($parentMsg->idThread > 0)? $parentMsg->idThread : $parentMsg->ID;
  981. $newMsg['uiTargetType'] = $uiTargetType;// TODO:? $parentMsg->uiTargetType
  982. $newMsg['uiTargetName'] = $uiTargetName;// TODO:? $parentMsg->uiTargetName
  983. $insertedId = $ds->insert('CRM_UI_MSGS', $newMsg);
  984. if (!$insertedId) throw new Exception("Nie udało się utworzyć rekordu");
  985. $msgAdded = $ds->getById('CRM_UI_MSGS', $insertedId);
  986. $response = new stdClass();
  987. $response->msg = "Wysłano wiadomość";
  988. $response->type = 'success';
  989. $response->record = $this->_convertMessageToJson($msgAdded);
  990. return $response;
  991. }
  992. public function removeMsgAction() {
  993. $idMsg = V::get('id', 0, $_GET, 'int');
  994. $usrLogin = V::get('usrLogin', 0, $_REQUEST, 'word');
  995. if ($idMsg <= 0) throw new HttpException("Wiadomość nie istnieje!", 404);
  996. if (empty($usrLogin)) throw new HttpException("Błęny user login", 404);
  997. SE_Layout::gora();
  998. SE_Layout::menu();
  999. try {
  1000. $msg = $this->_getMsg($idMsg, $usrLogin);
  1001. $msgsRoute = Router::getRoute('Msgs');
  1002. $msgsRoute->removeTableRecordMsg($idMsg);
  1003. } catch (Exception $e) {
  1004. SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
  1005. SE_Layout::dol();
  1006. exit;
  1007. }
  1008. ?>
  1009. <div class="container">
  1010. <div class="alert alert-success">
  1011. Wiadomość została usunięta <a class="btn btn-xs btn-default" href="index.php?_route=UserMsgs&usrLogin=<?php echo $usrLogin; ?>">wróć</a>
  1012. </div>
  1013. </div>
  1014. <?php
  1015. SE_Layout::dol();
  1016. }
  1017. }