agenda.lib.php 134 KB

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