GroupWare API
-------------

Copyright (c) 1999-2011 IceWarp Ltd. All rights reserved.

(*

Overview
--------
                                     
IceWarp GroupWare is a RDBMS server based application which has a unique API for the complete groupware usage.

All clients and server modules utilize this API (including SyncML, ActiveSync, IMAP Groupware Connector, WebDAV etc).
You have to be familiar with the database fields which can be explored in the calendar.xml file including
all field type values and comments, however you do not need to use any SQL to utilize the system.

There are several methods to connect to the groupware and use the API. You can use the GroupWare API Tool, COM interface,
BEEP protocol (TCP/IP), icewarpphp PHP extension, RPC or indirectly via WebDAV, ActiveSync etc.
It is highly recommended to get familiar with the tool first.

For examples and usage see the PHP class gw.php.

For RPC the URL is http://server/rpc/gw.html and you must call the final API functions described in this document.
See more information about RPC at http://www.xmlrpc.com/

The API (except RPC) has been designed so all calls are in only one wraping function described below:

result CalendarFunctionCall(string funcname, string param1, string param2, string param3, string param4)


Function Parameters                                                             
-------------------

funcname - function name from the API
param1..param4 - proper values for the API function <funcname>

There are several types of function parameters depending on the action.


Add:
Parameters contain an URL encoded field value string where each field contains a value in the following format.

Eg:
EvnNote=Note%20Here&EvnClass=T

Non-mandatory parameters specify an edit/update function of an existing record.
All add functions return the item ID of the inserted item or boolean result for updated items if successful.


List:
All list functions return an array of URL encoded lines. The first line contains the database field names
and following lines contain the values for the fields (according to their order).

Eg:
EVN_ID&Evn_EditCounter& CRLF
1234567&0&
2345678&1&


Where:
Where allows you to specify additional condition for the SQL statement. Use only simple statements
and beware of database specifics. Database specifics are dealt with automatically (escaping etc.).
When using LIKE escaping, use the following escaping syntax (exact case match):

LIKE '...' {ESCAPE '\'}


Eg:
EvnClass='E'
or
EvnTitle LIKE '%meeting\_1%' {ESCAPE '\'}


Attributes:
Some list functions allows you to specify attributes. Attributes are used to set special behavior to
the list function. The following syntax and parameters is used:

order=<fields> ["DESC"]         ; sort results by fields
position=<index>                ; start listing at <index> position
limit=<count>                   ; limit number of returned lists to <count>

Each attribute is separated with semi-colon.
Eg:
order=EvnTitle, EvnLocation DESC; limit=1000


Interval:
The interval parameter can be used in several functions. It can contain local date, local date and time,
UTC date, UTC date and time and a VTIMEZONE object for querying floating time objects:

(JDStart ["." JTStart] "-" JDEnd ["." JTEnd]) ";" ([UTC]) ";" (VTIMEZONE) ";" (JTEndAdd)

JD        - Julian date
JT        - Julian time as a frac of SecondsFromMidnight / SecsPerDay
UTC       - "Z" specifies a UTC date/time format, blank stands for local date/time
VTIMEZONE - VTIMEZONE object as in iCal RFC (URL encoded)

Eg:
2454718-2454719
2454718.10446-2454719.10446;Z


Function Reference
------------------

*)

// --------------
// Authentication
// --------------

Function LoginUser(EmailAddress, Password: String; IP: String = ''; Options: String = ''; _P: Pointer = Nil): String;
// Logs in the user with the email address password and IP connected to. If successul the function
// returns the SessionID which has to be used for other functions.
//
// To login anonymously use blank EmailAddress or "anyone". In such case a new anonymous session will be created with read only rights.


Function AuthenticateChallenge(ccP: Pointer = Nil): String;
// Returns the challenge string for authentication. The P is an internal parameter and will be ignored.

Function Authenticate(EmailAddress, Hash: String; IP: String = ''; Options: String = ''; _P: Pointer = Nil): String;
// Authenticates the user using the Options (Scheme "|" Challenge). Hash is the calcualted digest using the challenge string and the password.
// By default CRAM-MD5 authentication scheme is used. Supported schemes are (PLAIN, MD5, SHA1, CRAM-MD5, DIGEST-MD5, SYNCML-MD5)
// The result is the SessionID if successful.

Function LogoutUser(SessionID: String): Boolean;
// Logs out the user and terminates all group sessions. The GroupWare uses persistent sessions
// so if you do not log out the session will remain on the server and time out after some time. During
// this time you can reuse the session anytime. To check if it is still active use the UserLoggedOn.

Function SubstituteUser(SessionID: String; Email: String): Boolean;
// Lets you become someone else. Only super user can call this function.
// It is not possible to revert the session back to superuser.


// -------
// Session
// -------

// Lock/Unlock

Function Lock(SessionID: String): Boolean;
Function Unlock(SessionID: String): Boolean;
// These function are transaction lock and unlocks. They allow you to perform a lock, then insert/updates, notifications
// and unlock which will result in commit. Groupware transactions are write only, meaning you cannot see your changes
// made within a transaction in listing functions. You always need to perform Unlock for that.
//
// Some functions automatically use transactions internally. These are all add and delete functions.
// If you use the low level groupware access you should use transactions. If you use high level (versit functions)
// they are used automatically. However if importing a known number of vcards for instance you might want to perform
// a lock before importing them all so the whole process is really quick.

// Owner

Function GetOwnerInfo(SessionID: String): String;
// Returns the owner's details

Function UpdateOwnerInfo(SessionID: String; Parameters: String): Boolean;
// Set the owner's details.

Function RenameOwner(SessionID: String; OldEmail, NewEmail: String): Boolean;
// Rename owner's email address (admin only).

Function GetShareAccountList(SessionID: String; Flags: Longint): String;
// Returns the list of all accounts sharing resources to the owner of this session
// Flags is a bit value and can specify additional items to return
//
//  Bit0 - Accounts sharing resources to the owner
//  Bit1 - Groups the owner is a member of (including the domain itself)
//  Bit2 - Same as Bit1 but groups will be expanded (use Bit1 or Bit2, not simultaneously)
//
//  Bit3 - Requests names to be returned (OwnerName) (for all results)
//  Bit4 - Ignore public folder accounts (for Bit0)
//  Bit5 - Output Flags if account is a public group (for Bit0)
//
// Returns:
// FrtEmail Flags OwnerName

// Groups

Function GetGroupList(SessionID: String; EmailAddress: String = ''): String;
// Returns the list of all valid groups for the session. If EmailAddress supplied
// a group of that account will be queried for the list (if trusted user).
//
// GRP_ID - ID of the group
// GRPOWN_ID - ID of the owner
// GrpLink - Link/reference to the real group from this virtual group
// GrpLinkFolder - Link/reference to the real subscribed folder
// GrpTitle - Description and title for public / shared group

Function SubscribeUser(SessionID: String; EmailAddress: String; SubscribeAs: String = ''): String;
// Subscribes a shared calendar of user and returns the new GRP_ID of the calendar
// To unsubscribe delete the shared root folder.

Function OpenGroup(SessionID, GroupID: String; DefaultTitle: String = ''; _Flags: Longint = $00): String;
// Opens the group from the group list. A special groupid "*" stands for all user's groups.
// In such case GetFolderList and others will work with all the groups available.
// If successful a groupsessionid will be returned.
//
// It is also possible to open a shared group account directly via GroupID eg. "~john@doe.com" for instance.
// This way you can get directly access to the group of such account.
//
// DefaultTitle lets you specify the prefix for shared account group.

Function CloseGroup(GroupSessionID: String): Boolean;
// Closes an open group

Function GetGroupAccessRights(GroupSessionID: String; Folder: String = ''): String;
// Returns the bit rights for the group session. See more details for GetFolderRightList and its possible bit values.

Function AddGroup(SessionID: String; Parameters: String; GroupID: String = ''): String;
// Only owners can add new groups. Group is a collection for all objects and can can have
// different share modes and properties. By default every user has only one group.

Function DeleteGroup(SessionID: String; GroupID: String): Boolean;
// Delete existing group from the list.

Function ExportGroup(GroupSessionID: String; UserID: String = ''): String;
// Exports all group data to XML

Function ImportGroup(GroupSessionID: String; Data: String): Boolean;
// Imports all group data from XML

Function ExportData(SessionID: String; List: String): String;
// Export list of users to xml structure

Function ImportData(SessionID: String; Data: String): Boolean;
// Import xml structure created with ExportData function

Function DeleteGroupObjects(GroupSessionID: String): Boolean;
// Deletes all objects from the group.

Function GetGroupOwnerEmail(GroupSessionID: String): String;
// Returns the email address of the group owner

Function DeleteOwner(SessionID: String; EmailAddress: String): Boolean;
// Deletes account from groupware with all its groups and properties.
// Only superuser or administrator can do this and it is used by the account management system.

Function CreateUser(SessionID: String; EmailAddress: String; Flags: Longint = $00): String;
// Creates a new user in the groupware. The user does not need to exist as email account on the server.
// The result value is the new ownerid. Only superuser can create new users.

Function GetUserSettings(SessionID: String): String;
Function SetUserSettings(SessionID: String; Settings: String): Boolean;
// Get and set user settings and attributes. See the xml settings structure below.
// SessionID can be blank to query global server settings

(*

<settings>
  <forwarder>
    <forwardto/>
    <null/>
  <forwarder/>

  <responder>
    <mode/>
    <after/>
    <message/>
    <between/>
  </responder>

  <rules>
    <content/>
  </rules>

  <password>
    <newpassword/>
  </password>

  <bwlist>
    <white/>
    <black/>
  </bwlist>

  <folders>
    <mail/>
  </folders>

</settings>

*)


// Holidays

Function GetHolidays(SessionID: String; CS: String; Search: String = ''): String;
// Returns all system holidays containing the selected flag (holidays selected by the user)
//
// CS (CalendarService) - "holiday" / "weather" / "all"
// Search - lookup new location for "weather" CS

Function AddHoliday(SessionID: String; Parameters: String; CS: String): Boolean;
// Adds a new holiday

Function DeleteHolidays(SessionID: String; CS: String; ID: String = ''): Boolean;
// Deletes all holidays selected flag or only the specified HolidayID

Function ImportHolidays(SessionID: String; CS: String): Boolean;
// Imports holiday .ics files into calendarservice user
// Only superuser can call this function.



// -------
// Tickets
// -------

Function OpenTicket(SessionID: String; Ticket: String): String;
// Lets you open a ticket and returns a GroupSessionID to the ticket. You can then
// read the folder content and perform actions based on your rights. Tickets can be used for
// anonymous access so once a Ticket is known it can be used by anybody.
//
// TicketID is a gzipped structure containing parameters and attributes of the ticket.
// Apart from the params below there is also:
//
// group     - GroupID of the group
// folder    - FolderID
// key       - Authentication key

Function CreateTicket(GroupSessionID: String; Params: String): String;
// Creates a new ticket from the currently open folder. Use Params to specify the ticket
// properties. Is is also possible to create a ticket URL with GetAttachmentPath(..., 'TICKET').
//
// Params:
//
// rights      - Rights for the ticket owner
// expire      - Expiration of the ticket (unix timestamp)
// id          - ItemID/AttachID



// ------
// Folder
// ------

Function UpgradeTasks(Version: String; Force: String): String;
// sets internal version of GW Database if not already set
// Force - sets the internal version regardless on it being already set
// returns info if GW needs to be restarted

Function DBTasks(SessionID:String; Conn: String; Task: String): Boolean;
// performs DB operation with database given by connection string conn
// Task - one of "create","drop"
// superadmin SessionID required


Function GetFolderUpdate(SessionID: String): Integer;
// Returns the update ID. The client should remember this value and instead of UserLoggedOn call this function.
// If the ID changes it means there has been a change of folders on the account and client should refresh the list.
// If 0 is returned the session exists no more.

Function GetFolderList(GroupSessionID: String; OtherSelect: String = ''): String;
// Returns the list of folders
// OtherSelect lets you specify additional fields to return
//
// FDR_ID      - ID of the folder
// FDR_PARENT  - ID of the parent folder
// Fdr_Created - unix time stamp of the folder
// Fdr_Default - 1 if default folder
// FdrType     - Type of the folder
//
// If the groupsessionid is a link to "*" group then all folders in all groups will be returned.

Function AddFolder(GroupSessionID: String; Folder: String; Type_: String; Parameters: String): Boolean;
Function DeleteFolder(GroupSessionID: String; Folder: String; Attrib: Longint = 0): Boolean;
Function RenameFolder(GroupSessionID: String; OldFolder, NewFolder: String): Boolean;
// Manages folders
//
// AddFolder can be used to susbcribe a shared account if folder name as ~john@doe.com.
// DeleteFolder can be also used to unsubscribe shared account. In such case only the shared root folder name
// must be used and the account will be automatically unsubscribed.
//
// You can utilize the "F" files folder link to a real file system directory using the Parameters - FdrParam field.
// In such case FdrParam must contain an attribute "path=<fullpath>" and it will gain access to the <fullpath> directory
// thru the files folder.

Function SetDefaultFolder(GroupSessionID: String): Boolean;
// Clears the previous default folder of the same type and sets the new folder to be default.
// Default folders are required in some applications.


Function GetFolderInfo(GroupSessionID: String; Reload: Boolean = False): String;
// Returns the folder session information. Reload ensures to read fresh data from the database and updates the groupsession information.
// FDR_ID, FDR_PARENT, Fdr_Created, Fdr_Default, FdrType, FdrParam, FdrPublic, FdrShared, FdrOwner
//
// FdrShared
// 0 - Primary folder
// 1 - Public folder
// 2 - Shared folder

Function OpenFolder(GroupSessionID: String; Folder: String): String;
Function CloseFolder(GroupSessionID: String): Boolean;
// Get access to folder items and close access. The function opens a specified folder and returns a foldersessionid.
// Use OpenFolder and the resulting FolderSessionID to access folder items.
//
// It is possible to open multiple folders simultaneously using a virtual folder mode.
// These folders will be combined in all list and action functions. This means that you can search multiple
// folders or display multiple interval events in just one call. In such case separate multiple folders with
// CRLF in the Folder parameter. All functionality will be preserved and even Add functions will work.
//
// You can easily open a shared account folder that has not been subscribed yet with
// OpenFolder(GroupSessionID, '~john@doe.com'). In such case a new folder list will be returned in GetFolderList
//
// There is a special folder named @@GAL@@ which allows you to open GAL (Global Address List) without a groupware license
// capability. In such case all GAL folders will be opened and a virtual folder session id will be returned. @@GAL@@ can
// be also used in general virtual folder mode combined with other folders.
//
//
// Eg.:
// $sessid = LoginUser()
// $groupsessid = OpenGroup($sessid, "*");
// $foldersessid = OpenFolder($groupsessid, "@@GAL@@")
// $list = GetContactList($foldersessid)
// CloseFolder($foldersessid)
//
// Special folder names:
// @@DEFAULT@@#<FdrType> - Default folder for FdrTtoe
// @@ALL@@#<FdrType> - All folders mode of FdrType
// @@GAL@@ - GAL folders
// @@TRASH@@ - Trash folder for deleted items
//
// Eg.:
// $foldersessid = OpenFolder($groupsessid, "@@DEFAULT@@#C") // Open the default contacts folder


Function GetFolderRightList(GroupSessionID: String; Folder: String; MyRights: Boolean = False): String;
Function AddFolderRight(GroupSessionID: String; Folder: String; Email: String; Right: Longint): Boolean;
Function DeleteFolderRight(GroupSessionID: String; Folder: String; Email: String): Boolean;
// Folder access list right management (ACL). ACL is automatically hiearchic (natural inheritance) and controls the whole access behavior.
// Only users with Admin access rights can use these functions.
//
// GetFolderRightList returns also Frt_Folder field which contains the original folder name rights are inherited from.
//
// Email (FrtEmail) types:
// Email          - ordinary email address of the user
// Group / Domain - any system domain or groupname using the "[" group "]" notation
// Anyone         - default rights for everyone using the value "anyone"
// @              - in such case rights will be inherited from parent
//
// These types have their value/priority and email having the highest. If "anyone" has zero right, [group] read only and email full
// rights (all for the same account), the full rights of the user will be used.
//
// Rights (FrtRight):
// FrtRight can be of two types. A bit value or constant value. This is distinguished by checking the most left bit and
// if set bit value is used otherwise the constant values.
//
// Bits (with their IMAP ACL representation):
//  Bit0  - Owner (Read only)
//  Bit1  - Item Write          (i)
//  Bit2  - Admin               (a)
//  Bit3  - Item Delete         (t)
//  Bit4  - Item Modify         (w)
//  Bit5  - Folder Lookup       (l)
//  Bit6  - Folder Read         (r)
//  Bit7  - Folder Write        (k)
//  Bit8  - Folder Delete       (x)
//  ...
//  Bit31 - 1 indicates bit value
//
// Obsolete constants (do not use):
//  0 - frRead                   (lr)
//  1 - frReadWriteModifyDelete  (itwlr)
//  2 - frAdmin                  (iatwlrkx)
//  3 - frReadWrite              (ilr)
//  4 - frReadWriteModify        (iwlr)
//  5 - frNone                   ()
//
// Special folder names:
//  .   - Root
//      - Root
//  \   - IMAP groupped ACL


// -----
// Items
// -----

Function GetItemList(FolderSessID: String; Where: String = ''; OtherSelect: String = ''; Attributes: String = ''): String;
Function GetItemCount(FolderSessID: String; Where: String = ''; Attributes: String = ''): Cardinal;
Function GetItemDetailList(FolderSessID: String; Where: String = ''; OtherSelect: String = ''; Attributes: String = ''): String;
Function GetItemDetailCount(FolderSessID: String; Where: String = ''; Attributes: String = ''): Cardinal;
Function GetItemInfo(FolderSessID: String; ItemID: String): String;
Function GetItemObject(FolderSessID: String; ItemID: String; Params: String = ''): String;
Function AddItemObject(FolderSessID: String; Data: String; ItemID: String = ''; Params: String = ''): String;
Function DeleteItem(FolderSessID: String; ItemID: String; KeepTables: Boolean = False): Boolean;
Function MoveItem(FolderSessID: String; ItemID: String; NewFolder: String; _Deleted: Boolean = False): Boolean;
Function CopyItem(FolderSessID: String; ItemID: String; NewFolder: String; Params: String = ''): String;
// General item functions which call the calendar / contact functions according to folder type
// The same rules applies as to functions below. Object functions work with vCard/vCalendar
// For low level calls you must use the calendar/ contact functions directly
//
// MoveItem can be used to move all items from one folder to another (if ItemID blank) or just a single item.
// Source folder must have Delete rigths and destination folder must have Write rights.
//
// To undelete an item from @@TRASH@@ folder use MoveItem(trashsessid, itemid, itemOriginalFolder).
//
// CopyItem can be used to copy all items if ItemID blank.
//
// Multiple items operation in @@TRASH@@ folder is not possible/



// --------
// Calendar
// --------

Function GetEventList(GroupSessionID: String; Where: String = ''; OtherSelect: String = ''; Attributes: String = ''; _AllItems: Boolean = False): String;
Function GetEventCount(GroupSessionID: String; Where: String = ''; Attributes: String = ''): Cardinal;
Function GetAllIntervalEvents(GroupSessionID: String; Interval: String; Where: String = ''; OtherSelect: String = ''): String;
Function GetIntervalEvents(GroupSessionID: String; Interval: String; Where: String = ''; OtherSelect: String = ''): String;
// Returns a list of all Events for the group or the number of records
//
// Where specifies other SQL conditions.
//
// OtherSelect specifies what fields you want to return besides EVN_ID.
// Eg: EvnClass,EnvNote
//
// GetAllIntervalEvents and GetIntervalEvents returns events occuring in the given interval.
// GetIntervalEvents returns all events but without calendar services events.

Function GetEventDetailList(GroupSessionID: String; Where: String = ''; OtherSelect: String = ''; Attributes: String = ''): String;
Function GetEventDetailCount(GroupSessionID: String; Where: String = ''; Attributes: String = ''): Cardinal;
// Returns the same output as GetEventList plus joined recurrence and reminders

Function GetEventInfo(GroupSessionID: String; EventID: String; _AllItems: Boolean = False): String;
Function AddEventInfo(GroupSessionID: String; Parameters: String; EventID: String = ''; RCRID: String = ''; _Notif: String = ''; _Now: Longint = $00): String;
Function DeleteEvent(GroupSessionID: String; EventID: String; KeepTables: Boolean = False; _Notif: String = ''): Boolean;
// Manages calendar objects
//
// Special handling for item completion is used. For proper functionality and integrated functions
// you should call AddEventInfo once more after editing has been completed with blank Parameters and
// specified EventID. This notifies the server the item is finished and can process subsequent tasks
// with it.
//
// KeepTables - Does not delete the extension tables

Function GetvCalendar(GroupSessionID: String; EventID: String; Params: String = ''): String;
Function AddvCalendar(GroupSessionID: String; Item: String; EventID: String = ''; Params: String = ''): String;
// vCalendar of the calendar object (vEvent, vToDo, vJournal, vNote, File, etc.)
//
// Params specifies additional attribute parameters. See the list of supported parameters below and use ";" as delimiter.
// Parameter values are not URL encoded as ordinary API parameters.
//
// [FORMAT] - If additional parameters will be passed data format must be always present and separated with ";".
//            It can be blank for Versit/Iternet format or any of the following:
//
//            XML  - Versit converted to XML
//            SIF  - Funambol
//            EAS  - Exchange ActiveSync (supports format params eg. "EAS=2" (GAL request for GetvCard)
//            LDIF - LDAP LDIF
//            text/plain - A text plain value used for notes in some devices
//            application/vnd.omads-file+xml - OMA File object
//
// VERIFY   - Used to verify if the inserted item is already on ths server. In such case the item will
//            not be added and the id will be returned. A special compare and search method is used. Use only for slow synchronization.
// VERSION  - Specifies the versit version (1.0, 2.0, 2.1, 3.0)
// FILTER   - List of versit attributes not to be returned, use "," as attribute delimiter, use prefix "+" to return only the specified list of attributes
// NOTIF    - Notification parameters sent to the notification server
// PARAMS   - Support of additional groupware fields which you would supply to AddEventInfo/AddContactInfo functions (such as EvnRID=Value or ItmRID=Value), use "&" delimiter for multiple fields, values of fields must be URL encoded as in other Parameters
// EXPAND   - The list of versit objects will be expanded including the original UID and RECURRENCE-ID (used in GetVCalendars and GetPublicVCalendar)
// SETUID   - Tells the server to read UID from the versit object and set object with this UID in <Item>UID field
// MATCHUID - When ItemID blank the server will search for the item's UID on the server and use its ItemID so item will be updated and not added as new
// EMBEDATT - Instead of using WebDAV URL to all server's attachments embed objects as base64
// ITEMLIST - Interval contains a list of IDs separated with ; (used in GetVCalendars and GetPublicVCalendar)
// EXRESULT - The result of Add*() function will be an extended list result instead of just an ID
// CIDFILE  - Specifies the MIME CID file for CID attachments
//
// Eg:
// ";FILTER=VALARM;EXPAND;PARAMS=EvnRID=ID&EvnFlags=2"
// "EAS;VERIFY"
//
// AddvCalendar supports iCalendar format with multiple VEVENT objects so a complete .ics file can be added easily

Function GetVCalendars(GroupSessionID: String; Interval: String; Where: String = ''; Format: String = ''): String;
// Returns iCalendar for all events in the given Interval
// Format is the same type as in GetvCalendar function
// The function is analogous to GetPublicvCalendar
//
// A special behavior can be achieved if passed ";ITEMLIST" in the Format parameter. In such case
// the Interval should not contain time parameter but a list of EVN_IDs that will be returned in one
// complex vcalendar object.

Function ProcessvCalendar(GroupSessionID: String; EventID: String; Item: String; Parameters: String): String;
// Processes iTIP / iMIP requests and handles all possible actions. Actions are placed in the Parameters
//   Action requests: REQUEST, PUBLISH, CANCEL, REPLY, COUNTER
//   Action replies: CANCEL, ADD, REPLY, DECLINECOUNTER
//   Action list: SEND_ITIP[=CcEmail],REFRESH
//
// Action to accept or decline invitation REQUEST
// "REPLY=ACCEPTED" or "REPLY=DECLINED"
//
// Action "SEND_ITIP" returns the list response consisting of these fields:
// Attendee, Status, Data
//
// "SEND_ITIP" processes the iTIP vcalendar object and processes iMIP (creates and sends iMIP message)
// It can also process the VFREEBUSY object request
//
// Action "REFRESH" returns the current groupware object based on the Item (iCalendar) data UID. Usually used to retrieve
// the object when received DECLINECOUNTER response from organizer.
//
// This special and multi purpose function can be used for different tasks. It can be used to simply process
// any vcalendar object, reply actions or even processing and creating an iMIP message. There are use
// cases for each type.
//
// 1. Process a vcalendar object
//
// ProcessvCalendar(GroupSessID, '', vCalendarData, '')
//
// Applies to METHOD: REPLY, CANCEL, ADD, COUNTER (results in acceptance of object suggested time), REQUEST (results in acceptance of invitation)
//
// 2. Create a vcalendar request
//
// ProcessvCalendar(GroupSessID, EventID, '', Action)
//
// Applies to all action requests above and returns the new vCalendar object that can be used with SEND_ITIP such as
//
// ProcessvCalendar(GroupSessID, '', vCalendarData, 'SEND_ITIP=manager@icewarp.com')
//
// The email here is optional and is used as a Cc email address (a copy of iTIP will be sent to it)
//
// 3. Reply to a vcalendar request
//
// ProcessvCalendar(GroupSessID, '', vCalendarData, 'REPLY=DECLINED')
// ProcessvCalendar(GroupSessID, '', vCalendarData, 'DECLINECOUNTER')
//
// Applies to Action: REPLY, DECLINECOUNTER
//
// Additional Parameters attributes:
//
// OwnerEmail=john@doe.com (specifies the real item owner, used for sending invitations on behalf of somebody else)
//
// Eg. REPLY=DECLINED&OwnerEmail=john@doe.com
//
// VersitParams=%3BCIDFILE%3D%5Ctemp%5Cid.eml (specifies the AddvCalendar parameters - in our example it would be ";CIDFILE=\temp\id.eml" urlencoded)
//
// Eg. &VersitParams=%3BCIDFILE%3D%5Ctemp%5Cid.eml

Function GetEventReminders(GroupSessionID: String; EventID: String): String;
Function AddEventReminder(GroupSessionID: String; EventID: String; Parameters: String; ItemID: String = ''): String;
Function DeleteEventReminders(GroupSessionID: String; EventID: String; ID: String = ''): Boolean;
// Manages calendar reminders

Function GetReminderList(GroupSessionID: String; Interval: String; Where: String = ''): String;
// Returns the list of reminder events in the given interval. This list is used by the server to send reminder notifications.
// ReminderUnixTime specifies the exact calculated reminder time in unix time format

Function GetEventRecurrence(GroupSessionID: String; EventID: String): String;
Function AddEventRecurrence(GroupSessionID: String; EventID: String; Parameters: String; ItemID: String = ''): String;
Function DeleteEventRecurrence(GroupSessionID: String; EventID: String; KeepRCRID: Boolean = False): Boolean;
Function GetEventRecurrenceEndDate(GroupSessionID: String; Interval: String; Parameters: String): Longint;
// Manages calendar recurrences
//
// GetEventRecurrenceEndDate returns the julian event end date based on the recurrence parameters. Interval must be the
// start of the event and the end date you want to have checked (usually should beStart + k)

Function GetEventException(GroupSessionID: String; RecurrenceID: String): String;
Function AddEventException(GroupSessionID: String; RecurrenceID: String; Parameters: String; ItemID: String = ''): String;
Function DeleteEventException(GroupSessionID: String; ItemID: String): Boolean;
Function MoveEventException(GroupSessionID: String; OldRecurrenceID: String; NewRecurrenceID: String; Where: String = ''): Boolean;
// Manages calendar recurrence exceptions

Function GetEventContacts(GroupSessionID: String; EventID: String): String;
Function AddEventContact(GroupSessionID: String; EventID: String; Parameters: String; ItemID: String = ''): String;
Function DeleteEventContacts(GroupSessionID: String; EventID: String; ID: String = ''): Boolean;
// Manages calendar attendees


Function GetVFreeBusy(Email: String; Interval: String; Where: String = ''; Format: String = ''; _Originator: String = ''): String;
Function GetServerVFreeBusy(SessionID: String; Email: String; Interval: String; Format: String = ''): String;
Function GetGroupVFreeBusy(GroupSessionID: String; Interval: String; Where: String = ''; Format: String = ''): String;
// Returns the VFreeBusy versit object for the given interval.
//
// GetVFreeBusy is a public and anonymous function which should be used only to query local users such as in:
//
// http://server/freebusy/?john@doe.com
//
// GetServerVFreeBusy checks local freebusy status and also supports iSchedule protocol for remote servers and distributed domains


Function GetPublicVCalendar(Email: String; Interval: String; Where: String = ''; Format: String = ''): String;
// Returns iCalendar for the default calendar folder in the given Interval
// Format is the same type as in GetvCalendar function
//
// The result is "Internet Calendar" or .ics content used by many applications:
// http://server/calendar/?john@doe.com
//
// The user's share mode must not be set to Private and ACL applies.
// This means that the user must set "anyone" access rights for his default
// calendar folder or there will be no access to that folder.

Function ConvertVersit(SessionID, Data, Format: String): String;
// Converts a versit object to other formats and vice-versa
// Supported formats: XML, SIF, EAS, ''


// --------
// Contacts
// --------

Function GetContactList(GroupSessionID: String; Where: String = ''; OtherSelect: String = ''; Attributes: String = ''): String;
Function GetContactCount(GroupSessionID: String; Where: String = ''; Attributes: String = ''): Cardinal;
// Returns a list of all contacts in the group or the number of records

Function GetContactDetailList(GroupSessionID: String; Where: String = ''; OtherSelect: String = ''; Attributes: String = ''): String;
Function GetContactDetailCount(GroupSessionID: String; Where: String = ''; Attributes: String = ''): Cardinal;
// Returns the same output as GetContactList plus joined locations

Function GetContactInfo(GroupSessionID: String; ContactID: String): String;
Function AddContactInfo(GroupSessionID: String; Parameters: String; ContactID: String = ''; _Notif: String = ''; _Now: Longint = $00): String;
Function DeleteContact(GroupSessionID: String; ContactID: String; KeepTables: Boolean = False; _Notif: String = ''): Boolean;
// Manages contact objects
//
// Special handling for item completion is used. For proper functionality and integrated functions
// you should call AddContactInfo once more after editing has been completed with blank Parameters and
// specified ContactID. This notifies the server the item is finished and can process subsequent tasks
// with it.
//
// KeepTables - Does not delete the extension tables


Function GetvCard(GroupSessionID: String; ContactID: String; Format: String = ''): String;
Function GetvCards(GroupSessionID: String; Where: String = ''; Format: String = ''): String;
Function AddvCard(GroupSessionID: String; Item: String; ContactID: String = ''; Params: String = ''): String;
// vCard of the contact object
// The same rules for Format apply as for AddvCalendar function

Function GetContactLocations(GroupSessionID: String; ContactID: String; Where: String = ''): String;
Function AddContactLocation(GroupSessionID: String; ContactID: String; Parameters: String; ItemID: String = ''): String;
Function DeleteContactLocations(GroupSessionID: String; ContactID: String; LocationID: String = ''): Boolean;
// Manages contact locations


// ------------------------
// Attributes, Tags & Attachments
// ------------------------

Function GetItemAttributes(GroupSessionID: String; ObjectID: String; Where: String = ''; ListOnly: Boolean = False): String;
Function AddItemAttribute(GroupSessionID: String; ObjectID: String; Value: String; Params: String): String;
Function DeleteItemAttribute(GroupSessionID: String; ObjectID: String; AttrID: String = ''; AttrType: String = ''): Boolean;
// Manages item attributes
// A groupware object can any number of attributes such as certificates, notes, x- attributes or any other
//
// For AddItemAttribute params must always contain AtrType and may contain AtrParam (case sensitive)
//
// AtrType:
//  note - note for notes objects
//  cert - certificate for contacts
//  x    - versit X- properties
//  tz   - versit VTIMEZONE object
//
// AtrParam - custom attribute parameters
// AtrID - Attribute ID for editing object


Function GetEventLastModified(GroupSessionID: String; Where: String = ''): String;
Function GetContactLastModified(GroupSessionID: String; Where: String = ''): String;
// Returns the list containing last item modification timestamp and item count in fields Max_ and Count_.
// Can be used to check if there has been any recent change in the folder.


Function GetTagList(GroupSessionID: String; Where: String = ''; Attributes: String = ''; Global: Boolean = False): String;
Function GetTagCount(GroupSessionID: String; Where: String = ''; Attributes: String = ''; Global: Boolean = False): Cardinal;
Function GetTagDetailList(GroupSessionID: String; Where: String = ''; Attributes: String = ''; Global: Boolean = False): String;
Function DeleteTag(GroupSessionID: String; Tag: String): Boolean;
Function AddTag(GroupSessionID: String; Tag: String; OldTag: String = ''): String;
Function SetItemTags(GroupSessionID: String; ItemID: String; Tags: String): Boolean;
Function GetItemTags(GroupSessionID: String; ItemID: String): String;
// Manages tags and their list. These funtions are used automatically by vcard and vcalendar functions.
// Should you use low level API you are required to use them.
//
// GroupSessionID can take two different IDs. A global group session ID and in such case it will return all global Tags. A folder session ID and in such
// case it will return the folder Tags. Global variable indicates you want the global list even for foldersessid (used to get tags for shared/public folders).
//
// SetItemTags links an item (contact, event) with a list of tags.
// These tags are separated with comma
//
// In order to lookup item tags you need to use Where with {TAG}tagname{/TAG}
// Eg.
// GetContactList(foldersessid, '{TAG}Competition{/TAG} And {TAG}Favorites{/TAG}', '', '')


Function GetAttachmentList(GroupSessionID: String; ObjectID: String; AttName: String = ''): String;
// Returns list of all attachments for the object. Any object can have an infinite number of
// attachments including notes, contacts, tasks, journals, contacts etc.
//
// AttName   - ID of the attachment
// AttDesc   - Description or filename
// AttType   - F,I,U,P (F - File, I - Link [FolderType:FolderID:ItemID], U - URL, P - Photo)
// AttSize   - Size of the attachment
// AttTime   - Unix time of the last update
// AttParams - Custom params (mimetype, imagetype)
//
// AttSkipValue - Special parameter to skip value (original content will be preserved)

Function GetAttachment(GroupSessionID: String; ObjectID: String; Name: String): String;
// Returns attachment for the object in binary

Function AddAttachment(GroupSessionID: String; ObjectID: String; Parameters: String; Value: String): String;
// Adds a new attachment with data and value in binary format

Function DeleteAttachments(GroupSessionID: String; ObjectID: String; ID: String = ''): Boolean;
// Deletes attachments. If ID is blank all attachments will be deleted.

Function GetAttachmentPath(GroupSessionID: String; ObjectID: String; AttName: String; Params: String): String;
// Handles the file path to attachment. Use this function when setting or retrieving attachments.
// When setting attachments always use AddAttachment with blank content and then LOCK and UNLOCK via this function.
//
// This function can also be used to retrieve the WebDAV URL of the item. In such case the AttName needs to be blank
// (applies to URL, TICKET parameterts).
//
// Params specifies additional attribute parameters. See the list of supported parameters below.
//
// URL    - Used to retrieve the attachment WebDAV URL
// TICKET - Used to retrieve the attachment URL (ticket URL without the need of authentication)
// LOCK   - Locks and returns the file path to read or write
// UNLOCK - Unlocks and frees the file previously locked with LOCK

// --------------
// Other & System
// --------------

Function GetLastError(SessionID: String): String;
// Returns the error of the last failed function. Call this function only after
// the call to the previous function failed. Do not call this function to validate
// the success of previous calls.
//
// The error consists of:
// Code ":" Textual representation
//
// Possible error codes:
//  E_GLICENSE = 1;    // Server does not have the sufficient license
//  E_RIGHTS = 2;      // User does not have rights to perform this action
//  E_ACCESS = 3;      // User does not have access permissions to performs this action
//  E_DB = 4;          // Database error or no result returned
//  E_PARAMETERS = 5;  // No database record found
//  E_GROUP = 6;       // Group not found
//  E_NOTFOUND = 7;    // Not found
//  E_TOOBIG = 8;      // Size too big
//  E_VIRUS = 9;       // Virus
//  E_TRANSACTION = 10; // Transaction error
//
// Eg.
// 4:Specified key was too long; max key length is 768 bytes

Function SetSessionExpiration(SessionID: String; Minutes: Longint): Boolean;
// Set non default session expiration in minutes

Function MigrateData(SessionID: String; SourceDSN, DestinationDSN: String): Boolean;
// Migrates all tables to new database. Only superuser or administrator can do this.

Function MigrateDataProgress(SessionID: String): String;
// Returns information about progress of database migration being in progress

Function GetServerVersion: String;
// Returns the server version

Function GetServerTimeZone: String;
// Returns the server timezone

Function GetTZIDList(TZFormat: Longint = $00): String;
// Returns the TZID list
//
// TZFormat
//   0 - TZID list
//   1 - GMT offset list

Function GetTZIDTime(SourceTime, SourceTZ, DestTZ: String; TZFormat: Longint = $00): String;
// Converts time from source in ISO8601 format (eg. 2010-01-01T00:00:00) to dest TZID. Blank TZID stands for local TZ
//
// TZFormat:
//   0 - TimeZoneID
//   1 - ActiveSync base64 TZ

Function GetTZIDVTIMEZONE(TZID: String): String;
// Returns VTIMEZONE object. Blank TZID stands for local TZ

Function GetVTIMEZONETZID(VTimeZone: String): String;
// Returns TZID from VTimeZone object. Blank VTimeZone stands for local TZ and standardized TZID will be returned.

Function IsAddressBookEmail(OwnerEmail: String; Email: String; Separate: Boolean): Boolean;
// Returns true if email is found in the server's address book

Function GetOwnerList(SessionID: String; Where: String = ''): String;
// Returns all groupware owner/users and their IDs

Function GetSessionList(SessionID: String): String;
// Returns all current sessions on the server

Function DialSIPNumber(SessionID: String; Number: String; Address: String = ''): Boolean;
// Initiates the call dialer on the SIP server which dials your SIP client and then
// transfers the call to the Number. If Address blank the currently logged on SIP client
// to your account will be used otherwise the Address will be dialed.

Function SyncGroupUsersContacts(GroupSessionID: String; Email: String; Folder: String = ''): Boolean;
// Synchronize all group members with the contacts folder (contacts and distribution lists)
// Members will be expanded (every member to its final form (domain = members, group = group members, etc.)

Function RenameDomain(SessionID: String; OldDomain: String; NewDomain: String): Boolean;
// Renames a domain and updates all required information in the database so the data
// is still accessible for account from the new domain.

Function DeleteDomain(SessionID: String; Domain: String): Boolean;
// Deletes a domain and


// --------
// Obsolete
// --------

// These functions still work but were replaced by higher and simpler API functions
// Try to avoid calling these

Function UserLoggedOn(SessionID: String): Boolean;
// Returns true if sessionID exists on the server.
// Note: Use GetFolderUpdate function instead

Function GetGroupAccess(SessionID, GroupID: String; DefaultTitle: String = ''; _Flags: Longint = $00): String;
// An alias to OpenGroup()

Function GetGlobalGroupList(SessionID: String; Where: String = ''): String;
// Returns the list of all public groups available for the user
// Note: Public folders automatically appear in the folder list


Function GetGroupAccessRightsList(SessionID: String; GroupID: String = ''): String;
// Returns the list of all open groups and their rights
//
// Fields: GRP_ID, GrpRights, OWN_ID, Own_Email

Function GetGroupUsers(GroupSessionID: String): String;
Function AddGroupUser(GroupSessionID: String; Parameters: String; ID: String = ''): String;
Function DeleteGroupUsers(GroupSessionID: String; ID: String = ''): Boolean;
// Manages ACL for the root folder
// Note: Use FolderRight functions instead


Function GetEventNoteText(GroupSessionID: String; EventID: String): String;
Function SetEventNoteText(GroupSessionID: String; EventID: String; Text: String): Boolean;
// Manages note object's infinite text content
// Note: Use Attribute functions instead with AtrType=note

Function GetIntervalHolidays(SessionID: String; Interval: String; CS: String): String;
// Returns holiday values and attributes for the given interval
// Note: GetAllIntervalEvents returns subscribed holidays with the EvnClass=H automatically


Function GetContactCertificate(GroupSessionID: String; ContactID: String): String;
Function SetContactCertificate(GroupSessionID: String; ContactID: String; Cert: String): Boolean;
// Manages contact certificates
// Note: Use Attribute functions instead with AtrType=cert

Function GetContactLocationPhones(GroupSessionID: String; LocationID: String): String;
Function AddContactLocationPhone(GroupSessionID: String; LocationID: String; Parameters: String; ItemID: String = ''): String;
Function DeleteContactLocationPhones(GroupSessionID: String; LocationID: String; ItemID: String = ''): Boolean;
// Manages contact location phones
// Note: Use direct ContactLocation functions instead (LctPhn fields)

