message.lib.php 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use ChamiloSession as Session;
  4. use Chamilo\UserBundle\Entity\User;
  5. /**
  6. * Class MessageManager
  7. *
  8. * This class provides methods for messages management.
  9. * Include/require it in your code to use its features.
  10. *
  11. * @package chamilo.library
  12. */
  13. class MessageManager
  14. {
  15. /**
  16. * Get count new messages for the current user from the database.
  17. * @return int
  18. */
  19. public static function getCountNewMessages()
  20. {
  21. $userId = api_get_user_id();
  22. if (empty($userId)) {
  23. return false;
  24. }
  25. static $count;
  26. if (!isset($count)) {
  27. $cacheAvailable = api_get_configuration_value('apc');
  28. if ($cacheAvailable === true) {
  29. $var = api_get_configuration_value('apc_prefix').'social_messages_unread_u_'.$userId;
  30. if (apcu_exists($var)) {
  31. $count = apcu_fetch($var);
  32. } else {
  33. $count = self::getCountNewMessagesFromDB($userId);
  34. apcu_store($var, $count, 60);
  35. }
  36. } else {
  37. $count = self::getCountNewMessagesFromDB($userId);
  38. }
  39. }
  40. return $count;
  41. }
  42. /**
  43. * Execute the SQL necessary to know the number of messages in the database
  44. * @param int $userId The user for which we need the unread messages count
  45. * @return int The number of unread messages in the database for the given user
  46. */
  47. private static function getCountNewMessagesFromDB($userId)
  48. {
  49. if (empty($userId)) {
  50. return 0;
  51. }
  52. $table = Database::get_main_table(TABLE_MESSAGE);
  53. $sql = "SELECT COUNT(id) as count
  54. FROM $table
  55. WHERE
  56. user_receiver_id=".api_get_user_id()." AND
  57. msg_status = " . MESSAGE_STATUS_UNREAD;
  58. $result = Database::query($sql);
  59. $row = Database::fetch_assoc($result);
  60. return $row['count'];
  61. }
  62. /**
  63. * Gets the total number of messages, used for the inbox sortable table
  64. */
  65. public static function get_number_of_messages($unread = false)
  66. {
  67. $table_message = Database::get_main_table(TABLE_MESSAGE);
  68. if ($unread) {
  69. $condition_msg_status = ' msg_status = '.MESSAGE_STATUS_UNREAD.' ';
  70. } else {
  71. $condition_msg_status = ' msg_status IN('.MESSAGE_STATUS_NEW.','.MESSAGE_STATUS_UNREAD.') ';
  72. }
  73. $keyword = Session::read('message_search_keyword');
  74. $keywordCondition = '';
  75. if (!empty($keyword)) {
  76. $keyword = Database::escape_string($keyword);
  77. $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
  78. }
  79. $sql = "SELECT COUNT(id) as number_messages
  80. FROM $table_message
  81. WHERE $condition_msg_status AND
  82. user_receiver_id=".api_get_user_id()."
  83. $keywordCondition
  84. ";
  85. $result = Database::query($sql);
  86. $result = Database::fetch_array($result);
  87. return $result['number_messages'];
  88. }
  89. /**
  90. * Gets information about some messages, used for the inbox sortable table
  91. * @param int $from
  92. * @param int $number_of_items
  93. * @param string $direction
  94. */
  95. public static function get_message_data($from, $number_of_items, $column, $direction)
  96. {
  97. $from = intval($from);
  98. $number_of_items = intval($number_of_items);
  99. //forcing this order
  100. if (!isset($direction)) {
  101. $column = 3;
  102. $direction = 'DESC';
  103. } else {
  104. $column = intval($column);
  105. if (!in_array($direction, array('ASC', 'DESC'))) {
  106. $direction = 'ASC';
  107. }
  108. }
  109. $keyword = Session::read('message_search_keyword');
  110. $keywordCondition = '';
  111. if (!empty($keyword)) {
  112. $keyword = Database::escape_string($keyword);
  113. $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
  114. }
  115. $table_message = Database::get_main_table(TABLE_MESSAGE);
  116. $sql = "SELECT
  117. id as col0,
  118. user_sender_id as col1,
  119. title as col2,
  120. send_date as col3,
  121. msg_status as col4
  122. FROM $table_message
  123. WHERE
  124. user_receiver_id=".api_get_user_id()." AND
  125. msg_status IN (0,1)
  126. $keywordCondition
  127. ORDER BY col$column $direction
  128. LIMIT $from, $number_of_items";
  129. $sql_result = Database::query($sql);
  130. $i = 0;
  131. $message_list = array();
  132. while ($result = Database::fetch_row($sql_result)) {
  133. $message[0] = $result[0];
  134. $result[2] = Security::remove_XSS($result[2], STUDENT, true);
  135. $result[2] = cut($result[2], 80, true);
  136. if ($result[4] == 1) {
  137. $class = 'class = "unread"';
  138. } else {
  139. $class = 'class = "read"';
  140. }
  141. $link = '';
  142. if (isset($_GET['f']) && $_GET['f'] == 'social') {
  143. $link = '&f=social';
  144. }
  145. $userInfo = api_get_user_info($result[1]);
  146. $message[1] = '<a '.$class.' href="view_message.php?id='.$result[0].$link.'">'.$result[2].'</a><br />'.$userInfo['complete_name'];
  147. $message[3] = '<a href="new_message.php?re_id='.$result[0].$link.'">'.
  148. Display::return_icon('message_reply.png', get_lang('ReplyToMessage')).'</a>'.
  149. '&nbsp;&nbsp;<a onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmDeleteMessage')))."'".')) return false;" href="inbox.php?action=deleteone&id='.$result[0].$link.'">'.Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>';
  150. $message[2] = api_convert_and_format_date($result[3], DATE_TIME_FORMAT_LONG); //date stays the same
  151. foreach ($message as $key => $value) {
  152. $message[$key] = api_xml_http_response_encode($value);
  153. }
  154. $message_list[] = $message;
  155. $i++;
  156. }
  157. return $message_list;
  158. }
  159. /**
  160. * Sends a message to a user/group
  161. *
  162. * @param int $receiver_user_id
  163. * @param string $subject
  164. * @param string $content
  165. * @param array $file_attachments files array($_FILES) (optional)
  166. * @param array $file_comments about attachment files (optional)
  167. * @param int $group_id (optional)
  168. * @param int $parent_id (optional)
  169. * @param int $edit_message_id id for updating the message (optional)
  170. * @param int $topic_id (optional) the default value is the current user_id
  171. * @param int $sender_id
  172. * @param bool $directMessage
  173. *
  174. * @return bool
  175. */
  176. public static function send_message(
  177. $receiver_user_id,
  178. $subject,
  179. $content,
  180. array $file_attachments = [],
  181. array $file_comments = [],
  182. $group_id = 0,
  183. $parent_id = 0,
  184. $edit_message_id = 0,
  185. $topic_id = 0,
  186. $sender_id = null,
  187. $directMessage = false
  188. ) {
  189. $table_message = Database::get_main_table(TABLE_MESSAGE);
  190. $group_id = intval($group_id);
  191. $receiver_user_id = intval($receiver_user_id);
  192. $parent_id = intval($parent_id);
  193. $edit_message_id = intval($edit_message_id);
  194. $topic_id = intval($topic_id);
  195. if (!empty($receiver_user_id)) {
  196. $receiverUserInfo = api_get_user_info($receiver_user_id);
  197. // Disabling messages for inactive users.
  198. if ($receiverUserInfo['active'] == 0) {
  199. return false;
  200. }
  201. }
  202. if (empty($sender_id)) {
  203. $user_sender_id = api_get_user_id();
  204. } else {
  205. $user_sender_id = intval($sender_id);
  206. }
  207. $total_filesize = 0;
  208. if (is_array($file_attachments)) {
  209. foreach ($file_attachments as $file_attach) {
  210. $fileSize = isset($file_attach['size']) ? $file_attach['size'] : 0;
  211. if (is_array($fileSize)) {
  212. foreach ($fileSize as $size) {
  213. $total_filesize += $size;
  214. }
  215. } else {
  216. $total_filesize += $fileSize;
  217. }
  218. }
  219. }
  220. // Validating fields
  221. if (empty($subject) && empty($group_id)) {
  222. Display::addFlash(Display::return_message(get_lang('YouShouldWriteASubject'), 'warning'));
  223. return false;
  224. } else if ($total_filesize > intval(api_get_setting('message_max_upload_filesize'))) {
  225. $warning = sprintf(
  226. get_lang("FilesSizeExceedsX"),
  227. format_file_size(api_get_setting('message_max_upload_filesize'))
  228. );
  229. Display::addFlash(Display::return_message($warning, 'warning'));
  230. return false;
  231. }
  232. $inbox_last_id = null;
  233. //Just in case we replace the and \n and \n\r while saving in the DB
  234. //$content = str_replace(array("\n", "\n\r"), '<br />', $content);
  235. $now = api_get_utc_datetime();
  236. if (!empty($receiver_user_id) || !empty($group_id)) {
  237. // message for user friend
  238. //@todo it's possible to edit a message? yes, only for groups
  239. if ($edit_message_id) {
  240. $query = " UPDATE $table_message SET
  241. update_date = '".$now."',
  242. content = '".Database::escape_string($content)."'
  243. WHERE id = '$edit_message_id' ";
  244. Database::query($query);
  245. $inbox_last_id = $edit_message_id;
  246. } else {
  247. $params = [
  248. 'user_sender_id' => $user_sender_id,
  249. 'user_receiver_id' => $receiver_user_id,
  250. 'msg_status' => '1',
  251. 'send_date' => $now,
  252. 'title' => $subject,
  253. 'content' => $content,
  254. 'group_id' => $group_id,
  255. 'parent_id' => $parent_id,
  256. 'update_date' => $now
  257. ];
  258. $inbox_last_id = Database::insert($table_message, $params);
  259. }
  260. // Save attachment file for inbox messages
  261. if (is_array($file_attachments)) {
  262. $i = 0;
  263. foreach ($file_attachments as $file_attach) {
  264. if ($file_attach['error'] == 0) {
  265. self::save_message_attachment_file(
  266. $file_attach,
  267. isset($file_comments[$i]) ? $file_comments[$i] : null,
  268. $inbox_last_id,
  269. null,
  270. $receiver_user_id,
  271. $group_id
  272. );
  273. }
  274. $i++;
  275. }
  276. }
  277. if (empty($group_id)) {
  278. // message in outbox for user friend or group
  279. $params = [
  280. 'user_sender_id' => $user_sender_id,
  281. 'user_receiver_id' => $receiver_user_id,
  282. 'msg_status' => '4',
  283. 'send_date' => $now,
  284. 'title' => $subject,
  285. 'content' => $content,
  286. 'group_id' => $group_id,
  287. 'parent_id' => $parent_id,
  288. 'update_date' => $now
  289. ];
  290. $outbox_last_id = Database::insert($table_message, $params);
  291. // save attachment file for outbox messages
  292. if (is_array($file_attachments)) {
  293. $o = 0;
  294. foreach ($file_attachments as $file_attach) {
  295. if ($file_attach['error'] == 0) {
  296. $comment = isset($file_comments[$o]) ? $file_comments[$o] : '';
  297. self::save_message_attachment_file(
  298. $file_attach,
  299. $comment,
  300. $outbox_last_id,
  301. $user_sender_id
  302. );
  303. }
  304. $o++;
  305. }
  306. }
  307. }
  308. // Load user settings.
  309. $notification = new Notification();
  310. $sender_info = api_get_user_info($user_sender_id);
  311. // add file attachment additional attributes
  312. foreach ($file_attachments as $index => $file_attach) {
  313. $file_attachments[$index]['path'] = $file_attach['tmp_name'];
  314. $file_attachments[$index]['filename'] = $file_attach['name'];
  315. }
  316. if (empty($group_id)) {
  317. $type = Notification::NOTIFICATION_TYPE_MESSAGE;
  318. if ($directMessage) {
  319. $type = Notification::NOTIFICATION_TYPE_DIRECT_MESSAGE;
  320. }
  321. $notification->save_notification(
  322. $type,
  323. array($receiver_user_id),
  324. $subject,
  325. $content,
  326. $sender_info,
  327. $file_attachments
  328. );
  329. } else {
  330. $usergroup = new UserGroup();
  331. $group_info = $usergroup->get($group_id);
  332. $group_info['topic_id'] = $topic_id;
  333. $group_info['msg_id'] = $inbox_last_id;
  334. $user_list = $usergroup->get_users_by_group($group_id, false, array(), 0, 1000);
  335. // Adding more sense to the message group
  336. $subject = sprintf(get_lang('ThereIsANewMessageInTheGroupX'), $group_info['name']);
  337. $new_user_list = array();
  338. foreach ($user_list as $user_data) {
  339. $new_user_list[] = $user_data['id'];
  340. }
  341. $group_info = array(
  342. 'group_info' => $group_info,
  343. 'user_info' => $sender_info,
  344. );
  345. $notification->save_notification(
  346. Notification::NOTIFICATION_TYPE_GROUP,
  347. $new_user_list,
  348. $subject,
  349. $content,
  350. $group_info,
  351. $file_attachments
  352. );
  353. }
  354. return $inbox_last_id;
  355. }
  356. return false;
  357. }
  358. /**
  359. * @param int $receiver_user_id
  360. * @param int $subject
  361. * @param string $message
  362. * @param int $sender_id
  363. * @param bool $sendCopyToDrhUsers send copy to related DRH users
  364. * @param bool $directMessage
  365. *
  366. * @return bool
  367. */
  368. public static function send_message_simple(
  369. $receiver_user_id,
  370. $subject,
  371. $message,
  372. $sender_id = null,
  373. $sendCopyToDrhUsers = false,
  374. $directMessage = false
  375. ) {
  376. $result = self::send_message(
  377. $receiver_user_id,
  378. $subject,
  379. $message,
  380. $_FILES ? $_FILES : [],
  381. [],
  382. null,
  383. null,
  384. null,
  385. null,
  386. $sender_id,
  387. $directMessage
  388. );
  389. if ($sendCopyToDrhUsers) {
  390. $userInfo = api_get_user_info($receiver_user_id);
  391. $drhList = UserManager::getDrhListFromUser($receiver_user_id);
  392. if (!empty($drhList)) {
  393. foreach ($drhList as $drhInfo) {
  394. $message = sprintf(
  395. get_lang('CopyOfMessageSentToXUser'),
  396. $userInfo['complete_name']
  397. ).' <br />'.$message;
  398. self::send_message_simple(
  399. $drhInfo['user_id'],
  400. $subject,
  401. $message,
  402. $sender_id,
  403. false,
  404. $directMessage
  405. );
  406. }
  407. }
  408. }
  409. return $result;
  410. }
  411. /**
  412. * Update parent ids for other receiver user from current message in groups
  413. * @author Christian Fasanando Flores
  414. * @param int $parent_id
  415. * @param int $receiver_user_id
  416. * @param int $message_id
  417. * @return void
  418. */
  419. public static function update_parent_ids_from_reply($parent_id, $receiver_user_id, $message_id)
  420. {
  421. $table_message = Database::get_main_table(TABLE_MESSAGE);
  422. $parent_id = intval($parent_id);
  423. $receiver_user_id = intval($receiver_user_id);
  424. $message_id = intval($message_id);
  425. // first get data from message id (parent)
  426. $sql_message = "SELECT * FROM $table_message WHERE id = '$parent_id'";
  427. $rs_message = Database::query($sql_message);
  428. $row_message = Database::fetch_array($rs_message);
  429. // get message id from data found early for other receiver user
  430. $sql = "SELECT id FROM $table_message
  431. WHERE
  432. user_sender_id ='{$row_message['user_sender_id']}' AND
  433. title='{$row_message['title']}' AND
  434. content='{$row_message['content']}' AND
  435. group_id='{$row_message['group_id']}' AND
  436. user_receiver_id='$receiver_user_id'";
  437. $result = Database::query($sql);
  438. $row = Database::fetch_array($result);
  439. // update parent_id for other user receiver
  440. $sql = "UPDATE $table_message SET parent_id = ".$row['id']."
  441. WHERE id = $message_id";
  442. Database::query($sql);
  443. }
  444. /**
  445. * @param int $user_receiver_id
  446. * @param int $id
  447. * @return bool
  448. */
  449. public static function delete_message_by_user_receiver($user_receiver_id, $id)
  450. {
  451. $table_message = Database::get_main_table(TABLE_MESSAGE);
  452. if ($id != strval(intval($id))) {
  453. return false;
  454. }
  455. $user_receiver_id = intval($user_receiver_id);
  456. $id = intval($id);
  457. $sql = "SELECT * FROM $table_message
  458. WHERE id=".$id." AND msg_status<>4";
  459. $rs = Database::query($sql);
  460. if (Database::num_rows($rs) > 0) {
  461. // delete attachment file
  462. self::delete_message_attachment_file($id, $user_receiver_id);
  463. // delete message
  464. $query = "UPDATE $table_message
  465. SET msg_status = 3
  466. WHERE
  467. user_receiver_id=".$user_receiver_id." AND
  468. id = " . $id;
  469. Database::query($query);
  470. return true;
  471. } else {
  472. return false;
  473. }
  474. }
  475. /**
  476. * Set status deleted
  477. * @author Isaac FLores Paz <isaac.flores@dokeos.com>
  478. * @param int
  479. * @param int
  480. * @return bool
  481. */
  482. public static function delete_message_by_user_sender($user_sender_id, $id)
  483. {
  484. if ($id != strval(intval($id))) {
  485. return false;
  486. }
  487. $table_message = Database::get_main_table(TABLE_MESSAGE);
  488. $id = intval($id);
  489. $user_sender_id = intval($user_sender_id);
  490. $sql = "SELECT * FROM $table_message WHERE id='$id'";
  491. $rs = Database::query($sql);
  492. if (Database::num_rows($rs) > 0) {
  493. // delete attachment file
  494. self::delete_message_attachment_file($id, $user_sender_id);
  495. // delete message
  496. $sql = "UPDATE $table_message
  497. SET msg_status=3
  498. WHERE user_sender_id='$user_sender_id' AND id='$id'";
  499. Database::query($sql);
  500. return true;
  501. }
  502. return false;
  503. }
  504. /**
  505. * Saves a message attachment files
  506. * @param array $file_attach $_FILES['name']
  507. * @param string a comment about the uploaded file
  508. * @param int message id
  509. * @param int receiver user id (optional)
  510. * @param int sender user id (optional)
  511. * @param int group id (optional)
  512. * @return void
  513. */
  514. public static function save_message_attachment_file(
  515. $file_attach,
  516. $file_comment,
  517. $message_id,
  518. $receiver_user_id = 0,
  519. $sender_user_id = 0,
  520. $group_id = 0
  521. ) {
  522. $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  523. // Try to add an extension to the file if it hasn't one
  524. $new_file_name = add_ext_on_mime(stripslashes($file_attach['name']), $file_attach['type']);
  525. // user's file name
  526. $file_name = $file_attach['name'];
  527. if (!filter_extension($new_file_name)) {
  528. echo Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error');
  529. } else {
  530. $new_file_name = uniqid('');
  531. if (!empty($receiver_user_id)) {
  532. $message_user_id = $receiver_user_id;
  533. } else {
  534. $message_user_id = $sender_user_id;
  535. }
  536. // User-reserved directory where photos have to be placed.*
  537. $userGroup = new UserGroup();
  538. if (!empty($group_id)) {
  539. $path_user_info = $userGroup->get_group_picture_path_by_id($group_id, 'system', true);
  540. } else {
  541. $path_user_info['dir'] = UserManager::getUserPathById($message_user_id, 'system');
  542. }
  543. $path_message_attach = $path_user_info['dir'].'message_attachments/';
  544. // If this directory does not exist - we create it.
  545. if (!file_exists($path_message_attach)) {
  546. @mkdir($path_message_attach, api_get_permissions_for_new_directories(), true);
  547. }
  548. $new_path = $path_message_attach.$new_file_name;
  549. if (is_uploaded_file($file_attach['tmp_name'])) {
  550. @copy($file_attach['tmp_name'], $new_path);
  551. }
  552. // Storing the attachments if any
  553. $params = [
  554. 'filename' => $file_name,
  555. 'comment' => $file_comment,
  556. 'path' => $new_file_name,
  557. 'message_id' => $message_id,
  558. 'size' => $file_attach['size']
  559. ];
  560. Database::insert($tbl_message_attach, $params);
  561. }
  562. }
  563. /**
  564. * Delete message attachment files (logically updating the row with a suffix _DELETE_id)
  565. * @param int message id
  566. * @param int message user id (receiver user id or sender user id)
  567. * @param int group id (optional)
  568. * @return void
  569. */
  570. public static function delete_message_attachment_file($message_id, $message_uid, $group_id = 0)
  571. {
  572. $message_id = intval($message_id);
  573. $message_uid = intval($message_uid);
  574. $table_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  575. $sql = "SELECT * FROM $table_message_attach WHERE message_id = '$message_id'";
  576. $rs = Database::query($sql);
  577. while ($row = Database::fetch_array($rs)) {
  578. $path = $row['path'];
  579. $attach_id = $row['id'];
  580. $new_path = $path.'_DELETED_'.$attach_id;
  581. if (!empty($group_id)) {
  582. $userGroup = new UserGroup();
  583. $path_user_info = $userGroup->get_group_picture_path_by_id(
  584. $group_id,
  585. 'system',
  586. true
  587. );
  588. } else {
  589. $path_user_info['dir'] = UserManager::getUserPathById(
  590. $message_uid,
  591. 'system'
  592. );
  593. }
  594. $path_message_attach = $path_user_info['dir'].'message_attachments/';
  595. if (is_file($path_message_attach.$path)) {
  596. if (rename($path_message_attach.$path, $path_message_attach.$new_path)) {
  597. $sql = "UPDATE $table_message_attach set path='$new_path'
  598. WHERE id ='$attach_id'";
  599. Database::query($sql);
  600. }
  601. }
  602. }
  603. }
  604. /**
  605. * update messages by user id and message id
  606. * @param int $user_id
  607. * @param int $message_id
  608. * @return resource
  609. */
  610. public static function update_message($user_id, $message_id)
  611. {
  612. if ($message_id != strval(intval($message_id)) || $user_id != strval(intval($user_id))) {
  613. return false;
  614. }
  615. $table_message = Database::get_main_table(TABLE_MESSAGE);
  616. $sql = "UPDATE $table_message SET msg_status = '0'
  617. WHERE
  618. msg_status<>4 AND
  619. user_receiver_id=".intval($user_id)." AND
  620. id='" . intval($message_id)."'";
  621. Database::query($sql);
  622. }
  623. /**
  624. * @param int $user_id
  625. * @param int $message_id
  626. * @param string $type
  627. * @return bool
  628. */
  629. public static function update_message_status($user_id, $message_id, $type)
  630. {
  631. $type = intval($type);
  632. if ($message_id != strval(intval($message_id)) || $user_id != strval(intval($user_id))) {
  633. return false;
  634. }
  635. $table_message = Database::get_main_table(TABLE_MESSAGE);
  636. $sql = "UPDATE $table_message SET
  637. msg_status = '$type'
  638. WHERE
  639. user_receiver_id=".intval($user_id)." AND
  640. id='" . intval($message_id)."'";
  641. Database::query($sql);
  642. }
  643. /**
  644. * get messages by user id and message id
  645. * @param int $user_id
  646. * @param int $message_id
  647. * @return array
  648. */
  649. public static function get_message_by_user($user_id, $message_id)
  650. {
  651. if ($message_id != strval(intval($message_id)) || $user_id != strval(intval($user_id))) {
  652. return false;
  653. }
  654. $table_message = Database::get_main_table(TABLE_MESSAGE);
  655. $query = "SELECT * FROM $table_message
  656. WHERE user_receiver_id=".intval($user_id)." AND id='".intval($message_id)."'";
  657. $result = Database::query($query);
  658. return $row = Database::fetch_array($result);
  659. }
  660. /**
  661. * get messages by group id
  662. * @param int $group_id group id
  663. * @return array
  664. */
  665. public static function get_messages_by_group($group_id)
  666. {
  667. if ($group_id != strval(intval($group_id))) {
  668. return false;
  669. }
  670. $table_message = Database::get_main_table(TABLE_MESSAGE);
  671. $group_id = intval($group_id);
  672. $sql = "SELECT * FROM $table_message
  673. WHERE
  674. group_id= $group_id AND
  675. msg_status NOT IN ('".MESSAGE_STATUS_OUTBOX."', '".MESSAGE_STATUS_DELETED."')
  676. ORDER BY id";
  677. $rs = Database::query($sql);
  678. $data = array();
  679. if (Database::num_rows($rs) > 0) {
  680. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  681. $data[] = $row;
  682. }
  683. }
  684. return $data;
  685. }
  686. /**
  687. * get messages by group id
  688. * @param int $group_id
  689. * @param int $message_id
  690. * @return array
  691. */
  692. public static function get_messages_by_group_by_message($group_id, $message_id)
  693. {
  694. if ($group_id != strval(intval($group_id))) {
  695. return false;
  696. }
  697. $table_message = Database::get_main_table(TABLE_MESSAGE);
  698. $group_id = intval($group_id);
  699. $sql = "SELECT * FROM $table_message
  700. WHERE
  701. group_id = $group_id AND
  702. msg_status NOT IN ('".MESSAGE_STATUS_OUTBOX."', '".MESSAGE_STATUS_DELETED."')
  703. ORDER BY id ";
  704. $rs = Database::query($sql);
  705. $data = array();
  706. $parents = array();
  707. if (Database::num_rows($rs) > 0) {
  708. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  709. if ($message_id == $row['parent_id'] || in_array($row['parent_id'], $parents)) {
  710. $parents[] = $row['id'];
  711. $data[] = $row;
  712. }
  713. }
  714. }
  715. return $data;
  716. }
  717. /**
  718. * get messages by parent id optionally with limit
  719. * @param int parent id
  720. * @param int group id (optional)
  721. * @param int offset (optional)
  722. * @param int limit (optional)
  723. * @return array
  724. */
  725. public static function get_messages_by_parent($parent_id, $group_id = '', $offset = 0, $limit = 0)
  726. {
  727. if ($parent_id != strval(intval($parent_id))) {
  728. return false;
  729. }
  730. $table_message = Database::get_main_table(TABLE_MESSAGE);
  731. $parent_id = intval($parent_id);
  732. $condition_group_id = "";
  733. if ($group_id !== '') {
  734. $group_id = intval($group_id);
  735. $condition_group_id = " AND group_id = '$group_id' ";
  736. }
  737. $condition_limit = "";
  738. if ($offset && $limit) {
  739. $offset = ($offset - 1) * $limit;
  740. $condition_limit = " LIMIT $offset,$limit ";
  741. }
  742. $sql = "SELECT * FROM $table_message
  743. WHERE
  744. parent_id='$parent_id' AND
  745. msg_status <> ".MESSAGE_STATUS_OUTBOX."
  746. $condition_group_id
  747. ORDER BY send_date DESC $condition_limit ";
  748. $rs = Database::query($sql);
  749. $data = array();
  750. if (Database::num_rows($rs) > 0) {
  751. while ($row = Database::fetch_array($rs)) {
  752. $data[$row['id']] = $row;
  753. }
  754. }
  755. return $data;
  756. }
  757. /**
  758. * Gets information about if exist messages
  759. * @author Isaac FLores Paz <isaac.flores@dokeos.com>
  760. * @param integer
  761. * @param integer
  762. * @return boolean
  763. */
  764. public static function exist_message($user_id, $id)
  765. {
  766. if ($id != strval(intval($id)) || $user_id != strval(intval($user_id)))
  767. return false;
  768. $table_message = Database::get_main_table(TABLE_MESSAGE);
  769. $query = "SELECT id FROM $table_message
  770. WHERE
  771. user_receiver_id = ".intval($user_id)." AND
  772. id = '" . intval($id)."'";
  773. $result = Database::query($query);
  774. $num = Database::num_rows($result);
  775. if ($num > 0) {
  776. return true;
  777. } else {
  778. return false;
  779. }
  780. }
  781. /**
  782. * Gets information about messages sent
  783. * @param integer
  784. * @param integer
  785. * @param string
  786. * @return array
  787. */
  788. public static function get_message_data_sent($from, $number_of_items, $column, $direction)
  789. {
  790. $from = intval($from);
  791. $number_of_items = intval($number_of_items);
  792. if (!isset($direction)) {
  793. $column = 3;
  794. $direction = 'DESC';
  795. } else {
  796. $column = intval($column);
  797. if (!in_array($direction, array('ASC', 'DESC'))) {
  798. $direction = 'ASC';
  799. }
  800. }
  801. $table_message = Database::get_main_table(TABLE_MESSAGE);
  802. $request = api_is_xml_http_request();
  803. $keyword = Session::read('message_sent_search_keyword');
  804. $keywordCondition = '';
  805. if (!empty($keyword)) {
  806. $keyword = Database::escape_string($keyword);
  807. $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
  808. }
  809. $sql = "SELECT
  810. id as col0,
  811. user_sender_id as col1,
  812. title as col2,
  813. send_date as col3,
  814. user_receiver_id as col4,
  815. msg_status as col5
  816. FROM $table_message
  817. WHERE
  818. user_sender_id=".api_get_user_id()." AND
  819. msg_status=" . MESSAGE_STATUS_OUTBOX."
  820. $keywordCondition
  821. ORDER BY col$column $direction
  822. LIMIT $from, $number_of_items";
  823. $sql_result = Database::query($sql);
  824. $i = 0;
  825. $message_list = array();
  826. while ($result = Database::fetch_row($sql_result)) {
  827. if ($request === true) {
  828. $message[0] = '<input type="checkbox" value='.$result[0].' name="out[]">';
  829. } else {
  830. $message[0] = ($result[0]);
  831. }
  832. $class = 'class = "read"';
  833. $result[2] = Security::remove_XSS($result[2]);
  834. $userInfo = api_get_user_info($result[4]);
  835. if ($request === true) {
  836. $message[1] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.$userInfo['complete_name'].'</a>';
  837. $message[2] = '<a onclick="show_sent_message('.$result[0].')" href="javascript:void(0)">'.str_replace("\\", "", $result[2]).'</a>';
  838. $message[3] = api_convert_and_format_date($result[3], DATE_TIME_FORMAT_LONG); //date stays the same
  839. $message[4] = '&nbsp;&nbsp;<a onclick="delete_one_message_outbox('.$result[0].')" href="javascript:void(0)" >'.
  840. Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>';
  841. } else {
  842. $link = '';
  843. if (isset($_GET['f']) && $_GET['f'] == 'social') {
  844. $link = '&f=social';
  845. }
  846. $message[1] = '<a '.$class.' onclick="show_sent_message ('.$result[0].')" href="../messages/view_message.php?id_send='.$result[0].$link.'">'.$result[2].'</a><br />'.$userInfo['complete_name'];
  847. $message[2] = api_convert_and_format_date($result[3], DATE_TIME_FORMAT_LONG); //date stays the same
  848. $message[3] = '<a href="outbox.php?action=deleteone&id='.$result[0].'&'.$link.'" onclick="javascript:if(!confirm('."'".addslashes(api_htmlentities(get_lang('ConfirmDeleteMessage')))."'".')) return false;" >'.
  849. Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>';
  850. }
  851. foreach ($message as $key => $value) {
  852. $message[$key] = $value;
  853. }
  854. $message_list[] = $message;
  855. $i++;
  856. }
  857. return $message_list;
  858. }
  859. /**
  860. * Gets information about number messages sent
  861. * @author Isaac FLores Paz <isaac.flores@dokeos.com>
  862. * @param void
  863. * @return integer
  864. */
  865. public static function get_number_of_messages_sent()
  866. {
  867. $table_message = Database::get_main_table(TABLE_MESSAGE);
  868. $keyword = Session::read('message_sent_search_keyword');
  869. $keywordCondition = '';
  870. if (!empty($keyword)) {
  871. $keyword = Database::escape_string($keyword);
  872. $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
  873. }
  874. $sql = "SELECT COUNT(id) as number_messages
  875. FROM $table_message
  876. WHERE
  877. msg_status=".MESSAGE_STATUS_OUTBOX." AND
  878. user_sender_id=" . api_get_user_id()."
  879. $keywordCondition
  880. ";
  881. $result = Database::query($sql);
  882. $result = Database::fetch_array($result);
  883. return $result['number_messages'];
  884. }
  885. /**
  886. * display message box in the inbox
  887. * @param int the message id
  888. * @param string inbox or outbox strings are available
  889. * @todo replace numbers with letters in the $row array pff...
  890. * @return string html with the message content
  891. */
  892. public static function show_message_box($message_id, $source = 'inbox')
  893. {
  894. $table_message = Database::get_main_table(TABLE_MESSAGE);
  895. $message_id = intval($message_id);
  896. if ($source == 'outbox') {
  897. if (isset($message_id) && is_numeric($message_id)) {
  898. $query = "SELECT * FROM $table_message
  899. WHERE
  900. user_sender_id = ".api_get_user_id()." AND
  901. id = " . $message_id." AND
  902. msg_status = 4;";
  903. $result = Database::query($query);
  904. }
  905. } else {
  906. if (is_numeric($message_id) && !empty($message_id)) {
  907. $query = "UPDATE $table_message SET
  908. msg_status = '".MESSAGE_STATUS_NEW."'
  909. WHERE
  910. user_receiver_id=" . api_get_user_id()." AND
  911. id='" . $message_id."'";
  912. Database::query($query);
  913. $query = "SELECT * FROM $table_message
  914. WHERE
  915. msg_status<>4 AND
  916. user_receiver_id=".api_get_user_id()." AND
  917. id='" . $message_id."'";
  918. $result = Database::query($query);
  919. }
  920. }
  921. $row = Database::fetch_array($result, 'ASSOC');
  922. $user_sender_id = $row['user_sender_id'];
  923. // get file attachments by message id
  924. $files_attachments = self::get_links_message_attachment_files($message_id, $source);
  925. $title = Security::remove_XSS($row['title'], STUDENT, true);
  926. $content = Security::remove_XSS($row['content'], STUDENT, true);
  927. $from_user = api_get_user_info($user_sender_id);
  928. $name = $from_user['complete_name'];
  929. $message_content = Display::page_subheader(str_replace("\\", "", $title));
  930. $user_image = '';
  931. if (api_get_setting('allow_social_tool') == 'true') {
  932. $user_image = Display::img(
  933. $from_user['avatar_no_query'],
  934. $name,
  935. array('title' => $name, 'class' => 'img-responsive img-circle', 'style' => 'max-width:35px')
  936. );
  937. }
  938. $receiverUserInfo = api_get_user_info($row['user_receiver_id']);
  939. $message_content .= '<tr>';
  940. if (api_get_setting('allow_social_tool') == 'true') {
  941. $message_content .= '<div class="row">';
  942. if ($source == 'outbox') {
  943. $message_content .= '<div class="col-md-12">';
  944. $message_content .= '<ul class="list-message">';
  945. $message_content .= '<li>'.$user_image.'</li>';
  946. $message_content .= '<li><a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$user_sender_id.'">'.$name.'</a> ';
  947. $message_content .= api_strtolower(get_lang('To')).'&nbsp;<b>'.$receiverUserInfo['complete_name'].'</b></li>';
  948. $message_content .= '<li>'.Display::dateToStringAgoAndLongDate($row['send_date']).'</li>';
  949. $message_content .= '</ul>';
  950. $message_content .= '</div>';
  951. } else {
  952. $message_content .= '<div class="col-md-12">';
  953. $message_content .= '<ul class="list-message">';
  954. $message_content .= '<li>'.$user_image.'</li>';
  955. $message_content .= '<li><a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$user_sender_id.'">'.$name.'</a> </li>';
  956. $message_content .= '<li>'.Display::dateToStringAgoAndLongDate($row['send_date']).'</li>';
  957. $message_content .= '</ul>';
  958. $message_content .= '</div>';
  959. }
  960. $message_content .= '</div>';
  961. } else {
  962. if ($source == 'outbox') {
  963. $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.$receiverUserInfo['complete_name'].'</b>';
  964. } else {
  965. $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.get_lang('Me').'</b>';
  966. }
  967. }
  968. $message_content .= '
  969. <hr style="color:#ddd" />
  970. <table width="100%">
  971. <tr>
  972. <td valign=top class="view-message-content">' . str_replace("\\", "", $content).'</td>
  973. </tr>
  974. </table>
  975. <div id="message-attach">' . (!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>
  976. <div style="padding: 15px 0px 5px 0px">';
  977. $social_link = '';
  978. if (isset($_GET['f']) && $_GET['f'] == 'social') {
  979. $social_link = 'f=social';
  980. }
  981. if ($source == 'outbox') {
  982. $message_content .= '<a href="outbox.php?'.$social_link.'">'.
  983. Display::return_icon('back.png', get_lang('ReturnToOutbox')).'</a> &nbsp';
  984. } else {
  985. $message_content .= '<a href="inbox.php?'.$social_link.'">'.
  986. Display::return_icon('back.png', get_lang('ReturnToInbox')).'</a> &nbsp';
  987. $message_content .= '<a href="new_message.php?re_id='.$message_id.'&'.$social_link.'">'.
  988. Display::return_icon('message_reply.png', get_lang('ReplyToMessage')).'</a> &nbsp';
  989. }
  990. $message_content .= '<a href="inbox.php?action=deleteone&id='.$message_id.'&'.$social_link.'" >'.
  991. Display::return_icon('delete.png', get_lang('DeleteMessage')).'</a>&nbsp';
  992. $message_content .= '</div></td>
  993. <td width=10></td>
  994. </tr>
  995. </table>';
  996. return $message_content;
  997. }
  998. /**
  999. * get user id by user email
  1000. * @param string $user_email
  1001. * @return int user id
  1002. */
  1003. public static function get_user_id_by_email($user_email)
  1004. {
  1005. $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
  1006. $sql = 'SELECT user_id FROM '.$tbl_user.'
  1007. WHERE email="' . Database::escape_string($user_email).'";';
  1008. $rs = Database::query($sql);
  1009. $row = Database::fetch_array($rs, 'ASSOC');
  1010. if (isset($row['user_id'])) {
  1011. return $row['user_id'];
  1012. } else {
  1013. return null;
  1014. }
  1015. }
  1016. /**
  1017. * Displays messages of a group with nested view
  1018. *
  1019. * @param int $group_id
  1020. */
  1021. public static function display_messages_for_group($group_id)
  1022. {
  1023. global $my_group_role;
  1024. $rows = self::get_messages_by_group($group_id);
  1025. $topics_per_page = 10;
  1026. $html_messages = '';
  1027. $query_vars = array('id' => $group_id, 'topics_page_nr' => 0);
  1028. if (is_array($rows) && count($rows) > 0) {
  1029. // prepare array for topics with its items
  1030. $topics = array();
  1031. $x = 0;
  1032. foreach ($rows as $index => $value) {
  1033. if (empty($value['parent_id'])) {
  1034. $topics[$value['id']] = $value;
  1035. }
  1036. }
  1037. $new_topics = array();
  1038. foreach ($topics as $id => $value) {
  1039. $rows = null;
  1040. $rows = self::get_messages_by_group_by_message($group_id, $value['id']);
  1041. if (!empty($rows)) {
  1042. $count = count(self::calculate_children($rows, $value['id']));
  1043. } else {
  1044. $count = 0;
  1045. }
  1046. $value['count'] = $count;
  1047. $new_topics[$id] = $value;
  1048. }
  1049. $array_html = array();
  1050. foreach ($new_topics as $index => $topic) {
  1051. $html = '';
  1052. // topics
  1053. $user_sender_info = api_get_user_info($topic['user_sender_id']);
  1054. $name = $user_sender_info['complete_name'];
  1055. $html .= '<div class="groups-messages">';
  1056. $html .= '<div class="row">';
  1057. $items = $topic['count'];
  1058. $reply_label = ($items == 1) ? get_lang('GroupReply') : get_lang('GroupReplies');
  1059. $label = '<i class="fa fa-envelope"></i> '.$items.' '.$reply_label;
  1060. $topic['title'] = trim($topic['title']);
  1061. if (empty($topic['title'])) {
  1062. $topic['title'] = get_lang('Untitled');
  1063. }
  1064. $html .= '<div class="col-xs-8 col-md-10">';
  1065. $html .= Display::tag(
  1066. 'h4',
  1067. Display::url(
  1068. Security::remove_XSS($topic['title'], STUDENT, true),
  1069. api_get_path(WEB_CODE_PATH).'social/group_topics.php?id='.$group_id.'&topic_id='.$topic['id']
  1070. ), array('class' => 'title')
  1071. );
  1072. $actions = '';
  1073. if ($my_group_role == GROUP_USER_PERMISSION_ADMIN ||
  1074. $my_group_role == GROUP_USER_PERMISSION_MODERATOR
  1075. ) {
  1076. $actions = '<br />'.Display::url(get_lang('Delete'), api_get_path(WEB_CODE_PATH).'social/group_topics.php?action=delete&id='.$group_id.'&topic_id='.$topic['id'], array('class' => 'btn btn-default'));
  1077. }
  1078. $date = '';
  1079. if ($topic['send_date'] != $topic['update_date']) {
  1080. if (!empty($topic['update_date'])) {
  1081. $date .= '<i class="fa fa-calendar"></i> '.get_lang('LastUpdate').' '.date_to_str_ago($topic['update_date']);
  1082. }
  1083. } else {
  1084. $date .= '<i class="fa fa-calendar"></i> '.get_lang('Created').' '.date_to_str_ago($topic['send_date']);
  1085. }
  1086. $html .= '<div class="date">'.$label.' - '.$date.$actions.'</div>';
  1087. $html .= '</div>';
  1088. $image = $user_sender_info['avatar'];
  1089. $user_info = '<div class="author"><img class="img-responsive img-circle" src="'.$image.'" alt="'.$name.'" width="64" height="64" title="'.$name.'" /></div>';
  1090. $user_info .= '<div class="name"><a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$topic['user_sender_id'].'">'.$name.'&nbsp;</a></div>';
  1091. $html .= '<div class="col-xs-4 col-md-2">';
  1092. $html .= $user_info;
  1093. $html .= '</div>';
  1094. $html .= '</div>';
  1095. $html .= '</div>';
  1096. $array_html[] = array($html);
  1097. }
  1098. // grids for items and topics with paginations
  1099. $html_messages .= Display::return_sortable_grid(
  1100. 'topics',
  1101. array(),
  1102. $array_html,
  1103. array(
  1104. 'hide_navigation' => false,
  1105. 'per_page' => $topics_per_page
  1106. ),
  1107. $query_vars,
  1108. false,
  1109. array(true, true, true, false),
  1110. false
  1111. );
  1112. }
  1113. return $html_messages;
  1114. }
  1115. /**
  1116. * Displays messages of a group with nested view
  1117. * @param $group_id
  1118. * @param $topic_id
  1119. * @param $is_member
  1120. * @param $message_id
  1121. * @return string
  1122. */
  1123. public static function display_message_for_group($group_id, $topic_id, $is_member, $message_id)
  1124. {
  1125. global $my_group_role;
  1126. $main_message = self::get_message_by_id($topic_id);
  1127. if (empty($main_message)) {
  1128. return false;
  1129. }
  1130. $rows = self::get_messages_by_group_by_message($group_id, $topic_id);
  1131. $rows = self::calculate_children($rows, $topic_id);
  1132. $current_user_id = api_get_user_id();
  1133. $items_per_page = 50;
  1134. $query_vars = array('id' => $group_id, 'topic_id' => $topic_id, 'topics_page_nr' => 0);
  1135. // Main message
  1136. $links = '';
  1137. $main_content = '';
  1138. $html = '';
  1139. $items_page_nr = null;
  1140. $user_sender_info = api_get_user_info($main_message['user_sender_id']);
  1141. $files_attachments = self::get_links_message_attachment_files($main_message['id']);
  1142. $name = $user_sender_info['complete_name'];
  1143. $topic_page_nr = isset($_GET['topics_page_nr']) ? intval($_GET['topics_page_nr']) : null;
  1144. $links .= '<div class="pull-right">';
  1145. $links .= '<div class="btn-group btn-group-sm">';
  1146. if (($my_group_role == GROUP_USER_PERMISSION_ADMIN ||
  1147. $my_group_role == GROUP_USER_PERMISSION_MODERATOR) ||
  1148. $main_message['user_sender_id'] == $current_user_id
  1149. ) {
  1150. $urlEdit = api_get_path(WEB_CODE_PATH);
  1151. $urlEdit .= 'social/message_for_group_form.inc.php?';
  1152. $urlEdit .= http_build_query([
  1153. 'user_friend' => $current_user_id,
  1154. 'group_id' => $group_id,
  1155. 'message_id' => $main_message['id'],
  1156. 'action' => 'edit_message_group',
  1157. 'anchor_topic' => 'topic_'.$main_message['id'],
  1158. 'topics_page_nr' => $topic_page_nr,
  1159. 'items_page_nr' => $items_page_nr,
  1160. 'topic_id' => $main_message['id']
  1161. ]);
  1162. if (api_is_platform_admin()) {
  1163. $links .= Display::url(
  1164. Display::returnFontAwesomeIcon('trash'),
  1165. 'group_topics.php?action=delete&id='.$group_id.'&topic_id='.$topic_id,
  1166. [
  1167. 'class' => 'btn btn-default'
  1168. ]
  1169. );
  1170. }
  1171. $links .= Display::url(
  1172. Display::returnFontAwesomeIcon('pencil'),
  1173. $urlEdit,
  1174. [
  1175. 'class' => 'btn btn-default ajax',
  1176. 'title' => get_lang('Edit'),
  1177. 'data-title' => get_lang('Edit'),
  1178. 'data-size' => 'lg'
  1179. ]
  1180. );
  1181. }
  1182. $urlReply = api_get_path(WEB_CODE_PATH);
  1183. $urlReply .= 'social/message_for_group_form.inc.php?';
  1184. $urlReply .= http_build_query([
  1185. 'user_friend' => api_get_user_id(),
  1186. 'group_id' => $group_id,
  1187. 'message_id' => $main_message['id'],
  1188. 'action' => 'reply_message_group',
  1189. 'anchor_topic' => 'topic_'.$main_message['id'],
  1190. 'topics_page_nr' => $topic_page_nr,
  1191. 'topic_id' => $main_message['id']
  1192. ]);
  1193. $links .= Display::url(
  1194. Display::returnFontAwesomeIcon('commenting'),
  1195. $urlReply,
  1196. [
  1197. 'class' => 'btn btn-default ajax',
  1198. 'title' => get_lang('Reply'),
  1199. 'data-title' => get_lang('Reply'),
  1200. 'data-size' => 'lg'
  1201. ]
  1202. );
  1203. $links .= '</div>';
  1204. $links .= '</div>';
  1205. $title = '<h4>'.Security::remove_XSS($main_message['title'], STUDENT, true).$links.'</h4>';
  1206. $userPicture = $user_sender_info['avatar'];
  1207. $main_content .= '<div class="row">';
  1208. $main_content .= '<div class="col-md-2">';
  1209. $main_content .= '<div class="avatar-author">';
  1210. $main_content .= '<img width="60px" src="'.$userPicture.'" alt="'.$name.'" class="img-responsive img-circle" title="'.$name.'" />';
  1211. $main_content .= '</div>';
  1212. $main_content .= '</div>';
  1213. $date = '';
  1214. if ($main_message['send_date'] != $main_message['update_date']) {
  1215. if (!empty($main_message['update_date'])) {
  1216. $date = '<div class="date"> '.Display::returnFontAwesomeIcon('calendar').' '.get_lang('LastUpdate').' '.date_to_str_ago($main_message['update_date']).'</div>';
  1217. }
  1218. } else {
  1219. $date = '<div class="date"> '.Display::returnFontAwesomeIcon('calendar').' '.get_lang('Created').' '.date_to_str_ago($main_message['send_date']).'</div>';
  1220. }
  1221. $attachment = '<div class="message-attach">'.(!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>';
  1222. $main_content .= '<div class="col-md-10">';
  1223. $user_link = '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$main_message['user_sender_id'].'">'.$name.'</a>';
  1224. $main_content .= '<div class="message-content"> ';
  1225. $main_content .= '<div class="username">'.$user_link.'</div>';
  1226. $main_content .= $date;
  1227. $main_content .= '<div class="message">'.$main_message['content'].$attachment.'</div></div>';
  1228. $main_content .= '</div>';
  1229. $main_content .= '</div>';
  1230. $html .= Display::div(
  1231. Display::div(
  1232. $title.$main_content,
  1233. array('class' => 'message-topic')
  1234. ),
  1235. array('class' => 'sm-groups-message')
  1236. );
  1237. $topic_id = $main_message['id'];
  1238. if (is_array($rows) && count($rows) > 0) {
  1239. $topics = $rows;
  1240. $array_html_items = array();
  1241. foreach ($topics as $index => $topic) {
  1242. if (empty($topic['id'])) {
  1243. continue;
  1244. }
  1245. $items_page_nr = isset($_GET['items_'.$topic['id'].'_page_nr']) ? intval($_GET['items_'.$topic['id'].'_page_nr']) : null;
  1246. $links = '';
  1247. $links .= '<div class="pull-right">';
  1248. $html_items = '';
  1249. $user_sender_info = api_get_user_info($topic['user_sender_id']);
  1250. $files_attachments = self::get_links_message_attachment_files($topic['id']);
  1251. $name = $user_sender_info['complete_name'];
  1252. $links .= '<div class="btn-group btn-group-sm">';
  1253. if (($my_group_role == GROUP_USER_PERMISSION_ADMIN || $my_group_role == GROUP_USER_PERMISSION_MODERATOR) || $topic['user_sender_id'] == $current_user_id) {
  1254. $links .= '<a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?height=400&width=800&&user_friend='.$current_user_id.'&group_id='.$group_id.'&message_id='.$topic['id'].'&action=edit_message_group&anchor_topic=topic_'.$topic_id.'&topics_page_nr='.$topic_page_nr.'&items_page_nr='.$items_page_nr.'&topic_id='.$topic_id.'" class="ajax btn btn-default" data-size="lg" data-title="'.get_lang('Edit').'" title="'.get_lang('Edit').'">'.
  1255. Display::returnFontAwesomeIcon('pencil').'</a>';
  1256. }
  1257. $links .= '<a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?height=400&width=800&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&message_id='.$topic['id'].'&action=reply_message_group&anchor_topic=topic_'.$topic_id.'&topics_page_nr='.$topic_page_nr.'&items_page_nr='.$items_page_nr.'&topic_id='.$topic_id.'" class="ajax btn btn-default" data-size="lg" data-title="'.get_lang('Reply').'" title="'.get_lang('Reply').'">';
  1258. $links .= Display::returnFontAwesomeIcon('commenting').'</a>';
  1259. $links .= '</div>';
  1260. $links .= '</div>';
  1261. $userPicture = $user_sender_info['avatar'];
  1262. $user_link = '<a href="'.api_get_path(WEB_PATH).'main/social/profile.php?u='.$topic['user_sender_id'].'">'.$name.'&nbsp</a>';
  1263. $html_items .= '<div class="row">';
  1264. $html_items .= '<div class="col-md-2">';
  1265. $html_items .= '<div class="avatar-author"><img width="60px" src="'.$userPicture.'" alt="'.$name.'" class="img-responsive img-circle" title="'.$name.'" /></div>';
  1266. $html_items .= '</div>';
  1267. $date = '';
  1268. if ($topic['send_date'] != $topic['update_date']) {
  1269. if (!empty($topic['update_date'])) {
  1270. $date = '<div class="date"> '.Display::returnFontAwesomeIcon('calendar').' '.get_lang('LastUpdate').' '.date_to_str_ago($topic['update_date']).'</div>';
  1271. }
  1272. } else {
  1273. $date = '<div class="date"> '.Display::returnFontAwesomeIcon('calendar').get_lang('Created').' '.date_to_str_ago($topic['send_date']).'</div>';
  1274. }
  1275. $attachment = '<div class="message-attach">'.(!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>';
  1276. $html_items .= '<div class="col-md-10">';
  1277. $html_items .= '<div class="message-content">';
  1278. $html_items .= $links;
  1279. $html_items .= '<div class="username">'.$user_link.'</div>';
  1280. $html_items .= $date;
  1281. $html_items .= '<div class="message">'.Security::remove_XSS($topic['content'], STUDENT, true).'</div>'.$attachment.'</div>';
  1282. $html_items .= '</div>';
  1283. $html_items .= '</div>';
  1284. $base_padding = 20;
  1285. if ($topic['indent_cnt'] == 0) {
  1286. $indent = $base_padding;
  1287. } else {
  1288. $indent = intval($topic['indent_cnt']) * $base_padding + $base_padding;
  1289. }
  1290. $html_items = Display::div($html_items, array('class' => 'message-post', 'id' => 'msg_'.$topic['id']));
  1291. $html_items = Display::div($html_items, array('class' => '', 'style' => 'margin-left:'.$indent.'px'));
  1292. $array_html_items[] = array($html_items);
  1293. }
  1294. // grids for items with paginations
  1295. $options = array('hide_navigation' => false, 'per_page' => $items_per_page);
  1296. $visibility = array(true, true, true, false);
  1297. $style_class = array(
  1298. 'item' => array('class' => 'user-post'),
  1299. 'main' => array('class' => 'user-list'),
  1300. );
  1301. if (!empty($array_html_items)) {
  1302. $html .= Display::return_sortable_grid(
  1303. 'items_'.$topic['id'],
  1304. array(),
  1305. $array_html_items,
  1306. $options,
  1307. $query_vars,
  1308. null,
  1309. $visibility,
  1310. false,
  1311. $style_class
  1312. );
  1313. }
  1314. }
  1315. return $html;
  1316. }
  1317. /**
  1318. * Add children to messages by id is used for nested view messages
  1319. * @param array $rows rows of messages
  1320. * @return array $first_seed new list adding the item children
  1321. */
  1322. public static function calculate_children($rows, $first_seed)
  1323. {
  1324. $rows_with_children = array();
  1325. foreach ($rows as $row) {
  1326. $rows_with_children[$row["id"]] = $row;
  1327. $rows_with_children[$row["parent_id"]]["children"][] = $row["id"];
  1328. }
  1329. $rows = $rows_with_children;
  1330. $sorted_rows = array(0 => array());
  1331. self::message_recursive_sort($rows, $sorted_rows, $first_seed);
  1332. unset($sorted_rows[0]);
  1333. return $sorted_rows;
  1334. }
  1335. /**
  1336. * Sort recursively the messages, is used for for nested view messages
  1337. * @param array original rows of messages
  1338. * @param array list recursive of messages
  1339. * @param int seed for calculate the indent
  1340. * @param int indent for nested view
  1341. * @return void
  1342. */
  1343. public static function message_recursive_sort($rows, &$messages, $seed = 0, $indent = 0)
  1344. {
  1345. if ($seed > 0 && isset($rows[$seed]["id"])) {
  1346. $messages[$rows[$seed]["id"]] = $rows[$seed];
  1347. $messages[$rows[$seed]["id"]]["indent_cnt"] = $indent;
  1348. $indent++;
  1349. }
  1350. if (isset($rows[$seed]["children"])) {
  1351. foreach ($rows[$seed]["children"] as $child) {
  1352. self::message_recursive_sort($rows, $messages, $child, $indent);
  1353. }
  1354. }
  1355. }
  1356. /**
  1357. * Sort date by desc from a multi-dimensional array
  1358. * @param array $array1 first array to compare
  1359. * @param array $array2 second array to compare
  1360. * @return bool
  1361. */
  1362. public function order_desc_date($array1, $array2)
  1363. {
  1364. return strcmp($array2['send_date'], $array1['send_date']);
  1365. }
  1366. /**
  1367. * Get array of links (download) for message attachment files
  1368. * @param int $message_id
  1369. * @param string $type message list (inbox/outbox)
  1370. * @return array
  1371. */
  1372. public static function get_links_message_attachment_files($message_id, $type = '')
  1373. {
  1374. $tbl_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  1375. $message_id = intval($message_id);
  1376. // get file attachments by message id
  1377. $links_attach_file = array();
  1378. if (!empty($message_id)) {
  1379. $sql = "SELECT * FROM $tbl_message_attach
  1380. WHERE message_id = '$message_id'";
  1381. $rs_file = Database::query($sql);
  1382. if (Database::num_rows($rs_file) > 0) {
  1383. $attach_icon = Display::return_icon('attachment.gif', '');
  1384. $archiveURL = api_get_path(WEB_CODE_PATH).'messages/download.php?type='.$type.'&file=';
  1385. while ($row_file = Database::fetch_array($rs_file)) {
  1386. $archiveFile = $row_file['path'];
  1387. $filename = $row_file['filename'];
  1388. $filesize = format_file_size($row_file['size']);
  1389. $filecomment = Security::remove_XSS($row_file['comment']);
  1390. $filename = Security::remove_XSS($filename);
  1391. $links_attach_file[] = $attach_icon.'&nbsp;<a href="'.$archiveURL.$archiveFile.'">'.$filename.'</a>&nbsp;('.$filesize.')'.(!empty($filecomment) ? '&nbsp;-&nbsp;<i>'.$filecomment.'</i>' : '');
  1392. }
  1393. }
  1394. }
  1395. return $links_attach_file;
  1396. }
  1397. /**
  1398. * Get message list by id
  1399. * @param int $message_id
  1400. * @return array
  1401. */
  1402. public static function get_message_by_id($message_id)
  1403. {
  1404. $tbl_message = Database::get_main_table(TABLE_MESSAGE);
  1405. $message_id = intval($message_id);
  1406. $sql = "SELECT * FROM $tbl_message
  1407. WHERE
  1408. id = '$message_id' AND
  1409. msg_status <> '".MESSAGE_STATUS_DELETED."' ";
  1410. $res = Database::query($sql);
  1411. $item = array();
  1412. if (Database::num_rows($res) > 0) {
  1413. $item = Database::fetch_array($res, 'ASSOC');
  1414. }
  1415. return $item;
  1416. }
  1417. /**
  1418. *
  1419. * @return string
  1420. */
  1421. public static function generate_message_form()
  1422. {
  1423. $form = new FormValidator('send_message');
  1424. $form->addText('subject', get_lang('Subject'), false, ['id' => 'subject_id']);
  1425. $form->addTextarea('content', get_lang('Message'), ['id' => 'content_id', 'rows' => '5']);
  1426. return $form->returnForm();
  1427. }
  1428. /**
  1429. * @param $id
  1430. * @param array $params
  1431. * @return string
  1432. */
  1433. public static function generate_invitation_form($id, $params = array())
  1434. {
  1435. $form = new FormValidator('send_invitation');
  1436. $form->addTextarea('content', get_lang('AddPersonalMessage'), ['id' => 'content_invitation_id', 'rows' => 5]);
  1437. return $form->returnForm();
  1438. }
  1439. //@todo this functions should be in the message class
  1440. /**
  1441. * @param string $keyword
  1442. * @return string
  1443. */
  1444. public static function inbox_display($keyword = '')
  1445. {
  1446. $success = get_lang('SelectedMessagesDeleted');
  1447. $success_read = get_lang('SelectedMessagesRead');
  1448. $success_unread = get_lang('SelectedMessagesUnRead');
  1449. $html = '';
  1450. Session::write('message_search_keyword', $keyword);
  1451. if (isset($_REQUEST['action'])) {
  1452. switch ($_REQUEST['action']) {
  1453. case 'mark_as_unread' :
  1454. $number_of_selected_messages = count($_POST['id']);
  1455. if (is_array($_POST['id'])) {
  1456. foreach ($_POST['id'] as $index => $message_id) {
  1457. self::update_message_status(api_get_user_id(), $message_id, MESSAGE_STATUS_UNREAD);
  1458. }
  1459. }
  1460. $html .= Display::return_message(api_xml_http_response_encode($success_unread), 'normal', false);
  1461. break;
  1462. case 'mark_as_read' :
  1463. $number_of_selected_messages = count($_POST['id']);
  1464. if (is_array($_POST['id'])) {
  1465. foreach ($_POST['id'] as $index => $message_id) {
  1466. self::update_message_status(api_get_user_id(), $message_id, MESSAGE_STATUS_NEW);
  1467. }
  1468. }
  1469. $html .= Display::return_message(api_xml_http_response_encode($success_read), 'normal', false);
  1470. break;
  1471. case 'delete' :
  1472. $number_of_selected_messages = count($_POST['id']);
  1473. foreach ($_POST['id'] as $index => $message_id) {
  1474. self::delete_message_by_user_receiver(api_get_user_id(), $message_id);
  1475. }
  1476. $html .= Display::return_message(api_xml_http_response_encode($success), 'normal', false);
  1477. break;
  1478. case 'deleteone' :
  1479. self::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
  1480. $html .= Display::return_message(api_xml_http_response_encode($success), 'confirmation', false);
  1481. break;
  1482. }
  1483. }
  1484. // display sortable table with messages of the current user
  1485. $table = new SortableTable(
  1486. 'message_inbox',
  1487. array('MessageManager', 'get_number_of_messages'),
  1488. array('MessageManager', 'get_message_data'),
  1489. 3,
  1490. 20,
  1491. 'DESC'
  1492. );
  1493. $table->set_header(0, '', false, array('style' => 'width:15px;'));
  1494. $table->set_header(1, get_lang('Messages'), false);
  1495. $table->set_header(2, get_lang('Date'), true, array('style' => 'width:180px;'));
  1496. $table->set_header(3, get_lang('Modify'), false, array('style' => 'width:70px;'));
  1497. if (isset($_REQUEST['f']) && $_REQUEST['f'] == 'social') {
  1498. $parameters['f'] = 'social';
  1499. $table->set_additional_parameters($parameters);
  1500. }
  1501. $table->set_form_actions(
  1502. array(
  1503. 'delete' => get_lang('DeleteSelectedMessages'),
  1504. 'mark_as_unread' => get_lang('MailMarkSelectedAsUnread'),
  1505. 'mark_as_read' => get_lang('MailMarkSelectedAsRead'),
  1506. )
  1507. );
  1508. $html .= $table->return_table();
  1509. Session::erase('message_search_keyword');
  1510. return $html;
  1511. }
  1512. /**
  1513. * @param string $keyword
  1514. * @return null|string
  1515. */
  1516. public static function outbox_display($keyword = '')
  1517. {
  1518. $social_link = false;
  1519. if (isset($_REQUEST['f']) && $_REQUEST['f'] == 'social') {
  1520. $social_link = 'f=social';
  1521. }
  1522. Session::write('message_sent_search_keyword', $keyword);
  1523. $success = get_lang('SelectedMessagesDeleted').'&nbsp</b><br /><a href="outbox.php?'.$social_link.'">'.get_lang('BackToOutbox').'</a>';
  1524. $html = null;
  1525. if (isset($_REQUEST['action'])) {
  1526. switch ($_REQUEST['action']) {
  1527. case 'delete':
  1528. $number_of_selected_messages = count($_POST['id']);
  1529. if ($number_of_selected_messages != 0) {
  1530. foreach ($_POST['id'] as $index => $message_id) {
  1531. self::delete_message_by_user_receiver(api_get_user_id(), $message_id);
  1532. }
  1533. }
  1534. $html .= Display::return_message(api_xml_http_response_encode($success), 'normal', false);
  1535. break;
  1536. case 'deleteone':
  1537. self::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
  1538. $html .= Display::return_message(api_xml_http_response_encode($success), 'normal', false);
  1539. $html .= '<br/>';
  1540. break;
  1541. }
  1542. }
  1543. // display sortable table with messages of the current user
  1544. $table = new SortableTable(
  1545. 'message_outbox',
  1546. array('MessageManager', 'get_number_of_messages_sent'),
  1547. array('MessageManager', 'get_message_data_sent'),
  1548. 3,
  1549. 20,
  1550. 'DESC'
  1551. );
  1552. $parameters['f'] = isset($_GET['f']) && $_GET['f'] == 'social' ? 'social' : null;
  1553. $table->set_additional_parameters($parameters);
  1554. $table->set_header(0, '', false, array('style' => 'width:15px;'));
  1555. $table->set_header(1, get_lang('Messages'), false);
  1556. $table->set_header(2, get_lang('Date'), true, array('style' => 'width:160px;'));
  1557. $table->set_header(3, get_lang('Modify'), false, array('style' => 'width:70px;'));
  1558. $table->set_form_actions(array('delete' => get_lang('DeleteSelectedMessages')));
  1559. $html .= $table->return_table();
  1560. Session::erase('message_sent_search_keyword');
  1561. return $html;
  1562. }
  1563. /**
  1564. * Get the count of the last received messages for a user
  1565. * @param int $userId The user id
  1566. * @param int $lastId The id of the last received message
  1567. * @return int The count of new messages
  1568. */
  1569. public static function countMessagesFromLastReceivedMessage($userId, $lastId = 0)
  1570. {
  1571. $userId = intval($userId);
  1572. $lastId = intval($lastId);
  1573. if (empty($userId)) {
  1574. return 0;
  1575. }
  1576. $messagesTable = Database::get_main_table(TABLE_MESSAGE);
  1577. $conditions = array(
  1578. 'where' => array(
  1579. 'user_receiver_id = ?' => $userId,
  1580. 'AND msg_status = ?' => MESSAGE_STATUS_UNREAD,
  1581. 'AND id > ?' => $lastId
  1582. )
  1583. );
  1584. $result = Database::select('COUNT(1) AS qty', $messagesTable, $conditions);
  1585. if (!empty($result)) {
  1586. $row = current($result);
  1587. return $row['qty'];
  1588. }
  1589. return 0;
  1590. }
  1591. /**
  1592. * Get the data of the last received messages for a user
  1593. * @param int $userId The user id
  1594. * @param int $lastId The id of the last received message
  1595. * @return array
  1596. */
  1597. public static function getMessagesFromLastReceivedMessage($userId, $lastId = 0)
  1598. {
  1599. $userId = intval($userId);
  1600. $lastId = intval($lastId);
  1601. if (empty($userId)) {
  1602. return 0;
  1603. }
  1604. $messagesTable = Database::get_main_table(TABLE_MESSAGE);
  1605. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  1606. $sql = "SELECT m.*, u.user_id, u.lastname, u.firstname
  1607. FROM $messagesTable as m
  1608. INNER JOIN $userTable as u
  1609. ON m.user_sender_id = u.user_id
  1610. WHERE
  1611. m.user_receiver_id = $userId AND
  1612. m.msg_status = ".MESSAGE_STATUS_UNREAD."
  1613. AND m.id > $lastId
  1614. ORDER BY m.send_date DESC";
  1615. $result = Database::query($sql);
  1616. $messages = [];
  1617. if ($result !== false) {
  1618. while ($row = Database::fetch_assoc($result)) {
  1619. $messages[] = $row;
  1620. }
  1621. }
  1622. return $messages;
  1623. }
  1624. /**
  1625. * Check whether a message has attachments
  1626. * @param int $messageId The message id
  1627. * @return boolean Whether the message has attachments return true. Otherwise return false
  1628. */
  1629. public static function hasAttachments($messageId)
  1630. {
  1631. $messageId = intval($messageId);
  1632. if (empty($messageId)) {
  1633. return false;
  1634. }
  1635. $messageAttachmentTable = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  1636. $conditions = array(
  1637. 'where' => array(
  1638. 'message_id = ?' => $messageId
  1639. )
  1640. );
  1641. $result = Database::select('COUNT(1) AS qty', $messageAttachmentTable, $conditions, 'first');
  1642. if (!empty($result)) {
  1643. if ($result['qty'] > 0) {
  1644. return true;
  1645. }
  1646. }
  1647. return false;
  1648. }
  1649. /**
  1650. * @param string $url
  1651. *
  1652. * @return FormValidator
  1653. */
  1654. public static function getSearchForm($url)
  1655. {
  1656. $form = new FormValidator(
  1657. 'search',
  1658. 'post',
  1659. $url,
  1660. null,
  1661. [],
  1662. FormValidator::LAYOUT_INLINE
  1663. );
  1664. $form->addElement('text', 'keyword', false, array(
  1665. 'aria-label' => get_lang('Search')
  1666. ));
  1667. $form->addButtonSearch(get_lang('Search'));
  1668. return $form;
  1669. }
  1670. /**
  1671. * Send a notification to all admins when a new user is registered
  1672. * @param User $user
  1673. */
  1674. public static function sendNotificationByRegisteredUser(User $user)
  1675. {
  1676. $tplMailBody = new Template(
  1677. null,
  1678. false,
  1679. false,
  1680. false,
  1681. false,
  1682. false,
  1683. false
  1684. );
  1685. $tplMailBody->assign('user', $user);
  1686. $tplMailBody->assign('is_western_name_order', api_is_western_name_order());
  1687. $tplMailBody->assign('manageUrl', api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$user->getId());
  1688. $layoutContent = $tplMailBody->get_template('mail/new_user_mail_to_admin.tpl');
  1689. $emailsubject = '['.get_lang('UserRegistered').'] '.$user->getUsername();
  1690. $emailbody = $tplMailBody->fetch($layoutContent);
  1691. $admins = UserManager::get_all_administrators();
  1692. foreach ($admins as $admin_info) {
  1693. self::send_message(
  1694. $admin_info['user_id'],
  1695. $emailsubject,
  1696. $emailbody,
  1697. [],
  1698. [],
  1699. null,
  1700. null,
  1701. null,
  1702. null,
  1703. $user->getId()
  1704. );
  1705. }
  1706. }
  1707. /**
  1708. * Get the error log from failed mailing
  1709. * This assumes a complex setup where you have a cron script regularly copying the mail queue log
  1710. * into app/cache/mail/mailq.
  1711. * This can be done with a cron command like (check the location of your mail log file first):
  1712. * @example 0,30 * * * * root cp /var/log/exim4/mainlog /var/www/chamilo/app/cache/mail/mailq
  1713. * @return array|bool
  1714. */
  1715. public static function failedSentMailErrors()
  1716. {
  1717. $base = api_get_path(SYS_ARCHIVE_PATH).'mail/';
  1718. $mailq = $base.'mailq';
  1719. if (!file_exists($mailq) || !is_readable($mailq)) {
  1720. return false;
  1721. }
  1722. $file = fopen($mailq, 'r');
  1723. $i = 1;
  1724. while (!feof($file)) {
  1725. $line = fgets($file);
  1726. //$line = trim($line);
  1727. if (trim($line) == '') {
  1728. continue;
  1729. }
  1730. //Get the mail code, something like 1WBumL-0002xg-FF
  1731. if (preg_match('/(.*)\s((.*)-(.*)-(.*))\s<(.*)$/', $line, $codeMatches)) {
  1732. $mail_queue[$i]['code'] = $codeMatches[2];
  1733. }
  1734. $fullMail = $base.$mail_queue[$i]['code'];
  1735. $mailFile = fopen($fullMail, 'r');
  1736. //Get the reason of mail fail
  1737. $iX = 1;
  1738. while (!feof($mailFile)) {
  1739. $mailLine = fgets($mailFile);
  1740. #if ($iX == 4 && preg_match('/(.*):\s(.*)$/', $mailLine, $matches)) {
  1741. if (
  1742. $iX == 2 &&
  1743. preg_match('/(.*)(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s(.*)/', $mailLine, $detailsMatches)
  1744. ) {
  1745. $mail_queue[$i]['reason'] = $detailsMatches[3];
  1746. }
  1747. $iX++;
  1748. }
  1749. fclose($mailFile);
  1750. //Get the time of mail fail
  1751. if (preg_match('/^\s?(\d+)(\D+)\s+(.*)$/', $line, $timeMatches)) {
  1752. $mail_queue[$i]['time'] = $timeMatches[1].$timeMatches[2];
  1753. } elseif (preg_match('/^(\s+)((.*)@(.*))\s+(.*)$/', $line, $emailMatches)) {
  1754. $mail_queue[$i]['mail'] = $emailMatches[2];
  1755. $i++;
  1756. }
  1757. }
  1758. fclose($file);
  1759. return array_reverse($mail_queue);
  1760. }
  1761. }