message.lib.php 71 KB

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