Merge pull request #7328 from AJ0070/fix-api-search-array-param

fix: API events index applies the DateTime and StartTime/EndTime filters to query-string parameters too
This commit is contained in:
Isaac Connor authored and GitHub committed 2026-11-21 20:59:28 -05:00
commit adc36852b4
2 files changed
+219 -57

No files matched your search

@@ -0,0 +1,153 @@
<?php
/**
* EventsController::index() accepts filters either as CakePHP named parameters
* (/events/index/StartTime >=:...) or, when there are none, as the query string
* (/events.json?DateTime >=...). Only the named form renamed the legacy
* StartTime/EndTime to StartDateTime/EndDateTime and turned the DateTime
* pseudo-attribute into an overlap test, so on the query string the first was
* a 400 and the second reached MySQL as an unknown column (500).
*
* index() is run against stubs and the conditions handed to find() are checked,
* so the test works for both the fixed and the original source.
*
* Usage: php tests/php/test_api_events_index_querystring_time.php [repo-root]
*/
$root = isset($argv[1]) ? rtrim($argv[1], '/\\') : dirname(__DIR__, 2);
$controller_file = $root . '/web/api/app/Controller/EventsController.php';
$filter_file = $root . '/web/api/app/Controller/Component/FilterComponent.php';
class BadRequestException extends Exception {}
class UnauthorizedException extends Exception {}
class NotFoundException extends Exception {}
class Component {}
class App { static function uses() {} }
function __($s) { return $s; }
class StubDataSource {
function value($v, $type = null) { return "'".addslashes($v)."'"; }
}
class StubEvent {
public $recursive;
public $found = null;
function schema() {
$cols = array('Id', 'MonitorId', 'StartDateTime', 'EndDateTime', 'Length');
return array_combine($cols, $cols);
}
function getDataSource() { return new StubDataSource(); }
function find($type, $settings) { $this->found = $settings; return array(); }
}
class StubComponents {
function load($name) { return new FilterComponent(); }
}
class StubRequest {
public $params = array('named' => array());
function query($k) { return null; }
}
class AppController {
public $request;
public $Components;
public $Event;
public $Paginator;
function __construct() {
$this->Paginator = new stdClass();
$this->request = new StubRequest();
$this->Components = new StubComponents();
$this->Event = new StubEvent();
}
function viewableMonitorCondition($f) { return array(); }
function set($v) {}
}
function load_php($file) {
$src = file_get_contents($file);
if ($src === false) {
fwrite(STDERR, "cannot read $file\n");
exit(2);
}
$src = preg_replace('/^<\?php/', '', $src);
$src = preg_replace('/\?>\s*$/', '', $src);
return $src;
}
eval(load_php($filter_file));
$src = load_php($controller_file);
$src = str_replace("require_once __DIR__ .'/../../../includes/Event.php';", '', $src);
eval($src);
$failures = 0;
function check($label, $ok, $detail = '') {
global $failures;
if ($ok) {
echo "ok - $label\n";
} else {
$failures++;
echo "FAIL - $label" . ($detail !== '' ? ": $detail" : '') . "\n";
}
}
// Run index() with the given query string and return the find() conditions,
// or the exception message.
function run_index($query) {
$_REQUEST = $query;
$c = new EventsController();
try {
$c->index();
} catch (Exception $e) {
return get_class($e) . ': ' . $e->getMessage();
}
return $c->Event->found['conditions'][0];
}
$effective_end_marker = 'Event.EndDateTime IS NOT NULL';
// DateTime lower bound: overlap test, no bare DateTime column.
$r = run_index(array('DateTime >=' => '2024-01-01 00:00:00'));
check('query string DateTime >= is accepted', is_array($r), is_string($r) ? $r : '');
if (is_array($r)) {
check('query string DateTime >= leaves no DateTime column',
!array_key_exists('DateTime >=', $r) && !array_key_exists('DateTime', $r), var_export($r, true));
$found = false;
foreach ($r as $cond) {
if (is_string($cond) and false !== strpos($cond, $effective_end_marker)
and false !== strpos($cond, ">= '2024-01-01 00:00:00'")) {
$found = true;
}
}
check('query string DateTime >= tests the effective end', $found, var_export($r, true));
}
// DateTime upper bound: the event must have started by then.
$r = run_index(array('DateTime <=' => '2024-02-01 00:00:00'));
check('query string DateTime <= is accepted', is_array($r), is_string($r) ? $r : '');
if (is_array($r)) {
check('query string DateTime <= tests StartDateTime',
in_array(array('Event.StartDateTime <=' => '2024-02-01 00:00:00'), $r, true), var_export($r, true));
}
// Legacy names are renamed.
$r = run_index(array('StartTime >=' => '2024-01-01 00:00:00', 'EndTime <=' => '2024-02-01 00:00:00'));
check('query string StartTime/EndTime are accepted', is_array($r), is_string($r) ? $r : '');
if (is_array($r)) {
check('query string StartTime becomes StartDateTime',
($r['Event.StartDateTime >='] ?? null) === '2024-01-01 00:00:00', var_export($r, true));
check('query string EndTime becomes EndDateTime',
($r['Event.EndDateTime <='] ?? null) === '2024-02-01 00:00:00', var_export($r, true));
}
// Unchanged behaviour: ordinary filters and unknown fields.
$r = run_index(array('MonitorId' => '3'));
check('query string MonitorId still qualifies', is_array($r) and ($r['Event.MonitorId'] ?? null) === '3', var_export($r, true));
$r = run_index(array('Bogus' => '1'));
check('query string unknown field is still a 400', is_string($r) and 0 === strpos($r, 'BadRequestException'), var_export($r, true));
// Named form, the reference behaviour.
$c = new EventsController();
$c->request->params['named'] = array('StartTime >=' => '2024-01-01 00:00:00', 'DateTime <=' => '2024-02-01 00:00:00');
$c->index();
$named = $c->Event->found['conditions'][0];
check('named StartTime/DateTime still work',
($named['Event.StartDateTime >='] ?? null) === '2024-01-01 00:00:00'
and in_array(array('Event.StartDateTime <=' => '2024-02-01 00:00:00'), $named, true), var_export($named, true));
echo $failures ? "\n$failures failed\n" : "\nall passed\n";
exit($failures ? 1 : 0);
+66 -57
View File
@@ -38,6 +38,69 @@ class EventsController extends AppController {
);
}
private function renameLegacyTimeParams($params) {
# In 1.35.13 we renamed StartTime and EndTime to StartDateTime and EndDateTime.
# This hack renames the query string params
foreach ( $params as $k=>$v ) {
if ( false !== strpos($k, 'StartTime') ) {
$new_k = preg_replace('/StartTime/', 'StartDateTime', $k);
$params[$new_k] = $params[$k];
unset($params[$k]);
}
if ( false !== strpos($k, 'EndTime') ) {
$new_k = preg_replace('/EndTime/', 'EndDateTime', $k);
$params[$new_k] = $params[$k];
unset($params[$k]);
}
}
return $params;
}
private function datetimeConditions($conditions) {
# DateTime is a pseudo-attribute meaning "the event was running then", so a
# window over it is an overlap test: the event started by the upper bound
# and had not finished by the lower bound. Applying the term's own operator
# to both StartDateTime and EndDateTime instead makes the upper bound a
# containment test, which drops every event that spans the end of the
# window -- with continuous recording that is most of them.
$datetime_terms = array();
foreach ($conditions as $k=>$v) {
if ( 0 === strpos($k, 'DateTime') ) {
$datetime_terms[$k] = $v;
unset($conditions[$k]);
}
}
if ($datetime_terms) {
# An event still being written has no EndDateTime, but it is not
# unbounded: zmc flushes Length every few seconds, so StartDateTime +
# Length is its effective end. Only an event with neither falls back to
# NOW(). Treating a missing EndDateTime as "matches any window" instead
# made every crash-orphaned event ever recorded match every query.
$effective_end = '(CASE'
.' WHEN Event.EndDateTime IS NOT NULL THEN Event.EndDateTime'
.' WHEN Event.Length > 0 THEN DATE_ADD(Event.StartDateTime, INTERVAL FLOOR(Event.Length) SECOND)'
.' ELSE NOW() END)';
$ds = $this->Event->getDataSource();
foreach ($datetime_terms as $k=>$v) {
$op = trim(substr($k, strlen('DateTime')));
if ($op == '<' or $op == '<=') {
# Upper bound: the event must have started by then.
$conditions[] = array('Event.StartDateTime '.$op => $v);
} else if ($op == '>' or $op == '>=') {
# Lower bound: the event must not have ended before then.
$conditions[] = $effective_end.' '.$op.' '.$ds->value($v, 'string');
} else {
# Anything else (=, !=) still matches against either end.
$conditions[] = array('OR' => array(
array('Event.StartDateTime '.$op => $v),
array('Event.EndDateTime '.$op => $v),
));
}
}
} // end if datetime terms
return $conditions;
}
/**
* index method
*
@@ -69,20 +132,7 @@ class EventsController extends AppController {
$tag_filter_field = 'Name';
unset($named_params['Tags']);
}
# In 1.35.13 we renamed StartTime and EndTime to StartDateTime and EndDateTime.
# This hack renames the query string params
foreach ( $named_params as $k=>$v ) {
if ( false !== strpos($k, 'StartTime') ) {
$new_k = preg_replace('/StartTime/', 'StartDateTime', $k);
$named_params[$new_k] = $named_params[$k];
unset($named_params[$k]);
}
if ( false !== strpos($k, 'EndTime') ) {
$new_k = preg_replace('/EndTime/', 'EndDateTime', $k);
$named_params[$new_k] = $named_params[$k];
unset($named_params[$k]);
}
}
$named_params = $this->renameLegacyTimeParams($named_params);
// Events columns, plus the two names this action resolves itself: DateTime
// is a pseudo-attribute turned into an overlap test below, and GroupId is
// served by the Groups_Monitors join added further down. Anything else
@@ -93,49 +143,6 @@ class EventsController extends AppController {
$named_params = $this->FilterComponent->qualifyFields($named_params, $this->filterColumns(), array('DateTime', 'GroupId'));
$conditions = $this->FilterComponent->buildFilter($named_params, $valid_fields);
#ZM\Debug(print_r($conditions, true));
# DateTime is a pseudo-attribute meaning "the event was running then", so a
# window over it is an overlap test: the event started by the upper bound
# and had not finished by the lower bound. Applying the term's own operator
# to both StartDateTime and EndDateTime instead makes the upper bound a
# containment test, which drops every event that spans the end of the
# window -- with continuous recording that is most of them.
$datetime_terms = array();
foreach ($conditions as $k=>$v) {
if ( 0 === strpos($k, 'DateTime') ) {
$datetime_terms[$k] = $v;
unset($conditions[$k]);
}
}
if ($datetime_terms) {
# An event still being written has no EndDateTime, but it is not
# unbounded: zmc flushes Length every few seconds, so StartDateTime +
# Length is its effective end. Only an event with neither falls back to
# NOW(). Treating a missing EndDateTime as "matches any window" instead
# made every crash-orphaned event ever recorded match every query.
$effective_end = '(CASE'
.' WHEN Event.EndDateTime IS NOT NULL THEN Event.EndDateTime'
.' WHEN Event.Length > 0 THEN DATE_ADD(Event.StartDateTime, INTERVAL FLOOR(Event.Length) SECOND)'
.' ELSE NOW() END)';
$ds = $this->Event->getDataSource();
foreach ($datetime_terms as $k=>$v) {
$op = trim(substr($k, strlen('DateTime')));
if ($op == '<' or $op == '<=') {
# Upper bound: the event must have started by then.
$conditions[] = array('Event.StartDateTime '.$op => $v);
} else if ($op == '>' or $op == '>=') {
# Lower bound: the event must not have ended before then.
$conditions[] = $effective_end.' '.$op.' '.$ds->value($v, 'string');
} else {
# Anything else (=, !=) still matches against either end.
$conditions[] = array('OR' => array(
array('Event.StartDateTime '.$op => $v),
array('Event.EndDateTime '.$op => $v),
));
}
}
} // end if datetime terms
#ZM\Debug(print_r($conditions, true));
} else {
$raw_params = $_REQUEST;
// Legacy API authentication rides in the query string next to the filters.
@@ -155,9 +162,11 @@ class EventsController extends AppController {
$tag_filter_field = 'Name';
unset($raw_params['Tags']);
}
$raw_params = $this->renameLegacyTimeParams($raw_params);
$raw_params = $this->FilterComponent->qualifyFields($raw_params, $this->filterColumns(), array('DateTime', 'GroupId'));
$conditions = $this->FilterComponent->buildFilter($raw_params, array_merge(array_keys($this->Event->schema()), array('DateTime', 'GroupId')));
}
$conditions = $this->datetimeConditions($conditions);
$settings = array(
// https://github.com/ZoneMinder/ZoneMinder/issues/995
// 'limit' => $limit['ZM_WEB_EVENTS_PER_PAGE'],