system_announcements.lib.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class SystemAnnouncementManager
  5. */
  6. class SystemAnnouncementManager
  7. {
  8. const VISIBLE_GUEST = 'visible_guest';
  9. const VISIBLE_STUDENT = 'visible_student';
  10. const VISIBLE_TEACHER = 'visible_teacher';
  11. // Requires DB change
  12. const VISIBLE_DRH = 'visible_drh';
  13. const VISIBLE_SESSION_ADMIN = 'visible_session_admin';
  14. const VISIBLE_STUDENT_BOSS = 'visible_boss';
  15. /**
  16. * @return array
  17. */
  18. public static function getVisibilityList()
  19. {
  20. $extraRoles = self::newRolesActivated();
  21. $visibleToUsers = [
  22. self::VISIBLE_TEACHER => get_lang('Teacher'),
  23. self::VISIBLE_STUDENT => get_lang('Student'),
  24. self::VISIBLE_GUEST => get_lang('Guest')
  25. ];
  26. if ($extraRoles) {
  27. $visibleToUsers[self::VISIBLE_DRH] = get_lang('DRH');
  28. $visibleToUsers[self::VISIBLE_SESSION_ADMIN] = get_lang('SessionAdministrator');
  29. $visibleToUsers[self::VISIBLE_STUDENT_BOSS] = get_lang('StudentBoss');
  30. }
  31. return $visibleToUsers;
  32. }
  33. /**
  34. * @param string $visibility
  35. * @return string
  36. */
  37. public static function getVisibilityCondition($visibility)
  38. {
  39. $list = self::getVisibilityList();
  40. $visibilityCondition = " AND ".self::VISIBLE_GUEST." = 1 ";
  41. if (in_array($visibility, array_keys($list))) {
  42. $visibilityCondition = " AND $visibility = 1 ";
  43. }
  44. return $visibilityCondition;
  45. }
  46. /**
  47. * Displays all announcements
  48. * @param string $visibility VISIBLE_GUEST, VISIBLE_STUDENT or VISIBLE_TEACHER
  49. * @param int $id The identifier of the announcement to display
  50. */
  51. public static function display_announcements($visibility, $id = -1)
  52. {
  53. $user_selected_language = api_get_interface_language();
  54. $db_table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
  55. $tbl_announcement_group = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
  56. $userGroup = new UserGroup();
  57. $temp_user_groups = $userGroup->get_groups_by_user(api_get_user_id(), 0);
  58. $groups = array();
  59. foreach ($temp_user_groups as $user_group) {
  60. $groups = array_merge($groups, array($user_group['id']));
  61. $groups = array_merge($groups, $userGroup->get_parent_groups($user_group['id']));
  62. }
  63. $groups_string = '('.implode($groups, ',').')';
  64. $now = api_get_utc_datetime();
  65. $sql = "SELECT *, DATE_FORMAT(date_start,'%d-%m-%Y %h:%i:%s') AS display_date
  66. FROM $db_table
  67. WHERE
  68. (lang='$user_selected_language' OR lang IS NULL) AND
  69. (('$now' BETWEEN date_start AND date_end) OR date_end='0000-00-00') ";
  70. $sql .= self::getVisibilityCondition($visibility);
  71. if (count($groups) > 0) {
  72. $sql .= " OR id IN (
  73. SELECT announcement_id FROM $tbl_announcement_group
  74. WHERE group_id in $groups_string
  75. ) ";
  76. }
  77. $current_access_url_id = 1;
  78. if (api_is_multiple_url_enabled()) {
  79. $current_access_url_id = api_get_current_access_url_id();
  80. }
  81. $sql .= " AND access_url_id = '$current_access_url_id' ";
  82. $sql .= " ORDER BY date_start DESC LIMIT 0,7";
  83. $announcements = Database::query($sql);
  84. if (Database::num_rows($announcements) > 0) {
  85. $query_string = ereg_replace('announcement=[1-9]+', '', $_SERVER['QUERY_STRING']);
  86. $query_string = ereg_replace('&$', '', $query_string);
  87. $url = api_get_self();
  88. echo '<div class="system_announcements">';
  89. echo '<h3>'.get_lang('SystemAnnouncements').'</h3>';
  90. echo '<div style="margin:10px;text-align:right;"><a href="news_list.php">'.get_lang('More').'</a></div>';
  91. while ($announcement = Database::fetch_object($announcements)) {
  92. if ($id != $announcement->id) {
  93. if (strlen($query_string) > 0) {
  94. $show_url = 'news_list.php#'.$announcement->id;
  95. } else {
  96. $show_url = 'news_list.php#'.$announcement->id;
  97. }
  98. $display_date = api_convert_and_format_date($announcement->display_date, DATE_FORMAT_LONG);
  99. echo '<a name="'.$announcement->id.'"></a>
  100. <div class="system_announcement">
  101. <div class="system_announcement_title"><a name="ann'.$announcement->id.'" href="'.$show_url.'">'.$announcement->title.'</a></div><div class="system_announcement_date">'.$display_date.'</div>
  102. </div>';
  103. } else {
  104. echo '<div class="system_announcement">
  105. <div class="system_announcement_title">'
  106. .$announcement->display_date.'
  107. <a name="ann'.$announcement->id.'" href="'.$url.'?'.$query_string.'#ann'.$announcement->id.'">'.$announcement->title.'</a>
  108. </div>';
  109. }
  110. echo '<br />';
  111. }
  112. echo '</div>';
  113. }
  114. return;
  115. }
  116. /**
  117. * @param string $visibility
  118. * @param int $id
  119. * @param int $start
  120. * @param string $user_id
  121. * @return string
  122. */
  123. public static function displayAllAnnouncements($visibility, $id = -1, $start = 0, $user_id = '')
  124. {
  125. $user_selected_language = api_get_interface_language();
  126. $start = intval($start);
  127. $userGroup = new UserGroup();
  128. $tbl_announcement_group = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
  129. $temp_user_groups = $userGroup->get_groups_by_user(api_get_user_id(), 0);
  130. $groups = array();
  131. foreach ($temp_user_groups as $user_group) {
  132. $groups = array_merge($groups, array($user_group['id']));
  133. $groups = array_merge($groups, $userGroup->get_parent_groups($user_group['id']));
  134. }
  135. // Checks if tables exists to not break platform not updated
  136. $groups_string = '('.implode($groups, ',').')';
  137. $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
  138. $now = api_get_utc_datetime();
  139. $sql = "SELECT * FROM $table
  140. WHERE
  141. (lang = '$user_selected_language' OR lang IS NULL) AND
  142. ( '$now' >= date_start AND '$now' <= date_end) ";
  143. $sql .= self::getVisibilityCondition($visibility);
  144. if (count($groups) > 0) {
  145. $sql .= " OR id IN (
  146. SELECT announcement_id FROM $tbl_announcement_group
  147. WHERE group_id in $groups_string
  148. ) ";
  149. }
  150. if (api_is_multiple_url_enabled()) {
  151. $current_access_url_id = api_get_current_access_url_id();
  152. $sql .= " AND access_url_id IN ('1', '$current_access_url_id')";
  153. }
  154. if (!isset($_GET['start']) || $_GET['start'] == 0) {
  155. $sql .= " ORDER BY date_start DESC LIMIT ".$start.",20";
  156. } else {
  157. $sql .= " ORDER BY date_start DESC LIMIT ".($start + 1).",20";
  158. }
  159. $announcements = Database::query($sql);
  160. $content = '';
  161. if (Database::num_rows($announcements) > 0) {
  162. $content .= '<div class="system_announcements">';
  163. $content .= '<h3>'.get_lang('SystemAnnouncements').'</h3>';
  164. $content .= '<table align="center">';
  165. $content .= '<tr>';
  166. $content .= '<td>';
  167. $content .= self::display_arrow($user_id);
  168. $content .= '</td>';
  169. $content .= '</tr>';
  170. $content .= '</table>';
  171. $content .= '<table align="center" border="0" width="900px">';
  172. while ($announcement = Database::fetch_object($announcements)) {
  173. $display_date = api_convert_and_format_date($announcement->display_date, DATE_FORMAT_LONG);
  174. $content .= '<tr><td>';
  175. $content .= '<a name="'.$announcement->id.'"></a>
  176. <div class="system_announcement">
  177. <h2>'.$announcement->title.'</h2><div class="system_announcement_date">'.$display_date.'</div>
  178. <br />
  179. <div class="system_announcement_content">'
  180. .$announcement->content.'
  181. </div>
  182. </div><br />';
  183. $content .= '</tr></td>';
  184. }
  185. $content .= '</table>';
  186. $content .= '<table align="center">';
  187. $content .= '<tr>';
  188. $content .= '<td>';
  189. $content .= self::display_arrow($user_id);
  190. $content .= '</td>';
  191. $content .= '</tr>';
  192. $content .= '</table>';
  193. $content .= '</div>';
  194. }
  195. return $content;
  196. }
  197. /**
  198. * @param int $user_id
  199. * @return string
  200. */
  201. public static function display_arrow($user_id)
  202. {
  203. $start = (int) $_GET['start'];
  204. $nb_announcement = self::count_nb_announcement($start, $user_id);
  205. $next = ((int) $_GET['start'] + 19);
  206. $prev = ((int) $_GET['start'] - 19);
  207. $content = '';
  208. if (!isset($_GET['start']) || $_GET['start'] == 0) {
  209. if ($nb_announcement > 20) {
  210. $content .= '<a href="news_list.php?start='.$next.'">'.get_lang('NextBis').' >> </a>';
  211. }
  212. } else {
  213. echo '<a href="news_list.php?start='.$prev.'"> << '.get_lang('Prev').'</a>';
  214. if ($nb_announcement > 20) {
  215. $content .= '<a href="news_list.php?start='.$next.'">'.get_lang('NextBis').' >> </a>';
  216. }
  217. }
  218. return $content;
  219. }
  220. /**
  221. * @param int $start
  222. * @param string $user_id
  223. * @return int
  224. */
  225. public static function count_nb_announcement($start = 0, $user_id = '')
  226. {
  227. $start = intval($start);
  228. $user_selected_language = api_get_interface_language();
  229. $db_table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
  230. $sql = 'SELECT id FROM '.$db_table.'
  231. WHERE (lang="'.$user_selected_language.'" OR lang IS NULL) ';
  232. $visibility = self::getCurrentUserVisibility();
  233. $sql .= self::getVisibilityCondition($visibility);
  234. $current_access_url_id = 1;
  235. if (api_is_multiple_url_enabled()) {
  236. $current_access_url_id = api_get_current_access_url_id();
  237. }
  238. $sql .= " AND access_url_id = '$current_access_url_id' ";
  239. $sql .= 'LIMIT '.$start.', 21';
  240. $announcements = Database::query($sql);
  241. $i = 0;
  242. while ($rows = Database::fetch_array($announcements)) {
  243. $i++;
  244. }
  245. return $i;
  246. }
  247. /**
  248. * Get all announcements
  249. * @return array An array with all available system announcements (as php
  250. * objects)
  251. */
  252. public static function get_all_announcements()
  253. {
  254. $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
  255. $now = api_get_utc_datetime();
  256. $sql = "SELECT *, IF ( '$now' >= date_start AND '$now' <= date_end, '1', '0') AS visible
  257. FROM $table";
  258. $current_access_url_id = 1;
  259. if (api_is_multiple_url_enabled()) {
  260. $current_access_url_id = api_get_current_access_url_id();
  261. }
  262. $sql .= " WHERE access_url_id = '$current_access_url_id' ";
  263. $sql .= " ORDER BY date_start ASC";
  264. $result = Database::query($sql);
  265. $announcements = array();
  266. while ($announcement = Database::fetch_object($result)) {
  267. $announcements[] = $announcement;
  268. }
  269. return $announcements;
  270. }
  271. /**
  272. * Adds an announcement to the database
  273. *
  274. * @param string $title Title of the announcement
  275. * @param string $content Content of the announcement
  276. * @param string $date_start Start date (YYYY-MM-DD HH:II: SS)
  277. * @param string $date_end End date (YYYY-MM-DD HH:II: SS)
  278. * @param array $visibility
  279. * @param string $lang The language for which the announvement should be shown. Leave null for all langages
  280. * @param int $send_mail Whether to send an e-mail to all users (1) or not (0)
  281. * @param bool $add_to_calendar
  282. * @param bool $sendEmailTest
  283. *
  284. * @return mixed insert_id on success, false on failure
  285. */
  286. public static function add_announcement(
  287. $title,
  288. $content,
  289. $date_start,
  290. $date_end,
  291. $visibility,
  292. $lang = '',
  293. $send_mail = 0,
  294. $add_to_calendar = false,
  295. $sendEmailTest = false
  296. ) {
  297. $original_content = $content;
  298. $a_dateS = explode(' ', $date_start);
  299. $a_arraySD = explode('-', $a_dateS[0]);
  300. $a_arraySH = explode(':', $a_dateS[1]);
  301. $date_start_to_compare = array_merge($a_arraySD, $a_arraySH);
  302. $a_dateE = explode(' ', $date_end);
  303. $a_arrayED = explode('-', $a_dateE[0]);
  304. $a_arrayEH = explode(':', $a_dateE[1]);
  305. $date_end_to_compare = array_merge($a_arrayED, $a_arrayEH);
  306. $db_table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
  307. if (!checkdate($date_start_to_compare[1], $date_start_to_compare[2], $date_start_to_compare[0])) {
  308. Display::addFlash(Display::return_message(get_lang('InvalidStartDate'), 'warning'));
  309. return false;
  310. }
  311. if (($date_end_to_compare[1] ||
  312. $date_end_to_compare[2] ||
  313. $date_end_to_compare[0]) &&
  314. !checkdate($date_end_to_compare[1], $date_end_to_compare[2], $date_end_to_compare[0])
  315. ) {
  316. Display::addFlash(Display::return_message(get_lang('InvalidEndDate'), 'warning'));
  317. return false;
  318. }
  319. if (strlen(trim($title)) == 0) {
  320. Display::addFlash(Display::return_message(get_lang('InvalidTitle'), 'warning'));
  321. return false;
  322. }
  323. $start = api_get_utc_datetime($date_start);
  324. $end = api_get_utc_datetime($date_end);
  325. //Fixing urls that are sent by email
  326. //$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
  327. //$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
  328. $content = str_replace('src=\"'.api_get_path(REL_HOME_PATH), 'src=\"'.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH), $content);
  329. $content = str_replace('file='.api_get_path(REL_HOME_PATH), 'file='.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH), $content);
  330. $lang = is_null($lang) ? '' : $lang;
  331. $current_access_url_id = 1;
  332. if (api_is_multiple_url_enabled()) {
  333. $current_access_url_id = api_get_current_access_url_id();
  334. }
  335. $params = [
  336. 'title' => $title,
  337. 'content' => $content,
  338. 'date_start' => $start,
  339. 'date_end' => $end,
  340. 'lang' => $lang,
  341. 'access_url_id' => $current_access_url_id
  342. ];
  343. foreach ($visibility as $key => $value) {
  344. $params[$key] = $value;
  345. }
  346. $resultId = Database::insert($db_table, $params);
  347. if ($resultId) {
  348. if ($sendEmailTest) {
  349. self::send_system_announcement_by_email(
  350. $title,
  351. $content,
  352. $visibility,
  353. $lang,
  354. true
  355. );
  356. } else {
  357. if ($send_mail == 1) {
  358. self::send_system_announcement_by_email(
  359. $title,
  360. $content,
  361. $visibility,
  362. $lang
  363. );
  364. }
  365. }
  366. if ($add_to_calendar) {
  367. $agenda = new Agenda('admin');
  368. $agenda->addEvent(
  369. $date_start,
  370. $date_end,
  371. false,
  372. $title,
  373. $original_content
  374. );
  375. }
  376. return $resultId;
  377. }
  378. return false;
  379. }
  380. /**
  381. * Makes the announcement id visible only for groups in groups_array
  382. * @param int $announcement_id
  383. * @param array $group_array array of group id
  384. * @return bool
  385. **/
  386. public static function announcement_for_groups($announcement_id, $group_array)
  387. {
  388. $tbl_announcement_group = Database::get_main_table(
  389. TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS
  390. );
  391. //first delete all group associations for this announcement
  392. $res = Database::query(
  393. "DELETE FROM $tbl_announcement_group
  394. WHERE announcement_id=".intval($announcement_id)
  395. );
  396. if ($res === false) {
  397. return false;
  398. }
  399. foreach ($group_array as $group_id) {
  400. if (intval($group_id) != 0) {
  401. $sql = "INSERT INTO $tbl_announcement_group SET
  402. announcement_id=".intval($announcement_id).",
  403. group_id=".intval($group_id);
  404. $res = Database::query($sql);
  405. if ($res === false) {
  406. return false;
  407. }
  408. }
  409. }
  410. return true;
  411. }
  412. /**
  413. * Gets the groups of this announce
  414. * @param int announcement id
  415. * @return array array of group id
  416. **/
  417. public static function get_announcement_groups($announcement_id)
  418. {
  419. $tbl_announcement_group = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS_GROUPS);
  420. $tbl_group = Database::get_main_table(TABLE_USERGROUP);
  421. //first delete all group associations for this announcement
  422. $sql = "SELECT
  423. g.id as group_id,
  424. g.name as group_name
  425. FROM $tbl_group g , $tbl_announcement_group ag
  426. WHERE
  427. announcement_id =".intval($announcement_id)." AND
  428. ag.group_id = g.id";
  429. $res = Database::query($sql);
  430. $groups = Database::fetch_array($res);
  431. return $groups;
  432. }
  433. /**
  434. * Updates an announcement to the database
  435. *
  436. * @param integer $id of the announcement
  437. * @param string $title title of the announcement
  438. * @param string $content content of the announcement
  439. * @param array $date_start start date (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
  440. * @param array $date_end end date of (0 => day ; 1 => month ; 2 => year ; 3 => hour ; 4 => minute)
  441. * @param array $visibility
  442. * @return bool True on success, false on failure
  443. */
  444. public static function update_announcement(
  445. $id,
  446. $title,
  447. $content,
  448. $date_start,
  449. $date_end,
  450. $visibility,
  451. $lang = null,
  452. $send_mail = 0,
  453. $sendEmailTest = false
  454. ) {
  455. $em = Database::getManager();
  456. $announcement = $em->find('ChamiloCoreBundle:SysAnnouncement', $id);
  457. if (!$announcement) {
  458. return false;
  459. }
  460. $a_dateS = explode(' ', $date_start);
  461. $a_arraySD = explode('-', $a_dateS[0]);
  462. $a_arraySH = explode(':', $a_dateS[1]);
  463. $date_start_to_compare = array_merge($a_arraySD, $a_arraySH);
  464. $a_dateE = explode(' ', $date_end);
  465. $a_arrayED = explode('-', $a_dateE[0]);
  466. $a_arrayEH = explode(':', $a_dateE[1]);
  467. $date_end_to_compare = array_merge($a_arrayED, $a_arrayEH);
  468. $lang = is_null($lang) ? '' : $lang;
  469. if (!checkdate($date_start_to_compare[1], $date_start_to_compare[2], $date_start_to_compare[0])) {
  470. echo Display::return_message(get_lang('InvalidStartDate'));
  471. return false;
  472. }
  473. if (($date_end_to_compare[1] ||
  474. $date_end_to_compare[2] ||
  475. $date_end_to_compare[0]) &&
  476. !checkdate($date_end_to_compare[1], $date_end_to_compare[2], $date_end_to_compare[0])
  477. ) {
  478. echo Display::return_message(get_lang('InvalidEndDate'));
  479. return false;
  480. }
  481. if (strlen(trim($title)) == 0) {
  482. echo Display::return_message(get_lang('InvalidTitle'));
  483. return false;
  484. }
  485. $start = api_get_utc_datetime($date_start);
  486. $end = api_get_utc_datetime($date_end);
  487. //Fixing urls that are sent by email
  488. //$content = str_replace('src=\"/home/', 'src=\"'.api_get_path(WEB_PATH).'home/', $content);
  489. //$content = str_replace('file=/home/', 'file='.api_get_path(WEB_PATH).'home/', $content);
  490. $content = str_replace('src=\"'.api_get_path(REL_HOME_PATH), 'src=\"'.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH), $content);
  491. $content = str_replace('file='.api_get_path(REL_HOME_PATH), 'file='.api_get_path(WEB_PATH).api_get_path(REL_HOME_PATH), $content);
  492. if ($sendEmailTest) {
  493. self::send_system_announcement_by_email(
  494. $title,
  495. $content,
  496. null,
  497. null,
  498. $lang,
  499. $sendEmailTest
  500. );
  501. } else {
  502. if ($send_mail == 1) {
  503. self::send_system_announcement_by_email(
  504. $title,
  505. $content,
  506. $visibility,
  507. $lang
  508. );
  509. }
  510. }
  511. $dateStart = new DateTime($start, new DateTimeZone('UTC'));
  512. $dateEnd = new DateTime($end, new DateTimeZone('UTC'));
  513. $announcement
  514. ->setLang($lang)
  515. ->setTitle($title)
  516. ->setContent($content)
  517. ->setDateStart($dateStart)
  518. ->setDateEnd($dateEnd)
  519. //->setVisibleTeacher($visible_teacher)
  520. //->setVisibleStudent($visible_student)
  521. //->setVisibleGuest($visible_guest)
  522. ->setAccessUrlId(api_get_current_access_url_id());
  523. $em->merge($announcement);
  524. $em->flush();
  525. // Update visibility
  526. $list = self::getVisibilityList();
  527. $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
  528. foreach ($list as $key => $title) {
  529. $value = isset($visibility[$key]) && $visibility[$key] ? 1 : 0;
  530. $sql = "UPDATE $table SET $key = '$value' WHERE id = $id";
  531. Database::query($sql);
  532. }
  533. return true;
  534. }
  535. /**
  536. * Deletes an announcement
  537. * @param int $id The identifier of the announcement that should be
  538. * @return bool True on success, false on failure
  539. */
  540. public static function delete_announcement($id)
  541. {
  542. $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
  543. $id = intval($id);
  544. $sql = "DELETE FROM $table WHERE id =".$id;
  545. $res = Database::query($sql);
  546. if ($res === false) {
  547. return false;
  548. }
  549. return true;
  550. }
  551. /**
  552. * Gets an announcement
  553. * @param int $id The identifier of the announcement that should be
  554. * @return object Object of class StdClass or the required class, containing the query result row
  555. */
  556. public static function get_announcement($id)
  557. {
  558. $db_table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
  559. $id = intval($id);
  560. $sql = "SELECT * FROM ".$db_table." WHERE id = ".$id;
  561. $announcement = Database::fetch_object(Database::query($sql));
  562. return $announcement;
  563. }
  564. /**
  565. * Change the visibility of an announcement
  566. * @param int $id
  567. * @param int $user For who should the visibility be changed
  568. * @param bool $visible
  569. * @return bool True on success, false on failure
  570. */
  571. public static function set_visibility($id, $user, $visible)
  572. {
  573. $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
  574. $id = (int) $id;
  575. $list = array_keys(self::getVisibilityList());
  576. $user = trim($user);
  577. $visible = (int) $visible;
  578. if (!in_array($user, $list)) {
  579. return false;
  580. }
  581. $field = $user;
  582. $sql = "UPDATE $table SET ".$field." = '".$visible."'
  583. WHERE id='".$id."'";
  584. $res = Database::query($sql);
  585. if ($res === false) {
  586. return false;
  587. }
  588. return true;
  589. }
  590. /**
  591. * Send a system announcement by e-mail to all teachers/students depending on parameters
  592. * @param string $title
  593. * @param string $content
  594. * @param array $visibility
  595. * @param string $language Language (optional, considered for all languages if left empty)
  596. * @param bool $sendEmailTest
  597. * @return bool True if the message was sent or there was no destination matching.
  598. * False on database or e-mail sending error.
  599. */
  600. public static function send_system_announcement_by_email(
  601. $title,
  602. $content,
  603. $visibility,
  604. $language = null,
  605. $sendEmailTest = false
  606. ) {
  607. $content = str_replace(array('\r\n', '\n', '\r'), '', $content);
  608. $now = api_get_utc_datetime();
  609. $teacher = $visibility['visible_teacher'];
  610. $student = $visibility['visible_student'];
  611. if ($sendEmailTest) {
  612. MessageManager::send_message_simple(api_get_user_id(), $title, $content);
  613. return true;
  614. }
  615. $user_table = Database::get_main_table(TABLE_MAIN_USER);
  616. if (api_is_multiple_url_enabled()) {
  617. $current_access_url_id = api_get_current_access_url_id();
  618. $url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
  619. $url_condition = " INNER JOIN $url_rel_user uu ON uu.user_id = u.user_id ";
  620. }
  621. if ($teacher <> 0 && $student == 0) {
  622. $sql = "SELECT DISTINCT u.user_id FROM $user_table u $url_condition
  623. WHERE status = '1' ";
  624. }
  625. if ($teacher == 0 && $student <> 0) {
  626. $sql = "SELECT DISTINCT u.user_id FROM $user_table u $url_condition
  627. WHERE status = '5' ";
  628. }
  629. if ($teacher <> 0 && $student <> 0) {
  630. $sql = "SELECT DISTINCT u.user_id FROM $user_table u $url_condition
  631. WHERE 1 = 1 ";
  632. }
  633. if (!empty($language)) {
  634. //special condition because language was already treated for SQL insert before
  635. $sql .= " AND language = '".Database::escape_string($language)."' ";
  636. }
  637. if (api_is_multiple_url_enabled()) {
  638. $sql .= " AND access_url_id = '".$current_access_url_id."' ";
  639. }
  640. // Sent to active users.
  641. $sql .= " AND email <>'' AND active = 1 ";
  642. // Expiration date
  643. $sql .= " AND (expiration_date = '' OR expiration_date IS NULL OR expiration_date > '$now') ";
  644. if ((empty($teacher) || $teacher == '0') && (empty($student) || $student == '0')) {
  645. return true;
  646. }
  647. $result = Database::query($sql);
  648. if ($result === false) {
  649. return false;
  650. }
  651. $message_sent = false;
  652. while ($row = Database::fetch_array($result, 'ASSOC')) {
  653. MessageManager::send_message_simple($row['user_id'], $title, $content);
  654. $message_sent = true;
  655. }
  656. // Minor validation to clean up the attachment files in the announcement
  657. if (!empty($_FILES)) {
  658. $attachments = $_FILES;
  659. foreach ($attachments as $attachment) {
  660. unlink($attachment['tmp_name']);
  661. }
  662. }
  663. return $message_sent; //true if at least one e-mail was sent
  664. }
  665. /**
  666. * Displays announcements as an slideshow
  667. * @param string $visible see self::VISIBLE_* constants
  668. * @param int $id The identifier of the announcement to display
  669. *
  670. * @return string
  671. */
  672. public static function displayAnnouncementsSlider($visible, $id = null)
  673. {
  674. $user_selected_language = Database::escape_string(api_get_interface_language());
  675. $table = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
  676. $cut_size = 500;
  677. $now = api_get_utc_datetime();
  678. $sql = "SELECT * FROM $table
  679. WHERE
  680. (lang = '$user_selected_language' OR lang = '') AND
  681. ('$now' >= date_start AND '$now' <= date_end) ";
  682. $sql .= self::getVisibilityCondition($visible);
  683. if (isset($id) && !empty($id)) {
  684. $id = intval($id);
  685. $sql .= " AND id = $id ";
  686. }
  687. if (api_is_multiple_url_enabled()) {
  688. $current_url_id = api_get_current_access_url_id();
  689. $sql .= " AND access_url_id IN ('1', '$current_url_id') ";
  690. }
  691. $sql .= " ORDER BY date_start DESC";
  692. $result = Database::query($sql);
  693. $announcements = [];
  694. if (Database::num_rows($result) > 0) {
  695. while ($announcement = Database::fetch_object($result)) {
  696. $announcementData = [
  697. 'id' => $announcement->id,
  698. 'title' => $announcement->title,
  699. 'content' => $announcement->content,
  700. 'readMore' => null
  701. ];
  702. if (empty($id)) {
  703. if (api_strlen(strip_tags($announcement->content)) > $cut_size) {
  704. $announcementData['content'] = cut($announcement->content, $cut_size);
  705. $announcementData['readMore'] = true;
  706. }
  707. }
  708. $announcements[] = $announcementData;
  709. }
  710. }
  711. if (count($announcements) === 0) {
  712. return null;
  713. }
  714. $template = new Template(null, false, false);
  715. $template->assign('announcements', $announcements);
  716. $layout = $template->get_template('announcement/slider.tpl');
  717. return $template->fetch($layout);
  718. }
  719. /**
  720. * Get the HTML code for an announcement
  721. * @param int $announcementId The announcement ID
  722. * @param int $visibility The announcement visibility
  723. * @return string The HTML code
  724. */
  725. public static function displayAnnouncement($announcementId, $visibility)
  726. {
  727. $selectedUserLanguage = Database::escape_string(api_get_interface_language());
  728. $announcementTable = Database::get_main_table(TABLE_MAIN_SYSTEM_ANNOUNCEMENTS);
  729. $now = api_get_utc_datetime();
  730. $whereConditions = [
  731. "(lang = ? OR lang IS NULL OR lang = '') " => $selectedUserLanguage,
  732. "AND (? >= date_start AND ? <= date_end) " => [$now, $now],
  733. "AND id = ? " => intval($announcementId)
  734. ];
  735. $condition = self::getVisibilityCondition($visibility);
  736. $whereConditions[$condition] = 1;
  737. if (api_is_multiple_url_enabled()) {
  738. $whereConditions["AND access_url_id IN (1, ?) "] = api_get_current_access_url_id();
  739. }
  740. $announcement = Database::select(
  741. '*',
  742. $announcementTable,
  743. [
  744. 'where' => $whereConditions,
  745. 'order' => 'date_start',
  746. ],
  747. 'first'
  748. );
  749. $template = new Template(null, false, false);
  750. $template->assign('announcement', $announcement);
  751. $layout = $template->get_template('announcement/view.tpl');
  752. return $template->fetch($layout);
  753. }
  754. /**
  755. * @return bool
  756. */
  757. public static function newRolesActivated()
  758. {
  759. /* In order to use this option you need to run this SQL changes :
  760. ALTER TABLE sys_announcement ADD COLUMN visible_drh INT DEFAULT 0;
  761. ALTER TABLE sys_announcement ADD COLUMN visible_session_admin INT DEFAULT 0;
  762. ALTER TABLE sys_announcement ADD COLUMN visible_boss INT DEFAULT 0;
  763. */
  764. return api_get_configuration_value('system_announce_extra_roles');
  765. }
  766. /**
  767. * @return string
  768. */
  769. public static function getCurrentUserVisibility()
  770. {
  771. if (api_is_anonymous()) {
  772. return SystemAnnouncementManager::VISIBLE_GUEST;
  773. }
  774. if (self::newRolesActivated()) {
  775. if (api_is_student_boss()) {
  776. return SystemAnnouncementManager::VISIBLE_STUDENT_BOSS;
  777. }
  778. if (api_is_session_admin()) {
  779. return SystemAnnouncementManager::VISIBLE_SESSION_ADMIN;
  780. }
  781. if (api_is_drh()) {
  782. return SystemAnnouncementManager::VISIBLE_DRH;
  783. }
  784. if (api_is_allowed_to_create_course()) {
  785. return SystemAnnouncementManager::VISIBLE_TEACHER;
  786. } else {
  787. return SystemAnnouncementManager::VISIBLE_STUDENT;
  788. }
  789. } else {
  790. // Default behaviour
  791. return api_is_allowed_to_create_course() ? SystemAnnouncementManager::VISIBLE_TEACHER : SystemAnnouncementManager::VISIBLE_STUDENT;
  792. }
  793. }
  794. }