message.lib.php 74 KB

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