message.lib.php 78 KB

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