12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374 |
- <?php
- /* For licensing terms, see /license.txt */
- /**
- * Class Agenda
- *
- * @author: Julio Montoya <gugli100@gmail.com>
- */
- class Agenda
- {
- public $events = array();
- /** @var string Current type */
- public $type = 'personal';
- public $types = array('personal', 'admin', 'course');
- public $sessionId = 0;
- public $senderId;
- /** @var array */
- public $course;
- public $comment;
- private $isAllowedToEdit;
- /**
- * Constructor
- */
- public function __construct()
- {
- //Table definitions
- $this->tbl_global_agenda = Database::get_main_table(TABLE_MAIN_SYSTEM_CALENDAR);
- $this->tbl_personal_agenda = Database::get_main_table(TABLE_PERSONAL_AGENDA);
- $this->tbl_course_agenda = Database::get_course_table(TABLE_AGENDA);
- $this->table_repeat = Database::get_course_table(TABLE_AGENDA_REPEAT);
- //Setting the course object if we are in a course
- $this->course = null;
- $courseInfo = api_get_course_info();
- if (!empty($courseInfo)) {
- $this->course = $courseInfo;
- }
- $this->setSessionId(api_get_session_id());
- $this->setSenderId(api_get_user_id());
- $this->setIsAllowedToEdit(api_is_allowed_to_edit(null, true));
- $this->events = array();
- // Event colors
- $this->event_platform_color = 'red'; //red
- $this->event_course_color = '#458B00'; //green
- $this->event_group_color = '#A0522D'; //siena
- $this->event_session_color = '#00496D'; // kind of green
- $this->eventOtherSessionColor = '#999';
- $this->event_personal_color = 'steel blue'; //steel blue
- }
- /**
- * @param int $senderId
- */
- public function setSenderId($senderId)
- {
- $this->senderId = intval($senderId);
- }
- /**
- * @return int
- */
- public function getSenderId()
- {
- return $this->senderId;
- }
- /**
- * @param string $type can be 'personal', 'admin' or 'course'
- */
- public function setType($type)
- {
- $typeList = $this->getTypes();
- if (in_array($type, $typeList)) {
- $this->type = $type;
- }
- }
- /**
- * @param int $id
- */
- public function setSessionId($id)
- {
- $this->sessionId = intval($id);
- }
- /**
- * @return int $id
- */
- public function getSessionId()
- {
- return $this->sessionId;
- }
- /**
- * @param array $courseInfo
- */
- public function set_course($courseInfo)
- {
- $this->course = $courseInfo;
- }
- /**
- * @return array
- */
- public function getTypes()
- {
- return $this->types;
- }
- /**
- * Adds an event to the calendar
- * @param string $start datetime format: 2012-06-14 09:00:00
- * @param string $end datetime format: 2012-06-14 09:00:00
- * @param string $allDay (true, false)
- * @param string $title
- * @param string $content
- * @param array $usersToSend array('everyone') or a list of user/group ids
- * @param bool $addAsAnnouncement event as a *course* announcement
- * @param int $parentEventId
- * @param array $attachmentArray $_FILES['']
- * @param string $attachmentComment
- * @param string $eventComment
- * @param string $color
- *
- * @return int
- */
- public function addEvent(
- $start,
- $end,
- $allDay,
- $title,
- $content,
- $usersToSend = array(),
- $addAsAnnouncement = false,
- $parentEventId = null,
- $attachmentArray = array(),
- $attachmentComment = '',
- $eventComment = '',
- $color = ''
- ) {
- $start = api_get_utc_datetime($start);
- $end = api_get_utc_datetime($end);
- $allDay = isset($allDay) && $allDay == 'true' ? 1 : 0;
- $id = null;
- $content = Security::remove_XSS($content);
- $eventComment = nl2br($eventComment);
- switch ($this->type) {
- case 'personal':
- $attributes = array(
- 'user' => api_get_user_id(),
- 'title' => $title,
- 'text' => $content,
- 'date' => $start,
- 'enddate' => $end,
- 'all_day' => $allDay
- );
- if ($this->allowEventColoring) {
- $attributes['color'] = $color;
- }
- $id = Database::insert(
- $this->tbl_personal_agenda,
- $attributes
- );
- break;
- case 'course':
- $attributes = array(
- 'title' => $title,
- 'content' => $content,
- 'start_date' => $start,
- 'end_date' => $end,
- 'all_day' => $allDay,
- 'session_id' => $this->getSessionId(),
- 'c_id' => $this->course['real_id'],
- 'comment' => $eventComment,
- 'color' => $color
- );
- if (!empty($parentEventId)) {
- $attributes['parent_event_id'] = $parentEventId;
- }
- $senderId = $this->getSenderId();
- $sessionId = $this->getSessionId();
- // Simple course event.
- $id = Database::insert($this->tbl_course_agenda, $attributes);
- if ($id) {
- $sql = "UPDATE ".$this->tbl_course_agenda." SET id = iid WHERE iid = $id";
- Database::query($sql);
- $groupId = api_get_group_id();
- if (!empty($usersToSend)) {
- $sendTo = $this->parseSendToArray($usersToSend);
- if ($sendTo['everyone']) {
- api_item_property_update(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- "AgendaAdded",
- $senderId,
- $groupId,
- '',
- $start,
- $end,
- $sessionId
- );
- api_item_property_update(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- "visible",
- $senderId,
- $groupId,
- '',
- $start,
- $end,
- $sessionId
- );
- } else {
- // Storing the selected groups
- if (!empty($sendTo['groups'])) {
- foreach ($sendTo['groups'] as $group) {
- api_item_property_update(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- "AgendaAdded",
- $senderId,
- $group,
- 0,
- $start,
- $end,
- $sessionId
- );
- api_item_property_update(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- "visible",
- $senderId,
- $group,
- 0,
- $start,
- $end,
- $sessionId
- );
- }
- }
- // storing the selected users
- if (!empty($sendTo['users'])) {
- foreach ($sendTo['users'] as $userId) {
- api_item_property_update(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- "AgendaAdded",
- $senderId,
- $groupId,
- $userId,
- $start,
- $end,
- $sessionId
- );
- api_item_property_update(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- "visible",
- $senderId,
- $groupId,
- $userId,
- $start,
- $end,
- $sessionId
- );
- }
- }
- }
- }
- // Add announcement.
- if ($addAsAnnouncement) {
- $this->store_agenda_item_as_announcement($id, $usersToSend);
- }
- // Add attachment.
- if (isset($attachmentArray) && !empty($attachmentArray)) {
- $this->addAttachment(
- $id,
- $attachmentArray,
- $attachmentComment,
- $this->course
- );
- }
- }
- break;
- case 'admin':
- if (api_is_platform_admin()) {
- $attributes = array(
- 'title' => $title,
- 'content' => $content,
- 'start_date' => $start,
- 'end_date' => $end,
- 'all_day' => $allDay,
- 'access_url_id' => api_get_current_access_url_id()
- );
- $id = Database::insert($this->tbl_global_agenda, $attributes);
- }
- break;
- }
- return $id;
- }
- /**
- * @param int $eventId
- * @param int $courseId
- *
- * @return array
- */
- public function getRepeatedInfoByEvent($eventId, $courseId)
- {
- $repeatTable = Database::get_course_table(TABLE_AGENDA_REPEAT);
- $eventId = intval($eventId);
- $courseId = intval($courseId);
- $sql = "SELECT * FROM $repeatTable
- WHERE c_id = $courseId AND cal_id = $eventId";
- $res = Database::query($sql);
- $repeatInfo = array();
- if (Database::num_rows($res) > 0) {
- $repeatInfo = Database::fetch_array($res, 'ASSOC');
- }
- return $repeatInfo;
- }
- /**
- * @param int $eventId
- * @param string $type
- * @param string $end in local time
- * @param array $sentTo
- *
- * @return bool
- */
- public function addRepeatedItem($eventId, $type, $end, $sentTo = array())
- {
- $t_agenda = Database::get_course_table(TABLE_AGENDA);
- $t_agenda_r = Database::get_course_table(TABLE_AGENDA_REPEAT);
- if (empty($this->course)) {
- return false;
- }
- $course_id = $this->course['real_id'];
- $eventId = intval($eventId);
- $sql = "SELECT title, content, start_date, end_date, all_day
- FROM $t_agenda
- WHERE c_id = $course_id AND id = $eventId";
- $res = Database::query($sql);
- if (Database::num_rows($res) !== 1) {
- return false;
- }
- $row = Database::fetch_array($res);
- $origStartDate = api_strtotime($row['start_date'], 'UTC');
- $origEndDate = api_strtotime($row['end_date'], 'UTC');
- $diff = $origEndDate - $origStartDate;
- $title = $row['title'];
- $content = $row['content'];
- $allDay = $row['all_day'];
- $now = time();
- $type = Database::escape_string($type);
- $end = api_strtotime($end);
- if (1 <= $end && $end <= 500) {
- // We assume that, with this type of value, the user actually gives a count of repetitions
- //and that he wants us to calculate the end date with that (particularly in case of imports from ical)
- switch ($type) {
- case 'daily':
- $end = $origStartDate + (86400 * $end);
- break;
- case 'weekly':
- $end = $this->addWeek($origStartDate, $end);
- break;
- case 'monthlyByDate':
- $end = $this->addMonth($origStartDate, $end);
- break;
- case 'monthlyByDay':
- //TODO
- break;
- case 'monthlyByDayR':
- //TODO
- break;
- case 'yearly':
- $end = $this->addYear($origStartDate, $end);
- break;
- }
- }
- $typeList = array('daily', 'weekly', 'monthlyByDate', 'monthlyByDay', 'monthlyByDayR', 'yearly');
- // The event has to repeat *in the future*. We don't allow repeated
- // events in the past
- if ($end > $now && in_array($type, $typeList)) {
- $sql = "INSERT INTO $t_agenda_r (c_id, cal_id, cal_type, cal_end)
- VALUES ($course_id, '$eventId', '$type', '$end')";
- Database::query($sql);
- switch ($type) {
- // @todo improve loop.
- case 'daily':
- for ($i = $origStartDate + 86400; $i <= $end; $i += 86400) {
- $start = date('Y-m-d H:i:s', $i);
- $repeatEnd = date('Y-m-d H:i:s', $i + $diff);
- $this->addEvent(
- $start,
- $repeatEnd,
- $allDay,
- $title,
- $content,
- $sentTo,
- false,
- $eventId
- );
- }
- break;
- case 'weekly':
- for ($i = $origStartDate + 604800; $i <= $end; $i += 604800) {
- $start = date('Y-m-d H:i:s', $i);
- $repeatEnd = date('Y-m-d H:i:s', $i + $diff);
- $this->addEvent(
- $start,
- $repeatEnd,
- $allDay,
- $title,
- $content,
- $sentTo,
- false,
- $eventId
- );
- }
- break;
- case 'monthlyByDate':
- $next_start = $this->addMonth($origStartDate);
- while ($next_start <= $end) {
- $start = date('Y-m-d H:i:s', $next_start);
- $repeatEnd = date('Y-m-d H:i:s', $next_start + $diff);
- $this->addEvent(
- $start,
- $repeatEnd,
- $allDay,
- $title,
- $content,
- $sentTo,
- false,
- $eventId
- );
- $next_start = $this->addMonth($next_start);
- }
- break;
- case 'monthlyByDay':
- //not yet implemented
- break;
- case 'monthlyByDayR':
- //not yet implemented
- break;
- case 'yearly':
- $next_start = $this->addYear($origStartDate);
- while ($next_start <= $end) {
- $start = date('Y-m-d H:i:s', $next_start);
- $repeatEnd = date('Y-m-d H:i:s', $next_start + $diff);
- $this->addEvent(
- $start,
- $repeatEnd,
- $allDay,
- $title,
- $content,
- $sentTo,
- false,
- $eventId
- );
- $next_start = $this->addYear($next_start);
- }
- break;
- }
- }
- return true;
- }
- /**
- * @param int $item_id
- * @param array $sentTo
- * @return int
- */
- public function store_agenda_item_as_announcement($item_id, $sentTo = array())
- {
- $table_agenda = Database::get_course_table(TABLE_AGENDA);
- $course_id = api_get_course_int_id();
- // Check params
- if (empty($item_id) or $item_id != strval(intval($item_id))) {
- return -1;
- }
- // Get the agenda item.
- $item_id = intval($item_id);
- $sql = "SELECT * FROM $table_agenda WHERE c_id = $course_id AND id = ".$item_id;
- $res = Database::query($sql);
- if (Database::num_rows($res) > 0) {
- $row = Database::fetch_array($res, 'ASSOC');
- // Sending announcement
- if (!empty($sentTo)) {
- $id = AnnouncementManager::add_announcement(
- $row['title'],
- $row['content'],
- $sentTo,
- null,
- null,
- $row['end_date']
- );
- AnnouncementManager::send_email($id);
- }
- return $id;
- }
- return -1;
- }
- /**
- * Edits an event
- *
- * @param int $id
- * @param string $start datetime format: 2012-06-14 09:00:00
- * @param string $end datetime format: 2012-06-14 09:00:00
- * @param int $allDay is all day 'true' or 'false'
- * @param string $title
- * @param string $content
- * @param array $usersToSend
- * @param int $editRepeatType
- * @param array $attachmentArray
- * @param string $attachmentComment
- * @param string $comment
- * @param string $color
- *
- * @return bool
- */
- public function editEvent(
- $id,
- $start,
- $end,
- $allDay,
- $title,
- $content,
- $usersToSend = array(),
- $attachmentArray = array(),
- $attachmentComment = '',
- $comment = '',
- $color = ''
- ) {
- $start = api_get_utc_datetime($start);
- $end = api_get_utc_datetime($end);
- $allDay = isset($allDay) && $allDay == 'true' ? 1 : 0;
- $content = nl2br($content);
- $comment = nl2br($comment);
- switch ($this->type) {
- case 'personal':
- $eventInfo = $this->get_event($id);
- if ($eventInfo['user'] != api_get_user_id()) {
- break;
- }
- $attributes = array(
- 'title' => $title,
- 'text' => $content,
- 'date' => $start,
- 'enddate' => $end,
- 'all_day' => $allDay,
- 'color' => $color
- );
- Database::update(
- $this->tbl_personal_agenda,
- $attributes,
- array('id = ?' => $id)
- );
- break;
- case 'course':
- $eventInfo = $this->get_event($id);
- if (empty($eventInfo)) {
- return false;
- }
- $groupId = api_get_group_id();
- $course_id = $this->course['real_id'];
- if (empty($course_id)) {
- return false;
- }
- if ($this->getIsAllowedToEdit()) {
- $attributes = array(
- 'title' => $title,
- 'content' => $content,
- 'start_date' => $start,
- 'end_date' => $end,
- 'all_day' => $allDay,
- 'comment' => $comment,
- 'color' => $color
- );
- Database::update(
- $this->tbl_course_agenda,
- $attributes,
- array(
- 'id = ? AND c_id = ? AND session_id = ? ' => array(
- $id,
- $course_id,
- $this->sessionId
- )
- )
- );
- if (!empty($usersToSend)) {
- $sendTo = $this->parseSendToArray($usersToSend);
- $usersToDelete = array_diff($eventInfo['send_to']['users'], $sendTo['users']);
- $usersToAdd = array_diff($sendTo['users'], $eventInfo['send_to']['users']);
- $groupsToDelete = array_diff($eventInfo['send_to']['groups'], $sendTo['groups']);
- $groupToAdd = array_diff($sendTo['groups'], $eventInfo['send_to']['groups']);
- if ($sendTo['everyone']) {
- // Delete all from group
- if (isset($eventInfo['send_to']['groups']) &&
- !empty($eventInfo['send_to']['groups'])
- ) {
- foreach ($eventInfo['send_to']['groups'] as $group) {
- api_item_property_delete(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- 0,
- $group,
- $this->sessionId
- );
- }
- }
- // Storing the selected users.
- if (isset($eventInfo['send_to']['users']) &&
- !empty($eventInfo['send_to']['users'])
- ) {
- foreach ($eventInfo['send_to']['users'] as $userId) {
- api_item_property_delete(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- $userId,
- $groupId,
- $this->sessionId
- );
- }
- }
- // Add to everyone only.
- api_item_property_update(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- "visible",
- api_get_user_id(),
- $groupId,
- null,
- $start,
- $end,
- $this->sessionId
- );
- } else {
- // Delete "everyone".
- api_item_property_delete(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- 0,
- 0,
- $this->sessionId
- );
- // Add groups
- if (!empty($groupToAdd)) {
- foreach ($groupToAdd as $group) {
- api_item_property_update(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- "visible",
- api_get_user_id(),
- $group,
- 0,
- $start,
- $end,
- $this->sessionId
- );
- }
- }
- // Delete groups.
- if (!empty($groupsToDelete)) {
- foreach ($groupsToDelete as $group) {
- api_item_property_delete(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- 0,
- $group,
- $this->sessionId
- );
- }
- }
- // Add users.
- if (!empty($usersToAdd)) {
- foreach ($usersToAdd as $userId) {
- api_item_property_update(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- "visible",
- api_get_user_id(),
- $groupId,
- $userId,
- $start,
- $end,
- $this->sessionId
- );
- }
- }
- // Delete users.
- if (!empty($usersToDelete)) {
- foreach ($usersToDelete as $userId) {
- api_item_property_delete(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- $userId,
- $groupId,
- $this->sessionId
- );
- }
- }
- }
- }
- // Add announcement.
- /*if (isset($addAsAnnouncement) && !empty($addAsAnnouncement)) {
- $this->store_agenda_item_as_announcement($id);
- }*/
- // Add attachment.
- if (isset($attachmentArray) && !empty($attachmentArray)) {
- $this->updateAttachment(
- $id,
- $attachmentArray,
- $attachmentComment,
- $this->course
- );
- }
- }
- break;
- case 'admin':
- case 'platform':
- if (api_is_platform_admin()) {
- $attributes = array(
- 'title' => $title,
- 'content' => $content,
- 'start_date' => $start,
- 'end_date' => $end,
- 'all_day' => $allDay
- );
- Database::update(
- $this->tbl_global_agenda,
- $attributes,
- array('id = ?' => $id)
- );
- }
- break;
- }
- }
- /**
- * @param int $id
- * @param bool $deleteAllItemsFromSerie
- */
- public function delete_event($id, $deleteAllItemsFromSerie = false)
- {
- switch ($this->type) {
- case 'personal':
- $eventInfo = $this->get_event($id);
- if ($eventInfo['user'] == api_get_user_id()) {
- Database::delete(
- $this->tbl_personal_agenda,
- array('id = ?' => $id)
- );
- }
- break;
- case 'course':
- $course_id = api_get_course_int_id();
- if (!empty($course_id) && api_is_allowed_to_edit(null, true)) {
- // Delete
- if ($deleteAllItemsFromSerie) {
- $eventInfo = $this->get_event($id);
- /* This is one of the children.
- Getting siblings and delete 'Em all + the father! */
- if (isset($eventInfo['parent_event_id']) && !empty($eventInfo['parent_event_id'])) {
- // Removing items.
- $events = $this->getAllRepeatEvents($eventInfo['parent_event_id']);
- if (!empty($events)) {
- foreach ($events as $event) {
- $this->delete_event($event['id']);
- }
- }
- // Removing parent.
- $this->delete_event($eventInfo['parent_event_id']);
- } else {
- // This is the father looking for the children.
- $events = $this->getAllRepeatEvents($id);
- if (!empty($events)) {
- foreach ($events as $event) {
- $this->delete_event($event['id']);
- }
- }
- }
- }
- // Removing from events.
- Database::delete(
- $this->tbl_course_agenda,
- array('id = ? AND c_id = ?' => array($id, $course_id))
- );
- api_item_property_update(
- $this->course,
- TOOL_CALENDAR_EVENT,
- $id,
- 'delete',
- api_get_user_id()
- );
- // Removing from series.
- Database::delete(
- $this->table_repeat,
- array('cal_id = ? AND c_id = ?' => array($id, $course_id))
- );
- }
- break;
- case 'admin':
- if (api_is_platform_admin()) {
- Database::delete(
- $this->tbl_global_agenda,
- array('id = ?' => $id)
- );
- }
- break;
- }
- }
- /**
- * Get agenda events
- * @param int $start
- * @param int $end
- * @param int $course_id
- * @param int $groupId
- * @param int $user_id
- * @param string $format
- *
- * @return array|string
- */
- public function getEvents(
- $start,
- $end,
- $course_id = null,
- $groupId = null,
- $user_id = 0,
- $format = 'json'
- ) {
- switch ($this->type) {
- case 'admin':
- $this->getPlatformEvents($start, $end);
- break;
- case 'course':
- $session_id = $this->sessionId;
- $courseInfo = api_get_course_info_by_id($course_id);
- // Session coach can see all events inside a session.
- if (api_is_coach()) {
- // Own course
- $this->getCourseEvents(
- $start,
- $end,
- $courseInfo,
- $groupId,
- $session_id,
- $user_id
- );
- // Others
- $this->getSessionEvents(
- $start,
- $end,
- api_get_session_id(),
- $user_id,
- $this->eventOtherSessionColor
- );
- } else {
- $this->getCourseEvents(
- $start,
- $end,
- $courseInfo,
- $groupId,
- $session_id,
- $user_id
- );
- }
- break;
- case 'personal':
- default:
- $sessionFilterActive = false;
- if (!empty($this->sessionId)) {
- $sessionFilterActive = true;
- }
- if ($sessionFilterActive == false) {
- // Getting personal events
- $this->getPersonalEvents($start, $end);
- // Getting platform/admin events
- $this->getPlatformEvents($start, $end);
- }
- // Getting course events
- $my_course_list = array();
- if (!api_is_anonymous()) {
- $session_list = SessionManager::get_sessions_by_user(
- api_get_user_id()
- );
- $my_course_list = CourseManager::get_courses_list_by_user_id(
- api_get_user_id(),
- true
- );
- }
- if (api_is_drh()) {
- if (api_drh_can_access_all_session_content()) {
- $session_list = array();
- $sessionList = SessionManager::get_sessions_followed_by_drh(
- api_get_user_id(),
- null,
- null,
- null,
- true,
- false
- );
- if (!empty($sessionList)) {
- foreach ($sessionList as $sessionItem) {
- $sessionId = $sessionItem['id'];
- $courses = SessionManager::get_course_list_by_session_id(
- $sessionId
- );
- $sessionInfo = array(
- 'session_id' => $sessionId,
- 'courses' => $courses
- );
- $session_list[] = $sessionInfo;
- }
- }
- }
- }
- if (!empty($session_list)) {
- foreach ($session_list as $session_item) {
- if ($sessionFilterActive) {
- if ($this->sessionId != $session_item['session_id']) {
- continue;
- }
- }
- $my_courses = $session_item['courses'];
- $my_session_id = $session_item['session_id'];
- if (!empty($my_courses)) {
- foreach ($my_courses as $course_item) {
- $courseInfo = api_get_course_info_by_id($course_item['real_id']);
- $this->getCourseEvents(
- $start,
- $end,
- $courseInfo,
- 0,
- $my_session_id
- );
- }
- }
- $this->getSessionEvents(
- $start,
- $end,
- $my_session_id,
- api_get_user_id(),
- $this->eventOtherSessionColor
- );
- }
- }
- if (!empty($my_course_list) && $sessionFilterActive == false) {
- foreach ($my_course_list as $courseInfoItem) {
- $courseInfo = api_get_course_info_by_id($courseInfoItem['real_id']);
- if (isset($course_id) && !empty($course_id)) {
- if ($courseInfo['real_id'] == $course_id) {
- $this->getCourseEvents($start, $end, $courseInfo);
- }
- } else {
- $this->getCourseEvents(
- $start,
- $end,
- $courseInfo
- );
- }
- }
- }
- break;
- }
- if (!empty($this->events)) {
- switch ($format) {
- case 'json':
- return json_encode($this->events);
- break;
- case 'array':
- return $this->events;
- break;
- }
- }
- return '';
- }
- /**
- * @param int $id
- * @param int $day_delta
- * @param int $minute_delta
- * @return int
- */
- public function resize_event($id, $day_delta, $minute_delta)
- {
- // we convert the hour delta into minutes and add the minute delta
- $delta = ($day_delta * 60 * 24) + $minute_delta;
- $delta = intval($delta);
- $event = $this->get_event($id);
- if (!empty($event)) {
- switch ($this->type) {
- case 'personal':
- $sql = "UPDATE $this->tbl_personal_agenda SET all_day = 0, enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
- WHERE id=".intval($id);
- Database::query($sql);
- break;
- case 'course':
- $sql = "UPDATE $this->tbl_course_agenda SET all_day = 0, end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
- WHERE c_id = ".$this->course['real_id']." AND id=".intval($id);
- Database::query($sql);
- break;
- case 'admin':
- $sql = "UPDATE $this->tbl_global_agenda SET all_day = 0, end_date = DATE_ADD(end_date, INTERVAL $delta MINUTE)
- WHERE id=".intval($id);
- Database::query($sql);
- break;
- }
- }
- return 1;
- }
- /**
- * @param $id
- * @param $day_delta
- * @param $minute_delta
- * @return int
- */
- public function move_event($id, $day_delta, $minute_delta)
- {
- // we convert the hour delta into minutes and add the minute delta
- $delta = ($day_delta * 60 * 24) + $minute_delta;
- $delta = intval($delta);
- $event = $this->get_event($id);
- $allDay = 0;
- if ($day_delta == 0 && $minute_delta == 0) {
- $allDay = 1;
- }
- if (!empty($event)) {
- switch ($this->type) {
- case 'personal':
- $sql = "UPDATE $this->tbl_personal_agenda SET all_day = $allDay, date = DATE_ADD(date, INTERVAL $delta MINUTE), enddate = DATE_ADD(enddate, INTERVAL $delta MINUTE)
- WHERE id=".intval($id);
- $result = Database::query($sql);
- break;
- case 'course':
- $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)
- WHERE c_id = ".$this->course['real_id']." AND id=".intval($id);
- $result = Database::query($sql);
- break;
- case 'admin':
- $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)
- WHERE id=".intval($id);
- $result = Database::query($sql);
- break;
- }
- }
- return 1;
- }
- /**
- * Gets a single event
- *
- * @param int event id
- * @return array
- */
- public function get_event($id)
- {
- // make sure events of the personal agenda can only be seen by the user himself
- $id = intval($id);
- $event = null;
- switch ($this->type) {
- case 'personal':
- $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
- WHERE id = $id AND user = ".api_get_user_id();
- $result = Database::query($sql);
- if (Database::num_rows($result)) {
- $event = Database::fetch_array($result, 'ASSOC');
- $event['description'] = $event['text'];
- $event['content'] = $event['text'];
- $event['start_date'] = $event['date'];
- $event['end_date'] = $event['enddate'];
- }
- break;
- case 'course':
- if (!empty($this->course['real_id'])) {
- $sql = "SELECT * FROM ".$this->tbl_course_agenda."
- WHERE c_id = ".$this->course['real_id']." AND id = ".$id;
- $result = Database::query($sql);
- if (Database::num_rows($result)) {
- $event = Database::fetch_array($result, 'ASSOC');
- $event['description'] = $event['content'];
- // Getting send to array
- $event['send_to'] = $this->getUsersAndGroupSubscribedToEvent(
- $id,
- $this->course['real_id'],
- $this->sessionId
- );
- // Getting repeat info
- $event['repeat_info'] = $this->getRepeatedInfoByEvent(
- $id,
- $this->course['real_id']
- );
- if (!empty($event['parent_event_id'])) {
- $event['parent_info'] = $this->get_event($event['parent_event_id']);
- }
- $event['attachment'] = $this->getAttachment($id, $this->course);
- }
- }
- break;
- case 'admin':
- case 'platform':
- $sql = "SELECT * FROM ".$this->tbl_global_agenda."
- WHERE id = ".$id;
- $result = Database::query($sql);
- if (Database::num_rows($result)) {
- $event = Database::fetch_array($result, 'ASSOC');
- $event['description'] = $event['content'];
- }
- break;
- }
- return $event;
- }
- /**
- * Gets personal events
- * @param int $start
- * @param int $end
- * @return array
- */
- public function getPersonalEvents($start, $end)
- {
- $start = intval($start);
- $end = intval($end);
- $startCondition = '';
- $endCondition = '';
- if ($start !== 0) {
- $start = api_get_utc_datetime($start);
- $startCondition = "AND date >= '".$start."'";
- }
- if ($start !== 0) {
- $end = api_get_utc_datetime($end);
- $endCondition = "AND (enddate <= '".$end."' OR enddate IS NULL)";
- }
- $user_id = api_get_user_id();
- $sql = "SELECT * FROM ".$this->tbl_personal_agenda."
- WHERE user = $user_id $startCondition $endCondition";
- $result = Database::query($sql);
- $my_events = array();
- if (Database::num_rows($result)) {
- while ($row = Database::fetch_array($result, 'ASSOC')) {
- $event = array();
- $event['id'] = 'personal_'.$row['id'];
- $event['title'] = $row['title'];
- $event['className'] = 'personal';
- $event['borderColor'] = $event['backgroundColor'] = $this->event_personal_color;
- $event['editable'] = true;
- $event['sent_to'] = get_lang('Me');
- $event['type'] = 'personal';
- if (!empty($row['date']) && $row['date'] != '0000-00-00 00:00:00') {
- $event['start'] = $this->formatEventDate($row['date']);
- $event['start_date_localtime'] = api_get_local_time($row['date']);
- }
- if (!empty($row['enddate']) && $row['enddate'] != '0000-00-00 00:00:00') {
- $event['end'] = $this->formatEventDate($row['enddate']);
- $event['end_date_localtime'] = api_get_local_time($row['enddate']);
- }
- $event['description'] = $row['text'];
- $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
- $event['parent_event_id'] = 0;
- $event['has_children'] = 0;
- $my_events[] = $event;
- $this->events[] = $event;
- }
- }
- return $my_events;
- }
- /**
- * Get user/group list per event.
- *
- * @param int $eventId
- * @param int $courseId
- * @paraù int $sessionId
- *
- * @return array
- */
- public function getUsersAndGroupSubscribedToEvent($eventId, $courseId, $sessionId)
- {
- $eventId = intval($eventId);
- $courseId = intval($courseId);
- $sessionId = intval($sessionId);
- $sessionCondition = "ip.session_id = $sessionId";
- if (empty($sessionId)) {
- $sessionCondition = " (ip.session_id = 0 OR ip.session_id IS NULL) ";
- }
- $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
- $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
- // Get sent_tos
- $sql = "SELECT DISTINCT to_user_id, to_group_id
- FROM $tbl_property ip
- INNER JOIN $tlb_course_agenda agenda
- ON (ip.ref = agenda.id AND ip.c_id = agenda.c_id)
- WHERE
- ip.tool = '".TOOL_CALENDAR_EVENT."' AND
- ref = $eventId AND
- ip.visibility = '1' AND
- ip.c_id = $courseId AND
- $sessionCondition
- ";
- $result = Database::query($sql);
- $users = array();
- $groups = array();
- $everyone = false;
- while ($row = Database::fetch_array($result, 'ASSOC')) {
- if (!empty($row['to_group_id'])) {
- $groups[] = $row['to_group_id'];
- }
- if (!empty($row['to_user_id'])) {
- $users[] = $row['to_user_id'];
- }
- if (empty($groups) && empty($users)) {
- if ($row['to_group_id'] == 0) {
- $everyone = true;
- }
- }
- }
- return array(
- 'everyone' => $everyone,
- 'users' => $users,
- 'groups' => $groups
- );
- }
- /**
- * @param int $start
- * @param int $end
- * @param int $sessionId
- * @param int $userId
- * @param string $color
- *
- * @return array
- */
- public function getSessionEvents($start, $end, $sessionId = 0, $userId = 0, $color = '')
- {
- $courses = SessionManager::get_course_list_by_session_id($sessionId);
- if (!empty($courses)) {
- foreach ($courses as $course) {
- //if (api_is_coach($sessionId, $course['real_id'])) {
- $this->getCourseEvents(
- $start,
- $end,
- $course,
- 0,
- $sessionId,
- 0,
- $color
- );
- //}
- }
- }
- }
- /**
- * @param int $start
- * @param int $end
- * @param array $courseInfo
- * @param int $groupId
- * @param int $session_id
- * @param int $user_id
- * @param string $color
- *
- * @return array
- */
- public function getCourseEvents(
- $start,
- $end,
- $courseInfo,
- $groupId = 0,
- $session_id = 0,
- $user_id = 0,
- $color = ''
- ) {
- $start = isset($start) && !empty($start) ? api_get_utc_datetime(intval($start)) : null;
- $end = isset($end) && !empty($end) ? api_get_utc_datetime(intval($end)) : null;
- if (empty($courseInfo)) {
- return array();
- }
- $course_id = $courseInfo['real_id'];
- if (empty($course_id)) {
- return array();
- }
- $session_id = intval($session_id);
- $user_id = intval($user_id);
- $groupList = GroupManager::get_group_list(null, $courseInfo['code']);
- $group_name_list = array();
- if (!empty($groupList)) {
- foreach ($groupList as $group) {
- $group_name_list[$group['id']] = $group['name'];
- }
- }
- $group_memberships = [];
- if (!empty($groupId)) {
- if (!api_is_allowed_to_edit()) {
- $group_memberships = GroupManager::get_group_ids(
- $course_id,
- api_get_user_id()
- );
- $user_id = api_get_user_id();
- } else {
- $group_memberships = GroupManager::get_group_ids(
- $course_id,
- $user_id
- );
- }
- }
- $tlb_course_agenda = Database::get_course_table(TABLE_AGENDA);
- $tbl_property = Database::get_course_table(TABLE_ITEM_PROPERTY);
- if (!empty($groupId)) {
- $group_memberships = array($groupId);
- }
- if (is_array($group_memberships) && count($group_memberships) > 0) {
- if (api_is_allowed_to_edit()) {
- if (!empty($groupId)) {
- $where_condition = "( ip.to_group_id IN (".implode(", ", $group_memberships).") ) ";
- } else {
- if (!empty($user_id)) {
- $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).")) ) ";
- } else {
- $where_condition = "( ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).") ) ";
- }
- }
- } else {
- $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).")) ) ";
- }
- $sql = "SELECT DISTINCT
- agenda.*,
- ip.visibility,
- ip.to_group_id,
- ip.insert_user_id,
- ip.ref,
- to_user_id
- FROM $tlb_course_agenda agenda
- INNER JOIN $tbl_property ip
- ON (agenda.id = ip.ref AND agenda.c_id = ip.c_id)
- WHERE
- ip.tool = '".TOOL_CALENDAR_EVENT."' AND
- $where_condition AND
- ip.visibility = '1' AND
- agenda.c_id = $course_id AND
- ip.c_id = $course_id
- ";
- } else {
- $visibilityCondition = " ip.visibility='1' AND";
- if (api_is_allowed_to_edit()) {
- if ($user_id == 0) {
- $where_condition = "";
- } else {
- $where_condition = " (ip.to_user_id = ".$user_id.") OR ";
- }
- $visibilityCondition = " (ip.visibility IN ('1', '0')) AND ";
- } else {
- $where_condition = " ( ip.to_user_id = ".api_get_user_id()." AND (ip.to_group_id='0' OR ip.to_group_id IS NULL)) OR ";
- }
- $sessionCondition = " agenda.session_id = $session_id AND
- ip.session_id = $session_id ";
- if (empty($session_id)) {
- $sessionCondition = "
- (
- (agenda.session_id = 0 OR agenda.session_id IS NULL) AND
- (ip.session_id = 0 OR ip.session_id IS NULL)
- ) ";
- }
- $sql = "SELECT DISTINCT
- agenda.*,
- ip.visibility,
- ip.to_group_id,
- ip.insert_user_id,
- ip.ref,
- to_user_id
- FROM $tlb_course_agenda agenda
- INNER JOIN $tbl_property ip
- ON (agenda.id = ip.ref AND agenda.c_id = ip.c_id)
- WHERE
- ip.tool='".TOOL_CALENDAR_EVENT."' AND
- $where_condition
- $visibilityCondition
- agenda.c_id = $course_id AND
- ip.c_id = $course_id AND
- $sessionCondition
- ";
- }
- $dateCondition = null;
- if (!empty($start) && !empty($end)) {
- $dateCondition .= "AND (
- agenda.start_date BETWEEN '".$start."' AND '".$end."' OR
- agenda.end_date BETWEEN '".$start."' AND '".$end."' OR
- (
- agenda.start_date IS NOT NULL AND agenda.end_date IS NOT NULL AND
- YEAR(agenda.start_date) = YEAR(agenda.end_date) AND
- MONTH('$start') BETWEEN MONTH(agenda.start_date) AND MONTH(agenda.end_date)
- )
- )";
- }
- $sql .= $dateCondition;
- $result = Database::query($sql);
- $coachCanEdit = false;
- if (!empty($session_id)) {
- $coachCanEdit = api_is_coach($session_id, $course_id);
- }
- if (Database::num_rows($result)) {
- $eventsAdded = array_column($this->events, 'id');
- while ($row = Database::fetch_array($result, 'ASSOC')) {
- $eventId = $row['ref'];
- $items = $this->getUsersAndGroupSubscribedToEvent(
- $eventId,
- $course_id,
- $this->sessionId
- );
- $group_to_array = $items['groups'];
- $user_to_array = $items['users'];
- $event = array();
- $event['id'] = 'course_'.$row['id'];
- // To avoid doubles
- if (in_array($event['id'], $eventsAdded)) {
- continue;
- }
- $eventsAdded[] = $row['id'];
- $attachment = $this->getAttachment($row['id'], $courseInfo);
- if (!empty($attachment)) {
- $has_attachment = Display::return_icon('attachment.gif', get_lang('Attachment'));
- $user_filename = $attachment['filename'];
- $url = api_get_path(WEB_CODE_PATH).'calendar/download.php?file='.$attachment['path'].'&course_id='.$course_id.'&'.api_get_cidreq();
- $event['attachment'] = $has_attachment.Display::url($user_filename, $url);
- } else {
- $event['attachment'] = '';
- }
- $event['title'] = $row['title'];
- $event['className'] = 'course';
- $event['allDay'] = 'false';
- $event['course_id'] = $course_id;
- $event['borderColor'] = $event['backgroundColor'] = $this->event_course_color;
- $sessionInfo = [];
- if (isset($row['session_id']) && !empty($row['session_id'])) {
- $sessionInfo = api_get_session_info($session_id);
- $event['borderColor'] = $event['backgroundColor'] = $this->event_session_color;
- }
- $event['session_name'] = isset($sessionInfo['name']) ? $sessionInfo['name'] : '';
- $event['course_name'] = isset($courseInfo['title']) ? $courseInfo['title'] : '';
- if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
- $event['borderColor'] = $event['backgroundColor'] = $this->event_group_color;
- }
- if (!empty($color)) {
- $event['borderColor'] = $event['backgroundColor'] = $color;
- }
- if (isset($row['color']) && !empty($row['color'])) {
- $event['borderColor'] = $event['backgroundColor'] = $row['color'];
- }
- $event['editable'] = false;
- if (api_is_allowed_to_edit() && $this->type == 'course') {
- $event['editable'] = true;
- if (!empty($session_id)) {
- if ($coachCanEdit == false) {
- $event['editable'] = false;
- }
- }
- }
- if (!empty($row['start_date']) && $row['start_date'] != '0000-00-00 00:00:00') {
- $event['start'] = $this->formatEventDate($row['start_date']);
- $event['start_date_localtime'] = api_get_local_time($row['start_date']);
- }
- if (!empty($row['end_date']) && $row['end_date'] != '0000-00-00 00:00:00') {
- $event['end'] = $this->formatEventDate($row['end_date']);
- $event['end_date_localtime'] = api_get_local_time($row['end_date']);
- }
- $event['sent_to'] = '';
- $event['type'] = 'course';
- if ($row['session_id'] != 0) {
- $event['type'] = 'session';
- }
- // Event Sent to a group?
- if (isset($row['to_group_id']) && !empty($row['to_group_id'])) {
- $sent_to = array();
- if (!empty($group_to_array)) {
- foreach ($group_to_array as $group_item) {
- $sent_to[] = $group_name_list[$group_item];
- }
- }
- $sent_to = implode('@@', $sent_to);
- $sent_to = str_replace('@@', '</div><div class="label_tag notice">', $sent_to);
- $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
- $event['type'] = 'group';
- }
- //Event sent to a user?
- if (isset($row['to_user_id'])) {
- $sent_to = array();
- if (!empty($user_to_array)) {
- foreach ($user_to_array as $item) {
- $user_info = api_get_user_info($item);
- // Add username as tooltip for $event['sent_to'] - ref #4226
- $username = api_htmlentities(sprintf(get_lang('LoginX'), $user_info['username']), ENT_QUOTES);
- $sent_to[] = "<span title='".$username."'>".$user_info['complete_name']."</span>";
- }
- }
- $sent_to = implode('@@', $sent_to);
- $sent_to = str_replace('@@', '</div><div class="label_tag notice">', $sent_to);
- $event['sent_to'] = '<div class="label_tag notice">'.$sent_to.'</div>';
- }
- //Event sent to everyone!
- if (empty($event['sent_to'])) {
- $event['sent_to'] = '<div class="label_tag notice">'.get_lang('Everyone').'</div>';
- }
- $event['description'] = $row['content'];
- $event['visibility'] = $row['visibility'];
- $event['real_id'] = $row['id'];
- $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
- $event['parent_event_id'] = $row['parent_event_id'];
- $event['has_children'] = $this->hasChildren($row['id'], $course_id) ? 1 : 0;
- $event['comment'] = $row['comment'];
- $this->events[] = $event;
- }
- }
- return $this->events;
- }
- /**
- * @param int $start tms
- * @param int $end tms
- * @return array
- */
- public function getPlatformEvents($start, $end)
- {
- $start = isset($start) && !empty($start) ? api_get_utc_datetime(intval($start)) : null;
- $end = isset($end) && !empty($end) ? api_get_utc_datetime(intval($end)) : null;
- $dateCondition = '';
- if (!empty($start) && !empty($end)) {
- $dateCondition .= "AND (
- start_date BETWEEN '".$start."' AND '".$end."' OR
- end_date BETWEEN '".$start."' AND '".$end."' OR
- (
- start_date IS NOT NULL AND end_date IS NOT NULL AND
- YEAR(start_date) = YEAR(end_date) AND
- MONTH('$start') BETWEEN MONTH(start_date) AND MONTH(end_date)
- )
- )";
- }
- $access_url_id = api_get_current_access_url_id();
- $sql = "SELECT *
- FROM ".$this->tbl_global_agenda."
- WHERE access_url_id = $access_url_id
- $dateCondition";
- $result = Database::query($sql);
- $my_events = array();
- if (Database::num_rows($result)) {
- while ($row = Database::fetch_array($result, 'ASSOC')) {
- $event = array();
- $event['id'] = 'platform_'.$row['id'];
- $event['title'] = $row['title'];
- $event['className'] = 'platform';
- $event['allDay'] = 'false';
- $event['borderColor'] = $event['backgroundColor'] = $this->event_platform_color;
- $event['editable'] = false;
- $event['type'] = 'admin';
- if (api_is_platform_admin() && $this->type == 'admin') {
- $event['editable'] = true;
- }
- if (!empty($row['start_date']) && $row['start_date'] != '0000-00-00 00:00:00') {
- $event['start'] = $this->formatEventDate($row['start_date']);
- $event['start_date_localtime'] = api_get_local_time($row['start_date']);
- }
- if (!empty($row['end_date']) && $row['end_date'] != '0000-00-00 00:00:00') {
- $event['end'] = $this->formatEventDate($row['end_date']);
- $event['end_date_localtime'] = api_get_local_time($row['end_date']);
- }
- $event['description'] = $row['content'];
- $event['allDay'] = isset($row['all_day']) && $row['all_day'] == 1 ? $row['all_day'] : 0;
- $event['parent_event_id'] = 0;
- $event['has_children'] = 0;
- $my_events[] = $event;
- $this->events[] = $event;
- }
- }
- return $my_events;
- }
- /**
- * Format needed for the Fullcalendar js lib
- *
- * @param string $utcTime
- * @return bool|string
- */
- private function formatEventDate($utcTime)
- {
- $utcTimeZone = new DateTimeZone('UTC');
- $platformTimeZone = new DateTimeZone(_api_get_timezone());
- $eventDate = new DateTime($utcTime, $utcTimeZone);
- $eventDate->setTimezone($platformTimeZone);
- return $eventDate->format(DateTime::ISO8601);
- }
- /**
- * this function shows the form with the user that were not selected
- * @author: Patrick Cool <patrick.cool@UGent.be>, Ghent University
- * @return string code
- */
- public static function construct_not_selected_select_form($group_list = null, $user_list = null, $to_already_selected = array())
- {
- $html = '<select id="users_to_send_id" data-placeholder="'.get_lang('Select').'" name="users_to_send[]" multiple="multiple">';
- if ($to_already_selected == 'everyone') {
- $html .= '<option value="everyone" checked="checked">'.get_lang('Everyone').'</option>';
- } else {
- $html .= '<option value="everyone">'.get_lang('Everyone').'</option>';
- }
- if (is_array($group_list)) {
- $html .= '<optgroup label="'.get_lang('Groups').'">';
- foreach ($group_list as $this_group) {
- if (!is_array($to_already_selected) || !in_array("GROUP:".$this_group['id'], $to_already_selected)) {
- // $to_already_selected is the array containing the groups (and users) that are already selected
- $count_users = isset($this_group['count_users']) ? $this_group['count_users'] : $this_group['userNb'];
- $count_users = " – $count_users ".get_lang('Users');
- $html .= '<option value="GROUP:'.$this_group['id'].'"> '.$this_group['name'].$count_users.'</option>';
- }
- }
- $html .= '</optgroup>';
- }
- // adding the individual users to the select form
- if (is_array($group_list)) {
- $html .= '<optgroup label="'.get_lang('Users').'">';
- }
- foreach ($user_list as $this_user) {
- // $to_already_selected is the array containing the users (and groups) that are already selected
- if (!is_array($to_already_selected) || !in_array("USER:".$this_user['user_id'], $to_already_selected)) {
- $username = api_htmlentities(sprintf(get_lang('LoginX'), $this_user['username']), ENT_QUOTES);
- // @todo : add title attribute $username in the jqdialog window. wait for a chosen version to inherit title attribute
- $html .= '<option title="'.$username.'" value="USER:'.$this_user['user_id'].'">'.api_get_person_name($this_user['firstname'], $this_user['lastname']).' ('.$this_user['username'].') </option>';
- }
- }
- if (is_array($group_list)) {
- $html .= '</optgroup>';
- $html .= "</select>";
- }
- return $html;
- }
- /**
- * @param FormValidator $form
- * @param array $groupList
- * @param array $userList
- * @param array $sendTo array('users' => [1, 2], 'groups' => [3, 4])
- * @param array $attributes
- * @param bool $addOnlyItemsInSendTo
- * @param bool $required
- */
- public function setSendToSelect(
- $form,
- $groupList = null,
- $userList = null,
- $sendTo = array(),
- $attributes = array(),
- $addOnlyItemsInSendTo = false,
- $required = false
- ) {
- $params = array(
- 'id' => 'users_to_send_id',
- 'data-placeholder' => get_lang('Select'),
- 'multiple' => 'multiple',
- 'class' => 'multiple-select'
- );
- if (!empty($attributes)) {
- $params = array_merge($params, $attributes);
- if (empty($params['multiple'])) {
- unset($params['multiple']);
- }
- }
- $sendToGroups = isset($sendTo['groups']) ? $sendTo['groups'] : array();
- $sendToUsers = isset($sendTo['users']) ? $sendTo['users'] : array();
- /** @var HTML_QuickForm_select $select */
- $select = $form->addSelect('users_to_send', get_lang('To'), null, $params);
- if ($required) {
- $form->setRequired($select);
- }
- $selectedEveryoneOptions = array();
- if (isset($sendTo['everyone']) && $sendTo['everyone']) {
- $selectedEveryoneOptions = array('selected');
- $sendToUsers = array();
- }
- $select->addOption(get_lang('Everyone'), 'everyone', $selectedEveryoneOptions);
- $options = array();
- if (is_array($groupList)) {
- foreach ($groupList as $group) {
- $count_users = isset($group['count_users']) ? $group['count_users'] : $group['userNb'];
- $count_users = " – $count_users ".get_lang('Users');
- $option = array(
- 'text' => $group['name'].$count_users,
- 'value' => "GROUP:".$group['id']
- );
- $selected = in_array($group['id'], $sendToGroups) ? true : false;
- if ($selected) {
- $option['selected'] = 'selected';
- }
- if ($addOnlyItemsInSendTo) {
- if ($selected) {
- $options[] = $option;
- }
- } else {
- $options[] = $option;
- }
- }
- $select->addOptGroup($options, get_lang('Groups'));
- }
- // adding the individual users to the select form
- if (is_array($userList)) {
- $options = array();
- foreach ($userList as $user) {
- if ($user['status'] == ANONYMOUS) {
- continue;
- }
- $option = array(
- 'text' => api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].')',
- 'value' => "USER:".$user['user_id']
- );
- $selected = in_array($user['user_id'], $sendToUsers) ? true : false;
- if ($selected) {
- $option['selected'] = 'selected';
- }
- if ($addOnlyItemsInSendTo) {
- if ($selected) {
- $options[] = $option;
- }
- } else {
- $options[] = $option;
- }
- }
- $select->addOptGroup($options, get_lang('Users'));
- }
- }
- /**
- * Separates the users and groups array
- * users have a value USER:XXX (with XXX the user id
- * groups have a value GROUP:YYY (with YYY the group id)
- * use the 'everyone' key
- * @author Julio Montoya based in separate_users_groups in agenda.inc.php
- * @param array $to
- * @return array
- */
- public function parseSendToArray($to)
- {
- $groupList = array();
- $userList = array();
- $sendTo = null;
- $sendTo['everyone'] = false;
- if (is_array($to) && count($to) > 0) {
- foreach ($to as $item) {
- if ($item == 'everyone') {
- $sendTo['everyone'] = true;
- } else {
- list($type, $id) = explode(':', $item);
- switch ($type) {
- case 'GROUP':
- $groupList[] = $id;
- break;
- case 'USER':
- $userList[] = $id;
- break;
- }
- }
- }
- $sendTo['groups'] = $groupList;
- $sendTo['users'] = $userList;
- }
- return $sendTo;
- }
- /**
- * @param array $params
- * @return FormValidator
- */
- public function getForm($params = array())
- {
- $action = isset($params['action']) ? Security::remove_XSS($params['action']) : null;
- $id = isset($params['id']) ? intval($params['id']) : null;
- if ($this->type == 'course') {
- $url = api_get_self().'?'.api_get_cidreq().'&action='.$action.'&id='.$id.'&type='.$this->type;
- } else {
- $url = api_get_self().'?action='.$action.'&id='.$id.'&type='.$this->type;
- }
- if (isset($params['content'])) {
- $params['content'] = nl2br($params['content']);
- }
- $form = new FormValidator(
- 'add_event',
- 'post',
- $url,
- null,
- array('enctype' => 'multipart/form-data')
- );
- $idAttach = isset($params['id_attach']) ? intval($params['id_attach']) : null;
- $groupId = api_get_group_id();
- if ($id) {
- $form_title = get_lang('ModifyCalendarItem');
- } else {
- $form_title = get_lang('AddCalendarItem');
- }
- $form->addElement('header', $form_title);
- $form->addElement('hidden', 'id', $id);
- $form->addElement('hidden', 'action', $action);
- $form->addElement('hidden', 'id_attach', $idAttach);
- $isSubEventEdition = false;
- $isParentFromSerie = false;
- $showAttachmentForm = true;
- if ($this->type == 'course') {
- // Edition mode.
- if (!empty($id)) {
- $showAttachmentForm = false;
- if (isset($params['parent_event_id']) && !empty($params['parent_event_id'])) {
- $isSubEventEdition = true;
- }
- if (!empty($params['repeat_info'])) {
- $isParentFromSerie = true;
- }
- }
- }
- if ($isSubEventEdition) {
- $form->addElement(
- 'label',
- null,
- Display::return_message(get_lang('EditingThisEventWillRemoveItFromTheSerie'), 'warning')
- );
- }
- $form->addElement('text', 'title', get_lang('ItemTitle'));
- if (isset($groupId) && !empty($groupId)) {
- $form->addElement('hidden', 'selected_form[0]', "GROUP:'.$groupId.'");
- $form->addElement('hidden', 'to', 'true');
- } else {
- $sendTo = isset($params['send_to']) ? $params['send_to'] : null;
- if ($this->type == 'course') {
- $this->showToForm($form, $sendTo, array(), false, true);
- }
- }
- $form->addDateRangePicker('date_range', get_lang('StartDate'), false, array('id' => 'date_range'));
- $form->addElement('checkbox', 'all_day', null, get_lang('AllDay'));
- if ($this->type == 'course') {
- $repeat = $form->addElement('checkbox', 'repeat', null, get_lang('RepeatEvent'), array('onclick' => 'return plus_repeated_event();'));
- $form->addElement('html', '<div id="options2" style="display:none">');
- $form->addElement('select', 'repeat_type', get_lang('RepeatType'), self::getRepeatTypes());
- $form->addElement('date_picker', 'repeat_end_day', get_lang('RepeatEnd'), array('id' => 'repeat_end_date_form'));
- if ($isSubEventEdition || $isParentFromSerie) {
- if ($isSubEventEdition) {
- $parentEvent = $params['parent_info'];
- $repeatInfo = $parentEvent['repeat_info'];
- } else {
- $repeatInfo = $params['repeat_info'];
- }
- $params['repeat'] = 1;
- $params['repeat_type'] = $repeatInfo['cal_type'];
- $params['repeat_end_day'] = substr(api_get_local_time($repeatInfo['cal_end']), 0, 10);
- $form->freeze(array('repeat_type', 'repeat_end_day'));
- $repeat->_attributes['disabled'] = 'disabled';
- }
- $form->addElement('html', '</div>');
- }
- if (!empty($id)) {
- if (empty($params['end_date'])) {
- $params['date_range'] = $params['end_date'];
- }
- $params['date_range'] =
- substr(api_get_local_time($params['start_date']), 0, 16).' / '.
- substr(api_get_local_time($params['end_date']), 0, 16);
- }
- if (!api_is_allowed_to_edit(null, true)) {
- $toolbar = 'AgendaStudent';
- } else {
- $toolbar = 'Agenda';
- }
- $form->addElement(
- 'html_editor',
- 'content',
- get_lang('Description'),
- null,
- array('ToolbarSet' => $toolbar, 'Width' => '100%', 'Height' => '200')
- );
- if ($this->type == 'course') {
- $form->addElement('textarea', 'comment', get_lang('Comment'));
- $form->addElement('file', 'user_upload', get_lang('AddAnAttachment'));
- if ($showAttachmentForm) {
- if (isset($params['attachment']) && !empty($params['attachment'])) {
- $attachment = $params['attachment'];
- $params['file_comment'] = $attachment['comment'];
- if (!empty($attachment['path'])) {
- $form->addElement(
- 'checkbox',
- 'delete_attachment',
- null,
- get_lang('DeleteAttachment').' '.$attachment['filename']
- );
- }
- }
- }
- $form->addElement('textarea', 'file_comment', get_lang('FileComment'));
- }
- if (empty($id)) {
- $form->addElement(
- 'checkbox',
- 'add_announcement',
- null,
- get_lang('AddAnnouncement').' ('.get_lang('SendMail').')'
- );
- }
- if ($id) {
- $form->addButtonUpdate(get_lang('ModifyEvent'));
- } else {
- $form->addButtonSave(get_lang('AgendaAdd'));
- }
- $form->setDefaults($params);
- $form->addRule('date_range', get_lang('ThisFieldIsRequired'), 'required');
- $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
- return $form;
- }
- /**
- * @param FormValidator $form
- * @param array $sendTo array('everyone' => false, 'users' => [1, 2], 'groups' => [3, 4])
- * @param array $attributes
- * @param bool $addOnlyItemsInSendTo
- * @param bool $required
- * @return bool
- */
- public function showToForm(
- $form,
- $sendTo = array(),
- $attributes = array(),
- $addOnlyItemsInSendTo = false,
- $required = false
- ) {
- if ($this->type != 'course') {
- return false;
- }
- $order = 'lastname';
- if (api_is_western_name_order()) {
- $order = 'firstname';
- }
- $userList = CourseManager::get_user_list_from_course_code(
- api_get_course_id(),
- $this->sessionId,
- null,
- $order
- );
- $groupList = CourseManager::get_group_list_of_course(
- api_get_course_id(),
- $this->sessionId
- );
- $this->setSendToSelect(
- $form,
- $groupList,
- $userList,
- $sendTo,
- $attributes,
- $addOnlyItemsInSendTo,
- $required
- );
- return true;
- }
- /**
- * @param int $id
- * @param int $visibility 0= invisible, 1 visible
- * @param array $courseInfo
- * @param int $userId
- */
- public static function changeVisibility($id, $visibility, $courseInfo, $userId = null)
- {
- $id = intval($id);
- if (empty($userId)) {
- $userId = api_get_user_id();
- } else {
- $userId = intval($userId);
- }
- if ($visibility == 0) {
- api_item_property_update($courseInfo, TOOL_CALENDAR_EVENT, $id, "invisible", $userId);
- } else {
- api_item_property_update($courseInfo, TOOL_CALENDAR_EVENT, $id, "visible", $userId);
- }
- }
- /**
- * Get repeat types
- * @return array
- */
- public static function getRepeatTypes()
- {
- return array(
- 'daily' => get_lang('RepeatDaily'),
- 'weekly' => get_lang('RepeatWeekly'),
- 'monthlyByDate' => get_lang('RepeatMonthlyByDate'),
- //monthlyByDay"> get_lang('RepeatMonthlyByDay');
- //monthlyByDayR' => get_lang('RepeatMonthlyByDayR'),
- 'yearly' => get_lang('RepeatYearly')
- );
- }
- /**
- * Show a list with all the attachments according to the post's id
- * @param int $eventId
- * @param array $courseInfo
- * @return array with the post info
- */
- public function getAttachment($eventId, $courseInfo)
- {
- $tableAttachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
- $courseId = intval($courseInfo['real_id']);
- $eventId = intval($eventId);
- $row = array();
- $sql = "SELECT id, path, filename, comment
- FROM $tableAttachment
- WHERE
- c_id = $courseId AND
- agenda_id = $eventId";
- $result = Database::query($sql);
- if (Database::num_rows($result) != 0) {
- $row = Database::fetch_array($result, 'ASSOC');
- }
- return $row;
- }
- /**
- * Add an attachment file into agenda
- * @param int $eventId
- * @param array $fileUserUpload ($_FILES['user_upload'])
- * @param string comment about file
- * @param array $courseInfo
- * @return string
- */
- public function addAttachment($eventId, $fileUserUpload, $comment, $courseInfo)
- {
- $agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
- $eventId = intval($eventId);
- // Storing the attachments
- $upload_ok = false;
- if (!empty($fileUserUpload['name'])) {
- $upload_ok = process_uploaded_file($fileUserUpload);
- }
- if (!empty($upload_ok)) {
- $courseDir = $courseInfo['directory'].'/upload/calendar';
- $sys_course_path = api_get_path(SYS_COURSE_PATH);
- $uploadDir = $sys_course_path.$courseDir;
- // Try to add an extension to the file if it hasn't one
- $new_file_name = add_ext_on_mime(
- stripslashes($fileUserUpload['name']),
- $fileUserUpload['type']
- );
- // user's file name
- $file_name = $fileUserUpload['name'];
- if (!filter_extension($new_file_name)) {
- return Display::return_message(
- get_lang('UplUnableToSaveFileFilteredExtension'),
- 'error'
- );
- } else {
- $new_file_name = uniqid('');
- $new_path = $uploadDir.'/'.$new_file_name;
- $result = @move_uploaded_file($fileUserUpload['tmp_name'], $new_path);
- $course_id = api_get_course_int_id();
- $size = intval($fileUserUpload['size']);
- // Storing the attachments if any
- if ($result) {
- $params = [
- 'c_id' => $course_id,
- 'filename' => $file_name,
- 'comment' => $comment,
- 'path' => $new_file_name,
- 'agenda_id' => $eventId,
- 'size' => $size
- ];
- $id = Database::insert($agenda_table_attachment, $params);
- if ($id) {
- $sql = "UPDATE $agenda_table_attachment
- SET id = iid WHERE iid = $id";
- Database::query($sql);
- api_item_property_update(
- $courseInfo,
- 'calendar_event_attachment',
- $id,
- 'AgendaAttachmentAdded',
- api_get_user_id()
- );
- }
- }
- }
- }
- }
- /**
- * @param int $eventId
- * @param array $fileUserUpload
- * @param string $comment
- * @param array $courseInfo
- */
- public function updateAttachment($eventId, $fileUserUpload, $comment, $courseInfo)
- {
- $attachment = $this->getAttachment($eventId, $courseInfo);
- if (!empty($attachment)) {
- $this->deleteAttachmentFile($attachment['id'], $courseInfo);
- }
- $this->addAttachment($eventId, $fileUserUpload, $comment, $courseInfo);
- }
- /**
- * This function delete a attachment file by id
- * @param int $attachmentId
- * @param array $courseInfo
- * @return string
- */
- public function deleteAttachmentFile($attachmentId, $courseInfo)
- {
- $agenda_table_attachment = Database::get_course_table(TABLE_AGENDA_ATTACHMENT);
- $attachmentId = intval($attachmentId);
- $courseId = $courseInfo['real_id'];
- if (empty($courseId) || empty($attachmentId)) {
- return false;
- }
- $sql = "DELETE FROM $agenda_table_attachment
- WHERE c_id = $courseId AND id = ".$attachmentId;
- $result = Database::query($sql);
- // update item_property
- api_item_property_update(
- $courseInfo,
- 'calendar_event_attachment',
- $attachmentId,
- 'AgendaAttachmentDeleted',
- api_get_user_id()
- );
- if (!empty($result)) {
- return Display::return_message(get_lang("AttachmentFileDeleteSuccess"), 'confirmation');
- }
- }
- /**
- * Adds x weeks to a UNIX timestamp
- * @param int The timestamp
- * @param int The number of weeks to add
- * @return int The new timestamp
- */
- function addWeek($timestamp, $num = 1)
- {
- return $timestamp + $num * 604800;
- }
- /**
- * Adds x months to a UNIX timestamp
- * @param int The timestamp
- * @param int The number of years to add
- * @return int The new timestamp
- */
- function addMonth($timestamp, $num = 1)
- {
- list($y, $m, $d, $h, $n, $s) = split('/', date('Y/m/d/h/i/s', $timestamp));
- if ($m + $num > 12) {
- $y += floor($num / 12);
- $m += $num % 12;
- } else {
- $m += $num;
- }
- return mktime($h, $n, $s, $m, $d, $y);
- }
- /**
- * Adds x years to a UNIX timestamp
- * @param int The timestamp
- * @param int The number of years to add
- * @return int The new timestamp
- */
- function addYear($timestamp, $num = 1)
- {
- list($y, $m, $d, $h, $n, $s) = split('/', date('Y/m/d/h/i/s', $timestamp));
- return mktime($h, $n, $s, $m, $d, $y + $num);
- }
- /**
- * @param int $eventId
- * @return array
- */
- public function getAllRepeatEvents($eventId)
- {
- $events = array();
- switch ($this->type) {
- case 'personal':
- break;
- case 'course':
- if (!empty($this->course['real_id'])) {
- $sql = "SELECT * FROM ".$this->tbl_course_agenda."
- WHERE
- c_id = ".$this->course['real_id']." AND
- parent_event_id = ".$eventId;
- $result = Database::query($sql);
- if (Database::num_rows($result)) {
- while ($row = Database::fetch_array($result, 'ASSOC')) {
- $events[] = $row;
- }
- }
- }
- break;
- }
- return $events;
- }
- /**
- * @param int $eventId
- * @param int $courseId
- *
- * @return bool
- */
- public function hasChildren($eventId, $courseId)
- {
- $eventId = intval($eventId);
- $courseId = intval($courseId);
- $sql = "SELECT count(DISTINCT(id)) as count
- FROM ".$this->tbl_course_agenda."
- WHERE
- c_id = ".$courseId." AND
- parent_event_id = ".$eventId;
- $result = Database::query($sql);
- if (Database::num_rows($result)) {
- $row = Database::fetch_array($result, 'ASSOC');
- return $row['count'] > 0;
- }
- return false;
- }
- /**
- * @param int $filter
- * @param string $view
- * @return string
- */
- public function displayActions($view, $filter = 0)
- {
- $courseInfo = api_get_course_info();
- $toolbar = '';
- $toolbar .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda_js.php?type={$this->type}'>".
- Display::return_icon('calendar.png', get_lang('Calendar'), '', ICON_SIZE_MEDIUM)."</a>";
- $courseCondition = '';
- if (!empty($courseInfo)) {
- $courseCondition = api_get_cidreq();
- }
- $toolbar .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda_list.php?type={$this->type}&".$courseCondition."'>".
- Display::return_icon('week.png', get_lang('AgendaList'), '', ICON_SIZE_MEDIUM)."</a>";
- $form = '';
- if (api_is_allowed_to_edit(false, true) ||
- (api_get_course_setting('allow_user_edit_agenda') && !api_is_anonymous()) && api_is_allowed_to_session_edit(false, true) ||
- GroupManager::user_has_access(api_get_user_id(), api_get_group_id(), GroupManager::GROUP_TOOL_CALENDAR) &&
- GroupManager::is_tutor_of_group(api_get_user_id(), api_get_group_id())
- ) {
- $toolbar .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda.php?".api_get_cidreq()."&action=add&type=course'>".
- Display::return_icon('new_event.png', get_lang('AgendaAdd'), '', ICON_SIZE_MEDIUM)."</a>";
- $toolbar .= "<a href='".api_get_path(WEB_CODE_PATH)."calendar/agenda.php?".api_get_cidreq()."&action=importical&type=course'>".
- Display::return_icon('import_calendar.png', get_lang('ICalFileImport'), '', ICON_SIZE_MEDIUM)."</a>";
- if ($this->type == 'course') {
- if (!isset($_GET['action'])) {
- $form = new FormValidator(
- 'form-search',
- 'post',
- '',
- '',
- array(),
- FormValidator::LAYOUT_INLINE
- );
- $attributes = array(
- 'multiple' => false,
- 'id' => 'select_form_id_search'
- );
- $selectedValues = $this->parseAgendaFilter($filter);
- $this->showToForm($form, $selectedValues, $attributes);
- $form = $form->returnForm();
- }
- }
- }
- if (api_is_platform_admin() ||
- api_is_teacher() ||
- api_is_student_boss() ||
- api_is_drh() ||
- api_is_session_admin() ||
- api_is_coach()
- ) {
- if ($this->type == 'personal') {
- $form = null;
- if (!isset($_GET['action'])) {
- $form = new FormValidator(
- 'form-search',
- 'get',
- api_get_self().'?type=personal&',
- '',
- array(),
- FormValidator::LAYOUT_INLINE
- );
- $sessions = SessionManager::get_sessions_by_user(api_get_user_id());
- $form->addHidden('type', 'personal');
- $sessions = array_column($sessions, 'session_name', 'session_id');
- $sessions = ['0' => get_lang('SelectAnOption')] + $sessions;
- $form->addSelect(
- 'session_id',
- get_lang('Session'),
- $sessions,
- ['id' => 'session_id']
- );
- $form->addButtonFilter(get_lang('Filter'));
- $form->addButtonReset(get_lang('Reset'));
- $form = $form->returnForm();
- }
- }
- }
- $actions = '<div class="row">';
- $actions .= '<div class="col-md-9">';
- if ($view == 'calendar') {
- $actions .= $form;
- }
- $actions .= '</div>';
- $actions .= '<div class="col-md-3 right">';
- $actions .= $toolbar;
- $actions .= '</div>';
- $actions .= '</div>';
- return $actions;
- }
- /**
- * @return FormValidator
- */
- public function getImportCalendarForm()
- {
- $form = new FormValidator(
- 'frm_import_ical',
- 'post',
- api_get_self().'?action='.Security::remove_XSS($_GET['action']).'&type='.$this->type,
- array('enctype' => 'multipart/form-data')
- );
- $form->addElement('header', get_lang('ICalFileImport'));
- $form->addElement('file', 'ical_import', get_lang('ICalFileImport'));
- $form->addRule('ical_import', get_lang('ThisFieldIsRequired'), 'required');
- $form->addButtonImport(get_lang('Import'), 'ical_submit');
- return $form;
- }
- /**
- * @param array $courseInfo
- * @param $file
- * @return array|bool|string
- */
- public function importEventFile($courseInfo, $file)
- {
- $charset = api_get_system_encoding();
- $filepath = api_get_path(SYS_ARCHIVE_PATH).$file['name'];
- $messages = array();
- if (!@move_uploaded_file($file['tmp_name'], $filepath)) {
- error_log('Problem moving uploaded file: '.$file['error'].' in '.__FILE__.' line '.__LINE__);
- return false;
- }
- $data = file_get_contents($filepath);
- $trans = array(
- 'DAILY' => 'daily',
- 'WEEKLY' => 'weekly',
- 'MONTHLY' => 'monthlyByDate',
- 'YEARLY' => 'yearly'
- );
- $sentTo = array('everyone' => true);
- $calendar = Sabre\VObject\Reader::read($data);
- $currentTimeZone = _api_get_timezone();
- if (!empty($calendar->VEVENT)) {
- foreach ($calendar->VEVENT as $event) {
- $start = $event->DTSTART->getDateTime();
- $end = $event->DTEND->getDateTime();
- //Sabre\VObject\DateTimeParser::parseDateTime(string $dt, \Sabre\VObject\DateTimeZone $tz)
- $startDateTime = api_get_local_time($start->format('Y-m-d H:i:s'), $currentTimeZone, $start->format('e'));
- $endDateTime = api_get_local_time($end->format('Y-m-d H:i'), $currentTimeZone, $end->format('e'));
- $title = api_convert_encoding((string)$event->summary, $charset, 'UTF-8');
- $description = api_convert_encoding((string)$event->description, $charset, 'UTF-8');
- $id = $this->addEvent(
- $startDateTime,
- $endDateTime,
- 'false',
- $title,
- $description,
- $sentTo
- );
- $messages[] = " $title - ".$startDateTime." - ".$endDateTime;
- //$attendee = (string)$event->attendee;
- /** @var Sabre\VObject\Property\ICalendar\Recur $repeat */
- $repeat = $event->RRULE;
- if ($id && !empty($repeat)) {
- $repeat = $repeat->getParts();
- $freq = $trans[$repeat['FREQ']];
- if (isset($repeat['UNTIL']) && !empty($repeat['UNTIL'])) {
- // Check if datetime or just date (strlen == 8)
- if (strlen($repeat['UNTIL']) == 8) {
- // Fix the datetime format to avoid exception in the next step
- $repeat['UNTIL'] .= 'T000000';
- }
- $until = Sabre\VObject\DateTimeParser::parseDateTime($repeat['UNTIL'], new DateTimeZone($currentTimeZone));
- $until = $until->format('Y-m-d H:i');
- //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $until, $attendee);
- $this->addRepeatedItem(
- $id,
- $freq,
- $until,
- $sentTo
- );
- }
- if (!empty($repeat['COUNT'])) {
- /*$count = $repeat['COUNT'];
- $interval = $repeat['INTERVAL'];
- $endDate = null;
- switch($freq) {
- case 'daily':
- $start = api_strtotime($startDateTime);
- $date = new DateTime($startDateTime);
- $days = $count * $interval;
- var_dump($days);
- $date->add(new DateInterval("P".$days."D"));
- $endDate = $date->format('Y-m-d H:i');
- //$endDate = $count *
- for ($i = 0; $i < $count; $i++) {
- $days = 86400 * 7
- }
- }
- }*/
- //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $count, $attendee);
- /*$this->addRepeatedItem(
- $id,
- $freq,
- $endDate,
- $sentTo
- );*/
- }
- }
- }
- }
- if (!empty($messages)) {
- $messages = implode('<br /> ', $messages);
- } else {
- $messages = get_lang('NoAgendaItems');
- }
- return $messages;
- }
- /**
- * Parse filter turns USER:12 to ['users' => [12])] or G:1 ['groups' => [1]]
- * @param $filter
- * @return array
- */
- public function parseAgendaFilter($filter)
- {
- $everyone = false;
- $groupId = null;
- $userId = null;
- if ($filter == 'everyone') {
- $everyone = true;
- } else {
- if (substr($filter, 0, 1) == 'G') {
- $groupId = str_replace('GROUP:', '', $filter);
- } else {
- $userId = str_replace('USER:', '', $filter);
- }
- }
- if (empty($userId) && empty($groupId)) {
- $everyone = true;
- }
- return array(
- 'everyone' => $everyone,
- 'users' => array($userId),
- 'groups' => array($groupId)
- );
- }
- /**
- * This function retrieves all the agenda items of all the courses the user is subscribed to
- */
- public static function get_myagendaitems($user_id, $courses_dbs, $month, $year)
- {
- $user_id = intval($user_id);
- $items = array();
- $my_list = array();
- // get agenda-items for every course
- foreach ($courses_dbs as $key => $array_course_info) {
- //databases of the courses
- $TABLEAGENDA = Database :: get_course_table(TABLE_AGENDA);
- $TABLE_ITEMPROPERTY = Database :: get_course_table(TABLE_ITEM_PROPERTY);
- $group_memberships = GroupManager :: get_group_ids($array_course_info["real_id"], $user_id);
- $course_user_status = CourseManager::get_user_in_course_status($user_id, $array_course_info["code"]);
- // if the user is administrator of that course we show all the agenda items
- if ($course_user_status == '1') {
- //echo "course admin";
- $sqlquery = "SELECT DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
- FROM ".$TABLEAGENDA." agenda,
- ".$TABLE_ITEMPROPERTY." ip
- WHERE agenda.id = ip.ref
- AND MONTH(agenda.start_date)='".$month."'
- AND YEAR(agenda.start_date)='".$year."'
- AND ip.tool='".TOOL_CALENDAR_EVENT."'
- AND ip.visibility='1'
- GROUP BY agenda.id
- ORDER BY start_date ";
- } else {
- // if the user is not an administrator of that course
- if (is_array($group_memberships) && count($group_memberships)>0) {
- $sqlquery = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
- FROM ".$TABLEAGENDA." agenda,
- ".$TABLE_ITEMPROPERTY." ip
- WHERE agenda.id = ip.ref
- AND MONTH(agenda.start_date)='".$month."'
- AND YEAR(agenda.start_date)='".$year."'
- AND ip.tool='".TOOL_CALENDAR_EVENT."'
- AND ( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).")) )
- AND ip.visibility='1'
- ORDER BY start_date ";
- } else {
- $sqlquery = "SELECT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref
- FROM ".$TABLEAGENDA." agenda,
- ".$TABLE_ITEMPROPERTY." ip
- WHERE agenda.id = ip.ref
- AND MONTH(agenda.start_date)='".$month."'
- AND YEAR(agenda.start_date)='".$year."'
- AND ip.tool='".TOOL_CALENDAR_EVENT."'
- AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL)
- AND ip.visibility='1'
- ORDER BY start_date ";
- }
- }
- $result = Database::query($sqlquery);
- while ($item = Database::fetch_array($result, 'ASSOC')) {
- $agendaday = -1;
- if ($item['start_date'] != '0000-00-00 00:00:00') {
- $item['start_date'] = api_get_local_time($item['start_date']);
- $item['start_date_tms'] = api_strtotime($item['start_date']);
- $agendaday = date("j", $item['start_date_tms']);
- }
- if ($item['end_date'] != '0000-00-00 00:00:00') {
- $item['end_date'] = api_get_local_time($item['end_date']);
- }
- $url = api_get_path(WEB_CODE_PATH)."calendar/agenda.php?cidReq=".urlencode($array_course_info["code"])."&day=$agendaday&month=$month&year=$year#$agendaday";
- $item['url'] = $url;
- $item['course_name'] = $array_course_info['title'];
- $item['calendar_type'] = 'course';
- $item['course_id'] = $array_course_info['course_id'];
- $my_list[$agendaday][] = $item;
- }
- }
- // sorting by hour for every day
- $agendaitems = array ();
- while (list ($agendaday, $tmpitems) = each($items)) {
- if(!isset($agendaitems[$agendaday])) {
- $agendaitems[$agendaday] = '';
- }
- sort($tmpitems);
- while (list ($key, $val) = each($tmpitems)) {
- $agendaitems[$agendaday] .= $val;
- }
- }
- return $my_list;
- }
- /**
- * This function retrieves one personal agenda item returns it.
- * @param array The array containing existing events. We add to this array.
- * @param int Day
- * @param int Month
- * @param int Year (4 digits)
- * @param int Week number
- * @param string Type of view (month_view, week_view, day_view)
- * @return array The results of the database query, or null if not found
- */
- public static function get_global_agenda_items($agendaitems, $day = "", $month = "", $year = "", $week = "", $type)
- {
- $tbl_global_agenda = Database::get_main_table(
- TABLE_MAIN_SYSTEM_CALENDAR
- );
- $month = intval($month);
- $year = intval($year);
- $week = intval($week);
- $day = intval($day);
- // 1. creating the SQL statement for getting the personal agenda items in MONTH view
- $current_access_url_id = api_get_current_access_url_id();
- if ($type == "month_view" or $type == "") {
- // We are in month view
- $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";
- }
- // 2. creating the SQL statement for getting the personal agenda items in WEEK view
- if ($type == "week_view") { // we are in week view
- $start_end_day_of_week = self::calculate_start_end_of_week($week, $year);
- $start_day = $start_end_day_of_week['start']['day'];
- $start_month = $start_end_day_of_week['start']['month'];
- $start_year = $start_end_day_of_week['start']['year'];
- $end_day = $start_end_day_of_week['end']['day'];
- $end_month = $start_end_day_of_week['end']['month'];
- $end_year = $start_end_day_of_week['end']['year'];
- // in sql statements you have to use year-month-day for date calculations
- $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
- $start_filter = api_get_utc_datetime($start_filter);
- $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
- $end_filter = api_get_utc_datetime($end_filter);
- $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."' AND access_url_id = $current_access_url_id ";
- }
- // 3. creating the SQL statement for getting the personal agenda items in DAY view
- if ($type == "day_view") { // we are in day view
- // we could use mysql date() function but this is only available from 4.1 and higher
- $start_filter = $year."-".$month."-".$day." 00:00:00";
- $start_filter = api_get_utc_datetime($start_filter);
- $end_filter = $year."-".$month."-".$day." 23:59:59";
- $end_filter = api_get_utc_datetime($end_filter);
- $sql = " SELECT * FROM ".$tbl_global_agenda." WHERE start_date>='".$start_filter."' AND start_date<='".$end_filter."' AND access_url_id = $current_access_url_id";
- }
- $result = Database::query($sql);
- while ($item = Database::fetch_array($result)) {
- if ($item['start_date'] != '0000-00-00 00:00:00') {
- $item['start_date'] = api_get_local_time($item['start_date']);
- $item['start_date_tms'] = api_strtotime($item['start_date']);
- }
- if ($item['end_date'] != '0000-00-00 00:00:00') {
- $item['end_date'] = api_get_local_time($item['end_date']);
- }
- // we break the date field in the database into a date and a time part
- $agenda_db_date = explode(" ", $item['start_date']);
- $date = $agenda_db_date[0];
- $time = $agenda_db_date[1];
- // we divide the date part into a day, a month and a year
- $agendadate = explode("-", $date);
- $year = intval($agendadate[0]);
- $month = intval($agendadate[1]);
- $day = intval($agendadate[2]);
- // we divide the time part into hour, minutes, seconds
- $agendatime = explode(":", $time);
- $hour = $agendatime[0];
- $minute = $agendatime[1];
- $second = $agendatime[2];
- if ($type == 'month_view') {
- $item['calendar_type'] = 'global';
- $agendaitems[$day][] = $item;
- continue;
- }
- $start_time = api_format_date(
- $item['start_date'],
- TIME_NO_SEC_FORMAT
- );
- $end_time = '';
- if ($item['end_date'] != '0000-00-00 00:00:00') {
- $end_time = ' - '.api_format_date(
- $item['end_date'],
- DATE_TIME_FORMAT_LONG
- );
- }
- // if the student has specified a course we a add a link to that course
- if ($item['course'] <> "") {
- $url = api_get_path(
- WEB_CODE_PATH
- )."admin/agenda.php?cidReq=".urlencode(
- $item['course']
- )."&day=$day&month=$month&year=$year#$day"; // RH //Patrick Cool: to highlight the relevant agenda item
- $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
- } else {
- $course_link = "";
- }
- // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
- // if we have a day_view we use a half hour as index => key 33 = 16h30
- if ($type !== "day_view") {
- // This is the array construction for the WEEK or MONTH view
- //Display the Agenda global in the tab agenda (administrator)
- $agendaitems[$day] .= "<i>$start_time $end_time</i> - ";
- $agendaitems[$day] .= "<b>".get_lang('GlobalEvent')."</b>";
- $agendaitems[$day] .= "<div>".$item['title']."</div><br>";
- } else {
- // this is the array construction for the DAY view
- $halfhour = 2 * $agendatime['0'];
- if ($agendatime['1'] >= '30') {
- $halfhour = $halfhour + 1;
- }
- if (!is_array($agendaitems[$halfhour])) {
- $content = $agendaitems[$halfhour];
- }
- $agendaitems[$halfhour] = $content."<div><i>$hour:$minute</i> <b>".get_lang(
- 'GlobalEvent'
- ).": </b>".$item['title']."</div>";
- }
- }
- return $agendaitems;
- }
- /**
- * This function retrieves all the personal agenda items and add them to the agenda items found by the other functions.
- */
- public static function get_personal_agenda_items($user_id, $agendaitems, $day = "", $month = "", $year = "", $week = "", $type)
- {
- $tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
- $user_id = intval($user_id);
- // 1. creating the SQL statement for getting the personal agenda items in MONTH view
- if ($type == "month_view" or $type == "") {
- // we are in month view
- $sql = "SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' and MONTH(date)='".$month."' AND YEAR(date) = '".$year."' ORDER BY date ASC";
- }
- // 2. creating the SQL statement for getting the personal agenda items in WEEK view
- // we are in week view
- if ($type == "week_view") {
- $start_end_day_of_week = self::calculate_start_end_of_week($week, $year);
- $start_day = $start_end_day_of_week['start']['day'];
- $start_month = $start_end_day_of_week['start']['month'];
- $start_year = $start_end_day_of_week['start']['year'];
- $end_day = $start_end_day_of_week['end']['day'];
- $end_month = $start_end_day_of_week['end']['month'];
- $end_year = $start_end_day_of_week['end']['year'];
- // in sql statements you have to use year-month-day for date calculations
- $start_filter = $start_year."-".$start_month."-".$start_day." 00:00:00";
- $start_filter = api_get_utc_datetime($start_filter);
- $end_filter = $end_year."-".$end_month."-".$end_day." 23:59:59";
- $end_filter = api_get_utc_datetime($end_filter);
- $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
- }
- // 3. creating the SQL statement for getting the personal agenda items in DAY view
- if ($type == "day_view") {
- // we are in day view
- // we could use mysql date() function but this is only available from 4.1 and higher
- $start_filter = $year."-".$month."-".$day." 00:00:00";
- $start_filter = api_get_utc_datetime($start_filter);
- $end_filter = $year."-".$month."-".$day." 23:59:59";
- $end_filter = api_get_utc_datetime($end_filter);
- $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE user='".$user_id."' AND date>='".$start_filter."' AND date<='".$end_filter."'";
- }
- $result = Database::query($sql);
- while ($item = Database::fetch_array($result, 'ASSOC')) {
- $time_minute = api_convert_and_format_date($item['date'], TIME_NO_SEC_FORMAT);
- $item['date'] = api_get_local_time($item['date']);
- $item['start_date_tms'] = api_strtotime($item['date']);
- $item['content'] = $item['text'];
- // we break the date field in the database into a date and a time part
- $agenda_db_date = explode(" ", $item['date']);
- $date = $agenda_db_date[0];
- $time = $agenda_db_date[1];
- // we divide the date part into a day, a month and a year
- $agendadate = explode("-", $item['date']);
- $year = intval($agendadate[0]);
- $month = intval($agendadate[1]);
- $day = intval($agendadate[2]);
- // we divide the time part into hour, minutes, seconds
- $agendatime = explode(":", $time);
- $hour = $agendatime[0];
- $minute = $agendatime[1];
- $second = $agendatime[2];
- if ($type == 'month_view') {
- $item['calendar_type'] = 'personal';
- $item['start_date'] = $item['date'];
- $agendaitems[$day][] = $item;
- continue;
- }
- // if the student has specified a course we a add a link to that course
- if ($item['course'] <> "") {
- $url = api_get_path(WEB_CODE_PATH)."calendar/agenda.php?cidReq=".urlencode($item['course'])."&day=$day&month=$month&year=$year#$day"; // RH //Patrick Cool: to highlight the relevant agenda item
- $course_link = "<a href=\"$url\" title=\"".$item['course']."\">".$item['course']."</a>";
- } else {
- $course_link = "";
- }
- // Creating the array that will be returned. If we have week or month view we have an array with the date as the key
- // if we have a day_view we use a half hour as index => key 33 = 16h30
- if ($type !== "day_view") {
- // This is the array construction for the WEEK or MONTH view
- //Display events in agenda
- $agendaitems[$day] .= "<div><i>$time_minute</i> $course_link <a href=\"myagenda.php?action=view&view=personal&day=$day&month=$month&year=$year&id=".$item['id']."#".$item['id']."\" class=\"personal_agenda\">".$item['title']."</a></div><br />";
- } else {
- // this is the array construction for the DAY view
- $halfhour = 2 * $agendatime['0'];
- if ($agendatime['1'] >= '30') {
- $halfhour = $halfhour +1;
- }
- //Display events by list
- $agendaitems[$halfhour] .= "<div><i>$time_minute</i> $course_link <a href=\"myagenda.php?action=view&view=personal&day=$day&month=$month&year=$year&id=".$item['id']."#".$item['id']."\" class=\"personal_agenda\">".$item['title']."</a></div>";
- }
- }
- return $agendaitems;
- }
- /**
- * Show the monthcalender of the given month
- * @param array Agendaitems
- * @param int Month number
- * @param int Year number
- * @param array Array of strings containing long week day names (deprecated, you can send an empty array instead)
- * @param string The month name
- * @return void Direct output
- */
- public static function display_mymonthcalendar($user_id, $agendaitems, $month, $year, $weekdaynames = array(), $monthName, $show_content = true)
- {
- global $DaysShort, $course_path;
- //Handle leap year
- $numberofdays = array (0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
- if (($year % 400 == 0) or ($year % 4 == 0 and $year % 100 <> 0))
- $numberofdays[2] = 29;
- //Get the first day of the month
- $dayone = getdate(mktime(0, 0, 0, $month, 1, $year));
- //Start the week on monday
- $startdayofweek = $dayone['wday'] <> 0 ? ($dayone['wday'] - 1) : 6;
- $g_cc = (isset($_GET['courseCode'])?$_GET['courseCode']:'');
- $prev_icon = Display::return_icon('action_prev.png',get_lang('Previous'));
- $next_icon = Display::return_icon('action_next.png',get_lang('Next'));
- $next_month = ($month == 1 ? 12 : $month -1);
- $prev_month = ($month == 12 ? 1 : $month +1);
- $next_year = ($month == 1 ? $year -1 : $year);
- $prev_year = ($month == 12 ? $year +1 : $year);
- if ($show_content) {
- $back_url = Display::url($prev_icon, api_get_self()."?coursePath=".urlencode($course_path)."&courseCode=".Security::remove_XSS($g_cc)."&action=view&view=month&month=".$next_month."&year=".$next_year);
- $next_url = Display::url($next_icon, api_get_self()."?coursePath=".urlencode($course_path)."&courseCode=".Security::remove_XSS($g_cc)."&action=view&view=month&month=".$prev_month."&year=".$prev_year);
- } else {
- $back_url = Display::url($prev_icon, '', array('onclick'=>"load_calendar('".$user_id."','".$next_month."', '".$next_year."'); "));
- $next_url = Display::url($next_icon, '', array('onclick'=>"load_calendar('".$user_id."','".$prev_month."', '".$prev_year."'); "));
- }
- echo '<table id="agenda_list"><tr>';
- echo '<th width="10%">'.$back_url.'</th>';
- echo '<th width="80%" colspan="5"><br /><h3>'.$monthName." ".$year.'</h3></th>';
- echo '<th width="10%">'.$next_url.'</th>';
- echo '</tr>';
- echo '<tr>';
- for ($ii = 1; $ii < 8; $ii ++) {
- echo '<td class="weekdays">'.$DaysShort[$ii % 7].'</td>';
- }
- echo '</tr>';
- $curday = -1;
- $today = getdate();
- while ($curday <= $numberofdays[$month]) {
- echo "<tr>";
- for ($ii = 0; $ii < 7; $ii ++) {
- if (($curday == -1) && ($ii == $startdayofweek)) {
- $curday = 1;
- }
- if (($curday > 0) && ($curday <= $numberofdays[$month])) {
- $bgcolor = $class = 'class="days_week"';
- $dayheader = Display::div($curday, array('class'=>'agenda_day'));
- if (($curday == $today['mday']) && ($year == $today['year']) && ($month == $today['mon'])) {
- $class = "class=\"days_today\" style=\"width:10%;\"";
- }
- echo "<td ".$class.">".$dayheader;
- if (!empty($agendaitems[$curday])) {
- $items = $agendaitems[$curday];
- $items = msort($items, 'start_date_tms');
- foreach($items as $value) {
- $value['title'] = Security::remove_XSS($value['title']);
- $start_time = api_format_date($value['start_date'], TIME_NO_SEC_FORMAT);
- $end_time = '';
- if (!empty($value['end_date']) && $value['end_date'] != '0000-00-00 00:00:00') {
- $end_time = '- <i>'.api_format_date($value['end_date'], DATE_TIME_FORMAT_LONG).'</i>';
- }
- $complete_time = '<i>'.api_format_date($value['start_date'], DATE_TIME_FORMAT_LONG).'</i> '.$end_time;
- $time = '<i>'.$start_time.'</i>';
- switch($value['calendar_type']) {
- case 'personal':
- $bg_color = '#D0E7F4';
- $icon = Display::return_icon('user.png', get_lang('MyAgenda'), array(), ICON_SIZE_SMALL);
- break;
- case 'global':
- $bg_color = '#FFBC89';
- $icon = Display::return_icon('view_remove.png', get_lang('GlobalEvent'), array(), ICON_SIZE_SMALL);
- break;
- case 'course':
- $bg_color = '#CAFFAA';
- $icon_name = 'course.png';
- if (!empty($value['session_id'])) {
- $icon_name = 'session.png';
- }
- if ($show_content) {
- $icon = Display::url(Display::return_icon($icon_name, $value['course_name'].' '.get_lang('Course'), array(), ICON_SIZE_SMALL), $value['url']);
- } else {
- $icon = Display::return_icon($icon_name, $value['course_name'].' '.get_lang('Course'), array(), ICON_SIZE_SMALL);
- }
- break;
- default:
- break;
- }
- $result = '<div class="rounded_div_agenda" style="background-color:'.$bg_color.';">';
- if ($show_content) {
- //Setting a personal event to green
- $icon = Display::div($icon, array('style'=>'float:right'));
- $link = $value['calendar_type'].'_'.$value['id'].'_'.$value['course_id'].'_'.$value['session_id'];
- //Link to bubble
- $url = Display::url(cut($value['title'], 40), '#', array('id'=>$link, 'class'=>'opener'));
- $result .= $time.' '.$icon.' '.Display::div($url);
- //Hidden content
- $content = Display::div($icon.Display::tag('h2', $value['course_name']).'<hr />'.Display::tag('h3', $value['title']).$complete_time.'<hr />'.Security::remove_XSS($value['content']));
- //Main div
- $result .= Display::div($content, array('id'=>'main_'.$link, 'class' => 'dialog', 'style' => 'display:none'));
- $result .= '</div>';
- echo $result;
- //echo Display::div($content, array('id'=>'main_'.$value['calendar_type'].'_'.$value['id'], 'class' => 'dialog'));
- } else {
- echo $result .= $icon.'</div>';
- }
- }
- }
- echo "</td>";
- $curday ++;
- } else {
- echo "<td></td>";
- }
- }
- echo "</tr>";
- }
- echo "</table>";
- }
- /**
- * Get personal agenda items between two dates (=all events from all registered courses)
- * @param int user ID of the user
- * @param string Optional start date in datetime format (if no start date is given, uses today)
- * @param string Optional end date in datetime format (if no date is given, uses one year from now)
- * @return array Array of events ordered by start date, in
- * [0]('datestart','dateend','title'),[1]('datestart','dateend','title','link','coursetitle') format,
- * where datestart and dateend are in yyyyMMddhhmmss format.
- * @TODO Implement really personal events (from user DB) and global events (from main DB)
- */
- public static function get_personal_agenda_items_between_dates($user_id, $date_start='', $date_end='')
- {
- $items = array ();
- if ($user_id != strval(intval($user_id))) { return $items; }
- if (empty($date_start)) { $date_start = date('Y-m-d H:i:s');}
- if (empty($date_end)) { $date_end = date('Y-m-d H:i:s',mktime(0, 0, 0, date("m"), date("d"), date("Y")+1));}
- $expr = '/\d{4}-\d{2}-\d{2}\ \d{2}:\d{2}:\d{2}/';
- if(!preg_match($expr,$date_start)) { return $items; }
- if(!preg_match($expr,$date_end)) { return $items; }
- // get agenda-items for every course
- $courses = api_get_user_courses($user_id,false);
- foreach ($courses as $id => $course) {
- $c = api_get_course_info_by_id($course['real_id']);
- //databases of the courses
- $t_a = Database :: get_course_table(TABLE_AGENDA, $course['db']);
- $t_ip = Database :: get_course_table(TABLE_ITEM_PROPERTY, $course['db']);
- // get the groups to which the user belong
- $group_memberships = GroupManager :: get_group_ids($course['db'], $user_id);
- // if the user is administrator of that course we show all the agenda items
- if ($course['status'] == '1') {
- //echo "course admin";
- $sqlquery = "SELECT ".
- " DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
- " FROM ".$t_a." agenda, ".
- $t_ip." ip ".
- " WHERE agenda.id = ip.ref ".
- " AND agenda.start_date>='$date_start' ".
- " AND agenda.end_date<='$date_end' ".
- " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
- " AND ip.visibility='1' ".
- " GROUP BY agenda.id ".
- " ORDER BY start_date ";
- } else {
- // if the user is not an administrator of that course, then...
- if (is_array($group_memberships) && count($group_memberships)>0)
- {
- $sqlquery = "SELECT " .
- "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
- " FROM ".$t_a." agenda, ".
- $t_ip." ip ".
- " WHERE agenda.id = ip.ref ".
- " AND agenda.start_date>='$date_start' ".
- " AND agenda.end_date<='$date_end' ".
- " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
- " AND ( ip.to_user_id='".$user_id."' OR (ip.to_group_id IS NULL OR ip.to_group_id IN (0, ".implode(", ", $group_memberships).")) ) ".
- " AND ip.visibility='1' ".
- " ORDER BY start_date ";
- } else {
- $sqlquery = "SELECT ".
- "DISTINCT agenda.*, ip.visibility, ip.to_group_id, ip.insert_user_id, ip.ref ".
- " FROM ".$t_a." agenda, ".
- $t_ip." ip ".
- " WHERE agenda.id = ip.ref ".
- " AND agenda.start_date>='$date_start' ".
- " AND agenda.end_date<='$date_end' ".
- " AND ip.tool='".TOOL_CALENDAR_EVENT."' ".
- " AND ( ip.to_user_id='".$user_id."' OR ip.to_group_id='0' OR ip.to_group_id IS NULL) ".
- " AND ip.visibility='1' ".
- " ORDER BY start_date ";
- }
- }
- $result = Database::query($sqlquery);
- while ($item = Database::fetch_array($result)) {
- $agendaday = date("j",strtotime($item['start_date']));
- $month = date("n",strtotime($item['start_date']));
- $year = date("Y",strtotime($item['start_date']));
- $URL = api_get_path(WEB_PATH)."main/calendar/agenda.php?cidReq=".urlencode($course["code"])."&day=$agendaday&month=$month&year=$year#$agendaday";
- list($year,$month,$day,$hour,$min,$sec) = split('[-: ]',$item['start_date']);
- $start_date = $year.$month.$day.$hour.$min;
- list($year,$month,$day,$hour,$min,$sec) = split('[-: ]',$item['end_date']);
- $end_date = $year.$month.$day.$hour.$min;
- $items[] = array(
- 'datestart'=>$start_date,
- 'dateend'=>$end_date,
- 'title'=>$item['title'],
- 'link'=>$URL,
- 'coursetitle'=>$c['name'],
- );
- }
- }
- return $items;
- }
- /**
- * This function retrieves one personal agenda item returns it.
- * @param int The agenda item ID
- * @return array The results of the database query, or null if not found
- */
- public static function get_personal_agenda_item($id)
- {
- $tbl_personal_agenda = Database :: get_main_table(TABLE_PERSONAL_AGENDA);
- $id = intval($id);
- // make sure events of the personal agenda can only be seen by the user himself
- $user = api_get_user_id();
- $sql = " SELECT * FROM ".$tbl_personal_agenda." WHERE id=".$id." AND user = ".$user;
- $result = Database::query($sql);
- if(Database::num_rows($result)==1) {
- $item = Database::fetch_array($result);
- } else {
- $item = null;
- }
- return $item;
- }
- /**
- * This function calculates the startdate of the week (monday)
- * and the enddate of the week (sunday)
- * and returns it as an array
- */
- public static function calculate_start_end_of_week($week_number, $year)
- {
- // determine the start and end date
- // step 1: we calculate a timestamp for a day in this week
- $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
- // step 2: we which day this is (0=sunday, 1=monday, ...)
- $number_day_in_week = date('w', $random_day_in_week);
- // step 3: we calculate the timestamp of the monday of the week we are in
- $start_timestamp = $random_day_in_week - (($number_day_in_week -1) * 24 * 60 * 60);
- // step 4: we calculate the timestamp of the sunday of the week we are in
- $end_timestamp = $random_day_in_week + ((7 - $number_day_in_week +1) * 24 * 60 * 60) - 3600;
- // step 5: calculating the start_day, end_day, start_month, end_month, start_year, end_year
- $start_day = date('j', $start_timestamp);
- $start_month = date('n', $start_timestamp);
- $start_year = date('Y', $start_timestamp);
- $end_day = date('j', $end_timestamp);
- $end_month = date('n', $end_timestamp);
- $end_year = date('Y', $end_timestamp);
- $start_end_array['start']['day'] = $start_day;
- $start_end_array['start']['month'] = $start_month;
- $start_end_array['start']['year'] = $start_year;
- $start_end_array['end']['day'] = $end_day;
- $start_end_array['end']['month'] = $end_month;
- $start_end_array['end']['year'] = $end_year;
- return $start_end_array;
- }
- /**
- * @return bool
- */
- public function getIsAllowedToEdit()
- {
- return $this->isAllowedToEdit;
- }
- /**
- * @param bool $isAllowedToEdit
- */
- public function setIsAllowedToEdit($isAllowedToEdit)
- {
- $this->isAllowedToEdit = $isAllowedToEdit;
- }
- }
|