message.lib.php 71 KB

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