message.lib.php 70 KB

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