UserMsgs.php 37 KB

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