agenda.lib.php 148 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121
  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('LoginX'),
  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('AddCalendarItem');
  2123. if (!empty($id)) {
  2124. $form_Title = get_lang('ModifyCalendarItem');
  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('EditingThisEventWillRemoveItFromTheSerie'),
  2151. 'warning'
  2152. )
  2153. );
  2154. }
  2155. $form->addElement('text', 'title', get_lang('ItemTitle'));
  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('DateRange'),
  2172. false,
  2173. ['id' => 'date_range']
  2174. );
  2175. $form->addElement('checkbox', 'all_day', null, get_lang('AllDay'));
  2176. if ($this->type == 'course') {
  2177. $repeat = $form->addElement(
  2178. 'checkbox',
  2179. 'repeat',
  2180. null,
  2181. get_lang('RepeatEvent'),
  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('RepeatType'),
  2192. self::getRepeatTypes()
  2193. );
  2194. $form->addElement(
  2195. 'date_picker',
  2196. 'repeat_end_day',
  2197. get_lang('RepeatEnd'),
  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('FilesAttachment'),
  2245. '<span id="filepaths">
  2246. <div id="filepath_1">
  2247. <input type="file" name="attach_1"/><br />
  2248. '.get_lang('Description').'&nbsp;&nbsp;<input type="text" name="legend[]" /><br /><br />
  2249. </div>
  2250. </span>'
  2251. );
  2252. $form->addLabel(
  2253. '',
  2254. '<span id="link-more-attach">
  2255. <a href="javascript://" onclick="return add_image_form()">'.
  2256. get_lang('AddOneMoreFile').'</a>
  2257. </span>&nbsp;('.sprintf(
  2258. get_lang('MaximunFileSizeX'),
  2259. format_file_size(
  2260. api_get_setting('message_max_upload_filesize')
  2261. )
  2262. ).')'
  2263. );
  2264. if (isset($params['attachment']) && !empty($params['attachment'])) {
  2265. $attachmentList = $params['attachment'];
  2266. foreach ($attachmentList as $attachment) {
  2267. $params['file_comment'] = $attachment['comment'];
  2268. if (!empty($attachment['path'])) {
  2269. $form->addElement(
  2270. 'checkbox',
  2271. 'delete_attachment['.$attachment['id'].']',
  2272. null,
  2273. get_lang(
  2274. 'DeleteAttachment'
  2275. ).': '.$attachment['filename']
  2276. );
  2277. }
  2278. }
  2279. }
  2280. $form->addElement(
  2281. 'textarea',
  2282. 'file_comment',
  2283. get_lang('FileComment')
  2284. );
  2285. }
  2286. if (empty($id)) {
  2287. $form->addElement(
  2288. 'checkbox',
  2289. 'add_announcement',
  2290. null,
  2291. get_lang('AddAnnouncement').'&nbsp('.get_lang('SendMail').')'
  2292. );
  2293. }
  2294. if ($id) {
  2295. $form->addButtonUpdate(get_lang('ModifyEvent'));
  2296. } else {
  2297. $form->addButtonSave(get_lang('AgendaAdd'));
  2298. }
  2299. $form->setDefaults($params);
  2300. $form->addRule(
  2301. 'date_range',
  2302. get_lang('ThisFieldIsRequired'),
  2303. 'required'
  2304. );
  2305. $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
  2306. return $form;
  2307. }
  2308. /**
  2309. * @param FormValidator $form
  2310. * @param array $sendTo array('everyone' => false, 'users' => [1, 2], 'groups' => [3, 4])
  2311. * @param array $attributes
  2312. * @param bool $addOnlyItemsInSendTo
  2313. * @param bool $required
  2314. *
  2315. * @return bool
  2316. */
  2317. public function showToForm(
  2318. $form,
  2319. $sendTo = [],
  2320. $attributes = [],
  2321. $addOnlyItemsInSendTo = false,
  2322. $required = false
  2323. ) {
  2324. if ($this->type != 'course') {
  2325. return false;
  2326. }
  2327. $order = 'lastname';
  2328. if (api_is_western_name_order()) {
  2329. $order = 'firstname';
  2330. }
  2331. $userList = CourseManager::get_user_list_from_course_code(
  2332. api_get_course_id(),
  2333. $this->sessionId,
  2334. null,
  2335. $order
  2336. );
  2337. $groupList = CourseManager::get_group_list_of_course(
  2338. api_get_course_id(),
  2339. $this->sessionId
  2340. );
  2341. $this->setSendToSelect(
  2342. $form,
  2343. $groupList,
  2344. $userList,
  2345. $sendTo,
  2346. $attributes,
  2347. $addOnlyItemsInSendTo,
  2348. $required
  2349. );
  2350. return true;
  2351. }
  2352. /**
  2353. * @param int $id
  2354. * @param int $visibility 0= invisible, 1 visible
  2355. * @param array $courseInfo
  2356. * @param int $userId
  2357. */
  2358. public static function changeVisibility(
  2359. $id,
  2360. $visibility,
  2361. $courseInfo,
  2362. $userId = null
  2363. ) {
  2364. $id = intval($id);
  2365. if (empty($userId)) {
  2366. $userId = api_get_user_id();
  2367. } else {
  2368. $userId = intval($userId);
  2369. }
  2370. if ($visibility == 0) {
  2371. api_item_property_update(
  2372. $courseInfo,
  2373. TOOL_CALENDAR_EVENT,
  2374. $id,
  2375. 'invisible',
  2376. $userId
  2377. );
  2378. } else {
  2379. api_item_property_update(
  2380. $courseInfo,
  2381. TOOL_CALENDAR_EVENT,
  2382. $id,
  2383. 'visible',
  2384. $userId
  2385. );
  2386. }
  2387. }
  2388. /**
  2389. * Get repeat types.
  2390. *
  2391. * @return array
  2392. */
  2393. public static function getRepeatTypes()
  2394. {
  2395. return [
  2396. 'daily' => get_lang('RepeatDaily'),
  2397. 'weekly' => get_lang('RepeatWeekly'),
  2398. 'monthlyByDate' => get_lang('RepeatMonthlyByDate'),
  2399. //monthlyByDay"> get_lang('RepeatMonthlyByDay');
  2400. //monthlyByDayR' => get_lang('RepeatMonthlyByDayR'),
  2401. 'yearly' => get_lang('RepeatYearly'),
  2402. ];
  2403. }
  2404. /**
  2405. * Show a list with all the attachments according to the post's id.
  2406. *
  2407. * @param int $eventId
  2408. * @param array $courseInfo
  2409. *
  2410. * @return array with the post info
  2411. */
  2412. public function getAttachmentList($eventId, $courseInfo)
  2413. {
  2414. $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
  2415. $courseId = (int) $courseInfo['real_id'];
  2416. $eventId = (int) $eventId;
  2417. $sql = "SELECT id, path, filename, comment
  2418. FROM $tableAttachment
  2419. WHERE
  2420. c_id = $courseId AND
  2421. agenda_id = $eventId";
  2422. $result = Database::query($sql);
  2423. $list = [];
  2424. if (Database::num_rows($result) != 0) {
  2425. $list = Database::store_result($result, 'ASSOC');
  2426. }
  2427. return $list;
  2428. }
  2429. /**
  2430. * Show a list with all the attachments according to the post's id.
  2431. *
  2432. * @param int $attachmentId
  2433. * @param int $eventId
  2434. * @param array $courseInfo
  2435. *
  2436. * @return array with the post info
  2437. */
  2438. public function getAttachment($attachmentId, $eventId, $courseInfo)
  2439. {
  2440. if (empty($courseInfo) || empty($attachmentId) || empty($eventId)) {
  2441. return [];
  2442. }
  2443. $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
  2444. $courseId = (int) $courseInfo['real_id'];
  2445. $eventId = (int) $eventId;
  2446. $attachmentId = (int) $attachmentId;
  2447. $row = [];
  2448. $sql = "SELECT id, path, filename, comment
  2449. FROM $tableAttachment
  2450. WHERE
  2451. c_id = $courseId AND
  2452. agenda_id = $eventId AND
  2453. id = $attachmentId
  2454. ";
  2455. $result = Database::query($sql);
  2456. if (Database::num_rows($result) != 0) {
  2457. $row = Database::fetch_array($result, 'ASSOC');
  2458. }
  2459. return $row;
  2460. }
  2461. /**
  2462. * Add an attachment file into agenda.
  2463. *
  2464. * @param int $eventId
  2465. * @param array $fileUserUpload ($_FILES['user_upload'])
  2466. * @param string $comment about file
  2467. * @param array $courseInfo
  2468. *
  2469. * @return string
  2470. */
  2471. public function addAttachment(
  2472. $eventId,
  2473. $fileUserUpload,
  2474. $comment,
  2475. $courseInfo
  2476. ) {
  2477. $agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
  2478. $eventId = (int) $eventId;
  2479. // Storing the attachments
  2480. $upload_ok = false;
  2481. if (!empty($fileUserUpload['name'])) {
  2482. $upload_ok = process_uploaded_file($fileUserUpload);
  2483. }
  2484. if (!empty($upload_ok)) {
  2485. $courseDir = $courseInfo['directory'].'/upload/calendar';
  2486. $sys_course_path = api_get_path(SYS_COURSE_PATH);
  2487. $uploadDir = $sys_course_path.$courseDir;
  2488. // Try to add an extension to the file if it hasn't one
  2489. $new_file_name = add_ext_on_mime(
  2490. stripslashes($fileUserUpload['name']),
  2491. $fileUserUpload['type']
  2492. );
  2493. // user's file name
  2494. $file_name = $fileUserUpload['name'];
  2495. if (!filter_extension($new_file_name)) {
  2496. return Display::return_message(
  2497. get_lang('UplUnableToSaveFileFilteredExtension'),
  2498. 'error'
  2499. );
  2500. } else {
  2501. $new_file_name = uniqid('');
  2502. $new_path = $uploadDir.'/'.$new_file_name;
  2503. $result = @move_uploaded_file(
  2504. $fileUserUpload['tmp_name'],
  2505. $new_path
  2506. );
  2507. $courseId = api_get_course_int_id();
  2508. $size = intval($fileUserUpload['size']);
  2509. // Storing the attachments if any
  2510. if ($result) {
  2511. $params = [
  2512. 'c_id' => $courseId,
  2513. 'filename' => $file_name,
  2514. 'comment' => $comment,
  2515. 'path' => $new_file_name,
  2516. 'agenda_id' => $eventId,
  2517. 'size' => $size,
  2518. ];
  2519. $id = Database::insert($agenda_table_attachment, $params);
  2520. if ($id) {
  2521. $sql = "UPDATE $agenda_table_attachment
  2522. SET id = iid WHERE iid = $id";
  2523. Database::query($sql);
  2524. api_item_property_update(
  2525. $courseInfo,
  2526. 'calendar_event_attachment',
  2527. $id,
  2528. 'AgendaAttachmentAdded',
  2529. api_get_user_id()
  2530. );
  2531. }
  2532. }
  2533. }
  2534. }
  2535. }
  2536. /**
  2537. * @param int $attachmentId
  2538. * @param int $eventId
  2539. * @param array $fileUserUpload
  2540. * @param string $comment
  2541. * @param array $courseInfo
  2542. */
  2543. public function updateAttachment(
  2544. $attachmentId,
  2545. $eventId,
  2546. $fileUserUpload,
  2547. $comment,
  2548. $courseInfo
  2549. ) {
  2550. $attachment = $this->getAttachment(
  2551. $attachmentId,
  2552. $eventId,
  2553. $courseInfo
  2554. );
  2555. if (!empty($attachment)) {
  2556. $this->deleteAttachmentFile($attachmentId, $courseInfo);
  2557. }
  2558. $this->addAttachment($eventId, $fileUserUpload, $comment, $courseInfo);
  2559. }
  2560. /**
  2561. * This function delete a attachment file by id.
  2562. *
  2563. * @param int $attachmentId
  2564. * @param array $courseInfo
  2565. *
  2566. * @return string
  2567. */
  2568. public function deleteAttachmentFile($attachmentId, $courseInfo)
  2569. {
  2570. $table = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
  2571. $attachmentId = (int) $attachmentId;
  2572. $courseId = $courseInfo['real_id'];
  2573. if (empty($courseId) || empty($attachmentId)) {
  2574. return false;
  2575. }
  2576. $sql = "DELETE FROM $table
  2577. WHERE c_id = $courseId AND id = ".$attachmentId;
  2578. $result = Database::query($sql);
  2579. // update item_property
  2580. api_item_property_update(
  2581. $courseInfo,
  2582. 'calendar_event_attachment',
  2583. $attachmentId,
  2584. 'AgendaAttachmentDeleted',
  2585. api_get_user_id()
  2586. );
  2587. if (!empty($result)) {
  2588. return Display::return_message(
  2589. get_lang("AttachmentFileDeleteSuccess"),
  2590. 'confirmation'
  2591. );
  2592. }
  2593. }
  2594. /**
  2595. * @param int $eventId
  2596. *
  2597. * @return array
  2598. */
  2599. public function getAllRepeatEvents($eventId)
  2600. {
  2601. $events = [];
  2602. $eventId = (int) $eventId;
  2603. switch ($this->type) {
  2604. case 'personal':
  2605. break;
  2606. case 'course':
  2607. if (!empty($this->course['real_id'])) {
  2608. $sql = "SELECT * FROM ".$this->tbl_course_agenda."
  2609. WHERE
  2610. c_id = ".$this->course['real_id']." AND
  2611. parent_event_id = ".$eventId;
  2612. $result = Database::query($sql);
  2613. if (Database::num_rows($result)) {
  2614. while ($row = Database::fetch_array($result, 'ASSOC')) {
  2615. $events[] = $row;
  2616. }
  2617. }
  2618. }
  2619. break;
  2620. }
  2621. return $events;
  2622. }
  2623. /**
  2624. * @param int $eventId
  2625. * @param int $courseId
  2626. *
  2627. * @return bool
  2628. */
  2629. public function hasChildren($eventId, $courseId)
  2630. {
  2631. $eventId = (int) $eventId;
  2632. $courseId = (int) $courseId;
  2633. $sql = "SELECT count(DISTINCT(id)) as count
  2634. FROM ".$this->tbl_course_agenda."
  2635. WHERE
  2636. c_id = $courseId AND
  2637. parent_event_id = $eventId";
  2638. $result = Database::query($sql);
  2639. if (Database::num_rows($result)) {
  2640. $row = Database::fetch_array($result, 'ASSOC');
  2641. return $row['count'] > 0;
  2642. }
  2643. return false;
  2644. }
  2645. /**
  2646. * @param int $filter
  2647. * @param string $view
  2648. *
  2649. * @return string
  2650. */
  2651. public function displayActions($view, $filter = 0)
  2652. {
  2653. $groupInfo = GroupManager::get_group_properties(api_get_group_id());
  2654. $groupIid = isset($groupInfo['iid']) ? $groupInfo['iid'] : 0;
  2655. $codePath = api_get_path(WEB_CODE_PATH);
  2656. $currentUserId = api_get_user_id();
  2657. $cidReq = api_get_cidreq();
  2658. $actionsLeft = '';
  2659. $actionsLeft .= Display::url(
  2660. Display::return_icon('calendar.png', get_lang('Calendar'), [], ICON_SIZE_MEDIUM),
  2661. $codePath."calendar/agenda_js.php?type={$this->type}&$cidReq"
  2662. );
  2663. $actionsLeft .= Display::url(
  2664. Display::return_icon('week.png', get_lang('AgendaList'), [], ICON_SIZE_MEDIUM),
  2665. $codePath."calendar/agenda_list.php?type={$this->type}&$cidReq"
  2666. );
  2667. $form = '';
  2668. if (api_is_allowed_to_edit(false, true) ||
  2669. (api_get_course_setting('allow_user_edit_agenda') == '1' && !api_is_anonymous()) &&
  2670. api_is_allowed_to_session_edit(false, true)
  2671. || (
  2672. GroupManager::user_has_access($currentUserId, $groupIid, GroupManager::GROUP_TOOL_CALENDAR)
  2673. && GroupManager::is_tutor_of_group($currentUserId, $groupInfo)
  2674. )
  2675. ) {
  2676. $actionsLeft .= Display::url(
  2677. Display::return_icon('new_event.png', get_lang('AgendaAdd'), [], ICON_SIZE_MEDIUM),
  2678. $codePath."calendar/agenda.php?action=add&type={$this->type}&$cidReq"
  2679. );
  2680. $actionsLeft .= Display::url(
  2681. Display::return_icon('import_calendar.png', get_lang('ICalFileImport'), [], ICON_SIZE_MEDIUM),
  2682. $codePath."calendar/agenda.php?action=importical&type={$this->type}&$cidReq"
  2683. );
  2684. if ($this->type === 'course') {
  2685. if (!isset($_GET['action'])) {
  2686. $form = new FormValidator(
  2687. 'form-search',
  2688. 'post',
  2689. '',
  2690. '',
  2691. [],
  2692. FormValidator::LAYOUT_INLINE
  2693. );
  2694. $attributes = [
  2695. 'multiple' => false,
  2696. 'id' => 'select_form_id_search',
  2697. ];
  2698. $selectedValues = $this->parseAgendaFilter($filter);
  2699. $this->showToForm($form, $selectedValues, $attributes);
  2700. $form = $form->returnForm();
  2701. }
  2702. }
  2703. }
  2704. if ($this->type == 'personal' && !api_is_anonymous()) {
  2705. $actionsLeft .= Display::url(
  2706. Display::return_icon('1day.png', get_lang('SessionsPlanCalendar'), [], ICON_SIZE_MEDIUM),
  2707. $codePath."calendar/planification.php"
  2708. );
  2709. }
  2710. if (api_is_platform_admin() ||
  2711. api_is_teacher() ||
  2712. api_is_student_boss() ||
  2713. api_is_drh() ||
  2714. api_is_session_admin() ||
  2715. api_is_coach()
  2716. ) {
  2717. if ($this->type == 'personal') {
  2718. $form = null;
  2719. if (!isset($_GET['action'])) {
  2720. $form = new FormValidator(
  2721. 'form-search',
  2722. 'get',
  2723. api_get_self().'?type=personal&',
  2724. '',
  2725. [],
  2726. FormValidator::LAYOUT_INLINE
  2727. );
  2728. $sessions = [];
  2729. if (api_is_drh()) {
  2730. $sessionList = SessionManager::get_sessions_followed_by_drh($currentUserId);
  2731. if (!empty($sessionList)) {
  2732. foreach ($sessionList as $sessionItem) {
  2733. $sessions[$sessionItem['id']] = strip_tags($sessionItem['name']);
  2734. }
  2735. }
  2736. } else {
  2737. $sessions = SessionManager::get_sessions_by_user($currentUserId);
  2738. $sessions = array_column($sessions, 'session_name', 'session_id');
  2739. }
  2740. $form->addHidden('type', 'personal');
  2741. $sessions = ['0' => get_lang('SelectAnOption')] + $sessions;
  2742. $form->addSelect(
  2743. 'session_id',
  2744. get_lang('Session'),
  2745. $sessions,
  2746. ['id' => 'session_id', 'onchange' => 'submit();']
  2747. );
  2748. $form->addButtonReset(get_lang('Reset'));
  2749. $form = $form->returnForm();
  2750. }
  2751. }
  2752. }
  2753. $actionsRight = '';
  2754. if ($view == 'calendar') {
  2755. $actionsRight .= $form;
  2756. }
  2757. $toolbar = Display::toolbarAction(
  2758. 'toolbar-agenda',
  2759. [$actionsLeft, $actionsRight]
  2760. );
  2761. return $toolbar;
  2762. }
  2763. /**
  2764. * @return FormValidator
  2765. */
  2766. public function getImportCalendarForm()
  2767. {
  2768. $form = new FormValidator(
  2769. 'frm_import_ical',
  2770. 'post',
  2771. api_get_self().'?action=importical&type='.$this->type,
  2772. ['enctype' => 'multipart/form-data']
  2773. );
  2774. $form->addHeader(get_lang('ICalFileImport'));
  2775. $form->addElement('file', 'ical_import', get_lang('ICalFileImport'));
  2776. $form->addRule(
  2777. 'ical_import',
  2778. get_lang('ThisFieldIsRequired'),
  2779. 'required'
  2780. );
  2781. $form->addButtonImport(get_lang('Import'), 'ical_submit');
  2782. return $form;
  2783. }
  2784. /**
  2785. * @param array $courseInfo
  2786. * @param $file
  2787. *
  2788. * @return false|string
  2789. */
  2790. public function importEventFile($courseInfo, $file)
  2791. {
  2792. $charset = api_get_system_encoding();
  2793. $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
  2794. $messages = [];
  2795. if (!@move_uploaded_file($file['tmp_name'], $filepath)) {
  2796. error_log(
  2797. 'Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__
  2798. );
  2799. return false;
  2800. }
  2801. $data = file_get_contents($filepath);
  2802. $trans = [
  2803. 'DAILY' => 'daily',
  2804. 'WEEKLY' => 'weekly',
  2805. 'MONTHLY' => 'monthlyByDate',
  2806. 'YEARLY' => 'yearly',
  2807. ];
  2808. $sentTo = ['everyone' => true];
  2809. $calendar = Sabre\VObject\Reader::read($data);
  2810. $currentTimeZone = api_get_timezone();
  2811. if (!empty($calendar->VEVENT)) {
  2812. foreach ($calendar->VEVENT as $event) {
  2813. $start = $event->DTSTART->getDateTime();
  2814. $end = $event->DTEND->getDateTime();
  2815. //Sabre\VObject\DateTimeParser::parseDateTime(string $dt, \Sabre\VObject\DateTimeZone $tz)
  2816. $startDateTime = api_get_local_time(
  2817. $start->format('Y-m-d H:i:s'),
  2818. $currentTimeZone,
  2819. $start->format('e')
  2820. );
  2821. $endDateTime = api_get_local_time(
  2822. $end->format('Y-m-d H:i'),
  2823. $currentTimeZone,
  2824. $end->format('e')
  2825. );
  2826. $title = api_convert_encoding(
  2827. (string) $event->summary,
  2828. $charset,
  2829. 'UTF-8'
  2830. );
  2831. $description = api_convert_encoding(
  2832. (string) $event->description,
  2833. $charset,
  2834. 'UTF-8'
  2835. );
  2836. $id = $this->addEvent(
  2837. $startDateTime,
  2838. $endDateTime,
  2839. 'false',
  2840. $title,
  2841. $description,
  2842. $sentTo
  2843. );
  2844. $messages[] = " $title - ".$startDateTime." - ".$endDateTime;
  2845. //$attendee = (string)$event->attendee;
  2846. /** @var Sabre\VObject\Property\ICalendar\Recur $repeat */
  2847. $repeat = $event->RRULE;
  2848. if ($id && !empty($repeat)) {
  2849. $repeat = $repeat->getParts();
  2850. $freq = $trans[$repeat['FREQ']];
  2851. if (isset($repeat['UNTIL']) && !empty($repeat['UNTIL'])) {
  2852. // Check if datetime or just date (strlen == 8)
  2853. if (strlen($repeat['UNTIL']) == 8) {
  2854. // Fix the datetime format to avoid exception in the next step
  2855. $repeat['UNTIL'] .= 'T000000';
  2856. }
  2857. $until = Sabre\VObject\DateTimeParser::parseDateTime(
  2858. $repeat['UNTIL'],
  2859. new DateTimeZone($currentTimeZone)
  2860. );
  2861. $until = $until->format('Y-m-d H:i:s');
  2862. $this->addRepeatedItem(
  2863. $id,
  2864. $freq,
  2865. $until,
  2866. $sentTo
  2867. );
  2868. }
  2869. if (!empty($repeat['COUNT'])) {
  2870. /*$count = $repeat['COUNT'];
  2871. $interval = $repeat['INTERVAL'];
  2872. $endDate = null;
  2873. switch($freq) {
  2874. case 'daily':
  2875. $start = api_strtotime($startDateTime);
  2876. $date = new DateTime($startDateTime);
  2877. $days = $count * $interval;
  2878. var_dump($days);
  2879. $date->add(new DateInterval("P".$days."D"));
  2880. $endDate = $date->format('Y-m-d H:i');
  2881. //$endDate = $count *
  2882. for ($i = 0; $i < $count; $i++) {
  2883. $days = 86400 * 7
  2884. }
  2885. }
  2886. }*/
  2887. //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $count, $attendee);
  2888. /*$this->addRepeatedItem(
  2889. $id,
  2890. $freq,
  2891. $endDate,
  2892. $sentTo
  2893. );*/
  2894. }
  2895. }
  2896. }
  2897. }
  2898. if (!empty($messages)) {
  2899. $messages = implode('<br /> ', $messages);
  2900. } else {
  2901. $messages = get_lang('NoAgendaItems');
  2902. }
  2903. return $messages;
  2904. }
  2905. /**
  2906. * Parse filter turns USER:12 to ['users' => [12])] or G:1 ['groups' => [1]].
  2907. *
  2908. * @param int $filter
  2909. *
  2910. * @return array
  2911. */
  2912. public function parseAgendaFilter($filter)
  2913. {
  2914. $everyone = false;
  2915. $groupId = null;
  2916. $userId = null;
  2917. if ($filter == 'everyone') {
  2918. $everyone = true;
  2919. } else {
  2920. if (substr($filter, 0, 1) == 'G') {
  2921. $groupId = str_replace('GROUP:', '', $filter);
  2922. } else {
  2923. $userId = str_replace('USER:', '', $filter);
  2924. }
  2925. }
  2926. if (empty($userId) && empty($groupId)) {
  2927. $everyone = true;
  2928. }
  2929. return [
  2930. 'everyone' => $everyone,
  2931. 'users' => [$userId],
  2932. 'groups' => [$groupId],
  2933. ];
  2934. }
  2935. /**
  2936. * This function retrieves all the agenda items of all the courses the user is subscribed to.
  2937. */
  2938. public static function get_myagendaitems(
  2939. $user_id,
  2940. $courses_dbs,
  2941. $month,
  2942. $year
  2943. ) {
  2944. $user_id = intval($user_id);
  2945. $items = [];
  2946. $my_list = [];
  2947. // get agenda-items for every course
  2948. foreach ($courses_dbs as $key => $array_course_info) {
  2949. //databases of the courses
  2950. $TABLEAGENDA = Database::get_course_table(TABLE_AGENDA);
  2951. $TABLE_ITEMPROPERTY = Database::get_course_table(
  2952. TABLE_ITEM_PROPERTY
  2953. );
  2954. $group_memberships = GroupManager::get_group_ids(
  2955. $array_course_info['real_id'],
  2956. $user_id
  2957. );
  2958. $course_user_status = CourseManager::getUserInCourseStatus(
  2959. $user_id,
  2960. $array_course_info['real_id']
  2961. );
  2962. // if the user is administrator of that course we show all the agenda items
  2963. if ($course_user_status == '1') {
  2964. //echo "course admin";
  2965. $sqlquery = "SELECT DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
  2966. FROM ".$TABLEAGENDA." agenda,
  2967. ".$TABLE_ITEMPROPERTY." ip
  2968. WHERE agenda.id = ip.ref
  2969. AND MONTH(agenda.start_date)='".$month."'
  2970. AND YEAR(agenda.start_date)='".$year."'
  2971. AND ip.tool='".TOOL_CALENDAR_EVENT."'
  2972. AND ip.visibility='1'
  2973. GROUP BY agenda.id
  2974. ORDER BY start_date ";
  2975. } else {
  2976. // if the user is not an administrator of that course
  2977. if (is_array($group_memberships) && count(
  2978. $group_memberships
  2979. ) > 0
  2980. ) {
  2981. $sqlquery = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
  2982. FROM ".$TABLEAGENDA." agenda,
  2983. ".$TABLE_ITEMPROPERTY." ip
  2984. WHERE agenda.id = ip.ref
  2985. AND MONTH(agenda.start_date)='".$month."'
  2986. AND YEAR(agenda.start_date)='".$year."'
  2987. AND ip.tool='".TOOL_CALENDAR_EVENT."'
  2988. AND ( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(
  2989. ", ",
  2990. $group_memberships
  2991. ).")) )
  2992. AND ip.visibility='1'
  2993. ORDER BY start_date ";
  2994. } else {
  2995. $sqlquery = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
  2996. FROM ".$TABLEAGENDA." agenda,
  2997. ".$TABLE_ITEMPROPERTY." ip
  2998. WHERE agenda.id = ip.ref
  2999. AND MONTH(agenda.start_date)='".$month."'
  3000. AND YEAR(agenda.start_date)='".$year."'
  3001. AND ip.tool='".TOOL_CALENDAR_EVENT."'
  3002. AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
  3003. AND ip.visibility='1'
  3004. ORDER BY start_date ";
  3005. }
  3006. }
  3007. $result = Database::query($sqlquery);
  3008. while ($item = Database::fetch_array($result, 'ASSOC')) {
  3009. $agendaday = -1;
  3010. if (!empty($item['start_date'])) {
  3011. $item['start_date'] = api_get_local_time(
  3012. $item['start_date']
  3013. );
  3014. $item['start_date_tms'] = api_strtotime(
  3015. $item['start_date']
  3016. );
  3017. $agendaday = date("j", $item['start_date_tms']);
  3018. }
  3019. if (!empty($item['end_date'])) {
  3020. $item['end_date'] = api_get_local_time($item['end_date']);
  3021. }
  3022. $url = api_get_path(
  3023. WEB_CODE_PATH
  3024. )."calendar/agenda.php?cidReq=".urlencode(
  3025. $array_course_info["code"]
  3026. )."&day=$agendaday&month=$month&year=$year#$agendaday";
  3027. $item['url'] = $url;
  3028. $item['course_name'] = $array_course_info['title'];
  3029. $item['calendar_type'] = 'course';
  3030. $item['course_id'] = $array_course_info['course_id'];
  3031. $my_list[$agendaday][] = $item;
  3032. }
  3033. }
  3034. // sorting by hour for every day
  3035. $agendaitems = [];
  3036. foreach ($items as $agendaday => $tmpitems) {
  3037. if (!isset($agendaitems[$agendaday])) {
  3038. $agendaitems[$agendaday] = '';
  3039. }
  3040. sort($tmpitems);
  3041. foreach ($tmpitems as $val) {
  3042. $agendaitems[$agendaday] .= $val;
  3043. }
  3044. }
  3045. return $my_list;
  3046. }
  3047. /**
  3048. * This function retrieves one personal agenda item returns it.
  3049. *
  3050. * @param array The array containing existing events. We add to this array.
  3051. * @param int Day
  3052. * @param int Month
  3053. * @param int Year (4 digits)
  3054. * @param int Week number
  3055. * @param string Type of view (month_view, week_view, day_view)
  3056. *
  3057. * @return array The results of the database query, or null if not found
  3058. */
  3059. public static function get_global_agenda_items(
  3060. $agendaitems,
  3061. $day = "",
  3062. $month = "",
  3063. $year = "",
  3064. $week = "",
  3065. $type
  3066. ) {
  3067. $tbl_global_agenda = Database::get_main_table(
  3068. TABLE_MAIN_SYSTEM_CALENDAR
  3069. );
  3070. $month = intval($month);
  3071. $year = intval($year);
  3072. $week = intval($week);
  3073. $day = intval($day);
  3074. // 1. creating the SQL statement for getting the personal agenda items in MONTH view
  3075. $current_access_url_id = api_get_current_access_url_id();
  3076. if ($type == "month_view" or $type == "") {
  3077. // We are in month view
  3078. $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";
  3079. }
  3080. // 2. creating the SQL statement for getting the personal agenda items in WEEK view
  3081. if ($type == "week_view") { // we are in week view
  3082. $start_end_day_of_week = self::calculate_start_end_of_week(
  3083. $week,
  3084. $year
  3085. );
  3086. $start_day = $start_end_day_of_week['start']['day'];
  3087. $start_month = $start_end_day_of_week['start']['month'];
  3088. $start_year = $start_end_day_of_week['start']['year'];
  3089. $end_day = $start_end_day_of_week['end']['day'];
  3090. $end_month = $start_end_day_of_week['end']['month'];
  3091. $end_year = $start_end_day_of_week['end']['year'];
  3092. // in sql statements you have to use year-month-day for date calculations
  3093. $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
  3094. $start_filter = api_get_utc_datetime($start_filter);
  3095. $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
  3096. $end_filter = api_get_utc_datetime($end_filter);
  3097. $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."' AND access_url_id = $current_access_url_id ";
  3098. }
  3099. // 3. creating the SQL statement for getting the personal agenda items in DAY view
  3100. if ($type == "day_view") { // we are in day view
  3101. // we could use mysql date() function but this is only available from 4.1 and higher
  3102. $start_filter = $year."-".$month."-".$day." 00:00:00";
  3103. $start_filter = api_get_utc_datetime($start_filter);
  3104. $end_filter = $year."-".$month."-".$day." 23:59:59";
  3105. $end_filter = api_get_utc_datetime($end_filter);
  3106. $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."' AND access_url_id = $current_access_url_id";
  3107. }
  3108. $result = Database::query($sql);
  3109. while ($item = Database::fetch_array($result)) {
  3110. if (!empty($item['start_date'])) {
  3111. $item['start_date'] = api_get_local_time($item['start_date']);
  3112. $item['start_date_tms'] = api_strtotime($item['start_date']);
  3113. }
  3114. if (!empty($item['end_date'])) {
  3115. $item['end_date'] = api_get_local_time($item['end_date']);
  3116. }
  3117. // we break the date field in the database into a date and a time part
  3118. $agenda_db_date = explode(" ", $item['start_date']);
  3119. $date = $agenda_db_date[0];
  3120. $time = $agenda_db_date[1];
  3121. // we divide the date part into a day, a month and a year
  3122. $agendadate = explode("-", $date);
  3123. $year = intval($agendadate[0]);
  3124. $month = intval($agendadate[1]);
  3125. $day = intval($agendadate[2]);
  3126. // we divide the time part into hour, minutes, seconds
  3127. $agendatime = explode(":", $time);
  3128. $hour = $agendatime[0];
  3129. $minute = $agendatime[1];
  3130. $second = $agendatime[2];
  3131. if ($type == 'month_view') {
  3132. $item['calendar_type'] = 'global';
  3133. $agendaitems[$day][] = $item;
  3134. continue;
  3135. }
  3136. $start_time = api_format_date(
  3137. $item['start_date'],
  3138. TIME_NO_SEC_FORMAT
  3139. );
  3140. $end_time = '';
  3141. if (!empty($item['end_date'])) {
  3142. $end_time = ' - '.api_format_date(
  3143. $item['end_date'],
  3144. DATE_TIME_FORMAT_LONG
  3145. );
  3146. }
  3147. // if the student has specified a course we a add a link to that course
  3148. if ($item['course'] != "") {
  3149. $url = api_get_path(
  3150. WEB_CODE_PATH
  3151. )."admin/agenda.php?cidReq=".urlencode(
  3152. $item['course']
  3153. )."&day=$day&month=$month&year=$year#$day"; // RH //Patrick Cool: to highlight the relevant agenda item
  3154. $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
  3155. } else {
  3156. $course_link = "";
  3157. }
  3158. // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
  3159. // if we have a day_view we use a half hour as index => key 33 = 16h30
  3160. if ($type !== "day_view") {
  3161. // This is the array construction for the WEEK or MONTH view
  3162. //Display the Agenda global in the tab agenda (administrator)
  3163. $agendaitems[$day] .= "<i>$start_time $end_time</i>&nbsp;-&nbsp;";
  3164. $agendaitems[$day] .= "<b>".get_lang('GlobalEvent')."</b>";
  3165. $agendaitems[$day] .= "<div>".$item['title']."</div><br>";
  3166. } else {
  3167. // this is the array construction for the DAY view
  3168. $halfhour = 2 * $agendatime['0'];
  3169. if ($agendatime['1'] >= '30') {
  3170. $halfhour = $halfhour + 1;
  3171. }
  3172. if (!is_array($agendaitems[$halfhour])) {
  3173. $content = $agendaitems[$halfhour];
  3174. }
  3175. $agendaitems[$halfhour] = $content."<div><i>$hour:$minute</i> <b>".get_lang(
  3176. 'GlobalEvent'
  3177. ).": </b>".$item['title']."</div>";
  3178. }
  3179. }
  3180. return $agendaitems;
  3181. }
  3182. /**
  3183. * This function retrieves all the personal agenda items and add them to the agenda items found by the other
  3184. * functions.
  3185. */
  3186. public static function get_personal_agenda_items(
  3187. $user_id,
  3188. $agendaitems,
  3189. $day = "",
  3190. $month = "",
  3191. $year = "",
  3192. $week = "",
  3193. $type
  3194. ) {
  3195. $tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
  3196. $user_id = intval($user_id);
  3197. // 1. creating the SQL statement for getting the personal agenda items in MONTH view
  3198. if ($type == "month_view" or $type == "") {
  3199. // we are in month view
  3200. $sql = "SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' and MONTH(date)='".$month."' AND YEAR(date) = '".$year."' ORDER BY date ASC";
  3201. }
  3202. // 2. creating the SQL statement for getting the personal agenda items in WEEK view
  3203. // we are in week view
  3204. if ($type == "week_view") {
  3205. $start_end_day_of_week = self::calculate_start_end_of_week(
  3206. $week,
  3207. $year
  3208. );
  3209. $start_day = $start_end_day_of_week['start']['day'];
  3210. $start_month = $start_end_day_of_week['start']['month'];
  3211. $start_year = $start_end_day_of_week['start']['year'];
  3212. $end_day = $start_end_day_of_week['end']['day'];
  3213. $end_month = $start_end_day_of_week['end']['month'];
  3214. $end_year = $start_end_day_of_week['end']['year'];
  3215. // in sql statements you have to use year-month-day for date calculations
  3216. $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
  3217. $start_filter = api_get_utc_datetime($start_filter);
  3218. $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
  3219. $end_filter = api_get_utc_datetime($end_filter);
  3220. $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
  3221. }
  3222. // 3. creating the SQL statement for getting the personal agenda items in DAY view
  3223. if ($type == "day_view") {
  3224. // we are in day view
  3225. // we could use mysql date() function but this is only available from 4.1 and higher
  3226. $start_filter = $year."-".$month."-".$day." 00:00:00";
  3227. $start_filter = api_get_utc_datetime($start_filter);
  3228. $end_filter = $year."-".$month."-".$day." 23:59:59";
  3229. $end_filter = api_get_utc_datetime($end_filter);
  3230. $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
  3231. }
  3232. $result = Database::query($sql);
  3233. while ($item = Database::fetch_array($result, 'ASSOC')) {
  3234. $time_minute = api_convert_and_format_date(
  3235. $item['date'],
  3236. TIME_NO_SEC_FORMAT
  3237. );
  3238. $item['date'] = api_get_local_time($item['date']);
  3239. $item['start_date_tms'] = api_strtotime($item['date']);
  3240. $item['content'] = $item['text'];
  3241. // we break the date field in the database into a date and a time part
  3242. $agenda_db_date = explode(" ", $item['date']);
  3243. $date = $agenda_db_date[0];
  3244. $time = $agenda_db_date[1];
  3245. // we divide the date part into a day, a month and a year
  3246. $agendadate = explode("-", $item['date']);
  3247. $year = intval($agendadate[0]);
  3248. $month = intval($agendadate[1]);
  3249. $day = intval($agendadate[2]);
  3250. // we divide the time part into hour, minutes, seconds
  3251. $agendatime = explode(":", $time);
  3252. $hour = $agendatime[0];
  3253. $minute = $agendatime[1];
  3254. $second = $agendatime[2];
  3255. if ($type == 'month_view') {
  3256. $item['calendar_type'] = 'personal';
  3257. $item['start_date'] = $item['date'];
  3258. $agendaitems[$day][] = $item;
  3259. continue;
  3260. }
  3261. // if the student has specified a course we a add a link to that course
  3262. if ($item['course'] != "") {
  3263. $url = api_get_path(
  3264. WEB_CODE_PATH
  3265. )."calendar/agenda.php?cidReq=".urlencode(
  3266. $item['course']
  3267. )."&day=$day&month=$month&year=$year#$day"; // RH //Patrick Cool: to highlight the relevant agenda item
  3268. $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
  3269. } else {
  3270. $course_link = "";
  3271. }
  3272. // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
  3273. // if we have a day_view we use a half hour as index => key 33 = 16h30
  3274. if ($type !== "day_view") {
  3275. // This is the array construction for the WEEK or MONTH view
  3276. //Display events in agenda
  3277. $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 />";
  3278. } else {
  3279. // this is the array construction for the DAY view
  3280. $halfhour = 2 * $agendatime['0'];
  3281. if ($agendatime['1'] >= '30') {
  3282. $halfhour = $halfhour + 1;
  3283. }
  3284. //Display events by list
  3285. $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>";
  3286. }
  3287. }
  3288. return $agendaitems;
  3289. }
  3290. /**
  3291. * Show the monthcalender of the given month.
  3292. *
  3293. * @param array Agendaitems
  3294. * @param int Month number
  3295. * @param int Year number
  3296. * @param array Array of strings containing long week day names (deprecated, you can send an empty array
  3297. * instead)
  3298. * @param string The month name
  3299. */
  3300. public static function display_mymonthcalendar(
  3301. $user_id,
  3302. $agendaitems,
  3303. $month,
  3304. $year,
  3305. $weekdaynames = [],
  3306. $monthName,
  3307. $show_content = true
  3308. ) {
  3309. global $DaysShort, $course_path;
  3310. //Handle leap year
  3311. $numberofdays = [
  3312. 0,
  3313. 31,
  3314. 28,
  3315. 31,
  3316. 30,
  3317. 31,
  3318. 30,
  3319. 31,
  3320. 31,
  3321. 30,
  3322. 31,
  3323. 30,
  3324. 31,
  3325. ];
  3326. if (($year % 400 == 0) or ($year % 4 == 0 and $year % 100 != 0)) {
  3327. $numberofdays[2] = 29;
  3328. }
  3329. //Get the first day of the month
  3330. $dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
  3331. //Start the week on monday
  3332. $startdayofweek = $dayone['wday'] != 0 ? ($dayone['wday'] - 1) : 6;
  3333. $g_cc = (isset($_GET['courseCode']) ? $_GET['courseCode'] : '');
  3334. $next_month = ($month == 1 ? 12 : $month - 1);
  3335. $prev_month = ($month == 12 ? 1 : $month + 1);
  3336. $next_year = ($month == 1 ? $year - 1 : $year);
  3337. $prev_year = ($month == 12 ? $year + 1 : $year);
  3338. if ($show_content) {
  3339. $back_url = Display::url(
  3340. get_lang('Previous'),
  3341. api_get_self()."?coursePath=".urlencode(
  3342. $course_path
  3343. )."&courseCode=".Security::remove_XSS(
  3344. $g_cc
  3345. )."&action=view&view=month&month=".$next_month."&year=".$next_year
  3346. );
  3347. $next_url = Display::url(
  3348. get_lang('Next'),
  3349. api_get_self()."?coursePath=".urlencode(
  3350. $course_path
  3351. )."&courseCode=".Security::remove_XSS(
  3352. $g_cc
  3353. )."&action=view&view=month&month=".$prev_month."&year=".$prev_year
  3354. );
  3355. } else {
  3356. $back_url = Display::url(
  3357. get_lang('Previous'),
  3358. '',
  3359. [
  3360. 'onclick' => "load_calendar('".$user_id."','".$next_month."', '".$next_year."'); ",
  3361. 'class' => 'btn ui-button ui-widget ui-state-default',
  3362. ]
  3363. );
  3364. $next_url = Display::url(
  3365. get_lang('Next'),
  3366. '',
  3367. [
  3368. 'onclick' => "load_calendar('".$user_id."','".$prev_month."', '".$prev_year."'); ",
  3369. 'class' => 'pull-right btn ui-button ui-widget ui-state-default',
  3370. ]
  3371. );
  3372. }
  3373. $html = '';
  3374. $html .= '<div class="actions">';
  3375. $html .= '<div class="row">';
  3376. $html .= '<div class="col-md-4">'.$back_url.'</div>';
  3377. $html .= '<div class="col-md-4"><p class="agenda-title text-center">'.$monthName." ".$year.'</p></div>';
  3378. $html .= '<div class="col-md-4">'.$next_url.'</div>';
  3379. $html .= '</div>';
  3380. $html .= '</div>';
  3381. $html .= '<table id="agenda_list2" class="table table-bordered">';
  3382. $html .= '<tr>';
  3383. for ($ii = 1; $ii < 8; $ii++) {
  3384. $html .= '<td class="weekdays">'.$DaysShort[$ii % 7].'</td>';
  3385. }
  3386. $html .= '</tr>';
  3387. $curday = -1;
  3388. $today = getdate();
  3389. while ($curday <= $numberofdays[$month]) {
  3390. $html .= "<tr>";
  3391. for ($ii = 0; $ii < 7; $ii++) {
  3392. if (($curday == -1) && ($ii == $startdayofweek)) {
  3393. $curday = 1;
  3394. }
  3395. if (($curday > 0) && ($curday <= $numberofdays[$month])) {
  3396. $bgcolor = $class = 'class="days_week"';
  3397. $dayheader = Display::div(
  3398. $curday,
  3399. ['class' => 'agenda_day']
  3400. );
  3401. if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) {
  3402. $class = "class=\"days_today\" style=\"width:10%;\"";
  3403. }
  3404. $html .= "<td ".$class.">".$dayheader;
  3405. if (!empty($agendaitems[$curday])) {
  3406. $items = $agendaitems[$curday];
  3407. $items = msort($items, 'start_date_tms');
  3408. foreach ($items as $value) {
  3409. $value['title'] = Security::remove_XSS(
  3410. $value['title']
  3411. );
  3412. $start_time = api_format_date(
  3413. $value['start_date'],
  3414. TIME_NO_SEC_FORMAT
  3415. );
  3416. $end_time = '';
  3417. if (!empty($value['end_date'])) {
  3418. $end_time = '-&nbsp;<i>'.api_format_date(
  3419. $value['end_date'],
  3420. DATE_TIME_FORMAT_LONG
  3421. ).'</i>';
  3422. }
  3423. $complete_time = '<i>'.api_format_date(
  3424. $value['start_date'],
  3425. DATE_TIME_FORMAT_LONG
  3426. ).'</i>&nbsp;'.$end_time;
  3427. $time = '<i>'.$start_time.'</i>';
  3428. switch ($value['calendar_type']) {
  3429. case 'personal':
  3430. $bg_color = '#D0E7F4';
  3431. $icon = Display::return_icon(
  3432. 'user.png',
  3433. get_lang('MyAgenda'),
  3434. [],
  3435. ICON_SIZE_SMALL
  3436. );
  3437. break;
  3438. case 'global':
  3439. $bg_color = '#FFBC89';
  3440. $icon = Display::return_icon(
  3441. 'view_remove.png',
  3442. get_lang('GlobalEvent'),
  3443. [],
  3444. ICON_SIZE_SMALL
  3445. );
  3446. break;
  3447. case 'course':
  3448. $bg_color = '#CAFFAA';
  3449. $icon_name = 'course.png';
  3450. if (!empty($value['session_id'])) {
  3451. $icon_name = 'session.png';
  3452. }
  3453. if ($show_content) {
  3454. $icon = Display::url(
  3455. Display::return_icon(
  3456. $icon_name,
  3457. $value['course_name'].' '.get_lang(
  3458. 'Course'
  3459. ),
  3460. [],
  3461. ICON_SIZE_SMALL
  3462. ),
  3463. $value['url']
  3464. );
  3465. } else {
  3466. $icon = Display::return_icon(
  3467. $icon_name,
  3468. $value['course_name'].' '.get_lang(
  3469. 'Course'
  3470. ),
  3471. [],
  3472. ICON_SIZE_SMALL
  3473. );
  3474. }
  3475. break;
  3476. default:
  3477. break;
  3478. }
  3479. $result = '<div class="rounded_div_agenda" style="background-color:'.$bg_color.';">';
  3480. if ($show_content) {
  3481. //Setting a personal event to green
  3482. $icon = Display::div(
  3483. $icon,
  3484. ['style' => 'float:right']
  3485. );
  3486. $link = $value['calendar_type'].'_'.$value['id'].'_'.$value['course_id'].'_'.$value['session_id'];
  3487. //Link to bubble
  3488. $url = Display::url(
  3489. cut($value['title'], 40),
  3490. '#',
  3491. ['id' => $link, 'class' => 'opener']
  3492. );
  3493. $result .= $time.' '.$icon.' '.Display::div(
  3494. $url
  3495. );
  3496. //Hidden content
  3497. $content = Display::div(
  3498. $icon.Display::tag(
  3499. 'h2',
  3500. $value['course_name']
  3501. ).'<hr />'.Display::tag(
  3502. 'h3',
  3503. $value['title']
  3504. ).$complete_time.'<hr />'.Security::remove_XSS(
  3505. $value['content']
  3506. )
  3507. );
  3508. //Main div
  3509. $result .= Display::div(
  3510. $content,
  3511. [
  3512. 'id' => 'main_'.$link,
  3513. 'class' => 'dialog',
  3514. 'style' => 'display:none',
  3515. ]
  3516. );
  3517. $result .= '</div>';
  3518. $html .= $result;
  3519. } else {
  3520. $html .= $result .= $icon.'</div>';
  3521. }
  3522. }
  3523. }
  3524. $html .= "</td>";
  3525. $curday++;
  3526. } else {
  3527. $html .= "<td></td>";
  3528. }
  3529. }
  3530. $html .= "</tr>";
  3531. }
  3532. $html .= "</table>";
  3533. echo $html;
  3534. }
  3535. /**
  3536. * Get personal agenda items between two dates (=all events from all registered courses).
  3537. *
  3538. * @param int $user_id user ID of the user
  3539. * @param string Optional start date in datetime format (if no start date is given, uses today)
  3540. * @param string Optional end date in datetime format (if no date is given, uses one year from now)
  3541. *
  3542. * @return array array of events ordered by start date, in
  3543. * [0]('datestart','dateend','title'),[1]('datestart','dateend','title','link','coursetitle') format,
  3544. * where datestart and dateend are in yyyyMMddhhmmss format
  3545. *
  3546. * @deprecated use agenda events
  3547. */
  3548. public static function get_personal_agenda_items_between_dates(
  3549. $user_id,
  3550. $date_start = '',
  3551. $date_end = ''
  3552. ) {
  3553. $items = [];
  3554. if ($user_id != strval(intval($user_id))) {
  3555. return $items;
  3556. }
  3557. if (empty($date_start)) {
  3558. $date_start = date('Y-m-d H:i:s');
  3559. }
  3560. if (empty($date_end)) {
  3561. $date_end = date(
  3562. 'Y-m-d H:i:s',
  3563. mktime(0, 0, 0, date("m"), date("d"), date("Y") + 1)
  3564. );
  3565. }
  3566. $expr = '/\d{4}-\d{2}-\d{2}\ \d{2}:\d{2}:\d{2}/';
  3567. if (!preg_match($expr, $date_start)) {
  3568. return $items;
  3569. }
  3570. if (!preg_match($expr, $date_end)) {
  3571. return $items;
  3572. }
  3573. // get agenda-items for every course
  3574. $courses = api_get_user_courses($user_id, false);
  3575. foreach ($courses as $id => $course) {
  3576. $c = api_get_course_info_by_id($course['real_id']);
  3577. //databases of the courses
  3578. $t_a = Database::get_course_table(TABLE_AGENDA, $course['db']);
  3579. $t_ip = Database::get_course_table(
  3580. TABLE_ITEM_PROPERTY,
  3581. $course['db']
  3582. );
  3583. // get the groups to which the user belong
  3584. $group_memberships = GroupManager:: get_group_ids(
  3585. $course['db'],
  3586. $user_id
  3587. );
  3588. // if the user is administrator of that course we show all the agenda items
  3589. if ($course['status'] == '1') {
  3590. //echo "course admin";
  3591. $sqlquery = "SELECT ".
  3592. " DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
  3593. " FROM ".$t_a." agenda, ".
  3594. $t_ip." ip ".
  3595. " WHERE agenda.id = ip.ref ".
  3596. " AND agenda.start_date>='$date_start' ".
  3597. " AND agenda.end_date<='$date_end' ".
  3598. " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
  3599. " AND ip.visibility='1' ".
  3600. " GROUP BY agenda.id ".
  3601. " ORDER BY start_date ";
  3602. } else {
  3603. // if the user is not an administrator of that course, then...
  3604. if (is_array($group_memberships) && count(
  3605. $group_memberships
  3606. ) > 0
  3607. ) {
  3608. $sqlquery = "SELECT ".
  3609. "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
  3610. " FROM ".$t_a." agenda, ".
  3611. $t_ip." ip ".
  3612. " WHERE agenda.id = ip.ref ".
  3613. " AND agenda.start_date>='$date_start' ".
  3614. " AND agenda.end_date<='$date_end' ".
  3615. " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
  3616. " AND ( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(
  3617. ", ",
  3618. $group_memberships
  3619. ).")) ) ".
  3620. " AND ip.visibility='1' ".
  3621. " ORDER BY start_date ";
  3622. } else {
  3623. $sqlquery = "SELECT ".
  3624. "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
  3625. " FROM ".$t_a." agenda, ".
  3626. $t_ip." ip ".
  3627. " WHERE agenda.id = ip.ref ".
  3628. " AND agenda.start_date>='$date_start' ".
  3629. " AND agenda.end_date<='$date_end' ".
  3630. " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
  3631. " AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ".
  3632. " AND ip.visibility='1' ".
  3633. " ORDER BY start_date ";
  3634. }
  3635. }
  3636. $result = Database::query($sqlquery);
  3637. while ($item = Database::fetch_array($result)) {
  3638. $agendaday = date("j", strtotime($item['start_date']));
  3639. $month = date("n", strtotime($item['start_date']));
  3640. $year = date("Y", strtotime($item['start_date']));
  3641. $URL = api_get_path(
  3642. WEB_PATH
  3643. )."main/calendar/agenda.php?cidReq=".urlencode(
  3644. $course["code"]
  3645. )."&day=$agendaday&month=$month&year=$year#$agendaday";
  3646. list($year, $month, $day, $hour, $min, $sec) = explode(
  3647. '[-: ]',
  3648. $item['start_date']
  3649. );
  3650. $start_date = $year.$month.$day.$hour.$min;
  3651. list($year, $month, $day, $hour, $min, $sec) = explode(
  3652. '[-: ]',
  3653. $item['end_date']
  3654. );
  3655. $end_date = $year.$month.$day.$hour.$min;
  3656. $items[] = [
  3657. 'datestart' => $start_date,
  3658. 'dateend' => $end_date,
  3659. 'title' => $item['title'],
  3660. 'link' => $URL,
  3661. 'coursetitle' => $c['name'],
  3662. ];
  3663. }
  3664. }
  3665. return $items;
  3666. }
  3667. /**
  3668. * This function calculates the startdate of the week (monday)
  3669. * and the enddate of the week (sunday)
  3670. * and returns it as an array.
  3671. */
  3672. public static function calculate_start_end_of_week($week_number, $year)
  3673. {
  3674. // determine the start and end date
  3675. // step 1: we calculate a timestamp for a day in this week
  3676. $random_day_in_week = mktime(
  3677. 0,
  3678. 0,
  3679. 0,
  3680. 1,
  3681. 1,
  3682. $year
  3683. ) + ($week_number) * (7 * 24 * 60 * 60); // we calculate a random day in this week
  3684. // step 2: we which day this is (0=sunday, 1=monday, ...)
  3685. $number_day_in_week = date('w', $random_day_in_week);
  3686. // step 3: we calculate the timestamp of the monday of the week we are in
  3687. $start_timestamp = $random_day_in_week - (($number_day_in_week - 1) * 24 * 60 * 60);
  3688. // step 4: we calculate the timestamp of the sunday of the week we are in
  3689. $end_timestamp = $random_day_in_week + ((7 - $number_day_in_week + 1) * 24 * 60 * 60) - 3600;
  3690. // step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
  3691. $start_day = date('j', $start_timestamp);
  3692. $start_month = date('n', $start_timestamp);
  3693. $start_year = date('Y', $start_timestamp);
  3694. $end_day = date('j', $end_timestamp);
  3695. $end_month = date('n', $end_timestamp);
  3696. $end_year = date('Y', $end_timestamp);
  3697. $start_end_array['start']['day'] = $start_day;
  3698. $start_end_array['start']['month'] = $start_month;
  3699. $start_end_array['start']['year'] = $start_year;
  3700. $start_end_array['end']['day'] = $end_day;
  3701. $start_end_array['end']['month'] = $end_month;
  3702. $start_end_array['end']['year'] = $end_year;
  3703. return $start_end_array;
  3704. }
  3705. /**
  3706. * @return bool
  3707. */
  3708. public function getIsAllowedToEdit()
  3709. {
  3710. return $this->isAllowedToEdit;
  3711. }
  3712. /**
  3713. * @param bool $isAllowedToEdit
  3714. */
  3715. public function setIsAllowedToEdit($isAllowedToEdit)
  3716. {
  3717. $this->isAllowedToEdit = $isAllowedToEdit;
  3718. }
  3719. /**
  3720. * Format needed for the Fullcalendar js lib.
  3721. *
  3722. * @param string $utcTime
  3723. *
  3724. * @return bool|string
  3725. */
  3726. public function formatEventDate($utcTime)
  3727. {
  3728. $utcTimeZone = new DateTimeZone('UTC');
  3729. $platformTimeZone = new DateTimeZone(api_get_timezone());
  3730. $eventDate = new DateTime($utcTime, $utcTimeZone);
  3731. $eventDate->setTimezone($platformTimeZone);
  3732. return $eventDate->format(DateTime::ISO8601);
  3733. }
  3734. }