private static function row2array($row, $timezone, $hostname, $uid, $namespace_id) { $v = new vcalendar(); $v->setConfig('unique_id', $hostname); $v->setProperty('method', 'PUBLISH'); $v->setProperty("x-wr-calname", "AnimexxCal"); $v->setProperty("X-WR-CALDESC", "Animexx Calendar"); $v->setProperty("X-WR-TIMEZONE", $timezone); if ($row["adjust"]) { $start = datetime_convert('UTC', date_default_timezone_get(), $row["start"]); $finish = datetime_convert('UTC', date_default_timezone_get(), $row["finish"]); } else { $start = $row["start"]; $finish = $row["finish"]; } $allday = strpos($start, "00:00:00") !== false && strpos($finish, "00:00:00") !== false; /* if ($allday) { $dat = Datetime::createFromFormat("Y-m-d H:i:s", $finish_tmp); $dat->sub(new DateInterval("P1D")); $finish = datetime_convert("UTC", date_default_timezone_get(), $dat->format("Y-m-d H:i:s")); var_dump($finish); } */ $subject = substr(preg_replace("/\\[[^\\]]*\\]/", "", $row["desc"]), 0, 100); $description = preg_replace("/\\[[^\\]]*\\]/", "", $row["desc"]); $vevent = dav_create_vevent(wdcal_mySql2icalTime($row["start"]), wdcal_mySql2icalTime($row["finish"]), false); $vevent->setLocation(icalendar_sanitize_string($row["location"])); $vevent->setSummary(icalendar_sanitize_string($subject)); $vevent->setDescription(icalendar_sanitize_string($description)); $v->setComponent($vevent); $ical = $v->createCalendar(); return array("uid" => $uid, "namespace" => CALDAV_NAMESPACE_FRIENDICA_NATIVE, "namespace_id" => $namespace_id, "date" => $row["edited"], "data_uri" => "friendica-" . $namespace_id . "-" . $row["id"] . "@" . $hostname, "data_subject" => $subject, "data_location" => $row["location"], "data_description" => $description, "data_start" => $start, "data_end" => $finish, "data_allday" => $allday, "data_type" => $row["type"], "ical" => $ical, "ical_size" => strlen($ical), "ical_etag" => md5($ical)); }
public function ical($params) { $this->setView('ical.php'); $official = isset($params['official']); $group_name = isset($params['group']) ? $params['group'] : null; $event_model = new Event_Model(); $events = $event_model->getUpcoming($group_name, $official, false); // Creation of the iCal content $cache_entry = 'ical-' . (isset($group_name) ? $group_name : '') . '-' . ($official ? 'official' : 'non-official'); $content = Cache::read($cache_entry); if (!$content) { require_once APP_DIR . 'classes/class.iCalcreator.php'; $cal = new vcalendar(); $cal->setConfig('unique_id', $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']); $cal->setProperty('method', 'PUBLISH'); $cal->setProperty('x-wr-calname', $official ? __('EVENTS_TITLE_OFFICIAL') : __('EVENTS_TITLE_NONOFFICIAL')); $cal->setProperty('X-WR-CALDESC', ''); $cal->setProperty('X-WR-TIMEZONE', date('e')); foreach ($events as $event) { $vevent = new vevent(); $vevent->setProperty('dtstart', array('year' => (int) date('Y', $event['date_start']), 'month' => (int) date('n', $event['date_start']), 'day' => (int) date('j', $event['date_start']), 'hour' => (int) date('G', $event['date_start']), 'min' => (int) date('i', $event['date_start']), 'sec' => (int) date('s', $event['date_start']))); $vevent->setProperty('dtend', array('year' => (int) date('Y', $event['date_end']), 'month' => (int) date('n', $event['date_end']), 'day' => (int) date('j', $event['date_end']), 'hour' => (int) date('G', $event['date_end']), 'min' => (int) date('i', $event['date_end']), 'sec' => (int) date('s', $event['date_end']))); $vevent->setProperty('summary', $event['title']); $vevent->setProperty('description', $event['message']); $cal->setComponent($vevent); } $content = $cal->createCalendar(); Cache::write($cache_entry, $content, 2 * 3600); } $this->set('content', $content); }
$e->setProperty('rrule', array('FREQ' => 'YEARLY')); $c->setComponent($e); $str = $c->createCalendar(); echo $str; echo "<br />\n\n"; /* * BEGIN:VTODO * UID:19970901T130000Z-123404@host.com * DTSTAMP:19970901T1300Z * DTSTART:19970415T133000Z * DUE:19970416T045959Z * SUMMARY:1996 Income Tax Preparation * CLASS:CONFIDENTIAL * CATEGORIES:FAMILY,FINANCE * PRIORITY:1 * STATUS:NEEDS-ACTION * END:VTODO */ $c = new vcalendar(); $t = new vtodo(); $t->setProperty('dtstart', '19970415T133000 GMT'); $t->setProperty('due', '19970416T045959 GMT'); $t->setProperty('summary', '1996 Income Tax Preparation'); $t->setProperty('class', 'CONFIDENTIAL'); $t->setProperty('categories', 'FAMILY'); $t->setProperty('categories', 'FINANCE'); $t->setProperty('priority', 1); $t->setProperty('status', 'NEEDS-ACTION'); $c->setComponent($t); $str = $c->createCalendar(); echo $str;
/** * toICS() * * Outputs group schedules in ICS format */ function toICS() { require_once BPSP_PLUGIN_DIR . '/schedules/iCalcreator.class.php'; global $bp; define('ICAL_LANG', get_bloginfo('language')); $cal = new vcalendar(); $cal->setConfig('unique_id', str_replace('http://', '', get_bloginfo('siteurl'))); $cal->setConfig('filename', $bp->groups->current_group->slug); $cal->setProperty('X-WR-CALNAME', __('Calendar for: ', 'bpsp') . $bp->groups->current_group->name); $cal->setProperty('X-WR-CALDESC', $bp->groups->current_group->description); $cal->setProperty('X-WR-TIMEZONE', get_option('timezone_string')); $schedules = $this->has_schedules(); $assignments = BPSP_Assignments::has_assignments(); $entries = array_merge($assignments, $schedules); foreach ($entries as $entry) { setup_postdata($entry); $e = new vevent(); if ($entry->post_type == "schedule") { $date = getdate(strtotime($entry->start_date)); } elseif ($entry->post_type == "assignment") { $date = getdate(strtotime($entry->post_date)); } $dtstart['year'] = $date['year']; $dtstart['month'] = $date['mon']; $dtstart['day'] = $date['mday']; $dtstart['hour'] = $date['hours']; $dtstart['min'] = $date['minutes']; $dtstart['sec'] = $date['seconds']; $e->setProperty('dtstart', $dtstart); $e->setProperty('description', get_the_content() . "\n\n" . $entry->permalink); if (!empty($entry->location)) { $e->setProperty('location', $entry->location); } if ($entry->post_type == "assignment") { $entry->end_date = $entry->due_date; } // make assignments compatible with schedule parser if (!empty($entry->end_date)) { $date = getdate(strtotime($entry->end_date)); $dtend['year'] = $date['year']; $dtend['month'] = $date['mon']; $dtend['day'] = $date['mday']; $dtend['hour'] = $date['hours']; $dtend['min'] = $date['minutes']; $dtend['sec'] = $date['seconds']; $e->setProperty('dtend', $dtend); } else { $e->setProperty('duration', 0, 1, 0); } // Assume it's an one day event $e->setProperty('summary', get_the_title($entry->ID)); $e->setProperty('status', 'CONFIRMED'); $cal->setComponent($e); } header("HTTP/1.1 200 OK"); die($cal->returnCalendar()); }
/** * @param array $start * @param array $end * @param string $subject * @param bool $allday * @param string $description * @param string $location * @param null $color * @param string $timezone * @param bool $notification * @param null $notification_type * @param null $notification_value * @return array|string */ public function addItem($start, $end, $subject, $allday = false, $description = "", $location = "", $color = null, $timezone = "", $notification = true, $notification_type = null, $notification_value = null) { $a = get_app(); $v = new vcalendar(); $v->setConfig('unique_id', $a->get_hostname()); $v->setProperty('method', 'PUBLISH'); $v->setProperty("x-wr-calname", "AnimexxCal"); $v->setProperty("X-WR-CALDESC", "Animexx Calendar"); $v->setProperty("X-WR-TIMEZONE", $a->timezone); $vevent = dav_create_vevent($start, $end, $allday); $vevent->setLocation(icalendar_sanitize_string($location)); $vevent->setSummary(icalendar_sanitize_string($subject)); $vevent->setDescription(icalendar_sanitize_string($description)); if (!is_null($color) && $color >= 0) { $vevent->setProperty("X-ANIMEXX-COLOR", $color); } if ($notification && $notification_type == null) { if ($allday) { $notification_type = "hour"; $notification_value = 24; } else { $notification_type = "minute"; $notification_value = 60; } } if ($notification) { $valarm = new valarm(); $valarm->setTrigger($notification_type == "year" ? $notification_value : 0, $notification_type == "month" ? $notification_value : 0, $notification_type == "day" ? $notification_value : 0, $notification_type == "week" ? $notification_value : 0, $notification_type == "hour" ? $notification_value : 0, $notification_type == "minute" ? $notification_value : 0, $notification_type == "second" ? $notification_value : 0, true, $notification_value > 0); $valarm->setAction("DISPLAY"); $valarm->setDescription($subject); $vevent->setComponent($valarm); } $v->setComponent($vevent); $ical = $v->createCalendar(); $obj_id = trim($vevent->getProperty("UID")); $calendarBackend = new Sabre_CalDAV_Backend_Std(); $calendarBackend->createCalendarObject($this->getNamespace() . "-" . $this->namespace_id, $obj_id . ".ics", $ical); return $obj_id . ".ics"; }
/** * Prepare output in icalendar format a la RFC2445 * http://www.ietf.org/rfc/rfc2445.txt * * @return string */ public function icalendar() { $s = 'EJURI3ia8aj#912IKa'; $r = '#'; $e = 'aAEah38a;a33'; // ------------------------------------- // Some dummy tagdata we'll hand off to events() // ------------------------------------- $vars = array('event_title' => 'title', 'event_id' => 'id', 'event_summary' => 'summary', 'event_location' => 'location', 'event_start_date format="%Y"' => 'start_year', 'event_start_date format="%m"' => 'start_month', 'event_start_date format="%d"' => 'start_day', 'event_start_date format="%H"' => 'start_hour', 'event_start_date format="%i"' => 'start_minute', 'event_end_date format="%Y"' => 'end_year', 'event_end_date format="%m"' => 'end_month', 'event_end_date format="%d"' => 'end_day', 'event_end_date format="%H"' => 'end_hour', 'event_end_date format="%i"' => 'end_minute', 'event_calendar_tz_offset' => 'tz_offset', 'event_calendar_timezone' => 'timezone'); $rvars = array('rule_type', 'rule_start_date', 'rule_repeat_years', 'rule_repeat_months', 'rule_repeat_days', 'rule_repeat_weeks', 'rule_days_of_week', 'rule_relative_dow', 'rule_days_of_month', 'rule_months_of_year', 'rule_stop_by', 'rule_stop_after'); $evars = array('exception_start_date format="%Y%m%dT%H%i00"'); $ovars = array('occurrence_start_date format="%Y%m%dT%H%i00"', 'occurrence_end_date format="%Y%m%dT%H%i00"'); //ee()->TMPL->log_item('Calendar: Preparing tagdata'); $summary_field = ee()->TMPL->fetch_param('summary_field', 'event_title'); ee()->TMPL->tagdata = implode($s, array(LD . $summary_field . RD, LD . 'event_id' . RD, LD . 'if event_summary' . RD . LD . 'event_summary' . RD . LD . '/if' . RD, LD . 'if event_location' . RD . LD . 'event_location' . RD . LD . '/if' . RD, LD . 'event_start_date format="%Y"' . RD, LD . 'event_start_date format="%m"' . RD, LD . 'event_start_date format="%d"' . RD, LD . 'event_start_date format="%H"' . RD, LD . 'event_start_date format="%i"' . RD, LD . 'event_end_date format="%Y"' . RD, LD . 'event_end_date format="%m"' . RD, LD . 'event_end_date format="%d"' . RD, LD . 'event_end_date format="%H"' . RD, LD . 'event_end_date format="%i"' . RD, LD . 'event_calendar_tz_offset' . RD, LD . 'event_calendar_timezone' . RD, 'RULES' . LD . 'if event_has_rules' . RD . LD . 'rules' . RD . LD . implode(RD . $r . LD, $rvars) . RD . '|' . LD . T_SLASH . 'rules' . RD . LD . '/if' . RD, 'OCCURRENCES' . LD . 'if event_has_occurrences' . RD . LD . 'occurrences' . RD . LD . implode(RD . $r . LD, $ovars) . RD . '|' . LD . T_SLASH . 'occurrences' . RD . LD . '/if' . RD, 'EXCEPTIONS' . LD . 'if event_has_exceptions' . RD . LD . 'exceptions' . RD . LD . implode(RD . $r . LD, $evars) . RD . '|' . LD . T_SLASH . 'exceptions' . RD . LD . '/if' . RD, $e)); $tvars = ee()->functions->assign_variables(ee()->TMPL->tagdata); ee()->TMPL->var_single = $tvars['var_single']; ee()->TMPL->var_pair = $tvars['var_pair']; ee()->TMPL->tagdata = ee()->functions->prep_conditionals(ee()->TMPL->tagdata, array_keys($vars)); // ------------------------------------- // Fire up events() // ------------------------------------- //ee()->TMPL->log_item('Calendar: Firing up Events()'); $tagdata = ee()->TMPL->advanced_conditionals($this->events()); // ------------------------------------- // Collect the events // ------------------------------------- //ee()->TMPL->log_item('Calendar: Collecting events'); $events = explode($e, $tagdata); // ------------------------------------- // Fire up iCalCreator // ------------------------------------- //ee()->TMPL->log_item('Calendar: Starting iCalCreator'); if (!class_exists('vcalendar')) { require_once 'libraries/icalcreator/iCalcreator.class.php'; } $ICAL = new vcalendar(); //we are setting this manually because we need individual ones for each event for this to work //$ICAL->setConfig('unique_id', parse_url(ee()->config->item('site_url'), PHP_URL_HOST)); $host = parse_url(ee()->config->item('site_url'), PHP_URL_HOST); $vars = array_values($vars); //ee()->TMPL->log_item('Calendar: Iterating through the events'); foreach ($events as $key => $event) { if (trim($event) == '') { continue; } $E = new vevent(); $event = explode($s, $event); $rules = ''; $occurrences = ''; $exceptions = ''; foreach ($event as $k => $v) { if (isset($vars[$k])) { //-------------------------------------------- // Makes the local vars from above, if available: // $title, $summary, $location, // $start_year, $start_month, $start_day, // $start_hour, $start_minute, $end_year, // $end_month, $end_day, $end_hour, // $end_minute, $tz_offset, $timezone //-------------------------------------------- ${$vars}[$k] = $v; } elseif (substr($v, 0, 5) == 'RULES') { $rules = substr($v, 5); } elseif (substr($v, 0, 11) == 'OCCURRENCES') { $occurrences = substr($v, 11); } elseif (substr($v, 0, 10) == 'EXCEPTIONS') { $exceptions = substr($v, 10); } } // ------------------------------------- // Set the timezone for this calendar based on the first event's info // ------------------------------------- if ($key == 0) { // ------------------------------------- // Convert calendar_name to calendar_id // ------------------------------------- if ($this->P->value('calendar_id') == '' and $this->P->value('calendar_name') != '') { $ids = $this->data->get_calendar_id_from_name($this->P->value('calendar_name'), NULL, $this->P->params['calendar_name']['details']['not']); $this->P->set('calendar_id', implode('|', $ids)); } //-------------------------------------------- // lets try to get the timezone from the // passed calendar ID if there is one //-------------------------------------------- $cal_timezone = FALSE; $cal_tz_offset = FALSE; if ($this->P->value('calendar_id') != '') { $sql = "SELECT \ttz_offset, timezone\n\t\t\t\t\t\t\tFROM\texp_calendar_calendars\n\t\t\t\t\t\t\tWHERE \tcalendar_id\n\t\t\t\t\t\t\tIN \t\t(" . ee()->db->escape_str(implode(',', explode('|', $this->P->value('calendar_id')))) . ")\n\t\t\t\t\t\t\tLIMIT\t1"; $cal_tz_query = ee()->db->query($sql); if ($cal_tz_query->num_rows() > 0) { $cal_timezone = $cal_tz_query->row('timezone'); $cal_tz_offset = $cal_tz_query->row('tz_offset'); } } //last resort, we get it from the current event $T = new vtimezone(); $T->setProperty('tzid', $cal_timezone ? $cal_timezone : $timezone); $T->setProperty('tzoffsetfrom', '+0000'); $tzoffsetto = $cal_tz_offset ? $cal_tz_offset : $tz_offset; if ($tzoffsetto === '0000') { $tzoffsetto = '+0000'; } $T->setProperty('tzoffsetto', $tzoffsetto); $ICAL->setComponent($T); } $title = strip_tags($title); $description = strip_tags(trim($summary)); $location = strip_tags(trim($location)); // ------------------------------------- // Occurrences? // ------------------------------------- $occurrences = explode('|', rtrim($occurrences, '|')); $odata = array(); foreach ($occurrences as $k => $occ) { $occ = trim($occ); if ($occ == '') { continue; } $occ = explode($r, $occ); $odata[$k][] = $occ[0]; $odata[$k][] = $occ[1]; } // ------------------------------------- // Exceptions? // ------------------------------------- $exceptions = explode('|', rtrim($exceptions, '|')); $exdata = array(); foreach ($exceptions as $k => $exc) { $exc = trim($exc); if ($exc == '') { continue; } $exdata[] = $exc; } // ------------------------------------- // Rules? // ------------------------------------- $add_rules = FALSE; $erules = array(); $rules = explode('|', rtrim($rules, '|')); foreach ($rules as $rule) { $temp = explode($r, $rule); $rule = array(); foreach ($temp as $k => $v) { if ($v != FALSE) { $add_rules = TRUE; } $rule[substr($rvars[$k], 5)] = $v; } if ($add_rules === TRUE) { $temp = array(); if ($rule['repeat_years'] > 0) { $temp['FREQ'] = 'YEARLY'; if ($rule['repeat_years'] > 1) { $temp['INTERVAL'] = $rule['repeat_years']; } } elseif ($rule['repeat_months'] > 0) { $temp['FREQ'] = 'MONTHLY'; if ($rule['repeat_months'] > 1) { $temp['INTERVAL'] = $rule['repeat_months']; } } elseif ($rule['repeat_weeks'] > 0) { $temp['FREQ'] = 'WEEKLY'; if ($rule['repeat_weeks'] > 1) { $temp['INTERVAL'] = $rule['repeat_weeks']; } } elseif ($rule['repeat_days'] > 0) { $temp['FREQ'] = 'DAILY'; if ($rule['repeat_days'] > 1) { $temp['INTERVAL'] = $rule['repeat_days']; } } if ($rule['months_of_year'] > 0) { //this flips keys to make 'c' => 12, etc $m = array_flip(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C')); if (strlen($rule['months_of_year'] > 1)) { $months = str_split($rule['months_of_year']); foreach ($months as $month) { $temp['BYMONTH'][] = $m[$month] + 1; } } else { $temp['BYMONTH'] = $m[$month] + 1; } } if ($rule['days_of_month'] > '') { //this flips keys to make 'v' => 30, etc $d = array_flip(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V')); if (strlen($rule['days_of_month']) > 1) { $days = str_split($rule['days_of_month']); foreach ($days as $day) { $temp['BYMONTHDAY'][] = $d[$day] + 1; } } else { $temp['BYMONTHDAY'] = $d[$rule['days_of_month']] + 1; } } if ($rule['days_of_week'] != '' or $rule['days_of_week'] > 0) { $d = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'); $d_letter = array('U', 'M', 'T', 'W', 'R', 'F', 'S'); $dows = str_split($rule['days_of_week']); if ($rule['relative_dow'] > 0) { $rels = str_split($rule['relative_dow']); foreach ($dows as $dow) { foreach ($rels as $rel) { if ($rel == 6) { $rel = -1; } $temp['BYDAY'][] = $rel . $d[array_search($dow, $d_letter)]; } } } else { foreach ($dows as $dow) { $temp['BYDAY'][] = $d[array_search($dow, $d_letter)]; } } } if ($rule['stop_after'] > 0) { $temp['COUNT'] = $rule['stop_after']; } elseif ($rule['stop_by'] > 0) { // TODO: Add time // TODO: The "+1" below is because the ical standard treats // UNTIL as "less than", not "less than or equal to" (which // is how Calendar treats stop_by). Double check that a simple // "+1" accurately addresses this difference. $temp['UNTIL'] = $rule['stop_by'] + 1; } $erules[] = $temp; } } // ------------------------------------- // Put it together // ------------------------------------- //if this is all day we need to add the dates as params to the dstart and end items if ($this->_is_all_day($start_hour, $start_minute, $end_hour, $end_minute)) { $E->setProperty("dtstart", array('year' => $start_year, 'month' => $start_month, 'day' => $start_day), array('VALUE' => 'DATE')); //-------------------------------------------- // we need CDT so we can add a day // gcal, and ical are ok with this being the same day // stupid damned outlook barfs, hence the +1 // the +1 doesnt affect g/ical //-------------------------------------------- if (!isset($this->CDT) or !is_object($this->CDT)) { $this->load_calendar_datetime(); } $this->CDT->change_date($end_year, $end_month, $end_day); $this->CDT->add_day(); $E->setProperty("dtend", array('year' => $this->CDT->year, 'month' => $this->CDT->month, 'day' => $this->CDT->day), array('VALUE' => 'DATE')); } else { $E->setProperty('dtstart', $start_year, $start_month, $start_day, $start_hour, $start_minute, 00); $E->setProperty('dtend', $end_year, $end_month, $end_day, $end_hour, $end_minute, 00); } $E->setProperty('summary', $title); if (!empty($erules)) { foreach ($erules as $rule) { $E->setProperty('rrule', $rule); } } $extras = array(); $edits = array(); if (!empty($odata)) { $query = ee()->db->query("SELECT *\n\t\t\t\t\t FROM\texp_calendar_events_occurrences\n\t\t\t\t\t WHERE\tevent_id = " . ee()->db->escape_str($id)); foreach ($query->result_array() as $row) { //fix blank times $row['start_time'] = $row['start_time'] == 0 ? '0000' : $row['start_time']; $row['end_time'] = $row['end_time'] == 0 ? '2400' : $row['end_time']; //looks like an edited occurrence //edits without rules arent really edits. if ($row['event_id'] != $row['entry_id'] and empty($rules)) { $edits[] = $row; } else { $extras[] = $row; } } } if (!empty($exdata)) { $E->setProperty('exdate', $exdata); } if ($description != '') { $E->setProperty('description', $description); } if ($location != '') { $E->setProperty('location', $location); } $E->setProperty("uid", $this->make_uid() . '@' . $host); $ICAL->setComponent($E); //-------------------------------------------- // remove rules for subsequent items //-------------------------------------------- while ($E->deleteProperty("RRULE")) { continue; } //edits must come right after if (!empty($edits)) { foreach ($edits as $edit) { $edit_date = array("year" => $edit['start_year'], "month" => $edit['start_month'], "day" => $edit['start_day'], "hour" => substr($edit['start_time'], 0, 2), "min" => substr($edit['start_time'], 2, 2)); //if this is all day we need to add the dates as params to the dstart and end items if ($this->_is_all_day(substr($edit['start_time'], 0, 2), substr($edit['start_time'], 2, 2), substr($edit['end_time'], 0, 2), substr($edit['end_time'], 2, 2))) { $E->setProperty("dtstart", array('year' => $edit['start_year'], 'month' => $edit['start_month'], 'day' => $edit['start_day']), array('VALUE' => 'DATE')); //-------------------------------------------- // we need CDT so we can add a day // gcal, and ical are ok with this being the same day // stupid damned outlook barfs, hence the +1 // the +1 doesnt affect g/ical //-------------------------------------------- if (!isset($this->CDT) or !is_object($this->CDT)) { $this->load_calendar_datetime(); } $this->CDT->change_date($edit['end_year'], $edit['end_month'], $edit['end_day']); $this->CDT->add_day(); $E->setProperty("dtend", array('year' => $this->CDT->year, 'month' => $this->CDT->month, 'day' => $this->CDT->day), array('VALUE' => 'DATE')); } else { $E->setProperty('dtstart', $edit_date['year'], $edit_date['month'], $edit_date['day'], $edit_date['hour'], $edit_date['min'], 00); $E->setProperty('dtend', $edit['end_year'], $edit['end_month'], $edit['end_day'], substr($edit['end_time'], 0, 2), substr($edit['end_time'], 2, 2), 00); } $E->setProperty("RECURRENCE-ID", $edit_date); $E->setProperty("uid", $this->make_uid() . '@' . $host); $ICAL->setComponent($E); } //cleanup $E->deleteProperty("RECURRENCE-ID"); $E->setProperty('dtstart', $start_year, $start_month, $start_day, $start_hour, $start_minute, 00); $E->setProperty('dtend', $end_year, $end_month, $end_day, $end_hour, $end_minute, 00); } // these random ass add-in dates are non-standard to most cal creation // and need to be treated seperately as lumping don't work, dog if (!empty($extras)) { foreach ($extras as $extra) { //if this is all day we need to add the dates as params to the dstart and end items if ($this->_is_all_day(substr($extra['start_time'], 0, 2), substr($extra['start_time'], 2, 2), substr($extra['end_time'], 0, 2), substr($extra['end_time'], 2, 2))) { $E->setProperty("dtstart", array('year' => $extra['start_year'], 'month' => $extra['start_month'], 'day' => $extra['start_day']), array('VALUE' => 'DATE')); //-------------------------------------------- // we need CDT so we can add a day // gcal, and ical are ok with this being the same day // stupid damned outlook barfs, hence the +1 // the +1 doesnt affect g/ical //-------------------------------------------- if (!isset($this->CDT) or !is_object($this->CDT)) { $this->load_calendar_datetime(); } $this->CDT->change_date($extra['end_year'], $extra['end_month'], $extra['end_day']); $this->CDT->add_day(); $E->setProperty("dtend", array('year' => $this->CDT->year, 'month' => $this->CDT->month, 'day' => $this->CDT->day), array('VALUE' => 'DATE')); } else { $E->setProperty('dtstart', $extra['start_year'], $extra['start_month'], $extra['start_day'], substr($extra['start_time'], 0, 2), substr($extra['start_time'], 2, 2), 00); $E->setProperty('dtend', $extra['end_year'], $extra['end_month'], $extra['end_day'], substr($extra['end_time'], 0, 2), substr($extra['end_time'], 2, 2), 00); } $E->setProperty("uid", $this->make_uid() . '@' . $host); $ICAL->setComponent($E); } //clean in case we need to add more later $E->setProperty('dtstart', $start_year, $start_month, $start_day, $start_hour, $start_minute, 00); $E->setProperty('dtend', $end_year, $end_month, $end_day, $end_hour, $end_minute, 00); } } //return $ICAL->createCalendar(); return $ICAL->returnCalendar(); }
function send_iCal($entry_id) { global $login; // ## Getting entry $entry = getEntry($entry_id); if (!count($entry)) { return FALSE; } $description = template_ical($entry); // ## Making iCal-element $c = new vcalendar(); $e = new vevent(); $e->setProperty('dtstart', date('Y', $entry['time_start']), date('m', $entry['time_start']), date('d', $entry['time_start']), date('H', $entry['time_start']), date('i', $entry['time_start']), date('s', $entry['time_start'])); $e->setProperty('dtend', date('Y', $entry['time_end']), date('m', $entry['time_end']), date('d', $entry['time_end']), date('H', $entry['time_end']), date('i', $entry['time_end']), date('s', $entry['time_end'])); $e->setProperty('summary', $entry['entry_name']); $e->setProperty('class', 'PUBLIC'); $e->setProperty('description', $description); $e->setProperty('UID', 'entry' . $entry['entry_id'] . '@booking.jaermuseet.no'); $c->setProperty('method', 'REQUEST'); $c->setComponent($e); $ical = str_replace('DTSTART', 'X-GWITEM-TYPE:APPOINTMENT' . chr(10) . 'DTSTART', $c->createCalendar()); // ## Sending mail // Need to find who we are sending it to $users = array(); foreach ($entry['user_assigned'] as $user_id) { $user = getUser($user_id); if (count($user)) { $users[$user_id] = $user['user_email']; } } // Sending to the users foreach ($users as $user_mail) { $rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$rand}x"; $subject = 'Stadfesting av bestilling - ' . date('d-m-Y', $entry['time_start']) . ': ' . $entry['entry_name']; if (isset($login['user_email']) && $login['user_email'] != '') { $headers = 'From: ' . $login['user_email']; } else { $headers = 'From: ' . constant('EMAIL_FROM'); } // Add the headers for a file attachment $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; // Add a multipart boundary above the plain message $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . "{$description}\n\n"; // iCal $message .= "--{$mime_boundary}\n" . "Content-class: urn:content-classes:calendarmessage\n" . "Content-type: text/calendar; method=REQUEST; name=meeting.ics; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n"; $message .= $ical; $message .= "\n--{$mime_boundary}--"; $ok = mail($user_mail, $subject, $message, $headers); $ok = true; if (!$ok) { // TODO: Error handling for mail not sent echo 'Faild sending mail. Please contact somebody!!'; exit; } else { // It's okey... } } // ## Loging iCal sending // TODO: Log iCal sending return TRUE; }
$M2 = $M2 - 60; $h2 += 1; } } else { list($y2, $m2, $d2, $h2, $M2, $s2) = preg_split('/[\\s:-]/', $event['end_date']); } $vevent->setProperty('dtend', array('year' => $y2, 'month' => $m2, 'day' => $d2, 'hour' => $h2, 'min' => $M2, 'sec' => $s2)); //$vevent->setProperty( 'LOCATION', get_lang('Unknown') ); // property name - case independent $vevent->setProperty('description', api_convert_encoding($event['description'], 'UTF-8', $charset)); //$vevent->setProperty( 'comment', 'This is a comment' ); //$user = api_get_user_info($event['user']); //$vevent->setProperty('organizer',$user['mail']); //$vevent->setProperty('attendee',$user['mail']); //$vevent->setProperty( 'rrule', array( 'FREQ' => 'WEEKLY', 'count' => 4));// occurs also four next weeks $ical->setConfig('filename', $y . $m . $d . $h . $M . $s . '-' . rand(1, 1000) . '.ics'); $ical->setComponent($vevent); // add event to calendar $ical->returnCalendar(); break; case 'course': $vevent->setProperty('summary', api_convert_encoding($event['title'], 'UTF-8', $charset)); if (empty($event['start_date'])) { header('location:' . Security::remove_XSS($_SERVER['HTTP_REFERER'])); } list($y, $m, $d, $h, $M, $s) = preg_split('/[\\s:-]/', $event['start_date']); $vevent->setProperty('dtstart', array('year' => $y, 'month' => $m, 'day' => $d, 'hour' => $h, 'min' => $M, 'sec' => $s)); if (empty($event['end_date'])) { $y2 = $y; $m2 = $m; $d2 = $d; $h2 = $h;
/** * Generate ical file content * * @param $who user ID * @param $who_group group ID * * @return icalendar string **/ static function generateIcal($who, $who_group) { global $CFG_GLPI, $LANG; if ($who == 0 && $who_group == 0) { return false; } include_once GLPI_ROOT . "/lib/icalcreator/iCalcreator.class.php"; $v = new vcalendar(); if (!empty($CFG_GLPI["version"])) { $v->setConfig('unique_id', "GLPI-Planning-" . trim($CFG_GLPI["version"])); } else { $v->setConfig('unique_id', "GLPI-Planning-UnknownVersion"); } $v->setConfig('filename', "glpi.ics"); $v->setProperty("method", "PUBLISH"); $v->setProperty("version", "2.0"); $v->setProperty("x-wr-calname", "GLPI-" . $who . "-" . $who_group); $v->setProperty("calscale", "GREGORIAN"); $interv = array(); $begin = time() - MONTH_TIMESTAMP * 12; $end = time() + MONTH_TIMESTAMP * 12; $begin = date("Y-m-d H:i:s", $begin); $end = date("Y-m-d H:i:s", $end); // ---------------Tracking $interv = TicketPlanning::populatePlanning(array('who' => $who, 'who_group' => $who_group, 'begin' => $begin, 'end' => $end)); // ---------------Reminder $data = Reminder::populatePlanning(array('who' => $who, 'who_group' => $who_group, 'begin' => $begin, 'end' => $end)); $interv = array_merge($interv, $data); // ---------------Plugin $data = doHookFunction("planning_populate", array("begin" => $begin, "end" => $end, "who" => $who, "who_group" => $who_group)); if (isset($data["items"]) && count($data["items"])) { $interv = array_merge($data["items"], $interv); } if (count($interv) > 0) { foreach ($interv as $key => $val) { $vevent = new vevent(); //initiate EVENT if (isset($val["tickettasks_id"])) { $vevent->setProperty("uid", "Job#" . $val["tickettasks_id"]); } else { if (isset($val["reminders_id"])) { $vevent->setProperty("uid", "Event#" . $val["reminders_id"]); } else { if (isset($val['planningID'])) { // Specify the ID (for plugins) $vevent->setProperty("uid", "Plugin#" . $val['planningID']); } else { $vevent->setProperty("uid", "Plugin#" . $key); } } } $vevent->setProperty("dstamp", $val["begin"]); $vevent->setProperty("dtstart", $val["begin"]); $vevent->setProperty("dtend", $val["end"]); if (isset($val["tickets_id"])) { $vevent->setProperty("summary", $LANG['planning'][8] . " # " . $val["tickets_id"] . " " . $LANG['document'][14] . " # " . $val["device"]); } else { if (isset($val["name"])) { $vevent->setProperty("summary", $val["name"]); } } if (isset($val["content"])) { $vevent->setProperty("description", html_clean($val["content"])); } else { if (isset($val["name"])) { $vevent->setProperty("description", $val["name"]); } } if (isset($val["tickets_id"])) { $vevent->setProperty("url", $CFG_GLPI["url_base"] . "/index.php?redirect=tracking_" . $val["tickets_id"]); } $v->setComponent($vevent); } } $v->sort(); //$v->parse(); return $v->returnCalendar(); }
function display($tpl = null) { // Get a reference of the page instance in joomla $document = JFactory::getDocument(); $model = $this->getModel(); $project = $model->getProject(); //$config = $model->getTemplateConfig($this->getName()); if (isset($project)) { $this->project = $project; } $this->overallconfig = $model->getOverallConfig(); $this->config = $this->overallconfig; $this->matches = $model->getMatches(); $this->teams = $model->getTeamsFromMatches($this->matches); // load a class that handles ical formats. require_once JLG_PATH_SITE . DS . 'helpers' . DS . 'iCalcreator.class.php'; // create a new calendar instance $v = new vcalendar(); foreach ($this->matches as $match) { $hometeam = $this->teams[$match->team1]; $home = sprintf('%s', $hometeam->name); $guestteam = $this->teams[$match->team2]; $guest = sprintf('%s', $guestteam->name); $summary = $match->project_name . ': ' . $home . ' - ' . $guest; // check if match gots a date, if not it will not be included in ical if ($match->match_date) { $totalMatchTime = isset($project) ? $project->halftime * ($project->game_parts - 1) + $project->game_regular_time : 90; $start = JoomleagueHelper::getMatchStartTimestamp($match, 'Y-m-d H:i:s'); $end = JoomleagueHelper::getMatchEndTimestamp($match, $totalMatchTime, 'Y-m-d H:i:s'); // check if exist a playground in match or team or club $stringlocation = ''; $stringname = ''; if (!empty($match->playground_id)) { $stringlocation = $match->playground_address . ", " . $match->playground_zipcode . " " . $match->playground_city; $stringname = $match->playground_name; } elseif (!empty($match->team_playground_id)) { $stringlocation = $match->team_playground_address . ", " . $match->team_playground_zipcode . " " . $match->team_playground_city; $stringname = $match->team_playground_name; } elseif (!empty($match->club_playground_id)) { $stringlocation = $match->club_playground_address . ", " . $match->club_playground_zipcode . " " . $match->club_playground_city; $stringname = $match->club_playground_name; } $location = $stringlocation; //if someone want to insert more in description here is the place $description = $stringname; // create an event and insert it in calendar $vevent = new vevent(); $timezone = JoomleagueHelper::getMatchTimezone($match); $vevent->setProperty("dtstart", $start, array("TZID" => $timezone)); $vevent->setProperty("dtend", $end, array("TZID" => $timezone)); $vevent->setProperty('LOCATION', $location); $vevent->setProperty('summary', $summary); $vevent->setProperty('description', $description); $v->setComponent($vevent); } } $v->setProperty("X-WR-TIMEZONE", $timezone); $xprops = array("X-LIC-LOCATION" => $timezone); iCalUtilityFunctions::createTimezone($v, $timezone, $xprops); $v->returnCalendar(); //$debugstr = $v->createCalendar(); //echo "<pre>"; //echo $debugstr; // exit before display // parent::display( $tpl ); }
/** * @param string $iCal * @param string $myEmail * @param int $answer possible values: accept: 1, maybe: 2, decline: 3 */ public static function answerInvitation(string $iCal, string $myEmail, int $answer) { if ($answer == "1") { $text = "akzeptiert"; } if ($answer == "2") { $text = "vorläufig akzeptiert"; } if ($answer == "3") { $text = "abgelehnt"; } $VC = new vcalendar(); $VC->parse($iCal); $event = $VC->getComponent("vevent"); $targetAttendee = "MAILTO:" . $myEmail; $i = 1; while ($valueOccur = $event->getProperty("ATTENDEE", $i, true)) { if (stripos($valueOccur["value"], $targetAttendee) === false) { $i++; continue; } $params = $valueOccur["params"]; if ($answer == "1") { $params["PARTSTAT"] = "ACCEPTED"; } if ($answer == "2") { $params["PARTSTAT"] = "TENTATIVE"; } if ($answer == "3") { $params["PARTSTAT"] = "DECLINED"; } if (isset($params["RSVP"])) { unset($params["RSVP"]); } $event->setAttendee($targetAttendee, $params, $i); $i++; } $i = 1; while ($valueOccur = $event->getProperty("ATTENDEE", $i, true)) { if (stripos($valueOccur["value"], $targetAttendee) === false) { $i++; $event->deleteProperty("ATTENDEE"); continue; } $i++; } $event->setProperty("DTSTAMP", gmdate("Ymd") . "T" . gmdate("His") . "Z"); $event->setProperty("LAST-MODIFIED", gmdate("Ymd") . "T" . gmdate("His") . "Z"); $VC->deleteComponent("vevent"); $VC->setComponent($event); $VC->setMethod("REPLY"); $ics = $VC->createCalendar(); $fromName = Session::currentUser()->A("name"); $from = Session::currentUser()->A("UserEmail"); $mail = new htmlMimeMail5(); $mail->setFrom(utf8_decode($fromName . " <" . $from . ">")); if (!ini_get('safe_mode')) { $mail->setReturnPath($from); } $mail->setSubject(utf8_decode("Antwort Termineinladung (" . ucfirst($text) . "): " . $event->getProperty("SUMMARY"))); $mail->addAttachment(new stringAttachment($ics, "invite.ics", 'application/ics')); $mail->setCalendar($ics, "REPLY"); $mail->setCalendarCharset("UTF-8"); $mail->setTextCharset("UTF-8"); $mail->setText("{$fromName} hat diesen Termin {$text}"); $organizer = str_replace("MAILTO:", "", $event->getProperty("ORGANIZER")); return $mail->send(array($organizer)); }
<?php /** * Create a ical for the upcoming recordings * * @license GPL * * @package MythWeb * @subpackage TV * **/ $calendar = new vcalendar(); $calendar->setConfig($_SERVER['SERVER_SIGNATURE'], $_SERVER['HTTP_HOST']); $calendar->setProperty('method', 'PUBLISH'); foreach ($all_shows as $show) { $event = new vevent(); $event->setProperty('dtstart', array('year' => date('Y', $show->starttime), 'month' => date('m', $show->starttime), 'day' => date('d', $show->starttime), 'hour' => date('H', $show->starttime), 'min' => date('i', $show->starttime), 'sec' => date('s', $show->starttime))); $event->setProperty('dtend', array('year' => date('Y', $show->endtime), 'month' => date('m', $show->endtime), 'day' => date('d', $show->endtime), 'hour' => date('H', $show->endtime), 'min' => date('i', $show->endtime), 'sec' => date('s', $show->endtime))); $event->setProperty('summary', $show->title . ($show->subtitle ? ' - ' . $show->subtitle : '')); $event->setProperty('description', $show->description . "\n\n" . preg_replace('/([A-Z]+)/', ' $1', $show->recstatus)); $event->setProperty('location', $show->channel->callsign); $calendar->setComponent($event); } $calendar->returnCalendar();
function createTestFile() { $dirFile = CALDIR . DIRECTORY_SEPARATOR . TESTFILE; $calendar = new vcalendar(); $calendar->setConfig('unique_id', UNIQUE); if (!$calendar->setConfig('directory', CALDIR)) { addLogEntry(1, ' ERROR (11) when setting directory \'' . CALDIR . '\', check directory/file permissions!!'); return FALSE; } elseif (!$calendar->setConfig('filename', TESTFILE)) { addLogEntry(1, " ERROR (12) when setting directory/file '{$dirFile}', check directory/file permissions!!"); return FALSE; } $calendar->setProperty('METHOD', METHOD); $calendar->setProperty('X-WR-CALNAME', CALNAME); $calendar->setProperty('X-WR-CALDESC', CALDESC); $calendar->setProperty('X-WR-TIMEZONE', TIMEZONE); $date = mktime(0, 0, 0, (int) substr(THISDATE, 4, 2), (int) substr(THISDATE, 6, 2), (int) substr(THISDATE, 0, 4)); $stopDate = $date + 7 * 24 * 3600; $eventCount = 1; // random priority, 1 to 9. HIGH (1-4), MEDIUM (5), LOW (6-9) // reversed prio; HIGH: weight 1, MEDIUM weight 4, LOW: weight 8 $prioArr = array(); for ($r = 1; $r <= 9; $r++) { $weight = 5 < $r ? 1 : 5 > $r ? 8 : 4; for ($r1 = 1; $r1 <= $weight; $r1++) { $prioArr[] = $r; } } mt_srand(); shuffle($prioArr); // array to randomly select a summary from $summaries = array('Duis ac dui sit amet ante auctor euismod.', 'Suspendisse_pellentesque_velit_in_tortor.', 'Mauris vulputate.', 'Nulla sapien pede, dapibus sed.', 'Maecenas tristique, pede_id_sollicitudin_posuere, enim nibh mollis odio.', 'Lorem ipsum dolor sit amet, consectetuerAdipiscingElit.'); while ($date <= $stopDate) { $dayCount = 1; while ($dayCount < 4) { $event = new vevent(); $eventdate = $date + mt_rand(7, 18) * 3600; // random start hour, 7 to 18 $event->setProperty('DTSTART', array('timestamp' => $eventdate)); // random duration, 1-4 hours or 2 days if (9 > mt_rand(1, 9)) { $event->setProperty('DURATION', 0, 0, mt_rand(1, 4)); } else { $event->setProperty('DURATION', 0, 2); } // 2 days duration $event->setProperty('SUMMARY', "Event #{$eventCount}. " . $summaries[mt_rand(0, 5)]); $event->setProperty('CATEGORIES', "Category #{$eventCount}"); $event->setProperty('LOCATION', "Location #{$eventCount}"); $event->setProperty('RESOURCES', "Resource #{$eventCount}"); $event->setProperty('ORGANIZER', "chair.{$eventCount}@" . UNIQUE); $event->setProperty('CONTACT', "contact.{$eventCount}@" . UNIQUE); $event->setProperty('DESCRIPTION', 'Lorem ipsum dolor sit amet, ' . 'consectetuer adipiscing elit. ' . 'Mauris vulputate. Suspendisse ' . 'pellentesque velit in tortor. ' . 'Nulla sapien pede, dapibus sed.'); // random priority, 1 to 9. HIGH (1-4), MEDIUM (5), LOW (6-9) $event->setProperty('PRIORITY', $prioArr[mt_rand(0, count($prioArr) - 1)]); // two attendees every event $event->setProperty('ATTENDEE', 'attendee.' . $eventCount . '.1@' . UNIQUE); $event->setProperty('ATTENDEE', 'attendee.' . $eventCount . '.2@' . UNIQUE); // two comments every event $event->setProperty('COMMENT', 'Duis ac dui sit amet ante auctor euismod. Sed vulputate.'); $event->setProperty('COMMENT', 'Maecenas tristique, pede id sollicitudin posuere, enim nibh mollis odio.'); $event->setProperty('CREATED', array('timestamp' => $eventdate - 2 * 24 * 3600)); // fake two days before event startdate $event->setProperty('LAST-MODIFIED', array('timestamp' => $eventdate - 23 * 3600)); // fake 25 hours before event startdate if (5 > $eventCount) { $event->setProperty('RRULE', array('FREQ' => 'DAILY', 'COUNT' => 4, 'INTERVAL' => 3)); $event->setProperty('EXRULE', array('FREQ' => 'DAILY', 'COUNT' => 2, 'INTERVAL' => 6)); } $event->setProperty('URL', 'http://www.kigkonsult.se/tinycal/index.php'); if (FALSE === $calendar->setComponent($event)) { error_log('setComponent error'); } $eventCount++; $dayCount++; } $date += 24 * 3600; } $calendar->sort(); if (FALSE === $calendar->saveCalendar()) { addLogEntry(1, " ERROR (13) saving calendar file '{$dirFile}'"); } }
//Get events $q = $dbh->prepare("SELECT * FROM `cm_events_responsibles`,`cm_events`\n\t\tWHERE cm_events_responsibles.username = ?\n\t\tAND cm_events_responsibles.event_id = cm_events.id\n\t\tORDER by cm_events.start DESC"); $q->bindParam(1, $user); $q->execute(); $events = $q->fetchAll(PDO::FETCH_ASSOC); foreach ($events as $event) { $case_name = case_id_to_casename($dbh, $event['case_id']); $e = new vevent(); // initiate EVENT if ($event['all_day'] == '1') { $start = explode(' ', $event['start']); //all-day events are date only $e->setProperty('dtstart', $start[0]); if ($event['end'] == null) { $e->setProperty('dtend', $start[0]); //make end same as event } else { $end = explode(' ', $event['end']); $e->setProperty('dtend', $end[0]); } } else { $e->setProperty('dtstart', $event['start']); $e->setProperty('dtend', $event['end']); } $e->setProperty('summary', $case_name . ": " . $event['task']); $e->setProperty('description', $event['notes']); $v->setComponent($e); } $cal = $v->createCalendar(); echo $cal; }
private function getICalData($event) { // set Your unique id $config = array('unique_id' => 'ravebuild.com'); $caldesc_string = "RaveBuild-Calendar Events"; // create a new calendar instance $v_calendar = new vcalendar($config); // set download file name $v_calendar->filename = md5($event->getId()) . '.ics'; // required of some calendar software $v_calendar->setProperty('method', 'PUBLISH'); $v_calendar->setProperty('X-WR-CALNAME;VALUE=TEXT', $caldesc_string); $v_calendar->setProperty("X-WR-CALDESC", "This is " . $caldesc_string); $v_calendar->setProperty("X-WR-TIMEZONE", "Pacific/Auckland"); $start_time = strtotime($event->getStartTime()); $end_time = strtotime($event->getStartTime()); $end_hour = date('H', strtotime($event->getEndTime())); // star time $start = array('year' => date('Y', $start_time), 'month' => date('m', $start_time), 'day' => date('d', $start_time), 'hour' => date('H', $start_time), 'min' => 0, 'sec' => 0); // end time $end = array('year' => date('Y', $end_time), 'month' => date('m', $end_time), 'day' => date('d', $end_time), 'hour' => $end_hour, 'min' => 0, 'sec' => 0); $v_event = new vevent(); // create an event calendar component $v_event->setProperty('uid', md5($event->getId())); //$v_event->setProperty("recurrence-id", $start); $v_event->setProperty('created', $event->getCreatedAt()); $v_event->setProperty('last-modified', $event->getUpdatedAt()); $v_event->setProperty('dtstart', $start); $v_event->setProperty('dtend', $end); $v_event->setProperty('summary', $event->getSubject()); $v_event->setProperty('description', $event->getBody()); $v_calendar->setComponent($v_event); return $v_calendar; }
/** * Export an event as iCalendar (ics) */ public function generateIcal($eventID) { $ical = new \vcalendar(); $ical->setConfig('ical_' . $this->id); $ical->setProperty('method', 'PUBLISH'); $ical->setProperty("X-WR-TIMEZONE", $GLOBALS['TL_CONFIG']['timeZone']); $time = time(); // Get event $objEvent = \CalendarEventsModel::findByPk($eventID); $vevent = new \vevent(); if ($objEvent->addTime) { $vevent->setProperty('dtstart', array('year' => date('Y', $objEvent->startTime), 'month' => date('m', $objEvent->startTime), 'day' => date('d', $objEvent->startTime), 'hour' => date('H', $objEvent->startTime), 'min' => date('i', $objEvent->startTime), 'sec' => 0)); $vevent->setProperty('dtend', array('year' => date('Y', $objEvent->endTime), 'month' => date('m', $objEvent->endTime), 'day' => date('d', $objEvent->endTime), 'hour' => date('H', $objEvent->endTime), 'min' => date('i', $objEvent->endTime), 'sec' => 0)); } else { $vevent->setProperty('dtstart', date('Ymd', $objEvent->startDate), array('VALUE' => 'DATE')); if (!strlen($objEvent->endDate) || $objEvent->endDate == 0) { $vevent->setProperty('dtend', date('Ymd', $objEvent->startDate + 24 * 60 * 60), array('VALUE' => 'DATE')); } else { $vevent->setProperty('dtend', date('Ymd', $objEvent->endDate + 24 * 60 * 60), array('VALUE' => 'DATE')); } } $vevent->setProperty('summary', $objEvent->title, ENT_QUOTES, 'UTF-8'); $vevent->setProperty('description', strip_tags($objEvent->details ? $objEvent->details : $objEvent->teaser)); if ($objEvent->recurring) { $count = 0; $arrRepeat = deserialize($objEvent->repeatEach); $arg = $arrRepeat['value']; $unit = $arrRepeat['unit']; if ($arg == 1) { $unit = substr($unit, 0, -1); } $strtotime = '+ ' . $arg . ' ' . $unit; $newstart = strtotime($strtotime, $objEvent->startTime); $newend = strtotime($strtotime, $objEvent->endTime); $freq = 'YEARLY'; switch ($arrRepeat['unit']) { case 'days': $freq = 'DAILY'; break; case 'weeks': $freq = 'WEEKLY'; break; case 'months': $freq = 'MONTHLY'; break; case 'years': $freq = 'YEARLY'; break; } $rrule = array('FREQ' => $freq); if ($objEvent->recurrences > 0) { $rrule['count'] = $objEvent->recurrences; } if ($arg > 1) { $rrule['INTERVAL'] = $arg; } $vevent->setProperty('rrule', $rrule); } /* * begin module event_recurrences handling */ if ($objEvent->repeatExecptions) { $arrSkipDates = deserialize($objEvent->repeatExecptions); foreach ($arrSkipDates as $skipDate) { $exTStamp = strtotime($skipDate); $exdate = array(array(date('Y', $exTStamp), date('m', $exTStamp), date('d', $exTStamp), date('H', $objEvent->startTime), date('i', $objEvent->startTime), date('s', $objEvent->startTime))); $vevent->setProperty('exdate', $exdate); } } /* * end module event_recurrences handling */ $ical->setComponent($vevent); $ical->setConfig("FILENAME", urlencode($objEvent->title) . ".ics"); $ical->returnCalendar(); }
/** * function csv2iCal * * Convert csv file to iCal format and send file to browser (default) or save Ical file to disk * Definition iCal : rcf2445, http://kigkonsult.se/downloads/index.php#rfc2445 * Definition csv : http://en.wikipedia.org/wiki/Comma-separated_values * Using iCalcreator: http://kigkonsult.se/downloads/index.php#iCalcreator * csv directory/file read/write * * @author Kjell-Inge Gustafsson <*****@*****.**> * @since 3.0 - 2011-12-21 * @return bool return FALSE when error */ public function csv2iCal() { $timeexec = array('start' => microtime(TRUE)); if ($this->log) { $this->log->log(' ********** START **********', PEAR_LOG_NOTICE); } $conf = array(); foreach ($this->config as $key => $value) { if (in_array(strtolower($key), array('inputdirectory', 'outputdirectory', 'inputfilename', 'outputfilename', 'inputurl', 'backup', 'save', 'skip'))) { continue; } if (in_array($key, array('del', 'sep', 'nl'))) { $conf[$key] = "{$value}"; } else { $conf[strtoupper($value)] = strtoupper($key); // flip map names if ($this->log) { $this->log->log("{$value} mapped to {$key}", PEAR_LOG_DEBUG); } } } $fp = false; $string_to_parse = $this->getConfig('string_to_parse'); if ($string_to_parse) { $fp = fopen('php://temp/maxmemory:' . 1024 * 1024, 'rw'); fputs($fp, $string_to_parse); fseek($fp, 0); } else { /** check input/output directory and filename */ $inputdirFile = $outputdirFile = ''; $inputFileParts = $outputFileParts = array(); $remoteInput = $remoteOutput = FALSE; if (FALSE === $this->_fixIO('input', 'csv', $inputdirFile, $inputFileParts, $remoteInput)) { if ($this->log) { $this->log->log(number_format(microtime(TRUE) - $timeexec['start'], 5) . ' sec', PEAR_LOG_ERR); $this->log->log("ERROR 2, invalid input ({$inputdirFile})", PEAR_LOG_ERR); $this->log->flush(); } return FALSE; } if (FALSE === $this->_fixIO('output', FALSE, $outputdirFile, $outputFileParts, $remoteOutput)) { if (FALSE === $this->setConfig('outputfilename', $inputFileParts['filename'] . '.ics')) { if ($this->log) { $this->log->log(number_format(microtime(TRUE) - $timeexec['start'], 5) . ' sec', PEAR_LOG_ERR); $this->log->log('ERROR 3,invalid output (' . $inputFileParts['filename'] . '.csv)', PEAR_LOG_ERR); $this->log->flush(); } return FALSE; } $outputdirFile = $this->getConfig('outputdirectory') . DIRECTORY_SEPARATOR . $inputFileParts['filename'] . '.ics'; $outputFileParts = pathinfo($outputdirFile); if ($this->log) { $this->log->log("output set to '{$outputdirFile}'", PEAR_LOG_NOTICE); } } if ($this->log) { $this->log->log("INPUT..FILE:{$inputdirFile}", PEAR_LOG_NOTICE); $this->log->log("OUTPUT.FILE:{$outputdirFile}", PEAR_LOG_NOTICE); } /** read csv file into input array */ ini_set('auto_detect_line_endings', true); $fp = fopen($inputdirFile, "r"); if (FALSE === $fp) { if ($this->log) { $this->log->log("ERROR 4, unable to read file: '{$inputdirFile}'", PEAR_LOG_ERR); $this->log->log(number_format(microtime(TRUE) - $timeexec['start'], 5) . ' sec', PEAR_LOG_DEBUG); $this->log->flush(); } return FALSE; } } $rows = array(); while (FALSE !== ($row = fgetcsv($fp, FALSE, $conf['sep'], $conf['del']))) { $rows[] = $row; } fclose($fp); ini_set('auto_detect_line_endings', false); $cntrows = count($rows); /** iCalcreator checks when setting directory and filename */ $calendar = new vcalendar(); if (FALSE !== ($unique_id = $this->getConfig('unique_id'))) { $calendar->setConfig('unique_id', $unique_id); } if (!$this->getConfig('outputobj')) { if ($remoteOutput) { if (FALSE === $calendar->setConfig('url', $outputdirFile)) { if ($this->log) { $this->log->log("ERROR 5, iCalcreator: invalid url: '{$outputdirFile}'", PEAR_LOG_ERR); $this->log->log(number_format(microtime(TRUE) - $timeexec['start'], 5) . ' sec', PEAR_LOG_DEBUG); $this->log->flush(); } return FALSE; } } else { if (FALSE === $calendar->setConfig('directory', $outputFileParts['dirname'])) { if ($this->log) { $this->log->log("ERROR 6, INPUT FILE:'{$inputdirFile}' iCalcreator: invalid directory: '" . $outputFileParts['dirname'] . "'", PEAR_LOG_ERR); $this->log->log(number_format(microtime(TRUE) - $timeexec['start'], 5) . ' sec', PEAR_LOG_DEBUG); $this->log->flush(); } return FALSE; } if (FALSE === $calendar->setConfig('filename', $outputFileParts['basename'])) { if ($this->log) { $this->log->log("ERROR 7, INPUT FILE:'{$inputdirFile}' iCalcreator: invalid filename: '" . $outputFileParts['basename'] . "'", PEAR_LOG_ERR); $this->log->log(number_format(microtime(TRUE) - $timeexec['start'], 5) . ' sec', PEAR_LOG_DEBUG); $this->log->flush(); } return FALSE; } } } $timeexec['fileOk'] = microtime(TRUE); /** info rows */ $actrow = 0; for ($row = $actrow; $row < $cntrows; $row++) { if (empty($rows[$row]) || 1 >= count($rows[$row]) || '' >= $rows[$row][1] || 'iCal' == substr($rows[$row][0], 0, 4) || 'kigkonsult.se' == $rows[$row][0]) { continue; } elseif ('TYPE' == strtoupper($rows[$row][0])) { $actrow = $row; break; } elseif ('CALSCALE' == strtoupper($rows[$row][0])) { $calendar->setProperty('CALSCALE', $rows[$row][1]); } elseif ('METHOD' == strtoupper($rows[$row][0])) { $calendar->setProperty('METHOD', $rows[$row][1]); } elseif ('X-' == substr($rows[$row][0], 0, 2)) { $calendar->setProperty($rows[$row][0], $rows[$row][1]); } elseif (2 >= count($rows[$row])) { continue; } else { $actrow = $row; break; } } $timeexec['infoOk'] = microtime(TRUE); $cntprops = 0; $proporder = array(); /** fix opt. vtimezone */ if ($actrow < $cntrows && (in_array('tzid', $rows[$actrow]) || in_array('TZID', $rows[$actrow]))) { foreach ($rows[$actrow] as $key => $header) { $header = strtoupper($header); if (isset($conf[$header])) { $proporder[$conf[$header]] = $key; // check map of userfriendly name to iCal property name if ($this->log) { $this->log->log("header row ix:{$key} => {$header}, replaced by " . $conf[$header], PEAR_LOG_DEBUG); } } else { $proporder[$header] = $key; } } if ($this->log) { $this->log->log("comp proporder=" . implode(',', array_flip($proporder)), PEAR_LOG_DEBUG); } $allowedProps = array('VTIMEZONE' => array('TZID', 'LAST-MODIFIED', 'TZURL'), 'STANDARD' => array('DTSTART', 'TZOFFSETTO', 'TZOFFSETFROM', 'COMMENT', 'RDATE', 'RRULE', 'TZNAME'), 'DAYLIGHT' => array('DTSTART', 'TZOFFSETTO', 'TZOFFSETFROM', 'COMMENT', 'RDATE', 'RRULE', 'TZNAME')); $actrow++; $comp = $subcomp = $actcomp = FALSE; for ($row = $actrow; $row < $cntrows; $row++) { if (empty($rows[$row]) || 1 >= count($rows[$row])) { continue; } $compname = strtoupper($rows[$row][0]); if ('TYPE' == $compname) { // next header $actrow = $row; break; } if ($comp && $subcomp) { $comp->setComponent($subcomp); $subcomp = FALSE; } if ('VTIMEZONE' == $compname) { if ($comp) { $calendar->setComponent($comp); } $comp = new vtimezone(); $actcomp =& $comp; $cntprops += 1; } elseif ('STANDARD' == $compname) { $subcomp = new vtimezone('STANDARD'); $actcomp =& $subcomp; } elseif ('DAYLIGHT' == $compname) { $subcomp = new vtimezone('DAYLIGHT'); $actcomp =& $subcomp; } else { if ($this->log) { $this->log->log("skipped {$compname}", PEAR_LOG_WARNING); } continue; } foreach ($proporder as $propName => $col) { // insert all properties into component if (2 > $col || 'ORDER' == strtoupper($propName)) { continue; } $propName = strtoupper($propName); if ('X-' != substr($propName, 0, 2) && !in_array($propName, $allowedProps[$compname])) { // check if allowed property for the component if ($this->log) { $this->log->log("skipped {$compname}: {$propName}", PEAR_LOG_DEBUG); } continue; } if (isset($rows[$row][$col]) && !empty($rows[$row][$col])) { $rows[$row][$col] = str_replace(array("\r\n", "\n\r", "\n", "\r"), $conf['nl'], $rows[$row][$col]); $value = FALSE !== strpos($rows[$row][$col], $conf['nl']) ? explode($conf['nl'], $rows[$row][$col]) : array($rows[$row][$col]); foreach ($value as $val) { if (empty($val) && '0' != $val) { continue; } $del = FALSE !== strpos($val, ':') ? ';' : ':'; if (FALSE !== $actcomp->parse("{$propName}{$del}{$val}")) { if ($this->log) { $this->log->log("iCalcreator->parse( '{$propName} {$val}' )", PEAR_LOG_DEBUG); } } elseif ($this->log) { $this->log->log("ERROR 8, INPUT FILE:'{$inputdirFile}' iCalcreator: parse error: '{$propName}{$del}{$val}'", PEAR_LOG_ERR); } } // end foreach( $value } // end if( isset } // end foreach( $proporder } // end for( $row = $actrow if ($comp && $subcomp) { $comp->setComponent($subcomp); } if ($comp) { $calendar->setComponent($comp); } $comp = $subcomp = $actcomp = FALSE; } $timeexec['zoneOk'] = microtime(TRUE); /** fix data */ $proporder = array(); if ($actrow < $cntrows && isset($rows[$actrow][0]) && 'TYPE' == strtoupper($rows[$actrow][0])) { foreach ($rows[$actrow] as $key => $header) { $header = strtoupper($header); if (isset($conf[$header])) { $proporder[$conf[$header]] = $key; // check map of user friendly name to iCal property name if ($this->log) { $this->log->log("header row ix:'{$key} => {$header}', mapped to '" . $conf[$header] . "'", PEAR_LOG_DEBUG); } } else { $proporder[$header] = $key; } } if ($this->log) { $this->log->log("comp proporder=" . implode(',', array_flip($proporder)), PEAR_LOG_DEBUG); } $allowedProps = array('VEVENT' => array('ATTACH', 'ATTENDEE', 'CATEGORIES', 'CLASS', 'COMMENT', 'CONTACT', 'CREATED', 'DESCRIPTION', 'DTEND', 'DTSTAMP', 'DTSTART', 'DURATION', 'EXDATE', 'RXRULE', 'GEO', 'LAST-MODIFIED', 'LOCATION', 'ORGANIZER', 'PRIORITY', 'RDATE', 'RECURRENCE-ID', 'RELATED-TO', 'RESOURCES', 'RRULE', 'REQUEST-STATUS', 'SEQUENCE', 'STATUS', 'SUMMARY', 'TRANSP', 'UID', 'URL'), 'VTODO' => array('ATTACH', 'ATTENDEE', 'CATEGORIES', 'CLASS', 'COMMENT', 'COMPLETED', 'CONTACT', 'CREATED', 'DESCRIPTION', 'DTSTAMP', 'DTSTART', 'DUE', 'DURATION', 'EXDATE', 'EXRULE', 'GEO', 'LAST-MODIFIED', 'LOCATION', 'ORGANIZER', 'PERCENT', 'PRIORITY', 'RDATE', 'RECURRENCE-ID', 'RELATED-TO', 'RESOURCES', 'RRULE', 'REQUEST-STATUS', 'SEQUENCE', 'STATUS', 'SUMMARY', 'UID', 'URL'), 'VJOURNAL' => array('ATTACH', 'ATTENDEE', 'CATEGORIES', 'CLASS', 'COMMENT', 'CONTACT', 'CREATED', 'DESCRIPTION', 'DTSTAMP', 'DTSTART', 'EXDATE', 'EXRULE', 'LAST-MODIFIED', 'ORGANIZER', 'RDATE', 'RECURRENCE-ID', 'RELATED-TO', 'RRULE', 'REQUEST-STATUS', 'SEQUENCE', 'STATUS', 'SUMMARY', 'UID', 'URL'), 'VFREEBUSY' => array('ATTENDEE', 'COMMENT', 'CONTACT', 'DTEND', 'DTSTAMP', 'DTSTART', 'DURATION', 'FREEBUSY', 'ORGANIZER', 'UID', 'URL'), 'VALARM' => array('ACTION', 'ATTACH', 'ATTENDEE', 'DESCRIPTION', 'DURATION', 'REPEAT', 'SUMMARY', 'TRIGGER')); $actrow++; $comp = $subcomp = $actcomp = FALSE; $allowedComps = array('VEVENT', 'VTODO', 'VJOURNAL', 'VFREEBUSY'); for ($row = $actrow; $row < $cntrows; $row++) { if (empty($rows[$row]) || 1 >= count($rows[$row])) { continue; } if ($comp && $subcomp) { $comp->setComponent($subcomp); $subcomp = FALSE; } $compname = strtoupper($rows[$row][0]); if ($this->log) { $this->log->log("'{$compname}' START", PEAR_LOG_NOTICE); } if (in_array($compname, $allowedComps)) { if ($comp) { $calendar->setComponent($comp); } $comp = new $rows[$row][0](); $actcomp =& $comp; $cntprops += 1; } elseif ('VALARM' == $compname) { $subcomp = new valarm(); $actcomp =& $subcomp; } else { if ($this->log) { $this->log->log("skipped {$compname}", PEAR_LOG_WARNING); } continue; } foreach ($proporder as $propName => $col) { // insert all properties into component if (2 > $col || 'ORDER' == strtoupper($propName)) { continue; } $propName = strtoupper($propName); if ($this->log) { $this->log->log("{$compname} {$propName} START (col={$col})", PEAR_LOG_DEBUG); } if ('X-' != substr($propName, 0, 2) && !in_array($propName, $allowedProps[$compname])) { // check if allowed property for the component if ($this->log) { $this->log->log("skipped {$compname} {$propName}", PEAR_LOG_NOTICE); } continue; } if (isset($rows[$row][$col]) && !empty($rows[$row][$col]) || 'SEQUENCE' == $propName && '0' == $rows[$row][$col]) { $rows[$row][$col] = str_replace(array("\r\n", "\n\r", "\n", "\r"), $conf['nl'], $rows[$row][$col]); $value = FALSE !== strpos($rows[$row][$col], $conf['nl']) ? explode($conf['nl'], $rows[$row][$col]) : array($rows[$row][$col]); $ctests = array('://', 'fax:', 'cid:', 'sms:', 'tel:', 'urn:', 'crid:', 'news:', 'pres:', 'mailto:', 'MAILTO:'); foreach ($value as $val) { if (empty($val) && '0' != $val && 0 != $val) { continue; } if ('GEO' == $propName) { $parseval = FALSE !== strpos($val, ':') ? "GEO{$val}" : "GEO:{$val}"; if (FALSE === $actcomp->parse($parseval)) { if ($this->log) { $this->log->log("ERROR 11, INPUT FILE:'{$inputdirFile}' iCalcreator: parse error: '{$parseval}'", PEAR_LOG_ERR); } } } elseif ('REQUEST-STATUS' == $propName) { // 'REQUEST-STATUS' without any parameters.. . if (FALSE === $actcomp->parse("{$propName}:{$val}")) { if ($this->log) { $this->log->log("ERROR 12, INPUT FILE:'{$inputdirFile}' iCalcreator: parse error: '{$propName}:{$val}'", PEAR_LOG_ERR); } } } $cntm = $pos = 0; foreach ($ctests as $tst) { $cntm += substr_count($val, $tst); } $cntc = substr_count($val, ':'); $cntq = substr_count($val, '='); $cnts = substr_count($val, ';'); if (0 == $cntq && 0 == $cnts) { // no parameters $del = ':'; } elseif (1 == $cntc && $cntq + 1 == $cnts) { // parameters and colon $del = ';'; } elseif ($cntc == $cntm + 1) { $del = ';'; } else { $del = 1 > $cntm && 0 < $cntc ? ';' : ':'; } if ('X-' == substr($propName, 0, 2) || in_array($propName, array('CATEGORIES', 'COMMENT', 'CONTACT', 'DESCRIPTION', 'LOCATION', 'RESOURCES', 'SUMMARY'))) { $val = str_replace(',', '\\,', $val); if (FALSE !== ($pos = strpos($del . $val, ':'))) { while (FALSE !== ($pos2 = strpos($val, ';', $pos + 1))) { $val = substr($val, 0, $pos2) . '\\;' . substr($val, $pos2 + 1); if ($this->log) { $this->log->log("pos={$pos} pos2={$pos2} val='{$val}'", PEAR_LOG_DEBUG); } $pos = $pos2 + 1; } } } if (FALSE === $actcomp->parse("{$propName}{$del}{$val}")) { if ($this->log) { $this->log->log("ERROR 13, INPUT FILE:'{$inputdirFile}' iCalcreator: parse error: '{$propName}{$del}{$val}'", PEAR_LOG_ERR); } } elseif ($this->log) { $this->log->log("iCalcreator->parse( '{$propName}{$del}{$val}' )", PEAR_LOG_DEBUG); } } // end foreach( $value as $val } // end if( isset( $rows[$row][$col] } // end foreach( $proporder } // end for( $row = $actrow; if ($comp && $subcomp) { $comp->setComponent($subcomp); } if ($comp) { $calendar->setComponent($comp); } } $save = $this->getConfig('save'); if ($this->log) { $timeexec['exit'] = microtime(TRUE); $msg = "INPUT '{$inputdirFile}'"; $msg .= ' fileOk:' . number_format($timeexec['fileOk'] - $timeexec['start'], 5); $msg .= ' infoOk:' . number_format($timeexec['infoOk'] - $timeexec['fileOk'], 5); $msg .= ' zoneOk:' . number_format($timeexec['zoneOk'] - $timeexec['infoOk'], 5); $msg .= ' compOk:' . number_format($timeexec['exit'] - $timeexec['zoneOk'], 5); $msg .= ' total:' . number_format($timeexec['exit'] - $timeexec['start'], 5) . ' sec'; $this->log->log($msg, PEAR_LOG_DEBUG); $msg = "'{$inputdirFile}' (" . $cntprops . ' components) start:' . date('H:i:s', $timeexec['start']); $msg .= ' total:' . number_format($timeexec['exit'] - $timeexec['start'], 5) . ' sec'; if ($save) { $msg .= " -> '{$outputdirFile}'"; } $this->log->log($msg, PEAR_LOG_NOTICE); } /** return calendar, save or send the file */ if ($this->getConfig('outputobj')) { if ($this->log) { $this->log->log("INPUT FILE:'{$inputdirFile}' returning iCalcreator vcalendar instance", PEAR_LOG_NOTICE); $this->log->flush(); } return $calendar; exit; } $d = $calendar->getConfig('directory'); $f = $calendar->getConfig('filename'); $df = $d . DIRECTORY_SEPARATOR . $f; if ($save) { if (FALSE !== $calendar->saveCalendar()) { if ($this->log) { $this->log->log("INPUT FILE:'{$inputdirFile}' saved '{$df}'", PEAR_LOG_NOTICE); $this->log->flush(); } return TRUE; } else { // ?? if ($this->log) { $this->log->log("ERROR 16, INPUT FILE:'{$inputdirFile}' can't write to output file : '{$df}'", PEAR_LOG_ERR); $this->log->flush(); } return FALSE; } } else { if ($this->log) { $this->log->log("INPUT FILE:'{$inputdirFile}' returning : '{$f}'", PEAR_LOG_NOTICE); $this->log->flush(); } $output = $calendar->createCalendar(); $filesize = strlen($output); if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) { $output = gzencode($output, 9); $filesize = strlen($output); header('Content-Encoding: gzip'); header('Vary: *'); } header('Content-Type: text/calendar; charset=utf-8'); header("Content-Disposition: attachment; filename='{$f}'"); header('Cache-Control: max-age=10'); header('Content-Length: ' . $filesize); echo $output; } return TRUE; }
function ChangeMessage($folderid, $id, $message) { debugLog('CalDAV::ChangeMessage(' . $folderid . ', ' . $id . ', ..)'); debugLog("CalDAV::Their Message = "); if (trim($id) != "") { $return = $this->StatMessage($folderid, $id); } else { $return = false; } if ($return === false) { debugLog('CalDAV::Found new message on device'); #create new id, this is a new record from device. $date = date('Ymd\\THisT'); $unique = substr(microtime(), 2, 4); $base = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPrRsStTuUvVxXuUvVwWzZ1234567890'; $start = 0; $end = strlen($base) - 1; $length = 6; $str = null; for ($p = 0; $p < $length; $p++) { $unique .= $base[mt_rand($start, $end)]; } $id = $date . '-' . $unique . ".ics"; } else { debugLog('CalDAV::Event Already On Server'); } $task = false; if ($folderid == "tasks") { $vtodo = $this->converttovtodo($message); if (substr($id, strlen($id) - 4) == ".ics") { $vtodo->setProperty("UID", substr($id, 0, -4)); } else { $vtodo->setProperty("UID", $id); } } else { $vevent = $this->converttovevent($message); $exarray = array(); if (isset($message->exceptions) && is_array($message->exceptions)) { $deletedarray = array(); foreach ($message->exceptions as $ex) { if ($ex->deleted == "1") { array_push($deletedarray, $this->parseDate($ex->exceptionstarttime)); } else { debugLog('CalDAV::Found non deleted exception Converting...'); $tmpevent = $this->converttovevent($ex); if (isset($ex->alldayevent) && $ex->alldayevent == "1") { $tmpevent->setProperty("recurrence-id", $this->parseDate($ex->exceptionstarttime), array('VALUE' => 'DATE')); } else { $tmpevent->setProperty("recurrence-id", $this->parseDate($ex->exceptionstarttime)); } array_push($exarray, $tmpevent); } } debugLog("CalDAV:: " . print_r($deletedarray, true)); if (count($deletedarray) > 0) { $vevent->setProperty("exdate", $deletedarray); } } if (substr($id, strlen($id) - 4) == ".ics") { $vevent->setProperty("UID", substr($id, 0, -4)); } else { $vevent->setProperty("UID", $id); } } # $somethingelse = convert2ical(); debugLog('CalDAV::Converted to iCal: '); $v = new vcalendar(); if ($folderid == "tasks") { $v->setComponent($vtodo); } else { $v->setComponent($vevent); if (count($exarray) > 0) { foreach ($exarray as $exvevent) { $sdt = $exvevent->getProperty("dtstart"); if (substr($id, strlen($id) - 4) == ".ics") { $exvevent->setProperty("UID", substr($id, 0, -4)); } else { $exvevent->setProperty("UID", $id); } $v->setComponent($exvevent); } } } $output = $v->createCalendar(); debugLog("CalDAV::putting to " . $this->_path . $id); $etag = "*"; if ($return) { $etag = $return['etag']; } $retput = $this->cdc->DoPUTRequest($this->_path . $id, $output, $etag); debugLog("CalDAV::output putted etag: {$etag} new etag: {$retput}"); $obj = array(); $obj["etag"] = $retput; $obj["href"] = $id; $obj["data"] = $output; if ($folderid == "calendar") { $this->_events[$id] = $obj; } else { $this->_tasks[$id] = $obj; } return $this->StatMessage($folderid, $id); }
function display($tpl = null) { // Get a reference of the page instance in joomla $document = JFactory::getDocument(); $model = $this->getModel(); $project =& $model->getProject(); $config = $model->getTemplateConfig($this->getName()); if (isset($project)) { $this->assignRef('project', $project); $this->assignRef('overallconfig', $model->getOverallConfig()); $this->assignRef('config', $this->overallconfig); $this->assignRef('teams', $model->getTeamsIndexedByPtid()); $this->assignRef('matches', $model->getMatches($config)); } // load a class that handles ical formats. require_once JLG_PATH_SITE . DS . 'helpers' . DS . 'iCalcreator.class.php'; // create a new calendar instance $v = new vcalendar(); foreach ($this->matches as $match) { $hometeam = $this->teams[$match->projectteam1_id]; $home = sprintf('%s', $hometeam->name); $guestteam = $this->teams[$match->projectteam2_id]; $guest = sprintf('%s', $guestteam->name); $summary = $project->name . ': ' . $home . ' - ' . $guest; // check if match gots a date, if not it will not be included // in ical if (!strstr($match->match_date, "0000-00-00")) { $syear = JHTML::date($match->match_date, "%Y"); $sday = JHTML::date($match->match_date, "%d"); $smonth = JHTML::date($match->match_date, "%m"); $shour = JHTML::date($match->match_date, "%H"); $smin = JHTML::date($match->match_date, "%M"); //$start = JHTML::date($match->match_date, "%Y-%m-%d %H:%M:%S" ); $start = strftime("%Y-%m-%d %H:%M:%S", strtotime($match->match_date)); $start_oldphpversion = array('year' => $syear, 'month' => $smonth, 'day' => $sday, 'hour' => $shour, 'min' => $smin, 'sec' => 0); $time_to_ellapse = $project->halftime * ($project->game_parts - 1) + $project->game_regular_time; $endtime = JoomleagueHelper::getTimestamp($match->match_date) + $time_to_ellapse * 60; $year = JHTML::date($endtime, "%Y"); $day = JHTML::date($endtime, "%d"); $month = JHTML::date($endtime, "%m"); $hour = JHTML::date($endtime, "%H"); $min = JHTML::date($endtime, "%M"); //$end = JHTML::date($endtime, "%Y-%m-%d %H:%M:%S" ); $end = strftime("%Y-%m-%d %H:%M:%S", $endtime); $end_oldphpversion = array('year' => $year, 'month' => $month, 'day' => $day, 'hour' => $hour, 'min' => $min, 'sec' => 0); // check if exist a playground in match or team or club if ($match->playground_id != "") { $stringlocation = $match->playground_address . ", " . $match->playground_zipcode . " " . $match->playground_city; $stringname = $match->playground_name; } else { if ($match->team_playground_id != "") { $stringlocation = $match->team_playground_address . ", " . $match->team_playground_zipcode . " " . $match->team_playground_city; $stringname = $match->team_playground_name; } elseif ($match->club_playground_id != "") { $stringlocation = $match->club_playground_address . ", " . $match->club_playground_zipcode . " " . $match->club_playground_city; $stringname = $match->club_playground_name; } } $location = $stringlocation; //if someone want to insert more in description here is the place $description = $stringname; // create an event and insert it in calendar $vevent = new vevent(); $vevent->setProperty("dtstart", $start, array("TZID" => $project->timezone)); $vevent->setProperty("dtend", $end, array("TZID" => $project->timezone)); $vevent->setProperty('LOCATION', $location); $vevent->setProperty('summary', $summary); $vevent->setProperty('description', $description); $v->setComponent($vevent); } } $v->returnCalendar(); // exit before display // parent::display( $tpl ); }
if (strpos($meilleursujet, '-') !== false) { $double_time = true; } $dtstart['hour'] = intval(strtok(":Hh")); $a = intval(strtok(":Hh-")); $b = intval(strtok(":Hh-")); if ($b === false) { if ($double_time) { $dtend['hour'] = $a; } else { $dtstart['min'] = $a; } } else { $dtstart['min'] = $a; $dtend['hour'] = $b; $dtend['min'] = intval(strtok(":Hh-")); } if (!$double_time) { $dtend['hour'] = $dtstart['hour'] + 1; $dtend['min'] = $dtstart['min']; } $vevent->setProperty('dtstart', $dtstart); $vevent->setProperty('dtend', $dtend); $vevent->setProperty('summary', $_SESSION["sondagetitre"]); $v->setComponent($vevent); // add event to calendar $v->setConfig("language", "fr"); $v->setConfig("directory", "export"); $v->setConfig("filename", $_SESSION["numsondage"] . ".ics"); // set file name $v->returnCalendar();
/** * Export the Event with calendar and stop excuting script * * @return null */ function export() { global $_CONFIG; //create new calendar $objVCalendar = new \vcalendar(); $objVCalendar->setConfig('unique_id', $_CONFIG['coreGlobalPageTitle']); $objVCalendar->setConfig('filename', urlencode($this->title) . '.ics'); // set Your unique id //$v->setProperty('X-WR-CALNAME', 'Calendar Sample'); //$v->setProperty('X-WR-CALDESC', 'Calendar Description'); //$v->setProperty('X-WR-TIMEZONE', 'America/Los_Angeles'); $objVCalendar->setProperty('X-MS-OLK-FORCEINSPECTOROPEN', 'TRUE'); $objVCalendar->setProperty('METHOD', 'PUBLISH'); // create an event calendar component $objVEvent = new \vevent(); // start $startYear = date("Y", $this->startDate); $startMonth = date("m", $this->startDate); $startDay = date("d", $this->startDate); $startHour = date("H", $this->startDate); $startMinute = date("i", $this->startDate); $objVEvent->setProperty('dtstart', array('year' => $startYear, 'month' => $startMonth, 'day' => $startDay, 'hour' => $startHour, 'min' => $startMinute, 'sec' => 0)); // end $endYear = date("Y", $this->endDate); $endMonth = date("m", $this->endDate); $endDay = date("d", $this->endDate); $endHour = date("H", $this->endDate); $endMinute = date("i", $this->endDate); $objVEvent->setProperty('dtend', array('year' => $endYear, 'month' => $endMonth, 'day' => $endDay, 'hour' => $endHour, 'min' => $endMinute, 'sec' => 0)); // place if (!empty($this->place)) { $objVEvent->setProperty('location', html_entity_decode($this->place, ENT_QUOTES, CONTREXX_CHARSET)); } // title $objVEvent->setProperty('summary', html_entity_decode($this->title, ENT_QUOTES, CONTREXX_CHARSET)); // description $objVEvent->setProperty('description', html_entity_decode(strip_tags($this->description), ENT_QUOTES, CONTREXX_CHARSET)); // organizer $objVEvent->setProperty('organizer', $_CONFIG['coreGlobalPageTitle'] . ' <' . $_CONFIG['coreAdminEmail'] . '>'); // comment //$objVEvent->setProperty( 'comment', 'This is a comment' ); // attendee //$objVEvent->setProperty( 'attendee', '*****@*****.**' ); // ressourcen //$objVEvent->setProperty( 'resources', 'COMPUTER PROJECTOR' ); // series type //$objVEvent->setProperty( 'rrule', array( 'FREQ' => 'WEEKLY', 'count' => 4));// weekly, four occasions // add event to calendar $objVCalendar->setComponent($objVEvent); $objVCalendar->returnCalendar(); exit; }
/** * Export all tasks of a user via iCal * * @param int $user User ID * @param bool $show_long * @return bool */ function getIcal($user, $show_long = true) { $user = (int) $user; $show_long = (bool) $show_long; $username = $_SESSION["username"]; $project = new project(); $myprojects = $project->getMyProjects($user); $tasks = array(); if (!empty($myprojects)) { foreach ($myprojects as $proj) { $task = $this->getAllMyProjectTasks($proj["ID"], 10000); if (!empty($task)) { array_push($tasks, $task); } } } $etasks = reduceArray($tasks); require "class.ical.php"; $heute = date("d-m-y"); $cal = new vcalendar(); $fname = "tasks_" . $username . ".ics"; $cal->setConfig('directory', CL_ROOT . '/files/' . CL_CONFIG . '/ics'); $cal->setConfig('filename', $fname); $cal->setConfig('unique_id', ''); $cal->setProperty('X-WR-CALNAME', "Collabtive Aufgaben für " . $username); $cal->setProperty('X-WR-CALDESC', ''); $cal->setProperty('CALSCALE', 'GREGORIAN'); $cal->setProperty('METHOD', 'PUBLISH'); foreach ($etasks as $etask) { // split date in Y / M / D / h / min / sek variables $jahr = date("Y", $etask["start"]); $monat = date("m", $etask["start"]); $tag = date("d", $etask["start"]); $std = date("h", $etask["start"]); $min = date("i", $etask["start"]); $sek = date("s", $etask["start"]); // split date in Y / M / D / h / min / sek variables $ejahr = date("Y", $etask['end']); $emonat = date("m", $etask['end']); $etag = date("d", $etask['end']); $estd = date("h", $etask['end']); $emin = date("i", $etask['end']); $esek = date("s", $etask['end']); $e = new vevent(); $e->setProperty('categories', $etask['list']); if ($show_long) { // if we have a task lasting 10 month, normally it will be displayed every day within this time span. $e->setProperty('dtstart', $jahr, $monat, $tag, $std, $min); // 24 dec 2007 19.30 } else { // if the show_long flag is set, it will only be shown at the due date $e->setProperty('dtstart', $ejahr, $emonat, $etag, $estd, $emin); } $e->setProperty('due', $ejahr, $emonat, $etag, $estd, $emin); // 24 dec 2007 19.30 $e->setProperty('dtend', $ejahr, $emonat, $etag, $estd, $emin); $e->setProperty('description', $etask["text"]); $e->setProperty('status', "NEEDS-ACTION"); // $e->setProperty('comment' , $etask[text]); $e->setProperty('summary', $etask["title"]); $e->setProperty('location', 'Work'); $cal->setComponent($e); } $cal->returnCalendar(); return true; }