PHP SDK reference

Configure the PHP SDK's client and look up how each part of it behaves. For offline tests, see PHP testing.

Client settings

CalmLens\ServerClient takes your apiKey and projectId, and optionally:

SettingDefaultEffect
baseUrlhttps://api.calmlens.com/v1The API base URL.
cdnBaseUrlhttps://cdn.calmlens.com/v1The CDN base URL.
timeout120 secondsEach API request attempt, response included.
uploadTimeoutNoneEach binary upload attempt, since files may be large. Text uploads use timeout.
connectTimeout10 secondsOpening a connection.
maxRetries2Retries after the first attempt; see Retries and idempotency.
maxResponseBytes32 MiBThe largest API response body the client reads.
partSizeBytes8 MiB (8388608)Content larger than this is uploaded automatically in parts of this size; see Multipart uploads. From 5 MiB (5242880) to 64 MiB (67108864); anything else throws sdk/invalid-config.
httpClientA new Guzzle clientA Guzzle ClientInterface with your application's transport configuration.

The defaults are constants on ServerClient, such as ServerClient::DEFAULT_TIMEOUT. An invalid API key or project ID throws ConfigurationException with sdk/invalid-config. Requests send a calmlens-php/<version> (php/<version>) User-Agent.

Keep API keys on your server. Reuse a client within a request or worker: each client caches the lens definitions it has ensured.

Calls are synchronous. There is no separate cancellation handle; waitForDecision's timeout bounds the whole wait, and the other timeouts bound each attempt.

Options and return values

Every method takes one options array whose keys match the API's field names, such as ['assetId' => 'asset_5Gm2Rk8XqT3wLp9VbN4c']. Pass ['folderId' => null] to assets->move(), or ['parentId' => null] to folders->move(), to move to the project root.

assets->delete(), folders->delete(), hashLists->delete() and hashLists->removeEntry() return nothing. Other network methods return the decoded JSON response as an associative array.

Uploads

Supply a name and exactly one of content, part or url:

  • content holds one of plainText, base64, or data/bytes: a binary string, PHP stream resource or PSR-7 stream, with a concrete MIME type. Sized streams are sent from their current position, without loading them into memory.
  • part starts a multipart upload.
  • url submits a website, such as ['name' => 'page', 'url' => 'https://example.com'].
$file = fopen('/path/to/photo.jpg', 'rb');
try {
    $asset = $client->assets->create([
        'name' => 'photo.jpg',
        'content' => ['data' => $file, 'type' => 'image/jpeg'],
        'processingOptions' => ['keepContentAfterProcessing' => true],
        'metadata' => [['id' => 'source', 'value' => 'profile']],
    ]);
} finally {
    fclose($file);
}

Multipart uploads

assets->create() and assets->classify() send content larger than partSizeBytes (8 MiB by default) as a multipart upload for you, when the client knows its size and can read it again: binary strings, base64, and stream resources or PSR-7 streams that can seek, read from their current position. Text and streams that can't seek go in one request. Parts are partSizeBytes long, except the last. Each part is retried on its own, and part n from the second onwards carries the Idempotency-Key <idempotencyKey>:part-<n>, so an idempotencyKey for content sent in parts can be at most 240 characters. Parts the API already received are skipped, and the call returns the asset from the final part. If a call fails partway, call it again with the same idempotencyKey in requestOptions to resume: the API replays the parts it has and the client sends the rest.

$file = fopen('/path/to/report.pdf', 'rb');
try {
    $asset = $client->assets->create([
        'name' => 'report.pdf',
        'content' => ['data' => $file, 'type' => 'application/pdf'],
        'requestOptions' => ['idempotencyKey' => 'upload-report-42'],
    ]);
} finally {
    fclose($file);
}

Content in parts can be as large as its type allows: images up to 20 MiB, audio and video up to 50 MiB, other files up to 5,000 MiB.

To send the parts yourself, such as when you produce a file in chunks, start with part in place of content, then send later parts with uploadPart():

$client->assets->uploadPart([
    'assetId' => $id,
    'part' => ['data' => $bytes, 'partNumber' => 2, 'isFinal' => true],
]);

Parts need exact byte counts. Non-final parts must be at least 5 MiB, and images can be sent in parts at any size up to 20 MiB, including as one final part; pass totalSizeInBytes on the first call when you know it. CalmLens stores whether the first part returns without waiting (create(), wait=false) or waits for the decision (classify(), wait=true), so later parts can come from another process. Pass wait (a boolean) to uploadPart() only to override it.

Conversation context

For a post in a conversation, pass authorId (your label for who wrote it) and context, the earlier posts oldest first. CalmLens moderates only the content, and reads the earlier posts to understand who it addresses and what it refers to:

$asset = $client->text->classify([
    'text' => 'Same to you',
    'authorId' => 'user-9',
    'context' => ['items' => [
        ['text' => 'You played well today', 'authorId' => 'user-1'],
        ['text' => 'Thanks!', 'authorId' => 'user-9'],
    ]],
]);

The SDK sends only the posts CalmLens uses: the 5 most recent that fit in 2,000 characters (Unicode code points), always including the newest. CalmLens\ModerationContext::select($items) applies the same rule, with the limits in ModerationContext::USED_ITEMS and ModerationContext::USED_CHARACTERS. Assets return authorId and the context used, which becomes null once the content is removed. See Threaded moderation.

Moderation results

classification.moderation.status is pending, then allowed, limited, age-restricted, blocked or purged. Treat any other value as not ready. A classification failure is not a decision to allow: while classification.status is failed, classification.failureReason says why (see Failure reasons); otherwise it is null.

Manual reviews in classification.moderation.manualReviews record their decision as one of the five decided statuses. To list only allowed assets, filter with classification.moderation.status==allowed.

Record a reviewer's decision with assets->decide(); the note is required. An asset still pending moderation can only be blocked or purged, and purging deletes the stored content:

$client->assets->decide(['assetId' => $asset['id'], 'decision' => 'blocked', 'note' => 'Spam reported by members']);
$client->assets->decide(['assetId' => $asset['id'], 'decision' => 'purged', 'note' => 'Illegal content', 'confirmPurge' => true]);

assets->batch() takes assetIds (1 to 500) and an operation, Assets::BATCH_DELETE or Assets::BATCH_REMOVE_CONTENT. It checks the list before sending and is not retried.

Hash lists

Hash lists hold PDQ hashes of images you never want again. Image uploads are compared with every list in the project: a flag list reports matches, and a block list also blocks close ones.

$list = $client->hashLists->create(['name' => 'Removed images', 'action' => 'block']);
// Add a 64-character hex PDQ hash, or the hash of an image asset that finished processing.
$entry = $client->hashLists->addEntry(['hashListId' => $list['id'], 'assetId' => $assetId, 'label' => 'Report 1042']);
$page = $client->hashLists->listEntries(['hashListId' => $list['id'], 'pageSize' => 50]);
$client->hashLists->removeEntry(['entryId' => $entry['id']]);

Adding a hash the list already holds returns the existing entry. An asset without a perceptual hash fails with 409 hash-list/asset-not-hashed (ErrorCodes::HASH_LIST_ASSET_NOT_HASHED). update() takes name, description (null clears it) and action. Deleting a list deletes its entries. hashLists->each() and hashLists->eachEntry(['hashListId' => ...]) iterate over every list and every entry of a list.

Policies

Moderation policies belong to the API key's organisation, and its projects share them. Every change sends the policy's revision; a policy changed since is refused with 409 policy/revision-conflict (ErrorCodes::POLICY_REVISION_CONFLICT), so retrieve it again before retrying.

$current = $client->policies->retrieveAssigned();
$kids = $client->policies->create(['presetId' => 'children-platform', 'name' => 'Kids section']);
$updated = $client->policies->update(['policyId' => $kids['id'], 'revision' => $kids['revision'], 'description' => 'Stricter rules for the kids section']);
$client->policies->assign(['policyId' => $updated['id']]);
foreach ($client->policies->each() as $policy) {
    // Every policy of the organisation, oldest first.
}

list() returns one page of the organisation's policies, oldest first, and each() iterates over them all. retrieveAssigned() returns the policy the project moderates with. create() takes settings with a name, or a built-in presetId; settings['categorySettings'] defines every category, each with its action, allowances and restrictions.

A policy made from a preset has preset['mode']: live follows the preset's latest release, pinned is the organisation's own preset policy held at one release, and copy is a saved copy. reset() restores the settings of the release a pinned or copy policy is pinned to (send its preset['version'] as presetVersion), and upgrade() moves an unchanged one to the latest release (send preset['latestVersion']). setAutomaticUpdates() turns the organisation's own preset policy live or pinned. delete() refuses a policy a project or upload preset still uses with 409 policy/in-use.

Pagination and filters

Every list returns a cursor page with items, nextCursor and hasMore. Pass a page's nextCursor as cursor for the next one, and treat it as opaque. Lists take pageSize (1 to 100, 50 by default).

  • Asset, child, hash list, entry, policy and lens lists take sort: createdAt and id, comma-separated, each descending when prefixed with -, such as '-createdAt,id'. Assets, children, hash lists, entries and lenses list newest first by default, and policies oldest first.
  • Asset lists also take filter, such as 'folderId==' . $folderId for one folder's assets; see Pagination and filtering.
  • folders->list() sorts by name (the default) or createdAt, such as '-createdAt', and returns the ancestors needed to show the folders' paths.
  • assets->listTimeline() and events->list() take no sort. events->list() without cursor returns no events and a nextCursor for the current feed position. Save it to consume later events.
  • assets->search() has no cursor: it returns the best pageSize matches (1 to 20, 10 by default).
foreach ($client->assets->each(['pageSize' => 100, 'sort' => 'createdAt']) as $asset) {
    // Process each asset, oldest first.
}

Every list has a generator that follows the cursor for you, keeping the other options: assets->each(), assets->eachChild(), assets->eachTimelineSegment(), folders->each(), hashLists->each(), hashLists->eachEntry(), policies->each() and lenses->each() stop at a page without a next cursor, with hasMore false or with no items; events->eachPage() and events->each() stop when hasMore is false. Rather than loop, they throw InvalidResponseException with sdk/invalid-response (and the repeated cursor in details['cursor']) when a page with more to follow returns a cursor they already sent, without yielding that page.

Errors

Every error the SDK throws is a CalmLens\CalmLensException with:

  • errorCode: the API's error code, unchanged, or one of the SDK's own codes.
  • status: the HTTP status, or null without a response.
  • details: the API error's details object, such as validation issues. Transport errors carry no details.
  • headers and requestId: the X-Request-Id header, or the error body's requestId without it. Include it when you contact support.
  • getPrevious(): the underlying exception.

Helpers: retryAfter() (seconds from Retry-After, or null), isNotFound(), isRetryable() and header($name). Compare codes with the constants in CalmLens\ErrorCodes (with each code's HTTP status in ErrorCodes::STATUSES) and CalmLens\SdkErrorCodes, never with the message. To handle one kind of failure, catch a subclass from CalmLens\Exception:

ClassWhen
ApiException, and its subclasses BadRequestException (400), AuthenticationException (401), PermissionDeniedException (403), NotFoundException (404), ConflictException (409), RateLimitException (429) and ServerException (5xx)The API answered with an error status.
ConnectionException (sdk/transport-error), and its subclass TimeoutException (sdk/timeout)No complete response arrived, or waitForDecision had no decision in time.
InvalidResponseException (sdk/invalid-response, sdk/response-too-large)A successful response couldn't be read, or its body or declared Content-Length was larger than maxResponseBytes.
InvalidArgumentException (sdk/invalid-argument, or an upload/* code for payload checks the API also makes)An argument was rejected before sending, including an option the method doesn't take, such as a misspelt externalId.
ConfigurationException (sdk/invalid-config), a subclass of InvalidArgumentExceptionServerClient received an invalid setting.
WebhookVerificationException (sdk/invalid-webhook-signature, sdk/invalid-webhook-payload)A webhook delivery failed verification.

See Error handling.

Retries and idempotency

GET requests and uploads retry connection failures, timeouts, 429, 500, 502, 503, 504 and 409 idempotency/request-in-progress, up to maxRetries times. Each upload generates one idempotency key and reuses it on every retry. Other writes are retried only when you supply an idempotencyKey. Streams that can't seek are never replayed.

Retry n (counting from 0) waits half of min(8, 0.5 × 2ⁿ) seconds plus a random part of the other half. A Retry-After header (whole seconds or an HTTP date; 0 retries at once) replaces that wait, and one over 60 seconds returns the error to you instead. cdn->serve() retries the same way and returns the last response.

Redirects are never followed, to protect credentials: a 3xx fails with sdk/http-error, its status and request ID, and isn't retried, cdn->serve() included.

Pass per-call settings in a requestOptions key: timeout, uploadTimeout, connectTimeout, maxRetries, maxResponseBytes and idempotencyKey. The API checks the key: 1 to 255 printable characters, with no space at either end. See Retrying requests safely.

CDN URLs and transforms

$url = $client->cdn->getAssetUrl([
    'assetId' => $asset['id'],
    'resource' => 'rendered',
    'transform' => ['width' => 640, 'format' => 'webp'],
]);
$response = $client->cdn->serve(['assetId' => $asset['id']]);
// Check $response->getStatusCode(); read $response->getBody() in chunks, then close it.

URL builders name the asset by assetId or externalId and accept projectId (the client's by default), resource, lens, a string or array transform, and viewerClaims. Without resource, getAssetUrl() returns the asset URL, which every resource is a path beneath, and serve() fetches rendered. The resources are original, rendered, preview, placeholder, hls, embed and info; only rendered and preview take a lens or transform.

A transform is an options string or an options array. A transform is one path segment of options, such as fit=cover,format=webp,width=640, and a lens comes first in the same segment (/rendered/@thumbnail,width=320), with the transform's options replacing the lens's options of the same name. Array options are sorted, nested options are dotted (border.color) and hex colours drop the #, so the example above builds .../rendered/format=webp,width=640. See Lenses and transforms.

cdn->serve() returns a streaming PSR-7 response, HTTP error responses included. Its init option takes method (GET or HEAD) and headers, such as Range.

Signed asset URLs

cdn->signAssetUrl() signs a private asset's URL on your server, so browsers load it without your API key, and returns url and expiresAt (Unix milliseconds). expiresIn is 1 to 86400 seconds (Cdn::DEFAULT_SIGNED_URL_EXPIRES_IN, 900, by default), and 'original' => true lets the URL serve the original; without it, /original returns 403 signed-url/original-not-granted.

$signed = $client->cdn->signAssetUrl(['assetId' => $asset['id'], 'expiresIn' => 900]);
$thumbnail = $signed['url'] . '/rendered/@thumbnail';

Every resource is a path beneath the signed URL, as beneath a public one. The grant binds the project, the asset, original access and the expiry; resource, lens, transform and viewerClaims are appended unsigned, exactly as getAssetUrl() appends them, so you can change them without signing again. See Signed asset URLs.

cdn->getAssetInfo($url) reads an asset URL's display info, public or signed, without the API key: id, projectId, type, externalUrl, content and availability for the URL's viewer claims (or viewerClaims in its options). A refusal throws the CDN's code, such as 403 signed-url/expired.

Viewer claims

CDN methods and signAssetUrl() accept viewerClaims with region and ageConfirmed, appended unsigned to the URL, leaving out the defaults. Region defaults to the country of the connection reaching CalmLens, and age confirmation to false. CalmLens accepts these as your application's assertions without verifying them.

The CDN refuses age-restricted content with 403 viewer/age-confirmation-required unless ageConfirmed is true, even for API-key and signed-URL requests. Pass 'viewerClaims' => ['ageConfirmed' => true] only where your app has already decided the viewer may see age-restricted content; applications that never serve it, including processing jobs, should leave it false. Private assets separately need access permission, and claims can't override blocks or safety holds.

A limited asset is delivered exactly like an allowed one; it is marked so your app can reduce its reach. Blocked assets aren't served, and purged assets have no content. For proxies, raw HTTP and caching, see Viewer claims and Viewer region.

Lenses

A lens is a named transform the CDN applies at /@<identifier>, and the CDN serves files made with its current definition. $client->ensureLens($definition) creates a lens (identifier, name, type, active, description and transform), or changes it to this definition. $client->ensureLenses(['lenses' => [...]]) takes several, sends them in batches of at most 100 and caches the successful definitions on the client, so ensuring the same definition again makes no request. Use them for lenses your application declares in code. See Named lenses.

$client->lenses manages the project's lenses one by one:

$card = $client->lenses->create(['identifier' => 'card', 'name' => 'Card', 'type' => 'image', 'active' => true, 'transform' => ['width' => 640, 'format' => 'webp']]);
$client->lenses->update(['lensId' => $card['id'], 'transform' => ['width' => 1200, 'format' => 'webp']]);
foreach ($client->lenses->each() as $lens) {
    // Every lens of the project, newest first.
}
$client->lenses->delete(['lensId' => $card['id']]);

create() needs an identifier new to the project; one already used fails with 409 lens/identifier-taken (ErrorCodes::LENS_IDENTIFIER_TAKEN). retrieve(), update() and delete() take the lens's lensId, and an unknown one fails with 404 lens/not-found (ErrorCodes::LENS_NOT_FOUND). update() changes name, description, type, transform or active; the identifier stays. After a delete, URLs that select the lens stop being served. Changes made through lenses also clear the client's ensureLens cache for that lens.

Webhooks

CalmLens\Webhooks::parseEvent($payload, $signature, $timestamp, $secret) verifies a delivery and returns the event. It takes the exact raw body, compares the HMAC in constant time, and accepts timestamps within Webhooks::SIGNATURE_TOLERANCE_SECONDS (300) of your clock; pass toleranceSeconds to change it, where 0 accepts only the current second. Webhooks::verify() takes the same arguments and returns a boolean.

Pass null for the signature and timestamp, and headers (from getallheaders(), $_SERVER or a PSR-7 request's getHeaders()), to read them from the request. Header names match in any case, and repeated headers are joined with ,, so a signature list split across headers verifies and a repeated timestamp doesn't.

parseEvent throws sdk/invalid-webhook-payload unless the body is an object with a string id, type and projectId and a numeric createdAt, and its other known fields (severity, title, description, assetId, asset and facts) have the API's types.

Moderation sends asset.classified when classification finishes and one event per status, for automated and reviewer decisions alike: asset.allowed, asset.limited, asset.age-restricted, asset.blocked and asset.purged. asset.failed reports failed processing. Event asset snapshots carry classification.moderation.status.

Webhooks::eventFact($event, $key) returns one of an event's fact values, such as flagged-categories on asset.blocked, or null when the event doesn't carry it. Webhooks::eventFacts($event) returns them all as values by key; a repeated key keeps its first value. A fact's url, when it has one, stays on the fact in $event['facts'].

Retries of one delivery repeat its x-calmlens-delivery ID (Webhooks::DELIVERY_HEADER), so use it, or the event id, to skip duplicates. Test deliveries carry the registered test: true fact, which Webhooks::isTest($event) recognises. Deliveries can arrive out of order, so store the highest assetSequence you have applied for each asset. Webhooks::isNewerAssetEvent($event, $lastSequence) is false for an event whose assetSequence isn't higher than $lastSequence, and true for a newer one, an event that isn't about an asset, or a null $lastSequence. To test your receiver, see Webhook handlers.

Upload tokens

$client->uploadTokens->sign(['uploadPresetId' => $presetId, 'externalId' => $id]) returns token and expiresAt (Unix milliseconds). Signing is local and makes no request. Tokens last 600 seconds by default; set expiresIn from 1 to 3600. Issue a fresh token per upload, after authenticating and authorising the browser user. See Upload tokens.

Newer API versions

The SDK preserves response fields it doesn't know, unknown event types and fact keys, and structured fact values, so responses from a newer API keep working. Treat a status you don't recognise as not allowed.

Last updated

Signing in

Signing out

Cookies on CalmLens

We use essential cookies for sign-in and security. With your permission, functional cookies remember your preferences and Google Analytics measures website use and signups. Optional ad measurement cookies link Google ad clicks to signups. Personalised advertising stays off. Manage cookies