COCO' for key 'Name'"; } function translate($k) { return $k; } function validHtmlStr($s) { return htmlspecialchars($s); } // Runs an action file; returns its effects on $error_message/$redirect/$refreshParent. function run_action($file, $action, $request, $db_ok) { global $root; $src = file_get_contents($root.'/web/includes/actions/'.$file); $src = preg_replace('/^<\?php/', '', $src); $src = preg_replace('/\?>\s*$/', '', $src); $src = preg_replace('/^require_once\(.*$/m', '', $src); $problems = array(); set_error_handler(function ($no, $str) use (&$problems) { $problems[] = $str; return true; }); $_REQUEST = $request; $GLOBALS['db_ok'] = $db_ok; $fn = function ($action) use ($src) { global $error_message, $redirect, $refreshParent; $error_message = ''; $redirect = null; $refreshParent = null; try { eval($src); } catch (\Throwable $e) { return get_class($e).': '.$e->getMessage(); } return null; }; $ex = $fn($action); restore_error_handler(); $state = array( 'error_message' => $GLOBALS['error_message'], 'redirect' => $GLOBALS['redirect'], 'refreshParent' => $GLOBALS['refreshParent'], 'problems' => $problems, ); if ($ex) $state['problems'][] = $ex; return $state; } $cases = array( array('ai_dataset.php', 'newDataset', '?view=options&tab=ai_datasets'), array('ai_class.php', 'newClass', '?view=options&tab=ai_classes'), array('ai_model.php', 'newModel', '?view=options&tab=ai_models'), ); foreach ($cases as $case) { list($file, $key, $want_redirect) = $case; echo "$file\n"; echo " db failure (duplicate Name):\n"; $s = run_action($file, 'save', array($key => array('Name' => 'COCO')), false); check('reports Error saving', strpos($s['error_message'], 'Error saving') !== false); check('includes the db error', strpos($s['error_message'], 'Duplicate entry') !== false); check('escapes the db error', strpos($s['error_message'], '') === false && strpos($s['error_message'], '<b>COCO') !== false); check('redirect stays unset', $s['redirect'] === null); check('refreshParent is not true', $s['refreshParent'] !== true); check('raises no warnings', count($s['problems']) == 0); echo " db success:\n"; $s = run_action($file, 'save', array($key => array('Name' => 'COCO')), true); check('no error message', $s['error_message'] === ''); check('redirects to '.$want_redirect, $s['redirect'] === $want_redirect); check('refreshParent is true', $s['refreshParent'] === true); check('raises no warnings', count($s['problems']) == 0); } echo "\n$tests tests, $failures failures\n"; exit($failures ? 1 : 0);