agenda.lib.php 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class Agenda.
  5. *
  6. * @author: Julio Montoya <gugli100@gmail.com>
  7. */
  8. class Agenda
  9. {
  10. public $events = [];
  11. /** @var string Current type */
  12. public $type = 'personal';
  13. public $types = ['personal', 'admin', 'course'];
  14. public $sessionId = 0;
  15. public $senderId;
  16. /** @var array */
  17. public $course;
  18. /** @var string */
  19. public $comment;
  20. public $eventStudentPublicationColor;
  21. /** @var array */
  22. private $sessionInfo;
  23. /** @var bool */
  24. private $isAllowedToEdit;
  25. /**
  26. * Constructor.
  27. *
  28. * @param string $type
  29. * @param int $senderId Optional The user sender ID
  30. * @param int $courseId Optional. The course ID
  31. * @param int $sessionId Optional The session ID
  32. */
  33. public function __construct(
  34. $type,
  35. $senderId = 0,
  36. $courseId = 0,
  37. $sessionId = 0
  38. ) {
  39. // Table definitions
  40. $this->tbl_global_agenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
  41. $this->tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
  42. $this->tbl_course_agenda = Database::get_course_table(TABLE_AGENDA);
  43. $this->table_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT);
  44. $this->setType($type);
  45. $this->setSenderId($senderId ?: api_get_user_id());
  46. $isAllowToEdit = false;
  47. switch ($type) {
  48. case 'course':
  49. $sessionId = $sessionId ?: api_get_session_id();
  50. $sessionInfo = api_get_session_info($sessionId);
  51. $this->setSessionId($sessionId);
  52. $this->setSessionInfo($sessionInfo);
  53. // Setting the course object if we are in a course
  54. $courseInfo = api_get_course_info_by_id($courseId);
  55. if (!empty($courseInfo)) {
  56. $this->set_course($courseInfo);
  57. }
  58. // Check if teacher/admin rights.
  59. $isAllowToEdit = api_is_allowed_to_edit(false, true);
  60. // Check course setting.
  61. if (api_get_course_setting('allow_user_edit_agenda') === '1'
  62. && api_is_allowed_in_course()
  63. ) {
  64. $isAllowToEdit = true;
  65. }
  66. $groupId = api_get_group_id();
  67. if (!empty($groupId)) {
  68. $groupInfo = GroupManager::get_group_properties($groupId);
  69. $userHasAccess = GroupManager::user_has_access(
  70. api_get_user_id(),
  71. $groupInfo['iid'],
  72. GroupManager::GROUP_TOOL_CALENDAR
  73. );
  74. $isTutor = GroupManager::is_tutor_of_group(
  75. api_get_user_id(),
  76. $groupInfo
  77. );
  78. $isGroupAccess = $userHasAccess || $isTutor;
  79. $isAllowToEdit = false;
  80. if ($isGroupAccess) {
  81. $isAllowToEdit = true;
  82. }
  83. }
  84. if (!empty($sessionId)) {
  85. $allowDhrToEdit = api_get_configuration_value('allow_agenda_edit_for_hrm');
  86. if ($allowDhrToEdit) {
  87. $isHrm = SessionManager::isUserSubscribedAsHRM($sessionId, api_get_user_id());
  88. if ($isHrm) {
  89. $isAllowToEdit = true;
  90. }
  91. }
  92. }
  93. break;
  94. case 'admin':
  95. $isAllowToEdit = api_is_platform_admin();
  96. break;
  97. case 'personal':
  98. $isAllowToEdit = !api_is_anonymous();
  99. break;
  100. }
  101. $this->setIsAllowedToEdit($isAllowToEdit);
  102. $this->events = [];
  103. $agendaColors = array_merge(
  104. [
  105. 'platform' => 'red', //red
  106. 'course' => '#458B00', //green
  107. 'group' => '#A0522D', //siena
  108. 'session' => '#00496D', // kind of green
  109. 'other_session' => '#999', // kind of green
  110. 'personal' => 'steel blue', //steel blue
  111. 'student_publication' => '#FF8C00', //DarkOrange
  112. ],
  113. api_get_configuration_value('agenda_colors') ?: []
  114. );
  115. // Event colors
  116. $this->event_platform_color = $agendaColors['platform'];
  117. $this->event_course_color = $agendaColors['course'];
  118. $this->event_group_color = $agendaColors['group'];
  119. $this->event_session_color = $agendaColors['session'];
  120. $this->eventOtherSessionColor = $agendaColors['other_session'];
  121. $this->event_personal_color = $agendaColors['personal'];
  122. $this->eventStudentPublicationColor = $agendaColors['student_publication'];
  123. }
  124. /**
  125. * @param int $senderId
  126. */
  127. public function setSenderId($senderId)
  128. {
  129. $this->senderId = (int) $senderId;
  130. }
  131. /**
  132. * @return int
  133. */
  134. public function getSenderId()
  135. {
  136. return $this->senderId;
  137. }
  138. /**
  139. * @param string $type can be 'personal', 'admin' or 'course'
  140. */
  141. public function setType($type)
  142. {
  143. $typeList = $this->getTypes();
  144. if (in_array($type, $typeList)) {
  145. $this->type = $type;
  146. }
  147. }
  148. /**
  149. * Returns the type previously set (and filtered) through setType
  150. * If setType() was not called, then type defaults to "personal" as
  151. * set in the class definition.
  152. */
  153. public function getType()
  154. {
  155. if (isset($this->type)) {
  156. return $this->type;
  157. }
  158. }
  159. /**
  160. * @param int $id
  161. */
  162. public function setSessionId($id)
  163. {
  164. $this->sessionId = (int) $id;
  165. }
  166. /**
  167. * @param array $sessionInfo
  168. */
  169. public function setSessionInfo($sessionInfo)
  170. {
  171. $this->sessionInfo = $sessionInfo;
  172. }
  173. /**
  174. * @return int $id
  175. */
  176. public function getSessionId()
  177. {
  178. return $this->sessionId;
  179. }
  180. /**
  181. * @param array $courseInfo
  182. */
  183. public function set_course($courseInfo)
  184. {
  185. $this->course = $courseInfo;
  186. }
  187. /**
  188. * @return array
  189. */
  190. public function getTypes()
  191. {
  192. return $this->types;
  193. }
  194. /**
  195. * Adds an event to the calendar.
  196. *
  197. * @param string $start datetime format: 2012-06-14 09:00:00 in local time
  198. * @param string $end datetime format: 2012-06-14 09:00:00 in local time
  199. * @param string $allDay (true, false)
  200. * @param string $title
  201. * @param string $content
  202. * @param array $usersToSend array('everyone') or a list of user/group ids
  203. * @param bool $addAsAnnouncement event as a *course* announcement
  204. * @param int $parentEventId
  205. * @param array $attachmentArray array of $_FILES['']
  206. * @param array $attachmentCommentList
  207. * @param string $eventComment
  208. * @param string $color
  209. *
  210. * @return int
  211. */
  212. public function addEvent(
  213. $start,
  214. $end,
  215. $allDay,
  216. $title,
  217. $content,
  218. $usersToSend = [],
  219. $addAsAnnouncement = false,
  220. $parentEventId = null,
  221. $attachmentArray = [],
  222. $attachmentCommentList = [],
  223. $eventComment = null,
  224. $color = ''
  225. ) {
  226. $start = api_get_utc_datetime($start);
  227. $end = api_get_utc_datetime($end);
  228. $allDay = isset($allDay) && $allDay === 'true' ? 1 : 0;
  229. $id = null;
  230. switch ($this->type) {
  231. case 'personal':
  232. $attributes = [
  233. 'user' => api_get_user_id(),
  234. 'title' => $title,
  235. 'text' => $content,
  236. 'date' => $start,
  237. 'enddate' => $end,
  238. 'all_day' => $allDay,
  239. 'color' => $color,
  240. ];
  241. $id = Database::insert(
  242. $this->tbl_personal_agenda,
  243. $attributes
  244. );
  245. break;
  246. case 'course':
  247. $attributes = [
  248. 'title' => $title,
  249. 'content' => $content,
  250. 'start_date' => $start,
  251. 'end_date' => $end,
  252. 'all_day' => $allDay,
  253. 'session_id' => $this->getSessionId(),
  254. 'c_id' => $this->course['real_id'],
  255. 'comment' => $eventComment,
  256. 'color' => $color,
  257. ];
  258. if (!empty($parentEventId)) {
  259. $attributes['parent_event_id'] = $parentEventId;
  260. }
  261. $senderId = $this->getSenderId();
  262. $sessionId = $this->getSessionId();
  263. // Simple course event.
  264. $id = Database::insert($this->tbl_course_agenda, $attributes);
  265. if ($id) {
  266. $sql = "UPDATE ".$this->tbl_course_agenda." SET id = iid WHERE iid = $id";
  267. Database::query($sql);
  268. $groupId = api_get_group_id();
  269. $groupInfo = [];
  270. if ($groupId) {
  271. $groupInfo = GroupManager::get_group_properties(
  272. $groupId
  273. );
  274. }
  275. if (!empty($usersToSend)) {
  276. $sendTo = $this->parseSendToArray($usersToSend);
  277. if ($sendTo['everyone']) {
  278. api_item_property_update(
  279. $this->course,
  280. TOOL_CALENDAR_EVENT,
  281. $id,
  282. 'AgendaAdded',
  283. $senderId,
  284. $groupInfo,
  285. '',
  286. $start,
  287. $end,
  288. $sessionId
  289. );
  290. api_item_property_update(
  291. $this->course,
  292. TOOL_CALENDAR_EVENT,
  293. $id,
  294. 'visible',
  295. $senderId,
  296. $groupInfo,
  297. '',
  298. $start,
  299. $end,
  300. $sessionId
  301. );
  302. } else {
  303. // Storing the selected groups
  304. if (!empty($sendTo['groups'])) {
  305. foreach ($sendTo['groups'] as $group) {
  306. $groupInfoItem = [];
  307. if ($group) {
  308. $groupInfoItem = GroupManager::get_group_properties($group);
  309. }
  310. api_item_property_update(
  311. $this->course,
  312. TOOL_CALENDAR_EVENT,
  313. $id,
  314. 'AgendaAdded',
  315. $senderId,
  316. $groupInfoItem,
  317. 0,
  318. $start,
  319. $end,
  320. $sessionId
  321. );
  322. api_item_property_update(
  323. $this->course,
  324. TOOL_CALENDAR_EVENT,
  325. $id,
  326. 'visible',
  327. $senderId,
  328. $groupInfoItem,
  329. 0,
  330. $start,
  331. $end,
  332. $sessionId
  333. );
  334. }
  335. }
  336. // storing the selected users
  337. if (!empty($sendTo['users'])) {
  338. foreach ($sendTo['users'] as $userId) {
  339. api_item_property_update(
  340. $this->course,
  341. TOOL_CALENDAR_EVENT,
  342. $id,
  343. 'AgendaAdded',
  344. $senderId,
  345. $groupInfo,
  346. $userId,
  347. $start,
  348. $end,
  349. $sessionId
  350. );
  351. api_item_property_update(
  352. $this->course,
  353. TOOL_CALENDAR_EVENT,
  354. $id,
  355. 'visible',
  356. $senderId,
  357. $groupInfo,
  358. $userId,
  359. $start,
  360. $end,
  361. $sessionId
  362. );
  363. }
  364. }
  365. }
  366. }
  367. // Add announcement.
  368. if ($addAsAnnouncement) {
  369. $this->storeAgendaEventAsAnnouncement(
  370. $id,
  371. $usersToSend
  372. );
  373. }
  374. // Add attachment.
  375. if (isset($attachmentArray) && !empty($attachmentArray)) {
  376. $counter = 0;
  377. foreach ($attachmentArray as $attachmentItem) {
  378. $this->addAttachment(
  379. $id,
  380. $attachmentItem,
  381. $attachmentCommentList[$counter],
  382. $this->course
  383. );
  384. $counter++;
  385. }
  386. }
  387. }
  388. break;
  389. case 'admin':
  390. if (api_is_platform_admin()) {
  391. $attributes = [
  392. 'title' => $title,
  393. 'content' => $content,
  394. 'start_date' => $start,
  395. 'end_date' => $end,
  396. 'all_day' => $allDay,
  397. 'access_url_id' => api_get_current_access_url_id(),
  398. ];
  399. $id = Database::insert(
  400. $this->tbl_global_agenda,
  401. $attributes
  402. );
  403. }
  404. break;
  405. }
  406. return $id;
  407. }
  408. /**
  409. * @param int $eventId
  410. * @param int $courseId
  411. *
  412. * @return array
  413. */
  414. public function getRepeatedInfoByEvent($eventId, $courseId)
  415. {
  416. $repeatTable = Database::get_course_table(TABLE_AGENDA_REPEAT);
  417. $eventId = (int) $eventId;
  418. $courseId = (int) $courseId;
  419. $sql = "SELECT * FROM $repeatTable
  420. WHERE c_id = $courseId AND cal_id = $eventId";
  421. $res = Database::query($sql);
  422. $repeatInfo = [];
  423. if (Database::num_rows($res) > 0) {
  424. $repeatInfo = Database::fetch_array($res, 'ASSOC');
  425. }
  426. return $repeatInfo;
  427. }
  428. /**
  429. * @param string $type
  430. * @param string $startEvent in UTC
  431. * @param string $endEvent in UTC
  432. * @param string $repeatUntilDate in UTC
  433. *
  434. * @throws Exception
  435. *
  436. * @return array
  437. */
  438. public function generateDatesByType($type, $startEvent, $endEvent, $repeatUntilDate)
  439. {
  440. $continue = true;
  441. $repeatUntilDate = new DateTime($repeatUntilDate, new DateTimeZone('UTC'));
  442. $loopMax = 365;
  443. $counter = 0;
  444. $list = [];
  445. switch ($type) {
  446. case 'daily':
  447. $interval = 'P1D';
  448. break;
  449. case 'weekly':
  450. $interval = 'P1W';
  451. break;
  452. case 'monthlyByDate':
  453. $interval = 'P1M';
  454. break;
  455. case 'monthlyByDay':
  456. // not yet implemented
  457. break;
  458. case 'monthlyByDayR':
  459. // not yet implemented
  460. break;
  461. case 'yearly':
  462. $interval = 'P1Y';
  463. break;
  464. }
  465. if (empty($interval)) {
  466. return [];
  467. }
  468. $timeZone = api_get_timezone();
  469. while ($continue) {
  470. $startDate = new DateTime($startEvent, new DateTimeZone('UTC'));
  471. $endDate = new DateTime($endEvent, new DateTimeZone('UTC'));
  472. $startDate->add(new DateInterval($interval));
  473. $endDate->add(new DateInterval($interval));
  474. $newStartDate = $startDate->format('Y-m-d H:i:s');
  475. $newEndDate = $endDate->format('Y-m-d H:i:s');
  476. $startEvent = $newStartDate;
  477. $endEvent = $newEndDate;
  478. if ($endDate > $repeatUntilDate) {
  479. break;
  480. }
  481. // @todo remove comment code
  482. $startDateInLocal = new DateTime($newStartDate, new DateTimeZone($timeZone));
  483. //$originalOffset = $startDate->getOffset();
  484. if ($startDateInLocal->format('I') == 0) {
  485. // Is saving time? Then fix UTC time to add time
  486. $seconds = $startDateInLocal->getOffset();
  487. $startDate->add(new DateInterval("PT".$seconds."S"));
  488. $startDateFixed = $startDate->format('Y-m-d H:i:s');
  489. $startDateInLocalFixed = new DateTime($startDateFixed, new DateTimeZone($timeZone));
  490. $newStartDate = $startDateInLocalFixed->format('Y-m-d H:i:s');
  491. } else {
  492. /*$seconds = $startDateInLocal->getOffset();
  493. $startDate->add(new DateInterval("PT".$seconds."S"));
  494. $startDateFixed = $startDate->format('Y-m-d H:i:s');
  495. $startDateInLocalFixed = new DateTime($startDateFixed, new DateTimeZone($timeZone));
  496. $newStartDate = $startDateInLocalFixed->format('Y-m-d H:i:s');*/
  497. }
  498. //var_dump($newStartDate.' - '.$startDateInLocal->format('I'));
  499. $endDateInLocal = new DateTime($newEndDate, new DateTimeZone($timeZone));
  500. if ($endDateInLocal->format('I') == 0) {
  501. // Is saving time? Then fix UTC time to add time
  502. $seconds = $endDateInLocal->getOffset();
  503. $endDate->add(new DateInterval("PT".$seconds."S"));
  504. $endDateFixed = $endDate->format('Y-m-d H:i:s');
  505. $endDateInLocalFixed = new DateTime($endDateFixed, new DateTimeZone($timeZone));
  506. $newEndDate = $endDateInLocalFixed->format('Y-m-d H:i:s');
  507. }
  508. $list[] = ['start' => $newStartDate, 'end' => $newEndDate, 'i' => $startDateInLocal->format('I')];
  509. $counter++;
  510. // just in case stop if more than $loopMax
  511. if ($counter > $loopMax) {
  512. break;
  513. }
  514. }
  515. return $list;
  516. }
  517. /**
  518. * @param int $eventId
  519. * @param string $type
  520. * @param string $end in UTC
  521. * @param array $sentTo
  522. *
  523. * @return bool
  524. */
  525. public function addRepeatedItem($eventId, $type, $end, $sentTo = [])
  526. {
  527. $t_agenda = Database::get_course_table(TABLE_AGENDA);
  528. $t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT);
  529. if (empty($this->course)) {
  530. return false;
  531. }
  532. $courseId = $this->course['real_id'];
  533. $eventId = (int) $eventId;
  534. $sql = "SELECT title, content, start_date, end_date, all_day
  535. FROM $t_agenda
  536. WHERE c_id = $courseId AND id = $eventId";
  537. $res = Database::query($sql);
  538. if (Database::num_rows($res) !== 1) {
  539. return false;
  540. }
  541. $typeList = [
  542. 'daily',
  543. 'weekly',
  544. 'monthlyByDate',
  545. 'monthlyByDay',
  546. 'monthlyByDayR',
  547. 'yearly',
  548. ];
  549. if (!in_array($type, $typeList)) {
  550. return false;
  551. }
  552. $now = time();
  553. // The event has to repeat *in the future*. We don't allow repeated
  554. // events in the past
  555. if ($end > $now) {
  556. return false;
  557. }
  558. $row = Database::fetch_array($res);
  559. $title = $row['title'];
  560. $content = $row['content'];
  561. $allDay = $row['all_day'];
  562. $type = Database::escape_string($type);
  563. $end = Database::escape_string($end);
  564. $endTimeStamp = api_strtotime($end, 'UTC');
  565. $sql = "INSERT INTO $t_agenda_r (c_id, cal_id, cal_type, cal_end)
  566. VALUES ($courseId, '$eventId', '$type', '$endTimeStamp')";
  567. Database::query($sql);
  568. $generatedDates = $this->generateDatesByType($type, $row['start_date'], $row['end_date'], $end);
  569. if (empty($generatedDates)) {
  570. return false;
  571. }
  572. foreach ($generatedDates as $dateInfo) {
  573. $start = api_get_local_time($dateInfo['start']);
  574. $end = api_get_local_time($dateInfo['end']);
  575. $this->addEvent(
  576. $start,
  577. $end,
  578. $allDay,
  579. $title,
  580. $content,
  581. $sentTo,
  582. false,
  583. $eventId
  584. );
  585. }
  586. return true;
  587. }
  588. /**
  589. * @param int $item_id
  590. * @param array $sentTo
  591. *
  592. * @return int
  593. */
  594. public function storeAgendaEventAsAnnouncement($item_id, $sentTo = [])
  595. {
  596. $table_agenda = Database::get_course_table(TABLE_AGENDA);
  597. $courseId = api_get_course_int_id();
  598. // Check params
  599. if (empty($item_id) || $item_id != strval(intval($item_id))) {
  600. return -1;
  601. }
  602. // Get the agenda item.
  603. $item_id = intval($item_id);
  604. $sql = "SELECT * FROM $table_agenda
  605. WHERE c_id = $courseId AND id = ".$item_id;
  606. $res = Database::query($sql);
  607. if (Database::num_rows($res) > 0) {
  608. $row = Database::fetch_array($res, 'ASSOC');
  609. // Sending announcement
  610. if (!empty($sentTo)) {
  611. $id = AnnouncementManager::add_announcement(
  612. api_get_course_info(),
  613. api_get_session_id(),
  614. $row['title'],
  615. $row['content'],
  616. $sentTo,
  617. null,
  618. null,
  619. $row['end_date']
  620. );
  621. AnnouncementManager::sendEmail(
  622. api_get_course_info(),
  623. api_get_session_id(),
  624. $id
  625. );
  626. return $id;
  627. }
  628. }
  629. return -1;
  630. }
  631. /**
  632. * Edits an event.
  633. *
  634. * @param int $id
  635. * @param string $start datetime format: 2012-06-14 09:00:00
  636. * @param string $end datetime format: 2012-06-14 09:00:00
  637. * @param int $allDay is all day 'true' or 'false'
  638. * @param string $title
  639. * @param string $content
  640. * @param array $usersToSend
  641. * @param array $attachmentArray
  642. * @param array $attachmentCommentList
  643. * @param string $comment
  644. * @param string $color
  645. * @param bool $addAnnouncement
  646. * @param bool $updateContent
  647. * @param int $authorId
  648. *
  649. * @return bool
  650. */
  651. public function editEvent(
  652. $id,
  653. $start,
  654. $end,
  655. $allDay,
  656. $title,
  657. $content,
  658. $usersToSend = [],
  659. $attachmentArray = [],
  660. $attachmentCommentList = [],
  661. $comment = null,
  662. $color = '',
  663. $addAnnouncement = false,
  664. $updateContent = true,
  665. $authorId = 0
  666. ) {
  667. $start = api_get_utc_datetime($start);
  668. $end = api_get_utc_datetime($end);
  669. $allDay = isset($allDay) && $allDay == 'true' ? 1 : 0;
  670. $authorId = empty($authorId) ? api_get_user_id() : (int) $authorId;
  671. switch ($this->type) {
  672. case 'personal':
  673. $eventInfo = $this->get_event($id);
  674. if ($eventInfo['user'] != api_get_user_id()) {
  675. break;
  676. }
  677. $attributes = [
  678. 'title' => $title,
  679. 'date' => $start,
  680. 'enddate' => $end,
  681. 'all_day' => $allDay,
  682. ];
  683. if ($updateContent) {
  684. $attributes['text'] = $content;
  685. }
  686. if (!empty($color)) {
  687. $attributes['color'] = $color;
  688. }
  689. Database::update(
  690. $this->tbl_personal_agenda,
  691. $attributes,
  692. ['id = ?' => $id]
  693. );
  694. break;
  695. case 'course':
  696. $eventInfo = $this->get_event($id);
  697. if (empty($eventInfo)) {
  698. return false;
  699. }
  700. $groupId = api_get_group_id();
  701. $groupIid = 0;
  702. $groupInfo = [];
  703. if ($groupId) {
  704. $groupInfo = GroupManager::get_group_properties($groupId);
  705. if ($groupInfo) {
  706. $groupIid = $groupInfo['iid'];
  707. }
  708. }
  709. $courseId = $this->course['real_id'];
  710. if (empty($courseId)) {
  711. return false;
  712. }
  713. if ($this->getIsAllowedToEdit()) {
  714. $attributes = [
  715. 'title' => $title,
  716. 'start_date' => $start,
  717. 'end_date' => $end,
  718. 'all_day' => $allDay,
  719. 'comment' => $comment,
  720. ];
  721. if ($updateContent) {
  722. $attributes['content'] = $content;
  723. }
  724. if (!empty($color)) {
  725. $attributes['color'] = $color;
  726. }
  727. Database::update(
  728. $this->tbl_course_agenda,
  729. $attributes,
  730. [
  731. 'id = ? AND c_id = ? AND session_id = ? ' => [
  732. $id,
  733. $courseId,
  734. $this->sessionId,
  735. ],
  736. ]
  737. );
  738. if (!empty($usersToSend)) {
  739. $sendTo = $this->parseSendToArray($usersToSend);
  740. $usersToDelete = array_diff(
  741. $eventInfo['send_to']['users'],
  742. $sendTo['users']
  743. );
  744. $usersToAdd = array_diff(
  745. $sendTo['users'],
  746. $eventInfo['send_to']['users']
  747. );
  748. $groupsToDelete = array_diff(
  749. $eventInfo['send_to']['groups'],
  750. $sendTo['groups']
  751. );
  752. $groupToAdd = array_diff(
  753. $sendTo['groups'],
  754. $eventInfo['send_to']['groups']
  755. );
  756. if ($sendTo['everyone']) {
  757. // Delete all from group
  758. if (isset($eventInfo['send_to']['groups']) &&
  759. !empty($eventInfo['send_to']['groups'])
  760. ) {
  761. foreach ($eventInfo['send_to']['groups'] as $group) {
  762. $groupIidItem = 0;
  763. if ($group) {
  764. $groupInfoItem = GroupManager::get_group_properties(
  765. $group
  766. );
  767. if ($groupInfoItem) {
  768. $groupIidItem = $groupInfoItem['iid'];
  769. }
  770. }
  771. api_item_property_delete(
  772. $this->course,
  773. TOOL_CALENDAR_EVENT,
  774. $id,
  775. 0,
  776. $groupIidItem,
  777. $this->sessionId
  778. );
  779. }
  780. }
  781. // Storing the selected users.
  782. if (isset($eventInfo['send_to']['users']) &&
  783. !empty($eventInfo['send_to']['users'])
  784. ) {
  785. foreach ($eventInfo['send_to']['users'] as $userId) {
  786. api_item_property_delete(
  787. $this->course,
  788. TOOL_CALENDAR_EVENT,
  789. $id,
  790. $userId,
  791. $groupIid,
  792. $this->sessionId
  793. );
  794. }
  795. }
  796. // Add to everyone only.
  797. api_item_property_update(
  798. $this->course,
  799. TOOL_CALENDAR_EVENT,
  800. $id,
  801. 'visible',
  802. $authorId,
  803. $groupInfo,
  804. null,
  805. $start,
  806. $end,
  807. $this->sessionId
  808. );
  809. } else {
  810. // Delete "everyone".
  811. api_item_property_delete(
  812. $this->course,
  813. TOOL_CALENDAR_EVENT,
  814. $id,
  815. 0,
  816. 0,
  817. $this->sessionId
  818. );
  819. // Add groups
  820. if (!empty($groupToAdd)) {
  821. foreach ($groupToAdd as $group) {
  822. $groupInfoItem = [];
  823. if ($group) {
  824. $groupInfoItem = GroupManager::get_group_properties(
  825. $group
  826. );
  827. }
  828. api_item_property_update(
  829. $this->course,
  830. TOOL_CALENDAR_EVENT,
  831. $id,
  832. 'visible',
  833. $authorId,
  834. $groupInfoItem,
  835. 0,
  836. $start,
  837. $end,
  838. $this->sessionId
  839. );
  840. }
  841. }
  842. // Delete groups.
  843. if (!empty($groupsToDelete)) {
  844. foreach ($groupsToDelete as $group) {
  845. $groupIidItem = 0;
  846. $groupInfoItem = [];
  847. if ($group) {
  848. $groupInfoItem = GroupManager::get_group_properties(
  849. $group
  850. );
  851. if ($groupInfoItem) {
  852. $groupIidItem = $groupInfoItem['iid'];
  853. }
  854. }
  855. api_item_property_delete(
  856. $this->course,
  857. TOOL_CALENDAR_EVENT,
  858. $id,
  859. 0,
  860. $groupIidItem,
  861. $this->sessionId
  862. );
  863. }
  864. }
  865. // Add users.
  866. if (!empty($usersToAdd)) {
  867. foreach ($usersToAdd as $userId) {
  868. api_item_property_update(
  869. $this->course,
  870. TOOL_CALENDAR_EVENT,
  871. $id,
  872. 'visible',
  873. $authorId,
  874. $groupInfo,
  875. $userId,
  876. $start,
  877. $end,
  878. $this->sessionId
  879. );
  880. }
  881. }
  882. // Delete users.
  883. if (!empty($usersToDelete)) {
  884. foreach ($usersToDelete as $userId) {
  885. api_item_property_delete(
  886. $this->course,
  887. TOOL_CALENDAR_EVENT,
  888. $id,
  889. $userId,
  890. $groupInfo,
  891. $this->sessionId
  892. );
  893. }
  894. }
  895. }
  896. }
  897. // Add announcement.
  898. if (isset($addAnnouncement) && !empty($addAnnouncement)) {
  899. $this->storeAgendaEventAsAnnouncement(
  900. $id,
  901. $usersToSend
  902. );
  903. }
  904. // Add attachment.
  905. if (isset($attachmentArray) && !empty($attachmentArray)) {
  906. $counter = 0;
  907. foreach ($attachmentArray as $attachmentItem) {
  908. $this->updateAttachment(
  909. $attachmentItem['id'],
  910. $id,
  911. $attachmentItem,
  912. $attachmentCommentList[$counter],
  913. $this->course
  914. );
  915. $counter++;
  916. }
  917. }
  918. return true;
  919. } else {
  920. return false;
  921. }
  922. break;
  923. case 'admin':
  924. case 'platform':
  925. if (api_is_platform_admin()) {
  926. $attributes = [
  927. 'title' => $title,
  928. 'start_date' => $start,
  929. 'end_date' => $end,
  930. 'all_day' => $allDay,
  931. ];
  932. if ($updateContent) {
  933. $attributes['content'] = $content;
  934. }
  935. Database::update(
  936. $this->tbl_global_agenda,
  937. $attributes,
  938. ['id = ?' => $id]
  939. );
  940. }
  941. break;
  942. }
  943. }
  944. /**
  945. * @param int $id
  946. * @param bool $deleteAllItemsFromSerie
  947. */
  948. public function deleteEvent($id, $deleteAllItemsFromSerie = false)
  949. {
  950. switch ($this->type) {
  951. case 'personal':
  952. $eventInfo = $this->get_event($id);
  953. if ($eventInfo['user'] == api_get_user_id()) {
  954. Database::delete(
  955. $this->tbl_personal_agenda,
  956. ['id = ?' => $id]
  957. );
  958. }
  959. break;
  960. case 'course':
  961. $courseId = api_get_course_int_id();
  962. $sessionId = api_get_session_id();
  963. $isAllowToEdit = api_is_allowed_to_edit(null, true);
  964. if ($isAllowToEdit == false && !empty($sessionId)) {
  965. $allowDhrToEdit = api_get_configuration_value('allow_agenda_edit_for_hrm');
  966. if ($allowDhrToEdit) {
  967. $isHrm = SessionManager::isUserSubscribedAsHRM(
  968. $sessionId,
  969. api_get_user_id()
  970. );
  971. if ($isHrm) {
  972. $isAllowToEdit = true;
  973. }
  974. }
  975. }
  976. if (!empty($courseId) && $isAllowToEdit) {
  977. // Delete
  978. $eventInfo = $this->get_event($id);
  979. if ($deleteAllItemsFromSerie) {
  980. /* This is one of the children.
  981. Getting siblings and delete 'Em all + the father! */
  982. if (isset($eventInfo['parent_event_id']) && !empty($eventInfo['parent_event_id'])) {
  983. // Removing items.
  984. $events = $this->getAllRepeatEvents(
  985. $eventInfo['parent_event_id']
  986. );
  987. if (!empty($events)) {
  988. foreach ($events as $event) {
  989. $this->deleteEvent($event['id']);
  990. }
  991. }
  992. // Removing parent.
  993. $this->deleteEvent($eventInfo['parent_event_id']);
  994. } else {
  995. // This is the father looking for the children.
  996. $events = $this->getAllRepeatEvents($id);
  997. if (!empty($events)) {
  998. foreach ($events as $event) {
  999. $this->deleteEvent($event['id']);
  1000. }
  1001. }
  1002. }
  1003. }
  1004. // Removing from events.
  1005. Database::delete(
  1006. $this->tbl_course_agenda,
  1007. ['id = ? AND c_id = ?' => [$id, $courseId]]
  1008. );
  1009. api_item_property_update(
  1010. $this->course,
  1011. TOOL_CALENDAR_EVENT,
  1012. $id,
  1013. 'delete',
  1014. api_get_user_id()
  1015. );
  1016. // Removing from series.
  1017. Database::delete(
  1018. $this->table_repeat,
  1019. [
  1020. 'cal_id = ? AND c_id = ?' => [
  1021. $id,
  1022. $courseId,
  1023. ],
  1024. ]
  1025. );
  1026. if (isset($eventInfo['attachment']) && !empty($eventInfo['attachment'])) {
  1027. foreach ($eventInfo['attachment'] as $attachment) {
  1028. self::deleteAttachmentFile(
  1029. $attachment['id'],
  1030. $this->course
  1031. );
  1032. }
  1033. }
  1034. }
  1035. break;
  1036. case 'admin':
  1037. if (api_is_platform_admin()) {
  1038. Database::delete(
  1039. $this->tbl_global_agenda,
  1040. ['id = ?' => $id]
  1041. );
  1042. }
  1043. break;
  1044. }
  1045. }
  1046. /**
  1047. * Get agenda events.
  1048. *
  1049. * @param int $start
  1050. * @param int $end
  1051. * @param int $courseId
  1052. * @param int $groupId
  1053. * @param int $user_id
  1054. * @param string $format
  1055. *
  1056. * @return array|string
  1057. */
  1058. public function getEvents(
  1059. $start,
  1060. $end,
  1061. $courseId = null,
  1062. $groupId = null,
  1063. $user_id = 0,
  1064. $format = 'json'
  1065. ) {
  1066. switch ($this->type) {
  1067. case 'admin':
  1068. $this->getPlatformEvents($start, $end);
  1069. break;
  1070. case 'course':
  1071. $courseInfo = api_get_course_info_by_id($courseId);
  1072. // Session coach can see all events inside a session.
  1073. if (api_is_coach()) {
  1074. // Own course
  1075. $this->getCourseEvents(
  1076. $start,
  1077. $end,
  1078. $courseInfo,
  1079. $groupId,
  1080. $this->sessionId,
  1081. $user_id
  1082. );
  1083. // Others
  1084. $this->getSessionEvents(
  1085. $start,
  1086. $end,
  1087. $this->sessionId,
  1088. $user_id,
  1089. $this->eventOtherSessionColor
  1090. );
  1091. } else {
  1092. $this->getCourseEvents(
  1093. $start,
  1094. $end,
  1095. $courseInfo,
  1096. $groupId,
  1097. $this->sessionId,
  1098. $user_id
  1099. );
  1100. }
  1101. break;
  1102. case 'personal':
  1103. default:
  1104. $sessionFilterActive = false;
  1105. if (!empty($this->sessionId)) {
  1106. $sessionFilterActive = true;
  1107. }
  1108. if ($sessionFilterActive == false) {
  1109. // Getting personal events
  1110. $this->getPersonalEvents($start, $end);
  1111. // Getting platform/admin events
  1112. $this->getPlatformEvents($start, $end);
  1113. }
  1114. $ignoreVisibility = api_get_configuration_value('personal_agenda_show_all_session_events');
  1115. // Getting course events
  1116. $my_course_list = [];
  1117. if (!api_is_anonymous()) {
  1118. $session_list = SessionManager::get_sessions_by_user(
  1119. api_get_user_id(),
  1120. $ignoreVisibility
  1121. );
  1122. $my_course_list = CourseManager::get_courses_list_by_user_id(
  1123. api_get_user_id(),
  1124. false
  1125. );
  1126. }
  1127. if (api_is_drh()) {
  1128. if (api_drh_can_access_all_session_content()) {
  1129. $session_list = [];
  1130. $sessionList = SessionManager::get_sessions_followed_by_drh(
  1131. api_get_user_id(),
  1132. null,
  1133. null,
  1134. null,
  1135. true,
  1136. false
  1137. );
  1138. if (!empty($sessionList)) {
  1139. foreach ($sessionList as $sessionItem) {
  1140. $sessionId = $sessionItem['id'];
  1141. $courses = SessionManager::get_course_list_by_session_id(
  1142. $sessionId
  1143. );
  1144. $sessionInfo = [
  1145. 'session_id' => $sessionId,
  1146. 'courses' => $courses,
  1147. ];
  1148. $session_list[] = $sessionInfo;
  1149. }
  1150. }
  1151. }
  1152. }
  1153. if (!empty($session_list)) {
  1154. foreach ($session_list as $session_item) {
  1155. if ($sessionFilterActive) {
  1156. if ($this->sessionId != $session_item['session_id']) {
  1157. continue;
  1158. }
  1159. }
  1160. $my_courses = $session_item['courses'];
  1161. $my_session_id = $session_item['session_id'];
  1162. if (!empty($my_courses)) {
  1163. foreach ($my_courses as $course_item) {
  1164. $courseInfo = api_get_course_info_by_id(
  1165. $course_item['real_id']
  1166. );
  1167. $this->getCourseEvents(
  1168. $start,
  1169. $end,
  1170. $courseInfo,
  1171. 0,
  1172. $my_session_id
  1173. );
  1174. }
  1175. }
  1176. }
  1177. }
  1178. if (!empty($my_course_list) && $sessionFilterActive == false) {
  1179. foreach ($my_course_list as $courseInfoItem) {
  1180. $courseInfo = api_get_course_info_by_id(
  1181. $courseInfoItem['real_id']
  1182. );
  1183. if (isset($courseId) && !empty($courseId)) {
  1184. if ($courseInfo['real_id'] == $courseId) {
  1185. $this->getCourseEvents(
  1186. $start,
  1187. $end,
  1188. $courseInfo,
  1189. 0,
  1190. 0,
  1191. $user_id
  1192. );
  1193. }
  1194. } else {
  1195. $this->getCourseEvents(
  1196. $start,
  1197. $end,
  1198. $courseInfo,
  1199. 0,
  1200. 0,
  1201. $user_id
  1202. );
  1203. }
  1204. }
  1205. }
  1206. break;
  1207. }
  1208. $this->cleanEvents();
  1209. switch ($format) {
  1210. case 'json':
  1211. if (empty($this->events)) {
  1212. return '[]';
  1213. }
  1214. return json_encode($this->events);
  1215. break;
  1216. case 'array':
  1217. if (empty($this->events)) {
  1218. return [];
  1219. }
  1220. return $this->events;
  1221. break;
  1222. }
  1223. }
  1224. /**
  1225. * Clean events.
  1226. *
  1227. * @return bool
  1228. */
  1229. public function cleanEvents()
  1230. {
  1231. if (empty($this->events)) {
  1232. return false;
  1233. }
  1234. foreach ($this->events as &$event) {
  1235. $event['description'] = Security::remove_XSS($event['description']);
  1236. $event['title'] = Security::remove_XSS($event['title']);
  1237. }
  1238. return true;
  1239. }
  1240. /**
  1241. * @param int $id
  1242. * @param int $minute_delta
  1243. *
  1244. * @return int
  1245. */
  1246. public function resizeEvent($id, $minute_delta)
  1247. {
  1248. $id = (int) $id;
  1249. $delta = (int) $minute_delta;
  1250. $event = $this->get_event($id);
  1251. if (!empty($event)) {
  1252. switch ($this->type) {
  1253. case 'personal':
  1254. $sql = "UPDATE $this->tbl_personal_agenda SET
  1255. enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
  1256. WHERE id = ".$id;
  1257. Database::query($sql);
  1258. break;
  1259. case 'course':
  1260. $sql = "UPDATE $this->tbl_course_agenda SET
  1261. end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
  1262. WHERE
  1263. c_id = ".$this->course['real_id']." AND
  1264. id = ".$id;
  1265. Database::query($sql);
  1266. break;
  1267. case 'admin':
  1268. $sql = "UPDATE $this->tbl_global_agenda SET
  1269. end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
  1270. WHERE id = ".$id;
  1271. Database::query($sql);
  1272. break;
  1273. }
  1274. }
  1275. return 1;
  1276. }
  1277. /**
  1278. * @param int $id
  1279. * @param int $minute_delta minutes
  1280. * @param int $allDay
  1281. *
  1282. * @return int
  1283. */
  1284. public function move_event($id, $minute_delta, $allDay)
  1285. {
  1286. $id = (int) $id;
  1287. $event = $this->get_event($id);
  1288. if (empty($event)) {
  1289. return false;
  1290. }
  1291. // we convert the hour delta into minutes and add the minute delta
  1292. $delta = (int) $minute_delta;
  1293. $allDay = (int) $allDay;
  1294. if (!empty($event)) {
  1295. switch ($this->type) {
  1296. case 'personal':
  1297. $sql = "UPDATE $this->tbl_personal_agenda SET
  1298. all_day = $allDay, date = DATE_ADD(date, INTERVAL $delta MINUTE),
  1299. enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
  1300. WHERE id=".$id;
  1301. Database::query($sql);
  1302. break;
  1303. case 'course':
  1304. $sql = "UPDATE $this->tbl_course_agenda SET
  1305. all_day = $allDay,
  1306. start_date = DATE_ADD(start_date, INTERVAL $delta MINUTE),
  1307. end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
  1308. WHERE
  1309. c_id = ".$this->course['real_id']." AND
  1310. id=".$id;
  1311. Database::query($sql);
  1312. break;
  1313. case 'admin':
  1314. $sql = "UPDATE $this->tbl_global_agenda SET
  1315. all_day = $allDay,
  1316. start_date = DATE_ADD(start_date,INTERVAL $delta MINUTE),
  1317. end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
  1318. WHERE id=".$id;
  1319. Database::query($sql);
  1320. break;
  1321. }
  1322. }
  1323. return 1;
  1324. }
  1325. /**
  1326. * Gets a single event.
  1327. *
  1328. * @param int $id event id
  1329. *
  1330. * @return array
  1331. */
  1332. public function get_event($id)
  1333. {
  1334. // make sure events of the personal agenda can only be seen by the user himself
  1335. $id = (int) $id;
  1336. $event = null;
  1337. switch ($this->type) {
  1338. case 'personal':
  1339. $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
  1340. WHERE id = $id AND user = ".api_get_user_id();
  1341. $result = Database::query($sql);
  1342. if (Database::num_rows($result)) {
  1343. $event = Database::fetch_array($result, 'ASSOC');
  1344. $event['description'] = $event['text'];
  1345. $event['content'] = $event['text'];
  1346. $event['start_date'] = $event['date'];
  1347. $event['end_date'] = $event['enddate'];
  1348. }
  1349. break;
  1350. case 'course':
  1351. if (!empty($this->course['real_id'])) {
  1352. $sql = "SELECT * FROM ".$this->tbl_course_agenda."
  1353. WHERE c_id = ".$this->course['real_id']." AND id = ".$id;
  1354. $result = Database::query($sql);
  1355. if (Database::num_rows($result)) {
  1356. $event = Database::fetch_array($result, 'ASSOC');
  1357. $event['description'] = $event['content'];
  1358. // Getting send to array
  1359. $event['send_to'] = $this->getUsersAndGroupSubscribedToEvent(
  1360. $id,
  1361. $this->course['real_id'],
  1362. $this->sessionId
  1363. );
  1364. // Getting repeat info
  1365. $event['repeat_info'] = $this->getRepeatedInfoByEvent(
  1366. $id,
  1367. $this->course['real_id']
  1368. );
  1369. if (!empty($event['parent_event_id'])) {
  1370. $event['parent_info'] = $this->get_event(
  1371. $event['parent_event_id']
  1372. );
  1373. }
  1374. $event['attachment'] = $this->getAttachmentList(
  1375. $id,
  1376. $this->course
  1377. );
  1378. }
  1379. }
  1380. break;
  1381. case 'admin':
  1382. case 'platform':
  1383. $sql = "SELECT * FROM ".$this->tbl_global_agenda."
  1384. WHERE id = $id";
  1385. $result = Database::query($sql);
  1386. if (Database::num_rows($result)) {
  1387. $event = Database::fetch_array($result, 'ASSOC');
  1388. $event['description'] = $event['content'];
  1389. }
  1390. break;
  1391. }
  1392. return $event;
  1393. }
  1394. /**
  1395. * Gets personal events.
  1396. *
  1397. * @param int $start
  1398. * @param int $end
  1399. *
  1400. * @return array
  1401. */
  1402. public function getPersonalEvents($start, $end)
  1403. {
  1404. $start = (int) $start;
  1405. $end = (int) $end;
  1406. $startCondition = '';
  1407. $endCondition = '';
  1408. if ($start !== 0) {
  1409. $startCondition = "AND date >= '".api_get_utc_datetime($start)."'";
  1410. }
  1411. if ($start !== 0) {
  1412. $endCondition = "AND (enddate <= '".api_get_utc_datetime($end)."' OR enddate IS NULL)";
  1413. }
  1414. $user_id = api_get_user_id();
  1415. $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
  1416. WHERE user = $user_id $startCondition $endCondition";
  1417. $result = Database::query($sql);
  1418. $my_events = [];
  1419. if (Database::num_rows($result)) {
  1420. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1421. $event = [];
  1422. $event['id'] = 'personal_'.$row['id'];
  1423. $event['title'] = $row['title'];
  1424. $event['className'] = 'personal';
  1425. $event['borderColor'] = $event['backgroundColor'] = $this->event_personal_color;
  1426. $event['editable'] = true;
  1427. $event['sent_to'] = get_lang('Me');
  1428. $event['type'] = 'personal';
  1429. if (!empty($row['date'])) {
  1430. $event['start'] = $this->formatEventDate($row['date']);
  1431. $event['start_date_localtime'] = api_get_local_time($row['date']);
  1432. }
  1433. if (!empty($row['enddate'])) {
  1434. $event['end'] = $this->formatEventDate($row['enddate']);
  1435. $event['end_date_localtime'] = api_get_local_time($row['enddate']);
  1436. }
  1437. $event['description'] = $row['text'];
  1438. $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
  1439. $event['parent_event_id'] = 0;
  1440. $event['has_children'] = 0;
  1441. $my_events[] = $event;
  1442. $this->events[] = $event;
  1443. }
  1444. }
  1445. // Add plugin personal events
  1446. $this->plugin = new AppPlugin();
  1447. $plugins = $this->plugin->getInstalledPluginListObject();
  1448. /** @var Plugin $plugin */
  1449. foreach ($plugins as $plugin) {
  1450. if ($plugin->hasPersonalEvents && method_exists($plugin, 'getPersonalEvents')) {
  1451. $pluginEvents = $plugin->getPersonalEvents($this, $start, $end);
  1452. if (!empty($pluginEvents)) {
  1453. $this->events = array_merge($this->events, $pluginEvents);
  1454. }
  1455. }
  1456. }
  1457. return $my_events;
  1458. }
  1459. /**
  1460. * Get user/group list per event.
  1461. *
  1462. * @param int $eventId
  1463. * @param int $courseId
  1464. * @param int $sessionId
  1465. * @paraù int $sessionId
  1466. *
  1467. * @return array
  1468. */
  1469. public function getUsersAndGroupSubscribedToEvent(
  1470. $eventId,
  1471. $courseId,
  1472. $sessionId
  1473. ) {
  1474. $eventId = (int) $eventId;
  1475. $courseId = (int) $courseId;
  1476. $sessionId = (int) $sessionId;
  1477. $sessionCondition = "ip.session_id = $sessionId";
  1478. if (empty($sessionId)) {
  1479. $sessionCondition = " (ip.session_id = 0 OR ip.session_id IS NULL) ";
  1480. }
  1481. $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
  1482. $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1483. // Get sent_tos
  1484. $sql = "SELECT DISTINCT to_user_id, to_group_id
  1485. FROM $tbl_property ip
  1486. INNER JOIN $tlb_course_agenda agenda
  1487. ON (
  1488. ip.ref = agenda.id AND
  1489. ip.c_id = agenda.c_id AND
  1490. ip.tool = '".TOOL_CALENDAR_EVENT."'
  1491. )
  1492. WHERE
  1493. ref = $eventId AND
  1494. ip.visibility = '1' AND
  1495. ip.c_id = $courseId AND
  1496. $sessionCondition
  1497. ";
  1498. $result = Database::query($sql);
  1499. $users = [];
  1500. $groups = [];
  1501. $everyone = false;
  1502. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1503. if (!empty($row['to_group_id'])) {
  1504. $groups[] = $row['to_group_id'];
  1505. }
  1506. if (!empty($row['to_user_id'])) {
  1507. $users[] = $row['to_user_id'];
  1508. }
  1509. if (empty($groups) && empty($users)) {
  1510. if ($row['to_group_id'] == 0) {
  1511. $everyone = true;
  1512. }
  1513. }
  1514. }
  1515. return [
  1516. 'everyone' => $everyone,
  1517. 'users' => $users,
  1518. 'groups' => $groups,
  1519. ];
  1520. }
  1521. /**
  1522. * @param int $start
  1523. * @param int $end
  1524. * @param int $sessionId
  1525. * @param int $userId
  1526. * @param string $color
  1527. *
  1528. * @return array
  1529. */
  1530. public function getSessionEvents(
  1531. $start,
  1532. $end,
  1533. $sessionId = 0,
  1534. $userId = 0,
  1535. $color = ''
  1536. ) {
  1537. $courses = SessionManager::get_course_list_by_session_id($sessionId);
  1538. if (!empty($courses)) {
  1539. foreach ($courses as $course) {
  1540. $this->getCourseEvents(
  1541. $start,
  1542. $end,
  1543. $course,
  1544. 0,
  1545. $sessionId,
  1546. 0,
  1547. $color
  1548. );
  1549. }
  1550. }
  1551. }
  1552. /**
  1553. * @param int $start
  1554. * @param int $end
  1555. * @param array $courseInfo
  1556. * @param int $groupId
  1557. * @param int $sessionId
  1558. * @param int $user_id
  1559. * @param string $color
  1560. *
  1561. * @return array
  1562. */
  1563. public function getCourseEvents(
  1564. $start,
  1565. $end,
  1566. $courseInfo,
  1567. $groupId = 0,
  1568. $sessionId = 0,
  1569. $user_id = 0,
  1570. $color = ''
  1571. ) {
  1572. $start = isset($start) && !empty($start) ? api_get_utc_datetime(intval($start)) : null;
  1573. $end = isset($end) && !empty($end) ? api_get_utc_datetime(intval($end)) : null;
  1574. if (empty($courseInfo)) {
  1575. return [];
  1576. }
  1577. $courseId = $courseInfo['real_id'];
  1578. if (empty($courseId)) {
  1579. return [];
  1580. }
  1581. $sessionId = (int) $sessionId;
  1582. $user_id = (int) $user_id;
  1583. $groupList = GroupManager::get_group_list(
  1584. null,
  1585. $courseInfo,
  1586. null,
  1587. $sessionId
  1588. );
  1589. $groupNameList = [];
  1590. if (!empty($groupList)) {
  1591. foreach ($groupList as $group) {
  1592. $groupNameList[$group['iid']] = $group['name'];
  1593. }
  1594. }
  1595. if (api_is_platform_admin() || api_is_allowed_to_edit()) {
  1596. $isAllowToEdit = true;
  1597. } else {
  1598. $isAllowToEdit = CourseManager::is_course_teacher(
  1599. api_get_user_id(),
  1600. $courseInfo['code']
  1601. );
  1602. }
  1603. $isAllowToEditByHrm = false;
  1604. if (!empty($sessionId)) {
  1605. $allowDhrToEdit = api_get_configuration_value('allow_agenda_edit_for_hrm');
  1606. if ($allowDhrToEdit) {
  1607. $isHrm = SessionManager::isUserSubscribedAsHRM($sessionId, api_get_user_id());
  1608. if ($isHrm) {
  1609. $isAllowToEdit = $isAllowToEditByHrm = true;
  1610. }
  1611. }
  1612. }
  1613. $groupMemberships = [];
  1614. if (!empty($groupId)) {
  1615. $groupMemberships = [$groupId];
  1616. } else {
  1617. if ($isAllowToEdit) {
  1618. if (!empty($groupList)) {
  1619. // c_item_property.to_group_id field was migrated to use
  1620. // c_group_info.iid
  1621. $groupMemberships = array_column($groupList, 'iid');
  1622. }
  1623. } else {
  1624. // get only related groups from user
  1625. $groupMemberships = GroupManager::get_group_ids(
  1626. $courseId,
  1627. api_get_user_id()
  1628. );
  1629. }
  1630. }
  1631. $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
  1632. $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
  1633. if (empty($sessionId)) {
  1634. $sessionCondition = "
  1635. (
  1636. agenda.session_id = 0 AND (ip.session_id IS NULL OR ip.session_id = 0)
  1637. ) ";
  1638. } else {
  1639. $sessionCondition = "
  1640. (
  1641. agenda.session_id = $sessionId AND
  1642. ip.session_id = $sessionId
  1643. ) ";
  1644. }
  1645. if ($isAllowToEdit) {
  1646. // No group filter was asked
  1647. if (empty($groupId)) {
  1648. if (empty($user_id)) {
  1649. // Show all events not added in group
  1650. $userCondition = ' (ip.to_group_id IS NULL OR ip.to_group_id = 0) ';
  1651. // admin see only his stuff
  1652. if ($this->type === 'personal') {
  1653. $userCondition = " (ip.to_user_id = ".api_get_user_id()." AND (ip.to_group_id IS NULL OR ip.to_group_id = 0) ) ";
  1654. $userCondition .= " OR ( (ip.to_user_id = 0 OR ip.to_user_id is NULL) AND (ip.to_group_id IS NULL OR ip.to_group_id = 0) ) ";
  1655. }
  1656. if (!empty($groupMemberships)) {
  1657. // Show events sent to selected groups
  1658. $userCondition .= " OR (ip.to_user_id = 0 OR ip.to_user_id is NULL) AND (ip.to_group_id IN (".implode(", ", $groupMemberships).")) ";
  1659. }
  1660. } else {
  1661. // Show events of requested user in no group
  1662. $userCondition = " (ip.to_user_id = $user_id AND (ip.to_group_id IS NULL OR ip.to_group_id = 0)) ";
  1663. // Show events sent to selected groups
  1664. if (!empty($groupMemberships)) {
  1665. $userCondition .= " OR (ip.to_user_id = $user_id) AND (ip.to_group_id IN (".implode(", ", $groupMemberships).")) ";
  1666. }
  1667. }
  1668. } else {
  1669. // Show only selected groups (depending of user status)
  1670. $userCondition = " (ip.to_user_id = 0 OR ip.to_user_id is NULL) AND (ip.to_group_id IN (".implode(", ", $groupMemberships).")) ";
  1671. if (!empty($groupMemberships)) {
  1672. // Show send to $user_id in selected groups
  1673. $userCondition .= " OR (ip.to_user_id = $user_id) AND (ip.to_group_id IN (".implode(", ", $groupMemberships).")) ";
  1674. }
  1675. }
  1676. } else {
  1677. // No group filter was asked
  1678. if (empty($groupId)) {
  1679. // Show events sent to everyone and no group
  1680. $userCondition = ' ( (ip.to_user_id = 0 OR ip.to_user_id is NULL) AND (ip.to_group_id IS NULL OR ip.to_group_id = 0) ';
  1681. // Show events sent to selected groups
  1682. if (!empty($groupMemberships)) {
  1683. $userCondition .= " OR (ip.to_user_id = 0 OR ip.to_user_id is NULL) AND (ip.to_group_id IN (".implode(", ", $groupMemberships)."))) ";
  1684. } else {
  1685. $userCondition .= " ) ";
  1686. }
  1687. $userCondition .= " OR (ip.to_user_id = ".api_get_user_id()." AND (ip.to_group_id IS NULL OR ip.to_group_id = 0)) ";
  1688. } else {
  1689. if (!empty($groupMemberships)) {
  1690. // Show send to everyone - and only selected groups
  1691. $userCondition = " (ip.to_user_id = 0 OR ip.to_user_id is NULL) AND (ip.to_group_id IN (".implode(", ", $groupMemberships).")) ";
  1692. }
  1693. }
  1694. // Show sent to only me and no group
  1695. if (!empty($groupMemberships)) {
  1696. $userCondition .= " OR (ip.to_user_id = ".api_get_user_id().") AND (ip.to_group_id IN (".implode(", ", $groupMemberships).")) ";
  1697. } else {
  1698. // Show sent to only me and selected groups
  1699. }
  1700. }
  1701. if (api_is_allowed_to_edit()) {
  1702. $visibilityCondition = " (ip.visibility IN ('1', '0')) ";
  1703. } else {
  1704. $visibilityCondition = " (ip.visibility = '1') ";
  1705. }
  1706. $sql = "SELECT DISTINCT
  1707. agenda.*,
  1708. ip.visibility,
  1709. ip.to_group_id,
  1710. ip.insert_user_id,
  1711. ip.ref,
  1712. to_user_id
  1713. FROM $tlb_course_agenda agenda
  1714. INNER JOIN $tbl_property ip
  1715. ON (
  1716. agenda.id = ip.ref AND
  1717. agenda.c_id = ip.c_id AND
  1718. ip.tool = '".TOOL_CALENDAR_EVENT."'
  1719. )
  1720. WHERE
  1721. $sessionCondition AND
  1722. ($userCondition) AND
  1723. $visibilityCondition AND
  1724. agenda.c_id = $courseId
  1725. ";
  1726. $dateCondition = '';
  1727. if (!empty($start) && !empty($end)) {
  1728. $dateCondition .= "AND (
  1729. agenda.start_date BETWEEN '".$start."' AND '".$end."' OR
  1730. agenda.end_date BETWEEN '".$start."' AND '".$end."' OR
  1731. (
  1732. agenda.start_date IS NOT NULL AND agenda.end_date IS NOT NULL AND
  1733. YEAR(agenda.start_date) = YEAR(agenda.end_date) AND
  1734. MONTH('$start') BETWEEN MONTH(agenda.start_date) AND MONTH(agenda.end_date)
  1735. )
  1736. )";
  1737. }
  1738. $sql .= $dateCondition;
  1739. $result = Database::query($sql);
  1740. $coachCanEdit = false;
  1741. if (!empty($sessionId)) {
  1742. $coachCanEdit = api_is_coach($sessionId, $courseId) || api_is_platform_admin();
  1743. }
  1744. if (Database::num_rows($result)) {
  1745. $eventsAdded = array_column($this->events, 'unique_id');
  1746. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1747. $event = [];
  1748. $event['id'] = 'course_'.$row['id'];
  1749. $event['unique_id'] = $row['iid'];
  1750. // To avoid doubles
  1751. if (in_array($event['unique_id'], $eventsAdded)) {
  1752. continue;
  1753. }
  1754. $eventsAdded[] = $event['unique_id'];
  1755. $eventId = $row['ref'];
  1756. $items = $this->getUsersAndGroupSubscribedToEvent(
  1757. $eventId,
  1758. $courseId,
  1759. $this->sessionId
  1760. );
  1761. $group_to_array = $items['groups'];
  1762. $user_to_array = $items['users'];
  1763. $attachmentList = $this->getAttachmentList(
  1764. $row['id'],
  1765. $courseInfo
  1766. );
  1767. $event['attachment'] = '';
  1768. if (!empty($attachmentList)) {
  1769. foreach ($attachmentList as $attachment) {
  1770. $has_attachment = Display::return_icon(
  1771. 'attachment.gif',
  1772. get_lang('Attachment')
  1773. );
  1774. $user_filename = $attachment['filename'];
  1775. $url = api_get_path(WEB_CODE_PATH).'calendar/download.php?file='.$attachment['path'].'&course_id='.$courseId.'&'.api_get_cidreq();
  1776. $event['attachment'] .= $has_attachment.
  1777. Display::url(
  1778. $user_filename,
  1779. $url
  1780. ).'<br />';
  1781. }
  1782. }
  1783. $event['title'] = $row['title'];
  1784. $event['className'] = 'course';
  1785. $event['allDay'] = 'false';
  1786. $event['course_id'] = $courseId;
  1787. $event['borderColor'] = $event['backgroundColor'] = $this->event_course_color;
  1788. $sessionInfo = [];
  1789. if (isset($row['session_id']) && !empty($row['session_id'])) {
  1790. $sessionInfo = api_get_session_info($sessionId);
  1791. $event['borderColor'] = $event['backgroundColor'] = $this->event_session_color;
  1792. }
  1793. $event['session_name'] = isset($sessionInfo['name']) ? $sessionInfo['name'] : '';
  1794. $event['course_name'] = isset($courseInfo['title']) ? $courseInfo['title'] : '';
  1795. if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
  1796. $event['borderColor'] = $event['backgroundColor'] = $this->event_group_color;
  1797. }
  1798. if (!empty($color)) {
  1799. $event['borderColor'] = $event['backgroundColor'] = $color;
  1800. }
  1801. if (isset($row['color']) && !empty($row['color'])) {
  1802. $event['borderColor'] = $event['backgroundColor'] = $row['color'];
  1803. }
  1804. $event['editable'] = false;
  1805. if ($this->getIsAllowedToEdit() && $this->type == 'course') {
  1806. $event['editable'] = true;
  1807. if (!empty($sessionId)) {
  1808. if ($coachCanEdit == false) {
  1809. $event['editable'] = false;
  1810. }
  1811. if ($isAllowToEditByHrm) {
  1812. $event['editable'] = true;
  1813. }
  1814. }
  1815. // if user is author then he can edit the item
  1816. if (api_get_user_id() == $row['insert_user_id']) {
  1817. $event['editable'] = true;
  1818. }
  1819. }
  1820. if (!empty($row['start_date'])) {
  1821. $event['start'] = $this->formatEventDate($row['start_date']);
  1822. $event['start_date_localtime'] = api_get_local_time($row['start_date']);
  1823. }
  1824. if (!empty($row['end_date'])) {
  1825. $event['end'] = $this->formatEventDate($row['end_date']);
  1826. $event['end_date_localtime'] = api_get_local_time($row['end_date']);
  1827. }
  1828. $event['sent_to'] = '';
  1829. $event['type'] = 'course';
  1830. if ($row['session_id'] != 0) {
  1831. $event['type'] = 'session';
  1832. }
  1833. // Event Sent to a group?
  1834. if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
  1835. $sent_to = [];
  1836. if (!empty($group_to_array)) {
  1837. foreach ($group_to_array as $group_item) {
  1838. $sent_to[] = $groupNameList[$group_item];
  1839. }
  1840. }
  1841. $sent_to = implode('@@', $sent_to);
  1842. $sent_to = str_replace(
  1843. '@@',
  1844. '</div><div class="label_tag notice">',
  1845. $sent_to
  1846. );
  1847. $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
  1848. $event['type'] = 'group';
  1849. }
  1850. // Event sent to a user?
  1851. if (isset($row['to_user_id'])) {
  1852. $sent_to = [];
  1853. if (!empty($user_to_array)) {
  1854. foreach ($user_to_array as $item) {
  1855. $user_info = api_get_user_info($item);
  1856. // Add username as tooltip for $event['sent_to'] - ref #4226
  1857. $username = api_htmlentities(
  1858. sprintf(
  1859. get_lang('Login: %s'),
  1860. $user_info['username']
  1861. ),
  1862. ENT_QUOTES
  1863. );
  1864. $sent_to[] = "<span title='".$username."'>".$user_info['complete_name']."</span>";
  1865. }
  1866. }
  1867. $sent_to = implode('@@', $sent_to);
  1868. $sent_to = str_replace(
  1869. '@@',
  1870. '</div><div class="label_tag notice">',
  1871. $sent_to
  1872. );
  1873. $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
  1874. }
  1875. //Event sent to everyone!
  1876. if (empty($event['sent_to'])) {
  1877. $event['sent_to'] = '<div class="label_tag notice">'.get_lang('Everyone').'</div>';
  1878. }
  1879. $event['description'] = $row['content'];
  1880. $event['visibility'] = $row['visibility'];
  1881. $event['real_id'] = $row['id'];
  1882. $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
  1883. $event['parent_event_id'] = $row['parent_event_id'];
  1884. $event['has_children'] = $this->hasChildren($row['id'], $courseId) ? 1 : 0;
  1885. $event['comment'] = $row['comment'];
  1886. $this->events[] = $event;
  1887. }
  1888. }
  1889. return $this->events;
  1890. }
  1891. /**
  1892. * @param int $start tms
  1893. * @param int $end tms
  1894. *
  1895. * @return array
  1896. */
  1897. public function getPlatformEvents($start, $end)
  1898. {
  1899. $start = isset($start) && !empty($start) ? api_get_utc_datetime(intval($start)) : null;
  1900. $end = isset($end) && !empty($end) ? api_get_utc_datetime(intval($end)) : null;
  1901. $dateCondition = '';
  1902. if (!empty($start) && !empty($end)) {
  1903. $dateCondition .= "AND (
  1904. start_date BETWEEN '".$start."' AND '".$end."' OR
  1905. end_date BETWEEN '".$start."' AND '".$end."' OR
  1906. (
  1907. start_date IS NOT NULL AND end_date IS NOT NULL AND
  1908. YEAR(start_date) = YEAR(end_date) AND
  1909. MONTH('$start') BETWEEN MONTH(start_date) AND MONTH(end_date)
  1910. )
  1911. )";
  1912. }
  1913. $access_url_id = api_get_current_access_url_id();
  1914. $sql = "SELECT *
  1915. FROM ".$this->tbl_global_agenda."
  1916. WHERE access_url_id = $access_url_id
  1917. $dateCondition";
  1918. $result = Database::query($sql);
  1919. $my_events = [];
  1920. if (Database::num_rows($result)) {
  1921. while ($row = Database::fetch_array($result, 'ASSOC')) {
  1922. $event = [];
  1923. $event['id'] = 'platform_'.$row['id'];
  1924. $event['title'] = $row['title'];
  1925. $event['className'] = 'platform';
  1926. $event['allDay'] = 'false';
  1927. $event['borderColor'] = $event['backgroundColor'] = $this->event_platform_color;
  1928. $event['editable'] = false;
  1929. $event['type'] = 'admin';
  1930. if (api_is_platform_admin() && $this->type === 'admin') {
  1931. $event['editable'] = true;
  1932. }
  1933. if (!empty($row['start_date'])) {
  1934. $event['start'] = $this->formatEventDate($row['start_date']);
  1935. $event['start_date_localtime'] = api_get_local_time($row['start_date']);
  1936. }
  1937. if (!empty($row['end_date'])) {
  1938. $event['end'] = $this->formatEventDate($row['end_date']);
  1939. $event['end_date_localtime'] = api_get_local_time($row['end_date']);
  1940. }
  1941. $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
  1942. $event['parent_event_id'] = 0;
  1943. $event['has_children'] = 0;
  1944. $event['description'] = $row['content'];
  1945. $my_events[] = $event;
  1946. $this->events[] = $event;
  1947. }
  1948. }
  1949. return $my_events;
  1950. }
  1951. /**
  1952. * @param FormValidator $form
  1953. * @param array $groupList
  1954. * @param array $userList
  1955. * @param array $sendTo array('users' => [1, 2], 'groups' => [3, 4])
  1956. * @param array $attributes
  1957. * @param bool $addOnlyItemsInSendTo
  1958. * @param bool $required
  1959. */
  1960. public function setSendToSelect(
  1961. $form,
  1962. $groupList = [],
  1963. $userList = [],
  1964. $sendTo = [],
  1965. $attributes = [],
  1966. $addOnlyItemsInSendTo = false,
  1967. $required = false
  1968. ) {
  1969. $params = [
  1970. 'id' => 'users_to_send_id',
  1971. 'data-placeholder' => get_lang('Select'),
  1972. 'multiple' => 'multiple',
  1973. 'class' => 'multiple-select',
  1974. ];
  1975. if (!empty($attributes)) {
  1976. $params = array_merge($params, $attributes);
  1977. if (empty($params['multiple'])) {
  1978. unset($params['multiple']);
  1979. }
  1980. }
  1981. $sendToGroups = isset($sendTo['groups']) ? $sendTo['groups'] : [];
  1982. $sendToUsers = isset($sendTo['users']) ? $sendTo['users'] : [];
  1983. /** @var HTML_QuickForm_select $select */
  1984. $select = $form->addSelect(
  1985. 'users_to_send',
  1986. get_lang('To'),
  1987. null,
  1988. $params
  1989. );
  1990. if ($required) {
  1991. $form->setRequired($select);
  1992. }
  1993. $selectedEveryoneOptions = [];
  1994. if (isset($sendTo['everyone']) && $sendTo['everyone']) {
  1995. $selectedEveryoneOptions = ['selected'];
  1996. $sendToUsers = [];
  1997. }
  1998. $select->addOption(
  1999. get_lang('Everyone'),
  2000. 'everyone',
  2001. $selectedEveryoneOptions
  2002. );
  2003. $options = [];
  2004. if (is_array($groupList)) {
  2005. foreach ($groupList as $group) {
  2006. $count_users = isset($group['count_users']) ? $group['count_users'] : $group['userNb'];
  2007. $count_users = " &ndash; $count_users ".get_lang('Users');
  2008. $option = [
  2009. 'text' => $group['name'].$count_users,
  2010. 'value' => "GROUP:".$group['id'],
  2011. ];
  2012. $selected = in_array(
  2013. $group['id'],
  2014. $sendToGroups
  2015. ) ? true : false;
  2016. if ($selected) {
  2017. $option['selected'] = 'selected';
  2018. }
  2019. if ($addOnlyItemsInSendTo) {
  2020. if ($selected) {
  2021. $options[] = $option;
  2022. }
  2023. } else {
  2024. $options[] = $option;
  2025. }
  2026. }
  2027. $select->addOptGroup($options, get_lang('Groups'));
  2028. }
  2029. // adding the individual users to the select form
  2030. if (is_array($userList)) {
  2031. $options = [];
  2032. foreach ($userList as $user) {
  2033. if ($user['status'] == ANONYMOUS) {
  2034. continue;
  2035. }
  2036. $option = [
  2037. 'text' => api_get_person_name(
  2038. $user['firstname'],
  2039. $user['lastname']
  2040. ).' ('.$user['username'].')',
  2041. 'value' => "USER:".$user['user_id'],
  2042. ];
  2043. $selected = in_array(
  2044. $user['user_id'],
  2045. $sendToUsers
  2046. ) ? true : false;
  2047. if ($selected) {
  2048. $option['selected'] = 'selected';
  2049. }
  2050. if ($addOnlyItemsInSendTo) {
  2051. if ($selected) {
  2052. $options[] = $option;
  2053. }
  2054. } else {
  2055. $options[] = $option;
  2056. }
  2057. }
  2058. $select->addOptGroup($options, get_lang('Users'));
  2059. }
  2060. }
  2061. /**
  2062. * Separates the users and groups array
  2063. * users have a value USER:XXX (with XXX the user id
  2064. * groups have a value GROUP:YYY (with YYY the group id)
  2065. * use the 'everyone' key.
  2066. *
  2067. * @author Julio Montoya based in separate_users_groups in agenda.inc.php
  2068. *
  2069. * @param array $to
  2070. *
  2071. * @return array
  2072. */
  2073. public function parseSendToArray($to)
  2074. {
  2075. $groupList = [];
  2076. $userList = [];
  2077. $sendTo = null;
  2078. $sendTo['everyone'] = false;
  2079. if (is_array($to) && count($to) > 0) {
  2080. foreach ($to as $item) {
  2081. if ($item == 'everyone') {
  2082. $sendTo['everyone'] = true;
  2083. } else {
  2084. list($type, $id) = explode(':', $item);
  2085. switch ($type) {
  2086. case 'GROUP':
  2087. $groupList[] = $id;
  2088. break;
  2089. case 'USER':
  2090. $userList[] = $id;
  2091. break;
  2092. }
  2093. }
  2094. }
  2095. $sendTo['groups'] = $groupList;
  2096. $sendTo['users'] = $userList;
  2097. }
  2098. return $sendTo;
  2099. }
  2100. /**
  2101. * @param array $params
  2102. *
  2103. * @return FormValidator
  2104. */
  2105. public function getForm($params = [])
  2106. {
  2107. $action = isset($params['action']) ? Security::remove_XSS($params['action']) : null;
  2108. $id = isset($params['id']) ? (int) $params['id'] : 0;
  2109. $url = api_get_self().'?action='.$action.'&id='.$id.'&type='.$this->type;
  2110. if ($this->type == 'course') {
  2111. $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&id='.$id.'&type='.$this->type;
  2112. }
  2113. $form = new FormValidator(
  2114. 'add_event',
  2115. 'post',
  2116. $url,
  2117. null,
  2118. ['enctype' => 'multipart/form-data']
  2119. );
  2120. $idAttach = isset($params['id_attach']) ? (int) $params['id_attach'] : null;
  2121. $groupId = api_get_group_id();
  2122. $form_Title = get_lang('Add event to agenda');
  2123. if (!empty($id)) {
  2124. $form_Title = get_lang('Edit event');
  2125. }
  2126. $form->addHeader($form_Title);
  2127. $form->addElement('hidden', 'id', $id);
  2128. $form->addElement('hidden', 'action', $action);
  2129. $form->addElement('hidden', 'id_attach', $idAttach);
  2130. $isSubEventEdition = false;
  2131. $isParentFromSerie = false;
  2132. $showAttachmentForm = true;
  2133. if ($this->type == 'course') {
  2134. // Edition mode.
  2135. if (!empty($id)) {
  2136. $showAttachmentForm = false;
  2137. if (isset($params['parent_event_id']) && !empty($params['parent_event_id'])) {
  2138. $isSubEventEdition = true;
  2139. }
  2140. if (!empty($params['repeat_info'])) {
  2141. $isParentFromSerie = true;
  2142. }
  2143. }
  2144. }
  2145. if ($isSubEventEdition) {
  2146. $form->addElement(
  2147. 'label',
  2148. null,
  2149. Display::return_message(
  2150. get_lang('Editing this event will remove it from the serie of events it is currently part of'),
  2151. 'warning'
  2152. )
  2153. );
  2154. }
  2155. $form->addElement('text', 'title', get_lang('Event name'));
  2156. if (isset($groupId) && !empty($groupId)) {
  2157. $form->addElement(
  2158. 'hidden',
  2159. 'users_to_send[]',
  2160. "GROUP:$groupId"
  2161. );
  2162. $form->addElement('hidden', 'to', 'true');
  2163. } else {
  2164. $sendTo = isset($params['send_to']) ? $params['send_to'] : ['everyone' => true];
  2165. if ($this->type == 'course') {
  2166. $this->showToForm($form, $sendTo, [], false, true);
  2167. }
  2168. }
  2169. $form->addDateRangePicker(
  2170. 'date_range',
  2171. get_lang('Date range'),
  2172. false,
  2173. ['id' => 'date_range']
  2174. );
  2175. $form->addElement('checkbox', 'all_day', null, get_lang('All day'));
  2176. if ($this->type == 'course') {
  2177. $repeat = $form->addElement(
  2178. 'checkbox',
  2179. 'repeat',
  2180. null,
  2181. get_lang('Repeat event'),
  2182. ['onclick' => 'return plus_repeated_event();']
  2183. );
  2184. $form->addElement(
  2185. 'html',
  2186. '<div id="options2" style="display:none">'
  2187. );
  2188. $form->addElement(
  2189. 'select',
  2190. 'repeat_type',
  2191. get_lang('Repeat type'),
  2192. self::getRepeatTypes()
  2193. );
  2194. $form->addElement(
  2195. 'date_picker',
  2196. 'repeat_end_day',
  2197. get_lang('Repeat end date'),
  2198. ['id' => 'repeat_end_date_form']
  2199. );
  2200. if ($isSubEventEdition || $isParentFromSerie) {
  2201. $repeatInfo = $params['repeat_info'];
  2202. if ($isSubEventEdition) {
  2203. $parentEvent = $params['parent_info'];
  2204. $repeatInfo = $parentEvent['repeat_info'];
  2205. }
  2206. $params['repeat'] = 1;
  2207. $params['repeat_type'] = $repeatInfo['cal_type'];
  2208. $params['repeat_end_day'] = substr(
  2209. api_get_local_time($repeatInfo['cal_end']),
  2210. 0,
  2211. 10
  2212. );
  2213. $form->freeze(['repeat_type', 'repeat_end_day']);
  2214. $repeat->_attributes['disabled'] = 'disabled';
  2215. }
  2216. $form->addElement('html', '</div>');
  2217. }
  2218. if (!empty($id)) {
  2219. if (empty($params['end_date'])) {
  2220. $params['date_range'] = $params['end_date'];
  2221. }
  2222. $params['date_range'] =
  2223. substr(api_get_local_time($params['start_date']), 0, 16).' / '.
  2224. substr(api_get_local_time($params['end_date']), 0, 16);
  2225. }
  2226. $toolbar = 'Agenda';
  2227. if (!api_is_allowed_to_edit(null, true)) {
  2228. $toolbar = 'AgendaStudent';
  2229. }
  2230. $form->addElement(
  2231. 'html_editor',
  2232. 'content',
  2233. get_lang('Description'),
  2234. null,
  2235. [
  2236. 'ToolbarSet' => $toolbar,
  2237. 'Width' => '100%',
  2238. 'Height' => '200',
  2239. ]
  2240. );
  2241. if ($this->type == 'course') {
  2242. $form->addElement('textarea', 'comment', get_lang('Comment'));
  2243. $form->addLabel(
  2244. get_lang('Files attachments'),
  2245. '<div id="filepaths" class="file-upload-event">
  2246. <div id="filepath_1">
  2247. <input type="file" name="attach_1"/>
  2248. <label>'.get_lang('Description').'</label>
  2249. <input class="form-control" type="text" name="legend[]" />
  2250. </div>
  2251. </div>'
  2252. );
  2253. $form->addLabel(
  2254. '',
  2255. '<span id="link-more-attach">
  2256. <a href="javascript://" onclick="return add_image_form()">'.
  2257. get_lang('Add one more file').'</a>
  2258. </span>&nbsp;('.sprintf(
  2259. get_lang('Maximun file size: %s'),
  2260. format_file_size(
  2261. api_get_setting('message_max_upload_filesize')
  2262. )
  2263. ).')'
  2264. );
  2265. if (isset($params['attachment']) && !empty($params['attachment'])) {
  2266. $attachmentList = $params['attachment'];
  2267. foreach ($attachmentList as $attachment) {
  2268. $params['file_comment'] = $attachment['comment'];
  2269. if (!empty($attachment['path'])) {
  2270. $form->addElement(
  2271. 'checkbox',
  2272. 'delete_attachment['.$attachment['id'].']',
  2273. null,
  2274. get_lang(
  2275. 'DeleteAttachment'
  2276. ).': '.$attachment['filename']
  2277. );
  2278. }
  2279. }
  2280. }
  2281. $form->addElement(
  2282. 'textarea',
  2283. 'file_comment',
  2284. get_lang('File comment')
  2285. );
  2286. }
  2287. if (empty($id)) {
  2288. $form->addElement(
  2289. 'checkbox',
  2290. 'add_announcement',
  2291. null,
  2292. get_lang('Add an announcement').'&nbsp('.get_lang('Send mail').')'
  2293. );
  2294. }
  2295. if ($id) {
  2296. $form->addButtonUpdate(get_lang('Edit event'));
  2297. } else {
  2298. $form->addButtonSave(get_lang('Add event'));
  2299. }
  2300. $form->setDefaults($params);
  2301. $form->addRule(
  2302. 'date_range',
  2303. get_lang('Required field'),
  2304. 'required'
  2305. );
  2306. $form->addRule('title', get_lang('Required field'), 'required');
  2307. return $form;
  2308. }
  2309. /**
  2310. * @param FormValidator $form
  2311. * @param array $sendTo array('everyone' => false, 'users' => [1, 2], 'groups' => [3, 4])
  2312. * @param array $attributes
  2313. * @param bool $addOnlyItemsInSendTo
  2314. * @param bool $required
  2315. *
  2316. * @return bool
  2317. */
  2318. public function showToForm(
  2319. $form,
  2320. $sendTo = [],
  2321. $attributes = [],
  2322. $addOnlyItemsInSendTo = false,
  2323. $required = false
  2324. ) {
  2325. if ($this->type != 'course') {
  2326. return false;
  2327. }
  2328. $order = 'lastname';
  2329. if (api_is_western_name_order()) {
  2330. $order = 'firstname';
  2331. }
  2332. $userList = CourseManager::get_user_list_from_course_code(
  2333. api_get_course_id(),
  2334. $this->sessionId,
  2335. null,
  2336. $order
  2337. );
  2338. $groupList = CourseManager::get_group_list_of_course(
  2339. api_get_course_id(),
  2340. $this->sessionId
  2341. );
  2342. $this->setSendToSelect(
  2343. $form,
  2344. $groupList,
  2345. $userList,
  2346. $sendTo,
  2347. $attributes,
  2348. $addOnlyItemsInSendTo,
  2349. $required
  2350. );
  2351. return true;
  2352. }
  2353. /**
  2354. * @param int $id
  2355. * @param int $visibility 0= invisible, 1 visible
  2356. * @param array $courseInfo
  2357. * @param int $userId
  2358. */
  2359. public static function changeVisibility(
  2360. $id,
  2361. $visibility,
  2362. $courseInfo,
  2363. $userId = null
  2364. ) {
  2365. $id = intval($id);
  2366. if (empty($userId)) {
  2367. $userId = api_get_user_id();
  2368. } else {
  2369. $userId = intval($userId);
  2370. }
  2371. if ($visibility == 0) {
  2372. api_item_property_update(
  2373. $courseInfo,
  2374. TOOL_CALENDAR_EVENT,
  2375. $id,
  2376. 'invisible',
  2377. $userId
  2378. );
  2379. } else {
  2380. api_item_property_update(
  2381. $courseInfo,
  2382. TOOL_CALENDAR_EVENT,
  2383. $id,
  2384. 'visible',
  2385. $userId
  2386. );
  2387. }
  2388. }
  2389. /**
  2390. * Get repeat types.
  2391. *
  2392. * @return array
  2393. */
  2394. public static function getRepeatTypes()
  2395. {
  2396. return [
  2397. 'daily' => get_lang('Daily'),
  2398. 'weekly' => get_lang('Weekly'),
  2399. 'monthlyByDate' => get_lang('Monthly, by date'),
  2400. //monthlyByDay"> get_lang('Monthly, by day');
  2401. //monthlyByDayR' => get_lang('Monthly, by dayR'),
  2402. 'yearly' => get_lang('Yearly'),
  2403. ];
  2404. }
  2405. /**
  2406. * Show a list with all the attachments according to the post's id.
  2407. *
  2408. * @param int $eventId
  2409. * @param array $courseInfo
  2410. *
  2411. * @return array with the post info
  2412. */
  2413. public function getAttachmentList($eventId, $courseInfo)
  2414. {
  2415. $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
  2416. $courseId = (int) $courseInfo['real_id'];
  2417. $eventId = (int) $eventId;
  2418. $sql = "SELECT id, path, filename, comment
  2419. FROM $tableAttachment
  2420. WHERE
  2421. c_id = $courseId AND
  2422. agenda_id = $eventId";
  2423. $result = Database::query($sql);
  2424. $list = [];
  2425. if (Database::num_rows($result) != 0) {
  2426. $list = Database::store_result($result, 'ASSOC');
  2427. }
  2428. return $list;
  2429. }
  2430. /**
  2431. * Show a list with all the attachments according to the post's id.
  2432. *
  2433. * @param int $attachmentId
  2434. * @param int $eventId
  2435. * @param array $courseInfo
  2436. *
  2437. * @return array with the post info
  2438. */
  2439. public function getAttachment($attachmentId, $eventId, $courseInfo)
  2440. {
  2441. if (empty($courseInfo) || empty($attachmentId) || empty($eventId)) {
  2442. return [];
  2443. }
  2444. $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
  2445. $courseId = (int) $courseInfo['real_id'];
  2446. $eventId = (int) $eventId;
  2447. $attachmentId = (int) $attachmentId;
  2448. $row = [];
  2449. $sql = "SELECT id, path, filename, comment
  2450. FROM $tableAttachment
  2451. WHERE
  2452. c_id = $courseId AND
  2453. agenda_id = $eventId AND
  2454. id = $attachmentId
  2455. ";
  2456. $result = Database::query($sql);
  2457. if (Database::num_rows($result) != 0) {
  2458. $row = Database::fetch_array($result, 'ASSOC');
  2459. }
  2460. return $row;
  2461. }
  2462. /**
  2463. * Add an attachment file into agenda.
  2464. *
  2465. * @param int $eventId
  2466. * @param array $fileUserUpload ($_FILES['user_upload'])
  2467. * @param string $comment about file
  2468. * @param array $courseInfo
  2469. *
  2470. * @return string
  2471. */
  2472. public function addAttachment(
  2473. $eventId,
  2474. $fileUserUpload,
  2475. $comment,
  2476. $courseInfo
  2477. ) {
  2478. $agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
  2479. $eventId = (int) $eventId;
  2480. // Storing the attachments
  2481. $upload_ok = false;
  2482. if (!empty($fileUserUpload['name'])) {
  2483. $upload_ok = process_uploaded_file($fileUserUpload);
  2484. }
  2485. if (!empty($upload_ok)) {
  2486. $courseDir = $courseInfo['directory'].'/upload/calendar';
  2487. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  2488. $uploadDir = $sys_course_path.$courseDir;
  2489. // Try to add an extension to the file if it hasn't one
  2490. $new_file_name = add_ext_on_mime(
  2491. stripslashes($fileUserUpload['name']),
  2492. $fileUserUpload['type']
  2493. );
  2494. // user's file name
  2495. $file_name = $fileUserUpload['name'];
  2496. if (!filter_extension($new_file_name)) {
  2497. return Display::return_message(
  2498. get_lang('File upload failed: this file extension or file type is prohibited'),
  2499. 'error'
  2500. );
  2501. } else {
  2502. $new_file_name = uniqid('');
  2503. $new_path = $uploadDir.'/'.$new_file_name;
  2504. $result = @move_uploaded_file(
  2505. $fileUserUpload['tmp_name'],
  2506. $new_path
  2507. );
  2508. $courseId = api_get_course_int_id();
  2509. $size = intval($fileUserUpload['size']);
  2510. // Storing the attachments if any
  2511. if ($result) {
  2512. $params = [
  2513. 'c_id' => $courseId,
  2514. 'filename' => $file_name,
  2515. 'comment' => $comment,
  2516. 'path' => $new_file_name,
  2517. 'agenda_id' => $eventId,
  2518. 'size' => $size,
  2519. ];
  2520. $id = Database::insert($agenda_table_attachment, $params);
  2521. if ($id) {
  2522. $sql = "UPDATE $agenda_table_attachment
  2523. SET id = iid WHERE iid = $id";
  2524. Database::query($sql);
  2525. api_item_property_update(
  2526. $courseInfo,
  2527. 'calendar_event_attachment',
  2528. $id,
  2529. 'AgendaAttachmentAdded',
  2530. api_get_user_id()
  2531. );
  2532. }
  2533. }
  2534. }
  2535. }
  2536. }
  2537. /**
  2538. * @param int $attachmentId
  2539. * @param int $eventId
  2540. * @param array $fileUserUpload
  2541. * @param string $comment
  2542. * @param array $courseInfo
  2543. */
  2544. public function updateAttachment(
  2545. $attachmentId,
  2546. $eventId,
  2547. $fileUserUpload,
  2548. $comment,
  2549. $courseInfo
  2550. ) {
  2551. $attachment = $this->getAttachment(
  2552. $attachmentId,
  2553. $eventId,
  2554. $courseInfo
  2555. );
  2556. if (!empty($attachment)) {
  2557. $this->deleteAttachmentFile($attachmentId, $courseInfo);
  2558. }
  2559. $this->addAttachment($eventId, $fileUserUpload, $comment, $courseInfo);
  2560. }
  2561. /**
  2562. * This function delete a attachment file by id.
  2563. *
  2564. * @param int $attachmentId
  2565. * @param array $courseInfo
  2566. *
  2567. * @return string
  2568. */
  2569. public function deleteAttachmentFile($attachmentId, $courseInfo)
  2570. {
  2571. $table = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
  2572. $attachmentId = (int) $attachmentId;
  2573. $courseId = $courseInfo['real_id'];
  2574. if (empty($courseId) || empty($attachmentId)) {
  2575. return false;
  2576. }
  2577. $sql = "DELETE FROM $table
  2578. WHERE c_id = $courseId AND id = ".$attachmentId;
  2579. $result = Database::query($sql);
  2580. // update item_property
  2581. api_item_property_update(
  2582. $courseInfo,
  2583. 'calendar_event_attachment',
  2584. $attachmentId,
  2585. 'AgendaAttachmentDeleted',
  2586. api_get_user_id()
  2587. );
  2588. if (!empty($result)) {
  2589. return Display::return_message(
  2590. get_lang("The attached file has been deleted"),
  2591. 'confirmation'
  2592. );
  2593. }
  2594. }
  2595. /**
  2596. * @param int $eventId
  2597. *
  2598. * @return array
  2599. */
  2600. public function getAllRepeatEvents($eventId)
  2601. {
  2602. $events = [];
  2603. $eventId = (int) $eventId;
  2604. switch ($this->type) {
  2605. case 'personal':
  2606. break;
  2607. case 'course':
  2608. if (!empty($this->course['real_id'])) {
  2609. $sql = "SELECT * FROM ".$this->tbl_course_agenda."
  2610. WHERE
  2611. c_id = ".$this->course['real_id']." AND
  2612. parent_event_id = ".$eventId;
  2613. $result = Database::query($sql);
  2614. if (Database::num_rows($result)) {
  2615. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2616. $events[] = $row;
  2617. }
  2618. }
  2619. }
  2620. break;
  2621. }
  2622. return $events;
  2623. }
  2624. /**
  2625. * @param int $eventId
  2626. * @param int $courseId
  2627. *
  2628. * @return bool
  2629. */
  2630. public function hasChildren($eventId, $courseId)
  2631. {
  2632. $eventId = (int) $eventId;
  2633. $courseId = (int) $courseId;
  2634. $sql = "SELECT count(DISTINCT(id)) as count
  2635. FROM ".$this->tbl_course_agenda."
  2636. WHERE
  2637. c_id = $courseId AND
  2638. parent_event_id = $eventId";
  2639. $result = Database::query($sql);
  2640. if (Database::num_rows($result)) {
  2641. $row = Database::fetch_array($result, 'ASSOC');
  2642. return $row['count'] > 0;
  2643. }
  2644. return false;
  2645. }
  2646. /**
  2647. * @param int $filter
  2648. * @param string $view
  2649. *
  2650. * @return string
  2651. */
  2652. public function displayActions($view, $filter = 0)
  2653. {
  2654. $groupInfo = GroupManager::get_group_properties(api_get_group_id());
  2655. $groupIid = isset($groupInfo['iid']) ? $groupInfo['iid'] : 0;
  2656. $codePath = api_get_path(WEB_CODE_PATH);
  2657. $currentUserId = api_get_user_id();
  2658. $cidReq = api_get_cidreq();
  2659. $actionsLeft = '';
  2660. $actionsLeft .= Display::url(
  2661. Display::return_icon('calendar.png', get_lang('Calendar'), [], ICON_SIZE_MEDIUM),
  2662. $codePath."calendar/agenda_js.php?type={$this->type}&$cidReq"
  2663. );
  2664. $actionsLeft .= Display::url(
  2665. Display::return_icon('week.png', get_lang('Agenda list'), [], ICON_SIZE_MEDIUM),
  2666. $codePath."calendar/agenda_list.php?type={$this->type}&$cidReq"
  2667. );
  2668. $form = '';
  2669. if (api_is_allowed_to_edit(false, true) ||
  2670. (api_get_course_setting('allow_user_edit_agenda') == '1' && !api_is_anonymous()) &&
  2671. api_is_allowed_to_session_edit(false, true)
  2672. || (
  2673. GroupManager::user_has_access($currentUserId, $groupIid, GroupManager::GROUP_TOOL_CALENDAR)
  2674. && GroupManager::is_tutor_of_group($currentUserId, $groupInfo)
  2675. )
  2676. ) {
  2677. $actionsLeft .= Display::url(
  2678. Display::return_icon('new_event.png', get_lang('Add event'), [], ICON_SIZE_MEDIUM),
  2679. $codePath."calendar/agenda.php?action=add&type={$this->type}&$cidReq"
  2680. );
  2681. $actionsLeft .= Display::url(
  2682. Display::return_icon('import_calendar.png', get_lang('Outlook import'), [], ICON_SIZE_MEDIUM),
  2683. $codePath."calendar/agenda.php?action=importical&type={$this->type}&$cidReq"
  2684. );
  2685. if ($this->type === 'course') {
  2686. if (!isset($_GET['action'])) {
  2687. $form = new FormValidator(
  2688. 'form-search',
  2689. 'post',
  2690. '',
  2691. '',
  2692. [],
  2693. FormValidator::LAYOUT_INLINE
  2694. );
  2695. $attributes = [
  2696. 'multiple' => false,
  2697. 'id' => 'select_form_id_search',
  2698. ];
  2699. $selectedValues = $this->parseAgendaFilter($filter);
  2700. $this->showToForm($form, $selectedValues, $attributes);
  2701. $form = $form->returnForm();
  2702. }
  2703. }
  2704. }
  2705. if ($this->type == 'personal' && !api_is_anonymous()) {
  2706. $actionsLeft .= Display::url(
  2707. Display::return_icon('1day.png', get_lang('Sessions plan calendar'), [], ICON_SIZE_MEDIUM),
  2708. $codePath."calendar/planification.php"
  2709. );
  2710. }
  2711. if (api_is_platform_admin() ||
  2712. api_is_teacher() ||
  2713. api_is_student_boss() ||
  2714. api_is_drh() ||
  2715. api_is_session_admin() ||
  2716. api_is_coach()
  2717. ) {
  2718. if ($this->type == 'personal') {
  2719. $form = null;
  2720. if (!isset($_GET['action'])) {
  2721. $form = new FormValidator(
  2722. 'form-search',
  2723. 'get',
  2724. api_get_self().'?type=personal&',
  2725. '',
  2726. [],
  2727. FormValidator::LAYOUT_INLINE
  2728. );
  2729. $sessions = [];
  2730. if (api_is_drh()) {
  2731. $sessionList = SessionManager::get_sessions_followed_by_drh($currentUserId);
  2732. if (!empty($sessionList)) {
  2733. foreach ($sessionList as $sessionItem) {
  2734. $sessions[$sessionItem['id']] = strip_tags($sessionItem['name']);
  2735. }
  2736. }
  2737. } else {
  2738. $sessions = SessionManager::get_sessions_by_user($currentUserId);
  2739. $sessions = array_column($sessions, 'session_name', 'session_id');
  2740. }
  2741. $form->addHidden('type', 'personal');
  2742. $sessions = ['0' => get_lang('Please select an option')] + $sessions;
  2743. $form->addSelect(
  2744. 'session_id',
  2745. get_lang('Session'),
  2746. $sessions,
  2747. ['id' => 'session_id', 'onchange' => 'submit();']
  2748. );
  2749. $form->addButtonReset(get_lang('Reset'));
  2750. $form = $form->returnForm();
  2751. }
  2752. }
  2753. }
  2754. $actionsRight = '';
  2755. if ($view == 'calendar') {
  2756. $actionsRight .= $form;
  2757. }
  2758. $toolbar = Display::toolbarAction(
  2759. 'toolbar-agenda',
  2760. [$actionsLeft, $actionsRight]
  2761. );
  2762. return $toolbar;
  2763. }
  2764. /**
  2765. * @return FormValidator
  2766. */
  2767. public function getImportCalendarForm()
  2768. {
  2769. $form = new FormValidator(
  2770. 'frm_import_ical',
  2771. 'post',
  2772. api_get_self().'?action=importical&type='.$this->type,
  2773. ['enctype' => 'multipart/form-data']
  2774. );
  2775. $form->addHeader(get_lang('Outlook import'));
  2776. $form->addElement('file', 'ical_import', get_lang('Outlook import'));
  2777. $form->addRule(
  2778. 'ical_import',
  2779. get_lang('Required field'),
  2780. 'required'
  2781. );
  2782. $form->addButtonImport(get_lang('Import'), 'ical_submit');
  2783. return $form;
  2784. }
  2785. /**
  2786. * @param array $courseInfo
  2787. * @param $file
  2788. *
  2789. * @return false|string
  2790. */
  2791. public function importEventFile($courseInfo, $file)
  2792. {
  2793. $charset = api_get_system_encoding();
  2794. $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
  2795. $messages = [];
  2796. if (!@move_uploaded_file($file['tmp_name'], $filepath)) {
  2797. error_log(
  2798. 'Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__
  2799. );
  2800. return false;
  2801. }
  2802. $data = file_get_contents($filepath);
  2803. $trans = [
  2804. 'DAILY' => 'daily',
  2805. 'WEEKLY' => 'weekly',
  2806. 'MONTHLY' => 'monthlyByDate',
  2807. 'YEARLY' => 'yearly',
  2808. ];
  2809. $sentTo = ['everyone' => true];
  2810. $calendar = Sabre\VObject\Reader::read($data);
  2811. $currentTimeZone = api_get_timezone();
  2812. if (!empty($calendar->VEVENT)) {
  2813. foreach ($calendar->VEVENT as $event) {
  2814. $start = $event->DTSTART->getDateTime();
  2815. $end = $event->DTEND->getDateTime();
  2816. //Sabre\VObject\DateTimeParser::parseDateTime(string $dt, \Sabre\VObject\DateTimeZone $tz)
  2817. $startDateTime = api_get_local_time(
  2818. $start->format('Y-m-d H:i:s'),
  2819. $currentTimeZone,
  2820. $start->format('e')
  2821. );
  2822. $endDateTime = api_get_local_time(
  2823. $end->format('Y-m-d H:i'),
  2824. $currentTimeZone,
  2825. $end->format('e')
  2826. );
  2827. $title = api_convert_encoding(
  2828. (string) $event->summary,
  2829. $charset,
  2830. 'UTF-8'
  2831. );
  2832. $description = api_convert_encoding(
  2833. (string) $event->description,
  2834. $charset,
  2835. 'UTF-8'
  2836. );
  2837. $id = $this->addEvent(
  2838. $startDateTime,
  2839. $endDateTime,
  2840. 'false',
  2841. $title,
  2842. $description,
  2843. $sentTo
  2844. );
  2845. $messages[] = " $title - ".$startDateTime." - ".$endDateTime;
  2846. //$attendee = (string)$event->attendee;
  2847. /** @var Sabre\VObject\Property\ICalendar\Recur $repeat */
  2848. $repeat = $event->RRULE;
  2849. if ($id && !empty($repeat)) {
  2850. $repeat = $repeat->getParts();
  2851. $freq = $trans[$repeat['FREQ']];
  2852. if (isset($repeat['UNTIL']) && !empty($repeat['UNTIL'])) {
  2853. // Check if datetime or just date (strlen == 8)
  2854. if (strlen($repeat['UNTIL']) == 8) {
  2855. // Fix the datetime format to avoid exception in the next step
  2856. $repeat['UNTIL'] .= 'T000000';
  2857. }
  2858. $until = Sabre\VObject\DateTimeParser::parseDateTime(
  2859. $repeat['UNTIL'],
  2860. new DateTimeZone($currentTimeZone)
  2861. );
  2862. $until = $until->format('Y-m-d H:i:s');
  2863. $this->addRepeatedItem(
  2864. $id,
  2865. $freq,
  2866. $until,
  2867. $sentTo
  2868. );
  2869. }
  2870. if (!empty($repeat['COUNT'])) {
  2871. /*$count = $repeat['COUNT'];
  2872. $interval = $repeat['INTERVAL'];
  2873. $endDate = null;
  2874. switch($freq) {
  2875. case 'daily':
  2876. $start = api_strtotime($startDateTime);
  2877. $date = new DateTime($startDateTime);
  2878. $days = $count * $interval;
  2879. var_dump($days);
  2880. $date->add(new DateInterval("P".$days."D"));
  2881. $endDate = $date->format('Y-m-d H:i');
  2882. //$endDate = $count *
  2883. for ($i = 0; $i < $count; $i++) {
  2884. $days = 86400 * 7
  2885. }
  2886. }
  2887. }*/
  2888. //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $count, $attendee);
  2889. /*$this->addRepeatedItem(
  2890. $id,
  2891. $freq,
  2892. $endDate,
  2893. $sentTo
  2894. );*/
  2895. }
  2896. }
  2897. }
  2898. }
  2899. if (!empty($messages)) {
  2900. $messages = implode('<br /> ', $messages);
  2901. } else {
  2902. $messages = get_lang('There are no events');
  2903. }
  2904. return $messages;
  2905. }
  2906. /**
  2907. * Parse filter turns USER:12 to ['users' => [12])] or G:1 ['groups' => [1]].
  2908. *
  2909. * @param int $filter
  2910. *
  2911. * @return array
  2912. */
  2913. public function parseAgendaFilter($filter)
  2914. {
  2915. $everyone = false;
  2916. $groupId = null;
  2917. $userId = null;
  2918. if ($filter == 'everyone') {
  2919. $everyone = true;
  2920. } else {
  2921. if (substr($filter, 0, 1) == 'G') {
  2922. $groupId = str_replace('GROUP:', '', $filter);
  2923. } else {
  2924. $userId = str_replace('USER:', '', $filter);
  2925. }
  2926. }
  2927. if (empty($userId) && empty($groupId)) {
  2928. $everyone = true;
  2929. }
  2930. return [
  2931. 'everyone' => $everyone,
  2932. 'users' => [$userId],
  2933. 'groups' => [$groupId],
  2934. ];
  2935. }
  2936. /**
  2937. * This function retrieves all the agenda items of all the courses the user is subscribed to.
  2938. */
  2939. public static function get_myagendaitems(
  2940. $user_id,
  2941. $courses_dbs,
  2942. $month,
  2943. $year
  2944. ) {
  2945. $user_id = intval($user_id);
  2946. $items = [];
  2947. $my_list = [];
  2948. // get agenda-items for every course
  2949. foreach ($courses_dbs as $key => $array_course_info) {
  2950. //databases of the courses
  2951. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  2952. $TABLE_ITEMPROPERTY = Database::get_course_table(
  2953. TABLE_ITEM_PROPERTY
  2954. );
  2955. $group_memberships = GroupManager::get_group_ids(
  2956. $array_course_info['real_id'],
  2957. $user_id
  2958. );
  2959. $course_user_status = CourseManager::getUserInCourseStatus(
  2960. $user_id,
  2961. $array_course_info['real_id']
  2962. );
  2963. // if the user is administrator of that course we show all the agenda items
  2964. if ($course_user_status == '1') {
  2965. //echo "course admin";
  2966. $sqlquery = "SELECT DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
  2967. FROM ".$TABLEAGENDA." agenda,
  2968. ".$TABLE_ITEMPROPERTY." ip
  2969. WHERE agenda.id = ip.ref
  2970. AND MONTH(agenda.start_date)='".$month."'
  2971. AND YEAR(agenda.start_date)='".$year."'
  2972. AND ip.tool='".TOOL_CALENDAR_EVENT."'
  2973. AND ip.visibility='1'
  2974. GROUP BY agenda.id
  2975. ORDER BY start_date ";
  2976. } else {
  2977. // if the user is not an administrator of that course
  2978. if (is_array($group_memberships) && count(
  2979. $group_memberships
  2980. ) > 0
  2981. ) {
  2982. $sqlquery = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
  2983. FROM ".$TABLEAGENDA." agenda,
  2984. ".$TABLE_ITEMPROPERTY." ip
  2985. WHERE agenda.id = ip.ref
  2986. AND MONTH(agenda.start_date)='".$month."'
  2987. AND YEAR(agenda.start_date)='".$year."'
  2988. AND ip.tool='".TOOL_CALENDAR_EVENT."'
  2989. AND ( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(
  2990. ", ",
  2991. $group_memberships
  2992. ).")) )
  2993. AND ip.visibility='1'
  2994. ORDER BY start_date ";
  2995. } else {
  2996. $sqlquery = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
  2997. FROM ".$TABLEAGENDA." agenda,
  2998. ".$TABLE_ITEMPROPERTY." ip
  2999. WHERE agenda.id = ip.ref
  3000. AND MONTH(agenda.start_date)='".$month."'
  3001. AND YEAR(agenda.start_date)='".$year."'
  3002. AND ip.tool='".TOOL_CALENDAR_EVENT."'
  3003. AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
  3004. AND ip.visibility='1'
  3005. ORDER BY start_date ";
  3006. }
  3007. }
  3008. $result = Database::query($sqlquery);
  3009. while ($item = Database::fetch_array($result, 'ASSOC')) {
  3010. $agendaday = -1;
  3011. if (!empty($item['start_date'])) {
  3012. $item['start_date'] = api_get_local_time(
  3013. $item['start_date']
  3014. );
  3015. $item['start_date_tms'] = api_strtotime(
  3016. $item['start_date']
  3017. );
  3018. $agendaday = date("j", $item['start_date_tms']);
  3019. }
  3020. if (!empty($item['end_date'])) {
  3021. $item['end_date'] = api_get_local_time($item['end_date']);
  3022. }
  3023. $url = api_get_path(
  3024. WEB_CODE_PATH
  3025. )."calendar/agenda.php?cidReq=".urlencode(
  3026. $array_course_info["code"]
  3027. )."&day=$agendaday&month=$month&year=$year#$agendaday";
  3028. $item['url'] = $url;
  3029. $item['course_name'] = $array_course_info['title'];
  3030. $item['calendar_type'] = 'course';
  3031. $item['course_id'] = $array_course_info['course_id'];
  3032. $my_list[$agendaday][] = $item;
  3033. }
  3034. }
  3035. // sorting by hour for every day
  3036. $agendaitems = [];
  3037. foreach ($items as $agendaday => $tmpitems) {
  3038. if (!isset($agendaitems[$agendaday])) {
  3039. $agendaitems[$agendaday] = '';
  3040. }
  3041. sort($tmpitems);
  3042. foreach ($tmpitems as $val) {
  3043. $agendaitems[$agendaday] .= $val;
  3044. }
  3045. }
  3046. return $my_list;
  3047. }
  3048. /**
  3049. * This function retrieves one personal agenda item returns it.
  3050. *
  3051. * @param array The array containing existing events. We add to this array.
  3052. * @param int Day
  3053. * @param int Month
  3054. * @param int Year (4 digits)
  3055. * @param int Week number
  3056. * @param string Type of view (month_view, week_view, day_view)
  3057. *
  3058. * @return array The results of the database query, or null if not found
  3059. */
  3060. public static function get_global_agenda_items(
  3061. $agendaitems,
  3062. $day = "",
  3063. $month = "",
  3064. $year = "",
  3065. $week = "",
  3066. $type
  3067. ) {
  3068. $tbl_global_agenda = Database::get_main_table(
  3069. TABLE_MAIN_SYSTEM_CALENDAR
  3070. );
  3071. $month = intval($month);
  3072. $year = intval($year);
  3073. $week = intval($week);
  3074. $day = intval($day);
  3075. // 1. creating the SQL statement for getting the personal agenda items in MONTH view
  3076. $current_access_url_id = api_get_current_access_url_id();
  3077. if ($type == "month_view" or $type == "") {
  3078. // We are in month view
  3079. $sql = "SELECT * FROM ".$tbl_global_agenda." WHERE MONTH(start_date) = ".$month." AND YEAR(start_date) = ".$year." AND access_url_id = $current_access_url_id ORDER BY start_date ASC";
  3080. }
  3081. // 2. creating the SQL statement for getting the personal agenda items in WEEK view
  3082. if ($type == "week_view") { // we are in week view
  3083. $start_end_day_of_week = self::calculate_start_end_of_week(
  3084. $week,
  3085. $year
  3086. );
  3087. $start_day = $start_end_day_of_week['start']['day'];
  3088. $start_month = $start_end_day_of_week['start']['month'];
  3089. $start_year = $start_end_day_of_week['start']['year'];
  3090. $end_day = $start_end_day_of_week['end']['day'];
  3091. $end_month = $start_end_day_of_week['end']['month'];
  3092. $end_year = $start_end_day_of_week['end']['year'];
  3093. // in sql statements you have to use year-month-day for date calculations
  3094. $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
  3095. $start_filter = api_get_utc_datetime($start_filter);
  3096. $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
  3097. $end_filter = api_get_utc_datetime($end_filter);
  3098. $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."' AND access_url_id = $current_access_url_id ";
  3099. }
  3100. // 3. creating the SQL statement for getting the personal agenda items in DAY view
  3101. if ($type == "day_view") { // we are in day view
  3102. // we could use mysql date() function but this is only available from 4.1 and higher
  3103. $start_filter = $year."-".$month."-".$day." 00:00:00";
  3104. $start_filter = api_get_utc_datetime($start_filter);
  3105. $end_filter = $year."-".$month."-".$day." 23:59:59";
  3106. $end_filter = api_get_utc_datetime($end_filter);
  3107. $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."' AND access_url_id = $current_access_url_id";
  3108. }
  3109. $result = Database::query($sql);
  3110. while ($item = Database::fetch_array($result)) {
  3111. if (!empty($item['start_date'])) {
  3112. $item['start_date'] = api_get_local_time($item['start_date']);
  3113. $item['start_date_tms'] = api_strtotime($item['start_date']);
  3114. }
  3115. if (!empty($item['end_date'])) {
  3116. $item['end_date'] = api_get_local_time($item['end_date']);
  3117. }
  3118. // we break the date field in the database into a date and a time part
  3119. $agenda_db_date = explode(" ", $item['start_date']);
  3120. $date = $agenda_db_date[0];
  3121. $time = $agenda_db_date[1];
  3122. // we divide the date part into a day, a month and a year
  3123. $agendadate = explode("-", $date);
  3124. $year = intval($agendadate[0]);
  3125. $month = intval($agendadate[1]);
  3126. $day = intval($agendadate[2]);
  3127. // we divide the time part into hour, minutes, seconds
  3128. $agendatime = explode(":", $time);
  3129. $hour = $agendatime[0];
  3130. $minute = $agendatime[1];
  3131. $second = $agendatime[2];
  3132. if ($type == 'month_view') {
  3133. $item['calendar_type'] = 'global';
  3134. $agendaitems[$day][] = $item;
  3135. continue;
  3136. }
  3137. $start_time = api_format_date(
  3138. $item['start_date'],
  3139. TIME_NO_SEC_FORMAT
  3140. );
  3141. $end_time = '';
  3142. if (!empty($item['end_date'])) {
  3143. $end_time = ' - '.api_format_date(
  3144. $item['end_date'],
  3145. DATE_TIME_FORMAT_LONG
  3146. );
  3147. }
  3148. // if the student has specified a course we a add a link to that course
  3149. if ($item['course'] != "") {
  3150. $url = api_get_path(
  3151. WEB_CODE_PATH
  3152. )."admin/agenda.php?cidReq=".urlencode(
  3153. $item['course']
  3154. )."&day=$day&month=$month&year=$year#$day"; // RH //Patrick Cool: to highlight the relevant agenda item
  3155. $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
  3156. } else {
  3157. $course_link = "";
  3158. }
  3159. // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
  3160. // if we have a day_view we use a half hour as index => key 33 = 16h30
  3161. if ($type !== "day_view") {
  3162. // This is the array construction for the WEEK or MONTH view
  3163. //Display the Agenda global in the tab agenda (administrator)
  3164. $agendaitems[$day] .= "<i>$start_time $end_time</i>&nbsp;-&nbsp;";
  3165. $agendaitems[$day] .= "<b>".get_lang('Platform event')."</b>";
  3166. $agendaitems[$day] .= "<div>".$item['title']."</div><br>";
  3167. } else {
  3168. // this is the array construction for the DAY view
  3169. $halfhour = 2 * $agendatime['0'];
  3170. if ($agendatime['1'] >= '30') {
  3171. $halfhour = $halfhour + 1;
  3172. }
  3173. if (!is_array($agendaitems[$halfhour])) {
  3174. $content = $agendaitems[$halfhour];
  3175. }
  3176. $agendaitems[$halfhour] = $content."<div><i>$hour:$minute</i> <b>".get_lang(
  3177. 'Platform event'
  3178. ).": </b>".$item['title']."</div>";
  3179. }
  3180. }
  3181. return $agendaitems;
  3182. }
  3183. /**
  3184. * This function retrieves all the personal agenda items and add them to the agenda items found by the other
  3185. * functions.
  3186. */
  3187. public static function get_personal_agenda_items(
  3188. $user_id,
  3189. $agendaitems,
  3190. $day = "",
  3191. $month = "",
  3192. $year = "",
  3193. $week = "",
  3194. $type
  3195. ) {
  3196. $tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
  3197. $user_id = intval($user_id);
  3198. // 1. creating the SQL statement for getting the personal agenda items in MONTH view
  3199. if ($type == "month_view" or $type == "") {
  3200. // we are in month view
  3201. $sql = "SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' and MONTH(date)='".$month."' AND YEAR(date) = '".$year."' ORDER BY date ASC";
  3202. }
  3203. // 2. creating the SQL statement for getting the personal agenda items in WEEK view
  3204. // we are in week view
  3205. if ($type == "week_view") {
  3206. $start_end_day_of_week = self::calculate_start_end_of_week(
  3207. $week,
  3208. $year
  3209. );
  3210. $start_day = $start_end_day_of_week['start']['day'];
  3211. $start_month = $start_end_day_of_week['start']['month'];
  3212. $start_year = $start_end_day_of_week['start']['year'];
  3213. $end_day = $start_end_day_of_week['end']['day'];
  3214. $end_month = $start_end_day_of_week['end']['month'];
  3215. $end_year = $start_end_day_of_week['end']['year'];
  3216. // in sql statements you have to use year-month-day for date calculations
  3217. $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
  3218. $start_filter = api_get_utc_datetime($start_filter);
  3219. $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
  3220. $end_filter = api_get_utc_datetime($end_filter);
  3221. $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
  3222. }
  3223. // 3. creating the SQL statement for getting the personal agenda items in DAY view
  3224. if ($type == "day_view") {
  3225. // we are in day view
  3226. // we could use mysql date() function but this is only available from 4.1 and higher
  3227. $start_filter = $year."-".$month."-".$day." 00:00:00";
  3228. $start_filter = api_get_utc_datetime($start_filter);
  3229. $end_filter = $year."-".$month."-".$day." 23:59:59";
  3230. $end_filter = api_get_utc_datetime($end_filter);
  3231. $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
  3232. }
  3233. $result = Database::query($sql);
  3234. while ($item = Database::fetch_array($result, 'ASSOC')) {
  3235. $time_minute = api_convert_and_format_date(
  3236. $item['date'],
  3237. TIME_NO_SEC_FORMAT
  3238. );
  3239. $item['date'] = api_get_local_time($item['date']);
  3240. $item['start_date_tms'] = api_strtotime($item['date']);
  3241. $item['content'] = $item['text'];
  3242. // we break the date field in the database into a date and a time part
  3243. $agenda_db_date = explode(" ", $item['date']);
  3244. $date = $agenda_db_date[0];
  3245. $time = $agenda_db_date[1];
  3246. // we divide the date part into a day, a month and a year
  3247. $agendadate = explode("-", $item['date']);
  3248. $year = intval($agendadate[0]);
  3249. $month = intval($agendadate[1]);
  3250. $day = intval($agendadate[2]);
  3251. // we divide the time part into hour, minutes, seconds
  3252. $agendatime = explode(":", $time);
  3253. $hour = $agendatime[0];
  3254. $minute = $agendatime[1];
  3255. $second = $agendatime[2];
  3256. if ($type == 'month_view') {
  3257. $item['calendar_type'] = 'personal';
  3258. $item['start_date'] = $item['date'];
  3259. $agendaitems[$day][] = $item;
  3260. continue;
  3261. }
  3262. // if the student has specified a course we a add a link to that course
  3263. if ($item['course'] != "") {
  3264. $url = api_get_path(
  3265. WEB_CODE_PATH
  3266. )."calendar/agenda.php?cidReq=".urlencode(
  3267. $item['course']
  3268. )."&day=$day&month=$month&year=$year#$day"; // RH //Patrick Cool: to highlight the relevant agenda item
  3269. $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
  3270. } else {
  3271. $course_link = "";
  3272. }
  3273. // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
  3274. // if we have a day_view we use a half hour as index => key 33 = 16h30
  3275. if ($type !== "day_view") {
  3276. // This is the array construction for the WEEK or MONTH view
  3277. //Display events in agenda
  3278. $agendaitems[$day] .= "<div><i>$time_minute</i> $course_link <a href=\"myagenda.php?action=view&view=personal&day=$day&month=$month&year=$year&id=".$item['id']."#".$item['id']."\" class=\"personal_agenda\">".$item['title']."</a></div><br />";
  3279. } else {
  3280. // this is the array construction for the DAY view
  3281. $halfhour = 2 * $agendatime['0'];
  3282. if ($agendatime['1'] >= '30') {
  3283. $halfhour = $halfhour + 1;
  3284. }
  3285. //Display events by list
  3286. $agendaitems[$halfhour] .= "<div><i>$time_minute</i> $course_link <a href=\"myagenda.php?action=view&view=personal&day=$day&month=$month&year=$year&id=".$item['id']."#".$item['id']."\" class=\"personal_agenda\">".$item['title']."</a></div>";
  3287. }
  3288. }
  3289. return $agendaitems;
  3290. }
  3291. /**
  3292. * Show the monthcalender of the given month.
  3293. *
  3294. * @param array Agendaitems
  3295. * @param int Month number
  3296. * @param int Year number
  3297. * @param array Array of strings containing long week day names (deprecated, you can send an empty array
  3298. * instead)
  3299. * @param string The month name
  3300. */
  3301. public static function display_mymonthcalendar(
  3302. $user_id,
  3303. $agendaitems,
  3304. $month,
  3305. $year,
  3306. $weekdaynames = [],
  3307. $monthName,
  3308. $show_content = true
  3309. ) {
  3310. global $DaysShort, $course_path;
  3311. //Handle leap year
  3312. $numberofdays = [
  3313. 0,
  3314. 31,
  3315. 28,
  3316. 31,
  3317. 30,
  3318. 31,
  3319. 30,
  3320. 31,
  3321. 31,
  3322. 30,
  3323. 31,
  3324. 30,
  3325. 31,
  3326. ];
  3327. if (($year % 400 == 0) or ($year % 4 == 0 and $year % 100 != 0)) {
  3328. $numberofdays[2] = 29;
  3329. }
  3330. //Get the first day of the month
  3331. $dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
  3332. //Start the week on monday
  3333. $startdayofweek = $dayone['wday'] != 0 ? ($dayone['wday'] - 1) : 6;
  3334. $g_cc = (isset($_GET['courseCode']) ? $_GET['courseCode'] : '');
  3335. $next_month = ($month == 1 ? 12 : $month - 1);
  3336. $prev_month = ($month == 12 ? 1 : $month + 1);
  3337. $next_year = ($month == 1 ? $year - 1 : $year);
  3338. $prev_year = ($month == 12 ? $year + 1 : $year);
  3339. if ($show_content) {
  3340. $back_url = Display::url(
  3341. get_lang('Previous'),
  3342. api_get_self()."?coursePath=".urlencode(
  3343. $course_path
  3344. )."&courseCode=".Security::remove_XSS(
  3345. $g_cc
  3346. )."&action=view&view=month&month=".$next_month."&year=".$next_year
  3347. );
  3348. $next_url = Display::url(
  3349. get_lang('Next'),
  3350. api_get_self()."?coursePath=".urlencode(
  3351. $course_path
  3352. )."&courseCode=".Security::remove_XSS(
  3353. $g_cc
  3354. )."&action=view&view=month&month=".$prev_month."&year=".$prev_year
  3355. );
  3356. } else {
  3357. $back_url = Display::url(
  3358. get_lang('Previous'),
  3359. '',
  3360. [
  3361. 'onclick' => "load_calendar('".$user_id."','".$next_month."', '".$next_year."'); ",
  3362. 'class' => 'btn ui-button ui-widget ui-state-default',
  3363. ]
  3364. );
  3365. $next_url = Display::url(
  3366. get_lang('Next'),
  3367. '',
  3368. [
  3369. 'onclick' => "load_calendar('".$user_id."','".$prev_month."', '".$prev_year."'); ",
  3370. 'class' => 'pull-right btn ui-button ui-widget ui-state-default',
  3371. ]
  3372. );
  3373. }
  3374. $html = '';
  3375. $html .= '<div class="actions">';
  3376. $html .= '<div class="row">';
  3377. $html .= '<div class="col-md-4">'.$back_url.'</div>';
  3378. $html .= '<div class="col-md-4"><p class="agenda-title text-center">'.$monthName." ".$year.'</p></div>';
  3379. $html .= '<div class="col-md-4">'.$next_url.'</div>';
  3380. $html .= '</div>';
  3381. $html .= '</div>';
  3382. $html .= '<table id="agenda_list2" class="table table-bordered">';
  3383. $html .= '<tr>';
  3384. for ($ii = 1; $ii < 8; $ii++) {
  3385. $html .= '<td class="weekdays">'.$DaysShort[$ii % 7].'</td>';
  3386. }
  3387. $html .= '</tr>';
  3388. $curday = -1;
  3389. $today = getdate();
  3390. while ($curday <= $numberofdays[$month]) {
  3391. $html .= "<tr>";
  3392. for ($ii = 0; $ii < 7; $ii++) {
  3393. if (($curday == -1) && ($ii == $startdayofweek)) {
  3394. $curday = 1;
  3395. }
  3396. if (($curday > 0) && ($curday <= $numberofdays[$month])) {
  3397. $bgcolor = $class = 'class="days_week"';
  3398. $dayheader = Display::div(
  3399. $curday,
  3400. ['class' => 'agenda_day']
  3401. );
  3402. if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) {
  3403. $class = "class=\"days_today\" style=\"width:10%;\"";
  3404. }
  3405. $html .= "<td ".$class.">".$dayheader;
  3406. if (!empty($agendaitems[$curday])) {
  3407. $items = $agendaitems[$curday];
  3408. $items = msort($items, 'start_date_tms');
  3409. foreach ($items as $value) {
  3410. $value['title'] = Security::remove_XSS(
  3411. $value['title']
  3412. );
  3413. $start_time = api_format_date(
  3414. $value['start_date'],
  3415. TIME_NO_SEC_FORMAT
  3416. );
  3417. $end_time = '';
  3418. if (!empty($value['end_date'])) {
  3419. $end_time = '-&nbsp;<i>'.api_format_date(
  3420. $value['end_date'],
  3421. DATE_TIME_FORMAT_LONG
  3422. ).'</i>';
  3423. }
  3424. $complete_time = '<i>'.api_format_date(
  3425. $value['start_date'],
  3426. DATE_TIME_FORMAT_LONG
  3427. ).'</i>&nbsp;'.$end_time;
  3428. $time = '<i>'.$start_time.'</i>';
  3429. switch ($value['calendar_type']) {
  3430. case 'personal':
  3431. $bg_color = '#D0E7F4';
  3432. $icon = Display::return_icon(
  3433. 'user.png',
  3434. get_lang('Personal agenda'),
  3435. [],
  3436. ICON_SIZE_SMALL
  3437. );
  3438. break;
  3439. case 'global':
  3440. $bg_color = '#FFBC89';
  3441. $icon = Display::return_icon(
  3442. 'view_remove.png',
  3443. get_lang('Platform event'),
  3444. [],
  3445. ICON_SIZE_SMALL
  3446. );
  3447. break;
  3448. case 'course':
  3449. $bg_color = '#CAFFAA';
  3450. $icon_name = 'course.png';
  3451. if (!empty($value['session_id'])) {
  3452. $icon_name = 'session.png';
  3453. }
  3454. if ($show_content) {
  3455. $icon = Display::url(
  3456. Display::return_icon(
  3457. $icon_name,
  3458. $value['course_name'].' '.get_lang(
  3459. 'Course'
  3460. ),
  3461. [],
  3462. ICON_SIZE_SMALL
  3463. ),
  3464. $value['url']
  3465. );
  3466. } else {
  3467. $icon = Display::return_icon(
  3468. $icon_name,
  3469. $value['course_name'].' '.get_lang(
  3470. 'Course'
  3471. ),
  3472. [],
  3473. ICON_SIZE_SMALL
  3474. );
  3475. }
  3476. break;
  3477. default:
  3478. break;
  3479. }
  3480. $result = '<div class="rounded_div_agenda" style="background-color:'.$bg_color.';">';
  3481. if ($show_content) {
  3482. //Setting a personal event to green
  3483. $icon = Display::div(
  3484. $icon,
  3485. ['style' => 'float:right']
  3486. );
  3487. $link = $value['calendar_type'].'_'.$value['id'].'_'.$value['course_id'].'_'.$value['session_id'];
  3488. //Link to bubble
  3489. $url = Display::url(
  3490. cut($value['title'], 40),
  3491. '#',
  3492. ['id' => $link, 'class' => 'opener']
  3493. );
  3494. $result .= $time.' '.$icon.' '.Display::div(
  3495. $url
  3496. );
  3497. //Hidden content
  3498. $content = Display::div(
  3499. $icon.Display::tag(
  3500. 'h2',
  3501. $value['course_name']
  3502. ).'<hr />'.Display::tag(
  3503. 'h3',
  3504. $value['title']
  3505. ).$complete_time.'<hr />'.Security::remove_XSS(
  3506. $value['content']
  3507. )
  3508. );
  3509. //Main div
  3510. $result .= Display::div(
  3511. $content,
  3512. [
  3513. 'id' => 'main_'.$link,
  3514. 'class' => 'dialog',
  3515. 'style' => 'display:none',
  3516. ]
  3517. );
  3518. $result .= '</div>';
  3519. $html .= $result;
  3520. } else {
  3521. $html .= $result .= $icon.'</div>';
  3522. }
  3523. }
  3524. }
  3525. $html .= "</td>";
  3526. $curday++;
  3527. } else {
  3528. $html .= "<td></td>";
  3529. }
  3530. }
  3531. $html .= "</tr>";
  3532. }
  3533. $html .= "</table>";
  3534. echo $html;
  3535. }
  3536. /**
  3537. * Get personal agenda items between two dates (=all events from all registered courses).
  3538. *
  3539. * @param int $user_id user ID of the user
  3540. * @param string Optional start date in datetime format (if no start date is given, uses today)
  3541. * @param string Optional end date in datetime format (if no date is given, uses one year from now)
  3542. *
  3543. * @return array array of events ordered by start date, in
  3544. * [0]('datestart','dateend','title'),[1]('datestart','dateend','title','link','coursetitle') format,
  3545. * where datestart and dateend are in yyyyMMddhhmmss format
  3546. *
  3547. * @deprecated use agenda events
  3548. */
  3549. public static function get_personal_agenda_items_between_dates(
  3550. $user_id,
  3551. $date_start = '',
  3552. $date_end = ''
  3553. ) {
  3554. $items = [];
  3555. if ($user_id != strval(intval($user_id))) {
  3556. return $items;
  3557. }
  3558. if (empty($date_start)) {
  3559. $date_start = date('Y-m-d H:i:s');
  3560. }
  3561. if (empty($date_end)) {
  3562. $date_end = date(
  3563. 'Y-m-d H:i:s',
  3564. mktime(0, 0, 0, date("m"), date("d"), date("Y") + 1)
  3565. );
  3566. }
  3567. $expr = '/\d{4}-\d{2}-\d{2}\ \d{2}:\d{2}:\d{2}/';
  3568. if (!preg_match($expr, $date_start)) {
  3569. return $items;
  3570. }
  3571. if (!preg_match($expr, $date_end)) {
  3572. return $items;
  3573. }
  3574. // get agenda-items for every course
  3575. $courses = api_get_user_courses($user_id, false);
  3576. foreach ($courses as $id => $course) {
  3577. $c = api_get_course_info_by_id($course['real_id']);
  3578. //databases of the courses
  3579. $t_a = Database::get_course_table(TABLE_AGENDA, $course['db']);
  3580. $t_ip = Database::get_course_table(
  3581. TABLE_ITEM_PROPERTY,
  3582. $course['db']
  3583. );
  3584. // get the groups to which the user belong
  3585. $group_memberships = GroupManager:: get_group_ids(
  3586. $course['db'],
  3587. $user_id
  3588. );
  3589. // if the user is administrator of that course we show all the agenda items
  3590. if ($course['status'] == '1') {
  3591. //echo "course admin";
  3592. $sqlquery = "SELECT ".
  3593. " DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
  3594. " FROM ".$t_a." agenda, ".
  3595. $t_ip." ip ".
  3596. " WHERE agenda.id = ip.ref ".
  3597. " AND agenda.start_date>='$date_start' ".
  3598. " AND agenda.end_date<='$date_end' ".
  3599. " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
  3600. " AND ip.visibility='1' ".
  3601. " GROUP BY agenda.id ".
  3602. " ORDER BY start_date ";
  3603. } else {
  3604. // if the user is not an administrator of that course, then...
  3605. if (is_array($group_memberships) && count(
  3606. $group_memberships
  3607. ) > 0
  3608. ) {
  3609. $sqlquery = "SELECT ".
  3610. "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
  3611. " FROM ".$t_a." agenda, ".
  3612. $t_ip." ip ".
  3613. " WHERE agenda.id = ip.ref ".
  3614. " AND agenda.start_date>='$date_start' ".
  3615. " AND agenda.end_date<='$date_end' ".
  3616. " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
  3617. " AND ( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(
  3618. ", ",
  3619. $group_memberships
  3620. ).")) ) ".
  3621. " AND ip.visibility='1' ".
  3622. " ORDER BY start_date ";
  3623. } else {
  3624. $sqlquery = "SELECT ".
  3625. "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
  3626. " FROM ".$t_a." agenda, ".
  3627. $t_ip." ip ".
  3628. " WHERE agenda.id = ip.ref ".
  3629. " AND agenda.start_date>='$date_start' ".
  3630. " AND agenda.end_date<='$date_end' ".
  3631. " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
  3632. " AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ".
  3633. " AND ip.visibility='1' ".
  3634. " ORDER BY start_date ";
  3635. }
  3636. }
  3637. $result = Database::query($sqlquery);
  3638. while ($item = Database::fetch_array($result)) {
  3639. $agendaday = date("j", strtotime($item['start_date']));
  3640. $month = date("n", strtotime($item['start_date']));
  3641. $year = date("Y", strtotime($item['start_date']));
  3642. $URL = api_get_path(
  3643. WEB_PATH
  3644. )."main/calendar/agenda.php?cidReq=".urlencode(
  3645. $course["code"]
  3646. )."&day=$agendaday&month=$month&year=$year#$agendaday";
  3647. list($year, $month, $day, $hour, $min, $sec) = explode(
  3648. '[-: ]',
  3649. $item['start_date']
  3650. );
  3651. $start_date = $year.$month.$day.$hour.$min;
  3652. list($year, $month, $day, $hour, $min, $sec) = explode(
  3653. '[-: ]',
  3654. $item['end_date']
  3655. );
  3656. $end_date = $year.$month.$day.$hour.$min;
  3657. $items[] = [
  3658. 'datestart' => $start_date,
  3659. 'dateend' => $end_date,
  3660. 'title' => $item['title'],
  3661. 'link' => $URL,
  3662. 'coursetitle' => $c['name'],
  3663. ];
  3664. }
  3665. }
  3666. return $items;
  3667. }
  3668. /**
  3669. * This function calculates the startdate of the week (monday)
  3670. * and the enddate of the week (sunday)
  3671. * and returns it as an array.
  3672. */
  3673. public static function calculate_start_end_of_week($week_number, $year)
  3674. {
  3675. // determine the start and end date
  3676. // step 1: we calculate a timestamp for a day in this week
  3677. $random_day_in_week = mktime(
  3678. 0,
  3679. 0,
  3680. 0,
  3681. 1,
  3682. 1,
  3683. $year
  3684. ) + ($week_number) * (7 * 24 * 60 * 60); // we calculate a random day in this week
  3685. // step 2: we which day this is (0=sunday, 1=monday, ...)
  3686. $number_day_in_week = date('w', $random_day_in_week);
  3687. // step 3: we calculate the timestamp of the monday of the week we are in
  3688. $start_timestamp = $random_day_in_week - (($number_day_in_week - 1) * 24 * 60 * 60);
  3689. // step 4: we calculate the timestamp of the sunday of the week we are in
  3690. $end_timestamp = $random_day_in_week + ((7 - $number_day_in_week + 1) * 24 * 60 * 60) - 3600;
  3691. // step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
  3692. $start_day = date('j', $start_timestamp);
  3693. $start_month = date('n', $start_timestamp);
  3694. $start_year = date('Y', $start_timestamp);
  3695. $end_day = date('j', $end_timestamp);
  3696. $end_month = date('n', $end_timestamp);
  3697. $end_year = date('Y', $end_timestamp);
  3698. $start_end_array['start']['day'] = $start_day;
  3699. $start_end_array['start']['month'] = $start_month;
  3700. $start_end_array['start']['year'] = $start_year;
  3701. $start_end_array['end']['day'] = $end_day;
  3702. $start_end_array['end']['month'] = $end_month;
  3703. $start_end_array['end']['year'] = $end_year;
  3704. return $start_end_array;
  3705. }
  3706. /**
  3707. * @return bool
  3708. */
  3709. public function getIsAllowedToEdit()
  3710. {
  3711. return $this->isAllowedToEdit;
  3712. }
  3713. /**
  3714. * @param bool $isAllowedToEdit
  3715. */
  3716. public function setIsAllowedToEdit($isAllowedToEdit)
  3717. {
  3718. $this->isAllowedToEdit = $isAllowedToEdit;
  3719. }
  3720. /**
  3721. * Format needed for the Fullcalendar js lib.
  3722. *
  3723. * @param string $utcTime
  3724. *
  3725. * @return bool|string
  3726. */
  3727. public function formatEventDate($utcTime)
  3728. {
  3729. $utcTimeZone = new DateTimeZone('UTC');
  3730. $platformTimeZone = new DateTimeZone(api_get_timezone());
  3731. $eventDate = new DateTime($utcTime, $utcTimeZone);
  3732. $eventDate->setTimezone($platformTimeZone);
  3733. return $eventDate->format(DateTime::ISO8601);
  3734. }
  3735. }