agenda.lib.php 121 KB

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