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));
 }
 /**
  * @static
  * @param int $calendarId
  * @throws Sabre_DAV_Exception_NotFound
  * @return void
  */
 protected static function createCache_internal($calendarId)
 {
     $calendar = Sabre_CalDAV_Backend_Common::loadCalendarById($calendarId);
     switch ($calendar["uri"]) {
         case CALDAV_FRIENDICA_MINE:
             $sql_where = " AND cid = 0";
             break;
         case CALDAV_FRIENDICA_CONTACTS:
             $sql_where = " AND cid > 0";
             break;
         default:
             throw new Sabre_DAV_Exception_NotFound();
     }
     $r = q("SELECT * FROM `event` WHERE `uid` = %d " . $sql_where . " ORDER BY `start`", IntVal($calendar["namespace_id"]));
     foreach ($r as $row) {
         $uid = $calendar["uri"] . "-" . $row["id"];
         $vevent = dav_create_empty_vevent($uid);
         $component = dav_get_eventComponent($vevent);
         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"];
         }
         $summary = $row["summary"] != "" ? $row["summary"] : $row["desc"];
         $desc = $row["summary"] != "" ? $row["desc"] : "";
         $component->add("SUMMARY", icalendar_sanitize_string($summary));
         $component->add("LOCATION", icalendar_sanitize_string($row["location"]));
         $component->add("DESCRIPTION", icalendar_sanitize_string($desc));
         $ts_start = wdcal_mySql2PhpTime($start);
         $ts_end = wdcal_mySql2PhpTime($start);
         $allday = strpos($start, "00:00:00") !== false && strpos($finish, "00:00:00") !== false;
         $type = $allday ? Sabre\VObject\Property\DateTime::DATE : Sabre\VObject\Property\DateTime::LOCALTZ;
         $datetime_start = new Sabre\VObject\Property\DateTime("DTSTART");
         $datetime_start->setDateTime(new DateTime(date("Y-m-d H:i:s", $ts_start)), $type);
         $datetime_end = new Sabre\VObject\Property\DateTime("DTEND");
         $datetime_end->setDateTime(new DateTime(date("Y-m-d H:i:s", $ts_end)), $type);
         $component->add($datetime_start);
         $component->add($datetime_end);
         $data = $vevent->serialize();
         q("INSERT INTO %s%scal_virtual_object_cache (`calendar_id`, `data_uri`, `data_summary`, `data_location`, `data_start`, `data_end`, `data_allday`, `data_type`,\n\t\t\t\t`calendardata`, `size`, `etag`) VALUES (%d, '%s', '%s', '%s', '%s', '%s', %d, '%s', '%s', %d, '%s')", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calendarId, dbesc($uid), dbesc($summary), dbesc($row["location"]), dbesc($row["start"]), dbesc($row["finish"]), $allday ? 1 : 0, dbesc($row["type"] == "birthday" ? "birthday" : ""), dbesc($data), strlen($data), md5($data));
     }
 }
/**
 * @param string $uri
 * @param int $uid
 * @param string $timezone
 * @param string $goaway_url
 * @return array
 */
function wdcal_postEditPage($uri, $uid = 0, $timezone = "", $goaway_url = "")
{
    $uid = IntVal($uid);
    $localization = wdcal_local::getInstanceByUser($uid);
    $server = dav_create_server(true, true, false);
    if ($uri > 0) {
        $calendar = dav_get_current_user_calendar_by_id($server, $_REQUEST["calendar"], DAV_ACL_READ);
        $obj_uri = Sabre_CalDAV_Backend_Common::loadCalendarobjectById($uri);
        $obj_uri = $obj_uri["uri"];
        $vObject = dav_get_current_user_calendarobject($server, $calendar, $obj_uri, DAV_ACL_WRITE);
        $component = dav_get_eventComponent($vObject);
        if ($component == null) {
            return array("ok" => false, "msg" => t('Could not open component for editing'));
        }
    } else {
        $calendar = dav_get_current_user_calendar_by_id($server, $_REQUEST["calendar"], DAV_ACL_WRITE);
        $vObject = dav_create_empty_vevent();
        $component = dav_get_eventComponent($vObject);
        $obj_uri = $component->__get("UID");
    }
    $ts_start = wdcal_set_component_date($component, $localization);
    wdcal_set_component_recurrence($component, $localization);
    wdcal_set_component_alerts($component, $localization, icalendar_sanitize_string(dav_compat_parse_text_serverside("summary")), $ts_start);
    $component->__unset("LOCATION");
    $component->__unset("SUMMARY");
    $component->__unset("DESCRIPTION");
    $component->__unset("X-ANIMEXX-COLOR");
    $component->add("SUMMARY", icalendar_sanitize_string(dav_compat_parse_text_serverside("summary")));
    $component->add("LOCATION", icalendar_sanitize_string(dav_compat_parse_text_serverside("location")));
    $component->add("DESCRIPTION", icalendar_sanitize_string(dav_compat_parse_text_serverside("wdcal_desc")));
    if (isset($_REQUEST["color_override"])) {
        $component->add("X-ANIMEXX-COLOR", $_REQUEST["color"]);
    }
    $data = $vObject->serialize();
    if ($uri == 0) {
        $calendar->createFile($obj_uri . ".ics", $data);
    } else {
        $obj = $calendar->getChild($obj_uri);
        $obj->put($data);
    }
    return array("ok" => false, "msg" => t("Saved"));
}
/**
 *
 */
function wdcal_print_feed($base_path = "")
{
    $server = dav_create_server(true, true, false);
    $ret = null;
    $method = $_GET["method"];
    switch ($method) {
        case "add":
            $cs = wdcal_print_feed_getCal($server, DAV_ACL_WRITE);
            if ($cs == null) {
                echo wdcal_jsonp_encode(array('IsSuccess' => false, 'Msg' => t('No access')));
                killme();
            }
            try {
                $item = dav_create_empty_vevent();
                $component = dav_get_eventComponent($item);
                $component->add("SUMMARY", icalendar_sanitize_string(dav_compat_parse_text_serverside("CalendarTitle")));
                if (isset($_REQUEST["allday"])) {
                    $type = Sabre\VObject\Property\DateTime::DATE;
                } else {
                    $type = Sabre\VObject\Property\DateTime::LOCALTZ;
                }
                $datetime_start = new Sabre\VObject\Property\DateTime("DTSTART");
                $datetime_start->setDateTime(new DateTime(date("Y-m-d H:i:s", IntVal($_REQUEST["CalendarStartTime"]))), $type);
                $datetime_end = new Sabre\VObject\Property\DateTime("DTEND");
                $datetime_end->setDateTime(new DateTime(date("Y-m-d H:i:s", IntVal($_REQUEST["CalendarEndTime"]))), $type);
                $component->add($datetime_start);
                $component->add($datetime_end);
                $uid = $component->__get("UID");
                $data = $item->serialize();
                $cs->createFile($uid . ".ics", $data);
                $ret = array('IsSuccess' => true, 'Msg' => 'add success', 'Data' => $uid . ".ics");
            } catch (Exception $e) {
                $ret = array('IsSuccess' => false, 'Msg' => $e->__toString());
            }
            break;
        case "list":
            $weekstartday = isset($_REQUEST["weekstartday"]) ? IntVal($_REQUEST["weekstartday"]) : 1;
            // 1 = Monday
            $num_days = isset($_REQUEST["num_days"]) ? IntVal($_REQUEST["num_days"]) : 7;
            $ret = null;
            $date = wdcal_get_list_range_params($_REQUEST["showdate"], $weekstartday, $num_days, $_REQUEST["viewtype"]);
            $ret = array();
            $ret['events'] = array();
            $ret["issort"] = true;
            $ret["start"] = $date[0];
            $ret["end"] = $date[1];
            $ret['error'] = null;
            $cals = dav_get_current_user_calendars($server, DAV_ACL_READ);
            foreach ($cals as $cal) {
                $prop = $cal->getProperties(array("id"));
                if (isset($prop["id"]) && (!isset($_REQUEST["cal"]) || in_array($prop["id"], $_REQUEST["cal"]))) {
                    $backend = wdcal_calendar_factory_by_id($prop["id"]);
                    $events = $backend->listItemsByRange($prop["id"], $date[0], $date[1], $base_path);
                    $ret["events"] = array_merge($ret["events"], $events);
                }
            }
            $tmpev = array();
            foreach ($ret["events"] as $e) {
                if (!isset($tmpev[$e["start"]])) {
                    $tmpev[$e["start"]] = array();
                }
                $tmpev[$e["start"]][] = $e;
            }
            ksort($tmpev);
            $ret["events"] = array();
            foreach ($tmpev as $e) {
                foreach ($e as $f) {
                    $ret["events"][] = $f;
                }
            }
            break;
        case "update":
            $r = q("SELECT `calendarobject_id`, `calendar_id` FROM %s%sjqcalendar WHERE `id`=%d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($_REQUEST["jq_id"]));
            if (count($r) != 1) {
                echo wdcal_jsonp_encode(array('IsSuccess' => false, 'Msg' => t('No access')));
                killme();
            }
            try {
                $cs = dav_get_current_user_calendar_by_id($server, $r[0]["calendar_id"], DAV_ACL_READ);
                $obj_uri = Sabre_CalDAV_Backend_Common::loadCalendarobjectById($r[0]["calendarobject_id"]);
                $vObject = dav_get_current_user_calendarobject($server, $cs, $obj_uri["uri"], DAV_ACL_WRITE);
                $component = dav_get_eventComponent($vObject);
                if (!$component) {
                    echo wdcal_jsonp_encode(array('IsSuccess' => false, 'Msg' => t('No access')));
                    killme();
                }
                if (isset($_REQUEST["allday"])) {
                    $type = Sabre\VObject\Property\DateTime::DATE;
                } else {
                    $type = Sabre\VObject\Property\DateTime::LOCALTZ;
                }
                $datetime_start = new Sabre\VObject\Property\DateTime("DTSTART");
                $datetime_start->setDateTime(new DateTime(date("Y-m-d H:i:s", IntVal($_REQUEST["CalendarStartTime"]))), $type);
                $datetime_end = new Sabre\VObject\Property\DateTime("DTEND");
                $datetime_end->setDateTime(new DateTime(date("Y-m-d H:i:s", IntVal($_REQUEST["CalendarEndTime"]))), $type);
                $component->__unset("DTSTART");
                $component->__unset("DTEND");
                $component->add($datetime_start);
                $component->add($datetime_end);
                $data = $vObject->serialize();
                /** @var Sabre_CalDAV_CalendarObject $child  */
                $child = $cs->getChild($obj_uri["uri"]);
                $child->put($data);
                $ret = array('IsSuccess' => true, 'Msg' => 'Succefully');
            } catch (Exception $e) {
                echo wdcal_jsonp_encode(array('IsSuccess' => false, 'Msg' => t('No access')));
                killme();
            }
            break;
        case "remove":
            $r = q("SELECT `calendarobject_id`, `calendar_id` FROM %s%sjqcalendar WHERE `id`=%d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($_REQUEST["jq_id"]));
            if (count($r) != 1) {
                echo wdcal_jsonp_encode(array('IsSuccess' => false, 'Msg' => t('No access')));
                killme();
            }
            try {
                $cs = dav_get_current_user_calendar_by_id($server, $r[0]["calendar_id"], DAV_ACL_WRITE);
                $obj_uri = Sabre_CalDAV_Backend_Common::loadCalendarobjectById($r[0]["calendarobject_id"]);
                $child = $cs->getChild($obj_uri["uri"]);
                $child->delete();
                $ret = array('IsSuccess' => true, 'Msg' => 'Succefully');
            } catch (Exception $e) {
                echo wdcal_jsonp_encode(array('IsSuccess' => false, 'Msg' => t('No access')));
                killme();
            }
            break;
    }
    echo wdcal_jsonp_encode($ret);
    killme();
}
 /**
  * @param array $start
  * @param array $end
  * @param string $subject
  * @param bool $allday
  * @param string $description
  * @param string $location
  * @param null $color
  * @param string $timezone
  * @param bool $notification
  * @param null $notification_type
  * @param null $notification_value
  * @return array|string
  */
 public function addItem($start, $end, $subject, $allday = false, $description = "", $location = "", $color = null, $timezone = "", $notification = true, $notification_type = null, $notification_value = null)
 {
     $a = get_app();
     $v = new vcalendar();
     $v->setConfig('unique_id', $a->get_hostname());
     $v->setProperty('method', 'PUBLISH');
     $v->setProperty("x-wr-calname", "AnimexxCal");
     $v->setProperty("X-WR-CALDESC", "Animexx Calendar");
     $v->setProperty("X-WR-TIMEZONE", $a->timezone);
     $vevent = dav_create_vevent($start, $end, $allday);
     $vevent->setLocation(icalendar_sanitize_string($location));
     $vevent->setSummary(icalendar_sanitize_string($subject));
     $vevent->setDescription(icalendar_sanitize_string($description));
     if (!is_null($color) && $color >= 0) {
         $vevent->setProperty("X-ANIMEXX-COLOR", $color);
     }
     if ($notification && $notification_type == null) {
         if ($allday) {
             $notification_type = "hour";
             $notification_value = 24;
         } else {
             $notification_type = "minute";
             $notification_value = 60;
         }
     }
     if ($notification) {
         $valarm = new valarm();
         $valarm->setTrigger($notification_type == "year" ? $notification_value : 0, $notification_type == "month" ? $notification_value : 0, $notification_type == "day" ? $notification_value : 0, $notification_type == "week" ? $notification_value : 0, $notification_type == "hour" ? $notification_value : 0, $notification_type == "minute" ? $notification_value : 0, $notification_type == "second" ? $notification_value : 0, true, $notification_value > 0);
         $valarm->setAction("DISPLAY");
         $valarm->setDescription($subject);
         $vevent->setComponent($valarm);
     }
     $v->setComponent($vevent);
     $ical = $v->createCalendar();
     $obj_id = trim($vevent->getProperty("UID"));
     $calendarBackend = new Sabre_CalDAV_Backend_Std();
     $calendarBackend->createCalendarObject($this->getNamespace() . "-" . $this->namespace_id, $obj_id . ".ics", $ical);
     return $obj_id . ".ics";
 }
 /**
  * Updates an existing calendarobject, based on it's uri.
  *
  * It is possible return an etag from this function, which will be used in
  * the response to this PUT request. Note that the ETag must be surrounded
  * by double-quotes.
  *
  * However, you should only really return this ETag if you don't mangle the
  * calendar-data. If the result of a subsequent GET to this object is not
  * the exact same as this request body, you should omit the ETag.
  *
  * @param mixed $calendarId
  * @param string $objectUri
  * @param string $calendarData
  * @return string|null
  */
 function updateCalendarObject($calendarId, $objectUri, $calendarData)
 {
     $calendarData = icalendar_sanitize_string($calendarData);
     $extraData = $this->getDenormalizedData($calendarData);
     q("UPDATE %s%scalendarobjects SET `calendardata` = '%s', `lastmodified` = NOW(), `etag` = '%s', `size` = %d, `componentType` = '%s', `firstOccurence` = '%s', `lastOccurence` = '%s'\n\t\t\tWHERE `calendar_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($calendarData), dbesc($extraData["etag"]), IntVal($extraData["size"]), dbesc($extraData["componentType"]), dbesc(wdcal_php2MySqlTime($extraData["firstOccurence"])), dbesc(wdcal_php2MySqlTime($extraData["lastOccurence"])), IntVal($calendarId), dbesc($objectUri));
     $this->increaseCalendarCtag($calendarId);
     renderCalDavEntry_uri($objectUri);
     return '"' . $extraData['etag'] . '"';
 }