message.lib.php 98 KB

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