message.lib.php 75 KB

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