void create_simple_component(void)
{

    icalcomponent* calendar;
    icalproperty *version, *bogus;
      
    /* Create calendar and add properties */
    calendar = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);

    ok("create vcalendar component", (calendar!=NULL));

    icalcomponent_add_property(
	calendar,
	icalproperty_new_version("2.0")
	);
    
    version = icalcomponent_get_first_property(calendar,ICAL_VERSION_PROPERTY);
    ok("version property added", (version!=NULL));

    bogus = icalcomponent_get_first_property(calendar,ICAL_DTSTART_PROPERTY);
    ok("bogus dtstart not found", (bogus == NULL));

    if (VERBOSE && calendar)
      printf("%s\n",icalcomponent_as_ical_string(calendar));

    icalcomponent_free(calendar);
}
static void
test_remove_object (ETestServerFixture *fixture,
                    gconstpointer user_data)
{
	ECal *cal;
	icalcomponent *component;
	icalcomponent *component_final;
	gchar *uid;

	cal = E_TEST_SERVER_UTILS_SERVICE (fixture, ECal);

	component = icalcomponent_new (ICAL_VEVENT_COMPONENT);
	uid = ecal_test_utils_cal_create_object (cal, component);

	/* FIXME: In the same way test-ecal-create-object.c,
	 * this part of the test is broken, need to fix this.
	 */
	component_final = ecal_test_utils_cal_get_object (cal, uid);
	/* ecal_test_utils_cal_assert_objects_equal_shallow (component, component_final); */

	ecal_test_utils_cal_remove_object (cal, uid);

	g_free (uid);
	icalcomponent_free (component);
	icalcomponent_free (component_final);
}
static gpointer
alter_cal_client (gpointer user_data)
{
	ECalClient *cal_client = user_data;
	GError *error = NULL;
	icalcomponent *icalcomp;
	struct icaltimetype now;
	gchar *uid = NULL;

	g_return_val_if_fail (cal_client != NULL, NULL);

	now = icaltime_current_time_with_zone (icaltimezone_get_utc_timezone ());
	icalcomp = icalcomponent_new (ICAL_VEVENT_COMPONENT);
	icalcomponent_set_summary (icalcomp, "Initial event summary");
	icalcomponent_set_dtstart (icalcomp, now);
	icalcomponent_set_dtend   (icalcomp, icaltime_from_timet (icaltime_as_timet (now) + 60 * 60 * 60, 0));

	if (!e_cal_client_create_object_sync (cal_client, icalcomp, &uid, NULL, &error))
		g_error ("create object sync: %s", error->message);

	icalcomponent_set_uid (icalcomp, uid);
	icalcomponent_set_summary (icalcomp, "Modified event summary");

	if (!e_cal_client_modify_object_sync (cal_client, icalcomp, CALOBJ_MOD_ALL, NULL, &error))
		g_error ("modify object sync: %s", error->message);

	if (!e_cal_client_remove_object_sync (cal_client, uid, NULL, CALOBJ_MOD_ALL, NULL, &error))
		g_error ("remove object sync: %s", error->message);

	g_free (uid);
	icalcomponent_free (icalcomp);

	return FALSE;
}
Exemple #4
0
icalcomponent *icalparser_parse(icalparser *parser,
                                icalparser_line_gen_func line_gen_func)
{
    char *line;
    icalcomponent *c = 0;
    icalcomponent *root = 0;
    icalerrorstate es = icalerror_get_error_state(ICAL_MALFORMEDDATA_ERROR);
    int cont;

    icalerror_check_arg_rz((parser != 0), "parser");

    icalerror_set_error_state(ICAL_MALFORMEDDATA_ERROR, ICAL_ERROR_NONFATAL);

    do {
        line = icalparser_get_line(parser, line_gen_func);

        if ((c = icalparser_add_line(parser, line)) != 0) {

            if (icalcomponent_get_parent(c) != 0) {
                /* This is bad news... assert? */
            }

            assert(parser->root_component == 0);
            assert(pvl_count(parser->components) == 0);

            if (root == 0) {
                /* Just one component */
                root = c;
            } else if (icalcomponent_isa(root) != ICAL_XROOT_COMPONENT) {
                /*Got a second component, so move the two components under
                   an XROOT container */
                icalcomponent *tempc = icalcomponent_new(ICAL_XROOT_COMPONENT);

                icalcomponent_add_component(tempc, root);
                icalcomponent_add_component(tempc, c);
                root = tempc;
            } else if (icalcomponent_isa(root) == ICAL_XROOT_COMPONENT) {
                /* Already have an XROOT container, so add the component
                   to it */
                icalcomponent_add_component(root, c);

            } else {
                /* Badness */
                assert(0);
            }

            c = 0;
        }
        cont = 0;
        if (line != 0) {
            icalmemory_free_buffer(line);
            cont = 1;
        }
    } while (cont);

    icalerror_set_error_state(ICAL_MALFORMEDDATA_ERROR, es);

    return root;
}
gint
main (gint argc,
      gchar **argv)
{
	ECalClient *cal_client;
	GError *error = NULL;
	icalcomponent *icalcomp;
	struct icaltimetype now;
	gchar *uid = NULL;

	main_initialize ();

	cal_client = new_temp_client (E_CAL_CLIENT_SOURCE_TYPE_EVENTS, NULL);
	g_return_val_if_fail (cal_client != NULL, FALSE);

	if (!e_client_open_sync (E_CLIENT (cal_client), FALSE, NULL, &error)) {
		report_error ("client open sync", &error);
		g_object_unref (cal_client);
		return 1;
	}

	now = icaltime_current_time_with_zone (icaltimezone_get_utc_timezone ());
	icalcomp = icalcomponent_new (ICAL_VEVENT_COMPONENT);
	icalcomponent_set_summary (icalcomp, "Test event summary");
	icalcomponent_set_dtstart (icalcomp, now);
	icalcomponent_set_dtend   (icalcomp, icaltime_from_timet (icaltime_as_timet (now) + 60 * 60 * 60, 0));

	if (!e_cal_client_create_object_sync (cal_client, icalcomp, &uid, NULL, &error)) {
		report_error ("create object sync", &error);
		icalcomponent_free (icalcomp);
		g_object_unref (cal_client);
		return 1;
	}

	icalcomponent_free (icalcomp);
	g_free (uid);

	/* synchronously without main-loop */
	if (!test_sync (cal_client)) {
		g_object_unref (cal_client);
		return 1;
	}

	start_in_thread_with_main_loop (test_sync_in_thread, cal_client);

	if (!e_client_remove_sync (E_CLIENT (cal_client), NULL, &error)) {
		report_error ("client remove sync", &error);
		g_object_unref (cal_client);
		return 1;
	}

	g_object_unref (cal_client);

	if (get_main_loop_stop_result () == 0)
		g_print ("Test finished successfully.\n");

	return get_main_loop_stop_result ();
}
Exemple #6
0
icalcluster * icalcluster_new(const char* key, icalcomponent *data) {
	struct icalcluster_impl *impl = icalcluster_new_impl();
	assert(impl->data == 0);

	impl->key	= strdup(key);
	impl->changed	= 0;
	impl->data	= 0;

	if (data != NULL) {
		if (icalcomponent_isa(data) != ICAL_XROOT_COMPONENT) {
			impl->data = icalcomponent_new(ICAL_XROOT_COMPONENT);
			icalcomponent_add_component(impl->data, data);
		} else {
			impl->data = icalcomponent_new_clone(data);
		}
	} else {
		impl->data = icalcomponent_new(ICAL_XROOT_COMPONENT);
	}

	return impl;
}
static icalcomponent *
create_object (void)
{
	icalcomponent *icalcomp;
	struct icaltimetype now;

	now = icaltime_current_time_with_zone (icaltimezone_get_utc_timezone ());
	icalcomp = icalcomponent_new (ICAL_VEVENT_COMPONENT);
	icalcomponent_set_summary (icalcomp, "To-be-sent event summary");
	icalcomponent_set_dtstart (icalcomp, now);
	icalcomponent_set_dtend   (icalcomp, icaltime_from_timet_with_zone (icaltime_as_timet (now) + 60 * 60 * 60, 0, NULL));

	return icalcomp;
}
/**
 * jana_ecal_task_new:
 *
 * Creates a new #JanaEcalTask.
 *
 * Returns: A new #JanaEcalTask, cast as a #JanaTask.
 */
JanaTask *
jana_ecal_task_new ()
{
	ECalComponent *comp = e_cal_component_new ();
	JanaTask *task;

	e_cal_component_set_icalcomponent (comp,
		icalcomponent_new (ICAL_VTODO_COMPONENT));
	
	task = JANA_TASK (g_object_new (JANA_ECAL_TYPE_TASK,
		"ecalcomp", comp, NULL));
	
	return task;
}
Exemple #9
0
/**
 * e_cal_util_new_component:
 * @kind: Kind of the component to create.
 *
 * Creates a new #icalcomponent of the specified kind.
 *
 * Returns: the newly created component.
 */
icalcomponent *
e_cal_util_new_component (icalcomponent_kind kind)
{
	icalcomponent *comp;
	struct icaltimetype dtstamp;
	gchar *uid;

	comp = icalcomponent_new (kind);
	uid = e_cal_component_gen_uid ();
	icalcomponent_set_uid (comp, uid);
	g_free (uid);
	dtstamp = icaltime_current_time_with_zone (icaltimezone_get_utc_timezone ());
	icalcomponent_set_dtstamp (comp, dtstamp);

	return comp;
}
Exemple #10
0
void program_errors()
{
    /*Most routines will set icalerrno on errors. This is an
      enumeration defined in icalerror.h */

    icalerror_clear_errno();

    (void)icalcomponent_new(ICAL_VEVENT_COMPONENT);

    if (icalerrno != ICAL_NO_ERROR){

        fprintf(stderr,"Horrible libical error: %s\n",
                icalerror_strerror(icalerrno));

    }

}
static void
setup_cal (ECalClient *cal_client)
{
	GError *error = NULL;
	icalcomponent *icalcomp;
	struct icaltimetype now;
	gchar *uid = NULL;

	now = icaltime_current_time_with_zone (icaltimezone_get_utc_timezone ());
	icalcomp = icalcomponent_new (ICAL_VEVENT_COMPONENT);
	icalcomponent_set_summary (icalcomp, "Test event summary");
	icalcomponent_set_dtstart (icalcomp, now);
	icalcomponent_set_dtend   (icalcomp, icaltime_from_timet (icaltime_as_timet (now) + 60 * 60 * 60, 0));

	if (!e_cal_client_create_object_sync (cal_client, icalcomp, &uid, NULL, &error))
		g_error ("create object sync: %s", error->message);

	icalcomponent_free (icalcomp);
	g_free (uid);
}
Exemple #12
0
void MainWindow::createIcalTask(Task* task)
{
    icalcomponent *todo;
    icalproperty  *prop;

    todo = icalcomponent_new(ICAL_VTODO_COMPONENT);

    prop = icalproperty_new_summary(task->icalSummary().c_str());
    icalcomponent_add_property(todo, prop);

    prop = icalproperty_new_uid(task->icalUid().c_str());
    icalcomponent_add_property(todo, prop);

    if (task->icalRelatedTo() != "")
    {
        prop = icalproperty_new_relatedto(task->icalRelatedTo().c_str());
        icalcomponent_add_property(todo, prop);
    }

    saveToIcsFile(todo, task->icalUid());
}
static void
get_revision_compare_cycle (ECalClient *client)
{
       icalcomponent *icalcomp;
       struct icaltimetype now;
       gchar    *revision_before = NULL, *revision_after = NULL, *uid = NULL;
       GError   *error = NULL;

       /* Build up new component */
       now = icaltime_current_time_with_zone (icaltimezone_get_utc_timezone ());
       icalcomp = icalcomponent_new (ICAL_VEVENT_COMPONENT);
       icalcomponent_set_summary (icalcomp, "Test event summary");
       icalcomponent_set_dtstart (icalcomp, now);
       icalcomponent_set_dtend   (icalcomp, icaltime_from_timet (icaltime_as_timet (now) + 60 * 60 * 60, 0));

       if (!e_client_get_backend_property_sync (E_CLIENT (client), CLIENT_BACKEND_PROPERTY_REVISION,
						&revision_before, NULL, &error))
               g_error ("Error getting book revision: %s", error->message);

       if (!e_cal_client_create_object_sync (client, icalcomp, &uid, NULL, &error))
	       g_error ("Error creating object: %s", error->message);

       if (!e_client_get_backend_property_sync (E_CLIENT (client), CLIENT_BACKEND_PROPERTY_REVISION,
						&revision_after, NULL, &error))
               g_error ("Error getting book revision: %s", error->message);

       g_assert (revision_before);
       g_assert (revision_after);
       g_assert (strcmp (revision_before, revision_after) != 0);

       g_message ("Passed cycle, revision before '%s' revision after '%s'",
		  revision_before, revision_after);

       g_free (revision_before);
       g_free (revision_after);
       g_free (uid);

       icalcomponent_free (icalcomp);
}
static gchar *
create_object (ECalClient *cal_client)
{
	icalcomponent *icalcomp;
	struct icaltimetype now;
	gchar *uid = NULL;
	GError *error = NULL;

	g_return_val_if_fail (cal_client != NULL, NULL);

	now = icaltime_current_time_with_zone (icaltimezone_get_utc_timezone ());
	icalcomp = icalcomponent_new (ICAL_VEVENT_COMPONENT);
	icalcomponent_set_summary (icalcomp, "To-be-removed event summary");
	icalcomponent_set_dtstart (icalcomp, now);
	icalcomponent_set_dtend   (icalcomp, icaltime_from_timet_with_zone (icaltime_as_timet (now) + 60 * 60 * 60, 0, NULL));

	if (!e_cal_client_create_object_sync (cal_client, icalcomp, &uid, NULL, &error))
		g_error ("create object sync: %s", error->message);

	icalcomponent_free (icalcomp);

	return uid;
}
Exemple #15
0
void Todo::updateIcalFromData() {

    // clean event
    if (_ptrIcal) {
        assert(icalcomponent_isa(_ptrIcal) == ICAL_VTODO_COMPONENT);
        removeProperty(ICAL_SUMMARY_PROPERTY);
        removeProperty(ICAL_LOCATION_PROPERTY);
        removeProperty(ICAL_DESCRIPTION_PROPERTY);
    }
    else {
        _ptrIcal = icalcomponent_new(ICAL_VTODO_COMPONENT);
        assert(_ptrIcal);
    }

    // add new properties
    if (not _summary.empty())
        icalcomponent_add_property(_ptrIcal, icalproperty_new_summary(_summary.c_str()));

    if (not _location.empty())
        icalcomponent_add_property(_ptrIcal, icalproperty_new_location(_location.c_str()));

    if (not _description.empty())
        icalcomponent_add_property(_ptrIcal, icalproperty_new_description(_description.c_str()));
}
Exemple #16
0
/**
 * e_cal_util_new_top_level:
 *
 * Creates a new VCALENDAR component.
 *
 * Returns: the newly created top level component.
 */
icalcomponent *
e_cal_util_new_top_level (void)
{
	icalcomponent *icalcomp;
	icalproperty *prop;

	icalcomp = icalcomponent_new (ICAL_VCALENDAR_COMPONENT);

	/* RFC 2445, section 4.7.1 */
	prop = icalproperty_new_calscale ("GREGORIAN");
	icalcomponent_add_property (icalcomp, prop);

       /* RFC 2445, section 4.7.3 */
	prop = icalproperty_new_prodid ("-//Ximian//NONSGML Evolution Calendar//EN");
	icalcomponent_add_property (icalcomp, prop);

	/* RFC 2445, section 4.7.4.  This is the iCalendar spec version, *NOT*
	 * the product version!  Do not change this!
	 */
	prop = icalproperty_new_version ("2.0");
	icalcomponent_add_property (icalcomp, prop);

	return icalcomp;
}
NS_IMETHODIMP
calICSService::CreateIcalComponent(const nsACString &kind, calIIcalComponent **comp)
{
    NS_ENSURE_ARG_POINTER(comp);
    icalcomponent_kind compkind =
        icalcomponent_string_to_kind(PromiseFlatCString(kind).get());

    // Maybe someday I'll support X-COMPONENTs
    if (compkind == ICAL_NO_COMPONENT || compkind == ICAL_X_COMPONENT)
        return NS_ERROR_INVALID_ARG;

    icalcomponent *ical = icalcomponent_new(compkind);
    if (!ical)
        return NS_ERROR_OUT_OF_MEMORY; // XXX translate

    *comp = new calIcalComponent(ical, nullptr);
    if (!*comp) {
        icalcomponent_free(ical);
        return NS_ERROR_OUT_OF_MEMORY;
    }

    NS_ADDREF(*comp);
    return NS_OK;
}
Exemple #18
0
void MainWindow::createIcalEvent(Event *event)
{
    icalcomponent *iEvent;
    icalproperty  *prop;

    iEvent = icalcomponent_new(ICAL_VEVENT_COMPONENT);

    prop = icalproperty_new_summary(event->icalSummary().c_str());
    icalcomponent_add_property(iEvent, prop);

    prop = icalproperty_new_uid(event->icalUid().c_str());
    icalcomponent_add_property(iEvent, prop);

    prop = icalproperty_new_relatedto(event->icalRelatedTo().c_str());
    icalcomponent_add_property(iEvent, prop);

    prop = icalproperty_new_dtstart(event->icalDtStart());
    icalcomponent_add_property(iEvent, prop);

    prop = icalproperty_new_dtend(event->icalDtEnd());
    icalcomponent_add_property(iEvent, prop);

    saveToIcsFile(iEvent, event->icalUid());
}
Exemple #19
0
icalcomponent *icaltzutil_fetch_timezone(const char *location)
{
    tzinfo type_cnts;
    size_t i, num_trans, num_chars, num_leaps, num_isstd, num_isgmt;
    size_t num_types = 0;
    size_t size;
    time_t trans;
    int dstidx = -1, stdidx = -1, pos, sign, zidx, zp_idx;
    icalcomponent *std_comp = NULL;

    const char *zonedir;
    FILE *f = NULL;
    char *full_path = NULL;
    time_t *transitions = NULL;
    char *r_trans = NULL, *temp;
    int *trans_idx = NULL;
    ttinfo *types = NULL;
    char *znames = NULL;
    leap *leaps = NULL;
    char *tzid = NULL;

    time_t start, end;
    int idx, prev_idx;
    icalcomponent *tz_comp = NULL, *comp = NULL, *dst_comp;
    icalproperty *icalprop;
    icaltimetype dtstart, icaltime;
    struct icalrecurrencetype ical_recur;

    if (icaltimezone_get_builtin_tzdata()) {
        goto error;
    }

    zonedir = icaltzutil_get_zone_directory();
    if (!zonedir) {
        icalerror_set_errno(ICAL_FILE_ERROR);
        goto error;
    }

    size = strlen(zonedir) + strlen(location) + 2;
    full_path = (char *)malloc(size);
    if (full_path == NULL) {
        icalerror_set_errno(ICAL_NEWFAILED_ERROR);
        goto error;
    }
    snprintf(full_path, size, "%s/%s", zonedir, location);
    if ((f = fopen(full_path, "rb")) == 0) {
        icalerror_set_errno(ICAL_FILE_ERROR);
        goto error;
    }

    if (fseek(f, 20, SEEK_SET) != 0) {
        icalerror_set_errno(ICAL_FILE_ERROR);
        goto error;
    }

    EFREAD(&type_cnts, 24, 1, f);

    num_isgmt = (size_t)decode(type_cnts.ttisgmtcnt);
    num_leaps = (size_t)decode(type_cnts.leapcnt);
    num_chars = (size_t)decode(type_cnts.charcnt);
    num_trans = (size_t)decode(type_cnts.timecnt);
    num_isstd = (size_t)decode(type_cnts.ttisstdcnt);
    num_types = (size_t)decode(type_cnts.typecnt);

    transitions = calloc(num_trans, sizeof(time_t));
    if (transitions == NULL) {
        icalerror_set_errno(ICAL_NEWFAILED_ERROR);
        goto error;
    }
    r_trans = calloc(num_trans, 4);
    if (r_trans == NULL) {
        icalerror_set_errno(ICAL_NEWFAILED_ERROR);
        goto error;
    }

    EFREAD(r_trans, 4, num_trans, f);
    temp = r_trans;
    if (num_trans) {
        trans_idx = calloc(num_trans, sizeof(int));
        if (trans_idx == NULL) {
            icalerror_set_errno(ICAL_NEWFAILED_ERROR);
            goto error;
        }
        for (i = 0; i < num_trans; i++) {
            trans_idx[i] = fgetc(f);
            transitions[i] = (time_t) decode(r_trans);
            r_trans += 4;
        }
    }
    r_trans = temp;

    types = calloc(num_types, sizeof(ttinfo));
    if (types == NULL) {
        icalerror_set_errno(ICAL_NEWFAILED_ERROR);
        goto error;
    }
    for (i = 0; i < num_types; i++) {
        unsigned char a[4];
        int c;

        EFREAD(a, 4, 1, f);
        c = fgetc(f);
        types[i].isdst = (unsigned char)c;
        if ((c = fgetc(f)) < 0) {
            break;
        }
        types[i].abbr = (unsigned int)c;
        types[i].gmtoff = decode(a);
    }

    znames = (char *)malloc(num_chars);
    if (znames == NULL) {
        icalerror_set_errno(ICAL_NEWFAILED_ERROR);
        goto error;
    }
    EFREAD(znames, num_chars, 1, f);

    /* We got all the information which we need */

    leaps = calloc(num_leaps, sizeof(leap));
    if (leaps == NULL) {
        icalerror_set_errno(ICAL_NEWFAILED_ERROR);
        goto error;
    }
    for (i = 0; i < num_leaps; i++) {
        char c[4];

        EFREAD(c, 4, 1, f);
        leaps[i].transition = (time_t)decode(c);

        EFREAD(c, 4, 1, f);
        leaps[i].change = decode(c);
    }

    for (i = 0; i < num_isstd; ++i) {
        int c = getc(f);
        types[i].isstd = c != 0;
    }

    while (i < num_types) {
        types[i++].isstd = 0;
    }

    for (i = 0; i < num_isgmt; ++i) {
        int c = getc(f);

        types[i].isgmt = c != 0;
    }

    while (i < num_types) {
        types[i++].isgmt = 0;
    }

    /* Read all the contents now */

    for (i = 0; i < num_types; i++) {
        /* coverity[tainted_data] */
        types[i].zname = zname_from_stridx(znames, types[i].abbr);
    }

    if (!_s_use_exact_timezones) {
        if (num_trans != 0) {
            find_transidx(transitions, types, trans_idx, (long int)num_trans, &stdidx, &dstidx);
        } else {
            stdidx = 0;
        }
    }

    tz_comp = icalcomponent_new(ICAL_VTIMEZONE_COMPONENT);

    /* Add tzid property */
    size = strlen(icaltimezone_tzid_prefix()) + strlen(location) + 1;
    tzid = (char *)malloc(size);
    if (tzid == NULL) {
        icalerror_set_errno(ICAL_NEWFAILED_ERROR);
        goto error;
    }
    snprintf(tzid, size, "%s%s", icaltimezone_tzid_prefix(), location);
    icalprop = icalproperty_new_tzid(tzid);
    icalcomponent_add_property(tz_comp, icalprop);

    icalprop = icalproperty_new_x(location);
    icalproperty_set_x_name(icalprop, "X-LIC-LOCATION");
    icalcomponent_add_property(tz_comp, icalprop);

    if (!_s_use_exact_timezones) {
        if (stdidx != -1) {
            if (num_trans != 0) {
                zidx = trans_idx[stdidx];
            } else {
                zidx = 0;
            }

            std_comp = icalcomponent_new(ICAL_XSTANDARD_COMPONENT);
            icalprop = icalproperty_new_tzname(types[zidx].zname);
            icalcomponent_add_property(std_comp, icalprop);

            if (dstidx != -1) {
                zp_idx = trans_idx[stdidx-1];
            } else {
                zp_idx = zidx;
            }
            /* DTSTART localtime uses TZOFFSETFROM UTC offset */
            if (num_trans != 0) {
                trans = transitions[stdidx] + types[zp_idx].gmtoff;
            } else {
                trans = (time_t)types[zp_idx].gmtoff;
            }
            icaltime = icaltime_from_timet_with_zone(trans, 0, NULL);
            dtstart = icaltime;
            dtstart.year = 1970;
            dtstart.minute = dtstart.second = 0;
            icalprop = icalproperty_new_dtstart(dtstart);
            icalcomponent_add_property(std_comp, icalprop);

            /* If DST changes are present use RRULE */
            if (dstidx != -1) {
                icalrecurrencetype_clear(&ical_recur);
                ical_recur.freq = ICAL_YEARLY_RECURRENCE;
                ical_recur.by_month[0] = icaltime.month;
                pos = calculate_pos(icaltime);
                pos < 0 ? (sign = -1): (sign = 1);
                ical_recur.by_day[0] = sign * ((abs(pos) * 8) + icaltime_day_of_week(icaltime));
                icalprop = icalproperty_new_rrule(ical_recur);
                icalcomponent_add_property(std_comp, icalprop);

                adjust_dtstart_day_to_rrule(std_comp, ical_recur);
            }
            icalprop = icalproperty_new_tzoffsetfrom(types[zp_idx].gmtoff);
            icalcomponent_add_property(std_comp, icalprop);
            icalprop = icalproperty_new_tzoffsetto(types[zidx].gmtoff);
            icalcomponent_add_property(std_comp, icalprop);
            icalcomponent_add_component(tz_comp, std_comp);
        } else {
            icalerror_set_errno(ICAL_MALFORMEDDATA_ERROR);
        }

        if (dstidx != -1) {
            zidx = trans_idx[dstidx];
            zp_idx = trans_idx[dstidx-1];
            dst_comp = icalcomponent_new(ICAL_XDAYLIGHT_COMPONENT);
            icalprop = icalproperty_new_tzname(types[zidx].zname);
            icalcomponent_add_property(dst_comp, icalprop);

            /* DTSTART localtime uses TZOFFSETFROM UTC offset */
            trans = transitions[dstidx] + types[zp_idx].gmtoff;

            icaltime = icaltime_from_timet_with_zone(trans, 0, NULL);
            dtstart = icaltime;
            dtstart.year = 1970;
            dtstart.minute = dtstart.second = 0;
            icalprop = icalproperty_new_dtstart(dtstart);
            icalcomponent_add_property(dst_comp, icalprop);

            icalrecurrencetype_clear(&ical_recur);
            ical_recur.freq = ICAL_YEARLY_RECURRENCE;
            ical_recur.by_month[0] = icaltime.month;
            pos = calculate_pos(icaltime);
            pos < 0 ? (sign = -1): (sign = 1);
            ical_recur.by_day[0] = sign * ((abs(pos) * 8) + icaltime_day_of_week(icaltime));
            icalprop = icalproperty_new_rrule(ical_recur);
            icalcomponent_add_property(dst_comp, icalprop);

            adjust_dtstart_day_to_rrule(dst_comp, ical_recur);

            icalprop = icalproperty_new_tzoffsetfrom(types[zp_idx].gmtoff);
            icalcomponent_add_property(dst_comp, icalprop);

            icalprop = icalproperty_new_tzoffsetto(types[zidx].gmtoff);
            icalcomponent_add_property(dst_comp, icalprop);

            icalcomponent_add_component(tz_comp, dst_comp);
        }
    } else { /*exact vtimezones*/
        prev_idx = 0;
        if (num_trans == 0) {
            prev_idx = idx = 0;
        } else {
            idx = trans_idx[0];
        }
        start = 0;
        for (i = 1; i < num_trans; i++, start = end) {
            prev_idx = idx;
            idx = trans_idx[i];
            end = transitions[i] + types[prev_idx].gmtoff;
            /* don't bother starting until the epoch */
            if (0 > end)
                continue;

            if (types[prev_idx].isdst) {
                comp = icalcomponent_new(ICAL_XDAYLIGHT_COMPONENT);
            } else {
                comp = icalcomponent_new(ICAL_XSTANDARD_COMPONENT);
            }
            icalprop = icalproperty_new_tzname(types[prev_idx].zname);
            icalcomponent_add_property(comp, icalprop);
            dtstart = icaltime_from_timet_with_zone(start, 0, NULL);
            icalprop = icalproperty_new_dtstart(dtstart);
            icalcomponent_add_property(comp, icalprop);
            icalprop = icalproperty_new_tzoffsetfrom(types[idx].gmtoff);
            icalcomponent_add_property(comp, icalprop);
            icalprop = icalproperty_new_tzoffsetto(types[prev_idx].gmtoff);
            icalcomponent_add_property(comp, icalprop);
            icalcomponent_add_component(tz_comp, comp);
        }
        /* finally, add a last zone with no end date */
        if (types[idx].isdst) {
            comp = icalcomponent_new(ICAL_XDAYLIGHT_COMPONENT);
        } else {
            comp = icalcomponent_new(ICAL_XSTANDARD_COMPONENT);
        }
        icalprop = icalproperty_new_tzname(types[idx].zname);
        icalcomponent_add_property(comp, icalprop);
        dtstart = icaltime_from_timet_with_zone(start, 0, NULL);
        icalprop = icalproperty_new_dtstart(dtstart);
        icalcomponent_add_property(comp, icalprop);
        icalprop = icalproperty_new_tzoffsetfrom(types[prev_idx].gmtoff);
        icalcomponent_add_property(comp, icalprop);
        icalprop = icalproperty_new_tzoffsetto(types[idx].gmtoff);
        icalcomponent_add_property(comp, icalprop);
        icalcomponent_add_component(tz_comp, comp);
    }

  error:
    if (f)
        fclose(f);

    if (full_path)
        free(full_path);

    if (transitions)
        free(transitions);

    if (r_trans)
        free(r_trans);

    if (trans_idx)
        free(trans_idx);

    if (types) {
        for (i = 0; i < num_types; i++) {
            if (types[i].zname) {
                free(types[i].zname);
            }
        }
        free(types);
    }

    if (znames)
        free(znames);

    if (leaps)
        free(leaps);

    if (tzid)
        free(tzid);

    return tz_comp;
}
icalcomponent* icalparser_add_line(icalparser* parser,
                                       char* line)
{ 
    char *str;
    char *end;
    int vcount = 0;
    icalproperty *prop;
    icalproperty_kind prop_kind;
    icalvalue *value;
    icalvalue_kind value_kind = ICAL_NO_VALUE;


    icalerror_check_arg_rz((parser != 0),"parser");


    if (line == 0)
    {
	parser->state = ICALPARSER_ERROR;
	return 0;
    }

    if(line_is_blank(line) == 1){
	return 0;
    }

    /* Begin by getting the property name at the start of the line. The
       property name may end up being "BEGIN" or "END" in which case it
       is not really a property, but the marker for the start or end of
       a component */

    end = 0;
    str = parser_get_prop_name(line, &end);

    if (str == 0 || *str == '\0' ){
	/* Could not get a property name */
	icalcomponent *tail = pvl_data(pvl_tail(parser->components));

	if (tail){
	    insert_error(tail,line,
			 "Got a data line, but could not find a property name or component begin tag",
			 ICAL_XLICERRORTYPE_COMPONENTPARSEERROR);
	}
	tail = 0;
	parser->state = ICALPARSER_ERROR;
	icalmemory_free_buffer(str);
	str = NULL;
	return 0; 
    }

    /**********************************************************************
     * Handle begin and end of components
     **********************************************************************/
    /* If the property name is BEGIN or END, we are actually
       starting or ending a new component */


    if(strcasecmp(str,"BEGIN") == 0){
	icalcomponent *c;
        icalcomponent_kind comp_kind;

	icalmemory_free_buffer(str);
	str = NULL;

	parser->level++;
	str = parser_get_next_value(end,&end, value_kind);
	    

        comp_kind = icalenum_string_to_component_kind(str);


        if (comp_kind == ICAL_NO_COMPONENT){


	    c = icalcomponent_new(ICAL_XLICINVALID_COMPONENT);
	    insert_error(c,str,"Parse error in component name",
			 ICAL_XLICERRORTYPE_COMPONENTPARSEERROR);
        }

	c  =  icalcomponent_new(comp_kind);

	if (c == 0){
	    c = icalcomponent_new(ICAL_XLICINVALID_COMPONENT);
	    insert_error(c,str,"Parse error in component name",
			 ICAL_XLICERRORTYPE_COMPONENTPARSEERROR);
	}
	    
	pvl_push(parser->components,c);

	parser->state = ICALPARSER_BEGIN_COMP;

	icalmemory_free_buffer(str);
	str = NULL;
	return 0;

    } else if (strcasecmp(str,"END") == 0 ) {
	icalcomponent* tail;

	icalmemory_free_buffer(str);
	str = NULL;
	parser->level--;

	str = parser_get_next_value(end,&end, value_kind);

	/* Pop last component off of list and add it to the second-to-last*/
	parser->root_component = pvl_pop(parser->components);

	tail = pvl_data(pvl_tail(parser->components));

	if(tail != 0){
	    icalcomponent_add_component(tail,parser->root_component);
	} 

	tail = 0;
	icalmemory_free_buffer(str);
	str = NULL;

	/* Return the component if we are back to the 0th level */
	if (parser->level == 0){
	    icalcomponent *rtrn; 

	    if(pvl_count(parser->components) != 0){
	    /* There are still components on the stack -- this means
               that one of them did not have a proper "END" */
		pvl_push(parser->components,parser->root_component);
		icalparser_clean(parser); /* may reset parser->root_component*/
	    }

	    assert(pvl_count(parser->components) == 0);

	    parser->state = ICALPARSER_SUCCESS;
	    rtrn = parser->root_component;
	    parser->root_component = 0;
	    return rtrn;

	} else {
	    parser->state = ICALPARSER_END_COMP;
	    return 0;
	}
    }


    /* There is no point in continuing if we have not seen a
       component yet */

    if(pvl_data(pvl_tail(parser->components)) == 0){
	parser->state = ICALPARSER_ERROR;
	icalmemory_free_buffer(str);
	str = NULL;
	return 0;
    }


    /**********************************************************************
     * Handle property names
     **********************************************************************/
								       
    /* At this point, the property name really is a property name,
       (Not a component name) so make a new property and add it to
       the component */

    
    prop_kind = icalproperty_string_to_kind(str);

    prop = icalproperty_new(prop_kind);

    if (prop != 0){
	icalcomponent *tail = pvl_data(pvl_tail(parser->components));

        if(prop_kind==ICAL_X_PROPERTY){
            icalproperty_set_x_name(prop,str);
        }

	icalcomponent_add_property(tail, prop);

	/* Set the value kind for the default for this type of
	   property. This may be re-set by a VALUE parameter */
	value_kind = icalproperty_kind_to_value_kind(icalproperty_isa(prop));

    } else {
	icalcomponent* tail = pvl_data(pvl_tail(parser->components));

	insert_error(tail,str,"Parse error in property name",
		     ICAL_XLICERRORTYPE_PROPERTYPARSEERROR);
	    
	tail = 0;
	parser->state = ICALPARSER_ERROR;
	icalmemory_free_buffer(str);
	str = NULL;
	return 0;
    }

    icalmemory_free_buffer(str);
    str = NULL;

    /**********************************************************************
     * Handle parameter values
     **********************************************************************/								       

    /* Now, add any parameters to the last property */

    while(1) {

	if (*(end-1) == ':'){
	    /* if the last separator was a ":" and the value is a
	       URL, icalparser_get_next_parameter will find the
	       ':' in the URL, so better break now. */
	    break;
	}

	str = parser_get_next_parameter(end,&end);
	strstriplt(str);
	if (str != 0){
	    char* name = 0;
	    char* pvalue = 0;
	    char *buf_value = NULL;
        
	    icalparameter *param = 0;
	    icalparameter_kind kind;
	    icalcomponent *tail = pvl_data(pvl_tail(parser->components));

	    name = parser_get_param_name(str,&pvalue,&buf_value);

	    if (name == 0){
		/* 'tail' defined above */
		insert_error(tail, str, "Cant parse parameter name",
			     ICAL_XLICERRORTYPE_PARAMETERNAMEPARSEERROR);
		tail = 0;
		break;
	    }

	    kind = icalparameter_string_to_kind(name);

	    if(kind == ICAL_X_PARAMETER){
		param = icalparameter_new(ICAL_X_PARAMETER);
		
		if(param != 0){
		    icalparameter_set_xname(param,name);
		    icalparameter_set_xvalue(param,pvalue);
		}
		icalmemory_free_buffer(buf_value);
		buf_value = NULL;

	    } else if (kind != ICAL_NO_PARAMETER){
		param = icalparameter_new_from_value_string(kind,pvalue);

		icalmemory_free_buffer(buf_value);
		buf_value = NULL;

	    } else {
		/* Error. Failed to parse the parameter*/
		/* 'tail' defined above */

                /* Change for mozilla */
                /* have the option of being flexible towards unsupported parameters */
                #ifndef ICAL_ERRORS_ARE_FATAL
                continue;
                #endif

		insert_error(tail, str, "Cant parse parameter name",
			     ICAL_XLICERRORTYPE_PARAMETERNAMEPARSEERROR);
		tail = 0;
		parser->state = ICALPARSER_ERROR;
		/* if (pvalue) {
			free(pvalue);
			pvalue = 0;
		} */
		if (name) {
			free(name);
			name = 0;
		}
		return 0;
	    }

	    /* if (pvalue) {
		free(pvalue);
		pvalue = 0;
	    } */
	    if (name) {
		free(name);
		name = 0;
	    }

	    if (param == 0){
		/* 'tail' defined above */
		insert_error(tail,str,"Cant parse parameter value",
			     ICAL_XLICERRORTYPE_PARAMETERVALUEPARSEERROR);
		    
		tail = 0;
		parser->state = ICALPARSER_ERROR;
		
		icalmemory_free_buffer(buf_value);
		buf_value = NULL;
		icalmemory_free_buffer(name);
		name = NULL;
		icalmemory_free_buffer(str);
		str = NULL;
  	  	
		continue;
	    }

	    /* If it is a VALUE parameter, set the kind of value*/
	    if (icalparameter_isa(param)==ICAL_VALUE_PARAMETER){

		value_kind = (icalvalue_kind)
                    icalparameter_value_to_value_kind(
                                icalparameter_get_value(param)
                                );

		if (value_kind == ICAL_NO_VALUE){

		    /* Ooops, could not parse the value of the
		       parameter ( it was not one of the defined
		       values ), so reset the value_kind */
			
		    insert_error(
			tail, str, 
			"Got a VALUE parameter with an unknown type",
			ICAL_XLICERRORTYPE_PARAMETERVALUEPARSEERROR);
		    icalparameter_free(param);
			
		    value_kind = 
			icalproperty_kind_to_value_kind(
			    icalproperty_isa(prop));
			
		    icalparameter_free(param);
		    tail = 0;
		    parser->state = ICALPARSER_ERROR;

			icalmemory_free_buffer(name);
			name = NULL;
			icalmemory_free_buffer(str);
			str = NULL;
		    continue;
		} 
	    }
		icalmemory_free_buffer(name);
		name = NULL;

	    /* Everything is OK, so add the parameter */
	    icalproperty_add_parameter(prop,param);
	    tail = 0;
	    icalmemory_free_buffer(str);
	    str = NULL;

	} else { /* if ( str != 0)  */
	    /* If we did not get a param string, go on to looking for a value */
		if (str != NULL) {
			icalmemory_free_buffer(str);
			str = NULL;
		}
	    break;
	} /* if ( str != 0)  */

    } /* while(1) */	    
	
    /**********************************************************************
     * Handle values
     **********************************************************************/								       

    /* Look for values. If there are ',' characters in the values,
       then there are multiple values, so clone the current
       parameter and add one part of the value to each clone */

    vcount=0;
    while(1) {
        /* Only some properies can have multiple values. This list was taken
           from rfc2445. Also added the x-properties, because the spec actually
           says that commas should be escaped. For x-properties, other apps may
           depend on that behaviour
        */
        switch (prop_kind) {
            case ICAL_X_PROPERTY:
            case ICAL_CATEGORIES_PROPERTY:
            case ICAL_RESOURCES_PROPERTY:
            /* Referring to RFC 2445, section 4.8.5.3 and section 4.8.5.1:
               RDATE and EXDATE can specify a list of dates/date-times/periods.
            */
            case ICAL_RDATE_PROPERTY:
            case ICAL_EXDATE_PROPERTY:
            /* Referring to RFC 2445, section 4.8.2.6 Free/Busy Time:
               The "FREEBUSY" property can specify more than one value, separated by
               the COMMA character (US-ASCII decimal 44).
            */
            case ICAL_FREEBUSY_PROPERTY:
                 str = parser_get_next_value(end,&end, value_kind);
		 strstriplt (str);
                 break;
            default:
                 str = icalparser_get_value(end, &end, value_kind);
		 strstriplt (str);
                 break;
        }

	if (str != 0){
		
	    if (vcount > 0){
		/* Actually, only clone after the second value */
		icalproperty* clone = icalproperty_new_clone(prop);
		icalcomponent* tail = pvl_data(pvl_tail(parser->components));
		    
		icalcomponent_add_property(tail, clone);
		prop = clone;		    
		tail = 0;
	    }
		
	    value = icalvalue_new_from_string(value_kind, str);
		
	    /* Don't add properties without value */
	    if (value == 0){
		char temp[200]; /* HACK */

		icalproperty_kind prop_kind = icalproperty_isa(prop);
		icalcomponent* tail = pvl_data(pvl_tail(parser->components));

		snprintf(temp,sizeof(temp),"Can't parse as %s value in %s property. Removing entire property",
			icalvalue_kind_to_string(value_kind),
			icalproperty_kind_to_string(prop_kind));

		insert_error(tail, str, temp,
			     ICAL_XLICERRORTYPE_VALUEPARSEERROR);

		/* Remove the troublesome property */
		icalcomponent_remove_property(tail,prop);
		icalproperty_free(prop);
		prop = 0;
		tail = 0;
		parser->state = ICALPARSER_ERROR;
	
		icalmemory_free_buffer(str);
		str = NULL;
		return 0;
		    
	    } else {
		vcount++;
		icalproperty_set_value(prop, value);
	    }
 	    icalmemory_free_buffer(str);
	    str = NULL;

	} else {
		if (str != NULL) {
			icalmemory_free_buffer(str);
			str = NULL;
		}
			
	    if (vcount == 0){
		char temp[200]; /* HACK */
		
		icalproperty_kind prop_kind = icalproperty_isa(prop);
		icalcomponent *tail = pvl_data(pvl_tail(parser->components));
		
		snprintf(temp,sizeof(temp),"No value for %s property. Removing entire property",
			icalproperty_kind_to_string(prop_kind));

		insert_error(tail, str, temp,
			     ICAL_XLICERRORTYPE_VALUEPARSEERROR);

		/* Remove the troublesome property */
		icalcomponent_remove_property(tail,prop);
		icalproperty_free(prop);
		prop = 0;
		tail = 0;
		parser->state = ICALPARSER_ERROR;
		return 0;
	    } else {

		break;
	    }
	}
    }
	
    /****************************************************************
     * End of component parsing. 
     *****************************************************************/

    if (pvl_data(pvl_tail(parser->components)) == 0 &&
	parser->level == 0){
	/* HACK. Does this clause ever get executed? */
	parser->state = ICALPARSER_SUCCESS;
	assert(0);
	return parser->root_component;
    } else {
	parser->state = ICALPARSER_IN_PROGRESS;
	return 0;
    }

}
Exemple #21
0
/*
 * Construct an iCalendar component from a XML element.
 */
static icalcomponent *xml_element_to_icalcomponent(xmlNodePtr xcomp)
{
    icalcomponent_kind kind;
    icalcomponent *comp = NULL;
    xmlNodePtr node, xprop, xsub;

    if (!xcomp) return NULL;

    /* Get component type */
    kind =
        icalenum_string_to_component_kind(
            ucase(icalmemory_tmp_copy((const char *) xcomp->name)));
    if (kind == ICAL_NO_COMPONENT) {
        syslog(LOG_WARNING, "Unknown xCal component type: %s", xcomp->name);
        return NULL;
    }

    /* Create new component */
    comp = icalcomponent_new(kind);
    if (!comp) {
        syslog(LOG_ERR, "Creation of new %s component failed", xcomp->name);
        return NULL;
    }

    /* Add properties */
    node = xmlFirstElementChild(xcomp);
    if (!node || xmlStrcmp(node->name, BAD_CAST "properties")) {
        syslog(LOG_WARNING,
               "Expected <properties> XML element, received %s", node->name);
        goto error;
    }
    for (xprop = xmlFirstElementChild(node); xprop;
            xprop = xmlNextElementSibling(xprop)) {
        icalproperty *prop = xml_element_to_icalproperty(xprop);

        if (!prop) goto error;

        icalcomponent_add_property(comp, prop);
    }

    /* Add sub-components */
    if (!(node = xmlNextElementSibling(node))) return comp;

    if (xmlStrcmp(node->name, BAD_CAST "components")) {
        syslog(LOG_WARNING,
               "Expected <components> XML element, received %s", node->name);
        goto error;
    }

    for (xsub = xmlFirstElementChild(node); xsub;
            xsub = xmlNextElementSibling(xsub)) {
        icalcomponent *sub = xml_element_to_icalcomponent(xsub);

        if (!sub) goto error;

        icalcomponent_add_component(comp, sub);
    }

    /* Sanity check */
    if ((node = xmlNextElementSibling(node))) {
        syslog(LOG_WARNING,
               "Unexpected XML element in component: %s", node->name);
        goto error;
    }

    return comp;

error:
    icalcomponent_free(comp);
    return NULL;
}
Exemple #22
0
int main()
{
  vector<string> classes; //the first line of the ics7 file contains the elements of this
  
  icalproperty_set_x_name(ical_x_class_prop, "X-CLASS");

  icalcomponent* calendar = NULL;
  struct icaltimetype atime;
  struct icalperiodtype rtime;

  //FIXME Later versions will try to load from the default file here
  
  //If we don't have a saved calendar, make a new one
  if (calendar == NULL)
  {
    atime = icaltime_from_timet( time(0),0);

    rtime.start = icaltime_from_timet( time(0),0);
    rtime.end = icaltime_from_timet( time(0),0);
    rtime.end.hour++;
    
    calendar = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
  }
  
  //FIXME Find all non-school days by prompt?
  
  //FIXME Ask for start/end of semester
  
  //Actually manipulating the calendar
  while (true)
  {
    //Prompt for user action
    cout << "What would you like to do?\n" <<
      "1. Add a class\n" <<
      "2. Add an event\n" <<
      "3. Delete an event\n" <<
      "4. Edit an event\n" <<
      "5. Find an event\n" <<
      "6. View an event\n" << 
      "7. Delete a class\n" <<
      "8. Exit the program\n" << endl;
    cout << "Enter the integer corresponding to your choice" << endl;
    
    string user_choice = "";
    cin >> user_choice;
    
    bool user_choice_flag = true;
    
    //Check the string is all digits
    for (int i = 0; i < user_choice.size(); i++)
    {
      if (!isdigit(user_choice[i]))
      {
        cout << "Invalid selection (Not all digits)" << endl;
        user_choice_flag = false;
        break;
      }
    }
    
    if (!user_choice_flag)
    {
      continue;
    }
    
    //Given the choice, perform the desired action
    switch (atoi(user_choice.c_str()))
    {
      //ADD CLASS
      case 1:
      {
        add_class(calendar, classes);
        break;
      }
      
      //ADD EVENT (for a class or in general)
      case 2:
      {
        add_event(calendar);
        break;
      }
      
      //DELETE SINGLE EVENT
      case 3:
      {
        delete_event(calendar);
        break;
      }
      
      //EDIT EVENT (class or general)
      case 4:
      {
        edit_event(calendar);
        break;
      }
      
      //FIND EVENT
      case 5:
      {
        icalcomponent* event = find_event(calendar);
        if (event == NULL)
        {
          append_action_to_closed_log("Find event", false);
        }else
        {
          append_action_to_closed_log("Find event", true);
        }
        break;
      }
      
      //VIEW EVENT
      case 6:
      {
        view_event(calendar);
        break;
      }
      
      //DELETE CLASS
      //FIXME Not implemented in this sprint
      case 7:
      {
        //FIXME Ask for class name
        //FIXME Scan through first level of components for class
        //FIXME Print all matches and get the one to delete
        //FIXME Warn that all events for that class will be deleted
        //FIXME Delete class after user okay
        
        cout << "This feature is not implemented in this sprint." << endl;
        break;
      }
      
      //EXIT
      case 8:
      {
        //Prompt for okay
        if (yes_no_prompt("Your calendar data will not be saved. Continue? (y/n)"))
        {
          return 0;
        }
        
        break;
      }
      
      default:
      {
        cout << "Invalid selection (Not between 1 and 8 inclusive)" << endl;
        break;
      }
    }
  }
  
  return 0;
}
Exemple #23
0
/* This populates a cluster with the entire contents of a database */
static icalerrorenum icalbdbset_read_database(icalbdbset *bset, char *(*pfunc) (const DBT *dbt))
{
    DB *dbp;
    DBC *dbcp;
    DBT key, data;
    char *str;
    int ret = EINVAL;
    char keystore[256];
    char datastore[1024];
    char *more_mem = NULL;
    DB_TXN *tid;

    _unused(pfunc);

    memset(&key, 0, sizeof(DBT));
    memset(&data, 0, sizeof(DBT));

    if (bset->sdbp) {
        dbp = bset->sdbp;
    } else {
        dbp = bset->dbp;
    }

    if (!dbp) {
        return ICAL_FILE_ERROR;
    }

    bset->cluster = icalcomponent_new(ICAL_XROOT_COMPONENT);

    if ((ret = ICAL_DB_ENV->txn_begin(ICAL_DB_ENV, NULL, &tid, 0)) != 0) {
        /*char *foo = db_strerror(ret); */
        abort();
    }

    /* acquire a cursor for the database */
    if ((ret = dbp->cursor(dbp, tid, &dbcp, 0)) != 0) {
        dbp->err(dbp, ret, "primary index");
        goto err1;
    }

    key.flags = DB_DBT_USERMEM;
    key.data = keystore;
    key.ulen = (u_int32_t) sizeof(keystore);

    data.flags = DB_DBT_USERMEM;
    data.data = datastore;
    data.ulen = (u_int32_t) sizeof(datastore);

    /* fetch the key/data pair */
    while (1) {
        ret = dbcp->c_get(dbcp, &key, &data, DB_NEXT);
        if (ret == DB_NOTFOUND) {
            break;
        } else if (ret == ENOMEM) {
            if (more_mem) {
                free(more_mem);
            }
            more_mem = malloc(data.ulen + 1024);
            data.data = more_mem;
            data.ulen = data.ulen + 1024;
        } else if (ret == DB_LOCK_DEADLOCK) {
            /*char *foo = db_strerror(ret); */
            abort();    /* should retry in case of DB_LOCK_DEADLOCK */
        } else if (ret) {
            /*char *foo = db_strerror(ret); */
            /* some other weird-ass error  */
            dbp->err(dbp, ret, "cursor");
            abort();
        } else {
            icalcomponent *cl;

            /* this prevents an array read bounds error */
            if ((str = (char *)calloc(data.size + 1, sizeof(char))) == NULL) {
                goto err2;
            }
            memcpy(str, (char *)data.data, data.size);

            cl = icalparser_parse_string(str);

            icalcomponent_add_component(bset->cluster, cl);
            free(str);
        }
    }
    if (ret != DB_NOTFOUND) {
        goto err2;
    }

    if (more_mem) {
        free(more_mem);
        more_mem = NULL;
    }

    if ((ret = dbcp->c_close(dbcp)) != 0) {
        /*char *foo = db_strerror(ret); */
        abort();        /* should retry in case of DB_LOCK_DEADLOCK */
    }

    if ((ret = tid->commit(tid, 0)) != 0) {
        /*char *foo = db_strerror(ret); */
        abort();
    }

    return ICAL_NO_ERROR;

  err2:
    if (more_mem) {
        free(more_mem);
    }
    dbcp->c_close(dbcp);
    abort();    /* should retry in case of DB_LOCK_DEADLOCK */
    return ICAL_INTERNAL_ERROR;

  err1:
    dbp->err(dbp, ret, "cursor index");
    abort();
    return ICAL_FILE_ERROR;
}
icalcomponent* icalmime_parse(char* (*get_string)(char *s, size_t size, 
						       void *d),
				void *data)
{
    struct sspm_part *parts;
    int i, last_level=0;
    icalcomponent *root=0, *parent=0, *comp=0, *last = 0;

    if ( (parts = (struct sspm_part *)
	  malloc(NUM_PARTS*sizeof(struct sspm_part)))==0) {
	icalerror_set_errno(ICAL_NEWFAILED_ERROR);
	return 0;
    }

    memset(parts,0,sizeof(parts));

    sspm_parse_mime(parts, 
		    NUM_PARTS, /* Max parts */
		    icalmime_local_action_map, /* Actions */ 
		    get_string,
		    data, /* data for get_string*/
		    0 /* First header */);



    for(i = 0; i <NUM_PARTS && parts[i].header.major != SSPM_NO_MAJOR_TYPE ; i++){

#define TMPSZ 1024
	char mimetype[TMPSZ];			       
	const char* major = sspm_major_type_string(parts[i].header.major);
	const char* minor = sspm_minor_type_string(parts[i].header.minor);

	if(parts[i].header.minor == SSPM_UNKNOWN_MINOR_TYPE ){
	    assert(parts[i].header.minor_text !=0);
	    minor = parts[i].header.minor_text;
	}
	
	snprintf(mimetype,sizeof(mimetype),"%s/%s",major,minor);

	comp = icalcomponent_new(ICAL_XLICMIMEPART_COMPONENT);

	if(comp == 0){
	    /* HACK Handle Error */
	    assert(0);
	}

	if(parts[i].header.error!=SSPM_NO_ERROR){
	    const char *str="Unknown error";
	    char temp[256];
	    if(parts[i].header.error==SSPM_MALFORMED_HEADER_ERROR){
		str = "Malformed header, possibly due to input not in MIME format";
	    }

	    if(parts[i].header.error==SSPM_UNEXPECTED_BOUNDARY_ERROR){
		str = "Got an unexpected boundary, possibly due to a MIME header for a MULTIPART part that is missing the Content-Type line";
	    }

	    if(parts[i].header.error==SSPM_WRONG_BOUNDARY_ERROR){
		str = "Got the wrong boundary for the opening of a MULTIPART part.";
	    }

	    if(parts[i].header.error==SSPM_NO_BOUNDARY_ERROR){
		str = "Got a multipart header that did not specify a boundary";
	    }

	    if(parts[i].header.error==SSPM_NO_HEADER_ERROR){
		str = "Did not get a header for the part. Is there a blank\
line between the header and the previous boundary\?";

	    }

	    if(parts[i].header.error_text != 0){
		snprintf(temp,256,
			 "%s: %s",str,parts[i].header.error_text);
	    } else {
		strcpy(temp,str);
	    }

	    icalcomponent_add_property
		(comp,
		 icalproperty_vanew_xlicerror(
		     temp,
		     icalparameter_new_xlicerrortype(
			 ICAL_XLICERRORTYPE_MIMEPARSEERROR),
		     0));  
	}

	if(parts[i].header.major != SSPM_NO_MAJOR_TYPE &&
	   parts[i].header.major != SSPM_UNKNOWN_MAJOR_TYPE){

	    icalcomponent_add_property(comp,
		icalproperty_new_xlicmimecontenttype((char*)
				icalmemory_strdup(mimetype)));

	}

	if (parts[i].header.encoding != SSPM_NO_ENCODING){

	    icalcomponent_add_property(comp,
	       icalproperty_new_xlicmimeencoding(
		   sspm_encoding_string(parts[i].header.encoding)));
	}

	if (parts[i].header.filename != 0){
	    icalcomponent_add_property(comp,
	       icalproperty_new_xlicmimefilename(parts[i].header.filename));
	}

	if (parts[i].header.content_id != 0){
	    icalcomponent_add_property(comp,
	       icalproperty_new_xlicmimecid(parts[i].header.content_id));
	}

	if (parts[i].header.charset != 0){
	    icalcomponent_add_property(comp,
	       icalproperty_new_xlicmimecharset(parts[i].header.charset));
	}

	/* Add iCal components as children of the component */
	if(parts[i].header.major == SSPM_TEXT_MAJOR_TYPE &&
	   parts[i].header.minor == SSPM_CALENDAR_MINOR_TYPE &&
	   parts[i].data != 0){

	    icalcomponent_add_component(comp,
					(icalcomponent*)parts[i].data);
	    parts[i].data = 0;

	} else 	if(parts[i].header.major == SSPM_TEXT_MAJOR_TYPE &&
	   parts[i].header.minor != SSPM_CALENDAR_MINOR_TYPE &&
	   parts[i].data != 0){

	    /* Add other text components as "DESCRIPTION" properties */

	    icalcomponent_add_property(comp,
               icalproperty_new_description(
		   (char*)icalmemory_strdup((char*)parts[i].data)));

	    parts[i].data = 0;
	}
	

	if(root!= 0 && parts[i].level == 0){
	    /* We've already assigned the root, but there is another
               part at the root level. This is probably a parse
               error*/
	    icalcomponent_free(comp);
	    continue;
	}

	if(parts[i].level == last_level && last_level != 0){
	    icalerror_assert(parent!=0,"No parent for adding component");

	    icalcomponent_add_component(parent,comp);

	} else if (parts[i].level == last_level && last_level == 0 &&
	    root == 0) {

	    root = comp;
	    parent = comp;

	} else if (parts[i].level > last_level){	    

	    parent = last;
	    icalcomponent_add_component(parent,comp);

	    last_level = parts[i].level;

	} else if (parts[i].level < last_level){

	    if (parent) 
	        parent = icalcomponent_get_parent(parent);
	    icalcomponent_add_component(parent,comp);

	    last_level = parts[i].level;
	} else { 
	    assert(0);
	}

	last = comp;
	last_level = parts[i].level;
	assert(parts[i].data == 0);
    }

    sspm_free_parts(parts,NUM_PARTS);
    free(parts);

    return root;
}
/* Create a new component */
void create_new_component()
{
    icalcomponent* calendar;
    icalcomponent* timezone;
    icalcomponent* tzc;
    icalcomponent* event;
    struct icaltimetype atime = icaltime_from_timet( 1023398689, 0);
    struct icaldatetimeperiodtype rtime;
    icalproperty* property;
    char *calendar_as_string;

    rtime.period.start = icaltime_from_timet( 1023398689,0);
    rtime.period.end = icaltime_from_timet( 1023409689,0);
    rtime.period.end.hour++;
    rtime.time = icaltime_null_time();

    /* Create calendar and add properties */
    calendar = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);

    
    icalcomponent_add_property(
	calendar,
	icalproperty_new_version("2.0")
	);
    
    icalcomponent_add_property(
	calendar,
	icalproperty_new_prodid("-//RDU Software//NONSGML HandCal//EN")
	);
    
    /* Create a timezone object and add it to the calendar */

    timezone = icalcomponent_new(ICAL_VTIMEZONE_COMPONENT);

    icalcomponent_add_property(
	timezone,
	icalproperty_new_tzid("America/New_York")
	);

    /* Add a sub-component of the timezone */
    tzc = icalcomponent_new(ICAL_XDAYLIGHT_COMPONENT);

    icalcomponent_add_property(
	tzc, 
	icalproperty_new_dtstart(atime)
	);

    icalcomponent_add_property(
	tzc, 
	icalproperty_new_rdate(rtime)
	);
	    
    icalcomponent_add_property(
	tzc, 
	icalproperty_new_tzoffsetfrom(-5*3600)
	);

    icalcomponent_add_property(
	tzc, 
	icalproperty_new_tzoffsetto(-4*3600)
	);

    icalcomponent_add_property(
	tzc, 
	icalproperty_new_tzname("EST")
	);

    icalcomponent_add_component(timezone,tzc);

    icalcomponent_add_component(calendar,timezone);

    /* Add a second subcomponent */
    tzc = icalcomponent_new(ICAL_XSTANDARD_COMPONENT);

    icalcomponent_add_property(
	tzc, 
	icalproperty_new_dtstart(atime)
	);

    icalcomponent_add_property(
	tzc, 
	icalproperty_new_rdate(rtime)
	);
	    
    icalcomponent_add_property(
	tzc, 
	icalproperty_new_tzoffsetfrom(-4*3600)
	);

    icalcomponent_add_property(
	tzc, 
	icalproperty_new_tzoffsetto(-5*3600)
	);

    icalcomponent_add_property(
	tzc, 
	icalproperty_new_tzname("EST")
	);

    icalcomponent_add_component(timezone,tzc);

    /* Add an event */

    event = icalcomponent_new(ICAL_VEVENT_COMPONENT);

    icalcomponent_add_property(
	event,
	icalproperty_new_dtstamp(atime)
	);

    icalcomponent_add_property(
	event,
	icalproperty_new_uid("guid-1.host1.com")
	);

    /* add a property that has parameters */
    property = icalproperty_new_organizer("*****@*****.**");
    
    icalproperty_add_parameter(
	property,
	icalparameter_new_role(ICAL_ROLE_CHAIR)
	);

    icalcomponent_add_property(event,property);

    /* add another property that has parameters */
    property = icalproperty_new_attendee("*****@*****.**");
    
    icalproperty_add_parameter(
	property,
	icalparameter_new_role(ICAL_ROLE_REQPARTICIPANT)
	);

    icalproperty_add_parameter(
	property,
	icalparameter_new_rsvp(ICAL_RSVP_TRUE)
	);

    icalproperty_add_parameter(
	property,
	icalparameter_new_cutype(ICAL_CUTYPE_GROUP)
	);

    icalcomponent_add_property(event,property);


    /* more properties */

    icalcomponent_add_property(
	event,
	icalproperty_new_description("Project XYZ Review Meeting")
	);

    icalcomponent_add_property(
	event,
	icalproperty_new_categories("MEETING")
	);

    icalcomponent_add_property(
	event,
	icalproperty_new_class(ICAL_CLASS_PRIVATE)
	);
    
    icalcomponent_add_property(
	event,
	icalproperty_new_created(atime)
	);

    icalcomponent_add_property(
	event,
	icalproperty_new_summary("XYZ Project Review")
	);


    property = icalproperty_new_dtstart(atime);
    
    icalproperty_add_parameter(
	property,
	icalparameter_new_tzid("America/New_York")
	);

    icalcomponent_add_property(event,property);


    property = icalproperty_new_dtend(atime);
    
    icalproperty_add_parameter(
	property,
	icalparameter_new_tzid("America/New_York")
	);

    icalcomponent_add_property(event,property);

    icalcomponent_add_property(
	event,
	icalproperty_new_location("1CP Conference Room 4350")
	);

    icalcomponent_add_component(calendar,event);
    
    calendar_as_string = icalcomponent_as_ical_string(calendar);

    is("build large, complex component", 
       calendar_as_string,
       create_new_component_str);

    if (VERBOSE && calendar)
      printf("%s\n",icalcomponent_as_ical_string(calendar));


    if (calendar)
      icalcomponent_free(calendar);

}
icalcomponent* create_new_component()
{

    /* variable definitions */
    icalcomponent* calendar;
    icalcomponent* event;
    struct icaltimetype atime = icaltime_from_timet( time(0),0);
    struct icalperiodtype rtime;
    icalproperty* property;

    /* Define a time type that will use as data later. */
    rtime.start = icaltime_from_timet( time(0),0);
    rtime.end = icaltime_from_timet( time(0),0);
    rtime.end.hour++;

    /* Create calendar and add properties */

    calendar = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);
    
    /* Nearly every libical function call has the same general
       form. The first part of the name defines the 'class' for the
       function, and the first argument will be a pointer to a struct
       of that class. So, icalcomponent_ functions will all take
       icalcomponent* as their first argument. */

    /* The next call creates a new proeprty and immediately adds it to the 
       'calendar' component. */ 

    icalcomponent_add_property(
	calendar,
	icalproperty_new_version("2.0")
	);

    
    /* Here is the short version of the memory rules: 

         If the routine name has "new" in it: 
	     Caller owns the returned memory. 
             If you pass in a string, the routine takes the memory. 	 

         If the routine name has "add" in it:
	     The routine takes control of the component, property, 
	     parameter or value memory.

         If the routine returns a string ( "get" and "as_ical_string" )
	     The library owns the returned memory. 

	  There are more rules, so refer to the documentation for more 
	  details. 

    */

    icalcomponent_add_property(
	calendar,
	icalproperty_new_prodid("-//RDU Software//NONSGML HandCal//EN")
	);
    
    /* Add an event */

    event = icalcomponent_new(ICAL_VEVENT_COMPONENT);

    icalcomponent_add_property(
	event,
	icalproperty_new_dtstamp(atime)
	);

    /* In the previous call, atime is a struct, and it is passed in by value. 
       This is how all compound types of values are handled. */

    icalcomponent_add_property(
	event,
	icalproperty_new_uid("guid-1.host1.com")
	);

    /* add a property that has parameters */
    property = icalproperty_new_organizer("mailto:[email protected]");
    
    icalproperty_add_parameter(
	property,
	icalparameter_new_role(ICAL_ROLE_CHAIR)
	);

    icalcomponent_add_property(event,property);

    /* In this style of component creation, you need to use an extra
       call to add parameters to properties, but the form of this
       operation is the same as adding a property to a component */

    /* add another property that has parameters */
    property = icalproperty_new_attendee("mailto:[email protected]");
    
    icalproperty_add_parameter(
	property,
	icalparameter_new_role(ICAL_ROLE_REQPARTICIPANT)
	);

    icalproperty_add_parameter(
	property,
	icalparameter_new_rsvp(1)
	);

    icalproperty_add_parameter(
	property,
	icalparameter_new_cutype(ICAL_CUTYPE_GROUP)
	);

    icalcomponent_add_property(event,property);


    /* more properties */

    icalcomponent_add_property(
	event,
	icalproperty_new_description("Project XYZ Review Meeting")
	);

    icalcomponent_add_property(
	event,
	icalproperty_new_categories("MEETING")
	);

    icalcomponent_add_property(
	event,
	icalproperty_new_class(ICAL_CLASS_PUBLIC)
	);
    
    icalcomponent_add_property(
	event,
	icalproperty_new_created(atime)
	);

    icalcomponent_add_property(
	event,
	icalproperty_new_summary("XYZ Project Review")
	);

    property = icalproperty_new_dtstart(atime);
    
    icalproperty_add_parameter(
	property,
	icalparameter_new_tzid("US-Eastern")
	);

    icalcomponent_add_property(event,property);


    property = icalproperty_new_dtend(atime);
    
    icalproperty_add_parameter(
	property,
	icalparameter_new_tzid("US-Eastern")
	);

    icalcomponent_add_property(event,property);

    icalcomponent_add_property(
	event,
	icalproperty_new_location("1CP Conference Room 4350")
	);

    icalcomponent_add_component(calendar,event);

    return calendar;
}
// utility function to create a VCALENDAR from a single RideItem
static icalcomponent *createEvent(RideItem *rideItem)
{
    // calendar
    icalcomponent *root = icalcomponent_new(ICAL_VCALENDAR_COMPONENT);

    // calendar version
    icalproperty *version = icalproperty_new_version("2.0");
    icalcomponent_add_property(root, version);

    icalcomponent *event = icalcomponent_new(ICAL_VEVENT_COMPONENT);

    //
    // Unique ID
    //
    QString id = rideItem->ride()->id();
    if (id == "") {
        id = QUuid::createUuid().toString() + "@" + "goldencheetah.org";
    }
    icalproperty *uid = icalproperty_new_uid(id.toLatin1());
    icalcomponent_add_property(event, uid);

    //
    // START DATE
    //
    struct icaltimetype atime;
    QDateTime utc = QDateTime::currentDateTime().toUTC();
    atime.year = utc.date().year();
    atime.month = utc.date().month();
    atime.day = utc.date().day();
    atime.hour = utc.time().hour();
    atime.minute = utc.time().minute();
    atime.second = utc.time().second();
    // this is UTC is_utc is redundant but kept for completeness
    atime.is_utc = 1;
    atime.is_date = 0; // this is a date AND time
    atime.is_daylight = 0; // no daylight savings - its UTC
    atime.zone = icaltimezone_get_utc_timezone(); // set UTC timezone
    icalproperty *dtstart = icalproperty_new_dtstart(atime);
    icalcomponent_add_property(event, dtstart);

    //
    // Duration
    //

    // override values?
    QMap<QString, QString> lookup;
    lookup = rideItem->ride()->metricOverrides.value("workout_time");
    int secs = lookup.value("value", "0.0").toDouble();

    // from last - first timestamp?
    if (!rideItem->ride()->datePoints().isEmpty() &&
            rideItem->ride()->datePoints().last() != NULL) {
        if (!secs) {
            secs = rideItem->ride()->datePoints().last()->secs;
        }
    }

    // ok, got seconds so now create in vcard
    struct icaldurationtype dur;
    dur.is_neg = 0;
    dur.days = dur.weeks = 0;
    dur.hours = secs / 3600;
    dur.minutes = secs % 3600 / 60;
    dur.seconds = secs % 60;
    icalcomponent_set_duration(event, dur);

    // set title & description
    QString title = rideItem->ride()->getTag("Title", "");
    if (title == "") {
        title = rideItem->ride()->getTag("Sport", "") + " Workout";
    }
    icalcomponent_set_summary(event, title.toLatin1());
    icalcomponent_set_description(event,
              rideItem->ride()->getTag("Calendar Text", "").toLatin1());

    // put the event into root
    icalcomponent_add_component(root, event);
    return root;
}
Exemple #28
0
icalcomponent *icalparser_add_line(icalparser *parser, char *line)
{
    char *str;
    char *end;
    int pcount = 0;
    int vcount = 0;
    icalproperty *prop;
    icalproperty_kind prop_kind;
    icalvalue *value;
    icalvalue_kind value_kind = ICAL_NO_VALUE;

    icalerror_check_arg_rz((parser != 0), "parser");

    if (line == 0) {
        parser->state = ICALPARSER_ERROR;
        return 0;
    }

    if (line_is_blank(line) == 1) {
        return 0;
    }

    /* Begin by getting the property name at the start of the line. The
       property name may end up being "BEGIN" or "END" in which case it
       is not really a property, but the marker for the start or end of
       a component */

    end = 0;
    str = parser_get_prop_name(line, &end);

    if (str == 0 || *str == '\0') {
        /* Could not get a property name */
        icalcomponent *tail = pvl_data(pvl_tail(parser->components));

        if (tail) {
            insert_error(
                tail, line,
                "Got a data line, but could not find a property name or component begin tag",
                ICAL_XLICERRORTYPE_COMPONENTPARSEERROR);
        }
        tail = 0;
        parser->state = ICALPARSER_ERROR;
        icalmemory_free_buffer(str);
        str = NULL;
        return 0;
    }

    /**********************************************************************
     * Handle begin and end of components
     **********************************************************************/
    /* If the property name is BEGIN or END, we are actually
       starting or ending a new component */

    if (strcasecmp(str, "BEGIN") == 0) {
        icalcomponent *c;
        icalcomponent_kind comp_kind;

        parser->level++;
        icalmemory_free_buffer(str);
        str = parser_get_next_value(end, &end, value_kind);

        comp_kind = icalenum_string_to_component_kind(str);

        c = icalcomponent_new(comp_kind);

        if (c == 0) {
            c = icalcomponent_new(ICAL_XLICINVALID_COMPONENT);
            insert_error(c, str, "Parse error in component name",
                         ICAL_XLICERRORTYPE_COMPONENTPARSEERROR);
        }

        pvl_push(parser->components, c);

        parser->state = ICALPARSER_BEGIN_COMP;

        icalmemory_free_buffer(str);
        str = NULL;
        return 0;

    } else if (strcasecmp(str, "END") == 0) {
        icalcomponent *tail;

        parser->level--;
        icalmemory_free_buffer(str);
        str = parser_get_next_value(end, &end, value_kind);

        /* Pop last component off of list and add it to the second-to-last */
        parser->root_component = pvl_pop(parser->components);

        tail = pvl_data(pvl_tail(parser->components));

        if (tail != 0) {
            icalcomponent_add_component(tail, parser->root_component);
        }

        tail = 0;
        icalmemory_free_buffer(str);
        str = NULL;

        if (parser->level < 0) {
            // Encountered an END before any BEGIN, this must be invalid data
            icalerror_warn("Encountered END before BEGIN");

            parser->state = ICALPARSER_ERROR;
            parser->level = 0;
            return 0;
        } else if (parser->level == 0) {
            /* Return the component if we are back to the 0th level */
            icalcomponent *rtrn;

            if (pvl_count(parser->components) != 0) {
                /* There are still components on the stack -- this means
                   that one of them did not have a proper "END" */
                pvl_push(parser->components, parser->root_component);
                (void)icalparser_clean(parser); /* may reset parser->root_component */
            }

            assert(pvl_count(parser->components) == 0);

            parser->state = ICALPARSER_SUCCESS;
            rtrn = parser->root_component;
            parser->root_component = 0;
            return rtrn;

        } else {
            parser->state = ICALPARSER_END_COMP;
            return 0;
        }
    }

    /* There is no point in continuing if we have not seen a
       component yet */

    if (pvl_data(pvl_tail(parser->components)) == 0) {
        parser->state = ICALPARSER_ERROR;
        icalmemory_free_buffer(str);
        str = NULL;
        return 0;
    }

    /**********************************************************************
     * Handle property names
     **********************************************************************/

    /* At this point, the property name really is a property name,
       (Not a component name) so make a new property and add it to
       the component */

    prop_kind = icalproperty_string_to_kind(str);

    prop = icalproperty_new(prop_kind);

    if (prop != 0) {
        icalcomponent *tail = pvl_data(pvl_tail(parser->components));

        if (prop_kind == ICAL_X_PROPERTY) {
            icalproperty_set_x_name(prop, str);
        }

        icalcomponent_add_property(tail, prop);

        /* Set the value kind for the default for this type of
           property. This may be re-set by a VALUE parameter */
        value_kind = icalproperty_kind_to_value_kind(icalproperty_isa(prop));

    } else {
        icalcomponent *tail = pvl_data(pvl_tail(parser->components));

        insert_error(tail, str, "Parse error in property name",
                     ICAL_XLICERRORTYPE_PROPERTYPARSEERROR);

        tail = 0;
        parser->state = ICALPARSER_ERROR;
        icalmemory_free_buffer(str);
        str = NULL;
        return 0;
    }

    icalmemory_free_buffer(str);
    str = NULL;

    /**********************************************************************
     * Handle parameter values
     **********************************************************************/

    /* Now, add any parameters to the last property */

    while (pcount < MAXIMUM_ALLOWED_PARAMETERS) {
        if (*(end - 1) == ':') {
            /* if the last separator was a ":" and the value is a
               URL, icalparser_get_next_parameter will find the
               ':' in the URL, so better break now. */
            break;
        }

        icalmemory_free_buffer(str);
        str = parser_get_next_parameter(end, &end);
        strstriplt(str);
        if (str != 0) {
            char *name_heap = 0;
            char *pvalue_heap = 0;
            char name_stack[TMP_BUF_SIZE];
            char pvalue_stack[TMP_BUF_SIZE];
            char *name = name_stack;
            char *pvalue = pvalue_stack;

            icalparameter *param = 0;
            icalparameter_kind kind;
            icalcomponent *tail = pvl_data(pvl_tail(parser->components));

            if (!parser_get_param_name_stack(str, name_stack, sizeof(name_stack),
                                             pvalue_stack, sizeof(pvalue_stack))) {
                name_heap = parser_get_param_name_heap(str, &pvalue_heap);

                name = name_heap;
                pvalue = pvalue_heap;

                if (name_heap == 0) {
                    /* 'tail' defined above */
                    insert_error(tail, str, "Cant parse parameter name",
                                 ICAL_XLICERRORTYPE_PARAMETERNAMEPARSEERROR);
                    tail = 0;
                    break;
                }
            }

            kind = icalparameter_string_to_kind(name);

            if (kind == ICAL_X_PARAMETER) {
                param = icalparameter_new(ICAL_X_PARAMETER);
                if (param != 0) {
                    icalparameter_set_xname(param, name);
                    icalparameter_set_xvalue(param, pvalue);
                }
            } else if (kind == ICAL_IANA_PARAMETER) {
                ical_unknown_token_handling tokHandlingSetting =
                    ical_get_unknown_token_handling_setting();
                if (tokHandlingSetting == ICAL_DISCARD_TOKEN) {
                    if (name_heap) {
                        icalmemory_free_buffer(name_heap);
                        name_heap = 0;
                    }
                    if (pvalue_heap) {
                        icalmemory_free_buffer(pvalue_heap);
                        pvalue_heap = 0;
                    }
                    continue;
                }

                param = icalparameter_new(ICAL_IANA_PARAMETER);

                if (param != 0) {
                    icalparameter_set_xname(param, name);
                    icalparameter_set_xvalue(param, pvalue);
                }
            } else if (kind == ICAL_TZID_PARAMETER && *(end - 1) != ';') {
                /*
                   Special case handling for TZID to work around invalid incoming data.
                   For example, Google Calendar will send back stuff like this:
                   DTSTART;TZID=GMT+05:30:20120904T020000

                   In this case we read to the next semicolon or the last colon rather
                   than the first colon.  This way the TZID will become GMT+05:30 rather
                   than trying to parse the date-time as 30:20120904T020000.

                   This also handles properties that look like this:
                   DTSTART;TZID=GMT+05:30;VALUE=DATE-TIME:20120904T020000
                 */
                char *lastColon = 0;
                char *nextColon = end;
                char *nextSemicolon = parser_get_next_char(';', end, 1);

                /* Find the last colon in the line */
                do {
                    nextColon = parser_get_next_char(':', nextColon, 1);

                    if (nextColon) {
                        lastColon = nextColon;
                    }
                } while (nextColon);

                if (lastColon && nextSemicolon && nextSemicolon < lastColon) {
                    /*
                       Ensures that we don't read past a semicolon

                       Handles the following line:
                       DTSTART;TZID=GMT+05:30;VALUE=DATE-TIME:20120904T020000
                     */
                    lastColon = nextSemicolon;
                }

                /*
                   Rebuild str so that it includes everything up to the next semicolon
                   or the last colon. So given the above example, str will go from
                   "TZID=GMT+05" to "TZID=GMT+05:30"
                 */
                if (lastColon && *(lastColon + 1) != 0) {
                    char *strStart = line + strlen(name) + 2;

                    end = lastColon + 1;

                    icalmemory_free_buffer(str);
                    str = make_segment(strStart, end - 1);
                }

                /* Reparse the parameter name and value with the new segment */
                if (!parser_get_param_name_stack(str, name_stack, sizeof(name_stack),
                                                 pvalue_stack, sizeof(pvalue_stack))) {
                    if (pvalue_heap) {
                        icalmemory_free_buffer(pvalue_heap);
                        pvalue_heap = 0;
                        pvalue = 0;
                    }
                    if (name_heap) {
                        icalmemory_free_buffer(name_heap);
                        name = 0;
                    }
                    name_heap = parser_get_param_name_heap(str, &pvalue_heap);
                    pvalue = pvalue_heap;
                }
                param = icalparameter_new_from_value_string(kind, pvalue);
            } else if (kind != ICAL_NO_PARAMETER) {
                param = icalparameter_new_from_value_string(kind, pvalue);
            } else {
                /* Error. Failed to parse the parameter */
                /* 'tail' defined above */

                /* Change for mozilla */
                /* have the option of being flexible towards unsupported parameters */
#if ICAL_ERRORS_ARE_FATAL == 1
                insert_error(tail, str, "Cant parse parameter name",
                             ICAL_XLICERRORTYPE_PARAMETERNAMEPARSEERROR);
                tail = 0;
                parser->state = ICALPARSER_ERROR;
                if (pvalue_heap) {
                    icalmemory_free_buffer(pvalue_heap);
                    pvalue = 0;
                }
                if (name_heap) {
                    icalmemory_free_buffer(name_heap);
                    name = 0;
                }
                icalmemory_free_buffer(str);
                str = NULL;
                return 0;
#else
                if (name_heap) {
                    icalmemory_free_buffer(name_heap);
                    name_heap = 0;
                }
                if (pvalue_heap) {
                    icalmemory_free_buffer(pvalue_heap);
                    pvalue_heap = 0;
                }
                icalmemory_free_buffer(str);
                str = NULL;
                continue;
#endif
            }

            if (pvalue_heap) {
                icalmemory_free_buffer(pvalue_heap);
                pvalue_heap = 0;
            }

            if (name_heap) {
                icalmemory_free_buffer(name_heap);
                name_heap = 0;
            }

            if (param == 0) {
                /* 'tail' defined above */
                insert_error(tail, str, "Cant parse parameter value",
                             ICAL_XLICERRORTYPE_PARAMETERVALUEPARSEERROR);

                tail = 0;
                parser->state = ICALPARSER_ERROR;

                icalmemory_free_buffer(str);
                str = NULL;

                continue;
            }

            /* If it is a VALUE parameter, set the kind of value */
            if (icalparameter_isa(param) == ICAL_VALUE_PARAMETER) {
                value_kind =
                    (icalvalue_kind)icalparameter_value_to_value_kind(
                        icalparameter_get_value(param));

                if (!icalproperty_value_kind_is_valid(prop_kind, value_kind)) {

                    /* Ooops, invalid VALUE parameter, so reset the value_kind */

                    const char *err_str = "Invalid VALUE type for property";
                    const char *prop_str = icalproperty_kind_to_string(prop_kind);
                    size_t tmp_buf_len = strlen(err_str) + strlen(prop_str) + 2;
                    char *tmp_buf = icalmemory_tmp_buffer(tmp_buf_len);
                    snprintf(tmp_buf, tmp_buf_len, "%s %s", err_str, prop_str);

                    insert_error(tail, str, tmp_buf,
                                 ICAL_XLICERRORTYPE_PARAMETERVALUEPARSEERROR);

                    value_kind = icalproperty_kind_to_value_kind(prop_kind);

                    icalparameter_free(param);
                    tail = 0;
                    parser->state = ICALPARSER_ERROR;

                    icalmemory_free_buffer(str);
                    str = NULL;
                    pcount++;
                    continue;
                }
            }

            /* Everything is OK, so add the parameter */
            icalproperty_add_parameter(prop, param);
            tail = 0;
            icalmemory_free_buffer(str);
            str = NULL;
            pcount++;

        } else {
            /* str is NULL */
            break;
        }

    }   /* while(1) */

    /**********************************************************************
     * Handle values
     **********************************************************************/

    /* Look for values. If there are ',' characters in the values,
       then there are multiple values, so clone the current
       parameter and add one part of the value to each clone */

    vcount = 0;
    while (vcount < MAXIMUM_ALLOWED_MULTIPLE_VALUES) {
        /* Only some properties can have multiple values. This list was taken
           from rfc5545. Also added the x-properties, because the spec actually
           says that commas should be escaped. For x-properties, other apps may
           depend on that behaviour
         */
        icalmemory_free_buffer(str);
        str = NULL;

        if (icalproperty_value_kind_is_multivalued(prop_kind, &value_kind)) {
            str = parser_get_next_value(end, &end, value_kind);
        } else {
            str = icalparser_get_value(end, &end, value_kind);
        }
        strstriplt(str);

        if (str != 0) {

            if (vcount > 0) {
                /* Actually, only clone after the second value */
                icalproperty *clone = icalproperty_clone(prop);
                icalcomponent *tail = pvl_data(pvl_tail(parser->components));

                icalcomponent_add_property(tail, clone);
                prop = clone;
                tail = 0;
            }

            value = icalvalue_new_from_string(value_kind, str);

            /* Don't add properties without value */
            if (value == 0) {
                char temp[200]; /* HACK */

                icalproperty_kind prop_kind = icalproperty_isa(prop);
                icalcomponent *tail = pvl_data(pvl_tail(parser->components));

                snprintf(temp, sizeof(temp),
                         "Can't parse as %s value in %s property. Removing entire property",
                         icalvalue_kind_to_string(value_kind),
                         icalproperty_kind_to_string(prop_kind));

                insert_error(tail, str, temp, ICAL_XLICERRORTYPE_VALUEPARSEERROR);

                /* Remove the troublesome property */
                icalcomponent_remove_property(tail, prop);
                icalproperty_free(prop);
                prop = 0;
                tail = 0;
                parser->state = ICALPARSER_ERROR;

                icalmemory_free_buffer(str);
                str = NULL;
                return 0;

            } else {
                vcount++;
                icalproperty_set_value(prop, value);
            }
            icalmemory_free_buffer(str);
            str = NULL;

        } else {
#if ICAL_ALLOW_EMPTY_PROPERTIES
            /* Don't replace empty properties with an error.
               Set an empty length string (not null) as the value instead */
            if (vcount == 0) {
                icalproperty_set_value(prop, icalvalue_new(ICAL_NO_VALUE));
            }

            break;
#else
            if (vcount == 0) {
                char temp[200]; /* HACK */

                icalproperty_kind prop_kind = icalproperty_isa(prop);
                icalcomponent *tail = pvl_data(pvl_tail(parser->components));

                snprintf(temp, sizeof(temp), "No value for %s property. Removing entire property",
                         icalproperty_kind_to_string(prop_kind));

                insert_error(tail, str, temp, ICAL_XLICERRORTYPE_VALUEPARSEERROR);

                /* Remove the troublesome property */
                icalcomponent_remove_property(tail, prop);
                icalproperty_free(prop);
                prop = 0;
                tail = 0;
                parser->state = ICALPARSER_ERROR;
                return 0;
            } else {

                break;
            }
#endif
        }
    }

    /****************************************************************
     * End of component parsing.
     *****************************************************************/

    if (pvl_data(pvl_tail(parser->components)) == 0 && parser->level == 0) {
        /* HACK. Does this clause ever get executed? */
        parser->state = ICALPARSER_SUCCESS;
        assert(0);
        return parser->root_component;
    } else {
        parser->state = ICALPARSER_IN_PROGRESS;
        return 0;
    }
}
icalcomponent*
icaltzutil_fetch_timezone (const char *location)
{
	int ret = 0;
	FILE *f;
	tzinfo type_cnts;
	unsigned int num_trans, num_types, num_chars, num_leaps, num_isstd, num_isgmt;
	time_t *transitions = NULL;
	time_t trans;
	int *trans_idx = NULL, dstidx = -1, stdidx = -1, pos, sign, zidx, zp_idx, i;
	ttinfo *types = NULL;
	char *znames = NULL, *full_path, *tzid, *r_trans, *temp;
	leap *leaps = NULL;
	icalcomponent *tz_comp = NULL, *dst_comp = NULL, *std_comp = NULL;
	icalproperty *icalprop;
	icaltimetype dtstart, icaltime;
	struct icalrecurrencetype ical_recur;
	       
	if (!zdir) 
		set_zone_directory ();
	
	full_path = (char *) malloc (strlen (zdir) + strlen (location) + 2);
	sprintf (full_path,"%s/%s",zdir, location);

	if ((f = fopen (full_path, "rb")) == 0) {
		icalerror_set_errno (ICAL_FILE_ERROR);
		free (full_path);
		return NULL;
	}

	if ((ret = fseek (f, 20, SEEK_SET)) != 0) {
		icalerror_set_errno (ICAL_FILE_ERROR);
		goto error;	
	}

	EFREAD(&type_cnts, 24, 1, f);

	num_isgmt = decode (type_cnts.ttisgmtcnt);
	num_leaps = decode (type_cnts.leapcnt);
	num_chars = decode (type_cnts.charcnt);
	num_trans = decode (type_cnts.timecnt);
	num_isstd = decode (type_cnts.ttisstdcnt);
	num_types = decode (type_cnts.typecnt);

	transitions = calloc (num_trans, sizeof (time_t));
	r_trans = calloc (num_trans, 4);
	EFREAD(r_trans, 4, num_trans, f);
	temp = r_trans;	

	if (num_trans) {
		trans_idx = calloc (num_trans, sizeof (int));
		for (i = 0; i < num_trans; i++) {
			trans_idx [i] = fgetc (f);
			transitions [i] = decode (r_trans);
			r_trans += 4;
		}
	}
	
	free (temp);

	types = calloc (num_types, sizeof (ttinfo));
	for (i = 0; i < num_types; i++) {
		unsigned char a [4];
		int c;

		EFREAD(a, 4, 1, f);
		c = fgetc (f);
		types [i].isdst = c;
		if((c = fgetc (f)) < 0) {
		   c = 0;
		   break;
		}
		types [i].abbr = c;
		types [i].gmtoff = decode (a);
	}

	znames = (char *) malloc (num_chars);
	EFREAD(znames, num_chars, 1, f);

	/* We got all the information which we need */

	leaps = calloc (num_leaps, sizeof (leap));
	for (i = 0; i < num_leaps; i++) {
		char c [4];

		EFREAD (c, 4, 1, f);
		leaps [i].transition = decode (c);

		EFREAD (c, 4, 1, f);
		leaps [i].change = decode (c);
	}

	for (i = 0; i < num_isstd; ++i) {
		int c = getc (f);
		types [i].isstd = c != 0;
	}

	while (i < num_types)
		types [i++].isstd = 0;

	for (i = 0; i <  num_isgmt; ++i) {
		int c = getc (f);
		types [i].isgmt = c != 0;
	}

	while (i < num_types)
		types [i++].isgmt = 0;

	/* Read all the contents now */

	for (i = 0; i < num_types; i++) 
		types [i].zname = zname_from_stridx (znames, types [i].abbr);

	if (num_trans != 0)
		find_transidx (transitions, types, trans_idx, num_trans, &stdidx, &dstidx);
	else
		stdidx = 0;

	tz_comp = icalcomponent_new (ICAL_VTIMEZONE_COMPONENT);

	/* Add tzid property */
	tzid = (char *) malloc (strlen (ical_tzid_prefix) + strlen (location) + 8);
	sprintf (tzid, "%sTzfile/%s", ical_tzid_prefix, location);
	icalprop = icalproperty_new_tzid (tzid);
	icalcomponent_add_property (tz_comp, icalprop);
	free (tzid);

	icalprop = icalproperty_new_x (location);
	icalproperty_set_x_name (icalprop, "X-LIC-LOCATION");
	icalcomponent_add_property (tz_comp, icalprop);
	
	if (stdidx != -1) {
		if (num_trans != 0)
			zidx = trans_idx [stdidx];
		else 
			zidx = 0;

		std_comp = icalcomponent_new (ICAL_XSTANDARD_COMPONENT);
		icalprop = icalproperty_new_tzname (types [zidx].zname);
		icalcomponent_add_property (std_comp, icalprop);

		if (dstidx != -1)
			zp_idx = trans_idx [stdidx-1]; 
		else
			zp_idx = zidx;
		/* DTSTART localtime uses TZOFFSETFROM UTC offset */
		trans = transitions [stdidx] + types [zp_idx].gmtoff;
		icaltime = icaltime_from_timet (trans, 0);
		dtstart = icaltime;
		dtstart.year = 1970;
		dtstart.minute = dtstart.second = 0;
		icalprop = icalproperty_new_dtstart (dtstart);
		icalcomponent_add_property (std_comp, icalprop);

		/* If DST changes are present use RRULE */
		if (dstidx != -1) {
			icalrecurrencetype_clear (&ical_recur);
			ical_recur.freq = ICAL_YEARLY_RECURRENCE;
			ical_recur.by_month [0] = icaltime.month;
			pos = calculate_pos (icaltime);
			pos < 0 ? (sign = -1): (sign = 1);
			ical_recur.by_day [0] = sign * ((abs (pos) * 8) + icaltime_day_of_week (icaltime));
			icalprop = icalproperty_new_rrule (ical_recur);
			icalcomponent_add_property (std_comp, icalprop);

			adjust_dtstart_day_to_rrule (std_comp, ical_recur);
		}
        icalprop = icalproperty_new_tzoffsetfrom (types [zp_idx].gmtoff);
        icalcomponent_add_property (std_comp, icalprop);

		icalprop = icalproperty_new_tzoffsetto (types [zidx].gmtoff);
		icalcomponent_add_property (std_comp, icalprop);

		icalcomponent_add_component (tz_comp, std_comp);
	} else 
		icalerror_set_errno (ICAL_MALFORMEDDATA_ERROR);
	
	if (dstidx != -1) {
		zidx = trans_idx [dstidx];
		zp_idx = trans_idx [dstidx-1];
		dst_comp = icalcomponent_new (ICAL_XDAYLIGHT_COMPONENT);
		icalprop = icalproperty_new_tzname (types [zidx].zname);
		icalcomponent_add_property (dst_comp, icalprop);

		/* DTSTART localtime uses TZOFFSETFROM UTC offset */
		trans = transitions [dstidx] + types [zp_idx].gmtoff;
		icaltime = icaltime_from_timet (trans, 0);
		dtstart = icaltime;
		dtstart.year = 1970;
		dtstart.minute = dtstart.second = 0;
		icalprop = icalproperty_new_dtstart (dtstart);
		icalcomponent_add_property (dst_comp, icalprop);

		icalrecurrencetype_clear (&ical_recur);
		ical_recur.freq = ICAL_YEARLY_RECURRENCE;
		ical_recur.by_month [0] = icaltime.month;
		pos = calculate_pos (icaltime);
		pos < 0 ? (sign = -1): (sign = 1);
		ical_recur.by_day [0] = sign * ((abs (pos) * 8) + icaltime_day_of_week (icaltime));
		icalprop = icalproperty_new_rrule (ical_recur);
		icalcomponent_add_property (dst_comp, icalprop);

		adjust_dtstart_day_to_rrule (dst_comp, ical_recur);

		icalprop = icalproperty_new_tzoffsetfrom (types [zp_idx].gmtoff);
		icalcomponent_add_property (dst_comp, icalprop);

		icalprop = icalproperty_new_tzoffsetto (types [zidx].gmtoff);
		icalcomponent_add_property (dst_comp, icalprop);

		icalcomponent_add_component (tz_comp, dst_comp);
	}

error:
	if (f)
		fclose  (f);

	if (transitions)
		free (transitions);
	if (trans_idx)
		free (trans_idx);
	if (types) {
		for (i = 0; i < num_types; i++) 
			if (types [i].zname)
				free (types [i].zname);
		free (types);
	}
	if (znames)
		free (znames);
	free (full_path);
	if (leaps)
		free (leaps);

	return tz_comp;
}