Media: uploads, images and private files

The core plugin media gives every module one way to keep files of users and admins: _class('media') checks an upload against its context, re-encodes an image into a clean master (no EXIF, GPS, profiles or comments, the camera rotation applied, long side 4096 px) and the styles of the context (thumb, medium, ...), keeps private files outside the web root and shows them through short-lived signed links. Video and audio become a clean MP4 / M4A with a poster (when ffmpeg is installed), large images and virus scans can run as background jobs. Nothing changes on a site until code calls it. Cloud buckets, direct and chunked uploads, quotas and the admin media library come in later releases.

Contexts and styles

A context says what a file may be and who sees it. A plugin declares its contexts and styles in its plugin.json; the names start with the plugin's name (at most 64 characters; a longer or malformed name from the site config or the filter is left out and named by the doctor check media.contexts):

"provides": {
    "media": {
        "contexts": {
            "social.post": {"title": "Post photos", "kinds": ["image"], "visibility": "private", "styles": ["thumb", "social.large"],
                            "max_mb": 10, "max_pixels": 40000000, "can_view": "filter"},
            "social.cover": {"visibility": "public", "styles": ["medium"]}
        },
        "styles": {
            "social.large": {"width": 2048, "height": 2048, "fit": "contain", "format": "webp", "quality": 82}
        }
    }
}
Context fieldDefaultMeaning
kinds["image"]image (re-encoded, styles), file (kept as it is, always a download), video and audio (a clean MP4 / M4A made by a job; only while ffmpeg and ffprobe are installed, refused otherwise: video and audio)
visibilityprivatepublic: the styles go under the web root and are served by the web server; the master and files stay private
stylesmedia.DEFAULT_STYLESstyles written for each image
extensionsby kinda narrower list; SVG, HTML, XML, scripts are never stored, the checks of form2_file_handler::check_file() still apply
max_mb, max_pixels10, 40000000size before reading, width x height before decoding (never above media.MAX_PIXELS)
max_secondsmedia.AV_MAX_SECONDS (600)longest video or audio (never above AV_MAX_SECONDS)
can_viewfilter (private), public (public)besides the owner and admins: filter asks the filter media.can_view (default no), owner nobody else, public anyone; a public context is always public (its styles are public files)
guestfalsetrue: guests may store files in it
storagemedia.STORAGE (local)site contexts only ($PROJECT_CONF['media']['CONTEXTS']): the storage driver of new files; a plugin.json context with storage is left out
title, daily_mba label; the quota of a later release
scanoffrequired: every upload is quarantined until clamd scanned it (virus scan); without media.CLAMD_SOCKET such a context refuses every file ("virus scan not available")

Core styles: thumb 320, medium 1080, large 2048 (fit inside, WebP), avatar 256 square (cover). A style has width, height (0 = any), fit (contain or cover), format (webp, jpeg, png, auto = as the source), quality, upscale and jpeg_fallback (also a JPEG twin <style>-jpeg). Without WebP support styles are written as JPEG. A site changes or adds contexts and styles in its config (merged, the site wins, false removes one):

$PROJECT_CONF['media']['CONTEXTS']['social.post']['max_mb'] = 5;
$PROJECT_CONF['media']['CONTEXTS']['site.docs'] = ['kinds' => ['file'], 'can_view' => 'owner'];
$PROJECT_CONF['media']['STYLES']['thumb'] = ['width' => 400, 'height' => 400];

An entry of a plugin.json that is not valid (another plugin's name, an unknown field, can_view: public on a private context, owner or filter on a public one) is left out and shown by the doctor (check plugins.manifests).

API

// a POST of your module, after the CSRF check
$r = _class('media')->store_upload($_FILES['photo'], 'social.post');   // ['ok', 'id', 'error', 'row']
if ($r['ok']) {
    _class('media')->attach($r['id'], 'social_post:' . $post_id);
}
$src = _class('media')->url($id, 'thumb');      // public style: its URL; private: a signed link for this viewer
MethodWhat it does
store_upload(array $file, $context, $opts = [])stores one $_FILES entry (only an upload of this request); $opts: owner_type / owner_id (default the admin in the admin section, else the user, else system in the console), ref, styles (a subset), async (an image's master and styles from a job). The answer's row.status is ready, or processing / quarantined while a job works on it (wait for media.ready)
store_path($path, $original_name, $context, $opts = [])the same for a file already on the server (imports, jobs); the file is copied
attach($id, $ref), detach($id)links a media to its object (<object>:<id>)
get($id), variant_path($row, $variant)the row (variants decoded), the path of a stored file ('' the master)
url($media, $variant = '', $opts = [])the URL; $opts: viewer_id (a user id) or viewer, ttl
can_view($row, $viewer = null)whether a viewer may see it (owner, admins, the context's can_view)
remove($id, $reason = '', $by = 0)takes it down: status removed, files kept for admins, public styles no longer served
delete($id), erase_user($user_id)deletes the files and the row now; every media of a user (privacy erase)
contexts(), styles()the merged lists
kinds_stored(), kind_of($ext)kinds this server stores (video and audio only with ffmpeg); the kind of an extension
jobs(), av(), clamd()the job runner _class('media_jobs') (enqueue($media_id, $kind, $args = [], $delay = 0), run_due($limit, $max_seconds), stats()), the ffmpeg / ffprobe runner and the clamd client with this config

Errors are short English texts (file is too big, file type not allowed, image has too many pixels, login required, ...); translate them with t() where you show them. There is no upload endpoint of its own: the module that takes the upload checks POST and the CSRF token first.

Events and filters

  • media.stored {media_id, context, owner_type, owner_id, kind, status, source: media}, then media.ready when the styles are written; media.failed {media_id, context, error}; media.removed {media_id, context, reason, by}; media.erased {user_id, count}; media.infected {media_id, context, owner_type, owner_id, signature} (clamd found something; the media stays quarantined). For a deferred image, a video or an audio file media.stored has status processing (quarantined in a scanned context) and media.ready or media.failed comes from the job.
  • Filter media.can_view ($allowed = false, $row, $viewer_user_id): the owning plugin answers for its contexts with can_view: filter. Filter media.before_store ($verdict = ['ok' => true, 'error' => ''], $info): return ok false to refuse a file (banned hash, moderation). Filter media.contexts: contexts added at run time.

Video and audio

A context with "kinds": ["video"] (or audio) takes mp4, m4v, mov, webm, mkv (audio: mp3, m4a, aac, ogg, wav, flac) while ffmpeg and ffprobe are installed. The upload is checked (name, size, sniffed type), kept privately as status processing and a job of the worker makes the master: ffprobe reads the streams (the type must be the one the extension names; longer than max_seconds or more pixels than max_pixels fails), H.264 video (yuv420p, at most AV_MAX_SIDE) and AAC audio are copied into an MP4, anything else is transcoded (libx264, AV_PRESET, AV_CRF, scaled to AV_MAX_SIDE; AAC AV_AUDIO_KBPS); metadata, chapters, subtitles and data streams are dropped. A video gets a poster (one frame at 1 s, through the image pipeline) and the context's styles of it. Then ready and media.ready; on an error failed and media.failed (video is too long, invalid video, video could not be processed, ...). Audio becomes an M4A (AAC). The gate serves both with Range (seeking) and inline: video/mp4, audio/mp4. Video and audio need a running worker (media:worker from cron or a supervisor): without one, uploads stay processing and are never shown.

$r = _class('media')->store_upload($_FILES['clip'], 'social.clip');   // row.status processing
// later, in a media.ready listener or on the next page view
$video = _class('media')->url($id);              // signed link of the MP4
$poster = _class('media')->url($id, 'poster');   // or a style of the poster: 'thumb'

Settings

$PROJECT_CONF['media'][...]: IMAGE_LIBRARY (auto: Imagick when loaded, else GD; imagick, gd), CONTEXTS, STYLES, DEFAULT_STYLES, MASTER_MAX (4096), MASTER_QUALITY (90), MAX_PIXELS (40000000), MAX_MB (10), IMAGE_EXTENSIONS, FILE_EXTENSIONS, LINK_TTL (900 s; a link lives 1 to 2 periods and is the same URL within one, so browsers cache it), PRIVATE_DIR, PUBLIC_DIR, PUBLIC_URL, SECRET; ASYNC_PIXELS (0: images always at once; an image of at least so many pixels gets its master and styles from a job), VIDEO_EXTENSIONS, AUDIO_EXTENSIONS, FFMPEG, FFPROBE ('' looks in /usr/bin, /usr/local/bin, ...), AV_TIMEOUT (600 s), AV_MAX_SECONDS (600), AV_MAX_SIDE (1920), AV_PRESET (veryfast), AV_CRF (23), AV_AUDIO_KBPS (128), AV_THREADS (2), AV_NICE (10), AV_MAX_MEMORY_MB (2048), CLAMD_SOCKET (''), CLAMD_TIMEOUT (30 s), CLAMD_MAX_MB (25); STORAGE (local), STORAGE_DRIVERS, SENDFILE (''), SENDFILE_ACCEL_MAP (storage drivers). The jobs: $PROJECT_CONF['media_jobs'][...] (below).

Privacy

The privacy provider media (privacy data) exports the list of a user's media and their masters and erases them (both modes delete: a photo or a document of a person is personal as a whole).