message.lib.php 67 KB

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