AnnouncementEmail.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Announcement Email.
  5. *
  6. * @author Laurent Opprecht <laurent@opprecht.info> for the Univesity of Geneva
  7. * @author Julio Montoya <gugli100@gmail.com> Adding session support
  8. */
  9. class AnnouncementEmail
  10. {
  11. public $session_id = null;
  12. public $logger;
  13. protected $course = null;
  14. protected $announcement = null;
  15. /**
  16. * @param array $courseInfo
  17. * @param int $sessionId
  18. * @param int $announcementId
  19. * @param \Monolog\Logger $logger
  20. */
  21. public function __construct($courseInfo, $sessionId, $announcementId, $logger = null)
  22. {
  23. if (empty($courseInfo)) {
  24. $courseInfo = api_get_course_info();
  25. }
  26. $this->course = $courseInfo;
  27. $this->session_id = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
  28. if (is_numeric($announcementId)) {
  29. $this->announcement = AnnouncementManager::get_by_id($courseInfo['real_id'], $announcementId);
  30. }
  31. $this->logger = $logger;
  32. }
  33. /**
  34. * Course info.
  35. *
  36. * @param string $key
  37. *
  38. * @return string|null
  39. */
  40. public function course($key = '')
  41. {
  42. $result = $key ? $this->course[$key] : $this->course;
  43. $result = $key == 'id' ? intval($result) : $result;
  44. return $result;
  45. }
  46. /**
  47. * Announcement info.
  48. *
  49. * @param string $key
  50. *
  51. * @return array
  52. */
  53. public function announcement($key = '')
  54. {
  55. $result = $key ? $this->announcement[$key] : $this->announcement;
  56. $result = $key == 'id' ? intval($result) : $result;
  57. return $result;
  58. }
  59. /**
  60. * Returns either all course users or all session users depending on whether
  61. * session is turned on or not.
  62. *
  63. * @return array
  64. */
  65. public function all_users()
  66. {
  67. $courseCode = $this->course('code');
  68. if (empty($this->session_id)) {
  69. $group_id = api_get_group_id();
  70. if (empty($group_id)) {
  71. $userList = CourseManager::get_user_list_from_course_code($courseCode);
  72. } else {
  73. $userList = GroupManager::get_users($group_id);
  74. $new_user_list = [];
  75. foreach ($userList as $user) {
  76. $new_user_list[] = ['user_id' => $user];
  77. }
  78. $userList = $new_user_list;
  79. }
  80. } else {
  81. $userList = CourseManager::get_user_list_from_course_code(
  82. $courseCode,
  83. $this->session_id
  84. );
  85. }
  86. return $userList;
  87. }
  88. /**
  89. * Returns users and groups an announcement item has been sent to.
  90. *
  91. * @return array Array of users and groups to whom the element has been sent
  92. */
  93. public function sent_to_info()
  94. {
  95. $result = [];
  96. $result['groups'] = [];
  97. $result['users'] = [];
  98. $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  99. $tool = TOOL_ANNOUNCEMENT;
  100. $id = $this->announcement('id');
  101. $course_id = $this->course('real_id');
  102. $sessionCondition = api_get_session_condition($this->session_id);
  103. $sql = "SELECT to_group_id, to_user_id
  104. FROM $table
  105. WHERE
  106. c_id = $course_id AND
  107. tool = '$tool' AND
  108. ref = $id
  109. $sessionCondition";
  110. $rs = Database::query($sql);
  111. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  112. // if to_user_id <> 0 then it is sent to a specific user
  113. $user_id = $row['to_user_id'];
  114. if (!empty($user_id)) {
  115. $result['users'][] = (int) $user_id;
  116. // If user is set then skip the group
  117. continue;
  118. }
  119. // if to_group_id is null then it is sent to a specific user
  120. // if to_group_id = 0 then it is sent to everybody
  121. $group_id = $row['to_group_id'];
  122. if (!empty($group_id)) {
  123. $result['groups'][] = (int) $group_id;
  124. }
  125. }
  126. return $result;
  127. }
  128. /**
  129. * Returns the list of user info to which an announcement was sent.
  130. * This function returns a list of actual users even when recipient
  131. * are groups.
  132. *
  133. * @return array
  134. */
  135. public function sent_to()
  136. {
  137. $sent_to = $this->sent_to_info();
  138. $users = $sent_to['users'];
  139. $users = $users ? $users : [];
  140. $groups = $sent_to['groups'];
  141. if ($users) {
  142. $users = UserManager::get_user_list_by_ids($users, true);
  143. }
  144. if (!empty($groups)) {
  145. $groupUsers = GroupManager::get_groups_users($groups);
  146. $groupUsers = UserManager::get_user_list_by_ids($groupUsers, true);
  147. if (!empty($groupUsers)) {
  148. $users = array_merge($users, $groupUsers);
  149. }
  150. }
  151. if (empty($users)) {
  152. if (!empty($this->logger)) {
  153. $this->logger->addInfo('User list is empty. No users found. Trying all_users()');
  154. }
  155. $users = self::all_users();
  156. }
  157. // Clean users just in case
  158. $newListUsers = [];
  159. if (!empty($users)) {
  160. foreach ($users as $user) {
  161. $newListUsers[$user['user_id']] = ['user_id' => $user['user_id']];
  162. }
  163. }
  164. return $newListUsers;
  165. }
  166. /**
  167. * Email subject.
  168. *
  169. * @return string
  170. */
  171. public function subject()
  172. {
  173. $result = $this->course('title').' - '.$this->announcement('title');
  174. $result = stripslashes($result);
  175. return $result;
  176. }
  177. /**
  178. * Email message.
  179. *
  180. * @param int $receiverUserId
  181. *
  182. * @return string
  183. */
  184. public function message($receiverUserId)
  185. {
  186. $content = $this->announcement('content');
  187. $session_id = $this->session_id;
  188. $courseCode = $this->course('code');
  189. $content = AnnouncementManager::parseContent(
  190. $receiverUserId,
  191. $content,
  192. $courseCode,
  193. $session_id
  194. );
  195. // Build the link by hand because api_get_cidreq() doesn't accept course params
  196. $course_param = 'cidReq='.$courseCode.'&id_session='.$session_id.'&gidReq='.api_get_group_id();
  197. $course_name = $this->course('title');
  198. $result = "<div>$content</div>";
  199. // Adding attachment
  200. $attachment = $this->attachment();
  201. if (!empty($attachment)) {
  202. $result .= '<br />';
  203. $result .= Display::url(
  204. $attachment['filename'],
  205. api_get_path(WEB_CODE_PATH).'announcements/download.php?file='.basename($attachment['path']).'&'.$course_param
  206. );
  207. $result .= '<br />';
  208. }
  209. $result .= '<hr />';
  210. $userInfo = api_get_user_info();
  211. if (!empty($userInfo)) {
  212. $result .= '<a href="mailto:'.$userInfo['mail'].'">'.$userInfo['complete_name'].'</a><br/>';
  213. }
  214. $result .= '<a href="'.api_get_path(WEB_CODE_PATH).'announcements/announcements.php?'.$course_param.'">'.$course_name.'</a><br/>';
  215. return $result;
  216. }
  217. /**
  218. * Returns the one file that can be attached to an announcement.
  219. *
  220. * @return array
  221. */
  222. public function attachment()
  223. {
  224. $result = [];
  225. $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
  226. $id = $this->announcement('id');
  227. $course_id = $this->course('real_id');
  228. $sql = "SELECT * FROM $table
  229. WHERE c_id = $course_id AND announcement_id = $id ";
  230. $rs = Database::query($sql);
  231. $course_path = $this->course('directory');
  232. while ($row = Database::fetch_array($rs)) {
  233. $path = api_get_path(SYS_COURSE_PATH).$course_path.'/upload/announcements/'.$row['path'];
  234. $filename = $row['filename'];
  235. $result[] = ['path' => $path, 'filename' => $filename];
  236. }
  237. $result = $result ? reset($result) : [];
  238. return $result;
  239. }
  240. /**
  241. * Send announcement by email to myself.
  242. */
  243. public function sendAnnouncementEmailToMySelf()
  244. {
  245. $userId = api_get_user_id();
  246. $subject = $this->subject();
  247. $message = $this->message($userId);
  248. MessageManager::send_message_simple(
  249. $userId,
  250. $subject,
  251. $message,
  252. api_get_user_id(),
  253. false,
  254. true
  255. );
  256. }
  257. /**
  258. * Send emails to users.
  259. *
  260. * @param bool $sendToUsersInSession
  261. * @param bool $sendToDrhUsers send a copy of the message to the DRH users
  262. * @param int $senderId related to the main user
  263. *
  264. * @return array
  265. */
  266. public function send($sendToUsersInSession = false, $sendToDrhUsers = false, $senderId = 0)
  267. {
  268. $senderId = empty($senderId) ? api_get_user_id() : (int) $senderId;
  269. $subject = $this->subject();
  270. // Send email one by one to avoid antispam
  271. $users = $this->sent_to();
  272. $batchSize = 20;
  273. $counter = 1;
  274. $em = Database::getManager();
  275. if (empty($users) && !empty($this->logger)) {
  276. $this->logger->addInfo('User list is empty. No emails will be sent.');
  277. }
  278. $messageSentTo = [];
  279. foreach ($users as $user) {
  280. $message = $this->message($user['user_id']);
  281. $wasSent = MessageManager::messageWasAlreadySent($senderId, $user['user_id'], $subject, $message);
  282. if ($wasSent === false) {
  283. if (!empty($this->logger)) {
  284. $this->logger->addInfo(
  285. 'Announcement: #'.$this->announcement('id').'. Send email to user: #'.$user['user_id']
  286. );
  287. }
  288. $messageSentTo[] = $user['user_id'];
  289. MessageManager::send_message_simple(
  290. $user['user_id'],
  291. $subject,
  292. $message,
  293. $senderId,
  294. $sendToDrhUsers,
  295. true
  296. );
  297. } else {
  298. if (!empty($this->logger)) {
  299. $this->logger->addInfo(
  300. 'Message "'.$subject.'" was already sent. Announcement: #'.$this->announcement('id').'.
  301. User: #'.$user['user_id']
  302. );
  303. }
  304. }
  305. if (($counter % $batchSize) === 0) {
  306. $em->flush();
  307. $em->clear();
  308. }
  309. $counter++;
  310. }
  311. if ($sendToUsersInSession) {
  312. $sessionList = SessionManager::get_session_by_course($this->course['real_id']);
  313. if (!empty($sessionList)) {
  314. foreach ($sessionList as $sessionInfo) {
  315. $sessionId = $sessionInfo['id'];
  316. $message = $this->message(null);
  317. $userList = CourseManager::get_user_list_from_course_code(
  318. $this->course['code'],
  319. $sessionId
  320. );
  321. if (!empty($userList)) {
  322. foreach ($userList as $user) {
  323. $messageSentTo[] = $user['user_id'];
  324. MessageManager::send_message_simple(
  325. $user['user_id'],
  326. $subject,
  327. $message,
  328. $senderId,
  329. false,
  330. true
  331. );
  332. }
  333. }
  334. }
  335. }
  336. }
  337. $this->logMailSent();
  338. $messageSentTo = array_unique($messageSentTo);
  339. return $messageSentTo;
  340. }
  341. /**
  342. * Store that emails where sent.
  343. */
  344. public function logMailSent()
  345. {
  346. $id = $this->announcement('id');
  347. $courseId = $this->course('real_id');
  348. $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
  349. $sql = "UPDATE $table SET
  350. email_sent = 1
  351. WHERE
  352. c_id = $courseId AND
  353. id = $id AND
  354. session_id = {$this->session_id}
  355. ";
  356. Database::query($sql);
  357. }
  358. }