agenda.lib.php 130 KB

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