message.lib.php 96 KB

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