system_announcements.lib.php 33 KB

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