Esempio n. 1
0
VALUE occurrences( VALUE self, VALUE dtstart, VALUE dtend, VALUE rrule ) {
  char * _rrule;
  struct icaltimetype start, end;
  time_t tt;
  VALUE  tv_sec, occurr = rb_ary_new();

  /* Get method ID for Time.tv_sec */
  ID time_tv_sec  = rb_intern( "tv_sec" );
  ID to_string    = rb_intern( "to_string" );

  if( TYPE( rrule ) != T_STRING && rb_respond_to( rrule, to_string ) )
    rrule = rb_funcall( rrule, to_string, 0 );

  Check_Type(rrule, T_STRING);
  _rrule = RSTRING(rrule)->ptr;

  dtstart = to_time( dtstart, "dtstart" );
  dtend   = to_time( dtend,   "dtend" );

  /* Apply .tv_sec to our Time objects (if they are Times ...) */
  tv_sec = rb_funcall( dtstart, time_tv_sec, 0 );
  tt     = NUM2INT( tv_sec );
  start  = icaltime_from_timet( tt, 0 );

  tv_sec = rb_funcall( dtend, time_tv_sec, 0 );
  tt     = NUM2INT( tv_sec );
  end    = icaltime_from_timet( tt, 0 );

  icalerror_clear_errno();
  icalerror_set_error_state( ICAL_MALFORMEDDATA_ERROR, ICAL_ERROR_NONFATAL);

  struct icalrecurrencetype recur = icalrecurrencetype_from_string( _rrule );
  if( icalerrno != ICAL_NO_ERROR ) {
    rb_raise(rb_eArgError, "Malformed RRule");
    return Qnil;
  }

  icalrecur_iterator* ritr = icalrecur_iterator_new( recur, start );

  while(1) {
    struct icaltimetype next = icalrecur_iterator_next(ritr);

    if( icaltime_is_null_time(next) || ( icaltime_compare( next, end ) > 0 ) ) {
      icalrecur_iterator_free(ritr);
      return occurr;
    }

    rb_ary_push( occurr, rb_time_new( icaltime_as_timet( next ), 0 ) );
  };

  icalrecur_iterator_free(ritr);
  return occurr;
}
static void
adjust_dtstart_day_to_rrule (icalcomponent *comp, struct icalrecurrencetype rule)
{
	time_t now, year_start;
	struct icaltimetype start, comp_start, iter_start, itime;
	icalrecur_iterator *iter;

	now = time (NULL);
	itime = icaltime_from_timet (now, 0);
	itime.month = itime.day = 1;
	itime.hour = itime.minute = itime.second = 0;
	year_start = icaltime_as_timet(itime);

	comp_start = icalcomponent_get_dtstart (comp);
	start = icaltime_from_timet (year_start, 0);

	iter = icalrecur_iterator_new (rule, start);
	iter_start = icalrecur_iterator_next (iter);
	icalrecur_iterator_free (iter);

	if (iter_start.day != comp_start.day) {
		comp_start.day = iter_start.day;
		icalcomponent_set_dtstart (comp, comp_start);
	}
}
Esempio n. 3
0
/**
 * @brief
 * 	Get the occurrence as defined by the given recurrence rule,
 * 	index, and start time. This function assumes that the
 * 	time dtsart passed in is the one to start the occurrence from.
 *
 * @par	NOTE: This function should be made reentrant such that
 * 	it can be looped over without having to loop over every occurrence
 * 	over and over again.
 *
 * @param[in] rrule - The recurrence rule as defined by the user
 * @param[in] dtstart - The start time from which to start
 * @param[in] tz - The timezone associated to the recurrence rule
 * @param[in] idx - The index of the occurrence to start counting from
 *
 * @return 	time_t
 * @retval	The date of the next occurrence or -1 if the date exceeds libical's
 * 		Unix time in 2038
 *
 */
time_t
get_occurrence(char *rrule, time_t dtstart, char *tz, int idx)
{


#ifdef LIBICAL
	struct icalrecurrencetype rt;
	struct icaltimetype start;
	icaltimezone *localzone;
	struct icaltimetype next;
	struct icalrecur_iterator_impl *itr;
	int i;
	time_t next_occr = dtstart;

	if (rrule == NULL)
		return dtstart;

	if (tz == NULL)
		return -1;

	icalerror_clear_errno();

	icalerror_set_error_state(ICAL_PARSE_ERROR, ICAL_ERROR_NONFATAL);
#ifdef LIBICAL_API2
    icalerror_set_errors_are_fatal(0);
#else
    icalerror_errors_are_fatal = 0;
#endif
    localzone = icaltimezone_get_builtin_timezone(tz);

	if (localzone == NULL)
		return -1;

	rt = icalrecurrencetype_from_string(rrule);

	start = icaltime_from_timet_with_zone(dtstart, 0, NULL);
	icaltimezone_convert_time(&start, icaltimezone_get_utc_timezone(), localzone);
	next = start;

	itr = (struct icalrecur_iterator_impl*) icalrecur_iterator_new(rt, start);
	/* Skip as many occurrences as specified by idx */
	for (i = 0; i < idx && !icaltime_is_null_time(next); i++)
		next = icalrecur_iterator_next(itr);

	if (!icaltime_is_null_time(next)) {
		icaltimezone_convert_time(&next, localzone,
			icaltimezone_get_utc_timezone());
		next_occr = icaltime_as_timet(next);
	}
	else next_occr = -1; /* If reached end of possible date-time return -1 */

		icalrecur_iterator_free(itr);

	return next_occr;

#else

	return dtstart;
#endif
}
Esempio n. 4
0
/**
 * @brief
 * 	Returns the number of occurrences defined by a recurrence rule.
 *
 * @par	The total number of occurrences is currently limited to a hardcoded
 * 	3 years limit from the current date.
 *
 * @par	NOTE: Determine whether 3 years limit is the right way to go about setting
 * 	a limit on the total number of occurrences.
 *
 * @param[in] rrule - The recurrence rule as defined by the user
 * @param[in] tt - The start time of the first occurrence
 * @param[in] tz - The timezone associated to the recurrence rule
 *
 * @return	int
 * @retval 	the total number of occurrences
 *
 */
int
get_num_occurrences(char *rrule, time_t dtstart, char *tz)
{


#ifdef LIBICAL
	struct icalrecurrencetype rt;
	struct icaltimetype start;
	icaltimezone *localzone;
	struct icaltimetype next;
	struct icalrecur_iterator_impl *itr;
	time_t now;
	time_t date_limit;
	int num_resv = 0;

	/* if any of the argument is NULL, we are dealing with
	 * advance reservation, so return 1 occurrence */
	if (rrule == NULL || tz == NULL)
		return 1;

	icalerror_clear_errno();

	icalerror_set_error_state(ICAL_PARSE_ERROR, ICAL_ERROR_NONFATAL);
	icalerror_errors_are_fatal = 0;
	localzone = icaltimezone_get_builtin_timezone(tz);

	if (localzone == NULL)
		return 0;

	now = time((time_t *)0);
	date_limit = now + DATE_LIMIT;

	rt = icalrecurrencetype_from_string(rrule);

	start = icaltime_from_timet(dtstart, 0);
	icaltimezone_convert_time(&start, icaltimezone_get_utc_timezone(), localzone);

	itr = (struct icalrecur_iterator_impl*) icalrecur_iterator_new(rt, start);

	next = icalrecur_iterator_next(itr);

	/* Compute the total number of occurrences.
	 * Breaks out if the total number of allowed occurrences is exceeded */
	while (!icaltime_is_null_time(next) &&
		(icaltime_as_timet(next) < date_limit)) {
		num_resv++;
		next = icalrecur_iterator_next(itr);
	}
	icalrecur_iterator_free(itr);

	return num_resv;
#else

	if (rrule == NULL)
		return 1;

	return 0;
#endif
}
int main()
{

	const char *rrule = "FREQ=DAILY;UNTIL=20080820T143500Z"; 
	icaltimetype dtstart = icaltime_from_timet(time(0) - (2*24*3600), 0);
	time_t viewend;

	struct icalrecurrencetype recur;
	time_t utc_tim;
	time_t dtst_utc;
	bool loopexit = false;

	recur = icalrecurrencetype_from_string(rrule);

	printf ("date is given by %d:%d:%d\n\n", dtstart.year, dtstart.month, dtstart.day);
	
	dtst_utc = icaltime_as_timet(dtstart);
	icalrecur_iterator *ritr;
	ritr = icalrecur_iterator_new(recur, dtstart);


	struct icaltimetype next;
	next = icalrecur_iterator_next(ritr);

	while ((!icaltime_is_null_time(next)) && (!loopexit)) {

		utc_tim = icaltime_as_timet(next);

		if (time (0) < utc_tim)
		{
			printf ("Recurrent time : %s\n", ctime(&utc_tim));
			loopexit = true;
		}

		next = icalrecur_iterator_next(ritr);
	}

	icalrecur_iterator_free(ritr);
}
Esempio n. 6
0
/**
 * e_cal_util_split_at_instance:
 * @icalcomp: A (recurring) #icalcomponent
 * @rid: The base RECURRENCE-ID to remove
 * @master_dtstart: The DTSTART of the master object
 *
 * Splits a recurring @icalcomp into two at time @rid. The returned icalcomponent
 * is modified @icalcomp which contains recurrences beginning at @rid, inclusive.
 * The instance identified by @rid should exist. The @master_dtstart can be
 * a null time, then it is read from the @icalcomp.
 *
 * Use e_cal_util_remove_instances() with E_CAL_OBJ_MOD_THIS_AND_FUTURE mode
 * on the @icalcomp to remove the overlapping interval from it, if needed.
 *
 * Returns: the split icalcomponent, or %NULL.
 *
 * Since: 3.16
 **/
icalcomponent *
e_cal_util_split_at_instance (icalcomponent *icalcomp,
			      struct icaltimetype rid,
			      struct icaltimetype master_dtstart)
{
	icalproperty *prop;
	struct instance_data instance;
	struct icaltimetype start, end;
	struct icaldurationtype duration;
	GSList *remove_props = NULL, *link;

	g_return_val_if_fail (icalcomp != NULL, NULL);
	g_return_val_if_fail (!icaltime_is_null_time (rid), NULL);

	/* Make sure this is really recurring */
	if (!icalcomponent_get_first_property (icalcomp, ICAL_RRULE_PROPERTY) &&
	    !icalcomponent_get_first_property (icalcomp, ICAL_RDATE_PROPERTY))
		return NULL;

	/* Make sure the specified instance really exists */
	start = icaltime_convert_to_zone (rid, icaltimezone_get_utc_timezone ());
	end = start;
	icaltime_adjust (&end, 0, 0, 0, 1);

	instance.start = icaltime_as_timet (start);
	instance.found = FALSE;
	icalcomponent_foreach_recurrence (icalcomp, start, end,
					  check_instance, &instance);
	/* Make the copy */
	icalcomp = icalcomponent_new_clone (icalcomp);

	e_cal_util_remove_instances_ex (icalcomp, rid, E_CAL_OBJ_MOD_THIS_AND_PRIOR, TRUE, FALSE);

	start = rid;
	if (icaltime_is_null_time (master_dtstart))
		master_dtstart = icalcomponent_get_dtstart (icalcomp);
	duration = icalcomponent_get_duration (icalcomp);

	/* Expect that DTSTART and DTEND are already set when the instance could not be found */
	if (instance.found) {
		icalcomponent_set_dtstart (icalcomp, start);
		/* Update either DURATION or DTEND */
		if (icaltime_is_null_time (icalcomponent_get_dtend (icalcomp))) {
			icalcomponent_set_duration (icalcomp, duration);
		} else {
			end = start;
			if (duration.is_neg)
				icaltime_adjust (&end, -duration.days - 7 * duration.weeks, -duration.hours, -duration.minutes, -duration.seconds);
			else
				icaltime_adjust (&end, duration.days + 7 * duration.weeks, duration.hours, duration.minutes, duration.seconds);
			icalcomponent_set_dtend (icalcomp, end);
		}
	}

	/* any RRULE with 'count' should be shortened */
	for (prop = icalcomponent_get_first_property (icalcomp, ICAL_RRULE_PROPERTY);
	     prop;
	     prop = icalcomponent_get_next_property (icalcomp, ICAL_RRULE_PROPERTY)) {
		struct icaltimetype recur;
		struct icalrecurrencetype rule;

		rule = icalproperty_get_rrule (prop);

		if (rule.count != 0) {
			gint occurrences_count = 0;
			icalrecur_iterator *iter;

			iter = icalrecur_iterator_new (rule, master_dtstart);
			while (recur = icalrecur_iterator_next (iter), !icaltime_is_null_time (recur) && occurrences_count < rule.count) {
				if (icaltime_compare (recur, rid) >= 0)
					break;

				occurrences_count++;
			}

			icalrecur_iterator_free (iter);

			if (icaltime_is_null_time (recur)) {
				remove_props = g_slist_prepend (remove_props, prop);
			} else {
				rule.count -= occurrences_count;
				icalproperty_set_rrule (prop, rule);
				icalproperty_remove_parameter_by_name (prop, "X-EVOLUTION-ENDDATE");
			}
		}
	}

	for (link = remove_props; link; link = g_slist_next (link)) {
		prop = link->data;

		icalcomponent_remove_property (icalcomp, prop);
	}

	g_slist_free (remove_props);

	return icalcomp;
}
Esempio n. 7
0
static void
e_cal_util_remove_instances_ex (icalcomponent *icalcomp,
				struct icaltimetype rid,
				ECalObjModType mod,
				gboolean keep_rid,
				gboolean can_add_exrule)
{
	icalproperty *prop;
	struct icaltimetype itt, recur;
	struct icalrecurrencetype rule;
	icalrecur_iterator *iter;
	GSList *remove_props = NULL, *rrules = NULL, *link;

	g_return_if_fail (icalcomp != NULL);
	g_return_if_fail (mod != E_CAL_OBJ_MOD_ALL);

	/* First remove RDATEs and EXDATEs in the indicated range. */
	for (prop = icalcomponent_get_first_property (icalcomp, ICAL_RDATE_PROPERTY);
	     prop;
	     prop = icalcomponent_get_next_property (icalcomp, ICAL_RDATE_PROPERTY)) {
		struct icaldatetimeperiodtype period;

		period = icalproperty_get_rdate (prop);
		if (time_matches_rid (period.time, rid, mod) && (!keep_rid ||
		    icaltime_compare (period.time, rid) != 0))
			remove_props = g_slist_prepend (remove_props, prop);
	}
	for (prop = icalcomponent_get_first_property (icalcomp, ICAL_EXDATE_PROPERTY);
	     prop;
	     prop = icalcomponent_get_next_property (icalcomp, ICAL_EXDATE_PROPERTY)) {
		itt = icalproperty_get_exdate (prop);
		if (time_matches_rid (itt, rid, mod) && (!keep_rid ||
		    icaltime_compare (itt, rid) != 0))
			remove_props = g_slist_prepend (remove_props, prop);
	}

	for (link = remove_props; link; link = g_slist_next (link)) {
		prop = link->data;

		icalcomponent_remove_property (icalcomp, prop);
	}

	g_slist_free (remove_props);
	remove_props = NULL;

	/* If we're only removing one instance, just add an EXDATE. */
	if (mod == E_CAL_OBJ_MOD_THIS) {
		prop = icalproperty_new_exdate (rid);
		icalcomponent_add_property (icalcomp, prop);
		return;
	}

	/* Otherwise, iterate through RRULEs */
	/* FIXME: this may generate duplicate EXRULEs */
	for (prop = icalcomponent_get_first_property (icalcomp, ICAL_RRULE_PROPERTY);
	     prop;
	     prop = icalcomponent_get_next_property (icalcomp, ICAL_RRULE_PROPERTY)) {
		rrules = g_slist_prepend (rrules, prop);
	}

	for (link = rrules; link; link = g_slist_next (link)) {
		prop = link->data;
		rule = icalproperty_get_rrule (prop);

		iter = icalrecur_iterator_new (rule, rid);
		recur = icalrecur_iterator_next (iter);

		if (mod & E_CAL_OBJ_MOD_THIS_AND_FUTURE) {
			/* Truncate the rule at rid. */
			if (!icaltime_is_null_time (recur)) {
				/* Use count if it was used */
				if (rule.count > 0) {
					gint occurrences_count = 0;
					icalrecur_iterator *count_iter;
					struct icaltimetype count_recur;

					count_iter = icalrecur_iterator_new (rule, icalcomponent_get_dtstart (icalcomp));
					while (count_recur = icalrecur_iterator_next (count_iter), !icaltime_is_null_time (count_recur) && occurrences_count < rule.count) {
						if (icaltime_compare (count_recur, rid) >= 0)
							break;

						occurrences_count++;
					}

					icalrecur_iterator_free (count_iter);

					if (keep_rid && icaltime_compare (count_recur, rid) == 0)
						occurrences_count++;

					/* The caller should make sure that the remove will keep at least one instance */
					g_warn_if_fail (occurrences_count > 0);

					rule.count = occurrences_count;
				} else {
					if (keep_rid && icaltime_compare (recur, rid) == 0)
						rule.until = icaltime_add (rid, icalcomponent_get_duration (icalcomp));
					else
						rule.until = rid;
					icaltime_adjust (&rule.until, 0, 0, 0, -1);
				}

				icalproperty_set_rrule (prop, rule);
				icalproperty_remove_parameter_by_name (prop, "X-EVOLUTION-ENDDATE");
			}
		} else {
			/* (If recur == rid, skip to the next occurrence) */
			if (!keep_rid && icaltime_compare (recur, rid) == 0)
				recur = icalrecur_iterator_next (iter);

			/* If there is a recurrence after rid, add
			 * an EXRULE to block instances up to rid.
			 * Otherwise, just remove the RRULE.
			 */
			if (!icaltime_is_null_time (recur)) {
				if (can_add_exrule) {
					rule.count = 0;
					/* iCalendar says we should just use rid
					 * here, but Outlook/Exchange handle
					 * UNTIL incorrectly.
					 */
					if (keep_rid && icaltime_compare (recur, rid) == 0) {
						struct icaldurationtype duration = icalcomponent_get_duration (icalcomp);
						duration.is_neg = !duration.is_neg;
						rule.until = icaltime_add (rid, duration);
					} else
						rule.until = icaltime_add (rid, icalcomponent_get_duration (icalcomp));
					prop = icalproperty_new_exrule (rule);
					icalcomponent_add_property (icalcomp, prop);
				}
			} else {
				remove_props = g_slist_prepend (remove_props, prop);
			}
		}

		icalrecur_iterator_free (iter);
	}

	for (link = remove_props; link; link = g_slist_next (link)) {
		prop = link->data;

		icalcomponent_remove_property (icalcomp, prop);
	}

	g_slist_free (remove_props);
	g_slist_free (rrules);
}
Esempio n. 8
0
void test_recur_file()
{
    icalset *cin = 0;
    struct icaltimetype next;
    icalcomponent *itr;
    icalproperty *desc, *dtstart, *rrule;
    struct icalrecurrencetype recur;
    icalrecur_iterator* ritr;
    time_t tt;
    char* file; 
    int num_recurs_found = 0;
    icalfileset_options options = {O_RDONLY, 0644, 0};
	
    icalerror_set_error_state(ICAL_PARSE_ERROR, ICAL_ERROR_NONFATAL);
	
#ifndef WIN32
    signal(SIGALRM,sig_alrm);
#endif
    file = getenv("ICAL_RECUR_FILE");
    if (!file)
      file = TEST_DATADIR "/recur.txt";
	
#ifndef WIN32
    alarm(15); /* to get file lock */
#endif
    cin = icalset_new(ICAL_FILE_SET, file, &options);
#ifndef WIN32
    alarm(0);
#endif
	
    ok("opening file with recurring events", (cin!=NULL));
    assert(cin!=NULL);
	
    for (itr = icalfileset_get_first_component(cin);
	itr != 0;
	itr = icalfileset_get_next_component(cin)){
      int badcomp = 0;
      int expected_events = 0;
      char msg[128];


      struct icaltimetype start = icaltime_null_time();
      struct icaltimetype startmin = icaltime_from_timet(1,0);
      struct icaltimetype endmax = icaltime_null_time();
      const char *desc_str = "malformed component";

      desc = icalcomponent_get_first_property(itr,ICAL_DESCRIPTION_PROPERTY);
      dtstart = icalcomponent_get_first_property(itr,ICAL_DTSTART_PROPERTY);
      rrule = icalcomponent_get_first_property(itr,ICAL_RRULE_PROPERTY);
      if (desc) {
	desc_str = icalproperty_get_description(desc);
      }
      
      ok((char*)desc_str, !(desc == 0 || dtstart == 0 || rrule == 0));

      if (desc == 0 || dtstart == 0 || rrule == 0) {
	badcomp = 1;
	if (VERBOSE) {
	  printf("\n******** Error in input component ********\n");
	  printf("The following component is malformed:\n %s\n", desc_str);
	}
	continue;
      }
      if (VERBOSE) {
	printf("\n\n#### %s\n",desc_str);
	printf("#### %s\n",icalvalue_as_ical_string(icalproperty_get_value(rrule)));
      }
      
      recur = icalproperty_get_rrule(rrule);
      start = icalproperty_get_dtstart(dtstart);
      
      ritr = icalrecur_iterator_new(recur,start);
      
      tt = icaltime_as_timet(start);
      
      if (VERBOSE)
	printf("#### %s\n",ctime(&tt ));
      
      icalrecur_iterator_free(ritr);
      
      for(ritr = icalrecur_iterator_new(recur,start),
	    next = icalrecur_iterator_next(ritr); 
	  !icaltime_is_null_time(next);
	  next = icalrecur_iterator_next(ritr)){
	
	tt = icaltime_as_timet(next);
	
	if (VERBOSE)
	  printf("  %s",ctime(&tt ));		
	
      }

      icalrecur_iterator_free(ritr);
      num_recurs_found = 0;
      expected_events = get_expected_numevents(itr);

      icalcomponent_foreach_recurrence(itr, startmin, endmax, 
				       recur_callback, &num_recurs_found);
      
      sprintf(msg,"   expecting total of %d events", expected_events);
      int_is(msg, num_recurs_found, expected_events);
    }
    
    icalset_free(cin);
}
Esempio n. 9
0
icalcomponent *icalbdbsetiter_to_next(icalset *set, icalsetiter *i)
{
    icalcomponent *comp = NULL;
    struct icaltimetype start, next;
    icalproperty *dtstart, *rrule, *prop, *due;
    struct icalrecurrencetype recur;
    icaltimezone *u_zone;
    int g = 0;
    int orig_time_was_utc = 0;

    _unused(set);

    do {

        /* no pending occurrence, read the next component */
        if (i->last_component == NULL) {
            comp = icalcompiter_next(&(i->iter));
        } else {
            comp = i->last_component;
        }

        /* no next component, simply return */
        if (comp == 0) {
            return NULL;
        }
        if (i->gauge == 0) {
            return comp;
        }

        /* finding the next matched component and return it to the caller */

        rrule = icalcomponent_get_first_property(comp, ICAL_RRULE_PROPERTY);
        g = icalgauge_get_expand(i->gauge);

        /* a recurring component with expand query */
        if (rrule != 0 && g == 1) {

            u_zone = icaltimezone_get_builtin_timezone(i->tzid);

            /* use UTC, if that's all we have. */
            if (!u_zone) {
                u_zone = icaltimezone_get_utc_timezone();
            }

            recur = icalproperty_get_rrule(rrule);
            start = icaltime_from_timet(time(0), 0);

            if (icalcomponent_isa(comp) == ICAL_VEVENT_COMPONENT) {
                dtstart = icalcomponent_get_first_property(comp, ICAL_DTSTART_PROPERTY);
                if (dtstart) {
                    start = icalproperty_get_dtstart(dtstart);
                }
            } else if (icalcomponent_isa(comp) == ICAL_VTODO_COMPONENT) {
                due = icalcomponent_get_first_property(comp, ICAL_DUE_PROPERTY);
                if (due) {
                    start = icalproperty_get_due(due);
                }
            }

            /* Convert to the user's timezone in order to be able to compare
             * the results from the rrule iterator. */
            if (icaltime_is_utc(start)) {
                start = icaltime_convert_to_zone(start, u_zone);
                orig_time_was_utc = 1;
            }

            if (i->ritr == NULL) {
                i->ritr = icalrecur_iterator_new(recur, start);
                next = icalrecur_iterator_next(i->ritr);
                i->last_component = comp;
            } else {
                next = icalrecur_iterator_next(i->ritr);
                if (icaltime_is_null_time(next)) {
                    i->last_component = NULL;
                    icalrecur_iterator_free(i->ritr);
                    i->ritr = NULL;
                    /* no more occurrence, should go to get next component */
                    continue;
                } else {
                    i->last_component = comp;
                }
            }

            /* if it is excluded, do next one */
            if (icalproperty_recurrence_is_excluded(comp, &start, &next)) {
                next = icalrecur_iterator_next(i->ritr);
                continue;
            }

            /* set recurrence-id value to the property if the property already exist;
             * add the recurrence id property and the value if the property does not exist */
            prop = icalcomponent_get_first_property(comp, ICAL_RECURRENCEID_PROPERTY);
            if (prop == 0) {
                icalcomponent_add_property(comp, icalproperty_new_recurrenceid(next));
            } else {
                icalproperty_set_recurrenceid(prop, next);
            }

            if (orig_time_was_utc) {
                next = icaltime_convert_to_zone(next, icaltimezone_get_utc_timezone());
            }
        }
        /* end of recurring event with expand query */
        if (comp != 0 && (i->gauge == 0 || icalgauge_compare(i->gauge, comp) == 1)) {
            /* found a matched, return it */
            return comp;
        }
    } while (comp != 0);

    return NULL;        /*unreachable */
}
Esempio n. 10
0
icalcomponent *icalbdbset_form_a_matched_recurrence_component(icalsetiter *itr)
{
    icalcomponent *comp = NULL;
    struct icaltimetype start, next;
    icalproperty *dtstart, *rrule, *prop, *due;
    struct icalrecurrencetype recur;
    icaltimezone *u_zone;
    int orig_time_was_utc = 0;

    comp = itr->last_component;

    if (comp == NULL || itr->gauge == NULL) {
        return NULL;
    }

    rrule = icalcomponent_get_first_property(comp, ICAL_RRULE_PROPERTY);
    /* if there is no RRULE, simply return to the caller */
    if (rrule == NULL) {
        return NULL;
    }

    u_zone = icaltimezone_get_builtin_timezone(itr->tzid);

    /* use UTC, if that's all we have. */
    if (!u_zone) {
        u_zone = icaltimezone_get_utc_timezone();
    }

    recur = icalproperty_get_rrule(rrule);
    start = icaltime_from_timet(time(0), 0);

    if (icalcomponent_isa(comp) == ICAL_VEVENT_COMPONENT) {
        dtstart = icalcomponent_get_first_property(comp, ICAL_DTSTART_PROPERTY);
        if (dtstart) {
            start = icalproperty_get_dtstart(dtstart);
        }
    } else if (icalcomponent_isa(comp) == ICAL_VTODO_COMPONENT) {
        due = icalcomponent_get_first_property(comp, ICAL_DUE_PROPERTY);
        if (due) {
            start = icalproperty_get_due(due);
        }
    }

    /* Convert to the user's timezone in order to be able to compare the results
     * from the rrule iterator. */
    if (icaltime_is_utc(start)) {
        start = icaltime_convert_to_zone(start, u_zone);
        orig_time_was_utc = 1;
    }

    if (itr->ritr == NULL) {
        itr->ritr = icalrecur_iterator_new(recur, start);
        next = icalrecur_iterator_next(itr->ritr);
        itr->last_component = comp;
    } else {
        next = icalrecur_iterator_next(itr->ritr);
        if (icaltime_is_null_time(next)) {
            /* no more recurrence, returns */
            itr->last_component = NULL;
            icalrecur_iterator_free(itr->ritr);
            itr->ritr = NULL;
            /* no more pending matched occurrence,
             * all the pending matched occurrences have been returned */
            return NULL;
        } else {
            itr->last_component = comp;
        }
    }

    /* if it is excluded, return NULL to the caller */
    if (icalproperty_recurrence_is_excluded(comp, &start, &next)) {
        (void)icalrecur_iterator_next(itr->ritr);
        return NULL;
    }

    /* set recurrence-id value to the property if the property already exist;
     * add the recurrence id property and the value if the property does not exist */
    prop = icalcomponent_get_first_property(comp, ICAL_RECURRENCEID_PROPERTY);
    if (prop == 0) {
        icalcomponent_add_property(comp, icalproperty_new_recurrenceid(next));
    } else {
        icalproperty_set_recurrenceid(prop, next);
    }

    if (orig_time_was_utc) {
        next = icaltime_convert_to_zone(next, icaltimezone_get_utc_timezone());
    }

    if (itr->gauge == 0 || icalgauge_compare(itr->gauge, comp) == 1) {
        /* find a matched and return it */
        return comp;
    }

    /* not matched */
    return NULL;
}
Esempio n. 11
0
icalsetiter icalbdbset_begin_component(icalset *set, icalcomponent_kind kind,
                                       icalgauge *gauge, const char *tzid)
{
    icalsetiter itr = icalsetiter_null;
    icalcomponent *comp = NULL;
    icalcompiter citr;
    icalbdbset *bset;
    struct icaltimetype start, next;
    icalproperty *dtstart, *rrule, *prop, *due;
    struct icalrecurrencetype recur;
    icaltimezone *u_zone;
    int g = 0;
    int orig_time_was_utc = 0;

    icalerror_check_arg_re((set != 0), "set", icalsetiter_null);
    bset = (icalbdbset *) set;

    itr.gauge = gauge;
    itr.tzid = tzid;

    citr = icalcomponent_begin_component(bset->cluster, kind);
    comp = icalcompiter_deref(&citr);

    if (gauge == 0) {
        itr.iter = citr;
        return itr;
    }

    /* if there is a gauge, the first matched component is returned */
    while (comp != 0) {

        /* check if it is a recurring component and with guage expand, if so
         * we need to add recurrence-id property to the given component */
        rrule = icalcomponent_get_first_property(comp, ICAL_RRULE_PROPERTY);
        g = icalgauge_get_expand(gauge);

        if (rrule != 0 && g == 1) {

            /* it is a recurring event */

            u_zone = icaltimezone_get_builtin_timezone(itr.tzid);

            /* use UTC, if that's all we have. */
            if (!u_zone) {
                u_zone = icaltimezone_get_utc_timezone();
            }

            recur = icalproperty_get_rrule(rrule);
            start = icaltime_from_timet(time(0), 0);

            if (icalcomponent_isa(comp) == ICAL_VEVENT_COMPONENT) {
                dtstart = icalcomponent_get_first_property(comp, ICAL_DTSTART_PROPERTY);
                if (dtstart) {
                    start = icalproperty_get_dtstart(dtstart);
                }
            } else if (icalcomponent_isa(comp) == ICAL_VTODO_COMPONENT) {
                due = icalcomponent_get_first_property(comp, ICAL_DUE_PROPERTY);
                if (due) {
                    start = icalproperty_get_due(due);
                }
            }

            /* Convert to the user's timezone in order to be able to compare
             * the results from the rrule iterator. */
            if (icaltime_is_utc(start)) {
                start = icaltime_convert_to_zone(start, u_zone);
                orig_time_was_utc = 1;
            }

            if (itr.last_component == NULL) {
                itr.ritr = icalrecur_iterator_new(recur, start);
                next = icalrecur_iterator_next(itr.ritr);
                itr.last_component = comp;
            } else {
                next = icalrecur_iterator_next(itr.ritr);
                if (icaltime_is_null_time(next)) {
                    itr.last_component = NULL;
                    icalrecur_iterator_free(itr.ritr);
                    itr.ritr = NULL;
                    /* no matched occurrence */
                    goto getNextComp;
                } else {
                    itr.last_component = comp;
                }
            }

            /* if it is excluded, do next one */
            if (icalproperty_recurrence_is_excluded(comp, &start, &next)) {
                next = icalrecur_iterator_next(itr.ritr);
                continue;
            }

            /* add recurrence-id value to the property if the property already exist;
             * add the recurrence id property and the value if the property does not exist */
            prop = icalcomponent_get_first_property(comp, ICAL_RECURRENCEID_PROPERTY);
            if (prop == 0) {
                icalcomponent_add_property(comp, icalproperty_new_recurrenceid(next));
            } else {
                icalproperty_set_recurrenceid(prop, next);
            }

            /* convert the next recurrence time into the user's timezone */
            if (orig_time_was_utc) {
                next = icaltime_convert_to_zone(next, icaltimezone_get_utc_timezone());
            }
        }
        /* end of a recurring event */
        if (gauge == 0 || icalgauge_compare(itr.gauge, comp) == 1) {
            /* find a matched and return it */
            itr.iter = citr;
            return itr;
        }

        /* if it is a recurring but no matched occurrence has been found OR
         * it is not a recurring and no matched component has been found,
         * read the next component to find out */
      getNextComp:
        if ((rrule != NULL && itr.last_component == NULL) || (rrule == NULL)) {
            (void)icalcompiter_next(&citr);
            comp = icalcompiter_deref(&citr);
        }
    }   /* while */

    /* no matched component has found */
    return icalsetiter_null;
}
Esempio n. 12
0
int main(int argc, char *argv[])
{
    icalset *cin;
    struct icaltimetype next;
    icalcomponent *itr;
    icalproperty *desc, *dtstart, *rrule;
    struct icalrecurrencetype recur;
    icalrecur_iterator* ritr;
    time_t tt;
    char* file;

    icalerror_set_error_state(ICAL_PARSE_ERROR, ICAL_ERROR_NONFATAL);

#ifndef WIN32
    signal(SIGALRM,sig_alrm);
#endif

    if (argc <= 1) {
        file = "../../test-data/recur.txt";
    } else if (argc == 2) {
        file = argv[1];
    } else {
        fprintf(stderr,"usage: recur [input file]\n");
        exit(1);
    }

#ifndef WIN32
    alarm(300); /* to get file lock */
#endif
    cin = icalfileset_new(file);
#ifndef WIN32
    alarm(0);
#endif

    if(cin == 0) {
        fprintf(stderr,"recur: can't open file %s\n",file);
        exit(1);
    }


    for (itr = icalfileset_get_first_component(cin);
            itr != 0;
            itr = icalfileset_get_next_component(cin)) {

        struct icaltimetype start = icaltime_from_timet(1,0);
        struct icaltimetype end = icaltime_today();



        desc = icalcomponent_get_first_property(itr,ICAL_DESCRIPTION_PROPERTY);
        dtstart = icalcomponent_get_first_property(itr,ICAL_DTSTART_PROPERTY);
        rrule = icalcomponent_get_first_property(itr,ICAL_RRULE_PROPERTY);

        if (desc == 0 || dtstart == 0 || rrule == 0) {
            printf("\n******** Error in input component ********\n");
            printf("The following component is malformed:\n %s\n",
                   icalcomponent_as_ical_string(itr));
            continue;
        }

        printf("\n\n#### %s\n",icalproperty_get_description(desc));
        printf("#### %s\n",icalvalue_as_ical_string(icalproperty_get_value(rrule)));
        recur = icalproperty_get_rrule(rrule);
        start = icalproperty_get_dtstart(dtstart);

        ritr = icalrecur_iterator_new(recur,start);

        tt = icaltime_as_timet(start);

        printf("#### %s\n",ctime(&tt ));

        icalrecur_iterator_free(ritr);

        for(ritr = icalrecur_iterator_new(recur,start),
                next = icalrecur_iterator_next(ritr);
                !icaltime_is_null_time(next);
                next = icalrecur_iterator_next(ritr)) {

            tt = icaltime_as_timet(next);

            printf("  %s",ctime(&tt ));

        }
        icalrecur_iterator_free(ritr);

        icalcomponent_foreach_recurrence(itr, start, end,
                                         recur_callback, NULL);



    }

    icalset_free(cin);

    icaltimezone_free_builtin_timezones();

    icalmemory_free_ring();

    free_zone_directory();

    return 0;
}
Esempio n. 13
0
void parse_iCal(icalcomponent* comp)
{
  icalcomponent * c;
  icalproperty * rrule;
  icalproperty * exdate;

  icalrecur_iterator * data;
  struct icaldurationtype offset;
  struct icaltimetype time_start;
  struct icaltimetype time_end;
  struct icaltimetype time_next;
  struct icaltimetype exdatetime;
  struct icaltimetype now;
  struct icalrecurrencetype recur;
  int i = 0;
  double duration;

  // Get offset:
  time_t t = time(NULL);
  struct tm lt = {0};
  localtime_r(&t, &lt);
  if (debug_flag)
  {
    printf("Offset to GMT is %lds.\n", lt.tm_gmtoff);
  }
  offset.days = 0;
  offset.weeks = 0;
  offset.hours = 0;
  offset.minutes = 0;
  offset.seconds = 0;
  offset.hours = lt.tm_gmtoff / 3600;
  if (lt.tm_gmtoff < 0) {
   offset.is_neg = 1;
  } else {
   offset.is_neg = 0;
  }

  // Get time now:
  now = icaltime_today();

  // Read each event:
  for (c = icalcomponent_get_first_component(comp,ICAL_VEVENT_COMPONENT) ;
       c != 0 ;
       c = icalcomponent_get_next_component(comp,ICAL_VEVENT_COMPONENT)
  )
  {
    // Get details about the event:
    const char * summary = icalcomponent_get_summary(c);
    const char * description = icalcomponent_get_description(c);

    // Help:
    if (debug_flag)
    {
      if (summary != NULL)
      {
        printf("summary: %s\n", summary);
      }
      if (description != NULL)
      {
        printf("description: %s\n", description);
      }
    }

    // Ranging time:
    time_start = icalcomponent_get_dtstart (c);
    time_end = icalcomponent_get_dtend (c);
    duration = difftime(icaltime_as_timet(time_end), icaltime_as_timet(time_start));

    // Rules:
    rrule = icalcomponent_get_first_property(c,ICAL_RRULE_PROPERTY);
    recur = icalproperty_get_rrule(rrule);
    data = icalrecur_iterator_new (recur, time_start);

    // Find next event:
    while (1)
    {
      time_next = icalrecur_iterator_next (data);

      if (icaltime_is_null_time(time_next) == 1) break;
      if (icaltime_compare(time_next, now) >= 0) break;
    }

    // Help:
    if (debug_flag)
    {
      dump_icaltimetype("time start", time_start);
      dump_icaltimetype("time end", time_end);
      dump_icaltimetype("until", recur.until);
      dump_icaltimetype("time next", time_next);
    }

    // One shot event:
    if (
      icaltime_is_null_time(time_next) == 1
      &&
      icaltime_compare(time_start, now) < 0
    )
    {
      if (debug_flag) printf ("event (one shot) is in the past\n");
      continue;
    }

    // Old event: discard recurent events finished before today...
    if (
      icaltime_is_null_time(recur.until) == 0
      &&
      icaltime_compare(recur.until, now) < 0
    )
    {
      if (debug_flag) printf ("event is recurent in the past ...\n");
      continue;
    }

    // Some help:
    if (debug_flag > 2)
    {
      dump_icalrecurrencetype(recur);
    }


    // Set time and hours:
    struct icaltimetype local_time_start = icaltime_add(time_start, offset);
    printf ("%d	%d	", local_time_start.minute, local_time_start.hour);

    // Set option depending of recurence:
    switch (recur.freq)
    {
      // Weekly: OK but need to remove days not needed... ?
      case ICAL_WEEKLY_RECURRENCE:
        printf ("%s", "*	*	");
        for (i = 0; recur.by_day[i] != 32639; i++)
        {
          printf ("%02d", icalrecurrencetype_day_day_of_week(recur.by_day[i]) -1);
          if (recur.by_day[i+1] != 32639)
          {
            printf ("%s", ",");
          }
        }
        printf ("%s", "	");
        break;

      // Happening each month:
      case ICAL_MONTHLY_RECURRENCE:
        // The Xth of the month:
        if (recur.by_month_day[0] != 32639)
        {
          printf ("%02d	*	*	", recur.by_month_day[0]);
        }

        // Day of the week:
        else
        {
            printf ("%d	%d	*	", time_next.day, time_next.month);
        }
        break;


      // Event happening each year ...  OK???
      // OK: one shoot.
      case ICAL_YEARLY_RECURRENCE:
      case ICAL_NO_RECURRENCE:
      default:
        printf ("%02d	%02d	*	", 
          local_time_start.day,
          local_time_start.month
        );
    }



    // How many valid exclude dates:
    exdate = icalcomponent_get_first_property(c, ICAL_EXDATE_PROPERTY);
    unsigned int num_ex = 0;
    if (exdate != NULL)
    {
      for (; exdate != NULL; exdate = icalcomponent_get_next_property(c, ICAL_EXDATE_PROPERTY) )
      {
        exdatetime = icalvalue_get_datetime(icalproperty_get_value(exdate));
        if (icaltime_compare(exdatetime, now) >= 0)
        {
          num_ex++;
        }
      }
    }
    if (num_ex > 0)
    {
      exdate = icalcomponent_get_first_property(c, ICAL_EXDATE_PROPERTY);
      for (; exdate != NULL; exdate = icalcomponent_get_next_property(c, ICAL_EXDATE_PROPERTY) )
      {
        exdatetime = icalvalue_get_datetime(icalproperty_get_value(exdate));
        if (icaltime_compare(exdatetime, now) >= 0)
        {
          struct icaltimetype local_exdatetime = icaltime_add(exdatetime, offset);
          printf ("%s", "[ \"$(date \"+\\\%Y\\\%m\\\%d\")\" = \"");
          printf ("%04d%02d%02d", local_exdatetime.year, local_exdatetime.month, local_exdatetime.day);
          printf ("%s", "\" ] || ");
        }
      }
    }

    // And the action:
    printf ("%s %.0f\n", 
      summary,
      duration
    );

    icalrecur_iterator_free (data);
  }
}
Esempio n. 14
0
static void
icaltimezone_expand_vtimezone		(icalcomponent	*comp,
					 int		 end_year,
					 icalarray	*changes)
{
    icaltimezonechange change;
    icalproperty *prop;
    struct icaltimetype dtstart, occ;
    struct icalrecurrencetype rrule;
    icalrecur_iterator* rrule_iterator;
    struct icaldatetimeperiodtype rdate;
    int found_dtstart = 0, found_tzoffsetto = 0, found_tzoffsetfrom = 0;
    int has_recurrence = 0;

    /* First we check if it is a STANDARD or DAYLIGHT component, and
       just return if it isn't. */
    if (icalcomponent_isa (comp) == ICAL_XSTANDARD_COMPONENT)
	change.is_daylight = 0;
    else if (icalcomponent_isa (comp) == ICAL_XDAYLIGHT_COMPONENT)
	change.is_daylight = 1;
    else 
	return;

    /* Step through each of the properties to find the DTSTART,
       TZOFFSETFROM and TZOFFSETTO. We can't expand recurrences here
       since we need these properties before we can do that. */
    prop = icalcomponent_get_first_property (comp, ICAL_ANY_PROPERTY);
    while (prop) {
	switch (icalproperty_isa (prop)) {
	case ICAL_DTSTART_PROPERTY:
	    dtstart = icalproperty_get_dtstart (prop);
	    found_dtstart = 1;
	    break;
	case ICAL_TZOFFSETTO_PROPERTY:
	    change.utc_offset = icalproperty_get_tzoffsetto (prop);
	    /*printf ("Found TZOFFSETTO: %i\n", change.utc_offset);*/
	    found_tzoffsetto = 1;
	    break;
	case ICAL_TZOFFSETFROM_PROPERTY:
	    change.prev_utc_offset = icalproperty_get_tzoffsetfrom (prop);
	    /*printf ("Found TZOFFSETFROM: %i\n", change.prev_utc_offset);*/
	    found_tzoffsetfrom = 1;
	    break;
	case ICAL_RDATE_PROPERTY:
	case ICAL_RRULE_PROPERTY:
	    has_recurrence = 1;
	    break;
	default:
	    /* Just ignore any other properties. */
	    break;
	}

	prop = icalcomponent_get_next_property (comp, ICAL_ANY_PROPERTY);
    }

    /* If we didn't find a DTSTART, TZOFFSETTO and TZOFFSETFROM we have to
       ignore the component. FIXME: Add an error property? */
    if (!found_dtstart || !found_tzoffsetto || !found_tzoffsetfrom)
	return;

#if 0
    printf ("\n Expanding component DTSTART (Y/M/D): %i/%i/%i %i:%02i:%02i\n",
	    dtstart.year, dtstart.month, dtstart.day,
	    dtstart.hour, dtstart.minute, dtstart.second);
#endif

    /* If the STANDARD/DAYLIGHT component has no recurrence data, we just add
       a single change for the DTSTART. */
    if (!has_recurrence) {
	change.year   = dtstart.year;
	change.month  = dtstart.month;
	change.day    = dtstart.day;
	change.hour   = dtstart.hour;
	change.minute = dtstart.minute;
	change.second = dtstart.second;

	/* Convert to UTC. */
	icaltimezone_adjust_change (&change, 0, 0, 0, -change.prev_utc_offset);

#if 0
	printf ("  Appending single DTSTART (Y/M/D): %i/%02i/%02i %i:%02i:%02i\n",
		change.year, change.month, change.day,
		change.hour, change.minute, change.second);
#endif

	/* Add the change to the array. */
	icalarray_append (changes, &change);
	return;
    }

    /* The component has recurrence data, so we expand that now. */
    prop = icalcomponent_get_first_property (comp, ICAL_ANY_PROPERTY);
    while (prop) {
#if 0
	printf ("Expanding property...\n");
#endif
	switch (icalproperty_isa (prop)) {
	case ICAL_RDATE_PROPERTY:
	    rdate = icalproperty_get_rdate (prop);
	    change.year   = rdate.time.year;
	    change.month  = rdate.time.month;
	    change.day    = rdate.time.day;
	    /* RDATEs with a DATE value inherit the time from
	       the DTSTART. */
	    if (icaltime_is_date(rdate.time)) {
		change.hour   = dtstart.hour;
		change.minute = dtstart.minute;
		change.second = dtstart.second;
	    } else {
		change.hour   = rdate.time.hour;
		change.minute = rdate.time.minute;
		change.second = rdate.time.second;

		/* The spec was a bit vague about whether RDATEs were in local
		   time or UTC so we support both to be safe. So if it is in
		   UTC we have to add the UTC offset to get a local time. */
		if (!icaltime_is_utc(rdate.time))
		    icaltimezone_adjust_change (&change, 0, 0, 0,
						-change.prev_utc_offset);
	    }

#if 0
	    printf ("  Appending RDATE element (Y/M/D): %i/%02i/%02i %i:%02i:%02i\n",
		    change.year, change.month, change.day,
		    change.hour, change.minute, change.second);
#endif

	    icalarray_append (changes, &change);
	    break;
	case ICAL_RRULE_PROPERTY:
	    rrule = icalproperty_get_rrule (prop);

	    /* If the rrule UNTIL value is set and is in UTC, we convert it to
	       a local time, since the recurrence code has no way to convert
	       it itself. */
	    if (!icaltime_is_null_time (rrule.until) && rrule.until.is_utc) {
#if 0
		printf ("  Found RRULE UNTIL in UTC.\n");
#endif

		/* To convert from UTC to a local time, we use the TZOFFSETFROM
		   since that is the offset from UTC that will be in effect
		   when each of the RRULE occurrences happens. */
		icaltime_adjust (&rrule.until, 0, 0, 0,
				 change.prev_utc_offset);
		rrule.until.is_utc = 0;
	    }

	    rrule_iterator = icalrecur_iterator_new (rrule, dtstart);
	    for (;;) {
		occ = icalrecur_iterator_next (rrule_iterator);
		if (occ.year > end_year || icaltime_is_null_time (occ))
		    break;

		change.year   = occ.year;
		change.month  = occ.month;
		change.day    = occ.day;
		change.hour   = occ.hour;
		change.minute = occ.minute;
		change.second = occ.second;

#if 0
		printf ("  Appending RRULE element (Y/M/D): %i/%02i/%02i %i:%02i:%02i\n",
			change.year, change.month, change.day,
			change.hour, change.minute, change.second);
#endif

		icaltimezone_adjust_change (&change, 0, 0, 0,
					    -change.prev_utc_offset);

		icalarray_append (changes, &change);
	    }

	    icalrecur_iterator_free (rrule_iterator);
	    break;
	default:
	    break;
	}

	prop = icalcomponent_get_next_property (comp, ICAL_ANY_PROPERTY);
    }
}
Esempio n. 15
0
/**
 * @brief
 * 	Check if a recurrence rule is valid and consistent.
 * 	The recurrence rule is verified against a start date and checks
 * 	that the frequency of the recurrence matches the duration of the
 * 	submitted reservation. If the duration of a reservation exceeds the
 * 	granularity of the frequency then an error message is displayed.
 *
 * @par The recurrence rule is checked to contain a COUNT or an UNTIL.
 *
 * @par	Note that the PBS_TZID environment variable HAS to be set for the occurrence's
 * 	dates to be correctly computed.
 *  
 * @param[in] rrule - The recurrence rule to unroll
 * @param[in] dtstart - The start time associated to the reservation (1st occurrence)
 * @param[in] dtend - The end time associated to the reservation (1st occurrence)
 * @param[in] duration - The duration of an occurrence. This is used when a reservation is
 *  			submitted using the -D (duration) param instead of an end time
 * @param[in] tz - The timezone associated to the recurrence rule
 * @param[in] err_code - A pointer to the error code to return. Codes are defined in pbs_error.h
 *
 * @return	int
 * @retval	The total number of occurrences that the recurrence rule and start date
 * 
 * 		define. 1 for an advance reservation.
 *
 */
int
check_rrule(char *rrule, time_t dtstart, time_t dtend, char *tz, int *err_code)
{


#ifdef LIBICAL  /* Standing Reservation Recurrence */
	int count = 1;
	struct icalrecurrencetype rt;
	struct icaltimetype start;
	struct icaltimetype next;
	struct icaltimetype first;
	struct icaltimetype prev;
	struct icalrecur_iterator_impl *itr;
	icaltimezone *localzone;
	int time_err = 0;
	int i;
	long min_occr_duration = -1;
	long tmp_occr_duration = 0;
	long duration;

	*err_code = 0;
	icalerror_clear_errno();

	icalerror_set_error_state(ICAL_PARSE_ERROR, ICAL_ERROR_NONFATAL);
	icalerror_errors_are_fatal = 0;

	if (tz == NULL || rrule == NULL)
		return 0;

	localzone = icaltimezone_get_builtin_timezone(tz);
	/* If the timezone info directory is not accessible
	 * then bail
	 */
	if (localzone == NULL) {
		*err_code = PBSE_BAD_ICAL_TZ;
		return 0;
	}

	rt = icalrecurrencetype_from_string(rrule);

	/* Check if by_day rules are defined and valid
	 * the first item in the array of by_* rule
	 * determines whether the item exists or not.
	 */
	for (i = 0; rt.by_day[i] < 8; i++) {
		if (rt.by_day[i] <= 0) {
			*err_code = PBSE_BAD_RRULE_SYNTAX;
			return 0;
		}
	}

	/* Check if by_hour rules are defined and valid
	 * the first item in the array of by_* rule
	 * determines whether the item exists or not.
	 */
	for (i = 0; rt.by_hour[i] < 25; i++) {
		if (rt.by_hour[i] < 0) {
			*err_code = PBSE_BAD_RRULE_SYNTAX;
			return 0;
		}
	}

	/* Check if the rest of the by_* rules are defined
	 * and valid.
	 * currently no support for
	 * BYMONTHDAY, BYYEARDAY, BYSECOND,
	 * BYMINUTE, BYWEEKNO, or BYSETPOS
	 *
	 */
	if (rt.by_second[0] < 61 || /* by_second is negative such as in -10 */
		rt.by_minute[0] < 61 ||  /* by_minute is negative such as in -10 */
		rt.by_year_day[0] < 367 || /* a year day is defined */
		rt.by_month_day[0] < 31 || /* a month day is defined */
		rt.by_week_no[0] < 52 ||  /* a week number is defined */
		rt.by_set_pos[0] < 367) { /* a set pos is defined */
		*err_code = PBSE_BAD_RRULE_SYNTAX;
		return 0;
	}


	/* Require that either a COUNT or UNTIL be passed. But not both. */
	if ((rt.count == 0 && icaltime_is_null_time(rt.until)) ||
		(rt.count != 0 && !icaltime_is_null_time(rt.until))) {
		*err_code = PBSE_BAD_RRULE_SYNTAX2; /* Undefined iCalendar synax. A valid COUNT or UNTIL is required */
		return 0;
	}

	start = icaltime_from_timet(dtstart, 0);
	icaltimezone_convert_time(&start, icaltimezone_get_utc_timezone(), localzone);

	itr = (struct icalrecur_iterator_impl*) icalrecur_iterator_new(rt, start);

	duration = dtend -dtstart;

	/* First check if the syntax of the iCalendar rule is valid */
	next = icalrecur_iterator_next(itr);

	/* Catch case where first occurrence date is in the past */
	if (icaltime_is_null_time(next)) {
		*err_code = PBSE_BADTSPEC;
		icalrecur_iterator_free(itr);
		return 0;
	}

	first = next;
	prev = first;

	for (next=icalrecur_iterator_next(itr); !icaltime_is_null_time(next); next=icalrecur_iterator_next(itr), count++) {
		/* The interval duration between two occurrences
		 * is the time between the end of an occurrence and the
		 * start of the next one
		 */
		tmp_occr_duration = icaltime_as_timet(next) - icaltime_as_timet(prev);

		/* Set the minimum time interval between occurrences */
		if (min_occr_duration == -1)
			min_occr_duration = tmp_occr_duration;
		else if (tmp_occr_duration > 0 &&
			tmp_occr_duration < min_occr_duration)
			min_occr_duration = tmp_occr_duration;

		prev = next;
	}
	/* clean up */
	icalrecur_iterator_free(itr);

	if (icalerrno != ICAL_NO_ERROR) {
		*err_code = PBSE_BAD_RRULE_SYNTAX; /*  Undefined iCalendar syntax */
		return 0;
	}

	/* Then check if the duration fits in the frequency rule */
	switch (rt.freq) {

		case ICAL_SECONDLY_RECURRENCE:
			{
				if (duration > 1) {
#ifdef NAS /* localmod 005 */
					icalerrno = ICAL_BADARG_ERROR;
#else
					icalerrno = 1;
#endif /* localmod 005 */
					*err_code = PBSE_BAD_RRULE_SECONDLY; /* SECONDLY recurrence duration cannot exceed 1 second */
					time_err++;
				}
				break;
			}
		case ICAL_MINUTELY_RECURRENCE:
			{
				if (duration > 60) {
#ifdef NAS /* localmod 005 */
					icalerrno = ICAL_BADARG_ERROR;
#else
					icalerrno = 1;
#endif /* localmod 005 */
					*err_code = PBSE_BAD_RRULE_MINUTELY; /* MINUTELY recurrence duration cannot exceed 1 minute */
					time_err++;
				}
				break;
			}
		case ICAL_HOURLY_RECURRENCE:
			{
				if (duration > (60*60)) {
#ifdef NAS /* localmod 005 */
					icalerrno = ICAL_BADARG_ERROR;
#else
					icalerrno =1;
#endif /* localmod 005 */
					*err_code = PBSE_BAD_RRULE_HOURLY; /* HOURLY recurrence duration cannot exceed 1 hour */
					time_err++;
				}
				break;
			}
		case ICAL_DAILY_RECURRENCE:
			{
				if (duration > (60*60*24)) {
#ifdef NAS /* localmod 005 */
					icalerrno = ICAL_BADARG_ERROR;
#else
					icalerrno = 1;
#endif /* localmod 005 */
					*err_code = PBSE_BAD_RRULE_DAILY; /* DAILY recurrence duration cannot exceed 24 hours */
					time_err++;
				}
				break;
			}
		case ICAL_WEEKLY_RECURRENCE:
			{
				if (duration > (60*60*24*7)) {
#ifdef NAS /* localmod 005 */
					icalerrno = ICAL_BADARG_ERROR;
#else
					icalerrno = 1;
#endif /* localmod 005 */
					*err_code = PBSE_BAD_RRULE_WEEKLY; /* WEEKLY recurrence duration cannot exceed 1 week */
					time_err++;
				}
				break;
			}
		case ICAL_MONTHLY_RECURRENCE:
			{
				if (duration > (60*60*24*30)) {
#ifdef NAS /* localmod 005 */
					icalerrno = ICAL_BADARG_ERROR;
#else
					icalerrno = 1;
#endif /* localmod 005 */
					*err_code = PBSE_BAD_RRULE_MONTHLY; /* MONTHLY recurrence duration cannot exceed 1 month */
					time_err++;
				}
				break;
			}
		case ICAL_YEARLY_RECURRENCE:
			{
				if (duration > (60*60*24*30*365)) {
#ifdef NAS /* localmod 005 */
					icalerrno = ICAL_BADARG_ERROR;
#else
					icalerrno = 1;
#endif /* localmod 005 */
					*err_code = PBSE_BAD_RRULE_YEARLY; /* YEARLY recurrence duration cannot exceed 1 year */
					time_err++;
				}
				break;
			}
		default:
			{
				icalerror_set_errno(ICAL_MALFORMEDDATA_ERROR);
				return 0;
			}
	}

	if (time_err)
		return 0;

	/* If the requested reservation duration exceeds
	 * the occurrence's duration then print an error
	 * message and return */
	if (count != 1 && duration > min_occr_duration) {
		*err_code = PBSE_BADTSPEC; /*  Bad Time Specification(s) */
		return 0;
	}

	return count;

#else

	*err_code = PBSE_BAD_RRULE_SYNTAX; /* iCalendar is undefined */
	return 0;
#endif
}