/**
 * @param array $calendar
 * @param array $calendarobject
 * @throws Sabre_DAV_Exception_BadRequest
 * @return void
 */
function renderCalDavEntry_data(&$calendar, &$calendarobject)
{
    /** @var Sabre\VObject\Component\VCalendar $vObject  */
    $vObject = Sabre\VObject\Reader::read($calendarobject["calendardata"]);
    $componentType = null;
    /** @var Sabre\VObject\Component\VEvent $component  */
    $component = null;
    foreach ($vObject->getComponents() as $component) {
        if ($component->name !== 'VTIMEZONE') {
            $componentType = $component->name;
            break;
        }
    }
    if (!$componentType) {
        throw new Sabre_DAV_Exception_BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
    }
    $timezoneOffset = date("P");
    // @TODO Get the actual timezone from the event
    if ($componentType !== 'VEVENT') {
        return;
    }
    $event = array("description" => $component->__get("DESCRIPTION") ? $component->__get("DESCRIPTION")->value : null, "summary" => $component->__get("SUMMARY") ? $component->__get("SUMMARY")->value : null, "location" => $component->__get("LOCATION") ? $component->__get("LOCATION")->value : null, "color" => $component->__get("X-ANIMEXX-COLOR") ? $component->__get("X-ANIMEXX-COLOR")->value : null);
    $recurring = $component->__get("RRULE") ? 1 : 0;
    /** @var Sabre\VObject\Property\DateTime $dtstart  */
    $dtstart = $component->__get("DTSTART");
    $allday = $dtstart->getDateType() == Sabre\VObject\Property\DateTime::DATE ? 1 : 0;
    /** @var array|Sabre\VObject\Component\VAlarm[] $alarms  */
    $alarms = array();
    foreach ($component->getComponents() as $a_component) {
        if ($a_component->name == "VALARM") {
            /** var Sabre\VObject\Component\VAlarm $component */
            $alarms[] = $a_component;
        }
    }
    $it = new Sabre\VObject\RecurrenceIterator($vObject, (string) $component->__get("UID"));
    $last_end = 0;
    $max_ts = mktime(0, 0, 0, 1, 1, CALDAV_MAX_YEAR * 1);
    $first = true;
    while ($it->valid() && $last_end < $max_ts && ($recurring || $first)) {
        $first = false;
        $last_end = $it->getDtEnd()->getTimestamp();
        $start = $it->getDtStart()->getTimestamp();
        q("INSERT INTO %s%sjqcalendar (`calendar_id`, `calendarobject_id`, `Summary`, `StartTime`, `EndTime`, `IsEditable`, `IsAllDayEvent`, `IsRecurring`, `Color`) VALUES\n\t\t\t(%d, %d, '%s', CONVERT_TZ('%s', '{$timezoneOffset}', @@session.time_zone), CONVERT_TZ('%s', '{$timezoneOffset}', @@session.time_zone), %d, %d, %d, '%s')", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendar["id"]), IntVal($calendarobject["id"]), dbesc($event["summary"]), date("Y-m-d H:i:s", $start), date("Y-m-d H:i:s", $last_end), 1, $allday, $recurring, dbesc(substr($event["color"], 1)));
        foreach ($alarms as $alarm) {
            $alarm = renderCalDavEntry_calcalarm($alarm, $component);
            $notified = $alarm->getTimestamp() < time() ? 1 : 0;
            q("INSERT INTO %s%snotifications (`calendar_id`, `calendarobject_id`, `alert_date`, `notified`) VALUES (%d, %d, CONVERT_TZ('%s', '{$timezoneOffset}', @@session.time_zone), %d)", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendar["id"]), IntVal($calendarobject["id"]), $alarm->format("Y-m-d H:i:s"), $notified);
        }
        $it->next();
    }
    return;
}
Exemple #2
0
 /**
  * Parses the VObject
  * @param string $data VObject as string
  * @return Sabre\VObject\Reader|null
  */
 public static function parse($data)
 {
     try {
         Sabre\VObject\Property::$classMap['LAST-MODIFIED'] = 'Sabre\\VObject\\Property\\DateTime';
         $vObject = Sabre\VObject\Reader::read($data);
         if ($vObject instanceof Sabre\VObject\Component) {
             $vObject = new OC_VObject($vObject);
         }
         return $vObject;
     } catch (Exception $e) {
         OC_Log::write('vobject', $e->getMessage(), OC_Log::ERROR);
         return null;
     }
 }
include __DIR__ . '/../vendor/autoload.php';
if ($argc < 2) {
    echo "sabre/vobject ", Sabre\VObject\Version::VERSION, " freebusy benchmark\n";
    echo "\n";
    echo "This script can be used to measure the speed of generating a\n";
    echo "free-busy report based on a calendar.\n";
    echo "\n";
    echo "The process will be repeated 100 times to get accurate stats\n";
    echo "\n";
    echo "Usage: " . $argv[0] . " inputfile.ics\n";
    die;
}
list(, $inputFile) = $argv;
$bench = new Hoa\Bench\Bench();
$bench->parse->start();
$vcal = Sabre\VObject\Reader::read(fopen($inputFile, 'r'));
$bench->parse->stop();
$repeat = 100;
$start = new \DateTime('2000-01-01');
$end = new \DateTime('2020-01-01');
$timeZone = new \DateTimeZone('America/Toronto');
$bench->fb->start();
for ($i = 0; $i < $repeat; $i++) {
    $fb = new Sabre\VObject\FreeBusyGenerator($start, $end, $vcal, $timeZone);
    $results = $fb->getResult();
}
$bench->fb->stop();
echo $bench, "\n";
function formatMemory($input)
{
    if (strlen($input) > 6) {
Exemple #4
0
            }
        }
        showmessage('do_success', $url, 0);
    } else {
        showmessage('that_should_at_least_write_things');
    }
}
if ($op == 'leadin') {
    include_once S_ROOT . './source/function_blog.php';
    //检测是否有ICS文件日历需要导入
    if (!empty($_FILES) && !empty($_FILES['leading-in']['tmp_name'])) {
        $file_type = substr($_FILES['leading-in']['name'], strrpos($_FILES['leading-in']['name'], '.') + 1);
        if (strtolower($file_type) == 'ics') {
            //如果为ICALENDAR格式文件,则开始进行导入
            include S_ROOT . './source/vendor/autoload.php';
            $calendar = Sabre\VObject\Reader::read(file_get_contents($_FILES['leading-in']['tmp_name']));
            foreach ($calendar->vevent as $event) {
                $start_t = active_date((string) $event->dtstart);
                $end_t = !empty($event->dtend) ? active_date((string) $event->dtend) : $start_t + 3600;
                if ($_POST['leadin-type'] == 'person') {
                    $color = "#75D906";
                } else {
                    $color = "#7515E0";
                }
                $sql = 'INSERT INTO ' . tname("calendar_info") . ' (`calendar_id`,`content`,`start_t`,`end_t`,`bgcolor`,`dateline`) values (' . $calendar_id . ',"' . $event->summary . '","' . $start_t . '","' . $end_t . '","' . $color . '","' . time() . '")';
                $_SGLOBAL['db']->query($sql);
            }
        }
    }
    showmessage('日历导入成功', 'space.php?do=calendar');
    exit;
 /**
  * Parses some information from calendar objects, used for optimized
  * calendar-queries.
  *
  * Returns an array with the following keys:
  *   * etag
  *   * size
  *   * componentType
  *   * firstOccurence
  *   * lastOccurence
  *
  * @param string $calendarData
  * @throws Sabre_DAV_Exception_BadRequest
  * @return array
  */
 protected function getDenormalizedData($calendarData)
 {
     /** @var Sabre\VObject\Component\VEvent $vObject */
     $vObject = Sabre\VObject\Reader::read($calendarData);
     $componentType = null;
     $component = null;
     $firstOccurence = null;
     $lastOccurence = null;
     foreach ($vObject->getComponents() as $component) {
         if ($component->name !== 'VTIMEZONE') {
             $componentType = $component->name;
             break;
         }
     }
     if (!$componentType) {
         throw new Sabre_DAV_Exception_BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
     }
     if ($componentType === 'VEVENT') {
         /** @var Sabre\VObject\Component\VEvent $component */
         /** @var Sabre\VObject\Property\DateTime $dtstart  */
         $dtstart = $component->__get("DTSTART");
         $firstOccurence = $dtstart->getDateTime()->getTimeStamp();
         // Finding the last occurence is a bit harder
         if (!$component->__get("RRULE")) {
             $lastOccurence = self::getDtEndTimeStamp($component);
         } else {
             $it = new Sabre\VObject\RecurrenceIterator($vObject, (string) $component->__get("UID"));
             $maxDate = new DateTime(CALDAV_MAX_YEAR . "-01-01");
             if ($it->isInfinite()) {
                 $lastOccurence = $maxDate->getTimeStamp();
             } else {
                 $end = $it->getDtEnd();
                 while ($it->valid() && $end < $maxDate) {
                     $end = $it->getDtEnd();
                     $it->next();
                 }
                 $lastOccurence = $end->getTimeStamp();
             }
         }
     }
     return array('etag' => md5($calendarData), 'size' => strlen($calendarData), 'componentType' => $componentType, 'firstOccurence' => $firstOccurence, 'lastOccurence' => $lastOccurence);
 }
Exemple #6
0
//import the contacts
writeProgress('70');
$imported = 0;
$failed = 0;
if (!count($parts) > 0) {
    OCP\JSON::error(array('data' => array('message' => 'No contacts to import in ' . $_POST['file'] . '. Please check if the file is corrupted.', 'file' => $_POST['file'])));
    if (isset($_POST['fstype']) && $_POST['fstype'] == 'OC_FilesystemView') {
        if (!$view->unlink('/imports/' . $_POST['file'])) {
            OCP\Util::writeLog('contacts', 'Import: Error unlinking OC_FilesystemView ' . '/' . $_POST['file'], OCP\Util::ERROR);
        }
    }
    exit;
}
foreach ($parts as $part) {
    try {
        $vcard = Sabre\VObject\Reader::read($part);
    } catch (Exception $e) {
        $failed += 1;
        OCP\Util::writeLog('contacts', 'Import: skipping card. Error parsing VCard: ' . $e->getMessage(), OCP\Util::ERROR);
        continue;
        // Ditch cards that can't be parsed by Sabre.
    }
    try {
        OCA\Contacts\VCard::add($id, $vcard);
        $imported += 1;
    } catch (Exception $e) {
        OCP\Util::writeLog('contacts', 'Error importing vcard: ' . $e->getMessage() . $nl . $vcard, OCP\Util::ERROR);
        $failed += 1;
    }
}
//done the import
Exemple #7
0
$contacts_alphabet = array_merge($contacts_alphabet, OCA\Contacts\VCard::all($ids));
/*foreach($ids as $id) {
	if($id) {
		$contacts_alphabet = array_merge(
				$contacts_alphabet,
				OCA\Contacts\VCard::all($id, $offset, 50)
		);
	}
}*/
uasort($contacts_alphabet, 'cmp');
$contacts = array();
// Our new array for the contacts sorted by addressbook
if ($contacts_alphabet) {
    foreach ($contacts_alphabet as $contact) {
        try {
            $vcard = Sabre\VObject\Reader::read($contact['carddata']);
            $details = OCA\Contacts\VCard::structureContact($vcard);
            $contacts[] = array('id' => $contact['id'], 'aid' => $contact['addressbookid'], 'data' => $details);
        } catch (Exception $e) {
            continue;
        }
        // This should never execute.
        /*if(!isset($contacts_addressbook[$contact['addressbookid']])) {
        			$contacts_addressbook[$contact['addressbookid']] = array(
        				'contacts' => array('type' => 'book',)
        			);
        		}
        		$display = trim($contact['fullname']);
        		if(!$display) {
        			$vcard = OCA\Contacts\App::getContactVCard($contact['id']);
        			if(!is_null($vcard)) {
Exemple #8
0
$partial = 0;
if (!count($parts) > 0) {
    OCP\JSON::error(array('data' => array('message' => 'No contacts to import in ' . OCP\Util::sanitizeHTML($inputfile) . '. Please check if the file is corrupted.', 'file' => OCP\Util::sanitizeHTML($inputfile))));
    if (isset($_POST['fstype']) && $_POST['fstype'] == 'OC_FilesystemView') {
        if (!$view->unlink('/imports/' . $inputfile)) {
            OCP\Util::writeLog('contacts', 'Import: Error unlinking OC_FilesystemView ' . '/' . OCP\Util::sanitizeHTML($inputfile), OCP\Util::ERROR);
        }
    }
    exit;
}
foreach ($parts as $part) {
    try {
        $vcard = Sabre\VObject\Reader::read($part);
    } catch (Sabre\VObject\ParseException $e) {
        try {
            $vcard = Sabre\VObject\Reader::read($part, Sabre\VObject\Reader::OPTION_IGNORE_INVALID_LINES);
            $partial += 1;
            OCP\Util::writeLog('contacts', 'Import: Retrying reading card. Error parsing VCard: ' . $e->getMessage(), OCP\Util::ERROR);
        } catch (Exception $e) {
            $failed += 1;
            OCP\Util::writeLog('contacts', 'Import: skipping card. Error parsing VCard: ' . $e->getMessage(), OCP\Util::ERROR);
            continue;
            // Ditch cards that can't be parsed by Sabre.
        }
    }
    try {
        OCA\Contacts\VCard::add($id, $vcard);
        $imported += 1;
    } catch (Exception $e) {
        OCP\Util::writeLog('contacts', 'Error importing vcard: ' . $e->getMessage() . $nl . $vcard, OCP\Util::ERROR);
        $failed += 1;
Exemple #9
0
 /**
  * Parses some information from calendar objects, used for optimized
  * calendar-queries.
  *
  * Returns an array with the following keys:
  *   * etag - An md5 checksum of the object without the quotes.
  *   * size - Size of the object in bytes
  *   * componentType - VEVENT, VTODO or VJOURNAL
  *   * firstOccurence
  *   * lastOccurence
  *   * uid - value of the UID property
  *
  * @param string $calendarData
  * @return array
  */
 protected function getDenormalizedData($calendarData)
 {
     $vObject = Sabre\VObject\Reader::read($calendarData);
     $componentType = null;
     $component = null;
     $firstOccurence = null;
     $lastOccurence = null;
     $uid = null;
     foreach ($vObject->getComponents() as $component) {
         if ($component->name !== 'VTIMEZONE') {
             $componentType = $component->name;
             $uid = (string) $component->UID;
             break;
         }
     }
     if (!$componentType) {
         throw new Sabre\DAV\Exception\BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component');
     }
     if ($componentType === 'VEVENT') {
         $firstOccurence = $component->DTSTART->getDateTime()->getTimeStamp();
         // Finding the last occurence is a bit harder
         if (!isset($component->RRULE)) {
             if (isset($component->DTEND)) {
                 $lastOccurence = $component->DTEND->getDateTime()->getTimeStamp();
             } elseif (isset($component->DURATION)) {
                 $endDate = clone $component->DTSTART->getDateTime();
                 $endDate->add(VObject\DateTimeParser::parse($component->DURATION->getValue()));
                 $lastOccurence = $endDate->getTimeStamp();
             } elseif (!$component->DTSTART->hasTime()) {
                 $endDate = clone $component->DTSTART->getDateTime();
                 $endDate->modify('+1 day');
                 $lastOccurence = $endDate->getTimeStamp();
             } else {
                 $lastOccurence = $firstOccurence;
             }
         } else {
             $it = new Sabre\VObject\RecurrenceIterator($vObject, (string) $component->UID);
             $maxDate = new \DateTime(self::MAX_DATE);
             if ($it->isInfinite()) {
                 $lastOccurence = $maxDate->getTimeStamp();
             } else {
                 $end = $it->getDtEnd();
                 while ($it->valid() && $end < $maxDate) {
                     $end = $it->getDtEnd();
                     $it->next();
                 }
                 $lastOccurence = $end->getTimeStamp();
             }
         }
     }
     return ['etag' => md5($calendarData), 'size' => strlen($calendarData), 'componentType' => $componentType, 'firstOccurence' => $firstOccurence, 'lastOccurence' => $lastOccurence, 'uid' => $uid];
 }
/**
 * @param string $uid
 * @return Sabre\VObject\Component\VCalendar $vObject
 */
function dav_create_empty_vevent($uid = "")
{
    if ($uid == "") {
        $uid = uniqid();
    }
    return Sabre\VObject\Reader::read("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//" . DAV_APPNAME . "//DAV-Plugin//EN\r\nBEGIN:VEVENT\r\nUID:" . $uid . "@" . dav_compat_get_hostname() . "\r\nDTSTAMP:" . date("Ymd") . "T" . date("His") . "Z\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n");
}
Exemple #11
0
 /**
  * @brief Adds an object
  * @param integer $id Calendar id
  * @param string $data  object
  * @return insertid
  */
 public static function add($id, $data)
 {
     $calendar = OC_Calendar_Calendar::find($id);
     if ($calendar['userid'] != OCP\User::getUser()) {
         $sharedCalendar = OCP\Share::getItemSharedWithBySource('calendar', $id);
         if (!$sharedCalendar || !($sharedCalendar['permissions'] & OCP\PERMISSION_CREATE)) {
             throw new Exception(OC_Calendar_App::$l10n->t('You do not have the permissions to add events to this calendar.'));
         }
     }
     $object = Sabre\VObject\Reader::read($data);
     list($type, $startdate, $enddate, $summary, $repeating, $uid) = self::extractData($object);
     if (is_null($uid)) {
         $uid = \Sabre\VObject\UUIDUtil::getUUID();
         $object->UID = $uid;
         $data = $object->serialize();
     }
     $uri = 'owncloud-' . md5($data . rand() . time()) . '.ics';
     $stmt = OCP\DB::prepare('INSERT INTO `*PREFIX*clndr_objects` (`calendarid`,`objecttype`,`startdate`,`enddate`,`repeating`,`summary`,`calendardata`,`uri`,`lastmodified`) VALUES(?,?,?,?,?,?,?,?,?)');
     $stmt->execute(array($id, $type, $startdate, $enddate, $repeating, $summary, $data, $uri, time()));
     $object_id = OCP\DB::insertid('*PREFIX*clndr_objects');
     OC_Calendar_App::loadCategoriesFromVCalendar($object_id, $object);
     self::addAlarmsDBFromData($object->VEVENT, $object_id);
     OC_Calendar_Calendar::touchCalendar($id);
     OCP\Util::emitHook('OC_Calendar', 'addEvent', $object_id);
     return $object_id;
 }
Exemple #12
0
 public function updateRecord($rekord, $card)
 {
     $this->log->debug(__CLASS__ . '::' . __METHOD__ . ' | Start Card ID:' . $card['id']);
     $vcard = Sabre\VObject\Reader::read($card['carddata']);
     $head = $vcard->N->getParts();
     $module = $rekord->getModuleName();
     $rekord->set('mode', 'edit');
     if ($module == 'Contacts') {
         $rekord->set('firstname', $head[1]);
         $rekord->set('lastname', $head[0]);
     }
     if ($module == 'OSSEmployees') {
         $rekord->set('name', $head[1]);
         $rekord->set('last_name', $head[0]);
     }
     if ($leadId != '') {
         $rekord->set('parent_id', $leadId);
     }
     foreach ($this->telFields[$module] as $key => $val) {
         $rekord->set($key, $this->getCardTel($vcard, $val));
     }
     foreach ($this->mailFields[$module] as $key => $val) {
         $rekord->set($key, $this->getCardMail($vcard, $val));
     }
     $rekord->save();
     $stmt = $this->pdo->prepare('UPDATE dav_cards SET crmid = ? WHERE id = ?;');
     $stmt->execute([$rekord->getId(), $card['id']]);
     $stmt = $this->pdo->prepare('UPDATE vtiger_crmentity SET modifiedtime = ? WHERE crmid = ?;');
     $stmt->execute([date('Y-m-d H:i:s', $card['lastmodified']), $rekord->getId()]);
     $this->log->debug(__CLASS__ . '::' . __METHOD__ . ' | End');
 }
/**
 * @param int $calendar_id
 * @return string
 */
function wdcal_import_user_ics($calendar_id)
{
    $a = get_app();
    $calendar_id = IntVal($calendar_id);
    $o = "";
    $server = dav_create_server(true, true, false);
    $calendar = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_WRITE);
    if (!$calendar) {
        goaway($a->get_baseurl() . "/dav/wdcal/");
    }
    if (isset($_REQUEST["save"])) {
        check_form_security_token_redirectOnErr('/dav/settings/', 'icsimport');
        if ($_FILES["ics_file"]["tmp_name"] != "" && is_uploaded_file($_FILES["ics_file"]["tmp_name"])) {
            try {
                $text = file_get_contents($_FILES["ics_file"]["tmp_name"]);
                /** @var Sabre\VObject\Component\VCalendar $vObject  */
                $vObject = Sabre\VObject\Reader::read($text);
                $comp = $vObject->getComponents();
                $imported = array();
                foreach ($comp as $c) {
                    try {
                        /** @var Sabre\VObject\Component\VEvent $c */
                        $uid = $c->__get("UID")->value;
                        if (!isset($imported[$uid])) {
                            $imported[$uid] = "";
                        }
                        $imported[$uid] .= $c->serialize();
                    } catch (Exception $e) {
                        notice(t("Something went wrong when trying to import the file. Sorry. Maybe some events were imported anyway."));
                    }
                }
                if (isset($_REQUEST["overwrite"])) {
                    $children = $calendar->getChildren();
                    foreach ($children as $child) {
                        /** @var Sabre_CalDAV_CalendarObject $child */
                        $child->delete();
                    }
                    $i = 1;
                } else {
                    $i = 0;
                    $children = $calendar->getChildren();
                    foreach ($children as $child) {
                        /** @var Sabre_CalDAV_CalendarObject $child */
                        $name = $child->getName();
                        if (preg_match("/import\\-([0-9]+)\\.ics/siu", $name, $matches)) {
                            if ($matches[1] > $i) {
                                $i = $matches[1];
                            }
                        }
                    }
                    $i++;
                }
                foreach ($imported as $object) {
                    try {
                        $str = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Friendica//DAV-Plugin//EN\r\n";
                        $str .= trim($object);
                        $str .= "\r\nEND:VCALENDAR\r\n";
                        $calendar->createFile("import-" . $i . ".ics", $str);
                        $i++;
                    } catch (Exception $e) {
                        notice(t("Something went wrong when trying to import the file. Sorry."));
                    }
                }
                $o = t("The ICS-File has been imported.");
            } catch (Exception $e) {
                notice(t("Something went wrong when trying to import the file. Sorry. Maybe some events were imported anyway."));
            }
        } else {
            notice(t("No file was uploaded."));
        }
    }
    $o .= "<a href='" . $a->get_baseurl() . "/dav/wdcal/'>" . t("Go back to the calendar") . "</a><br><br>";
    $num = q("SELECT COUNT(*) num FROM %s%scalendarobjects WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calendar_id);
    $o .= "<h2>" . t("Import a ICS-file") . "</h2>";
    $o .= '<form method="POST" action="' . $a->get_baseurl() . '/dav/wdcal/' . $calendar_id . '/ics-import/" enctype="multipart/form-data">';
    $o .= "<input type='hidden' name='form_security_token' value='" . get_form_security_token('icsimport') . "'>\n";
    $o .= "<label for='ics_file'>" . t("ICS-File") . "</label><input type='file' name='ics_file' id='ics_file'><br>\n";
    if ($num[0]["num"] > 0) {
        $o .= "<label for='overwrite'>" . str_replace("#num#", $num[0]["num"], t("Overwrite all #num# existing events")) . "</label> <input name='overwrite' id='overwrite' type='checkbox'><br>\n";
    }
    $o .= "<input type='submit' name='save' value='" . t("Upload") . "'>";
    $o .= '</form>';
    return $o;
}
Exemple #14
0
 /**
  * @brief edits a card with the data provided by sabredav
  * @param integer $id Addressbook id
  * @param string $uri   the uri of the card
  * @param string $data  vCard file
  * @return boolean
  */
 public static function editFromDAVData($aid, $uri, $data)
 {
     $oldcard = self::findWhereDAVDataIs($aid, $uri);
     try {
         $vcard = Sabre\VObject\Reader::read($data);
     } catch (\Exception $e) {
         \OCP\Util::writeLog('contacts', __METHOD__ . ', Unable to parse VCARD, : ' . $e->getMessage(), \OCP\Util::ERROR);
         return false;
     }
     try {
         self::edit($oldcard['id'], $vcard);
         return true;
     } catch (\Exception $e) {
         \OCP\Util::writeLog('contacts', __METHOD__ . ', exception: ' . $e->getMessage() . ', ' . \OCP\USER::getUser(), \OCP\Util::ERROR);
         \OCP\Util::writeLog('contacts', __METHOD__ . ', uri' . $uri, \OCP\Util::DEBUG);
         return false;
     }
 }
Exemple #15
0
#!/usr/bin/env php
<?php 
include __DIR__ . '/../vendor/autoload.php';
$data = stream_get_contents(STDIN);
$start = microtime(true);
$lol = Sabre\VObject\Reader::read($data);
echo "time: " . (microtime(true) - $start) . "\n";
Exemple #16
0
 /**
  * @brief Mass updates an array of cards
  * @param array $objects  An array of [id, carddata].
  */
 public static function updateDataByID($objects)
 {
     $stmt = \OCP\DB::prepare('UPDATE `*PREFIX*contacts_cards` SET `carddata` = ?, `lastmodified` = ? WHERE `id` = ?');
     $now = new \DateTime();
     foreach ($objects as $object) {
         $vcard = null;
         try {
             $vcard = Sabre\VObject\Reader::read($contact['carddata']);
         } catch (\Exception $e) {
             \OC_Log::write('contacts', __METHOD__ . $e->getMessage(), \OCP\Util::ERROR);
         }
         if (!is_null($vcard)) {
             $oldcard = self::find($object[0]);
             if (!$oldcard) {
                 return false;
             }
             $addressbook = Addressbook::find($oldcard['addressbookid']);
             if ($addressbook['userid'] != \OCP\User::getUser()) {
                 $sharedContact = \OCP\Share::getItemSharedWithBySource('contact', $object[0], \OCP\Share::FORMAT_NONE, null, true);
                 if (!$sharedContact || !($sharedContact['permissions'] & \OCP\PERMISSION_UPDATE)) {
                     return false;
                 }
             }
             $vcard->{'REV'} = $now->format(\DateTime::W3C);
             $data = $vcard->serialize();
             try {
                 $result = $stmt->execute(array($data, time(), $object[0]));
                 if (\OC_DB::isError($result)) {
                     \OC_Log::write('contacts', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($result), \OCP\Util::ERROR);
                 }
                 //OCP\Util::writeLog('contacts','OCA\Contacts\VCard::updateDataByID, id: '.$object[0].': '.$object[1],OCP\Util::DEBUG);
             } catch (Exception $e) {
                 \OCP\Util::writeLog('contacts', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR);
                 \OCP\Util::writeLog('contacts', __METHOD__ . ', id: ' . $object[0], \OCP\Util::DEBUG);
             }
             App::updateDBProperties($object[0], $vcard);
         }
     }
 }
 /**
  * @param array $courseInfo
  * @param $file
  * @return array|bool|string
  */
 public function importEventFile($courseInfo, $file)
 {
     $charset = api_get_system_encoding();
     $filepath = api_get_path(SYS_ARCHIVE_PATH) . $file['name'];
     $messages = array();
     if (!@move_uploaded_file($file['tmp_name'], $filepath)) {
         error_log('Problem moving uploaded file: ' . $file['error'] . ' in ' . __FILE__ . ' line ' . __LINE__);
         return false;
     }
     $data = file_get_contents($filepath);
     $trans = array('DAILY' => 'daily', 'WEEKLY' => 'weekly', 'MONTHLY' => 'monthlyByDate', 'YEARLY' => 'yearly');
     $sentTo = array('everyone' => true);
     $calendar = Sabre\VObject\Reader::read($data);
     $currentTimeZone = _api_get_timezone();
     if (!empty($calendar->VEVENT)) {
         foreach ($calendar->VEVENT as $event) {
             $start = $event->DTSTART->getDateTime();
             $end = $event->DTEND->getDateTime();
             //Sabre\VObject\DateTimeParser::parseDateTime(string $dt, \Sabre\VObject\DateTimeZone $tz)
             $startDateTime = api_get_local_time($start->format('Y-m-d H:i:s'), $currentTimeZone, $start->format('e'));
             $endDateTime = api_get_local_time($end->format('Y-m-d H:i'), $currentTimeZone, $end->format('e'));
             $title = api_convert_encoding((string) $event->summary, $charset, 'UTF-8');
             $description = api_convert_encoding((string) $event->description, $charset, 'UTF-8');
             $id = $this->addEvent($startDateTime, $endDateTime, 'false', $title, $description, $sentTo);
             $messages[] = " {$title} - " . $startDateTime . " - " . $endDateTime;
             //$attendee = (string)$event->attendee;
             /** @var Sabre\VObject\Property\ICalendar\Recur $repeat */
             $repeat = $event->RRULE;
             if ($id && !empty($repeat)) {
                 $repeat = $repeat->getParts();
                 $freq = $trans[$repeat['FREQ']];
                 if (isset($repeat['UNTIL']) && !empty($repeat['UNTIL'])) {
                     // Check if datetime or just date (strlen == 8)
                     if (strlen($repeat['UNTIL']) == 8) {
                         // Fix the datetime format to avoid exception in the next step
                         $repeat['UNTIL'] .= 'T000000';
                     }
                     $until = Sabre\VObject\DateTimeParser::parseDateTime($repeat['UNTIL'], new DateTimeZone($currentTimeZone));
                     $until = $until->format('Y-m-d H:i');
                     //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $until, $attendee);
                     $this->addRepeatedItem($id, $freq, $until, $sentTo);
                 }
                 if (!empty($repeat['COUNT'])) {
                     /*$count = $repeat['COUNT'];
                       $interval = $repeat['INTERVAL'];
                       $endDate = null;
                       switch($freq) {
                           case 'daily':
                               $start = api_strtotime($startDateTime);
                               $date = new DateTime($startDateTime);
                               $days = $count * $interval;
                               var_dump($days);
                               $date->add(new DateInterval("P".$days."D"));
                               $endDate = $date->format('Y-m-d H:i');
                               //$endDate = $count *
                               for ($i = 0; $i < $count; $i++) {
                                   $days = 86400 * 7
                               }
                           }
                       }*/
                     //$res = agenda_add_repeat_item($courseInfo, $id, $freq, $count, $attendee);
                     /*$this->addRepeatedItem(
                           $id,
                           $freq,
                           $endDate,
                           $sentTo
                       );*/
                 }
             }
         }
     }
     if (!empty($messages)) {
         $messages = implode('<br /> ', $messages);
     } else {
         $messages = get_lang('NoAgendaItems');
     }
     return $messages;
 }
 public function run()
 {
     $dbc = CalendarPluginDB::get();
     /**
       Use prepare statements instead of models
       for efficiency. Could be issuing a large number
       of queries with many subscriptions
     */
     $uidP = $dbc->prepare('
         SELECT eventID
         FROM monthview_events
         WHERE calendarID=?
             AND subscriptionUID=?');
     $insertP = $dbc->prepare('
         INSERT INTO monthview_events
         (calendarID, eventDate, eventText, uid, subscriptionUID)
         VALUES
         (?, ?, ?, 0, ?)');
     $updateP = $dbc->prepare('
         UPDATE monthview_events
         SET eventDate=?,
             eventText=?
         WHERE eventID=?');
     $calendarsQ = '
         SELECT c.calendarID,
             s.url
         FROM calendars AS c
             INNER JOIN CalendarSubscriptions AS s 
                 ON c.calendarSubscriptionID=s.calendarSubscriptionID';
     $calendarsR = $dbc->query($calendarsQ);
     $our_tz = new DateTimeZone(date_default_timezone_get());
     /**
       For each subscribed calendar:
       * Download the feed URL to temporary storage
       * Parse the feed data and extract VEvents
       * Loop through the events and add/update them
       * Delete any events in the calendar that
         a) do not match one of the event unique IDs
         b) fall within the same timespan as the
            parsed events
         These two conditions *probably* indicate
         the event was deleted in the source calendar
     */
     while ($calendarsW = $dbc->fetchRow($calendarsR)) {
         $calendarID = $calendarsW['calendarID'];
         $file = $this->downloadFeed($calendarsW['url']);
         if ($file === false) {
             // error downloading feed
             continue;
         }
         $fp = fopen($file, 'r');
         $document = Sabre\VObject\Reader::read($fp, Sabre\VObject\Reader::OPTION_FORGIVING);
         $events = $document->getBaseComponents('VEvent');
         $subscribedIDs = array();
         $earliest = new DateTime('today');
         $latest = new DateTime('today');
         foreach ($events as $event) {
             if (!isset($event->DTSTART) || !isset($event->UID)) {
                 // malformed event
                 continue;
             }
             $summary = false;
             if (isset($event->SUMMARY)) {
                 $summary = $event->SUMMARY->getValue();
             }
             $description = false;
             if (isset($event->DESCRIPTION)) {
                 $description = $event->DESCRIPTION->getValue();
             }
             if (!$summary && !$description) {
                 // event has no useful content
                 continue;
             }
             $uniqueID = $event->UID;
             $start = $event->DTSTART->getDateTime();
             $start->setTimezone($our_tz);
             $hours = false;
             if ($event->DTEND) {
                 $end = $event->DTEND->getDateTime();
                 $end->setTimezone($our_tz);
                 if ($start->format('Y-m-d') == $end->format('Y-m-d')) {
                     $t1 = $start->format('H:ia');
                     $t2 = $end->format('H:ia');
                     if ($t1 != $t2) {
                         $hours = $t1 . ' - ' . $t2;
                     }
                 }
             }
             $eventText = '';
             if ($hours) {
                 $eventText .= $hours . "\n";
             }
             if ($summary) {
                 $eventText .= $summary . "\n";
             }
             if ($description) {
                 $eventText .= $description . "\n";
             }
             $uidR = $dbc->execute($uidP, array($calendarID, $uniqueID));
             if ($dbc->numRows($uidR) == 0) {
                 $dbc->execute($insertP, array($calendarID, $start->format('Y-m-d'), nl2br($eventText), $uniqueID));
             } else {
                 $uidW = $dbc->fetchRow($uidR);
                 $dbc->execute($updateP, array($start->format('Y-m-d'), nl2br($eventText), $uidW['eventID']));
             }
             $subscribedIDs[] = $uniqueID;
             if ($start < $earliest) {
                 $earliest = $start;
             }
             if ($start > $latest) {
                 $latest = $start;
             }
         }
         if (count($subscribedIDs) > 0) {
             $cleanQ = '
                 DELETE FROM monthview_events
                 WHERE calendarID=?
                     AND eventDate BETWEEN ? AND ?
                     AND subscriptionUID NOT IN (';
             $cleanArgs = array($calendarID, $earliest->format('Y-m-d'), $latest->format('Y-m-d'));
             foreach ($subscribedIDs as $sID) {
                 $cleanQ .= '?,';
                 $cleanArgs[] = $sID;
             }
             $cleanQ = substr($cleanQ, 0, strlen($cleanQ) - 1);
             $cleanQ .= ')';
             $cleanP = $dbc->prepare($cleanQ);
             $cleanR = $dbc->execute($cleanP, $cleanArgs);
         }
         fclose($fp);
         unlink($file);
     }
 }