Пример #1
0
 /**
  * @return array
  */
 private function getICalPeriods()
 {
     $response = [];
     $iCalLink = $this->checkForICalHref();
     if ($this->checkAccessToFile($iCalLink)) {
         $startArray = array();
         $endArray = array();
         require_once 'iCalcreator.php';
         $v = new \vcalendar();
         // initiate new CALENDAR
         $config = array("unique_id" => "ukrapts.com", "url" => "{$iCalLink}");
         $v->setConfig($config);
         $v->parse();
         $v->sort();
         $i = 0;
         while ($comp = $v->getComponent("VEVENT")) {
             $dtstart_array = $comp->getProperty("DTSTART", 1, TRUE);
             $dtstart = $dtstart_array["value"];
             $startDate = "{$dtstart["year"]}-{$dtstart["month"]}-{$dtstart["day"]}";
             $dtend_array = $comp->getProperty("dtend", 1, TRUE);
             $dtend = $dtend_array["value"];
             $endDate = "{$dtend["year"]}-{$dtend["month"]}-{$dtend["day"]}";
             if ($endDate >= $this->DBQueries()->currentDate()) {
                 $startArray[] = $startDate;
                 $endArray[] = $endDate;
             }
             $i++;
         }
         sort($startArray);
         sort($endArray);
         $response['start'] = $startArray;
         $response['end'] = $endArray;
     }
     return $response;
 }
Пример #2
0
 /**
  * Creates an event in an iCalendar 
  * 
  * @param vcalendar $cal
  * @return vevent
  */
 public function createVevent($cal)
 {
     $event = $cal->newComponent('vevent');
     $event->setProperty('dtstart', $this->makeDateArray());
     // End date must be the day after to make it an all-day event
     $endDate = clone $this;
     $endDate->addDays(1);
     $event->setProperty('dtend', $endDate->makeDateArray());
     return $event;
 }
 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));
 }
Пример #4
0
 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);
 }
Пример #5
0
 public function onPreInit($param)
 {
     if (isset($_GET['idtm_termin'])) {
         $TerminRecord = TerminRecord::finder()->findByPK($_GET['idtm_termin']);
     } else {
         echo "Kein Termin";
         exit;
     }
     date_default_timezone_set('Europe/Berlin');
     $v = new vcalendar();
     // initiate new CALENDAR
     $v->setConfig('pliq_hpartner', 'planlogiq.com');
     // config with site domain
     $e = new vevent();
     // initiate a new EVENT
     $SDateArray = explode('-', $TerminRecord->ter_startdate);
     $EDateArray = explode('-', $TerminRecord->ter_enddate);
     $STimeArray = explode(':', $TerminRecord->ter_starttime);
     $ETimeArray = explode(':', $TerminRecord->ter_endtime);
     $e->setProperty('categories', ActivityRecord::finder()->findByPK($TerminRecord->idtm_activity)->act_name);
     // catagorize
     $e->setProperty('dtstart', $SDateArray[0], $SDateArray[1], $SDateArray[2], $STimeArray[0], $STimeArray[1], 00);
     // 24 dec 2006 19.30
     $e->setProperty('dtend', $EDateArray[0], $EDateArray[1], $EDateArray[2], $ETimeArray[0], $ETimeArray[1], 00);
     // 24 dec 2006 19.30
     //$e->setProperty( 'duration'
     //               , 0, 0, 3 );                    // 3 hours
     $e->setProperty('summary', $TerminRecord->ter_betreff);
     // describe the event
     $e->setProperty('description', $TerminRecord->ter_descr);
     // describe the event
     $e->setProperty('location', $TerminRecord->ter_ort);
     // locate the event
     $v->addComponent($e);
     // add component to calendar
     /* alt. production */
     // $v->returnCalendar();                       // generate and redirect output to user browser
     /* alt. dev. and test */
     $str = $v->createCalendar();
     // generate and get output in string, for testing?
     $this->getResponse()->appendHeader("Content-Type:" . $this->header);
     $this->getResponse()->appendHeader("Content-Disposition:inline;filename=" . $this->docName . '.' . $this->ext);
     echo $str;
     $writer->save('php://output');
     exit;
 }
Пример #6
0
 function display($tpl = null)
 {
     $mainframe = JFactory::getApplication();
     $option = JRequest::getCmd('option');
     $model = $this->getModel();
     $results = $model->getResults(JRequest::getVar('p', 0, '', 'int'));
     $project = $model->getProject(JRequest::getVar('p', 0, '', 'int'));
     $document = JFactory::getDocument();
     $v = new vcalendar();
     // initiate new CALENDAR
     $v->setConfig('project' . $project->id, $mainframe->getCfg('live_site'));
     // config with site domain
     $v->setProperty('X-WR-CALNAME', $project->name);
     // set some X-properties, name, content.. .
     $v->setProperty('X-WR-CALDESC', JText::_('COM_TRACKS_Project_calendar'));
     $v->setConfig("filename", 'project_' . $project->id . '.ics');
     foreach ((array) $results as $result) {
         if (!ereg('([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})', $result->start_date, $start_date)) {
             continue;
         }
         $e = new vevent();
         // initiate a new EVENT
         $e->setProperty('categories', $project->name);
         // catagorize
         $e->setProperty('dtstart', $start_date[1], $start_date[2], $start_date[3], $start_date[4], $start_date[5], $start_date[6]);
         if (ereg('([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})', $result->end_date, $end_date)) {
             $e->setProperty('dtend', $end_date[1], $end_date[2], $end_date[3], $end_date[4], $end_date[5], $end_date[6]);
         }
         $description = array();
         $description[] = $result->round_name;
         if ($result->winner && $result->winner->last_name) {
             $winner = JText::_('COM_TRACKS_Winner') . $result->winner->first_name . ' ' . $result->winner->last_name;
             if ($result->winner->team_name) {
                 $winner .= ' (' . $result->winner->team_name . ')';
             }
             $description[] = $winner;
         }
         $description = implode('\\n', $description);
         $e->setProperty('description', $description);
         // describe the event
         $e->setProperty('location', $result->round_name);
         // locate the event
         $v->addComponent($e);
         // add component to calendar
     }
     /* alt. production */
     // $v->returnCalendar();                       // generate and redirect output to user browser
     /* alt. dev. and test */
     $str = $v->createCalendar();
     // generate and get output in string, for testing?
     //      echo $str;return;
     $v->returnCalendar();
 }
Пример #7
0
 function __construct($name)
 {
     parent::__construct();
     $this->name = $name;
     $filename = $this->name . '.ics';
     $this->setConfig('directory', CALENDAR_DIR);
     // identify directory
     $this->setConfig('filename', $filename);
     // identify file name
     $this->parse();
 }
 function __construct($name, $description = "")
 {
     parent::__construct();
     //Ajout de quelques proporiétés
     $this->setProperty("method", "PUBLISH");
     $this->setProperty("x-wr-calname", $name);
     if ($description) {
         $this->setProperty("X-WR-CALDESC", $description);
     }
     $this->setProperty("X-WR-TIMEZONE", CAppUI::conf("timezone"));
 }
Пример #9
0
 /**
  * The file contents is looked at and events are created here.
  * @param string $fileContents
  * @return integer The number of events saved.
  */
 public function setEventsFromICal($fullDir, $fullFileName, $personId)
 {
     //start parse of local file
     $v = new vcalendar();
     // set directory
     $v->setConfig('directory', $fullDir);
     // set file name
     $v->setConfig('filename', $fullFileName);
     $v->parse();
     $count = 0;
     foreach ($v->components as $component => $info) {
         # get first vevent
         $comp = $v->getComponent("VEVENT");
         $summary_array = $comp->getProperty("summary", 1, TRUE);
         //echo "Event: ", $summary_array["value"], "\n";
         $dtstart_array = $comp->getProperty("dtstart", 1, TRUE);
         $dtstart = $dtstart_array["value"];
         $startDate = "{$dtstart["year"]}-{$dtstart["month"]}-{$dtstart["day"]}";
         $startTime = "{$dtstart["hour"]}:{$dtstart["min"]}:{$dtstart["sec"]}";
         $dtend_array = $comp->getProperty("dtend", 1, TRUE);
         $dtend = $dtend_array["value"];
         $endDate = "{$dtend["year"]}-{$dtend["month"]}-{$dtend["day"]}";
         $endTime = "{$dtend["hour"]}:{$dtend["min"]}:{$dtend["sec"]}";
         //echo "start: ",  $startDate,"T",$startTime, "\n";
         //echo "end: ",  $endDate,"T",$endTime, "\n";
         $location_array = $comp->getProperty("location", 1, TRUE);
         //echo "Location: ", $location_array["value"], "\n <br>";
         //TODO: Check that this event does not already exist.
         $event = new Event();
         $event->setPersonId($personId);
         $event->setName($summary_array["value"]);
         $event->setStartTime($startDate . "T" . $startTime);
         $event->setEndTime($endDate . "T" . $endTime);
         $event->setLocation($location_array["value"]);
         $event->save();
         $count++;
     }
     return $count;
 }
Пример #10
0
 function create($name, $description = '', $tz = 'US/Pacific')
 {
     $v = new vcalendar();
     $v->setConfig('unique_id', $name . '.' . 'yourdomain.com');
     $v->setProperty('method', 'PUBLISH');
     $v->setProperty('x-wr-calname', $name . ' Calendar');
     $v->setProperty("X-WR-CALDESC", $description);
     $v->setProperty("X-WR-TIMEZONE", $tz);
     $this->calendar = $v;
 }
Пример #11
0
 function exportar($aObj = array(), $directo_a_browser = 1)
 {
     if (is_array($aObj)) {
         $v = new vcalendar();
         $v->setConfig('DIRECTORY', sfConfig::get('sf_cache_dir'));
         foreach ($aObj as $link_evento) {
             if ($link_evento->getEvento()) {
                 $e = new vevent();
                 $e->setProperty('DESCRIPTION', '');
                 $e->setProperty('SUMMARY', $link_evento->getEvento()->getTitulo());
                 $e->setProperty('class', 'PUBLIC');
                 $aFechaInicio = getdate(strtotime($link_evento->getEvento()->getFechaInicio()));
                 $e->setProperty('dtstart', $aFechaInicio['year'], $aFechaInicio['mon'], $aFechaInicio['mday'], $aFechaInicio['hours'], $aFechaInicio['minutes'], 0);
                 $aFechaFin = getdate(strtotime($link_evento->getEvento()->getFechaFin()));
                 $e->setProperty('dtend', $aFechaFin['year'], $aFechaFin['mon'], $aFechaFin['mday'], $aFechaFin['hours'], $aFechaFin['minutes'], 0);
                 $e->setProperty('dtstamp', gmdate('Ymd\\THi00\\Z'));
                 if ($link_evento->getEvento()->getFrecuencia()) {
                     $freq = $this->aFreq[$link_evento->getEvento()->getFrecuencia()];
                     $interval = $link_evento->getEvento()->getFrecuenciaIntervalo();
                     $aRrule = array();
                     $aRrule['FREQ'] = $freq;
                     $aRrule['INTERVAL'] = $interval;
                     if ($freq == "WEEKLY") {
                         $aRrule['BYDAY'] = array_chunk(explode(",", $link_evento->getEvento()->getRecurrenciaDiasIcal()), 1);
                     }
                     if ($link_evento->getEvento()->getRecurrenciaFin() != "") {
                         if (is_numeric($link_evento->getEvento()->getRecurrenciaFin())) {
                             $aRrule['COUNT'] = $link_evento->getEvento()->getRecurrenciaFin();
                         } else {
                             $aRrule['UNTIL'] = gmdate('Ymd\\THi00\\Z', strtotime($link_evento->getEvento()->getRecurrenciaFin()));
                         }
                     }
                     $e->setProperty('rrule', $aRrule);
                 }
                 $v->addComponent($e);
             }
         }
         if ($directo_a_browser == 1) {
             $v->returnCalendar();
         } else {
             $v->saveCalendar();
             return $v->getConfig('filename');
         }
     } else {
         $error = 'No envío un array para la exportación';
         throw new Exception($error);
     }
 }
Пример #12
0
 /**
  * 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();
 }
Пример #13
0
 /**
  * Convert an event from a feed into a new Ai1ec_Event object and add it to
  * the calendar.
  *
  * @param Ai1ec_Event $event    Event object.
  * @param vcalendar   $calendar Calendar object.
  * @param bool        $export   States whether events are created for export.
  * @param array       $params   Additional parameters for export.
  *
  * @return void
  */
 protected function _insert_event_in_calendar(Ai1ec_Event $event, vcalendar $calendar, $export = false, array $params = array())
 {
     $tz = $this->_registry->get('date.timezone')->get_default_timezone();
     $e =& $calendar->newComponent('vevent');
     $uid = '';
     if ($event->get('ical_uid')) {
         $uid = addcslashes($event->get('ical_uid'), "\\;,\n");
     } else {
         $uid = $event->get_uid();
         $event->set('ical_uid', $uid);
         $event->save(true);
     }
     $e->setProperty('uid', $this->_sanitize_value($uid));
     $e->setProperty('url', get_permalink($event->get('post_id')));
     // =========================
     // = Summary & description =
     // =========================
     $e->setProperty('summary', $this->_sanitize_value(html_entity_decode(apply_filters('the_title', $event->get('post')->post_title), ENT_QUOTES, 'UTF-8')));
     $content = apply_filters('the_content', $event->get('post')->post_content);
     $content = str_replace(']]>', ']]&gt;', $content);
     $content = html_entity_decode($content, ENT_QUOTES, 'UTF-8');
     // Prepend featured image if available.
     $size = null;
     $avatar = $this->_registry->get('view.event.avatar');
     if ($img_url = $avatar->get_post_thumbnail_url($event, $size)) {
         $content = '<div class="ai1ec-event-avatar alignleft timely"><img src="' . esc_attr($img_url) . '" width="' . $size[0] . '" height="' . $size[1] . '" /></div>' . $content;
     }
     if (isset($params['no_html']) && $params['no_html']) {
         $e->setProperty('description', $this->_sanitize_value(strip_tags(strip_shortcodes($content))));
         if (!empty($content)) {
             $html_content = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">\\n' . '<HTML>\\n<HEAD>\\n<TITLE></TITLE>\\n</HEAD>\\n<BODY>' . $content . '</BODY></HTML>';
             $e->setProperty('X-ALT-DESC', $this->_sanitize_value($html_content), array('FMTTYPE' => 'text/html'));
             unset($html_content);
         }
     } else {
         $e->setProperty('description', $this->_sanitize_value($content));
     }
     $revision = (int) current(array_keys(wp_get_post_revisions($event->get('post_id'))));
     $e->setProperty('sequence', $revision);
     // =====================
     // = Start & end times =
     // =====================
     $dtstartstring = '';
     $dtstart = $dtend = array();
     if ($event->is_allday()) {
         $dtstart['VALUE'] = $dtend['VALUE'] = 'DATE';
         // For exporting all day events, don't set a timezone
         if ($tz && !$export) {
             $dtstart['TZID'] = $dtend['TZID'] = $tz;
         }
         // For exportin' all day events, only set the date not the time
         if ($export) {
             $e->setProperty('dtstart', $this->_sanitize_value($event->get('start')->format('Ymd')), $dtstart);
             $e->setProperty('dtend', $this->_sanitize_value($event->get('end')->format('Ymd')), $dtend);
         } else {
             $e->setProperty('dtstart', $this->_sanitize_value($event->get('start')->format("Ymd\\T")), $dtstart);
             $e->setProperty('dtend', $this->_sanitize_value($event->get('end')->format("Ymd\\T")), $dtend);
         }
     } else {
         if ($tz) {
             $dtstart['TZID'] = $dtend['TZID'] = $tz;
         }
         // This is used later.
         $dtstartstring = $event->get('start')->format("Ymd\\THis");
         $e->setProperty('dtstart', $this->_sanitize_value($dtstartstring), $dtstart);
         $e->setProperty('dtend', $this->_sanitize_value($event->get('end')->format("Ymd\\THis")), $dtend);
     }
     // ========================
     // = Latitude & longitude =
     // ========================
     if (floatval($event->get('latitude')) || floatval($event->get('longitude'))) {
         $e->setProperty('geo', $event->get('latitude'), $event->get('longitude'));
     }
     // ===================
     // = Venue & address =
     // ===================
     if ($event->get('venue') || $event->get('address')) {
         $location = array($event->get('venue'), $event->get('address'));
         $location = array_filter($location);
         $location = implode(' @ ', $location);
         $e->setProperty('location', $this->_sanitize_value($location));
     }
     $categories = array();
     $language = get_bloginfo('language');
     foreach ($this->_taxonomy_model->get_post_categories($event->get('post_id')) as $cat) {
         $categories[] = $cat->name;
     }
     $e->setProperty('categories', implode(',', $categories), array("LANGUAGE" => $language));
     $tags = array();
     foreach ($this->_taxonomy_model->get_post_tags($event->get('post_id')) as $tag) {
         $tags[] = $tag->name;
     }
     if (!empty($tags)) {
         $e->setProperty('X-TAGS', implode(',', $tags), array("LANGUAGE" => $language));
     }
     // ==================
     // = Cost & tickets =
     // ==================
     if ($event->get('cost')) {
         $e->setProperty('X-COST', $this->_sanitize_value($event->get('cost')));
     }
     if ($event->get('ticket_url')) {
         $e->setProperty('X-TICKETS-URL', $this->_sanitize_value($event->get_nonloggable_url($event->get('ticket_url'))));
     }
     // ====================================
     // = Contact name, phone, e-mail, URL =
     // ====================================
     $contact = array($event->get('contact_name'), $event->get('contact_phone'), $event->get('contact_email'), $event->get_nonloggable_url($event->get('contact_url')));
     $contact = array_filter($contact);
     $contact = implode('; ', $contact);
     $e->setProperty('contact', $this->_sanitize_value($contact));
     // ====================
     // = Recurrence rules =
     // ====================
     $rrule = array();
     $recurrence = $event->get('recurrence_rules');
     if (!empty($recurrence)) {
         $rules = array();
         foreach (explode(';', $event->get('recurrence_rules')) as $v) {
             if (strpos($v, '=') === false) {
                 continue;
             }
             list($k, $v) = explode('=', $v);
             $k = strtoupper($k);
             // If $v is a comma-separated list, turn it into array for iCalcreator
             switch ($k) {
                 case 'BYSECOND':
                 case 'BYMINUTE':
                 case 'BYHOUR':
                 case 'BYDAY':
                 case 'BYMONTHDAY':
                 case 'BYYEARDAY':
                 case 'BYWEEKNO':
                 case 'BYMONTH':
                 case 'BYSETPOS':
                     $exploded = explode(',', $v);
                     break;
                 default:
                     $exploded = $v;
                     break;
             }
             // iCalcreator requires a more complex array structure for BYDAY...
             if ($k == 'BYDAY') {
                 $v = array();
                 foreach ($exploded as $day) {
                     $v[] = array('DAY' => $day);
                 }
             } else {
                 $v = $exploded;
             }
             $rrule[$k] = $v;
         }
     }
     // ===================
     // = Exception rules =
     // ===================
     $exceptions = $event->get('exception_rules');
     $exrule = array();
     if (!empty($exceptions)) {
         $rules = array();
         foreach (explode(';', $exceptions) as $v) {
             if (strpos($v, '=') === false) {
                 continue;
             }
             list($k, $v) = explode('=', $v);
             $k = strtoupper($k);
             // If $v is a comma-separated list, turn it into array for iCalcreator
             switch ($k) {
                 case 'BYSECOND':
                 case 'BYMINUTE':
                 case 'BYHOUR':
                 case 'BYDAY':
                 case 'BYMONTHDAY':
                 case 'BYYEARDAY':
                 case 'BYWEEKNO':
                 case 'BYMONTH':
                 case 'BYSETPOS':
                     $exploded = explode(',', $v);
                     break;
                 default:
                     $exploded = $v;
                     break;
             }
             // iCalcreator requires a more complex array structure for BYDAY...
             if ($k == 'BYDAY') {
                 $v = array();
                 foreach ($exploded as $day) {
                     $v[] = array('DAY' => $day);
                 }
             } else {
                 $v = $exploded;
             }
             $exrule[$k] = $v;
         }
     }
     // add rrule to exported calendar
     if (!empty($rrule)) {
         $e->setProperty('rrule', $this->_sanitize_value($rrule));
     }
     // add exrule to exported calendar
     if (!empty($exrule)) {
         $e->setProperty('exrule', $this->_sanitize_value($exrule));
     }
     // ===================
     // = Exception dates =
     // ===================
     // For all day events that use a date as DTSTART, date must be supplied
     // For other other events which use DATETIME, we must use that as well
     // We must also match the exact starting time
     $exception_dates = $event->get('exception_dates');
     if (!empty($exception_dates)) {
         $params = array('VALUE' => 'DATE-TIME', 'TZID' => $tz);
         $dt_suffix = $event->get('start')->format('\\THis');
         foreach (explode(',', $exception_dates) as $exdate) {
             $exdate = $this->_registry->get('date.time', $exdate)->format('Ymd');
             $e->setProperty('exdate', array($exdate . $dt_suffix), $params);
         }
     }
     return $calendar;
 }
Пример #14
0
$e->setProperty('categories', 'PERSONAL');
$e->setProperty('categories', 'SPECIAL OCCASION');
$e->setProperty('rrule', array('FREQ' => 'YEARLY'));
echo nl2br($v->createCalendar());
// generate and get output in string, for testing?
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(array('unique_id' => 'kigkonsult.se'));
$t =& $c->newComponent('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');
echo nl2br($v->createCalendar());
// generate and get output in string, for testing?
Пример #15
0
 function _get_events_url(&$events, $url, $date)
 {
     $v = new vcalendar();
     $v->setConfig('unique_id', 'barchat');
     $v->setProperty('method', 'PUBLISH');
     $v->setProperty("x-wr-calname", "Calendar Sample");
     $v->setProperty("X-WR-CALDESC", "Calendar Description");
     $v->setProperty("X-WR-TIMEZONE", "America/New_York");
     $v->setConfig('url', $url);
     try {
         $v->parse();
     } catch (exception $e) {
     }
     $v->sort();
     $m = $date->format('n');
     $d = $date->format('j');
     $y = $date->format('Y');
     $eventArray = $v->selectComponents($y, $m, 1, $y, $m, 31);
     foreach ((array) $eventArray as $yearkey => $yeararray) {
         foreach ((array) $yeararray as $monthkey => $montharray) {
             foreach ((array) $montharray as $daykey => $dayarray) {
                 foreach ((array) $dayarray as $eventnumber => $event) {
                     //echo "{$y}-{$m}-{$daykey} [{$eventnumber}]: ";
                     $time = $event->dtstart['value'];
                     $tz = $event->dtstart['params']['TZID'] == '' ? 'America/New_York' : $event->dtstart['params']['TZID'];
                     if ($time['tz'] == 'Z') {
                         $tz = 'GMT';
                     }
                     if (isset($event->dtstart['params']['VALUE']) && $event->dtstart['params']['VALUE'] == 'DATE') {
                         $allday = new DateTime("{$time['year']}-{$time['month']}-{$time['day']}", new DateTimeZone($tz));
                         $allday->setTimezone(new DateTimeZone('America/New_York'));
                         $d = sprintf('%04d-%02d-%02d', $y, $m, $daykey);
                         if (!is_array($events[$d])) {
                             $events[$d] = array();
                         }
                         $alldayint = intval($allday->format('U'));
                         while (isset($events[$d][$alldayint])) {
                             $alldayint++;
                         }
                         $events[$d][$alldayint] = '<span class="calendartime">All Day</span> ' . trim($event->summary['value']);
                         //var_dump(date('r', $allday) . ' = ' . $allday);
                         //var_dump($event->summary['value']);
                     } else {
                         if (isset($event->xprop['X-CURRENT-DTSTART'])) {
                             $dt = new DateTime($event->xprop['X-CURRENT-DTSTART']['value'], new DateTimeZone($tz));
                         } else {
                             $dt = new DateTime("{$time['year']}-{$time['month']}-{$time['day']} {$time['hour']}:{$time['min']}:{$time['sec']}", new DateTimeZone($tz));
                         }
                         $dt->setTimezone(new DateTimeZone('America/New_York'));
                         if (isset($event->xprop['X-CURRENT-DTEND'])) {
                             $dte = new DateTime($event->xprop['X-CURRENT-DTEND']['value'], new DateTimeZone($tz));
                         } else {
                             $timee = $event->dtstart['value'];
                             $dte = new DateTime("{$timee['year']}-{$timee['month']}-{$timee['day']} {$timee['hour']}:{$timee['min']}:{$timee['sec']}", new DateTimeZone($tz));
                         }
                         $dte->setTimezone(new DateTimeZone('America/New_York'));
                         if (!is_array($events[$d])) {
                             $events[$d] = array();
                         }
                         $d = sprintf('%04d-%02d-%02d', $y, $m, $daykey);
                         $daytime = $dt->format('U');
                         while (isset($events[$d][$daytime])) {
                             $daytime++;
                         }
                         if ($dt->format('g:ia') != $dte->format('g:ia')) {
                             $events[$d][$daytime] = '<span class="calendartime">' . $dt->format('g:ia') . ' - ' . $dte->format('g:ia') . '</span> ' . trim($event->summary['value']);
                         } else {
                             $events[$d][$daytime] = '<span class="calendartime">' . $dt->format('g:ia') . '</span> ' . trim($event->summary['value']);
                         }
                         //var_dump($event->dtstart);
                         //var_dump($event->summary['value']);
                         //var_dump($dt->format('r'));
                         //var_dump($event);
                     }
                 }
             }
         }
     }
 }
Пример #16
0
 /**
  *  Generate ical file content
  *
  * @param $who             user ID
  * @param $who_group       group ID
  * @param $limititemtype   itemtype only display this itemtype (default '')
  *
  * @return icalendar string
  **/
 static function generateIcal($who, $who_group, $limititemtype = '')
 {
     global $CFG_GLPI;
     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");
     }
     $tz = date_default_timezone_get();
     $v->setConfig('TZID', $tz);
     $v->setProperty("method", "PUBLISH");
     $v->setProperty("version", "2.0");
     $v->setProperty("X-WR-TIMEZONE", $tz);
     $xprops = array("X-LIC-LOCATION" => $tz);
     iCalUtilityFunctions::createTimezone($v, $tz, $xprops);
     $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);
     $params = array('who' => $who, 'who_group' => $who_group, 'begin' => $begin, 'end' => $end);
     $interv = array();
     if (empty($limititemtype)) {
         foreach ($CFG_GLPI['planning_types'] as $itemtype) {
             $interv = array_merge($interv, $itemtype::populatePlanning($params));
         }
     } else {
         $interv = $limititemtype::populatePlanning($params);
     }
     if (count($interv) > 0) {
         foreach ($interv as $key => $val) {
             $vevent = new vevent();
             //initiate EVENT
             if (isset($val['itemtype'])) {
                 if (isset($val[getForeignKeyFieldForItemType($val['itemtype'])])) {
                     $vevent->setProperty("uid", $val['itemtype'] . "#" . $val[getForeignKeyFieldForItemType($val['itemtype'])]);
                 } else {
                     $vevent->setProperty("uid", "Other#" . $key);
                 }
             } else {
                 $vevent->setProperty("uid", "Other#" . $key);
             }
             $vevent->setProperty("dstamp", $val["begin"]);
             $vevent->setProperty("dtstart", $val["begin"]);
             $vevent->setProperty("dtend", $val["end"]);
             if (isset($val["tickets_id"])) {
                 $vevent->setProperty("summary", sprintf(__('Ticket #%1$s %2$s'), $val["tickets_id"], $val["name"]));
             } else {
                 if (isset($val["name"])) {
                     $vevent->setProperty("summary", $val["name"]);
                 }
             }
             if (isset($val["content"])) {
                 $text = $val["content"];
                 // be sure to replace nl by \r\n
                 $text = preg_replace("/<br( [^>]*)?" . ">/i", "\r\n", $text);
                 $text = Html::clean($text);
                 $vevent->setProperty("description", $text);
             } else {
                 if (isset($val["name"])) {
                     $text = $val["name"];
                     // be sure to replace nl by \r\n
                     $text = preg_replace("/<br( [^>]*)?" . ">/i", "\r\n", $text);
                     $text = Html::clean($text);
                     $vevent->setProperty("description", $text);
                 }
             }
             if (isset($val["url"])) {
                 $vevent->setProperty("url", $val["url"]);
             }
             $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->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 );
 }
Пример #18
0
             }
             $myOut = registry::register('file_handler')->FileLink('rss/' . $data['url'], 'eqdkp', 'relative');
         }
     }
     break;
     // generate an ical feed
 // generate an ical feed
 case 'icalfeed':
     // the permissions for the single modules
     $permissions = array('calendar' => 'po_calendarevent');
     $modulename = registry::register('input')->get('module', '');
     // check for permission
     $userid = registry::fetch('user')->getUserIDfromExchangeKey(registry::register('input')->get('key', ''));
     if (isset($permissions[$modulename]) && registry::fetch('user')->check_auth($permissions[$modulename], false, $userid)) {
         require $eqdkp_root_path . 'libraries/icalcreator/iCalcreator.class.php';
         $v = new vcalendar();
         $v->setConfig('unique_id', registry::register('config')->get('server_name'));
         $v->setProperty('x-wr-calname', sprintf(registry::fetch('user')->lang('icalfeed_name'), registry::register('config')->get('guildtag')));
         $v->setProperty('X-WR-CALDESC', registry::fetch('user')->lang('icalfeed_description'));
         // set the timezone - required by some clients
         $timezone = registry::register('config')->get('timezone');
         $v->setProperty("X-WR-TIMEZONE", $timezone);
         iCalUtilityFunctions::createTimezone($v, $timezone, array("X-LIC-LOCATION" => $timezone));
         switch ($modulename) {
             case 'calendar':
                 $eventtypes = registry::register('input')->get('type', 'raids');
                 switch ($eventtypes) {
                     case 'raids':
                         $eventsfilter = true;
                         break;
                     case 'all':
Пример #19
0
 /**
  * function iCal2xls
  *
  * Convert iCal file to xls format and send file to browser (default) or save xls file to disk
  * Definition iCal  : rcf2445, http://kigkonsult.se/downloads/index.php#rfc
  * Using iCalcreator: http://kigkonsult.se/downloads/index.php#iCalcreator
  * Based on PEAR Spreadsheet_Excel_Writer-0.9.1 (and OLE-1.0.0RC1)
  * to be installed as
  * pear install channel://pear.php.net/OLE-1.0.0RC1
  * pear install channel://pear.php.net/Spreadsheet_Excel_Writer-0.9.1
  *
  * @author Kjell-Inge Gustafsson <*****@*****.**>
  * @since  3.0 - 2011-12-21
  * @param  object $calendar opt. iCalcreator calendar instance
  * @return bool   returns FALSE when error
  */
 public function iCal2xls($calendar = FALSE)
 {
     $timeexec = array('start' => microtime(TRUE));
     if ($this->log) {
         $this->log->log(' ********** START **********', PEAR_LOG_NOTICE);
     }
     /** check input/output directory and filename */
     $inputdirFile = $outputdirFile = '';
     $inputFileParts = $outputFileParts = array();
     $remoteInput = $remoteOutput = FALSE;
     if ($calendar) {
         $inputdirFile = $calendar->getConfig('DIRFILE');
         $inputFileParts = pathinfo($inputdirFile);
         $inputFileParts['dirname'] = realpath($inputFileParts['dirname']);
         if ($this->log) {
             $this->log->log('fileParts:' . var_export($inputFileParts, TRUE), PEAR_LOG_DEBUG);
         }
     } elseif (FALSE === $this->_fixIO('input', 'ics', $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'] . '.xls')) {
             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'] . '.xls';
         $outputFileParts = pathinfo($outputdirFile);
         if ($this->log) {
             $this->log->log("output set to '{$outputdirFile}'", PEAR_LOG_INFO);
         }
     }
     if ($this->log) {
         $this->log->log("INPUT..FILE:{$inputdirFile}", PEAR_LOG_NOTICE);
         $this->log->log("OUTPUT.FILE:{$outputdirFile}", PEAR_LOG_NOTICE);
     }
     $save = $this->getConfig('save');
     if ($calendar) {
         $calnl = $calendar->getConfig('nl');
     } else {
         /** iCalcreator set config, read and parse input iCal file */
         $calendar = new vcalendar();
         if (FALSE !== ($unique_id = $this->getConfig('unique_id'))) {
             $calendar->setConfig('unique_id', $unique_id);
         }
         $calnl = $calendar->getConfig('nl');
         if ($remoteInput) {
             if (FALSE === $calendar->setConfig('url', $inputdirFile)) {
                 if ($this->log) {
                     $this->log->log("ERROR 3 INPUT FILE:'{$inputdirFile}' iCalcreator: invalid url", 3);
                 }
                 return FALSE;
             }
         } else {
             if (FALSE === $calendar->setConfig('directory', $inputFileParts['dirname'])) {
                 if ($this->log) {
                     $this->log->log("ERROR 4 INPUT FILE:'{$inputdirFile}' iCalcreator: invalid directory: '" . $inputFileParts['dirname'] . "'", 3);
                     $this->log->flush();
                 }
                 return FALSE;
             }
             if (FALSE === $calendar->setConfig('filename', $inputFileParts['basename'])) {
                 if ($this->log) {
                     $this->log->log("ERROR 5 INPUT FILE:'{$inputdirFile}' iCalcreator: invalid filename: '" . $inputFileParts['basename'] . "'", 3);
                     $this->log->flush();
                 }
                 return FALSE;
             }
         }
         if (FALSE === $calendar->parse()) {
             if ($this->log) {
                 $this->log->log("ERROR 6 INPUT FILE:'{$inputdirFile}' iCalcreator parse error", 3);
                 $this->log->flush();
             }
             return FALSE;
         }
     }
     // end if( !$calendar )
     $timeexec['fileOk'] = microtime(TRUE);
     if (!function_exists('iCaldate2timestamp')) {
         function iCaldate2timestamp($d)
         {
             if (6 > count($d)) {
                 return mktime(0, 0, 0, $d['month'], $d['day'], $d['year']);
             } else {
                 return mktime($d['hour'], $d['min'], $d['sec'], $d['month'], $d['day'], $d['year']);
             }
         }
     }
     if (!function_exists('fixiCalString')) {
         function fixiCalString($s)
         {
             global $calnl;
             $s = str_replace('\\,', ',', $s);
             $s = str_replace('\\;', ';', $s);
             $s = str_replace('\\n ', chr(10), $s);
             $s = str_replace('\\\\', '\\', $s);
             $s = str_replace("{$calnl}", chr(10), $s);
             return utf8_decode($s);
         }
     }
     /** Creating a workbook */
     require_once 'Spreadsheet/Excel/Writer.php';
     if ($save) {
         $workbook = new Spreadsheet_Excel_Writer($outputdirFile);
     } else {
         $workbook = new Spreadsheet_Excel_Writer();
     }
     $workbook->setVersion(8);
     // Use Excel97/2000 Format
     /** opt. sending HTTP headers */
     if (!$save) {
         $workbook->send($outputFileParts['basename']);
     }
     /** Creating a worksheet */
     $worksheet =& $workbook->addWorksheet($inputFileParts['filename']);
     /** fix formats */
     $format_bold =& $workbook->addFormat();
     $format_bold->setBold();
     $timeexec['wrkbkOk'] = microtime(TRUE);
     /** info rows */
     $row = -1;
     $worksheet->writeString(++$row, 0, 'kigkonsult.se', $format_bold);
     $worksheet->writeString($row, 1, ICALCREATOR_VERSION, $format_bold);
     $worksheet->writeString($row, 2, ICALCNVVERSION . ' iCal2xls', $format_bold);
     $worksheet->writeString($row, 3, date('Y-m-d H:i:s'));
     $filename = $remoteInput ? $inputdirFile : $inputFileParts['basename'];
     $worksheet->writeString(++$row, 0, 'iCal input', $format_bold);
     $worksheet->writeString($row, 1, $filename);
     $worksheet->writeString($row, 2, 'xls output', $format_bold);
     $worksheet->writeString($row, 3, $outputFileParts['basename']);
     if (FALSE !== ($prop = $calendar->getProperty('CALSCALE'))) {
         $worksheet->writeString(++$row, 0, 'CALSCALE', $format_bold);
         $worksheet->writeString($row, 1, $prop);
     }
     if (FALSE !== ($prop = $calendar->getProperty('METHOD'))) {
         $worksheet->writeString(++$row, 0, 'METHOD', $format_bold);
         $worksheet->writeString($row, 1, $prop);
     }
     while (FALSE !== ($xprop = $calendar->getProperty())) {
         $worksheet->writeString(++$row, 0, $xprop[0], $format_bold);
         $worksheet->writeString($row, 1, $xprop[1]);
     }
     $timeexec['infoOk'] = microtime(TRUE);
     if (FALSE === ($propsToSkip = $this->getConfig('skip'))) {
         $propsToSkip = array();
     }
     /** fix property order list */
     $proporderOrg = array();
     for ($key = 2; $key < 99; $key++) {
         if (FALSE !== ($value = $this->getConfig($key))) {
             $proporderOrg[$value] = $key;
             if ($this->log) {
                 $this->log->log("{$value} in column {$key}", 7);
             }
         }
     }
     /** fix vtimezone property order list */
     $proporder = $proporderOrg;
     $proporder['TYPE'] = 0;
     $proporder['ORDER'] = 1;
     $props = array('TZID', 'LAST-MODIFIED', 'TZURL', 'DTSTART', 'TZOFFSETTO', 'TZOFFSETFROM', 'COMMENT', 'RRULE', 'RDATE', 'TZNAME');
     $pix = 2;
     foreach ($props as $prop) {
         if (isset($proporder[$prop])) {
             continue;
         }
         if (in_array($prop, $propsToSkip)) {
             if ($this->log) {
                 $this->log->log("'{$prop}' removed from output", 7);
             }
             continue;
         }
         while (in_array($pix, $proporder)) {
             $pix++;
         }
         $proporder[$prop] = $pix++;
     }
     /** remove unused properties from and add x-props to property order list */
     $maxpropix = 11;
     if ($maxpropix != count($proporder) - 1) {
         $maxpropix = count($proporder) - 1;
     }
     $compsinfo = $calendar->getConfig('compsinfo');
     $potmp = array();
     $potmp[0] = 'TYPE';
     $potmp[1] = 'ORDER';
     foreach ($compsinfo as $cix => $compinfo) {
         if ('vtimezone' != $compinfo['type']) {
             continue;
         }
         $comp = $calendar->getComponent($compinfo['ordno']);
         foreach ($compinfo['props'] as $propName => $propcnt) {
             if (!in_array($propName, $potmp) && isset($proporder[$propName])) {
                 $potmp[$proporder[$propName]] = $propName;
             } elseif ('X-PROP' == $propName) {
                 while ($xprop = $comp->getProperty()) {
                     if (!in_array($xprop[0], $potmp)) {
                         $maxpropix += 1;
                         $potmp[$maxpropix] = $xprop[0];
                     }
                     // end if
                 }
                 // end while xprop
             }
             // end X-PROP
         }
         // end $compinfo['props']
         if (isset($compinfo['sub'])) {
             foreach ($compinfo['sub'] as $compinfo2) {
                 foreach ($compinfo2['props'] as $propName => $propcnt) {
                     if (!in_array($propName, $potmp) && isset($proporder[$propName])) {
                         $potmp[$proporder[$propName]] = $propName;
                     } elseif ('X-PROP' == $propName) {
                         $scomp = $comp->getComponent($compinfo2['ordno']);
                         while ($xprop = $scomp->getProperty()) {
                             if (!in_array($xprop[0], $potmp)) {
                                 $maxpropix += 1;
                                 $potmp[$maxpropix] = $xprop[0];
                             }
                             // end if
                         }
                         // end while xprop
                     }
                     // end X-PROP
                 }
                 // end $compinfo['sub']['props']
             }
             // end foreach( $compinfo['sub']
         }
         // end if( isset( $compinfo['sub']
     }
     // end foreach compinfo - vtimezone
     ksort($potmp, SORT_NUMERIC);
     $proporder = array_flip(array_values($potmp));
     if ($this->log) {
         $this->log->log("timezone proporder=" . implode(',', array_flip($proporder)), 7);
     }
     /** create vtimezone info */
     if (2 < count($proporder)) {
         $row += 1;
         /** create vtimezone header row */
         foreach ($proporder as $propName => $col) {
             if (isset($this->config[$propName])) {
                 $worksheet->writeString($row, $col, $this->config[$propName], $format_bold);
                 // check map of userfriendly name to iCal property name
                 if ($this->log) {
                     $this->log->log("header row, col={$col}: {$propName}, replaced by " . $this->config[$propName], 7);
                 }
             } else {
                 $worksheet->writeString($row, $col, $propName, $format_bold);
             }
         }
         $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'));
         /** create vtimezone data rows */
         foreach ($compsinfo as $cix => $compinfo) {
             if ('vtimezone' != $compinfo['type']) {
                 continue;
             }
             $row += 1;
             $worksheet->writeString($row, $proporder['TYPE'], $compinfo['type']);
             $worksheet->writeString($row, $proporder['ORDER'], $compinfo['ordno']);
             $comp = $calendar->getComponent($compinfo['ordno']);
             foreach ($proporder as $propName => $col) {
                 if ('TYPE' == $propName || 'ORDER' == $propName) {
                     continue;
                 }
                 if ('X-' == substr($propName, 0, 2)) {
                     continue;
                 }
                 if (!in_array($propName, $allowedProps['VTIMEZONE'])) {
                     // check if component allows property
                     if ($this->log) {
                         $this->log->log("ERROR 7, INPUT FILE:'{$inputdirFile}' iCalcreator: unvalid property for component '" . $compinfo['type'] . "': '{$propName}'", PEAR_LOG_INFO);
                     }
                     continue;
                 }
                 if (isset($compinfo['props'][$propName])) {
                     if ('LAST-MODIFIED' == $propName) {
                         $fcn = 'createLastModified';
                     } else {
                         $fcn = 'create' . strtoupper(substr($propName, 0, 1)) . strtolower(substr($propName, 1));
                     }
                     if (!method_exists($comp, $fcn)) {
                         if ($this->log) {
                             $this->log->log('ERROR 8 INPUT FILE:"' . $filename . '" iCalcreator: unknown property: "' . $propName . '" (' . $fcn . ')', PEAR_LOG_INFO);
                         }
                         continue;
                     }
                     $output = str_replace("{$calnl} ", '', rtrim($comp->{$fcn}()));
                     $output = str_replace($propName . ';', '', $output);
                     $output = str_replace($propName . ':', '', $output);
                     $worksheet->writeString($row, $proporder[$propName], fixiCalString($output));
                 }
             }
             // end foreach( $proporder
             if (isset($compinfo['props']['X-PROP'])) {
                 while ($xprop = $comp->getProperty()) {
                     $output = str_replace("{$calnl} ", '', rtrim($xprop[1]));
                     $worksheet->writeString($row, $proporder[$xprop[0]], fixiCalString($output));
                 }
             }
             if (isset($compinfo['sub'])) {
                 foreach ($compinfo['sub'] as $compinfo2) {
                     $row += 1;
                     $worksheet->writeString($row, $proporder['TYPE'], $compinfo2['type']);
                     $worksheet->writeString($row, $proporder['ORDER'], $compinfo['ordno'] . ':' . $compinfo2['ordno']);
                     $scomp = $comp->getComponent($compinfo2['ordno']);
                     foreach ($proporder as $propName => $col) {
                         if ('TYPE' == $propName || 'ORDER' == $propName) {
                             continue;
                         }
                         if ('X-' == substr($propName, 0, 2)) {
                             continue;
                         }
                         if (!in_array($propName, $allowedProps[strtoupper($compinfo2['type'])])) {
                             // check if component allows property
                             if ($this->log) {
                                 $this->log->log("ERROR 9, INPUT FILE:'{$inputdirFile}' iCalcreator: unvalid property for component '" . $compinfo2['type'] . "': '{$propName}'", PEAR_LOG_INFO);
                             }
                             continue;
                         }
                         if (isset($compinfo2['props'][$propName])) {
                             $fcn = 'create' . strtoupper(substr($propName, 0, 1)) . strtolower(substr($propName, 1));
                             if (!method_exists($scomp, $fcn)) {
                                 if ($this->log) {
                                     $this->log->log('ERROR 10 INPUT FILE:"' . $filename . '" iCalcreator: unknown property: "' . $propName . '" (' . $fcn . ')', PEAR_LOG_INFO);
                                 }
                                 continue;
                             }
                             $output = str_replace("{$calnl} ", '', rtrim($scomp->{$fcn}()));
                             $output = str_replace($propName . ';', '', $output);
                             $output = str_replace($propName . ':', '', $output);
                             $worksheet->writeString($row, $proporder[$propName], fixiCalString($output));
                         }
                     }
                     // end foreach( $proporder
                     if (isset($compinfo2['props']['X-PROP'])) {
                         while ($xprop = $scomp->getProperty()) {
                             $output = str_replace("{$calnl} ", '', rtrim($xprop[1]));
                             $worksheet->writeString($row, $proporder[$xprop[0]], fixiCalString($output));
                         }
                     }
                 }
                 // end foreach( $compinfo['sub']
             }
             // end if( isset( $compinfo['sub']['props'] ))
         }
         // end foreach
     }
     // end vtimezone
     $timeexec['zoneOk'] = microtime(TRUE);
     $maxColCount = count($proporder);
     /** fix property order list */
     $proporder = $proporderOrg;
     $proporder['TYPE'] = 0;
     $proporder['ORDER'] = 1;
     $props = array('UID', 'DTSTAMP', 'SUMMARY', 'DTSTART', 'DURATION', 'DTEND', 'DUE', 'RRULE', 'RDATE', 'EXRULE', 'EXDATE', 'DESCRIPTION', 'CATEGORIES', 'ORGANIZER', 'LOCATION', 'RESOURCES', 'CONTACT', 'URL', 'COMMENT', 'PRIORITY', 'ATTENDEE', 'CLASS', 'TRANSP', 'SEQUENCE', 'STATUS', 'COMPLETED', 'CREATED', 'LAST-MODIFIED', 'ACTION', 'TRIGGER', 'REPEAT', 'ATTACH', 'FREEBUSY', 'RELATED-TO', 'REQUEST-STATUS', 'GEO', 'PERCENT-COMPLETE', 'RECURRENCE-ID');
     $pix = 2;
     foreach ($props as $prop) {
         if (isset($proporder[$prop])) {
             continue;
         }
         if (in_array($prop, $propsToSkip)) {
             if ($this->log) {
                 $this->log->log("'{$prop}' removed from output", 7);
             }
             continue;
         }
         while (in_array($pix, $proporder)) {
             $pix++;
         }
         $proporder[$prop] = $pix++;
     }
     /** remove unused properties from and add x-props to property order list */
     if ($maxpropix < count($proporder) - 1) {
         $maxpropix = count($proporder) - 1;
     }
     $potmp = array();
     $potmp[0] = 'TYPE';
     $potmp[1] = 'ORDER';
     //  $potmp[2]                   =  'UID';
     foreach ($compsinfo as $cix => $compinfo) {
         if ('vtimezone' == $compinfo['type']) {
             continue;
         }
         foreach ($compinfo['props'] as $propName => $propcnt) {
             if (!in_array($propName, $potmp) && isset($proporder[$propName])) {
                 $potmp[$proporder[$propName]] = $propName;
             } elseif ('X-PROP' == $propName) {
                 $comp = $calendar->getComponent($compinfo['ordno']);
                 while ($xprop = $comp->getProperty()) {
                     if (!in_array($xprop[0], $potmp)) {
                         $maxpropix += 1;
                         $potmp[$maxpropix] = $xprop[0];
                     }
                     // end if
                 }
                 // while( $xprop
             }
             // end elseif( 'X-PROP'
         }
         // end foreach( $compinfo['props']
         if (isset($compinfo['sub'])) {
             foreach ($compinfo['sub'] as $compinfo2) {
                 foreach ($compinfo2['props'] as $propName => $propcnt) {
                     if (!in_array($propName, $potmp) && isset($proporder[$propName])) {
                         $potmp[$proporder[$propName]] = $propName;
                     } elseif ('X-PROP' == $propName) {
                         $scomp = $comp->getComponent($compinfo2['ordno']);
                         while ($xprop = $scomp->getProperty()) {
                             if (!in_array($xprop[0], $potmp)) {
                                 $maxpropix += 1;
                                 $potmp[$maxpropix] = $xprop[0];
                             }
                             // end if
                         }
                         // end while xprop
                     }
                     // end X-PROP
                 }
                 // end $compinfo['sub']['props']
             }
             // end foreach( $compinfo['sub']
         }
         // end if( isset( $compinfo['sub']
     }
     ksort($potmp, SORT_NUMERIC);
     $proporder = array_flip(array_values($potmp));
     if ($this->log) {
         $this->log->log("comp proporder=" . implode(',', array_flip($proporder)), 7);
     }
     if ($maxColCount < count($proporder)) {
         $maxColCount = count($proporder);
     }
     /** create header row */
     $row += 1;
     foreach ($proporder as $propName => $col) {
         if (isset($this->config[$propName])) {
             $worksheet->writeString($row, $col, $this->config[$propName], $format_bold);
             // check map of userfriendly name to iCal property name
             if ($this->log) {
                 $this->log->log("header row, col={$col}: {$propName}, replaced by " . $this->config[$propName], 7);
             }
         } else {
             $worksheet->writeString($row, $col, $propName, $format_bold);
         }
     }
     $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'));
     /** create data rows */
     foreach ($compsinfo as $cix => $compinfo) {
         if ('vtimezone' == $compinfo['type']) {
             continue;
         }
         $row += 1;
         $worksheet->writeString($row, $proporder['TYPE'], $compinfo['type']);
         $worksheet->writeString($row, $proporder['ORDER'], $compinfo['ordno']);
         //    $worksheet->write(         $row, $proporder['UID'],   $compinfo['uid'] );
         $comp = $calendar->getComponent($compinfo['ordno']);
         foreach ($proporder as $propName => $col) {
             if ('TYPE' == $propName || 'ORDER' == $propName) {
                 continue;
             }
             if ('X-' == substr($propName, 0, 2)) {
                 continue;
             }
             if (!in_array($propName, $allowedProps[strtoupper($compinfo['type'])])) {
                 // check if component allows property
                 if ($this->log) {
                     $this->log->log("ERROR 11, INPUT FILE:'{$inputdirFile}' iCalcreator: unvalid property for component '" . $compinfo['type'] . "': '{$propName}'", PEAR_LOG_INFO);
                 }
                 continue;
             }
             if (isset($compinfo['props'][$propName])) {
                 switch ($propName) {
                     case 'LAST-MODIFIED':
                         $fcn = 'createLastModified';
                         break;
                     case 'RECURRENCE-ID':
                         $fcn = 'createRecurrenceid';
                         break;
                     case 'RELATED-TO':
                         $fcn = 'createRelatedTo';
                         break;
                     case 'REQUEST-STATUS':
                         $fcn = 'createRequestStatus';
                         break;
                     case 'PERCENT-COMPLETE':
                         $fcn = 'createPercentComplete';
                         break;
                     default:
                         $fcn = 'create' . strtoupper(substr($propName, 0, 1)) . strtolower(substr($propName, 1));
                 }
                 if (!method_exists($comp, $fcn)) {
                     if ($this->log) {
                         $this->log->log("ERROR 12 INPUT FILE:'{$filename}' iCalcreator: unknown property: '{$propName}' ({$fcn})", PEAR_LOG_INFO);
                     }
                     continue;
                 }
                 $output = str_replace("{$calnl} ", '', rtrim($comp->{$fcn}()));
                 $output = str_replace($propName . ';', '', $output);
                 $output = str_replace($propName . ':', '', $output);
                 $worksheet->writeString($row, $proporder[$propName], fixiCalString($output));
             }
         }
         // end foreach( $proporder
         if (isset($compinfo['props']['X-PROP'])) {
             while ($xprop = $comp->getProperty()) {
                 $output = str_replace("{$calnl} ", '', rtrim($xprop[1]));
                 $worksheet->writeString($row, $proporder[$xprop[0]], fixiCalString($output));
             }
         }
         if (isset($compinfo['sub'])) {
             foreach ($compinfo['sub'] as $compinfo2) {
                 $row += 1;
                 $worksheet->writeString($row, $proporder['TYPE'], $compinfo2['type']);
                 $worksheet->writeString($row, $proporder['ORDER'], $compinfo['ordno'] . ':' . $compinfo2['ordno']);
                 $scomp = $comp->getComponent($compinfo2['ordno']);
                 foreach ($proporder as $propName => $col) {
                     if ('TYPE' == $propName || 'ORDER' == $propName) {
                         continue;
                     }
                     if ('X-' == substr($propName, 0, 2)) {
                         continue;
                     }
                     if (!in_array($propName, $allowedProps[strtoupper($compinfo2['type'])])) {
                         // check if component allows property
                         if ($this->log) {
                             $this->log->log("ERROR 13, INPUT FILE:'{$inputdirFile}' iCalcreator: unvalid property for component '" . $compinfo2['type'] . "': '{$propName}'", PEAR_LOG_INFO);
                         }
                         continue;
                     }
                     if (isset($compinfo2['props'][$propName])) {
                         $fcn = 'create' . strtoupper(substr($propName, 0, 1)) . strtolower(substr($propName, 1));
                         if (!method_exists($scomp, $fcn)) {
                             if ($this->log) {
                                 $this->log->log("ERROR 14 INPUT FILE:'{$filename}' iCalcreator: unknown property: '{$propName}' ({$fcn})", PEAR_LOG_INFO);
                             }
                             continue;
                         }
                         $output = str_replace("{$calnl} ", '', rtrim($scomp->{$fcn}()));
                         $output = str_replace($propName . ';', '', $output);
                         $output = str_replace($propName . ':', '', $output);
                         $worksheet->writeString($row, $proporder[$propName], fixiCalString($output));
                     }
                     // end if( isset( $compinfo2['props'][$propName]
                 }
                 // end foreach( $proporder
                 if (isset($compinfo2['props']['X-PROP'])) {
                     while ($xprop = $scomp->getProperty()) {
                         $output = str_replace("{$calnl} ", '', rtrim($xprop[1]));
                         $output = str_replace('\\n ', chr(10), $output);
                         $worksheet->writeString($row, $proporder[$xprop[0]], fixiCalString($output));
                     }
                 }
                 // end if( isset( $compinfo2['props']['X-PROP']
             }
             // end foreach( $compinfo['sub']
         }
         // end if( isset( $compinfo['sub']
     }
     // foreach( $compsinfo as
     if ($this->log) {
         $timeexec['exit'] = microtime(TRUE);
         $msg = "'{$filename}'";
         $msg .= ' fileOk:' . number_format($timeexec['fileOk'] - $timeexec['start'], 5);
         $msg .= ' wrkbkOk:' . number_format($timeexec['wrkbkOk'] - $timeexec['fileOk'], 5);
         $msg .= ' infoOk:' . number_format($timeexec['infoOk'] - $timeexec['wrkbkOk'], 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';
         $msg .= ', ' . ($row + 1) . " rows, {$maxColCount} cols";
         $this->log->log($msg, PEAR_LOG_DEBUG);
         $msg = "'{$filename}' (" . count($compsinfo) . ' components) start:' . date('H:i:s', $timeexec['start']);
         $msg .= ' total:' . number_format($timeexec['exit'] - $timeexec['start'], 5) . 'sec';
         if ($save) {
             $msg .= " saved as '{$outputdirFile}'";
         } else {
             $msg .= " redirected as '" . $outputFileParts['basename'] . "'";
         }
         $this->log->log($msg, PEAR_LOG_NOTICE);
     }
     /** Close and, opt., send the file */
     if ($this->log) {
         $this->log->flush();
     }
     $workbook->close();
     return TRUE;
 }
 /**
  * Convert an event from a feed into a new Ai1ec_Event object and add it to
  * the calendar.
  *
  * @param Ai1ec_Event $event    Event object
  * @param vcalendar   $calendar Calendar object
  * @param bool        $export   States whether events are created for export
  *
  * @return void
  */
 function insert_event_in_calendar(Ai1ec_Event $event, vcalendar &$calendar, $export = false)
 {
     global $ai1ec_events_helper;
     $tz = Ai1ec_Meta::get_option('timezone_string');
     $e =& $calendar->newComponent('vevent');
     $uid = '';
     if ($event->ical_uid) {
         $uid = addcslashes($event->ical_uid, "\\;,\n");
     } else {
         $uid = sprintf($this->get_uid_format(), $event->post->ID);
     }
     $e->setProperty('uid', $this->_sanitize_value($uid));
     $e->setProperty('url', get_permalink($event->post_id));
     // =========================
     // = Summary & description =
     // =========================
     $e->setProperty('summary', $this->_sanitize_value(html_entity_decode(apply_filters('the_title', $event->post->post_title), ENT_QUOTES, 'UTF-8')));
     $content = apply_filters('the_content', $event->post->post_content);
     $content = str_replace(']]>', ']]&gt;', $content);
     $content = html_entity_decode($content, ENT_QUOTES, 'UTF-8');
     // Prepend featured image if available.
     $size = null;
     if ($img_url = $event->get_post_thumbnail_url($size)) {
         $content = '<div class="ai1ec-event-avatar alignleft timely"><img src="' . esc_attr($img_url) . '" width="' . $size[0] . '" height="' . $size[1] . '" /></div>' . $content;
     }
     $e->setProperty('description', $this->_sanitize_value($content));
     // =====================
     // = Start & end times =
     // =====================
     $dtstartstring = '';
     $dtstart = $dtend = array();
     if ($event->allday) {
         $dtstart["VALUE"] = $dtend["VALUE"] = 'DATE';
         // For exporting all day events, don't set a timezone
         if ($tz && !$export) {
             $dtstart["TZID"] = $dtend["TZID"] = $tz;
         }
         // For exportin' all day events, only set the date not the time
         if ($export) {
             $e->setProperty('dtstart', $this->_sanitize_value(gmdate("Ymd", $ai1ec_events_helper->gmt_to_local($event->start))), $dtstart);
             $e->setProperty('dtend', $this->_sanitize_value(gmdate("Ymd", $ai1ec_events_helper->gmt_to_local($event->end))), $dtend);
         } else {
             $e->setProperty('dtstart', $this->_sanitize_value(gmdate("Ymd\\T", $ai1ec_events_helper->gmt_to_local($event->start))), $dtstart);
             $e->setProperty('dtend', $this->_sanitize_value(gmdate("Ymd\\T", $ai1ec_events_helper->gmt_to_local($event->end))), $dtend);
         }
     } else {
         if ($tz) {
             $dtstart["TZID"] = $dtend["TZID"] = $tz;
         }
         // This is used later.
         $dtstartstring = gmdate("Ymd\\THis", $ai1ec_events_helper->gmt_to_local($event->start));
         $e->setProperty('dtstart', $this->_sanitize_value($dtstartstring), $dtstart);
         $e->setProperty('dtend', $this->_sanitize_value(gmdate("Ymd\\THis", $ai1ec_events_helper->gmt_to_local($event->end))), $dtend);
     }
     // ========================
     // = Latitude & longitude =
     // ========================
     if (floatval($event->latitude) || floatval($event->longitude)) {
         $e->setProperty('geo', $event->latitude, $event->longitude);
     }
     // ===================
     // = Venue & address =
     // ===================
     if ($event->venue || $event->address) {
         $location = array($event->venue, $event->address);
         $location = array_filter($location);
         $location = implode(' @ ', $location);
         $e->setProperty('location', $this->_sanitize_value($location));
     }
     $categories = array();
     $language = get_bloginfo('language');
     foreach (wp_get_post_terms($event->post_id, 'events_categories') as $cat) {
         $categories[] = $cat->name;
     }
     $e->setProperty('categories', implode(',', $categories), array("LANGUAGE" => $language));
     $tags = array();
     foreach (wp_get_post_terms($event->post_id, 'events_tags') as $tag) {
         $tags[] = $tag->name;
     }
     if (!empty($tags)) {
         $e->setProperty('X-TAGS', implode(',', $tags), array("LANGUAGE" => $language));
     }
     // ==================
     // = Cost & tickets =
     // ==================
     if ($event->cost) {
         $e->setProperty('X-COST', $this->_sanitize_value($event->cost));
     }
     if ($event->ticket_url) {
         $e->setProperty('X-TICKETS-URL', $this->_sanitize_value($event->ticket_url));
     }
     // ====================================
     // = Contact name, phone, e-mail, URL =
     // ====================================
     $contact = array($event->contact_name, $event->contact_phone, $event->contact_email, $event->contact_url);
     $contact = array_filter($contact);
     $contact = implode('; ', $contact);
     $e->setProperty('contact', $this->_sanitize_value($contact));
     // ====================
     // = Recurrence rules =
     // ====================
     $rrule = array();
     if (!empty($event->recurrence_rules)) {
         $rules = array();
         foreach (explode(';', $event->recurrence_rules) as $v) {
             if (strpos($v, '=') === false) {
                 continue;
             }
             list($k, $v) = explode('=', $v);
             $k = strtoupper($k);
             // If $v is a comma-separated list, turn it into array for iCalcreator
             switch ($k) {
                 case 'BYSECOND':
                 case 'BYMINUTE':
                 case 'BYHOUR':
                 case 'BYDAY':
                 case 'BYMONTHDAY':
                 case 'BYYEARDAY':
                 case 'BYWEEKNO':
                 case 'BYMONTH':
                 case 'BYSETPOS':
                     $exploded = explode(',', $v);
                     break;
                 default:
                     $exploded = $v;
                     break;
             }
             // iCalcreator requires a more complex array structure for BYDAY...
             if ($k == 'BYDAY') {
                 $v = array();
                 foreach ($exploded as $day) {
                     $v[] = array('DAY' => $day);
                 }
             } else {
                 $v = $exploded;
             }
             $rrule[$k] = $v;
         }
     }
     // ===================
     // = Exception rules =
     // ===================
     $exrule = array();
     if (!empty($event->exception_rules)) {
         $rules = array();
         foreach (explode(';', $event->exception_rules) as $v) {
             if (strpos($v, '=') === false) {
                 continue;
             }
             list($k, $v) = explode('=', $v);
             $k = strtoupper($k);
             // If $v is a comma-separated list, turn it into array for iCalcreator
             switch ($k) {
                 case 'BYSECOND':
                 case 'BYMINUTE':
                 case 'BYHOUR':
                 case 'BYDAY':
                 case 'BYMONTHDAY':
                 case 'BYYEARDAY':
                 case 'BYWEEKNO':
                 case 'BYMONTH':
                 case 'BYSETPOS':
                     $exploded = explode(',', $v);
                     break;
                 default:
                     $exploded = $v;
                     break;
             }
             // iCalcreator requires a more complex array structure for BYDAY...
             if ($k == 'BYDAY') {
                 $v = array();
                 foreach ($exploded as $day) {
                     $v[] = array('DAY' => $day);
                 }
             } else {
                 $v = $exploded;
             }
             $exrule[$k] = $v;
         }
     }
     // add rrule to exported calendar
     if (!empty($rrule)) {
         $e->setProperty('rrule', $this->_sanitize_value($rrule));
     }
     // add exrule to exported calendar
     if (!empty($exrule)) {
         $e->setProperty('exrule', $this->_sanitize_value($exrule));
     }
     // ===================
     // = Exception dates =
     // ===================
     // For all day events that use a date as DTSTART, date must be supplied
     // For other other events which use DATETIME, we must use that as well
     // We must also match the exact starting time
     if (!empty($event->exception_dates)) {
         foreach (explode(',', $event->exception_dates) as $exdate) {
             if ($event->allday) {
                 // the local date will be always something like 20121122T000000Z
                 // we just need the date
                 $exdate = substr($ai1ec_events_helper->exception_dates_to_local($exdate), 0, 8);
                 $e->setProperty('exdate', array($exdate), array('VALUE' => 'DATE'));
             } else {
                 $params = array();
                 if ($tz) {
                     $params["TZID"] = $tz;
                 }
                 $exdate = $ai1ec_events_helper->exception_dates_to_local($exdate);
                 // get only the date + T
                 $exdate = substr($exdate, 0, 9);
                 // Take the time from
                 $exdate .= substr($dtstartstring, 9);
                 $e->setProperty('exdate', array($exdate), $params);
             }
         }
     }
 }
Пример #21
0
 /**
  *  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();
 }
Пример #22
0
 /**
  * Export to the specified format
  * @param array	$input	-	ATutor dates to be exported
  * @param int $mode	-	Mode of operation of export [ 0 | 1 ] 
  *							*	mode 0 - returns the exported dates as a string
  *							* 	mode 1 - returns the name of the file that has the exported dates
  * @param string $format - Export Format	DEFAULT 'ical'
  * @return string
  * @author Anurup Raveendran
  *
  */
 function cal_export($input = null, $mode, $format = 'ical')
 {
     $cal = "";
     //output
     $user = "";
     if ($input == null) {
         $time_zone = "";
     } else {
         $time_zone = $input['timezone'];
     }
     global $db;
     require_once 'iCalcreator.class.php';
     require_once 'html_parser.inc.php';
     $v = new vcalendar(array('unique_id' => 'Inclusive Design Insitute'));
     //create an instance of the ical obj
     // ADD EXTRA DETAILS
     if (isset($_SESSION['member_id'])) {
         // GET USER DETAILS
         $m_id = $_SESSION['member_id'];
         // GET TIME ZONE
         // CHECK USER TABLE FOR PREF_TIMEZONE
         $sql = "SELECT first_name,last_name,preferences FROM " . TABLE_PREFIX . "members WHERE member_id='" . $m_id . "'";
         $result = mysql_query($sql, $db) or die(mysql_error());
         $row = mysql_fetch_assoc($result);
         $user = $row['first_name'] . ' ' . $row['last_name'];
         if ($time_zone == "") {
             $prefs = unserialize($row['preferences']);
             $time_zone_offset = $prefs['PREF_TIMEZONE'];
             if ($time_zone_offset == "") {
                 // CHECK CONFIG TABLE SET BY ADMIN
                 $sql = "SELECT value \n\t\t\t\t\tFROM " . TABLE_PREFIX . "config\n\t\t\t\t\tWHERE name='pref_defaults'";
                 $result = mysql_query($sql, $db) or die(mysql_error());
                 if (mysql_num_rows($result) > 0) {
                     //pref_defaults is set
                     $row = mysql_fetch_row($result);
                     $prefs = unserialize($row[0]);
                     $time_zone_offset = $prefs['PREF_TIMEZONE'];
                 }
             }
             if ($time_zone_offset != "") {
                 $sql = "SELECT time_zone \n\t\t\t\t\t\tFROM " . TABLE_PREFIX . "calendar_timezone_offset \n\t\t\t\t\t\tWHERE offset='" . $time_zone_offset . "'";
                 $result = mysql_query($sql, $db) or die(mysql_error());
                 $row = mysql_fetch_row($result);
                 $time_zone = $row[0];
             } else {
                 // GET TIMEZONE FROM SERVER
                 $version = phpversion();
                 $version = str_replace('Current PHP version: ', '', $version);
                 $version = explode('.', $version);
                 if ($version[0] > 4) {
                     $time_zone = date_default_timezone_get();
                 } else {
                     // get from ini file
                     $time_zone = ini_get('date.timezone');
                 }
                 $sql = "SELECT offset \n\t\t\t\t\t\t\tFROM " . TABLE_PREFIX . "calendar_timezone_offset \n\t\t\t\t\t\t\tWHERE time_zone='" . $time_zone . "'";
                 $result = mysql_query($sql, $db) or die(mysql_error());
                 $row = mysql_fetch_row($result);
                 $time_zone_offset = $row[0];
             }
         } else {
             $sql = "SELECT offset \n\t\t\t\t\t\t\tFROM " . TABLE_PREFIX . "calendar_timezone_offset \n\t\t\t\t\t\t\tWHERE time_zone='" . $time_zone . "'";
             $result = mysql_query($sql, $db) or die(mysql_error());
             $row = mysql_fetch_row($result);
             $time_zone_offset = $row[0];
         }
     }
     /** HEADER **/
     $v->setProperty('X-WR-CALNAME', $user);
     $v->setProperty('X-WR-CALDESC', 'ATutor Dates');
     $v->setProperty('X-WR-TIMEZONE', $time_zone);
     // set the ical timezone component
     $e =& $v->newComponent('vtimezone');
     $e->setProperty('TZID', $time_zone);
     $e->setProperty('X-LIC-LOCATION', $time_zone);
     $t =& $e->newComponent('standard');
     $t->setProperty('tzoffsetfrom', $this->get_tz_offset($time_zone_offset));
     $t->setProperty('tzoffsetto', $this->get_tz_offset($time_zone_offset));
     $t->setProperty('dtstart', 1970, 1, 1, 0, 0, 00);
     /** HEADER **/
     // NOW LOAD THE EVENTS
     global $moduleFactory;
     $coursesmod = $moduleFactory->getModule("_core/courses");
     $assignmentsmod = $moduleFactory->getModule("_standard/assignments");
     $testsmod = $moduleFactory->getModule("_standard/tests");
     // GET ALL THE COURSES THE USER IS ENROLLED IN
     $sql = "SELECT course_id\n            \tFROM " . TABLE_PREFIX . "course_enrollment \n            \tWHERE member_id = '" . $_SESSION['member_id'] . "'";
     $course_result = mysql_query($sql, $db) or die(mysql_error());
     while ($row = mysql_fetch_row($course_result)) {
         $course = $coursesmod->extend_date($row[0]);
         $course = $course[0];
         // get the dates
         $course_start_unix_ts = $course[0]['unixts'];
         $course_end_unix_ts = $course[1]['unixts'];
         $cs =& $v->newComponent('vevent');
         // initiate COURSE_START event
         $cs->setProperty('dtstart', date("Y", $course_start_unix_ts), date("n", $course_start_unix_ts), date("j", $course_start_unix_ts), date("G", $course_start_unix_ts), date("m", $course_start_unix_ts), date("i", $course_start_unix_ts));
         // COURSE_START DTSTART
         $cs->setProperty('dtend', date("Y", $course_start_unix_ts), date("n", $course_start_unix_ts), date("j", $course_start_unix_ts), date("G", $course_start_unix_ts), date("m", $course_start_unix_ts), date("i", $course_start_unix_ts));
         // COURSE_START DTEND
         $cs->setProperty('dtstamp', date("Y"), date("n"), date("j"), date("G"), date("m"), date("i"));
         // CALENDAR TS
         //parse the html content to get the summary
         $html = str_get_html($course[0]['content']);
         foreach ($html->find('div.content') as $d) {
             $div = $d;
         }
         foreach ($div->find('span.module') as $m) {
             $module = $m->innertext;
         }
         foreach ($div->find('span.title') as $tl) {
             $title = $tl->innertext;
         }
         foreach ($div->find('span.content') as $c) {
             $content = $c->innertext;
         }
         unset($html);
         unset($div);
         $summary = $module . $title . $content;
         $cs->setProperty('summary', $summary);
         // SUMMARY
         $cs->setProperty('sequence', 0);
         // SEQUENCE NUMBER
         $cs->setProperty('status', 'CONFIRMED');
         // STATUS
         $cs->setProperty('transp', 'TRANSPARENT');
         // TRANSPARENCY
         $ce =& $v->newComponent('vevent');
         // initiate COURSE_END event
         $ce->setProperty('dtstart', date("Y", $course_end_unix_ts), date("n", $course_end_unix_ts), date("j", $course_end_unix_ts), date("G", $course_end_unix_ts), date("m", $course_end_unix_ts), date("i", $course_end_unix_ts));
         // COURSE_END DTSTART
         $ce->setProperty('dtend', date("Y", $course_end_unix_ts), date("n", $course_end_unix_ts), date("j", $course_end_unix_ts), date("G", $course_end_unix_ts), date("m", $course_end_unix_ts), date("i", $course_end_unix_ts));
         // COURSE_END DTEND
         $ce->setProperty('dtstamp', date("Y"), date("n"), date("j"), date("G"), date("m"), date("i"));
         // CALENDAR TS
         //parse the html content to get the summary
         $html = str_get_html($course[1]['content']);
         foreach ($html->find('div.content') as $d) {
             $div = $d;
         }
         foreach ($div->find('span.module') as $m) {
             $module = $m->innertext;
         }
         foreach ($div->find('span.title') as $tl) {
             $title = $tl->innertext;
         }
         foreach ($div->find('span.content') as $c) {
             $content = $c->innertext;
         }
         unset($html);
         unset($div);
         $summary = $module . $title . $content;
         $ce->setProperty('summary', $summary);
         // SUMMARY
         $ce->setProperty('sequence', 0);
         // SEQUENCE NUMBER
         $ce->setProperty('status', 'CONFIRMED');
         // STATUS
         $ce->setProperty('transp', 'TRANSPARENT');
         // TRANSPARENCY
         //GET THE ASSIGNMENTS FOR THIS COURSE
         $assignments = $assignmentsmod->extend_date($row[0]);
         foreach ($assignments as $key => $assignment) {
             // get the dates
             $assignment_due_unix_ts = $assignment[0]['unixts'];
             $assignment_cutoff_unix_ts = $assignment[1]['unixts'];
             $ad =& $v->newComponent('vevent');
             // initiate ASSIGNMENT_DUE event
             $ad->setProperty('dtstart', date("Y", $assignment_due_unix_ts), date("n", $assignment_due_unix_ts), date("j", $assignment_due_unix_ts), date("G", $assignment_due_unix_ts), date("m", $assignment_due_unix_ts), date("i", $assignment_due_unix_ts));
             // ASSIGNMENT_DUE DTSTART
             $ad->setProperty('dtend', date("Y", $assignment_due_unix_ts), date("n", $assignment_due_unix_ts), date("j", $assignment_due_unix_ts), date("G", $assignment_due_unix_ts), date("m", $assignment_due_unix_ts), date("i", $assignment_due_unix_ts));
             // ASSIGNMENT_DUE DTEND
             $ad->setProperty('dtstamp', date("Y"), date("n"), date("j"), date("G"), date("m"), date("i"));
             // WHEN THE CAL WAS EXPORTED
             //parse the html content to get the summary
             $html = str_get_html($assignment[0]['content']);
             foreach ($html->find('div.content') as $d) {
                 $div = $d;
             }
             foreach ($div->find('span.module') as $m) {
                 $module = $m->innertext;
             }
             foreach ($div->find('span.title') as $tl) {
                 $title = $tl->innertext;
             }
             foreach ($div->find('span.content') as $c) {
                 $content = $c->innertext;
             }
             unset($html);
             unset($div);
             $summary = $module . $title . $content;
             $ad->setProperty('summary', $summary);
             // SUMMARY
             $ad->setProperty('sequence', 0);
             $ad->setProperty('status', 'CONFIRMED');
             // STATUS
             $ad->setProperty('transp', 'TRANSPARENT');
             // TRANSPARENCY
             $ac =& $v->newComponent('vevent');
             // initiate ASSIGNMENT_CUTOFF event
             $ac->setProperty('dtstart', date("Y", $assignment_cutoff_unix_ts), date("n", $assignment_cutoff_unix_ts), date("j", $assignment_cutoff_unix_ts), date("G", $assignment_cutoff_unix_ts), date("m", $assignment_cutoff_unix_ts), date("i", $assignment_cutoff_unix_ts));
             // ASSIGNMENT_CUTOFF DTSTART
             $ac->setProperty('dtend', date("Y", $assignment_cutoff_unix_ts), date("n", $assignment_cutoff_unix_ts), date("j", $assignment_cutoff_unix_ts), date("G", $assignment_cutoff_unix_ts), date("m", $assignment_cutoff_unix_ts), date("i", $assignment_cutoff_unix_ts));
             // ASSIGNMENT_CUTOFF DTEND
             $ac->setProperty('dtstamp', date("Y"), date("n"), date("j"), date("G"), date("m"), date("i"));
             // WHEN THE CAL WAS EXPORTED
             //parse the html content to get the summary
             $html = str_get_html($assignment[1]['content']);
             foreach ($html->find('div.content') as $d) {
                 $div = $d;
             }
             foreach ($div->find('span.module') as $m) {
                 $module = $m->innertext;
             }
             foreach ($div->find('span.title') as $tl) {
                 $title = $tl->innertext;
             }
             foreach ($div->find('span.content') as $c) {
                 $content = $c->innertext;
             }
             unset($html);
             unset($div);
             $summary = $module . $title . $content;
             $ac->setProperty('summary', $summary);
             // SUMMARY
             $ac->setProperty('sequence', 0);
             $ac->setProperty('status', 'CONFIRMED');
             // STATUS
             $ac->setProperty('transp', 'TRANSPARENT');
             // TRANSPARENCY
         }
         //GET THE TESTS FOR THIS COURSE
         $tests = $testsmod->extend_date($row[0]);
         foreach ($tests as $test) {
             // get the dates
             $test_start_unix_ts = $test[0]['unixts'];
             $test_end_unix_ts = $test[1]['unixts'];
             $ts =& $v->newComponent('vevent');
             // initiate TEST_START event
             $ts->setProperty('dtstart', date("Y", $test_start_unix_ts), date("n", $test_start_unix_ts), date("j", $test_start_unix_ts), date("G", $test_start_unix_ts), date("m", $test_start_unix_ts), date("i", $test_start_unix_ts));
             // TEST_START DTSTART
             $ts->setProperty('dtend', date("Y", $test_start_unix_ts), date("n", $test_start_unix_ts), date("j", $test_start_unix_ts), date("G", $test_start_unix_ts), date("m", $test_start_unix_ts), date("i", $test_start_unix_ts));
             // TEST_START DTEND
             $ts->setProperty('dtstamp', date("Y"), date("n"), date("j"), date("G"), date("m"), date("i"));
             // CALENDAR TS
             //parse the html content to get the summary
             $html = str_get_html($test[0]['content']);
             foreach ($html->find('div.content') as $d) {
                 $div = $d;
             }
             foreach ($div->find('span.module') as $m) {
                 $module = $m->innertext;
             }
             foreach ($div->find('span.title') as $tl) {
                 $title = $tl->innertext;
             }
             foreach ($div->find('span.content') as $c) {
                 $content = $c->innertext;
             }
             unset($html);
             unset($div);
             $summary = $module . $title . $content;
             $ts->setProperty('summary', $summary);
             // SUMMARY
             $ts->setProperty('sequence', 0);
             // SEQUENCE NUMBER
             $ts->setProperty('status', 'CONFIRMED');
             // STATUS
             $ts->setProperty('transp', 'TRANSPARENT');
             // TRANSPARENCY
             $te =& $v->newComponent('vevent');
             // initiate TEST_END EVENT
             $te->setProperty('dtstart', date("Y", $test_end_unix_ts), date("n", $test_end_unix_ts), date("j", $test_end_unix_ts), date("G", $test_end_unix_ts), date("m", $test_end_unix_ts), date("i", $test_end_unix_ts));
             // TEST_END DTSTART
             $te->setProperty('dtend', date("Y", $test_end_unix_ts), date("n", $test_end_unix_ts), date("j", $test_end_unix_ts), date("G", $test_end_unix_ts), date("m", $test_end_unix_ts), date("i", $test_end_unix_ts));
             // TEST_END DTEND
             $te->setProperty('dtstamp', date("Y"), date("n"), date("j"), date("G"), date("m"), date("i"));
             // CALENDAR TS
             //parse the html content to get the summary
             $html = str_get_html($test[1]['content']);
             foreach ($html->find('div.content') as $d) {
                 $div = $d;
             }
             foreach ($div->find('span.module') as $m) {
                 $module = $m->innertext;
             }
             foreach ($div->find('span.title') as $tl) {
                 $title = $tl->innertext;
             }
             foreach ($div->find('span.content') as $c) {
                 $content = $c->innertext;
             }
             unset($html);
             unset($div);
             $summary = $module . $title . $content;
             $te->setProperty('summary', $summary);
             // SUMMARY
             $te->setProperty('sequence', 0);
             // SEQUENCE NUMBER
             $te->setProperty('status', 'CONFIRMED');
             // STATUS
             $te->setProperty('transp', 'TRANSPARENT');
             // TRANSPARENCY
         }
     }
     $str = $v->createCalendar();
     return $str;
 }
Пример #23
0
$id = explode('_', $_GET['id']);
$type = $id[0];
$id = $id[1];
$agenda = new Agenda();
$agenda->type = $type;
//course,admin or personal
if (isset($_GET['course_id'])) {
    $course_info = api_get_course_info_by_id($_GET['course_id']);
    if (!empty($course_info)) {
        $agenda->set_course($course_info);
    }
}
$event = $agenda->get_event($id);
if (!empty($event)) {
    define('ICAL_LANG', api_get_language_isocode());
    $ical = new vcalendar();
    $ical->setConfig('unique_id', api_get_path(WEB_PATH));
    $ical->setProperty('method', 'PUBLISH');
    $ical->setConfig('url', api_get_path(WEB_PATH));
    $vevent = new vevent();
    switch ($_GET['class']) {
        case 'public':
            $vevent->setClass('PUBLIC');
            break;
        case 'private':
            $vevent->setClass('PRIVATE');
            break;
        case 'confidential':
            $vevent->setClass('CONFIDENTIAL');
            break;
        default:
Пример #24
0
 /**
  * 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());
 }
 public function generate_ical()
 {
     $eventdata = $this->pdh->get('calendar_events', 'data', array($this->url_id));
     require $this->root_path . 'libraries/icalcreator/iCalcreator.class.php';
     $v = new vcalendar();
     $v->setConfig('unique_id', $this->config->get('server_name'));
     $v->setProperty('x-wr-calname', sprintf(registry::fetch('user')->lang('icalfeed_name'), registry::register('config')->get('guildtag')));
     $v->setProperty('X-WR-CALDESC', registry::fetch('user')->lang('icalfeed_description'));
     // set the timezone - required by some clients
     $timezone = registry::register('config')->get('timezone');
     $v->setProperty("X-WR-TIMEZONE", $timezone);
     iCalUtilityFunctions::createTimezone($v, $timezone, array("X-LIC-LOCATION" => $timezone));
     // Generate the vevents...
     $e = new vevent();
     $e->setProperty('dtstart', array("timestamp" => $eventdata['timestamp_start'] . 'Z'));
     $e->setProperty('dtend', array("timestamp" => $eventdata['timestamp_end'] . 'Z'));
     $e->setProperty('dtstamp', array("timestamp" => $this->time->time));
     $e->setProperty('summary', $this->pdh->get('event', 'name', array($eventdata['extension']['raid_eventid'])));
     $e->setProperty('description', $eventdata['notes']);
     $e->setProperty('class', 'PUBLIC');
     $e->setProperty('categories', 'PERSONAL');
     $v->setComponent($e);
     // Save or Output the ICS File..
     if ($icsfile == true) {
         $v->setConfig('filename', $icsfile);
         $v->saveCalendar();
     } else {
         header('Content-type: text/calendar; charset=utf-8;');
         header('Content-Disposition: filename=raidevent-' . $eventdata['timestamp_start'] . '.ics');
         echo $v->createCalendar();
         exit;
     }
 }
Пример #26
0
$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;
 /**
  * export_events function
  *
  * Export events
  *
  * @return void
  **/
 function export_events()
 {
     global $ai1ec_events_helper, $ai1ec_exporter_helper, $ai1ec_localization_helper;
     $ai1ec_cat_ids = !empty($_REQUEST['ai1ec_cat_ids']) ? $_REQUEST['ai1ec_cat_ids'] : false;
     $ai1ec_tag_ids = !empty($_REQUEST['ai1ec_tag_ids']) ? $_REQUEST['ai1ec_tag_ids'] : false;
     $ai1ec_post_ids = !empty($_REQUEST['ai1ec_post_ids']) ? $_REQUEST['ai1ec_post_ids'] : false;
     if (!empty($_REQUEST['lang'])) {
         $ai1ec_localization_helper->set_language($_REQUEST['lang']);
     }
     $filter = array();
     if ($ai1ec_cat_ids) {
         $filter['cat_ids'] = explode(',', $ai1ec_cat_ids);
     }
     if ($ai1ec_tag_ids) {
         $filter['tag_ids'] = explode(',', $ai1ec_tag_ids);
     }
     if ($ai1ec_post_ids) {
         $filter['post_ids'] = explode(',', $ai1ec_post_ids);
     }
     // when exporting events by post_id, do not look up the event's start/end date/time
     $start = $ai1ec_post_ids !== false ? false : Ai1ec_Time_Utility::current_time(true) - 24 * 60 * 60;
     // Include any events ending today
     $end = false;
     $c = new vcalendar();
     $c->setProperty('calscale', 'GREGORIAN');
     $c->setProperty('method', 'PUBLISH');
     $c->setProperty('X-WR-CALNAME', get_bloginfo('name'));
     $c->setProperty('X-WR-CALDESC', get_bloginfo('description'));
     $c->setProperty('X-FROM-URL', home_url());
     // Timezone setup
     $tz = Ai1ec_Meta::get_option('timezone_string');
     if ($tz) {
         $c->setProperty('X-WR-TIMEZONE', $tz);
         $tz_xprops = array('X-LIC-LOCATION' => $tz);
         iCalUtilityFunctions::createTimezone($c, $tz, $tz_xprops);
     }
     $events = $ai1ec_events_helper->get_matching_events($start, $end, $filter);
     foreach ($events as $event) {
         $ai1ec_exporter_helper->insert_event_in_calendar($event, $c, $export = true);
     }
     $str = ltrim($c->createCalendar());
     header('Content-type: text/calendar; charset=utf-8');
     echo $str;
     exit;
 }
Пример #28
0
 public function import_ics_data($calendar_id)
 {
     // -------------------------------------
     //	Get some basic info to use later
     // -------------------------------------
     $cbasics = $this->data->calendar_basics();
     $cbasics = $cbasics[$calendar_id];
     $urls = $cbasics['ics_url'];
     if ($urls == '') {
         return FALSE;
     }
     $tz_offset = $cbasics['tz_offset'] != '' ? $cbasics['tz_offset'] : '0000';
     /*
     
     		This shouldn't be happening because DST is only something that
     		would need to be applied when generating the users current local time.
     		If an event were at 7pm EST or EDT, it would still be at 7pm either way.
     		I hate DST.
     
     		if ($tz_offset != '0000' AND ee()->config->item('daylight_savings') == 'y')
     		{
     			$tz_offset += 100;
     		}
     */
     $channel_id = $this->data->channel_is_events_channel();
     $author_id = $cbasics['author_id'];
     // -------------------------------------
     //	Prepare the URLs
     // -------------------------------------
     if (!is_array($urls)) {
         $urls = explode("\n", $urls);
     }
     foreach ($urls as $k => $url) {
         $urls[$k] = trim($url);
     }
     // -------------------------------------
     //	Load iCalCreator
     // -------------------------------------
     if (!class_exists('vcalendar')) {
         require_once CALENDAR_PATH_ASSETS . 'icalcreator/iCalcreator.class.php';
     }
     // -------------------------------------
     //	Load Calendar_datetime
     // -------------------------------------
     if (!class_exists('Calendar_datetime')) {
         require_once CALENDAR_PATH . 'calendar.datetime' . EXT;
     }
     $CDT = new Calendar_datetime();
     $CDT_end = new Calendar_datetime();
     // -------------------------------------
     //	Load Publish
     // -------------------------------------
     if (APP_VER < 2.0) {
         //need to set DSP if not present
         if (!isset($GLOBALS['DSP']) or !is_object($GLOBALS['DSP'])) {
             if (!class_exists('Display')) {
                 require_once PATH_CP . 'cp.display' . EXT;
             }
             $GLOBALS['DSP'] = new Display();
         }
         if (!class_exists('Publish')) {
             require_once PATH_CP . 'cp.publish' . EXT;
         }
         $PB = new Publish();
         $PB->assign_cat_parent = ee()->config->item('auto_assign_cat_parents') == 'n' ? FALSE : TRUE;
     } else {
         ee()->load->library('api');
         ee()->api->instantiate(array('channel_entries', 'channel_categories', 'channel_fields'));
         ee()->api_channel_entries->assign_cat_parent = ee()->config->item('auto_assign_cat_parents') == 'n' ? FALSE : TRUE;
     }
     // -------------------------------------
     //	Tell our extensions that we're running the icalendar import
     // -------------------------------------
     $this->cache['ical'] = TRUE;
     // -------------------------------------
     //	Get already-imported events
     // -------------------------------------
     $imported = $this->data->get_imported_events($calendar_id);
     // -------------------------------------
     //	Don't let EXT drop us early
     // -------------------------------------
     ee()->extensions->in_progress = '';
     // -------------------------------------
     //	Cycle through the URLs
     // -------------------------------------
     foreach ($urls as $url) {
         $ICAL = new vcalendar();
         $ICAL->parse($this->fetch_url($url));
         // -------------------------------------
         //	Iterate among the events
         // -------------------------------------
         while ($event = $ICAL->getComponent('vevent')) {
             // -------------------------------------
             //	Times
             // -------------------------------------
             $hour = isset($event->dtstart['value']['hour']) ? $event->dtstart['value']['hour'] : 00;
             $minute = isset($event->dtstart['value']['min']) ? $event->dtstart['value']['min'] : 00;
             $end_hour = isset($event->dtend['value']['hour']) ? $event->dtend['value']['hour'] : $hour;
             $end_minute = isset($event->dtend['value']['min']) ? $event->dtend['value']['min'] : $minute;
             // -------------------------------------
             //	Last-modified date
             // -------------------------------------
             if (isset($event->lastmodified['value'])) {
                 $lm_date = $event->lastmodified['value']['year'] . $event->lastmodified['value']['month'] . $event->lastmodified['value']['day'] . $event->lastmodified['value']['hour'] . $event->lastmodified['value']['min'];
             } elseif (isset($event->dtstamp['value'])) {
                 $lm_date = $event->dtstamp['value']['year'] . $event->dtstamp['value']['month'] . $event->dtstamp['value']['day'] . $event->dtstamp['value']['hour'] . $event->dtstamp['value']['min'];
             } else {
                 $lm_date = $event->created['value']['year'] . $event->created['value']['month'] . $event->created['value']['day'] . $event->created['value']['hour'] . $event->created['value']['min'];
             }
             // -------------------------------------
             //	Does this event already exist? Do we need to update?
             // -------------------------------------
             if (isset($imported[$event->uid['value']])) {
                 // -------------------------------------
                 //	Has the event been updated? No reason
                 //	to do any work if it's the same old stuff.
                 // -------------------------------------
                 if ($lm_date == $imported[$event->uid['value']]['last_mod']) {
                     continue;
                 } elseif ($lm_date == $imported[$event->uid['value']]['last_mod']) {
                     continue;
                 }
                 $entry_id = $imported[$event->uid['value']]['entry_id'];
             } else {
                 $entry_id = '';
             }
             // -------------------------------------
             //	Adjust CDT
             // -------------------------------------
             $CDT->change_datetime($event->dtstart['value']['year'], $event->dtstart['value']['month'], $event->dtstart['value']['day'], $hour, $minute);
             if (isset($event->dtend['value'])) {
                 $CDT_end->change_datetime($event->dtend['value']['year'], $event->dtend['value']['month'], $event->dtend['value']['day'], $end_hour, $end_minute);
             } else {
                 $CDT_end->change_ymd($CDT->ymd);
                 $CDT_end->change_time($end_hour, $end_minute);
             }
             // -------------------------------------
             //	Adjust to the correct timezone for thie calendar
             // -------------------------------------
             if (!isset($event->dtstart['params']['TZID']) or $event->dtstart['params']['TZID'] == '') {
                 if (isset($event->dtstart['value']['hour'])) {
                     $CDT->add_time($tz_offset);
                     $CDT_end->add_time($tz_offset);
                 } else {
                     $CDT_end->add_day(-1);
                 }
             }
             // -------------------------------------
             //	Variableification
             // -------------------------------------
             $title = isset($event->summary['value']) ? $event->summary['value'] : lang('no_title');
             $summary = (isset($event->description) and is_array($event->description) and isset($event->description[0]['value'])) ? $event->description[0]['value'] : '';
             $location = isset($event->location['value']) ? $event->location['value'] : '';
             $rules = $this->ical_rule_to_calendar_rule($event->rrule);
             $exceptions = array('date' => array());
             if (mb_strlen($title) > 100) {
                 $title = substr($title, 0, 100);
             }
             if (is_array($event->exdate) and !empty($event->exdate)) {
                 $exceptions = $this->ical_exdate_to_calendar_exception($event->exdate);
             }
             $recurs = (is_array($event->rrule) and !empty($event->rrule)) ? 'y' : 'n';
             // -------------------------------------
             //	Fix some linebreak problems
             // -------------------------------------
             $summary = str_replace(array("\r", "\n"), '', $summary);
             $summary = str_replace('\\n', "\n", $summary);
             // -------------------------------------
             //	Set up $_POST
             // -------------------------------------
             $_POST = $post_data = array('site_id' => $this->data->get_site_id(), 'author_id' => $author_id, 'entry_id' => $entry_id, 'weblog_id' => $channel_id, 'channel_id' => $channel_id, 'status' => 'open', 'entry_date' => date('Y-m-d H:i a', ee()->localize->now - 3600 * 24 * 2), 'title' => $title, 'calendar_id' => $calendar_id, 'field_id_' . $this->data->get_field_id(CALENDAR_EVENTS_FIELD_PREFIX . 'summary') => $summary, 'field_id_' . $this->data->get_field_id(CALENDAR_EVENTS_FIELD_PREFIX . 'location') => $location, 'rule_id' => array(), 'start_date' => array($CDT->ymd), 'start_time' => array($CDT->hour . $CDT->minute), 'end_date' => array($CDT_end->ymd), 'end_time' => array($CDT_end->hour . $CDT_end->minute), 'all_day' => !isset($event->dtstart['value']['hour']) ? 'y' : 'n', 'rule_type' => $rules['rule_type'], 'repeat_years' => $rules['repeat_years'], 'repeat_months' => $rules['repeat_months'], 'repeat_weeks' => $rules['repeat_weeks'], 'repeat_days' => $rules['repeat_days'], 'days_of_week' => $rules['days_of_week'], 'relative_dow' => $rules['relative_dow'], 'days_of_month' => $rules['days_of_month'], 'months_of_year' => $rules['months_of_year'], 'end_by' => $rules['end_by'], 'end_after' => $rules['end_after'], 'occurrences' => $exceptions, 'expiration_date' => '', 'comment_expiration_date' => '', 'allow_comments' => 'n');
             // -------------------------------------
             //	Let Publish do its things
             // -------------------------------------
             if (APP_VER < 2.0) {
                 $PB->submit_new_entry(FALSE);
                 //<- LOOK HOW EASY IT USED TO BE >:|
             } else {
                 //EE 1.x doesn't have this field
                 $opt_field = 'field_id_' . $this->data->get_field_id(CALENDAR_EVENTS_FIELD_PREFIX . 'dates_and_options');
                 $_POST[$opt_field] = $calendar_id;
                 $post_data[$opt_field] = $calendar_id;
                 //this worked pre EE 2.1.3, then stopped working? *sigh*
                 //now we have to do all of this mess manually for field
                 //settings before inserting new entries via the API
                 //ee()->api_channel_fields->fetch_custom_channel_fields();
                 //--------------------------------------------
                 //	Check for custom field group
                 //--------------------------------------------
                 $fg_query = ee()->db->query("SELECT field_group\n\t\t\t\t\t\t FROM\texp_channels\n\t\t\t\t\t\t WHERE\tchannel_id = '" . ee()->db->escape_str($channel_id) . "'");
                 if ($fg_query->num_rows() > 0) {
                     $field_group = $fg_query->row('field_group');
                     ee()->lang->loadfile('channel');
                     ee()->lang->loadfile('content');
                     ee()->load->model('field_model');
                     ee()->load->model('channel_model');
                     // Rudimentary handling of custom fields
                     $field_query = ee()->channel_model->get_channel_fields($field_group);
                     $dst_enabled = ee()->session->userdata('daylight_savings');
                     foreach ($field_query->result_array() as $row) {
                         $field_data = '';
                         $field_dt = '';
                         $field_fmt = $row['field_fmt'];
                         // Settings that need to be prepped
                         $settings = array('field_instructions' => trim($row['field_instructions']), 'field_text_direction' => $row['field_text_direction'] == 'rtl' ? 'rtl' : 'ltr', 'field_fmt' => $field_fmt, 'field_dt' => $field_dt, 'field_data' => $field_data, 'field_name' => 'field_id_' . $row['field_id'], 'dst_enabled' => $dst_enabled);
                         $ft_settings = array();
                         if (isset($row['field_settings']) and strlen($row['field_settings'])) {
                             $ft_settings = unserialize(base64_decode($row['field_settings']));
                         }
                         $settings = array_merge($row, $settings, $ft_settings);
                         ee()->api_channel_fields->set_settings($row['field_id'], $settings);
                     }
                 }
                 //now we can do the new entry
                 ee()->api_channel_entries->submit_new_entry($channel_id, $post_data);
             }
             // -------------------------------------
             //	Update the imports table
             // -------------------------------------
             $data = array('calendar_id' => $calendar_id, 'event_id' => $this->cache['ical_event_id'], 'entry_id' => $this->cache['ical_entry_id'], 'uid' => $event->uid['value'], 'last_mod' => $lm_date);
             if ($entry_id != '') {
                 $data['import_id'] = $imported[$event->uid['value']]['import_id'];
                 $this->data->update_imported_event($data);
             } else {
                 //$data['import_id'] = '0';
                 $this->data->add_imported_event($data);
             }
         }
     }
     $this->data->update_ics_updated($calendar_id);
     ee()->extensions->end_script = FALSE;
     ee()->extensions->in_progress = APP_VER < 2.0 ? 'submit_new_entry_end' : 'entry_submission_end';
     return TRUE;
 }
Пример #29
0
 /**
  * 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;
 }
Пример #30
0
 public function processFeeds()
 {
     require_once dirname(__FILE__) . '/mxcalendars.ics.class.php';
     $f = $this->modx->newQuery('mxCalendarFeed');
     $f->where(array('active:=' => 1, 'nextrunon:<=' => time()));
     $f->prepare();
     $mxcfeeds = $this->modx->getCollection('mxCalendarFeed', $f);
     if ($this->loggingEnabled) {
         $this->logEvent('feed', 'feeds processor called\\n\\nSQL:\\n' . $f->toSql());
     }
     //$this->modx->setLogLevel(modX::LOG_LEVEL_INFO);
     foreach ($mxcfeeds as $feed) {
         $hadmodifications = 0;
         if ($feed->get('type') == 'ical') {
             $activeUrl = $feed->get('feed');
             $myics = file_get_contents($activeUrl);
             // Cache the response for giggles
             //$this->modx->cacheManager->set('mxcfeed-'.$feed->get('id'),$myics,3600);
             $config = array("unique_id" => 'mxcfeed-' . $feed->get('id') . '-' . time(), "url" => $activeUrl);
             $vcalendar = new vcalendar($config);
             $vcalendar->parse();
             //$this->modx->setLogLevel(modX::LOG_LEVEL_INFO);
             //$this->modx->log(modX::LOG_LEVEL_INFO,'Parsing feed #'.$feed->get('id').' events. ['.$feed->get('feed').']\n\nResponse:\n'.$myics);
             if ($this->loggingEnabled) {
                 $this->logEvent('feed parse', 'Parsing feed #' . $feed->get('id') . ' events. [' . $feed->get('feed') . ']\\n\\nResponse:\\n' . $myics);
             }
             while ($vevent = $vcalendar->getComponent("vevent")) {
                 if ($vevent->dtstart['value']) {
                     $start = mktime($vevent->dtstart['value']['hour'], $vevent->dtstart['value']['min'], $vevent->dtstart['value']['sec'], $vevent->dtstart['value']['month'], $vevent->dtstart['value']['day'], $vevent->dtstart['value']['year']);
                     // one occurrence
                 } else {
                     $start = '';
                 }
                 if ($vevent->dtend['value']) {
                     $end = mktime($vevent->dtend['value']['hour'], $vevent->dtend['value']['min'], $vevent->dtend['value']['sec'], $vevent->dtend['value']['month'], $vevent->dtend['value']['day'], $vevent->dtend['value']['year']);
                 } else {
                     $end = '';
                 }
                 if ($vevent->lastmodified['value']) {
                     $lastchange = mktime($vevent->lastmodified['value']['hour'], $vevent->lastmodified['value']['min'], $vevent->lastmodified['value']['sec'], $vevent->lastmodified['value']['month'], $vevent->lastmodified['value']['day'], $vevent->lastmodified['value']['year']);
                 } else {
                     $lastchange = '';
                 }
                 if ($vevent->created['value']) {
                     $createdDate = mktime($vevent->created['value']['hour'], $vevent->created['value']['min'], $vevent->created['value']['sec'], $vevent->created['value']['month'], $vevent->created['value']['day'], $vevent->created['value']['year']);
                 } else {
                     $createdDate = '';
                 }
                 $description = $vevent->getProperty("description");
                 // one occurrence
                 $location = $vevent->getProperty("location");
                 $title = $vevent->getProperty("summary");
                 $feedEventUID = $vevent->getProperty("uid");
                 //-- Multiple Occurances
                 //while( $comment = $vevent->getProperty( "comment" )) { // MAY occur more than once
                 //   echo json_encode($comment).'<br /><hr /><br />';
                 //}
                 // Output for testing
                 $event = array('title' => $title, 'description' => !empty($description) ? $description : '', 'location_name' => $location, 'startdate' => $start, 'enddate' => $end, 'source' => 'feed', 'lastedit' => $lastchange, 'feeds_id' => $feed->get('id'), 'feeds_uid' => $feedEventUID, 'context' => '', 'categoryid' => $feed->get('defaultcategoryid'), 'createdon' => $createDate, 'repeattype' => 0, 'repeaton' => '', 'repeatfrequency' => 0);
                 //echo 'Title: '.$title.'<br />'.json_encode($event).'<br /><hr><br /><br />';
                 //-- Save the new event
                 if (!empty($feedEventUID)) {
                     $existingEvent = $this->modx->getObject('mxCalendarEvents', array('feeds_uid' => $feedEventUID));
                     if (!is_object($existingEvent)) {
                         $existingEvent = $this->modx->getObject('mxCalendarEvents', array('title' => $title));
                     }
                 } else {
                     $existingEvent = $this->modx->getObject('mxCalendarEvents', array('title' => $title));
                 }
                 if (is_object($existingEvent)) {
                     // Check and modify existing event if modified since last update
                     if ($existingEvent->get('lastedit') <= $lastchange) {
                         // Event has been updated so lets just update all properties
                         $existingEvent->fromArray($event);
                         $existingEvent->save();
                         if ($this->loggingEnabled) {
                             $this->logEvent('feed', 'Update Event (' . $existingEvent->get('id') . ') for feed #' . $feed->get('id') . '\\n\\nEvent JSON:\\n' . json_encode($event));
                         }
                         $hadmodifications++;
                     }
                 } else {
                     // Create the newly found event from the feed
                     $feedEvent = $this->modx->newObject('mxCalendarEvents');
                     $feedEvent->fromArray($event);
                     $feedEvent->save();
                     if ($this->loggingEnabled) {
                         $this->logEvent('feed', 'New Event (' . $feedEvent->get('id') . ') for feed #' . $feed->get('id') . '\\n\\nEvent JSON:\\n' . json_encode($event));
                     }
                     $hadmodifications++;
                 }
             }
             //-- Update the feed next run time
             $nextTime = strtotime('+' . $feed->get('timerint') . ' ' . $feed->get('timermeasurement'));
             $feed->set('lastrunon', time());
             $feed->set('nextrunon', $nextTime);
             $feed->save();
             if ($hadmodifications) {
                 $this->logEvent('feed', 'Parsing feed #' . $feed->get('id') . ' had <strong>' . $hadmodifications . '</strong> event' . ($hadmodifications > 1 ? 's' : '') . ' added/updated [' . $feed->get('feed') . ']');
             } else {
                 $this->logEvent('feed', 'Parsing feed #' . $feed->get('id') . ' had no changes. [' . $feed->get('feed') . ']');
             }
         } else {
             //-- ==================== --//
             //-- Process the XML feed --//
             //-- ==================== --//
             $activeUrl = $feed->get('feed');
             $xmlEvents = file_get_contents($activeUrl);
             $events = new SimpleXMLElement($xmlEvents);
             $idx = 0;
             foreach ($events->event as $event) {
                 if (strtolower($event->timebegin) !== 'all day') {
                     $startDateTime = strtotime($event->date . ' ' . $event->timebegin);
                     $endDateTime = strtotime($event->date . ' ' . str_replace('- ', '', $event->timeend));
                 } else {
                     $startDateTime = strtotime($event->date . ' 00:00:00');
                     $endDateTime = strtotime($event->date . ' 23:59:59');
                 }
                 $lastchange = !empty($event->lastedit) ? $event->lastedit : time();
                 // Output for testing
                 $eventdata = array('title' => $event->title, 'description' => !empty($event->description) ? $event->description : '', 'location_name' => !empty($event->location) ? $event->location : '', 'startdate' => $startDateTime, 'enddate' => $endDateTime, 'source' => 'feed', 'lastedit' => $lastchange, 'feeds_id' => $feed->get('id'), 'feeds_uid' => !empty($event->eventid) ? $event->eventid : '', 'context' => '', 'categoryid' => $feed->get('defaultcategoryid'), 'createdon' => !empty($event->createDate) ? $event->createDate : time(), 'repeattype' => 0, 'repeaton' => '', 'repeatfrequency' => 0);
                 //-- Save the new event
                 if (!empty($event->eventid) && isset($event->eventid)) {
                     $q = $this->modx->newQuery('mxCalendarEvents');
                     $title = (string) $event->title;
                     $feeduid = (string) $event->eventid;
                     $q->where(array('mxCalendarEvents.title' => $title, 'mxCalendarEvents.feeds_id' => $feed->get('id'), 'mxCalendarEvents.feeds_uid' => $feeduid));
                     $q->prepare();
                     //echo 'SQL ['.$event->title.' '.$event->eventid.']: <br />'.$q->toSQL().'<br /><br />';
                     $existingEvent = $this->modx->getObject('mxCalendarEvents', $q);
                     //$existingEvent = $this->modx->getObject('mxCalendarEvents',array());
                 } else {
                     $existingEvent = false;
                 }
                 if (is_object($existingEvent)) {
                     // Check and modify existing event if modified since last update
                     if ($existingEvent->get('lastedit') <= $lastchange) {
                         // Event has been updated so lets just update all properties
                         $existingEvent->fromArray($eventdata);
                         $existingEvent->save();
                         if ($this->loggingEnabled) {
                             $this->logEvent('feed', 'Update Event (' . $existingEvent->get('id') . ')[' . $event->eventid . '] for feed #' . $feed->get('id') . '\\n\\nEvent JSON:\\n' . json_encode($event));
                         }
                         $hadmodifications++;
                     }
                 } else {
                     // Create the newly found event from the feed
                     $feedEvent = $this->modx->newObject('mxCalendarEvents');
                     $feedEvent->fromArray($eventdata);
                     $feedEvent->save();
                     if ($this->loggingEnabled) {
                         $this->logEvent('feed', 'New Event (' . $feedEvent->get('id') . ') for feed #' . $feed->get('id') . '\\n\\nEvent JSON:\\n' . json_encode($event));
                     }
                     $hadmodifications++;
                 }
                 //unset($event);
                 $idx++;
             }
             //-- Update the feed next run time
             $nextTime = strtotime('+' . $feed->get('timerint') . ' ' . $feed->get('timermeasurement'));
             $feed->set('lastrunon', time());
             $feed->set('nextrunon', $nextTime);
             $feed->save();
             if ($hadmodifications) {
                 $this->logEvent('feed', 'Parsing feed #' . $feed->get('id') . ' had <strong>' . $hadmodifications . '</strong> event' . ($hadmodifications > 1 ? 's' : '') . ' added/updated [' . $feed->get('feed') . ']');
             } else {
                 $this->logEvent('feed', 'Parsing feed #' . $feed->get('id') . ' had no changes. [' . $feed->get('feed') . ']');
             }
         }
     }
 }