agenda.lib.php 148 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125
  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. }