-
-
Notifications
You must be signed in to change notification settings - Fork 27
CardDAV Contact Sync Developer Guide
How FreeITSM reads a CardDAV address book and turns its contacts into rows in users. Shipped in 1.8.0, asked for in #133.
This page covers the transport and the mapping β connecting, reading, and turning a vCard into a person. The import itself, the scope rules and the run lifecycle are on CardDAV import internals.
π Reading only. Sending a change the other way β surgical vCard editing, folding, escaping and the conflict rule β is a separate file (
includes/carddav_write.php) and a separate page: CardDAV write-back internals. The split is deliberate, so that "the import issuesPROPFINDandREPORTand nothing else" stays a fact about the code.
For the administrator's view, see CardDAV contact sync.
Directory sync already knew how to bring people into
userssafely. What it did not know was how to speak anything but LDAP.
includes/directory_sync.php owns the policy: nobody is ever deleted, a run that returns far fewer people than last time changes nothing, missing once is noise. None of that is about LDAP β and none of it was rebuilt.
What is about LDAP is every extension point around it: the columns are named ldap_attr_*, paging uses LDAP_CONTROL_PAGEDRESULTS, identity is objectGUID or entryUUID, and a manager is a distinguished name. CardDAV is HTTP and vCard β no DNs, no paged controls, identity is a URL plus an ETag.
So this is a fetch-and-map layer bolted under an existing policy layer, deliberately narrow:
βββββββββββββββββ CardDAV βββββββββββββββββ βββββ LDAP βββββ
β includes/carddav.php (transport) β β ldap_*() β
β includes/carddav_sync.php (map + run) β β β
ββββββββββββββββββββββ¬βββββββββββββββββββββ ββββββββ¬ββββββββ
β β
ββββββββββββββββ¬ββββββββββββββββ
βΌ
includes/directory_sync.php (the policy layer)
dsyncFindExisting / dsyncCreate / dsyncApplyToExisting
dsyncHandleMissing / syncBrakeTripped / dsyncGetRun
βΌ
users, directory_sync_runs
π The policy layer turned out to be genuinely transport-agnostic, which was not a given β it was written with only LDAP in mind. The import calls ten of its functions and nine are used exactly as the LDAP path uses them. The one change needed was cosmetic: syncBrakeTripped() gained an optional $words parameter so its message can say "the wrong address book, or a group renamed on the server" instead of naming a base DN. LDAP's defaults are untouched, so that path behaves identically.
Colour key: ποΈ schema Β· βοΈ engine Β· π API Β· π₯οΈ UI Β· π i18n Β· π³ test rig
| File | What it does | |
|---|---|---|
| βοΈ | includes/carddav.php |
the transport. HTTP, auth, PROPFIND/REPORT, vCard tokenising. Knows nothing about users. |
| βοΈ | includes/carddav_sync.php |
the import. vCard β person, scope resolution, the run. |
| βοΈ | includes/directory_sync.php |
the policy layer, shared with LDAP. Touched once, additively. |
| ποΈ | auth_providers |
protocol gains 'carddav'; carddav_addressbook, carddav_scope, carddav_scope_value, carddav_auth
|
| π | api/system/test_carddav_connection.php |
connect, list books, and scan the chosen one |
| π | api/system/run_directory_sync.php |
routes to the right engine by protocol
|
| π | api/system/save_sso_provider.php |
the third protocol branch |
| π₯οΈ | system/sso/carddav.php |
the config page β Connection / Contacts / History |
| π₯οΈ | system/sso/index.php |
the provider list, and the carddav type option |
| βοΈ | scripts/directory_sync.php |
--all filters protocol IN ('ldap','carddav') and routes |
| π | lang/en/system.php |
field_carddav_*, carddav_*, and the sso_keywords that make it findable |
| βοΈ | includes/carddav_write.php |
the write half: editing an existing card, and the portal and analyst pushes - see write-back internals |
| βοΈ | includes/carddav_create.php |
adding a new contact and linking the person - write-back internals Β§17 |
| π |
api/tickets/address_book_add.php Β· π₯οΈ assets/js/address-book-add.js
|
the Add to address book button on Tickets β Users and Assets β Users |
| ποΈ |
auth_providers.carddav_write_back Β· carddav_allow_create
|
write-back, and letting analysts add people (both default 0; the second is forced off without the first) |
| π³ | docker/carddav-test/ |
BaΓ―kal 0.12.1 in a container, with a seed script |
Read this before changing anything in carddav.php.
A stock BaΓ―kal β the standard sabre/dav server, and what the reporter runs β ships dav_auth_type: Digest. Measured against 0.12.1:
| Scheme | Result |
|---|---|
| Basic | 401 |
| Digest | 207 |
CURLAUTH_ANY |
207 |
Basic is the obvious choice and what almost every REST integration reaches for, and against a default install it fails outright. The operator then sees "authentication failed", checks a password that is correct, and concludes FreeITSM is broken.
$authMode = CURLAUTH_ANY;
if (($cfg['auth'] ?? 'auto') === 'digest') $authMode = CURLAUTH_DIGEST;
if (($cfg['auth'] ?? 'auto') === 'basic') $authMode = CURLAUTH_BASIC;So: CURLAUTH_ANY by default, an explicit override for the rare server that needs one, and the connection test reports which scheme actually won β because that is the one thing the operator cannot discover for themselves.
Three smaller things in cardDavRequest() that exist for a reason:
-
It sends a real
User-Agent. PHP's cURL sends none by default, and something in front of a server will read that as a bot and block it. That exact mistake once cost an afternoon of chasing a phantom WAF. -
It follows redirects.
http://βhttps://, or a path gaining a trailing slash, are both routine. -
cardDavExplainStatus()turns a status code into a sentence.405in particular is worth a real explanation: it means the address is reachable but is not a CardDAV endpoint β almost always a web page rather than the DAV path. A bare "HTTP 405" sends somebody to check their password.
$body = '<?xml version="1.0" encoding="utf-8"?>' .
'<d:propfind xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav" β¦>' .
'<d:prop><d:displayname/><d:resourcetype/><cs:getctag/></d:prop>' .
'</d:propfind>';A collection carrying the {urn:ietf:params:xml:ns:carddav}addressbook resource type is an address book. Everything else in the response β including the container you asked about β is not, which is how the parent gets excluded without special-casing it by URL.
β οΈ Namespaces are not optional. Servers use different prefixes for the same namespaces: BaΓ―kal answers withd:andcard:, others withD:andC:. Anything matching on prefixes works against one server and silently finds nothing against the next.cardDavParseAddressBooks()registers the URIs and queries those:$xp->registerNamespace('d', 'DAV:'); $xp->registerNamespace('card', 'urn:ietf:params:xml:ns:carddav');
π
nulland[]are different answers and must not be collapsed.cardDavParseAddressBooks()returnsnullwhen the body will not parse as DAV at all, and[]when it parsed fine and held no address books. The first is a wrong URL; the second is an empty account. Merging them produces "no address books found" for somebody who typed their web interface by mistake, and they will check their address books rather than their URL.
$body = '<?xml version="1.0" encoding="utf-8"?>' .
'<card:addressbook-query xmlns:d="DAV:" xmlns:card="urn:ietf:params:xml:ns:carddav">' .
'<d:prop><d:getetag/><card:address-data/></d:prop>' .
'</card:addressbook-query>';address-data returns the vCards inline, so this is one round trip. The obvious alternative β PROPFIND for the hrefs then a GET per card β is, on an address book of a few thousand contacts, the difference between one request and a few thousand.
β οΈ A server may answer with an absolute URL, a root-relative path, or a bare segment, and all three are legal. Concatenating blindly gives youhttps://host/dav.php/addressbooks/jsmith//dav.php/addressbooks/jsmith/itsm/β a 404 that reads like a missing address book rather than a client bug.cardDavAbsoluteUrl()handles the three cases.
RFC 6350 folds any line longer than 75 octets by inserting CRLF followed by a single space or tab. Servers really do this, and a long CATEGORIES list is exactly the kind of property that gets folded.
Parse the raw text line by line and you read:
CATEGORIES:customer,supplier,pa
rtner
as two lines β so the last value in a long list silently goes missing and everything still looks like it worked. One line prevents it:
$norm = str_replace(["\r\n", "\r"], "\n", $vcard);
$norm = preg_replace("/\n[ \t]/", '', $norm); // a continuation is \n + exactly one space or tabCATEGORIES:a,b and CATEGORIES;TYPE=x:a,b are the same property. An implementation looking for the literal CATEGORIES: misses the second. cardDavProperty() strips parameters, then compares case-insensitively because the spec says property names are case-insensitive:
$left = substr($line, 0, $colon);
$semi = strpos($left, ';');
$prop = strtoupper(trim($semi === false ? $left : substr($left, 0, $semi)));A comma inside a value is escaped, so splitting on a bare comma breaks it. Every split in this code uses a negative lookbehind:
preg_split('/(?<!\\\\),/', $rawCategories) // commas, but not \,
preg_split('/(?<!\\\\);/', $rawOrg) // semicolons, but not \;cdsyncMapCard() returns the array the policy layer expects, or null to skip the card.
return [
'guid' => $uid, // the policy layer's name; for LDAP it is objectGUID
'username' => '', // a contact has no sign-in name
'email' => $email ?: null,
'name' => $name,
'job_title' => trim(cardDavProperty($lines, 'TITLE')[0] ?? '') ?: null,
'department' => $org['department'],
'office' => cdsyncLocality($lines),
'phone' => $phone,
'mobile' => $mobile,
'employee_id' => null, // vCard has nowhere to keep one
'manager_dn' => null, // RELATED;TYPE=manager exists, almost nothing writes it
'dn' => $href, // for logging: the display equivalent of a DN
];// A KIND:group card is a container, not a person. "ITSM" is not somebody
// called ITSM, and importing one creates a contact nobody can explain.
if (strtolower(trim(cardDavProperty($lines, 'KIND')[0] ?? '')) === 'group') return null;
// β οΈ The UID is the identity. Without one there is nothing stable to match on
// across runs β the next run would create a second copy of the same person.
if ($uid === '') return null;π Skipping on a missing UID rather than falling back to the name is the important one. A name is not unique and not stable, so matching on it would either merge two different people or duplicate one person every run. Skipping is visible and recoverable; a duplicate every night is neither.
| Field | Source | The decision |
|---|---|---|
name |
FN, then N, then email, then UID |
FN is mandatory in the spec and absent in the wild. The chain exists so nobody lands as a blank row in the people list. |
email |
first EMAIL passing FILTER_VALIDATE_EMAIL
|
also the match key for an existing person, so a malformed one must not be stored |
phone / mobile
|
TEL by parameter |
CELL/MOBILE β mobile. Otherwise WORK wins, then any untyped number β a single untyped number on a card is the number somebody wants rung. |
department |
ORG component 2
|
ORG:Acme Ltd;Finance. Component 1 is the organisation, which FreeITSM has nowhere to put: a person's company is users.tenant_id, a real relationship rather than a string. |
office |
ADR component 4
|
ADR has seven components β PO box, extended, street, locality, region, postcode, country. The fourth is the town, which is what answers "which site are they at". |
employee_id |
β | Left null. Filling it with something that merely looks like a payroll number is worse than leaving it empty. |
manager_dn |
β | Left null. RELATED;TYPE=manager is in RFC 6350 and almost nothing writes it, so the chain is not imported rather than half-imported. |
Why
usernameis''and not the email. A contact has no sign-in. The policy layer already storesNULLrather than an empty string for it, so contacts do not pile up against a unique index.
- CardDAV import internals β scope resolution, the run lifecycle, the counts bug, the CLI, and the Docker test rig
- Directory sync developer guide β the policy layer this sits under
- Extending directory sync β Β§2, the extension points this deliberately does NOT use
- CalDAV and CardDAV β Β§5 priced this work before it was done, and was right
- CardDAV contact sync β the administrator's view
- CardDAV write-back internals β the other direction, and the reason it is a separate file
- CalDAV and CardDAV β the original analysis, and CalDAV, which is still not built
FreeITSM β an open-source IT Service Management platform Β· github.com/edmozley/freeitsm Β· MIT licence
- Installation
- β° Scheduled tasks (cron jobs)
- Architecture
- π§ͺ Developer tests
- AI Providers
- Internationalisation (i18n)
- Timezones & Time Handling
- π Date & Time Formats
- Theming & Dark Mode
- ποΈ Recent β getting back to what you were doing
- β¨οΈ Command palette (βK)
- π Searching inside tickets
- π Attached documents
-
MobileβFriendly
- β³ π« Mobile: Tickets
- β³ π» Mobile: Assets
- β³ π Mobile: Calendar
- β³ π Mobile: Knowledge
- β³ π¦ Mobile: Service Status
- β³ πΌ Mobile: Watchtower
- β³ π§© Mobile: Problem Management
- β³ π Mobile: Change Management
- β³ πΏ Mobile: Software
- β³ β Mobile: Tasks
- β³ π Mobile: Forms
- β³ π Mobile: Contracts
- β³ π Mobile: Domains
- β³ π Mobile: People
- β³ π Mobile: LMS
- β³ πΊοΈ Mobile: CMDB
- β³ πΊοΈ Mobile: Network Mapper
- β³ π§ Mobile: Process Mapper
- β³ βοΈ Mobile: Workflow
- β³ π₯οΈ Mobile: System
- β³ π Mobile: Reporting
- β³ π Mobile: System Wiki
- β³ π Mobile: Self-Service Portal
- β³ π§° Mobile: Techniques & Tricks
-
Security
- Layer 1 β which modules you can enter
- β³ π§© Module Access Control
- β³ π οΈ Module Access β Developer Guide
- Layer 2 β what you can administer
- β³ π Roles & Permissions
- β³ π οΈ Roles β Developer Guide
- β³ π€ Why capabilities are constants
- Layer 3 β the System module
- β³ π Admin Access Control
- Hardening
- β³ π Security review response 2026-08
- β³ π‘οΈ Security hardening 2026-08
- β³ π οΈ Security hardening 2026-08 β Developer Guide
- β³ π‘οΈ Round three β plain English
- β³ π οΈ Round three β Developer Guide
- β³ π‘οΈ CSRF protection (S4) β Developer Guide
- Single Sign-On (SSO)
- ποΈ LDAP & Active Directory
- π CardDAV contact sync
- Browser Extension
- API Reference
-
π REST API β how it works
- β³ π« REST API: Tickets
- β³ π» REST API: Assets
- β³ π΄ REST API: Problems
- β³ π REST API: Changes
- β³ π REST API: Knowledge
- β³ β REST API: Tasks
- β³ ποΈ REST API: CMDB
- β³ π REST API: Contracts
- β³ ποΈ REST API: Calendar
- β³ πΏ REST API: Software
- β³ π REST API: Domains
- β³ π¦ REST API: Service Status
- β³ βοΈ REST API: Morning Checks
- β³ π REST API: Forms
- β³ βοΈ REST API: Workflow
- β³ π·οΈ REST API: Cost centres
- β³ πΊοΈ REST API: Network Mapper
- β³ π§ Using the API docs page
- β³ π OpenAPI specification
- β³ β OpenAPI: kept correct
- β³ π οΈ Maintaining the catalogue
- Watchtower
-
Tickets
- β³ π Rota copy and paste β Developer Deep Dive
- β³ β Checklists & SOPs
- β³ βοΈ Mandatory fields
- β³ π·οΈ Ticket categories
- β³ π₯ Assigning tickets to a team, and escalation
- β³ π’ One board across every company
- β³ Mailbox Authentication
- β³ π€ Email send log
- β³ Basic IMAP mailboxes
- β³ Email rendering & images
- β³ SLA Management
- β³ WhatsApp channel
-
β³
βοΈ Telegram channel - β³ β CSAT company scope and filters β Developer Guide
- β³ π₯ Microsoft Teams channel
- β³ π¨οΈ Mattermost channel
- β³ π¬ Web chat channel
- β³ π£ Slack channel
- β³ π Linking tickets
- β³ β Record previews
- β³ π Ticket notes: internal or shared
- β³ ποΈ Canned responses
- β³ βοΈ Limiting replies to particular senders
- β³ π¨ Telling the analyst a ticket is theirs
- β³ βοΈ Email signatures
- β³ π The public web address
- β³ π’ Ticket numbering
- β³ π Raising a ticket for someone else
- β³ π Merging tickets
- β³ π Confidential tickets
- β³ π₯ Portal managers
- β³ π Who has seen a ticket
- β³ π Reading long tickets
- β³ β Splitting tickets
- β³ β Selecting several tickets
- β³ ποΈ The folder pane
- β³ π½ Just my tickets, or no closed ones
- β³ π οΈ Snoozing tickets β Developer Guide
- β³ π₯ Collision detection
- β³ β±οΈ Time tracking
- β³ π Scheduled work in your own calendar
- Problem Management
- Tasks
-
Assets
- β³ π’ Moving an asset between companies
- β³ π Shared asset locations
- β³ π§βπΌ Assigning assets to analysts
- β³ π Warranty and lease alerts
- β³ π Saved table views
- β³ π¨οΈ Recording anything, and importing it
- β³ π·οΈ QR asset labels
- β³ π Who holds what, and handover documents
- β³ π₯οΈ The inventory agent (PowerShell)
- β³ ποΈ Proxmox VE servers
- β³ βοΈ VMware Cloud Director servers
- β³ π Linking equipment to tickets
- β³ βοΈ Follow-up tasks on a ticket
- Knowledge
- Change Management
- Calendar
- Morning Checks
- Reporting
- Software
-
Forms
- β³ π¨ The form designer β Developer Guide
- β³ π Layout & the grid β Developer Guide
- β³ ποΈ Collections β grouping submissions
- β³ π Submissions as PDFs
- β³ β‘ What happens next β a form's own actions
- β³ π οΈ Sections & conditional logic β Developer Guide
- β³ π οΈ Lookup fields β Developer Guide
- β³ π‘οΈ Catalogue request approvals
- People
- Domains
- Contracts
- Service Status
- π Notifications
- π¨ War Room
- Self-Service Portal
- LMS
- Process Mapper
- CMDB
- Network Mapper
- Workflows
- Issue trackers (Jira, Azure DevOps)
- System
-
Overview
- β³ π Progress tracker
- β³ Concepts & vocabulary
- β³ Email routing & mailboxes
- β³ Settings: global vs per-company
- β³ Users & self-service
- β³ Staff cross-company access
- β³ π’ One board across every company
- β³ Worked examples
- β³ Pitfalls & gotchas
- β³ Scope: what it's for
- β³ π οΈ Developer Guide (make a module multi-company)
- β³ ποΈ Case study: CMDB (a linked graph)
- β³ π§ͺ Test harness (prove it's isolated)
- What this is
-
π Bugs resolved
- β³ π’ Chat tickets ignored your ticket numbering
- β³ π Dates shown as a dash, or in server time
- β³ π Assets β Users showed people from other companies
- β³ π Restricted analysts could read other modules' data
- β³ πΌοΈ Replies with a picture in the thread failed to send
- β³ π Reply attachments never reached the customer
- β³ π οΈ Outbound email attachments β Developer Guide
- β³ π A global SSO provider was missing from the portal
- β³ π Behind a proxy, the SSO redirect said http
- β³ βοΈ The portal tagline moved when you saved it
- β³ π¨ The portal settings screen forgot what you saved
- β³ π‘οΈ The approvals inbox said "Error" and nothing else
- β³ π A table's answers were missing from the PDF
- β³ β A single-select column let you tick every option
- β³ π The portal ignored a form's field widths
- β³ π The tasks board stopped taking clicks
- β³ ποΈ #121 The index list is out of date after upgrading
- β³ π #133 The calendar subscription was empty
- β³ π #131 Tasks always reopened on the board
- β³ π₯ #129 Every page returned HTTP 500 after upgrading
- β³ π³ #127 A PHP warning above the System page
- β³ π #126 Notes stamped with the server's clock
- β³ π Storing every date in UTC
- β³ πͺ The portal was down for everyone signed in
- β³ βοΈ #120 Workflow notes could never be written
- β³ βοΈ #123 Three errors when running Database Verification
- β³ π #122 The description box was a stub in the corner
- β³ π£ Demo data deleted real accounts
- β³ π #117 Sign-in redirected to the wrong address
- β³ π¨ #108 The priority dot was invisible
- β³ β±οΈ #116 Time logged from the right-click menu
- β³ π #114 API keys refused by our own guard
- β³ ποΈ #110 Assigning a task told nobody
- β³ πͺ #107 Signed out while still working
- β³ π #103 "Share with Requester" reached nobody
- β³ π #102 Search found nothing for hyphens
- β³ πͺ #101 Source code editor opened behind
- β³ βοΈ #88 Subtasks could not be ticked off
- β³ π» #84 Asset deep link selected nothing
- β³ π« #79 A new ticket arrived with no status
- β³ π§ #79 A ticket from email did not say so
- β³ π #78 Bell opened to nothing
- β³ π¬ #77 Mail only collected from Inbox
- β³ π #74 The default password could not be changed
- β³ π¦ #70 Renaming an impact level
- β³ π€ #67 App-only mailboxes could not send
- β³ π #45 Verify only ever worked for Microsoft
- β³ π #45 IMAP reported as not authenticated
- β³ βοΈ An email template stopped escaping itself
- β³ π The portal dashboard showed the wrong time
- β³ π’ The folder said 99 and the list showed 96