AnnouncementManager.php 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\CoreBundle\Entity\ExtraField as ExtraFieldEntity;
  4. use Chamilo\CoreBundle\Entity\ExtraFieldValues;
  5. use Chamilo\CourseBundle\Entity\CAnnouncement;
  6. use Chamilo\CourseBundle\Entity\CItemProperty;
  7. /**
  8. * Include file with functions for the announcements module.
  9. *
  10. * @author jmontoya
  11. *
  12. * @package chamilo.announcements
  13. *
  14. * @todo use OOP
  15. */
  16. class AnnouncementManager
  17. {
  18. /**
  19. * Constructor.
  20. */
  21. public function __construct()
  22. {
  23. }
  24. /**
  25. * @return array
  26. */
  27. public static function getTags()
  28. {
  29. $tags = [
  30. '((user_name))',
  31. '((user_email))',
  32. '((user_firstname))',
  33. '((user_lastname))',
  34. '((user_official_code))',
  35. '((course_title))',
  36. '((course_link))',
  37. ];
  38. $tags[] = '((teachers))';
  39. $extraField = new ExtraField('user');
  40. $extraFields = $extraField->get_all(['filter = ?' => 1]);
  41. if (!empty($extraFields)) {
  42. foreach ($extraFields as $extra) {
  43. $tags[] = "((extra_".$extra['variable']."))";
  44. }
  45. }
  46. $sessionId = api_get_session_id();
  47. if (!empty($sessionId)) {
  48. $tags[] = '((coaches))';
  49. $tags[] = '((general_coach))';
  50. $tags[] = '((general_coach_email))';
  51. }
  52. return $tags;
  53. }
  54. /**
  55. * @param int $userId
  56. * @param string $content
  57. * @param string $courseCode
  58. * @param int $sessionId
  59. *
  60. * @return string
  61. */
  62. public static function parseContent(
  63. $userId,
  64. $content,
  65. $courseCode,
  66. $sessionId = 0
  67. ) {
  68. $readerInfo = api_get_user_info($userId, false, false, true, true);
  69. $courseInfo = api_get_course_info($courseCode);
  70. $teacherList = CourseManager::getTeacherListFromCourseCodeToString($courseInfo['code']);
  71. $generalCoachName = '';
  72. $generalCoachEmail = '';
  73. $coaches = '';
  74. if (!empty($sessionId)) {
  75. $sessionInfo = api_get_session_info($sessionId);
  76. $coaches = CourseManager::get_coachs_from_course_to_string(
  77. $sessionId,
  78. $courseInfo['real_id']
  79. );
  80. $generalCoach = api_get_user_info($sessionInfo['id_coach']);
  81. $generalCoachName = $generalCoach['complete_name'];
  82. $generalCoachEmail = $generalCoach['email'];
  83. }
  84. $data = [];
  85. $data['user_name'] = '';
  86. $data['user_firstname'] = '';
  87. $data['user_lastname'] = '';
  88. $data['user_official_code'] = '';
  89. $data['user_email'] = '';
  90. if (!empty($readerInfo)) {
  91. $data['user_name'] = $readerInfo['username'];
  92. $data['user_email'] = $readerInfo['email'];
  93. $data['user_firstname'] = $readerInfo['firstname'];
  94. $data['user_lastname'] = $readerInfo['lastname'];
  95. $data['user_official_code'] = $readerInfo['official_code'];
  96. }
  97. $data['course_title'] = $courseInfo['name'];
  98. $courseLink = api_get_course_url($courseCode, $sessionId);
  99. $data['course_link'] = Display::url($courseLink, $courseLink);
  100. $data['teachers'] = $teacherList;
  101. if (!empty($readerInfo)) {
  102. $extraField = new ExtraField('user');
  103. $extraFields = $extraField->get_all(['filter = ?' => 1]);
  104. if (!empty($extraFields)) {
  105. foreach ($extraFields as $extra) {
  106. $data['extra_'.$extra['variable']] = '';
  107. }
  108. }
  109. if (!empty($readerInfo['extra'])) {
  110. foreach ($readerInfo['extra'] as $extra) {
  111. if (isset($extra['value'])) {
  112. /** @var \Chamilo\CoreBundle\Entity\ExtraFieldValues $value */
  113. $value = $extra['value'];
  114. if ($value instanceof ExtraFieldValues) {
  115. $field = $value->getField();
  116. if ($field instanceof ExtraFieldEntity) {
  117. $data['extra_'.$field->getVariable()] = $value->getValue();
  118. }
  119. }
  120. }
  121. }
  122. }
  123. }
  124. if (!empty($sessionId)) {
  125. $data['coaches'] = $coaches;
  126. $data['general_coach'] = $generalCoachName;
  127. $data['general_coach_email'] = $generalCoachEmail;
  128. }
  129. $tags = self::getTags();
  130. foreach ($tags as $tag) {
  131. $simpleTag = str_replace(['((', '))'], '', $tag);
  132. $value = isset($data[$simpleTag]) ? $data[$simpleTag] : '';
  133. $content = str_replace($tag, $value, $content);
  134. }
  135. return $content;
  136. }
  137. /**
  138. * Gets all announcements from a course.
  139. *
  140. * @param array $course_info
  141. * @param int $session_id
  142. *
  143. * @return array html with the content and count of announcements or false otherwise
  144. */
  145. public static function get_all_annoucement_by_course($course_info, $session_id = 0)
  146. {
  147. $session_id = (int) $session_id;
  148. $courseId = $course_info['real_id'];
  149. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  150. $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  151. $sql = "SELECT DISTINCT
  152. announcement.id,
  153. announcement.title,
  154. announcement.content
  155. FROM $tbl_announcement announcement
  156. INNER JOIN $tbl_item_property i
  157. ON (announcement.id = i.ref AND announcement.c_id = i.c_id)
  158. WHERE
  159. i.tool='announcement' AND
  160. announcement.session_id = '$session_id' AND
  161. announcement.c_id = $courseId AND
  162. i.c_id = $courseId
  163. ORDER BY display_order DESC";
  164. $rs = Database::query($sql);
  165. $num_rows = Database::num_rows($rs);
  166. if ($num_rows > 0) {
  167. $list = [];
  168. while ($row = Database::fetch_array($rs)) {
  169. $list[] = $row;
  170. }
  171. return $list;
  172. }
  173. return false;
  174. }
  175. /**
  176. * This functions switches the visibility a course resource
  177. * using the visibility field in 'item_property'.
  178. *
  179. * @param array $courseInfo
  180. * @param int $id ID of the element of the corresponding type
  181. *
  182. * @return bool False on failure, True on success
  183. */
  184. public static function change_visibility_announcement($courseInfo, $id)
  185. {
  186. $session_id = api_get_session_id();
  187. $item_visibility = api_get_item_visibility(
  188. $courseInfo,
  189. TOOL_ANNOUNCEMENT,
  190. $id,
  191. $session_id
  192. );
  193. if ($item_visibility == '1') {
  194. api_item_property_update(
  195. $courseInfo,
  196. TOOL_ANNOUNCEMENT,
  197. $id,
  198. 'invisible',
  199. api_get_user_id()
  200. );
  201. } else {
  202. api_item_property_update(
  203. $courseInfo,
  204. TOOL_ANNOUNCEMENT,
  205. $id,
  206. 'visible',
  207. api_get_user_id()
  208. );
  209. }
  210. return true;
  211. }
  212. /**
  213. * Deletes an announcement.
  214. *
  215. * @param array $courseInfo the course array
  216. * @param int $id the announcement id
  217. */
  218. public static function delete_announcement($courseInfo, $id)
  219. {
  220. api_item_property_update(
  221. $courseInfo,
  222. TOOL_ANNOUNCEMENT,
  223. $id,
  224. 'delete',
  225. api_get_user_id()
  226. );
  227. }
  228. /**
  229. * Deletes all announcements by course.
  230. *
  231. * @param array $courseInfo the course array
  232. */
  233. public static function delete_all_announcements($courseInfo)
  234. {
  235. $announcements = self::get_all_annoucement_by_course(
  236. $courseInfo,
  237. api_get_session_id()
  238. );
  239. if (!empty($announcements)) {
  240. foreach ($announcements as $annon) {
  241. api_item_property_update(
  242. $courseInfo,
  243. TOOL_ANNOUNCEMENT,
  244. $annon['id'],
  245. 'delete',
  246. api_get_user_id()
  247. );
  248. }
  249. }
  250. }
  251. /**
  252. * @param string $title
  253. * @param int $courseId
  254. * @param int $sessionId
  255. * @param int $visibility 1 or 0
  256. *
  257. * @return mixed
  258. */
  259. public static function getAnnouncementsByTitle(
  260. $title,
  261. $courseId,
  262. $sessionId = 0,
  263. $visibility = 1
  264. ) {
  265. $dql = "SELECT a
  266. FROM ChamiloCourseBundle:CAnnouncement a
  267. JOIN ChamiloCourseBundle:CItemProperty ip
  268. WITH a.id = ip.ref AND a.cId = ip.course
  269. WHERE
  270. ip.tool = 'announcement' AND
  271. a.cId = :course AND
  272. a.sessionId = :session AND
  273. a.title like :title AND
  274. ip.visibility = :visibility
  275. ORDER BY a.displayOrder DESC";
  276. $qb = Database::getManager()->createQuery($dql);
  277. $result = $qb->execute(
  278. [
  279. 'course' => $courseId,
  280. 'session' => $sessionId,
  281. 'visibility' => $visibility,
  282. 'title' => "%$title%",
  283. ]
  284. );
  285. return $result;
  286. }
  287. /**
  288. * @param int $announcementId
  289. * @param int $courseId
  290. * @param int $userId
  291. * @param int $groupId
  292. *
  293. * @return array
  294. */
  295. public static function getAnnouncementInfoById(
  296. $announcementId,
  297. $courseId,
  298. $userId,
  299. $groupId = 0
  300. ) {
  301. $announcementId = (int) $announcementId;
  302. $courseId = (int) $courseId;
  303. $userId = (int) $userId;
  304. $groupId = (int) $groupId;
  305. if (api_is_allowed_to_edit(false, true) ||
  306. (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
  307. ) {
  308. $dql = "SELECT a, ip
  309. FROM ChamiloCourseBundle:CAnnouncement a
  310. JOIN ChamiloCourseBundle:CItemProperty ip
  311. WITH a.id = ip.ref AND a.cId = ip.course
  312. WHERE
  313. a.id = :announcement AND
  314. ip.tool = 'announcement' AND
  315. a.cId = :course
  316. ORDER BY a.displayOrder DESC";
  317. } else {
  318. $groupList[] = $groupId;
  319. if (api_get_user_id() != 0) {
  320. $extraGroupCondition = '';
  321. if (!empty($groupId)) {
  322. $groupProperties = GroupManager::get_group_properties($groupId);
  323. if ($groupProperties['announcements_state'] == GroupManager::TOOL_PRIVATE_BETWEEN_USERS) {
  324. $extraGroupCondition = " AND (
  325. ip.toUser = $userId AND ip.group = $groupId OR
  326. (ip.group IN ('0') OR ip.group IS NULL) OR
  327. (ip.group = $groupId AND (ip.toUser IS NULL OR ip.toUser = 0))
  328. )";
  329. }
  330. }
  331. $dql = "SELECT a, ip
  332. FROM ChamiloCourseBundle:CAnnouncement a
  333. JOIN ChamiloCourseBundle:CItemProperty ip
  334. WITH a.id = ip.ref AND a.cId = ip.course
  335. WHERE
  336. a.id = :announcement AND
  337. ip.tool='announcement' AND
  338. (
  339. ip.toUser = $userId OR
  340. ip.group IN ('0', '".$groupId."') OR
  341. ip.group IS NULL
  342. ) AND
  343. ip.visibility = '1' AND
  344. ip.course = :course
  345. $extraGroupCondition
  346. ORDER BY a.displayOrder DESC";
  347. } else {
  348. $dql = "SELECT a, ip
  349. FROM ChamiloCourseBundle:CAnnouncement a
  350. JOIN ChamiloCourseBundle:CItemProperty ip
  351. WITH a.id = ip.ref AND a.cId = ip.course
  352. WHERE
  353. a.id = :announcement AND
  354. ip.tool = 'announcement' AND
  355. (ip.group = '0' OR ip.group IS NULL) AND
  356. ip.visibility = '1' AND
  357. ip.course = :course";
  358. }
  359. }
  360. $qb = Database::getManager()->createQuery($dql);
  361. $result = $qb->execute(
  362. [
  363. 'announcement' => $announcementId,
  364. 'course' => $courseId,
  365. ]
  366. );
  367. if (!empty($result)) {
  368. return [
  369. 'announcement' => $result[0],
  370. 'item_property' => $result[1],
  371. ];
  372. }
  373. return [];
  374. }
  375. /**
  376. * Displays one specific announcement.
  377. *
  378. * @param int $id, the id of the announcement you want to display
  379. *
  380. * @return string
  381. */
  382. public static function displayAnnouncement($id)
  383. {
  384. $id = (int) $id;
  385. if (empty($id)) {
  386. return '';
  387. }
  388. global $charset;
  389. $html = '';
  390. $result = self::getAnnouncementInfoById(
  391. $id,
  392. api_get_course_int_id(),
  393. api_get_user_id(),
  394. api_get_group_id()
  395. );
  396. if (empty($result)) {
  397. return '';
  398. }
  399. /** @var CAnnouncement $announcement */
  400. $announcement = $result['announcement'];
  401. /** @var CItemProperty $itemProperty */
  402. $itemProperty = $result['item_property'];
  403. if (empty($announcement) || empty($itemProperty)) {
  404. return '';
  405. }
  406. $title = $announcement->getTitle();
  407. $content = $announcement->getContent();
  408. $html .= "<table height=\"100\" width=\"100%\" cellpadding=\"5\" cellspacing=\"0\" class=\"data_table\">";
  409. $html .= "<tr><td><h2>".$title."</h2></td></tr>";
  410. if (api_is_allowed_to_edit(false, true) ||
  411. (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous())
  412. ) {
  413. $modify_icons = "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=modify&id=".$id."\">".
  414. Display::return_icon('edit.png', get_lang('Edit'), '', ICON_SIZE_SMALL)."</a>";
  415. $image_visibility = 'invisible';
  416. $alt_visibility = get_lang('Visible');
  417. if ($itemProperty->getVisibility() === 1) {
  418. $image_visibility = 'visible';
  419. $alt_visibility = get_lang('Hide');
  420. }
  421. global $stok;
  422. $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=showhide&id=".$id."&sec_token=".$stok."\">".
  423. Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
  424. if (api_is_allowed_to_edit(false, true)) {
  425. $modify_icons .= "<a href=\"".api_get_self()."?".api_get_cidreq()."&action=delete&id=".$id."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(api_htmlentities(get_lang('ConfirmYourChoice'), ENT_QUOTES, $charset))."')) return false;\">".
  426. Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).
  427. "</a>";
  428. }
  429. $html .= "<tr><th style='text-align:right'>$modify_icons</th></tr>";
  430. }
  431. // The user id is always the current one.
  432. $toUserId = api_get_user_id();
  433. $content = self::parseContent(
  434. $toUserId,
  435. $content,
  436. api_get_course_id(),
  437. api_get_session_id()
  438. );
  439. $html .= "<tr><td>$content</td></tr>";
  440. $html .= "<tr>";
  441. $html .= "<td class=\"announcements_datum\">".get_lang('LastUpdateDate')." : ";
  442. $lastEdit = $itemProperty->getLasteditDate();
  443. $html .= Display::dateToStringAgoAndLongDate($lastEdit);
  444. $html .= "</td></tr>";
  445. $allow = !api_get_configuration_value('hide_announcement_sent_to_users_info');
  446. if ($allow && api_is_allowed_to_edit(false, true)) {
  447. $sent_to = self::sent_to('announcement', $id);
  448. $sentToForm = self::sent_to_form($sent_to);
  449. $html .= Display::tag(
  450. 'td',
  451. get_lang('SentTo').': '.$sentToForm,
  452. ['class' => 'announcements_datum']
  453. );
  454. }
  455. $attachment_list = self::get_attachment($id);
  456. if (count($attachment_list) > 0) {
  457. $html .= "<tr><td>";
  458. $realname = $attachment_list['path'];
  459. $user_filename = $attachment_list['filename'];
  460. $full_file_name = 'download.php?'.api_get_cidreq().'&file='.$realname;
  461. $html .= '<br/>';
  462. $html .= Display::return_icon('attachment.gif', get_lang('Attachment'));
  463. $html .= '<a href="'.$full_file_name.' "> '.$user_filename.' </a>';
  464. $html .= ' - <span class="forum_attach_comment" >'.$attachment_list['comment'].'</span>';
  465. if (api_is_allowed_to_edit(false, true)) {
  466. $url = api_get_self()."?".api_get_cidreq().
  467. "&action=delete_attachment&id_attach=".$attachment_list['id']."&sec_token=".$stok;
  468. $html .= Display::url(
  469. Display::return_icon(
  470. 'delete.png',
  471. get_lang('Delete'),
  472. '',
  473. 16
  474. ),
  475. $url
  476. );
  477. }
  478. $html .= '</td></tr>';
  479. }
  480. $html .= '</table>';
  481. return $html;
  482. }
  483. /**
  484. * @param array $courseInfo
  485. *
  486. * @return int
  487. */
  488. public static function getLastAnnouncementOrder($courseInfo)
  489. {
  490. if (empty($courseInfo)) {
  491. return 0;
  492. }
  493. if (!isset($courseInfo['real_id'])) {
  494. return false;
  495. }
  496. $courseId = $courseInfo['real_id'];
  497. $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
  498. $sql = "SELECT MAX(display_order)
  499. FROM $table
  500. WHERE c_id = $courseId ";
  501. $result = Database::query($sql);
  502. $order = 0;
  503. if (Database::num_rows($result)) {
  504. $row = Database::fetch_array($result);
  505. $order = (int) $row[0] + 1;
  506. }
  507. return $order;
  508. }
  509. /**
  510. * Store an announcement in the database (including its attached file if any).
  511. *
  512. * @param array $courseInfo
  513. * @param int $sessionId
  514. * @param string $title Announcement title (pure text)
  515. * @param string $newContent Content of the announcement (can be HTML)
  516. * @param array $sentTo Array of users and groups to send the announcement to
  517. * @param array $file uploaded file $_FILES
  518. * @param string $file_comment Comment describing the attachment
  519. * @param string $end_date
  520. * @param bool $sendToUsersInSession
  521. * @param int $authorId
  522. *
  523. * @return int false on failure, ID of the announcement on success
  524. */
  525. public static function add_announcement(
  526. $courseInfo,
  527. $sessionId,
  528. $title,
  529. $newContent,
  530. $sentTo,
  531. $file = [],
  532. $file_comment = null,
  533. $end_date = null,
  534. $sendToUsersInSession = false,
  535. $authorId = 0
  536. ) {
  537. if (empty($courseInfo)) {
  538. return false;
  539. }
  540. if (!isset($courseInfo['real_id'])) {
  541. return false;
  542. }
  543. $courseId = $courseInfo['real_id'];
  544. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  545. $authorId = empty($authorId) ? api_get_user_id() : $authorId;
  546. if (empty($end_date)) {
  547. $end_date = api_get_utc_datetime();
  548. }
  549. $order = self::getLastAnnouncementOrder($courseInfo);
  550. // store in the table announcement
  551. $params = [
  552. 'c_id' => $courseId,
  553. 'content' => $newContent,
  554. 'title' => $title,
  555. 'end_date' => $end_date,
  556. 'display_order' => $order,
  557. 'session_id' => (int) $sessionId,
  558. ];
  559. $last_id = Database::insert($tbl_announcement, $params);
  560. if (empty($last_id)) {
  561. return false;
  562. } else {
  563. $sql = "UPDATE $tbl_announcement SET id = iid WHERE iid = $last_id";
  564. Database::query($sql);
  565. if (!empty($file)) {
  566. self::add_announcement_attachment_file(
  567. $last_id,
  568. $file_comment,
  569. $_FILES['user_upload']
  570. );
  571. }
  572. // store in item_property (first the groups, then the users
  573. if (empty($sentTo) ||
  574. (!empty($sentTo) && isset($sentTo[0]) && $sentTo[0] == 'everyone')
  575. ) {
  576. // The message is sent to EVERYONE, so we set the group to 0
  577. api_item_property_update(
  578. $courseInfo,
  579. TOOL_ANNOUNCEMENT,
  580. $last_id,
  581. 'AnnouncementAdded',
  582. $authorId,
  583. '0',
  584. null,
  585. null,
  586. null,
  587. $sessionId
  588. );
  589. } else {
  590. $send_to = CourseManager::separateUsersGroups($sentTo);
  591. $batchSize = 20;
  592. $em = Database::getManager();
  593. // Storing the selected groups
  594. if (is_array($send_to['groups']) &&
  595. !empty($send_to['groups'])
  596. ) {
  597. $counter = 1;
  598. foreach ($send_to['groups'] as $group) {
  599. $groupInfo = GroupManager::get_group_properties($group);
  600. api_item_property_update(
  601. $courseInfo,
  602. TOOL_ANNOUNCEMENT,
  603. $last_id,
  604. 'AnnouncementAdded',
  605. $authorId,
  606. $groupInfo
  607. );
  608. if (($counter % $batchSize) === 0) {
  609. $em->flush();
  610. $em->clear();
  611. }
  612. $counter++;
  613. }
  614. }
  615. // Storing the selected users
  616. if (is_array($send_to['users'])) {
  617. $counter = 1;
  618. foreach ($send_to['users'] as $user) {
  619. api_item_property_update(
  620. $courseInfo,
  621. TOOL_ANNOUNCEMENT,
  622. $last_id,
  623. 'AnnouncementAdded',
  624. $authorId,
  625. '',
  626. $user
  627. );
  628. if (($counter % $batchSize) === 0) {
  629. $em->flush();
  630. $em->clear();
  631. }
  632. $counter++;
  633. }
  634. }
  635. }
  636. if ($sendToUsersInSession) {
  637. self::addAnnouncementToAllUsersInSessions($last_id);
  638. }
  639. return $last_id;
  640. }
  641. }
  642. /**
  643. * @param string $title
  644. * @param string $newContent
  645. * @param int $groupId
  646. * @param array $to_users
  647. * @param array $file
  648. * @param string $file_comment
  649. * @param bool $sendToUsersInSession
  650. *
  651. * @return bool|int
  652. */
  653. public static function addGroupAnnouncement(
  654. $title,
  655. $newContent,
  656. $groupId,
  657. $to_users,
  658. $file = [],
  659. $file_comment = '',
  660. $sendToUsersInSession = false
  661. ) {
  662. $courseInfo = api_get_course_info();
  663. // Database definitions
  664. $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
  665. $order = self::getLastAnnouncementOrder($courseInfo);
  666. $now = api_get_utc_datetime();
  667. $courseId = api_get_course_int_id();
  668. // store in the table announcement
  669. $params = [
  670. 'c_id' => $courseId,
  671. 'content' => $newContent,
  672. 'title' => $title,
  673. 'end_date' => $now,
  674. 'display_order' => $order,
  675. 'session_id' => api_get_session_id(),
  676. ];
  677. $last_id = Database::insert($table, $params);
  678. // Store the attach file
  679. if ($last_id) {
  680. $sql = "UPDATE $table SET id = iid
  681. WHERE iid = $last_id";
  682. Database::query($sql);
  683. if (!empty($file)) {
  684. self::add_announcement_attachment_file(
  685. $last_id,
  686. $file_comment,
  687. $file
  688. );
  689. }
  690. $send_to_users = CourseManager::separateUsersGroups($to_users);
  691. // if nothing was selected in the menu then send to all the group
  692. $sentToAllGroup = false;
  693. if (empty($send_to_users['groups']) && empty($send_to_users['users'])) {
  694. $groupInfo = GroupManager::get_group_properties($groupId);
  695. api_item_property_update(
  696. $courseInfo,
  697. TOOL_ANNOUNCEMENT,
  698. $last_id,
  699. 'AnnouncementAdded',
  700. api_get_user_id(),
  701. $groupInfo
  702. );
  703. $sentToAllGroup = true;
  704. }
  705. if ($sentToAllGroup === false) {
  706. if (!empty($send_to_users['groups'])) {
  707. foreach ($send_to_users['groups'] as $group) {
  708. $groupInfo = GroupManager::get_group_properties($group);
  709. api_item_property_update(
  710. $courseInfo,
  711. TOOL_ANNOUNCEMENT,
  712. $last_id,
  713. 'AnnouncementAdded',
  714. api_get_user_id(),
  715. $groupInfo
  716. );
  717. }
  718. }
  719. $groupInfo = GroupManager::get_group_properties($groupId);
  720. if (!empty($send_to_users['users'])) {
  721. foreach ($send_to_users['users'] as $user) {
  722. api_item_property_update(
  723. $courseInfo,
  724. TOOL_ANNOUNCEMENT,
  725. $last_id,
  726. 'AnnouncementAdded',
  727. api_get_user_id(),
  728. $groupInfo,
  729. $user
  730. );
  731. }
  732. }
  733. }
  734. if ($sendToUsersInSession) {
  735. self::addAnnouncementToAllUsersInSessions($last_id);
  736. }
  737. }
  738. return $last_id;
  739. }
  740. /**
  741. * This function stores the announcement item in the announcement table
  742. * and updates the item_property table.
  743. *
  744. * @param int $id id of the announcement
  745. * @param string $title
  746. * @param string $newContent
  747. * @param array $to users that will receive the announcement
  748. * @param mixed $file attachment
  749. * @param string $file_comment file comment
  750. * @param bool $sendToUsersInSession
  751. */
  752. public static function edit_announcement(
  753. $id,
  754. $title,
  755. $newContent,
  756. $to,
  757. $file = [],
  758. $file_comment = '',
  759. $sendToUsersInSession = false
  760. ) {
  761. $courseInfo = api_get_course_info();
  762. $courseId = api_get_course_int_id();
  763. $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  764. $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
  765. $id = (int) $id;
  766. $params = [
  767. 'title' => $title,
  768. 'content' => $newContent,
  769. ];
  770. Database::update(
  771. $table,
  772. $params,
  773. ['c_id = ? AND id = ?' => [$courseId, $id]]
  774. );
  775. // save attachment file
  776. $row_attach = self::get_attachment($id);
  777. $id_attach = 0;
  778. if ($row_attach) {
  779. $id_attach = (int) $row_attach['id'];
  780. }
  781. if (!empty($file)) {
  782. if (empty($id_attach)) {
  783. self::add_announcement_attachment_file(
  784. $id,
  785. $file_comment,
  786. $file
  787. );
  788. } else {
  789. self::edit_announcement_attachment_file(
  790. $id_attach,
  791. $file,
  792. $file_comment
  793. );
  794. }
  795. }
  796. // We remove everything from item_property for this
  797. $sql = "DELETE FROM $tbl_item_property
  798. WHERE c_id = $courseId AND ref='$id' AND tool='announcement'";
  799. Database::query($sql);
  800. if ($sendToUsersInSession) {
  801. self::addAnnouncementToAllUsersInSessions($id);
  802. }
  803. // store in item_property (first the groups, then the users
  804. if (!empty($to)) {
  805. // !is_null($to): when no user is selected we send it to everyone
  806. $send_to = CourseManager::separateUsersGroups($to);
  807. // storing the selected groups
  808. if (is_array($send_to['groups'])) {
  809. foreach ($send_to['groups'] as $group) {
  810. $groupInfo = GroupManager::get_group_properties($group);
  811. if (empty($groupInfo)) {
  812. // Probably the group id and iid are different try checking the iid
  813. $groupInfo = GroupManager::get_group_properties($group, true);
  814. }
  815. if ($groupInfo) {
  816. api_item_property_update(
  817. $courseInfo,
  818. TOOL_ANNOUNCEMENT,
  819. $id,
  820. 'AnnouncementUpdated',
  821. api_get_user_id(),
  822. $groupInfo
  823. );
  824. }
  825. }
  826. }
  827. // storing the selected users
  828. if (is_array($send_to['users'])) {
  829. foreach ($send_to['users'] as $user) {
  830. api_item_property_update(
  831. $courseInfo,
  832. TOOL_ANNOUNCEMENT,
  833. $id,
  834. 'AnnouncementUpdated',
  835. api_get_user_id(),
  836. 0,
  837. $user
  838. );
  839. }
  840. }
  841. // Send to everyone
  842. if (isset($to[0]) && $to[0] === 'everyone') {
  843. api_item_property_update(
  844. $courseInfo,
  845. TOOL_ANNOUNCEMENT,
  846. $id,
  847. 'AnnouncementUpdated',
  848. api_get_user_id(),
  849. 0
  850. );
  851. }
  852. } else {
  853. // the message is sent to everyone, so we set the group to 0
  854. api_item_property_update(
  855. $courseInfo,
  856. TOOL_ANNOUNCEMENT,
  857. $id,
  858. 'AnnouncementUpdated',
  859. api_get_user_id(),
  860. 0
  861. );
  862. }
  863. }
  864. /**
  865. * @param int $announcementId
  866. */
  867. public static function addAnnouncementToAllUsersInSessions($announcementId)
  868. {
  869. $courseCode = api_get_course_id();
  870. $courseInfo = api_get_course_info();
  871. $sessionList = SessionManager::get_session_by_course(api_get_course_int_id());
  872. if (!empty($sessionList)) {
  873. foreach ($sessionList as $sessionInfo) {
  874. $sessionId = $sessionInfo['id'];
  875. $userList = CourseManager::get_user_list_from_course_code(
  876. $courseCode,
  877. $sessionId
  878. );
  879. if (!empty($userList)) {
  880. foreach ($userList as $user) {
  881. api_item_property_update(
  882. $courseInfo,
  883. TOOL_ANNOUNCEMENT,
  884. $announcementId,
  885. 'AnnouncementUpdated',
  886. api_get_user_id(),
  887. 0,
  888. $user['user_id'],
  889. 0,
  890. 0,
  891. $sessionId
  892. );
  893. }
  894. }
  895. }
  896. }
  897. }
  898. /**
  899. * @param int $insert_id
  900. *
  901. * @return bool
  902. */
  903. public static function update_mail_sent($insert_id)
  904. {
  905. $table = Database::get_course_table(TABLE_ANNOUNCEMENT);
  906. if ($insert_id != strval(intval($insert_id))) {
  907. return false;
  908. }
  909. $insert_id = intval($insert_id);
  910. $courseId = api_get_course_int_id();
  911. // store the modifications in the table tbl_annoucement
  912. $sql = "UPDATE $table SET email_sent='1'
  913. WHERE c_id = $courseId AND id = $insert_id";
  914. Database::query($sql);
  915. }
  916. /**
  917. * @param int $user_id
  918. *
  919. * @return array|bool
  920. */
  921. public static function getAnnoucementCourseTotalByUser($user_id)
  922. {
  923. $user_id = (int) $user_id;
  924. if (empty($user_id)) {
  925. return false;
  926. }
  927. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  928. $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  929. $sql = "SELECT DISTINCT
  930. announcement.c_id,
  931. count(announcement.id) count
  932. FROM $tbl_announcement announcement
  933. INNER JOIN $tbl_item_property ip
  934. ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
  935. WHERE
  936. ip.tool='announcement' AND
  937. (
  938. ip.to_user_id = '$user_id' AND
  939. (ip.to_group_id='0' OR ip.to_group_id IS NULL)
  940. )
  941. AND ip.visibility='1'
  942. AND announcement.session_id = 0
  943. GROUP BY announcement.c_id";
  944. $rs = Database::query($sql);
  945. $num_rows = Database::num_rows($rs);
  946. $result = [];
  947. if ($num_rows > 0) {
  948. while ($row = Database::fetch_array($rs, 'ASSOC')) {
  949. if (empty($row['c_id'])) {
  950. continue;
  951. }
  952. $result[] = ['course' => api_get_course_info_by_id($row['c_id']), 'count' => $row['count']];
  953. }
  954. }
  955. return $result;
  956. }
  957. /**
  958. * Returns announcement info from its id.
  959. *
  960. * @param int $courseId
  961. * @param int $id
  962. *
  963. * @return array
  964. */
  965. public static function get_by_id($courseId, $id)
  966. {
  967. $id = (int) $id;
  968. $courseId = $courseId ? (int) $courseId : api_get_course_int_id();
  969. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  970. $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  971. $sql = "SELECT DISTINCT
  972. announcement.id,
  973. announcement.title,
  974. announcement.content,
  975. ip.to_group_id
  976. FROM $tbl_announcement announcement
  977. INNER JOIN $tbl_item_property ip
  978. ON
  979. announcement.id = ip.ref AND
  980. announcement.c_id = ip.c_id
  981. WHERE
  982. announcement.c_id = $courseId AND
  983. ip.tool='announcement' AND
  984. announcement.id = $id
  985. ";
  986. $result = Database::query($sql);
  987. if (Database::num_rows($result)) {
  988. return Database::fetch_array($result);
  989. }
  990. return [];
  991. }
  992. /**
  993. * this function gets all the groups of the course,
  994. * not including linked courses.
  995. */
  996. public static function get_course_groups()
  997. {
  998. $session_id = api_get_session_id();
  999. if ($session_id != 0) {
  1000. $new_group_list = CourseManager::get_group_list_of_course(
  1001. api_get_course_id(),
  1002. $session_id,
  1003. 1
  1004. );
  1005. } else {
  1006. $new_group_list = CourseManager::get_group_list_of_course(
  1007. api_get_course_id(),
  1008. 0,
  1009. 1
  1010. );
  1011. }
  1012. return $new_group_list;
  1013. }
  1014. /**
  1015. * This tools loads all the users and all the groups who have received
  1016. * a specific item (in this case an announcement item).
  1017. *
  1018. * @param string $tool
  1019. * @param int $id
  1020. * @param bool $includeGroupWhenLoadingUser
  1021. *
  1022. * @return array
  1023. */
  1024. public static function loadEditUsers($tool, $id, $includeGroupWhenLoadingUser = false)
  1025. {
  1026. $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1027. $tool = Database::escape_string($tool);
  1028. $id = (int) $id;
  1029. $courseId = api_get_course_int_id();
  1030. $groupId = api_get_group_id();
  1031. $sql = "SELECT to_user_id, to_group_id FROM $table
  1032. WHERE c_id = $courseId AND tool='$tool' AND ref = $id";
  1033. $result = Database::query($sql);
  1034. $to = [];
  1035. while ($row = Database::fetch_array($result)) {
  1036. // This is the iid of c_group_info
  1037. $toGroup = $row['to_group_id'];
  1038. if (empty($row['to_user_id']) && !empty($groupId) && $groupId != $toGroup) {
  1039. //continue;
  1040. }
  1041. switch ($toGroup) {
  1042. // it was send to one specific user
  1043. case null:
  1044. if (isset($row['to_user_id']) && !empty($row['to_user_id'])) {
  1045. if (!in_array('USER:'.$row['to_user_id'], $to)) {
  1046. $to[] = 'USER:'.$row['to_user_id'];
  1047. }
  1048. }
  1049. break;
  1050. // it was sent to everyone
  1051. case 0:
  1052. return 'everyone';
  1053. break;
  1054. default:
  1055. if (isset($row['to_user_id']) && !empty($row['to_user_id'])) {
  1056. if (!in_array('USER:'.$row['to_user_id'], $to)) {
  1057. $to[] = 'USER:'.$row['to_user_id'];
  1058. }
  1059. } else {
  1060. if (!in_array('GROUP:'.$toGroup, $to)) {
  1061. $to[] = 'GROUP:'.$toGroup;
  1062. }
  1063. }
  1064. if ($includeGroupWhenLoadingUser) {
  1065. if (!in_array('GROUP:'.$toGroup, $to)) {
  1066. $to[] = 'GROUP:'.$toGroup;
  1067. }
  1068. }
  1069. break;
  1070. }
  1071. }
  1072. return $to;
  1073. }
  1074. /**
  1075. * constructs the form to display all the groups and users the message has been sent to.
  1076. *
  1077. * @param array $sent_to_array
  1078. * input:
  1079. * $sent_to_array is a 2 dimensional array containing the groups and the users
  1080. * the first level is a distinction between groups and users:
  1081. * $sent_to_array['groups'] * and $sent_to_array['users']
  1082. * $sent_to_array['groups'] (resp. $sent_to_array['users']) is also an array
  1083. * containing all the id's of the groups (resp. users) who have received this message.
  1084. *
  1085. * @return string
  1086. *
  1087. * @author Patrick Cool <patrick.cool@>
  1088. */
  1089. public static function sent_to_form($sent_to_array)
  1090. {
  1091. // we find all the names of the groups
  1092. $group_names = self::get_course_groups();
  1093. // we count the number of users and the number of groups
  1094. $number_users = 0;
  1095. if (isset($sent_to_array['users'])) {
  1096. $number_users = count($sent_to_array['users']);
  1097. }
  1098. $number_groups = 0;
  1099. if (isset($sent_to_array['groups'])) {
  1100. $number_groups = count($sent_to_array['groups']);
  1101. }
  1102. $total_numbers = $number_users + $number_groups;
  1103. // starting the form if there is more than one user/group
  1104. $output = [];
  1105. if ($total_numbers > 1) {
  1106. // outputting the name of the groups
  1107. if (is_array($sent_to_array['groups'])) {
  1108. foreach ($sent_to_array['groups'] as $group_id) {
  1109. $users = GroupManager::getStudents($group_id, true);
  1110. $userToArray = [];
  1111. foreach ($users as $student) {
  1112. $userToArray[] = $student['complete_name_with_username'];
  1113. }
  1114. $output[] =
  1115. '<br />'.
  1116. Display::label($group_names[$group_id]['name'], 'info').
  1117. '&nbsp;'.implode(', ', $userToArray);
  1118. }
  1119. }
  1120. if (isset($sent_to_array['users'])) {
  1121. if (is_array($sent_to_array['users'])) {
  1122. $usersToArray = [];
  1123. foreach ($sent_to_array['users'] as $user_id) {
  1124. $user_info = api_get_user_info($user_id);
  1125. $usersToArray[] = $user_info['complete_name_with_username'];
  1126. }
  1127. $output[] = '<br />'.Display::label(get_lang('Users')).'&nbsp;'.implode(', ', $usersToArray);
  1128. }
  1129. }
  1130. } else {
  1131. // there is only one user/group
  1132. if (isset($sent_to_array['users']) && is_array($sent_to_array['users'])) {
  1133. $user_info = api_get_user_info($sent_to_array['users'][0]);
  1134. $output[] = api_get_person_name($user_info['firstname'], $user_info['lastname']);
  1135. }
  1136. if (isset($sent_to_array['groups']) &&
  1137. is_array($sent_to_array['groups']) &&
  1138. isset($sent_to_array['groups'][0]) &&
  1139. $sent_to_array['groups'][0] !== 0
  1140. ) {
  1141. $group_id = $sent_to_array['groups'][0];
  1142. $users = GroupManager::getStudents($group_id, true);
  1143. $userToArray = [];
  1144. foreach ($users as $student) {
  1145. $userToArray[] = $student['complete_name_with_username'];
  1146. }
  1147. $output[] =
  1148. '<br />'.
  1149. Display::label($group_names[$group_id]['name'], 'info').
  1150. '&nbsp;'.implode(', ', $userToArray);
  1151. }
  1152. if (empty($sent_to_array['groups']) && empty($sent_to_array['users'])) {
  1153. $output[] = "&nbsp;".get_lang('Everybody');
  1154. }
  1155. }
  1156. if (!empty($output)) {
  1157. $output = array_filter($output);
  1158. if (count($output) > 0) {
  1159. $output = implode('<br />', $output);
  1160. }
  1161. return $output;
  1162. }
  1163. }
  1164. /**
  1165. * Returns all the users and all the groups a specific announcement item
  1166. * has been sent to.
  1167. *
  1168. * @param string The tool (announcement, agenda, ...)
  1169. * @param int ID of the element of the corresponding type
  1170. *
  1171. * @return array Array of users and groups to whom the element has been sent
  1172. */
  1173. public static function sent_to($tool, $id)
  1174. {
  1175. $table = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1176. $tool = Database::escape_string($tool);
  1177. $id = (int) $id;
  1178. $sent_to_group = [];
  1179. $sent_to = [];
  1180. $courseId = api_get_course_int_id();
  1181. $sql = "SELECT to_group_id, to_user_id
  1182. FROM $table
  1183. WHERE c_id = $courseId AND tool = '$tool' AND ref=".$id;
  1184. $result = Database::query($sql);
  1185. while ($row = Database::fetch_array($result)) {
  1186. // if to_user_id <> 0 then it is sent to a specific user
  1187. if ($row['to_user_id'] != 0) {
  1188. $sent_to_user[] = $row['to_user_id'];
  1189. continue;
  1190. }
  1191. // if to_group_id is null then it is sent to a specific user
  1192. // if to_group_id = 0 then it is sent to everybody
  1193. if ($row['to_group_id'] != 0) {
  1194. $sent_to_group[] = $row['to_group_id'];
  1195. }
  1196. }
  1197. if (isset($sent_to_group)) {
  1198. $sent_to['groups'] = $sent_to_group;
  1199. }
  1200. if (isset($sent_to_user)) {
  1201. $sent_to['users'] = $sent_to_user;
  1202. }
  1203. return $sent_to;
  1204. }
  1205. /**
  1206. * Show a list with all the attachments according to the post's id.
  1207. *
  1208. * @param int $announcementId
  1209. *
  1210. * @return array with the post info
  1211. *
  1212. * @author Arthur Portugal
  1213. *
  1214. * @version November 2009, dokeos 1.8.6.2
  1215. */
  1216. public static function get_attachment($announcementId)
  1217. {
  1218. $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
  1219. $announcementId = (int) $announcementId;
  1220. $courseId = api_get_course_int_id();
  1221. $row = [];
  1222. $sql = 'SELECT id, path, filename, comment
  1223. FROM '.$table.'
  1224. WHERE c_id = '.$courseId.' AND announcement_id = '.$announcementId;
  1225. $result = Database::query($sql);
  1226. if (Database::num_rows($result) != 0) {
  1227. $row = Database::fetch_array($result, 'ASSOC');
  1228. }
  1229. return $row;
  1230. }
  1231. /**
  1232. * This function add a attachment file into announcement.
  1233. *
  1234. * @param int announcement id
  1235. * @param string file comment
  1236. * @param array uploaded file $_FILES
  1237. *
  1238. * @return int -1 if failed, 0 if unknown (should not happen), 1 if success
  1239. */
  1240. public static function add_announcement_attachment_file(
  1241. $announcement_id,
  1242. $file_comment,
  1243. $file
  1244. ) {
  1245. $courseInfo = api_get_course_info();
  1246. $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
  1247. $return = 0;
  1248. $announcement_id = intval($announcement_id);
  1249. $courseId = api_get_course_int_id();
  1250. if (is_array($file) && $file['error'] == 0) {
  1251. // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
  1252. $courseDir = $courseInfo['path'].'/upload/announcements';
  1253. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  1254. $updir = $sys_course_path.$courseDir;
  1255. // Try to add an extension to the file if it hasn't one
  1256. $new_file_name = add_ext_on_mime(stripslashes($file['name']), $file['type']);
  1257. // user's file name
  1258. $file_name = $file['name'];
  1259. if (!filter_extension($new_file_name)) {
  1260. $return = -1;
  1261. echo Display::return_message(get_lang('UplUnableToSaveFileFilteredExtension'), 'error');
  1262. } else {
  1263. $new_file_name = uniqid('');
  1264. $new_path = $updir.'/'.$new_file_name;
  1265. // This file is copy here but its cleaned in api_mail_html in api.lib.php
  1266. copy($file['tmp_name'], $new_path);
  1267. $params = [
  1268. 'c_id' => $courseId,
  1269. 'filename' => $file_name,
  1270. 'comment' => $file_comment,
  1271. 'path' => $new_file_name,
  1272. 'announcement_id' => $announcement_id,
  1273. 'size' => intval($file['size']),
  1274. ];
  1275. $insertId = Database::insert($table, $params);
  1276. if ($insertId) {
  1277. $sql = "UPDATE $table SET id = iid
  1278. WHERE iid = $insertId";
  1279. Database::query($sql);
  1280. }
  1281. $return = 1;
  1282. }
  1283. }
  1284. return $return;
  1285. }
  1286. /**
  1287. * This function edit a attachment file into announcement.
  1288. *
  1289. * @param int attach id
  1290. * @param array uploaded file $_FILES
  1291. * @param string file comment
  1292. *
  1293. * @return int
  1294. */
  1295. public static function edit_announcement_attachment_file(
  1296. $id_attach,
  1297. $file,
  1298. $file_comment
  1299. ) {
  1300. $courseInfo = api_get_course_info();
  1301. $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
  1302. $return = 0;
  1303. $courseId = api_get_course_int_id();
  1304. if (is_array($file) && $file['error'] == 0) {
  1305. // TODO: This path is obsolete. The new document repository scheme should be kept in mind here.
  1306. $courseDir = $courseInfo['path'].'/upload/announcements';
  1307. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  1308. $updir = $sys_course_path.$courseDir;
  1309. // Try to add an extension to the file if it hasn't one
  1310. $new_file_name = add_ext_on_mime(
  1311. stripslashes($file['name']),
  1312. $file['type']
  1313. );
  1314. // user's file name
  1315. $file_name = $file['name'];
  1316. if (!filter_extension($new_file_name)) {
  1317. $return = -1;
  1318. echo Display::return_message(
  1319. get_lang('UplUnableToSaveFileFilteredExtension'),
  1320. 'error'
  1321. );
  1322. } else {
  1323. $new_file_name = uniqid('');
  1324. $new_path = $updir.'/'.$new_file_name;
  1325. copy($file['tmp_name'], $new_path);
  1326. $safe_file_comment = Database::escape_string($file_comment);
  1327. $safe_file_name = Database::escape_string($file_name);
  1328. $safe_new_file_name = Database::escape_string($new_file_name);
  1329. $id_attach = intval($id_attach);
  1330. $sql = "UPDATE $table SET
  1331. filename = '$safe_file_name',
  1332. comment = '$safe_file_comment',
  1333. path = '$safe_new_file_name',
  1334. size ='".intval($file['size'])."'
  1335. WHERE c_id = $courseId AND id = '$id_attach'";
  1336. $result = Database::query($sql);
  1337. if ($result === false) {
  1338. $return = -1;
  1339. echo Display::return_message(
  1340. get_lang('UplUnableToSaveFile'),
  1341. 'error'
  1342. );
  1343. } else {
  1344. $return = 1;
  1345. }
  1346. }
  1347. }
  1348. return $return;
  1349. }
  1350. /**
  1351. * This function delete a attachment file by id.
  1352. *
  1353. * @param int $id attachment file Id
  1354. *
  1355. * @return bool
  1356. */
  1357. public static function delete_announcement_attachment_file($id)
  1358. {
  1359. $table = Database::get_course_table(TABLE_ANNOUNCEMENT_ATTACHMENT);
  1360. $id = intval($id);
  1361. $courseId = api_get_course_int_id();
  1362. if (empty($courseId) || empty($id)) {
  1363. return false;
  1364. }
  1365. $sql = "DELETE FROM $table
  1366. WHERE c_id = $courseId AND id = $id";
  1367. Database::query($sql);
  1368. return true;
  1369. }
  1370. /**
  1371. * @param array $courseInfo
  1372. * @param int $sessionId
  1373. * @param int $announcementId
  1374. * @param bool $sendToUsersInSession
  1375. * @param bool $sendToDrhUsers
  1376. * @param Monolog\Handler\HandlerInterface logger
  1377. * @param int $senderId
  1378. * @param bool $directMessage
  1379. *
  1380. * @return array
  1381. */
  1382. public static function sendEmail(
  1383. $courseInfo,
  1384. $sessionId,
  1385. $announcementId,
  1386. $sendToUsersInSession = false,
  1387. $sendToDrhUsers = false,
  1388. $logger = null,
  1389. $senderId = 0,
  1390. $directMessage = false
  1391. ) {
  1392. $email = new AnnouncementEmail($courseInfo, $sessionId, $announcementId, $logger);
  1393. return $email->send($sendToUsersInSession, $sendToDrhUsers, $senderId, $directMessage);
  1394. }
  1395. /**
  1396. * @param $stok
  1397. * @param $announcement_number
  1398. * @param bool $getCount
  1399. * @param null $start
  1400. * @param null $limit
  1401. * @param string $sidx
  1402. * @param string $sord
  1403. * @param string $titleToSearch
  1404. * @param int $userIdToSearch
  1405. * @param int $userId
  1406. * @param int $courseId
  1407. * @param int $sessionId
  1408. *
  1409. * @return array
  1410. */
  1411. public static function getAnnouncements(
  1412. $stok,
  1413. $announcement_number,
  1414. $getCount = false,
  1415. $start = null,
  1416. $limit = null,
  1417. $sidx = '',
  1418. $sord = '',
  1419. $titleToSearch = '',
  1420. $userIdToSearch = 0,
  1421. $userId = 0,
  1422. $courseId = 0,
  1423. $sessionId = 0
  1424. ) {
  1425. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  1426. $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1427. $user_id = $userId ?: api_get_user_id();
  1428. $group_id = api_get_group_id();
  1429. $session_id = $sessionId ?: api_get_session_id();
  1430. if (empty($courseId)) {
  1431. $courseInfo = api_get_course_info();
  1432. $courseId = $courseInfo['real_id'];
  1433. } else {
  1434. $courseId = (int) $courseId;
  1435. $courseInfo = api_get_course_info_by_id($courseId);
  1436. }
  1437. if (empty($courseInfo)) {
  1438. return [];
  1439. }
  1440. $condition_session = api_get_session_condition(
  1441. $session_id,
  1442. true,
  1443. true,
  1444. 'announcement.session_id'
  1445. );
  1446. $group_memberships = GroupManager::get_group_ids(
  1447. $courseId,
  1448. api_get_user_id()
  1449. );
  1450. $allowUserEditSetting = api_get_course_setting('allow_user_edit_announcement');
  1451. $select = ' DISTINCT
  1452. announcement.*,
  1453. ip.visibility,
  1454. ip.to_group_id,
  1455. ip.insert_user_id,
  1456. ip.insert_date,
  1457. ip.lastedit_date';
  1458. $groupBy = ' GROUP BY announcement.iid';
  1459. if ($getCount) {
  1460. $groupBy = '';
  1461. $select = ' COUNT(DISTINCT announcement.iid) count';
  1462. }
  1463. $searchCondition = '';
  1464. if (!empty($titleToSearch)) {
  1465. $titleToSearch = Database::escape_string($titleToSearch);
  1466. $searchCondition .= " AND (title LIKE '%$titleToSearch%')";
  1467. }
  1468. if (!empty($userIdToSearch)) {
  1469. $userIdToSearch = (int) $userIdToSearch;
  1470. $searchCondition .= " AND (ip.insert_user_id = $userIdToSearch)";
  1471. }
  1472. $allowOnlyGroup = api_get_configuration_value('hide_base_course_announcements_in_group');
  1473. $extraGroupCondition = '';
  1474. if ($allowOnlyGroup) {
  1475. $extraGroupCondition = " AND ip.to_group_id = $group_id ";
  1476. }
  1477. $allowDrhAccess = api_get_configuration_value('allow_drh_access_announcement');
  1478. if ($allowDrhAccess && api_is_drh()) {
  1479. // DRH only can see visible
  1480. $searchCondition .= ' AND (ip.visibility = 1)';
  1481. }
  1482. if (api_is_allowed_to_edit(false, true) ||
  1483. ($allowUserEditSetting && !api_is_anonymous()) ||
  1484. ($allowDrhAccess && api_is_drh())
  1485. ) {
  1486. // A.1. you are a course admin with a USER filter
  1487. // => see only the messages of this specific user + the messages of the group (s)he is member of.
  1488. //if (!empty($user_id)) {
  1489. if (0) {
  1490. if (is_array($group_memberships) &&
  1491. count($group_memberships) > 0
  1492. ) {
  1493. $sql = "SELECT $select
  1494. FROM $tbl_announcement announcement
  1495. INNER JOIN $tbl_item_property ip
  1496. ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
  1497. WHERE
  1498. announcement.c_id = $courseId AND
  1499. ip.c_id = $courseId AND
  1500. ip.tool = 'announcement' AND
  1501. (
  1502. ip.to_user_id = $user_id OR
  1503. ip.to_group_id IS NULL OR
  1504. ip.to_group_id IN (0, ".implode(", ", $group_memberships).")
  1505. ) AND
  1506. ip.visibility IN ('1', '0')
  1507. $condition_session
  1508. $searchCondition
  1509. ORDER BY display_order DESC";
  1510. } else {
  1511. $sql = "SELECT $select
  1512. FROM $tbl_announcement announcement
  1513. INNER JOIN $tbl_item_property ip
  1514. ON (announcement.id = ip.ref AND ip.c_id = announcement.c_id)
  1515. WHERE
  1516. announcement.c_id = $courseId AND
  1517. ip.c_id = $courseId AND
  1518. ip.tool ='announcement' AND
  1519. (ip.to_user_id = $user_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL) AND
  1520. ip.visibility IN ('1', '0')
  1521. $condition_session
  1522. $searchCondition
  1523. ORDER BY display_order DESC";
  1524. }
  1525. } elseif ($group_id != 0) {
  1526. // A.2. you are a course admin with a GROUP filter
  1527. // => see only the messages of this specific group
  1528. $sql = "SELECT $select
  1529. FROM $tbl_announcement announcement
  1530. INNER JOIN $tbl_item_property ip
  1531. ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
  1532. WHERE
  1533. ip.tool='announcement' AND
  1534. announcement.c_id = $courseId AND
  1535. ip.c_id = $courseId AND
  1536. ip.visibility<>'2' AND
  1537. (ip.to_group_id = $group_id OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
  1538. $condition_session
  1539. $searchCondition
  1540. $extraGroupCondition
  1541. $groupBy
  1542. ORDER BY display_order DESC";
  1543. } else {
  1544. // A.3 you are a course admin without any group or user filter
  1545. // A.3.a you are a course admin without user or group filter but WITH studentview
  1546. // => see all the messages of all the users and groups without editing possibilities
  1547. if (isset($isStudentView) && $isStudentView == 'true') {
  1548. $sql = "SELECT $select
  1549. FROM $tbl_announcement announcement
  1550. INNER JOIN $tbl_item_property ip
  1551. ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
  1552. WHERE
  1553. ip.tool='announcement' AND
  1554. announcement.c_id = $courseId AND
  1555. ip.c_id = $courseId AND
  1556. ip.visibility='1'
  1557. $condition_session
  1558. $searchCondition
  1559. $groupBy
  1560. ORDER BY display_order DESC";
  1561. } else {
  1562. // A.3.a you are a course admin without user or group filter and WTIHOUT studentview (= the normal course admin view)
  1563. // => see all the messages of all the users and groups with editing possibilities
  1564. $sql = "SELECT $select
  1565. FROM $tbl_announcement announcement
  1566. INNER JOIN $tbl_item_property ip
  1567. ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
  1568. WHERE
  1569. ip.tool = 'announcement' AND
  1570. announcement.c_id = $courseId AND
  1571. ip.c_id = $courseId AND
  1572. (ip.visibility='0' OR ip.visibility='1')
  1573. $condition_session
  1574. $searchCondition
  1575. $groupBy
  1576. ORDER BY display_order DESC";
  1577. }
  1578. }
  1579. } else {
  1580. // STUDENT
  1581. if (is_array($group_memberships) && count($group_memberships) > 0) {
  1582. if ($allowUserEditSetting && !api_is_anonymous()) {
  1583. if ($group_id == 0) {
  1584. // No group
  1585. $cond_user_id = " AND (
  1586. ip.lastedit_user_id = '".$user_id."' OR (
  1587. (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) OR
  1588. (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
  1589. )
  1590. ) ";
  1591. } else {
  1592. $cond_user_id = " AND (
  1593. ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id.")
  1594. )";
  1595. $cond_user_id .= $extraGroupCondition;
  1596. }
  1597. } else {
  1598. if ($group_id == 0) {
  1599. $cond_user_id = " AND (
  1600. (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
  1601. (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships)."))
  1602. ) ";
  1603. } else {
  1604. $cond_user_id = " AND (
  1605. (ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
  1606. (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".$group_id."))
  1607. )";
  1608. $cond_user_id .= $extraGroupCondition;
  1609. }
  1610. }
  1611. $sql = "SELECT $select
  1612. FROM $tbl_announcement announcement INNER JOIN
  1613. $tbl_item_property ip
  1614. ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
  1615. WHERE
  1616. announcement.c_id = $courseId AND
  1617. ip.c_id = $courseId AND
  1618. ip.tool='announcement'
  1619. $cond_user_id
  1620. $condition_session
  1621. $searchCondition AND
  1622. ip.visibility='1'
  1623. $groupBy
  1624. ORDER BY display_order DESC";
  1625. } else {
  1626. if ($user_id) {
  1627. if ($allowUserEditSetting && !api_is_anonymous()) {
  1628. $cond_user_id = " AND (
  1629. ip.lastedit_user_id = '".api_get_user_id()."' OR
  1630. ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
  1631. (ip.to_group_id='0' OR ip.to_group_id IS NULL)
  1632. )
  1633. ) ";
  1634. } else {
  1635. $cond_user_id = " AND ((ip.to_user_id='$user_id' OR ip.to_user_id IS NULL) AND
  1636. (ip.to_group_id='0' OR ip.to_group_id IS NULL) ) ";
  1637. }
  1638. $sql = "SELECT $select
  1639. FROM $tbl_announcement announcement
  1640. INNER JOIN $tbl_item_property ip
  1641. ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
  1642. WHERE
  1643. announcement.c_id = $courseId AND
  1644. ip.c_id = $courseId AND
  1645. ip.tool='announcement'
  1646. $cond_user_id
  1647. $condition_session
  1648. $searchCondition
  1649. AND ip.visibility='1'
  1650. AND announcement.session_id IN(0, ".$session_id.")
  1651. $groupBy
  1652. ORDER BY display_order DESC";
  1653. } else {
  1654. if (($allowUserEditSetting && !api_is_anonymous())) {
  1655. $cond_user_id = " AND (
  1656. ip.lastedit_user_id = '".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
  1657. )";
  1658. } else {
  1659. $cond_user_id = " AND ip.to_group_id='0' OR ip.to_group_id IS NULL ";
  1660. }
  1661. $sql = "SELECT $select
  1662. FROM $tbl_announcement announcement
  1663. INNER JOIN $tbl_item_property ip
  1664. ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
  1665. WHERE
  1666. announcement.c_id = $courseId AND
  1667. ip.c_id = $courseId AND
  1668. ip.tool='announcement'
  1669. $cond_user_id
  1670. $condition_session
  1671. $searchCondition AND
  1672. ip.visibility='1' AND
  1673. announcement.session_id IN ( 0,".api_get_session_id().")
  1674. $groupBy
  1675. ";
  1676. }
  1677. }
  1678. }
  1679. if (!is_null($start) && !is_null($limit)) {
  1680. $start = (int) $start;
  1681. $limit = (int) $limit;
  1682. $sql .= " LIMIT $start, $limit";
  1683. }
  1684. $result = Database::query($sql);
  1685. if ($getCount) {
  1686. $result = Database::fetch_array($result, 'ASSOC');
  1687. return $result['count'];
  1688. }
  1689. $iterator = 1;
  1690. $bottomAnnouncement = $announcement_number;
  1691. $displayed = [];
  1692. $results = [];
  1693. $actionUrl = api_get_path(WEB_CODE_PATH).'announcements/announcements.php?'.api_get_cidreq();
  1694. $emailIcon = '<i class="fa fa-envelope-o" title="'.get_lang('AnnounceSentByEmail').'"></i>';
  1695. $attachmentIcon = '<i class="fa fa-paperclip" title="'.get_lang('Attachment').'"></i>';
  1696. $editIcon = Display::return_icon(
  1697. 'edit.png',
  1698. get_lang('Edit'),
  1699. '',
  1700. ICON_SIZE_SMALL
  1701. );
  1702. $editIconDisable = Display::return_icon(
  1703. 'edit_na.png',
  1704. get_lang('Edit'),
  1705. '',
  1706. ICON_SIZE_SMALL
  1707. );
  1708. $deleteIcon = Display::return_icon(
  1709. 'delete.png',
  1710. get_lang('Delete'),
  1711. '',
  1712. ICON_SIZE_SMALL
  1713. );
  1714. $deleteIconDisable = Display::return_icon(
  1715. 'delete_na.png',
  1716. get_lang('Delete'),
  1717. '',
  1718. ICON_SIZE_SMALL
  1719. );
  1720. $isTutor = false;
  1721. if (!empty($group_id)) {
  1722. $groupInfo = GroupManager::get_group_properties(api_get_group_id());
  1723. //User has access in the group?
  1724. $isTutor = GroupManager::is_tutor_of_group(
  1725. api_get_user_id(),
  1726. $groupInfo
  1727. );
  1728. }
  1729. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1730. if (!in_array($row['id'], $displayed)) {
  1731. $sent_to_icon = '';
  1732. // the email icon
  1733. if ($row['email_sent'] == '1') {
  1734. $sent_to_icon = ' '.$emailIcon;
  1735. }
  1736. $groupReference = $row['to_group_id'] > 0 ? ' <span class="label label-info">'.get_lang('Group').'</span> ' : '';
  1737. $disableEdit = false;
  1738. $to = self::loadEditUsers('announcement', $row['id'], true);
  1739. $separated = CourseManager::separateUsersGroups($to);
  1740. if (!empty($group_id)) {
  1741. // If the announcement was sent to many groups, disable edition inside a group
  1742. if (isset($separated['groups']) && count($separated['groups']) > 1) {
  1743. $disableEdit = true;
  1744. }
  1745. // If the announcement was sent only to the course disable edition
  1746. if (empty($separated['groups']) && empty($separated['users'])) {
  1747. $disableEdit = true;
  1748. }
  1749. // Announcement sent to only a user
  1750. if ($separated['groups'] > 1 && !in_array($group_id, $separated['groups'])) {
  1751. $disableEdit = true;
  1752. }
  1753. } else {
  1754. if (isset($separated['groups']) && count($separated['groups']) > 1) {
  1755. $groupReference = '';
  1756. }
  1757. }
  1758. $title = $row['title'].$groupReference.$sent_to_icon;
  1759. $item_visibility = api_get_item_visibility(
  1760. $courseInfo,
  1761. TOOL_ANNOUNCEMENT,
  1762. $row['id'],
  1763. $session_id
  1764. );
  1765. $row['visibility'] = $item_visibility;
  1766. // show attachment list
  1767. $attachment_list = self::get_attachment($row['id']);
  1768. $attachment_icon = '';
  1769. if (count($attachment_list) > 0) {
  1770. $attachment_icon = ' '.$attachmentIcon;
  1771. }
  1772. /* TITLE */
  1773. $user_info = api_get_user_info($row['insert_user_id']);
  1774. $username = sprintf(get_lang('LoginX'), $user_info['username']);
  1775. $username_span = Display::tag(
  1776. 'span',
  1777. $user_info['complete_name'],
  1778. ['title' => $username]
  1779. );
  1780. $title = Display::url(
  1781. $title.$attachment_icon,
  1782. $actionUrl.'&action=view&id='.$row['id']
  1783. );
  1784. // we can edit if : we are the teacher OR the element belongs to
  1785. // the session we are coaching OR the option to allow users to edit is on
  1786. if (api_is_allowed_to_edit(false, true) ||
  1787. (api_is_session_general_coach() && api_is_element_in_the_session(TOOL_ANNOUNCEMENT, $row['id'])) ||
  1788. (api_get_course_setting('allow_user_edit_announcement') && !api_is_anonymous()) ||
  1789. ($row['to_group_id'] == $group_id && $isTutor)
  1790. ) {
  1791. if ($disableEdit === true) {
  1792. $modify_icons = "<a href='#'>".$editIconDisable."</a>";
  1793. } else {
  1794. $modify_icons = "<a href=\"".$actionUrl."&action=modify&id=".$row['id']."\">".$editIcon."</a>";
  1795. }
  1796. if ($row['visibility'] == 1) {
  1797. $image_visibility = "visible";
  1798. $alt_visibility = get_lang('Hide');
  1799. } else {
  1800. $image_visibility = "invisible";
  1801. $alt_visibility = get_lang('Visible');
  1802. }
  1803. $modify_icons .= "<a href=\"".$actionUrl."&action=showhide&id=".$row['id']."&sec_token=".$stok."\">".
  1804. Display::return_icon($image_visibility.'.png', $alt_visibility, '', ICON_SIZE_SMALL)."</a>";
  1805. // DISPLAY MOVE UP COMMAND only if it is not the top announcement
  1806. if ($iterator != 1) {
  1807. $modify_icons .= "<a href=\"".$actionUrl."&action=move&up=".$row["id"]."&sec_token=".$stok."\">".
  1808. Display::return_icon('up.gif', get_lang('Up'))."</a>";
  1809. } else {
  1810. $modify_icons .= Display::return_icon('up_na.gif', get_lang('Up'));
  1811. }
  1812. if ($iterator < $bottomAnnouncement) {
  1813. $modify_icons .= "<a href=\"".$actionUrl."&action=move&down=".$row["id"]."&sec_token=".$stok."\">".
  1814. Display::return_icon('down.gif', get_lang('Down'))."</a>";
  1815. } else {
  1816. $modify_icons .= Display::return_icon('down_na.gif', get_lang('Down'));
  1817. }
  1818. if (api_is_allowed_to_edit(false, true)) {
  1819. if ($disableEdit === true) {
  1820. $modify_icons .= Display::url($deleteIconDisable, '#');
  1821. } else {
  1822. $modify_icons .= "<a href=\"".$actionUrl."&action=delete&id=".$row['id']."&sec_token=".$stok."\" onclick=\"javascript:if(!confirm('".addslashes(
  1823. api_htmlentities(
  1824. get_lang('ConfirmYourChoice'),
  1825. ENT_QUOTES,
  1826. api_get_system_encoding()
  1827. )
  1828. )."')) return false;\">".
  1829. $deleteIcon."</a>";
  1830. }
  1831. }
  1832. $iterator++;
  1833. } else {
  1834. $modify_icons = Display::url(
  1835. Display::return_icon('default.png'),
  1836. $actionUrl.'&action=view&id='.$row['id']
  1837. );
  1838. }
  1839. $announcement = [
  1840. 'id' => $row['id'],
  1841. 'title' => $title,
  1842. 'username' => $username_span,
  1843. 'insert_date' => api_convert_and_format_date(
  1844. $row['insert_date'],
  1845. DATE_TIME_FORMAT_LONG
  1846. ),
  1847. 'lastedit_date' => api_convert_and_format_date(
  1848. $row['lastedit_date'],
  1849. DATE_TIME_FORMAT_LONG
  1850. ),
  1851. 'actions' => $modify_icons,
  1852. ];
  1853. $results[] = $announcement;
  1854. }
  1855. $displayed[] = $row['id'];
  1856. }
  1857. return $results;
  1858. }
  1859. /**
  1860. * @return int
  1861. */
  1862. public static function getNumberAnnouncements()
  1863. {
  1864. // Maximum title messages to display
  1865. $maximum = '12';
  1866. // Database Table Definitions
  1867. $tbl_announcement = Database::get_course_table(TABLE_ANNOUNCEMENT);
  1868. $tbl_item_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1869. $session_id = api_get_session_id();
  1870. $courseInfo = api_get_course_info();
  1871. $courseId = $courseInfo['real_id'];
  1872. $userId = api_get_user_id();
  1873. $condition_session = api_get_session_condition(
  1874. $session_id,
  1875. true,
  1876. true,
  1877. 'announcement.session_id'
  1878. );
  1879. if (api_is_allowed_to_edit(false, true)) {
  1880. // check teacher status
  1881. if (empty($_GET['origin']) || $_GET['origin'] !== 'learnpath') {
  1882. if (api_get_group_id() == 0) {
  1883. $group_condition = '';
  1884. } else {
  1885. $group_condition = " AND (ip.to_group_id='".api_get_group_id()."' OR ip.to_group_id = 0 OR ip.to_group_id IS NULL)";
  1886. }
  1887. $sql = "SELECT
  1888. announcement.*,
  1889. ip.visibility,
  1890. ip.to_group_id,
  1891. ip.insert_user_id
  1892. FROM $tbl_announcement announcement
  1893. INNER JOIN $tbl_item_property ip
  1894. ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
  1895. WHERE
  1896. announcement.c_id = $courseId AND
  1897. ip.c_id = $courseId AND
  1898. ip.tool = 'announcement' AND
  1899. ip.visibility <> '2'
  1900. $group_condition
  1901. $condition_session
  1902. GROUP BY ip.ref
  1903. ORDER BY display_order DESC
  1904. LIMIT 0, $maximum";
  1905. }
  1906. } else {
  1907. // students only get to see the visible announcements
  1908. if (empty($_GET['origin']) || $_GET['origin'] !== 'learnpath') {
  1909. $group_memberships = GroupManager::get_group_ids(
  1910. $courseInfo['real_id'],
  1911. $userId
  1912. );
  1913. if ((api_get_course_setting('allow_user_edit_announcement') &&
  1914. !api_is_anonymous())
  1915. ) {
  1916. if (api_get_group_id() == 0) {
  1917. $cond_user_id = " AND (
  1918. ip.lastedit_user_id = '".$userId."' OR (
  1919. ip.to_user_id='".$userId."' OR
  1920. ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
  1921. ip.to_group_id IS NULL
  1922. )
  1923. )
  1924. ";
  1925. } else {
  1926. $cond_user_id = " AND (
  1927. ip.lastedit_user_id = '".$userId."'OR
  1928. ip.to_group_id IN (0, ".api_get_group_id().") OR
  1929. ip.to_group_id IS NULL
  1930. )";
  1931. }
  1932. } else {
  1933. if (api_get_group_id() == 0) {
  1934. $cond_user_id = " AND (
  1935. ip.to_user_id='".$userId."' OR
  1936. ip.to_group_id IN (0, ".implode(", ", $group_memberships).") OR
  1937. ip.to_group_id IS NULL
  1938. ) ";
  1939. } else {
  1940. $cond_user_id = " AND (
  1941. ip.to_user_id='".$userId."' OR
  1942. ip.to_group_id IN (0, ".api_get_group_id().") OR
  1943. ip.to_group_id IS NULL
  1944. ) ";
  1945. }
  1946. }
  1947. // the user is member of several groups => display personal announcements AND
  1948. // his group announcements AND the general announcements
  1949. if (is_array($group_memberships) && count($group_memberships) > 0) {
  1950. $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
  1951. FROM $tbl_announcement announcement
  1952. INNER JOIN $tbl_item_property ip
  1953. ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
  1954. WHERE
  1955. announcement.c_id = $courseId AND
  1956. ip.c_id = $courseId AND
  1957. ip.tool='announcement' AND
  1958. ip.visibility='1'
  1959. $cond_user_id
  1960. $condition_session
  1961. GROUP BY ip.ref
  1962. ORDER BY display_order DESC
  1963. LIMIT 0, $maximum";
  1964. } else {
  1965. // the user is not member of any group
  1966. // this is an identified user => show the general announcements AND his personal announcements
  1967. if ($userId) {
  1968. if ((api_get_course_setting('allow_user_edit_announcement') &&
  1969. !api_is_anonymous())
  1970. ) {
  1971. $cond_user_id = " AND (
  1972. ip.lastedit_user_id = '".$userId."' OR
  1973. ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
  1974. ) ";
  1975. } else {
  1976. $cond_user_id = " AND ( ip.to_user_id='".$userId."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ";
  1977. }
  1978. $sql = "SELECT announcement.*, ip.visibility, ip.to_group_id, ip.insert_user_id
  1979. FROM $tbl_announcement announcement
  1980. INNER JOIN $tbl_item_property ip
  1981. ON (announcement.c_id = ip.c_id AND announcement.id = ip.ref)
  1982. WHERE
  1983. announcement.c_id = $courseId AND
  1984. ip.c_id = $courseId AND
  1985. ip.tool='announcement' AND
  1986. ip.visibility='1'
  1987. $cond_user_id
  1988. $condition_session
  1989. GROUP BY ip.ref
  1990. ORDER BY display_order DESC
  1991. LIMIT 0, $maximum";
  1992. } else {
  1993. if (api_get_course_setting('allow_user_edit_announcement')) {
  1994. $cond_user_id = " AND (
  1995. ip.lastedit_user_id = '".api_get_user_id()."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL
  1996. ) ";
  1997. } else {
  1998. $cond_user_id = " AND ip.to_group_id='0' ";
  1999. }
  2000. // the user is not identiefied => show only the general announcements
  2001. $sql = "SELECT
  2002. announcement.*,
  2003. ip.visibility,
  2004. ip.to_group_id,
  2005. ip.insert_user_id
  2006. FROM $tbl_announcement announcement
  2007. INNER JOIN $tbl_item_property ip
  2008. ON (announcement.id = ip.ref AND announcement.c_id = ip.c_id)
  2009. WHERE
  2010. announcement.c_id = $courseId AND
  2011. ip.c_id = $courseId AND
  2012. ip.tool='announcement' AND
  2013. ip.visibility='1' AND
  2014. ip.to_group_id='0'
  2015. $condition_session
  2016. GROUP BY ip.ref
  2017. ORDER BY display_order DESC
  2018. LIMIT 0, $maximum";
  2019. }
  2020. }
  2021. }
  2022. }
  2023. $result = Database::query($sql);
  2024. return Database::num_rows($result);
  2025. }
  2026. }