public function rfcString($include_timezone = true)
{
$str = '';
if ($this->rule['DTSTART']) {
if (!$include_timezone) {
$str = sprintf("DTSTART:%s\nRRULE:", $this->dtstart->format('Ymd\\THis'));
} else {
$dtstart = clone $this->dtstart;
$timezone_name = $dtstart->getTimeZone()->getName();
if (strpos($timezone_name, ':') !== false) {
// handle unsupported timezones like "+02:00"
// we convert them to UTC to generate a valid string
// note: there is possibly other weird timezones out there that we should catch
$dtstart->setTimezone(new \DateTimeZone('UTC'));
$timezone_name = 'UTC';
}
if (in_array($timezone_name, array('UTC', 'GMT', 'Z'))) {
$str = sprintf("DTSTART:%s\nRRULE:", $dtstart->format('Ymd\\THis\\Z'));
} else {
$str = sprintf("DTSTART;TZID=%s:%s\nRRULE:", $timezone_name, $dtstart->format('Ymd\\THis'));
}
}
}
$parts = array();
foreach ($this->rule as $key => $value) {
if ($key === 'DTSTART') {
continue;
}
if ($key === 'INTERVAL' && $value == 1) {
continue;
}
if ($key === 'WKST' && $value === 'MO') {
continue;
}
if ($key === 'UNTIL' && $value) {
if (!$include_timezone) {
$tmp = clone $this->until;
// put until on the same timezone as DTSTART
$tmp->setTimeZone($this->dtstart->getTimezone());
$parts[] = 'UNTIL=' . $tmp->format('Ymd\\THis');
} else {
// according to the RFC, UNTIL must be in UTC
$tmp = clone $this->until;
$tmp->setTimezone(new \DateTimeZone('UTC'));
$parts[] = 'UNTIL=' . $tmp->format('Ymd\\THis\\Z');
}
continue;
}
if ($key === 'FREQ' && $value && !array_key_exists($value, static::$frequencies)) {
$frequency_key = array_search($value, static::$frequencies);
if ($frequency_key !== false) {
$value = $frequency_key;
}
}
if ($value) {
if (is_array($value)) {
$value = implode(',', $value);
}
$parts[] = strtoupper(str_replace(' ', '', "{$key}={$value}"));
}
}
$str .= implode(';', $parts);
return $str;
}