agenda.lib.php 131 KB

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