Page Menu
Home
Phorge
Search
Configure Global Search
Log In
Files
F256952
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
185 KB
Referenced Files
None
Subscribers
None
View Options
diff --git a/plugins/libkolab/bin/Date_Recurrence_weekday.diff b/plugins/libkolab/bin/Date_Recurrence_weekday.diff
deleted file mode 100644
index e8b767df..00000000
--- a/plugins/libkolab/bin/Date_Recurrence_weekday.diff
+++ /dev/null
@@ -1,325 +0,0 @@
---- Date/Recurrence.php.orig 2012-07-10 19:54:48.000000000 +0200
-+++ Date/Recurrence.php 2012-07-10 19:55:38.000000000 +0200
-@@ -95,6 +95,20 @@
- public $recurData = null;
-
- /**
-+ * BYDAY recurrence number
-+ *
-+ * @var integer
-+ */
-+ public $recurNthDay = null;
-+
-+ /**
-+ * BYMONTH recurrence data
-+ *
-+ * @var array
-+ */
-+ public $recurMonths = array();
-+
-+ /**
- * All the exceptions from recurrence for this event.
- *
- * @var array
-@@ -157,6 +171,44 @@
- }
-
- /**
-+ *
-+ * @param integer $nthDay The nth weekday of month to repeat events on
-+ */
-+ public function setRecurNthWeekday($nth)
-+ {
-+ $this->recurNthDay = (int)$nth;
-+ }
-+
-+ /**
-+ *
-+ * @return integer The nth weekday of month to repeat events.
-+ */
-+ public function getRecurNthWeekday()
-+ {
-+ return isset($this->recurNthDay) ? $this->recurNthDay : ceil($this->start->mday / 7);
-+ }
-+
-+ /**
-+ * Specifies the months for yearly (weekday) recurrence
-+ *
-+ * @param array $months List of months (integers) this event recurs on.
-+ */
-+ function setRecurByMonth($months)
-+ {
-+ $this->recurMonths = (array)$months;
-+ }
-+
-+ /**
-+ * Returns a list of months this yearly event recurs on
-+ *
-+ * @return array List of months (integers) this event recurs on.
-+ */
-+ function getRecurByMonth()
-+ {
-+ return $this->recurMonths;
-+ }
-+
-+ /**
- * Returns the days this event recurs on.
- *
- * @return integer A mask consisting of Horde_Date::MASK_* constants
-@@ -546,8 +598,13 @@
- $estart = clone $this->start;
-
- // What day of the week, and week of the month, do we recur on?
-- $nth = ceil($this->start->mday / 7);
-- $weekday = $estart->dayOfWeek();
-+ if (isset($this->recurNthDay)) {
-+ $nth = $this->recurNthDay;
-+ $weekday = log($this->recurData, 2);
-+ } else {
-+ $nth = ceil($this->start->mday / 7);
-+ $weekday = $estart->dayOfWeek();
-+ }
-
- // Adjust $estart to be the first candidate.
- $offset = ($after->month - $estart->month) + ($after->year - $estart->year) * 12;
-@@ -660,8 +717,13 @@
- $estart = clone $this->start;
-
- // What day of the week, and week of the month, do we recur on?
-- $nth = ceil($this->start->mday / 7);
-- $weekday = $estart->dayOfWeek();
-+ if (isset($this->recurNthDay)) {
-+ $nth = $this->recurNthDay;
-+ $weekday = log($this->recurData, 2);
-+ } else {
-+ $nth = ceil($this->start->mday / 7);
-+ $weekday = $estart->dayOfWeek();
-+ }
-
- // Adjust $estart to be the first candidate.
- $offset = floor(($after->year - $estart->year + $this->recurInterval - 1) / $this->recurInterval) * $this->recurInterval;
-@@ -894,15 +956,6 @@
- case 'W':
- $this->setRecurType(self::RECUR_WEEKLY);
- if (!empty($remainder)) {
-- $maskdays = array(
-- 'SU' => Horde_Date::MASK_SUNDAY,
-- 'MO' => Horde_Date::MASK_MONDAY,
-- 'TU' => Horde_Date::MASK_TUESDAY,
-- 'WE' => Horde_Date::MASK_WEDNESDAY,
-- 'TH' => Horde_Date::MASK_THURSDAY,
-- 'FR' => Horde_Date::MASK_FRIDAY,
-- 'SA' => Horde_Date::MASK_SATURDAY,
-- );
- $mask = 0;
- while (preg_match('/^ ?[A-Z]{2} ?/', $remainder, $matches)) {
- $day = trim($matches[0]);
-@@ -953,7 +1006,10 @@
- list($year, $month, $mday) = sscanf($remainder, '%04d%02d%02d');
- $this->setRecurEnd(new Horde_Date(array('year' => $year,
- 'month' => $month,
-- 'mday' => $mday)));
-+ 'mday' => $mday,
-+ 'hour' => 23,
-+ 'min' => 59,
-+ 'sec' => 59)));
- }
- }
- }
-@@ -1049,6 +1105,16 @@
- // Always default the recurInterval to 1.
- $this->setRecurInterval(isset($rdata['INTERVAL']) ? $rdata['INTERVAL'] : 1);
-
-+ $maskdays = array(
-+ 'SU' => Horde_Date::MASK_SUNDAY,
-+ 'MO' => Horde_Date::MASK_MONDAY,
-+ 'TU' => Horde_Date::MASK_TUESDAY,
-+ 'WE' => Horde_Date::MASK_WEDNESDAY,
-+ 'TH' => Horde_Date::MASK_THURSDAY,
-+ 'FR' => Horde_Date::MASK_FRIDAY,
-+ 'SA' => Horde_Date::MASK_SATURDAY,
-+ );
-+
- switch (Horde_String::upper($rdata['FREQ'])) {
- case 'DAILY':
- $this->setRecurType(self::RECUR_DAILY);
-@@ -1057,15 +1123,6 @@
- case 'WEEKLY':
- $this->setRecurType(self::RECUR_WEEKLY);
- if (isset($rdata['BYDAY'])) {
-- $maskdays = array(
-- 'SU' => Horde_Date::MASK_SUNDAY,
-- 'MO' => Horde_Date::MASK_MONDAY,
-- 'TU' => Horde_Date::MASK_TUESDAY,
-- 'WE' => Horde_Date::MASK_WEDNESDAY,
-- 'TH' => Horde_Date::MASK_THURSDAY,
-- 'FR' => Horde_Date::MASK_FRIDAY,
-- 'SA' => Horde_Date::MASK_SATURDAY,
-- );
- $days = explode(',', $rdata['BYDAY']);
- $mask = 0;
- foreach ($days as $day) {
-@@ -1090,6 +1147,10 @@
- case 'MONTHLY':
- if (isset($rdata['BYDAY'])) {
- $this->setRecurType(self::RECUR_MONTHLY_WEEKDAY);
-+ if (preg_match('/(-?[1-4])([A-Z]+)/', $rdata['BYDAY'], $m)) {
-+ $this->setRecurOnDay($maskdays[$m[2]]);
-+ $this->setRecurNthWeekday($m[1]);
-+ }
- } else {
- $this->setRecurType(self::RECUR_MONTHLY_DATE);
- }
-@@ -1100,6 +1161,14 @@
- $this->setRecurType(self::RECUR_YEARLY_DAY);
- } elseif (isset($rdata['BYDAY'])) {
- $this->setRecurType(self::RECUR_YEARLY_WEEKDAY);
-+ if (preg_match('/(-?[1-4])([A-Z]+)/', $rdata['BYDAY'], $m)) {
-+ $this->setRecurOnDay($maskdays[$m[2]]);
-+ $this->setRecurNthWeekday($m[1]);
-+ }
-+ if ($rdata['BYMONTH']) {
-+ $months = explode(',', $rdata['BYMONTH']);
-+ $this->setRecurByMonth($months);
-+ }
- } else {
- $this->setRecurType(self::RECUR_YEARLY_DATE);
- }
-@@ -1163,13 +1232,19 @@
- break;
-
- case self::RECUR_MONTHLY_WEEKDAY:
-- $nth_weekday = (int)($this->start->mday / 7);
-- if (($this->start->mday % 7) > 0) {
-- $nth_weekday++;
-+ if (isset($this->recurNthDay)) {
-+ $nth_weekday = $this->recurNthDay;
-+ $day_of_week = log($this->recurData, 2);
-+ } else {
-+ $day_of_week = $this->start->dayOfWeek();
-+ $nth_weekday = (int)($this->start->mday / 7);
-+ if (($this->start->mday % 7) > 0) {
-+ $nth_weekday++;
-+ }
- }
- $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA');
- $rrule = 'FREQ=MONTHLY;INTERVAL=' . $this->recurInterval
-- . ';BYDAY=' . $nth_weekday . $vcaldays[$this->start->dayOfWeek()];
-+ . ';BYDAY=' . $nth_weekday . $vcaldays[$day_of_week];
- break;
-
- case self::RECUR_YEARLY_DATE:
-@@ -1182,15 +1257,22 @@
- break;
-
- case self::RECUR_YEARLY_WEEKDAY:
-- $nth_weekday = (int)($this->start->mday / 7);
-- if (($this->start->mday % 7) > 0) {
-- $nth_weekday++;
-- }
-+ if (isset($this->recurNthDay)) {
-+ $nth_weekday = $this->recurNthDay;
-+ $day_of_week = log($this->recurData, 2);
-+ } else {
-+ $day_of_week = $this->start->dayOfWeek();
-+ $nth_weekday = (int)($this->start->mday / 7);
-+ if (($this->start->mday % 7) > 0) {
-+ $nth_weekday++;
-+ }
-+ }
-+ $months = !empty($this->recurMonths) ? join(',', $this->recurMonths) : $this->start->month;
- $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA');
- $rrule = 'FREQ=YEARLY;INTERVAL=' . $this->recurInterval
- . ';BYDAY='
- . $nth_weekday
-- . $vcaldays[$this->start->dayOfWeek()]
-+ . $vcaldays[$day_of_week]
- . ';BYMONTH=' . $this->start->month;
- break;
- }
-@@ -1223,6 +1305,21 @@
-
- $this->setRecurInterval((int)$hash['interval']);
-
-+ $month2number = array(
-+ 'january' => 1,
-+ 'february' => 2,
-+ 'march' => 3,
-+ 'april' => 4,
-+ 'may' => 5,
-+ 'june' => 6,
-+ 'july' => 7,
-+ 'august' => 8,
-+ 'september' => 9,
-+ 'october' => 10,
-+ 'november' => 11,
-+ 'december' => 12,
-+ );
-+
- $parse_day = false;
- $set_daymask = false;
- $update_month = false;
-@@ -1255,11 +1352,9 @@
-
- case 'weekday':
- $this->setRecurType(self::RECUR_MONTHLY_WEEKDAY);
-- $nth_weekday = (int)$hash['daynumber'];
-- $hash['daynumber'] = 1;
-+ $this->setRecurNthWeekday($hash['daynumber']);
- $parse_day = true;
-- $update_daynumber = true;
-- $update_weekday = true;
-+ $set_daymask = true;
- break;
- }
- break;
-@@ -1297,12 +1392,13 @@
- }
-
- $this->setRecurType(self::RECUR_YEARLY_WEEKDAY);
-- $nth_weekday = (int)$hash['daynumber'];
-- $hash['daynumber'] = 1;
-+ $this->setRecurNthWeekday($hash['daynumber']);
- $parse_day = true;
-- $update_month = true;
-- $update_daynumber = true;
-- $update_weekday = true;
-+ $set_daymask = true;
-+
-+ if ($hash['month'] && isset($month2number[$hash['month']])) {
-+ $this->setRecurByMonth($month2number[$hash['month']]);
-+ }
- break;
- }
- }
-@@ -1368,21 +1464,6 @@
-
- if ($update_month || $update_daynumber || $update_weekday) {
- if ($update_month) {
-- $month2number = array(
-- 'january' => 1,
-- 'february' => 2,
-- 'march' => 3,
-- 'april' => 4,
-- 'may' => 5,
-- 'june' => 6,
-- 'july' => 7,
-- 'august' => 8,
-- 'september' => 9,
-- 'october' => 10,
-- 'november' => 11,
-- 'december' => 12,
-- );
--
- if (isset($month2number[$hash['month']])) {
- $this->start->month = $month2number[$hash['month']];
- }
-@@ -1398,7 +1479,7 @@
- }
-
- if ($update_weekday) {
-- $this->start->setNthWeekday($last_found_day, $nth_weekday);
-+ $this->setNthWeekday($nth_weekday);
- }
- }
-
diff --git a/plugins/libkolab/bin/Date_last_weekday.diff b/plugins/libkolab/bin/Date_last_weekday.diff
deleted file mode 100644
index d2603609..00000000
--- a/plugins/libkolab/bin/Date_last_weekday.diff
+++ /dev/null
@@ -1,37 +0,0 @@
---- Date.php.orig 2012-07-10 19:14:26.000000000 +0200
-+++ Date.php 2012-07-10 19:16:22.000000000 +0200
-@@ -627,16 +627,25 @@
- return;
- }
-
-- $this->_mday = 1;
-- $first = $this->dayOfWeek();
-- if ($weekday < $first) {
-- $this->_mday = 8 + $weekday - $first;
-- } else {
-- $this->_mday = $weekday - $first + 1;
-+ if ($nth < 0) { // last $weekday of month
-+ $this->_mday = $lastday = Horde_Date_Utils::daysInMonth($this->_month, $this->_year);
-+ $last = $this->dayOfWeek();
-+ $this->_mday += ($weekday - $last);
-+ if ($this->_mday > $lastday)
-+ $this->_mday -= 7;
-+ }
-+ else {
-+ $this->_mday = 1;
-+ $first = $this->dayOfWeek();
-+ if ($weekday < $first) {
-+ $this->_mday = 8 + $weekday - $first;
-+ } else {
-+ $this->_mday = $weekday - $first + 1;
-+ }
-+ $diff = 7 * $nth - 7;
-+ $this->_mday += $diff;
-+ $this->_correct(self::MASK_DAY, $diff < 0);
- }
-- $diff = 7 * $nth - 7;
-- $this->_mday += $diff;
-- $this->_correct(self::MASK_DAY, $diff < 0);
- }
-
- /**
diff --git a/plugins/libkolab/bin/get_horde_date.sh b/plugins/libkolab/bin/get_horde_date.sh
deleted file mode 100755
index b8e663d4..00000000
--- a/plugins/libkolab/bin/get_horde_date.sh
+++ /dev/null
@@ -1,64 +0,0 @@
-#!/bin/sh
-
-# Copy Horde_Date_Recurrence classes and dependencies to the given target directory.
-# This will create a standalone copy of the classes requried for date recurrence computation.
-
-SRCDIR=$1
-DESTDIR=$2
-BINDIR=`dirname $0`
-
-if [ ! -d "$SRCDIR" -o ! -d "$DESTDIR" ]; then
- echo "Usage: get_horde_date.sh SRCDIR DESTDIR"
- echo "Please enter valid source and destination directories for the Horde libs"
- exit 1
-fi
-
-
-# concat Date.php and Date/Utils.php
-HORDE_DATE="$DESTDIR/Horde_Date.php"
-
-echo "<?php
-
-/**
- * This is a concatenated copy of the following files:
- * Horde/Date.php, Horde/Date/Utils.php
- * Pull the latest version of these files from the PEAR channel of the Horde
- * project at http://pear.horde.org by installing the Horde_Date package.
- */
-" > $HORDE_DATE
-
-patch $SRCDIR/Date.php $BINDIR/Date_last_weekday.diff --output=$HORDE_DATE.patched
-sed 's/<?php//; s/?>//' $HORDE_DATE.patched >> $HORDE_DATE
-sed 's/<?php//; s/?>//' $SRCDIR/Date/Utils.php >> $HORDE_DATE
-
-# copy and patch Date/Recurrence.php
-HORDE_DATE_RECURRENCE="$DESTDIR/Horde_Date_Recurrence.php"
-
-echo "<?php
-
-/**
- * This is a modified copy of Horde/Date/Recurrence.php
- * Pull the latest version of this file from the PEAR channel of the Horde
- * project at http://pear.horde.org by installing the Horde_Date package.
- */
-
-if (!class_exists('Horde_Date'))
- require_once(dirname(__FILE__) . '/Horde_Date.php');
-
-// minimal required implementation of Horde_Date_Translation to avoid a huge dependency nightmare
-class Horde_Date_Translation
-{
- function t(\$arg) { return \$arg; }
- function ngettext(\$sing, \$plur, \$num) { return (\$num > 1 ? \$plur : \$sing); }
-}
-" > $HORDE_DATE_RECURRENCE
-
-patch $SRCDIR/Date/Recurrence.php $BINDIR/Date_Recurrence_weekday.diff --output=$HORDE_DATE_RECURRENCE.patched
-sed 's/<?php//; s/?>//' $HORDE_DATE_RECURRENCE.patched >> $HORDE_DATE_RECURRENCE
-
-# remove dependency to Horde_String
-sed -i '' "s/Horde_String::/strto/" $HORDE_DATE_RECURRENCE
-
-rm $DESTDIR/Horde_Date*.patched
-
-
diff --git a/plugins/libkolab/lib/Horde_Date.php b/plugins/libkolab/lib/Horde_Date.php
deleted file mode 100644
index 9197f846..00000000
--- a/plugins/libkolab/lib/Horde_Date.php
+++ /dev/null
@@ -1,1304 +0,0 @@
-<?php
-
-/**
- * This is a concatenated copy of the following files:
- * Horde/Date/Utils.php, Horde/Date/Recurrence.php
- * Pull the latest version of these files from the PEAR channel of the Horde
- * project at http://pear.horde.org by installing the Horde_Date package.
- */
-
-
-/**
- * Horde Date wrapper/logic class, including some calculation
- * functions.
- *
- * @category Horde
- * @package Date
- *
- * @TODO in format():
- * http://php.net/intldateformatter
- *
- * @TODO on timezones:
- * http://trac.agavi.org/ticket/1008
- * http://trac.agavi.org/changeset/3659
- *
- * @TODO on switching to PHP::DateTime:
- * The only thing ever stored in the database *IS* Unix timestamps. Doing
- * anything other than that is unmanageable, yet some frameworks use 'server
- * based' times in their systems, simply because they do not bother with
- * daylight saving and only 'serve' one timezone!
- *
- * The second you have to manage 'real' time across timezones then daylight
- * saving becomes essential, BUT only on the display side! Since the browser
- * only provides a time offset, this is useless and to be honest should simply
- * be ignored ( until it is upgraded to provide the correct information ;)
- * ). So we need a 'display' function that takes a simple numeric epoch, and a
- * separate timezone id into which the epoch is to be 'converted'. My W3C
- * mapping works simply because ADOdb then converts that to it's own simple
- * offset abbreviation - in my case GMT or BST. As long as DateTime passes the
- * full 64 bit number the date range from 100AD is also preserved ( and
- * further back if 2 digit years are disabled ). If I want to display the
- * 'real' timezone with this 'time' then I just add it in place of ADOdb's
- * 'timezone'. I am tempted to simply adjust the ADOdb class to take a
- * timezone in place of the simple GMT switch it currently uses.
- *
- * The return path is just the reverse and simply needs to take the client
- * display offset off prior to storage of the UTC epoch. SO we use
- * DateTimeZone to get an offset value for the clients timezone and simply add
- * or subtract this from a timezone agnostic display on the client end when
- * entering new times.
- *
- *
- * It's not really feasible to store dates in specific timezone, as most
- * national/local timezones support DST - and that is a pain to support, as
- * eg. sorting breaks when some timestamps get repeated. That's why it's
- * usually better to store datetimes as either UTC datetime or plain unix
- * timestamp. I usually go with the former - using database datetime type.
- */
-
-/**
- * @category Horde
- * @package Date
- */
-class Horde_Date
-{
- const DATE_SUNDAY = 0;
- const DATE_MONDAY = 1;
- const DATE_TUESDAY = 2;
- const DATE_WEDNESDAY = 3;
- const DATE_THURSDAY = 4;
- const DATE_FRIDAY = 5;
- const DATE_SATURDAY = 6;
-
- const MASK_SUNDAY = 1;
- const MASK_MONDAY = 2;
- const MASK_TUESDAY = 4;
- const MASK_WEDNESDAY = 8;
- const MASK_THURSDAY = 16;
- const MASK_FRIDAY = 32;
- const MASK_SATURDAY = 64;
- const MASK_WEEKDAYS = 62;
- const MASK_WEEKEND = 65;
- const MASK_ALLDAYS = 127;
-
- const MASK_SECOND = 1;
- const MASK_MINUTE = 2;
- const MASK_HOUR = 4;
- const MASK_DAY = 8;
- const MASK_MONTH = 16;
- const MASK_YEAR = 32;
- const MASK_ALLPARTS = 63;
-
- const DATE_DEFAULT = 'Y-m-d H:i:s';
- const DATE_JSON = 'Y-m-d\TH:i:s';
-
- /**
- * Year
- *
- * @var integer
- */
- protected $_year;
-
- /**
- * Month
- *
- * @var integer
- */
- protected $_month;
-
- /**
- * Day
- *
- * @var integer
- */
- protected $_mday;
-
- /**
- * Hour
- *
- * @var integer
- */
- protected $_hour = 0;
-
- /**
- * Minute
- *
- * @var integer
- */
- protected $_min = 0;
-
- /**
- * Second
- *
- * @var integer
- */
- protected $_sec = 0;
-
- /**
- * String representation of the date's timezone.
- *
- * @var string
- */
- protected $_timezone;
-
- /**
- * Default format for __toString()
- *
- * @var string
- */
- protected $_defaultFormat = self::DATE_DEFAULT;
-
- /**
- * Default specs that are always supported.
- * @var string
- */
- protected static $_defaultSpecs = '%CdDeHImMnRStTyY';
-
- /**
- * Internally supported strftime() specifiers.
- * @var string
- */
- protected static $_supportedSpecs = '';
-
- /**
- * Map of required correction masks.
- *
- * @see __set()
- *
- * @var array
- */
- protected static $_corrections = array(
- 'year' => self::MASK_YEAR,
- 'month' => self::MASK_MONTH,
- 'mday' => self::MASK_DAY,
- 'hour' => self::MASK_HOUR,
- 'min' => self::MASK_MINUTE,
- 'sec' => self::MASK_SECOND,
- );
-
- protected $_formatCache = array();
-
- /**
- * Builds a new date object. If $date contains date parts, use them to
- * initialize the object.
- *
- * Recognized formats:
- * - arrays with keys 'year', 'month', 'mday', 'day'
- * 'hour', 'min', 'minute', 'sec'
- * - objects with properties 'year', 'month', 'mday', 'hour', 'min', 'sec'
- * - yyyy-mm-dd hh:mm:ss
- * - yyyymmddhhmmss
- * - yyyymmddThhmmssZ
- * - yyyymmdd (might conflict with unix timestamps between 31 Oct 1966 and
- * 03 Mar 1973)
- * - unix timestamps
- * - anything parsed by strtotime()/DateTime.
- *
- * @throws Horde_Date_Exception
- */
- public function __construct($date = null, $timezone = null)
- {
- if (!self::$_supportedSpecs) {
- self::$_supportedSpecs = self::$_defaultSpecs;
- if (function_exists('nl_langinfo')) {
- self::$_supportedSpecs .= 'bBpxX';
- }
- }
-
- if (func_num_args() > 2) {
- // Handle args in order: year month day hour min sec tz
- $this->_initializeFromArgs(func_get_args());
- return;
- }
-
- $this->_initializeTimezone($timezone);
-
- if (is_null($date)) {
- return;
- }
-
- if (is_string($date)) {
- $date = trim($date, '"');
- }
-
- if (is_object($date)) {
- $this->_initializeFromObject($date);
- } elseif (is_array($date)) {
- $this->_initializeFromArray($date);
- } elseif (preg_match('/^(\d{4})-?(\d{2})-?(\d{2})T? ?(\d{2}):?(\d{2}):?(\d{2})(?:\.\d+)?(Z?)$/', $date, $parts)) {
- $this->_year = (int)$parts[1];
- $this->_month = (int)$parts[2];
- $this->_mday = (int)$parts[3];
- $this->_hour = (int)$parts[4];
- $this->_min = (int)$parts[5];
- $this->_sec = (int)$parts[6];
- if ($parts[7]) {
- $this->_initializeTimezone('UTC');
- }
- } elseif (preg_match('/^(\d{4})-?(\d{2})-?(\d{2})$/', $date, $parts) &&
- $parts[2] > 0 && $parts[2] <= 12 &&
- $parts[3] > 0 && $parts[3] <= 31) {
- $this->_year = (int)$parts[1];
- $this->_month = (int)$parts[2];
- $this->_mday = (int)$parts[3];
- $this->_hour = $this->_min = $this->_sec = 0;
- } elseif ((string)(int)$date == $date) {
- // Try as a timestamp.
- $parts = @getdate($date);
- if ($parts) {
- $this->_year = $parts['year'];
- $this->_month = $parts['mon'];
- $this->_mday = $parts['mday'];
- $this->_hour = $parts['hours'];
- $this->_min = $parts['minutes'];
- $this->_sec = $parts['seconds'];
- }
- } else {
- // Use date_create() so we can catch errors with PHP 5.2. Use
- // "new DateTime() once we require 5.3.
- $parsed = date_create($date);
- if (!$parsed) {
- throw new Horde_Date_Exception(sprintf(Horde_Date_Translation::t("Failed to parse time string (%s)"), $date));
- }
- $parsed->setTimezone(new DateTimeZone(date_default_timezone_get()));
- $this->_year = (int)$parsed->format('Y');
- $this->_month = (int)$parsed->format('m');
- $this->_mday = (int)$parsed->format('d');
- $this->_hour = (int)$parsed->format('H');
- $this->_min = (int)$parsed->format('i');
- $this->_sec = (int)$parsed->format('s');
- $this->_initializeTimezone(date_default_timezone_get());
- }
- }
-
- /**
- * Returns a simple string representation of the date object
- *
- * @return string This object converted to a string.
- */
- public function __toString()
- {
- try {
- return $this->format($this->_defaultFormat);
- } catch (Exception $e) {
- return '';
- }
- }
-
- /**
- * Returns a DateTime object representing this object.
- *
- * @return DateTime
- */
- public function toDateTime()
- {
- $date = new DateTime(null, new DateTimeZone($this->_timezone));
- $date->setDate($this->_year, $this->_month, $this->_mday);
- $date->setTime($this->_hour, $this->_min, $this->_sec);
- return $date;
- }
-
- /**
- * Converts a date in the proleptic Gregorian calendar to the no of days
- * since 24th November, 4714 B.C.
- *
- * Returns the no of days since Monday, 24th November, 4714 B.C. in the
- * proleptic Gregorian calendar (which is 24th November, -4713 using
- * 'Astronomical' year numbering, and 1st January, 4713 B.C. in the
- * proleptic Julian calendar). This is also the first day of the 'Julian
- * Period' proposed by Joseph Scaliger in 1583, and the number of days
- * since this date is known as the 'Julian Day'. (It is not directly
- * to do with the Julian calendar, although this is where the name
- * is derived from.)
- *
- * The algorithm is valid for all years (positive and negative), and
- * also for years preceding 4714 B.C.
- *
- * Algorithm is from PEAR::Date_Calc
- *
- * @author Monte Ohrt <monte@ispi.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Daniel Convissor <danielc@php.net>
- * @author C.A. Woodcock <c01234@netcomuk.co.uk>
- *
- * @return integer The number of days since 24th November, 4714 B.C.
- */
- public function toDays()
- {
- if (function_exists('GregorianToJD')) {
- return gregoriantojd($this->_month, $this->_mday, $this->_year);
- }
-
- $day = $this->_mday;
- $month = $this->_month;
- $year = $this->_year;
-
- if ($month > 2) {
- // March = 0, April = 1, ..., December = 9,
- // January = 10, February = 11
- $month -= 3;
- } else {
- $month += 9;
- --$year;
- }
-
- $hb_negativeyear = $year < 0;
- $century = intval($year / 100);
- $year = $year % 100;
-
- if ($hb_negativeyear) {
- // Subtract 1 because year 0 is a leap year;
- // And N.B. that we must treat the leap years as occurring
- // one year earlier than they do, because for the purposes
- // of calculation, the year starts on 1st March:
- //
- return intval((14609700 * $century + ($year == 0 ? 1 : 0)) / 400) +
- intval((1461 * $year + 1) / 4) +
- intval((153 * $month + 2) / 5) +
- $day + 1721118;
- } else {
- return intval(146097 * $century / 4) +
- intval(1461 * $year / 4) +
- intval((153 * $month + 2) / 5) +
- $day + 1721119;
- }
- }
-
- /**
- * Converts number of days since 24th November, 4714 B.C. (in the proleptic
- * Gregorian calendar, which is year -4713 using 'Astronomical' year
- * numbering) to Gregorian calendar date.
- *
- * Returned date belongs to the proleptic Gregorian calendar, using
- * 'Astronomical' year numbering.
- *
- * The algorithm is valid for all years (positive and negative), and
- * also for years preceding 4714 B.C. (i.e. for negative 'Julian Days'),
- * and so the only limitation is platform-dependent (for 32-bit systems
- * the maximum year would be something like about 1,465,190 A.D.).
- *
- * N.B. Monday, 24th November, 4714 B.C. is Julian Day '0'.
- *
- * Algorithm is from PEAR::Date_Calc
- *
- * @author Monte Ohrt <monte@ispi.net>
- * @author Pierre-Alain Joye <pajoye@php.net>
- * @author Daniel Convissor <danielc@php.net>
- * @author C.A. Woodcock <c01234@netcomuk.co.uk>
- *
- * @param int $days the number of days since 24th November, 4714 B.C.
- * @param string $format the string indicating how to format the output
- *
- * @return Horde_Date A Horde_Date object representing the date.
- */
- public static function fromDays($days)
- {
- if (function_exists('JDToGregorian')) {
- list($month, $day, $year) = explode('/', JDToGregorian($days));
- } else {
- $days = intval($days);
-
- $days -= 1721119;
- $century = floor((4 * $days - 1) / 146097);
- $days = floor(4 * $days - 1 - 146097 * $century);
- $day = floor($days / 4);
-
- $year = floor((4 * $day + 3) / 1461);
- $day = floor(4 * $day + 3 - 1461 * $year);
- $day = floor(($day + 4) / 4);
-
- $month = floor((5 * $day - 3) / 153);
- $day = floor(5 * $day - 3 - 153 * $month);
- $day = floor(($day + 5) / 5);
-
- $year = $century * 100 + $year;
- if ($month < 10) {
- $month +=3;
- } else {
- $month -=9;
- ++$year;
- }
- }
-
- return new Horde_Date($year, $month, $day);
- }
-
- /**
- * Getter for the date and time properties.
- *
- * @param string $name One of 'year', 'month', 'mday', 'hour', 'min' or
- * 'sec'.
- *
- * @return integer The property value, or null if not set.
- */
- public function __get($name)
- {
- if ($name == 'day') {
- $name = 'mday';
- }
-
- return $this->{'_' . $name};
- }
-
- /**
- * Setter for the date and time properties.
- *
- * @param string $name One of 'year', 'month', 'mday', 'hour', 'min' or
- * 'sec'.
- * @param integer $value The property value.
- */
- public function __set($name, $value)
- {
- if ($name == 'timezone') {
- $this->_initializeTimezone($value);
- return;
- }
- if ($name == 'day') {
- $name = 'mday';
- }
-
- if ($name != 'year' && $name != 'month' && $name != 'mday' &&
- $name != 'hour' && $name != 'min' && $name != 'sec') {
- throw new InvalidArgumentException('Undefined property ' . $name);
- }
-
- $down = $value < $this->{'_' . $name};
- $this->{'_' . $name} = $value;
- $this->_correct(self::$_corrections[$name], $down);
- $this->_formatCache = array();
- }
-
- /**
- * Returns whether a date or time property exists.
- *
- * @param string $name One of 'year', 'month', 'mday', 'hour', 'min' or
- * 'sec'.
- *
- * @return boolen True if the property exists and is set.
- */
- public function __isset($name)
- {
- if ($name == 'day') {
- $name = 'mday';
- }
- return ($name == 'year' || $name == 'month' || $name == 'mday' ||
- $name == 'hour' || $name == 'min' || $name == 'sec') &&
- isset($this->{'_' . $name});
- }
-
- /**
- * Adds a number of seconds or units to this date, returning a new Date
- * object.
- */
- public function add($factor)
- {
- $d = clone($this);
- if (is_array($factor) || is_object($factor)) {
- foreach ($factor as $property => $value) {
- $d->$property += $value;
- }
- } else {
- $d->sec += $factor;
- }
-
- return $d;
- }
-
- /**
- * Subtracts a number of seconds or units from this date, returning a new
- * Horde_Date object.
- */
- public function sub($factor)
- {
- if (is_array($factor)) {
- foreach ($factor as &$value) {
- $value *= -1;
- }
- } else {
- $factor *= -1;
- }
-
- return $this->add($factor);
- }
-
- /**
- * Converts this object to a different timezone.
- *
- * @param string $timezone The new timezone.
- *
- * @return Horde_Date This object.
- */
- public function setTimezone($timezone)
- {
- $date = $this->toDateTime();
- $date->setTimezone(new DateTimeZone($timezone));
- $this->_timezone = $timezone;
- $this->_year = (int)$date->format('Y');
- $this->_month = (int)$date->format('m');
- $this->_mday = (int)$date->format('d');
- $this->_hour = (int)$date->format('H');
- $this->_min = (int)$date->format('i');
- $this->_sec = (int)$date->format('s');
- $this->_formatCache = array();
- return $this;
- }
-
- /**
- * Sets the default date format used in __toString()
- *
- * @param string $format
- */
- public function setDefaultFormat($format)
- {
- $this->_defaultFormat = $format;
- }
-
- /**
- * Returns the day of the week (0 = Sunday, 6 = Saturday) of this date.
- *
- * @return integer The day of the week.
- */
- public function dayOfWeek()
- {
- if ($this->_month > 2) {
- $month = $this->_month - 2;
- $year = $this->_year;
- } else {
- $month = $this->_month + 10;
- $year = $this->_year - 1;
- }
-
- $day = (floor((13 * $month - 1) / 5) +
- $this->_mday + ($year % 100) +
- floor(($year % 100) / 4) +
- floor(($year / 100) / 4) - 2 *
- floor($year / 100) + 77);
-
- return (int)($day - 7 * floor($day / 7));
- }
-
- /**
- * Returns the day number of the year (1 to 365/366).
- *
- * @return integer The day of the year.
- */
- public function dayOfYear()
- {
- return $this->format('z') + 1;
- }
-
- /**
- * Returns the week of the month.
- *
- * @return integer The week number.
- */
- public function weekOfMonth()
- {
- return ceil($this->_mday / 7);
- }
-
- /**
- * Returns the week of the year, first Monday is first day of first week.
- *
- * @return integer The week number.
- */
- public function weekOfYear()
- {
- return $this->format('W');
- }
-
- /**
- * Returns the number of weeks in the given year (52 or 53).
- *
- * @param integer $year The year to count the number of weeks in.
- *
- * @return integer $numWeeks The number of weeks in $year.
- */
- public static function weeksInYear($year)
- {
- // Find the last Thursday of the year.
- $date = new Horde_Date($year . '-12-31');
- while ($date->dayOfWeek() != self::DATE_THURSDAY) {
- --$date->mday;
- }
- return $date->weekOfYear();
- }
-
- /**
- * Sets the date of this object to the $nth weekday of $weekday.
- *
- * @param integer $weekday The day of the week (0 = Sunday, etc).
- * @param integer $nth The $nth $weekday to set to (defaults to 1).
- */
- public function setNthWeekday($weekday, $nth = 1)
- {
- if ($weekday < self::DATE_SUNDAY || $weekday > self::DATE_SATURDAY) {
- return;
- }
-
- if ($nth < 0) { // last $weekday of month
- $this->_mday = $lastday = Horde_Date_Utils::daysInMonth($this->_month, $this->_year);
- $last = $this->dayOfWeek();
- $this->_mday += ($weekday - $last);
- if ($this->_mday > $lastday)
- $this->_mday -= 7;
- }
- else {
- $this->_mday = 1;
- $first = $this->dayOfWeek();
- if ($weekday < $first) {
- $this->_mday = 8 + $weekday - $first;
- } else {
- $this->_mday = $weekday - $first + 1;
- }
- $diff = 7 * $nth - 7;
- $this->_mday += $diff;
- $this->_correct(self::MASK_DAY, $diff < 0);
- }
- }
-
- /**
- * Is the date currently represented by this object a valid date?
- *
- * @return boolean Validity, counting leap years, etc.
- */
- public function isValid()
- {
- return ($this->_year >= 0 && $this->_year <= 9999);
- }
-
- /**
- * Compares this date to another date object to see which one is
- * greater (later). Assumes that the dates are in the same
- * timezone.
- *
- * @param mixed $other The date to compare to.
- *
- * @return integer == 0 if they are on the same date
- * >= 1 if $this is greater (later)
- * <= -1 if $other is greater (later)
- */
- public function compareDate($other)
- {
- if (!($other instanceof Horde_Date)) {
- $other = new Horde_Date($other);
- }
-
- if ($this->_year != $other->year) {
- return $this->_year - $other->year;
- }
- if ($this->_month != $other->month) {
- return $this->_month - $other->month;
- }
-
- return $this->_mday - $other->mday;
- }
-
- /**
- * Returns whether this date is after the other.
- *
- * @param mixed $other The date to compare to.
- *
- * @return boolean True if this date is after the other.
- */
- public function after($other)
- {
- return $this->compareDate($other) > 0;
- }
-
- /**
- * Returns whether this date is before the other.
- *
- * @param mixed $other The date to compare to.
- *
- * @return boolean True if this date is before the other.
- */
- public function before($other)
- {
- return $this->compareDate($other) < 0;
- }
-
- /**
- * Returns whether this date is the same like the other.
- *
- * @param mixed $other The date to compare to.
- *
- * @return boolean True if this date is the same like the other.
- */
- public function equals($other)
- {
- return $this->compareDate($other) == 0;
- }
-
- /**
- * Compares this to another date object by time, to see which one
- * is greater (later). Assumes that the dates are in the same
- * timezone.
- *
- * @param mixed $other The date to compare to.
- *
- * @return integer == 0 if they are at the same time
- * >= 1 if $this is greater (later)
- * <= -1 if $other is greater (later)
- */
- public function compareTime($other)
- {
- if (!($other instanceof Horde_Date)) {
- $other = new Horde_Date($other);
- }
-
- if ($this->_hour != $other->hour) {
- return $this->_hour - $other->hour;
- }
- if ($this->_min != $other->min) {
- return $this->_min - $other->min;
- }
-
- return $this->_sec - $other->sec;
- }
-
- /**
- * Compares this to another date object, including times, to see
- * which one is greater (later). Assumes that the dates are in the
- * same timezone.
- *
- * @param mixed $other The date to compare to.
- *
- * @return integer == 0 if they are equal
- * >= 1 if $this is greater (later)
- * <= -1 if $other is greater (later)
- */
- public function compareDateTime($other)
- {
- if (!($other instanceof Horde_Date)) {
- $other = new Horde_Date($other);
- }
-
- if ($diff = $this->compareDate($other)) {
- return $diff;
- }
-
- return $this->compareTime($other);
- }
-
- /**
- * Returns number of days between this date and another.
- *
- * @param Horde_Date $other The other day to diff with.
- *
- * @return integer The absolute number of days between the two dates.
- */
- public function diff($other)
- {
- return abs($this->toDays() - $other->toDays());
- }
-
- /**
- * Returns the time offset for local time zone.
- *
- * @param boolean $colon Place a colon between hours and minutes?
- *
- * @return string Timezone offset as a string in the format +HH:MM.
- */
- public function tzOffset($colon = true)
- {
- return $colon ? $this->format('P') : $this->format('O');
- }
-
- /**
- * Returns the unix timestamp representation of this date.
- *
- * @return integer A unix timestamp.
- */
- public function timestamp()
- {
- if ($this->_year >= 1970 && $this->_year < 2038) {
- return mktime($this->_hour, $this->_min, $this->_sec,
- $this->_month, $this->_mday, $this->_year);
- }
- return $this->format('U');
- }
-
- /**
- * Returns the unix timestamp representation of this date, 12:00am.
- *
- * @return integer A unix timestamp.
- */
- public function datestamp()
- {
- if ($this->_year >= 1970 && $this->_year < 2038) {
- return mktime(0, 0, 0, $this->_month, $this->_mday, $this->_year);
- }
- $date = new DateTime($this->format('Y-m-d'));
- return $date->format('U');
- }
-
- /**
- * Formats date and time to be passed around as a short url parameter.
- *
- * @return string Date and time.
- */
- public function dateString()
- {
- return sprintf('%04d%02d%02d', $this->_year, $this->_month, $this->_mday);
- }
-
- /**
- * Formats date and time to the ISO format used by JSON.
- *
- * @return string Date and time.
- */
- public function toJson()
- {
- return $this->format(self::DATE_JSON);
- }
-
- /**
- * Formats date and time to the RFC 2445 iCalendar DATE-TIME format.
- *
- * @param boolean $floating Whether to return a floating date-time
- * (without time zone information).
- *
- * @return string Date and time.
- */
- public function toiCalendar($floating = false)
- {
- if ($floating) {
- return $this->format('Ymd\THis');
- }
- $dateTime = $this->toDateTime();
- $dateTime->setTimezone(new DateTimeZone('UTC'));
- return $dateTime->format('Ymd\THis\Z');
- }
-
- /**
- * Formats time using the specifiers available in date() or in the DateTime
- * class' format() method.
- *
- * To format in languages other than English, use strftime() instead.
- *
- * @param string $format
- *
- * @return string Formatted time.
- */
- public function format($format)
- {
- if (!isset($this->_formatCache[$format])) {
- $this->_formatCache[$format] = $this->toDateTime()->format($format);
- }
- return $this->_formatCache[$format];
- }
-
- /**
- * Formats date and time using strftime() format.
- *
- * @return string strftime() formatted date and time.
- */
- public function strftime($format)
- {
- if (preg_match('/%[^' . self::$_supportedSpecs . ']/', $format)) {
- return strftime($format, $this->timestamp());
- } else {
- return $this->_strftime($format);
- }
- }
-
- /**
- * Formats date and time using a limited set of the strftime() format.
- *
- * @return string strftime() formatted date and time.
- */
- protected function _strftime($format)
- {
- return preg_replace(
- array('/%b/e',
- '/%B/e',
- '/%C/e',
- '/%d/e',
- '/%D/e',
- '/%e/e',
- '/%H/e',
- '/%I/e',
- '/%m/e',
- '/%M/e',
- '/%n/',
- '/%p/e',
- '/%R/e',
- '/%S/e',
- '/%t/',
- '/%T/e',
- '/%x/e',
- '/%X/e',
- '/%y/e',
- '/%Y/',
- '/%%/'),
- array('$this->_strftime(Horde_Nls::getLangInfo(constant(\'ABMON_\' . (int)$this->_month)))',
- '$this->_strftime(Horde_Nls::getLangInfo(constant(\'MON_\' . (int)$this->_month)))',
- '(int)($this->_year / 100)',
- 'sprintf(\'%02d\', $this->_mday)',
- '$this->_strftime(\'%m/%d/%y\')',
- 'sprintf(\'%2d\', $this->_mday)',
- 'sprintf(\'%02d\', $this->_hour)',
- 'sprintf(\'%02d\', $this->_hour == 0 ? 12 : ($this->_hour > 12 ? $this->_hour - 12 : $this->_hour))',
- 'sprintf(\'%02d\', $this->_month)',
- 'sprintf(\'%02d\', $this->_min)',
- "\n",
- '$this->_strftime(Horde_Nls::getLangInfo($this->_hour < 12 ? AM_STR : PM_STR))',
- '$this->_strftime(\'%H:%M\')',
- 'sprintf(\'%02d\', $this->_sec)',
- "\t",
- '$this->_strftime(\'%H:%M:%S\')',
- '$this->_strftime(Horde_Nls::getLangInfo(D_FMT))',
- '$this->_strftime(Horde_Nls::getLangInfo(T_FMT))',
- 'substr(sprintf(\'%04d\', $this->_year), -2)',
- (int)$this->_year,
- '%'),
- $format);
- }
-
- /**
- * Corrects any over- or underflows in any of the date's members.
- *
- * @param integer $mask We may not want to correct some overflows.
- * @param integer $down Whether to correct the date up or down.
- */
- protected function _correct($mask = self::MASK_ALLPARTS, $down = false)
- {
- if ($mask & self::MASK_SECOND) {
- if ($this->_sec < 0 || $this->_sec > 59) {
- $mask |= self::MASK_MINUTE;
-
- $this->_min += (int)($this->_sec / 60);
- $this->_sec %= 60;
- if ($this->_sec < 0) {
- $this->_min--;
- $this->_sec += 60;
- }
- }
- }
-
- if ($mask & self::MASK_MINUTE) {
- if ($this->_min < 0 || $this->_min > 59) {
- $mask |= self::MASK_HOUR;
-
- $this->_hour += (int)($this->_min / 60);
- $this->_min %= 60;
- if ($this->_min < 0) {
- $this->_hour--;
- $this->_min += 60;
- }
- }
- }
-
- if ($mask & self::MASK_HOUR) {
- if ($this->_hour < 0 || $this->_hour > 23) {
- $mask |= self::MASK_DAY;
-
- $this->_mday += (int)($this->_hour / 24);
- $this->_hour %= 24;
- if ($this->_hour < 0) {
- $this->_mday--;
- $this->_hour += 24;
- }
- }
- }
-
- if ($mask & self::MASK_MONTH) {
- $this->_correctMonth($down);
- /* When correcting the month, always correct the day too. Months
- * have different numbers of days. */
- $mask |= self::MASK_DAY;
- }
-
- if ($mask & self::MASK_DAY) {
- while ($this->_mday > 28 &&
- $this->_mday > Horde_Date_Utils::daysInMonth($this->_month, $this->_year)) {
- if ($down) {
- $this->_mday -= Horde_Date_Utils::daysInMonth($this->_month + 1, $this->_year) - Horde_Date_Utils::daysInMonth($this->_month, $this->_year);
- } else {
- $this->_mday -= Horde_Date_Utils::daysInMonth($this->_month, $this->_year);
- $this->_month++;
- }
- $this->_correctMonth($down);
- }
- while ($this->_mday < 1) {
- --$this->_month;
- $this->_correctMonth($down);
- $this->_mday += Horde_Date_Utils::daysInMonth($this->_month, $this->_year);
- }
- }
- }
-
- /**
- * Corrects the current month.
- *
- * This cannot be done in _correct() because that would also trigger a
- * correction of the day, which would result in an infinite loop.
- *
- * @param integer $down Whether to correct the date up or down.
- */
- protected function _correctMonth($down = false)
- {
- $this->_year += (int)($this->_month / 12);
- $this->_month %= 12;
- if ($this->_month < 1) {
- $this->_year--;
- $this->_month += 12;
- }
- }
-
- /**
- * Handles args in order: year month day hour min sec tz
- */
- protected function _initializeFromArgs($args)
- {
- $tz = (isset($args[6])) ? array_pop($args) : null;
- $this->_initializeTimezone($tz);
-
- $args = array_slice($args, 0, 6);
- $keys = array('year' => 1, 'month' => 1, 'mday' => 1, 'hour' => 0, 'min' => 0, 'sec' => 0);
- $date = array_combine(array_slice(array_keys($keys), 0, count($args)), $args);
- $date = array_merge($keys, $date);
-
- $this->_initializeFromArray($date);
- }
-
- protected function _initializeFromArray($date)
- {
- if (isset($date['year']) && is_string($date['year']) && strlen($date['year']) == 2) {
- if ($date['year'] > 70) {
- $date['year'] += 1900;
- } else {
- $date['year'] += 2000;
- }
- }
-
- foreach ($date as $key => $val) {
- if (in_array($key, array('year', 'month', 'mday', 'hour', 'min', 'sec'))) {
- $this->{'_'. $key} = (int)$val;
- }
- }
-
- // If $date['day'] is present and numeric we may have been passed
- // a Horde_Form_datetime array.
- if (isset($date['day']) &&
- (string)(int)$date['day'] == $date['day']) {
- $this->_mday = (int)$date['day'];
- }
- // 'minute' key also from Horde_Form_datetime
- if (isset($date['minute']) &&
- (string)(int)$date['minute'] == $date['minute']) {
- $this->_min = (int)$date['minute'];
- }
-
- $this->_correct();
- }
-
- protected function _initializeFromObject($date)
- {
- if ($date instanceof DateTime) {
- $this->_year = (int)$date->format('Y');
- $this->_month = (int)$date->format('m');
- $this->_mday = (int)$date->format('d');
- $this->_hour = (int)$date->format('H');
- $this->_min = (int)$date->format('i');
- $this->_sec = (int)$date->format('s');
- $this->_initializeTimezone($date->getTimezone()->getName());
- } else {
- $is_horde_date = $date instanceof Horde_Date;
- foreach (array('year', 'month', 'mday', 'hour', 'min', 'sec') as $key) {
- if ($is_horde_date || isset($date->$key)) {
- $this->{'_' . $key} = (int)$date->$key;
- }
- }
- if (!$is_horde_date) {
- $this->_correct();
- } else {
- $this->_initializeTimezone($date->timezone);
- }
- }
- }
-
- protected function _initializeTimezone($timezone)
- {
- if (empty($timezone)) {
- $timezone = date_default_timezone_get();
- }
- $this->_timezone = $timezone;
- }
-
-}
-
-/**
- * @category Horde
- * @package Date
- */
-
-/**
- * Horde Date wrapper/logic class, including some calculation
- * functions.
- *
- * @category Horde
- * @package Date
- */
-class Horde_Date_Utils
-{
- /**
- * Returns whether a year is a leap year.
- *
- * @param integer $year The year.
- *
- * @return boolean True if the year is a leap year.
- */
- public static function isLeapYear($year)
- {
- if (strlen($year) != 4 || preg_match('/\D/', $year)) {
- return false;
- }
-
- return (($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0);
- }
-
- /**
- * Returns the date of the year that corresponds to the first day of the
- * given week.
- *
- * @param integer $week The week of the year to find the first day of.
- * @param integer $year The year to calculate for.
- *
- * @return Horde_Date The date of the first day of the given week.
- */
- public static function firstDayOfWeek($week, $year)
- {
- return new Horde_Date(sprintf('%04dW%02d', $year, $week));
- }
-
- /**
- * Returns the number of days in the specified month.
- *
- * @param integer $month The month
- * @param integer $year The year.
- *
- * @return integer The number of days in the month.
- */
- public static function daysInMonth($month, $year)
- {
- static $cache = array();
- if (!isset($cache[$year][$month])) {
- $date = new DateTime(sprintf('%04d-%02d-01', $year, $month));
- $cache[$year][$month] = $date->format('t');
- }
- return $cache[$year][$month];
- }
-
- /**
- * Returns a relative, natural language representation of a timestamp
- *
- * @todo Wider range of values ... maybe future time as well?
- * @todo Support minimum resolution parameter.
- *
- * @param mixed $time The time. Any format accepted by Horde_Date.
- * @param string $date_format Format to display date if timestamp is
- * more then 1 day old.
- * @param string $time_format Format to display time if timestamp is 1
- * day old.
- *
- * @return string The relative time (i.e. 2 minutes ago)
- */
- public static function relativeDateTime($time, $date_format = '%x',
- $time_format = '%X')
- {
- $date = new Horde_Date($time);
-
- $delta = time() - $date->timestamp();
- if ($delta < 60) {
- return sprintf(Horde_Date_Translation::ngettext("%d second ago", "%d seconds ago", $delta), $delta);
- }
-
- $delta = round($delta / 60);
- if ($delta < 60) {
- return sprintf(Horde_Date_Translation::ngettext("%d minute ago", "%d minutes ago", $delta), $delta);
- }
-
- $delta = round($delta / 60);
- if ($delta < 24) {
- return sprintf(Horde_Date_Translation::ngettext("%d hour ago", "%d hours ago", $delta), $delta);
- }
-
- if ($delta > 24 && $delta < 48) {
- $date = new Horde_Date($time);
- return sprintf(Horde_Date_Translation::t("yesterday at %s"), $date->strftime($time_format));
- }
-
- $delta = round($delta / 24);
- if ($delta < 7) {
- return sprintf(Horde_Date_Translation::t("%d days ago"), $delta);
- }
-
- if (round($delta / 7) < 5) {
- $delta = round($delta / 7);
- return sprintf(Horde_Date_Translation::ngettext("%d week ago", "%d weeks ago", $delta), $delta);
- }
-
- // Default to the user specified date format.
- return $date->strftime($date_format);
- }
-
- /**
- * Tries to convert strftime() formatters to date() formatters.
- *
- * Unsupported formatters will be removed.
- *
- * @param string $format A strftime() formatting string.
- *
- * @return string A date() formatting string.
- */
- public static function strftime2date($format)
- {
- $replace = array(
- '/%a/' => 'D',
- '/%A/' => 'l',
- '/%d/' => 'd',
- '/%e/' => 'j',
- '/%j/' => 'z',
- '/%u/' => 'N',
- '/%w/' => 'w',
- '/%U/' => '',
- '/%V/' => 'W',
- '/%W/' => '',
- '/%b/' => 'M',
- '/%B/' => 'F',
- '/%h/' => 'M',
- '/%m/' => 'm',
- '/%C/' => '',
- '/%g/' => '',
- '/%G/' => 'o',
- '/%y/' => 'y',
- '/%Y/' => 'Y',
- '/%H/' => 'H',
- '/%I/' => 'h',
- '/%i/' => 'g',
- '/%M/' => 'i',
- '/%p/' => 'A',
- '/%P/' => 'a',
- '/%r/' => 'h:i:s A',
- '/%R/' => 'H:i',
- '/%S/' => 's',
- '/%T/' => 'H:i:s',
- '/%X/e' => 'Horde_Date_Utils::strftime2date(Horde_Nls::getLangInfo(T_FMT))',
- '/%z/' => 'O',
- '/%Z/' => '',
- '/%c/' => '',
- '/%D/' => 'm/d/y',
- '/%F/' => 'Y-m-d',
- '/%s/' => 'U',
- '/%x/e' => 'Horde_Date_Utils::strftime2date(Horde_Nls::getLangInfo(D_FMT))',
- '/%n/' => "\n",
- '/%t/' => "\t",
- '/%%/' => '%'
- );
-
- return preg_replace(array_keys($replace), array_values($replace), $format);
- }
-
-}
diff --git a/plugins/libkolab/lib/Horde_Date_Recurrence.php b/plugins/libkolab/lib/Horde_Date_Recurrence.php
deleted file mode 100644
index 81f0857d..00000000
--- a/plugins/libkolab/lib/Horde_Date_Recurrence.php
+++ /dev/null
@@ -1,1673 +0,0 @@
-<?php
-
-/**
- * This is a modified copy of Horde/Date/Recurrence.php
- * Pull the latest version of this file from the PEAR channel of the Horde
- * project at http://pear.horde.org by installing the Horde_Date package.
- */
-
-if (!class_exists('Horde_Date'))
- require_once(dirname(__FILE__) . '/Horde_Date.php');
-
-// minimal required implementation of Horde_Date_Translation to avoid a huge dependency nightmare
-class Horde_Date_Translation
-{
- function t($arg) { return $arg; }
- function ngettext($sing, $plur, $num) { return ($num > 1 ? $plur : $sing); }
-}
-
-
-/**
- * This file contains the Horde_Date_Recurrence class and according constants.
- *
- * Copyright 2007-2012 Horde LLC (http://www.horde.org/)
- *
- * See the enclosed file COPYING for license information (LGPL). If you
- * did not receive this file, see http://www.horde.org/licenses/lgpl21.
- *
- * @category Horde
- * @package Date
- */
-
-/**
- * The Horde_Date_Recurrence class implements algorithms for calculating
- * recurrences of events, including several recurrence types, intervals,
- * exceptions, and conversion from and to vCalendar and iCalendar recurrence
- * rules.
- *
- * All methods expecting dates as parameters accept all values that the
- * Horde_Date constructor accepts, i.e. a timestamp, another Horde_Date
- * object, an ISO time string or a hash.
- *
- * @author Jan Schneider <jan@horde.org>
- * @category Horde
- * @package Date
- */
-class Horde_Date_Recurrence
-{
- /** No Recurrence **/
- const RECUR_NONE = 0;
-
- /** Recurs daily. */
- const RECUR_DAILY = 1;
-
- /** Recurs weekly. */
- const RECUR_WEEKLY = 2;
-
- /** Recurs monthly on the same date. */
- const RECUR_MONTHLY_DATE = 3;
-
- /** Recurs monthly on the same week day. */
- const RECUR_MONTHLY_WEEKDAY = 4;
-
- /** Recurs yearly on the same date. */
- const RECUR_YEARLY_DATE = 5;
-
- /** Recurs yearly on the same day of the year. */
- const RECUR_YEARLY_DAY = 6;
-
- /** Recurs yearly on the same week day. */
- const RECUR_YEARLY_WEEKDAY = 7;
-
- /**
- * The start time of the event.
- *
- * @var Horde_Date
- */
- public $start;
-
- /**
- * The end date of the recurrence interval.
- *
- * @var Horde_Date
- */
- public $recurEnd = null;
-
- /**
- * The number of recurrences.
- *
- * @var integer
- */
- public $recurCount = null;
-
- /**
- * The type of recurrence this event follows. RECUR_* constant.
- *
- * @var integer
- */
- public $recurType = self::RECUR_NONE;
-
- /**
- * The length of time between recurrences. The time unit depends on the
- * recurrence type.
- *
- * @var integer
- */
- public $recurInterval = 1;
-
- /**
- * Any additional recurrence data.
- *
- * @var integer
- */
- public $recurData = null;
-
- /**
- * BYDAY recurrence number
- *
- * @var integer
- */
- public $recurNthDay = null;
-
- /**
- * BYMONTH recurrence data
- *
- * @var array
- */
- public $recurMonths = array();
-
- /**
- * All the exceptions from recurrence for this event.
- *
- * @var array
- */
- public $exceptions = array();
-
- /**
- * All the dates this recurrence has been marked as completed.
- *
- * @var array
- */
- public $completions = array();
-
- /**
- * Constructor.
- *
- * @param Horde_Date $start Start of the recurring event.
- */
- public function __construct($start)
- {
- $this->start = new Horde_Date($start);
- }
-
- /**
- * Resets the class properties.
- */
- public function reset()
- {
- $this->recurEnd = null;
- $this->recurCount = null;
- $this->recurType = self::RECUR_NONE;
- $this->recurInterval = 1;
- $this->recurData = null;
- $this->exceptions = array();
- $this->completions = array();
- }
-
- /**
- * Checks if this event recurs on a given day of the week.
- *
- * @param integer $dayMask A mask consisting of Horde_Date::MASK_*
- * constants specifying the day(s) to check.
- *
- * @return boolean True if this event recurs on the given day(s).
- */
- public function recurOnDay($dayMask)
- {
- return ($this->recurData & $dayMask);
- }
-
- /**
- * Specifies the days this event recurs on.
- *
- * @param integer $dayMask A mask consisting of Horde_Date::MASK_*
- * constants specifying the day(s) to recur on.
- */
- public function setRecurOnDay($dayMask)
- {
- $this->recurData = $dayMask;
- }
-
- /**
- *
- * @param integer $nthDay The nth weekday of month to repeat events on
- */
- public function setRecurNthWeekday($nth)
- {
- $this->recurNthDay = (int)$nth;
- }
-
- /**
- *
- * @return integer The nth weekday of month to repeat events.
- */
- public function getRecurNthWeekday()
- {
- return isset($this->recurNthDay) ? $this->recurNthDay : ceil($this->start->mday / 7);
- }
-
- /**
- * Specifies the months for yearly (weekday) recurrence
- *
- * @param array $months List of months (integers) this event recurs on.
- */
- function setRecurByMonth($months)
- {
- $this->recurMonths = (array)$months;
- }
-
- /**
- * Returns a list of months this yearly event recurs on
- *
- * @return array List of months (integers) this event recurs on.
- */
- function getRecurByMonth()
- {
- return $this->recurMonths;
- }
-
- /**
- * Returns the days this event recurs on.
- *
- * @return integer A mask consisting of Horde_Date::MASK_* constants
- * specifying the day(s) this event recurs on.
- */
- public function getRecurOnDays()
- {
- return $this->recurData;
- }
-
- /**
- * Returns whether this event has a specific recurrence type.
- *
- * @param integer $recurrence RECUR_* constant of the
- * recurrence type to check for.
- *
- * @return boolean True if the event has the specified recurrence type.
- */
- public function hasRecurType($recurrence)
- {
- return ($recurrence == $this->recurType);
- }
-
- /**
- * Sets a recurrence type for this event.
- *
- * @param integer $recurrence A RECUR_* constant.
- */
- public function setRecurType($recurrence)
- {
- $this->recurType = $recurrence;
- }
-
- /**
- * Returns recurrence type of this event.
- *
- * @return integer A RECUR_* constant.
- */
- public function getRecurType()
- {
- return $this->recurType;
- }
-
- /**
- * Returns a description of this event's recurring type.
- *
- * @return string Human readable recurring type.
- */
- public function getRecurName()
- {
- switch ($this->getRecurType()) {
- case self::RECUR_NONE: return Horde_Date_Translation::t("No recurrence");
- case self::RECUR_DAILY: return Horde_Date_Translation::t("Daily");
- case self::RECUR_WEEKLY: return Horde_Date_Translation::t("Weekly");
- case self::RECUR_MONTHLY_DATE:
- case self::RECUR_MONTHLY_WEEKDAY: return Horde_Date_Translation::t("Monthly");
- case self::RECUR_YEARLY_DATE:
- case self::RECUR_YEARLY_DAY:
- case self::RECUR_YEARLY_WEEKDAY: return Horde_Date_Translation::t("Yearly");
- }
- }
-
- /**
- * Sets the length of time between recurrences of this event.
- *
- * @param integer $interval The time between recurrences.
- */
- public function setRecurInterval($interval)
- {
- if ($interval > 0) {
- $this->recurInterval = $interval;
- }
- }
-
- /**
- * Retrieves the length of time between recurrences of this event.
- *
- * @return integer The number of seconds between recurrences.
- */
- public function getRecurInterval()
- {
- return $this->recurInterval;
- }
-
- /**
- * Sets the number of recurrences of this event.
- *
- * @param integer $count The number of recurrences.
- */
- public function setRecurCount($count)
- {
- if ($count > 0) {
- $this->recurCount = (int)$count;
- // Recurrence counts and end dates are mutually exclusive.
- $this->recurEnd = null;
- } else {
- $this->recurCount = null;
- }
- }
-
- /**
- * Retrieves the number of recurrences of this event.
- *
- * @return integer The number recurrences.
- */
- public function getRecurCount()
- {
- return $this->recurCount;
- }
-
- /**
- * Returns whether this event has a recurrence with a fixed count.
- *
- * @return boolean True if this recurrence has a fixed count.
- */
- public function hasRecurCount()
- {
- return isset($this->recurCount);
- }
-
- /**
- * Sets the start date of the recurrence interval.
- *
- * @param Horde_Date $start The recurrence start.
- */
- public function setRecurStart($start)
- {
- $this->start = clone $start;
- }
-
- /**
- * Retrieves the start date of the recurrence interval.
- *
- * @return Horde_Date The recurrence start.
- */
- public function getRecurStart()
- {
- return $this->start;
- }
-
- /**
- * Sets the end date of the recurrence interval.
- *
- * @param Horde_Date $end The recurrence end.
- */
- public function setRecurEnd($end)
- {
- if (!empty($end)) {
- // Recurrence counts and end dates are mutually exclusive.
- $this->recurCount = null;
- $this->recurEnd = clone $end;
- } else {
- $this->recurEnd = $end;
- }
- }
-
- /**
- * Retrieves the end date of the recurrence interval.
- *
- * @return Horde_Date The recurrence end.
- */
- public function getRecurEnd()
- {
- return $this->recurEnd;
- }
-
- /**
- * Returns whether this event has a recurrence end.
- *
- * @return boolean True if this recurrence ends.
- */
- public function hasRecurEnd()
- {
- return isset($this->recurEnd) && isset($this->recurEnd->year) &&
- $this->recurEnd->year != 9999;
- }
-
- /**
- * Finds the next recurrence of this event that's after $afterDate.
- *
- * @param Horde_Date|string $after Return events after this date.
- *
- * @return Horde_Date|boolean The date of the next recurrence or false
- * if the event does not recur after
- * $afterDate.
- */
- public function nextRecurrence($after)
- {
- if (!($after instanceof Horde_Date)) {
- $after = new Horde_Date($after);
- } else {
- $after = clone($after);
- }
-
- // Make sure $after and $this->start are in the same TZ
- $after->setTimezone($this->start->timezone);
- if ($this->start->compareDateTime($after) >= 0) {
- return clone $this->start;
- }
-
- if ($this->recurInterval == 0) {
- return false;
- }
-
- switch ($this->getRecurType()) {
- case self::RECUR_DAILY:
- $diff = $this->start->diff($after);
- $recur = ceil($diff / $this->recurInterval);
- if ($this->recurCount && $recur >= $this->recurCount) {
- return false;
- }
-
- $recur *= $this->recurInterval;
- $next = $this->start->add(array('day' => $recur));
- if ((!$this->hasRecurEnd() ||
- $next->compareDateTime($this->recurEnd) <= 0) &&
- $next->compareDateTime($after) >= 0) {
- return $next;
- }
- break;
-
- case self::RECUR_WEEKLY:
- if (empty($this->recurData)) {
- return false;
- }
-
- $start_week = Horde_Date_Utils::firstDayOfWeek($this->start->format('W'),
- $this->start->year);
- $start_week->timezone = $this->start->timezone;
- $start_week->hour = $this->start->hour;
- $start_week->min = $this->start->min;
- $start_week->sec = $this->start->sec;
-
- // Make sure we are not at the ISO-8601 first week of year while
- // still in month 12...OR in the ISO-8601 last week of year while
- // in month 1 and adjust the year accordingly.
- $week = $after->format('W');
- if ($week == 1 && $after->month == 12) {
- $theYear = $after->year + 1;
- } elseif ($week >= 52 && $after->month == 1) {
- $theYear = $after->year - 1;
- } else {
- $theYear = $after->year;
- }
-
- $after_week = Horde_Date_Utils::firstDayOfWeek($week, $theYear);
- $after_week->timezone = $this->start->timezone;
- $after_week_end = clone $after_week;
- $after_week_end->mday += 7;
-
- $diff = $start_week->diff($after_week);
- $interval = $this->recurInterval * 7;
- $repeats = floor($diff / $interval);
- if ($diff % $interval < 7) {
- $recur = $diff;
- } else {
- /**
- * If the after_week is not in the first week interval the
- * search needs to skip ahead a complete interval. The way it is
- * calculated here means that an event that occurs every second
- * week on Monday and Wednesday with the event actually starting
- * on Tuesday or Wednesday will only have one incidence in the
- * first week.
- */
- $recur = $interval * ($repeats + 1);
- }
-
- if ($this->hasRecurCount()) {
- $recurrences = 0;
- /**
- * Correct the number of recurrences by the number of events
- * that lay between the start of the start week and the
- * recurrence start.
- */
- $next = clone $start_week;
- while ($next->compareDateTime($this->start) < 0) {
- if ($this->recurOnDay((int)pow(2, $next->dayOfWeek()))) {
- $recurrences--;
- }
- ++$next->mday;
- }
- if ($repeats > 0) {
- $weekdays = $this->recurData;
- $total_recurrences_per_week = 0;
- while ($weekdays > 0) {
- if ($weekdays % 2) {
- $total_recurrences_per_week++;
- }
- $weekdays = ($weekdays - ($weekdays % 2)) / 2;
- }
- $recurrences += $total_recurrences_per_week * $repeats;
- }
- }
-
- $next = clone $start_week;
- $next->mday += $recur;
- while ($next->compareDateTime($after) < 0 &&
- $next->compareDateTime($after_week_end) < 0) {
- if ($this->hasRecurCount()
- && $next->compareDateTime($after) < 0
- && $this->recurOnDay((int)pow(2, $next->dayOfWeek()))) {
- $recurrences++;
- }
- ++$next->mday;
- }
- if ($this->hasRecurCount() &&
- $recurrences >= $this->recurCount) {
- return false;
- }
- if (!$this->hasRecurEnd() ||
- $next->compareDateTime($this->recurEnd) <= 0) {
- if ($next->compareDateTime($after_week_end) >= 0) {
- return $this->nextRecurrence($after_week_end);
- }
- while (!$this->recurOnDay((int)pow(2, $next->dayOfWeek())) &&
- $next->compareDateTime($after_week_end) < 0) {
- ++$next->mday;
- }
- if (!$this->hasRecurEnd() ||
- $next->compareDateTime($this->recurEnd) <= 0) {
- if ($next->compareDateTime($after_week_end) >= 0) {
- return $this->nextRecurrence($after_week_end);
- } else {
- return $next;
- }
- }
- }
- break;
-
- case self::RECUR_MONTHLY_DATE:
- $start = clone $this->start;
- if ($after->compareDateTime($start) < 0) {
- $after = clone $start;
- } else {
- $after = clone $after;
- }
-
- // If we're starting past this month's recurrence of the event,
- // look in the next month on the day the event recurs.
- if ($after->mday > $start->mday) {
- ++$after->month;
- $after->mday = $start->mday;
- }
-
- // Adjust $start to be the first match.
- $offset = ($after->month - $start->month) + ($after->year - $start->year) * 12;
- $offset = floor(($offset + $this->recurInterval - 1) / $this->recurInterval) * $this->recurInterval;
-
- if ($this->recurCount &&
- ($offset / $this->recurInterval) >= $this->recurCount) {
- return false;
- }
- $start->month += $offset;
- $count = $offset / $this->recurInterval;
-
- do {
- if ($this->recurCount &&
- $count++ >= $this->recurCount) {
- return false;
- }
-
- // Bail if we've gone past the end of recurrence.
- if ($this->hasRecurEnd() &&
- $this->recurEnd->compareDateTime($start) < 0) {
- return false;
- }
- if ($start->isValid()) {
- return $start;
- }
-
- // If the interval is 12, and the date isn't valid, then we
- // need to see if February 29th is an option. If not, then the
- // event will _never_ recur, and we need to stop checking to
- // avoid an infinite loop.
- if ($this->recurInterval == 12 && ($start->month != 2 || $start->mday > 29)) {
- return false;
- }
-
- // Add the recurrence interval.
- $start->month += $this->recurInterval;
- } while (true);
-
- break;
-
- case self::RECUR_MONTHLY_WEEKDAY:
- // Start with the start date of the event.
- $estart = clone $this->start;
-
- // What day of the week, and week of the month, do we recur on?
- if (isset($this->recurNthDay)) {
- $nth = $this->recurNthDay;
- $weekday = log($this->recurData, 2);
- } else {
- $nth = ceil($this->start->mday / 7);
- $weekday = $estart->dayOfWeek();
- }
-
- // Adjust $estart to be the first candidate.
- $offset = ($after->month - $estart->month) + ($after->year - $estart->year) * 12;
- $offset = floor(($offset + $this->recurInterval - 1) / $this->recurInterval) * $this->recurInterval;
-
- // Adjust our working date until it's after $after.
- $estart->month += $offset - $this->recurInterval;
-
- $count = $offset / $this->recurInterval;
- do {
- if ($this->recurCount &&
- $count++ >= $this->recurCount) {
- return false;
- }
-
- $estart->month += $this->recurInterval;
-
- $next = clone $estart;
- $next->setNthWeekday($weekday, $nth);
-
- if ($next->compareDateTime($after) < 0) {
- // We haven't made it past $after yet, try again.
- continue;
- }
- if ($this->hasRecurEnd() &&
- $next->compareDateTime($this->recurEnd) > 0) {
- // We've gone past the end of recurrence; we can give up
- // now.
- return false;
- }
-
- // We have a candidate to return.
- break;
- } while (true);
-
- return $next;
-
- case self::RECUR_YEARLY_DATE:
- // Start with the start date of the event.
- $estart = clone $this->start;
- $after = clone $after;
-
- if ($after->month > $estart->month ||
- ($after->month == $estart->month && $after->mday > $estart->mday)) {
- ++$after->year;
- $after->month = $estart->month;
- $after->mday = $estart->mday;
- }
-
- // Seperate case here for February 29th
- if ($estart->month == 2 && $estart->mday == 29) {
- while (!Horde_Date_Utils::isLeapYear($after->year)) {
- ++$after->year;
- }
- }
-
- // Adjust $estart to be the first candidate.
- $offset = $after->year - $estart->year;
- if ($offset > 0) {
- $offset = floor(($offset + $this->recurInterval - 1) / $this->recurInterval) * $this->recurInterval;
- $estart->year += $offset;
- }
-
- // We've gone past the end of recurrence; give up.
- if ($this->recurCount &&
- $offset >= $this->recurCount) {
- return false;
- }
- if ($this->hasRecurEnd() &&
- $this->recurEnd->compareDateTime($estart) < 0) {
- return false;
- }
-
- return $estart;
-
- case self::RECUR_YEARLY_DAY:
- // Check count first.
- $dayofyear = $this->start->dayOfYear();
- $count = ($after->year - $this->start->year) / $this->recurInterval + 1;
- if ($this->recurCount &&
- ($count > $this->recurCount ||
- ($count == $this->recurCount &&
- $after->dayOfYear() > $dayofyear))) {
- return false;
- }
-
- // Start with a rough interval.
- $estart = clone $this->start;
- $estart->year += floor($count - 1) * $this->recurInterval;
-
- // Now add the difference to the required day of year.
- $estart->mday += $dayofyear - $estart->dayOfYear();
-
- // Add an interval if the estimation was wrong.
- if ($estart->compareDate($after) < 0) {
- $estart->year += $this->recurInterval;
- $estart->mday += $dayofyear - $estart->dayOfYear();
- }
-
- // We've gone past the end of recurrence; give up.
- if ($this->hasRecurEnd() &&
- $this->recurEnd->compareDateTime($estart) < 0) {
- return false;
- }
-
- return $estart;
-
- case self::RECUR_YEARLY_WEEKDAY:
- // Start with the start date of the event.
- $estart = clone $this->start;
-
- // What day of the week, and week of the month, do we recur on?
- if (isset($this->recurNthDay)) {
- $nth = $this->recurNthDay;
- $weekday = log($this->recurData, 2);
- } else {
- $nth = ceil($this->start->mday / 7);
- $weekday = $estart->dayOfWeek();
- }
-
- // Adjust $estart to be the first candidate.
- $offset = floor(($after->year - $estart->year + $this->recurInterval - 1) / $this->recurInterval) * $this->recurInterval;
-
- // Adjust our working date until it's after $after.
- $estart->year += $offset - $this->recurInterval;
-
- $count = $offset / $this->recurInterval;
- do {
- if ($this->recurCount &&
- $count++ >= $this->recurCount) {
- return false;
- }
-
- $estart->year += $this->recurInterval;
-
- $next = clone $estart;
- $next->setNthWeekday($weekday, $nth);
-
- if ($next->compareDateTime($after) < 0) {
- // We haven't made it past $after yet, try again.
- continue;
- }
- if ($this->hasRecurEnd() &&
- $next->compareDateTime($this->recurEnd) > 0) {
- // We've gone past the end of recurrence; we can give up
- // now.
- return false;
- }
-
- // We have a candidate to return.
- break;
- } while (true);
-
- return $next;
- }
-
- // We didn't find anything, the recurType was bad, or something else
- // went wrong - return false.
- return false;
- }
-
- /**
- * Returns whether this event has any date that matches the recurrence
- * rules and is not an exception.
- *
- * @return boolean True if an active recurrence exists.
- */
- public function hasActiveRecurrence()
- {
- if (!$this->hasRecurEnd()) {
- return true;
- }
-
- $next = $this->nextRecurrence(new Horde_Date($this->start));
- while (is_object($next)) {
- if (!$this->hasException($next->year, $next->month, $next->mday) &&
- !$this->hasCompletion($next->year, $next->month, $next->mday)) {
- return true;
- }
-
- $next = $this->nextRecurrence($next->add(array('day' => 1)));
- }
-
- return false;
- }
-
- /**
- * Returns the next active recurrence.
- *
- * @param Horde_Date $afterDate Return events after this date.
- *
- * @return Horde_Date|boolean The date of the next active
- * recurrence or false if the event
- * has no active recurrence after
- * $afterDate.
- */
- public function nextActiveRecurrence($afterDate)
- {
- $next = $this->nextRecurrence($afterDate);
- while (is_object($next)) {
- if (!$this->hasException($next->year, $next->month, $next->mday) &&
- !$this->hasCompletion($next->year, $next->month, $next->mday)) {
- return $next;
- }
- $next->mday++;
- $next = $this->nextRecurrence($next);
- }
-
- return false;
- }
-
- /**
- * Adds an exception to a recurring event.
- *
- * @param integer $year The year of the execption.
- * @param integer $month The month of the execption.
- * @param integer $mday The day of the month of the exception.
- */
- public function addException($year, $month, $mday)
- {
- $this->exceptions[] = sprintf('%04d%02d%02d', $year, $month, $mday);
- }
-
- /**
- * Deletes an exception from a recurring event.
- *
- * @param integer $year The year of the execption.
- * @param integer $month The month of the execption.
- * @param integer $mday The day of the month of the exception.
- */
- public function deleteException($year, $month, $mday)
- {
- $key = array_search(sprintf('%04d%02d%02d', $year, $month, $mday), $this->exceptions);
- if ($key !== false) {
- unset($this->exceptions[$key]);
- }
- }
-
- /**
- * Checks if an exception exists for a given reccurence of an event.
- *
- * @param integer $year The year of the reucrance.
- * @param integer $month The month of the reucrance.
- * @param integer $mday The day of the month of the reucrance.
- *
- * @return boolean True if an exception exists for the given date.
- */
- public function hasException($year, $month, $mday)
- {
- return in_array(sprintf('%04d%02d%02d', $year, $month, $mday),
- $this->getExceptions());
- }
-
- /**
- * Retrieves all the exceptions for this event.
- *
- * @return array Array containing the dates of all the exceptions in
- * YYYYMMDD form.
- */
- public function getExceptions()
- {
- return $this->exceptions;
- }
-
- /**
- * Adds a completion to a recurring event.
- *
- * @param integer $year The year of the execption.
- * @param integer $month The month of the execption.
- * @param integer $mday The day of the month of the completion.
- */
- public function addCompletion($year, $month, $mday)
- {
- $this->completions[] = sprintf('%04d%02d%02d', $year, $month, $mday);
- }
-
- /**
- * Deletes a completion from a recurring event.
- *
- * @param integer $year The year of the execption.
- * @param integer $month The month of the execption.
- * @param integer $mday The day of the month of the completion.
- */
- public function deleteCompletion($year, $month, $mday)
- {
- $key = array_search(sprintf('%04d%02d%02d', $year, $month, $mday), $this->completions);
- if ($key !== false) {
- unset($this->completions[$key]);
- }
- }
-
- /**
- * Checks if a completion exists for a given reccurence of an event.
- *
- * @param integer $year The year of the reucrance.
- * @param integer $month The month of the recurrance.
- * @param integer $mday The day of the month of the recurrance.
- *
- * @return boolean True if a completion exists for the given date.
- */
- public function hasCompletion($year, $month, $mday)
- {
- return in_array(sprintf('%04d%02d%02d', $year, $month, $mday),
- $this->getCompletions());
- }
-
- /**
- * Retrieves all the completions for this event.
- *
- * @return array Array containing the dates of all the completions in
- * YYYYMMDD form.
- */
- public function getCompletions()
- {
- return $this->completions;
- }
-
- /**
- * Parses a vCalendar 1.0 recurrence rule.
- *
- * @link http://www.imc.org/pdi/vcal-10.txt
- * @link http://www.shuchow.com/vCalAddendum.html
- *
- * @param string $rrule A vCalendar 1.0 conform RRULE value.
- */
- public function fromRRule10($rrule)
- {
- $this->reset();
-
- if (!$rrule) {
- return;
- }
-
- if (!preg_match('/([A-Z]+)(\d+)?(.*)/', $rrule, $matches)) {
- // No recurrence data - event does not recur.
- $this->setRecurType(self::RECUR_NONE);
- }
-
- // Always default the recurInterval to 1.
- $this->setRecurInterval(!empty($matches[2]) ? $matches[2] : 1);
-
- $remainder = trim($matches[3]);
-
- switch ($matches[1]) {
- case 'D':
- $this->setRecurType(self::RECUR_DAILY);
- break;
-
- case 'W':
- $this->setRecurType(self::RECUR_WEEKLY);
- if (!empty($remainder)) {
- $mask = 0;
- while (preg_match('/^ ?[A-Z]{2} ?/', $remainder, $matches)) {
- $day = trim($matches[0]);
- $remainder = substr($remainder, strlen($matches[0]));
- $mask |= $maskdays[$day];
- }
- $this->setRecurOnDay($mask);
- } else {
- // Recur on the day of the week of the original recurrence.
- $maskdays = array(
- Horde_Date::DATE_SUNDAY => Horde_Date::MASK_SUNDAY,
- Horde_Date::DATE_MONDAY => Horde_Date::MASK_MONDAY,
- Horde_Date::DATE_TUESDAY => Horde_Date::MASK_TUESDAY,
- Horde_Date::DATE_WEDNESDAY => Horde_Date::MASK_WEDNESDAY,
- Horde_Date::DATE_THURSDAY => Horde_Date::MASK_THURSDAY,
- Horde_Date::DATE_FRIDAY => Horde_Date::MASK_FRIDAY,
- Horde_Date::DATE_SATURDAY => Horde_Date::MASK_SATURDAY,
- );
- $this->setRecurOnDay($maskdays[$this->start->dayOfWeek()]);
- }
- break;
-
- case 'MP':
- $this->setRecurType(self::RECUR_MONTHLY_WEEKDAY);
- break;
-
- case 'MD':
- $this->setRecurType(self::RECUR_MONTHLY_DATE);
- break;
-
- case 'YM':
- $this->setRecurType(self::RECUR_YEARLY_DATE);
- break;
-
- case 'YD':
- $this->setRecurType(self::RECUR_YEARLY_DAY);
- break;
- }
-
- // We don't support modifiers at the moment, strip them.
- while ($remainder && !preg_match('/^(#\d+|\d{8})($| |T\d{6})/', $remainder)) {
- $remainder = substr($remainder, 1);
- }
- if (!empty($remainder)) {
- if (strpos($remainder, '#') === 0) {
- $this->setRecurCount(substr($remainder, 1));
- } else {
- list($year, $month, $mday) = sscanf($remainder, '%04d%02d%02d');
- $this->setRecurEnd(new Horde_Date(array('year' => $year,
- 'month' => $month,
- 'mday' => $mday,
- 'hour' => 23,
- 'min' => 59,
- 'sec' => 59)));
- }
- }
- }
-
- /**
- * Creates a vCalendar 1.0 recurrence rule.
- *
- * @link http://www.imc.org/pdi/vcal-10.txt
- * @link http://www.shuchow.com/vCalAddendum.html
- *
- * @param Horde_Icalendar $calendar A Horde_Icalendar object instance.
- *
- * @return string A vCalendar 1.0 conform RRULE value.
- */
- public function toRRule10($calendar)
- {
- switch ($this->recurType) {
- case self::RECUR_NONE:
- return '';
-
- case self::RECUR_DAILY:
- $rrule = 'D' . $this->recurInterval;
- break;
-
- case self::RECUR_WEEKLY:
- $rrule = 'W' . $this->recurInterval;
- $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA');
-
- for ($i = 0; $i <= 7; ++$i) {
- if ($this->recurOnDay(pow(2, $i))) {
- $rrule .= ' ' . $vcaldays[$i];
- }
- }
- break;
-
- case self::RECUR_MONTHLY_DATE:
- $rrule = 'MD' . $this->recurInterval . ' ' . trim($this->start->mday);
- break;
-
- case self::RECUR_MONTHLY_WEEKDAY:
- $nth_weekday = (int)($this->start->mday / 7);
- if (($this->start->mday % 7) > 0) {
- $nth_weekday++;
- }
-
- $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA');
- $rrule = 'MP' . $this->recurInterval . ' ' . $nth_weekday . '+ ' . $vcaldays[$this->start->dayOfWeek()];
-
- break;
-
- case self::RECUR_YEARLY_DATE:
- $rrule = 'YM' . $this->recurInterval . ' ' . trim($this->start->month);
- break;
-
- case self::RECUR_YEARLY_DAY:
- $rrule = 'YD' . $this->recurInterval . ' ' . $this->start->dayOfYear();
- break;
-
- default:
- return '';
- }
-
- if ($this->hasRecurEnd()) {
- $recurEnd = clone $this->recurEnd;
- return $rrule . ' ' . $calendar->_exportDateTime($recurEnd);
- }
-
- return $rrule . ' #' . (int)$this->getRecurCount();
- }
-
- /**
- * Parses an iCalendar 2.0 recurrence rule.
- *
- * @link http://rfc.net/rfc2445.html#s4.3.10
- * @link http://rfc.net/rfc2445.html#s4.8.5
- * @link http://www.shuchow.com/vCalAddendum.html
- *
- * @param string $rrule An iCalendar 2.0 conform RRULE value.
- */
- public function fromRRule20($rrule)
- {
- $this->reset();
-
- // Parse the recurrence rule into keys and values.
- $rdata = array();
- $parts = explode(';', $rrule);
- foreach ($parts as $part) {
- list($key, $value) = explode('=', $part, 2);
- $rdata[strtoupper($key)] = $value;
- }
-
- if (isset($rdata['FREQ'])) {
- // Always default the recurInterval to 1.
- $this->setRecurInterval(isset($rdata['INTERVAL']) ? $rdata['INTERVAL'] : 1);
-
- $maskdays = array(
- 'SU' => Horde_Date::MASK_SUNDAY,
- 'MO' => Horde_Date::MASK_MONDAY,
- 'TU' => Horde_Date::MASK_TUESDAY,
- 'WE' => Horde_Date::MASK_WEDNESDAY,
- 'TH' => Horde_Date::MASK_THURSDAY,
- 'FR' => Horde_Date::MASK_FRIDAY,
- 'SA' => Horde_Date::MASK_SATURDAY,
- );
-
- switch (strtoupper($rdata['FREQ'])) {
- case 'DAILY':
- $this->setRecurType(self::RECUR_DAILY);
- break;
-
- case 'WEEKLY':
- $this->setRecurType(self::RECUR_WEEKLY);
- if (isset($rdata['BYDAY'])) {
- $days = explode(',', $rdata['BYDAY']);
- $mask = 0;
- foreach ($days as $day) {
- $mask |= $maskdays[$day];
- }
- $this->setRecurOnDay($mask);
- } else {
- // Recur on the day of the week of the original
- // recurrence.
- $maskdays = array(
- Horde_Date::DATE_SUNDAY => Horde_Date::MASK_SUNDAY,
- Horde_Date::DATE_MONDAY => Horde_Date::MASK_MONDAY,
- Horde_Date::DATE_TUESDAY => Horde_Date::MASK_TUESDAY,
- Horde_Date::DATE_WEDNESDAY => Horde_Date::MASK_WEDNESDAY,
- Horde_Date::DATE_THURSDAY => Horde_Date::MASK_THURSDAY,
- Horde_Date::DATE_FRIDAY => Horde_Date::MASK_FRIDAY,
- Horde_Date::DATE_SATURDAY => Horde_Date::MASK_SATURDAY);
- $this->setRecurOnDay($maskdays[$this->start->dayOfWeek()]);
- }
- break;
-
- case 'MONTHLY':
- if (isset($rdata['BYDAY'])) {
- $this->setRecurType(self::RECUR_MONTHLY_WEEKDAY);
- if (preg_match('/(-?[1-4])([A-Z]+)/', $rdata['BYDAY'], $m)) {
- $this->setRecurOnDay($maskdays[$m[2]]);
- $this->setRecurNthWeekday($m[1]);
- }
- } else {
- $this->setRecurType(self::RECUR_MONTHLY_DATE);
- }
- break;
-
- case 'YEARLY':
- if (isset($rdata['BYYEARDAY'])) {
- $this->setRecurType(self::RECUR_YEARLY_DAY);
- } elseif (isset($rdata['BYDAY'])) {
- $this->setRecurType(self::RECUR_YEARLY_WEEKDAY);
- if (preg_match('/(-?[1-4])([A-Z]+)/', $rdata['BYDAY'], $m)) {
- $this->setRecurOnDay($maskdays[$m[2]]);
- $this->setRecurNthWeekday($m[1]);
- }
- if ($rdata['BYMONTH']) {
- $months = explode(',', $rdata['BYMONTH']);
- $this->setRecurByMonth($months);
- }
- } else {
- $this->setRecurType(self::RECUR_YEARLY_DATE);
- }
- break;
- }
-
- if (isset($rdata['UNTIL'])) {
- list($year, $month, $mday) = sscanf($rdata['UNTIL'],
- '%04d%02d%02d');
- $this->setRecurEnd(new Horde_Date(array('year' => $year,
- 'month' => $month,
- 'mday' => $mday,
- 'hour' => 23,
- 'min' => 59,
- 'sec' => 59)));
- }
- if (isset($rdata['COUNT'])) {
- $this->setRecurCount($rdata['COUNT']);
- }
- } else {
- // No recurrence data - event does not recur.
- $this->setRecurType(self::RECUR_NONE);
- }
- }
-
- /**
- * Creates an iCalendar 2.0 recurrence rule.
- *
- * @link http://rfc.net/rfc2445.html#s4.3.10
- * @link http://rfc.net/rfc2445.html#s4.8.5
- * @link http://www.shuchow.com/vCalAddendum.html
- *
- * @param Horde_Icalendar $calendar A Horde_Icalendar object instance.
- *
- * @return string An iCalendar 2.0 conform RRULE value.
- */
- public function toRRule20($calendar)
- {
- switch ($this->recurType) {
- case self::RECUR_NONE:
- return '';
-
- case self::RECUR_DAILY:
- $rrule = 'FREQ=DAILY;INTERVAL=' . $this->recurInterval;
- break;
-
- case self::RECUR_WEEKLY:
- $rrule = 'FREQ=WEEKLY;INTERVAL=' . $this->recurInterval . ';BYDAY=';
- $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA');
-
- for ($i = $flag = 0; $i <= 7; ++$i) {
- if ($this->recurOnDay(pow(2, $i))) {
- if ($flag) {
- $rrule .= ',';
- }
- $rrule .= $vcaldays[$i];
- $flag = true;
- }
- }
- break;
-
- case self::RECUR_MONTHLY_DATE:
- $rrule = 'FREQ=MONTHLY;INTERVAL=' . $this->recurInterval;
- break;
-
- case self::RECUR_MONTHLY_WEEKDAY:
- if (isset($this->recurNthDay)) {
- $nth_weekday = $this->recurNthDay;
- $day_of_week = log($this->recurData, 2);
- } else {
- $day_of_week = $this->start->dayOfWeek();
- $nth_weekday = (int)($this->start->mday / 7);
- if (($this->start->mday % 7) > 0) {
- $nth_weekday++;
- }
- }
- $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA');
- $rrule = 'FREQ=MONTHLY;INTERVAL=' . $this->recurInterval
- . ';BYDAY=' . $nth_weekday . $vcaldays[$day_of_week];
- break;
-
- case self::RECUR_YEARLY_DATE:
- $rrule = 'FREQ=YEARLY;INTERVAL=' . $this->recurInterval;
- break;
-
- case self::RECUR_YEARLY_DAY:
- $rrule = 'FREQ=YEARLY;INTERVAL=' . $this->recurInterval
- . ';BYYEARDAY=' . $this->start->dayOfYear();
- break;
-
- case self::RECUR_YEARLY_WEEKDAY:
- if (isset($this->recurNthDay)) {
- $nth_weekday = $this->recurNthDay;
- $day_of_week = log($this->recurData, 2);
- } else {
- $day_of_week = $this->start->dayOfWeek();
- $nth_weekday = (int)($this->start->mday / 7);
- if (($this->start->mday % 7) > 0) {
- $nth_weekday++;
- }
- }
- $months = !empty($this->recurMonths) ? join(',', $this->recurMonths) : $this->start->month;
- $vcaldays = array('SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA');
- $rrule = 'FREQ=YEARLY;INTERVAL=' . $this->recurInterval
- . ';BYDAY='
- . $nth_weekday
- . $vcaldays[$day_of_week]
- . ';BYMONTH=' . $this->start->month;
- break;
- }
-
- if ($this->hasRecurEnd()) {
- $recurEnd = clone $this->recurEnd;
- $rrule .= ';UNTIL=' . $calendar->_exportDateTime($recurEnd);
- }
- if ($count = $this->getRecurCount()) {
- $rrule .= ';COUNT=' . $count;
- }
- return $rrule;
- }
-
- /**
- * Parses the recurrence data from a hash.
- *
- * @param array $hash The hash to convert.
- *
- * @return boolean True if the hash seemed valid, false otherwise.
- */
- public function fromHash($hash)
- {
- $this->reset();
-
- if (!isset($hash['interval']) || !isset($hash['cycle'])) {
- $this->setRecurType(self::RECUR_NONE);
- return false;
- }
-
- $this->setRecurInterval((int)$hash['interval']);
-
- $month2number = array(
- 'january' => 1,
- 'february' => 2,
- 'march' => 3,
- 'april' => 4,
- 'may' => 5,
- 'june' => 6,
- 'july' => 7,
- 'august' => 8,
- 'september' => 9,
- 'october' => 10,
- 'november' => 11,
- 'december' => 12,
- );
-
- $parse_day = false;
- $set_daymask = false;
- $update_month = false;
- $update_daynumber = false;
- $update_weekday = false;
- $nth_weekday = -1;
-
- switch ($hash['cycle']) {
- case 'daily':
- $this->setRecurType(self::RECUR_DAILY);
- break;
-
- case 'weekly':
- $this->setRecurType(self::RECUR_WEEKLY);
- $parse_day = true;
- $set_daymask = true;
- break;
-
- case 'monthly':
- if (!isset($hash['daynumber'])) {
- $this->setRecurType(self::RECUR_NONE);
- return false;
- }
-
- switch ($hash['type']) {
- case 'daynumber':
- $this->setRecurType(self::RECUR_MONTHLY_DATE);
- $update_daynumber = true;
- break;
-
- case 'weekday':
- $this->setRecurType(self::RECUR_MONTHLY_WEEKDAY);
- $this->setRecurNthWeekday($hash['daynumber']);
- $parse_day = true;
- $set_daymask = true;
- break;
- }
- break;
-
- case 'yearly':
- if (!isset($hash['type'])) {
- $this->setRecurType(self::RECUR_NONE);
- return false;
- }
-
- switch ($hash['type']) {
- case 'monthday':
- $this->setRecurType(self::RECUR_YEARLY_DATE);
- $update_month = true;
- $update_daynumber = true;
- break;
-
- case 'yearday':
- if (!isset($hash['month'])) {
- $this->setRecurType(self::RECUR_NONE);
- return false;
- }
-
- $this->setRecurType(self::RECUR_YEARLY_DAY);
- // Start counting days in January.
- $hash['month'] = 'january';
- $update_month = true;
- $update_daynumber = true;
- break;
-
- case 'weekday':
- if (!isset($hash['daynumber'])) {
- $this->setRecurType(self::RECUR_NONE);
- return false;
- }
-
- $this->setRecurType(self::RECUR_YEARLY_WEEKDAY);
- $this->setRecurNthWeekday($hash['daynumber']);
- $parse_day = true;
- $set_daymask = true;
-
- if ($hash['month'] && isset($month2number[$hash['month']])) {
- $this->setRecurByMonth($month2number[$hash['month']]);
- }
- break;
- }
- }
-
- if (isset($hash['range-type']) && isset($hash['range'])) {
- switch ($hash['range-type']) {
- case 'number':
- $this->setRecurCount((int)$hash['range']);
- break;
-
- case 'date':
- $recur_end = new Horde_Date($hash['range']);
- $recur_end->hour = 23;
- $recur_end->min = 59;
- $recur_end->sec = 59;
- $this->setRecurEnd($recur_end);
- break;
- }
- }
-
- // Need to parse <day>?
- $last_found_day = -1;
- if ($parse_day) {
- if (!isset($hash['day'])) {
- $this->setRecurType(self::RECUR_NONE);
- return false;
- }
-
- $mask = 0;
- $bits = array(
- 'monday' => Horde_Date::MASK_MONDAY,
- 'tuesday' => Horde_Date::MASK_TUESDAY,
- 'wednesday' => Horde_Date::MASK_WEDNESDAY,
- 'thursday' => Horde_Date::MASK_THURSDAY,
- 'friday' => Horde_Date::MASK_FRIDAY,
- 'saturday' => Horde_Date::MASK_SATURDAY,
- 'sunday' => Horde_Date::MASK_SUNDAY,
- );
- $days = array(
- 'monday' => Horde_Date::DATE_MONDAY,
- 'tuesday' => Horde_Date::DATE_TUESDAY,
- 'wednesday' => Horde_Date::DATE_WEDNESDAY,
- 'thursday' => Horde_Date::DATE_THURSDAY,
- 'friday' => Horde_Date::DATE_FRIDAY,
- 'saturday' => Horde_Date::DATE_SATURDAY,
- 'sunday' => Horde_Date::DATE_SUNDAY,
- );
-
- foreach ($hash['day'] as $day) {
- // Validity check.
- if (empty($day) || !isset($bits[$day])) {
- continue;
- }
-
- $mask |= $bits[$day];
- $last_found_day = $days[$day];
- }
-
- if ($set_daymask) {
- $this->setRecurOnDay($mask);
- }
- }
-
- if ($update_month || $update_daynumber || $update_weekday) {
- if ($update_month) {
- if (isset($month2number[$hash['month']])) {
- $this->start->month = $month2number[$hash['month']];
- }
- }
-
- if ($update_daynumber) {
- if (!isset($hash['daynumber'])) {
- $this->setRecurType(self::RECUR_NONE);
- return false;
- }
-
- $this->start->mday = $hash['daynumber'];
- }
-
- if ($update_weekday) {
- $this->setNthWeekday($nth_weekday);
- }
- }
-
- // Exceptions.
- if (isset($hash['exceptions'])) {
- $this->exceptions = $hash['exceptions'];
- }
-
- if (isset($hash['completions'])) {
- $this->completions = $hash['completions'];
- }
-
- return true;
- }
-
- /**
- * Export this object into a hash.
- *
- * @return array The recurrence hash.
- */
- public function toHash()
- {
- if ($this->getRecurType() == self::RECUR_NONE) {
- return array();
- }
-
- $day2number = array(
- 0 => 'sunday',
- 1 => 'monday',
- 2 => 'tuesday',
- 3 => 'wednesday',
- 4 => 'thursday',
- 5 => 'friday',
- 6 => 'saturday'
- );
- $month2number = array(
- 1 => 'january',
- 2 => 'february',
- 3 => 'march',
- 4 => 'april',
- 5 => 'may',
- 6 => 'june',
- 7 => 'july',
- 8 => 'august',
- 9 => 'september',
- 10 => 'october',
- 11 => 'november',
- 12 => 'december'
- );
-
- $hash = array('interval' => $this->getRecurInterval());
- $start = $this->getRecurStart();
-
- switch ($this->getRecurType()) {
- case self::RECUR_DAILY:
- $hash['cycle'] = 'daily';
- break;
-
- case self::RECUR_WEEKLY:
- $hash['cycle'] = 'weekly';
- $bits = array(
- 'monday' => Horde_Date::MASK_MONDAY,
- 'tuesday' => Horde_Date::MASK_TUESDAY,
- 'wednesday' => Horde_Date::MASK_WEDNESDAY,
- 'thursday' => Horde_Date::MASK_THURSDAY,
- 'friday' => Horde_Date::MASK_FRIDAY,
- 'saturday' => Horde_Date::MASK_SATURDAY,
- 'sunday' => Horde_Date::MASK_SUNDAY,
- );
- $days = array();
- foreach ($bits as $name => $bit) {
- if ($this->recurOnDay($bit)) {
- $days[] = $name;
- }
- }
- $hash['day'] = $days;
- break;
-
- case self::RECUR_MONTHLY_DATE:
- $hash['cycle'] = 'monthly';
- $hash['type'] = 'daynumber';
- $hash['daynumber'] = $start->mday;
- break;
-
- case self::RECUR_MONTHLY_WEEKDAY:
- $hash['cycle'] = 'monthly';
- $hash['type'] = 'weekday';
- $hash['daynumber'] = $start->weekOfMonth();
- $hash['day'] = array ($day2number[$start->dayOfWeek()]);
- break;
-
- case self::RECUR_YEARLY_DATE:
- $hash['cycle'] = 'yearly';
- $hash['type'] = 'monthday';
- $hash['daynumber'] = $start->mday;
- $hash['month'] = $month2number[$start->month];
- break;
-
- case self::RECUR_YEARLY_DAY:
- $hash['cycle'] = 'yearly';
- $hash['type'] = 'yearday';
- $hash['daynumber'] = $start->dayOfYear();
- break;
-
- case self::RECUR_YEARLY_WEEKDAY:
- $hash['cycle'] = 'yearly';
- $hash['type'] = 'weekday';
- $hash['daynumber'] = $start->weekOfMonth();
- $hash['day'] = array ($day2number[$start->dayOfWeek()]);
- $hash['month'] = $month2number[$start->month];
- }
-
- if ($this->hasRecurCount()) {
- $hash['range-type'] = 'number';
- $hash['range'] = $this->getRecurCount();
- } elseif ($this->hasRecurEnd()) {
- $date = $this->getRecurEnd();
- $hash['range-type'] = 'date';
- $hash['range'] = $date->datestamp();
- } else {
- $hash['range-type'] = 'none';
- $hash['range'] = '';
- }
-
- // Recurrence exceptions
- $hash['exceptions'] = $this->exceptions;
- $hash['completions'] = $this->completions;
-
- return $hash;
- }
-
- /**
- * Returns a simple object suitable for json transport representing this
- * object.
- *
- * Possible properties are:
- * - t: type
- * - i: interval
- * - e: end date
- * - c: count
- * - d: data
- * - co: completions
- * - ex: exceptions
- *
- * @return object A simple object.
- */
- public function toJson()
- {
- $json = new stdClass;
- $json->t = $this->recurType;
- $json->i = $this->recurInterval;
- if ($this->hasRecurEnd()) {
- $json->e = $this->recurEnd->toJson();
- }
- if ($this->recurCount) {
- $json->c = $this->recurCount;
- }
- if ($this->recurData) {
- $json->d = $this->recurData;
- }
- if ($this->completions) {
- $json->co = $this->completions;
- }
- if ($this->exceptions) {
- $json->ex = $this->exceptions;
- }
- return $json;
- }
-
-}
diff --git a/plugins/libkolab/lib/Horde_Kolab_Format_XML_configuration.php b/plugins/libkolab/lib/Horde_Kolab_Format_XML_configuration.php
deleted file mode 100644
index c80fbd3d..00000000
--- a/plugins/libkolab/lib/Horde_Kolab_Format_XML_configuration.php
+++ /dev/null
@@ -1,76 +0,0 @@
-<?php
-
-/**
- * Kolab XML handler for configuration (KEP:9).
- *
- * @author Aleksander Machniak <machniak@kolabsys.com>
- *
- * Copyright (C) 2011, Kolab Systems AG <contact@kolabsys.com>
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-class Horde_Kolab_Format_XML_configuration extends Horde_Kolab_Format_XML {
- /**
- * Specific data fields for the configuration object
- *
- * @var Kolab
- */
- var $_fields_specific;
-
- var $_root_version = 2.1;
-
- /**
- * Constructor
- */
- function Horde_Kolab_Format_XML_configuration($params = array())
- {
- $this->_root_name = 'configuration';
-
- // Specific configuration fields, in kolab format specification order
- $this->_fields_specific = array(
- 'application' => array (
- 'type' => HORDE_KOLAB_XML_TYPE_STRING,
- 'value' => HORDE_KOLAB_XML_VALUE_MAYBE_MISSING,
- ),
- 'type' => array(
- 'type' => HORDE_KOLAB_XML_TYPE_STRING,
- 'value' => HORDE_KOLAB_XML_VALUE_NOT_EMPTY,
- ),
- );
-
- // Dictionary fields
- if (!empty($params['subtype']) && preg_match('/^dictionary.*/', $params['subtype'])) {
- $this->_fields_specific = array_merge($this->_fields_specific, array(
- 'language' => array (
- 'type' => HORDE_KOLAB_XML_TYPE_STRING,
- 'value' => HORDE_KOLAB_XML_VALUE_NOT_EMPTY,
- ),
- 'e' => array(
- 'type' => HORDE_KOLAB_XML_TYPE_MULTIPLE,
- 'value' => HORDE_KOLAB_XML_VALUE_NOT_EMPTY,
- 'array' => array(
- 'type' => HORDE_KOLAB_XML_TYPE_STRING,
- 'value' => HORDE_KOLAB_XML_VALUE_NOT_EMPTY,
- ),
- ),
- ));
- }
-
- parent::Horde_Kolab_Format_XML($params);
-
- unset($this->_fields_basic['body']);
- unset($this->_fields_basic['categories']);
- unset($this->_fields_basic['sensitivity']);
- }
-}
diff --git a/plugins/libkolab/lib/kolab_format.php b/plugins/libkolab/lib/kolab_format.php
index a4147812..c3c1b12c 100644
--- a/plugins/libkolab/lib/kolab_format.php
+++ b/plugins/libkolab/lib/kolab_format.php
@@ -1,419 +1,412 @@
<?php
/**
* Kolab format model class wrapping libkolabxml bindings
*
* Abstract base class for different Kolab groupware objects read from/written
* to the new Kolab 3 format using the PHP bindings of libkolabxml.
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class kolab_format
{
public static $timezone;
public /*abstract*/ $CTYPE;
public /*abstract*/ $CTYPEv2;
protected /*abstract*/ $objclass;
protected /*abstract*/ $read_func;
protected /*abstract*/ $write_func;
protected $obj;
protected $data;
protected $xmldata;
protected $xmlobject;
protected $loaded = false;
protected $version = 3.0;
const KTYPE_PREFIX = 'application/x-vnd.kolab.';
const PRODUCT_ID = 'Roundcube-libkolab-0.9';
/**
* Factory method to instantiate a kolab_format object of the given type and version
*
* @param string Object type to instantiate
* @param float Format version
* @param string Cached xml data to initialize with
* @return object kolab_format
*/
public static function factory($type, $version = 3.0, $xmldata = null)
{
if (!isset(self::$timezone))
self::$timezone = new DateTimeZone('UTC');
if (!self::supports($version))
return PEAR::raiseError("No support for Kolab format version " . $version);
$type = preg_replace('/configuration\.[a-z.]+$/', 'configuration', $type);
$suffix = preg_replace('/[^a-z]+/', '', $type);
$classname = 'kolab_format_' . $suffix;
if (class_exists($classname))
return new $classname($xmldata, $version);
return PEAR::raiseError("Failed to load Kolab Format wrapper for type " . $type);
}
/**
* Determine support for the given format version
*
* @param float Format version to check
* @return boolean True if supported, False otherwise
*/
public static function supports($version)
{
if ($version == 2.0)
return class_exists('kolabobject');
// default is version 3
return class_exists('kolabformat');
}
/**
* Convert the given date/time value into a cDateTime object
*
* @param mixed Date/Time value either as unix timestamp, date string or PHP DateTime object
* @param DateTimeZone The timezone the date/time is in. Use global default if Null, local time if False
* @param boolean True of the given date has no time component
* @return object The libkolabxml date/time object
*/
public static function get_datetime($datetime, $tz = null, $dateonly = false)
{
// use timezone information from datetime of global setting
if (!$tz && $tz !== false) {
if ($datetime instanceof DateTime)
$tz = $datetime->getTimezone();
if (!$tz)
$tz = self::$timezone;
}
$result = new cDateTime();
// got a unix timestamp (in UTC)
if (is_numeric($datetime)) {
$datetime = new DateTime('@'.$datetime, new DateTimeZone('UTC'));
if ($tz) $datetime->setTimezone($tz);
}
else if (is_string($datetime) && strlen($datetime))
$datetime = new DateTime($datetime, $tz ?: null);
if ($datetime instanceof DateTime) {
$result->setDate($datetime->format('Y'), $datetime->format('n'), $datetime->format('j'));
if (!$dateonly)
$result->setTime($datetime->format('G'), $datetime->format('i'), $datetime->format('s'));
if ($tz && $tz->getName() == 'UTC')
$result->setUTC(true);
else if ($tz !== false)
$result->setTimezone($tz->getName());
}
return $result;
}
/**
* Convert the given cDateTime into a PHP DateTime object
*
* @param object cDateTime The libkolabxml datetime object
* @return object DateTime PHP datetime instance
*/
public static function php_datetime($cdt)
{
if (!is_object($cdt) || !$cdt->isValid())
return null;
$d = new DateTime;
$d->setTimezone(self::$timezone);
try {
if ($tzs = $cdt->timezone()) {
$tz = new DateTimeZone($tzs);
$d->setTimezone($tz);
}
else if ($cdt->isUTC()) {
$d->setTimezone(new DateTimeZone('UTC'));
}
}
catch (Exception $e) { }
$d->setDate($cdt->year(), $cdt->month(), $cdt->day());
if ($cdt->isDateOnly()) {
$d->_dateonly = true;
$d->setTime(12, 0, 0); // set time to noon to avoid timezone troubles
}
else {
$d->setTime($cdt->hour(), $cdt->minute(), $cdt->second());
}
return $d;
}
/**
* Convert a libkolabxml vector to a PHP array
*
* @param object vector Object
* @return array Indexed array contaning vector elements
*/
public static function vector2array($vec, $max = PHP_INT_MAX)
{
$arr = array();
for ($i=0; $i < $vec->size() && $i < $max; $i++)
$arr[] = $vec->get($i);
return $arr;
}
/**
* Build a libkolabxml vector (string) from a PHP array
*
* @param array Array with vector elements
* @return object vectors
*/
public static function array2vector($arr)
{
$vec = new vectors;
foreach ((array)$arr as $val) {
if (strlen($val))
$vec->push($val);
}
return $vec;
}
/**
* Parse the X-Kolab-Type header from MIME messages and return the object type in short form
*
* @param string X-Kolab-Type header value
* @return string Kolab object type (contact,event,task,note,etc.)
*/
public static function mime2object_type($x_kolab_type)
{
return preg_replace('/dictionary.[a-z.]+$/', 'dictionary', substr($x_kolab_type, strlen(self::KTYPE_PREFIX)));
}
/**
* Default constructor of all kolab_format_* objects
*/
public function __construct($xmldata = null, $version = null)
{
$this->obj = new $this->objclass;
$this->xmldata = $xmldata;
if ($version)
$this->version = $version;
// use libkolab module if available
if (class_exists('kolabobject'))
$this->xmlobject = new XMLObject();
}
/**
* Check for format errors after calling kolabformat::write*()
*
* @return boolean True if there were errors, False if OK
*/
protected function format_errors()
{
$ret = $log = false;
switch (kolabformat::error()) {
case kolabformat::NoError:
$ret = false;
break;
case kolabformat::Warning:
$ret = false;
$log = "Warning";
break;
default:
$ret = true;
$log = "Error";
}
if ($log) {
rcube::raise_error(array(
'code' => 660,
'type' => 'php',
'file' => __FILE__,
'line' => __LINE__,
'message' => "kolabformat $log: " . kolabformat::errorMessage(),
), true);
}
return $ret;
}
/**
* Save the last generated UID to the object properties.
* Should be called after kolabformat::writeXXXX();
*/
protected function update_uid()
{
// get generated UID
if (!$this->data['uid']) {
$this->data['uid'] = $this->xmlobject ? $this->xmlobject->getSerializedUID() : kolabformat::getSerializedUID();
$this->obj->setUid($this->data['uid']);
}
}
/**
* Initialize libkolabxml object with cached xml data
*/
protected function init()
{
if (!$this->loaded) {
if ($this->xmldata) {
$this->load($this->xmldata);
$this->xmldata = null;
}
$this->loaded = true;
}
}
/**
* Get constant value for libkolab's version parameter
*
* @param float Version value to convert
* @return int Constant value of either kolabobject::KolabV2 or kolabobject::KolabV3 or false if kolabobject module isn't available
*/
protected function libversion($v = null)
{
if (class_exists('kolabobject')) {
$version = $v ?: $this->version;
if ($version <= 2.0)
return kolabobject::KolabV2;
else
return kolabobject::KolabV3;
}
return false;
}
/**
* Determine the correct libkolab(xml) wrapper function for the given call
* depending on the available PHP modules
*/
protected function libfunc($func)
{
if (is_array($func) || strpos($func, '::'))
return $func;
else if (class_exists('kolabobject'))
return array($this->xmlobject, $func);
else
return 'kolabformat::' . $func;
}
/**
* Direct getter for object properties
*/
public function __get($var)
{
return $this->data[$var];
}
/**
* Load Kolab object data from the given XML block
*
* @param string XML data
* @return boolean True on success, False on failure
*/
public function load($xml)
{
$read_func = $this->libfunc($this->read_func);
if (is_array($read_func))
$r = call_user_func($read_func, $xml, $this->libversion());
else
$r = call_user_func($read_func, $xml, false);
if (is_resource($r))
$this->obj = new $this->objclass($r);
else if (is_a($r, $this->objclass))
$this->obj = $r;
$this->loaded = !$this->format_errors();
}
/**
* Write object data to XML format
*
* @param float Format version to write
* @return string XML data
*/
public function write($version = null)
{
$this->init();
$write_func = $this->libfunc($this->write_func);
if (is_array($write_func))
$this->xmldata = call_user_func($write_func, $this->obj, $this->libversion($version), self::PRODUCT_ID);
else
$this->xmldata = call_user_func($write_func, $this->obj, self::PRODUCT_ID);
if (!$this->format_errors())
$this->update_uid();
else
$this->xmldata = null;
return $this->xmldata;
}
/**
* Set properties to the kolabformat object
*
* @param array Object data as hash array
*/
abstract public function set(&$object);
/**
*
*/
abstract public function is_valid();
/**
* Convert the Kolab object into a hash array data structure
*
* @return array Kolab object data as hash array
*/
abstract public function to_array();
- /**
- * Load object data from Kolab2 format
- *
- * @param array Hash array with object properties (produced by Horde Kolab_Format classes)
- */
- abstract public function fromkolab2($object);
-
/**
* Callback for kolab_storage_cache to get object specific tags to cache
*
* @return array List of tags to save in cache
*/
public function get_tags()
{
return array();
}
/**
* Callback for kolab_storage_cache to get words to index for fulltext search
*
* @return array List of words to save in cache
*/
public function get_words()
{
return array();
}
}
diff --git a/plugins/libkolab/lib/kolab_format_configuration.php b/plugins/libkolab/lib/kolab_format_configuration.php
index 918928b2..0edc6a24 100644
--- a/plugins/libkolab/lib/kolab_format_configuration.php
+++ b/plugins/libkolab/lib/kolab_format_configuration.php
@@ -1,159 +1,146 @@
<?php
/**
* Kolab Configuration data model class
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_format_configuration extends kolab_format
{
public $CTYPE = 'application/x-vnd.kolab.configuration';
public $CTYPEv2 = 'application/x-vnd.kolab.configuration';
protected $objclass = 'Configuration';
protected $read_func = 'readConfiguration';
protected $write_func = 'writeConfiguration';
private $type_map = array(
'dictionary' => Configuration::TypeDictionary,
'category' => Configuration::TypeCategoryColor,
);
/**
* Set properties to the kolabformat object
*
* @param array Object data as hash array
*/
public function set(&$object)
{
$this->init();
// read type-specific properties
switch ($object['type']) {
case 'dictionary':
$dict = new Dictionary($object['language']);
$dict->setEntries(self::array2vector($object['e']));
$this->obj = new Configuration($dict);
break;
case 'category':
// TODO: implement this
$categories = new vectorcategorycolor;
$this->obj = new Configuration($categories);
break;
default:
return false;
}
// set some automatic values if missing
if (!empty($object['uid']))
$this->obj->setUid($object['uid']);
if (!empty($object['created']))
$this->obj->setCreated(self::get_datetime($object['created']));
// adjust content-type string
$this->CTYPE = $this->CTYPEv2 = 'application/x-vnd.kolab.configuration.' . $object['type'];
// cache this data
$this->data = $object;
unset($this->data['_formatobj']);
}
/**
*
*/
public function is_valid()
{
return $this->data || (is_object($this->obj) && $this->obj->isValid());
}
/**
* Convert the Configuration object into a hash array data structure
*
* @return array Config object data as hash array
*/
public function to_array()
{
// return cached result
if (!empty($this->data))
return $this->data;
$this->init();
$type_map = array_flip($this->type_map);
// read object properties
$object = array(
'uid' => $this->obj->uid(),
'created' => self::php_datetime($this->obj->created()),
'changed' => self::php_datetime($this->obj->lastModified()),
'type' => $type_map[$this->obj->type()],
);
// read type-specific properties
switch ($object['type']) {
case 'dictionary':
$dict = $this->obj->dictionary();
$object['language'] = $dict->language();
$object['e'] = self::vector2array($dict->entries());
break;
case 'category':
// TODO: implement this
break;
}
// adjust content-type string
if ($object['type'])
$this->CTYPE = $this->CTYPEv2 = 'application/x-vnd.kolab.configuration.' . $object['type'];
$this->data = $object;
return $this->data;
}
- /**
- * Load data from old Kolab2 format
- */
- public function fromkolab2($record)
- {
- $object = array(
- 'uid' => $record['uid'],
- 'changed' => $record['last-modification-date'],
- );
-
- $this->data = $object + $record;
- }
-
/**
* Callback for kolab_storage_cache to get object specific tags to cache
*
* @return array List of tags to save in cache
*/
public function get_tags()
{
$tags = array();
if ($this->data['type'] == 'dictionary')
$tags = array($this->data['language']);
return $tags;
}
}
diff --git a/plugins/libkolab/lib/kolab_format_contact.php b/plugins/libkolab/lib/kolab_format_contact.php
index b147c384..39e579cd 100644
--- a/plugins/libkolab/lib/kolab_format_contact.php
+++ b/plugins/libkolab/lib/kolab_format_contact.php
@@ -1,512 +1,421 @@
<?php
/**
* Kolab Contact model class
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_format_contact extends kolab_format
{
public $CTYPE = 'application/vcard+xml';
public $CTYPEv2 = 'application/x-vnd.kolab.contact';
protected $objclass = 'Contact';
protected $read_func = 'readContact';
protected $write_func = 'writeContact';
public static $fulltext_cols = array('name', 'firstname', 'surname', 'middlename', 'email');
public $phonetypes = array(
'home' => Telephone::Home,
'work' => Telephone::Work,
'text' => Telephone::Text,
'main' => Telephone::Voice,
'homefax' => Telephone::Fax,
'workfax' => Telephone::Fax,
'mobile' => Telephone::Cell,
'video' => Telephone::Video,
'pager' => Telephone::Pager,
'car' => Telephone::Car,
'other' => Telephone::Textphone,
);
public $addresstypes = array(
'home' => Address::Home,
'work' => Address::Work,
'office' => 0,
);
private $gendermap = array(
'female' => Contact::Female,
'male' => Contact::Male,
);
private $relatedmap = array(
'manager' => Related::Manager,
'assistant' => Related::Assistant,
'spouse' => Related::Spouse,
'children' => Related::Child,
);
- // old Kolab 2 format field map
- private $kolab2_fieldmap = array(
- // kolab => roundcube
- 'full-name' => 'name',
- 'given-name' => 'firstname',
- 'middle-names' => 'middlename',
- 'last-name' => 'surname',
- 'prefix' => 'prefix',
- 'suffix' => 'suffix',
- 'nick-name' => 'nickname',
- 'organization' => 'organization',
- 'department' => 'department',
- 'job-title' => 'jobtitle',
- 'birthday' => 'birthday',
- 'anniversary' => 'anniversary',
- 'phone' => 'phone',
- 'im-address' => 'im',
- 'web-page' => 'website',
- 'profession' => 'profession',
- 'manager-name' => 'manager',
- 'assistant' => 'assistant',
- 'spouse-name' => 'spouse',
- 'children' => 'children',
- 'body' => 'notes',
- 'pgp-publickey' => 'pgppublickey',
- 'free-busy-url' => 'freebusyurl',
- 'picture' => 'photo',
- );
- private $kolab2_phonetypes = array(
- 'home1' => 'home',
- 'business1' => 'work',
- 'business2' => 'work',
- 'businessfax' => 'workfax',
- );
- private $kolab2_addresstypes = array(
- 'business' => 'work'
- );
- private $kolab2_gender = array(0 => 'male', 1 => 'female');
-
/**
* Default constructor
*/
function __construct($xmldata = null, $version = 3.0)
{
parent::__construct($xmldata, $version);
// complete phone types
$this->phonetypes['homefax'] |= Telephone::Home;
$this->phonetypes['workfax'] |= Telephone::Work;
}
/**
* Set contact properties to the kolabformat object
*
* @param array Contact data as hash array
*/
public function set(&$object)
{
$this->init();
// set some automatic values if missing
if (false && !$this->obj->created()) {
if (!empty($object['created']))
$object['created'] = new DateTime('now', self::$timezone);
$this->obj->setCreated(self::get_datetime($object['created']));
}
if (!empty($object['uid']))
$this->obj->setUid($object['uid']);
$object['changed'] = new DateTime('now', self::$timezone);
$this->obj->setLastModified(self::get_datetime($object['changed'], new DateTimeZone('UTC')));
// do the hard work of setting object values
$nc = new NameComponents;
$nc->setSurnames(self::array2vector($object['surname']));
$nc->setGiven(self::array2vector($object['firstname']));
$nc->setAdditional(self::array2vector($object['middlename']));
$nc->setPrefixes(self::array2vector($object['prefix']));
$nc->setSuffixes(self::array2vector($object['suffix']));
$this->obj->setNameComponents($nc);
$this->obj->setName($object['name']);
if (isset($object['nickname']))
$this->obj->setNickNames(self::array2vector($object['nickname']));
if (isset($object['profession']))
$this->obj->setTitles(self::array2vector($object['profession']));
// organisation related properties (affiliation)
$org = new Affiliation;
$offices = new vectoraddress;
if ($object['organization'])
$org->setOrganisation($object['organization']);
if ($object['department'])
$org->setOrganisationalUnits(self::array2vector($object['department']));
if ($object['jobtitle'])
$org->setRoles(self::array2vector($object['jobtitle']));
$rels = new vectorrelated;
if ($object['manager']) {
foreach ((array)$object['manager'] as $manager)
$rels->push(new Related(Related::Text, $manager, Related::Manager));
}
if ($object['assistant']) {
foreach ((array)$object['assistant'] as $assistant)
$rels->push(new Related(Related::Text, $assistant, Related::Assistant));
}
$org->setRelateds($rels);
// email, im, url
$this->obj->setEmailAddresses(self::array2vector($object['email']));
$this->obj->setIMaddresses(self::array2vector($object['im']));
$vurls = new vectorurl;
foreach ((array)$object['website'] as $url) {
$type = $url['type'] == 'blog' ? Url::Blog : Url::NoType;
$vurls->push(new Url($url['url'], $type));
}
$this->obj->setUrls($vurls);
// addresses
$adrs = new vectoraddress;
foreach ((array)$object['address'] as $address) {
$adr = new Address;
$type = $this->addresstypes[$address['type']];
if (isset($type))
$adr->setTypes($type);
else if ($address['type'])
$adr->setLabel($address['type']);
if ($address['street'])
$adr->setStreet($address['street']);
if ($address['locality'])
$adr->setLocality($address['locality']);
if ($address['code'])
$adr->setCode($address['code']);
if ($address['region'])
$adr->setRegion($address['region']);
if ($address['country'])
$adr->setCountry($address['country']);
if ($address['type'] == 'office')
$offices->push($adr);
else
$adrs->push($adr);
}
$this->obj->setAddresses($adrs);
$org->setAddresses($offices);
// add org affiliation after addresses are set
$orgs = new vectoraffiliation;
$orgs->push($org);
$this->obj->setAffiliations($orgs);
// telephones
$tels = new vectortelephone;
foreach ((array)$object['phone'] as $phone) {
$tel = new Telephone;
if (isset($this->phonetypes[$phone['type']]))
$tel->setTypes($this->phonetypes[$phone['type']]);
$tel->setNumber($phone['number']);
$tels->push($tel);
}
$this->obj->setTelephones($tels);
if (isset($object['gender']))
$this->obj->setGender($this->gendermap[$object['gender']] ? $this->gendermap[$object['gender']] : Contact::NotSet);
if (isset($object['notes']))
$this->obj->setNote($object['notes']);
if (isset($object['freebusyurl']))
$this->obj->setFreeBusyUrl($object['freebusyurl']);
if (isset($object['birthday']))
$this->obj->setBDay(self::get_datetime($object['birthday'], false, true));
if (isset($object['anniversary']))
$this->obj->setAnniversary(self::get_datetime($object['anniversary'], false, true));
if (!empty($object['photo'])) {
if ($type = rcube_mime::image_content_type($object['photo']))
$this->obj->setPhoto($object['photo'], $type);
}
else if (isset($object['photo']))
$this->obj->setPhoto('','');
else if ($this->obj->photoMimetype()) // load saved photo for caching
$object['photo'] = $this->obj->photo();
// spouse and children are relateds
$rels = new vectorrelated;
if ($object['spouse']) {
$rels->push(new Related(Related::Text, $object['spouse'], Related::Spouse));
}
if ($object['children']) {
foreach ((array)$object['children'] as $child)
$rels->push(new Related(Related::Text, $child, Related::Child));
}
$this->obj->setRelateds($rels);
// insert/replace crypto keys
$pgp_index = $pkcs7_index = -1;
$keys = $this->obj->keys();
for ($i=0; $i < $keys->size(); $i++) {
$key = $keys->get($i);
if ($pgp_index < 0 && $key->type() == Key::PGP)
$pgp_index = $i;
else if ($pkcs7_index < 0 && $key->type() == Key::PKCS7_MIME)
$pkcs7_index = $i;
}
$pgpkey = $object['pgppublickey'] ? new Key($object['pgppublickey'], Key::PGP) : new Key();
$pkcs7key = $object['pkcs7publickey'] ? new Key($object['pkcs7publickey'], Key::PKCS7_MIME) : new Key();
if ($pgp_index >= 0)
$keys->set($pgp_index, $pgpkey);
else if (!empty($object['pgppublickey']))
$keys->push($pgpkey);
if ($pkcs7_index >= 0)
$keys->set($pkcs7_index, $pkcs7key);
else if (!empty($object['pkcs7publickey']))
$keys->push($pkcs7key);
$this->obj->setKeys($keys);
// TODO: handle language, gpslocation, etc.
// cache this data
$this->data = $object;
unset($this->data['_formatobj']);
}
/**
*
*/
public function is_valid()
{
return $this->data || (is_object($this->obj) && $this->obj->uid() /*$this->obj->isValid()*/);
}
/**
* Convert the Contact object into a hash array data structure
*
* @return array Contact data as hash array
*/
public function to_array()
{
// return cached result
if (!empty($this->data))
return $this->data;
$this->init();
// read object properties into local data object
$object = array(
'uid' => $this->obj->uid(),
'name' => $this->obj->name(),
'changed' => self::php_datetime($this->obj->lastModified()),
);
$nc = $this->obj->nameComponents();
$object['surname'] = join(' ', self::vector2array($nc->surnames()));
$object['firstname'] = join(' ', self::vector2array($nc->given()));
$object['middlename'] = join(' ', self::vector2array($nc->additional()));
$object['prefix'] = join(' ', self::vector2array($nc->prefixes()));
$object['suffix'] = join(' ', self::vector2array($nc->suffixes()));
$object['nickname'] = join(' ', self::vector2array($this->obj->nickNames()));
$object['profession'] = join(' ', self::vector2array($this->obj->titles()));
// organisation related properties (affiliation)
$orgs = $this->obj->affiliations();
if ($orgs->size()) {
$org = $orgs->get(0);
$object['organization'] = $org->organisation();
$object['jobtitle'] = join(' ', self::vector2array($org->roles()));
$object['department'] = join(' ', self::vector2array($org->organisationalUnits()));
$this->read_relateds($org->relateds(), $object);
}
$object['email'] = self::vector2array($this->obj->emailAddresses());
$object['im'] = self::vector2array($this->obj->imAddresses());
$urls = $this->obj->urls();
for ($i=0; $i < $urls->size(); $i++) {
$url = $urls->get($i);
$subtype = $url->type() == Url::Blog ? 'blog' : 'homepage';
$object['website'][] = array('url' => $url->url(), 'type' => $subtype);
}
// addresses
$this->read_addresses($this->obj->addresses(), $object);
if ($org && ($offices = $org->addresses()))
$this->read_addresses($offices, $object, 'office');
// telehones
$tels = $this->obj->telephones();
$teltypes = array_flip($this->phonetypes);
for ($i=0; $i < $tels->size(); $i++) {
$tel = $tels->get($i);
$object['phone'][] = array('number' => $tel->number(), 'type' => $teltypes[$tel->types()]);
}
$object['notes'] = $this->obj->note();
$object['freebusyurl'] = $this->obj->freeBusyUrl();
if ($bday = self::php_datetime($this->obj->bDay()))
$object['birthday'] = $bday->format('c');
if ($anniversary = self::php_datetime($this->obj->anniversary()))
$object['anniversary'] = $anniversary->format('c');
$gendermap = array_flip($this->gendermap);
if (($g = $this->obj->gender()) && $gendermap[$g])
$object['gender'] = $gendermap[$g];
if ($this->obj->photoMimetype())
$object['photo'] = $this->obj->photo();
else if ($this->xmlobject && ($photo_name = $this->xmlobject->pictureAttachmentName()))
$object['photo'] = $photo_name;
// relateds -> spouse, children
$this->read_relateds($this->obj->relateds(), $object);
// crypto settings: currently only key values are supported
$keys = $this->obj->keys();
for ($i=0; is_object($keys) && $i < $keys->size(); $i++) {
$key = $keys->get($i);
if ($key->type() == Key::PGP)
$object['pgppublickey'] = $key->key();
else if ($key->type() == Key::PKCS7_MIME)
$object['pkcs7publickey'] = $key->key();
}
$this->data = $object;
return $this->data;
}
/**
* Callback for kolab_storage_cache to get words to index for fulltext search
*
* @return array List of words to save in cache
*/
public function get_words()
{
$data = '';
foreach (self::$fulltext_cols as $col) {
$val = is_array($this->data[$col]) ? join(' ', $this->data[$col]) : $this->data[$col];
if (strlen($val))
$data .= $val . ' ';
}
return array_unique(rcube_utils::normalize_string($data, true));
}
- /**
- * Load data from old Kolab2 format
- *
- * @param array Hash array with object properties
- */
- public function fromkolab2($record)
- {
- $object = array(
- 'uid' => $record['uid'],
- 'email' => array(),
- 'phone' => array(),
- );
-
- foreach ($this->kolab2_fieldmap as $kolab => $rcube) {
- if (is_array($record[$kolab]) || strlen($record[$kolab]))
- $object[$rcube] = $record[$kolab];
- }
-
- if (isset($record['gender']))
- $object['gender'] = $this->kolab2_gender[$record['gender']];
-
- foreach ((array)$record['email'] as $i => $email)
- $object['email'][] = $email['smtp-address'];
-
- if (!$record['email'] && $record['emails'])
- $object['email'] = preg_split('/,\s*/', $record['emails']);
-
- if (is_array($record['address'])) {
- foreach ($record['address'] as $i => $adr) {
- $object['address'][] = array(
- 'type' => $this->kolab2_addresstypes[$adr['type']] ? $this->kolab2_addresstypes[$adr['type']] : $adr['type'],
- 'street' => $adr['street'],
- 'locality' => $adr['locality'],
- 'code' => $adr['postal-code'],
- 'region' => $adr['region'],
- 'country' => $adr['country'],
- );
- }
- }
-
- // office location goes into an address block
- if ($record['office-location'])
- $object['address'][] = array('type' => 'office', 'locality' => $record['office-location']);
-
- // merge initials into nickname
- if ($record['initials'])
- $object['nickname'] = trim($object['nickname'] . ', ' . $record['initials'], ', ');
-
- // remove empty fields
- $this->data = array_filter($object);
- }
-
/**
* Helper method to copy contents of an Address vector to the contact data object
*/
private function read_addresses($addresses, &$object, $type = null)
{
$adrtypes = array_flip($this->addresstypes);
for ($i=0; $i < $addresses->size(); $i++) {
$adr = $addresses->get($i);
$object['address'][] = array(
'type' => $type ? $type : ($adrtypes[$adr->types()] ? $adrtypes[$adr->types()] : ''), /*$adr->label()),*/
'street' => $adr->street(),
'code' => $adr->code(),
'locality' => $adr->locality(),
'region' => $adr->region(),
'country' => $adr->country()
);
}
}
/**
* Helper method to map contents of a Related vector to the contact data object
*/
private function read_relateds($rels, &$object)
{
$typemap = array_flip($this->relatedmap);
for ($i=0; $i < $rels->size(); $i++) {
$rel = $rels->get($i);
if ($rel->type() != Related::Text) // we can't handle UID relations yet
continue;
$types = $rel->relationTypes();
foreach ($typemap as $t => $field) {
if ($types & $t) {
$object[$field][] = $rel->text();
break;
}
}
}
}
}
diff --git a/plugins/libkolab/lib/kolab_format_distributionlist.php b/plugins/libkolab/lib/kolab_format_distributionlist.php
index ba54742b..5622fc55 100644
--- a/plugins/libkolab/lib/kolab_format_distributionlist.php
+++ b/plugins/libkolab/lib/kolab_format_distributionlist.php
@@ -1,143 +1,120 @@
<?php
/**
* Kolab Distribution List model class
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_format_distributionlist extends kolab_format
{
public $CTYPE = 'application/vcard+xml';
public $CTYPEv2 = 'application/x-vnd.kolab.distribution-list';
protected $objclass = 'DistList';
protected $read_func = 'readDistlist';
protected $write_func = 'writeDistlist';
/**
* Set properties to the kolabformat object
*
* @param array Object data as hash array
*/
public function set(&$object)
{
$this->init();
// set some automatic values if missing
if (!empty($object['uid']))
$this->obj->setUid($object['uid']);
$object['changed'] = new DateTime('now', self::$timezone);
$this->obj->setLastModified(self::get_datetime($object['changed'], new DateTimeZone('UTC')));
$this->obj->setName($object['name']);
$seen = array();
$members = new vectorcontactref;
foreach ((array)$object['member'] as $member) {
if ($member['uid'])
$m = new ContactReference(ContactReference::UidReference, $member['uid']);
else if ($member['email'])
$m = new ContactReference(ContactReference::EmailReference, $member['email']);
else
continue;
$m->setName($member['name']);
$members->push($m);
$seen[$member['email']]++;
}
$this->obj->setMembers($members);
// set type property for proper caching
$object['_type'] = 'distribution-list';
// cache this data
$this->data = $object;
unset($this->data['_formatobj']);
}
public function is_valid()
{
return $this->data || (is_object($this->obj) && $this->obj->isValid());
}
- /**
- * Load data from old Kolab2 format
- */
- public function fromkolab2($record)
- {
- $object = array(
- 'uid' => $record['uid'],
- 'changed' => $record['last-modification-date'],
- 'name' => $record['last-name'],
- 'member' => array(),
- );
-
- foreach ((array)$record['member'] as $member) {
- $object['member'][] = array(
- 'email' => $member['smtp-address'],
- 'name' => $member['display-name'],
- 'uid' => $member['uid'],
- );
- }
-
- $this->data = $object;
- }
-
/**
* Convert the Distlist object into a hash array data structure
*
* @return array Distribution list data as hash array
*/
public function to_array()
{
// return cached result
if (!empty($this->data))
return $this->data;
$this->init();
// read object properties
$object = array(
'uid' => $this->obj->uid(),
'changed' => self::php_datetime($this->obj->lastModified()),
'name' => $this->obj->name(),
'member' => array(),
'_type' => 'distribution-list',
);
$members = $this->obj->members();
for ($i=0; $i < $members->size(); $i++) {
$member = $members->get($i);
# if ($member->type() == ContactReference::UidReference && ($uid = $member->uid()))
$object['member'][] = array(
'uid' => $member->uid(),
'email' => $member->email(),
'name' => $member->name(),
);
}
$this->data = $object;
return $this->data;
}
}
diff --git a/plugins/libkolab/lib/kolab_format_event.php b/plugins/libkolab/lib/kolab_format_event.php
index bcd6de1d..4ef6735f 100644
--- a/plugins/libkolab/lib/kolab_format_event.php
+++ b/plugins/libkolab/lib/kolab_format_event.php
@@ -1,320 +1,185 @@
<?php
/**
* Kolab Event model class
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_format_event extends kolab_format_xcal
{
public $CTYPEv2 = 'application/x-vnd.kolab.event';
protected $objclass = 'Event';
protected $read_func = 'readEvent';
protected $write_func = 'writeEvent';
- private $kolab2_rolemap = array(
- 'required' => 'REQ-PARTICIPANT',
- 'optional' => 'OPT-PARTICIPANT',
- 'resource' => 'CHAIR',
- );
- private $kolab2_statusmap = array(
- 'none' => 'NEEDS-ACTION',
- 'tentative' => 'TENTATIVE',
- 'accepted' => 'CONFIRMED',
- 'accepted' => 'ACCEPTED',
- 'declined' => 'DECLINED',
- );
- private $kolab2_monthmap = array('', 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december');
-
/**
* Clones into an instance of libcalendaring's extended EventCal class
*
* @return mixed EventCal object or false on failure
*/
public function to_libcal()
{
static $error_logged = false;
if (class_exists('kolabcalendaring')) {
return new EventCal($this->obj);
}
else if (!$error_logged) {
$error_logged = true;
rcube::raise_error(array(
'code' => 900, 'type' => 'php',
'message' => "required kolabcalendaring module not found"
), true);
}
return false;
}
/**
* Set event properties to the kolabformat object
*
* @param array Event data as hash array
*/
public function set(&$object)
{
$this->init();
// set common xcal properties
parent::set($object);
// do the hard work of setting object values
$this->obj->setStart(self::get_datetime($object['start'], null, $object['allday']));
$this->obj->setEnd(self::get_datetime($object['end'], null, $object['allday']));
$this->obj->setTransparency($object['free_busy'] == 'free');
$status = kolabformat::StatusUndefined;
if ($object['free_busy'] == 'tentative')
$status = kolabformat::StatusTentative;
if ($object['cancelled'])
$status = kolabformat::StatusCancelled;
$this->obj->setStatus($status);
// save attachments
$vattach = new vectorattachment;
foreach ((array)$object['_attachments'] as $cid => $attr) {
if (empty($attr))
continue;
$attach = new Attachment;
$attach->setLabel((string)$attr['name']);
$attach->setUri('cid:' . $cid, $attr['mimetype']);
$vattach->push($attach);
}
$this->obj->setAttachments($vattach);
// cache this data
$this->data = $object;
unset($this->data['_formatobj']);
}
/**
*
*/
public function is_valid()
{
return $this->data || (is_object($this->obj) && $this->obj->isValid() && $this->obj->uid());
}
/**
* Convert the Event object into a hash array data structure
*
* @return array Event data as hash array
*/
public function to_array()
{
// return cached result
if (!empty($this->data))
return $this->data;
$this->init();
// read common xcal props
$object = parent::to_array();
// read object properties
$object += array(
'end' => self::php_datetime($this->obj->end()),
'allday' => $this->obj->start()->isDateOnly(),
'free_busy' => $this->obj->transparency() ? 'free' : 'busy', // TODO: transparency is only boolean
'attendees' => array(),
);
// organizer is part of the attendees list in Roundcube
if ($object['organizer']) {
$object['organizer']['role'] = 'ORGANIZER';
array_unshift($object['attendees'], $object['organizer']);
}
// status defines different event properties...
$status = $this->obj->status();
if ($status == kolabformat::StatusTentative)
$object['free_busy'] = 'tentative';
else if ($status == kolabformat::StatusCancelled)
$objec['cancelled'] = true;
// handle attachments
$vattach = $this->obj->attachments();
for ($i=0; $i < $vattach->size(); $i++) {
$attach = $vattach->get($i);
// skip cid: attachments which are mime message parts handled by kolab_storage_folder
if (substr($attach->uri(), 0, 4) != 'cid:' && $attach->label()) {
$name = $attach->label();
$data = $attach->data();
$object['_attachments'][$name] = array(
'name' => $name,
'mimetype' => $attach->mimetype(),
'size' => strlen($data),
'content' => $data,
);
}
}
$this->data = $object;
return $this->data;
}
/**
* Callback for kolab_storage_cache to get object specific tags to cache
*
* @return array List of tags to save in cache
*/
public function get_tags()
{
$tags = array();
foreach ((array)$this->data['categories'] as $cat) {
$tags[] = rcube_utils::normalize_string($cat);
}
if (!empty($this->data['alarms'])) {
$tags[] = 'x-has-alarms';
}
return $tags;
}
- /**
- * Load data from old Kolab2 format
- */
- public function fromkolab2($rec)
- {
- if (PEAR::isError($rec))
- return;
-
- $start_time = date('H:i:s', $rec['start-date']);
- $allday = $rec['_is_all_day'] || ($start_time == '00:00:00' && $start_time == date('H:i:s', $rec['end-date']));
-
- // in Roundcube all-day events go from 12:00 to 13:00
- if ($allday) {
- $now = new DateTime('now', self::$timezone);
- $gmt_offset = $now->getOffset();
-
- $rec['start-date'] += 12 * 3600;
- $rec['end-date'] -= 11 * 3600;
- $rec['end-date'] -= $gmt_offset - date('Z', $rec['end-date']); // shift times from server's timezone to user's timezone
- $rec['start-date'] -= $gmt_offset - date('Z', $rec['start-date']); // because generated with mktime() in Horde_Kolab_Format_Date::decodeDate()
- // sanity check
- if ($rec['end-date'] <= $rec['start-date'])
- $rec['end-date'] += 86400;
- }
-
- // convert alarm time into internal format
- if ($rec['alarm']) {
- $alarm_value = $rec['alarm'];
- $alarm_unit = 'M';
- if ($rec['alarm'] % 1440 == 0) {
- $alarm_value /= 1440;
- $alarm_unit = 'D';
- }
- else if ($rec['alarm'] % 60 == 0) {
- $alarm_value /= 60;
- $alarm_unit = 'H';
- }
- $alarm_value *= -1;
- }
-
- // convert recurrence rules into internal pseudo-vcalendar format
- if ($recurrence = $rec['recurrence']) {
- $rrule = array(
- 'FREQ' => strtoupper($recurrence['cycle']),
- 'INTERVAL' => intval($recurrence['interval']),
- );
-
- if ($recurrence['range-type'] == 'number')
- $rrule['COUNT'] = intval($recurrence['range']);
- else if ($recurrence['range-type'] == 'date')
- $rrule['UNTIL'] = date_create('@'.$recurrence['range']);
-
- if ($recurrence['day']) {
- $byday = array();
- $prefix = ($rrule['FREQ'] == 'MONTHLY' || $rrule['FREQ'] == 'YEARLY') ? intval($recurrence['daynumber'] ? $recurrence['daynumber'] : 1) : '';
- foreach ($recurrence['day'] as $day)
- $byday[] = $prefix . substr(strtoupper($day), 0, 2);
- $rrule['BYDAY'] = join(',', $byday);
- }
- if ($recurrence['daynumber']) {
- if ($recurrence['type'] == 'monthday' || $recurrence['type'] == 'daynumber')
- $rrule['BYMONTHDAY'] = $recurrence['daynumber'];
- else if ($recurrence['type'] == 'yearday')
- $rrule['BYYEARDAY'] = $recurrence['daynumber'];
- }
- if ($recurrence['month']) {
- $monthmap = array_flip($this->kolab2_monthmap);
- $rrule['BYMONTH'] = strtolower($monthmap[$recurrence['month']]);
- }
-
- if ($recurrence['exclusion']) {
- foreach ((array)$recurrence['exclusion'] as $excl)
- $rrule['EXDATE'][] = date_create($excl . date(' H:i:s', $rec['start-date'])); // use time of event start
- }
- }
-
- $attendees = array();
- if ($rec['organizer']) {
- $attendees[] = array(
- 'role' => 'ORGANIZER',
- 'name' => $rec['organizer']['display-name'],
- 'email' => $rec['organizer']['smtp-address'],
- 'status' => 'ACCEPTED',
- );
- $_attendees .= $rec['organizer']['display-name'] . ' ' . $rec['organizer']['smtp-address'] . ' ';
- }
-
- foreach ((array)$rec['attendee'] as $attendee) {
- $attendees[] = array(
- 'role' => $this->kolab2_rolemap[$attendee['role']],
- 'name' => $attendee['display-name'],
- 'email' => $attendee['smtp-address'],
- 'status' => $this->kolab2_statusmap[$attendee['status']],
- 'rsvp' => $attendee['request-response'],
- );
- $_attendees .= $rec['organizer']['display-name'] . ' ' . $rec['organizer']['smtp-address'] . ' ';
- }
-
- $this->data = array(
- 'uid' => $rec['uid'],
- 'title' => $rec['summary'],
- 'location' => $rec['location'],
- 'description' => $rec['body'],
- 'start' => new DateTime('@'.$rec['start-date']),
- 'end' => new DateTime('@'.$rec['end-date']),
- 'allday' => $allday,
- 'recurrence' => $rrule,
- 'alarms' => $alarm_value . $alarm_unit,
- 'categories' => explode(',', $rec['categories']),
- 'attachments' => $attachments,
- 'attendees' => $attendees,
- 'free_busy' => $rec['show-time-as'],
- 'priority' => $rec['priority'],
- 'sensitivity' => $rec['sensitivity'],
- 'changed' => $rec['last-modification-date'],
- );
-
- // assign current timezone to event start/end
- $this->data['start']->setTimezone(self::$timezone);
- $this->data['end']->setTimezone(self::$timezone);
- }
}
diff --git a/plugins/libkolab/lib/kolab_format_file.php b/plugins/libkolab/lib/kolab_format_file.php
index 1560c46f..b3ab1580 100644
--- a/plugins/libkolab/lib/kolab_format_file.php
+++ b/plugins/libkolab/lib/kolab_format_file.php
@@ -1,174 +1,161 @@
<?php
/**
* Kolab File model class
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
* @author Aleksander Machniak <machniak@kolabsys.com>
*
* Copyright (C) 2012, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_format_file extends kolab_format
{
public $CTYPE = 'application/x-vnd.kolab.file';
protected $read_func = 'kolabformat::readKolabFile';
protected $write_func = 'kolabformat::writeKolabFile';
protected $sensitivity_map = array(
'public' => kolabformat::ClassPublic,
'private' => kolabformat::ClassPrivate,
'confidential' => kolabformat::ClassConfidential,
);
function __construct($xmldata = null)
{
$this->obj = new File;
$this->xmldata = $xmldata;
}
/**
* Set properties to the kolabformat object
*
* @param array Object data as hash array
*/
public function set(&$object)
{
$this->init();
// set some automatic values if missing
if (!empty($object['uid']))
$this->obj->setUid($object['uid']);
$object['changed'] = new DateTime('now', self::$timezone);
$this->obj->setLastModified(self::get_datetime($object['changed'], new DateTimeZone('UTC')));
$this->obj->setClassification($this->sensitivity_map[$object['sensitivity']]);
$this->obj->setCategories(self::array2vector($object['categories']));
if (isset($object['notes'])) {
$this->obj->setNote($object['notes']);
}
// Add file attachment
if (!empty($object['_attachments'])) {
$cid = key($object['_attachments']);
$attach_attr = $object['_attachments'][$cid];
$attach = new Attachment;
$attach->setLabel((string)$attach_attr['name']);
$attach->setUri('cid:' . $cid, $attach_attr['mimetype']);
$this->obj->setFile($attach);
// make sure size is set, so object saved in cache contains this info
if (!isset($attach_attr['size'])) {
if (isset($attach_attr['content'])) {
$object['_attachments'][$cid]['size'] = strlen($attach_attr['content']);
}
else if (isset($attach_attr['path'])) {
$object['_attachments'][$cid]['size'] = @filesize($attach_attr['path']);
}
}
}
// cache this data
$this->data = $object;
unset($this->data['_formatobj']);
}
/**
*
*/
public function is_valid()
{
return $this->data || (is_object($this->obj) && $this->obj->isValid());
}
- /**
- * Load data from old Kolab2 format
- */
- public function fromkolab2($record)
- {
- $object = array(
- 'uid' => $record['uid'],
- 'changed' => $record['last-modification-date'],
- );
-
- $this->data = $object;
- }
-
/**
* Convert the Configuration object into a hash array data structure
*
* @return array Config object data as hash array
*/
public function to_array()
{
// return cached result
if (!empty($this->data))
return $this->data;
$this->init();
$sensitivity_map = array_flip($this->sensitivity_map);
// read object properties
$object = array(
'uid' => $this->obj->uid(),
'created' => self::php_datetime($this->obj->created()),
'changed' => self::php_datetime($this->obj->lastModified()),
'sensitivity' => $sensitivity_map[$this->obj->classification()],
'categories' => self::vector2array($this->obj->categories()),
'notes' => $this->obj->note(),
);
// attachments are mime message parts handled by kolab_storage_folder
// @TODO: handle inline attachments
$this->data = $object;
return $this->data;
}
/**
* Callback for kolab_storage_cache to get object specific tags to cache
*
* @return array List of tags to save in cache
*/
public function get_tags()
{
$tags = array();
foreach ((array)$this->data['categories'] as $cat) {
$tags[] = rcube_utils::normalize_string($cat);
}
return $tags;
}
/**
* Callback for kolab_storage_cache to get words to index for fulltext search
*
* @return array List of words to save in cache
*/
public function get_words()
{
// Store filename in 'words' for fast access to file by name
$attachment = array_shift($this->data['_attachments']);
return array($attachment['name']);
}
}
diff --git a/plugins/libkolab/lib/kolab_format_journal.php b/plugins/libkolab/lib/kolab_format_journal.php
index 9144ea2d..daab1acb 100644
--- a/plugins/libkolab/lib/kolab_format_journal.php
+++ b/plugins/libkolab/lib/kolab_format_journal.php
@@ -1,108 +1,93 @@
<?php
/**
* Kolab Journal model class
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_format_journal extends kolab_format
{
public $CTYPE = 'application/calendar+xml';
public $CTYPEv2 = 'application/x-vnd.kolab.journal';
protected $objclass = 'Journal';
protected $read_func = 'readJournal';
protected $write_func = 'writeJournal';
/**
* Set properties to the kolabformat object
*
* @param array Object data as hash array
*/
public function set(&$object)
{
$this->init();
// set some automatic values if missing
if (!empty($object['uid']))
$this->obj->setUid($object['uid']);
$object['changed'] = new DateTime('now', self::$timezone);
$this->obj->setLastModified(self::get_datetime($object['changed'], new DateTimeZone('UTC')));
// TODO: set object propeties
// cache this data
$this->data = $object;
unset($this->data['_formatobj']);
}
/**
*
*/
public function is_valid()
{
return $this->data || (is_object($this->obj) && $this->obj->isValid());
}
- /**
- * Load data from old Kolab2 format
- */
- public function fromkolab2($record)
- {
- $object = array(
- 'uid' => $record['uid'],
- 'changed' => $record['last-modification-date'],
- );
-
- // TODO: implement this
-
- $this->data = $object;
- }
-
/**
* Convert the Configuration object into a hash array data structure
*
* @return array Config object data as hash array
*/
public function to_array()
{
// return cached result
if (!empty($this->data))
return $this->data;
$this->init();
// read object properties
$object = array(
'uid' => $this->obj->uid(),
'created' => self::php_datetime($this->obj->created()),
'changed' => self::php_datetime($this->obj->lastModified()),
);
// TODO: read object properties
$this->data = $object;
return $this->data;
}
}
diff --git a/plugins/libkolab/lib/kolab_format_note.php b/plugins/libkolab/lib/kolab_format_note.php
index 48e963e1..5af93434 100644
--- a/plugins/libkolab/lib/kolab_format_note.php
+++ b/plugins/libkolab/lib/kolab_format_note.php
@@ -1,107 +1,93 @@
<?php
/**
* Kolab Note model class
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_format_note extends kolab_format
{
public $CTYPE = 'application/x-vnd.kolab.note';
public $CTYPEv2 = 'application/x-vnd.kolab.note';
protected $objclass = 'Note';
protected $read_func = 'readNote';
protected $write_func = 'writeNote';
/**
* Set properties to the kolabformat object
*
* @param array Object data as hash array
*/
public function set(&$object)
{
$this->init();
// set some automatic values if missing
if (!empty($object['uid']))
$this->obj->setUid($object['uid']);
$object['changed'] = new DateTime('now', self::$timezone);
$this->obj->setLastModified(self::get_datetime($object['changed'], new DateTimeZone('UTC')));
// TODO: set object propeties
// cache this data
$this->data = $object;
unset($this->data['_formatobj']);
}
/**
*
*/
public function is_valid()
{
return $this->data || (is_object($this->obj) && $this->obj->isValid());
}
- /**
- * Load data from old Kolab2 format
- */
- public function fromkolab2($record)
- {
- $object = array(
- 'uid' => $record['uid'],
- 'changed' => $record['last-modification-date'],
- );
-
-
- $this->data = $object;
- }
-
/**
* Convert the Configuration object into a hash array data structure
*
* @return array Config object data as hash array
*/
public function to_array()
{
// return cached result
if (!empty($this->data))
return $this->data;
$this->init();
// read object properties
$object = array(
'uid' => $this->obj->uid(),
'created' => self::php_datetime($this->obj->created()),
'changed' => self::php_datetime($this->obj->lastModified()),
);
// TODO: read object properties
$this->data = $object;
return $this->data;
}
}
diff --git a/plugins/libkolab/lib/kolab_format_task.php b/plugins/libkolab/lib/kolab_format_task.php
index 0bfac3dd..77870c71 100644
--- a/plugins/libkolab/lib/kolab_format_task.php
+++ b/plugins/libkolab/lib/kolab_format_task.php
@@ -1,142 +1,127 @@
<?php
/**
* Kolab Task (ToDo) model class
*
* @version @package_version@
* @author Thomas Bruederli <bruederli@kolabsys.com>
*
* Copyright (C) 2012, Kolab Systems AG <contact@kolabsys.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class kolab_format_task extends kolab_format_xcal
{
public $CTYPEv2 = 'application/x-vnd.kolab.task';
protected $objclass = 'Todo';
protected $read_func = 'readTodo';
protected $write_func = 'writeTodo';
/**
* Set properties to the kolabformat object
*
* @param array Object data as hash array
*/
public function set(&$object)
{
$this->init();
// set common xcal properties
parent::set($object);
$this->obj->setPercentComplete(intval($object['complete']));
if (isset($object['start']))
$this->obj->setStart(self::get_datetime($object['start'], null, $object['start']->_dateonly));
$this->obj->setDue(self::get_datetime($object['due'], null, $object['due']->_dateonly));
$related = new vectors;
if (!empty($object['parent_id']))
$related->push($object['parent_id']);
$this->obj->setRelatedTo($related);
// cache this data
$this->data = $object;
unset($this->data['_formatobj']);
}
/**
*
*/
public function is_valid()
{
return $this->data || (is_object($this->obj) && $this->obj->isValid());
}
/**
* Convert the Configuration object into a hash array data structure
*
* @return array Config object data as hash array
*/
public function to_array()
{
// return cached result
if (!empty($this->data))
return $this->data;
$this->init();
// read common xcal props
$object = parent::to_array();
$object['complete'] = intval($this->obj->percentComplete());
// if due date is set
if ($due = $this->obj->due())
$object['due'] = self::php_datetime($due);
// related-to points to parent task; we only support one relation
$related = self::vector2array($this->obj->relatedTo());
if (count($related))
$object['parent_id'] = $related[0];
// TODO: map more properties
$this->data = $object;
return $this->data;
}
- /**
- * Load data from old Kolab2 format
- */
- public function fromkolab2($record)
- {
- $object = array(
- 'uid' => $record['uid'],
- 'changed' => $record['last-modification-date'],
- );
-
- // TODO: implement this
-
- $this->data = $object;
- }
-
/**
* Callback for kolab_storage_cache to get object specific tags to cache
*
* @return array List of tags to save in cache
*/
public function get_tags()
{
$tags = array();
if ($this->data['status'] == 'COMPLETED' || $this->data['complete'] == 100)
$tags[] = 'x-complete';
if ($this->data['priority'] == 1)
$tags[] = 'x-flagged';
if (!empty($this->data['alarms']))
$tags[] = 'x-has-alarms';
if ($this->data['parent_id'])
$tags[] = 'x-parent:' . $this->data['parent_id'];
return $tags;
}
}
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Tue, Jun 10, 8:17 AM (1 d, 16 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
197005
Default Alt Text
(185 KB)
Attached To
Mode
R14 roundcubemail-plugins-kolab
Attached
Detach File
Event Timeline
Log In to Comment