message.lib.php 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\Message;
  4. use Chamilo\UserBundle\Entity\User;
  5. use ChamiloSession as Session;
  6. /**
  7. * Class MessageManager.
  8. *
  9. * This class provides methods for messages management.
  10. * Include/require it in your code to use its features.
  11. *
  12. * @package chamilo.library
  13. */
  14. class MessageManager
  15. {
  16. /**
  17. * Get count new messages for the current user from the database.
  18. *
  19. * @return int
  20. */
  21. public static function getCountNewMessages()
  22. {
  23. $userId = api_get_user_id();
  24. if (empty($userId)) {
  25. return false;
  26. }
  27. static $count;
  28. if (!isset($count)) {
  29. $cacheAvailable = api_get_configuration_value('apc');
  30. if ($cacheAvailable === true) {
  31. $var = api_get_configuration_value('apc_prefix').'social_messages_unread_u_'.$userId;
  32. if (apcu_exists($var)) {
  33. $count = apcu_fetch($var);
  34. } else {
  35. $count = self::getCountNewMessagesFromDB($userId);
  36. apcu_store($var, $count, 60);
  37. }
  38. } else {
  39. $count = self::getCountNewMessagesFromDB($userId);
  40. }
  41. }
  42. return $count;
  43. }
  44. /**
  45. * Gets the total number of messages, used for the inbox sortable table.
  46. *
  47. * @param bool $unread
  48. *
  49. * @return int
  50. */
  51. public static function getNumberOfMessages($unread = false)
  52. {
  53. $table = Database::get_main_table(TABLE_MESSAGE);
  54. if ($unread) {
  55. $condition_msg_status = ' msg_status = '.MESSAGE_STATUS_UNREAD.' ';
  56. } else {
  57. $condition_msg_status = ' msg_status IN('.MESSAGE_STATUS_NEW.','.MESSAGE_STATUS_UNREAD.') ';
  58. }
  59. $keyword = Session::read('message_search_keyword');
  60. $keywordCondition = '';
  61. if (!empty($keyword)) {
  62. $keyword = Database::escape_string($keyword);
  63. $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
  64. }
  65. $sql = "SELECT COUNT(id) as number_messages
  66. FROM $table
  67. WHERE $condition_msg_status AND
  68. user_receiver_id=".api_get_user_id()."
  69. $keywordCondition
  70. ";
  71. $result = Database::query($sql);
  72. $result = Database::fetch_array($result);
  73. if ($result) {
  74. return (int) $result['number_messages'];
  75. }
  76. return 0;
  77. }
  78. /**
  79. * Gets information about some messages, used for the inbox sortable table.
  80. *
  81. * @param int $from
  82. * @param int $number_of_items
  83. * @param string $column
  84. * @param string $direction
  85. * @param int $userId
  86. *
  87. * @return array
  88. */
  89. public static function get_message_data(
  90. $from,
  91. $number_of_items,
  92. $column,
  93. $direction,
  94. $userId = 0
  95. ) {
  96. $from = (int) $from;
  97. $number_of_items = (int) $number_of_items;
  98. $userId = empty($userId) ? api_get_user_id() : (int) $userId;
  99. // Forcing this order.
  100. if (!isset($direction)) {
  101. $column = 2;
  102. $direction = 'DESC';
  103. } else {
  104. $column = (int) $column;
  105. if (!in_array($direction, ['ASC', 'DESC'])) {
  106. $direction = 'ASC';
  107. }
  108. }
  109. if (!in_array($column, [0, 1, 2])) {
  110. $column = 2;
  111. }
  112. $keyword = Session::read('message_search_keyword');
  113. $keywordCondition = '';
  114. if (!empty($keyword)) {
  115. $keyword = Database::escape_string($keyword);
  116. $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
  117. }
  118. $table = Database::get_main_table(TABLE_MESSAGE);
  119. $sql = "SELECT
  120. id as col0,
  121. title as col1,
  122. send_date as col2,
  123. msg_status as col3,
  124. user_sender_id
  125. FROM $table
  126. WHERE
  127. user_receiver_id=".$userId." AND
  128. msg_status IN (".MESSAGE_STATUS_NEW.", ".MESSAGE_STATUS_UNREAD.")
  129. $keywordCondition
  130. ORDER BY col$column $direction
  131. LIMIT $from, $number_of_items";
  132. $result = Database::query($sql);
  133. $messageList = [];
  134. $newMessageLink = api_get_path(WEB_CODE_PATH).'messages/new_message.php';
  135. while ($row = Database::fetch_array($result, 'ASSOC')) {
  136. $messageId = $row['col0'];
  137. $title = $row['col1'];
  138. $sendDate = $row['col2'];
  139. $status = $row['col3'];
  140. $senderId = $row['user_sender_id'];
  141. $title = Security::remove_XSS($title, STUDENT, true);
  142. $title = cut($title, 80, true);
  143. $class = 'class = "read"';
  144. if ($status == 1) {
  145. $class = 'class = "unread"';
  146. }
  147. $userInfo = api_get_user_info($senderId);
  148. if (!empty($senderId) && !empty($userInfo)) {
  149. $message[1] = '<a '.$class.' href="view_message.php?id='.$messageId.'">'.$title.'</a><br />';
  150. $message[1] .= $userInfo['complete_name_with_username'];
  151. $message[3] =
  152. Display::url(
  153. Display::returnFontAwesomeIcon('reply', 2),
  154. $newMessageLink.'?re_id='.$messageId,
  155. ['title' => get_lang('ReplyToMessage')]
  156. );
  157. } else {
  158. $message[1] = '<a '.$class.' href="view_message.php?id='.$messageId.'">'.$title.'</a><br />';
  159. $message[1] .= get_lang('UnknownUser');
  160. $message[3] =
  161. Display::url(
  162. Display::returnFontAwesomeIcon('reply', 2),
  163. '#',
  164. ['title' => get_lang('ReplyToMessage')]
  165. );
  166. }
  167. $message[0] = $messageId;
  168. $message[2] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
  169. $message[3] .=
  170. '&nbsp;&nbsp;'.
  171. Display::url(
  172. Display::returnFontAwesomeIcon('share', 2),
  173. $newMessageLink.'?forward_id='.$messageId,
  174. ['title' => get_lang('ForwardMessage')]
  175. ).
  176. '&nbsp;&nbsp;<a title="'.addslashes(
  177. get_lang('DeleteMessage')
  178. ).'" onclick="javascript:if(!confirm('."'".addslashes(
  179. api_htmlentities(get_lang('ConfirmDeleteMessage'))
  180. )."'".')) return false;" href="inbox.php?action=deleteone&id='.$messageId.'">'.
  181. Display::returnFontAwesomeIcon('trash', 2).'</a>';
  182. foreach ($message as $key => $value) {
  183. $message[$key] = api_xml_http_response_encode($value);
  184. }
  185. $messageList[] = $message;
  186. }
  187. return $messageList;
  188. }
  189. /**
  190. * @param array $aboutUserInfo
  191. * @param array $fromUserInfo
  192. * @param string $subject
  193. * @param string $content
  194. *
  195. * @return bool
  196. */
  197. public static function sendMessageAboutUser(
  198. $aboutUserInfo,
  199. $fromUserInfo,
  200. $subject,
  201. $content
  202. ) {
  203. if (empty($aboutUserInfo) || empty($fromUserInfo)) {
  204. return false;
  205. }
  206. if (empty($fromUserInfo['id']) || empty($aboutUserInfo['id'])) {
  207. return false;
  208. }
  209. $table = Database::get_main_table(TABLE_MESSAGE);
  210. $now = api_get_utc_datetime();
  211. $params = [
  212. 'user_sender_id' => $fromUserInfo['id'],
  213. 'user_receiver_id' => $aboutUserInfo['id'],
  214. 'msg_status' => MESSAGE_STATUS_CONVERSATION,
  215. 'send_date' => $now,
  216. 'title' => $subject,
  217. 'content' => $content,
  218. 'group_id' => 0,
  219. 'parent_id' => 0,
  220. 'update_date' => $now,
  221. ];
  222. $id = Database::insert($table, $params);
  223. if ($id) {
  224. return true;
  225. }
  226. return false;
  227. }
  228. /**
  229. * @param array $aboutUserInfo
  230. *
  231. * @return array
  232. */
  233. public static function getMessagesAboutUser($aboutUserInfo)
  234. {
  235. if (!empty($aboutUserInfo)) {
  236. $table = Database::get_main_table(TABLE_MESSAGE);
  237. $sql = 'SELECT id FROM '.$table.'
  238. WHERE
  239. user_receiver_id = '.$aboutUserInfo['id'].' AND
  240. msg_status = '.MESSAGE_STATUS_CONVERSATION.'
  241. ';
  242. $result = Database::query($sql);
  243. $messages = [];
  244. $repo = Database::getManager()->getRepository('ChamiloCoreBundle:Message');
  245. while ($row = Database::fetch_array($result)) {
  246. $message = $repo->find($row['id']);
  247. $messages[] = $message;
  248. }
  249. return $messages;
  250. }
  251. return [];
  252. }
  253. /**
  254. * @param array $userInfo
  255. *
  256. * @return string
  257. */
  258. public static function getMessagesAboutUserToString($userInfo)
  259. {
  260. $messages = self::getMessagesAboutUser($userInfo);
  261. $html = '';
  262. if (!empty($messages)) {
  263. /** @var Message $message */
  264. foreach ($messages as $message) {
  265. $tag = 'message_'.$message->getId();
  266. $tagAccordion = 'accordion_'.$message->getId();
  267. $tagCollapse = 'collapse_'.$message->getId();
  268. $date = Display::dateToStringAgoAndLongDate(
  269. $message->getSendDate()
  270. );
  271. $localTime = api_get_local_time(
  272. $message->getSendDate(),
  273. null,
  274. null,
  275. false,
  276. false
  277. );
  278. $senderId = $message->getUserSenderId();
  279. $senderInfo = api_get_user_info($senderId);
  280. $html .= Display::panelCollapse(
  281. $localTime.' '.$senderInfo['complete_name'].' '.$message->getTitle(),
  282. $message->getContent().'<br />'.$date.'<br />'.get_lang(
  283. 'Author'
  284. ).': '.$senderInfo['complete_name_with_message_link'],
  285. $tag,
  286. null,
  287. $tagAccordion,
  288. $tagCollapse,
  289. false
  290. );
  291. }
  292. }
  293. return $html;
  294. }
  295. /**
  296. * @param int $senderId
  297. * @param int $receiverId
  298. * @param string $subject
  299. * @param string $message
  300. *
  301. * @return bool
  302. */
  303. public static function messageWasAlreadySent($senderId, $receiverId, $subject, $message)
  304. {
  305. $table = Database::get_main_table(TABLE_MESSAGE);
  306. $senderId = (int) $senderId;
  307. $receiverId = (int) $receiverId;
  308. $subject = Database::escape_string($subject);
  309. $message = Database::escape_string($message);
  310. $sql = "SELECT * FROM $table
  311. WHERE
  312. user_sender_id = $senderId AND
  313. user_receiver_id = $receiverId AND
  314. title = '$subject' AND
  315. content = '$message' AND
  316. (msg_status = ".MESSAGE_STATUS_UNREAD." OR msg_status = ".MESSAGE_STATUS_NEW.")
  317. ";
  318. $result = Database::query($sql);
  319. return Database::num_rows($result) > 0;
  320. }
  321. /**
  322. * Sends a message to a user/group.
  323. *
  324. * @param int $receiver_user_id
  325. * @param string $subject
  326. * @param string $content
  327. * @param array $attachments files array($_FILES) (optional)
  328. * @param array $fileCommentList about attachment files (optional)
  329. * @param int $group_id (optional)
  330. * @param int $parent_id (optional)
  331. * @param int $editMessageId id for updating the message (optional)
  332. * @param int $topic_id (optional) the default value is the current user_id
  333. * @param int $sender_id
  334. * @param bool $directMessage
  335. * @param int $forwardId
  336. * @param array $smsParameters
  337. * @param bool $checkCurrentAudioId
  338. * @param bool $forceTitleWhenSendingEmail force the use of $title as subject instead of "You have a new message"
  339. *
  340. * @return bool
  341. */
  342. public static function send_message(
  343. $receiver_user_id,
  344. $subject,
  345. $content,
  346. array $attachments = [],
  347. array $fileCommentList = [],
  348. $group_id = 0,
  349. $parent_id = 0,
  350. $editMessageId = 0,
  351. $topic_id = 0,
  352. $sender_id = 0,
  353. $directMessage = false,
  354. $forwardId = 0,
  355. $smsParameters = [],
  356. $checkCurrentAudioId = false,
  357. $forceTitleWhenSendingEmail = false
  358. ) {
  359. $table = Database::get_main_table(TABLE_MESSAGE);
  360. $group_id = (int) $group_id;
  361. $receiver_user_id = (int) $receiver_user_id;
  362. $parent_id = (int) $parent_id;
  363. $editMessageId = (int) $editMessageId;
  364. $topic_id = (int) $topic_id;
  365. if (!empty($receiver_user_id)) {
  366. $receiverUserInfo = api_get_user_info($receiver_user_id);
  367. // Disabling messages for inactive users.
  368. if ($receiverUserInfo['active'] == 0) {
  369. return false;
  370. }
  371. }
  372. $user_sender_id = empty($sender_id) ? api_get_user_id() : (int) $sender_id;
  373. if (empty($user_sender_id)) {
  374. Display::addFlash(Display::return_message(get_lang('UserDoesNotExist'), 'warning'));
  375. return false;
  376. }
  377. $totalFileSize = 0;
  378. $attachmentList = [];
  379. if (is_array($attachments)) {
  380. $counter = 0;
  381. foreach ($attachments as $attachment) {
  382. $attachment['comment'] = isset($fileCommentList[$counter]) ? $fileCommentList[$counter] : '';
  383. $fileSize = isset($attachment['size']) ? $attachment['size'] : 0;
  384. if (is_array($fileSize)) {
  385. foreach ($fileSize as $size) {
  386. $totalFileSize += $size;
  387. }
  388. } else {
  389. $totalFileSize += $fileSize;
  390. }
  391. $attachmentList[] = $attachment;
  392. $counter++;
  393. }
  394. }
  395. if ($checkCurrentAudioId) {
  396. // Add the audio file as an attachment
  397. $audioId = Session::read('current_audio_id');
  398. if (!empty($audioId)) {
  399. $file = api_get_uploaded_file('audio_message', api_get_user_id(), $audioId);
  400. if (!empty($file)) {
  401. $audioAttachment = [
  402. 'name' => basename($file),
  403. 'comment' => 'audio_message',
  404. 'size' => filesize($file),
  405. 'tmp_name' => $file,
  406. 'error' => 0,
  407. 'type' => DocumentManager::file_get_mime_type(basename($file)),
  408. ];
  409. // create attachment from audio message
  410. $attachmentList[] = $audioAttachment;
  411. }
  412. }
  413. }
  414. // Validating fields
  415. if (empty($subject) && empty($group_id)) {
  416. Display::addFlash(
  417. Display::return_message(
  418. get_lang('YouShouldWriteASubject'),
  419. 'warning'
  420. )
  421. );
  422. return false;
  423. } elseif ($totalFileSize > intval(api_get_setting('message_max_upload_filesize'))) {
  424. $warning = sprintf(
  425. get_lang('FilesSizeExceedsX'),
  426. format_file_size(api_get_setting('message_max_upload_filesize'))
  427. );
  428. Display::addFlash(Display::return_message($warning, 'warning'));
  429. return false;
  430. }
  431. // Just in case we replace the and \n and \n\r while saving in the DB
  432. // $content = str_replace(array("\n", "\n\r"), '<br />', $content);
  433. $now = api_get_utc_datetime();
  434. if (!empty($receiver_user_id) || !empty($group_id)) {
  435. // message for user friend
  436. //@todo it's possible to edit a message? yes, only for groups
  437. if (!empty($editMessageId)) {
  438. $query = " UPDATE $table SET
  439. update_date = '".$now."',
  440. content = '".Database::escape_string($content)."'
  441. WHERE id = '$editMessageId' ";
  442. Database::query($query);
  443. $messageId = $editMessageId;
  444. } else {
  445. $params = [
  446. 'user_sender_id' => $user_sender_id,
  447. 'user_receiver_id' => $receiver_user_id,
  448. 'msg_status' => MESSAGE_STATUS_UNREAD,
  449. 'send_date' => $now,
  450. 'title' => $subject,
  451. 'content' => $content,
  452. 'group_id' => $group_id,
  453. 'parent_id' => $parent_id,
  454. 'update_date' => $now,
  455. ];
  456. $messageId = Database::insert($table, $params);
  457. }
  458. // Forward also message attachments
  459. if (!empty($forwardId)) {
  460. $attachments = self::getAttachmentList($forwardId);
  461. foreach ($attachments as $attachment) {
  462. if (!empty($attachment['file_source'])) {
  463. $file = [
  464. 'name' => $attachment['filename'],
  465. 'tmp_name' => $attachment['file_source'],
  466. 'size' => $attachment['size'],
  467. 'error' => 0,
  468. 'comment' => $attachment['comment'],
  469. ];
  470. // Inject this array so files can be added when sending and email with the mailer
  471. $attachmentList[] = $file;
  472. }
  473. }
  474. }
  475. // Save attachment file for inbox messages
  476. if (is_array($attachmentList)) {
  477. foreach ($attachmentList as $attachment) {
  478. if ($attachment['error'] == 0) {
  479. $comment = $attachment['comment'];
  480. self::saveMessageAttachmentFile(
  481. $attachment,
  482. $comment,
  483. $messageId,
  484. null,
  485. $receiver_user_id,
  486. $group_id
  487. );
  488. }
  489. }
  490. }
  491. if (empty($group_id)) {
  492. // message in outbox for user friend or group
  493. $params = [
  494. 'user_sender_id' => $user_sender_id,
  495. 'user_receiver_id' => $receiver_user_id,
  496. 'msg_status' => MESSAGE_STATUS_OUTBOX,
  497. 'send_date' => $now,
  498. 'title' => $subject,
  499. 'content' => $content,
  500. 'group_id' => $group_id,
  501. 'parent_id' => $parent_id,
  502. 'update_date' => $now,
  503. ];
  504. $outbox_last_id = Database::insert($table, $params);
  505. // save attachment file for outbox messages
  506. if (is_array($attachmentList)) {
  507. foreach ($attachmentList as $attachment) {
  508. if ($attachment['error'] == 0) {
  509. $comment = $attachment['comment'];
  510. self::saveMessageAttachmentFile(
  511. $attachment,
  512. $comment,
  513. $outbox_last_id,
  514. $user_sender_id
  515. );
  516. }
  517. }
  518. }
  519. }
  520. // Load user settings.
  521. $notification = new Notification();
  522. $sender_info = api_get_user_info($user_sender_id);
  523. // add file attachment additional attributes
  524. $attachmentAddedByMail = [];
  525. foreach ($attachmentList as $attachment) {
  526. $attachmentAddedByMail[] = [
  527. 'path' => $attachment['tmp_name'],
  528. 'filename' => $attachment['name'],
  529. ];
  530. }
  531. if (empty($group_id)) {
  532. $type = Notification::NOTIFICATION_TYPE_MESSAGE;
  533. if ($directMessage) {
  534. $type = Notification::NOTIFICATION_TYPE_DIRECT_MESSAGE;
  535. }
  536. $notification->saveNotification(
  537. $messageId,
  538. $type,
  539. [$receiver_user_id],
  540. $subject,
  541. $content,
  542. $sender_info,
  543. $attachmentAddedByMail,
  544. $smsParameters,
  545. $forceTitleWhenSendingEmail
  546. );
  547. } else {
  548. $usergroup = new UserGroup();
  549. $group_info = $usergroup->get($group_id);
  550. $group_info['topic_id'] = $topic_id;
  551. $group_info['msg_id'] = $messageId;
  552. $user_list = $usergroup->get_users_by_group(
  553. $group_id,
  554. false,
  555. [],
  556. 0,
  557. 1000
  558. );
  559. // Adding more sense to the message group
  560. $subject = sprintf(get_lang('ThereIsANewMessageInTheGroupX'), $group_info['name']);
  561. $new_user_list = [];
  562. foreach ($user_list as $user_data) {
  563. $new_user_list[] = $user_data['id'];
  564. }
  565. $group_info = [
  566. 'group_info' => $group_info,
  567. 'user_info' => $sender_info,
  568. ];
  569. $notification->saveNotification(
  570. $messageId,
  571. Notification::NOTIFICATION_TYPE_GROUP,
  572. $new_user_list,
  573. $subject,
  574. $content,
  575. $group_info,
  576. $attachmentAddedByMail,
  577. $smsParameters
  578. );
  579. }
  580. return $messageId;
  581. }
  582. return false;
  583. }
  584. /**
  585. * @param int $receiver_user_id
  586. * @param int $subject
  587. * @param string $message
  588. * @param int $sender_id
  589. * @param bool $sendCopyToDrhUsers send copy to related DRH users
  590. * @param bool $directMessage
  591. * @param array $smsParameters
  592. * @param bool $uploadFiles Do not upload files using the MessageManager class
  593. * @param array $attachmentList
  594. *
  595. * @return bool
  596. */
  597. public static function send_message_simple(
  598. $receiver_user_id,
  599. $subject,
  600. $message,
  601. $sender_id = 0,
  602. $sendCopyToDrhUsers = false,
  603. $directMessage = false,
  604. $smsParameters = [],
  605. $uploadFiles = true,
  606. $attachmentList = []
  607. ) {
  608. $files = $_FILES ? $_FILES : [];
  609. if ($uploadFiles === false) {
  610. $files = [];
  611. }
  612. // $attachmentList must have: tmp_name, name, size keys
  613. if (!empty($attachmentList)) {
  614. $files = $attachmentList;
  615. }
  616. $result = self::send_message(
  617. $receiver_user_id,
  618. $subject,
  619. $message,
  620. $files,
  621. [],
  622. null,
  623. null,
  624. null,
  625. null,
  626. $sender_id,
  627. $directMessage,
  628. 0,
  629. $smsParameters
  630. );
  631. if ($sendCopyToDrhUsers) {
  632. $userInfo = api_get_user_info($receiver_user_id);
  633. $drhList = UserManager::getDrhListFromUser($receiver_user_id);
  634. if (!empty($drhList)) {
  635. foreach ($drhList as $drhInfo) {
  636. $message = sprintf(
  637. get_lang('CopyOfMessageSentToXUser'),
  638. $userInfo['complete_name']
  639. ).' <br />'.$message;
  640. self::send_message_simple(
  641. $drhInfo['user_id'],
  642. $subject,
  643. $message,
  644. $sender_id,
  645. false,
  646. $directMessage
  647. );
  648. }
  649. }
  650. }
  651. return $result;
  652. }
  653. /**
  654. * Update parent ids for other receiver user from current message in groups.
  655. *
  656. * @author Christian Fasanando Flores
  657. *
  658. * @param int $parent_id
  659. * @param int $receiver_user_id
  660. * @param int $messageId
  661. */
  662. public static function update_parent_ids_from_reply(
  663. $parent_id,
  664. $receiver_user_id,
  665. $messageId
  666. ) {
  667. $table = Database::get_main_table(TABLE_MESSAGE);
  668. $parent_id = intval($parent_id);
  669. $receiver_user_id = intval($receiver_user_id);
  670. $messageId = intval($messageId);
  671. // first get data from message id (parent)
  672. $sql = "SELECT * FROM $table WHERE id = '$parent_id'";
  673. $rs_message = Database::query($sql);
  674. $row_message = Database::fetch_array($rs_message);
  675. // get message id from data found early for other receiver user
  676. $sql = "SELECT id FROM $table
  677. WHERE
  678. user_sender_id ='{$row_message['user_sender_id']}' AND
  679. title='{$row_message['title']}' AND
  680. content='{$row_message['content']}' AND
  681. group_id='{$row_message['group_id']}' AND
  682. user_receiver_id='$receiver_user_id'";
  683. $result = Database::query($sql);
  684. $row = Database::fetch_array($result);
  685. // update parent_id for other user receiver
  686. $sql = "UPDATE $table SET parent_id = ".$row['id']."
  687. WHERE id = $messageId";
  688. Database::query($sql);
  689. }
  690. /**
  691. * @param int $user_receiver_id
  692. * @param int $id
  693. *
  694. * @return bool
  695. */
  696. public static function delete_message_by_user_receiver($user_receiver_id, $id)
  697. {
  698. $table = Database::get_main_table(TABLE_MESSAGE);
  699. if ($id != strval(intval($id))) {
  700. return false;
  701. }
  702. $id = (int) $id;
  703. $user_receiver_id = (int) $user_receiver_id;
  704. $sql = "SELECT * FROM $table
  705. WHERE id = ".$id." AND msg_status <>".MESSAGE_STATUS_OUTBOX;
  706. $rs = Database::query($sql);
  707. if (Database::num_rows($rs) > 0) {
  708. // delete attachment file
  709. self::delete_message_attachment_file($id, $user_receiver_id);
  710. // delete message
  711. $query = "UPDATE $table
  712. SET msg_status = ".MESSAGE_STATUS_DELETED."
  713. WHERE
  714. user_receiver_id=".$user_receiver_id." AND
  715. id = ".$id;
  716. Database::query($query);
  717. return true;
  718. } else {
  719. return false;
  720. }
  721. }
  722. /**
  723. * Set status deleted.
  724. *
  725. * @author Isaac FLores Paz <isaac.flores@dokeos.com>
  726. *
  727. * @param int
  728. * @param int
  729. *
  730. * @return bool
  731. */
  732. public static function delete_message_by_user_sender($user_sender_id, $id)
  733. {
  734. if ($id != strval(intval($id))) {
  735. return false;
  736. }
  737. $table = Database::get_main_table(TABLE_MESSAGE);
  738. $id = intval($id);
  739. $user_sender_id = intval($user_sender_id);
  740. $sql = "SELECT * FROM $table WHERE id='$id'";
  741. $rs = Database::query($sql);
  742. if (Database::num_rows($rs) > 0) {
  743. // delete attachment file
  744. self::delete_message_attachment_file($id, $user_sender_id);
  745. // delete message
  746. $sql = "UPDATE $table
  747. SET msg_status = ".MESSAGE_STATUS_DELETED."
  748. WHERE user_sender_id='$user_sender_id' AND id='$id'";
  749. Database::query($sql);
  750. return true;
  751. }
  752. return false;
  753. }
  754. /**
  755. * Saves a message attachment files.
  756. *
  757. * @param array $file_attach $_FILES['name']
  758. * @param string a comment about the uploaded file
  759. * @param int message id
  760. * @param int receiver user id (optional)
  761. * @param int sender user id (optional)
  762. * @param int group id (optional)
  763. */
  764. public static function saveMessageAttachmentFile(
  765. $file_attach,
  766. $file_comment,
  767. $message_id,
  768. $receiver_user_id = 0,
  769. $sender_user_id = 0,
  770. $group_id = 0
  771. ) {
  772. $table = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  773. // Try to add an extension to the file if it hasn't one
  774. $type = isset($file_attach['type']) ? $file_attach['type'] : '';
  775. if (empty($type)) {
  776. $type = DocumentManager::file_get_mime_type($file_attach['name']);
  777. }
  778. $new_file_name = add_ext_on_mime(stripslashes($file_attach['name']), $type);
  779. // user's file name
  780. $file_name = $file_attach['name'];
  781. if (!filter_extension($new_file_name)) {
  782. Display::addFlash(Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error'));
  783. } else {
  784. $new_file_name = uniqid('');
  785. if (!empty($receiver_user_id)) {
  786. $message_user_id = $receiver_user_id;
  787. } else {
  788. $message_user_id = $sender_user_id;
  789. }
  790. // User-reserved directory where photos have to be placed.*
  791. $userGroup = new UserGroup();
  792. if (!empty($group_id)) {
  793. $path_user_info = $userGroup->get_group_picture_path_by_id(
  794. $group_id,
  795. 'system',
  796. true
  797. );
  798. } else {
  799. $path_user_info['dir'] = UserManager::getUserPathById($message_user_id, 'system');
  800. }
  801. $path_message_attach = $path_user_info['dir'].'message_attachments/';
  802. // If this directory does not exist - we create it.
  803. if (!file_exists($path_message_attach)) {
  804. @mkdir($path_message_attach, api_get_permissions_for_new_directories(), true);
  805. }
  806. $new_path = $path_message_attach.$new_file_name;
  807. $fileCopied = false;
  808. if (isset($file_attach['tmp_name']) && !empty($file_attach['tmp_name'])) {
  809. if (is_uploaded_file($file_attach['tmp_name'])) {
  810. @copy($file_attach['tmp_name'], $new_path);
  811. $fileCopied = true;
  812. } else {
  813. // 'tmp_name' can be set by the ticket or when forwarding a message
  814. if (file_exists($file_attach['tmp_name'])) {
  815. @copy($file_attach['tmp_name'], $new_path);
  816. $fileCopied = true;
  817. }
  818. }
  819. }
  820. if ($fileCopied) {
  821. // Storing the attachments if any
  822. $params = [
  823. 'filename' => $file_name,
  824. 'comment' => $file_comment,
  825. 'path' => $new_file_name,
  826. 'message_id' => $message_id,
  827. 'size' => $file_attach['size'],
  828. ];
  829. return Database::insert($table, $params);
  830. }
  831. }
  832. return false;
  833. }
  834. /**
  835. * Delete message attachment files (logically updating the row with a suffix _DELETE_id).
  836. *
  837. * @param int message id
  838. * @param int message user id (receiver user id or sender user id)
  839. * @param int group id (optional)
  840. */
  841. public static function delete_message_attachment_file(
  842. $message_id,
  843. $message_uid,
  844. $group_id = 0
  845. ) {
  846. $message_id = (int) $message_id;
  847. $message_uid = (int) $message_uid;
  848. $table_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  849. $sql = "SELECT * FROM $table_message_attach
  850. WHERE message_id = '$message_id'";
  851. $rs = Database::query($sql);
  852. while ($row = Database::fetch_array($rs)) {
  853. $path = $row['path'];
  854. $attach_id = $row['id'];
  855. $new_path = $path.'_DELETED_'.$attach_id;
  856. if (!empty($group_id)) {
  857. $userGroup = new UserGroup();
  858. $path_user_info = $userGroup->get_group_picture_path_by_id(
  859. $group_id,
  860. 'system',
  861. true
  862. );
  863. } else {
  864. $path_user_info['dir'] = UserManager::getUserPathById(
  865. $message_uid,
  866. 'system'
  867. );
  868. }
  869. $path_message_attach = $path_user_info['dir'].'message_attachments/';
  870. if (is_file($path_message_attach.$path)) {
  871. if (rename($path_message_attach.$path, $path_message_attach.$new_path)) {
  872. $sql = "UPDATE $table_message_attach set path='$new_path'
  873. WHERE id ='$attach_id'";
  874. Database::query($sql);
  875. }
  876. }
  877. }
  878. }
  879. /**
  880. * @param int $user_id
  881. * @param int $message_id
  882. * @param int $type
  883. *
  884. * @return bool
  885. */
  886. public static function update_message_status($user_id, $message_id, $type)
  887. {
  888. $user_id = (int) $user_id;
  889. $message_id = (int) $message_id;
  890. $type = (int) $type;
  891. if (empty($user_id) || empty($message_id)) {
  892. return false;
  893. }
  894. $table_message = Database::get_main_table(TABLE_MESSAGE);
  895. $sql = "UPDATE $table_message SET
  896. msg_status = '$type'
  897. WHERE
  898. user_receiver_id = ".$user_id." AND
  899. id = '".$message_id."'";
  900. Database::query($sql);
  901. }
  902. /**
  903. * get messages by group id.
  904. *
  905. * @param int $group_id group id
  906. *
  907. * @return array
  908. */
  909. public static function get_messages_by_group($group_id)
  910. {
  911. if ($group_id != strval(intval($group_id))) {
  912. return false;
  913. }
  914. $table = Database::get_main_table(TABLE_MESSAGE);
  915. $group_id = intval($group_id);
  916. $sql = "SELECT * FROM $table
  917. WHERE
  918. group_id= $group_id AND
  919. msg_status NOT IN ('".MESSAGE_STATUS_OUTBOX."', '".MESSAGE_STATUS_DELETED."')
  920. ORDER BY id";
  921. $rs = Database::query($sql);
  922. $data = [];
  923. if (Database::num_rows($rs) > 0) {
  924. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  925. $data[] = $row;
  926. }
  927. }
  928. return $data;
  929. }
  930. /**
  931. * get messages by group id.
  932. *
  933. * @param int $group_id
  934. * @param int $message_id
  935. *
  936. * @return array
  937. */
  938. public static function get_messages_by_group_by_message($group_id, $message_id)
  939. {
  940. if ($group_id != strval(intval($group_id))) {
  941. return false;
  942. }
  943. $table = Database::get_main_table(TABLE_MESSAGE);
  944. $group_id = intval($group_id);
  945. $sql = "SELECT * FROM $table
  946. WHERE
  947. group_id = $group_id AND
  948. msg_status NOT IN ('".MESSAGE_STATUS_OUTBOX."', '".MESSAGE_STATUS_DELETED."')
  949. ORDER BY id ";
  950. $rs = Database::query($sql);
  951. $data = [];
  952. $parents = [];
  953. if (Database::num_rows($rs) > 0) {
  954. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  955. if ($message_id == $row['parent_id'] || in_array($row['parent_id'], $parents)) {
  956. $parents[] = $row['id'];
  957. $data[] = $row;
  958. }
  959. }
  960. }
  961. return $data;
  962. }
  963. /**
  964. * Get messages by parent id optionally with limit.
  965. *
  966. * @param int parent id
  967. * @param int group id (optional)
  968. * @param int offset (optional)
  969. * @param int limit (optional)
  970. *
  971. * @return array
  972. */
  973. public static function getMessagesByParent($parentId, $groupId = 0, $offset = 0, $limit = 0)
  974. {
  975. $table = Database::get_main_table(TABLE_MESSAGE);
  976. $parentId = (int) $parentId;
  977. if (empty($parentId)) {
  978. return [];
  979. }
  980. $condition_group_id = '';
  981. if (!empty($groupId)) {
  982. $groupId = (int) $groupId;
  983. $condition_group_id = " AND group_id = '$groupId' ";
  984. }
  985. $condition_limit = '';
  986. if ($offset && $limit) {
  987. $offset = (int) $offset;
  988. $limit = (int) $limit;
  989. $offset = ($offset - 1) * $limit;
  990. $condition_limit = " LIMIT $offset,$limit ";
  991. }
  992. $sql = "SELECT * FROM $table
  993. WHERE
  994. parent_id='$parentId' AND
  995. msg_status NOT IN (".MESSAGE_STATUS_OUTBOX.", ".MESSAGE_STATUS_WALL_DELETE.")
  996. $condition_group_id
  997. ORDER BY send_date DESC $condition_limit ";
  998. $rs = Database::query($sql);
  999. $data = [];
  1000. if (Database::num_rows($rs) > 0) {
  1001. while ($row = Database::fetch_array($rs)) {
  1002. $data[$row['id']] = $row;
  1003. }
  1004. }
  1005. return $data;
  1006. }
  1007. /**
  1008. * Gets information about messages sent.
  1009. *
  1010. * @param int
  1011. * @param int
  1012. * @param string
  1013. * @param string
  1014. *
  1015. * @return array
  1016. */
  1017. public static function get_message_data_sent(
  1018. $from,
  1019. $number_of_items,
  1020. $column,
  1021. $direction
  1022. ) {
  1023. $from = (int) $from;
  1024. $number_of_items = (int) $number_of_items;
  1025. if (!isset($direction)) {
  1026. $column = 2;
  1027. $direction = 'DESC';
  1028. } else {
  1029. $column = (int) $column;
  1030. if (!in_array($direction, ['ASC', 'DESC'])) {
  1031. $direction = 'ASC';
  1032. }
  1033. }
  1034. if (!in_array($column, [0, 1, 2])) {
  1035. $column = 2;
  1036. }
  1037. $table = Database::get_main_table(TABLE_MESSAGE);
  1038. $request = api_is_xml_http_request();
  1039. $keyword = Session::read('message_sent_search_keyword');
  1040. $keywordCondition = '';
  1041. if (!empty($keyword)) {
  1042. $keyword = Database::escape_string($keyword);
  1043. $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
  1044. }
  1045. $sql = "SELECT
  1046. id as col0,
  1047. title as col1,
  1048. send_date as col2,
  1049. user_receiver_id,
  1050. msg_status,
  1051. user_sender_id
  1052. FROM $table
  1053. WHERE
  1054. user_sender_id = ".api_get_user_id()." AND
  1055. msg_status = ".MESSAGE_STATUS_OUTBOX."
  1056. $keywordCondition
  1057. ORDER BY col$column $direction
  1058. LIMIT $from, $number_of_items";
  1059. $result = Database::query($sql);
  1060. $message_list = [];
  1061. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1062. $messageId = $row['col0'];
  1063. $title = $row['col1'];
  1064. $sendDate = $row['col2'];
  1065. $senderId = $row['user_sender_id'];
  1066. if ($request === true) {
  1067. $message[0] = '<input type="checkbox" value='.$messageId.' name="out[]">';
  1068. } else {
  1069. $message[0] = $messageId;
  1070. }
  1071. $class = 'class = "read"';
  1072. $title = Security::remove_XSS($title);
  1073. $userInfo = api_get_user_info($senderId);
  1074. if ($request === true) {
  1075. $message[1] = '<a onclick="show_sent_message('.$messageId.')" href="javascript:void(0)">'.
  1076. $userInfo['complete_name_with_username'].'</a>';
  1077. $message[2] = '<a onclick="show_sent_message('.$messageId.')" href="javascript:void(0)">'.str_replace(
  1078. "\\",
  1079. "",
  1080. $title
  1081. ).'</a>';
  1082. //date stays the same
  1083. $message[3] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
  1084. $message[4] = '&nbsp;&nbsp;<a title="'.addslashes(
  1085. get_lang('DeleteMessage')
  1086. ).'" onclick="delete_one_message_outbox('.$messageId.')" href="javascript:void(0)" >'.
  1087. Display::returnFontAwesomeIcon('trash', 2).'</a>';
  1088. } else {
  1089. $message[1] = '<a '.$class.' onclick="show_sent_message('.$messageId.')" href="../messages/view_message.php?id_send='.$messageId.'">'.$title.'</a><br />'.$userInfo['complete_name_with_username'];
  1090. $message[2] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
  1091. $message[3] = '<a title="'.addslashes(
  1092. get_lang('DeleteMessage')
  1093. ).'" href="outbox.php?action=deleteone&id='.$messageId.'" onclick="javascript:if(!confirm('."'".addslashes(
  1094. api_htmlentities(get_lang('ConfirmDeleteMessage'))
  1095. )."'".')) return false;" >'.
  1096. Display::returnFontAwesomeIcon('trash', 2).'</a>';
  1097. }
  1098. $message_list[] = $message;
  1099. }
  1100. return $message_list;
  1101. }
  1102. /**
  1103. * Gets information about number messages sent.
  1104. *
  1105. * @author Isaac FLores Paz <isaac.flores@dokeos.com>
  1106. *
  1107. * @param void
  1108. *
  1109. * @return int
  1110. */
  1111. public static function getNumberOfMessagesSent()
  1112. {
  1113. $table = Database::get_main_table(TABLE_MESSAGE);
  1114. $keyword = Session::read('message_sent_search_keyword');
  1115. $keywordCondition = '';
  1116. if (!empty($keyword)) {
  1117. $keyword = Database::escape_string($keyword);
  1118. $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
  1119. }
  1120. $sql = "SELECT COUNT(id) as number_messages
  1121. FROM $table
  1122. WHERE
  1123. msg_status = ".MESSAGE_STATUS_OUTBOX." AND
  1124. user_sender_id = ".api_get_user_id()."
  1125. $keywordCondition
  1126. ";
  1127. $result = Database::query($sql);
  1128. $result = Database::fetch_array($result);
  1129. return $result['number_messages'];
  1130. }
  1131. /**
  1132. * display message box in the inbox.
  1133. *
  1134. * @param int the message id
  1135. * @param string inbox or outbox strings are available
  1136. *
  1137. * @todo replace numbers with letters in the $row array pff...
  1138. *
  1139. * @return string html with the message content
  1140. */
  1141. public static function showMessageBox($messageId, $source = 'inbox')
  1142. {
  1143. $table = Database::get_main_table(TABLE_MESSAGE);
  1144. $messageId = (int) $messageId;
  1145. $currentUserId = api_get_user_id();
  1146. if ($source == 'outbox') {
  1147. if (isset($messageId) && is_numeric($messageId)) {
  1148. $query = "SELECT * FROM $table
  1149. WHERE
  1150. user_sender_id = ".$currentUserId." AND
  1151. id = $messageId AND
  1152. msg_status = ".MESSAGE_STATUS_OUTBOX;
  1153. $result = Database::query($query);
  1154. }
  1155. } else {
  1156. if (is_numeric($messageId) && !empty($messageId)) {
  1157. $query = "UPDATE $table SET
  1158. msg_status = '".MESSAGE_STATUS_NEW."'
  1159. WHERE
  1160. user_receiver_id=".$currentUserId." AND
  1161. id = '".$messageId."'";
  1162. Database::query($query);
  1163. $query = "SELECT * FROM $table
  1164. WHERE
  1165. msg_status<> ".MESSAGE_STATUS_OUTBOX." AND
  1166. user_receiver_id = ".$currentUserId." AND
  1167. id = '".$messageId."'";
  1168. $result = Database::query($query);
  1169. }
  1170. }
  1171. $row = Database::fetch_array($result, 'ASSOC');
  1172. if (empty($row)) {
  1173. return '';
  1174. }
  1175. $user_sender_id = $row['user_sender_id'];
  1176. // get file attachments by message id
  1177. $files_attachments = self::getAttachmentLinkList(
  1178. $messageId,
  1179. $source
  1180. );
  1181. $row['content'] = str_replace('</br>', '<br />', $row['content']);
  1182. $title = Security::remove_XSS($row['title'], STUDENT, true);
  1183. $content = Security::remove_XSS($row['content'], STUDENT, true);
  1184. $name = get_lang('UnknownUser');
  1185. $fromUser = api_get_user_info($user_sender_id);
  1186. $userImage = '';
  1187. if (!empty($user_sender_id) && !empty($fromUser)) {
  1188. $name = $fromUser['complete_name_with_username'];
  1189. $userImage = Display::img(
  1190. $fromUser['avatar_small'],
  1191. $name,
  1192. ['title' => $name, 'class' => 'img-responsive img-circle', 'style' => 'max-width:35px'],
  1193. false
  1194. );
  1195. }
  1196. $message_content = Display::page_subheader(str_replace("\\", "", $title));
  1197. $receiverUserInfo = [];
  1198. if (!empty($row['user_receiver_id'])) {
  1199. $receiverUserInfo = api_get_user_info($row['user_receiver_id']);
  1200. }
  1201. $message_content .= '<tr>';
  1202. if (api_get_setting('allow_social_tool') === 'true') {
  1203. $message_content .= '<div class="row">';
  1204. if ($source == 'outbox') {
  1205. $message_content .= '<div class="col-md-12">';
  1206. $message_content .= '<ul class="list-message">';
  1207. $message_content .= '<li>'.$userImage.'</li>';
  1208. $message_content .= '<li>'.$name.'&nbsp;';
  1209. if (!empty($receiverUserInfo)) {
  1210. $message_content .= api_strtolower(
  1211. get_lang('To')
  1212. ).'&nbsp;<b>'.$receiverUserInfo['complete_name_with_username'].'</b></li>';
  1213. } else {
  1214. $message_content .= api_strtolower(get_lang('To')).'&nbsp;<b>-</b></li>';
  1215. }
  1216. $message_content .= '<li>'.Display::dateToStringAgoAndLongDate($row['send_date']).'</li>';
  1217. $message_content .= '</ul>';
  1218. $message_content .= '</div>';
  1219. } else {
  1220. $message_content .= '<div class="col-md-12">';
  1221. $message_content .= '<ul class="list-message">';
  1222. if (!empty($user_sender_id)) {
  1223. $message_content .= '<li>'.$userImage.'</li>';
  1224. $message_content .= '<li><a href="'.api_get_path(
  1225. WEB_PATH
  1226. ).'main/social/profile.php?u='.$user_sender_id.'">'.$name.'</a>';
  1227. } else {
  1228. $message_content .= '<li>'.$name;
  1229. }
  1230. $message_content .= '&nbsp;'.api_strtolower(get_lang('To')).'&nbsp;'.get_lang('Me');
  1231. $message_content .= '<li>'.Display::dateToStringAgoAndLongDate($row['send_date']).'</li>';
  1232. $message_content .= '</ul>';
  1233. $message_content .= '</div>';
  1234. }
  1235. $message_content .= '</div>';
  1236. } else {
  1237. if ($source == 'outbox') {
  1238. $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.
  1239. $receiverUserInfo['complete_name_with_username'].'</b>';
  1240. } else {
  1241. $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.
  1242. get_lang('Me').'</b>';
  1243. }
  1244. }
  1245. $message_content .= '
  1246. <hr style="color:#ddd" />
  1247. <table width="100%">
  1248. <tr>
  1249. <td valign=top class="view-message-content">'.str_replace("\\", "", $content).'</td>
  1250. </tr>
  1251. </table>
  1252. <div id="message-attach">'.(!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>
  1253. <div style="padding: 15px 0px 5px 0px">';
  1254. $social_link = '';
  1255. if (isset($_GET['f']) && $_GET['f'] == 'social') {
  1256. $social_link = 'f=social';
  1257. }
  1258. if ($source == 'outbox') {
  1259. $message_content .= '<a href="outbox.php?'.$social_link.'">'.
  1260. Display::return_icon('back.png', get_lang('ReturnToOutbox')).'</a> &nbsp';
  1261. } else {
  1262. $message_content .= '<a href="inbox.php?'.$social_link.'">'.
  1263. Display::return_icon('back.png', get_lang('ReturnToInbox')).'</a> &nbsp';
  1264. $message_content .= '<a href="new_message.php?re_id='.$messageId.'&'.$social_link.'">'.
  1265. Display::return_icon('message_reply.png', get_lang('ReplyToMessage')).'</a> &nbsp';
  1266. }
  1267. $message_content .= '<a href="inbox.php?action=deleteone&id='.$messageId.'&'.$social_link.'" >'.
  1268. Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>&nbsp';
  1269. $message_content .= '</div></td>
  1270. <td width=10></td>
  1271. </tr>
  1272. </table>';
  1273. return $message_content;
  1274. }
  1275. /**
  1276. * get user id by user email.
  1277. *
  1278. * @param string $user_email
  1279. *
  1280. * @return int user id
  1281. */
  1282. public static function get_user_id_by_email($user_email)
  1283. {
  1284. $table = Database::get_main_table(TABLE_MAIN_USER);
  1285. $sql = 'SELECT user_id
  1286. FROM '.$table.'
  1287. WHERE email="'.Database::escape_string($user_email).'";';
  1288. $rs = Database::query($sql);
  1289. $row = Database::fetch_array($rs, 'ASSOC');
  1290. if (isset($row['user_id'])) {
  1291. return $row['user_id'];
  1292. }
  1293. return null;
  1294. }
  1295. /**
  1296. * Displays messages of a group with nested view.
  1297. *
  1298. * @param int $groupId
  1299. *
  1300. * @return string
  1301. */
  1302. public static function display_messages_for_group($groupId)
  1303. {
  1304. global $my_group_role;
  1305. $rows = self::get_messages_by_group($groupId);
  1306. $topics_per_page = 10;
  1307. $html_messages = '';
  1308. $query_vars = ['id' => $groupId, 'topics_page_nr' => 0];
  1309. if (is_array($rows) && count($rows) > 0) {
  1310. // prepare array for topics with its items
  1311. $topics = [];
  1312. $x = 0;
  1313. foreach ($rows as $index => $value) {
  1314. if (empty($value['parent_id'])) {
  1315. $topics[$value['id']] = $value;
  1316. }
  1317. }
  1318. $new_topics = [];
  1319. foreach ($topics as $id => $value) {
  1320. $rows = null;
  1321. $rows = self::get_messages_by_group_by_message($groupId, $value['id']);
  1322. if (!empty($rows)) {
  1323. $count = count(self::calculate_children($rows, $value['id']));
  1324. } else {
  1325. $count = 0;
  1326. }
  1327. $value['count'] = $count;
  1328. $new_topics[$id] = $value;
  1329. }
  1330. $array_html = [];
  1331. foreach ($new_topics as $index => $topic) {
  1332. $html = '';
  1333. // topics
  1334. $user_sender_info = api_get_user_info($topic['user_sender_id']);
  1335. $name = $user_sender_info['complete_name'];
  1336. $html .= '<div class="groups-messages">';
  1337. $html .= '<div class="row">';
  1338. $items = $topic['count'];
  1339. $reply_label = ($items == 1) ? get_lang('GroupReply') : get_lang('GroupReplies');
  1340. $label = '<i class="fa fa-envelope"></i> '.$items.' '.$reply_label;
  1341. $topic['title'] = trim($topic['title']);
  1342. if (empty($topic['title'])) {
  1343. $topic['title'] = get_lang('Untitled');
  1344. }
  1345. $html .= '<div class="col-xs-8 col-md-10">';
  1346. $html .= Display::tag(
  1347. 'h4',
  1348. Display::url(
  1349. Security::remove_XSS($topic['title'], STUDENT, true),
  1350. api_get_path(WEB_CODE_PATH).'social/group_topics.php?id='.$groupId.'&topic_id='.$topic['id']
  1351. ),
  1352. ['class' => 'title']
  1353. );
  1354. $actions = '';
  1355. if ($my_group_role == GROUP_USER_PERMISSION_ADMIN ||
  1356. $my_group_role == GROUP_USER_PERMISSION_MODERATOR
  1357. ) {
  1358. $actions = '<br />'.Display::url(
  1359. get_lang('Delete'),
  1360. api_get_path(
  1361. WEB_CODE_PATH
  1362. ).'social/group_topics.php?action=delete&id='.$groupId.'&topic_id='.$topic['id'],
  1363. ['class' => 'btn btn-default']
  1364. );
  1365. }
  1366. $date = '';
  1367. if ($topic['send_date'] != $topic['update_date']) {
  1368. if (!empty($topic['update_date'])) {
  1369. $date .= '<i class="fa fa-calendar"></i> '.get_lang(
  1370. 'LastUpdate'
  1371. ).' '.Display::dateToStringAgoAndLongDate($topic['update_date']);
  1372. }
  1373. } else {
  1374. $date .= '<i class="fa fa-calendar"></i> '.get_lang(
  1375. 'Created'
  1376. ).' '.Display::dateToStringAgoAndLongDate($topic['send_date']);
  1377. }
  1378. $html .= '<div class="date">'.$label.' - '.$date.$actions.'</div>';
  1379. $html .= '</div>';
  1380. $image = $user_sender_info['avatar'];
  1381. $user_info = '<div class="author"><img class="img-responsive img-circle" src="'.$image.'" alt="'.$name.'" width="64" height="64" title="'.$name.'" /></div>';
  1382. $user_info .= '<div class="name"><a href="'.api_get_path(
  1383. WEB_PATH
  1384. ).'main/social/profile.php?u='.$topic['user_sender_id'].'">'.$name.'&nbsp;</a></div>';
  1385. $html .= '<div class="col-xs-4 col-md-2">';
  1386. $html .= $user_info;
  1387. $html .= '</div>';
  1388. $html .= '</div>';
  1389. $html .= '</div>';
  1390. $array_html[] = [$html];
  1391. }
  1392. // grids for items and topics with paginations
  1393. $html_messages .= Display::return_sortable_grid(
  1394. 'topics',
  1395. [],
  1396. $array_html,
  1397. [
  1398. 'hide_navigation' => false,
  1399. 'per_page' => $topics_per_page,
  1400. ],
  1401. $query_vars,
  1402. false,
  1403. [true, true, true, false],
  1404. false
  1405. );
  1406. }
  1407. return $html_messages;
  1408. }
  1409. /**
  1410. * Displays messages of a group with nested view.
  1411. *
  1412. * @param $groupId
  1413. * @param $topic_id
  1414. *
  1415. * @return string
  1416. */
  1417. public static function display_message_for_group($groupId, $topic_id)
  1418. {
  1419. global $my_group_role;
  1420. $main_message = self::get_message_by_id($topic_id);
  1421. if (empty($main_message)) {
  1422. return false;
  1423. }
  1424. $webCodePath = api_get_path(WEB_CODE_PATH);
  1425. $iconCalendar = Display::returnFontAwesomeIcon('calendar');
  1426. $langEdit = get_lang('Edit');
  1427. $langReply = get_lang('Reply');
  1428. $langLastUpdated = get_lang('LastUpdated');
  1429. $langCreated = get_lang('Created');
  1430. $rows = self::get_messages_by_group_by_message($groupId, $topic_id);
  1431. $rows = self::calculate_children($rows, $topic_id);
  1432. $current_user_id = api_get_user_id();
  1433. $items_per_page = 50;
  1434. $query_vars = ['id' => $groupId, 'topic_id' => $topic_id, 'topics_page_nr' => 0];
  1435. // Main message
  1436. $links = '';
  1437. $main_content = '';
  1438. $html = '';
  1439. $items_page_nr = null;
  1440. $user_sender_info = api_get_user_info($main_message['user_sender_id']);
  1441. $files_attachments = self::getAttachmentLinkList($main_message['id']);
  1442. $name = $user_sender_info['complete_name'];
  1443. $topic_page_nr = isset($_GET['topics_page_nr']) ? (int) $_GET['topics_page_nr'] : null;
  1444. $links .= '<div class="pull-right">';
  1445. $links .= '<div class="btn-group btn-group-sm">';
  1446. if (($my_group_role == GROUP_USER_PERMISSION_ADMIN || $my_group_role == GROUP_USER_PERMISSION_MODERATOR) ||
  1447. $main_message['user_sender_id'] == $current_user_id
  1448. ) {
  1449. $urlEdit = $webCodePath.'social/message_for_group_form.inc.php?'
  1450. .http_build_query(
  1451. [
  1452. 'user_friend' => $current_user_id,
  1453. 'group_id' => $groupId,
  1454. 'message_id' => $main_message['id'],
  1455. 'action' => 'edit_message_group',
  1456. 'anchor_topic' => 'topic_'.$main_message['id'],
  1457. 'topics_page_nr' => $topic_page_nr,
  1458. 'items_page_nr' => $items_page_nr,
  1459. 'topic_id' => $main_message['id'],
  1460. ]
  1461. );
  1462. $links .= Display::toolbarButton(
  1463. $langEdit,
  1464. $urlEdit,
  1465. 'pencil',
  1466. 'default',
  1467. ['class' => 'ajax', 'data-title' => $langEdit, 'data-size' => 'lg'],
  1468. false
  1469. );
  1470. }
  1471. $links .= self::getLikesButton($main_message['id'], $current_user_id, $groupId);
  1472. $urlReply = $webCodePath.'social/message_for_group_form.inc.php?'
  1473. .http_build_query(
  1474. [
  1475. 'user_friend' => $current_user_id,
  1476. 'group_id' => $groupId,
  1477. 'message_id' => $main_message['id'],
  1478. 'action' => 'reply_message_group',
  1479. 'anchor_topic' => 'topic_'.$main_message['id'],
  1480. 'topics_page_nr' => $topic_page_nr,
  1481. 'topic_id' => $main_message['id'],
  1482. ]
  1483. );
  1484. $links .= Display::toolbarButton(
  1485. $langReply,
  1486. $urlReply,
  1487. 'commenting',
  1488. 'default',
  1489. ['class' => 'ajax', 'data-title' => $langReply, 'data-size' => 'lg'],
  1490. false
  1491. );
  1492. if (api_is_platform_admin()) {
  1493. $links .= Display::toolbarButton(
  1494. get_lang('Delete'),
  1495. 'group_topics.php?action=delete&id='.$groupId.'&topic_id='.$topic_id,
  1496. 'trash',
  1497. 'default',
  1498. [],
  1499. false
  1500. );
  1501. }
  1502. $links .= '</div>';
  1503. $links .= '</div>';
  1504. $title = '<h4>'.Security::remove_XSS($main_message['title'], STUDENT, true).$links.'</h4>';
  1505. $userPicture = $user_sender_info['avatar'];
  1506. $main_content .= '<div class="row">';
  1507. $main_content .= '<div class="col-md-2">';
  1508. $main_content .= '<div class="avatar-author">';
  1509. $main_content .= Display::img(
  1510. $userPicture,
  1511. $name,
  1512. ['width' => '60px', 'class' => 'img-responsive img-circle'],
  1513. false
  1514. );
  1515. $main_content .= '</div>';
  1516. $main_content .= '</div>';
  1517. $date = '';
  1518. if ($main_message['send_date'] != $main_message['update_date']) {
  1519. if (!empty($main_message['update_date'])) {
  1520. $date = '<div class="date"> '
  1521. ."$iconCalendar $langLastUpdated "
  1522. .Display::dateToStringAgoAndLongDate($main_message['update_date'])
  1523. .'</div>';
  1524. }
  1525. } else {
  1526. $date = '<div class="date"> '
  1527. ."$iconCalendar $langCreated "
  1528. .Display::dateToStringAgoAndLongDate($main_message['send_date'])
  1529. .'</div>';
  1530. }
  1531. $attachment = '<div class="message-attach">'
  1532. .(!empty($files_attachments) ? implode('<br />', $files_attachments) : '')
  1533. .'</div>';
  1534. $main_content .= '<div class="col-md-10">';
  1535. $user_link = Display::url(
  1536. $name,
  1537. $webCodePath.'social/profile.php?u='.$main_message['user_sender_id']
  1538. );
  1539. $main_content .= '<div class="message-content"> ';
  1540. $main_content .= '<div class="username">'.$user_link.'</div>';
  1541. $main_content .= $date;
  1542. $main_content .= '<div class="message">'.$main_message['content'].$attachment.'</div></div>';
  1543. $main_content .= '</div>';
  1544. $main_content .= '</div>';
  1545. $html .= Display::div(
  1546. Display::div(
  1547. $title.$main_content,
  1548. ['class' => 'message-topic']
  1549. ),
  1550. ['class' => 'sm-groups-message']
  1551. );
  1552. $topic_id = $main_message['id'];
  1553. if (is_array($rows) && count($rows) > 0) {
  1554. $topics = $rows;
  1555. $array_html_items = [];
  1556. foreach ($topics as $index => $topic) {
  1557. if (empty($topic['id'])) {
  1558. continue;
  1559. }
  1560. $items_page_nr = isset($_GET['items_'.$topic['id'].'_page_nr'])
  1561. ? (int) $_GET['items_'.$topic['id'].'_page_nr']
  1562. : null;
  1563. $links = '';
  1564. $links .= '<div class="pull-right">';
  1565. $html_items = '';
  1566. $user_sender_info = api_get_user_info($topic['user_sender_id']);
  1567. $files_attachments = self::getAttachmentLinkList($topic['id']);
  1568. $name = $user_sender_info['complete_name'];
  1569. $links .= '<div class="btn-group btn-group-sm">';
  1570. if (
  1571. ($my_group_role == GROUP_USER_PERMISSION_ADMIN ||
  1572. $my_group_role == GROUP_USER_PERMISSION_MODERATOR
  1573. ) ||
  1574. $topic['user_sender_id'] == $current_user_id
  1575. ) {
  1576. $links .= Display::toolbarButton(
  1577. $langEdit,
  1578. $webCodePath.'social/message_for_group_form.inc.php?'
  1579. .http_build_query(
  1580. [
  1581. 'user_friend' => $current_user_id,
  1582. 'group_id' => $groupId,
  1583. 'message_id' => $topic['id'],
  1584. 'action' => 'edit_message_group',
  1585. 'anchor_topic' => 'topic_'.$topic_id,
  1586. 'topics_page_nr' => $topic_page_nr,
  1587. 'items_page_nr' => $items_page_nr,
  1588. 'topic_id' => $topic_id,
  1589. ]
  1590. ),
  1591. 'pencil',
  1592. 'default',
  1593. ['class' => 'ajax', 'data-title' => $langEdit, 'data-size' => 'lg'],
  1594. false
  1595. );
  1596. }
  1597. $links .= self::getLikesButton($topic['id'], $current_user_id, $groupId);
  1598. $links .= Display::toolbarButton(
  1599. $langReply,
  1600. $webCodePath.'social/message_for_group_form.inc.php?'
  1601. .http_build_query(
  1602. [
  1603. 'user_friend' => $current_user_id,
  1604. 'group_id' => $groupId,
  1605. 'message_id' => $topic['id'],
  1606. 'action' => 'reply_message_group',
  1607. 'anchor_topic' => 'topic_'.$topic_id,
  1608. 'topics_page_nr' => $topic_page_nr,
  1609. 'items_page_nr' => $items_page_nr,
  1610. 'topic_id' => $topic_id,
  1611. ]
  1612. ),
  1613. 'commenting',
  1614. 'default',
  1615. ['class' => 'ajax', 'data-title' => $langReply, 'data-size' => 'lg'],
  1616. false
  1617. );
  1618. $links .= '</div>';
  1619. $links .= '</div>';
  1620. $userPicture = $user_sender_info['avatar'];
  1621. $user_link = Display::url(
  1622. $name,
  1623. $webCodePath.'social/profile.php?u='.$topic['user_sender_id']
  1624. );
  1625. $html_items .= '<div class="row">';
  1626. $html_items .= '<div class="col-md-2">';
  1627. $html_items .= '<div class="avatar-author">';
  1628. $html_items .= Display::img(
  1629. $userPicture,
  1630. $name,
  1631. ['width' => '60px', 'class' => 'img-responsive img-circle'],
  1632. false
  1633. );
  1634. $html_items .= '</div>';
  1635. $html_items .= '</div>';
  1636. $date = '';
  1637. if ($topic['send_date'] != $topic['update_date']) {
  1638. if (!empty($topic['update_date'])) {
  1639. $date = '<div class="date"> '
  1640. ."$iconCalendar $langLastUpdated "
  1641. .Display::dateToStringAgoAndLongDate($topic['update_date'])
  1642. .'</div>';
  1643. }
  1644. } else {
  1645. $date = '<div class="date"> '
  1646. ."$iconCalendar $langCreated "
  1647. .Display::dateToStringAgoAndLongDate($topic['send_date'])
  1648. .'</div>';
  1649. }
  1650. $attachment = '<div class="message-attach">'
  1651. .(!empty($files_attachments) ? implode('<br />', $files_attachments) : '')
  1652. .'</div>';
  1653. $html_items .= '<div class="col-md-10">'
  1654. .'<div class="message-content">'
  1655. .$links
  1656. .'<div class="username">'.$user_link.'</div>'
  1657. .$date
  1658. .'<div class="message">'
  1659. .Security::remove_XSS($topic['content'], STUDENT, true)
  1660. .'</div>'.$attachment.'</div>'
  1661. .'</div>'
  1662. .'</div>';
  1663. $base_padding = 20;
  1664. if ($topic['indent_cnt'] == 0) {
  1665. $indent = $base_padding;
  1666. } else {
  1667. $indent = (int) $topic['indent_cnt'] * $base_padding + $base_padding;
  1668. }
  1669. $html_items = Display::div($html_items, ['class' => 'message-post', 'id' => 'msg_'.$topic['id']]);
  1670. $html_items = Display::div($html_items, ['class' => '', 'style' => 'margin-left:'.$indent.'px']);
  1671. $array_html_items[] = [$html_items];
  1672. }
  1673. // grids for items with paginations
  1674. $options = ['hide_navigation' => false, 'per_page' => $items_per_page];
  1675. $visibility = [true, true, true, false];
  1676. $style_class = [
  1677. 'item' => ['class' => 'user-post'],
  1678. 'main' => ['class' => 'user-list'],
  1679. ];
  1680. if (!empty($array_html_items)) {
  1681. $html .= Display::return_sortable_grid(
  1682. 'items_'.$topic['id'],
  1683. [],
  1684. $array_html_items,
  1685. $options,
  1686. $query_vars,
  1687. null,
  1688. $visibility,
  1689. false,
  1690. $style_class
  1691. );
  1692. }
  1693. }
  1694. return $html;
  1695. }
  1696. /**
  1697. * Add children to messages by id is used for nested view messages.
  1698. *
  1699. * @param array $rows rows of messages
  1700. *
  1701. * @return array $first_seed new list adding the item children
  1702. */
  1703. public static function calculate_children($rows, $first_seed)
  1704. {
  1705. $rows_with_children = [];
  1706. foreach ($rows as $row) {
  1707. $rows_with_children[$row["id"]] = $row;
  1708. $rows_with_children[$row["parent_id"]]["children"][] = $row["id"];
  1709. }
  1710. $rows = $rows_with_children;
  1711. $sorted_rows = [0 => []];
  1712. self::message_recursive_sort($rows, $sorted_rows, $first_seed);
  1713. unset($sorted_rows[0]);
  1714. return $sorted_rows;
  1715. }
  1716. /**
  1717. * Sort recursively the messages, is used for for nested view messages.
  1718. *
  1719. * @param array original rows of messages
  1720. * @param array list recursive of messages
  1721. * @param int seed for calculate the indent
  1722. * @param int indent for nested view
  1723. */
  1724. public static function message_recursive_sort(
  1725. $rows,
  1726. &$messages,
  1727. $seed = 0,
  1728. $indent = 0
  1729. ) {
  1730. if ($seed > 0 && isset($rows[$seed]["id"])) {
  1731. $messages[$rows[$seed]["id"]] = $rows[$seed];
  1732. $messages[$rows[$seed]["id"]]["indent_cnt"] = $indent;
  1733. $indent++;
  1734. }
  1735. if (isset($rows[$seed]["children"])) {
  1736. foreach ($rows[$seed]["children"] as $child) {
  1737. self::message_recursive_sort($rows, $messages, $child, $indent);
  1738. }
  1739. }
  1740. }
  1741. /**
  1742. * @param int $messageId
  1743. *
  1744. * @return array
  1745. */
  1746. public static function getAttachmentList($messageId)
  1747. {
  1748. $table = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  1749. $messageId = (int) $messageId;
  1750. if (empty($messageId)) {
  1751. return [];
  1752. }
  1753. $messageInfo = self::get_message_by_id($messageId);
  1754. if (empty($messageInfo)) {
  1755. return [];
  1756. }
  1757. $attachmentDir = UserManager::getUserPathById($messageInfo['user_receiver_id'], 'system');
  1758. $attachmentDir .= 'message_attachments/';
  1759. $sql = "SELECT * FROM $table
  1760. WHERE message_id = '$messageId'";
  1761. $result = Database::query($sql);
  1762. $files = [];
  1763. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1764. $row['file_source'] = '';
  1765. if (file_exists($attachmentDir.$row['path'])) {
  1766. $row['file_source'] = $attachmentDir.$row['path'];
  1767. }
  1768. $files[] = $row;
  1769. }
  1770. return $files;
  1771. }
  1772. /**
  1773. * Get array of links (download) for message attachment files.
  1774. *
  1775. * @param int $messageId
  1776. * @param string $type message list (inbox/outbox)
  1777. *
  1778. * @return array
  1779. */
  1780. public static function getAttachmentLinkList($messageId, $type = '')
  1781. {
  1782. $files = self::getAttachmentList($messageId);
  1783. // get file attachments by message id
  1784. $list = [];
  1785. if ($files) {
  1786. $attachIcon = Display::return_icon('attachment.gif', '');
  1787. $archiveURL = api_get_path(WEB_CODE_PATH).'messages/download.php?type='.$type.'&file=';
  1788. foreach ($files as $row_file) {
  1789. $archiveFile = $row_file['path'];
  1790. $filename = $row_file['filename'];
  1791. $size = format_file_size($row_file['size']);
  1792. $comment = Security::remove_XSS($row_file['comment']);
  1793. $filename = Security::remove_XSS($filename);
  1794. $link = Display::url($filename, $archiveURL.$archiveFile);
  1795. $comment = !empty($comment) ? '&nbsp;-&nbsp;<i>'.$comment.'</i>' : '';
  1796. $attachmentLine = $attachIcon.'&nbsp;'.$link.'&nbsp;('.$size.')'.$comment;
  1797. if ($row_file['comment'] == 'audio_message') {
  1798. $attachmentLine = '<audio src="'.$archiveURL.$archiveFile.'"/>';
  1799. }
  1800. $list[] = $attachmentLine;
  1801. }
  1802. }
  1803. return $list;
  1804. }
  1805. /**
  1806. * Get message list by id.
  1807. *
  1808. * @param int $messageId
  1809. *
  1810. * @return array
  1811. */
  1812. public static function get_message_by_id($messageId)
  1813. {
  1814. $table = Database::get_main_table(TABLE_MESSAGE);
  1815. $messageId = (int) $messageId;
  1816. $sql = "SELECT * FROM $table
  1817. WHERE
  1818. id = '$messageId' AND
  1819. msg_status <> '".MESSAGE_STATUS_DELETED."' ";
  1820. $res = Database::query($sql);
  1821. $item = [];
  1822. if (Database::num_rows($res) > 0) {
  1823. $item = Database::fetch_array($res, 'ASSOC');
  1824. }
  1825. return $item;
  1826. }
  1827. /**
  1828. * @return string
  1829. */
  1830. public static function generate_message_form()
  1831. {
  1832. $form = new FormValidator('send_message');
  1833. $form->addText(
  1834. 'subject',
  1835. get_lang('Subject'),
  1836. false,
  1837. ['id' => 'subject_id']
  1838. );
  1839. $form->addTextarea(
  1840. 'content',
  1841. get_lang('Message'),
  1842. ['id' => 'content_id', 'rows' => '5']
  1843. );
  1844. return $form->returnForm();
  1845. }
  1846. /**
  1847. * @return string
  1848. */
  1849. public static function generate_invitation_form()
  1850. {
  1851. $form = new FormValidator('send_invitation');
  1852. $form->addTextarea(
  1853. 'content',
  1854. get_lang('AddPersonalMessage'),
  1855. ['id' => 'content_invitation_id', 'rows' => 5]
  1856. );
  1857. return $form->returnForm();
  1858. }
  1859. /**
  1860. * @param string $keyword
  1861. *
  1862. * @return string
  1863. */
  1864. public static function inbox_display($keyword = '')
  1865. {
  1866. $success = get_lang('SelectedMessagesDeleted');
  1867. $success_read = get_lang('SelectedMessagesRead');
  1868. $success_unread = get_lang('SelectedMessagesUnRead');
  1869. $html = '';
  1870. Session::write('message_search_keyword', $keyword);
  1871. if (isset($_REQUEST['action'])) {
  1872. switch ($_REQUEST['action']) {
  1873. case 'mark_as_unread':
  1874. if (is_array($_POST['id'])) {
  1875. foreach ($_POST['id'] as $index => $message_id) {
  1876. self::update_message_status(
  1877. api_get_user_id(),
  1878. $message_id,
  1879. MESSAGE_STATUS_UNREAD
  1880. );
  1881. }
  1882. }
  1883. $html .= Display::return_message(
  1884. api_xml_http_response_encode($success_unread),
  1885. 'normal',
  1886. false
  1887. );
  1888. break;
  1889. case 'mark_as_read':
  1890. if (is_array($_POST['id'])) {
  1891. foreach ($_POST['id'] as $index => $message_id) {
  1892. self::update_message_status(
  1893. api_get_user_id(),
  1894. $message_id,
  1895. MESSAGE_STATUS_NEW
  1896. );
  1897. }
  1898. }
  1899. $html .= Display::return_message(
  1900. api_xml_http_response_encode($success_read),
  1901. 'normal',
  1902. false
  1903. );
  1904. break;
  1905. case 'delete':
  1906. foreach ($_POST['id'] as $index => $message_id) {
  1907. self::delete_message_by_user_receiver(api_get_user_id(), $message_id);
  1908. }
  1909. $html .= Display::return_message(
  1910. api_xml_http_response_encode($success),
  1911. 'normal',
  1912. false
  1913. );
  1914. break;
  1915. case 'deleteone':
  1916. self::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
  1917. $html .= Display::return_message(
  1918. api_xml_http_response_encode($success),
  1919. 'confirmation',
  1920. false
  1921. );
  1922. break;
  1923. }
  1924. }
  1925. // display sortable table with messages of the current user
  1926. $table = new SortableTable(
  1927. 'message_inbox',
  1928. ['MessageManager', 'getNumberOfMessages'],
  1929. ['MessageManager', 'get_message_data'],
  1930. 2,
  1931. 20,
  1932. 'DESC'
  1933. );
  1934. $table->set_header(0, '', false, ['style' => 'width:15px;']);
  1935. $table->set_header(1, get_lang('Messages'), false);
  1936. $table->set_header(2, get_lang('Date'), true, ['style' => 'width:180px;']);
  1937. $table->set_header(3, get_lang('Modify'), false, ['style' => 'width:120px;']);
  1938. if (isset($_REQUEST['f']) && $_REQUEST['f'] == 'social') {
  1939. $parameters['f'] = 'social';
  1940. $table->set_additional_parameters($parameters);
  1941. }
  1942. $table->set_form_actions(
  1943. [
  1944. 'delete' => get_lang('DeleteSelectedMessages'),
  1945. 'mark_as_unread' => get_lang('MailMarkSelectedAsUnread'),
  1946. 'mark_as_read' => get_lang('MailMarkSelectedAsRead'),
  1947. ]
  1948. );
  1949. $html .= $table->return_table();
  1950. Session::erase('message_search_keyword');
  1951. return $html;
  1952. }
  1953. /**
  1954. * @param string $keyword
  1955. *
  1956. * @return string
  1957. */
  1958. public static function outbox_display($keyword = '')
  1959. {
  1960. Session::write('message_sent_search_keyword', $keyword);
  1961. $success = get_lang('SelectedMessagesDeleted').'&nbsp</b><br />
  1962. <a href="outbox.php">'.get_lang('BackToOutbox').'</a>';
  1963. $html = '';
  1964. if (isset($_REQUEST['action'])) {
  1965. switch ($_REQUEST['action']) {
  1966. case 'delete':
  1967. $number_of_selected_messages = count($_POST['id']);
  1968. if ($number_of_selected_messages != 0) {
  1969. foreach ($_POST['id'] as $index => $message_id) {
  1970. self::delete_message_by_user_receiver(
  1971. api_get_user_id(),
  1972. $message_id
  1973. );
  1974. }
  1975. }
  1976. $html .= Display::return_message(api_xml_http_response_encode($success), 'normal', false);
  1977. break;
  1978. case 'deleteone':
  1979. self::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
  1980. $html .= Display::return_message(api_xml_http_response_encode($success), 'normal', false);
  1981. $html .= '<br/>';
  1982. break;
  1983. }
  1984. }
  1985. // display sortable table with messages of the current user
  1986. $table = new SortableTable(
  1987. 'message_outbox',
  1988. ['MessageManager', 'getNumberOfMessagesSent'],
  1989. ['MessageManager', 'get_message_data_sent'],
  1990. 2,
  1991. 20,
  1992. 'DESC'
  1993. );
  1994. $table->set_header(0, '', false, ['style' => 'width:15px;']);
  1995. $table->set_header(1, get_lang('Messages'), false);
  1996. $table->set_header(2, get_lang('Date'), true, ['style' => 'width:180px;']);
  1997. $table->set_header(3, get_lang('Modify'), false, ['style' => 'width:70px;']);
  1998. $table->set_form_actions(['delete' => get_lang('DeleteSelectedMessages')]);
  1999. $html .= $table->return_table();
  2000. Session::erase('message_sent_search_keyword');
  2001. return $html;
  2002. }
  2003. /**
  2004. * Get the data of the last received messages for a user.
  2005. *
  2006. * @param int $userId The user id
  2007. * @param int $lastId The id of the last received message
  2008. *
  2009. * @return array
  2010. */
  2011. public static function getMessagesFromLastReceivedMessage($userId, $lastId = 0)
  2012. {
  2013. $userId = (int) $userId;
  2014. $lastId = (int) $lastId;
  2015. if (empty($userId)) {
  2016. return [];
  2017. }
  2018. $messagesTable = Database::get_main_table(TABLE_MESSAGE);
  2019. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  2020. $sql = "SELECT m.*, u.user_id, u.lastname, u.firstname
  2021. FROM $messagesTable as m
  2022. INNER JOIN $userTable as u
  2023. ON m.user_sender_id = u.user_id
  2024. WHERE
  2025. m.user_receiver_id = $userId AND
  2026. m.msg_status = ".MESSAGE_STATUS_UNREAD."
  2027. AND m.id > $lastId
  2028. ORDER BY m.send_date DESC";
  2029. $result = Database::query($sql);
  2030. $messages = [];
  2031. if ($result !== false) {
  2032. while ($row = Database::fetch_assoc($result)) {
  2033. $messages[] = $row;
  2034. }
  2035. }
  2036. return $messages;
  2037. }
  2038. /**
  2039. * Check whether a message has attachments.
  2040. *
  2041. * @param int $messageId The message id
  2042. *
  2043. * @return bool Whether the message has attachments return true. Otherwise return false
  2044. */
  2045. public static function hasAttachments($messageId)
  2046. {
  2047. $messageId = (int) $messageId;
  2048. if (empty($messageId)) {
  2049. return false;
  2050. }
  2051. $messageAttachmentTable = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  2052. $conditions = [
  2053. 'where' => [
  2054. 'message_id = ?' => $messageId,
  2055. ],
  2056. ];
  2057. $result = Database::select(
  2058. 'COUNT(1) AS qty',
  2059. $messageAttachmentTable,
  2060. $conditions,
  2061. 'first'
  2062. );
  2063. if (!empty($result)) {
  2064. if ($result['qty'] > 0) {
  2065. return true;
  2066. }
  2067. }
  2068. return false;
  2069. }
  2070. /**
  2071. * @param int $messageId
  2072. *
  2073. * @return array|bool
  2074. */
  2075. public static function getAttachment($messageId)
  2076. {
  2077. $messageId = (int) $messageId;
  2078. if (empty($messageId)) {
  2079. return false;
  2080. }
  2081. $table = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  2082. $conditions = [
  2083. 'where' => [
  2084. 'id = ?' => $messageId,
  2085. ],
  2086. ];
  2087. $result = Database::select(
  2088. '*',
  2089. $table,
  2090. $conditions,
  2091. 'first'
  2092. );
  2093. if (!empty($result)) {
  2094. return $result;
  2095. }
  2096. return false;
  2097. }
  2098. /**
  2099. * @param string $url
  2100. *
  2101. * @return FormValidator
  2102. */
  2103. public static function getSearchForm($url)
  2104. {
  2105. $form = new FormValidator(
  2106. 'search',
  2107. 'post',
  2108. $url,
  2109. null,
  2110. [],
  2111. FormValidator::LAYOUT_INLINE
  2112. );
  2113. $form->addElement(
  2114. 'text',
  2115. 'keyword',
  2116. false,
  2117. [
  2118. 'aria-label' => get_lang('Search'),
  2119. ]
  2120. );
  2121. $form->addButtonSearch(get_lang('Search'));
  2122. return $form;
  2123. }
  2124. /**
  2125. * Send a notification to all admins when a new user is registered.
  2126. *
  2127. * @param User $user
  2128. */
  2129. public static function sendNotificationByRegisteredUser(User $user)
  2130. {
  2131. $tplMailBody = new Template(
  2132. null,
  2133. false,
  2134. false,
  2135. false,
  2136. false,
  2137. false,
  2138. false
  2139. );
  2140. $tplMailBody->assign('user', $user);
  2141. $tplMailBody->assign('is_western_name_order', api_is_western_name_order());
  2142. $tplMailBody->assign(
  2143. 'manageUrl',
  2144. api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$user->getId()
  2145. );
  2146. $layoutContent = $tplMailBody->get_template('mail/new_user_mail_to_admin.tpl');
  2147. $emailsubject = '['.get_lang('UserRegistered').'] '.$user->getUsername();
  2148. $emailbody = $tplMailBody->fetch($layoutContent);
  2149. $admins = UserManager::get_all_administrators();
  2150. foreach ($admins as $admin_info) {
  2151. self::send_message(
  2152. $admin_info['user_id'],
  2153. $emailsubject,
  2154. $emailbody,
  2155. [],
  2156. [],
  2157. null,
  2158. null,
  2159. null,
  2160. null,
  2161. $user->getId()
  2162. );
  2163. }
  2164. }
  2165. /**
  2166. * Get the error log from failed mailing
  2167. * This assumes a complex setup where you have a cron script regularly copying the mail queue log
  2168. * into app/cache/mail/mailq.
  2169. * This can be done with a cron command like (check the location of your mail log file first):.
  2170. *
  2171. * @example 0,30 * * * * root cp /var/log/exim4/mainlog /var/www/chamilo/app/cache/mail/mailq
  2172. *
  2173. * @return array|bool
  2174. */
  2175. public static function failedSentMailErrors()
  2176. {
  2177. $base = api_get_path(SYS_ARCHIVE_PATH).'mail/';
  2178. $mailq = $base.'mailq';
  2179. if (!file_exists($mailq) || !is_readable($mailq)) {
  2180. return false;
  2181. }
  2182. $file = fopen($mailq, 'r');
  2183. $i = 1;
  2184. while (!feof($file)) {
  2185. $line = fgets($file);
  2186. // $line = trim($line);
  2187. if (trim($line) == '') {
  2188. continue;
  2189. }
  2190. // Get the mail code, something like 1WBumL-0002xg-FF
  2191. if (preg_match('/(.*)\s((.*)-(.*)-(.*))\s<(.*)$/', $line, $codeMatches)) {
  2192. $mail_queue[$i]['code'] = $codeMatches[2];
  2193. }
  2194. $fullMail = $base.$mail_queue[$i]['code'];
  2195. $mailFile = fopen($fullMail, 'r');
  2196. // Get the reason of mail fail
  2197. $iX = 1;
  2198. while (!feof($mailFile)) {
  2199. $mailLine = fgets($mailFile);
  2200. //if ($iX == 4 && preg_match('/(.*):\s(.*)$/', $mailLine, $matches)) {
  2201. if ($iX == 2 &&
  2202. preg_match('/(.*)(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s(.*)/', $mailLine, $detailsMatches)
  2203. ) {
  2204. $mail_queue[$i]['reason'] = $detailsMatches[3];
  2205. }
  2206. $iX++;
  2207. }
  2208. fclose($mailFile);
  2209. // Get the time of mail fail
  2210. if (preg_match('/^\s?(\d+)(\D+)\s+(.*)$/', $line, $timeMatches)) {
  2211. $mail_queue[$i]['time'] = $timeMatches[1].$timeMatches[2];
  2212. } elseif (preg_match('/^(\s+)((.*)@(.*))\s+(.*)$/', $line, $emailMatches)) {
  2213. $mail_queue[$i]['mail'] = $emailMatches[2];
  2214. $i++;
  2215. }
  2216. }
  2217. fclose($file);
  2218. return array_reverse($mail_queue);
  2219. }
  2220. /**
  2221. * @param int $userId
  2222. *
  2223. * @return array
  2224. */
  2225. public static function getUsersThatHadConversationWithUser($userId)
  2226. {
  2227. $messagesTable = Database::get_main_table(TABLE_MESSAGE);
  2228. $userId = (int) $userId;
  2229. $sql = "SELECT DISTINCT
  2230. user_sender_id
  2231. FROM $messagesTable
  2232. WHERE
  2233. user_receiver_id = ".$userId;
  2234. $result = Database::query($sql);
  2235. $users = Database::store_result($result);
  2236. $userList = [];
  2237. foreach ($users as $userData) {
  2238. $userId = $userData['user_sender_id'];
  2239. if (empty($userId)) {
  2240. continue;
  2241. }
  2242. $userInfo = api_get_user_info($userId);
  2243. if ($userInfo) {
  2244. $userList[$userId] = $userInfo;
  2245. }
  2246. }
  2247. return $userList;
  2248. }
  2249. /**
  2250. * @param int $userId
  2251. * @param int $otherUserId
  2252. *
  2253. * @return array
  2254. */
  2255. public static function getAllMessagesBetweenStudents($userId, $otherUserId)
  2256. {
  2257. $messagesTable = Database::get_main_table(TABLE_MESSAGE);
  2258. $userId = (int) $userId;
  2259. $otherUserId = (int) $otherUserId;
  2260. if (empty($otherUserId) || empty($userId)) {
  2261. return [];
  2262. }
  2263. $sql = "SELECT DISTINCT *
  2264. FROM $messagesTable
  2265. WHERE
  2266. (user_receiver_id = $userId AND user_sender_id = $otherUserId) OR
  2267. (user_receiver_id = $otherUserId AND user_sender_id = $userId)
  2268. ORDER BY send_date DESC
  2269. ";
  2270. $result = Database::query($sql);
  2271. $messages = Database::store_result($result);
  2272. $list = [];
  2273. foreach ($messages as $message) {
  2274. $list[] = $message;
  2275. }
  2276. return $list;
  2277. }
  2278. /**
  2279. * @param string $subject
  2280. * @param string $message
  2281. * @param array $courseInfo
  2282. * @param int $sessionId
  2283. *
  2284. * @return bool
  2285. */
  2286. public static function sendMessageToAllUsersInCourse($subject, $message, $courseInfo, $sessionId = 0)
  2287. {
  2288. if (empty($courseInfo)) {
  2289. return false;
  2290. }
  2291. $senderId = api_get_user_id();
  2292. if (empty($senderId)) {
  2293. return false;
  2294. }
  2295. if (empty($sessionId)) {
  2296. // Course students and teachers
  2297. $users = CourseManager::get_user_list_from_course_code($courseInfo['code']);
  2298. } else {
  2299. // Course-session students and course session coaches
  2300. $users = CourseManager::get_user_list_from_course_code($courseInfo['code'], $sessionId);
  2301. }
  2302. if (empty($users)) {
  2303. return false;
  2304. }
  2305. foreach ($users as $userInfo) {
  2306. self::send_message_simple(
  2307. $userInfo['user_id'],
  2308. $subject,
  2309. $message,
  2310. $senderId,
  2311. false,
  2312. false,
  2313. [],
  2314. false
  2315. );
  2316. }
  2317. }
  2318. /**
  2319. * Clean audio messages already added in the message tool.
  2320. */
  2321. public static function cleanAudioMessage()
  2322. {
  2323. $audioId = Session::read('current_audio_id');
  2324. if (!empty($audioId)) {
  2325. api_remove_uploaded_file_by_id('audio_message', api_get_user_id(), $audioId);
  2326. Session::erase('current_audio_id');
  2327. }
  2328. }
  2329. /**
  2330. * @param int $senderId
  2331. * @param string $subject
  2332. * @param string $message
  2333. */
  2334. public static function sendMessageToAllAdminUsers(
  2335. $senderId,
  2336. $subject,
  2337. $message
  2338. ) {
  2339. $admins = UserManager::get_all_administrators();
  2340. foreach ($admins as $admin) {
  2341. self::send_message_simple($admin['user_id'], $subject, $message, $senderId);
  2342. }
  2343. }
  2344. /**
  2345. * @param int $messageId
  2346. * @param int $userId
  2347. *
  2348. * @return array
  2349. */
  2350. public static function countLikesAndDislikes($messageId, $userId)
  2351. {
  2352. if (!api_get_configuration_value('social_enable_messages_feedback')) {
  2353. return [];
  2354. }
  2355. $messageId = (int) $messageId;
  2356. $userId = (int) $userId;
  2357. $em = Database::getManager();
  2358. $query = $em
  2359. ->createQuery('
  2360. SELECT SUM(l.liked) AS likes, SUM(l.disliked) AS dislikes FROM ChamiloCoreBundle:MessageFeedback l
  2361. WHERE l.message = :message
  2362. ')
  2363. ->setParameters(['message' => $messageId]);
  2364. try {
  2365. $counts = $query->getSingleResult();
  2366. } catch (Exception $e) {
  2367. $counts = ['likes' => 0, 'dislikes' => 0];
  2368. }
  2369. $userLike = $em
  2370. ->getRepository('ChamiloCoreBundle:MessageFeedback')
  2371. ->findOneBy(['message' => $messageId, 'user' => $userId]);
  2372. return [
  2373. 'likes' => (int) $counts['likes'],
  2374. 'dislikes' => (int) $counts['dislikes'],
  2375. 'user_liked' => $userLike ? $userLike->isLiked() : false,
  2376. 'user_disliked' => $userLike ? $userLike->isDisliked() : false,
  2377. ];
  2378. }
  2379. /**
  2380. * @param int $messageId
  2381. * @param int $userId
  2382. * @param int $groupId Optional.
  2383. *
  2384. * @return string
  2385. */
  2386. public static function getLikesButton($messageId, $userId, $groupId = 0)
  2387. {
  2388. if (!api_get_configuration_value('social_enable_messages_feedback')) {
  2389. return '';
  2390. }
  2391. $countLikes = self::countLikesAndDislikes($messageId, $userId);
  2392. $btnLike = Display::button(
  2393. 'like',
  2394. Display::returnFontAwesomeIcon('thumbs-up', '', true)
  2395. .PHP_EOL.'<span>'.$countLikes['likes'].'</span>',
  2396. [
  2397. 'title' => get_lang('VoteLike'),
  2398. 'class' => 'btn btn-default social-like '.($countLikes['user_liked'] ? 'disabled' : ''),
  2399. 'data-status' => 'like',
  2400. 'data-message' => $messageId,
  2401. 'data-group' => $groupId,
  2402. ]
  2403. );
  2404. $btnDislike = Display::button(
  2405. 'like',
  2406. Display::returnFontAwesomeIcon('thumbs-down', '', true)
  2407. .PHP_EOL.'<span>'.$countLikes['dislikes'].'</span>',
  2408. [
  2409. 'title' => get_lang('VoteDislike'),
  2410. 'class' => 'btn btn-default social-like '.($countLikes['user_disliked'] ? 'disabled' : ''),
  2411. 'data-status' => 'dislike',
  2412. 'data-message' => $messageId,
  2413. 'data-group' => $groupId,
  2414. ]
  2415. );
  2416. return $btnLike.PHP_EOL.$btnDislike;
  2417. }
  2418. /**
  2419. * Execute the SQL necessary to know the number of messages in the database.
  2420. *
  2421. * @param int $userId The user for which we need the unread messages count
  2422. *
  2423. * @return int The number of unread messages in the database for the given user
  2424. */
  2425. public static function getCountNewMessagesFromDB($userId)
  2426. {
  2427. $userId = (int) $userId;
  2428. if (empty($userId)) {
  2429. return 0;
  2430. }
  2431. $table = Database::get_main_table(TABLE_MESSAGE);
  2432. $sql = "SELECT COUNT(id) as count
  2433. FROM $table
  2434. WHERE
  2435. user_receiver_id=".$userId." AND
  2436. msg_status = ".MESSAGE_STATUS_UNREAD;
  2437. $result = Database::query($sql);
  2438. $row = Database::fetch_assoc($result);
  2439. return $row['count'];
  2440. }
  2441. }