agenda.lib.php 136 KB

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