* feat: name what an ONVIF camera detected in the event note refs #7688
The ONVIF event note was the raw topic plus the value of the first Data
SimpleItem, e.g. "tns1:RuleEngine/MyRuleDetector/PeopleDetect/true".
parse_event_message() dropped every other item, the item names and the
Source Rule, so cameras that name the detection in an item (Tapo
IsPeople=true under a generic TPSmartEvent topic) or in a value (Ajax
ClassTypes="Human Vehicle") produced notes that did not say what was
detected.
parse_event_message() now also returns every Data SimpleItem and the
Source Rule, and ONVIFEventNote() builds the note from them with rules
that hold across vendors rather than a per-camera list:
- strip the namespace prefix of every topic segment (tns1:, tnsajax:)
- drop a leading RuleEngine/, the root of every analytics topic
- leave out items that are empty or inactive, by the same words
interpret_alarm_value() uses for the alarm state, and per-object ids,
which would otherwise add a note per object as notes only accumulate
- leave out the value of items that say active, and State/LogicalState
items that say active
- add the Rule in parentheses when the camera names one
Reolink MyRuleDetector/PeopleDetect
Tapo TPSmartEventDetector/TPSmartEvent IsPeople (MyTPSmartEventDetectorRule)
Ajax ObjectDetection/Object ClassTypes=Human Vehicle (AjaxObjectRule)
The word lists that drive this sit together, so a camera with other
vocabulary is handled by extending them. The inactive words move from
interpret_alarm_value() into that shared list unchanged. A value found
outside the Data SimpleItems (ElementItem, fallback search) still goes in
the note, and a topic that reduces to nothing is used as it is.
Alarm on/off decisions, the value they use, ONVIF_Alarm_Text matching and
the alarms map keys are unchanged; a test pins interpret_alarm_value() to
its previous results. parse_event_message() and interpret_alarm_value()
are now static, as they use no member state, so they can be tested.
Notes change format: filters matching the old text (e.g. Notes LIKE
"tns1:RuleEngine" or "/true") need updating.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix: link existing tags to events and stop logging new ones as errors refs #7688
Event::AddPacket_ tagged events from object detections, but when the tag
name was already in Tags it neither linked it to the event nor cached it,
and leaked the Tag that Tag::find returned. Only a tag name created for the
first time was ever linked, so detections of person, car, ... after the
first never reached Events_Tags.
Move the tagging into Event::AddTag, which finds or creates the tag, links
it once per event and caches it. A mutex guards the cache so the analysis
thread can tag the event too. Event_Tag::save uses INSERT IGNORE so a link
another writer made first (zm_detect via pyzm) is not an error, and
Tag::find returns nullptr without logging two errors when the name is not
there yet, which is how callers learn a tag is new.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat: tag events with the objects an ONVIF camera reports refs #7688
Add a per-monitor "Tag Events From ONVIF" checkbox (Monitors.ONVIF_Event_Tags,
off by default). When set, events raised by the ONVIF event listener are
tagged with what the camera detected, through the existing Tags and
Events_Tags tables.
ONVIFEventTags() reads the object from wherever the camera puts it, using
the items parse_event_message() already collects for the note: the topic
(Reolink PeopleDetect), an active item name without its "Is" (Tapo
IsPeople) or the classes in an item value (Ajax ClassTypes="Human
Vehicle"). Camera names map to the names object detection uses, so one tag
means one thing: person, vehicle, animal, package, face, and doorbell for
a Visitor press. An alarm that names no object (motion, tamper, line
crossing, an unknown detector) is tagged with its last topic segment, e.g.
MotionAlarm. The names are a table next to the note vocabulary; items are
judged by the same helper the note uses (inactive, per-object id, generic
state).
Each alarm entry keeps its tags beside its note, SetTagSet() returns them
as SetNoteSet() returns notes, including for a pulse that has already
cleared, and Monitor::Analyse() hands them to Event::AddTag().
Schema: zm_update-1.39.55.sql adds the column, zm_create.sql.in matches,
version 1.39.55. Web: checkbox and help text next to ONVIF Event Listener,
unticked default for the save action. Perl: Monitor field list.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat: map camera object names to AI object classes for ONVIF tags refs #7688
ONVIF event tags were mapped from a word list compiled into zmc, so a
camera using another word for an object needed a code change. Move the
mapping into the database, on the object classes ZM already has.
- Add AI_Object_Classes.Aliases, a comma separated list of what cameras
call the class, editable in Options, AI Classes.
- Seed aliases on the COCO person class and add a Camera dataset for
the objects COCO has no class for: vehicle, animal, package, face and
doorbell. Aliases already set are kept when the migration reruns.
- zmc loads the class names and aliases when the ONVIF listener starts
on a monitor with ONVIF_Event_Tags set. A class name maps to itself,
so a camera reporting Car is tagged car, as object detection would.
- Without the classes (an older database) alarms are tagged with their
topic, as for an alarm that names no object.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix: address review of the ONVIF event tags refs #7688
- Event::AddTag tries each name once per event, so a tag that can't be
saved is not looked up and logged on every frame, and cuts names to
the 64 characters of Tags.Name. It no longer holds tags_mutex_ over
the database work, and the Events_Tags row goes through dbQueue, so
the analysis thread waits on at most the tag lookup.
- Tag::save returns the existing Id when another process created the
same tag first, instead of failing on the unique Name.
- Event_Tag::save ignores only the duplicate key, not other errors.
- An ONVIF message whose first state item is inactive and a later one
active (Tapo IsVehicle=false, IsPeople=true) raises the alarm.
- The Is prefix of an item name is matched in any case.
- load_tag_names leaves the error to zmDbFetch, which has logged it.
- The help text says to restart the monitor after changing aliases.
- Re-indent two lines in ProcessPullResponse.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat: restart ONVIF tagging monitors when an AI class changes refs #7688
zmc reads the object class names and aliases when it starts listening
for ONVIF events, so an alias saved in Options, AI Classes did nothing
until the monitor was restarted by hand. Saving or deleting a class now
restarts the zmc of each monitor with ONVIF_Event_Listener and
ONVIF_Event_Tags set, as saving zones does for their monitor.
Add the Aliases label to en_gb so it can be translated like the other
strings, and say in the help text that saving restarts those monitors.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix: address Copilot review of the ONVIF event tags refs #7688
- Only a later alarm-state item (IsX, State, Alarm, ...) overrides an
inactive first one. A later ObjectId or Count describes the object,
so IsInside=false followed by ObjectId=3 stays an alarm-off.
- 1 is true for a flag item such as IsPeople, as it already was for
State, so IsPeople=1 is tagged person rather than the topic.
- Cut tag names at 64 UTF-8 characters, the size of Tags.Name, without
splitting a character, using a new Utf8Truncate helper.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat: leave ONVIF detections out of the note when they are tagged refs #7688
With ONVIF_Event_Tags on, the tags already say what the camera
detected, and name the topic when no object is named, so the note
repeated them: "Motion: MyRuleDetector/PeopleDetect, ONVIF" next to a
person tag. Such a monitor's note now just says ONVIF. With tags off
the note still names the detection.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat: edit AI class aliases as tags refs #7688
A plain text field gave no hint that aliases are a comma list. Edit
them like an event's tags instead, with the same tag styles: each alias
is a removable tag, and Enter, space or comma adds the one typed. They
are still saved as the comma list zmc reads, so nothing else changes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix: split ONVIF class values on commas and drop the DogCat alias refs #7688
A camera listing its classes as ClassTypes="Human,Vehicle" was tagged
with neither, as values were split on spaces only. Split on commas too.
Drop DogCat from the animal aliases: no camera is known to send it,
Reolink sends DogCatDetect. Say in the seed where the starter aliases
come from, which of them have been seen from a camera, and that more
are added in Options, AI Classes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* feat: give a new AI class the next free index and refuse a taken one refs #7688
A class's index is the number its dataset's model gives it, which a
dataset with no model behind it (Camera) has no use for, yet the form
required one and took any number, so a second class could get 0.
Leave the index empty on a new class to get the next one in its
dataset, and refuse an index another class of the dataset already has,
naming that class.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix: number the placeholders of ClassIndexInUse so translations can reorder them refs #7688
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* refactor: source the camera class seed from the 1.39.55 migration refs #7688
The migration carried a copy of db/camera_classes.sql, so the starter
aliases lived in two places. Make it a .sql.in that sources the seed
file, as zm_update-1.39.26.sql.in does with triggers.sql, so fresh
installs and upgrades share one copy. Note in the seed that it must
keep working on a 1.39.55 database.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Isaac Connor <isaac@zoneminder.com>
* fix: Options dnsmasq save refuses directives that run programs or include files and values with line breaks refs #7520
* fix: dnsmasq save also refuses conf-script and dumpfile refs #7520
* fix: html_input and filter terms escape their values and attributes refs #7458
* fix: filter bar also escapes a term's id, placeholder and Date data-cookie refs #7458
Added a reusable htmlAttributes() helper function to cleanly render arbitrary HTML attributes (such as title, data-*, and boolean attributes) on <select> and <option> elements without breaking backward compatibility.
Preserved existing htmlspecialchars() encoding flags (double_encode = false) to avoid double-encoding regressions.
-------------------------------------
Zone View (zone.php & Localization):
Replaced raw enum strings in the Zone Type dropdown with localized labels via translate() and added explanatory title tooltips for each zone type (Active, Inclusive, Exclusive, Preclusive, Inactive, Privacy).
Assigned semantic CSS classes (zone-type-*) to options and the initial <select> element.
-------------------------------------
Dynamic Styling (zone.js & Skin CSS):
Updated applyZoneType() to dynamically sync the selected option's color class with the <select> element on page load and change events (CSP-compliant, no inline JS).
Added theme-specific color rules for .zone-type-* across light and dark skins to ensure proper contrast and readability.
PHP 8.0 is now the minimum, so these branches can no longer run:
- functions.php: str_starts_with/str_ends_with/str_contains polyfills;
zm_random_bytes() fallbacks to mcrypt and openssl (random_bytes() is
always there).
- auth.php: the password_hash() check in migrateHash().
- session.php: pre-7.3 setcookie()/session_set_cookie_params() forms
without samesite, and the pre-5.4 is_session_started().
- stream.php: blocking sem_acquire() for PHP < 5.6.1, and the PHP < 5.6
half of the 64 bit event id unpack check (the 32 bit PHP_INT_SIZE half
stays).
- database.php: the magic quotes branch of dbEscape();
get_magic_quotes_gpc() was removed in PHP 8.
- logger.php: the PHP >= 5.2 guards around error_get_last().
- Event.php, ImageComponent.php: the PHP < 4.3.10 sprintf('%.3f').
- image.php: the imagedestroy() branch for PHP < 8.
database.php keeps its PHP_VERSION_ID >= 80100 check, as 8.0 is still
supported.
Tests: tests/php/test_php_minimum.php checks the declared minimum in
composer.json, the platform check, the rpm and deb dependencies, and that
no PHP 4/5/7 version check is left in the web code.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
CORSHeaders() (web UI) and AppController::beforeFilter() (API) send
Access-Control-Allow-Origin with Access-Control-Allow-Credentials: true.
With no Servers rows and ZM_MIN_STREAMING_PORT set they reflected any
Origin, and with Servers rows they matched the Origin against each
server's Hostname and Name with a regex anchored only at the start, so
https://zm.example.com.evil.net was accepted for zm.example.com.
Both now call corsAllowedOrigin() in Network.php, which accepts an
Origin of the form scheme://host[:port] whose host equals a server's
Hostname or Name, or, without Servers rows and with streaming ports,
the host this request was made to. Any port is accepted, so multi-port
streaming keeps working. Same-origin and unlisted origins get no CORS
headers, as before; the web UI still warns about unlisted origins only
when Servers rows exist.
Tests: tests/php/test_cors_allowed_origin.php
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When the other server of a multi-server install did not answer,
file_get_contents() raised a PHP warning whose text is the call and its
URL, ?auth=<hash> or user=/pass= included, and PHP wrote it to the web
server's error log (Event.php, Filter.php). The same happened with the
image proxy's digest retry (camera user:password@) and the X-Frame
check of a website monitor (get_headers()), which also took the false
it returns on failure for an array.
Fetch with @ and log lastErrorForLog(), the reason without the call
and its URL, next to urlForLog() of the URL. Server::SendToApi()
already used @ and now logs the reason too.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The policy allows any script that carries the page nonce, wherever it is
loaded from, and the skin's nonced scripts use relative srcs. Markup
injected into a page before them (an unescaped request value) could add
<base href> pointing at another host, and the browser then loaded and
ran that host's script with the nonce.
Add base-uri 'self'. ZoneMinder doesn't use <base>; jQuery's parseHTML
sets one to the page's own URL in a detached document, which 'self'
still allows.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ajax/stream.php sends stream commands (query, pause, seek, zoom, quit)
to the zms whose unix socket matches a connkey, with no permission
check. Connkeys are six random digits chosen when the stream starts,
so any logged-in user who guessed or saw one could read the status of
another user's stream, of a monitor they may not view included, and
pause or end it. A second zms started with the same connkey also waited
on the first one's lock and then took over its socket.
zms already authenticates the user and checks their access to the
monitor or event before it streams. Keep that user's id and put it in
the lock, command socket and reply socket names
(zms-<connkey>-<user id>s.sock); stream.php builds the names from the
caller's own id through zmsSocketPath(), so a request reaches only the
caller's streams. Without authentication the id is 0 on both sides.
Adds a StreamBase test in tests/zm_stream.cpp and
tests/php/test_zms_socket_path.php, which pin the same names. The
existing command-socket-teardown test is updated for the owner-suffixed
names (it postdates the reporter's base commit).
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
getZmuCommand() and the API's alarm action put the user's credentials on
zmu's command line, where every local user can read them (ps,
/proc/<pid>/cmdline): an auth hash with the default hashed relay, the
plaintext password with ZM_AUTH_RELAY=plain. The API also wrote the
whole command to the debug log. With the default ZM_AUTH_HASH_IPS=0 that
hash is accepted as an auth= login from any address for ZM_AUTH_HASH_TTL
hours.
zmuCredentials() builds them in one place: with a usable
ZM_AUTH_HASH_SECRET, an access token for the user that expires after a
minute (zmu -T, accepted with every relay). Without the secret zmu
refuses tokens, so it gets what it did before. The API logs the command
without the credentials.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 32bc2b3fee87b752590ba6f210403afd9222d9ff)
Looking for other instances of the CronTab.php fatal in the previous commit
found eleven, in ten files, dating from 2019 to 2023. Each is a call to a
logger function from the global namespace without the \ZM\ prefix, so each is
a fatal the moment its branch runs:
web/ajax/console.php, events.php, reports.php, add_monitors.php, status.php
web/includes/actions/snapshot.php (two), donate.php
web/includes/functions.php, session.php
web/views/image.php
They have survived this long because of where they sit. Every one is on an
error or diagnostic path -- an invalid sort order, a zero byte download, a
failed read lock -- so the call is only reached when something has already
gone wrong, and then it turns a handled problem into a blank 500. That is the
shape of the bug on the monitor save: the write had worked, and the thing that
broke was the attempt to log.
Verified before changing any of them that each file is in the global
namespace, does not define the function itself and does not import it, so the
call really does not resolve.
Tests: tests/php/test_logger_calls_qualified.php, 16 checks. It tokenizes
every php file under web/ and reports unqualified calls, with the function
names read out of logger.php rather than listed, so a new one is covered the
day it is added. web/api is skipped as cakephp with its own logging, and
assets as third party.
Php's own tokenizer rather than a regex, because the distinctions matter: a
method call on an object that happens to have an Error() method is fine, as
is a definition, a mention, a qualified call, the same call from inside
namespace ZM, and the name appearing in a comment or a string. There is a
check for each of those, since a scan that quietly matched nothing would pass
the tree-wide check on its own.
Verified the scan fails when the Debug() in CronTab.php is put back.
Ran: tests/php/test_logger_calls_qualified.php (16 passed), the rest of
tests/php and tests/js, npx eslint . (clean), utils/check-homoglyphs.py
(clean). test_bandwidth_clamp.php fails on this box for an unrelated reason:
it cannot read /etc/zm/conf.d/03custom.conf and the permission warning lands
in its captured output.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JpiSWBmtQkR5bcgpHWY4ME
ZM_Object's constructor takes either an id (which it loads from the database)
or an array, which it trusts as the record's own fields. Several request-fed
call sites passed the raw request value straight to new ZM\Event(), so a request
that sends an array instead of a scalar -- eid[Id]=...&eid[MonitorId]=... -- had
its fields adopted as the event row. The request then chose the MonitorId that
canView() checks and the StorageId/Scheme/Id that Path() is built from.
Impact: view_video.php turned this into an arbitrary file read (forge a viewable
MonitorId, point Path() at any directory, append file=); ajax/events.php let a
forged row pass the per-event permission check so archive/delete acted on a row
the user could not see, and delete ran unlink on the forged Path().
validInt()/validCardinal() already return '' for a non-scalar, so route the
request value through them first; an array becomes '' and ZM\Event loads the
real row (or none). Fixed at the two affected sinks and centrally in
getAffectedIds(), which several action handlers use to build the id list.
Addresses GHSA-6h8f-gx4m-qqw4.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
ZM_Object's constructor treats an array as the object's row, and validInt()
and validCardinal() returned an array as they got it (preg_replace() does).
So wherever a request id reached `new ZM\X(...)`, raw or through those
validators, a crafted array built an object whose Id, UserId or MonitorId
the sender chose. The permission check then looked at those, and the delete
or update that followed used the Id. A user with Events=View deleted another
user's filter by posting Id[Id]=<filter>&Id[UserId]=<self> to the filter
delete action; the same shape reached events (MonitorId), users, reports,
snapshots and storage.
validInt() and validCardinal() now give '' for anything that isn't a single
value. The places that built an object from a raw $_REQUEST value (the
control and event ajax handlers, the event, filter, report, snapshot and
storage actions, view_hls, and the download and event detail modals) take
the id through validCardinal().
tests/php/test_request_ids_scalar.php covers the validators with arrays and
fails if web code builds an object straight from $_REQUEST, $_GET or $_POST.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
After saving a zone, actions/zone.php redirected to the REFERER the zone form
posted, which the form fills from the Referer its page was loaded with. A
zone editor who reached the zone page through a link on another site was sent
to that site after saving: an open redirect, usable to lead someone from a
trusted ZoneMinder page to a look-alike login. Forging the POST itself is
blocked by the CSRF token, so it needs an editor who followed such a link.
localRedirectUrl() returns the target only if it is a query-only URL or an
absolute http(s) URL on the host and port of the current request, and the
fallback otherwise: another host, //host, backslashes, user@host, other
schemes and control characters all give the fallback. The zone save falls
back to the zones list, as it already does with no Referer (#5207).
tests/php/test_local_redirect_url.php covers 21 cases.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The classic event actions checked only the global Events permission and
then acted on whatever event ids the request supplied, so a user denied a
monitor could still change that monitor's events:
- deleteEvent() deleted when the user had Events=Edit. It now requires
Event::canEdit(), which also requires access to the event's monitor.
This covers the events form, the event form and monitor deletion.
- The events form archive/unarchive updated Events by id. Each event now
needs canEdit().
- ajax events archiveRequest() updated by id under the page-wide Events
view check. Archive now needs canView() on the event and unarchive
canEdit(), keeping the intent that viewers may archive.
- actions/event.php returned early whenever an eid was supplied, so none
of its actions ran. Fix that inverted test, and require canEdit() on the
event for rename, detail edits, archive, unarchive and delete, rather
than the global permission.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
sortHeader() concatenated $_REQUEST['filter']['query'] into the href of
every export view column header without escaping, allowing reflected
HTML injection (iframe, meta refresh, style) via a crafted link. Pass it
through validHtmlStr() like the other request values in the same string
are passed through validInt()/validCardinal().
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit 7517018879f2be9ba1f9439e3364686ccee226ed)