CourseChatUtils.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Michelf\MarkdownExtra;
  4. use Doctrine\Common\Collections\Criteria;
  5. use Chamilo\CourseBundle\Entity\CChatConnected;
  6. use Chamilo\CoreBundle\Entity\Course;
  7. use Chamilo\CoreBundle\Entity\Session;
  8. /**
  9. * Class CourseChat
  10. * Manage the chat for a course
  11. */
  12. class CourseChatUtils
  13. {
  14. private $groupId;
  15. private $courseId;
  16. private $sessionId;
  17. private $userId;
  18. /**
  19. * CourseChat constructor.
  20. * @param int $courseId
  21. * @param int $userId
  22. * @param int $sessionId
  23. * @param int $groupId
  24. */
  25. public function __construct($courseId, $userId, $sessionId = 0, $groupId = 0)
  26. {
  27. $this->courseId = (int) $courseId;
  28. $this->userId = (int) $userId;
  29. $this->sessionId = (int) $sessionId;
  30. $this->groupId = (int) $groupId;
  31. }
  32. /**
  33. * Get the users subscriptions (SessionRelCourseRelUser array or CourseRelUser array) for chat
  34. * @return \Doctrine\Common\Collections\ArrayCollection
  35. * @throws \Doctrine\ORM\ORMException
  36. * @throws \Doctrine\ORM\OptimisticLockException
  37. * @throws \Doctrine\ORM\TransactionRequiredException
  38. */
  39. private function getUsersSubscriptions()
  40. {
  41. $em = Database::getManager();
  42. /** @var Course $course */
  43. $course = $em->find('ChamiloCoreBundle:Course', $this->courseId);
  44. if ($this->sessionId) {
  45. /** @var Session $session */
  46. $session = $em->find('ChamiloCoreBundle:Session', $this->sessionId);
  47. $criteria = Criteria::create()->where(Criteria::expr()->eq('course', $course));
  48. $userIsCoach = api_is_course_session_coach($this->userId, $course->getId(), $session->getId());
  49. if (api_get_configuration_value('course_chat_restrict_to_coach')) {
  50. if ($userIsCoach) {
  51. $criteria->andWhere(
  52. Criteria::expr()->eq('status', Session::STUDENT)
  53. );
  54. } else {
  55. $criteria->andWhere(
  56. Criteria::expr()->eq('status', Session::COACH)
  57. );
  58. }
  59. }
  60. $criteria->orderBy(['status' => Criteria::DESC]);
  61. return $session
  62. ->getUserCourseSubscriptions()
  63. ->matching($criteria);
  64. }
  65. return $course->getUsers();
  66. }
  67. /**
  68. * Prepare a message. Clean and insert emojis
  69. * @param string $message The message to prepare
  70. * @return string
  71. */
  72. public static function prepareMessage($message)
  73. {
  74. if (empty($message)) {
  75. return '';
  76. }
  77. Emojione\Emojione::$imagePathPNG = api_get_path(WEB_LIBRARY_PATH).'javascript/emojione/png/';
  78. Emojione\Emojione::$ascii = true;
  79. $message = trim($message);
  80. $message = nl2br($message);
  81. // Security XSS
  82. $message = Security::remove_XSS($message);
  83. //search urls
  84. $message = preg_replace(
  85. '@((https?://)?([-\w]+\.[-\w\.]+)+\w(:\d+)?(/([-\w/_\.]*(\?\S+)?)?)*)@',
  86. '<a href="$1" target="_blank">$1</a>',
  87. $message
  88. );
  89. // add "http://" if not set
  90. $message = preg_replace(
  91. '/<a\s[^>]*href\s*=\s*"((?!https?:\/\/)[^"]*)"[^>]*>/i',
  92. '<a href="http://$1" target="_blank">',
  93. $message
  94. );
  95. // Parsing emojis
  96. $message = Emojione\Emojione::toImage($message);
  97. // Parsing text to understand markdown (code highlight)
  98. $message = MarkdownExtra::defaultTransform($message);
  99. return $message;
  100. }
  101. /**
  102. * Save a chat message in a HTML file
  103. * @param string$message
  104. * @param int $friendId
  105. * @return bool
  106. * @throws \Doctrine\ORM\ORMException
  107. * @throws \Doctrine\ORM\OptimisticLockException
  108. * @throws \Doctrine\ORM\TransactionRequiredException
  109. */
  110. public function saveMessage($message, $friendId = 0)
  111. {
  112. if (empty($message)) {
  113. return false;
  114. }
  115. $user = api_get_user_entity($this->userId);
  116. $courseInfo = api_get_course_info_by_id($this->courseId);
  117. $isMaster = (bool) api_is_course_admin();
  118. $document_path = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document';
  119. $basepath_chat = '/chat_files';
  120. $group_info = [];
  121. if (!$this->groupId) {
  122. $group_info = GroupManager::get_group_properties($this->groupId);
  123. $basepath_chat = $group_info['directory'].'/chat_files';
  124. }
  125. $chat_path = $document_path.$basepath_chat.'/';
  126. if (!is_dir($chat_path)) {
  127. if (is_file($chat_path)) {
  128. @unlink($chat_path);
  129. }
  130. }
  131. $date_now = date('Y-m-d');
  132. $timeNow = date('d/m/y H:i:s');
  133. $basename_chat = 'messages-'.$date_now;
  134. if ($this->groupId && !$friendId) {
  135. $basename_chat = 'messages-'.$date_now.'_gid-'.$this->groupId;
  136. } elseif ($this->sessionId && !$friendId) {
  137. $basename_chat = 'messages-'.$date_now.'_sid-'.$this->sessionId;
  138. } elseif ($friendId) {
  139. if ($this->userId < $friendId) {
  140. $basename_chat = 'messages-'.$date_now.'_uid-'.$this->userId.'-'.$friendId;
  141. } else {
  142. $basename_chat = 'messages-'.$date_now.'_uid-'.$friendId.'-'.$this->userId;
  143. }
  144. }
  145. $message = self::prepareMessage($message);
  146. $fileTitle = $basename_chat.'.log.html';
  147. $filePath = $basepath_chat.'/'.$fileTitle;
  148. $absoluteFilePath = $chat_path.$fileTitle;
  149. if (!file_exists($absoluteFilePath)) {
  150. $doc_id = add_document($courseInfo, $filePath, 'file', 0, $fileTitle);
  151. $documentLogTypes = ['DocumentAdded', 'invisible'];
  152. foreach ($documentLogTypes as $logType) {
  153. api_item_property_update(
  154. $courseInfo,
  155. TOOL_DOCUMENT,
  156. $doc_id,
  157. $logType,
  158. $this->userId,
  159. $group_info,
  160. null,
  161. null,
  162. null,
  163. $this->sessionId
  164. );
  165. }
  166. item_property_update_on_folder($courseInfo, $basepath_chat, $this->userId);
  167. } else {
  168. $doc_id = DocumentManager::get_document_id($courseInfo, $filePath);
  169. }
  170. $fp = fopen($absoluteFilePath, 'a');
  171. $userPhoto = UserManager::getUserPicture($this->userId, USER_IMAGE_SIZE_MEDIUM);
  172. if ($isMaster) {
  173. $fileContent = '
  174. <div class="message-teacher">
  175. <div class="content-message">
  176. <div class="chat-message-block-name">' . $user->getCompleteName().'</div>
  177. <div class="chat-message-block-content">' . $message.'</div>
  178. <div class="message-date">' . $timeNow.'</div>
  179. </div>
  180. <div class="icon-message"></div>
  181. <img class="chat-image" src="' . $userPhoto.'">
  182. </div>
  183. ';
  184. } else {
  185. $fileContent = '
  186. <div class="message-student">
  187. <img class="chat-image" src="' . $userPhoto.'">
  188. <div class="icon-message"></div>
  189. <div class="content-message">
  190. <div class="chat-message-block-name">' . $user->getCompleteName().'</div>
  191. <div class="chat-message-block-content">' . $message.'</div>
  192. <div class="message-date">' . $timeNow.'</div>
  193. </div>
  194. </div>
  195. ';
  196. }
  197. fputs($fp, $fileContent);
  198. fclose($fp);
  199. $chat_size = filesize($absoluteFilePath);
  200. update_existing_document($courseInfo, $doc_id, $chat_size);
  201. item_property_update_on_folder($courseInfo, $basepath_chat, $this->userId);
  202. return true;
  203. }
  204. /**
  205. * Disconnect a user from course chats
  206. * @param $userId
  207. */
  208. public static function exitChat($userId)
  209. {
  210. $listCourse = CourseManager::get_courses_list_by_user_id($userId);
  211. foreach ($listCourse as $course) {
  212. Database::getManager()
  213. ->createQuery('
  214. DELETE FROM ChamiloCourseBundle:CChatConnected ccc
  215. WHERE ccc.cId = :course AND ccc.userId = :user
  216. ')
  217. ->execute([
  218. 'course' => intval($course['real_id']),
  219. 'user' => intval($userId)
  220. ]);
  221. }
  222. }
  223. /**
  224. * Disconnect users who are more than 5 seconds inactive
  225. */
  226. public function disconnectInactiveUsers()
  227. {
  228. $em = Database::getManager();
  229. $extraCondition = "AND ccc.toGroupId = {$this->groupId}";
  230. if (empty($this->groupId)) {
  231. $extraCondition = "AND ccc.sessionId = {$this->sessionId}";
  232. }
  233. $connectedUsers = $em
  234. ->createQuery("
  235. SELECT ccc FROM ChamiloCourseBundle:CChatConnected ccc
  236. WHERE ccc.cId = :course $extraCondition
  237. ")
  238. ->setParameter('course', $this->courseId)
  239. ->getResult();
  240. $now = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
  241. $cd_count_time_seconds = $now->getTimestamp();
  242. foreach ($connectedUsers as $connection) {
  243. $date_count_time_seconds = $connection->getLastConnection()->getTimestamp();
  244. if (strcmp($now->format('Y-m-d'), $connection->getLastConnection()->format('Y-m-d')) !== 0) {
  245. continue;
  246. }
  247. if (($cd_count_time_seconds - $date_count_time_seconds) <= 5) {
  248. continue;
  249. }
  250. $em
  251. ->createQuery('
  252. DELETE FROM ChamiloCourseBundle:CChatConnected ccc
  253. WHERE ccc.cId = :course AND ccc.userId = :user AND ccc.toGroupId = :group
  254. ')
  255. ->execute([
  256. 'course' => $this->courseId,
  257. 'user' => $connection->getUserId(),
  258. 'group' => $this->groupId
  259. ]);
  260. }
  261. }
  262. /**
  263. * Keep registered to a user as connected
  264. * @throws \Doctrine\ORM\NonUniqueResultException
  265. */
  266. public function keepUserAsConnected()
  267. {
  268. $em = Database::getManager();
  269. $extraCondition = null;
  270. if ($this->groupId) {
  271. $extraCondition = 'AND ccc.toGroupId = '.intval($this->groupId);
  272. } else {
  273. $extraCondition = 'AND ccc.sessionId = '.intval($this->sessionId);
  274. }
  275. $currentTime = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
  276. $connection = $em
  277. ->createQuery("
  278. SELECT ccc FROM ChamiloCourseBundle:CChatConnected ccc
  279. WHERE ccc.userId = :user AND ccc.cId = :course $extraCondition
  280. ")
  281. ->setParameters([
  282. 'user' => $this->userId,
  283. 'course' => $this->courseId
  284. ])
  285. ->getOneOrNullResult();
  286. if ($connection) {
  287. $connection->setLastConnection($currentTime);
  288. $em->merge($connection);
  289. $em->flush();
  290. return;
  291. }
  292. $connection = new CChatConnected();
  293. $connection
  294. ->setCId($this->courseId)
  295. ->setUserId($this->userId)
  296. ->setLastConnection($currentTime)
  297. ->setSessionId($this->sessionId)
  298. ->setToGroupId($this->groupId);
  299. $em->persist($connection);
  300. $em->flush();
  301. }
  302. /**
  303. * Get the emoji allowed on course chat
  304. * @return array
  305. */
  306. public static function getEmojiStrategy()
  307. {
  308. return require_once api_get_path(SYS_CODE_PATH).'chat/emoji_strategy.php';
  309. }
  310. /**
  311. * Get the emoji list to include in chat
  312. * @return array
  313. */
  314. public static function getEmojisToInclude()
  315. {
  316. return [
  317. ':bowtie:',
  318. ':smile:' |
  319. ':laughing:',
  320. ':blush:',
  321. ':smiley:',
  322. ':relaxed:',
  323. ':smirk:',
  324. ':heart_eyes:',
  325. ':kissing_heart:',
  326. ':kissing_closed_eyes:',
  327. ':flushed:',
  328. ':relieved:',
  329. ':satisfied:',
  330. ':grin:',
  331. ':wink:',
  332. ':stuck_out_tongue_winking_eye:',
  333. ':stuck_out_tongue_closed_eyes:',
  334. ':grinning:',
  335. ':kissing:',
  336. ':kissing_smiling_eyes:',
  337. ':stuck_out_tongue:',
  338. ':sleeping:',
  339. ':worried:',
  340. ':frowning:',
  341. ':anguished:',
  342. ':open_mouth:',
  343. ':grimacing:',
  344. ':confused:',
  345. ':hushed:',
  346. ':expressionless:',
  347. ':unamused:',
  348. ':sweat_smile:',
  349. ':sweat:',
  350. ':disappointed_relieved:',
  351. ':weary:',
  352. ':pensive:',
  353. ':disappointed:',
  354. ':confounded:',
  355. ':fearful:',
  356. ':cold_sweat:',
  357. ':persevere:',
  358. ':cry:',
  359. ':sob:',
  360. ':joy:',
  361. ':astonished:',
  362. ':scream:',
  363. ':neckbeard:',
  364. ':tired_face:',
  365. ':angry:',
  366. ':rage:',
  367. ':triumph:',
  368. ':sleepy:',
  369. ':yum:',
  370. ':mask:',
  371. ':sunglasses:',
  372. ':dizzy_face:',
  373. ':imp:',
  374. ':smiling_imp:',
  375. ':neutral_face:',
  376. ':no_mouth:',
  377. ':innocent:',
  378. ':alien:'
  379. ];
  380. }
  381. /**
  382. * Get the chat history file name
  383. * @param bool $absolute Optional. Whether get the base or the absolute file path
  384. * @param int $friendId Optional.
  385. * @return string
  386. */
  387. public function getFileName($absolute = false, $friendId = 0)
  388. {
  389. $date = date('Y-m-d');
  390. $base = 'messages-'.$date.'.log.html';
  391. if ($this->groupId && !$friendId) {
  392. $base = 'messages-'.$date.'_gid-'.$this->groupId.'.log.html';
  393. } elseif ($this->sessionId && !$friendId) {
  394. $base = 'messages-'.$date.'_sid-'.$this->sessionId.'.log.html';
  395. } elseif ($friendId) {
  396. if ($this->userId < $friendId) {
  397. $base = 'messages-'.$date.'_uid-'.$this->userId.'-'.$friendId.'.log.html';
  398. } else {
  399. $base = 'messages-'.$date.'_uid-'.$friendId.'-'.$this->userId.'.log.html';
  400. }
  401. }
  402. if (!$absolute) {
  403. return $base;
  404. }
  405. $courseInfo = api_get_course_info_by_id($this->courseId);
  406. $document_path = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document';
  407. $chatPath = $document_path.'/chat_files/';
  408. if ($this->groupId) {
  409. $group_info = GroupManager::get_group_properties($this->groupId);
  410. $chatPath = $document_path.$group_info['directory'].'/chat_files/';
  411. }
  412. return $chatPath.$base;
  413. }
  414. /**
  415. * Get the chat history
  416. * @param bool $reset
  417. * @param int $friendId Optional.
  418. * @return string
  419. */
  420. public function readMessages($reset = false, $friendId = 0)
  421. {
  422. $courseInfo = api_get_course_info_by_id($this->courseId);
  423. $date_now = date('Y-m-d');
  424. $isMaster = (bool) api_is_course_admin();
  425. $basepath_chat = '/chat_files';
  426. $document_path = api_get_path(SYS_COURSE_PATH).$courseInfo['path'].'/document';
  427. $group_info = [];
  428. if ($this->groupId) {
  429. $group_info = GroupManager:: get_group_properties($this->groupId);
  430. $basepath_chat = $group_info['directory'].'/chat_files';
  431. }
  432. $chat_path = $document_path.$basepath_chat.'/';
  433. if (!is_dir($chat_path)) {
  434. if (is_file($chat_path)) {
  435. @unlink($chat_path);
  436. }
  437. if (!api_is_anonymous()) {
  438. @mkdir($chat_path, api_get_permissions_for_new_directories());
  439. // Save chat files document for group into item property
  440. if ($this->groupId) {
  441. $doc_id = add_document($courseInfo, $basepath_chat, 'folder', 0, 'chat_files');
  442. api_item_property_update(
  443. $courseInfo,
  444. TOOL_DOCUMENT,
  445. $doc_id,
  446. 'FolderCreated',
  447. null,
  448. $group_info,
  449. null,
  450. null,
  451. null
  452. );
  453. }
  454. }
  455. }
  456. $filename_chat = 'messages-'.$date_now.'.log.html';
  457. if ($this->groupId && !$friendId) {
  458. $filename_chat = 'messages-'.$date_now.'_gid-'.$this->groupId.'.log.html';
  459. } elseif ($this->sessionId && !$friendId) {
  460. $filename_chat = 'messages-'.$date_now.'_sid-'.$this->sessionId.'.log.html';
  461. } elseif ($friendId) {
  462. if ($this->userId < $friendId) {
  463. $filename_chat = 'messages-'.$date_now.'_uid-'.$this->userId.'-'.$friendId.'.log.html';
  464. } else {
  465. $filename_chat = 'messages-'.$date_now.'_uid-'.$friendId.'-'.$this->userId.'.log.html';
  466. }
  467. }
  468. if (!file_exists($chat_path.$filename_chat)) {
  469. @fclose(fopen($chat_path.$filename_chat, 'w'));
  470. if (!api_is_anonymous()) {
  471. $doc_id = add_document($courseInfo, $basepath_chat.'/'.$filename_chat, 'file', 0, $filename_chat);
  472. api_item_property_update(
  473. $courseInfo,
  474. TOOL_DOCUMENT,
  475. $doc_id,
  476. 'DocumentAdded',
  477. $this->userId,
  478. $group_info,
  479. null,
  480. null,
  481. null,
  482. $this->sessionId
  483. );
  484. api_item_property_update(
  485. $courseInfo,
  486. TOOL_DOCUMENT,
  487. $doc_id,
  488. 'invisible',
  489. $this->userId,
  490. $group_info,
  491. null,
  492. null,
  493. null,
  494. $this->sessionId
  495. );
  496. item_property_update_on_folder($courseInfo, $basepath_chat, $this->userId);
  497. }
  498. }
  499. $basename_chat = 'messages-'.$date_now;
  500. if ($this->groupId && !$friendId) {
  501. $basename_chat = 'messages-'.$date_now.'_gid-'.$this->groupId;
  502. } elseif ($this->sessionId && !$friendId) {
  503. $basename_chat = 'messages-'.$date_now.'_sid-'.$this->sessionId;
  504. } elseif ($friendId) {
  505. if ($this->userId < $friendId) {
  506. $basename_chat = 'messages-'.$date_now.'_uid-'.$this->userId.'-'.$friendId;
  507. } else {
  508. $basename_chat = 'messages-'.$date_now.'_uid-'.$friendId.'-'.$this->userId;
  509. }
  510. }
  511. if ($reset && $isMaster) {
  512. $i = 1;
  513. while (file_exists($chat_path.$basename_chat.'-'.$i.'.log.html')) {
  514. $i++;
  515. }
  516. @rename($chat_path.$basename_chat.'.log.html', $chat_path.$basename_chat.'-'.$i.'.log.html');
  517. @fclose(fopen($chat_path.$basename_chat.'.log.html', 'w'));
  518. $doc_id = add_document(
  519. $courseInfo,
  520. $basepath_chat.'/'.$basename_chat.'-'.$i.'.log.html',
  521. 'file',
  522. filesize($chat_path.$basename_chat.'-'.$i.'.log.html'),
  523. $basename_chat.'-'.$i.'.log.html'
  524. );
  525. api_item_property_update(
  526. $courseInfo,
  527. TOOL_DOCUMENT,
  528. $doc_id,
  529. 'DocumentAdded',
  530. $this->userId,
  531. $group_info,
  532. null,
  533. null,
  534. null,
  535. $this->sessionId
  536. );
  537. api_item_property_update(
  538. $courseInfo,
  539. TOOL_DOCUMENT,
  540. $doc_id,
  541. 'invisible',
  542. $this->userId,
  543. $group_info,
  544. null,
  545. null,
  546. null,
  547. $this->sessionId
  548. );
  549. item_property_update_on_folder($courseInfo, $basepath_chat, $this->userId);
  550. $doc_id = DocumentManager::get_document_id(
  551. $courseInfo,
  552. $basepath_chat.'/'.$basename_chat.'.log.html'
  553. );
  554. update_existing_document($courseInfo, $doc_id, 0);
  555. }
  556. $remove = 0;
  557. $content = [];
  558. if (file_exists($chat_path.$basename_chat.'.log.html')) {
  559. $content = file($chat_path.$basename_chat.'.log.html');
  560. $nbr_lines = sizeof($content);
  561. $remove = $nbr_lines - 100;
  562. }
  563. if ($remove < 0) {
  564. $remove = 0;
  565. }
  566. array_splice($content, 0, $remove);
  567. if (isset($_GET['origin']) && $_GET['origin'] == 'whoisonline') {
  568. //the caller
  569. $content[0] = get_lang('CallSent').'<br />'.$content[0];
  570. }
  571. $history = '<div id="content-chat">';
  572. foreach ($content as $this_line) {
  573. $history .= $this_line;
  574. }
  575. $history .= '</div>';
  576. if ($isMaster || $GLOBALS['is_session_general_coach']) {
  577. $history .= '
  578. <div id="clear-chat">
  579. <button type="button" id="chat-reset" class="btn btn-danger btn-sm">
  580. ' . get_lang('ClearList').'
  581. </button>
  582. </div>
  583. ';
  584. }
  585. return $history;
  586. }
  587. /**
  588. * Get the number of users connected in chat
  589. * @return mixed
  590. */
  591. public function countUsersOnline()
  592. {
  593. $date = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
  594. $date->modify('-5 seconds');
  595. $extraCondition = null;
  596. if ($this->groupId) {
  597. $extraCondition = 'AND ccc.toGroupId = '.intval($this->groupId);
  598. } else {
  599. $extraCondition = 'AND ccc.sessionId = '.intval($this->sessionId);
  600. }
  601. $number = Database::getManager()
  602. ->createQuery("
  603. SELECT COUNT(ccc.userId) FROM ChamiloCourseBundle:CChatConnected ccc
  604. WHERE ccc.lastConnection > :date AND ccc.cId = :course $extraCondition
  605. ")
  606. ->setParameters([
  607. 'date' => $date,
  608. 'course' => $this->courseId
  609. ])
  610. ->getSingleScalarResult();
  611. return intval($number);
  612. }
  613. /**
  614. * Check if a user is connected in course chat
  615. * @param int $userId
  616. * @return int
  617. */
  618. private function userIsConnected($userId)
  619. {
  620. $date = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
  621. $date->modify('-5 seconds');
  622. $extraCondition = null;
  623. if ($this->groupId) {
  624. $extraCondition = 'AND ccc.toGroupId = '.intval($this->groupId);
  625. } else {
  626. $extraCondition = 'AND ccc.sessionId = '.intval($this->sessionId);
  627. }
  628. $number = Database::getManager()
  629. ->createQuery("
  630. SELECT COUNT(ccc.userId) FROM ChamiloCourseBundle:CChatConnected ccc
  631. WHERE ccc.lastConnection > :date AND ccc.cId = :course AND ccc.userId = :user $extraCondition
  632. ")
  633. ->setParameters([
  634. 'date' => $date,
  635. 'course' => $this->courseId,
  636. 'user' => $userId
  637. ])
  638. ->getSingleScalarResult();
  639. return intval($number);
  640. }
  641. /**
  642. * Get the users online data
  643. * @return string
  644. */
  645. public function listUsersOnline()
  646. {
  647. $subscriptions = $this->getUsersSubscriptions();
  648. $usersInfo = [];
  649. foreach ($subscriptions as $subscription) {
  650. $user = $subscription->getUser();
  651. $usersInfo[] = [
  652. 'id' => $user->getId(),
  653. 'firstname' => $user->getFirstname(),
  654. 'lastname' => $user->getLastname(),
  655. 'status' => !$this->sessionId ? $subscription->getStatus() : $user->getStatus(),
  656. 'image_url' => UserManager::getUserPicture($user->getId(), USER_IMAGE_SIZE_MEDIUM),
  657. 'profile_url' => api_get_path(WEB_CODE_PATH).'social/profile.php?u='.$user->getId(),
  658. 'complete_name' => $user->getCompleteName(),
  659. 'username' => $user->getUsername(),
  660. 'email' => $user->getEmail(),
  661. 'isConnected' => $this->userIsConnected($user->getId())
  662. ];
  663. }
  664. return $usersInfo;
  665. }
  666. }