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);
     }
 }
Example #2
0
 /**
  * function csv2iCal
  *
  * Convert csv file to iCal format and send file to browser (default) or save Ical file to disk
  * Definition iCal  : rcf2445, http://kigkonsult.se/downloads/index.php#rfc2445
  * Definition csv   : http://en.wikipedia.org/wiki/Comma-separated_values
  * Using iCalcreator: http://kigkonsult.se/downloads/index.php#iCalcreator
  * csv directory/file read/write
  *
  * @author Kjell-Inge Gustafsson <*****@*****.**>
  * @since  3.0 - 2011-12-21
  * @return bool return FALSE when error
  */
 public function csv2iCal()
 {
     $timeexec = array('start' => microtime(TRUE));
     if ($this->log) {
         $this->log->log(' ********** START **********', PEAR_LOG_NOTICE);
     }
     $conf = array();
     foreach ($this->config as $key => $value) {
         if (in_array(strtolower($key), array('inputdirectory', 'outputdirectory', 'inputfilename', 'outputfilename', 'inputurl', 'backup', 'save', 'skip'))) {
             continue;
         }
         if (in_array($key, array('del', 'sep', 'nl'))) {
             $conf[$key] = "{$value}";
         } else {
             $conf[strtoupper($value)] = strtoupper($key);
             // flip map names
             if ($this->log) {
                 $this->log->log("{$value} mapped to {$key}", PEAR_LOG_DEBUG);
             }
         }
     }
     $fp = false;
     $string_to_parse = $this->getConfig('string_to_parse');
     if ($string_to_parse) {
         $fp = fopen('php://temp/maxmemory:' . 1024 * 1024, 'rw');
         fputs($fp, $string_to_parse);
         fseek($fp, 0);
     } else {
         /** check input/output directory and filename */
         $inputdirFile = $outputdirFile = '';
         $inputFileParts = $outputFileParts = array();
         $remoteInput = $remoteOutput = FALSE;
         if (FALSE === $this->_fixIO('input', 'csv', $inputdirFile, $inputFileParts, $remoteInput)) {
             if ($this->log) {
                 $this->log->log(number_format(microtime(TRUE) - $timeexec['start'], 5) . ' sec', PEAR_LOG_ERR);
                 $this->log->log("ERROR 2, invalid input ({$inputdirFile})", PEAR_LOG_ERR);
                 $this->log->flush();
             }
             return FALSE;
         }
         if (FALSE === $this->_fixIO('output', FALSE, $outputdirFile, $outputFileParts, $remoteOutput)) {
             if (FALSE === $this->setConfig('outputfilename', $inputFileParts['filename'] . '.ics')) {
                 if ($this->log) {
                     $this->log->log(number_format(microtime(TRUE) - $timeexec['start'], 5) . ' sec', PEAR_LOG_ERR);
                     $this->log->log('ERROR 3,invalid output (' . $inputFileParts['filename'] . '.csv)', PEAR_LOG_ERR);
                     $this->log->flush();
                 }
                 return FALSE;
             }
             $outputdirFile = $this->getConfig('outputdirectory') . DIRECTORY_SEPARATOR . $inputFileParts['filename'] . '.ics';
             $outputFileParts = pathinfo($outputdirFile);
             if ($this->log) {
                 $this->log->log("output set to '{$outputdirFile}'", PEAR_LOG_NOTICE);
             }
         }
         if ($this->log) {
             $this->log->log("INPUT..FILE:{$inputdirFile}", PEAR_LOG_NOTICE);
             $this->log->log("OUTPUT.FILE:{$outputdirFile}", PEAR_LOG_NOTICE);
         }
         /** read csv file into input array */
         ini_set('auto_detect_line_endings', true);
         $fp = fopen($inputdirFile, "r");
         if (FALSE === $fp) {
             if ($this->log) {
                 $this->log->log("ERROR 4, unable to read file: '{$inputdirFile}'", PEAR_LOG_ERR);
                 $this->log->log(number_format(microtime(TRUE) - $timeexec['start'], 5) . ' sec', PEAR_LOG_DEBUG);
                 $this->log->flush();
             }
             return FALSE;
         }
     }
     $rows = array();
     while (FALSE !== ($row = fgetcsv($fp, FALSE, $conf['sep'], $conf['del']))) {
         $rows[] = $row;
     }
     fclose($fp);
     ini_set('auto_detect_line_endings', false);
     $cntrows = count($rows);
     /** iCalcreator checks when setting directory and filename */
     $calendar = new vcalendar();
     if (FALSE !== ($unique_id = $this->getConfig('unique_id'))) {
         $calendar->setConfig('unique_id', $unique_id);
     }
     if (!$this->getConfig('outputobj')) {
         if ($remoteOutput) {
             if (FALSE === $calendar->setConfig('url', $outputdirFile)) {
                 if ($this->log) {
                     $this->log->log("ERROR 5, iCalcreator: invalid url: '{$outputdirFile}'", PEAR_LOG_ERR);
                     $this->log->log(number_format(microtime(TRUE) - $timeexec['start'], 5) . ' sec', PEAR_LOG_DEBUG);
                     $this->log->flush();
                 }
                 return FALSE;
             }
         } else {
             if (FALSE === $calendar->setConfig('directory', $outputFileParts['dirname'])) {
                 if ($this->log) {
                     $this->log->log("ERROR 6, INPUT FILE:'{$inputdirFile}'  iCalcreator: invalid directory: '" . $outputFileParts['dirname'] . "'", PEAR_LOG_ERR);
                     $this->log->log(number_format(microtime(TRUE) - $timeexec['start'], 5) . ' sec', PEAR_LOG_DEBUG);
                     $this->log->flush();
                 }
                 return FALSE;
             }
             if (FALSE === $calendar->setConfig('filename', $outputFileParts['basename'])) {
                 if ($this->log) {
                     $this->log->log("ERROR 7, INPUT FILE:'{$inputdirFile}' iCalcreator: invalid filename: '" . $outputFileParts['basename'] . "'", PEAR_LOG_ERR);
                     $this->log->log(number_format(microtime(TRUE) - $timeexec['start'], 5) . ' sec', PEAR_LOG_DEBUG);
                     $this->log->flush();
                 }
                 return FALSE;
             }
         }
     }
     $timeexec['fileOk'] = microtime(TRUE);
     /** info rows */
     $actrow = 0;
     for ($row = $actrow; $row < $cntrows; $row++) {
         if (empty($rows[$row]) || 1 >= count($rows[$row]) || '' >= $rows[$row][1] || 'iCal' == substr($rows[$row][0], 0, 4) || 'kigkonsult.se' == $rows[$row][0]) {
             continue;
         } elseif ('TYPE' == strtoupper($rows[$row][0])) {
             $actrow = $row;
             break;
         } elseif ('CALSCALE' == strtoupper($rows[$row][0])) {
             $calendar->setProperty('CALSCALE', $rows[$row][1]);
         } elseif ('METHOD' == strtoupper($rows[$row][0])) {
             $calendar->setProperty('METHOD', $rows[$row][1]);
         } elseif ('X-' == substr($rows[$row][0], 0, 2)) {
             $calendar->setProperty($rows[$row][0], $rows[$row][1]);
         } elseif (2 >= count($rows[$row])) {
             continue;
         } else {
             $actrow = $row;
             break;
         }
     }
     $timeexec['infoOk'] = microtime(TRUE);
     $cntprops = 0;
     $proporder = array();
     /** fix opt. vtimezone */
     if ($actrow < $cntrows && (in_array('tzid', $rows[$actrow]) || in_array('TZID', $rows[$actrow]))) {
         foreach ($rows[$actrow] as $key => $header) {
             $header = strtoupper($header);
             if (isset($conf[$header])) {
                 $proporder[$conf[$header]] = $key;
                 // check map of userfriendly name to iCal property name
                 if ($this->log) {
                     $this->log->log("header row ix:{$key} => {$header}, replaced by " . $conf[$header], PEAR_LOG_DEBUG);
                 }
             } else {
                 $proporder[$header] = $key;
             }
         }
         if ($this->log) {
             $this->log->log("comp proporder=" . implode(',', array_flip($proporder)), PEAR_LOG_DEBUG);
         }
         $allowedProps = array('VTIMEZONE' => array('TZID', 'LAST-MODIFIED', 'TZURL'), 'STANDARD' => array('DTSTART', 'TZOFFSETTO', 'TZOFFSETFROM', 'COMMENT', 'RDATE', 'RRULE', 'TZNAME'), 'DAYLIGHT' => array('DTSTART', 'TZOFFSETTO', 'TZOFFSETFROM', 'COMMENT', 'RDATE', 'RRULE', 'TZNAME'));
         $actrow++;
         $comp = $subcomp = $actcomp = FALSE;
         for ($row = $actrow; $row < $cntrows; $row++) {
             if (empty($rows[$row]) || 1 >= count($rows[$row])) {
                 continue;
             }
             $compname = strtoupper($rows[$row][0]);
             if ('TYPE' == $compname) {
                 // next header
                 $actrow = $row;
                 break;
             }
             if ($comp && $subcomp) {
                 $comp->setComponent($subcomp);
                 $subcomp = FALSE;
             }
             if ('VTIMEZONE' == $compname) {
                 if ($comp) {
                     $calendar->setComponent($comp);
                 }
                 $comp = new vtimezone();
                 $actcomp =& $comp;
                 $cntprops += 1;
             } elseif ('STANDARD' == $compname) {
                 $subcomp = new vtimezone('STANDARD');
                 $actcomp =& $subcomp;
             } elseif ('DAYLIGHT' == $compname) {
                 $subcomp = new vtimezone('DAYLIGHT');
                 $actcomp =& $subcomp;
             } else {
                 if ($this->log) {
                     $this->log->log("skipped {$compname}", PEAR_LOG_WARNING);
                 }
                 continue;
             }
             foreach ($proporder as $propName => $col) {
                 // insert all properties into component
                 if (2 > $col || 'ORDER' == strtoupper($propName)) {
                     continue;
                 }
                 $propName = strtoupper($propName);
                 if ('X-' != substr($propName, 0, 2) && !in_array($propName, $allowedProps[$compname])) {
                     // check if allowed property for the component
                     if ($this->log) {
                         $this->log->log("skipped {$compname}: {$propName}", PEAR_LOG_DEBUG);
                     }
                     continue;
                 }
                 if (isset($rows[$row][$col]) && !empty($rows[$row][$col])) {
                     $rows[$row][$col] = str_replace(array("\r\n", "\n\r", "\n", "\r"), $conf['nl'], $rows[$row][$col]);
                     $value = FALSE !== strpos($rows[$row][$col], $conf['nl']) ? explode($conf['nl'], $rows[$row][$col]) : array($rows[$row][$col]);
                     foreach ($value as $val) {
                         if (empty($val) && '0' != $val) {
                             continue;
                         }
                         $del = FALSE !== strpos($val, ':') ? ';' : ':';
                         if (FALSE !== $actcomp->parse("{$propName}{$del}{$val}")) {
                             if ($this->log) {
                                 $this->log->log("iCalcreator->parse( '{$propName} {$val}' )", PEAR_LOG_DEBUG);
                             }
                         } elseif ($this->log) {
                             $this->log->log("ERROR 8, INPUT FILE:'{$inputdirFile}' iCalcreator: parse error: '{$propName}{$del}{$val}'", PEAR_LOG_ERR);
                         }
                     }
                     // end foreach( $value
                 }
                 // end if( isset
             }
             // end foreach( $proporder
         }
         // end for( $row = $actrow
         if ($comp && $subcomp) {
             $comp->setComponent($subcomp);
         }
         if ($comp) {
             $calendar->setComponent($comp);
         }
         $comp = $subcomp = $actcomp = FALSE;
     }
     $timeexec['zoneOk'] = microtime(TRUE);
     /** fix data */
     $proporder = array();
     if ($actrow < $cntrows && isset($rows[$actrow][0]) && 'TYPE' == strtoupper($rows[$actrow][0])) {
         foreach ($rows[$actrow] as $key => $header) {
             $header = strtoupper($header);
             if (isset($conf[$header])) {
                 $proporder[$conf[$header]] = $key;
                 // check map of user friendly name to iCal property name
                 if ($this->log) {
                     $this->log->log("header row ix:'{$key} => {$header}', mapped to '" . $conf[$header] . "'", PEAR_LOG_DEBUG);
                 }
             } else {
                 $proporder[$header] = $key;
             }
         }
         if ($this->log) {
             $this->log->log("comp proporder=" . implode(',', array_flip($proporder)), PEAR_LOG_DEBUG);
         }
         $allowedProps = array('VEVENT' => array('ATTACH', 'ATTENDEE', 'CATEGORIES', 'CLASS', 'COMMENT', 'CONTACT', 'CREATED', 'DESCRIPTION', 'DTEND', 'DTSTAMP', 'DTSTART', 'DURATION', 'EXDATE', 'RXRULE', 'GEO', 'LAST-MODIFIED', 'LOCATION', 'ORGANIZER', 'PRIORITY', 'RDATE', 'RECURRENCE-ID', 'RELATED-TO', 'RESOURCES', 'RRULE', 'REQUEST-STATUS', 'SEQUENCE', 'STATUS', 'SUMMARY', 'TRANSP', 'UID', 'URL'), 'VTODO' => array('ATTACH', 'ATTENDEE', 'CATEGORIES', 'CLASS', 'COMMENT', 'COMPLETED', 'CONTACT', 'CREATED', 'DESCRIPTION', 'DTSTAMP', 'DTSTART', 'DUE', 'DURATION', 'EXDATE', 'EXRULE', 'GEO', 'LAST-MODIFIED', 'LOCATION', 'ORGANIZER', 'PERCENT', 'PRIORITY', 'RDATE', 'RECURRENCE-ID', 'RELATED-TO', 'RESOURCES', 'RRULE', 'REQUEST-STATUS', 'SEQUENCE', 'STATUS', 'SUMMARY', 'UID', 'URL'), 'VJOURNAL' => array('ATTACH', 'ATTENDEE', 'CATEGORIES', 'CLASS', 'COMMENT', 'CONTACT', 'CREATED', 'DESCRIPTION', 'DTSTAMP', 'DTSTART', 'EXDATE', 'EXRULE', 'LAST-MODIFIED', 'ORGANIZER', 'RDATE', 'RECURRENCE-ID', 'RELATED-TO', 'RRULE', 'REQUEST-STATUS', 'SEQUENCE', 'STATUS', 'SUMMARY', 'UID', 'URL'), 'VFREEBUSY' => array('ATTENDEE', 'COMMENT', 'CONTACT', 'DTEND', 'DTSTAMP', 'DTSTART', 'DURATION', 'FREEBUSY', 'ORGANIZER', 'UID', 'URL'), 'VALARM' => array('ACTION', 'ATTACH', 'ATTENDEE', 'DESCRIPTION', 'DURATION', 'REPEAT', 'SUMMARY', 'TRIGGER'));
         $actrow++;
         $comp = $subcomp = $actcomp = FALSE;
         $allowedComps = array('VEVENT', 'VTODO', 'VJOURNAL', 'VFREEBUSY');
         for ($row = $actrow; $row < $cntrows; $row++) {
             if (empty($rows[$row]) || 1 >= count($rows[$row])) {
                 continue;
             }
             if ($comp && $subcomp) {
                 $comp->setComponent($subcomp);
                 $subcomp = FALSE;
             }
             $compname = strtoupper($rows[$row][0]);
             if ($this->log) {
                 $this->log->log("'{$compname}' START", PEAR_LOG_NOTICE);
             }
             if (in_array($compname, $allowedComps)) {
                 if ($comp) {
                     $calendar->setComponent($comp);
                 }
                 $comp = new $rows[$row][0]();
                 $actcomp =& $comp;
                 $cntprops += 1;
             } elseif ('VALARM' == $compname) {
                 $subcomp = new valarm();
                 $actcomp =& $subcomp;
             } else {
                 if ($this->log) {
                     $this->log->log("skipped {$compname}", PEAR_LOG_WARNING);
                 }
                 continue;
             }
             foreach ($proporder as $propName => $col) {
                 // insert all properties into component
                 if (2 > $col || 'ORDER' == strtoupper($propName)) {
                     continue;
                 }
                 $propName = strtoupper($propName);
                 if ($this->log) {
                     $this->log->log("{$compname} {$propName} START (col={$col})", PEAR_LOG_DEBUG);
                 }
                 if ('X-' != substr($propName, 0, 2) && !in_array($propName, $allowedProps[$compname])) {
                     // check if allowed property for the component
                     if ($this->log) {
                         $this->log->log("skipped {$compname} {$propName}", PEAR_LOG_NOTICE);
                     }
                     continue;
                 }
                 if (isset($rows[$row][$col]) && !empty($rows[$row][$col]) || 'SEQUENCE' == $propName && '0' == $rows[$row][$col]) {
                     $rows[$row][$col] = str_replace(array("\r\n", "\n\r", "\n", "\r"), $conf['nl'], $rows[$row][$col]);
                     $value = FALSE !== strpos($rows[$row][$col], $conf['nl']) ? explode($conf['nl'], $rows[$row][$col]) : array($rows[$row][$col]);
                     $ctests = array('://', 'fax:', 'cid:', 'sms:', 'tel:', 'urn:', 'crid:', 'news:', 'pres:', 'mailto:', 'MAILTO:');
                     foreach ($value as $val) {
                         if (empty($val) && '0' != $val && 0 != $val) {
                             continue;
                         }
                         if ('GEO' == $propName) {
                             $parseval = FALSE !== strpos($val, ':') ? "GEO{$val}" : "GEO:{$val}";
                             if (FALSE === $actcomp->parse($parseval)) {
                                 if ($this->log) {
                                     $this->log->log("ERROR 11, INPUT FILE:'{$inputdirFile}' iCalcreator: parse error: '{$parseval}'", PEAR_LOG_ERR);
                                 }
                             }
                         } elseif ('REQUEST-STATUS' == $propName) {
                             // 'REQUEST-STATUS' without any parameters.. .
                             if (FALSE === $actcomp->parse("{$propName}:{$val}")) {
                                 if ($this->log) {
                                     $this->log->log("ERROR 12, INPUT FILE:'{$inputdirFile}' iCalcreator: parse error: '{$propName}:{$val}'", PEAR_LOG_ERR);
                                 }
                             }
                         }
                         $cntm = $pos = 0;
                         foreach ($ctests as $tst) {
                             $cntm += substr_count($val, $tst);
                         }
                         $cntc = substr_count($val, ':');
                         $cntq = substr_count($val, '=');
                         $cnts = substr_count($val, ';');
                         if (0 == $cntq && 0 == $cnts) {
                             // no parameters
                             $del = ':';
                         } elseif (1 == $cntc && $cntq + 1 == $cnts) {
                             // parameters and colon
                             $del = ';';
                         } elseif ($cntc == $cntm + 1) {
                             $del = ';';
                         } else {
                             $del = 1 > $cntm && 0 < $cntc ? ';' : ':';
                         }
                         if ('X-' == substr($propName, 0, 2) || in_array($propName, array('CATEGORIES', 'COMMENT', 'CONTACT', 'DESCRIPTION', 'LOCATION', 'RESOURCES', 'SUMMARY'))) {
                             $val = str_replace(',', '\\,', $val);
                             if (FALSE !== ($pos = strpos($del . $val, ':'))) {
                                 while (FALSE !== ($pos2 = strpos($val, ';', $pos + 1))) {
                                     $val = substr($val, 0, $pos2) . '\\;' . substr($val, $pos2 + 1);
                                     if ($this->log) {
                                         $this->log->log("pos={$pos} pos2={$pos2} val='{$val}'", PEAR_LOG_DEBUG);
                                     }
                                     $pos = $pos2 + 1;
                                 }
                             }
                         }
                         if (FALSE === $actcomp->parse("{$propName}{$del}{$val}")) {
                             if ($this->log) {
                                 $this->log->log("ERROR 13, INPUT FILE:'{$inputdirFile}' iCalcreator: parse error: '{$propName}{$del}{$val}'", PEAR_LOG_ERR);
                             }
                         } elseif ($this->log) {
                             $this->log->log("iCalcreator->parse( '{$propName}{$del}{$val}' )", PEAR_LOG_DEBUG);
                         }
                     }
                     // end foreach( $value as $val
                 }
                 // end if( isset( $rows[$row][$col]
             }
             // end foreach( $proporder
         }
         // end for( $row = $actrow;
         if ($comp && $subcomp) {
             $comp->setComponent($subcomp);
         }
         if ($comp) {
             $calendar->setComponent($comp);
         }
     }
     $save = $this->getConfig('save');
     if ($this->log) {
         $timeexec['exit'] = microtime(TRUE);
         $msg = "INPUT '{$inputdirFile}'";
         $msg .= ' fileOk:' . number_format($timeexec['fileOk'] - $timeexec['start'], 5);
         $msg .= ' infoOk:' . number_format($timeexec['infoOk'] - $timeexec['fileOk'], 5);
         $msg .= ' zoneOk:' . number_format($timeexec['zoneOk'] - $timeexec['infoOk'], 5);
         $msg .= ' compOk:' . number_format($timeexec['exit'] - $timeexec['zoneOk'], 5);
         $msg .= ' total:' . number_format($timeexec['exit'] - $timeexec['start'], 5) . ' sec';
         $this->log->log($msg, PEAR_LOG_DEBUG);
         $msg = "'{$inputdirFile}' (" . $cntprops . ' components) start:' . date('H:i:s', $timeexec['start']);
         $msg .= ' total:' . number_format($timeexec['exit'] - $timeexec['start'], 5) . ' sec';
         if ($save) {
             $msg .= " -> '{$outputdirFile}'";
         }
         $this->log->log($msg, PEAR_LOG_NOTICE);
     }
     /** return calendar, save or send the file */
     if ($this->getConfig('outputobj')) {
         if ($this->log) {
             $this->log->log("INPUT FILE:'{$inputdirFile}' returning iCalcreator vcalendar instance", PEAR_LOG_NOTICE);
             $this->log->flush();
         }
         return $calendar;
         exit;
     }
     $d = $calendar->getConfig('directory');
     $f = $calendar->getConfig('filename');
     $df = $d . DIRECTORY_SEPARATOR . $f;
     if ($save) {
         if (FALSE !== $calendar->saveCalendar()) {
             if ($this->log) {
                 $this->log->log("INPUT FILE:'{$inputdirFile}' saved '{$df}'", PEAR_LOG_NOTICE);
                 $this->log->flush();
             }
             return TRUE;
         } else {
             // ??
             if ($this->log) {
                 $this->log->log("ERROR 16, INPUT FILE:'{$inputdirFile}' can't write to output file : '{$df}'", PEAR_LOG_ERR);
                 $this->log->flush();
             }
             return FALSE;
         }
     } else {
         if ($this->log) {
             $this->log->log("INPUT FILE:'{$inputdirFile}' returning : '{$f}'", PEAR_LOG_NOTICE);
             $this->log->flush();
         }
         $output = $calendar->createCalendar();
         $filesize = strlen($output);
         if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) {
             $output = gzencode($output, 9);
             $filesize = strlen($output);
             header('Content-Encoding: gzip');
             header('Vary: *');
         }
         header('Content-Type: text/calendar; charset=utf-8');
         header("Content-Disposition: attachment; filename='{$f}'");
         header('Cache-Control: max-age=10');
         header('Content-Length: ' . $filesize);
         echo $output;
     }
     return TRUE;
 }
Example #3
0
    $c->setConfig(array("directory" => "Calevents", "filename" => "{$iduser}.ics"));
    $vivek->getAllTaskByuser($iduser);
    while ($vivek->fetch()) {
        $stdt = explode('-', $vivek->getData("due_date_dateformat"));
        $startdate = "{$stdt['0']}" . "{$stdt['1']}" . "{$stdt['2']}";
        $enddate = $startdate;
        $e =& $c->newComponent('vevent');
        //$e->setProperty( 'dtstart', $startdate );
        //$e->setProperty( 'dtend', $enddate );
        $e->setProperty("dtstart", "{$startdate}", array("VALUE" => "DATE"));
        $e->setProperty('description', $vivek->getData("task_description"));
        $e->setProperty('summary', $vivek->getData("task_description"));
        $e->setProperty('class', 'PUBLIC');
    }
    $c->createCalendar();
    $str = $c->saveCalendar();
    $tt = $_SERVER["SERVER_NAME"];
    $path = "http://" . "{$tt}" . "/" . "Calevents/" . "{$iduser}.ics";
    $ff = "Calevents/{$iduser}.ics";
    system("chmod 0777 {$ff}");
    echo _('Your iCal URL is : ' . $path . ' ');
} else {
    echo _('You do not yet have an API key. ');
    echo _('Please generate one ');
    echo $e_set_api->getLink('here');
    echo '<div class="spacerblock_20"></div>';
}
?>
</div>
        <div class="solidline"></div>
    </td></tr></table>
Example #4
0
// 3 hours
$e->setProperty('description', 'x-mas evening - diner');
// describe the event
$e->setProperty('location', 'Jeffikus');
// 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;
echo "<br />\n\n";*/
$v->setConfig('directory', '');
$v->setConfig('filename', 'calendar.ics');
$v->saveCalendar();
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  */
/*$v = new vcalendar();                          // initiate new CALENDAR
$v->setConfig( 'unique_id'
             , 'testdomain.com' );             // config with site domain
$v->setProperty( 'X-WR-CALNAME'
               , 'Sample calendar' );          // set some X-properties, name, content.. .
$v->setProperty( 'X-WR-CALDESC'
               , 'Description of the calendar' );
$v->setProperty( 'X-WR-TIMEZONE'
               , 'Europe/Stockholm' );

$e = new vevent();                             // initiate EVENT
$e->setProperty( 'categories'
               , 'FAMILY' );                   // catagorize
$e->setProperty( 'dtstart'
Example #5
0
function cs_event_calendar($post_id = '')
{
    if (!isset($post_id) && $post_id == '') {
        global $post;
        $post_id = $post->ID;
    }
    $cal_post = get_post($post_id);
    if ($cal_post) {
        $event_from_date = get_post_meta($post_id, "cs_event_from_date", true);
        $cs_event_to_date = get_post_meta($post_id, "cs_event_to_date", true);
        $cs_event_meta = get_post_meta($post_id, "cs_event_meta", true);
        if ($cs_event_meta != "") {
            $cs_event_meta = new SimpleXMLElement($cs_event_meta);
            if ($cs_event_meta->event_address != '') {
                $address_map = get_the_title("{$cs_event_meta->event_address}");
            } else {
                $address_map = '';
            }
        }
        $cs_event_loc = get_post_meta($cs_event_meta->event_address, "cs_event_loc_meta", true);
        if ($cs_event_loc != "") {
            $cs_xmlObject = new SimpleXMLElement($cs_event_loc);
            $loc_address = $cs_xmlObject->loc_address;
            $event_loc_lat = $cs_xmlObject->event_loc_lat;
            $event_loc_long = $cs_xmlObject->event_loc_long;
            $event_loc_zoom = $cs_xmlObject->event_loc_zoom;
            $loc_city = $cs_xmlObject->loc_city;
            $loc_postcode = $cs_xmlObject->loc_postcode;
            $loc_country = $cs_xmlObject->loc_country;
            $location = $loc_address . ', ' . $loc_city . ', ' . $loc_postcode . ', ' . $loc_country;
        } else {
            $loc_address = '';
            $event_loc_lat = '';
            $event_loc_long = '';
            $event_loc_zoom = '';
            $loc_city = '';
            $loc_postcode = '';
            $loc_country = '';
            $location = '';
        }
        $start_year = date('Y', strtotime($event_from_date));
        $start_month = date('m', strtotime($event_from_date));
        $start_day = date('d', strtotime($event_from_date));
        $end_year = date('Y', strtotime($cs_event_to_date));
        $end_month = date('m', strtotime($cs_event_to_date));
        $end_day = date('d', strtotime($cs_event_to_date));
        if ($cs_event_meta->event_all_day != "on") {
            $start_time = calender_time($cs_event_meta->event_start_time);
            $end_time = calender_time($cs_event_meta->event_end_time);
        } else {
            $start_time = $end_time = '';
        }
        if ($start_time != '' && $start_time != ':') {
            $event_start_time = explode(":", $start_time);
        }
        if ($end_time != '' && $end_time != ':') {
            $event_end_time = explode(":", $end_time);
        }
        $post_title = get_the_title($post_id);
        $cs_vcalendar = new vcalendar();
        $cs_vevent = new vevent();
        $site_info = get_bloginfo('name') . 'Events';
        $cs_vevent->setProperty('categories', $site_info);
        if (isset($event_start_time)) {
            @$cs_vevent->setProperty('dtstart', @$start_year, @$start_month, @$start_day, @$event_start_time[0], @$event_start_time[1], 00);
        } else {
            $cs_vevent->setProperty('dtstart', $start_year, $start_month, $start_day);
        }
        // YY MM dd hh mm ss
        if (isset($event_end_time)) {
            @$cs_vevent->setProperty('dtend', $end_year, $end_month, $end_day, $event_end_time[0], $event_end_time[1], 00);
        } else {
            $cs_vevent->setProperty('dtend', $end_year, $end_month, $end_day);
        }
        // YY MM dd hh mm ss
        $cs_vevent->setProperty('description', strip_tags($cal_post->post_excerpt));
        if (isset($location)) {
            $cs_vevent->setProperty('location', $location);
        }
        $cs_vevent->setProperty('summary', $post_title);
        $cs_vcalendar->addComponent($cs_vevent);
        $templateurl = get_template_directory_uri() . '/cache/';
        //makeDir(get_bloginfo('template_directory').'/cache/');
        $home = home_url();
        $dir = str_replace($home, '', $templateurl);
        $dir = str_replace('/wp-content/', 'wp-content/', $dir);
        $directory_url = get_template_directory_uri();
        $directorypath = explode('/', $directory_url);
        $themefolderName = $directorypath[count($directorypath) - 1];
        $cs_vcalendar->setConfig('directory', ABSPATH . 'wp-content/themes/' . $themefolderName . '/cache');
        $cs_vcalendar->setConfig('filename', 'event-' . $post_id . '.ics');
        $cs_vcalendar->saveCalendar();
        ////OUT LOOK & iCAL URL//
        $output_calendar_url['ical'] = $templateurl . 'event-' . $post_id . '.ics';
        ////GOOGLE URL//
        $google_url = "http://www.google.com/calendar/event?action=TEMPLATE";
        $google_url .= "&text=" . urlencode($post_title);
        if (isset($event_start_time) && isset($event_end_time)) {
            $google_url .= "&dates=" . @$start_year . @$start_month . @$start_day . "T" . str_replace('.', '', @$event_start_time[0]) . str_replace('.', '', @$event_start_time[1]) . "00/" . @$end_year . @$end_month . @$end_day . "T" . str_replace('.', '', @$event_end_time[0]) . str_replace('.', '', @$event_end_time[1]) . "00";
        } else {
            $google_url .= "&dates=" . $start_year . $start_month . $start_day . "/" . $end_year . $end_month . $end_day;
        }
        $google_url .= "&sprop=website:" . get_permalink($post_id);
        $google_url .= "&details=" . strip_tags($cal_post->post_excerpt);
        if (isset($location)) {
            $google_url .= "&location=" . $location;
        } else {
            $google_url .= "&location=Unknown";
        }
        $google_url .= "&trp=true";
        $output_calendar_url['google'] = $google_url;
        ////YAHOO CALENDAR URL///
        $yahoo_url = "http://calendar.yahoo.com/?v=60&view=d&type=20";
        $yahoo_url .= "&title=" . str_replace(' ', '+', $post_title);
        if (isset($event_start_time)) {
            $yahoo_url .= "&st=" . @$start_year . @$start_month . @$start_day . "T" . @$event_start_time[0] . @$event_start_time[1] . "00";
        } else {
            $yahoo_url .= "&st=" . $start_year . $start_month . $start_day;
        }
        if (isset($event_end_time)) {
            //$yahoo_url .= "&dur=".$event_start_time[0].$event_start_time[1];
        }
        $yahoo_url .= "&desc=" . str_replace(' ', '+', strip_tags($cal_post->post_excerpt)) . ' -- ' . get_permalink($post_id);
        $yahoo_url .= "&in_loc=" . str_replace(' ', '+', $location);
        $output_calendar_url['yahoo'] = $yahoo_url;
    }
    return $output_calendar_url;
}
function createTestFile()
{
    $dirFile = CALDIR . DIRECTORY_SEPARATOR . TESTFILE;
    $calendar = new vcalendar();
    $calendar->setConfig('unique_id', UNIQUE);
    if (!$calendar->setConfig('directory', CALDIR)) {
        addLogEntry(1, '  ERROR (11) when setting directory \'' . CALDIR . '\', check directory/file permissions!!');
        return FALSE;
    } elseif (!$calendar->setConfig('filename', TESTFILE)) {
        addLogEntry(1, "  ERROR (12) when setting directory/file '{$dirFile}', check directory/file permissions!!");
        return FALSE;
    }
    $calendar->setProperty('METHOD', METHOD);
    $calendar->setProperty('X-WR-CALNAME', CALNAME);
    $calendar->setProperty('X-WR-CALDESC', CALDESC);
    $calendar->setProperty('X-WR-TIMEZONE', TIMEZONE);
    $date = mktime(0, 0, 0, (int) substr(THISDATE, 4, 2), (int) substr(THISDATE, 6, 2), (int) substr(THISDATE, 0, 4));
    $stopDate = $date + 7 * 24 * 3600;
    $eventCount = 1;
    // random priority, 1 to 9. HIGH (1-4), MEDIUM (5), LOW (6-9)
    // reversed prio; HIGH: weight 1, MEDIUM weight 4, LOW: weight 8
    $prioArr = array();
    for ($r = 1; $r <= 9; $r++) {
        $weight = 5 < $r ? 1 : 5 > $r ? 8 : 4;
        for ($r1 = 1; $r1 <= $weight; $r1++) {
            $prioArr[] = $r;
        }
    }
    mt_srand();
    shuffle($prioArr);
    // array to randomly select a summary from
    $summaries = array('Duis ac dui sit amet ante auctor euismod.', 'Suspendisse_pellentesque_velit_in_tortor.', 'Mauris vulputate.', 'Nulla sapien pede, dapibus sed.', 'Maecenas tristique, pede_id_sollicitudin_posuere, enim nibh mollis odio.', 'Lorem ipsum dolor sit amet, consectetuerAdipiscingElit.');
    while ($date <= $stopDate) {
        $dayCount = 1;
        while ($dayCount < 4) {
            $event = new vevent();
            $eventdate = $date + mt_rand(7, 18) * 3600;
            // random start hour, 7 to 18
            $event->setProperty('DTSTART', array('timestamp' => $eventdate));
            // random duration, 1-4 hours or 2 days
            if (9 > mt_rand(1, 9)) {
                $event->setProperty('DURATION', 0, 0, mt_rand(1, 4));
            } else {
                $event->setProperty('DURATION', 0, 2);
            }
            // 2 days duration
            $event->setProperty('SUMMARY', "Event #{$eventCount}. " . $summaries[mt_rand(0, 5)]);
            $event->setProperty('CATEGORIES', "Category #{$eventCount}");
            $event->setProperty('LOCATION', "Location #{$eventCount}");
            $event->setProperty('RESOURCES', "Resource #{$eventCount}");
            $event->setProperty('ORGANIZER', "chair.{$eventCount}@" . UNIQUE);
            $event->setProperty('CONTACT', "contact.{$eventCount}@" . UNIQUE);
            $event->setProperty('DESCRIPTION', 'Lorem ipsum dolor sit amet, ' . 'consectetuer adipiscing elit. ' . 'Mauris vulputate. Suspendisse ' . 'pellentesque velit in tortor. ' . 'Nulla sapien pede, dapibus sed.');
            // random priority, 1 to 9. HIGH (1-4), MEDIUM (5), LOW (6-9)
            $event->setProperty('PRIORITY', $prioArr[mt_rand(0, count($prioArr) - 1)]);
            // two attendees every event
            $event->setProperty('ATTENDEE', 'attendee.' . $eventCount . '.1@' . UNIQUE);
            $event->setProperty('ATTENDEE', 'attendee.' . $eventCount . '.2@' . UNIQUE);
            // two comments every event
            $event->setProperty('COMMENT', 'Duis ac dui sit amet ante auctor euismod. Sed vulputate.');
            $event->setProperty('COMMENT', 'Maecenas tristique, pede id sollicitudin posuere, enim nibh mollis odio.');
            $event->setProperty('CREATED', array('timestamp' => $eventdate - 2 * 24 * 3600));
            // fake two days before event startdate
            $event->setProperty('LAST-MODIFIED', array('timestamp' => $eventdate - 23 * 3600));
            // fake 25 hours before event startdate
            if (5 > $eventCount) {
                $event->setProperty('RRULE', array('FREQ' => 'DAILY', 'COUNT' => 4, 'INTERVAL' => 3));
                $event->setProperty('EXRULE', array('FREQ' => 'DAILY', 'COUNT' => 2, 'INTERVAL' => 6));
            }
            $event->setProperty('URL', 'http://www.kigkonsult.se/tinycal/index.php');
            if (FALSE === $calendar->setComponent($event)) {
                error_log('setComponent error');
            }
            $eventCount++;
            $dayCount++;
        }
        $date += 24 * 3600;
    }
    $calendar->sort();
    if (FALSE === $calendar->saveCalendar()) {
        addLogEntry(1, "  ERROR (13) saving calendar file '{$dirFile}'");
    }
}