agenda.lib.php 134 KB

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