-
-
Notifications
You must be signed in to change notification settings - Fork 29
CardDAV Import Internals
β Back to CardDAV contact sync β developer guide, which covers the transport and the vCard mapping.
This page is the half that writes to the database: how scope is resolved, how a run is bookkept, what the policy layer does for free, and the two bugs that only showed up when the documented scheduled-task command was actually run.
A KIND:group card lists its members by UID. So you cannot decide whether an ordinary card is in scope until you have read the group card β and filtering in a single pass silently imports nobody when the group card happens to sort after its members, which alphabetically it usually does.
cdsyncResolveScope() therefore resolves the whole scope up front and returns a set, before anything is imported:
/**
* @return array ['uids' => set of in-scope UIDs, 'emails' => set of in-scope emails]
* or null when the scope is 'all' and everything is in scope.
*/
function cdsyncResolveScope(array $cards, string $scope, array $wanted): ?arrayThree modes, and the two filtered ones work differently:
carddav_scope |
Passes | How |
|---|---|---|
all |
β | returns null; cdsyncInScope() short-circuits to true
|
category |
one | a tag lives on each card, so one pass is enough |
group |
two | find the chosen group cards, then collect their MEMBERs |
All three of these are legal, and different clients write different ones:
MEMBER:urn:uuid:alice-1234
MEMBER:mailto:alice@example.com
MEMBER:alice-1234
So the scheme is stripped and both the UID and the email are accepted as ways of naming a member β which is why the resolved scope is two sets rather than one:
if (stripos($member, 'mailto:') === 0) {
$emails[mb_strtolower(substr($member, 7))] = true;
continue;
}
$pos = strrpos($member, ':'); // urn:uuid:xxx, or a bare UID
$uidPart = $pos === false ? $member : substr($member, $pos + 1);$isWanted = in_array(mb_strtolower($uid), $wantedLower, true)
|| in_array(mb_strtolower($name), $wantedLower, true);The picker stores the UID, which is the stable identifier β but a group deleted and recreated on the server gets a new UID and keeps its name. Accepting either means that case survives instead of silently importing nobody.
Category comparison is case-insensitive for the same class of reason: clients do not agree on case, and ITSM and itsm are the same tag to every one of them.
cardDavScanBook() reads every card once and reports what the book can be filtered by, so the UI offers a list of tick boxes instead of a text box the operator has to guess into:
$out = [
'contacts' => 0, // ordinary cards β what "bring in everything" would import
'groups' => [], // KIND:group cards, each with its MEMBER count
'categories' => [], // every distinct CATEGORIES value, with a count
];π Both are always reported, never one or the other. A server can use either or both, the two conventions come from different client families β KIND:group is how Apple Contacts stores a group, CATEGORIES is how Thunderbird and many Android clients do it β and the operator is the only one who knows which of their groups is the real one.
Categories come back most-used first (arsort), because the tag somebody wants is far more likely to be the one on eighty cards than the one on a stray two.
This is also why the original request β "scope it to one group called
itsm" β was answered with an enumerated picker rather than a text field. Asking the server what it has is both more flexible and less to explain than asking the operator to type a name correctly.
cardDavSyncRun($conn, $provider, $mode, $analystId) mirrors directorySyncRun() and shares its bookkeeping table, its counts and every one of its safety rules. $mode is 'live' or 'preview'; preview runs the identical code path with the writes suppressed.
INSERT directory_sync_runs (status 'running')
β
address book chosen? β throw
cardDavFetchCards() β throw on transport failure
cap at CDSYNC_MAX_CONTACTS
β
cdsyncResolveScope()
scope resolved to NOTHING? β throw (see below)
β
map every card, drop groups and no-UID cards, filter by scope
counts['seen'] = count($people)
β
syncBrakeTripped() β 'stopped', change nothing
β
ββ the policy layer, reused verbatim ββ
foreach person:
dsyncFindExisting() β [$existing, $how]
conflict + flag mode? β count, log, skip
existing? β dsyncApplyToExisting() (adopted | updated | unchanged)
otherwise β dsyncCreate()
β
dsyncHandleMissing() β rules 1 and 3
UPDATE auth_providers SET sync_last_count (live only β this is the brake's baseline)
β
dsyncFinishRun(); return dsyncGetRun()
if ($resolved !== null && !$resolved['uids'] && !$resolved['emails']) {
throw new RuntimeException('Stopped without changing anything: nothing in that
address book matches the chosen group. That is far more often a group or tag
renamed on the server than everybody leaving it, so no contact has been touched.');
}Without this the run imports nobody, and then dsyncHandleMissing() correctly observes that every managed contact was absent and starts counting them towards deactivation. A renamed group would begin quietly retiring your customer list. Same reasoning as the sanity brake, and it has to be a separate check because the brake only compares counts against a previous run.
| Rule | Where | Default |
|---|---|---|
| Nobody is ever deleted |
dsyncHandleMissing() deactivates, never deletes |
β |
| A run that looks wrong changes nothing | syncBrakeTripped() |
sync_brake_percent 20; 0 disables; a first run (no baseline) is never braked |
| Missing once is noise |
sync_missed_count increments |
sync_deactivate_after 3; 0 means never deactivate automatically |
// β οΈ `dsyncApplyToExisting()` returns a DESCRIPTION OF THE CHANGES, not an
// action keyword. Written as `if ($action === 'updated')` this loop compiled,
// ran, imported everybody correctly β and counted nothing, because no branch
// ever matched.The import was completely correct. Every job title, department and office was written. And the run summary and the History tab both said "0 updated", because the return value was being compared against words it never contains.
π Found by changing a card on the server and reading the counts β not by reading the code. A function that returns "job title, office" and one that returns "updated" are indistinguishable until you look at a number that should not be zero. It also put the changes string into the log rows' action column, which is where it first became visible.
Whether somebody was adopted rather than updated comes from $how, which says which rung of dsyncFindExisting() matched:
if ($how === 'email') {
$counts['adopted']++;
// β οΈ Their contact details are now maintained in the address book, so they
// can no longer be edited in FreeITSM β and their portal password stops
// working. That deserves its own word in the log, not "updated".
}cardDavSyncRun() originally returned a hand-built ['status' => β¦, 'counts' => [β¦]]. directorySyncRun() returns the run's database row via dsyncGetRun(). It also used the words 'error' and 'refused' where the LDAP path uses 'failed' and 'stopped'.
Two things broke silently, and neither was visible from the screen:
-
scripts/directory_sync.phpprints the flat column names β$run['seen_count']and friends β so every number the CLI reported was0while the message printed beside it said "Contacts read: 2. Created: 2." A scheduled task's own output contradicting itself. - Worse: the script sets its exit code from those two words. With
'error'and'refused'it matched neither, so a CardDAV import that failed exited 0 β and anything monitoring that task would have reported a healthy nightly import of nobody.
// π΄ Return the run ROW, exactly as directorySyncRun() does, and use its
// status words β 'ok' | 'stopped' | 'failed'.
return dsyncGetRun($conn, $runId);One shape and one vocabulary means the CLI, the web endpoint, the page and the History tab treat both kinds of source identically for free.
Verified by running it: exit 1 on failure, 2 on a stopped run, 0 when healthy.
β οΈ And the first attempt to verify that was itself wrong.php β¦ | tailreportstail's exit code, not PHP's, so everything looked like 0 and it nearly sent me chasing a bug that was already fixed.
auth_providers.protocol is 'oidc' | 'ldap' | 'carddav'. Only two of the three import people, and every place that assumed a binary had to be found:
// scripts/directory_sync.php --all
AND protocol IN ('ldap','carddav')π΄
--allpreviously selected onenabledandsync_enabledwith no protocol filter. That was a complete question while exactly one protocol could import, and wrong the moment a second could β it would have handed an address book to the LDAP engine. An OIDC id asked for by name is now refused with a sentence rather than a connection error.
π΄ Three protocols broke four
isLdap ? β¦ : β¦ternaries inapi/system/save_sso_provider.php. A two-way conditional reads as exhaustive and compiles fine; it would have stored every CardDAV provider as OIDC. Anywhere a protocol is branched on, grep for the binary form.
There is no internal scheduler. The operator sets up a task:
php scripts/directory_sync.php --all
It picks up every enabled source with importing switched on, address books and directories alike, and routes each by protocol. Documented on Scheduled tasks β where, until 1.8.0, the LDAP job had never been listed either, so no operator could learn from the documentation that any of this could be automated.
docker/ldap-test/ runs Samba AD and OpenLDAP side by side precisely so a new LDAP flavour cannot be added blind. CalDAV and CardDAV Β§5 predicted a CardDAV source would need its own equivalent "or it ships untested against a real server". It does, and it got one.
docker/carddav-test/ β BaΓ―kal 0.12.1, php:8.3-apache, port 8092:
docker compose up -d # then complete the web installer once
./seed.sh # two address books, five contacts, a group and tags
Notes worth keeping:
- The image installs the official release zip, pinned by sha256 (
0449abb72b151d39d9c08c63cb83a05d9e9adb065b1165ef6786b0b6a13d203c).β οΈ sabre/davitself is a library, not a server β you cannotcomposer requireyour way to something that answers PROPFIND. That is why the fixture is BaΓ―kal. - Leave
dav_auth_typeat its default of Digest. It is tempting to switch it to Basic to make the fixture simpler, and doing so would have hidden the single most likely real-world failure. - The seeded data deliberately includes a
KIND:groupcard,CATEGORIEStags, a foldedCATEGORIESline, and a card with no UID β one per trap on this page and the transport page.
π΄ The dev database is Ed's real data. Capture the row ids first, scope every write to them, and restore afterwards β verified back to 71 users, 0 runs, 0 identities after each round.
And the lesson that cost two rounds: assert that the response parses, not that it reads correctly.
A PHP warning printed before the JSON breaks every caller's
JSON.parsewhile the body still reads perfectly to a human. It happened twice in one day β once fromin_array($data['x'] ?? 'auto', [β¦]) ? $data['x'] : 'auto', which reads the key twice, and once from the carddav branch ofsave_sso_provider.phpnever setting$secretInput. A test that greps the body for the right words passes both times.
π΄ And a third time, shipped (#133, #1722). The read-it-twice fix was applied to
carddav_auth, and the identical line forcarddav_scope, directly below it, was left alone. It stayed harmless for exactly as long as the Add dialog sent a scope, which was twelve minutes; after the picker moved tocarddav.php, nobody could add an address book from 1.8.0 to 2.0.0. When you fix a pattern, grep for its twins.The same report exposed #1723: three screens save a provider and none sends every setting, so the endpoint now follows the house rule from Contact details - on an update, absent means don't touch - for every setting the protocol reads from the request.
- CardDAV contact sync β developer guide β transport, auth and vCard parsing
-
CardDAV write-back internals β the other direction.
β οΈ The import recordssource_refandsource_etagon every sighting for the write-back; if you change whatdsyncLinkIdentity()stores, read that page first. - CardDAV contact sync β the administrator's view
- Directory sync developer guide β the policy layer in full
- CalDAV and CardDAV β Β§5 priced this work before it was done, and Β§10 records what was expected to move the write-back
- Scheduled tasks β automating the import
- Contact details β the seven fields and who owns each one
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
- β³ πΌοΈ Logo and courses broke on Apache with PHP-FPM
- β³ π’ 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