EmbedRegistryPlugin.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\Course;
  4. use Chamilo\CoreBundle\Entity\Session;
  5. use Chamilo\PluginBundle\Entity\EmbedRegistry\Embed;
  6. use Symfony\Component\Filesystem\Filesystem;
  7. /**
  8. * Class EmbedRegistryPlugin.
  9. */
  10. class EmbedRegistryPlugin extends Plugin
  11. {
  12. const SETTING_ENABLED = 'tool_enabled';
  13. const SETTING_TITLE = 'tool_title';
  14. const SETTING_EXTERNAL_URL = 'external_url';
  15. const TBL_EMBED = 'plugin_embed_registry_embed';
  16. /**
  17. * EmbedRegistryPlugin constructor.
  18. */
  19. protected function __construct()
  20. {
  21. $authors = [
  22. 'Angel Fernando Quiroz Campos',
  23. ];
  24. parent::__construct(
  25. '1.0',
  26. implode(', ', $authors),
  27. [
  28. self::SETTING_ENABLED => 'boolean',
  29. self::SETTING_TITLE => 'text',
  30. self::SETTING_EXTERNAL_URL => 'text',
  31. ]
  32. );
  33. }
  34. /**
  35. * @return string
  36. */
  37. public function getToolTitle()
  38. {
  39. $title = $this->get(self::SETTING_TITLE);
  40. if (!empty($title)) {
  41. return $title;
  42. }
  43. return $this->get_title();
  44. }
  45. /**
  46. * @return EmbedRegistryPlugin|null
  47. */
  48. public static function create()
  49. {
  50. static $result = null;
  51. return $result ? $result : $result = new self();
  52. }
  53. public function install()
  54. {
  55. $entityPath = $this->getEntityPath();
  56. if (!is_dir($entityPath)) {
  57. if (!is_writable(dirname($entityPath))) {
  58. Display::addFlash(
  59. Display::return_message(
  60. get_lang('ErrorCreatingDir').' '.$entityPath,
  61. 'error'
  62. )
  63. );
  64. return false;
  65. }
  66. mkdir($entityPath, api_get_permissions_for_new_directories());
  67. }
  68. $fs = new Filesystem();
  69. $fs->mirror(__DIR__.'/Entity/', $entityPath, null, ['override']);
  70. $this->createPluginTables();
  71. }
  72. public function uninstall()
  73. {
  74. $entityPath = $this->getEntityPath();
  75. $fs = new Filesystem();
  76. if ($fs->exists($entityPath)) {
  77. $fs->remove($entityPath);
  78. }
  79. Database::query('DROP TABLE IF EXISTS '.self::TBL_EMBED);
  80. }
  81. /**
  82. * @return EmbedRegistryPlugin
  83. */
  84. public function performActionsAfterConfigure()
  85. {
  86. $em = Database::getManager();
  87. $this->deleteCourseToolLinks();
  88. if ('true' === $this->get(self::SETTING_ENABLED)) {
  89. $courses = $em->createQuery('SELECT c.id FROM ChamiloCoreBundle:Course c')->getResult();
  90. foreach ($courses as $course) {
  91. $this->createLinkToCourseTool($this->getToolTitle(), $course['id']);
  92. }
  93. }
  94. return $this;
  95. }
  96. /**
  97. * @param int $courseId
  98. */
  99. public function doWhenDeletingCourse($courseId)
  100. {
  101. Database::getManager()
  102. ->createQuery('DELETE FROM ChamiloPluginBundle:EmbedRegistry\Embed e WHERE e.course = :course')
  103. ->execute(['course' => (int) $courseId]);
  104. }
  105. /**
  106. * @param int $sessionId
  107. */
  108. public function doWhenDeletingSession($sessionId)
  109. {
  110. Database::getManager()
  111. ->createQuery('DELETE FROM ChamiloPluginBundle:EmbedRegistry\Embed e WHERE e.session = :session')
  112. ->execute(['session' => (int) $sessionId]);
  113. }
  114. /**
  115. * @param Course $course
  116. * @param Session|null $session
  117. *
  118. * @throws \Doctrine\ORM\NonUniqueResultException
  119. *
  120. * @return Embed
  121. */
  122. public function getCurrentEmbed(Course $course, Session $session = null)
  123. {
  124. $embedRepo = Database::getManager()->getRepository('ChamiloPluginBundle:EmbedRegistry\Embed');
  125. $qb = $embedRepo->createQueryBuilder('e');
  126. $query = $qb
  127. ->where('e.displayStartDate <= :now')
  128. ->andWhere('e.displayEndDate >= :now')
  129. ->andWhere(
  130. $qb->expr()->eq('e.course', $course->getId())
  131. );
  132. $query->andWhere(
  133. $session
  134. ? $qb->expr()->eq('e.session', $session->getId())
  135. : $qb->expr()->isNull('e.session')
  136. );
  137. $query = $query
  138. ->orderBy('e.displayStartDate', 'DESC')
  139. ->setMaxResults(1)
  140. ->setParameters(['now' => api_get_utc_datetime(null, false, true)])
  141. ->getQuery();
  142. return $query->getOneOrNullResult();
  143. }
  144. /**
  145. * @param Embed $embed
  146. *
  147. * @return string
  148. */
  149. public function formatDisplayDate(Embed $embed)
  150. {
  151. $startDate = sprintf(
  152. '<time datetime="%s">%s</time>',
  153. $embed->getDisplayStartDate()->format(DateTime::W3C),
  154. api_convert_and_format_date($embed->getDisplayStartDate())
  155. );
  156. $endDate = sprintf(
  157. '<time datetime="%s">%s</time>',
  158. $embed->getDisplayEndDate()->format(DateTime::W3C),
  159. api_convert_and_format_date($embed->getDisplayEndDate())
  160. );
  161. return sprintf(get_lang('FromDateXToDateY'), $startDate, $endDate);
  162. }
  163. /**
  164. * @param Embed $embed
  165. *
  166. * @return string
  167. */
  168. public function getViewUrl(Embed $embed)
  169. {
  170. return api_get_path(WEB_PLUGIN_PATH).'embedregistry/view.php?id='.$embed->getId().'&'.api_get_cidreq();
  171. }
  172. /**
  173. * @param Embed $embed
  174. *
  175. * @throws \Doctrine\ORM\Query\QueryException
  176. *
  177. * @return int
  178. */
  179. public function getMembersCount(Embed $embed)
  180. {
  181. $dql = 'SELECT COUNT(DISTINCT tea.accessUserId) FROM ChamiloCoreBundle:TrackEAccess tea
  182. WHERE
  183. tea.accessTool = :tool AND
  184. (tea.accessDate >= :start_date AND tea.accessDate <= :end_date) AND
  185. tea.cId = :course';
  186. $params = [
  187. 'tool' => 'plugin_'.$this->get_name(),
  188. 'start_date' => $embed->getDisplayStartDate(),
  189. 'end_date' => $embed->getDisplayEndDate(),
  190. 'course' => $embed->getCourse(),
  191. ];
  192. if ($embed->getSession()) {
  193. $dql .= ' AND tea.accessSessionId = :session ';
  194. $params['session'] = $embed->getSession();
  195. }
  196. $count = Database::getManager()
  197. ->createQuery($dql)
  198. ->setParameters($params)
  199. ->getSingleScalarResult();
  200. return $count;
  201. }
  202. public function saveEventAccessTool()
  203. {
  204. $tableAccess = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ACCESS);
  205. $params = [
  206. 'access_user_id' => api_get_user_id(),
  207. 'c_id' => api_get_course_int_id(),
  208. 'access_tool' => 'plugin_'.$this->get_name(),
  209. 'access_date' => api_get_utc_datetime(),
  210. 'access_session_id' => api_get_session_id(),
  211. 'user_ip' => api_get_real_ip(),
  212. ];
  213. Database::insert($tableAccess, $params);
  214. }
  215. private function createPluginTables()
  216. {
  217. $connection = Database::getManager()->getConnection();
  218. if ($connection->getSchemaManager()->tablesExist(self::TBL_EMBED)) {
  219. return;
  220. }
  221. $queries = [
  222. 'CREATE TABLE plugin_embed_registry_embed (id INT AUTO_INCREMENT NOT NULL, c_id INT NOT NULL, session_id INT DEFAULT NULL, title LONGTEXT NOT NULL, display_start_date DATETIME NOT NULL, display_end_date DATETIME NOT NULL, html_code LONGTEXT NOT NULL, INDEX IDX_5236D25991D79BD3 (c_id), INDEX IDX_5236D259613FECDF (session_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB',
  223. 'ALTER TABLE plugin_embed_registry_embed ADD CONSTRAINT FK_5236D25991D79BD3 FOREIGN KEY (c_id) REFERENCES course (id)',
  224. 'ALTER TABLE plugin_embed_registry_embed ADD CONSTRAINT FK_5236D259613FECDF FOREIGN KEY (session_id) REFERENCES session (id)',
  225. ];
  226. foreach ($queries as $query) {
  227. Database::query($query);
  228. }
  229. }
  230. /**
  231. * @return string
  232. */
  233. private function getEntityPath()
  234. {
  235. return api_get_path(SYS_PATH).'src/Chamilo/PluginBundle/Entity/'.$this->getCamelCaseName();
  236. }
  237. private function deleteCourseToolLinks()
  238. {
  239. Database::getManager()
  240. ->createQuery('DELETE FROM ChamiloCourseBundle:CTool t WHERE t.category = :category AND t.link LIKE :link')
  241. ->execute(['category' => 'plugin', 'link' => 'embedregistry/start.php%']);
  242. }
  243. }