message.lib.php 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\Message;
  4. use Chamilo\UserBundle\Entity\User;
  5. use ChamiloSession as Session;
  6. /**
  7. * Class MessageManager.
  8. *
  9. * This class provides methods for messages management.
  10. * Include/require it in your code to use its features.
  11. *
  12. * @package chamilo.library
  13. */
  14. class MessageManager
  15. {
  16. public const MESSAGE_TYPE_INBOX = 1;
  17. public const MESSAGE_TYPE_OUTBOX = 2;
  18. public const MESSAGE_TYPE_PROMOTED = 3;
  19. /**
  20. * Get count new messages for the current user from the database.
  21. *
  22. * @return int
  23. */
  24. public static function getCountNewMessages()
  25. {
  26. $userId = api_get_user_id();
  27. if (empty($userId)) {
  28. return false;
  29. }
  30. static $count;
  31. if (!isset($count)) {
  32. $cacheAvailable = api_get_configuration_value('apc');
  33. if ($cacheAvailable === true) {
  34. $var = api_get_configuration_value('apc_prefix').'social_messages_unread_u_'.$userId;
  35. if (apcu_exists($var)) {
  36. $count = apcu_fetch($var);
  37. } else {
  38. $count = self::getCountNewMessagesFromDB($userId);
  39. apcu_store($var, $count, 60);
  40. }
  41. } else {
  42. $count = self::getCountNewMessagesFromDB($userId);
  43. }
  44. }
  45. return $count;
  46. }
  47. /**
  48. * Gets the total number of messages, used for the inbox sortable table.
  49. *
  50. * @param array $params
  51. *
  52. * @return int
  53. */
  54. public static function getNumberOfMessages($params)
  55. {
  56. $table = Database::get_main_table(TABLE_MESSAGE);
  57. $conditions = self::getWhereConditions($params);
  58. $sql = "SELECT COUNT(id) as number_messages
  59. FROM $table
  60. WHERE
  61. $conditions
  62. ";
  63. $result = Database::query($sql);
  64. $result = Database::fetch_array($result);
  65. if ($result) {
  66. return (int) $result['number_messages'];
  67. }
  68. return 0;
  69. }
  70. /**
  71. * @param array $extraParams
  72. *
  73. * @return string
  74. */
  75. public static function getWhereConditions($extraParams)
  76. {
  77. $userId = api_get_user_id();
  78. $keyword = isset($extraParams['keyword']) && !empty($extraParams['keyword']) ? $extraParams['keyword'] : '';
  79. $type = isset($extraParams['type']) && !empty($extraParams['type']) ? $extraParams['type'] : '';
  80. if (empty($type)) {
  81. return '';
  82. }
  83. switch ($type) {
  84. case self::MESSAGE_TYPE_INBOX:
  85. $statusList = [MESSAGE_STATUS_NEW, MESSAGE_STATUS_UNREAD];
  86. $userCondition = " user_receiver_id = $userId AND";
  87. break;
  88. case self::MESSAGE_TYPE_OUTBOX:
  89. $statusList = [MESSAGE_STATUS_OUTBOX];
  90. $userCondition = " user_sender_id = $userId AND";
  91. break;
  92. case self::MESSAGE_TYPE_PROMOTED:
  93. $statusList = [MESSAGE_STATUS_PROMOTED];
  94. $userCondition = " user_receiver_id = $userId AND";
  95. break;
  96. }
  97. if (empty($statusList)) {
  98. return '';
  99. }
  100. $keywordCondition = '';
  101. if (!empty($keyword)) {
  102. $keyword = Database::escape_string($keyword);
  103. $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
  104. }
  105. $messageStatusCondition = implode("','", $statusList);
  106. return " $userCondition
  107. msg_status IN ('$messageStatusCondition')
  108. $keywordCondition";
  109. }
  110. /**
  111. * Gets information about some messages, used for the inbox sortable table.
  112. *
  113. * @param int $from
  114. * @param int $numberOfItems
  115. * @param string $column
  116. * @param string $direction
  117. * @param array $extraParams
  118. *
  119. * @return array
  120. */
  121. public static function getMessageData(
  122. $from,
  123. $numberOfItems,
  124. $column,
  125. $direction,
  126. $extraParams = []
  127. ) {
  128. $from = (int) $from;
  129. $numberOfItems = (int) $numberOfItems;
  130. // Forcing this order.
  131. if (!isset($direction)) {
  132. $column = 2;
  133. $direction = 'DESC';
  134. } else {
  135. $column = (int) $column;
  136. if (!in_array($direction, ['ASC', 'DESC'])) {
  137. $direction = 'ASC';
  138. }
  139. }
  140. if (!in_array($column, [0, 1, 2])) {
  141. $column = 2;
  142. }
  143. $type = isset($extraParams['type']) && !empty($extraParams['type']) ? $extraParams['type'] : '';
  144. if (empty($type)) {
  145. return [];
  146. }
  147. $viewUrl = '';
  148. switch ($type) {
  149. case self::MESSAGE_TYPE_OUTBOX:
  150. case self::MESSAGE_TYPE_INBOX:
  151. $viewUrl = api_get_path(WEB_CODE_PATH).'messages/view_message.php';
  152. break;
  153. case self::MESSAGE_TYPE_PROMOTED:
  154. $viewUrl = api_get_path(WEB_CODE_PATH).'social/view_promoted_message.php';
  155. break;
  156. }
  157. $viewUrl .= '?type='.$type;
  158. $whereConditions = self::getWhereConditions($extraParams);
  159. if (empty($whereConditions)) {
  160. return [];
  161. }
  162. $table = Database::get_main_table(TABLE_MESSAGE);
  163. $sql = "SELECT
  164. id as col0,
  165. title as col1,
  166. send_date as col2,
  167. msg_status as col3,
  168. user_sender_id
  169. FROM $table
  170. WHERE
  171. $whereConditions
  172. ORDER BY col$column $direction
  173. LIMIT $from, $numberOfItems";
  174. $result = Database::query($sql);
  175. $messageList = [];
  176. $newMessageLink = api_get_path(WEB_CODE_PATH).'messages/new_message.php';
  177. $actions = $extraParams['actions'];
  178. $url = api_get_self();
  179. while ($row = Database::fetch_array($result, 'ASSOC')) {
  180. $messageId = $row['col0'];
  181. $title = $row['col1'];
  182. $sendDate = $row['col2'];
  183. $status = $row['col3'];
  184. $senderId = $row['user_sender_id'];
  185. $title = Security::remove_XSS($title, STUDENT, true);
  186. $title = cut($title, 80, true);
  187. $class = 'class = "read"';
  188. if ($status == 1) {
  189. $class = 'class = "unread"';
  190. }
  191. $userInfo = api_get_user_info($senderId);
  192. $message[3] = '';
  193. if (!empty($senderId) && !empty($userInfo)) {
  194. $message[1] = '<a '.$class.' href="'.$viewUrl.'&id='.$messageId.'">'.$title.'</a><br />';
  195. $message[1] .= $userInfo['complete_name_with_username'];
  196. if (in_array('reply', $actions)) {
  197. $message[3] =
  198. Display::url(
  199. Display::returnFontAwesomeIcon('reply', 2),
  200. $newMessageLink.'?re_id='.$messageId,
  201. ['title' => get_lang('Reply to this message')]
  202. );
  203. }
  204. } else {
  205. $message[1] = '<a '.$class.' href="'.$viewUrl.'&id='.$messageId.'">'.$title.'</a><br />';
  206. $message[1] .= get_lang('Unknown user');
  207. if (in_array('reply', $actions)) {
  208. $message[3] =
  209. Display::url(
  210. Display::returnFontAwesomeIcon('reply', 2),
  211. '#',
  212. ['title' => get_lang('Reply to this message')]
  213. );
  214. }
  215. }
  216. $message[0] = $messageId;
  217. $message[2] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
  218. // Actions
  219. if (in_array('edit', $actions)) {
  220. $message[3] .=
  221. '&nbsp;&nbsp;'.
  222. Display::url(
  223. Display::returnFontAwesomeIcon('pencil', 2),
  224. $newMessageLink.'?action=edit&id='.$messageId,
  225. ['title' => get_lang('Forward message')]
  226. );
  227. }
  228. // Actions
  229. if (in_array('forward', $actions)) {
  230. $message[3] .=
  231. '&nbsp;&nbsp;'.
  232. Display::url(
  233. Display::returnFontAwesomeIcon('share', 2),
  234. $newMessageLink.'?forward_id='.$messageId,
  235. ['title' => get_lang('Forward message')]
  236. );
  237. }
  238. if (in_array('delete', $actions)) {
  239. $message[3] .= '&nbsp;&nbsp;<a title="'.addslashes(
  240. get_lang('Delete message')
  241. ).'" onclick="javascript:if(!confirm('."'".addslashes(
  242. api_htmlentities(get_lang('ConfirmDelete message'))
  243. )."'".')) return false;" href="'.$url.'?action=deleteone&id='.$messageId.'">'.
  244. Display::returnFontAwesomeIcon('trash', 2).'</a>';
  245. }
  246. foreach ($message as $key => $value) {
  247. $message[$key] = api_xml_http_response_encode($value);
  248. }
  249. $messageList[] = $message;
  250. }
  251. return $messageList;
  252. }
  253. /**
  254. * @param array $aboutUserInfo
  255. * @param array $fromUserInfo
  256. * @param string $subject
  257. * @param string $content
  258. *
  259. * @return bool
  260. */
  261. public static function sendMessageAboutUser(
  262. $aboutUserInfo,
  263. $fromUserInfo,
  264. $subject,
  265. $content
  266. ) {
  267. if (empty($aboutUserInfo) || empty($fromUserInfo)) {
  268. return false;
  269. }
  270. if (empty($fromUserInfo['id']) || empty($aboutUserInfo['id'])) {
  271. return false;
  272. }
  273. $table = Database::get_main_table(TABLE_MESSAGE);
  274. $now = api_get_utc_datetime();
  275. $params = [
  276. 'user_sender_id' => $fromUserInfo['id'],
  277. 'user_receiver_id' => $aboutUserInfo['id'],
  278. 'msg_status' => MESSAGE_STATUS_CONVERSATION,
  279. 'send_date' => $now,
  280. 'title' => $subject,
  281. 'content' => $content,
  282. 'group_id' => 0,
  283. 'parent_id' => 0,
  284. 'update_date' => $now,
  285. ];
  286. $id = Database::insert($table, $params);
  287. if ($id) {
  288. return true;
  289. }
  290. return false;
  291. }
  292. /**
  293. * @param array $aboutUserInfo
  294. *
  295. * @return array
  296. */
  297. public static function getMessagesAboutUser($aboutUserInfo)
  298. {
  299. if (!empty($aboutUserInfo)) {
  300. $table = Database::get_main_table(TABLE_MESSAGE);
  301. $sql = 'SELECT id FROM '.$table.'
  302. WHERE
  303. user_receiver_id = '.$aboutUserInfo['id'].' AND
  304. msg_status = '.MESSAGE_STATUS_CONVERSATION.'
  305. ';
  306. $result = Database::query($sql);
  307. $messages = [];
  308. $repo = Database::getManager()->getRepository('ChamiloCoreBundle:Message');
  309. while ($row = Database::fetch_array($result)) {
  310. $message = $repo->find($row['id']);
  311. $messages[] = $message;
  312. }
  313. return $messages;
  314. }
  315. return [];
  316. }
  317. /**
  318. * @param array $userInfo
  319. *
  320. * @return string
  321. */
  322. public static function getMessagesAboutUserToString($userInfo)
  323. {
  324. $messages = self::getMessagesAboutUser($userInfo);
  325. $html = '';
  326. if (!empty($messages)) {
  327. /** @var Message $message */
  328. foreach ($messages as $message) {
  329. $tag = 'message_'.$message->getId();
  330. $tagAccordion = 'accordion_'.$message->getId();
  331. $tagCollapse = 'collapse_'.$message->getId();
  332. $date = Display::dateToStringAgoAndLongDate(
  333. $message->getSendDate()
  334. );
  335. $localTime = api_get_local_time(
  336. $message->getSendDate(),
  337. null,
  338. null,
  339. false,
  340. false
  341. );
  342. $senderId = $message->getUserSenderId();
  343. $senderInfo = api_get_user_info($senderId);
  344. $html .= Display::panelCollapse(
  345. $localTime.' '.$senderInfo['complete_name'].' '.$message->getTitle(),
  346. $message->getContent().'<br />'.$date.'<br />'.get_lang(
  347. 'Author'
  348. ).': '.$senderInfo['complete_name_with_message_link'],
  349. $tag,
  350. null,
  351. $tagAccordion,
  352. $tagCollapse,
  353. false
  354. );
  355. }
  356. }
  357. return $html;
  358. }
  359. /**
  360. * @param int $senderId
  361. * @param int $receiverId
  362. * @param string $subject
  363. * @param string $message
  364. *
  365. * @return bool
  366. */
  367. public static function messageWasAlreadySent($senderId, $receiverId, $subject, $message)
  368. {
  369. $table = Database::get_main_table(TABLE_MESSAGE);
  370. $senderId = (int) $senderId;
  371. $receiverId = (int) $receiverId;
  372. $subject = Database::escape_string($subject);
  373. $message = Database::escape_string($message);
  374. $sql = "SELECT * FROM $table
  375. WHERE
  376. user_sender_id = $senderId AND
  377. user_receiver_id = $receiverId AND
  378. title = '$subject' AND
  379. content = '$message' AND
  380. (msg_status = ".MESSAGE_STATUS_UNREAD." OR msg_status = ".MESSAGE_STATUS_NEW.")
  381. ";
  382. $result = Database::query($sql);
  383. return Database::num_rows($result) > 0;
  384. }
  385. /**
  386. * Sends a message to a user/group.
  387. *
  388. * @param int $receiver_user_id
  389. * @param string $subject
  390. * @param string $content
  391. * @param array $attachments files array($_FILES) (optional)
  392. * @param array $fileCommentList about attachment files (optional)
  393. * @param int $group_id (optional)
  394. * @param int $parent_id (optional)
  395. * @param int $editMessageId id for updating the message (optional)
  396. * @param int $topic_id (optional) the default value is the current user_id
  397. * @param int $sender_id
  398. * @param bool $directMessage
  399. * @param int $forwardId
  400. * @param array $smsParameters
  401. * @param bool $checkCurrentAudioId
  402. * @param bool $forceTitleWhenSendingEmail force the use of $title as subject instead of "You have a new message"
  403. *
  404. * @return bool
  405. */
  406. public static function send_message(
  407. $receiver_user_id,
  408. $subject,
  409. $content,
  410. array $attachments = [],
  411. array $fileCommentList = [],
  412. $group_id = 0,
  413. $parent_id = 0,
  414. $editMessageId = 0,
  415. $topic_id = 0,
  416. $sender_id = 0,
  417. $directMessage = false,
  418. $forwardId = 0,
  419. $smsParameters = [],
  420. $checkCurrentAudioId = false,
  421. $forceTitleWhenSendingEmail = false,
  422. $status = 0
  423. ) {
  424. $table = Database::get_main_table(TABLE_MESSAGE);
  425. $group_id = (int) $group_id;
  426. $receiver_user_id = (int) $receiver_user_id;
  427. $parent_id = (int) $parent_id;
  428. $editMessageId = (int) $editMessageId;
  429. $topic_id = (int) $topic_id;
  430. $status = empty($status) ? MESSAGE_STATUS_UNREAD : (int) $status;
  431. if (!empty($receiver_user_id)) {
  432. $receiverUserInfo = api_get_user_info($receiver_user_id);
  433. // Disabling messages for inactive users.
  434. if ($receiverUserInfo['active'] == 0) {
  435. return false;
  436. }
  437. }
  438. $user_sender_id = empty($sender_id) ? api_get_user_id() : (int) $sender_id;
  439. if (empty($user_sender_id)) {
  440. Display::addFlash(Display::return_message(get_lang('This user doesn\'t exist'), 'warning'));
  441. return false;
  442. }
  443. $totalFileSize = 0;
  444. $attachmentList = [];
  445. if (is_array($attachments)) {
  446. $counter = 0;
  447. foreach ($attachments as $attachment) {
  448. $attachment['comment'] = isset($fileCommentList[$counter]) ? $fileCommentList[$counter] : '';
  449. $fileSize = isset($attachment['size']) ? $attachment['size'] : 0;
  450. if (is_array($fileSize)) {
  451. foreach ($fileSize as $size) {
  452. $totalFileSize += $size;
  453. }
  454. } else {
  455. $totalFileSize += $fileSize;
  456. }
  457. $attachmentList[] = $attachment;
  458. $counter++;
  459. }
  460. }
  461. if ($checkCurrentAudioId) {
  462. // Add the audio file as an attachment
  463. $audioId = Session::read('current_audio_id');
  464. if (!empty($audioId)) {
  465. $file = api_get_uploaded_file('audio_message', api_get_user_id(), $audioId);
  466. if (!empty($file)) {
  467. $audioAttachment = [
  468. 'name' => basename($file),
  469. 'comment' => 'audio_message',
  470. 'size' => filesize($file),
  471. 'tmp_name' => $file,
  472. 'error' => 0,
  473. 'type' => DocumentManager::file_get_mime_type(basename($file)),
  474. ];
  475. // create attachment from audio message
  476. $attachmentList[] = $audioAttachment;
  477. }
  478. }
  479. }
  480. // Validating fields
  481. if (empty($subject) && empty($group_id)) {
  482. Display::addFlash(
  483. Display::return_message(
  484. get_lang('You should write a subject'),
  485. 'warning'
  486. )
  487. );
  488. return false;
  489. } elseif ($totalFileSize > intval(api_get_setting('message_max_upload_filesize'))) {
  490. $warning = sprintf(
  491. get_lang('Files size exceeds'),
  492. format_file_size(api_get_setting('message_max_upload_filesize'))
  493. );
  494. Display::addFlash(Display::return_message($warning, 'warning'));
  495. return false;
  496. }
  497. // Just in case we replace the and \n and \n\r while saving in the DB
  498. // $content = str_replace(array("\n", "\n\r"), '<br />', $content);
  499. $now = api_get_utc_datetime();
  500. if (!empty($receiver_user_id) || !empty($group_id)) {
  501. // message for user friend
  502. //@todo it's possible to edit a message? yes, only for groups
  503. if (!empty($editMessageId)) {
  504. $query = " UPDATE $table SET
  505. update_date = '".$now."',
  506. content = '".Database::escape_string($content)."'
  507. WHERE id = '$editMessageId' ";
  508. Database::query($query);
  509. $messageId = $editMessageId;
  510. } else {
  511. $params = [
  512. 'user_sender_id' => $user_sender_id,
  513. 'msg_status' => $status,
  514. 'send_date' => $now,
  515. 'title' => $subject,
  516. 'content' => $content,
  517. 'group_id' => $group_id,
  518. 'parent_id' => $parent_id,
  519. 'update_date' => $now,
  520. ];
  521. if (!empty($receiver_user_id)) {
  522. $params['user_receiver_id'] = $receiver_user_id;
  523. }
  524. $messageId = Database::insert($table, $params);
  525. }
  526. // Forward also message attachments
  527. if (!empty($forwardId)) {
  528. $attachments = self::getAttachmentList($forwardId);
  529. foreach ($attachments as $attachment) {
  530. if (!empty($attachment['file_source'])) {
  531. $file = [
  532. 'name' => $attachment['filename'],
  533. 'tmp_name' => $attachment['file_source'],
  534. 'size' => $attachment['size'],
  535. 'error' => 0,
  536. 'comment' => $attachment['comment'],
  537. ];
  538. // Inject this array so files can be added when sending and email with the mailer
  539. $attachmentList[] = $file;
  540. }
  541. }
  542. }
  543. // Save attachment file for inbox messages
  544. if (is_array($attachmentList)) {
  545. foreach ($attachmentList as $attachment) {
  546. if ($attachment['error'] == 0) {
  547. $comment = $attachment['comment'];
  548. self::saveMessageAttachmentFile(
  549. $attachment,
  550. $comment,
  551. $messageId,
  552. null,
  553. $receiver_user_id,
  554. $group_id
  555. );
  556. }
  557. }
  558. }
  559. // Save message in the outbox for user friend or group.
  560. if (empty($group_id) && $status == MESSAGE_STATUS_UNREAD) {
  561. $params = [
  562. 'user_sender_id' => $user_sender_id,
  563. 'user_receiver_id' => $receiver_user_id,
  564. 'msg_status' => MESSAGE_STATUS_OUTBOX,
  565. 'send_date' => $now,
  566. 'title' => $subject,
  567. 'content' => $content,
  568. 'group_id' => $group_id,
  569. 'parent_id' => $parent_id,
  570. 'update_date' => $now,
  571. ];
  572. $outbox_last_id = Database::insert($table, $params);
  573. // save attachment file for outbox messages
  574. if (is_array($attachmentList)) {
  575. foreach ($attachmentList as $attachment) {
  576. if ($attachment['error'] == 0) {
  577. $comment = $attachment['comment'];
  578. self::saveMessageAttachmentFile(
  579. $attachment,
  580. $comment,
  581. $outbox_last_id,
  582. $user_sender_id
  583. );
  584. }
  585. }
  586. }
  587. }
  588. // Load user settings.
  589. $notification = new Notification();
  590. $sender_info = api_get_user_info($user_sender_id);
  591. // add file attachment additional attributes
  592. $attachmentAddedByMail = [];
  593. foreach ($attachmentList as $attachment) {
  594. $attachmentAddedByMail[] = [
  595. 'path' => $attachment['tmp_name'],
  596. 'filename' => $attachment['name'],
  597. ];
  598. }
  599. if (empty($group_id)) {
  600. $type = Notification::NOTIFICATION_TYPE_MESSAGE;
  601. if ($directMessage) {
  602. $type = Notification::NOTIFICATION_TYPE_DIRECT_MESSAGE;
  603. }
  604. $notification->saveNotification(
  605. $messageId,
  606. $type,
  607. [$receiver_user_id],
  608. $subject,
  609. $content,
  610. $sender_info,
  611. $attachmentAddedByMail,
  612. $smsParameters,
  613. $forceTitleWhenSendingEmail
  614. );
  615. } else {
  616. $usergroup = new UserGroup();
  617. $group_info = $usergroup->get($group_id);
  618. $group_info['topic_id'] = $topic_id;
  619. $group_info['msg_id'] = $messageId;
  620. $user_list = $usergroup->get_users_by_group(
  621. $group_id,
  622. false,
  623. [],
  624. 0,
  625. 1000
  626. );
  627. // Adding more sense to the message group
  628. $subject = sprintf(get_lang('There is a new message in group %s'), $group_info['name']);
  629. $new_user_list = [];
  630. foreach ($user_list as $user_data) {
  631. $new_user_list[] = $user_data['id'];
  632. }
  633. $group_info = [
  634. 'group_info' => $group_info,
  635. 'user_info' => $sender_info,
  636. ];
  637. $notification->saveNotification(
  638. $messageId,
  639. Notification::NOTIFICATION_TYPE_GROUP,
  640. $new_user_list,
  641. $subject,
  642. $content,
  643. $group_info,
  644. $attachmentAddedByMail,
  645. $smsParameters
  646. );
  647. }
  648. return $messageId;
  649. }
  650. return false;
  651. }
  652. /**
  653. * @param int $receiver_user_id
  654. * @param int $subject
  655. * @param string $message
  656. * @param int $sender_id
  657. * @param bool $sendCopyToDrhUsers send copy to related DRH users
  658. * @param bool $directMessage
  659. * @param array $smsParameters
  660. * @param bool $uploadFiles Do not upload files using the MessageManager class
  661. * @param array $attachmentList
  662. *
  663. * @return bool
  664. */
  665. public static function send_message_simple(
  666. $receiver_user_id,
  667. $subject,
  668. $message,
  669. $sender_id = 0,
  670. $sendCopyToDrhUsers = false,
  671. $directMessage = false,
  672. $smsParameters = [],
  673. $uploadFiles = true,
  674. $attachmentList = []
  675. ) {
  676. $files = $_FILES ? $_FILES : [];
  677. if ($uploadFiles === false) {
  678. $files = [];
  679. }
  680. // $attachmentList must have: tmp_name, name, size keys
  681. if (!empty($attachmentList)) {
  682. $files = $attachmentList;
  683. }
  684. $result = self::send_message(
  685. $receiver_user_id,
  686. $subject,
  687. $message,
  688. $files,
  689. [],
  690. null,
  691. null,
  692. null,
  693. null,
  694. $sender_id,
  695. $directMessage,
  696. 0,
  697. $smsParameters
  698. );
  699. if ($sendCopyToDrhUsers) {
  700. $userInfo = api_get_user_info($receiver_user_id);
  701. $drhList = UserManager::getDrhListFromUser($receiver_user_id);
  702. if (!empty($drhList)) {
  703. foreach ($drhList as $drhInfo) {
  704. $message = sprintf(
  705. get_lang('Copy of message sent to %s'),
  706. $userInfo['complete_name']
  707. ).' <br />'.$message;
  708. self::send_message_simple(
  709. $drhInfo['user_id'],
  710. $subject,
  711. $message,
  712. $sender_id,
  713. false,
  714. $directMessage
  715. );
  716. }
  717. }
  718. }
  719. return $result;
  720. }
  721. /**
  722. * Update parent ids for other receiver user from current message in groups.
  723. *
  724. * @author Christian Fasanando Flores
  725. *
  726. * @param int $parent_id
  727. * @param int $receiver_user_id
  728. * @param int $messageId
  729. */
  730. public static function update_parent_ids_from_reply(
  731. $parent_id,
  732. $receiver_user_id,
  733. $messageId
  734. ) {
  735. $table = Database::get_main_table(TABLE_MESSAGE);
  736. $parent_id = intval($parent_id);
  737. $receiver_user_id = intval($receiver_user_id);
  738. $messageId = intval($messageId);
  739. // first get data from message id (parent)
  740. $sql = "SELECT * FROM $table WHERE id = '$parent_id'";
  741. $rs_message = Database::query($sql);
  742. $row_message = Database::fetch_array($rs_message);
  743. // get message id from data found early for other receiver user
  744. $sql = "SELECT id FROM $table
  745. WHERE
  746. user_sender_id ='{$row_message['user_sender_id']}' AND
  747. title='{$row_message['title']}' AND
  748. content='{$row_message['content']}' AND
  749. group_id='{$row_message['group_id']}' AND
  750. user_receiver_id='$receiver_user_id'";
  751. $result = Database::query($sql);
  752. $row = Database::fetch_array($result);
  753. // update parent_id for other user receiver
  754. $sql = "UPDATE $table SET parent_id = ".$row['id']."
  755. WHERE id = $messageId";
  756. Database::query($sql);
  757. }
  758. /**
  759. * @param int $user_receiver_id
  760. * @param int $id
  761. *
  762. * @return bool
  763. */
  764. public static function delete_message_by_user_receiver($user_receiver_id, $id)
  765. {
  766. $table = Database::get_main_table(TABLE_MESSAGE);
  767. $id = (int) $id;
  768. $user_receiver_id = (int) $user_receiver_id;
  769. if (empty($id) || empty($user_receiver_id)) {
  770. return false;
  771. }
  772. $sql = "SELECT * FROM $table
  773. WHERE
  774. id = $id AND
  775. user_receiver_id = $user_receiver_id AND
  776. msg_status <> ".MESSAGE_STATUS_OUTBOX;
  777. $rs = Database::query($sql);
  778. if (Database::num_rows($rs) > 0) {
  779. // Delete attachment file.
  780. self::delete_message_attachment_file($id, $user_receiver_id);
  781. // Soft delete message.
  782. $query = "UPDATE $table
  783. SET msg_status = ".MESSAGE_STATUS_DELETED."
  784. WHERE
  785. id = $id AND
  786. user_receiver_id = $user_receiver_id ";
  787. Database::query($query);
  788. return true;
  789. }
  790. return false;
  791. }
  792. /**
  793. * Set status deleted.
  794. *
  795. * @author Isaac FLores Paz <isaac.flores@dokeos.com>
  796. *
  797. * @param int
  798. * @param int
  799. *
  800. * @return bool
  801. */
  802. public static function delete_message_by_user_sender($user_sender_id, $id)
  803. {
  804. $user_sender_id = (int) $user_sender_id;
  805. $id = (int) $id;
  806. if (empty($id) || empty($user_sender_id)) {
  807. return false;
  808. }
  809. $table = Database::get_main_table(TABLE_MESSAGE);
  810. $sql = "SELECT * FROM $table WHERE id = $id AND user_sender_id= $user_sender_id";
  811. $rs = Database::query($sql);
  812. if (Database::num_rows($rs) > 0) {
  813. // delete attachment file
  814. self::delete_message_attachment_file($id, $user_sender_id);
  815. // delete message
  816. $sql = "UPDATE $table
  817. SET msg_status = '".MESSAGE_STATUS_DELETED."'
  818. WHERE user_sender_id= $user_sender_id AND id= $id";
  819. Database::query($sql);
  820. return true;
  821. }
  822. return false;
  823. }
  824. /**
  825. * Saves a message attachment files.
  826. *
  827. * @param array $file_attach $_FILES['name']
  828. * @param string a comment about the uploaded file
  829. * @param int message id
  830. * @param int receiver user id (optional)
  831. * @param int sender user id (optional)
  832. * @param int group id (optional)
  833. */
  834. public static function saveMessageAttachmentFile(
  835. $file_attach,
  836. $file_comment,
  837. $message_id,
  838. $receiver_user_id = 0,
  839. $sender_user_id = 0,
  840. $group_id = 0
  841. ) {
  842. $table = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  843. // Try to add an extension to the file if it hasn't one
  844. $type = isset($file_attach['type']) ? $file_attach['type'] : '';
  845. if (empty($type)) {
  846. $type = DocumentManager::file_get_mime_type($file_attach['name']);
  847. }
  848. $new_file_name = add_ext_on_mime(stripslashes($file_attach['name']), $type);
  849. // user's file name
  850. $file_name = $file_attach['name'];
  851. if (!filter_extension($new_file_name)) {
  852. Display::addFlash(Display::return_message(get_lang('File upload failed: this file extension or file type is prohibited'), 'error'));
  853. } else {
  854. $new_file_name = uniqid('');
  855. if (!empty($receiver_user_id)) {
  856. $message_user_id = $receiver_user_id;
  857. } else {
  858. $message_user_id = $sender_user_id;
  859. }
  860. // User-reserved directory where photos have to be placed.*
  861. $userGroup = new UserGroup();
  862. if (!empty($group_id)) {
  863. $path_user_info = $userGroup->get_group_picture_path_by_id(
  864. $group_id,
  865. 'system',
  866. true
  867. );
  868. } else {
  869. $path_user_info['dir'] = UserManager::getUserPathById($message_user_id, 'system');
  870. }
  871. $path_message_attach = $path_user_info['dir'].'message_attachments/';
  872. // If this directory does not exist - we create it.
  873. if (!file_exists($path_message_attach)) {
  874. @mkdir($path_message_attach, api_get_permissions_for_new_directories(), true);
  875. }
  876. $new_path = $path_message_attach.$new_file_name;
  877. $fileCopied = false;
  878. if (isset($file_attach['tmp_name']) && !empty($file_attach['tmp_name'])) {
  879. if (is_uploaded_file($file_attach['tmp_name'])) {
  880. @copy($file_attach['tmp_name'], $new_path);
  881. $fileCopied = true;
  882. } else {
  883. // 'tmp_name' can be set by the ticket or when forwarding a message
  884. if (file_exists($file_attach['tmp_name'])) {
  885. @copy($file_attach['tmp_name'], $new_path);
  886. $fileCopied = true;
  887. }
  888. }
  889. }
  890. if ($fileCopied) {
  891. // Storing the attachments if any
  892. $params = [
  893. 'filename' => $file_name,
  894. 'comment' => $file_comment,
  895. 'path' => $new_file_name,
  896. 'message_id' => $message_id,
  897. 'size' => $file_attach['size'],
  898. ];
  899. return Database::insert($table, $params);
  900. }
  901. }
  902. return false;
  903. }
  904. /**
  905. * Delete message attachment files (logically updating the row with a suffix _DELETE_id).
  906. *
  907. * @param int message id
  908. * @param int message user id (receiver user id or sender user id)
  909. * @param int group id (optional)
  910. */
  911. public static function delete_message_attachment_file(
  912. $message_id,
  913. $message_uid,
  914. $group_id = 0
  915. ) {
  916. $message_id = (int) $message_id;
  917. $message_uid = (int) $message_uid;
  918. $table_message_attach = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  919. $sql = "SELECT * FROM $table_message_attach
  920. WHERE message_id = '$message_id'";
  921. $rs = Database::query($sql);
  922. while ($row = Database::fetch_array($rs)) {
  923. $path = $row['path'];
  924. $attach_id = (int) $row['id'];
  925. $new_path = $path.'_DELETED_'.$attach_id;
  926. if (!empty($group_id)) {
  927. $userGroup = new UserGroup();
  928. $path_user_info = $userGroup->get_group_picture_path_by_id(
  929. $group_id,
  930. 'system',
  931. true
  932. );
  933. } else {
  934. $path_user_info['dir'] = UserManager::getUserPathById(
  935. $message_uid,
  936. 'system'
  937. );
  938. }
  939. $path_message_attach = $path_user_info['dir'].'message_attachments/';
  940. if (is_file($path_message_attach.$path)) {
  941. if (rename($path_message_attach.$path, $path_message_attach.$new_path)) {
  942. $sql = "UPDATE $table_message_attach
  943. SET path = '$new_path'
  944. WHERE id = $attach_id ";
  945. Database::query($sql);
  946. }
  947. }
  948. }
  949. }
  950. /**
  951. * @param int $user_id
  952. * @param int $message_id
  953. * @param int $type
  954. *
  955. * @return bool
  956. */
  957. public static function update_message_status($user_id, $message_id, $type)
  958. {
  959. $user_id = (int) $user_id;
  960. $message_id = (int) $message_id;
  961. $type = (int) $type;
  962. if (empty($user_id) || empty($message_id)) {
  963. return false;
  964. }
  965. $table_message = Database::get_main_table(TABLE_MESSAGE);
  966. $sql = "UPDATE $table_message SET
  967. msg_status = '$type'
  968. WHERE
  969. user_receiver_id = ".$user_id." AND
  970. id = '".$message_id."'";
  971. Database::query($sql);
  972. }
  973. /**
  974. * get messages by group id.
  975. *
  976. * @param int $group_id group id
  977. *
  978. * @return array
  979. */
  980. public static function get_messages_by_group($group_id)
  981. {
  982. $group_id = (int) $group_id;
  983. if (empty($group_id)) {
  984. return false;
  985. }
  986. $table = Database::get_main_table(TABLE_MESSAGE);
  987. $sql = "SELECT * FROM $table
  988. WHERE
  989. group_id= $group_id AND
  990. msg_status NOT IN ('".MESSAGE_STATUS_OUTBOX."', '".MESSAGE_STATUS_DELETED."')
  991. ORDER BY id";
  992. $rs = Database::query($sql);
  993. $data = [];
  994. if (Database::num_rows($rs) > 0) {
  995. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  996. $data[] = $row;
  997. }
  998. }
  999. return $data;
  1000. }
  1001. /**
  1002. * get messages by group id.
  1003. *
  1004. * @param int $group_id
  1005. * @param int $message_id
  1006. *
  1007. * @return array
  1008. */
  1009. public static function get_messages_by_group_by_message($group_id, $message_id)
  1010. {
  1011. $group_id = (int) $group_id;
  1012. if (empty($group_id)) {
  1013. return false;
  1014. }
  1015. $table = Database::get_main_table(TABLE_MESSAGE);
  1016. $sql = "SELECT * FROM $table
  1017. WHERE
  1018. group_id = $group_id AND
  1019. msg_status NOT IN ('".MESSAGE_STATUS_OUTBOX."', '".MESSAGE_STATUS_DELETED."')
  1020. ORDER BY id ";
  1021. $rs = Database::query($sql);
  1022. $data = [];
  1023. $parents = [];
  1024. if (Database::num_rows($rs) > 0) {
  1025. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  1026. if ($message_id == $row['parent_id'] || in_array($row['parent_id'], $parents)) {
  1027. $parents[] = $row['id'];
  1028. $data[] = $row;
  1029. }
  1030. }
  1031. }
  1032. return $data;
  1033. }
  1034. /**
  1035. * Get messages by parent id optionally with limit.
  1036. *
  1037. * @param int parent id
  1038. * @param int group id (optional)
  1039. * @param int offset (optional)
  1040. * @param int limit (optional)
  1041. *
  1042. * @return array
  1043. */
  1044. public static function getMessagesByParent($parentId, $groupId = 0, $offset = 0, $limit = 0)
  1045. {
  1046. $table = Database::get_main_table(TABLE_MESSAGE);
  1047. $parentId = (int) $parentId;
  1048. if (empty($parentId)) {
  1049. return [];
  1050. }
  1051. $condition_group_id = '';
  1052. if (!empty($groupId)) {
  1053. $groupId = (int) $groupId;
  1054. $condition_group_id = " AND group_id = '$groupId' ";
  1055. }
  1056. $condition_limit = '';
  1057. if ($offset && $limit) {
  1058. $offset = (int) $offset;
  1059. $limit = (int) $limit;
  1060. $offset = ($offset - 1) * $limit;
  1061. $condition_limit = " LIMIT $offset,$limit ";
  1062. }
  1063. $sql = "SELECT * FROM $table
  1064. WHERE
  1065. parent_id='$parentId' AND
  1066. msg_status NOT IN (".MESSAGE_STATUS_OUTBOX.", ".MESSAGE_STATUS_WALL_DELETE.")
  1067. $condition_group_id
  1068. ORDER BY send_date DESC $condition_limit ";
  1069. $rs = Database::query($sql);
  1070. $data = [];
  1071. if (Database::num_rows($rs) > 0) {
  1072. while ($row = Database::fetch_array($rs)) {
  1073. $data[$row['id']] = $row;
  1074. }
  1075. }
  1076. return $data;
  1077. }
  1078. /**
  1079. * Gets information about messages sent.
  1080. *
  1081. * @param int
  1082. * @param int
  1083. * @param string
  1084. * @param string
  1085. *
  1086. * @return array
  1087. */
  1088. public static function get_message_data_sent(
  1089. $from,
  1090. $numberOfItems,
  1091. $column,
  1092. $direction,
  1093. $extraParams = []
  1094. ) {
  1095. $from = (int) $from;
  1096. $numberOfItems = (int) $numberOfItems;
  1097. if (!isset($direction)) {
  1098. $column = 2;
  1099. $direction = 'DESC';
  1100. } else {
  1101. $column = (int) $column;
  1102. if (!in_array($direction, ['ASC', 'DESC'])) {
  1103. $direction = 'ASC';
  1104. }
  1105. }
  1106. if (!in_array($column, [0, 1, 2])) {
  1107. $column = 2;
  1108. }
  1109. $table = Database::get_main_table(TABLE_MESSAGE);
  1110. $request = api_is_xml_http_request();
  1111. $keyword = isset($extraParams['keyword']) && !empty($extraParams['keyword']) ? $extraParams['keyword'] : '';
  1112. $keywordCondition = '';
  1113. if (!empty($keyword)) {
  1114. $keyword = Database::escape_string($keyword);
  1115. $keywordCondition = " AND (title like '%$keyword%' OR content LIKE '%$keyword%') ";
  1116. }
  1117. $sql = "SELECT
  1118. id as col0,
  1119. title as col1,
  1120. send_date as col2,
  1121. user_receiver_id,
  1122. msg_status,
  1123. user_sender_id
  1124. FROM $table
  1125. WHERE
  1126. user_sender_id = ".api_get_user_id()." AND
  1127. msg_status = ".MESSAGE_STATUS_OUTBOX."
  1128. $keywordCondition
  1129. ORDER BY col$column $direction
  1130. LIMIT $from, $numberOfItems";
  1131. $result = Database::query($sql);
  1132. $message_list = [];
  1133. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1134. $messageId = $row['col0'];
  1135. $title = $row['col1'];
  1136. $sendDate = $row['col2'];
  1137. $senderId = $row['user_sender_id'];
  1138. if ($request === true) {
  1139. $message[0] = '<input type="checkbox" value='.$messageId.' name="out[]">';
  1140. } else {
  1141. $message[0] = $messageId;
  1142. }
  1143. $class = 'class = "read"';
  1144. $title = Security::remove_XSS($title);
  1145. $userInfo = api_get_user_info($senderId);
  1146. if ($request === true) {
  1147. $message[1] = '<a onclick="show_sent_message('.$messageId.')" href="javascript:void(0)">'.
  1148. $userInfo['complete_name_with_username'].'</a>';
  1149. $message[2] = '<a onclick="show_sent_message('.$messageId.')" href="javascript:void(0)">'.str_replace(
  1150. "\\",
  1151. "",
  1152. $title
  1153. ).'</a>';
  1154. //date stays the same
  1155. $message[3] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
  1156. $message[4] = '&nbsp;&nbsp;<a title="'.addslashes(
  1157. get_lang('Delete message')
  1158. ).'" onclick="delete_one_message_outbox('.$messageId.')" href="javascript:void(0)" >'.
  1159. Display::returnFontAwesomeIcon('trash', 2).'</a>';
  1160. } else {
  1161. $message[1] = '<a '.$class.' onclick="show_sent_message('.$messageId.')" href="../messages/view_message.php?id_send='.$messageId.'">'.$title.'</a><br />'.$userInfo['complete_name_with_username'];
  1162. $message[2] = api_convert_and_format_date($sendDate, DATE_TIME_FORMAT_LONG);
  1163. $message[3] = '<a title="'.addslashes(
  1164. get_lang('Delete message')
  1165. ).'" href="outbox.php?action=deleteone&id='.$messageId.'" onclick="javascript:if(!confirm('."'".addslashes(
  1166. api_htmlentities(get_lang('ConfirmDelete message'))
  1167. )."'".')) return false;" >'.
  1168. Display::returnFontAwesomeIcon('trash', 2).'</a>';
  1169. }
  1170. $message_list[] = $message;
  1171. }
  1172. return $message_list;
  1173. }
  1174. /**
  1175. * display message box in the inbox.
  1176. *
  1177. * @param int $messageId
  1178. * @param int $type
  1179. *
  1180. * @todo replace numbers with letters in the $row array pff...
  1181. *
  1182. * @return string html with the message content
  1183. */
  1184. public static function showMessageBox($messageId, $type)
  1185. {
  1186. $messageId = (int) $messageId;
  1187. if (empty($messageId) || empty($type)) {
  1188. return '';
  1189. }
  1190. $currentUserId = api_get_user_id();
  1191. $table = Database::get_main_table(TABLE_MESSAGE);
  1192. if (empty($type)) {
  1193. return '';
  1194. }
  1195. switch ($type) {
  1196. case self::MESSAGE_TYPE_OUTBOX:
  1197. $status = MESSAGE_STATUS_OUTBOX;
  1198. $userCondition = " user_sender_id = $currentUserId AND ";
  1199. break;
  1200. case self::MESSAGE_TYPE_INBOX:
  1201. $status = MESSAGE_STATUS_NEW;
  1202. $userCondition = " user_receiver_id = $currentUserId AND ";
  1203. $query = "UPDATE $table SET
  1204. msg_status = '".MESSAGE_STATUS_NEW."'
  1205. WHERE id = $messageId ";
  1206. Database::query($query);
  1207. break;
  1208. case self::MESSAGE_TYPE_PROMOTED:
  1209. $status = MESSAGE_STATUS_PROMOTED;
  1210. $userCondition = " user_receiver_id = $currentUserId AND ";
  1211. break;
  1212. }
  1213. if (empty($userCondition)) {
  1214. return '';
  1215. }
  1216. $query = "SELECT * FROM $table
  1217. WHERE
  1218. id = $messageId AND
  1219. $userCondition
  1220. msg_status = $status";
  1221. $result = Database::query($query);
  1222. $row = Database::fetch_array($result, 'ASSOC');
  1223. if (empty($row)) {
  1224. return '';
  1225. }
  1226. $user_sender_id = $row['user_sender_id'];
  1227. // get file attachments by message id
  1228. $files_attachments = self::getAttachmentLinkList($messageId, $type);
  1229. $row['content'] = str_replace('</br>', '<br />', $row['content']);
  1230. $title = Security::remove_XSS($row['title'], STUDENT, true);
  1231. $content = Security::remove_XSS($row['content'], STUDENT, true);
  1232. $name = get_lang('Unknown user');
  1233. $fromUser = api_get_user_info($user_sender_id);
  1234. $userImage = '';
  1235. if (!empty($user_sender_id) && !empty($fromUser)) {
  1236. $name = $fromUser['complete_name_with_username'];
  1237. $userImage = Display::img(
  1238. $fromUser['avatar_small'],
  1239. $name,
  1240. ['title' => $name, 'class' => 'img-responsive img-circle', 'style' => 'max-width:35px'],
  1241. false
  1242. );
  1243. }
  1244. $message_content = Display::page_subheader(str_replace("\\", '', $title));
  1245. $receiverUserInfo = [];
  1246. if (!empty($row['user_receiver_id'])) {
  1247. $receiverUserInfo = api_get_user_info($row['user_receiver_id']);
  1248. }
  1249. $message_content .= '<tr>';
  1250. if (api_get_setting('allow_social_tool') === 'true') {
  1251. $message_content .= '<div class="row">';
  1252. $message_content .= '<div class="col-md-12">';
  1253. $message_content .= '<ul class="list-message">';
  1254. if (!empty($user_sender_id)) {
  1255. $message_content .= '<li>'.$userImage.'</li>';
  1256. $message_content .= '<li>';
  1257. $message_content .= Display::url(
  1258. $name,
  1259. api_get_path(WEB_PATH).'main/social/profile.php?u='.$user_sender_id
  1260. );
  1261. } else {
  1262. $message_content .= '<li>'.$name;
  1263. }
  1264. switch ($type) {
  1265. case self::MESSAGE_TYPE_INBOX:
  1266. //$message_content .= api_strtolower(get_lang('To')).'&nbsp;<b>-</b></li>';
  1267. $message_content .= '&nbsp;'.api_strtolower(get_lang('To')).'&nbsp;'.get_lang('Me');
  1268. break;
  1269. case self::MESSAGE_TYPE_OUTBOX:
  1270. if (!empty($receiverUserInfo)) {
  1271. $message_content .= '&nbsp;'.api_strtolower(
  1272. get_lang('To')
  1273. ).'&nbsp;<b>'.$receiverUserInfo['complete_name_with_username'].'</b></li>';
  1274. }
  1275. break;
  1276. case self::MESSAGE_TYPE_PROMOTED:
  1277. break;
  1278. }
  1279. $message_content .= '&nbsp;<li>'.Display::dateToStringAgoAndLongDate($row['send_date']).'</li>';
  1280. $message_content .= '</ul>';
  1281. $message_content .= '</div>';
  1282. $message_content .= '</div>';
  1283. } else {
  1284. switch ($type) {
  1285. case self::MESSAGE_TYPE_INBOX:
  1286. $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.
  1287. get_lang('Me').'</b>';
  1288. break;
  1289. case self::MESSAGE_TYPE_OUTBOX:
  1290. $message_content .= get_lang('From').':&nbsp;'.$name.'</b> '.api_strtolower(get_lang('To')).' <b>'.
  1291. $receiverUserInfo['complete_name_with_username'].'</b>';
  1292. break;
  1293. }
  1294. }
  1295. $message_content .= '
  1296. <hr style="color:#ddd" />
  1297. <table width="100%">
  1298. <tr>
  1299. <td valign=top class="view-message-content">'.str_replace("\\", "", $content).'</td>
  1300. </tr>
  1301. </table>
  1302. <div id="message-attach">'.(!empty($files_attachments) ? implode('<br />', $files_attachments) : '').'</div>
  1303. <div style="padding: 15px 0px 5px 0px">';
  1304. $social_link = '';
  1305. if (isset($_GET['f']) && $_GET['f'] == 'social') {
  1306. $social_link = 'f=social';
  1307. }
  1308. switch ($type) {
  1309. case self::MESSAGE_TYPE_OUTBOX:
  1310. $message_content .= '<a href="outbox.php?'.$social_link.'">'.
  1311. Display::return_icon('back.png', get_lang('Return to outbox')).'</a> &nbsp';
  1312. $message_content .= '<a href="outbox.php?action=deleteone&id='.$messageId.'&'.$social_link.'" >'.
  1313. Display::return_icon('delete.png', get_lang('Delete message')).'</a>&nbsp';
  1314. break;
  1315. case self::MESSAGE_TYPE_INBOX:
  1316. $message_content .= '<a href="inbox.php?'.$social_link.'">'.
  1317. Display::return_icon('back.png', get_lang('Return to inbox')).'</a> &nbsp';
  1318. $message_content .= '<a href="new_message.php?re_id='.$messageId.'&'.$social_link.'">'.
  1319. Display::return_icon('message_reply.png', get_lang('Reply to this message')).'</a> &nbsp';
  1320. $message_content .= '<a href="inbox.php?action=deleteone&id='.$messageId.'&'.$social_link.'" >'.
  1321. Display::return_icon('delete.png', get_lang('Delete message')).'</a>&nbsp';
  1322. break;
  1323. }
  1324. $message_content .= '</div></td>
  1325. <td width=10></td>
  1326. </tr>
  1327. </table>';
  1328. return $message_content;
  1329. }
  1330. /**
  1331. * get user id by user email.
  1332. *
  1333. * @param string $user_email
  1334. *
  1335. * @return int user id
  1336. */
  1337. public static function get_user_id_by_email($user_email)
  1338. {
  1339. $table = Database::get_main_table(TABLE_MAIN_USER);
  1340. $sql = 'SELECT user_id
  1341. FROM '.$table.'
  1342. WHERE email="'.Database::escape_string($user_email).'";';
  1343. $rs = Database::query($sql);
  1344. $row = Database::fetch_array($rs, 'ASSOC');
  1345. if (isset($row['user_id'])) {
  1346. return $row['user_id'];
  1347. }
  1348. return null;
  1349. }
  1350. /**
  1351. * Displays messages of a group with nested view.
  1352. *
  1353. * @param int $groupId
  1354. *
  1355. * @return string
  1356. */
  1357. public static function display_messages_for_group($groupId)
  1358. {
  1359. global $my_group_role;
  1360. $rows = self::get_messages_by_group($groupId);
  1361. $topics_per_page = 10;
  1362. $html_messages = '';
  1363. $query_vars = ['id' => $groupId, 'topics_page_nr' => 0];
  1364. if (is_array($rows) && count($rows) > 0) {
  1365. // prepare array for topics with its items
  1366. $topics = [];
  1367. $x = 0;
  1368. foreach ($rows as $index => $value) {
  1369. if (empty($value['parent_id'])) {
  1370. $topics[$value['id']] = $value;
  1371. }
  1372. }
  1373. $new_topics = [];
  1374. foreach ($topics as $id => $value) {
  1375. $rows = null;
  1376. $rows = self::get_messages_by_group_by_message($groupId, $value['id']);
  1377. if (!empty($rows)) {
  1378. $count = count(self::calculate_children($rows, $value['id']));
  1379. } else {
  1380. $count = 0;
  1381. }
  1382. $value['count'] = $count;
  1383. $new_topics[$id] = $value;
  1384. }
  1385. $array_html = [];
  1386. foreach ($new_topics as $index => $topic) {
  1387. $html = '';
  1388. // topics
  1389. $user_sender_info = api_get_user_info($topic['user_sender_id']);
  1390. $name = $user_sender_info['complete_name'];
  1391. $html .= '<div class="groups-messages">';
  1392. $html .= '<div class="row">';
  1393. $items = $topic['count'];
  1394. $reply_label = ($items == 1) ? get_lang('Reply') : get_lang('Replies');
  1395. $label = '<i class="fa fa-envelope"></i> '.$items.' '.$reply_label;
  1396. $topic['title'] = trim($topic['title']);
  1397. if (empty($topic['title'])) {
  1398. $topic['title'] = get_lang('Untitled');
  1399. }
  1400. $html .= '<div class="col-xs-8 col-md-10">';
  1401. $html .= Display::tag(
  1402. 'h4',
  1403. Display::url(
  1404. Security::remove_XSS($topic['title'], STUDENT, true),
  1405. api_get_path(WEB_CODE_PATH).'social/group_topics.php?id='.$groupId.'&topic_id='.$topic['id']
  1406. ),
  1407. ['class' => 'title']
  1408. );
  1409. $actions = '';
  1410. if ($my_group_role == GROUP_USER_PERMISSION_ADMIN ||
  1411. $my_group_role == GROUP_USER_PERMISSION_MODERATOR
  1412. ) {
  1413. $actions = '<br />'.Display::url(
  1414. get_lang('Delete'),
  1415. api_get_path(
  1416. WEB_CODE_PATH
  1417. ).'social/group_topics.php?action=delete&id='.$groupId.'&topic_id='.$topic['id'],
  1418. ['class' => 'btn btn-default']
  1419. );
  1420. }
  1421. $date = '';
  1422. if ($topic['send_date'] != $topic['update_date']) {
  1423. if (!empty($topic['update_date'])) {
  1424. $date .= '<i class="fa fa-calendar"></i> '.get_lang(
  1425. 'LastUpdate'
  1426. ).' '.Display::dateToStringAgoAndLongDate($topic['update_date']);
  1427. }
  1428. } else {
  1429. $date .= '<i class="fa fa-calendar"></i> '.get_lang(
  1430. 'Created'
  1431. ).' '.Display::dateToStringAgoAndLongDate($topic['send_date']);
  1432. }
  1433. $html .= '<div class="date">'.$label.' - '.$date.$actions.'</div>';
  1434. $html .= '</div>';
  1435. $image = $user_sender_info['avatar'];
  1436. $user_info = '<div class="author"><img class="img-responsive img-circle" src="'.$image.'" alt="'.$name.'" width="64" height="64" title="'.$name.'" /></div>';
  1437. $user_info .= '<div class="name"><a href="'.api_get_path(
  1438. WEB_PATH
  1439. ).'main/social/profile.php?u='.$topic['user_sender_id'].'">'.$name.'&nbsp;</a></div>';
  1440. $html .= '<div class="col-xs-4 col-md-2">';
  1441. $html .= $user_info;
  1442. $html .= '</div>';
  1443. $html .= '</div>';
  1444. $html .= '</div>';
  1445. $array_html[] = [$html];
  1446. }
  1447. // grids for items and topics with paginations
  1448. $html_messages .= Display::return_sortable_grid(
  1449. 'topics',
  1450. [],
  1451. $array_html,
  1452. [
  1453. 'hide_navigation' => false,
  1454. 'per_page' => $topics_per_page,
  1455. ],
  1456. $query_vars,
  1457. false,
  1458. [true, true, true, false],
  1459. false
  1460. );
  1461. }
  1462. return $html_messages;
  1463. }
  1464. /**
  1465. * Displays messages of a group with nested view.
  1466. *
  1467. * @param $groupId
  1468. * @param $topic_id
  1469. *
  1470. * @return string
  1471. */
  1472. public static function display_message_for_group($groupId, $topic_id)
  1473. {
  1474. global $my_group_role;
  1475. $main_message = self::get_message_by_id($topic_id);
  1476. if (empty($main_message)) {
  1477. return false;
  1478. }
  1479. $webCodePath = api_get_path(WEB_CODE_PATH);
  1480. $iconCalendar = Display::returnFontAwesomeIcon('calendar');
  1481. $langEdit = get_lang('Edit');
  1482. $langReply = get_lang('Reply');
  1483. $langLastUpdated = get_lang('LastUpdated');
  1484. $langCreated = get_lang('Created');
  1485. $rows = self::get_messages_by_group_by_message($groupId, $topic_id);
  1486. $rows = self::calculate_children($rows, $topic_id);
  1487. $current_user_id = api_get_user_id();
  1488. $items_per_page = 50;
  1489. $query_vars = ['id' => $groupId, 'topic_id' => $topic_id, 'topics_page_nr' => 0];
  1490. // Main message
  1491. $links = '';
  1492. $main_content = '';
  1493. $html = '';
  1494. $items_page_nr = null;
  1495. $user_sender_info = api_get_user_info($main_message['user_sender_id']);
  1496. $files_attachments = self::getAttachmentLinkList($main_message['id'], 0);
  1497. $name = $user_sender_info['complete_name'];
  1498. $topic_page_nr = isset($_GET['topics_page_nr']) ? (int) $_GET['topics_page_nr'] : null;
  1499. $links .= '<div class="pull-right">';
  1500. $links .= '<div class="btn-group btn-group-sm">';
  1501. if (($my_group_role == GROUP_USER_PERMISSION_ADMIN || $my_group_role == GROUP_USER_PERMISSION_MODERATOR) ||
  1502. $main_message['user_sender_id'] == $current_user_id
  1503. ) {
  1504. $urlEdit = $webCodePath.'social/message_for_group_form.inc.php?'
  1505. .http_build_query(
  1506. [
  1507. 'user_friend' => $current_user_id,
  1508. 'group_id' => $groupId,
  1509. 'message_id' => $main_message['id'],
  1510. 'action' => 'edit_message_group',
  1511. 'anchor_topic' => 'topic_'.$main_message['id'],
  1512. 'topics_page_nr' => $topic_page_nr,
  1513. 'items_page_nr' => $items_page_nr,
  1514. 'topic_id' => $main_message['id'],
  1515. ]
  1516. );
  1517. $links .= Display::toolbarButton(
  1518. $langEdit,
  1519. $urlEdit,
  1520. 'pencil',
  1521. 'default',
  1522. ['class' => 'ajax', 'data-title' => $langEdit, 'data-size' => 'lg'],
  1523. false
  1524. );
  1525. }
  1526. $links .= self::getLikesButton($main_message['id'], $current_user_id, $groupId);
  1527. $urlReply = $webCodePath.'social/message_for_group_form.inc.php?'
  1528. .http_build_query(
  1529. [
  1530. 'user_friend' => $current_user_id,
  1531. 'group_id' => $groupId,
  1532. 'message_id' => $main_message['id'],
  1533. 'action' => 'reply_message_group',
  1534. 'anchor_topic' => 'topic_'.$main_message['id'],
  1535. 'topics_page_nr' => $topic_page_nr,
  1536. 'topic_id' => $main_message['id'],
  1537. ]
  1538. );
  1539. $links .= Display::toolbarButton(
  1540. $langReply,
  1541. $urlReply,
  1542. 'commenting',
  1543. 'default',
  1544. ['class' => 'ajax', 'data-title' => $langReply, 'data-size' => 'lg'],
  1545. false
  1546. );
  1547. if (api_is_platform_admin()) {
  1548. $links .= Display::toolbarButton(
  1549. get_lang('Delete'),
  1550. 'group_topics.php?action=delete&id='.$groupId.'&topic_id='.$topic_id,
  1551. 'trash',
  1552. 'default',
  1553. [],
  1554. false
  1555. );
  1556. }
  1557. $links .= '</div>';
  1558. $links .= '</div>';
  1559. $title = '<h4>'.Security::remove_XSS($main_message['title'], STUDENT, true).$links.'</h4>';
  1560. $userPicture = $user_sender_info['avatar'];
  1561. $main_content .= '<div class="row">';
  1562. $main_content .= '<div class="col-md-2">';
  1563. $main_content .= '<div class="avatar-author">';
  1564. $main_content .= Display::img(
  1565. $userPicture,
  1566. $name,
  1567. ['width' => '60px', 'class' => 'img-responsive img-circle'],
  1568. false
  1569. );
  1570. $main_content .= '</div>';
  1571. $main_content .= '</div>';
  1572. $date = '';
  1573. if ($main_message['send_date'] != $main_message['update_date']) {
  1574. if (!empty($main_message['update_date'])) {
  1575. $date = '<div class="date"> '
  1576. ."$iconCalendar $langLastUpdated "
  1577. .Display::dateToStringAgoAndLongDate($main_message['update_date'])
  1578. .'</div>';
  1579. }
  1580. } else {
  1581. $date = '<div class="date"> '
  1582. ."$iconCalendar $langCreated "
  1583. .Display::dateToStringAgoAndLongDate($main_message['send_date'])
  1584. .'</div>';
  1585. }
  1586. $attachment = '<div class="message-attach">'
  1587. .(!empty($files_attachments) ? implode('<br />', $files_attachments) : '')
  1588. .'</div>';
  1589. $main_content .= '<div class="col-md-10">';
  1590. $user_link = Display::url(
  1591. $name,
  1592. $webCodePath.'social/profile.php?u='.$main_message['user_sender_id']
  1593. );
  1594. $main_content .= '<div class="message-content"> ';
  1595. $main_content .= '<div class="username">'.$user_link.'</div>';
  1596. $main_content .= $date;
  1597. $main_content .= '<div class="message">'.$main_message['content'].$attachment.'</div></div>';
  1598. $main_content .= '</div>';
  1599. $main_content .= '</div>';
  1600. $html .= Display::div(
  1601. Display::div(
  1602. $title.$main_content,
  1603. ['class' => 'message-topic']
  1604. ),
  1605. ['class' => 'sm-groups-message']
  1606. );
  1607. $topic_id = $main_message['id'];
  1608. if (is_array($rows) && count($rows) > 0) {
  1609. $topics = $rows;
  1610. $array_html_items = [];
  1611. foreach ($topics as $index => $topic) {
  1612. if (empty($topic['id'])) {
  1613. continue;
  1614. }
  1615. $items_page_nr = isset($_GET['items_'.$topic['id'].'_page_nr'])
  1616. ? (int) $_GET['items_'.$topic['id'].'_page_nr']
  1617. : null;
  1618. $links = '';
  1619. $links .= '<div class="pull-right">';
  1620. $html_items = '';
  1621. $user_sender_info = api_get_user_info($topic['user_sender_id']);
  1622. $files_attachments = self::getAttachmentLinkList($topic['id'], 0);
  1623. $name = $user_sender_info['complete_name'];
  1624. $links .= '<div class="btn-group btn-group-sm">';
  1625. if (
  1626. ($my_group_role == GROUP_USER_PERMISSION_ADMIN ||
  1627. $my_group_role == GROUP_USER_PERMISSION_MODERATOR
  1628. ) ||
  1629. $topic['user_sender_id'] == $current_user_id
  1630. ) {
  1631. $links .= Display::toolbarButton(
  1632. $langEdit,
  1633. $webCodePath.'social/message_for_group_form.inc.php?'
  1634. .http_build_query(
  1635. [
  1636. 'user_friend' => $current_user_id,
  1637. 'group_id' => $groupId,
  1638. 'message_id' => $topic['id'],
  1639. 'action' => 'edit_message_group',
  1640. 'anchor_topic' => 'topic_'.$topic_id,
  1641. 'topics_page_nr' => $topic_page_nr,
  1642. 'items_page_nr' => $items_page_nr,
  1643. 'topic_id' => $topic_id,
  1644. ]
  1645. ),
  1646. 'pencil',
  1647. 'default',
  1648. ['class' => 'ajax', 'data-title' => $langEdit, 'data-size' => 'lg'],
  1649. false
  1650. );
  1651. }
  1652. $links .= self::getLikesButton($topic['id'], $current_user_id, $groupId);
  1653. $links .= Display::toolbarButton(
  1654. $langReply,
  1655. $webCodePath.'social/message_for_group_form.inc.php?'
  1656. .http_build_query(
  1657. [
  1658. 'user_friend' => $current_user_id,
  1659. 'group_id' => $groupId,
  1660. 'message_id' => $topic['id'],
  1661. 'action' => 'reply_message_group',
  1662. 'anchor_topic' => 'topic_'.$topic_id,
  1663. 'topics_page_nr' => $topic_page_nr,
  1664. 'items_page_nr' => $items_page_nr,
  1665. 'topic_id' => $topic_id,
  1666. ]
  1667. ),
  1668. 'commenting',
  1669. 'default',
  1670. ['class' => 'ajax', 'data-title' => $langReply, 'data-size' => 'lg'],
  1671. false
  1672. );
  1673. $links .= '</div>';
  1674. $links .= '</div>';
  1675. $userPicture = $user_sender_info['avatar'];
  1676. $user_link = Display::url(
  1677. $name,
  1678. $webCodePath.'social/profile.php?u='.$topic['user_sender_id']
  1679. );
  1680. $html_items .= '<div class="row">';
  1681. $html_items .= '<div class="col-md-2">';
  1682. $html_items .= '<div class="avatar-author">';
  1683. $html_items .= Display::img(
  1684. $userPicture,
  1685. $name,
  1686. ['width' => '60px', 'class' => 'img-responsive img-circle'],
  1687. false
  1688. );
  1689. $html_items .= '</div>';
  1690. $html_items .= '</div>';
  1691. $date = '';
  1692. if ($topic['send_date'] != $topic['update_date']) {
  1693. if (!empty($topic['update_date'])) {
  1694. $date = '<div class="date"> '
  1695. ."$iconCalendar $langLastUpdated "
  1696. .Display::dateToStringAgoAndLongDate($topic['update_date'])
  1697. .'</div>';
  1698. }
  1699. } else {
  1700. $date = '<div class="date"> '
  1701. ."$iconCalendar $langCreated "
  1702. .Display::dateToStringAgoAndLongDate($topic['send_date'])
  1703. .'</div>';
  1704. }
  1705. $attachment = '<div class="message-attach">'
  1706. .(!empty($files_attachments) ? implode('<br />', $files_attachments) : '')
  1707. .'</div>';
  1708. $html_items .= '<div class="col-md-10">'
  1709. .'<div class="message-content">'
  1710. .$links
  1711. .'<div class="username">'.$user_link.'</div>'
  1712. .$date
  1713. .'<div class="message">'
  1714. .Security::remove_XSS($topic['content'], STUDENT, true)
  1715. .'</div>'.$attachment.'</div>'
  1716. .'</div>'
  1717. .'</div>';
  1718. $base_padding = 20;
  1719. if ($topic['indent_cnt'] == 0) {
  1720. $indent = $base_padding;
  1721. } else {
  1722. $indent = (int) $topic['indent_cnt'] * $base_padding + $base_padding;
  1723. }
  1724. $html_items = Display::div($html_items, ['class' => 'message-post', 'id' => 'msg_'.$topic['id']]);
  1725. $html_items = Display::div($html_items, ['class' => '', 'style' => 'margin-left:'.$indent.'px']);
  1726. $array_html_items[] = [$html_items];
  1727. }
  1728. // grids for items with paginations
  1729. $options = ['hide_navigation' => false, 'per_page' => $items_per_page];
  1730. $visibility = [true, true, true, false];
  1731. $style_class = [
  1732. 'item' => ['class' => 'user-post'],
  1733. 'main' => ['class' => 'user-list'],
  1734. ];
  1735. if (!empty($array_html_items)) {
  1736. $html .= Display::return_sortable_grid(
  1737. 'items_'.$topic['id'],
  1738. [],
  1739. $array_html_items,
  1740. $options,
  1741. $query_vars,
  1742. null,
  1743. $visibility,
  1744. false,
  1745. $style_class
  1746. );
  1747. }
  1748. }
  1749. return $html;
  1750. }
  1751. /**
  1752. * Add children to messages by id is used for nested view messages.
  1753. *
  1754. * @param array $rows rows of messages
  1755. *
  1756. * @return array $first_seed new list adding the item children
  1757. */
  1758. public static function calculate_children($rows, $first_seed)
  1759. {
  1760. $rows_with_children = [];
  1761. foreach ($rows as $row) {
  1762. $rows_with_children[$row["id"]] = $row;
  1763. $rows_with_children[$row["parent_id"]]["children"][] = $row["id"];
  1764. }
  1765. $rows = $rows_with_children;
  1766. $sorted_rows = [0 => []];
  1767. self::message_recursive_sort($rows, $sorted_rows, $first_seed);
  1768. unset($sorted_rows[0]);
  1769. return $sorted_rows;
  1770. }
  1771. /**
  1772. * Sort recursively the messages, is used for for nested view messages.
  1773. *
  1774. * @param array original rows of messages
  1775. * @param array list recursive of messages
  1776. * @param int seed for calculate the indent
  1777. * @param int indent for nested view
  1778. */
  1779. public static function message_recursive_sort(
  1780. $rows,
  1781. &$messages,
  1782. $seed = 0,
  1783. $indent = 0
  1784. ) {
  1785. if ($seed > 0 && isset($rows[$seed]["id"])) {
  1786. $messages[$rows[$seed]["id"]] = $rows[$seed];
  1787. $messages[$rows[$seed]["id"]]["indent_cnt"] = $indent;
  1788. $indent++;
  1789. }
  1790. if (isset($rows[$seed]["children"])) {
  1791. foreach ($rows[$seed]["children"] as $child) {
  1792. self::message_recursive_sort($rows, $messages, $child, $indent);
  1793. }
  1794. }
  1795. }
  1796. /**
  1797. * @param int $messageId
  1798. *
  1799. * @return array
  1800. */
  1801. public static function getAttachmentList($messageId)
  1802. {
  1803. $table = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  1804. $messageId = (int) $messageId;
  1805. if (empty($messageId)) {
  1806. return [];
  1807. }
  1808. $messageInfo = self::get_message_by_id($messageId);
  1809. if (empty($messageInfo)) {
  1810. return [];
  1811. }
  1812. $attachmentDir = UserManager::getUserPathById($messageInfo['user_receiver_id'], 'system');
  1813. $attachmentDir .= 'message_attachments/';
  1814. $sql = "SELECT * FROM $table
  1815. WHERE message_id = '$messageId'";
  1816. $result = Database::query($sql);
  1817. $files = [];
  1818. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1819. $row['file_source'] = '';
  1820. if (file_exists($attachmentDir.$row['path'])) {
  1821. $row['file_source'] = $attachmentDir.$row['path'];
  1822. }
  1823. $files[] = $row;
  1824. }
  1825. return $files;
  1826. }
  1827. /**
  1828. * Get array of links (download) for message attachment files.
  1829. *
  1830. * @param int $messageId
  1831. * @param int $type
  1832. *
  1833. * @return array
  1834. */
  1835. public static function getAttachmentLinkList($messageId, $type)
  1836. {
  1837. $files = self::getAttachmentList($messageId);
  1838. // get file attachments by message id
  1839. $list = [];
  1840. if ($files) {
  1841. $attachIcon = Display::return_icon('attachment.gif', '');
  1842. $archiveURL = api_get_path(WEB_CODE_PATH).'messages/download.php?type='.$type.'&file=';
  1843. foreach ($files as $row_file) {
  1844. $archiveFile = $row_file['path'];
  1845. $filename = $row_file['filename'];
  1846. $size = format_file_size($row_file['size']);
  1847. $comment = Security::remove_XSS($row_file['comment']);
  1848. $filename = Security::remove_XSS($filename);
  1849. $link = Display::url($filename, $archiveURL.$archiveFile);
  1850. $comment = !empty($comment) ? '&nbsp;-&nbsp;<i>'.$comment.'</i>' : '';
  1851. $attachmentLine = $attachIcon.'&nbsp;'.$link.'&nbsp;('.$size.')'.$comment;
  1852. if ($row_file['comment'] === 'audio_message') {
  1853. $attachmentLine = '<audio src="'.$archiveURL.$archiveFile.'"/>';
  1854. }
  1855. $list[] = $attachmentLine;
  1856. }
  1857. }
  1858. return $list;
  1859. }
  1860. /**
  1861. * Get message list by id.
  1862. *
  1863. * @param int $messageId
  1864. *
  1865. * @return array
  1866. */
  1867. public static function get_message_by_id($messageId)
  1868. {
  1869. $table = Database::get_main_table(TABLE_MESSAGE);
  1870. $messageId = (int) $messageId;
  1871. $sql = "SELECT * FROM $table
  1872. WHERE
  1873. id = '$messageId' AND
  1874. msg_status <> '".MESSAGE_STATUS_DELETED."' ";
  1875. $res = Database::query($sql);
  1876. $item = [];
  1877. if (Database::num_rows($res) > 0) {
  1878. $item = Database::fetch_array($res, 'ASSOC');
  1879. }
  1880. return $item;
  1881. }
  1882. /**
  1883. * @return string
  1884. */
  1885. public static function generate_message_form()
  1886. {
  1887. $form = new FormValidator('send_message');
  1888. $form->addText(
  1889. 'subject',
  1890. get_lang('Subject'),
  1891. false,
  1892. ['id' => 'subject_id']
  1893. );
  1894. $form->addTextarea(
  1895. 'content',
  1896. get_lang('Message'),
  1897. ['id' => 'content_id', 'rows' => '5']
  1898. );
  1899. return $form->returnForm();
  1900. }
  1901. /**
  1902. * @return string
  1903. */
  1904. public static function generate_invitation_form()
  1905. {
  1906. $form = new FormValidator('send_invitation');
  1907. $form->addTextarea(
  1908. 'content',
  1909. get_lang('Add a personal message'),
  1910. ['id' => 'content_invitation_id', 'rows' => 5]
  1911. );
  1912. return $form->returnForm();
  1913. }
  1914. /**
  1915. * @param string $type
  1916. * @param string $keyword
  1917. * @param array $actions
  1918. *
  1919. * @return string
  1920. */
  1921. public static function getMessageGrid($type, $keyword, $actions = [])
  1922. {
  1923. $html = '';
  1924. // display sortable table with messages of the current user
  1925. $table = new SortableTable(
  1926. 'message_inbox',
  1927. ['MessageManager', 'getNumberOfMessages'],
  1928. ['MessageManager', 'getMessageData'],
  1929. 2,
  1930. 20,
  1931. 'DESC'
  1932. );
  1933. $table->setDataFunctionParams(
  1934. ['keyword' => $keyword, 'type' => $type, 'actions' => $actions]
  1935. );
  1936. $table->set_header(0, '', false, ['style' => 'width:15px;']);
  1937. $table->set_header(1, get_lang('Messages'), false);
  1938. $table->set_header(2, get_lang('Date'), true, ['style' => 'width:180px;']);
  1939. $table->set_header(3, get_lang('Edit'), false, ['style' => 'width:120px;']);
  1940. if (isset($_REQUEST['f']) && $_REQUEST['f'] === 'social') {
  1941. $parameters['f'] = 'social';
  1942. $table->set_additional_parameters($parameters);
  1943. }
  1944. $defaultActions = [
  1945. 'delete' => get_lang('Delete selected messages'),
  1946. 'mark_as_unread' => get_lang('Mark as unread'),
  1947. 'mark_as_read' => get_lang('Mark as read'),
  1948. ];
  1949. if (!in_array('delete', $actions)) {
  1950. unset($defaultActions['delete']);
  1951. }
  1952. if (!in_array('mark_as_unread', $actions)) {
  1953. unset($defaultActions['mark_as_unread']);
  1954. }
  1955. if (!in_array('mark_as_read', $actions)) {
  1956. unset($defaultActions['mark_as_read']);
  1957. }
  1958. $table->set_form_actions($defaultActions);
  1959. $html .= $table->return_table();
  1960. return $html;
  1961. }
  1962. /**
  1963. * @param string $keyword
  1964. *
  1965. * @return string
  1966. */
  1967. public static function inboxDisplay($keyword = '')
  1968. {
  1969. $success = get_lang('The selected messages have been deleted');
  1970. $success_read = get_lang('Selected messages have been marked as read');
  1971. $success_unread = get_lang('Selected messages have been marked as unread');
  1972. $currentUserId = api_get_user_id();
  1973. if (isset($_REQUEST['action'])) {
  1974. switch ($_REQUEST['action']) {
  1975. case 'mark_as_unread':
  1976. if (is_array($_POST['id'])) {
  1977. foreach ($_POST['id'] as $index => $messageId) {
  1978. self::update_message_status(
  1979. $currentUserId,
  1980. $messageId,
  1981. MESSAGE_STATUS_UNREAD
  1982. );
  1983. }
  1984. }
  1985. Display::addFlash(Display::return_message(
  1986. $success_unread,
  1987. 'normal',
  1988. false
  1989. ));
  1990. break;
  1991. case 'mark_as_read':
  1992. if (is_array($_POST['id'])) {
  1993. foreach ($_POST['id'] as $index => $messageId) {
  1994. self::update_message_status(
  1995. $currentUserId,
  1996. $messageId,
  1997. MESSAGE_STATUS_NEW
  1998. );
  1999. }
  2000. }
  2001. Display::addFlash(Display::return_message(
  2002. $success_read,
  2003. 'normal',
  2004. false
  2005. ));
  2006. break;
  2007. case 'delete':
  2008. foreach ($_POST['id'] as $index => $messageId) {
  2009. self::delete_message_by_user_receiver($currentUserId, $messageId);
  2010. }
  2011. Display::addFlash(Display::return_message(
  2012. $success,
  2013. 'normal',
  2014. false
  2015. ));
  2016. break;
  2017. case 'deleteone':
  2018. $result = self::delete_message_by_user_receiver($currentUserId, $_GET['id']);
  2019. if ($result) {
  2020. Display::addFlash(
  2021. Display::return_message(
  2022. $success,
  2023. 'confirmation',
  2024. false
  2025. )
  2026. );
  2027. }
  2028. break;
  2029. }
  2030. header('Location: '.api_get_self());
  2031. exit;
  2032. }
  2033. $actions = ['reply', 'mark_as_unread', 'mark_as_read', 'forward', 'delete'];
  2034. $html = self::getMessageGrid(self::MESSAGE_TYPE_INBOX, $keyword, $actions);
  2035. return $html;
  2036. }
  2037. /**
  2038. * @param string $keyword
  2039. *
  2040. * @return string
  2041. */
  2042. public static function getPromotedMessagesGrid($keyword)
  2043. {
  2044. $actions = ['delete'];
  2045. $currentUserId = api_get_user_id();
  2046. $success = get_lang('The selected messages have been deleted');
  2047. if (isset($_REQUEST['action'])) {
  2048. switch ($_REQUEST['action']) {
  2049. case 'delete':
  2050. foreach ($_POST['id'] as $index => $messageId) {
  2051. self::delete_message_by_user_receiver($currentUserId, $messageId);
  2052. }
  2053. Display::addFlash(Display::return_message(
  2054. $success,
  2055. 'normal',
  2056. false
  2057. ));
  2058. break;
  2059. case 'deleteone':
  2060. self::delete_message_by_user_receiver($currentUserId, $_GET['id']);
  2061. Display::addFlash(Display::return_message(
  2062. $success,
  2063. 'confirmation',
  2064. false
  2065. ));
  2066. break;
  2067. }
  2068. header('Location: '.api_get_self());
  2069. exit;
  2070. }
  2071. $html = self::getMessageGrid(self::MESSAGE_TYPE_PROMOTED, $keyword, $actions);
  2072. return $html;
  2073. }
  2074. /**
  2075. * @param string $keyword
  2076. *
  2077. * @return string
  2078. */
  2079. public static function outBoxDisplay($keyword)
  2080. {
  2081. $actions = ['delete'];
  2082. $success = get_lang('The selected messages have been deleted');
  2083. $currentUserId = api_get_user_id();
  2084. if (isset($_REQUEST['action'])) {
  2085. switch ($_REQUEST['action']) {
  2086. case 'delete':
  2087. foreach ($_POST['id'] as $index => $messageId) {
  2088. self::delete_message_by_user_sender($currentUserId, $messageId);
  2089. }
  2090. Display::addFlash(Display::return_message(
  2091. $success,
  2092. 'normal',
  2093. false
  2094. ));
  2095. break;
  2096. case 'deleteone':
  2097. self::delete_message_by_user_sender($currentUserId, $_GET['id']);
  2098. Display::addFlash(Display::return_message(
  2099. $success,
  2100. 'confirmation',
  2101. false
  2102. ));
  2103. break;
  2104. }
  2105. header('Location: '.api_get_self());
  2106. exit;
  2107. }
  2108. $html = self::getMessageGrid(self::MESSAGE_TYPE_OUTBOX, $keyword, $actions);
  2109. return $html;
  2110. }
  2111. /**
  2112. * @param string $keyword
  2113. *
  2114. * @return string
  2115. */
  2116. public static function outbox_display($keyword = '')
  2117. {
  2118. Session::write('message_sent_search_keyword', $keyword);
  2119. $success = get_lang('The selected messages have been deleted').'&nbsp</b><br />
  2120. <a href="outbox.php">'.get_lang('Back to outbox').'</a>';
  2121. $html = '';
  2122. if (isset($_REQUEST['action'])) {
  2123. switch ($_REQUEST['action']) {
  2124. case 'delete':
  2125. $count = count($_POST['id']);
  2126. if ($count != 0) {
  2127. foreach ($_POST['id'] as $index => $messageId) {
  2128. self::delete_message_by_user_receiver(
  2129. api_get_user_id(),
  2130. $messageId
  2131. );
  2132. }
  2133. }
  2134. $html .= Display::return_message(api_xml_http_response_encode($success), 'normal', false);
  2135. break;
  2136. case 'deleteone':
  2137. self::delete_message_by_user_receiver(api_get_user_id(), $_GET['id']);
  2138. $html .= Display::return_message(api_xml_http_response_encode($success), 'normal', false);
  2139. $html .= '<br/>';
  2140. break;
  2141. }
  2142. }
  2143. // display sortable table with messages of the current user
  2144. $table = new SortableTable(
  2145. 'message_outbox',
  2146. ['MessageManager', 'getNumberOfMessages'],
  2147. ['MessageManager', 'getMessageData'],
  2148. 2,
  2149. 20,
  2150. 'DESC'
  2151. );
  2152. $table->setDataFunctionParams(
  2153. ['keyword' => $keyword, 'type' => self::MESSAGE_TYPE_OUTBOX]
  2154. );
  2155. $table->set_header(0, '', false, ['style' => 'width:15px;']);
  2156. $table->set_header(1, get_lang('Messages'), false);
  2157. $table->set_header(2, get_lang('Date'), true, ['style' => 'width:180px;']);
  2158. $table->set_header(3, get_lang('Edit'), false, ['style' => 'width:70px;']);
  2159. $table->set_form_actions(['delete' => get_lang('Delete selected messages')]);
  2160. $html .= $table->return_table();
  2161. return $html;
  2162. }
  2163. /**
  2164. * Get the data of the last received messages for a user.
  2165. *
  2166. * @param int $userId The user id
  2167. * @param int $lastId The id of the last received message
  2168. *
  2169. * @return array
  2170. */
  2171. public static function getMessagesFromLastReceivedMessage($userId, $lastId = 0)
  2172. {
  2173. $userId = (int) $userId;
  2174. $lastId = (int) $lastId;
  2175. if (empty($userId)) {
  2176. return [];
  2177. }
  2178. $messagesTable = Database::get_main_table(TABLE_MESSAGE);
  2179. $userTable = Database::get_main_table(TABLE_MAIN_USER);
  2180. $sql = "SELECT m.*, u.user_id, u.lastname, u.firstname
  2181. FROM $messagesTable as m
  2182. INNER JOIN $userTable as u
  2183. ON m.user_sender_id = u.user_id
  2184. WHERE
  2185. m.user_receiver_id = $userId AND
  2186. m.msg_status = ".MESSAGE_STATUS_UNREAD."
  2187. AND m.id > $lastId
  2188. ORDER BY m.send_date DESC";
  2189. $result = Database::query($sql);
  2190. $messages = [];
  2191. if ($result !== false) {
  2192. while ($row = Database::fetch_assoc($result)) {
  2193. $messages[] = $row;
  2194. }
  2195. }
  2196. return $messages;
  2197. }
  2198. /**
  2199. * Check whether a message has attachments.
  2200. *
  2201. * @param int $messageId The message id
  2202. *
  2203. * @return bool Whether the message has attachments return true. Otherwise return false
  2204. */
  2205. public static function hasAttachments($messageId)
  2206. {
  2207. $messageId = (int) $messageId;
  2208. if (empty($messageId)) {
  2209. return false;
  2210. }
  2211. $messageAttachmentTable = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  2212. $conditions = [
  2213. 'where' => [
  2214. 'message_id = ?' => $messageId,
  2215. ],
  2216. ];
  2217. $result = Database::select(
  2218. 'COUNT(1) AS qty',
  2219. $messageAttachmentTable,
  2220. $conditions,
  2221. 'first'
  2222. );
  2223. if (!empty($result)) {
  2224. if ($result['qty'] > 0) {
  2225. return true;
  2226. }
  2227. }
  2228. return false;
  2229. }
  2230. /**
  2231. * @param int $messageId
  2232. *
  2233. * @return array|bool
  2234. */
  2235. public static function getAttachment($messageId)
  2236. {
  2237. $messageId = (int) $messageId;
  2238. if (empty($messageId)) {
  2239. return false;
  2240. }
  2241. $table = Database::get_main_table(TABLE_MESSAGE_ATTACHMENT);
  2242. $conditions = [
  2243. 'where' => [
  2244. 'id = ?' => $messageId,
  2245. ],
  2246. ];
  2247. $result = Database::select(
  2248. '*',
  2249. $table,
  2250. $conditions,
  2251. 'first'
  2252. );
  2253. if (!empty($result)) {
  2254. return $result;
  2255. }
  2256. return false;
  2257. }
  2258. /**
  2259. * @param string $url
  2260. *
  2261. * @return FormValidator
  2262. */
  2263. public static function getSearchForm($url)
  2264. {
  2265. $form = new FormValidator(
  2266. 'search',
  2267. 'post',
  2268. $url,
  2269. null,
  2270. [],
  2271. FormValidator::LAYOUT_INLINE
  2272. );
  2273. $form->addElement(
  2274. 'text',
  2275. 'keyword',
  2276. false,
  2277. [
  2278. 'aria-label' => get_lang('Search'),
  2279. ]
  2280. );
  2281. $form->addButtonSearch(get_lang('Search'));
  2282. return $form;
  2283. }
  2284. /**
  2285. * Send a notification to all admins when a new user is registered.
  2286. *
  2287. * @param User $user
  2288. */
  2289. public static function sendNotificationByRegisteredUser(User $user)
  2290. {
  2291. $tplMailBody = new Template(
  2292. null,
  2293. false,
  2294. false,
  2295. false,
  2296. false,
  2297. false,
  2298. false
  2299. );
  2300. $tplMailBody->assign('user', $user);
  2301. $tplMailBody->assign('is_western_name_order', api_is_western_name_order());
  2302. $tplMailBody->assign(
  2303. 'manageUrl',
  2304. api_get_path(WEB_CODE_PATH).'admin/user_edit.php?user_id='.$user->getId()
  2305. );
  2306. $layoutContent = $tplMailBody->get_template('mail/new_user_mail_to_admin.tpl');
  2307. $emailsubject = '['.get_lang('The user has been registered').'] '.$user->getUsername();
  2308. $emailbody = $tplMailBody->fetch($layoutContent);
  2309. $admins = UserManager::get_all_administrators();
  2310. foreach ($admins as $admin_info) {
  2311. self::send_message(
  2312. $admin_info['user_id'],
  2313. $emailsubject,
  2314. $emailbody,
  2315. [],
  2316. [],
  2317. null,
  2318. null,
  2319. null,
  2320. null,
  2321. $user->getId()
  2322. );
  2323. }
  2324. }
  2325. /**
  2326. * Get the error log from failed mailing
  2327. * This assumes a complex setup where you have a cron script regularly copying the mail queue log
  2328. * into app/cache/mail/mailq.
  2329. * This can be done with a cron command like (check the location of your mail log file first):.
  2330. *
  2331. * @example 0,30 * * * * root cp /var/log/exim4/mainlog /var/www/chamilo/app/cache/mail/mailq
  2332. *
  2333. * @return array|bool
  2334. */
  2335. public static function failedSentMailErrors()
  2336. {
  2337. $base = api_get_path(SYS_ARCHIVE_PATH).'mail/';
  2338. $mailq = $base.'mailq';
  2339. if (!file_exists($mailq) || !is_readable($mailq)) {
  2340. return false;
  2341. }
  2342. $file = fopen($mailq, 'r');
  2343. $i = 1;
  2344. while (!feof($file)) {
  2345. $line = fgets($file);
  2346. if (trim($line) == '') {
  2347. continue;
  2348. }
  2349. // Get the mail code, something like 1WBumL-0002xg-FF
  2350. if (preg_match('/(.*)\s((.*)-(.*)-(.*))\s<(.*)$/', $line, $codeMatches)) {
  2351. $mail_queue[$i]['code'] = $codeMatches[2];
  2352. }
  2353. $fullMail = $base.$mail_queue[$i]['code'];
  2354. $mailFile = fopen($fullMail, 'r');
  2355. // Get the reason of mail fail
  2356. $iX = 1;
  2357. while (!feof($mailFile)) {
  2358. $mailLine = fgets($mailFile);
  2359. //if ($iX == 4 && preg_match('/(.*):\s(.*)$/', $mailLine, $matches)) {
  2360. if ($iX == 2 &&
  2361. preg_match('/(.*)(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s(.*)/', $mailLine, $detailsMatches)
  2362. ) {
  2363. $mail_queue[$i]['reason'] = $detailsMatches[3];
  2364. }
  2365. $iX++;
  2366. }
  2367. fclose($mailFile);
  2368. // Get the time of mail fail
  2369. if (preg_match('/^\s?(\d+)(\D+)\s+(.*)$/', $line, $timeMatches)) {
  2370. $mail_queue[$i]['time'] = $timeMatches[1].$timeMatches[2];
  2371. } elseif (preg_match('/^(\s+)((.*)@(.*))\s+(.*)$/', $line, $emailMatches)) {
  2372. $mail_queue[$i]['mail'] = $emailMatches[2];
  2373. $i++;
  2374. }
  2375. }
  2376. fclose($file);
  2377. return array_reverse($mail_queue);
  2378. }
  2379. /**
  2380. * @param int $userId
  2381. *
  2382. * @return array
  2383. */
  2384. public static function getUsersThatHadConversationWithUser($userId)
  2385. {
  2386. $messagesTable = Database::get_main_table(TABLE_MESSAGE);
  2387. $userId = (int) $userId;
  2388. $sql = "SELECT DISTINCT
  2389. user_sender_id
  2390. FROM $messagesTable
  2391. WHERE
  2392. user_receiver_id = ".$userId;
  2393. $result = Database::query($sql);
  2394. $users = Database::store_result($result);
  2395. $userList = [];
  2396. foreach ($users as $userData) {
  2397. $userId = $userData['user_sender_id'];
  2398. if (empty($userId)) {
  2399. continue;
  2400. }
  2401. $userInfo = api_get_user_info($userId);
  2402. if ($userInfo) {
  2403. $userList[$userId] = $userInfo;
  2404. }
  2405. }
  2406. return $userList;
  2407. }
  2408. /**
  2409. * @param int $userId
  2410. * @param int $otherUserId
  2411. *
  2412. * @return array
  2413. */
  2414. public static function getAllMessagesBetweenStudents($userId, $otherUserId)
  2415. {
  2416. $messagesTable = Database::get_main_table(TABLE_MESSAGE);
  2417. $userId = (int) $userId;
  2418. $otherUserId = (int) $otherUserId;
  2419. if (empty($otherUserId) || empty($userId)) {
  2420. return [];
  2421. }
  2422. $sql = "SELECT DISTINCT *
  2423. FROM $messagesTable
  2424. WHERE
  2425. (user_receiver_id = $userId AND user_sender_id = $otherUserId) OR
  2426. (user_receiver_id = $otherUserId AND user_sender_id = $userId)
  2427. ORDER BY send_date DESC
  2428. ";
  2429. $result = Database::query($sql);
  2430. $messages = Database::store_result($result);
  2431. $list = [];
  2432. foreach ($messages as $message) {
  2433. $list[] = $message;
  2434. }
  2435. return $list;
  2436. }
  2437. /**
  2438. * @param string $subject
  2439. * @param string $message
  2440. * @param array $courseInfo
  2441. * @param int $sessionId
  2442. *
  2443. * @return bool
  2444. */
  2445. public static function sendMessageToAllUsersInCourse($subject, $message, $courseInfo, $sessionId = 0)
  2446. {
  2447. if (empty($courseInfo)) {
  2448. return false;
  2449. }
  2450. $senderId = api_get_user_id();
  2451. if (empty($senderId)) {
  2452. return false;
  2453. }
  2454. if (empty($sessionId)) {
  2455. // Course students and teachers
  2456. $users = CourseManager::get_user_list_from_course_code($courseInfo['code']);
  2457. } else {
  2458. // Course-session students and course session coaches
  2459. $users = CourseManager::get_user_list_from_course_code($courseInfo['code'], $sessionId);
  2460. }
  2461. if (empty($users)) {
  2462. return false;
  2463. }
  2464. foreach ($users as $userInfo) {
  2465. self::send_message_simple(
  2466. $userInfo['user_id'],
  2467. $subject,
  2468. $message,
  2469. $senderId,
  2470. false,
  2471. false,
  2472. [],
  2473. false
  2474. );
  2475. }
  2476. }
  2477. /**
  2478. * Clean audio messages already added in the message tool.
  2479. */
  2480. public static function cleanAudioMessage()
  2481. {
  2482. $audioId = Session::read('current_audio_id');
  2483. if (!empty($audioId)) {
  2484. api_remove_uploaded_file_by_id('audio_message', api_get_user_id(), $audioId);
  2485. Session::erase('current_audio_id');
  2486. }
  2487. }
  2488. /**
  2489. * @param int $senderId
  2490. * @param string $subject
  2491. * @param string $message
  2492. */
  2493. public static function sendMessageToAllAdminUsers(
  2494. $senderId,
  2495. $subject,
  2496. $message
  2497. ) {
  2498. $admins = UserManager::get_all_administrators();
  2499. foreach ($admins as $admin) {
  2500. self::send_message_simple($admin['user_id'], $subject, $message, $senderId);
  2501. }
  2502. }
  2503. /**
  2504. * @param int $messageId
  2505. * @param int $userId
  2506. *
  2507. * @return array
  2508. */
  2509. public static function countLikesAndDislikes($messageId, $userId)
  2510. {
  2511. if (!api_get_configuration_value('social_enable_messages_feedback')) {
  2512. return [];
  2513. }
  2514. $messageId = (int) $messageId;
  2515. $userId = (int) $userId;
  2516. $em = Database::getManager();
  2517. $query = $em
  2518. ->createQuery('
  2519. SELECT SUM(l.liked) AS likes, SUM(l.disliked) AS dislikes FROM ChamiloCoreBundle:MessageFeedback l
  2520. WHERE l.message = :message
  2521. ')
  2522. ->setParameters(['message' => $messageId]);
  2523. try {
  2524. $counts = $query->getSingleResult();
  2525. } catch (Exception $e) {
  2526. $counts = ['likes' => 0, 'dislikes' => 0];
  2527. }
  2528. $userLike = $em
  2529. ->getRepository('ChamiloCoreBundle:MessageFeedback')
  2530. ->findOneBy(['message' => $messageId, 'user' => $userId]);
  2531. return [
  2532. 'likes' => (int) $counts['likes'],
  2533. 'dislikes' => (int) $counts['dislikes'],
  2534. 'user_liked' => $userLike ? $userLike->isLiked() : false,
  2535. 'user_disliked' => $userLike ? $userLike->isDisliked() : false,
  2536. ];
  2537. }
  2538. /**
  2539. * @param int $messageId
  2540. * @param int $userId
  2541. * @param int $groupId Optional.
  2542. *
  2543. * @return string
  2544. */
  2545. public static function getLikesButton($messageId, $userId, $groupId = 0)
  2546. {
  2547. if (!api_get_configuration_value('social_enable_messages_feedback')) {
  2548. return '';
  2549. }
  2550. $countLikes = self::countLikesAndDislikes($messageId, $userId);
  2551. $class = $countLikes['user_liked'] ? 'btn-primary' : 'btn-default';
  2552. $btnLike = Display::button(
  2553. 'like',
  2554. Display::returnFontAwesomeIcon('thumbs-up', '', true)
  2555. .PHP_EOL.'<span>'.$countLikes['likes'].'</span>',
  2556. [
  2557. 'title' => get_lang('Like'),
  2558. 'class' => 'btn social-like '.$class,
  2559. 'data-status' => 'like',
  2560. 'data-message' => $messageId,
  2561. 'data-group' => $groupId,
  2562. ]
  2563. );
  2564. $btnDislike = '';
  2565. if (api_get_configuration_value('disable_dislike_option') === false) {
  2566. $disabled = $countLikes['user_disliked'] ? 'btn-danger' : 'btn-default';
  2567. $btnDislike = Display::button(
  2568. 'like',
  2569. Display::returnFontAwesomeIcon('thumbs-down', '', true)
  2570. .PHP_EOL.'<span>'.$countLikes['dislikes'].'</span>',
  2571. [
  2572. 'title' => get_lang('Dislike'),
  2573. 'class' => 'btn social-like '.$disabled,
  2574. 'data-status' => 'dislike',
  2575. 'data-message' => $messageId,
  2576. 'data-group' => $groupId,
  2577. ]
  2578. );
  2579. }
  2580. return $btnLike.PHP_EOL.$btnDislike;
  2581. }
  2582. /**
  2583. * Execute the SQL necessary to know the number of messages in the database.
  2584. *
  2585. * @param int $userId The user for which we need the unread messages count
  2586. *
  2587. * @return int The number of unread messages in the database for the given user
  2588. */
  2589. public static function getCountNewMessagesFromDB($userId)
  2590. {
  2591. $userId = (int) $userId;
  2592. if (empty($userId)) {
  2593. return 0;
  2594. }
  2595. $table = Database::get_main_table(TABLE_MESSAGE);
  2596. $sql = "SELECT COUNT(id) as count
  2597. FROM $table
  2598. WHERE
  2599. user_receiver_id = $userId AND
  2600. msg_status = ".MESSAGE_STATUS_UNREAD;
  2601. $result = Database::query($sql);
  2602. $row = Database::fetch_assoc($result);
  2603. return (int) $row['count'];
  2604. }
  2605. }