Appearance
Services, Support and Integrations ​
Overview ​
This page covers the non-model, non-controller code under app/: the service classes in app/Services, the static helpers in app/Support, the global helper file, the traits, and the small legacy folders (app/RestResource, app/ZipCode, app/PushNotification, app/ProjectActivity, app/WorkSpaceActivity, app/Logging, app/storage). The last section lists every external service the code actually calls, with the config file and env variable names.
| Folder | What it holds |
|---|---|
app/Services/BigQueryLog | Log spooler and loggers that ship API, job, cron, webhook and SSO logs to BigQuery |
app/Services/DAM | FolderVisibilityRecalculator, the shared portal visibility calculator for folders |
app/Services/Sso | SAML 2.0 company sign-in (enterprise SSO) |
app/Services/WorkspaceMailService.php | Per-workspace SMTP for white-label workspaces |
app/Services/*Token.php, PortalLoginTicket, SingleShareLink, UploadedObjectUrl, RichTextSanitizer | Signed link tokens and input hardening (added in PR #453) |
app/Support | CustomFieldValue, RequestEnvironment, TimezoneName, WorkspaceBrand, WorkspaceMailContext |
app/Helpers/Helper.php | Global functions, autoloaded through composer.json autoload.files |
app/Traits, app/Permissions, app/Exports/Concerns | Four traits |
app/RestResource | RestResponse, the JSON envelope used by almost every controller (see Resources and requests) |
app/ZipCode, app/PushNotification, app/ProjectActivity, app/WorkSpaceActivity | Facade-backed helpers from the older lead-management (LM) and project modules |
app/Logging | Custom log channel factory and the per-workspace import log writer |
app/storage | A stray storage-style folder (not Laravel's storage/) |
Models are documented separately on the models page.
app/Services ​
BigQueryLog ​
Namespace App\Services\BigQueryLog. Logs are written to local NDJSON spool files with no network call on the request path, then shipped in batches by the bigquery:ship command. Everything is gated by config('bigquerylog.enabled').
| Class | Role |
|---|---|
Spooler | write($table, $row) appends one JSON line to {spool_path}/{table}.ndjson with LOCK_EX. Never throws (a failure is logged as a warning). sanitize($data) masks keys listed in bigquerylog.sensitive_keys with ***, replaces UploadedFile values with {_file, size, mime}, and returns {_truncated: true, _size_bytes} when the JSON is larger than max_request_data. Also truncate() and timestamp() (UTC, microseconds, Z). |
JobLogger | register() adds a Queue::createPayloadUsing hook that stamps bq.request_id and bq.dispatched_at into every job payload, then listens to JobProcessing, JobProcessed, JobFailed, JobExceptionOccurred. Writes one job_logs row per run: job_id, request_id, job_class, queue, payload.models (up to 5 model identifiers pulled from the serialized command by regex, no DB queries), workspace_id, related_type, related_id, dispatched_at, started_at, finished_at, wait_ms, duration_ms, attempt, status (success, released, failed), error, created_at. |
CronLogger | register() listens to ScheduledTaskStarting, ScheduledTaskFinished, ScheduledTaskSkipped, ScheduledTaskFailed. Writes cron_runs rows: run_id, command, arguments, started_at, finished_at, duration_ms, status (success, failed, skipped), exit_code, output (failures only, 4096 bytes max), created_at. Skips bigquery:ship itself. |
WebhookLogger | incoming($source, $payload, $status, $body, $context) writes a webhook_calls row. Called from WebhookController with source file_preview. |
Related code outside the folder:
| Piece | File | Notes |
|---|---|---|
| Provider | app/Providers/BigQueryLogServiceProvider.php | Calls JobLogger::register() and CronLogger::register() when enabled. Registered in config/app.php. |
| Request logger | app/Http/Middleware/LogApiRequests.php | First middleware of the api group. Sets bq_request_id, counts DB queries, returns X-Request-Id, and in terminate() writes an api_requests row (request_id, domain, referer, origin, ip, user_agent, method, path, action, workspace_id, workspace_name, user_id, user_name, request_data, response_status, response_body, response_size_bytes, duration_ms, db_query_count, db_time_ms, created_at). |
| SSO events | App\Models\SsoLoginEvent::record() | Writes the DB row and mirrors it to the sso_login_events spool. |
| Shipper | app/Console/Commands/ShipLogsToBigQuery.php (bigquery:ship) | Scheduled everyFiveMinutes()->withoutOverlapping() in app/Console/Kernel.php. |
| Config | config/bigquerylog.php | enabled, project_id, dataset, key_file, spool_path (storage/app/bigquery-spool), max_response_body, max_request_data, excluded_paths (up, health, api/health), sensitive_keys. |
Shipping gaps
ShipLogsToBigQuery::TABLES is api_requests, job_logs, cron_runs, webhook_calls, frontend_events. sso_login_events is spooled but is not in that list, so its .ndjson file is never rotated and never shipped. Nothing in app/ writes frontend_events. LogApiRequests::terminate() skips paths matching excluded_paths (Str::is).
DAM: FolderVisibilityRecalculator ​
App\Services\DAM\FolderVisibilityRecalculator (constructed per workspace) decides the per-portal (instance) visibility of folders. It replaced copies of the same logic in several controllers and is used by CategoryController, DamPermissionController, AssetController, the *ByInstance helpers in Helper.php, and Console/Commands/Import/WorkspaceRestructureRun.php.
Rules from the class docblock: 0 public (everything beneath is public), 2 protected (mixed content, navigable path, only set when the folder is currently 1), 1 private (everything beneath is private or there is nothing beneath). An asset or folder with no dam_instance_permissions row for the instance counts as private.
| Method | Purpose |
|---|---|
refreshTree() | Drop the cached folder tree (call after creating, moving or trashing folders mid-run) |
exists($folderId) | Live folder of this workspace |
ancestorsOf($id, $includeSelf), collectAncestors($ids, $includeSelf) | Ancestor chain, nearest first |
descendantsOf($id), selfAndDescendantsOf($id) | Descendant folder ids from the in-memory tree |
anyPublicAsset, anyPrivateAsset, anyPublicFolder, anyPrivateFolder, hasPublicContent | Indexed EXISTS probes per instance; ids are never pulled into PHP, so there is no 65K-placeholder limit |
recalculate($folderIds, $instanceIds) | Evaluate each (instance, folder) pair once, deepest folder first, write 0/1/2 rows; returns the live folder ids to reindex |
Sso ​
Namespace App\Services\Sso. Per-workspace SAML 2.0 sign-in built on onelogin/php-saml. Called from Api/v1/Auth/SsoAuthController, Api/v1/Workspace/SsoSettingsController, the SyncSsoMetadata job, and VerifyUserWithWorkSpace middleware (entry re-check).
| Class | Role |
|---|---|
SamlService | SP identifiers keyed by workspace url_slug: spEntityId() (saml.sp.entity_id_base + slug), acsUrl() (/api/v1/auth/sso/{slug}/acs), metadataUrl(), redirectUrl(). settingsArray() builds strict onelogin settings (RSA-SHA256, accepts multiple IdP signing certs during rotation). loginUrl() returns the IdP URL with AuthnRequest and RelayState. processResponse() validates the POSTed response and returns name_id, stable_id, email, name, attributes, session_index (email falls back through common claim names). spMetadataXml(), fetchMetadata() (https only outside local; every DNS address of the host must be public, including IPv4-mapped IPv6 and carrier-grade NAT, IPv6 unique-local and link-local ranges; redirects are followed by hand and each request is pinned to the checked address so DNS cannot change between check and fetch; size and timeout limits), parseMetadata(), certificateExpiry(), recheckSignature() (HMAC of slug and user id with the app key). |
SsoLoginService | handleAssertion() runs the sign-in rules (diagram below), writes every outcome to sso_login_events, and issues a Passport personal access token named SSO Token with a saml.token_ttl_days lifetime. Emails the workspace owner (SendSsoSeatBlockedEmail, at most once per person per day) when seats are full. |
SsoEntryCheck | response($userId, $workspaceId, $urlSlug, $request): the periodic company re-check run in VerifyUserWithWorkSpace. Returns null to continue, a 428 JSON with data.sso_recheck = required and a signed redirect_url, or a 403 with data.sso_recheck = failed during the hold after a failed re-check. Any error lets the request through. |
ReturnTarget | Picks and validates the return origin (explicit candidate, then Origin/Referer, then FRONTEND_URL) against FRONTEND_URL, the workspace's verified custom domain and saml.extra_return_origins. safePath() accepts relative paths only. encodeRelayState() / decodeRelayState() HMAC-sign the RelayState. |
DomainVerifier | check(WorkspaceSsoDomain) reads every TXT record at txtName() and then at the bare domain (dns_get_record, quotes and whitespace stripped) and compares with txtValue() using hash_equals; returns ['ok' => bool, 'error' => ?string]. isPublicEmailDomain() checks saml.domain_verification.public_email_domains. See SSO domain verification. |
SsoException | Failure that is not the user's fault; carries a machine reason() |
SsoBlockedException | Valid response but Collage refuses sign-in (domain_not_allowed now also covers an existing account that is not in the workspace). Reasons: domain_not_allowed, seats_full, deactivated, suspended, recheck_failed, recheck_mismatch, signin_failed |
Routes (from routes/api.php): POST auth/sso/resolve, GET auth/sso/{url_slug}/redirect, POST auth/sso/{url_slug}/acs, GET auth/sso/{url_slug}/metadata, plus owner-only settings under sso with checkWorkspaceOwner and checkSsoAllowed.
SSO login flow ​
redirect and acs only need the connection to be synced (isReady()) and workspaces.sso_enabled on; enabled on the connection controls visibility in resolve. A re-check redirect (recheck=1) must carry a valid uid and sig.
handleAssertion rules ​
Other blocks inside these steps: a re-check that resolves to a different user (recheck_mismatch), seats full (seats_full, owner emailed), inactive or unverified user, or a deactivated workspace_users row (deactivated). ensureDefaultRole throws SsoException when the workspace has no DAM roles or the chosen role is admin / super-admin.
Config config/saml.php: sp.entity_id_base, sp.x509cert_path, sp.private_key_path, sp.sign_authn_requests, recheck_days, recheck_failure_hold_minutes, token_ttl_days, stale_days, metadata_timeout, metadata_max_bytes, extra_return_origins, name_attributes, given_name_attributes, surname_attributes.
Signed tokens and input hardening ​
Added in PR #453. Each signed token is an HMAC-SHA256 keyed with the app key (config('app.key')), compared with hash_equals. All of them replaced values that anyone could compute (md5(user id), base64(asset id)) or trust the client sent.
| Class | Format and lifetime | Issued by | Read by | Stops working when |
|---|---|---|---|---|
PasswordSetupToken | <user id>.<expires>.<64 hex>, 7 days; HMAC covers password-setup|<user id>|<expires>|<password hash> | Super-admin and subscription flows that email /password-setup?token= or /subscription/generate-password?token= | AuthController@generateCommonPassword | Expired, or the user's password hash changed (single use) |
EmailVerificationToken | <user id>.<expires>.<64 hex>, TTL_MINUTES = 60; HMAC covers email, password hash and is_verified | AuthController@register | AuthController@verifyEmail | Expired, account verified, or registered again. Neither method has a route since register was removed from routes/api.php. |
PortalLoginTicket | <user id>.<portal id>.<expires>.<64 hex>, 12 hours | DamInstance::getLoginUrlAttribute() (login_url) | DAM AuthController@loginById | Expired, or used on another portal |
SingleShareLink | base64("<asset id>.<portal id or empty>.<32 hex>"), no expiry | forApp() in Admin share and External API asset payloads, forPortal() (binds the request's dam_instance_id) in portal dashboard, folder and asset payloads | parse() in both ShareAssetsController@showShareAssets | Never expires; a portal link only opens in its own portal and the asset must still be visible there |
UploadedObjectUrl::forWorkspace($workspaceSlug, $fileName) returns a 1-day presigned S3 URL for <slug>/digital_assets/<file_name>, or null when file_name is not a plain file name (isPlainFileName(): 1-255 characters, no /, \, .. or control characters). The upload flows (AssetController upload and version upload, ExternalUserController external upload) now fetch the original from that URL instead of the display_file URL the browser sent (SSRF and local file read); a bad name returns 422 Invalid file name.
RichTextSanitizer cleans announcement bodies with HTMLPurifier before they are stored. Allowed tags: p, br, strong, em, u, b, i, span, div, h1-h6, ul, ol, li, blockquote, a[href|title|target|rel], img[src|alt|width|height]. No CSS properties; URL schemes http, https, mailto, tel; link target _blank only, with noopener and noreferrer added. clean() turns null or non-strings into ''; isBlank() is true when the cleaned HTML has no image and no visible text (entities and decoded). AnnouncementController create and update return a validation error Description cannot be empty. when the cleaned body is blank.
WorkspaceMailService ​
App\Services\WorkspaceMailService swaps the SMTP mailer to a white-label workspace's own server.
| Method | Behaviour |
|---|---|
applyForWorkspace(Workspace) | Only when white_label_enabled and the workspace mailSetting has mail_host and mail_from_address. Snapshots the env defaults once, sets mail.mailers.smtp.* and mail.from.*, purges the mailer. Returns true when applied. |
applyForWorkspaceId(int) | Loads the workspace with mailSetting and calls the above |
restoreDefaults() | Puts the snapshotted env values back and purges the mailer |
scoped(?int $workspaceId, Closure) | Sets WorkspaceMailContext, applies the workspace SMTP, runs the callback, then clears the context and restores defaults in finally |
Used by many mail jobs under app/Jobs/DAM (invitations, activation, daily and Tuesday/Thursday mails, announcements, feedback, storage analytics, and others) and by SsoLoginService. The MessageSending listener ApplyWorkspaceMailToMessage reads WorkspaceMailContext; for a white-label workspace without SMTP details it logs a warning and cancels the send (returns false).
app/Support ​
| Class | Methods | Purpose |
|---|---|---|
CustomFieldValue | isMulti, settings, decodeArray, values, encode, fromRequest, toResponse | Storage format for custom field values. Dropdown data (option lists, multi-select and single-select values) is stored as JSON arrays; text values are plain strings. Legacy comma-separated rows must be converted with php artisan custom-fields:migrate-to-json. values() feeds search indexing and facets. |
RequestEnvironment (final) | isAgent, agentClient, notAgent | Tells agent (Collage MCP) requests apart from human ones so analytics can leave them out. Constants AGENT = 'agent' and CLIENT_HEADER = 'X-Collage-Client'. See Agent (MCP) requests in analytics. |
TimezoneName | canonical($tz) | Maps 148 legacy IANA aliases (from the backward file, for example Asia/Calcutta to Asia/Kolkata) to current names and returns null for anything not in timezone_identifiers_list() (empty, non-string, truncated values such as America/Indiana). Browsers still send legacy names and Ubuntu 24.04 PHP cannot load them without tzdata-legacy. Used by ConvertDatesToViewerTimezone, ResolvesViewerTimezone and date formatting in DamInstanceController, FeedbackController and the super-admin UserController, which fall back to UTC. |
WorkspaceBrand (final) | isWhiteLabel, name, supportEmail, frontendUrl | Brand values for user-facing text. Defaults are Collage and the Collage support address; under white label the workspace name and support_email are used. frontendUrl() returns https://{workspace url} when domain_status is verified, else constant.FRONTEND_URL. |
WorkspaceMailContext | setForWorkspace, setForWorkspaceId, currentWorkspaceId, currentWorkspace, clear | Static holder of the workspace whose mail is being sent. Read by mail classes (SendExistingUserInvitation, SendUserRegistrationEmail, SendSsoSeatBlockedEmail, DAM/Welcome, and others) and by ApplyWorkspaceMailToMessage. |
Agent (MCP) requests in analytics ​
Added in 8d907a3. The Collage MCP server calls the same Admin API endpoints as the admin app with a user's token, so before this change every asset it read was logged as a human view and inflated customer dashboards and monthly reports. App\Support\RequestEnvironment marks such requests, the activity is written to transaction_activities under a new environment value agent (next to admin, dealer, external and anonymous), and the analytics readers leave agent rows out.
How a request is recognised. agentClient(Request) returns the client marker, or null for a normal request. Rules, in order:
| Order | Source | Matches when | Returned value |
|---|---|---|---|
| 1 | X-Collage-Client header, trimmed | it starts with mcp/ | the header value, cut to 64 characters (CLIENT_MAX_LENGTH) |
| 2 | User-Agent, trimmed | it starts with collage-mcp/ (older MCP versions send only this) | the User-Agent, cut to 64 characters |
| 3 | - | neither | null (not an agent) |
isAgent(Request) is agentClient(...) !== null. The header wins over the User-Agent when both are present. Matching is a case-sensitive prefix test: MCP/1.0, x-mcp/1.0 or a browser User-Agent are not agents (see tests/Unit/RequestEnvironmentTest.php).
text
X-Collage-Client: mcp/<version> -> agent, system_data {"client":"mcp/<version>"}
User-Agent: collage-mcp/<version> -> agent (fallback)
User-Agent: Mozilla/5.0 ... -> not an agentN1 yes and N2 yes both lead to the agent branch; N2 no leads to normal logging.
Writing. TransactionActivity::recordAgentEvent($request, $workspaceId, $event, $subEvent, $ids) creates one transaction_activities row with environment = 'agent', user_id = the token's user (the agent acts as that user), system_data = {"client": "<marker>"}, ipv4 = the request IP and transaction_number = the current highest + 1. $ids carries the subject columns (asset_id, version_id, collection_id, category_id, share_id, instance_id). No geo lookup is done, because a hosted agent's IP is the MCP server's, not a person's, so city, state, country_code, postal and country_name stay empty.
Where it is used (8d907a3).
| Place | Human request | Agent request |
|---|---|---|
POST /api/v1/digital-assets/view-detail (AssetController@viewDetails) | digital_assets_downloads row, type = view, download_by (default desktop), location and IP | No digital_assets_downloads row. recordAgentEvent(..., 'asset', 'viewed', ['asset_id', 'version_id']) instead, so the view never reaches view counts |
Readers that leave agent rows out. RequestEnvironment::notAgent($column = 'environment') returns a where-closure, used as ->where(RequestEnvironment::notAgent()). It keeps environment IS NULL OR environment <> 'agent': the column is nullable and <> 'agent' alone would also drop the NULL rows.
| Reader | Filter |
|---|---|
NewDashboardController@weeklyInsightsDownloadedData (POST /api/v1/digital-assets/new-dashboard/weekly-insights, downloaded series) | notAgent() |
ShareAssetsController@getShareAssetsListNew (GET /api/v1/digital-assets/dashboard/list-share-assets-url), last_30_days_visited subquery over shared / viewed rows | the same condition written into the raw SQL |
php artisan send:monthly-workspace-reports, assets_data (per-asset viewed, downloaded, shared counts over event = 'asset' rows) | notAgent('transaction_activities.environment') |
php artisan send:monthly-workspace-reports, date_data (activity by date) and user_data (per user) | Not filtered: agent rows stay in, with environment agent, and users is joined for environment IN ('admin', 'agent') so their user name resolves like an admin's |
Edge cases:
- Views shown on the dashboard and the asset analytics summary come from
digital_assets_downloads, which agent reads no longer write, so they need no filter. - Other readers of
transaction_activitiesare not filtered yet. They only seeagentrows if a future endpoint callsrecordAgentEvent()for that event. - The header is set by the caller and is not checked against the token, so any client that sends
X-Collage-Client: mcp/...is logged as an agent and its asset views are left out of view counts.
Helper functions ​
composer.json autoloads one file: app/Helpers/Helper.php (661 lines). Every function is wrapped in function_exists.
| Function | Purpose |
|---|---|
getWorkspaceIdsByDomain(Request) | Workspace ids for a request coming from a verified custom domain; empty when the domain is FRONTEND_URL |
getOriginUrl($request) | Origin in priority order: Origin/Referer header, origin_url param, url param, FRONTEND_URL |
getUserName($id) | User name, or email when name is null |
getModuleWithWorkspace($workspaceId, $moduleId) | Active module_workspaces row |
sortMultiDimensionArrayByKey(&$arr, $col, $dir) | In-place sort by column |
imageTagSuggest($imageData) | Google Vision label detection through the Vision facade (yedincisenol/vision) |
googleImageVision($imageData) | Google Vision REST images:annotate (faces, objects, labels, image properties). Returns nulls when constant.AUTO_TAG is off. Used by AssetController and the AssignVisionTagToAsset command. |
formatSizeUnits($bytes), formatBytes($size, $precision) | Human-readable sizes |
updateDealerLastActivity($id) | Sets dealer_users.last_activity (and last_login if empty) |
updateDealerUsersActivity(...), updateSubscriptionUsersActivity(...) | Insert DealerUsersActivity / SubscriptionUserActivity rows |
getDealershipName($id), getTaskStatusName($id) | LM lookups |
updateLeadAddressDetails($leadId, $zip), updateDealershipAddressDetails($id, $zip) | LM address fill through ZipCode::findAddressFromZipRadar |
getAllNestedFolders, getAllParentFolders | Folder tree walks |
checkPublic/PrivateFolder/AssetAvailability, checkPublic/PrivateAvailability | Workspace-level visibility checks on visibility columns |
check*AvailabilityByInstance (5 functions) | Per-portal checks delegated to FolderVisibilityRecalculator |
forgetDamDashboardCache($workspaceId) | Forgets dam:dashboard:common:{workspace}:{instance} for every portal. Must be called after any change to which assets a portal can see. |
Traits ​
| Trait | File | Used by | Purpose |
|---|---|---|---|
HasPermissionTrait | app/Permissions/HasPermissionTrait.php | App\Models\User | Workspace-scoped role and permission helpers: roles, permissions, syncRole, attachRole, detachRole, getRole, getRoleData, getRoleId, hasRole, syncPermissions, attachPermissions, getPermissions, hasPermissions, and related |
WithBoldHeaderRow | app/Exports/Concerns/WithBoldHeaderRow.php | Monthly workspace report sheets | AfterSheet event: bold row 1, left-align the used range |
ResolvesViewerTimezone | app/Traits/ResolvesViewerTimezone.php | NewDashboard/NewDashboardController, DigitalAssets/AssetController, DigitalAssets/ShareAssetsController, DigitalAssets/DamCollectionController, App\Http\Middleware\ConvertDatesToViewerTimezone | Viewer timezone for analytics buckets, share-link expiry and share-page dates. See Viewer timezone below |
ResumeHoldLMInvitationEmail | app/Traits/ResumeHoldLMInvitationEmail.php | EmailControl/EmailManageController | holdInvite() stores an LM email in HoldResumeLmInvitation; sendInvite() sends it by email_class (dealership invitation and verification, new lead, lead assignment, and others) to the user or to a hard-coded internal review address |
Viewer timezone for analytics ​
Added in c3c5f54 and d17bb30, extended in 44b17a4 for visitors without a profile. The analytics endpoints receive calendar dates (from_date, to_date) that the admin app computes in the user's profile timezone, but every created_at in the database is a naive string in config('app.timezone') (APP_TIMEZONE, default Asia/Kolkata). Comparing the two directly put a US user's afternoon activity on the next day. The trait converts each viewer-local day into app-timezone timestamps before the query runs, and expresses stored timestamps in the viewer's zone for share-link responses.
The trait defines public const VIEWER_TIMEZONE_HEADER = 'X-Timezone', the header both frontends send on every browser request.
| Method | Input | Output |
|---|---|---|
resolveViewerTimezone(Request $request, string $fallback = 'UTC') | The request and a fallback zone | First valid value, in this order: (1) $request->user()->timezone (users.timezone, column default UTC); (2) the X-Timezone header, reached only when there is no profile timezone (share-link visitors, public-portal guests, external uploaders, partner users, since dealer_users has no timezone column); (3) $fallback. Each candidate goes through TimezoneName::canonical(), so a legacy alias such as Asia/Calcutta resolves to Asia/Kolkata instead of being treated as missing. Request parameters are ignored, and the header never overrides a profile, so a chart cannot disagree with the rest of the admin UI. Analytics calls use the default UTC fallback; share-link expiry writers pass config('app.timezone') so a client that sends neither keeps the old meaning. |
toViewerIso($value, string $viewerTz) | A stored timestamp (string or DateTimeInterface) | ISO 8601 with offset (DATE_ATOM), for example 2026-11-04T14:00:00-07:00. Naive Y-m-d H:i:s strings (uncast columns such as modified_at) are parsed in config('app.timezone'); Carbon instances and zoned strings keep their own zone. null or '' in, or an unparsable value, returns null. |
localDateRangesToAppTimezone(array $splitDate, string $viewerTz) | splitDate() buckets [['Y-m-d', 'Y-m-d'], ...] | [['Y-m-d H:i:s', 'Y-m-d H:i:s'], ...] re-indexed 0..n-1 in input order. Start is 00:00:00 and end 23:59:59 in the viewer zone, each converted to the app zone on its own, so a daylight-saving change inside the window is handled. |
buildDateRangeCaseWhen(array $dateRanges, string $column) | Converted ranges and a column name | WHEN {column} >= 'start' AND {column} <= 'end' THEN {i} ... for a CASE expression. The boundaries are Carbon-formatted, so they are inlined into SQL. |
Example: a user whose profile timezone is America/New_York asks for 2026-11-04. With the default app timezone the bucket becomes 2026-11-04 10:30:00 to 2026-11-05 10:29:59 (EST is UTC-5, IST UTC+5:30). Chart labels stay the viewer's own dates because the splitDate() keys are reused.
| Endpoint | Controller method | Column bucketed |
|---|---|---|
POST /api/v1/digital-assets/new-dashboard/weekly-insights | NewDashboardController@getWeeklyInsights (via weeklyInsightsUploadData, weeklyInsightsviewedData, weeklyInsightsSharedData, weeklyInsightsDownloadedData) | digital_assets.created_at, digital_assets_downloads.created_at, share_assets_category.created_at, transaction_activities.created_at |
POST /api/v1/digital-assets/analytics/summary | AssetController@assetSummary (bar_data only) | digital_assets_downloads.created_at (was DATE(created_at) before, which also stopped the index from being used) |
The totals (total_download, total_view, total_share) in the asset summary are not date-bound and do not change.
Share links use the same trait (44b17a4, ceee95e):
| Where | Timezone used | What it does |
|---|---|---|
ShareAssetsController@generateShareAssetsURL, @updateShareUrl, DamCollectionController@generateShareUrl | resolveViewerTimezone($request, config('app.timezone')) | Turns the picked expiration date into expires_at and expires_timezone with ShareAssetsCategory::expiryColumns() (on update only when the date changed). See Sharing: expiry. |
ShareAssetsController@showShareAssets, @getSharedCategoryAndFiles | resolveViewerTimezone($request) (header, else UTC) | Rewrites modified_at on the returned assets, folders and breadcrumb with toViewerIso() and adds viewer_timezone to the response. created_at and updated_at already serialise as UTC ISO, so only the uncast modified_at is converted. |
ConvertDatesToViewerTimezone middleware (dam.viewer-timezone) | X-Timezone header only | Converts every date-looking value in Portal API JSON responses. See Middleware. |
Other app/ folders ​
All of these are bound in a service provider and aliased in config/app.php.
| Folder | Class / facade alias | Provider | What it does |
|---|---|---|---|
app/RestResource | RestResponse | RestResourceProvider | Static success, error, warning, validationError, sayHello. See Resources and requests. |
app/ZipCode | ZipCode (alias points at App\Zipcode\ZipCodeFacade) | ZipCodeServiceProvider | Geocoding and distance for LM: findLatLonFromZip, findAddressFromZip (OpenStreetMap Nominatim), findAddressFromZipRadar, findDistanceFromLatLongRadar (Radar), findDistanceFromOpenRouteService, findDistanceFromZip, findDistanceFromDB, saveDistance (ZipcodeDistance), sanitize, sanitize2, zipCodeCountry. Called from Helper.php and the lead and dealership imports. |
app/PushNotification | PushNotification | PushNotificationServiceProvider (listed three times in config/app.php) | sendNotification, sendReportNotification, sendLmNotification: send to every DeviceToken.fcm_token of a user via the legacy FCM HTTP endpoint with cURL |
app/ProjectActivity | Activity | ProjectAtivityProvider | insertData($data) writes a ProjectAcivity row (project activity log) |
app/WorkSpaceActivity | WorkSpaceActivity | WorkSpaceActivityProvider | insertData($workspaceId, $userId) seeds three DealershipDesignation rows (Regional Manager, Branch Manager, Salesperson); the old task status, severity and project type seeds are commented out. Called from WorkspaceController. |
app/Logging | CreateWeeklyLog | config/logging.php channel weekly | Monolog factory writing to storage/logs/weekly/{start}-to-{end}.log |
app/Logging | ImportMigrationLogger | none (static) | log($workspaceSlug, ImportData, $status, $assetId, $addedCustomFields) writes a readable per-asset block (status, id, name, folder, tags, custom fields, description) to storage/logs/{url_slug}.log. Used by ProcessAssetImportJob, ImportAssetsDBToPlatform and CustomFieldMigration. |
app/storage | none | none | Copy of a storage layout inside app/: api-docs/api-docs.json, app/public, framework/*, and logs (the oauth-private.key / oauth-public.key files were removed). l5-swagger reads storage_path('api-docs'), which is the root storage/ folder, not this one. Nothing in app/ or config/ references app/storage. |
Keys in source
Since PR #453 the Passport key files are gone from app/storage (and /app/storage/*.key is in .gitignore), Controller::findGoogleDistance reads config('constant.GOOGLE_KEY') with no fallback, and ZipCode::findDistanceFromOpenRouteService reads config('constant.OPENROUTESERVICE_KEY'); both skip the lookup when no key is set. The old key files and API keys are still in the git history, so they should be rotated.
Third-party integrations ​
Only services the code calls are listed. Packages that are installed but not used from app/ are noted at the end.
| Service | Used for | Where in code | Config file | Env names |
|---|---|---|---|---|
| AWS S3 | Asset storage (Storage::disk('s3') in about 50 files), backups disk s3_backup | Asset controllers, jobs, commands, AssetsVersion | config/filesystems.php, config/constant.php, config/backup.php | AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_DEFAULT_REGION, AWS_BUCKET, AWS_URL, AWS_ENDPOINT, AWS_USE_PATH_STYLE_ENDPOINT, AWS_BACKUP_BUCKET, AWS_BACKUP_URL, FILESYSTEM_DRIVER, FILESYSTEM_CLOUD |
| AWS CloudFront | Second bucket served through CloudFront (s3Cloudfront disk) and createInvalidation after a file is replaced | AssetController (around line 2120), AssetsVersion (around line 220), DAM/v1/External/AssetsController, Web/Subscription/UserController | config/filesystems.php, config/constant.php | AWS_BUCKET2, AWS_URL2, AWS_DISTRIBUTION_ID |
| Typesense (Laravel Scout) | Search index for DigitalAssets, DigitalAssetsCategory, DigitalAssetsTag, DamCollection (Searchable) and reindex jobs | Models above, ReindexAssetsByIds, ReindexAssetTagsByAssetIds, DAM controllers, HealthController (search check) | config/scout.php | SCOUT_DRIVER, SCOUT_PREFIX, SCOUT_QUEUE, TYPESENSE_API_KEY, TYPESENSE_HOST, TYPESENSE_PORT, TYPESENSE_PATH, TYPESENSE_PROTOCOL, TYPESENSE_CONNECTION_TIMEOUT_SECONDS, TYPESENSE_NUM_RETRIES, TYPESENSE_RETRY_INTERVAL_SECONDS, TYPESENSE_HEALTHCHECK_INTERVAL_SECONDS, TYPESENSE_CHUNK_SIZE, TYPESENSE_MAX_TOTAL_RESULTS |
| Google BigQuery | Request, job, cron, webhook and SSO logs | app/Services/BigQueryLog, LogApiRequests, ShipLogsToBigQuery | config/bigquerylog.php | BIGQUERY_LOG_ENABLED, BIGQUERY_PROJECT_ID, BIGQUERY_DATASET, BIGQUERY_KEY_FILE, BIGQUERY_LOG_MAX_BODY, BIGQUERY_LOG_MAX_REQUEST_DATA |
| Google Cloud Vision | Auto-tagging (labels, objects, faces, colours) | Helper.php googleImageVision, imageTagSuggest | config/vision.php, config/constant.php | VISION_API_KEY, VISION_CREDENTIALS_PATH, AUTO_TAG |
| FilePreviews.io | Preview generation for uploaded files; results arrive at POST /api/v1/filepreviews/webhook (WebhookController, logged with WebhookLogger). 429 responses are retried. | Jobs/DAM/AssetUpload, file-preview commands under Console/Commands/DAM/Asset | config/constant.php | FILE_PREVIEWS_API_KEY, FILE_PREVIEWS_SECRETE_KEY |
| SAML 2.0 identity providers | Enterprise SSO (any IdP; the code mentions Microsoft Entra metadata) | app/Services/Sso, SsoAuthController, SyncSsoMetadata | config/saml.php | SAML_SP_ENTITY_ID_BASE, SAML_SP_CERT_PATH, SAML_SP_KEY_PATH, SAML_SIGN_REQUESTS, SSO_RECHECK_DAYS, SSO_RECHECK_HOLD_MINUTES, SSO_TOKEN_TTL_DAYS, SSO_STALE_DAYS, SAML_METADATA_TIMEOUT, SAML_EXTRA_RETURN_ORIGINS, FRONTEND_URL |
| Google and Microsoft OAuth (Socialite) | Social login at GET auth/login/{service} and /callback. SocialMiddleware allows google, facebook, microsoft only when config('services.{service}') exists; only google and microsoft are configured. | Auth/SocialAuthController, EventServiceProvider (MicrosoftExtendSocialite) | config/services.php | GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_CLIENT_REDIRECT, MICROSOFT_CLIENT_ID, MICROSOFT_CLIENT_SECRET, MICROSOFT_CLIENT_REDIRECT, MICROSOFT_TENANT_ID |
| WebAuthn / passkeys | Passkey login (passkeys/login/options, passkeys/login) and management; challenges in cache through App\WebAuthn\CacheChallengeRepository | Auth/PasskeyController, AppServiceProvider, User | config/webauthn.php | WEBAUTHN_ID, WEBAUTHN_NAME, WEBAUTHN_ORIGINS |
| Laravel Passport | OAuth2 access tokens for all API guards | Auth controllers, SsoLoginService::issueToken | config/passport.php | PASSPORT_PRIVATE_KEY, PASSPORT_PUBLIC_KEY, PASSPORT_PERSONAL_ACCESS_CLIENT_ID, PASSPORT_PERSONAL_ACCESS_CLIENT_SECRET, PASSPORT_CONNECTION |
| Pusher (broadcasting) | Private channels: user.{id}, user.{id}.DAMFrontendAnnouncementNotification, user.{id}.getUserSubscriptionChannel, user.{id}.projectBatchNotification, logoutDealershipUser.{id} and others | app/Events/* | config/broadcasting.php | BROADCAST_DRIVER, PUSHER_APP_ID, PUSHER_APP_KEY, PUSHER_APP_SECRET, PUSHER_APP_CLUSTER, PUSHER_TLS |
| Stripe | Subscriptions, invoices, payment methods (new \Stripe\StripeClient(config('dam.STRIPE_SECRET'))) | Api/v1/DigitalAssets/SubscriptionController, Web/Subscription/*, WorkspaceController, subscription commands (TrialExpire, SuspendAccount, and others), DAMRemoveWorkspaceData | config/dam.php | STRIPE_KEY, STRIPE_SECRET |
| SMTP | Default mailer, plus per-workspace SMTP for white label (WorkspaceMailService) | app/Mail, mail jobs | config/mail.php | MAIL_MAILER, MAIL_HOST, MAIL_PORT, MAIL_USERNAME, MAIL_PASSWORD, MAIL_ENCRYPTION, MAIL_FROM_ADDRESS, MAIL_FROM_NAME |
| Firebase Cloud Messaging | Mobile push (legacy fcm.googleapis.com/fcm/send) | app/PushNotification/PushNotification.php | read with env() directly | FCM_SERVER_KEY (DAM_FCM_SERVER_KEY exists in config/constant.php) |
| Heroku Platform API | Custom domain checks (apps/{app}/domains/{domain}) | CheckIsDomainPointed, DamCheckCustomDomainExistOrNot | config/constant.php | HEROKU_API_KEY, DAM_APP_NAME |
| ZIP worker | External worker service; HealthController pings its URL as the worker health check (other callers not traced in this pass) | HealthController | config/services.php (zip_worker.url) | ZIP_WORKER_URL |
| ffmpeg (CLI) | Video GIF / MP4 previews and frame grabs (DigitalAssets::generateFileFromVideo) | Models/DAM/DigitalAssets.php, GenerateVideoPreviewJob | config/video-thumbnail.php | FFMPEG, FFPROBE |
Imagick and heif-convert (CLI) | HEIC to JPEG and other renditions | RegenerateAssetRenditionsJob, AssetUpload, CheckMissingRenditions, thumbnail commands | none | none |
| Intervention Image | Resizing and compression in asset, banner, tile and portal controllers and thumbnail commands | See left | config/image.php | IMAGE_DRIVER |
IP geolocation (stevebauman/location, IpApi driver) | Location of the user's IP at login | Models/User.php, Support/AuthController, TransactionActivityController | config/location.php | IP_API_TOKEN and other driver tokens (IPINFO_TOKEN, IPDATA_TOKEN, MAXMIND_*, KLOUDEND_TOKEN, IP2LOCATIONIO_TOKEN) |
| Radar, OpenStreetMap Nominatim, OpenRouteService, Google Distance Matrix | LM zip-code geocoding and distances | app/ZipCode/ZipCode.php, Controller::findGoogleDistance, Helper.php, LM imports | config/app.php (RADAR_AUTH_KEY) | RADAR_AUTH_KEY, GOOGLE_KEY |
| Slack | Slash command dam-db-backup hitting POST dam-db-backup/db-backup-run in routes/web.php; backup notifications | routes/web.php, config/backup.php | config/services.php, config/backup.php | SLACK_WEBHOOK_URL, SLACK_CHANNEL, SLACK_USERNAME, SLACK_ICON |
| New Relic | newrelic_notice_error() in RestResponse::error when the extension is loaded and env is production | app/RestResource/RestResponse.php | none | none |
| Laravel Telescope | Optional; prune is scheduled only when the class exists | app/Console/Kernel.php | config/telescope.php | TELESCOPE_ENABLED and TELESCOPE_* watchers |
Stored but not called by the backend: Dropbox and Google Drive. DashboardController returns dropbox_token, gdrive_access_token and gdrive_refresh_token from the workspace, and ProcessAssetImportJob handles Dropbox MIME types for imported files, but no Dropbox or Drive API call was found in app/ (spatie/dropbox-api is installed but not referenced). Asana is only asana_id columns on User and Workspace. Mautic is CRUD for stored accounts and forms in Web/MauticController with no HTTP calls to Mautic. "OpenAI" appears only as an openai_image_count token counter in subscriptions. Mux is mentioned in a WebhookLogger comment only. webklex/laravel-imap is configured (IMAP_*) but not referenced in app/.