UserMsgs.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082
  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, $fromTime = 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. if (!empty($fromTime)) {
  342. $sqlWhereAddFilter .= "\n and m.`A_RECORD_CREATE_DATE`>='{$fromTime}'";
  343. }
  344. $sqlLimit = $this->_listLimit + 1;
  345. $sql = "select m.*
  346. from `CRM_UI_MSGS` m
  347. where m.`uiTargetType`='default_db_table_record'
  348. -- and m.`uiTargetName`='{$tableName}.{$idRow}'
  349. {$sqlWhereAddFilter}
  350. order by m.`ID` DESC
  351. limit {$sqlLimit}
  352. ";
  353. DBG::_('DBG_MSGS', '>1', "sql", $sql, __CLASS__, __FUNCTION__, __LINE__);
  354. $db = DB::getDB();
  355. $res = $db->query($sql);
  356. while ($r = $db->fetch($res)) {
  357. $msg['message'] = $r->msg;
  358. $msg['type'] = $r->msgType;
  359. $msg['_raw'] = $r;
  360. $msg['_read'] = ('WAITING' != $r->A_STATUS);
  361. $msg['_readDate'] = $r->actionExecutedTime;
  362. $msgsList[$r->ID] = $msg;
  363. }
  364. return $msgsList;
  365. }
  366. public function _validate($args) {
  367. $toType = V::get('to_type', '', $args);
  368. $to = V::get('to', '', $args);
  369. $msg = V::get('msg', '', $args);
  370. if (!in_array($toType, array('everyone', 'user', 'group'))) {
  371. throw new Exception("Niedozwolony typ odbiorcy");
  372. }
  373. if (empty($to) && 'everyone' != $toType) {
  374. throw new Exception("Proszę podać odbiorcę wiadomości");
  375. }
  376. if (empty($msg)) {
  377. throw new Exception("Proszę podać treść wiadomości");
  378. }
  379. }
  380. public function _create($args, $tableName, $idRow) {
  381. $toType = V::get('to_type', '', $args);
  382. $to = V::get('to', '', $args);
  383. $msg = V::get('msg', '', $args);
  384. $usrLogin = User::getLogin();
  385. $db = DB::getDB();
  386. if (!$db) throw new Exception("Brak dazy danych!");
  387. if ($db->has_errors()) throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  388. $item = array();
  389. $item['`uiTargetType`'] = "'default_db_table_record'";
  390. $item['`uiTargetName`'] = "'{$tableName}.{$idRow}'";
  391. $item['`userTargetType`'] = "'{$toType}'";
  392. $item['`userTargetName`'] = "'{$to}'";
  393. $item['`msg`'] = "'" . $db->_($msg) . "'";
  394. $item['`A_RECORD_CREATE_DATE`'] = "NOW()";
  395. $item['`A_RECORD_CREATE_AUTHOR`'] = "'{$usrLogin}'";
  396. $item['`A_STATUS`'] = "'WAITING'";
  397. $item['`app_className`'] = "'TableMsgs'";
  398. $sql = "insert into `CRM_UI_MSGS` (" . implode(",", array_keys($item)) . ")
  399. values (" . implode(",", array_values($item)) . ")
  400. ";
  401. $res = $db->query($sql);
  402. 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()));
  403. $createdId = $db->insert_id();
  404. if ($createdId <= 0) throw new Exception("Nie udało się zapisać wiadomości.");
  405. return $createdId;
  406. }
  407. public function _printMsgForm($args) {
  408. $toType = V::get('to_type', '', $args);
  409. $to = V::get('to', '', $args);
  410. $msg = V::get('msg', '', $args);
  411. $listTo = array();
  412. $listTo['everyone'] = 'Wszyscy';
  413. $listTo['user'] = 'Użytkownik';
  414. $listTo['group'] = 'Grupa';
  415. $toType = (array_key_exists($toType, $listTo))? $toType : 'everyone';
  416. $typeSpecialGroupId = TypespecialVariable::getInstance(-1, '__ZASOB');
  417. $typeSpecialUserLogin = TypespecialVariable::getInstance(-1, '__USER_LOGIN');
  418. $selectedLogin = ('user' == $toType)? $to : '';
  419. $selectedGroupId = ('group' == $toType)? $to : '';
  420. ?>
  421. <form class="form-horizontal" action="" method="post">
  422. <div class="form-group">
  423. <label class="col-sm-2 control-label" for="to">Do:</label>
  424. <div class="col-sm-3">
  425. <select name="to_type" class="form-control" onChange="return selectTblMsgsToType(this);">
  426. <?php foreach ($listTo as $type => $typeLabel) : ?>
  427. <option <?php echo ($type == $toType)? 'selected' : ''; ?>
  428. value="<?php echo $type; ?>"><?php echo $typeLabel; ?></option>
  429. <?php endforeach; ?>
  430. </select>
  431. </div>
  432. <div class="col-sm-7">
  433. <div id="tblMsgsTo-everyone" style="<?php echo ('everyone' == $toType)? '' : 'display:none'; ?>">
  434. <input name="to-everyone" type="text" class="form-control" disabled>
  435. </div>
  436. <div id="tblMsgsTo-group" style="<?php echo ('group' == $toType)? '' : 'display:none'; ?>">
  437. <?php if ($typeSpecialGroupId) : ?>
  438. <?php
  439. $fldName = 'to-group';
  440. $fldParams = array();
  441. $fldParams['allowCreate'] = false;
  442. $fldParams['ajaxDataUrlBase'] = "index.php?_route=TableMsgs&_task=typeSpecialGroupId";
  443. $fldParams['placeholder'] = 'Grupa...';
  444. //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
  445. echo $typeSpecialUserLogin->showFormItem($tblID = -1, $fldName, $selectedGroupId, $fldParams);
  446. ?>
  447. <?php else : ?>
  448. <input name="to-group" type="text" class="form-control" placeholder="Grupa">
  449. <?php endif; ?>
  450. </div>
  451. <div id="tblMsgsTo-user" style="<?php echo ('user' == $toType)? '' : 'display:none'; ?>">
  452. <?php if ($typeSpecialUserLogin) : ?>
  453. <?php
  454. $fldName = 'to-user';
  455. $fldParams = array();
  456. $fldParams['allowCreate'] = false;
  457. $fldParams['ajaxDataUrlBase'] = "index.php?_route=TableMsgs&_task=typeSpecialUserLogin";
  458. $fldParams['placeholder'] = 'Użytkownik...';
  459. //$fldParams['ajaxDataUrlBase'] .= "&DBG_TS=3";
  460. echo $typeSpecialUserLogin->showFormItem($tblID = -1, $fldName, $selectedLogin, $fldParams);
  461. ?>
  462. <?php else : ?>
  463. <input name="to-user" type="text" class="form-control" placeholder="Użytkownik">
  464. <?php endif; ?>
  465. </div>
  466. </div>
  467. </div>
  468. <div class="form-group">
  469. <label for="to" class="col-sm-2 control-label">Wiadomość:</label>
  470. <div class="col-sm-10">
  471. <textarea name="msg" class="form-control"><?php echo htmlspecialchars($msg); ?></textarea>
  472. </div>
  473. </div>
  474. <div class="form-group">
  475. <div class="col-sm-10 col-sm-offset-2">
  476. <input class="btn btn-primary" type="submit" value="Wyślij">
  477. </div>
  478. </div>
  479. </form>
  480. <script>
  481. function selectTblMsgsToType(n) {
  482. var toTypes = <?php echo json_encode(array_keys($listTo)); ?>,
  483. selectedType = n.value
  484. ;
  485. if (-1 !== toTypes.indexOf(n.value)) {
  486. toTypes.forEach(function(type) {
  487. if (type == selectedType) {
  488. document.getElementById('tblMsgsTo-' + type).style.display = 'block';
  489. } else {
  490. document.getElementById('tblMsgsTo-' + type).style.display = 'none';
  491. }
  492. });
  493. }
  494. }
  495. </script>
  496. <?php
  497. }
  498. public function typeSpecialUserLoginAction() {
  499. header("Content-type: application/json");
  500. $typeSpecialUserId = TypespecialVariable::getInstance(-1, '__USER_LOGIN');
  501. if (!$typeSpecialUserId) {
  502. $jsonData = new stdClass();
  503. $jsonData->message = "TypeSpecial '__USER_LOGIN' not exists";
  504. echo json_encode($jsonData);
  505. exit;
  506. }
  507. $query = V::get('q', '', $_REQUEST);
  508. $rawRows = null;
  509. $jsonData = array();
  510. $queryParams = array();
  511. $rows = $typeSpecialUserId->getValuesWithExports($query, $queryParams);
  512. foreach ($rows as $kID => $vItem) {
  513. $itemJson = new stdClass();
  514. $itemJson->id = $vItem->id;
  515. $itemJson->name = $vItem->param_out;
  516. if (!empty($vItem->exports)) {
  517. $itemJson->exports = $vItem->exports;
  518. }
  519. $jsonData[] = $itemJson;
  520. }
  521. echo json_encode($jsonData);
  522. }
  523. public function typeSpecialGroupIdAction() {
  524. header("Content-type: application/json");
  525. Lib::loadClass('TypespecialVariable');
  526. $typeSpecialZasob = TypespecialVariable::getInstance(-1, '__ZASOB');
  527. if (!$typeSpecialZasob) {
  528. $jsonData = new stdClass();
  529. $jsonData->message = "TypeSpecial '__ZASOB' not exists";
  530. echo json_encode($jsonData);
  531. exit;
  532. }
  533. $query = V::get('q', '', $_REQUEST);
  534. $rawRows = null;
  535. $jsonData = array();
  536. $queryParams = array();
  537. $queryParams['zasob_type_in'] = array('STANOWISKO', 'PODMIOT', 'DZIAL');
  538. $rows = $typeSpecialZasob->getValuesWithExports($query, $queryParams);
  539. DBG::_('DBG_TS', '>1', "rows({$query})", $rows, __CLASS__, __FUNCTION__, __LINE__);
  540. foreach ($rows as $kID => $vItem) {
  541. $itemJson = new stdClass();
  542. $itemJson->id = $vItem->id;
  543. $itemJson->name = $vItem->param_out;
  544. if (!empty($vItem->exports)) {
  545. $itemJson->exports = $vItem->exports;
  546. }
  547. $jsonData[] = $itemJson;
  548. }
  549. echo json_encode($jsonData);
  550. }
  551. public function readAction() {
  552. $idMsg = V::get('id', 0, $_GET, 'int');
  553. $usrLogin = V::get('usrLogin', '', $_REQUEST, 'word');
  554. if ($idMsg <= 0) throw new HttpException("Wiadomość nie istnieje!", 404);
  555. if (empty($usrLogin)) throw new HttpException("Błęny user login!", 404);
  556. SE_Layout::gora();
  557. SE_Layout::menu();
  558. try {
  559. $msg = $this->_getMsg($idMsg, $usrLogin);
  560. $this->_markAsRead($msg);
  561. $this->viewMsg($msg);
  562. } catch (Exception $e) {
  563. SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
  564. }
  565. SE_Layout::dol();
  566. }
  567. public function viewAction() {
  568. $idMsg = V::get('id', 0, $_GET, 'int');
  569. $usrLogin = V::get('usrLogin', 0, $_REQUEST, 'word');
  570. if ($idMsg <= 0) throw new HttpException("Wiadomość nie istnieje!", 404);
  571. if (empty($usrLogin)) throw new HttpException("Błęny user login", 404);
  572. SE_Layout::gora();
  573. SE_Layout::menu();
  574. try {
  575. $msg = $this->_getMsg($idMsg, $usrLogin);
  576. $this->viewMsg($msg);
  577. } catch (Exception $e) {
  578. SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
  579. }
  580. SE_Layout::dol();
  581. }
  582. public function _getMsg($idMsg, $usrLogin) {
  583. $msgsRoute = Router::getRoute('Msgs');
  584. $msg['_raw'] = $msgsRoute->getMessage($idMsg);
  585. if (!$msg['_raw']) throw new HttpException("Wiadomość nie istnieje!", 404);
  586. $msg['usrLogin'] = $usrLogin;
  587. $msg['message'] = $msg['_raw']->msg;
  588. $msg['type'] = $msg['_raw']->msgType;
  589. $msg['_read'] = ('WAITING' != $msg['_raw']->A_STATUS);
  590. // $msg['_raw']->uiTargetType => default_db_table_record
  591. // $msg['_raw']->uiTargetName => TEST_PERMS.31
  592. if ('default_db_table_record' !== $msg['_raw']->uiTargetType) {
  593. throw new Exception("Parse message target type error!");
  594. }
  595. $parts = explode('.', $msg['_raw']->uiTargetName);
  596. if (2 !== count($parts)) throw new Exception("Parse message target type error!");
  597. $msg['tblName'] = $parts[0];
  598. $msg['idRow'] = $parts[1];
  599. if (!is_numeric($msg['idRow'])) throw new Exception("Parse message target type - id row type error!");
  600. return $msg;
  601. }
  602. public function _markAsRead($msg) {
  603. if ($msg['_read']) return;
  604. $usrLogin = User::getLogin();
  605. $db = DB::getDB();
  606. if (!$db) throw new Exception("Brak dazy danych!");
  607. if ($db->has_errors()) throw new Exception("DB Errors: " . implode("\n<br>", $db->get_errors()));
  608. $sql = "update `CRM_UI_MSGS`
  609. set `A_STATUS`='NORMAL'
  610. , `A_RECORD_UPDATE_AUTHOR`='{$usrLogin}'
  611. , `A_RECORD_UPDATE_DATE`=NOW()
  612. , `actionExecutedTime`=NOW()
  613. where `ID`='{$msg['_raw']->ID}'
  614. and `A_STATUS`='WAITING'
  615. and `A_RECORD_UPDATE_AUTHOR`=''
  616. and `A_RECORD_UPDATE_DATE` is null
  617. and (
  618. ('{$usrLogin}'!=`A_RECORD_CREATE_AUTHOR`)
  619. or ('{$usrLogin}'=`A_RECORD_CREATE_AUTHOR`
  620. and 'user'=`userTargetType`
  621. and '{$usrLogin}'=`userTargetName`
  622. )
  623. )
  624. ";
  625. $res = $db->query($sql);
  626. 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()));
  627. }
  628. public function viewMsg($msg) {
  629. $usrLogin = User::getLogin();
  630. $idTable = 0;
  631. if (!empty($msg['tblName'])) {
  632. $tblName = $msg['tblName'];
  633. $idTable = ProcesHelper::getZasobTableID($tblName);
  634. if (!$idTable) throw new Exception("Nie udało się odnaleźć nr tabeli '{$tblName}'");
  635. $idRow = $msg['idRow'];
  636. if (!$idRow) throw new Exception("Brak numeru powiązanego rekordu!");
  637. $usrAcl = User::getAcl();
  638. $tblAcl = $usrAcl->getTableAcl($idTable);
  639. }
  640. $linkBase = "index.php?_route=UserMsgs";
  641. $linkBase .= "&usrLogin={$usrLogin}";
  642. //$rmMsgLink = "{$linkBase}&_task=removeMsg&id={$msg['_raw']->ID}";
  643. $backLink = "{$linkBase}";
  644. ?>
  645. <div class="container">
  646. <h3><i class="glyphicon glyphicon-envelope"></i> <a href="<?php echo $backLink; ?>">Wiadomości <?php echo $usrLogin; ?></a>
  647. &raquo; Wiadomość nr <?php echo $msg['_raw']->ID; ?>
  648. <?php if ($idTable > 0) : ?>
  649. <!-- <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>
  650. z tabeli <a href="index.php?MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $idTable; ?>"><?php echo $tblAcl->getLabel(); ?></a>
  651. </small>
  652. -->
  653. <small style="display:block; text-align:right">
  654. <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>
  655. <span style="font-size:12px; line-height:15px; vertical-align:text-bottom;">z tabeli</span>
  656. <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>
  657. </small>
  658. <?php endif; ?>
  659. </h3>
  660. </div>
  661. <?php $this->printWidgetViewMsg($msg); ?>
  662. <?php
  663. }
  664. public function printWidgetViewMsg($msg) {
  665. $messageList = array();
  666. $uiTargetName = $msg['_raw']->uiTargetName;
  667. $uiTargetType = $msg['_raw']->uiTargetType;
  668. $replyLink = "index.php?_route=UserMsgs&_task=reply&uiTargetName={$uiTargetName}&uiTargetType={$uiTargetType}";
  669. $markAsReadLink = "index.php?_route=UserMsgs&_task=markAsRead";
  670. $message = $this->_convertMessageToJson($msg['_raw']);
  671. {//if ($message->idThread > 0) {
  672. $sqlLimit = 100;
  673. $ds = DB::getDataSource();
  674. $sqlIdThread = ($message->idThread > 0)? $message->idThread : $message->id;
  675. $sql = "
  676. select m.*
  677. from `CRM_UI_MSGS` m
  678. where (m.`idThread` = {$sqlIdThread} or m.`ID` = {$sqlIdThread})
  679. -- and m.`ID` < {$message->id}
  680. order by m.`ID` asc
  681. limit {$sqlLimit}
  682. ";
  683. $moreMsgs = $ds->getListByQuery($sql);
  684. foreach ($moreMsgs as $msg) $messageList[] = $this->_convertMessageToJson($msg);
  685. }
  686. //$messageList[] = $message;
  687. ?>
  688. <link rel="stylesheet" href="./stuff/widget-select.css">
  689. <style type="text/css">
  690. .user_avatar {
  691. display:block;
  692. width:40px;
  693. height:40px;
  694. margin:0 auto 10px auto;
  695. padding:0;
  696. border:1px solid #ddd;
  697. line-height: 38px;
  698. font-size:16px;
  699. text-align:center;
  700. vertical-align:middle;
  701. color:#aaa;
  702. }
  703. </style>
  704. <div id="widget-msg-tree" style="max-width:1000px; margin:0 auto;"></div>
  705. <script src="stuff/vendors.js"></script>
  706. <script src="stuff/bundle.se_route_user_msgs.js"></script>
  707. <script>
  708. var testNewRecordCounter = 0;
  709. jQuery("#widget-msg-tree").MsgThread({
  710. usrLogin: '<?php echo User::getLogin(); ?>',
  711. idThread: <?php echo $message->idThread; ?>,
  712. msgs: <?php echo json_encode($messageList); ?>,
  713. fetchMessages: (function() {
  714. var _msgsXhr = null;
  715. return function(reqData, callback) {
  716. if (_msgsXhr && _msgsXhr.state() === 'pending') {
  717. _msgsXhr.abort();
  718. _msgsXhr = null;
  719. }
  720. _msgsXhr = $.ajax({
  721. url: 'index.php?_route=UserMsgs&_task=getMessagesById&idThread=<?php echo $message->idThread; ?>',
  722. data: reqData,
  723. dataType: 'json'
  724. });
  725. _msgsXhr.done(function(data, textStatus, jqXHR) {
  726. if (data && data.msgs && data.msgs.length > 0) {
  727. callback(null, {msgs: data.msgs});
  728. } else {
  729. callback(null, {msgs: []});//"Error no data!");
  730. }
  731. });
  732. _msgsXhr.fail(function() {
  733. callback(null, {options: []});//"Error no data!");
  734. });
  735. _msgsXhr.always(function() {
  736. _msgsXhr = null;
  737. });
  738. };
  739. })(),
  740. fetchOptionsForGroup: (function() {
  741. var _groupXhr = null;
  742. return function(input, callback) {
  743. if (_groupXhr && _groupXhr.state() === 'pending') {
  744. _groupXhr.abort();
  745. _groupXhr = null;
  746. }
  747. _groupXhr = $.ajax({
  748. url: 'index.php?_route=UserMsgs&_task=typeSpecialGroupId&q=' + input,
  749. dataType: 'json'
  750. });
  751. _groupXhr.done(function(data, textStatus, jqXHR) {
  752. if (data && data.length > 0) {
  753. var options = [];
  754. data.forEach(function(item) {
  755. options.push({value: item.id, label: item.name});
  756. });
  757. callback(null, {options: options});
  758. } else {
  759. callback(null, {options: []});//"Error no data!");
  760. }
  761. });
  762. _groupXhr.fail(function() {
  763. callback(null, {options: []});//"Error no data!");
  764. });
  765. _groupXhr.always(function() {
  766. _groupXhr = null;
  767. });
  768. };
  769. })(),
  770. fetchOptionsForUser: (function() {
  771. var _userXhr = null;
  772. return function(input, callback) {
  773. if (_userXhr && _userXhr.state() === 'pending') {
  774. _userXhr.abort();
  775. _userXhr = null;
  776. }
  777. _userXhr = $.ajax({
  778. url: 'index.php?_route=UserMsgs&_task=typeSpecialUserLogin&q=' + input,
  779. dataType: 'json'
  780. });
  781. _userXhr.done(function(data, textStatus, jqXHR) {
  782. if (data && data.length > 0) {
  783. var options = [];
  784. data.forEach(function(item) {
  785. options.push({value: item.id, label: item.name});
  786. });
  787. callback(null, {options: options});
  788. } else {
  789. callback(null, {options: []});//"Error no data!");
  790. }
  791. });
  792. _userXhr.fail(function() {
  793. callback(null, {options: []});//"Error no data!");
  794. });
  795. _userXhr.always(function() {
  796. _userXhr = null;
  797. });
  798. };
  799. })(),
  800. saveReply: function(data, callback) {
  801. //console.log('#widget-msg-tree/MsgThread::saveReply: data:', data, 'callback', callback);
  802. $.ajax({
  803. url: '<?php echo $replyLink; ?>',
  804. method: 'POST',
  805. data: data,
  806. dataType: 'json'
  807. })
  808. .done(function(data, textStatus, jqXHR) {
  809. var returnData = {message: '', type: 'danger'};
  810. if (data && data.record) {
  811. returnData.msg = data.msg || 'Wysłano wiadomość';
  812. returnData.record = data.record;
  813. returnData.type = 'success';
  814. } else if (data.validateErrors) {
  815. returnData.msg = data.msg || 'Wystąpiły błędy w formularzu';
  816. returnData.type = 'warning';
  817. returnData.validateErrors = data.validateErrors;
  818. } else {
  819. returnData.msg = data.msg || 'Nie udało się wysłać wiadomości!';
  820. returnData.type = 'danger';
  821. }
  822. callback(null, returnData);
  823. })
  824. .fail(function() {
  825. callback(null, {message: 'Nie udało się wysłać wiadomości!', type: 'danger'});
  826. });
  827. },
  828. markAsRead: function(idMsg, callback) {
  829. //console.log('#widget-msg-tree/MsgThread::markAsRead: idMsg:', idMsg);
  830. $.ajax({
  831. url: '<?php echo $markAsReadLink; ?>&idMsg=' + idMsg,
  832. method: 'GET',
  833. dataType: 'json'
  834. })
  835. .done(function(data, textStatus, jqXHR) {
  836. var returnData = {message: '', type: 'danger'};
  837. if (data && data.record) {
  838. returnData.msg = data.msg || 'Oznaczono wiadomość jako odczytaną';
  839. returnData.record = data.record;
  840. returnData.type = 'success';
  841. } else {
  842. returnData.msg = data.msg || 'Nie udało się oznaczyć wiadomości jako odczytanej!';
  843. returnData.type = 'danger';
  844. }
  845. callback(null, returnData);
  846. })
  847. .fail(function() {
  848. callback(null, {message: 'Nie udało się oznaczyć wiadomości jako odczytanej!', type: 'danger'});
  849. });
  850. },
  851. dbg: false
  852. });
  853. // jQuery("#widget-msg-tree").on('change', function(e, data) {
  854. // console.log('#widget-msg-tree/MsgThread::onChange: data:', data);
  855. // });
  856. </script>
  857. <?php
  858. }
  859. public function _convertMessageToJson($rawMsg) {
  860. /* $msg = {_raw: {A_RECORD_CREATE_AUTHOR: "plabudda",
  861. A_RECORD_CREATE_DATE: "2015-10-26 12:20:05",
  862. A_RECORD_DELETE_AUTHOR: "",
  863. A_RECORD_DELETE_DATE: null,
  864. A_RECORD_UPDATE_AUTHOR: "plabudda",
  865. A_RECORD_UPDATE_DATE: "2015-11-02 12:44:59",
  866. A_STATUS: "NORMAL",
  867. ID: "67",
  868. actionExecutedTime: "2015-11-02 12:44:59",
  869. actionNotes: "",
  870. app_className: "TableMsgs",
  871. msg: "test Y",
  872. msgType: "info",
  873. uiTargetName: "TEST_PERMS.31",
  874. uiTargetType: "default_db_table_record",
  875. userTargetName: "plabudda",
  876. userTargetType: "user"}
  877. _read: true,
  878. idRow: "31",
  879. message: "test Y",
  880. tblName: "TEST_PERMS",
  881. type: "info",
  882. usrLogin: "plabudda"} */
  883. $usrLogin = User::getLogin();
  884. $message = new stdClass();
  885. $message->id = $rawMsg->ID;
  886. $message->idThread = $rawMsg->idThread;// TODO: ID_THREAD
  887. $message->idReplyTo = $rawMsg->idReplyTo;// TODO: ID_REPLY_TO
  888. $message->message = $rawMsg->msg;
  889. $message->type = $rawMsg->msgType;
  890. $message->to = $rawMsg->userTargetName;
  891. $message->toType = $rawMsg->userTargetType;
  892. $message->author = $rawMsg->A_RECORD_CREATE_AUTHOR;
  893. $message->created = $rawMsg->A_RECORD_CREATE_DATE;
  894. $message->_read = ('WAITING' != $rawMsg->A_STATUS);
  895. $message->_readByUser = ('WAITING' != $rawMsg->A_STATUS);
  896. if ('WAITING' == $rawMsg->A_STATUS
  897. && $usrLogin == $rawMsg->A_RECORD_CREATE_AUTHOR) {
  898. if ('user' == $rawMsg->userTargetType
  899. && $usrLogin == $rawMsg->userTargetName) {
  900. $message->_readByUser = false;
  901. } else {
  902. $message->_readByUser = true;
  903. }
  904. }
  905. if ($message->_read) {
  906. if (!empty($rawMsg->A_RECORD_UPDATE_DATE)) $message->_readDate = $rawMsg->A_RECORD_UPDATE_DATE;
  907. if (!empty($rawMsg->A_RECORD_UPDATE_AUTHOR)) $message->_readBy = $rawMsg->A_RECORD_UPDATE_AUTHOR;
  908. }
  909. return $message;
  910. }
  911. public function getMessagesByIdAction() {
  912. try {
  913. $idThread = V::get('idThread', '', $_GET, 'int');
  914. $idLastMsg = V::get('idLastMsg', '', $_GET, 'int');
  915. if ($idThread <= 0) throw new Exception("Wrong param id!");
  916. $sqlLimit = 10;// TODO: 100?
  917. $ds = DB::getDataSource();
  918. $sql = "
  919. select m.*
  920. from `CRM_UI_MSGS` m
  921. where m.`idThread` = {$idThread}
  922. and m.`ID` > {$idLastMsg}
  923. order by m.`ID` asc
  924. limit {$sqlLimit}
  925. ";
  926. $moreMsgs = $ds->getListByQuery($sql);
  927. $response = new stdClass();
  928. $response->msg = "Nowe wiadomości";
  929. $response->type = 'success';
  930. $response->msgs = array();
  931. foreach ($moreMsgs as $msg) {
  932. $response->msgs[] = $this->_convertMessageToJson($msg);
  933. }
  934. } catch (Exception $e) {
  935. $response = new stdClass();
  936. $response->msg = "Wystąpiły błędy: " . $e->getMessage();
  937. $response->type = 'danger';
  938. }
  939. echo json_encode($response);
  940. }
  941. public function replyAction() {
  942. try {
  943. $uiTargetType = V::get('uiTargetType', '', $_GET);
  944. $uiTargetName = V::get('uiTargetName', '', $_GET);
  945. $response = $this->_reply($uiTargetType, $uiTargetName, $_POST);
  946. } catch (Exception $e) {
  947. $response = new stdClass();
  948. $response->msg = "Wystąpiły błędy: " . $e->getMessage();
  949. $response->type = 'danger';
  950. }
  951. echo json_encode($response);
  952. }
  953. public function markAsReadAction() {
  954. $usrLogin = User::getLogin();
  955. try {
  956. $idMsg = V::get('idMsg', '', $_GET, 'int');
  957. $msg = $this->_getMsg($idMsg, $usrLogin);
  958. $this->_markAsRead($msg);
  959. $response = new stdClass();
  960. //$response->msg = "";
  961. $response->type = "success";
  962. $msg = $this->_getMsg($idMsg, $usrLogin);
  963. $response->record = $this->_convertMessageToJson($msg['_raw']);
  964. } catch (Exception $e) {
  965. $response = new stdClass();
  966. $response->msg = "Wystąpiły błędy: " . $e->getMessage();
  967. $response->type = 'danger';
  968. }
  969. echo json_encode($response);
  970. }
  971. public function _reply($uiTargetType, $uiTargetName, $args) {
  972. $ds = DB::getDataSource();
  973. $newMsg = array();
  974. $newMsg['idReplyTo'] = V::get('idReplyTo', '', $args, 'int');
  975. $newMsg['msg'] = V::get('message', '', $args);
  976. $newMsg['msgType'] = V::get('msgType', 'info', $args);
  977. $newMsg['userTargetType'] = V::get('toType', '', $args);
  978. $newMsg['userTargetName'] = V::get('to', '', $args);
  979. $newMsg['A_RECORD_CREATE_DATE'] = 'NOW()';
  980. $newMsg['A_RECORD_CREATE_AUTHOR'] = User::getLogin();
  981. $newMsg['app_className'] = 'TableMsgs';
  982. //DBG::_(true, true, "newMsg", $newMsg, __CLASS__, __FUNCTION__, __LINE__);
  983. if ($newMsg['idReplyTo'] <= 0) throw new Exception("Wrong id reply to msg");
  984. $parentMsg = $ds->getById('CRM_UI_MSGS', $newMsg['idReplyTo']);
  985. if (!$parentMsg) throw new Exception("Nie znaleziono wiadomości");
  986. $newMsg['idThread'] = ($parentMsg->idThread > 0)? $parentMsg->idThread : $parentMsg->ID;
  987. $newMsg['uiTargetType'] = $uiTargetType;// TODO:? $parentMsg->uiTargetType
  988. $newMsg['uiTargetName'] = $uiTargetName;// TODO:? $parentMsg->uiTargetName
  989. $insertedId = $ds->insert('CRM_UI_MSGS', $newMsg);
  990. if (!$insertedId) throw new Exception("Nie udało się utworzyć rekordu");
  991. $msgAdded = $ds->getById('CRM_UI_MSGS', $insertedId);
  992. $response = new stdClass();
  993. $response->msg = "Wysłano wiadomość";
  994. $response->type = 'success';
  995. $response->record = $this->_convertMessageToJson($msgAdded);
  996. return $response;
  997. }
  998. public function removeMsgAction() {
  999. $idMsg = V::get('id', 0, $_GET, 'int');
  1000. $usrLogin = V::get('usrLogin', 0, $_REQUEST, 'word');
  1001. if ($idMsg <= 0) throw new HttpException("Wiadomość nie istnieje!", 404);
  1002. if (empty($usrLogin)) throw new HttpException("Błęny user login", 404);
  1003. SE_Layout::gora();
  1004. SE_Layout::menu();
  1005. try {
  1006. $msg = $this->_getMsg($idMsg, $usrLogin);
  1007. $msgsRoute = Router::getRoute('Msgs');
  1008. $msgsRoute->removeTableRecordMsg($idMsg);
  1009. } catch (Exception $e) {
  1010. SE_Layout::alert('danger', $e->getMessage() . ' #' . $e->getLine());
  1011. SE_Layout::dol();
  1012. exit;
  1013. }
  1014. ?>
  1015. <div class="container">
  1016. <div class="alert alert-success">
  1017. Wiadomość została usunięta <a class="btn btn-xs btn-default" href="index.php?_route=UserMsgs&usrLogin=<?php echo $usrLogin; ?>">wróć</a>
  1018. </div>
  1019. </div>
  1020. <?php
  1021. SE_Layout::dol();
  1022. }
  1023. }