message.lib.php 98 KB

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