system_announcements.lib.php 33 KB

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