From bd38983abb405502185585e28176f12b0b02b92a Mon Sep 17 00:00:00 2001 From: johnnyq Date: Wed, 2 Dec 2026 17:46:03 -0500 Subject: [PATCH 1/8] API / service accounts take no seat on the agent user limit, the managed instance's or config.php's: getActiveAgentUserCount() leaves them out, so the seats taken, the limit checks and the report to the manager do too; one can be added, enabled, restored or bulk enabled when every seat is taken, New User stays open with the window saying so, and turning an active one back into an agent who signs in needs a free seat (serviceAccountLeavingNeedsSeat()); 26.12.5 changelog --- CHANGELOG.md | 14 ++++++++++++++ admin/managed_instance.php | 2 +- admin/modals/user/user_add.php | 2 +- admin/modals/user/user_form.php | 2 +- admin/modals/user/user_restore.php | 2 +- admin/post/users.php | 21 +++++++++++++++------ admin/users.php | 9 +++++---- functions/app.php | 6 ++++-- functions/managed.php | 3 ++- functions/service_account.php | 19 +++++++++++++++++++ 10 files changed, 63 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 83f23f2b2..ab249e8f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ This file documents all notable changes made to ITFlow. +## [26.12.5] + +### Upgrading to 26.12.5 + +Update from Maintenance > Update as usual. There are no database changes. + +### New Features & Updates + +- An API / service account no longer takes a seat on the agent user limit - the one your hosting provider sets, or one set for your installation. Nobody signs in as it: it's the login an integration's API keys act as. You can add one, enable one or restore one when every seat is taken, and Admin > Users shows the seats without them. Turning one back into an agent who signs in takes a seat, so there has to be one free. A hosted instance's manager sees it the same way: its seats taken leave API accounts out, and its list of agents marks them. + +### Developer Updates + +- `getActiveAgentUserCount()` (`functions/app.php`) leaves out `users.user_service_account = 1` with `serviceAccountsOutSql()`, so `getAgentSeatsTaken()`, `agentUserLimitReached()` and the managed report's `agents.active` do too (the report's list still carries them, with `service` set). `admin/post/users.php` skips `agentUserLimitReached()` for an API / service account in `add_user`, `activate_user`, `restore_user` and `bulk_activate_users`, and `edit_user` refuses turning an active one into an agent at the limit before changing anything (`serviceAccountLeavingNeedsSeat()`, `functions/service_account.php`). Admin > Users keeps New User open at the limit when service accounts are available, and the New User window says one can still be added. + ## [26.12.4] ### Upgrading to 26.12.4 diff --git a/admin/managed_instance.php b/admin/managed_instance.php index e2bfe4a64..ba6176b50 100644 --- a/admin/managed_instance.php +++ b/admin/managed_instance.php @@ -352,7 +352,7 @@ if ($error_count > 0) {
Invited - API account + API account
diff --git a/admin/modals/user/user_add.php b/admin/modals/user/user_add.php index 2838d9da6..2d5ec669c 100644 --- a/admin/modals/user/user_add.php +++ b/admin/modals/user/user_add.php @@ -27,7 +27,7 @@ ob_start(); diff --git a/admin/modals/user/user_form.php b/admin/modals/user/user_form.php index f340b86d4..c8e6eb0a9 100644 --- a/admin/modals/user/user_form.php +++ b/admin/modals/user/user_form.php @@ -189,7 +189,7 @@ $value = function ($key) use ($form) { >
- For a login that API keys act as, for an integration. It keeps its role, so its keys work, but it's left out of the calendar, every assign picker, the reports and the other agent lists, gets no notifications, and can't sign in to ITFlow. + For a login that API keys act as, for an integration. It keeps its role, so its keys work, but it takes no seat on the agent user limit, it's left out of the calendar, every assign picker, the reports and the other agent lists, gets no notifications, and can't sign in to ITFlow.
diff --git a/admin/modals/user/user_restore.php b/admin/modals/user/user_restore.php index e08ee5935..8d069d704 100644 --- a/admin/modals/user/user_restore.php +++ b/admin/modals/user/user_restore.php @@ -34,7 +34,7 @@ ob_start(); - +
diff --git a/admin/post/users.php b/admin/post/users.php index e8fcced19..805f0b1ad 100644 --- a/admin/post/users.php +++ b/admin/post/users.php @@ -52,9 +52,11 @@ if (isset($_POST['add_user'])) { redirect(); } - // An invite waiting for them holds a seat already - it is this one + // An invite waiting for them holds a seat already - it is this one. An API / service account + // takes none (functions/service_account.php) $open = userInviteFor($email); - if (agentUserLimitReached($open && userInviteState($open) === 'pending' ? intval($open['invite_id']) : 0)) { + $service_new = !empty($_POST['service_account']) && serviceAccountsReady(); + if (!$service_new && agentUserLimitReached($open && userInviteState($open) === 'pending' ? intval($open['invite_id']) : 0)) { flashAlert(agentUserLimitMessage(), 'error'); redirect(); } @@ -268,6 +270,11 @@ if (isset($_POST['edit_user'])) { if (intval($row['role_is_admin']) && !intval($role['role_is_admin'])) { userGuardLastAdmin($row, 'a role without admin'); } + // An API / service account takes no seat - an agent who signs in does (functions/service_account.php) + if (serviceAccountLeavingNeedsSeat($row, $_POST)) { + flashAlert('' . escapeHtml($row['user_name']) . ' is still an API / service account, which takes no seat - as an agent who signs in it would need one. ' . agentUserLimitMessage(), 'error'); + redirect(); + } mysqli_query($mysqli, "UPDATE users SET user_name = '" . escapeSql($name) . "', user_email = '" . escapeSql($email) . "', user_role_id = " . intval($role['role_id']) . " WHERE user_id = $user_id"); $force_mfa = !empty($_POST['force_mfa']) ? 1 : 0; @@ -332,8 +339,9 @@ if (isset($_GET['activate_user'])) { $row = userForRequest($_GET['activate_user']); $user_id = intval($row['user_id']); - // Only a user who isn't already using a seat can push the count over the limit - if ((intval($row['user_status']) !== 1 || $row['user_archived_at']) && agentUserLimitReached()) { + // Only a user who isn't already using a seat can push the count over the limit - and an API / + // service account takes none (functions/service_account.php) + if ((intval($row['user_status']) !== 1 || $row['user_archived_at']) && !serviceAccountIs($user_id) && agentUserLimitReached()) { flashAlert(agentUserLimitMessage(), 'error'); redirect(); } @@ -443,7 +451,8 @@ if (isset($_POST['restore_user'])) { $row = userForRequest($_POST['user_id'] ?? 0); $user_id = intval($row['user_id']); - if (agentUserLimitReached()) { + // An API / service account takes no seat (functions/service_account.php) + if (!serviceAccountIs($user_id) && agentUserLimitReached()) { flashAlert(agentUserLimitMessage(), 'error'); redirect(); } @@ -549,7 +558,7 @@ if (isset($_POST['bulk_disable_users']) || isset($_POST['bulk_activate_users'])) if ($row['user_archived_at'] || intval($row['user_status']) === ($activate ? 1 : 0)) { continue; } - if ($activate && agentUserLimitReached()) { + if ($activate && !serviceAccountIs($user_id) && agentUserLimitReached()) { $kept[] = $row['user_name']; continue; } diff --git a/admin/users.php b/admin/users.php index 9a98ff9a9..8e8d9f50c 100644 --- a/admin/users.php +++ b/admin/users.php @@ -64,7 +64,7 @@ if (serviceAccountsReady()) { $shows[$view_key]['where'] .= ' AND user_service_account = 0'; } $shows = array_slice($shows, 0, array_search('archived', array_keys($shows), true), true) - + ['service' => ['label' => 'API accounts', 'icon' => 'fa-plug', 'where' => 'user_archived_at IS NULL AND user_service_account = 1', 'title' => 'Logins only for API keys to act as - left out of every agent list, and unable to sign in']] + + ['service' => ['label' => 'API accounts', 'icon' => 'fa-plug', 'where' => 'user_archived_at IS NULL AND user_service_account = 1', 'title' => 'Logins only for API keys to act as - left out of every agent list, unable to sign in, and taking no seat']] + $shows; } $show = isset($shows[$_GET['show'] ?? '']) ? ($_GET['show'] ?? '') : ''; @@ -201,7 +201,8 @@ if (isset($shows['invited'])) { // Those who can sign in to the portal $view_counts['portal'] = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM users $portal_joins WHERE $portal_filters AND " . PORTAL_USER_ON_SQL))[0]); -// Agent user limit (set in config.php, 0 / unset = unlimited) - an invite waiting holds a seat +// Agent user limit (set in config.php, 0 / unset = unlimited) - an invite waiting holds a seat, an API / +// service account doesn't (functions/service_account.php) $agent_user_limit = getAgentUserLimit(); $agent_user_count = getActiveAgentUserCount(); $agent_invites_holding = userInvitesHoldingSeats(); @@ -231,14 +232,14 @@ $csrf = $_SESSION['csrf_token'];

Users 0) { ?> , of the agent user limit "> + title=" active agent, of the agent user limit "> of seats

- + diff --git a/functions/app.php b/functions/app.php index 2133a34f4..0bdeb7f1d 100644 --- a/functions/app.php +++ b/functions/app.php @@ -1101,7 +1101,9 @@ function getProductsForAutocomplete($mysqli, $client_id = 0): string * An active agent is user_type 1, enabled and not archived. Disabled and archived * users do not use a seat. An invite waiting and in date does * (userInvitesHoldingSeats(), functions/user_invite.php) - it is a seat promised. - * The manager's support user doesn't: it is the manager's, not one of theirs. + * The manager's support user doesn't: it is the manager's, not one of theirs. Nor does an API / + * service account (functions/service_account.php): it can't sign in, so nobody uses ITFlow as it - + * it is an integration's login for its API keys. */ function getAgentUserLimit(): int { @@ -1122,7 +1124,7 @@ function getActiveAgentUserCount(): int $support_user_id = managedSupportUserId(); $row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(user_id) FROM users WHERE user_type = 1 AND user_status = 1 AND user_archived_at IS NULL" - . ($support_user_id ? " AND user_id <> $support_user_id" : ''))); + . serviceAccountsOutSql() . ($support_user_id ? " AND user_id <> $support_user_id" : ''))); return intval($row[0]); } diff --git a/functions/managed.php b/functions/managed.php index 5a3c384c5..b4b7c95d8 100644 --- a/functions/managed.php +++ b/functions/managed.php @@ -572,7 +572,8 @@ function managedReport(): array $clients = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM clients WHERE client_archived_at IS NULL AND client_lead = 0"))[0] ?? 0); // Who holds the seats - the active agents (not the support user, which takes none), then the - // invites waiting in date - as getAgentSeatsTaken() counts them + // invites waiting in date - as getAgentSeatsTaken() counts them. API / service accounts are + // listed with 'service' set, and take none either (functions/service_account.php) $agent_list = []; $support_user_id = managedSupportUserId(); $service = function_exists('serviceAccountsReady') && serviceAccountsReady(); diff --git a/functions/service_account.php b/functions/service_account.php index 7b98514ad..e9c92d07c 100644 --- a/functions/service_account.php +++ b/functions/service_account.php @@ -13,6 +13,9 @@ * - it can't sign in to ITFlow in a browser (login.php; includes/load_user_session.php ends a * session it already had) * - Admin > Users lists it in a section of its own; Roles and API Keys show it as before + * - it takes no seat on the agent user limit (getActiveAgentUserCount(), functions/app.php), so + * one can be added, enabled or restored when every seat is taken - but turning one back into + * an agent who signs in takes a seat (serviceAccountLeavingNeedsSeat()) */ /** Whether the 3.8.1 update has run. */ @@ -69,3 +72,19 @@ function serviceAccountSave($user_id, array $post) { mysqli_query($mysqli, "UPDATE users SET user_service_account = " . ($want ? 1 : 0) . " WHERE user_id = $user_id AND user_type = 1"); return $want ? 'now an API / service account' : 'no longer an API / service account'; } + +/* + * Would the Edit user window's $post turn $row - an active API / service account - into an agent who + * signs in when every seat is taken? Then it waits for a free seat, or marking someone an API account + * for a moment would be a way past the limit. A disabled or archived one takes no seat until it is + * enabled or restored, and that checks then. + */ +function serviceAccountLeavingNeedsSeat(array $row, array $post) { + if (!serviceAccountsReady() || !isset($post['service_account_present']) || !empty($post['service_account'])) { + return false; + } + if (intval($row['user_status'] ?? 0) !== 1 || !empty($row['user_archived_at']) || !serviceAccountIs($row['user_id'] ?? 0)) { + return false; + } + return agentUserLimitReached(); +} From 9e74c0240aa511dfdf09b28e6b6a258ea9959d9d Mon Sep 17 00:00:00 2001 From: johnnyq Date: Wed, 2 Dec 2026 18:02:56 -0500 Subject: [PATCH 2/8] Cron leaves alone the jobs with nothing to do on an install: a job can declare not_in_use in includes/cron_jobs.php, the same check its script stops on, and cron.php skips it before its lock and claim unless it is asked to Run Now, registering its row the first time (cronJobRegister()); checks for AI Triage, Text Messages, RMM Sync, RMM Alerts, the Ticket Email Parser, Mail Queue, Payment Provider Fees, Update Check, Manager Check-in and Managed Instances; AI Triage no longer runs with triage off or no AI model (aiTriageNotInUse()); Maintenance > Cron shows them as Not in use with the reason, Cron Watch doesn't expect them to run, and CONTRIBUTING.md has the rule; 26.12.5 changelog --- CHANGELOG.md | 6 +++ CONTRIBUTING.md | 2 + admin/cron.php | 23 ++++++--- cron/ai_triage.php | 6 +++ cron/cron.php | 37 ++++++++++++-- functions/ai_ticket.php | 15 ++++++ functions/cron_health.php | 5 +- includes/cron_jobs.php | 101 ++++++++++++++++++++++++++++++++++++++ 8 files changed, 182 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ab249e8f6..034fefc6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,11 +10,17 @@ Update from Maintenance > Update as usual. There are no database changes. ### New Features & Updates +- Cron leaves alone the jobs that have nothing to do on your ITFlow - what they work with is switched off or isn't set up: AI Triage, Text Messages, RMM Sync and RMM Alerts, the Ticket Email Parser with email to ticket off or no mailbox, the Mail Queue with no mail server, Payment Provider Fees without Stripe, the Update Check on an install that isn't a git checkout, and Manager Check-in and Managed Instances when there's nothing connected. Before, each one started every minute only to stop itself. Maintenance > Cron shows them as **Not in use**, with why under each; they start by themselves once that changes, and **Run Now** still runs them. Cron Watch doesn't email about them falling behind. - An API / service account no longer takes a seat on the agent user limit - the one your hosting provider sets, or one set for your installation. Nobody signs in as it: it's the login an integration's API keys act as. You can add one, enable one or restore one when every seat is taken, and Admin > Users shows the seats without them. Turning one back into an agent who signs in takes a seat, so there has to be one free. A hosted instance's manager sees it the same way: its seats taken leave API accounts out, and its list of agents marks them. +### Bug Fixes + +- AI Triage no longer runs every minute when AI triage is off in Settings > Tickets or there's no AI model to ask - before, it ran anyway and showed **Completed** every minute with nothing done. + ### Developer Updates - `getActiveAgentUserCount()` (`functions/app.php`) leaves out `users.user_service_account = 1` with `serviceAccountsOutSql()`, so `getAgentSeatsTaken()`, `agentUserLimitReached()` and the managed report's `agents.active` do too (the report's list still carries them, with `service` set). `admin/post/users.php` skips `agentUserLimitReached()` for an API / service account in `add_user`, `activate_user`, `restore_user` and `bulk_activate_users`, and `edit_user` refuses turning an active one into an agent at the limit before changing anything (`serviceAccountLeavingNeedsSeat()`, `functions/service_account.php`). Admin > Users keeps New User open at the limit when service accounts are available, and the New User window says one can still be added. +- Cron jobs can declare `'not_in_use' => function () { ... }` in `includes/cron_jobs.php`, returning why the job has nothing to do on this install or `''` (`cronJobNotInUse()`, which counts a check that throws as in use; `cronJobSettings()` reads the settings the checks need once a request). `cron/cron.php` reads every job's row and Run Now flag once a cycle and skips a job not in use before its lock and claim - registering its row the first time (`cronJobRegister()`, split out of `cronJobClaim()`) - unless it is asked to Run Now. `cronHealthJobs()` leaves such jobs out, so Cron Watch neither waits on nor flags them, and `admin/cron.php` shows them in a new `unused` state. Checks added for `manager_checkin`, `mail_queue`, `sms_queue`, `rmm_sync`, `rmm_alerts`, `ticket_email_parser`, `ai_triage`, `managed_instances`, `payment_provider_fees` and `update_check`, each the same condition its script stops on. `aiTriageNotInUse()` (`functions/ai_ticket.php`) is new, and `cron/ai_triage.php` now stops on it too. CONTRIBUTING.md has the rule. ## [26.12.4] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 632f8a714..503015d98 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -108,6 +108,8 @@ A job can also ship switched off with `'enabled' => 0` in the registry. The row ### The master switch +A job whose work hangs on a feature that can be off or not set up - texting, an RMM provider, AI triage, a mailbox - declares `'not_in_use' => function () { ... }` in `includes/cron_jobs.php`, returning why it has nothing to do or `''` when it has. The dispatcher then doesn't lock, claim or load it at all, Maintenance > Cron shows it as **Not in use** with the reason, and Cron Watch doesn't expect it to run. Make it the same check the script stops on - cheap, and the database only, never the network - so leaving the job out never leaves its work undone; the script keeps its own check, for Run Now and for running it by hand. + `config_enable_cron` is a second, coarser switch that sits above the per-job ones. It is **not** enforced by the dispatcher — every job checks it in its own header and stops itself with `cronJobStop()`. A new job has to make that check too; one that skips it keeps running on an install that believes cron is off, which is exactly the trap `ticket_email_parser` and `ticket_sla` sat in until 26.08. Be precise about what it does, because it is easy to oversell. It is **not** a guard on restored data: a full backup dumps the `settings` table, so a restored copy comes back with `config_enable_cron = 1` alongside every enabled `cron_jobs` row, exactly as production had them. What it gives you is one reversible bit — the fastest way to stop an install acting on live data once you have noticed, and the only way to stop everything without editing seven rows. diff --git a/admin/cron.php b/admin/cron.php index 7e575f6e0..9b8d0554a 100644 --- a/admin/cron.php +++ b/admin/cron.php @@ -74,7 +74,8 @@ while ($job_row = mysqli_fetch_assoc($sql)) { * Each job the registry lists, with what its row says. How its last run went is one of: * queued (Run now, not picked up yet), running, lost (still Running hours later - it was cut * off, and nothing recorded how), completed, failed, skipped (it stopped itself early, and - * says why), paused (by a manager), never. + * says why), paused (by a manager), never - or unused: it has nothing to do here, its feature + * off or not set up, so cron leaves it alone until that changes (cronJobNotInUse()). */ $jobs = []; foreach (cronJobRegistry() as $position => $entry) { @@ -98,6 +99,7 @@ foreach (cronJobRegistry() as $position => $entry) { 'last_error' => trim((string) ($job_row['cron_job_last_error'] ?? '')), 'last_error_at' => $job_row['cron_job_last_error_at'] ?? null, 'reason' => '', + 'not_in_use' => cronJobNotInUse($entry), ]; $job['schedule_text'] = cronJobScheduleDescription($job['schedule'], $job['interval_minutes'], $job['daily_at']); $job['every_minute'] = $job['schedule'] !== 'Daily' && $job['interval_minutes'] === 1; @@ -122,8 +124,14 @@ foreach (cronJobRegistry() as $position => $entry) { } } + // Nothing to do here - whatever its last run said, unless it's asked for or going now + if ($job['not_in_use'] !== '' && !in_array($job['state'], ['queued', 'running'], true)) { + $job['state'] = 'unused'; + $job['reason'] = $job['not_in_use']; + } + // When it runs next - nothing to say while cron isn't running, is switched off, or holds this job back - $dispatched = $cron_heard && $cron_on && ($managed_mode === 'active' || in_array($job['name'], $managed_kept, true)); + $dispatched = $cron_heard && $cron_on && $job['state'] !== 'unused' && ($managed_mode === 'active' || in_array($job['name'], $managed_kept, true)); $job['next_run'] = $job_row && $job['enabled'] && $dispatched ? cronJobNextRun($job_row) : null; $jobs[$job['name']] = $job; @@ -131,6 +139,8 @@ foreach (cronJobRegistry() as $position => $entry) { $jobs_on = array_filter($jobs, function ($job) { return $job['enabled']; }); $jobs_off = count($jobs) - count($jobs_on); +// On, with nothing to do here yet +$jobs_unused = count(array_filter($jobs_on, function ($job) { return $job['state'] === 'unused'; })); // Failed on its last run - with an error, or cut off without a word $jobs_failed = array_filter($jobs, function ($job) { return in_array($job['state'], ['failed', 'lost'], true); }); // Failed before and has run since - its error stays until somebody dismisses it @@ -223,7 +233,7 @@ $sort_keys = [ 'schedule' => function ($job) { return $job['schedule'] === 'Daily' ? 100000 + intval(substr($job['daily_at'], 0, 2)) * 60 + intval(substr($job['daily_at'], 3, 2)) : $job['interval_minutes']; }, 'last_run' => function ($job) { return $job['last_run_at'] ? strtotime($job['last_run_at']) : 0; }, // What needs a look first - 'status' => function ($job) { return array_search($job['state'], ['failed', 'lost', 'queued', 'running', 'paused', 'skipped', 'never', 'completed'], true); }, + 'status' => function ($job) { return array_search($job['state'], ['failed', 'lost', 'queued', 'running', 'paused', 'skipped', 'never', 'completed', 'unused'], true); }, ]; if (!isset($sort_keys[$sort])) { $sort = 'schedule'; @@ -247,6 +257,7 @@ $status_looks = [ 'skipped' => ['label' => 'Skipped', 'tone' => 'secondary'], 'paused' => ['label' => 'Paused', 'tone' => 'warning'], 'never' => ['label' => 'Not run yet', 'tone' => 'secondary'], + 'unused' => ['label' => 'Not in use', 'tone' => 'secondary', 'title' => "It has nothing to do here, so cron doesn't run it - it starts by itself once that changes. Run now still works."], ]; ?> @@ -299,7 +310,7 @@ $status_looks = [

- It last ran . job on, and none failed on its last run. + It last ran . job on, and none failed on its last run. Next is , . @@ -352,7 +363,7 @@ $status_looks = [ @@ -384,7 +395,7 @@ $status_looks = [ - + > diff --git a/cron/ai_triage.php b/cron/ai_triage.php index 490fe764c..37fd9fff8 100644 --- a/cron/ai_triage.php +++ b/cron/ai_triage.php @@ -32,6 +32,12 @@ if (intval($row['config_enable_cron'] ?? 0) === 0) { cronJobStop("Cron: is not enabled -- Quitting.."); } +// Triage off, or no AI model to ask - nothing to do (functions/ai_ticket.php) +$ai_triage_not_in_use = aiTriageNotInUse(); +if ($ai_triage_not_in_use !== '') { + cronJobStop($ai_triage_not_in_use); +} + // Development mode: no AI calls on production's key, and no changes to the tickets (functions/dev_mode.php) if (devModeOn()) { cronJobStop("Development mode - AI Triage doesn't run"); diff --git a/cron/cron.php b/cron/cron.php index 03aeceafa..05edc5354 100644 --- a/cron/cron.php +++ b/cron/cron.php @@ -71,13 +71,13 @@ require_once "../includes/cron_jobs.php"; * With $paused (why), the job is not claimed: if it is due, its status says why it hasn't run, * and it is left due - a Run Now request standing - so it runs as soon as it isn't paused. */ -function cronJobClaim($mysqli, array $job, string $paused = ''): bool +/* + * Register the job the first time it is seen, seeded with the schedule it ships with. From here on + * the row is what runs - Maintenance > Cron writes to it. + */ +function cronJobRegister($mysqli, array $job): void { $name = escapeSql($job['name']); - $now = date('Y-m-d H:i:s'); - - // Register the job the first time it is seen, seeded with the schedule it ships with. - // From here on the row is what runs - Maintenance > Cron writes to it. $default_schedule = escapeSql($job['schedule']); $default_interval = intval($job['interval_minutes'] ?? 1); $default_daily_at = isset($job['daily_at']) ? "'" . escapeSql($job['daily_at']) . ":00'" : 'NULL'; @@ -90,6 +90,14 @@ function cronJobClaim($mysqli, array $job, string $paused = ''): bool cron_job_schedule = '$default_schedule', cron_job_interval_minutes = $default_interval, cron_job_daily_at = $default_daily_at"); +} + +function cronJobClaim($mysqli, array $job, string $paused = ''): bool +{ + $name = escapeSql($job['name']); + $now = date('Y-m-d H:i:s'); + + cronJobRegister($mysqli, $job); $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT cron_job_daily_at, cron_job_enabled, cron_job_interval_minutes, cron_job_schedule FROM cron_jobs WHERE cron_job_name = '$name' LIMIT 1")); @@ -221,6 +229,17 @@ $cron_dispatch_started = null; */ $cron_dispatch_stop_cycle = false; +/* + * The jobs with a row, and those asked to Run Now - read once, for the jobs not in use: one of those + * isn't locked, claimed or loaded (includes/cron_jobs.php), only given its row the first time, so + * Maintenance > Cron can change it, and run when somebody asks. + */ +$cron_dispatch_rows = []; +$cron_dispatch_result = mysqli_query($mysqli, "SELECT cron_job_name, cron_job_run_now FROM cron_jobs"); +while ($cron_dispatch_result && ($cron_dispatch_row = mysqli_fetch_assoc($cron_dispatch_result))) { + $cron_dispatch_rows[$cron_dispatch_row['cron_job_name']] = intval($cron_dispatch_row['cron_job_run_now']); +} + register_shutdown_function(function () use (&$cron_dispatch_running, &$cron_dispatch_started, $mysqli) { if ($cron_dispatch_running === null) { return; @@ -243,6 +262,14 @@ foreach (cronJobRegistry() as $cron_dispatch_job) { continue; } + // Nothing to do here - its feature is off or not set up - so it isn't run at all, unless asked to + if (empty($cron_dispatch_rows[$cron_dispatch_job['name']]) && cronJobNotInUse($cron_dispatch_job) !== '') { + if (!isset($cron_dispatch_rows[$cron_dispatch_job['name']])) { + cronJobRegister($mysqli, $cron_dispatch_job); + } + continue; + } + // Locked before the schedule is consulted: if the previous run of this job is still // going there is nothing to decide, and its claim already stands. $cron_dispatch_lock = cronLockAcquire($cron_dispatch_path); diff --git a/functions/ai_ticket.php b/functions/ai_ticket.php index 2cf4e801f..18ea2bd1c 100644 --- a/functions/ai_ticket.php +++ b/functions/ai_ticket.php @@ -335,6 +335,21 @@ function aiTriageMode() { return max(0, min(2, intval($row[0] ?? 0))); } +/* + * Why AI Triage has nothing to do here - it is off, or there is no AI model it could ask - or '' when it + * has. The cron job stops on it, and the dispatcher doesn't run the job at all while it says so + * (includes/cron_jobs.php). + */ +function aiTriageNotInUse() { + if (aiTriageMode() === 0) { + return 'AI triage is off in Settings > Tickets'; + } + if (getAiModel('Tickets') === null) { + return 'No AI model to ask - add one in Admin > AI Models'; + } + return ''; +} + /* The ways new tickets can be triaged, for Settings > Tickets. */ function aiTriageModes() { return [ diff --git a/functions/cron_health.php b/functions/cron_health.php index 65f20dbed..146d2236a 100644 --- a/functions/cron_health.php +++ b/functions/cron_health.php @@ -60,7 +60,8 @@ function cronHealthSaveState(array $state) { /* * The switched-on jobs cron is expected to run, with their rows: name => row + label. - * A job a manager has paused (a read-only or suspended managed instance) isn't expected to. + * A job a manager has paused (a read-only or suspended managed instance) isn't expected to, + * nor one with nothing to do here (cronJobNotInUse(), includes/cron_jobs.php). */ function cronHealthJobs() { global $mysqli; @@ -75,7 +76,7 @@ function cronHealthJobs() { } $jobs = []; foreach (cronJobRegistry() as $entry) { - if (!isset($rows[$entry['name']]) || ($kept !== null && !in_array($entry['name'], $kept, true))) { + if (!isset($rows[$entry['name']]) || ($kept !== null && !in_array($entry['name'], $kept, true)) || cronJobNotInUse($entry) !== '') { continue; } $jobs[$entry['name']] = $rows[$entry['name']] + ['label' => $entry['label']]; diff --git a/includes/cron_jobs.php b/includes/cron_jobs.php index 54419e770..d42563f90 100644 --- a/includes/cron_jobs.php +++ b/includes/cron_jobs.php @@ -29,6 +29,14 @@ * until somebody turns it on in Maintenance > Cron. Used for work an install should opt into * rather than inherit from an upgrade, like the backup job filling a disk overnight. * + * 'not_in_use' => function () { ... } says why the job has nothing to do on this install - its + * feature is off or not set up - or '' when it has (cronJobNotInUse()). The dispatcher doesn't run + * such a job at all: no lock, no claim, no script loaded and nothing written every minute, until + * the answer changes - a Run Now still runs it. Maintenance > Cron shows it as Not in use with the + * reason, and Cron Watch doesn't expect it to run. Make it the same check the job's script stops + * on, cheap and offline (the database, never the network), so nothing the job would have done is + * left undone. + * * 'interval_safe' => false marks a job whose work repeats if the day repeats - nightly's * late fees and overdue reminders fire again on a second run of the same day. Maintenance > * Cron only offers the daily schedule for such a job, and the dispatcher refuses to run @@ -73,6 +81,9 @@ function cronJobRegistry(): array 'description' => 'For an ITFlow managed by another (Admin > Managed By): reports how it is doing and takes what its manager sets. Stops straight away when it isn\'t managed.', 'schedule' => 'Interval', 'interval_minutes' => 1, + 'not_in_use' => function () { + return managedIsManaged() ? '' : 'Not managed by another ITFlow'; + }, ], [ 'name' => 'mail_queue', @@ -82,6 +93,13 @@ function cronJobRegistry(): array 'description' => 'Sends everything ITFlow has queued - invoices, quotes, ticket replies, notifications.', 'schedule' => 'Interval', 'interval_minutes' => 1, + 'not_in_use' => function () { + // Development mode with no test inbox still cancels what's queued (cron/mail_queue.php) + if (trim((string) (cronJobSettings()['config_smtp_provider'] ?? '')) === '' && !(devModeOn() && devModeMailTo() === '')) { + return 'No mail server is set up to send through - Admin > Settings > Mail'; + } + return ''; + }, ], [ 'name' => 'sms_queue', @@ -91,6 +109,9 @@ function cronJobRegistry(): array 'description' => 'Sends the texts waiting to go, a second apart, texts reminders of visits and calls coming up, and tidies the text log - once texting is set up in Admin > Text Messaging.', 'schedule' => 'Interval', 'interval_minutes' => 1, + 'not_in_use' => function () { + return smsProvider() ? '' : "Texting isn't set up - Admin > Text Messaging"; + }, ], [ 'name' => 'rmm_sync', @@ -100,6 +121,14 @@ function cronJobRegistry(): array 'description' => 'Brings in the devices of the RMM clients linked in Admin > RMM Providers, and of the network platforms\' sites linked in Admin > Network Platforms, as assets, and keeps up whether each is online - once one is set up there.', 'schedule' => 'Interval', 'interval_minutes' => 15, + 'not_in_use' => function () { + foreach (rmmProviders(true) as $provider) { + if (rmmProviderUsable($provider)) { + return ''; + } + } + return 'No RMM provider or network platform is set up and on'; + }, ], [ 'name' => 'rmm_alerts', @@ -109,6 +138,17 @@ function cronJobRegistry(): array 'description' => 'Opens a ticket for each new alert from an RMM provider whose alerts open tickets in Admin > RMM Providers, or for each device that goes offline on a network platform in Admin > Network Platforms, and resolves it when the alert clears.', 'schedule' => 'Interval', 'interval_minutes' => 1, + 'not_in_use' => function () { + if (intval(cronJobSettings()['config_module_enable_ticketing'] ?? 0) === 0) { + return 'Ticketing is turned off'; + } + foreach (rmmProviders(true) as $provider) { + if (rmmAlertsOn($provider)) { + return ''; + } + } + return 'No RMM provider or network platform opens tickets for its alerts'; + }, ], [ 'name' => 'ticket_email_parser', @@ -118,6 +158,16 @@ function cronJobRegistry(): array 'description' => 'Reads the support mailbox and turns incoming mail into tickets and replies.', 'schedule' => 'Interval', 'interval_minutes' => 1, + 'not_in_use' => function () { + $settings = cronJobSettings(); + if (intval($settings['config_ticket_email_parse'] ?? 0) === 0) { + return 'Email to ticket is off in Settings > Tickets'; + } + if (trim((string) ($settings['config_imap_provider'] ?? '')) === '') { + return 'No mailbox is set up to read - Admin > Settings > Mail'; + } + return ''; + }, ], [ 'name' => 'ticket_sla', @@ -145,6 +195,9 @@ function cronJobRegistry(): array 'description' => 'Gives new tickets from email, the portal and the API a category and priority by AI, when Settings > Tickets says to. Up to 5 a run.', 'schedule' => 'Interval', 'interval_minutes' => 1, + 'not_in_use' => function () { + return aiTriageNotInUse(); + }, ], [ 'name' => 'managed_instances', @@ -154,6 +207,15 @@ function cronJobRegistry(): array 'description' => 'For an ITFlow that manages others (Admin > Managed Instances): notifies when one stops checking in, opens tickets for their problems when set to, and closes requests that were never answered.', 'schedule' => 'Interval', 'interval_minutes' => 5, + 'not_in_use' => function () { + global $mysqli; + if (!settingsColumnExists($mysqli, 'config_manager_keys')) { + return ''; + } + $connected = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM managed_instances + WHERE managed_instance_archived_at IS NULL AND managed_instance_secret_hash IS NOT NULL"))[0] ?? 0); + return $connected ? '' : 'No instances connected'; + }, ], [ 'name' => 'payment_provider_fees', @@ -163,6 +225,10 @@ function cronJobRegistry(): array 'description' => 'Records what Stripe charged on each card payment as an expense, once Stripe has settled it - while Admin > Payment Providers records its fees.', 'schedule' => 'Interval', 'interval_minutes' => 15, + 'not_in_use' => function () { + global $mysqli; + return mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM payment_providers WHERE payment_provider_name = 'Stripe' LIMIT 1")) ? '' : 'No Stripe payment provider - Admin > Payment Providers'; + }, ], [ 'name' => 'ticket_pictures', @@ -220,6 +286,9 @@ function cronJobRegistry(): array 'description' => 'Asks the git remote whether a newer release exists and stores the answer for Maintenance > Update.', 'schedule' => 'Daily', 'daily_at' => '02:30', + 'not_in_use' => function () { + return file_exists(dirname(__DIR__) . '/.git') ? '' : 'Not a git checkout - there is no remote to check against'; + }, ], [ 'name' => 'cron_watch', @@ -328,3 +397,35 @@ function cronJobNextRun(array $row): ?string return date('Y-m-d H:i:s', max($next, time())); } + +/* + * Why a job has nothing to do here - its 'not_in_use' answer - or '' when it has, or has no such + * check. A check that throws (a table the update hasn't made yet, say) counts as in use: the job runs + * and says for itself what's wrong. + */ +function cronJobNotInUse(array $job): string +{ + if (!isset($job['not_in_use']) || !is_callable($job['not_in_use'])) { + return ''; + } + try { + return trim((string) ($job['not_in_use'])()); + } catch (Throwable $e) { + return ''; + } +} + +/* + * The settings the 'not_in_use' checks read, once a request - the dispatcher asks every minute, and + * cron reads none of config.php's globals for them. + */ +function cronJobSettings(): array +{ + global $mysqli; + static $settings = null; + if ($settings === null) { + $settings = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT config_smtp_provider, config_imap_provider, config_ticket_email_parse, + config_module_enable_ticketing FROM settings WHERE company_id = 1")) ?: []; + } + return $settings; +} From 0c7b521f57690f8c7dd50ade45e20690dc20729b Mon Sep 17 00:00:00 2001 From: johnnyq Date: Wed, 2 Dec 2026 18:58:46 -0500 Subject: [PATCH 3/8] Cron and runs outside it (DB 4.4.2): old crontab lines that run job scripts on their own, like those the install script left in /etc/cron.d/itflow before 26.08, are listed on Maintenance > Cron, Debug and in Cron Watch's email (cronStrayLines()); such a run without a terminal steps aside while cron.php is running, and one cron.php finds holding the lock is recorded on the job (cron_job_outside_at) and said as started by something other than cron.php instead of fallen behind; a lock file the dispatcher can't open fails only that job with the file to delete instead of ending the cycle; cron started as root becomes the user that owns ITFlow's files first (cronLockRunAsOwner()); 26.12.5 changelog and CONTRIBUTING.md --- CHANGELOG.md | 8 +- CONTRIBUTING.md | 2 + admin/cron.php | 40 +++++++- admin/database_updates/4.4.2.php | 21 +++++ cron/cron.php | 71 +++++++++++++- cron/includes/cron_lock.php | 153 ++++++++++++++++++++++++++++--- db.sql | 1 + functions/cron_health.php | 148 +++++++++++++++++++++++++++++- functions/system_health.php | 5 + health.php | 6 +- 10 files changed, 436 insertions(+), 19 deletions(-) create mode 100644 admin/database_updates/4.4.2.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 034fefc6d..dc3aeb7cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,10 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.12.5 -Update from Maintenance > Update as usual. There are no database changes. +Update from Maintenance > Update as usual. This release has one database change, 4.4.2, which keeps when a cron job was last started by something other than cron.php. + +- If ITFlow was installed with the install script before 26.08, `/etc/cron.d/itflow` may still have a line for each job besides the `cron.php` one - the 26.08 upgrade asked for them to come out. Maintenance > Cron now lists any it finds, with the file and line. Take them out: `cron.php` runs every job. Until then they step aside while `cron.php` is running, so nothing runs twice. +- Cron started as root - a crontab line for root, or `php cron/cron.php` typed in a root shell - now runs as the user that owns ITFlow's files, so what it makes is that user's. ### New Features & Updates @@ -15,12 +18,15 @@ Update from Maintenance > Update as usual. There are no database changes. ### Bug Fixes +- A cron job that an old cron line also ran - the line for the Ticket Email Parser or the Mail Queue left in `/etc/cron.d/itflow` by the install script before 26.08 - no longer looks stopped. The old line's run took the job's lock, so `cron.php` passed it by: its last run on Maintenance > Cron stayed days old and Cron Watch emailed that it had fallen behind, while its work got done - and turning it off didn't stop it. Now the old line's run steps aside while `cron.php` is running, Maintenance > Cron lists the lines to take out, with the file and line, and so do Debug and Cron Watch's email. A line ITFlow can't see - in a user's own crontab - is still found from its runs, and said with where to look. +- A cron job whose lock file was made by a run as root no longer stops cron. The web server's user can't open such a file, and every job after it in the list stopped, every minute, without a word - Cron Watch with them - until the server restarted. Now that job fails, saying which file to delete, and the rest run. Cron started as root now becomes the user that owns ITFlow's files first, so it doesn't leave such files - or uploads, backups and git files the web server can't use - behind. - AI Triage no longer runs every minute when AI triage is off in Settings > Tickets or there's no AI model to ask - before, it ran anyway and showed **Completed** every minute with nothing done. ### Developer Updates - `getActiveAgentUserCount()` (`functions/app.php`) leaves out `users.user_service_account = 1` with `serviceAccountsOutSql()`, so `getAgentSeatsTaken()`, `agentUserLimitReached()` and the managed report's `agents.active` do too (the report's list still carries them, with `service` set). `admin/post/users.php` skips `agentUserLimitReached()` for an API / service account in `add_user`, `activate_user`, `restore_user` and `bulk_activate_users`, and `edit_user` refuses turning an active one into an agent at the limit before changing anything (`serviceAccountLeavingNeedsSeat()`, `functions/service_account.php`). Admin > Users keeps New User open at the limit when service accounts are available, and the New User window says one can still be added. - Cron jobs can declare `'not_in_use' => function () { ... }` in `includes/cron_jobs.php`, returning why the job has nothing to do on this install or `''` (`cronJobNotInUse()`, which counts a check that throws as in use; `cronJobSettings()` reads the settings the checks need once a request). `cron/cron.php` reads every job's row and Run Now flag once a cycle and skips a job not in use before its lock and claim - registering its row the first time (`cronJobRegister()`, split out of `cronJobClaim()`) - unless it is asked to Run Now. `cronHealthJobs()` leaves such jobs out, so Cron Watch neither waits on nor flags them, and `admin/cron.php` shows them in a new `unused` state. Checks added for `manager_checkin`, `mail_queue`, `sms_queue`, `rmm_sync`, `rmm_alerts`, `ticket_email_parser`, `ai_triage`, `managed_instances`, `payment_provider_fees` and `update_check`, each the same condition its script stops on. `aiTriageNotInUse()` (`functions/ai_ticket.php`) is new, and `cron/ai_triage.php` now stops on it too. CONTRIBUTING.md has the rule. +- Cron and runs outside it (database 4.4.2, `cron_jobs.cron_job_outside_at`): `cron/includes/cron_lock.php` gains `cronLockFile()`, `cronLockHolder()`, `cronLockFileProblem()`, `cronLockDispatchBeat()`, `cronLockOutsideFile()`, `cronLockAttended()` and `cronLockRunAsOwner()`, run first: started as root on an install whose `cron/cron.php` is another user's, it calls `posix_initgroups()`, `posix_setgid()` and `posix_setuid()` to become that user, or exits saying how to run it. `cronLockAcquire($path, $stamp)` returns null for a lock file it can't open (it used to `die()`, ending the dispatch at that job), and writes `direct` or `terminal` into the file while a run on its own holds it. The dispatcher touches the heartbeat file each cycle; a run on its own without a terminal on STDIN (`stream_isatty()`) while it is under 180 seconds old exits 0, quietly, and touches its `.outside` file. The dispatcher records that file's time, or a lock found held by a `direct` run, as `cron_job_outside_at` (`cronJobNoteOutside()`, at most every ten minutes), and fails a job whose lock can't be opened with `cronLockFileProblem()` as its error (`cronJobLockFailed()`, logged to App Logs once). `functions/cron_health.php`: `cronStrayLines()` reads `/etc/crontab` and the `/etc/cron.d` files cron would read for lines that run this install's job scripts on their own (anything in `cron/` but `cron.php`, and the old `scripts/cron*.php` and `cron_*.php`), `cronStrayText()`, `cronStrayWhat()`, `cronOutsideJobs()` (the last `CRON_HEALTH_OUTSIDE_HOURS`, 26), `cronOutsideReady()` and `cronFilesOwner()`; `cronHealthProblems()` adds a `stray` problem and an `outside` one per job the lines don't cover, and doesn't call a job overdue while it is run outside. `health.php` leaves both kinds out, so an uptime monitor doesn't go red for them. Maintenance > Cron has a card for the lines (`data-cron-stray`, `data-cron-stray-line`) and a note on each job run outside (`data-cron-outside`); Debug's Background jobs adds Old cron lines. CONTRIBUTING.md has the rule. ## [26.12.4] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 503015d98..92036aa27 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -110,6 +110,8 @@ A job can also ship switched off with `'enabled' => 0` in the registry. The row A job whose work hangs on a feature that can be off or not set up - texting, an RMM provider, AI triage, a mailbox - declares `'not_in_use' => function () { ... }` in `includes/cron_jobs.php`, returning why it has nothing to do or `''` when it has. The dispatcher then doesn't lock, claim or load it at all, Maintenance > Cron shows it as **Not in use** with the reason, and Cron Watch doesn't expect it to run. Make it the same check the script stops on - cheap, and the database only, never the network - so leaving the job out never leaves its work undone; the script keeps its own check, for Run Now and for running it by hand. +A job's script can still be run on its own - `php cron/mail_queue.php`, from **Copy the Command to Run It** - and before 26.08 each one had a crontab line of its own, which some installs keep. Such a run without a terminal while `cron.php` has run in the last three minutes steps aside: the dispatcher runs the job, on its schedule and under its switch, and records that something else tried (`cron_job_outside_at`), and Maintenance > Cron, Debug and Cron Watch name the lines in `/etc/crontab` and `/etc/cron.d` to take out. Run from a terminal, a script always runs. Started as root, cron becomes the user that owns ITFlow's files before it makes anything (`cronLockRunAsOwner()`), and a lock file the dispatcher can't open fails only that job. Don't take any of that away: a lock file left by another user used to stop every job after it, silently, until the server restarted. + `config_enable_cron` is a second, coarser switch that sits above the per-job ones. It is **not** enforced by the dispatcher — every job checks it in its own header and stops itself with `cronJobStop()`. A new job has to make that check too; one that skips it keeps running on an install that believes cron is off, which is exactly the trap `ticket_email_parser` and `ticket_sla` sat in until 26.08. Be precise about what it does, because it is easy to oversell. It is **not** a guard on restored data: a full backup dumps the `settings` table, so a restored copy comes back with `config_enable_cron = 1` alongside every enabled `cron_jobs` row, exactly as production had them. What it gives you is one reversible bit — the fastest way to stop an install acting on live data once you have noticed, and the only way to stop everything without editing seven rows. diff --git a/admin/cron.php b/admin/cron.php index 9b8d0554a..5b37ca537 100644 --- a/admin/cron.php +++ b/admin/cron.php @@ -65,7 +65,7 @@ $tidy_reason = function ($reason) { $job_rows = []; $sql = mysqli_query($mysqli, "SELECT cron_job_daily_at, cron_job_enabled, cron_job_id, cron_job_interval_minutes, cron_job_last_duration, cron_job_last_error, cron_job_last_error_at, cron_job_last_run_at, cron_job_last_status, - cron_job_name, cron_job_run_now, cron_job_schedule FROM cron_jobs"); + cron_job_name, cron_job_run_now, cron_job_schedule" . (cronOutsideReady() ? ', cron_job_outside_at' : '') . " FROM cron_jobs"); while ($job_row = mysqli_fetch_assoc($sql)) { $job_rows[$job_row['cron_job_name']] = $job_row; } @@ -100,6 +100,8 @@ foreach (cronJobRegistry() as $position => $entry) { 'last_error_at' => $job_row['cron_job_last_error_at'] ?? null, 'reason' => '', 'not_in_use' => cronJobNotInUse($entry), + // Run by something other than cron.php lately - an old crontab line (functions/cron_health.php) + 'outside_at' => !empty($job_row['cron_job_outside_at']) && strtotime($job_row['cron_job_outside_at']) > time() - CRON_HEALTH_OUTSIDE_HOURS * 3600 ? $job_row['cron_job_outside_at'] : null, ]; $job['schedule_text'] = cronJobScheduleDescription($job['schedule'], $job['interval_minutes'], $job['daily_at']); $job['every_minute'] = $job['schedule'] !== 'Daily' && $job['interval_minutes'] === 1; @@ -137,6 +139,10 @@ foreach (cronJobRegistry() as $position => $entry) { $jobs[$job['name']] = $job; } +// Old crontab lines that run job scripts on their own, besides cron.php +$stray_lines = cronStrayLines(); +$stray_jobs = array_filter(array_column($stray_lines, 'job')); + $jobs_on = array_filter($jobs, function ($job) { return $job['enabled']; }); $jobs_off = count($jobs) - count($jobs_on); // On, with nothing to do here yet @@ -344,6 +350,33 @@ $status_looks = [

+ + +
+
+
+ +
+
Old cron lines run some jobs a second time
+

+ Before 26.08 each job had a cron line of its own. These are still in the server's cron files and start their jobs on their own, besides + cron.php. While cron.php is running they step aside, so the schedules and switches here hold - but whenever it isn't, they run their jobs outside them. Take them out - cron.php runs every job now: +

+ +
+
, line -
+
+
+ +

+ Put # in front of each, or delete the file if every line in it is one of these - with sudo nano, say. Then this goes by itself. +

+
+
+
+
+ +
@@ -449,6 +482,11 @@ $status_looks = [
+ +
Also started by something other than cron.php, last - + crontab -l, as root and as ' . escapeHtml(cronFilesOwner()) . '.' ?> Take it out - while cron.php runs, it steps aside.
+ +
diff --git a/admin/database_updates/4.4.2.php b/admin/database_updates/4.4.2.php new file mode 100644 index 000000000..bb76089d5 --- /dev/null +++ b/admin/database_updates/4.4.2.php @@ -0,0 +1,21 @@ + Cron and Cron Watch say so (functions/cron_health.php). + * + * Re-runnable: the column is made only where it isn't there. + */ + +defined('FROM_DB_UPDATER') || die("Direct file access is not allowed"); + + $itflow_cron_outside = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'cron_jobs' AND COLUMN_NAME = 'cron_job_outside_at' LIMIT 1"); + if (!$itflow_cron_outside || mysqli_num_rows($itflow_cron_outside) === 0) { + mysqli_query($mysqli, "ALTER TABLE `cron_jobs` ADD `cron_job_outside_at` datetime DEFAULT NULL AFTER `cron_job_last_error_at`"); + } diff --git a/cron/cron.php b/cron/cron.php index 05edc5354..8d213cc11 100644 --- a/cron/cron.php +++ b/cron/cron.php @@ -161,6 +161,51 @@ function cronJobClaim($mysqli, array $job, string $paused = ''): bool return mysqli_affected_rows($mysqli) === 1; } +/* + * Note that $job was run by something other than cron.php at $seen (a timestamp) - an old crontab line that + * runs its script on its own (cron/includes/cron_lock.php). Written at most every ten minutes: such a line + * runs every minute, and Maintenance > Cron and Cron Watch only need to know it still does. + */ +function cronJobNoteOutside($mysqli, array $job, int $seen, array &$rows): void +{ + if (!cronOutsideReady()) { + return; + } + $last = $rows[$job['name']]['outside_at'] ?? null; + if ($last && strtotime($last) > $seen - 600) { + return; + } + if (!isset($rows[$job['name']])) { + cronJobRegister($mysqli, $job); + } + $at = date('Y-m-d H:i:s', $seen); + mysqli_query($mysqli, "UPDATE cron_jobs SET cron_job_outside_at = '$at' WHERE cron_job_name = '" . escapeSql($job['name']) . "'"); + $rows[$job['name']]['outside_at'] = $at; +} + +/* + * The job's lock file can't be opened - another user made it, root most likely. The job can't run until it's + * gone, so it fails, saying which file to delete, and the cycle carries on with the next job. Logged when it + * starts, and its error's time kept within the hour while it lasts - not rewritten every minute. + */ +function cronJobLockFailed($mysqli, array $job, string $problem): void +{ + cronJobRegister($mysqli, $job); + $name = escapeSql($job['name']); + $error = escapeSql(substr($problem, 0, 1000)); + $now = date('Y-m-d H:i:s'); + $hour_ago = date('Y-m-d H:i:s', time() - 3600); + mysqli_query($mysqli, "UPDATE cron_jobs SET cron_job_last_status = 'Failed', cron_job_last_error = '$error', cron_job_last_error_at = '$now' + WHERE cron_job_name = '$name' AND NOT (cron_job_last_status <=> 'Failed' AND cron_job_last_error <=> '$error' AND cron_job_last_error_at > '$hour_ago')"); + if (mysqli_affected_rows($mysqli) === 1) { + try { + logApp("Cron", "error", "Cron job {$job['name']} can't run: $problem"); + } catch (Throwable $e) { + // Logging must never end the cycle it is reporting on + } + } +} + /* * Record how a job ended. The status is the outcome of the run that just happened; the error * is sticky and survives later successes, because the run that failed is usually long gone by @@ -211,6 +256,10 @@ if (backupRestoreInProgress()) { // "no job was due" apart from "nothing has run this since the server was rebuilt". mysqli_query($mysqli, "UPDATE settings SET config_cron_last_dispatch_at = '" . date('Y-m-d H:i:s') . "' WHERE company_id = 1"); +// And one a job's script run on its own can see without the database - while it's fresh, such a run steps +// aside and leaves this to run the job (cron/includes/cron_lock.php) +@touch(cronLockDispatchBeat()); + // Best effort: ask the server not to hang up while a long job is quiet. if (function_exists('backupDbHoldOpen')) { backupDbHoldOpen($mysqli); @@ -235,9 +284,9 @@ $cron_dispatch_stop_cycle = false; * Maintenance > Cron can change it, and run when somebody asks. */ $cron_dispatch_rows = []; -$cron_dispatch_result = mysqli_query($mysqli, "SELECT cron_job_name, cron_job_run_now FROM cron_jobs"); +$cron_dispatch_result = mysqli_query($mysqli, "SELECT cron_job_name, cron_job_run_now, " . (cronOutsideReady() ? 'cron_job_outside_at' : 'NULL AS cron_job_outside_at') . " FROM cron_jobs"); while ($cron_dispatch_result && ($cron_dispatch_row = mysqli_fetch_assoc($cron_dispatch_result))) { - $cron_dispatch_rows[$cron_dispatch_row['cron_job_name']] = intval($cron_dispatch_row['cron_job_run_now']); + $cron_dispatch_rows[$cron_dispatch_row['cron_job_name']] = ['run_now' => intval($cron_dispatch_row['cron_job_run_now']), 'outside_at' => $cron_dispatch_row['cron_job_outside_at']]; } register_shutdown_function(function () use (&$cron_dispatch_running, &$cron_dispatch_started, $mysqli) { @@ -262,8 +311,14 @@ foreach (cronJobRegistry() as $cron_dispatch_job) { continue; } + // A run of its script on its own stepped aside for this one since we last looked - an old crontab line + $cron_dispatch_outside = @filemtime(cronLockOutsideFile($cron_dispatch_path)); + if ($cron_dispatch_outside) { + cronJobNoteOutside($mysqli, $cron_dispatch_job, $cron_dispatch_outside, $cron_dispatch_rows); + } + // Nothing to do here - its feature is off or not set up - so it isn't run at all, unless asked to - if (empty($cron_dispatch_rows[$cron_dispatch_job['name']]) && cronJobNotInUse($cron_dispatch_job) !== '') { + if (empty($cron_dispatch_rows[$cron_dispatch_job['name']]['run_now']) && cronJobNotInUse($cron_dispatch_job) !== '') { if (!isset($cron_dispatch_rows[$cron_dispatch_job['name']])) { cronJobRegister($mysqli, $cron_dispatch_job); } @@ -273,7 +328,17 @@ foreach (cronJobRegistry() as $cron_dispatch_job) { // Locked before the schedule is consulted: if the previous run of this job is still // going there is nothing to decide, and its claim already stands. $cron_dispatch_lock = cronLockAcquire($cron_dispatch_path); + if ($cron_dispatch_lock === null) { + // A lock file another user made - this job fails, saying which, and the rest of the cycle runs + cronJobLockFailed($mysqli, $cron_dispatch_job, cronLockFileProblem($cron_dispatch_path)); + continue; + } if ($cron_dispatch_lock === false) { + // Taken by its script run on its own, unattended - an old crontab line, before this cycle's heartbeat + // was there for it to see - is worth saying; one run by hand, or still going from before, isn't + if (cronLockHolder($cron_dispatch_path) === 'direct') { + cronJobNoteOutside($mysqli, $cron_dispatch_job, time(), $cron_dispatch_rows); + } continue; } diff --git a/cron/includes/cron_lock.php b/cron/includes/cron_lock.php index ca47f20a5..e2fe1b6f7 100644 --- a/cron/includes/cron_lock.php +++ b/cron/includes/cron_lock.php @@ -37,6 +37,32 @@ * itself early - that would take the rest of the cycle down with it. cronJobStop() is * the replacement: it exits when the script was run directly and unwinds back to the * dispatcher when it wasn't. + * + * RUNS OUTSIDE THE DISPATCHER + * + * Before 26.08 each job had a crontab line of its own, and an install that kept one - the + * install script wrote them to /etc/cron.d/itflow - runs that job twice a minute: once on + * its own, once by cron.php. The run on its own held the lock, so the dispatcher passed the + * job by, its row never changed, Maintenance > Cron showed it last running days ago and + * Cron Watch said it had fallen behind - while its work got done, and its Off switch was + * ignored. So now: + * - the dispatcher touches a heartbeat file each cycle (cronLockDispatchBeat()), and a run + * on its own with no terminal - cron, a timer - while it is fresh steps aside: cron.php + * runs the job, on its schedule. It leaves a mark (cronLockOutsideFile()) the dispatcher + * records on the job's row, and Maintenance > Cron and Cron Watch say so. An install + * with only its old lines and no cron.php line runs them as before, and a job run by + * hand from a terminal always runs. + * - a run on its own writes "direct" into its lock file, so a dispatcher that finds the + * lock taken can tell who has it. + * + * RUN AS ROOT + * + * A run as root left its lock files, and whatever else it wrote, owned by root. The web + * server's user can't open a lock file root made in /tmp, and every later run of that job + * - and, before 26.12.5, the whole cycle behind it - stopped there until the server was + * restarted. Started as root, cron now becomes the user that owns ITFlow's files first + * (cronLockRunAsOwner()); and a lock file that can't be opened fails that one job, saying + * which file to delete (cronLockAcquire()'s null). */ /* @@ -66,20 +92,31 @@ function cronJobStop(string $message = '', int $exit_code = 0): void } /* - * Take the single-run lock for a cron script. $script_path must be the script's own - * __FILE__ (or the same resolved path when the dispatcher takes it on the job's behalf), - * because that path is what the lock is named after. - * - * Returns the open handle on success, or false when another run holds the lock. The - * handle must stay open for as long as the lock is wanted - closing it releases the lock. + * A cron script's lock file. $script_path must be the script's own __FILE__ (or the same + * resolved path when the dispatcher takes it on the job's behalf), because that path is + * what the lock is named after. */ -function cronLockAcquire(string $script_path) +function cronLockFile(string $script_path): string { - $lock_file = sys_get_temp_dir() . '/itflow_cron_' . md5($script_path) . '.lock'; + return sys_get_temp_dir() . '/itflow_cron_' . md5($script_path) . '.lock'; +} - $lock_handle = fopen($lock_file, 'c'); +/* + * Take the single-run lock for a cron script. Returns the open handle on success, false + * when another run holds the lock, or null when the lock file can't be opened at all - one + * another user made, usually root (cronLockFileProblem() says what to do). The handle must + * stay open for as long as the lock is wanted - closing it releases the lock. + * + * $stamp is written into the file while the lock is held: "direct" for a run on its own, + * '' for the dispatcher - so whoever finds the lock taken can tell who has it. + */ +function cronLockAcquire(string $script_path, string $stamp = '') +{ + $lock_file = cronLockFile($script_path); + + $lock_handle = @fopen($lock_file, 'c'); if ($lock_handle === false) { - die("Cannot open the cron lock file at $lock_file - check permissions and open_basedir.\n"); + return null; } if (!flock($lock_handle, LOCK_EX | LOCK_NB)) { @@ -88,9 +125,88 @@ function cronLockAcquire(string $script_path) return false; } + // Ours now - say whose, for anyone who finds it taken (a stamp left by a run before goes) + @ftruncate($lock_handle, 0); + if ($stamp !== '') { + @fwrite($lock_handle, $stamp); + @fflush($lock_handle); + } + return $lock_handle; } +/* Who holds a lock found taken: 'direct' (unattended), 'terminal' (run by hand) or '' (the dispatcher, or unknown). */ +function cronLockHolder(string $script_path): string +{ + $stamp = trim((string) @file_get_contents(cronLockFile($script_path), false, null, 0, 100)); + return in_array($stamp, ['direct', 'terminal'], true) ? $stamp : ''; +} + +/* Why a lock file can't be opened, and what to do about it - for the job's error. */ +function cronLockFileProblem(string $script_path): string +{ + $lock_file = cronLockFile($script_path); + $owner = @fileowner($lock_file); + $name = $owner !== false && function_exists('posix_getpwuid') ? (posix_getpwuid($owner)['name'] ?? "user $owner") : ''; + if ($owner === false) { + return "Can't make its lock file, $lock_file - check that the temp folder can be written to, and open_basedir."; + } + return "Can't open its lock file, $lock_file" . ($name !== '' ? " - it belongs to $name, from a run as that user" : '') + . ". Delete it - it's only a lock: sudo rm $lock_file - or restart the server. Cron runs as the user that owns ITFlow's files from now on."; +} + +/* The heartbeat the dispatcher touches each cycle, for runs on their own to find (one per install). */ +function cronLockDispatchBeat(): string +{ + return sys_get_temp_dir() . '/itflow_cron_dispatch_' . md5(dirname(__DIR__, 2)) . '.beat'; +} + +/* The mark a run on its own leaves when it steps aside or holds the lock - its mtime is when. */ +function cronLockOutsideFile(string $script_path): string +{ + return sys_get_temp_dir() . '/itflow_cron_' . md5($script_path) . '.outside'; +} + +/* Whether a person started this - a terminal on its input. Cron, timers and scripts have none. */ +function cronLockAttended(): bool +{ + return defined('STDIN') && function_exists('stream_isatty') && @stream_isatty(STDIN); +} + +/* + * Started as root on an install whose files are another user's: become that user, so nothing + * this run makes - lock files, uploads, backups, git's own files - ends up root's, where the + * web server and the next run can't use it. Root's own install (files owned by root) runs as + * root, as before. An owner with no account here - a container's bind mount, say - is taken + * with the files' group. If it can't be done, or there are no posix functions to do it with, + * the run carries on as root, as it did before 26.12.5, and says so: stopping cron there would + * be worse than the files it leaves. + */ +function cronLockRunAsOwner(): void +{ + if (!function_exists('posix_geteuid') || posix_geteuid() !== 0) { + return; + } + $owner = @fileowner(dirname(__DIR__) . '/cron.php'); + if ($owner === false || $owner === 0) { + return; + } + $user = posix_getpwuid($owner) ?: null; + $group = $user ? intval($user['gid']) : @filegroup(dirname(__DIR__) . '/cron.php'); + $name = $user['name'] ?? "user $owner"; + $switched = $group !== false + && (!$user || @posix_initgroups($user['name'], $group)) + && @posix_setgid($group) + && @posix_setuid($owner) + && posix_geteuid() === $owner; + if (!$switched) { + fwrite(STDERR, "Cron was started as root and couldn't become $name, the user that owns ITFlow's files, so it runs as root - run it as that user: sudo -u $name php " . ($_SERVER['argv'][0] ?? 'cron/cron.php') . "\n"); + } +} + +// First, before anything here can make a file +cronLockRunAsOwner(); + /* * Release a lock taken by cronLockAcquire(). Only the dispatcher needs this - a direct run * holds its lock until the process ends and the kernel drops it. @@ -111,7 +227,22 @@ if (!defined('ITFLOW_CRON_DISPATCHER')) { die("Cron scripts must set \$cron_lock_script = __FILE__ before requiring cron/includes/cron_lock.php.\n"); } - $cron_lock_handle = cronLockAcquire($cron_lock_script); + $cron_lock_attended = cronLockAttended(); + + // Unattended - a crontab line from before 26.08, say - while cron.php is running: cron.php runs this + // job on its schedule, so this run steps aside, and leaves a mark for Maintenance > Cron to say so + $cron_lock_beat = @filemtime(cronLockDispatchBeat()); + if (!$cron_lock_attended && $cron_lock_beat && time() - $cron_lock_beat < 180) { + @touch(cronLockOutsideFile($cron_lock_script)); + exit(0); + } + + $cron_lock_handle = cronLockAcquire($cron_lock_script, $cron_lock_attended ? 'terminal' : 'direct'); + + if ($cron_lock_handle === null) { + echo cronLockFileProblem($cron_lock_script) . "\n"; + exit(1); + } if ($cron_lock_handle === false) { // Exit silently. On a per-minute schedule, finding a previous run still going is diff --git a/db.sql b/db.sql index 511998c2a..0ad8d4dba 100644 --- a/db.sql +++ b/db.sql @@ -1449,6 +1449,7 @@ CREATE TABLE `cron_jobs` ( `cron_job_last_status` varchar(200) DEFAULT NULL, `cron_job_last_error` text DEFAULT NULL, `cron_job_last_error_at` datetime DEFAULT NULL, + `cron_job_outside_at` datetime DEFAULT NULL, PRIMARY KEY (`cron_job_id`), UNIQUE KEY `cron_job_name` (`cron_job_name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; diff --git a/functions/cron_health.php b/functions/cron_health.php index 146d2236a..5d7f938ad 100644 --- a/functions/cron_health.php +++ b/functions/cron_health.php @@ -21,6 +21,8 @@ // A job still running after this many minutes counts as stuck const CRON_HEALTH_STUCK_MINUTES = 120; +// A job run by something other than cron.php is said so for this long after the last time - a day and a bit, for a nightly line +const CRON_HEALTH_OUTSIDE_HOURS = 26; // The dispatcher writes its heartbeat every minute - older than this and cron isn't running const CRON_HEALTH_HEARTBEAT_SECONDS = 300; @@ -70,7 +72,7 @@ function cronHealthJobs() { $kept = $mode === 'active' ? null : (MANAGED_KEEP_JOBS[$mode] ?? []); $rows = []; $result = mysqli_query($mysqli, "SELECT cron_job_name, cron_job_schedule, cron_job_interval_minutes, cron_job_daily_at, cron_job_last_run_at, - cron_job_last_status, cron_job_last_error, cron_job_last_error_at FROM cron_jobs WHERE cron_job_enabled = 1"); + cron_job_last_status, cron_job_last_error, cron_job_last_error_at, " . (cronOutsideReady() ? 'cron_job_outside_at' : 'NULL AS cron_job_outside_at') . " FROM cron_jobs WHERE cron_job_enabled = 1"); while ($row = mysqli_fetch_assoc($result)) { $rows[$row['cron_job_name']] = $row; } @@ -146,6 +148,23 @@ function cronHealthProblems($fresh = false) { return $problems; } + // Old crontab lines that run job scripts on their own, and jobs found run that way + $outside = cronOutsideJobs(); + $stray = cronStrayLines(); + if ($stray) { + $problems[] = ['key' => 'stray:' . md5(json_encode(array_column($stray, 'text'))), 'job' => '', 'label' => 'Cron', 'kind' => 'stray', + 'text' => cronStrayText($stray), + 'detail' => implode("\n", array_map(function ($line) { return $line['file'] . ' line ' . $line['line'] . ': ' . $line['text']; }, $stray))]; + } + $stray_jobs = array_filter(array_column($stray, 'job')); + foreach ($outside as $name => $job) { + if (!in_array($name, $stray_jobs, true)) { + $problems[] = ['key' => "outside:$name", 'job' => $name, 'label' => $job['label'], 'kind' => 'outside', 'detail' => '', + 'text' => $job['label'] . ' is started by something other than cron.php too - last ' . timeAgo($job['at']) + . '. A crontab line from before 26.08, most likely - crontab -l, as root and as ' . cronFilesOwner() . '. Take it out: cron.php runs it now.']; + } + } + foreach (cronHealthJobs() as $name => $job) { $label = $job['label']; $status = (string) $job['cron_job_last_status']; @@ -168,7 +187,8 @@ function cronHealthProblems($fresh = false) { } elseif ($status === 'Running' && time() - strtotime($job['cron_job_last_run_at']) > CRON_HEALTH_STUCK_MINUTES * 60) { $problems[] = ['key' => "stuck:$name", 'job' => $name, 'label' => $label, 'kind' => 'stuck', 'detail' => '', 'text' => "$label started " . timeAgo($job['cron_job_last_run_at']) . ' and is still running - it may have stopped part way.']; - } elseif ($running && cronHealthOverdue($job)) { + } elseif ($running && cronHealthOverdue($job) && !isset($outside[$name])) { + // Behind because something else runs it is said above, as what it is // Late only means something while cron is running - otherwise "isn't running" says it all $problems[] = ['key' => "overdue:$name", 'job' => $name, 'label' => $label, 'kind' => 'overdue', 'detail' => '', 'text' => "$label is behind - it last ran " . timeAgo($job['cron_job_last_run_at']) . '.']; @@ -341,3 +361,127 @@ function cronHealthUrl() { global $config_base_url; return 'https://' . $config_base_url . '/health.php?key=' . cronHealthKey(); } + +/** Whether the 4.4.2 update has run - cron_jobs.cron_job_outside_at is there. */ +function cronOutsideReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + if (defined('CURRENT_DATABASE_VERSION')) { + $version = CURRENT_DATABASE_VERSION; + } else { + $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"); + $version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0'; + } + $ready = version_compare($version, '4.4.2', '>='); + } + return $ready; +} + +/* + * The jobs found run by something other than cron.php in the last CRON_HEALTH_OUTSIDE_HOURS - an old + * crontab line that runs the job's script on its own (cron/includes/cron_lock.php): name => ['label', 'at']. + * Whether the job is on or off - a line that runs a job switched off is the point. + */ +function cronOutsideJobs() { + global $mysqli; + if (!cronOutsideReady()) { + return []; + } + require_once __DIR__ . '/../includes/cron_jobs.php'; + $registry = cronJobRegistryByName(); + $since = date('Y-m-d H:i:s', time() - CRON_HEALTH_OUTSIDE_HOURS * 3600); + $jobs = []; + $result = mysqli_query($mysqli, "SELECT cron_job_name, cron_job_outside_at FROM cron_jobs WHERE cron_job_outside_at > '$since'"); + while ($result && ($row = mysqli_fetch_assoc($result))) { + if (isset($registry[$row['cron_job_name']])) { + $jobs[$row['cron_job_name']] = ['label' => $registry[$row['cron_job_name']]['label'], 'at' => $row['cron_job_outside_at']]; + } + } + return $jobs; +} + +/* + * Lines in the system's cron files - /etc/crontab and /etc/cron.d - that run one of this install's job scripts + * on its own: a script in cron/ other than cron.php, or the scripts/cron*.php and cron_*.php from before 26.08. + * The install script wrote them to /etc/cron.d/itflow, and since 26.08 cron.php runs every job, so they only run + * the job a second time, outside its schedule and its Off switch. Each: file, line (from 1), text, script (as the + * line names it), job and label (the job it is for), gone (the script isn't there any more - the line only errors). + * A file cron itself skips - a name + * with a dot, like itflow.bak - isn't read, and nor is anything this user can't read (users' own crontabs). + * $files is for tests. + */ +function cronStrayLines(?array $files = null) { + $root = dirname(__DIR__); + $roots = array_values(array_unique(array_filter([$root, (string) realpath($root)]))); + if ($files === null) { + $files = ['/etc/crontab']; + foreach ((@scandir('/etc/cron.d') ?: []) as $name) { + if (preg_match('/^[A-Za-z0-9_-]+$/', $name)) { + $files[] = "/etc/cron.d/$name"; + } + } + } + require_once __DIR__ . '/../includes/cron_jobs.php'; + $by_script = []; + foreach (cronJobRegistry() as $job) { + $by_script[$job['script']] = $job; + } + $found = []; + foreach ($files as $file) { + if (!@is_file($file) || !@is_readable($file)) { + continue; + } + foreach ((@file($file, FILE_IGNORE_NEW_LINES) ?: []) as $i => $text) { + $text = trim($text); + if ($text === '' || $text[0] === '#') { + continue; + } + foreach ($roots as $install) { + // This install's folder - /var/www/itflow/cron/x.php, or cd /var/www/itflow && php cron/x.php - not /var/www/itflow2's + if (!preg_match('#' . preg_quote(rtrim($install, '/'), '#') . '(?=[/\s;&|"\']|$)#', $text) + || !preg_match('#(?:^|[\s/])(cron/(?!cron\.php\b)[A-Za-z0-9_]+\.php|scripts/cron[A-Za-z0-9_]*\.php|cron_[A-Za-z0-9_]+\.php)#', $text, $match)) { + continue; + } + // cron/mail_queue.php, or what it was called before: scripts/cron_mail_queue.php, cron_mail_queue.php + $script = preg_replace('#^(?:cron/|scripts/)?(?:cron_)?#', '', $match[1]); + $job = $by_script[$script] ?? null; + $found[] = ['file' => $file, 'line' => $i + 1, 'text' => mb_substr($text, 0, 300), 'script' => $match[1], + 'job' => $job['name'] ?? '', 'label' => $job['label'] ?? '', 'gone' => !is_file(rtrim($install, '/') . '/' . $match[1])]; + break; + } + } + } + return $found; +} + +/* What cronStrayLines() found, in a sentence: which file and lines, and what they run. */ +function cronStrayText(array $stray) { + $by_file = []; + foreach ($stray as $line) { + $by_file[$line['file']][] = 'line ' . $line['line'] . ' (' . cronStrayWhat($line) . ')'; + } + $where = []; + foreach ($by_file as $file => $lines) { + $where[] = $file . ' ' . implode(', ', $lines); + } + return 'Old cron lines run ITFlow\'s jobs on their own, besides cron.php: ' . implode('; ', $where) + . '. Take them out - cron.php runs every job now. While it runs they step aside, but whenever it doesn\'t, they run their jobs outside the schedules and switches on Maintenance > Cron.'; +} + +/* The user that owns ITFlow's files - who cron should run as. */ +function cronFilesOwner() { + $owner = @fileowner(dirname(__DIR__) . '/cron/cron.php'); + if ($owner !== false && function_exists('posix_getpwuid')) { + return (string) (posix_getpwuid($owner)['name'] ?? 'the user that owns ITFlow\'s files'); + } + return 'the user that owns ITFlow\'s files'; +} + +/* What a stray line is for: "Mail Queue", or "an old Mail Queue script that no longer exists - it only errors". */ +function cronStrayWhat(array $line) { + if (!$line['gone']) { + return $line['label'] !== '' ? $line['label'] : $line['script']; + } + return 'an old ' . ($line['label'] !== '' ? $line['label'] . ' ' : '') . 'script that no longer exists - it only errors'; +} diff --git a/functions/system_health.php b/functions/system_health.php index 269a63a5e..eaa872c45 100644 --- a/functions/system_health.php +++ b/functions/system_health.php @@ -216,6 +216,11 @@ function healthJobChecks() { } else { $items[] = healthItem('Cron', 'ok', 'Last ran ' . healthAgo($heard)); } + // Old crontab lines that run job scripts on their own, besides cron.php (functions/cron_health.php) + $stray = function_exists('cronStrayLines') ? cronStrayLines() : []; + if ($stray) { + $items[] = healthItem('Old cron lines', 'warning', count($stray) . ' still there', escapeHtml(cronStrayText($stray)), 'cron.php', 'Maintenance > Cron'); + } if (empty($settings['config_enable_cron'])) { $items[] = healthItem('Cron switch', 'danger', 'Off', 'Every job stops itself while it is off. Turn it on, unless this is a copy that mustn\'t email clients or charge cards.', 'cron.php', 'Maintenance > Cron'); } diff --git a/health.php b/health.php index 24e42248b..49a3d36a5 100644 --- a/health.php +++ b/health.php @@ -39,7 +39,11 @@ if ($health_key === '' || !hash_equals($health_key, $health_given)) { } try { - $health_problems = cronHealthProblems(); + // Old cron lines that run jobs a second time are for tidying up, not for waking someone - the jobs still run + // (Maintenance > Cron and Cron Watch's email say so) + $health_problems = array_values(array_filter(cronHealthProblems(), function ($problem) { + return !in_array($problem['kind'], ['stray', 'outside'], true); + })); } catch (Throwable $e) { http_response_code(503); exit("PROBLEM\n- The health check could not read the database\n"); From 2d2574ab4965310590f0ec2d41e74f8174fd2719 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Wed, 2 Dec 2026 22:31:37 -0500 Subject: [PATCH 4/8] Passkeys and the credential vault: a passkey that gives its PRF secret at sign-in but has no copy of the vault key that opens with it (added where the browser didn't give the secret then, like Windows Hello before Chrome 147) has the secret kept for the session (passkeySealKeep(), encrypted with its key in the passkey_seal_key cookie) and a copy sealed to it once the vault opens (passkeySealKept()), so it opens the vault by itself from the next sign-in; the Unlock window offers Unlock with a Passkey when the agent has a passkey that opens the vault (vaultUnlockPasskey(), passkeyVerify() with an unlock challenge, vault_unlock_passkey_options and vault_unlock_passkey in agent/ajax.php); 26.12.5 changelog --- CHANGELOG.md | 3 + agent/ajax.php | 18 ++++ agent/user/post/profile.php | 2 +- functions/credential.php | 6 +- functions/passkey.php | 192 ++++++++++++++++++++++++++++++++++-- includes/footer.php | 25 ++++- js/credentials.js | 28 ++++-- js/passkey.js | 69 +++++++++++++ login_passkey.php | 13 ++- post/logout.php | 4 + 10 files changed, 332 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dc3aeb7cf..44f2ed960 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,18 +15,21 @@ Update from Maintenance > Update as usual. This release has one database change, - Cron leaves alone the jobs that have nothing to do on your ITFlow - what they work with is switched off or isn't set up: AI Triage, Text Messages, RMM Sync and RMM Alerts, the Ticket Email Parser with email to ticket off or no mailbox, the Mail Queue with no mail server, Payment Provider Fees without Stripe, the Update Check on an install that isn't a git checkout, and Manager Check-in and Managed Instances when there's nothing connected. Before, each one started every minute only to stop itself. Maintenance > Cron shows them as **Not in use**, with why under each; they start by themselves once that changes, and **Run Now** still runs them. Cron Watch doesn't email about them falling behind. - An API / service account no longer takes a seat on the agent user limit - the one your hosting provider sets, or one set for your installation. Nobody signs in as it: it's the login an integration's API keys act as. You can add one, enable one or restore one when every seat is taken, and Admin > Users shows the seats without them. Turning one back into an agent who signs in takes a seat, so there has to be one free. A hosted instance's manager sees it the same way: its seats taken leave API accounts out, and its list of agents marks them. +- Unlock your credentials with a passkey. When a passkey sign-in leaves them locked although your passkey opens them - signing in by scanning a QR code with your phone, or some password managers' autofill - the Unlock window offers **Unlock with a Passkey** before your password, with any passkey of yours that opens them. It's there while passkeys are on in Admin > Settings > Security. ### Bug Fixes - A cron job that an old cron line also ran - the line for the Ticket Email Parser or the Mail Queue left in `/etc/cron.d/itflow` by the install script before 26.08 - no longer looks stopped. The old line's run took the job's lock, so `cron.php` passed it by: its last run on Maintenance > Cron stayed days old and Cron Watch emailed that it had fallen behind, while its work got done - and turning it off didn't stop it. Now the old line's run steps aside while `cron.php` is running, Maintenance > Cron lists the lines to take out, with the file and line, and so do Debug and Cron Watch's email. A line ITFlow can't see - in a user's own crontab - is still found from its runs, and said with where to look. - A cron job whose lock file was made by a run as root no longer stops cron. The web server's user can't open such a file, and every job after it in the list stopped, every minute, without a word - Cron Watch with them - until the server restarted. Now that job fails, saying which file to delete, and the rest run. Cron started as root now becomes the user that owns ITFlow's files first, so it doesn't leave such files - or uploads, backups and git files the web server can't use - behind. - AI Triage no longer runs every minute when AI triage is off in Settings > Tickets or there's no AI model to ask - before, it ran anyway and showed **Completed** every minute with nothing done. +- A passkey that didn't open your credentials when it was added now opens them after you type your password once. Some browsers don't let a passkey open them when it's made, though they do at every sign-in after - Windows Hello in Chrome before version 147, for one, and some password managers - and every sign-in with such a passkey asked for the password again, for as long as you had it. Now the first sign-in with it says in the Unlock window that your passkey will open them from then on; type your password, and from the next sign-in it opens them by itself, and Your account > Security says **opens your credentials** under it. A passkey that never gives what opens them still takes your password each time. ### Developer Updates - `getActiveAgentUserCount()` (`functions/app.php`) leaves out `users.user_service_account = 1` with `serviceAccountsOutSql()`, so `getAgentSeatsTaken()`, `agentUserLimitReached()` and the managed report's `agents.active` do too (the report's list still carries them, with `service` set). `admin/post/users.php` skips `agentUserLimitReached()` for an API / service account in `add_user`, `activate_user`, `restore_user` and `bulk_activate_users`, and `edit_user` refuses turning an active one into an agent at the limit before changing anything (`serviceAccountLeavingNeedsSeat()`, `functions/service_account.php`). Admin > Users keeps New User open at the limit when service accounts are available, and the New User window says one can still be added. - Cron jobs can declare `'not_in_use' => function () { ... }` in `includes/cron_jobs.php`, returning why the job has nothing to do on this install or `''` (`cronJobNotInUse()`, which counts a check that throws as in use; `cronJobSettings()` reads the settings the checks need once a request). `cron/cron.php` reads every job's row and Run Now flag once a cycle and skips a job not in use before its lock and claim - registering its row the first time (`cronJobRegister()`, split out of `cronJobClaim()`) - unless it is asked to Run Now. `cronHealthJobs()` leaves such jobs out, so Cron Watch neither waits on nor flags them, and `admin/cron.php` shows them in a new `unused` state. Checks added for `manager_checkin`, `mail_queue`, `sms_queue`, `rmm_sync`, `rmm_alerts`, `ticket_email_parser`, `ai_triage`, `managed_instances`, `payment_provider_fees` and `update_check`, each the same condition its script stops on. `aiTriageNotInUse()` (`functions/ai_ticket.php`) is new, and `cron/ai_triage.php` now stops on it too. CONTRIBUTING.md has the rule. - Cron and runs outside it (database 4.4.2, `cron_jobs.cron_job_outside_at`): `cron/includes/cron_lock.php` gains `cronLockFile()`, `cronLockHolder()`, `cronLockFileProblem()`, `cronLockDispatchBeat()`, `cronLockOutsideFile()`, `cronLockAttended()` and `cronLockRunAsOwner()`, run first: started as root on an install whose `cron/cron.php` is another user's, it calls `posix_initgroups()`, `posix_setgid()` and `posix_setuid()` to become that user, or exits saying how to run it. `cronLockAcquire($path, $stamp)` returns null for a lock file it can't open (it used to `die()`, ending the dispatch at that job), and writes `direct` or `terminal` into the file while a run on its own holds it. The dispatcher touches the heartbeat file each cycle; a run on its own without a terminal on STDIN (`stream_isatty()`) while it is under 180 seconds old exits 0, quietly, and touches its `.outside` file. The dispatcher records that file's time, or a lock found held by a `direct` run, as `cron_job_outside_at` (`cronJobNoteOutside()`, at most every ten minutes), and fails a job whose lock can't be opened with `cronLockFileProblem()` as its error (`cronJobLockFailed()`, logged to App Logs once). `functions/cron_health.php`: `cronStrayLines()` reads `/etc/crontab` and the `/etc/cron.d` files cron would read for lines that run this install's job scripts on their own (anything in `cron/` but `cron.php`, and the old `scripts/cron*.php` and `cron_*.php`), `cronStrayText()`, `cronStrayWhat()`, `cronOutsideJobs()` (the last `CRON_HEALTH_OUTSIDE_HOURS`, 26), `cronOutsideReady()` and `cronFilesOwner()`; `cronHealthProblems()` adds a `stray` problem and an `outside` one per job the lines don't cover, and doesn't call a job overdue while it is run outside. `health.php` leaves both kinds out, so an uptime monitor doesn't go red for them. Maintenance > Cron has a card for the lines (`data-cron-stray`, `data-cron-stray-line`) and a note on each job run outside (`data-cron-outside`); Debug's Background jobs adds Old cron lines. CONTRIBUTING.md has the rule. +- Passkeys sealed to the vault after they were added (`functions/passkey.php`, no database change): `login_passkey.php` keeps a passkey's PRF result for the session when it has no `passkey_vault` that opens with it - `passkeySealKeep()`, AES-256-GCM in `$_SESSION['passkey_seal']` with its key in the httponly `passkey_seal_key` cookie, set as `user_encryption_session_key` is - and once the vault opens, `vaultUnlock()` or the new `vaultUnlockPasskey()` seals the vault key to it (`passkeySealKept()`, checked to open before `passkey_vault` is written; the kept secret is dropped either way, and logout clears the cookie). `vaultUnlockPasskey()` checks an assertion for the new `unlock` challenge purpose against the signed-in agent's own passkeys - `passkeyVerify($post, $purpose, $user_id)`, which `passkeyVerifySignIn()` now wraps - and opens the vault with its PRF result; a passkey whose copy doesn't open with it keeps that result for the password to seal. `passkeyUnlockOptions()`, `passkeyVaultCount()` and `passkeySealPending()` feed the Unlock window (`includes/footer.php`, `[data-vault-unlock-passkey]`), and `agent/ajax.php` adds `vault_unlock_passkey_options` and `vault_unlock_passkey` (POST, CSRF). `js/passkey.js` handles the button, runs once per page (`window.itflowPasskeys`) and fires `itflow:vault-unlocked` on `#vaultUnlockModal`, which `js/credentials.js` now listens for. A passkey that doesn't unlock is logged as Login / Unlock Failed. `vaultLockedReason()` for a passkey sign-in now reads "your passkey sign-in didn't open them". ## [26.12.4] diff --git a/agent/ajax.php b/agent/ajax.php index 5084ce0d4..69de205a4 100644 --- a/agent/ajax.php +++ b/agent/ajax.php @@ -59,6 +59,24 @@ if (isset($_POST['vault_unlock'])) { exit; } +/* + * Or with a passkey of theirs that opens the vault (vaultUnlockPasskey(), js/passkey.js): + * vault_unlock_passkey_options is what to ask the browser for, vault_unlock_passkey checks its answer. + */ +if (isset($_POST['vault_unlock_passkey_options']) || isset($_POST['vault_unlock_passkey'])) { + validateCSRFToken(); + header('Content-Type: application/json'); + if (!passkeyVaultCount($session_user_id)) { + exit(json_encode(['error' => 'None of your passkeys opens your credentials here - type your password.'])); + } + if (isset($_POST['vault_unlock_passkey_options'])) { + exit(json_encode(passkeyUnlockOptions($session_user_id))); + } + [$unlocked, $unlock_message] = vaultUnlockPasskey($session_user_id, $_POST); + echo json_encode($unlocked ? ['unlocked' => true] : ['error' => $unlock_message]); + exit; +} + /* * Markdown for a document's editors (js/document_markdown.js, functions/markdown.php): Markdown as * the HTML it shows as - its Preview, switching it to the rich text editor, and Markdown pasted diff --git a/agent/user/post/profile.php b/agent/user/post/profile.php index 7fc0e4063..c6b133c65 100644 --- a/agent/user/post/profile.php +++ b/agent/user/post/profile.php @@ -314,7 +314,7 @@ if (isset($_POST['add_your_passkey'])) { flashAlert("Passkey " . escapeHtml($name) . " added - " . ($how === 'opens' ? 'it signs you in and opens your credentials' - : 'it signs you in, and you type your password once each time to open your credentials')); + : 'it signs you in. The first time you sign in with it, unlock your credentials with your password - from then on it opens them too, if the passkey can')); redirect("user_security.php"); diff --git a/functions/credential.php b/functions/credential.php index 388802880..c8ff76f0e 100644 --- a/functions/credential.php +++ b/functions/credential.php @@ -268,7 +268,7 @@ function credentialFormSet($post, $client_id, &$error = '') { $password = encryptCredentialEntry(trim((string) ($post['password'] ?? ''))); $otp = credentialOtpEncrypt($otp); if ($username === false || $password === false || $otp === false) { - $error = vaultLocked() ? 'Your credentials are locked - ' . vaultLockedReason() . '. Unlock them with your password (the lock beside a username), then save again.' + $error = vaultLocked() ? 'Your credentials are locked - ' . vaultLockedReason() . '. Unlock them (the lock beside a username), then save again.' : 'Your vault session has expired, so the login could not be encrypted - sign out and back in, then try again.'; return null; } @@ -314,8 +314,8 @@ function credentialUsername($row) { function credentialUsernameHtml($username, $empty = '-') { $username = escapeHtml($username); if ($username === '' && vaultLocked()) { - // Signed in with a passkey that couldn't open the vault - their password unlocks it (js/credentials.js) - return 'Locked'; + // Signed in with a passkey that didn't open the vault - their password, or a passkey that opens it, unlocks it (js/credentials.js) + return 'Locked'; } if ($username === '') { return '' . $empty . ''; diff --git a/functions/passkey.php b/functions/passkey.php index 9aedb2dbe..016f45f0e 100644 --- a/functions/passkey.php +++ b/functions/passkey.php @@ -19,6 +19,14 @@ * under HKDF-SHA256 of the secret) - so signing in with it opens the vault too. One that doesn't * leaves the vault locked; the agent types their password once to open it (vaultUnlock()). * + * That copy is made when the passkey is added, if the browser gives the secret then - and some + * don't, though the same passkey gives it at every sign-in after (Windows Hello before Chrome 147, + * some password managers). So a passkey sign-in that gives the secret, with no copy that opens with + * it, keeps the secret for the session (passkeySealKeep()) until the vault is opened - by their + * password, or another passkey - and a copy is sealed to it then (passkeySealKept()). A sign-in + * that didn't bring the secret (a phone's QR code, some autofill) can be followed by Unlock with a + * passkey, which asks for one of theirs that opens the vault (vaultUnlockPasskey()). + * * Passkeys are made for this install's address (config_base_url) - one made for another address * doesn't work here, and moving ITFlow to a new address means adding them again. */ @@ -29,6 +37,7 @@ const PASSKEY_CHALLENGE_SECONDS = 300; const PASSKEY_VAULT_FORMAT = 'pk1:'; const PASSKEY_PER_USER = 20; const PASSKEY_NAME_MAX = 60; +const PASSKEY_SEAL_COOKIE = 'passkey_seal_key'; /* * Whether the database has passkeys yet (4.2.2), and whether they can be used to sign in - Admin > @@ -95,7 +104,7 @@ function passkeyPrfSalt() { return hash('sha256', 'ITFlow passkey vault key', true); } -/** A new challenge for $purpose (sign_in, create), kept in the session - replacing any before it. */ +/** A new challenge for $purpose (sign_in, create, unlock), kept in the session - replacing any before it. */ function passkeyChallenge($purpose, $user_id = 0) { $challenge = random_bytes(32); $_SESSION['passkey_challenge'] = ['value' => passkeyB64url($challenge), 'purpose' => $purpose, 'user_id' => intval($user_id), 'created' => time()]; @@ -315,23 +324,35 @@ function passkeyRegister($user_id, $name, array $post, $master = null) { * person was verified. [the passkey and its user, or false; why not, for the log; the user it was, if known]. */ function passkeyVerifySignIn(array $post) { + return passkeyVerify($post, 'sign_in'); +} + +/** + * Check a passkey's answer to the challenge given this session for $purpose - sign_in (any passkey + * added here) or unlock (one of $user_id's). As passkeyVerifySignIn(). + */ +function passkeyVerify(array $post, $purpose, $user_id = 0) { global $mysqli; - $challenge = passkeyChallengeTake('sign_in'); + $user_id = intval($user_id); + $challenge = passkeyChallengeTake($purpose, $user_id); if ($challenge === false) { - return [false, 'the sign-in took too long', 0]; + return [false, 'the sign-in took too long', $user_id]; } $id = passkeyFromB64url($post['id'] ?? ''); $client_data = passkeyFromB64url($post['client_data'] ?? ''); $authenticator_data = passkeyFromB64url($post['authenticator_data'] ?? ''); $signature = passkeyFromB64url($post['signature'] ?? ''); if ($id === false || $client_data === false || $authenticator_data === false || $signature === false) { - return [false, 'the browser sent no passkey', 0]; + return [false, 'the browser sent no passkey', $user_id]; } $hash = hash('sha256', $id); $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_passkeys.*, users.user_id, users.user_email, users.user_name, users.user_type, users.user_passkey_handle FROM user_passkeys JOIN users ON users.user_id = user_passkeys.passkey_user_id WHERE passkey_credential_hash = '$hash'")); if (!$row) { - return [false, 'the passkey is not one added here - it may have been removed', 0]; + return [false, 'the passkey is not one added here - it may have been removed', $user_id]; + } + if ($user_id && intval($row['user_id']) !== $user_id) { + return [false, 'the passkey is someone else\'s', $user_id]; } $user_id = intval($row['user_id']); $handle = passkeyFromB64url($post['user_handle'] ?? ''); @@ -370,7 +391,8 @@ function passkeyMetaHtml(array $passkey, $vault = true) { /** * Is this agent's vault locked - they have a copy of the vault key, but this session's vault - * doesn't open (a passkey sign-in that couldn't open it)? Unlocked with their password (vaultUnlock()). + * doesn't open (a passkey sign-in that couldn't open it)? Unlocked with their password (vaultUnlock()), + * or a passkey of theirs that opens it (vaultUnlockPasskey()). */ function vaultLocked() { global $mysqli, $session_user_id; @@ -422,7 +444,7 @@ function vaultSessionMaster() { return is_string($master) && strlen($master) === 16 ? $master : false; } -/** Open a locked vault with the agent's password. [ok, message]. */ +/** Open a locked vault with the agent's password - sealing it to a passkey kept for that (passkeySealKept()). [ok, message]. */ function vaultUnlock($user_id, #[\SensitiveParameter] $password) { [$ok, $message, $row] = passkeyPasswordCheck($user_id, $password, 'unlock their credentials'); if (!$ok) { @@ -431,20 +453,170 @@ function vaultUnlock($user_id, #[\SensitiveParameter] $password) { if (intval($row['user_type']) !== 1 || !vaultSignIn(intval($user_id), $row['user_specific_encryption_ciphertext'], $password)) { return [false, 'Your copy of the vault key did not open - ask an administrator to set your password again.']; } - logAudit('Login', 'Unlock', escapeSql($row['user_name']) . ' unlocked their credentials with their password', 0, intval($user_id)); + // The vault key vaultSignIn() just opened - remembered from there, not worked out again + $sealed = passkeySealKept($user_id, decryptUserSpecificKey($row['user_specific_encryption_ciphertext'], $password)); + logAudit('Login', 'Unlock', escapeSql($row['user_name']) . ' unlocked their credentials with their password' + . ($sealed !== '' ? ' - their passkey (' . escapeSql($sealed) . ') opens them from now on' : ''), 0, intval($user_id)); return [true, '']; } +/* + * Open a locked vault with a passkey (Unlock, js/passkey.js) - one of theirs with a copy of the vault + * key, and the PRF secret it gives. One whose copy doesn't open with the secret it gave keeps that + * secret, for their password to seal a copy that does (passkeySealKept()). [ok, message]. + */ +function vaultUnlockPasskey($user_id, array $post) { + global $mysqli; + $user_id = intval($user_id); + [$passkey, $why] = passkeyVerify($post, 'unlock', $user_id); + if (!$passkey) { + $name = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT user_name FROM users WHERE user_id = $user_id"))[0] ?? 'Someone'); + logAudit('Login', 'Unlock Failed', escapeSql("$name couldn't unlock their credentials with a passkey - $why"), 0, $user_id); + return [false, str_starts_with($why, 'the sign-in took too long') ? 'That took too long - try again.' + : 'That passkey didn\'t unlock them - try again, or type your password.']; + } + $prf = passkeyFromB64url($post['prf'] ?? ''); + if ($prf === false || strlen($prf) < 32) { + return [false, 'Your passkey didn\'t give what opens your credentials in this browser - type your password instead.']; + } + $master = $passkey['passkey_vault'] !== '' ? passkeyOpenVault($passkey['passkey_vault'], $prf, $passkey['passkey_credential_hash']) : false; + if ($master === false) { + passkeySealKeep($passkey, $prf); + return [false, 'That passkey didn\'t open them - type your password, and it will from your next sign-in.']; + } + generateUserSessionKey($master); + $sealed = passkeySealKept($user_id, $master); + logAudit('Login', 'Unlock', escapeSql($passkey['user_name']) . ' unlocked their credentials with a passkey (' . escapeSql($passkey['passkey_name']) . ')' + . ($sealed !== '' ? ' - their passkey (' . escapeSql($sealed) . ') opens them from now on' : ''), 0, $user_id); + return [true, '']; +} + +/** What Unlock asks the browser for - one of $user_id's passkeys that opens the vault, and its PRF secret. Null when none of theirs does. */ +function passkeyUnlockOptions($user_id) { + global $mysqli; + $allow = []; + $sql = mysqli_query($mysqli, "SELECT passkey_credential_id, passkey_transports FROM user_passkeys WHERE passkey_user_id = " . intval($user_id) . " AND passkey_vault <> ''"); + while ($sql && $row = mysqli_fetch_assoc($sql)) { + $item = ['type' => 'public-key', 'id' => $row['passkey_credential_id']]; + if ($row['passkey_transports'] !== '') { + $item['transports'] = explode(',', $row['passkey_transports']); + } + $allow[] = $item; + } + if (!$allow) { + return null; + } + $rp = passkeyRp(); + return [ + 'challenge' => passkeyChallenge('unlock', $user_id), + 'rpId' => $rp['id'], + 'timeout' => 120000, + 'userVerification' => 'required', + 'allowCredentials' => $allow, + 'extensions' => ['prf' => ['eval' => ['first' => passkeyB64url(passkeyPrfSalt())]]], + 'address' => $rp['address'], + ]; +} + +/** How many of $user_id's passkeys open the vault - for Unlock to offer them. 0 while passkeys are off or not in the database yet. */ +function passkeyVaultCount($user_id) { + global $mysqli; + if (!passkeysReady() || !passkeysOn()) { + return 0; + } + $sql = mysqli_query($mysqli, "SELECT COUNT(*) FROM user_passkeys WHERE passkey_user_id = " . intval($user_id) . " AND passkey_vault <> ''"); + return $sql ? intval(mysqli_fetch_row($sql)[0]) : 0; +} + +/* + * A passkey's PRF secret, kept for this session until the vault opens (passkeySealKept()) - from a + * sign-in (login_passkey.php) or Unlock that gave it, where the passkey has no copy of the vault key + * that opens with it. Encrypted, with its key in a cookie, as the vault session is (generateUserSessionKey()), + * so neither the session store nor the browser has it alone. + */ +function passkeySealKeep(array $passkey, #[\SensitiveParameter] $prf) { + $key = random_bytes(32); + $nonce = random_bytes(12); + $tag = ''; + $ciphertext = openssl_encrypt((string) $prf, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $nonce, $tag, 'ITFlow passkey seal'); + $_SESSION['passkey_seal'] = [ + 'user_id' => intval($passkey['passkey_user_id']), + 'passkey_id' => intval($passkey['passkey_id']), + 'hash' => (string) $passkey['passkey_credential_hash'], + 'name' => (string) $passkey['passkey_name'], + 'secret' => base64_encode($nonce . $tag . $ciphertext), + ]; + passkeySealCookie(base64_encode($key)); +} + +/** The name of the passkey whose secret is kept for $user_id, waiting for the vault to open - '' when there is none. */ +function passkeySealPending($user_id) { + $kept = $_SESSION['passkey_seal'] ?? null; + return is_array($kept) && intval($kept['user_id'] ?? 0) === intval($user_id) && !empty($_COOKIE[PASSKEY_SEAL_COOKIE]) ? (string) $kept['name'] : ''; +} + +/* + * The vault just opened with $master, the vault key: seal a copy of it to the passkey kept for that + * (passkeySealKeep()), so the passkey opens the vault itself from then on - checked to open before + * it is written. The kept secret is dropped either way. The passkey's name, or '' when nothing was sealed. + */ +function passkeySealKept($user_id, #[\SensitiveParameter] $master) { + global $mysqli; + $kept = $_SESSION['passkey_seal'] ?? null; + $key = base64_decode((string) ($_COOKIE[PASSKEY_SEAL_COOKIE] ?? ''), true); + unset($_SESSION['passkey_seal']); + if (isset($_COOKIE[PASSKEY_SEAL_COOKIE])) { + passkeySealCookie(''); + } + if (!is_array($kept) || intval($kept['user_id'] ?? 0) !== intval($user_id) || !is_string($master) || strlen($master) < 16 || !is_string($key) || strlen($key) !== 32) { + return ''; + } + $raw = base64_decode((string) ($kept['secret'] ?? ''), true); + $prf = is_string($raw) && strlen($raw) > 28 + ? openssl_decrypt(substr($raw, 28), 'aes-256-gcm', $key, OPENSSL_RAW_DATA, substr($raw, 0, 12), substr($raw, 12, 16), 'ITFlow passkey seal') : false; + if (!is_string($prf) || strlen($prf) < 32) { + return ''; + } + $hash = (string) $kept['hash']; + $sealed = passkeySealVault($master, $prf, $hash); + if (passkeyOpenVault($sealed, $prf, $hash) !== $master) { + return ''; + } + mysqli_query($mysqli, "UPDATE user_passkeys SET passkey_vault = '" . escapeSql($sealed) . "' + WHERE passkey_id = " . intval($kept['passkey_id']) . " AND passkey_user_id = " . intval($user_id) . " AND passkey_credential_hash = '" . escapeSql($hash) . "'"); + return mysqli_affected_rows($mysqli) > 0 ? (string) $kept['name'] : ''; +} + +/** The cookie with the key to a kept secret (passkeySealKeep()) - set as the vault session's is (generateUserSessionKey()), or cleared with ''. */ +function passkeySealCookie($value) { + global $config_https_only; + if (!isset($config_https_only)) { + include __DIR__ . '/../config.php'; + } + $options = ['path' => '/', 'httponly' => true, 'expires' => $value === '' ? time() - 3600 : 0]; + if ($config_https_only) { + $options += ['secure' => true, 'samesite' => 'None']; + } else { + $options['samesite'] = 'Lax'; + } + if (!headers_sent()) { + setcookie(PASSKEY_SEAL_COOKIE, (string) $value, $options); + } + if ($value === '') { + unset($_COOKIE[PASSKEY_SEAL_COOKIE]); + } +} + /* * Why the vault is locked, as it is said to the agent - how they signed in without the password - * that opens it (login.php): a passkey that can't, an identity provider, or their mail password. + * that opens it (login.php): a passkey sign-in that didn't, an identity provider, or their mail password. */ function vaultLockedReason() { $via = trim((string) ($_SESSION['signed_in_via'] ?? '')); return [ 'provider' => 'you signed in with ' . ($via !== '' ? $via : 'an identity provider') . ', which can\'t open them', 'imap' => 'you signed in with your mail password, which can\'t open them', - ][$_SESSION['signed_in_with'] ?? ''] ?? 'you signed in with a passkey that can\'t open them'; + ][$_SESSION['signed_in_with'] ?? ''] ?? 'your passkey sign-in didn\'t open them'; } /** The note in a credential window while the vault is locked - with the button that unlocks it (js/credentials.js). */ diff --git a/includes/footer.php b/includes/footer.php index 90b15d330..056a355c2 100644 --- a/includes/footer.php +++ b/includes/footer.php @@ -96,12 +96,21 @@ try { + + + diff --git a/js/credentials.js b/js/credentials.js index 92efc10a6..96b59f14a 100644 --- a/js/credentials.js +++ b/js/credentials.js @@ -11,8 +11,10 @@ * is one of the credential's earlier passwords, fetched the same way. * * After a passkey sign-in that couldn't open the vault, both answer {locked}: - * the Unlock window (includes/footer.php) asks for their password, then what - * was asked for is tried again. [data-vault-unlock] opens it too. + * the Unlock window (includes/footer.php) asks for their password - or a + * passkey that opens it (js/passkey.js, which says so with the + * itflow:vault-unlocked event) - then what was asked for is tried again. + * [data-vault-unlock] opens it too. */ (function () { @@ -30,7 +32,9 @@ modal.itflowThen = then; bootstrap.Modal.getOrCreateInstance(modal).show(); setTimeout(function () { - var input = modal.querySelector('[name=password]'); + // A passkey that opens it first, where there is one (js/passkey.js shows its button) + var passkey = modal.querySelector('[data-vault-unlock-passkey-box]:not([hidden]) [data-vault-unlock-passkey]'); + var input = passkey || modal.querySelector('[name=password]'); if (input) { input.focus(); } @@ -39,6 +43,17 @@ var unlockModal = document.getElementById('vaultUnlockModal'); if (unlockModal) { + // Unlocked - with the password here, or a passkey (js/passkey.js): try again what was asked for, or show the page afresh + var unlocked = function () { + bootstrap.Modal.getOrCreateInstance(unlockModal).hide(); + if (document.querySelector('[data-vault-locked]') || typeof unlockModal.itflowThen !== 'function') { + window.location.reload(); + return; + } + unlockModal.itflowThen(); + }; + unlockModal.addEventListener('itflow:vault-unlocked', unlocked); + unlockModal.querySelector('[data-vault-unlock-form]').addEventListener('submit', function (e) { e.preventDefault(); var form = this; @@ -65,12 +80,7 @@ return; } input.value = ''; - bootstrap.Modal.getOrCreateInstance(unlockModal).hide(); - if (document.querySelector('[data-vault-locked]') || typeof unlockModal.itflowThen !== 'function') { - window.location.reload(); - return; - } - unlockModal.itflowThen(); + unlocked(); }).catch(function () { submit.disabled = false; }); diff --git a/js/passkey.js b/js/passkey.js index 4262916fb..cce401088 100644 --- a/js/passkey.js +++ b/js/passkey.js @@ -11,10 +11,20 @@ * passkey can open their credentials) gets what to ask the browser for, makes the passkey, and * sends it with the form - its name and their password - as an ordinary post. A passkey that does * PRF but didn't give its secret on being made is asked once more for it, to seal the vault key. + * + * Unlock: the Unlock window (includes/footer.php) of an agent whose credentials are locked, with a + * passkey that opens them, shows [data-vault-unlock-passkey] - it asks for one of those and its secret + * (agent/ajax.php, vaultUnlockPasskey()), and says itflow:vault-unlocked to js/credentials.js once open. */ (function () { 'use strict'; + // Loaded once - the Security page has it, and so does the Unlock window + if (window.itflowPasskeys) { + return; + } + window.itflowPasskeys = true; + function toBytes(text) { text = String(text || '').replace(/-/g, '+').replace(/_/g, '/'); while (text.length % 4) { @@ -296,4 +306,63 @@ }); }); }); + + /* ---------------------------------------------------------------- Unlock the credentials */ + + var unlockModal = document.getElementById('vaultUnlockModal'); + var unlockButton = unlockModal && unlockModal.querySelector('[data-vault-unlock-passkey]'); + if (unlockButton && supported()) { + var unlockMessage = unlockModal.querySelector('[data-vault-unlock-message]'); + unlockModal.querySelector('[data-vault-unlock-passkey-box]').hidden = false; + + unlockButton.addEventListener('click', function () { + var address = ''; + showMessage(unlockMessage, ''); + unlockButton.disabled = true; + post('/agent/ajax.php', { vault_unlock_passkey_options: 1, csrf_token: unlockModal.dataset.csrf }).then(function (options) { + if (options.error) { + throw { message: options.error }; + } + address = options.address; + return navigator.credentials.get({ + publicKey: { + challenge: toBytes(options.challenge), + rpId: options.rpId, + timeout: options.timeout, + userVerification: options.userVerification, + allowCredentials: options.allowCredentials.map(function (item) { + return { type: item.type, id: toBytes(item.id), transports: item.transports }; + }), + extensions: prfExtension(options) + } + }); + }).then(function (credential) { + var response = credential.response; + return post('/agent/ajax.php', { + vault_unlock_passkey: 1, + csrf_token: unlockModal.dataset.csrf, + id: toText(credential.rawId), + client_data: toText(response.clientDataJSON), + authenticator_data: toText(response.authenticatorData), + signature: toText(response.signature), + user_handle: toText(response.userHandle), + prf: prfOf(credential) + }); + }).then(function (result) { + unlockButton.disabled = false; + if (!result.unlocked) { + throw { message: result.error || 'That passkey didn\'t unlock them - type your password instead.' }; + } + unlockModal.dispatchEvent(new CustomEvent('itflow:vault-unlocked')); + }).catch(function (error) { + unlockButton.disabled = false; + var text = error && error.name ? whyNot(error, address) : ((error && error.message) || 'That passkey didn\'t unlock them - type your password instead.'); + showMessage(unlockMessage, text, 'warning'); + var password = unlockModal.querySelector('[name=password]'); + if (password && text) { + password.focus(); + } + }); + }); + } })(); diff --git a/login_passkey.php b/login_passkey.php index 1308ccd74..00c33185c 100644 --- a/login_passkey.php +++ b/login_passkey.php @@ -4,7 +4,8 @@ * The sign-in page's passkey (functions/passkey.php) - JSON, POST only: * action=options - what to ask the browser for, with a challenge kept in the session * action=verify - the browser's answer, checked. For an agent, the vault is opened with the - * passkey's PRF secret where it can be. Then {token}: the page posts it to + * passkey's PRF secret where it can be - or the secret kept, to seal a copy of + * the vault key to the passkey once the vault opens (passkeySealKeep()). Then {token}: the page posts it to * login.php (passkey_login), which signs them in its usual way, as it does * after a two-step code - a passkey counts as two-step sign-in. * Failures count towards the same lockout as passwords. @@ -127,8 +128,8 @@ $token = bin2hex(random_bytes(32)); if (intval($user['user_type']) === 1) { // The vault: opened with the passkey's PRF secret when it has a copy and the browser gave one - - // otherwise it stays locked until they type their password (vaultUnlock()) - unset($_SESSION['user_encryption_session_ciphertext'], $_SESSION['user_encryption_session_iv']); + // otherwise it stays locked until they type their password (vaultUnlock()) or use a passkey that opens it + unset($_SESSION['user_encryption_session_ciphertext'], $_SESSION['user_encryption_session_iv'], $_SESSION['passkey_seal']); $agent_vault = false; $prf = passkeyFromB64url($_POST['prf'] ?? ''); if ($passkey['passkey_vault'] !== '' && $prf !== false) { @@ -138,6 +139,12 @@ if (intval($user['user_type']) === 1) { $agent_vault = true; } } + // It gave its secret but has no copy that opens with it - added where the browser didn't give the + // secret then. Kept until the vault opens this session, which seals a copy to it (passkeySealKept()), + // so from the next sign-in it opens the vault itself + if (!$agent_vault && $prf !== false && strlen($prf) >= 32 && trim((string) $user['user_specific_encryption_ciphertext']) !== '') { + passkeySealKeep($passkey, $prf); + } $_SESSION['pending_passkey_login'] = [ 'type' => 'agent', diff --git a/post/logout.php b/post/logout.php index 7c9f3afba..83de41e3c 100644 --- a/post/logout.php +++ b/post/logout.php @@ -20,6 +20,10 @@ if (isset($_GET['logout'])) { setcookie("user_extension_key", '', time() - 3600, "/"); unset($_COOKIE['user_extension_key']); + // A passkey's secret kept to seal the vault to (passkeySealKeep()) + setcookie("passkey_seal_key", '', time() - 3600, "/"); + unset($_COOKIE['passkey_seal_key']); + session_unset(); session_destroy(); From ea83e249d19cd72578a80d477d6189835fb9f7fb Mon Sep 17 00:00:00 2001 From: johnnyq Date: Wed, 2 Dec 2026 23:05:42 -0500 Subject: [PATCH 5/8] Unlock window works with password managers: the form drops autocomplete off and carries the agent's email in a hidden username field, so Bitwarden and the like fill the ITFlow password they keep for signing in, as on the sign-in page; 26.12.5 changelog --- CHANGELOG.md | 3 ++- includes/footer.php | 8 +++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 44f2ed960..dec743b06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ Update from Maintenance > Update as usual. This release has one database change, - Cron leaves alone the jobs that have nothing to do on your ITFlow - what they work with is switched off or isn't set up: AI Triage, Text Messages, RMM Sync and RMM Alerts, the Ticket Email Parser with email to ticket off or no mailbox, the Mail Queue with no mail server, Payment Provider Fees without Stripe, the Update Check on an install that isn't a git checkout, and Manager Check-in and Managed Instances when there's nothing connected. Before, each one started every minute only to stop itself. Maintenance > Cron shows them as **Not in use**, with why under each; they start by themselves once that changes, and **Run Now** still runs them. Cron Watch doesn't email about them falling behind. - An API / service account no longer takes a seat on the agent user limit - the one your hosting provider sets, or one set for your installation. Nobody signs in as it: it's the login an integration's API keys act as. You can add one, enable one or restore one when every seat is taken, and Admin > Users shows the seats without them. Turning one back into an agent who signs in takes a seat, so there has to be one free. A hosted instance's manager sees it the same way: its seats taken leave API accounts out, and its list of agents marks them. - Unlock your credentials with a passkey. When a passkey sign-in leaves them locked although your passkey opens them - signing in by scanning a QR code with your phone, or some password managers' autofill - the Unlock window offers **Unlock with a Passkey** before your password, with any passkey of yours that opens them. It's there while passkeys are on in Admin > Settings > Security. +- Password managers fill your password in the Unlock window. Bitwarden and the like offer the ITFlow password they keep for signing in, as they do on the sign-in page - handy where your passkey can't open your credentials itself, as with passkeys kept in Bitwarden. ### Bug Fixes @@ -29,7 +30,7 @@ Update from Maintenance > Update as usual. This release has one database change, - `getActiveAgentUserCount()` (`functions/app.php`) leaves out `users.user_service_account = 1` with `serviceAccountsOutSql()`, so `getAgentSeatsTaken()`, `agentUserLimitReached()` and the managed report's `agents.active` do too (the report's list still carries them, with `service` set). `admin/post/users.php` skips `agentUserLimitReached()` for an API / service account in `add_user`, `activate_user`, `restore_user` and `bulk_activate_users`, and `edit_user` refuses turning an active one into an agent at the limit before changing anything (`serviceAccountLeavingNeedsSeat()`, `functions/service_account.php`). Admin > Users keeps New User open at the limit when service accounts are available, and the New User window says one can still be added. - Cron jobs can declare `'not_in_use' => function () { ... }` in `includes/cron_jobs.php`, returning why the job has nothing to do on this install or `''` (`cronJobNotInUse()`, which counts a check that throws as in use; `cronJobSettings()` reads the settings the checks need once a request). `cron/cron.php` reads every job's row and Run Now flag once a cycle and skips a job not in use before its lock and claim - registering its row the first time (`cronJobRegister()`, split out of `cronJobClaim()`) - unless it is asked to Run Now. `cronHealthJobs()` leaves such jobs out, so Cron Watch neither waits on nor flags them, and `admin/cron.php` shows them in a new `unused` state. Checks added for `manager_checkin`, `mail_queue`, `sms_queue`, `rmm_sync`, `rmm_alerts`, `ticket_email_parser`, `ai_triage`, `managed_instances`, `payment_provider_fees` and `update_check`, each the same condition its script stops on. `aiTriageNotInUse()` (`functions/ai_ticket.php`) is new, and `cron/ai_triage.php` now stops on it too. CONTRIBUTING.md has the rule. - Cron and runs outside it (database 4.4.2, `cron_jobs.cron_job_outside_at`): `cron/includes/cron_lock.php` gains `cronLockFile()`, `cronLockHolder()`, `cronLockFileProblem()`, `cronLockDispatchBeat()`, `cronLockOutsideFile()`, `cronLockAttended()` and `cronLockRunAsOwner()`, run first: started as root on an install whose `cron/cron.php` is another user's, it calls `posix_initgroups()`, `posix_setgid()` and `posix_setuid()` to become that user, or exits saying how to run it. `cronLockAcquire($path, $stamp)` returns null for a lock file it can't open (it used to `die()`, ending the dispatch at that job), and writes `direct` or `terminal` into the file while a run on its own holds it. The dispatcher touches the heartbeat file each cycle; a run on its own without a terminal on STDIN (`stream_isatty()`) while it is under 180 seconds old exits 0, quietly, and touches its `.outside` file. The dispatcher records that file's time, or a lock found held by a `direct` run, as `cron_job_outside_at` (`cronJobNoteOutside()`, at most every ten minutes), and fails a job whose lock can't be opened with `cronLockFileProblem()` as its error (`cronJobLockFailed()`, logged to App Logs once). `functions/cron_health.php`: `cronStrayLines()` reads `/etc/crontab` and the `/etc/cron.d` files cron would read for lines that run this install's job scripts on their own (anything in `cron/` but `cron.php`, and the old `scripts/cron*.php` and `cron_*.php`), `cronStrayText()`, `cronStrayWhat()`, `cronOutsideJobs()` (the last `CRON_HEALTH_OUTSIDE_HOURS`, 26), `cronOutsideReady()` and `cronFilesOwner()`; `cronHealthProblems()` adds a `stray` problem and an `outside` one per job the lines don't cover, and doesn't call a job overdue while it is run outside. `health.php` leaves both kinds out, so an uptime monitor doesn't go red for them. Maintenance > Cron has a card for the lines (`data-cron-stray`, `data-cron-stray-line`) and a note on each job run outside (`data-cron-outside`); Debug's Background jobs adds Old cron lines. CONTRIBUTING.md has the rule. -- Passkeys sealed to the vault after they were added (`functions/passkey.php`, no database change): `login_passkey.php` keeps a passkey's PRF result for the session when it has no `passkey_vault` that opens with it - `passkeySealKeep()`, AES-256-GCM in `$_SESSION['passkey_seal']` with its key in the httponly `passkey_seal_key` cookie, set as `user_encryption_session_key` is - and once the vault opens, `vaultUnlock()` or the new `vaultUnlockPasskey()` seals the vault key to it (`passkeySealKept()`, checked to open before `passkey_vault` is written; the kept secret is dropped either way, and logout clears the cookie). `vaultUnlockPasskey()` checks an assertion for the new `unlock` challenge purpose against the signed-in agent's own passkeys - `passkeyVerify($post, $purpose, $user_id)`, which `passkeyVerifySignIn()` now wraps - and opens the vault with its PRF result; a passkey whose copy doesn't open with it keeps that result for the password to seal. `passkeyUnlockOptions()`, `passkeyVaultCount()` and `passkeySealPending()` feed the Unlock window (`includes/footer.php`, `[data-vault-unlock-passkey]`), and `agent/ajax.php` adds `vault_unlock_passkey_options` and `vault_unlock_passkey` (POST, CSRF). `js/passkey.js` handles the button, runs once per page (`window.itflowPasskeys`) and fires `itflow:vault-unlocked` on `#vaultUnlockModal`, which `js/credentials.js` now listens for. A passkey that doesn't unlock is logged as Login / Unlock Failed. `vaultLockedReason()` for a passkey sign-in now reads "your passkey sign-in didn't open them". +- Passkeys sealed to the vault after they were added (`functions/passkey.php`, no database change): `login_passkey.php` keeps a passkey's PRF result for the session when it has no `passkey_vault` that opens with it - `passkeySealKeep()`, AES-256-GCM in `$_SESSION['passkey_seal']` with its key in the httponly `passkey_seal_key` cookie, set as `user_encryption_session_key` is - and once the vault opens, `vaultUnlock()` or the new `vaultUnlockPasskey()` seals the vault key to it (`passkeySealKept()`, checked to open before `passkey_vault` is written; the kept secret is dropped either way, and logout clears the cookie). `vaultUnlockPasskey()` checks an assertion for the new `unlock` challenge purpose against the signed-in agent's own passkeys - `passkeyVerify($post, $purpose, $user_id)`, which `passkeyVerifySignIn()` now wraps - and opens the vault with its PRF result; a passkey whose copy doesn't open with it keeps that result for the password to seal. `passkeyUnlockOptions()`, `passkeyVaultCount()` and `passkeySealPending()` feed the Unlock window (`includes/footer.php`, `[data-vault-unlock-passkey]`), and `agent/ajax.php` adds `vault_unlock_passkey_options` and `vault_unlock_passkey` (POST, CSRF). `js/passkey.js` handles the button, runs once per page (`window.itflowPasskeys`) and fires `itflow:vault-unlocked` on `#vaultUnlockModal`, which `js/credentials.js` now listens for. A passkey that doesn't unlock is logged as Login / Unlock Failed. `vaultLockedReason()` for a passkey sign-in now reads "your passkey sign-in didn't open them". The Unlock window's form drops `autocomplete="off"` and carries the agent's email in a hidden `autocomplete="username"` field (as `join.php` does), so password managers match it to the sign-in they keep. ## [26.12.4] diff --git a/includes/footer.php b/includes/footer.php index 056a355c2..153945c71 100644 --- a/includes/footer.php +++ b/includes/footer.php @@ -119,7 +119,7 @@ if ($itflow_vault_locked) { ?>
- + - + + +
- +
diff --git a/agent/kb_article.php b/agent/kb_article.php index 4c80740de..ac8ed8061 100644 --- a/agent/kb_article.php +++ b/agent/kb_article.php @@ -6,7 +6,7 @@ * page: a header card with the actions, the article beside a column with its * category, who can read it, its review, how its readers found it, what they * said didn't help and its versions; its files under it. It can be taken as - * a PDF, and reviewed by AI (modals/kb/kb_article_review.php). + * a PDF or a Markdown file, and reviewed by AI (modals/kb/kb_article_review.php). * * Open to anyone who can read Support; changing it takes Support edit, like * the handlers behind it (agent/post/kb.php). @@ -98,6 +98,7 @@ $page_title = $row['kb_article_title']; Updated · Written · earlier version + · Markdown
@@ -116,8 +117,17 @@ $page_title = $row['kb_article_title']; Review with AI - - PDF +
- +
Saving keeps what it says now in the article's versions, so it can be put back.
diff --git a/agent/modals/kb/kb_article_from_ticket.php b/agent/modals/kb/kb_article_from_ticket.php index 148a22846..d9ab37023 100644 --- a/agent/modals/kb/kb_article_from_ticket.php +++ b/agent/modals/kb/kb_article_from_ticket.php @@ -9,7 +9,8 @@ * people and its systems left out - an article is for every client. Without * it, the window starts with the ticket's subject and what was asked, and the * steps are written here. add_kb_article (agent/post/kb.php) creates it, and - * the ticket's history says it was written up. + * the ticket's history says it was written up. Written in Markdown - the + * agent's way of writing last time - the AI's draft goes in as Markdown. */ require_once '../../../includes/modal_header.php'; @@ -107,15 +108,22 @@ ob_start(); } form.querySelector('[name="title"]').value = answer.title; form.querySelector('[name="summary"]').value = answer.description; + var done = function () { + say('success', 'fa-check-circle', 'Written by AI from the ticket' + (answer.removed ? ' - ' + answer.removed + ' password' + (answer.removed === 1 ? '' : 's') + ' or key' + (answer.removed === 1 ? '' : 's') + ' left out as [removed]' : '') + '. Read it through for anything about the client, then create it.'); + status.setAttribute('data-kb-from-ticket-ready', ''); + save.disabled = false; + }; + // The form in Markdown (includes/document_editors.php) - the draft made Markdown + if (window.itflowDocumentFormat && itflowDocumentFormat.isMarkdown(form)) { + return itflowDocumentFormat.putHtml(form, answer.html).then(done); + } editor(function (ed) { if (ed) { ed.setContent(answer.html); } else { textarea.value = answer.html; } - say('success', 'fa-check-circle', 'Written by AI from the ticket' + (answer.removed ? ' - ' + answer.removed + ' password' + (answer.removed === 1 ? '' : 's') + ' or key' + (answer.removed === 1 ? '' : 's') + ' left out as [removed]' : '') + '. Read it through for anything about the client, then create it.'); - status.setAttribute('data-kb-from-ticket-ready', ''); - save.disabled = false; + done(); }); }) .catch(function (error) { diff --git a/agent/modals/kb/kb_import_markdown.php b/agent/modals/kb/kb_import_markdown.php new file mode 100644 index 000000000..7fff2a6e8 --- /dev/null +++ b/agent/modals/kb/kb_import_markdown.php @@ -0,0 +1,65 @@ + $kb_closed])); +} + +$kb_import_category = kbCategoryId($_GET['category'] ?? 0); + +ob_start(); + +?> + + + + + + + + + false, 'content' => '', ] + kbAudienceFields($row)); + // In Markdown when it is written in it $content = (string) $row['kb_article_content']; + $markdown = $row['kb_article_markdown'] ?? null; $from = kbArticleDir($row['kb_article_id']); if (is_dir($from)) { copyDirectory($from, kbArticleDir($kb_article_id)); $content = str_replace('/uploads/kb/' . intval($row['kb_article_id']) . '/', "/uploads/kb/$kb_article_id/", $content); + $markdown = $markdown === null ? null : str_replace('/uploads/kb/' . intval($row['kb_article_id']) . '/', "/uploads/kb/$kb_article_id/", $markdown); kbArticleCopyFileRows($row['kb_article_id'], $kb_article_id); } mysqli_query($mysqli, "UPDATE kb_articles SET kb_article_content = '" . mysqli_real_escape_string($mysqli, $content) . "', kb_article_content_raw = '" . escapeSql(kbArticleContentRaw('Copy of ' . $row['kb_article_title'], (string) $row['kb_article_summary'], $content)) . "' + " . kbMarkdownSet($markdown) . " WHERE kb_article_id = $kb_article_id"); mysqli_query($mysqli, "INSERT INTO kb_article_tags (kb_article_id, tag_id) SELECT $kb_article_id, tag_id FROM kb_article_tags WHERE kb_article_id = " . intval($row['kb_article_id'])); @@ -214,7 +218,8 @@ if (isset($_GET['copy_kb_article'])) { if (isset($_POST['restore_kb_article_version'])) { $kb_article_version_id = intval($_POST['kb_article_version_id'] ?? 0); - $version = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT kb_article_version_title, kb_article_version_summary, kb_article_version_content, kb_article_version_kb_article_id + $version = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT kb_article_version_title, kb_article_version_summary, kb_article_version_content, + " . kbMarkdownSql('kb_article_version_markdown') . ", kb_article_version_kb_article_id FROM kb_article_versions WHERE kb_article_version_id = $kb_article_version_id")); if (!$version) { flashAlert('That version no longer exists.', 'error'); @@ -223,7 +228,7 @@ if (isset($_POST['restore_kb_article_version'])) { $row = kbArticleForHandler($version['kb_article_version_kb_article_id']); $kb_article_id = intval($row['kb_article_id']); - // What it says now becomes a version itself + // What it says now becomes a version itself - and it is back in the way it was written then, Markdown or rich text kbArticleSave([ 'title' => $version['kb_article_version_title'], 'summary' => (string) $version['kb_article_version_summary'], @@ -231,6 +236,7 @@ if (isset($_POST['restore_kb_article_version'])) { 'review_months' => intval($row['kb_article_review_months']), 'published' => !empty($row['kb_article_published_at']), 'content' => (string) $version['kb_article_version_content'], + 'markdown' => $version['kb_article_version_markdown'], ] + kbAudienceFields($row), $row); logAudit("Knowledge Base", "Edit", "$session_name put back an earlier version of article " . escapeSql($version['kb_article_version_title']), 0, $kb_article_id); @@ -469,3 +475,98 @@ if (isset($_GET['export_kb_article'])) { require_once '../functions/document_pdf.php'; billingPdfSend(documentPdfRender(documentPdfKbArticle($row))); } + +/* + * An article as a Markdown file (documentMarkdownFile(), functions/markdown.php) - as it was + * written when it is in Markdown, its rich text made Markdown otherwise - with its title on top. + */ +if (isset($_GET['export_kb_article_markdown'])) { + + validateCSRFToken(); + $kb_closed = kbClosedText(1); + if ($kb_closed !== '') { + flashAlert(escapeHtml($kb_closed), 'error'); + redirect(); + } + $row = kbArticleForHandler($_GET['export_kb_article_markdown'], false); + + logAudit("Knowledge Base", "Export", "$session_name downloaded article " . escapeSql($row['kb_article_title']) . " as Markdown", 0, intval($row['kb_article_id'])); + + $file_name = trim(preg_replace('/[^A-Za-z0-9 ._-]/', '', $row['kb_article_title'])) ?: 'Article'; + header('Content-Type: text/markdown; charset=UTF-8'); + header('Content-Disposition: attachment; filename="' . $file_name . '.md"; filename*=UTF-8\'\'' . rawurlencode(trim($row['kb_article_title']) . '.md')); + header('X-Content-Type-Options: nosniff'); + echo documentMarkdownFile($row['kb_article_title'], $row['kb_article_content'], $row['kb_article_markdown'] ?? null); + exit; +} + +/* + * Markdown files made into articles (agent/modals/kb/kb_import_markdown.php) - one each, written + * in Markdown, as drafts for agents only, in the category picked. Each is named by the title in + * its front matter or the heading it starts with, else its file name (markdownImportSplit()). + */ +if (isset($_POST['import_markdown_kb_articles'])) { + + if (!kbMarkdownReady()) { + flashAlert('Markdown files can\'t be imported here yet - run the database update from Maintenance > Update first.', 'error'); + redirect(); + } + $category_id = kbCategoryId($_POST['category_id'] ?? 0); + + $files = $_FILES['files'] ?? null; + $count = is_array($files['name'] ?? null) ? count($files['name']) : 0; + $imported = []; + $skipped = []; + for ($i = 0; $i < $count && count($imported) < 50; $i++) { + $original = basename((string) $files['name'][$i]); + if ($files['error'][$i] === UPLOAD_ERR_NO_FILE) { + continue; + } + if ($files['error'][$i] !== UPLOAD_ERR_OK || !is_uploaded_file($files['tmp_name'][$i])) { + $skipped[] = "$original (it didn't upload)"; + continue; + } + if (!preg_match('/\.(md|markdown|mdown|mkd)$/i', $original)) { + $skipped[] = "$original (not a .md file)"; + continue; + } + if ($files['size'][$i] > 5 * 1024 * 1024) { + $skipped[] = "$original (over 5 MB)"; + continue; + } + $text = (string) file_get_contents($files['tmp_name'][$i]); + if (!mb_check_encoding($text, 'UTF-8')) { + $skipped[] = "$original (not UTF-8 text)"; + continue; + } + + [$title, $markdown] = markdownImportSplit($text, preg_replace('/\.(md|markdown|mdown|mkd)$/i', '', $original)); + $kb_article_id = kbArticleSave([ + 'title' => $title, + 'summary' => '', + 'category_id' => $category_id, + 'review_months' => 12, + 'published' => false, + 'content' => '', + 'markdown' => $markdown, + 'visibility' => 'agents', + 'all_clients' => false, + 'client_tag_ids' => [], + 'client_ids' => [], + ]); + + logAudit("Knowledge Base", "Create", "$session_name imported a draft of article " . escapeSql($title) . " from " . escapeSql($original), 0, $kb_article_id); + $imported[] = [$kb_article_id, $title]; + } + + if (!$imported) { + flashAlert('Nothing was imported' . ($skipped ? ': ' . escapeHtml(implode(', ', $skipped)) : ' - pick the .md files to import.'), 'error'); + redirect(); + } + + $what = count($imported) === 1 ? 'Article ' . escapeHtml($imported[0][1]) . ' imported as a draft' : count($imported) . ' articles imported as drafts'; + flashAlert($what . ($skipped ? ' - left out ' . escapeHtml(implode(', ', $skipped)) : ''), $skipped ? 'warning' : 'success'); + + // One goes straight to it; several, to the drafts + redirect(count($imported) === 1 ? "kb_article.php?kb_article_id={$imported[0][0]}" : 'kb.php?show=drafts'); +} diff --git a/db.sql b/db.sql index 0ad8d4dba..cfc7aeddb 100644 --- a/db.sql +++ b/db.sql @@ -2257,6 +2257,7 @@ CREATE TABLE `kb_article_versions` ( `kb_article_version_title` varchar(200) NOT NULL, `kb_article_version_summary` varchar(255) DEFAULT NULL, `kb_article_version_content` longtext NOT NULL, + `kb_article_version_markdown` longtext DEFAULT NULL, `kb_article_version_created_at` datetime NOT NULL DEFAULT current_timestamp(), `kb_article_version_created_by` int(11) NOT NULL DEFAULT 0, `kb_article_version_kb_article_id` int(11) NOT NULL, @@ -2278,6 +2279,7 @@ CREATE TABLE `kb_articles` ( `kb_article_summary` varchar(255) DEFAULT NULL, `kb_article_content` longtext NOT NULL, `kb_article_content_raw` longtext NOT NULL, + `kb_article_markdown` longtext DEFAULT NULL, `kb_article_category_id` int(11) NOT NULL DEFAULT 0, `kb_article_published_at` datetime DEFAULT NULL, `kb_article_visibility` varchar(20) NOT NULL DEFAULT 'agents', diff --git a/functions/kb.php b/functions/kb.php index ad3cef02b..4399b516c 100644 --- a/functions/kb.php +++ b/functions/kb.php @@ -13,7 +13,15 @@ * An article has a title, a line saying what it is for, a category (Admin > * Categories, the 'kb' kind), tags (the kb_article kind) and its content - the * editor's HTML, purified wherever it is shown (documentHtmlPurify()). Without - * a publish date it is a draft. Each edit keeps what it said before as a + * a publish date it is a draft. + * + * Written in Markdown (database 4.4.3, kbMarkdownReady()), as a document can + * be (functions/markdown.php, includes/document_editors.php): what was written + * is kept in kb_article_markdown, and kb_article_content is the HTML made from + * it each time it is saved - so everywhere an article is shown, searched, put + * in a reply or made a PDF stays as it is. It switches either way, versions + * keep their Markdown, .md files are imported as articles, and an article + * downloads as one. Each edit keeps what it said before as a * version. When it says how often, it is due for review that long after it was * last made, edited or reviewed - an edit counts, as it does for documents. * @@ -56,6 +64,36 @@ function kbPublicOn() { return kbOn() && intval($GLOBALS['config_kb_public_enable']) === 1; } +/** Can articles be written in Markdown - the database at 4.4.3? */ +function kbMarkdownReady() { + global $mysqli; + static $ready = null; + if ($ready === null) { + if (defined('CURRENT_DATABASE_VERSION')) { + $version = CURRENT_DATABASE_VERSION; + } else { + $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings WHERE company_id = 1"); + $version = $result && ($row = mysqli_fetch_row($result)) ? (string) $row[0] : '0'; + } + $ready = version_compare($version, '4.4.3', '>='); + } + return $ready; +} + +/** The column to SELECT for what a Markdown article (or version) says - NULL before 4.4.3. */ +function kbMarkdownSql($column = 'kb_article_markdown') { + return kbMarkdownReady() ? $column : "NULL AS $column"; +} + +/** ", kb_article_markdown = ..." for an UPDATE or INSERT - NULL for rich text, nothing before 4.4.3. */ +function kbMarkdownSet($markdown, $column = 'kb_article_markdown') { + global $mysqli; + if (!kbMarkdownReady()) { + return ''; + } + return ", $column = " . ($markdown === null ? 'NULL' : "'" . mysqli_real_escape_string($mysqli, (string) $markdown) . "'"); +} + /* The published articles a client's portal shows, as a WHERE condition on kb_articles. */ function kbClientSql($client_id) { $client_id = intval($client_id); @@ -263,7 +301,7 @@ function kbClosedText($level = 1) { function kbArticleRow($kb_article_id) { global $mysqli; $kb_article_id = intval($kb_article_id); - return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT kb_article_id, kb_article_title, kb_article_summary, kb_article_content, kb_article_category_id, + return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT kb_article_id, kb_article_title, kb_article_summary, kb_article_content, " . kbMarkdownSql() . ", kb_article_category_id, kb_article_published_at, kb_article_visibility, kb_article_all_clients, kb_article_review_months, kb_article_reviewed_at, kb_article_reviewed_by, " . (kbFeedbackReady() ? 'kb_article_views' : '0 AS kb_article_views') . ", kb_article_created_at, kb_article_created_by, kb_article_updated_at, kb_article_updated_by, kb_article_archived_at, @@ -280,7 +318,9 @@ function kbArticleRow($kb_article_id) { /* * An article's fields from a form - title (required), summary, category_id, * review_months, published (on or off) and content - as [fields, error]. A - * category must be a Knowledge Base one; anything else counts as none. + * category must be a Knowledge Base one; anything else counts as none. Written + * in Markdown (format, includes/document_editors.php), markdown is what was + * written and content is made from it on saving; otherwise markdown is null. */ function kbArticleFields(array $in) { $title = trim((string) ($in['title'] ?? '')); @@ -296,6 +336,7 @@ function kbArticleFields(array $in) { } $category_id = kbCategoryId($in['category_id'] ?? 0); $review_months = intval($in['review_months'] ?? 0); + $markdown = kbMarkdownReady() && ($in['format'] ?? '') === 'markdown' ? str_replace(["\r\n", "\r"], "\n", (string) ($in['markdown'] ?? '')) : null; // Who can read it - clients need a way to be picked $visibility = isset(KB_VISIBILITY[$in['visibility'] ?? '']) ? (string) $in['visibility'] : 'agents'; @@ -315,7 +356,8 @@ function kbArticleFields(array $in) { 'category_id' => $category_id, 'review_months' => isset(KB_REVIEW_MONTHS[$review_months]) ? $review_months : 0, 'published' => !empty($in['published']), - 'content' => (string) ($in['content'] ?? ''), + 'content' => $markdown === null ? (string) ($in['content'] ?? '') : '', + 'markdown' => $markdown, 'visibility' => $visibility, 'all_clients' => $all_clients, 'client_tag_ids' => $client_tag_ids, @@ -372,7 +414,7 @@ function kbArticleDir($kb_article_id) { return dirname(__DIR__) . '/uploads/kb/' . intval($kb_article_id); } -/** Keep what an article says now as a version, before it changes. */ +/** Keep what an article says now as a version, before it changes - its Markdown too, when it is written in it. */ function kbKeepVersion(array $row) { global $mysqli; $by = intval($row['kb_article_updated_by']) ?: intval($row['kb_article_created_by']); @@ -380,7 +422,8 @@ function kbKeepVersion(array $row) { mysqli_query($mysqli, "INSERT INTO kb_article_versions SET kb_article_version_title = '" . escapeSql($row['kb_article_title']) . "', kb_article_version_summary = '" . escapeSql((string) $row['kb_article_summary']) . "', - kb_article_version_content = '" . mysqli_real_escape_string($mysqli, (string) $row['kb_article_content']) . "', + kb_article_version_content = '" . mysqli_real_escape_string($mysqli, (string) $row['kb_article_content']) . "' + " . kbMarkdownSet($row['kb_article_markdown'] ?? null, 'kb_article_version_markdown') . ", kb_article_version_created_at = '$at', kb_article_version_created_by = $by, kb_article_version_kb_article_id = " . intval($row['kb_article_id'])); @@ -389,11 +432,14 @@ function kbKeepVersion(array $row) { /* * Save an article - a new one ($row null), or a change to $row, which keeps * what it said before as a version when its words change. Images pasted into - * the editor go into its folder. Its id. + * the editor go into its folder. With markdown (a string - null or left out + * for rich text) its content is the HTML made from that, and pictures pasted + * into the Markdown go into its folder too. Its id. */ function kbArticleSave(array $f, $row = null) { global $mysqli, $session_user_id; $user_id = intval($session_user_id ?? 0); + $markdown = kbMarkdownReady() && isset($f['markdown']) ? str_replace(["\r\n", "\r"], "\n", (string) $f['markdown']) : null; if ($row === null) { mysqli_query($mysqli, "INSERT INTO kb_articles SET kb_article_title = '" . escapeSql($f['title']) . "', kb_article_content = '', kb_article_content_raw = '', kb_article_created_by = $user_id"); @@ -401,18 +447,26 @@ function kbArticleSave(array $f, $row = null) { $published_sql = $f['published'] ? 'NOW()' : 'NULL'; } else { $kb_article_id = intval($row['kb_article_id']); - if ($f['title'] !== $row['kb_article_title'] || $f['summary'] !== (string) $row['kb_article_summary'] || $f['content'] !== (string) $row['kb_article_content']) { + $was_markdown = $row['kb_article_markdown'] ?? null; + $words_changed = $markdown !== null ? $markdown !== $was_markdown : ($was_markdown !== null || $f['content'] !== (string) $row['kb_article_content']); + if ($words_changed || $f['title'] !== $row['kb_article_title'] || $f['summary'] !== (string) $row['kb_article_summary']) { kbKeepVersion($row); } // Published stays when it was - its date is when it first went out $published_sql = $f['published'] ? ($row['kb_article_published_at'] ? 'kb_article_published_at' : 'NOW()') : 'NULL'; } - $content = saveBase64Images($f['content'], dirname(__DIR__) . '/uploads/kb/', 'uploads/kb/', $kb_article_id); + if ($markdown !== null) { + $markdown = markdownSaveImages($markdown, $kb_article_id, 'kb'); + $content = markdownToHtml($markdown); + } else { + $content = saveBase64Images($f['content'], dirname(__DIR__) . '/uploads/kb/', 'uploads/kb/', $kb_article_id); + } mysqli_query($mysqli, "UPDATE kb_articles SET kb_article_title = '" . escapeSql($f['title']) . "', kb_article_summary = " . ($f['summary'] !== '' ? "'" . escapeSql($f['summary']) . "'" : 'NULL') . ", kb_article_content = '" . mysqli_real_escape_string($mysqli, $content) . "', - kb_article_content_raw = '" . escapeSql(kbArticleContentRaw($f['title'], $f['summary'], $content)) . "', + kb_article_content_raw = '" . escapeSql(kbArticleContentRaw($f['title'], $f['summary'], $content)) . "' + " . kbMarkdownSet($markdown) . ", kb_article_category_id = " . intval($f['category_id']) . ", kb_article_review_months = " . intval($f['review_months']) . ", kb_article_published_at = $published_sql, @@ -533,13 +587,14 @@ function kbArticleDelete($kb_article_id) { /* * A new draft article from a client's document - its name, description and - * content, with copies of its images. The caller has checked the document's - * client. The article's id, or 0. + * content, with copies of its images. A document written in Markdown makes an + * article written in Markdown. The caller has checked the document's client. + * The article's id, or 0. */ function kbArticleFromDocument($document_id) { global $mysqli; $document_id = intval($document_id); - $doc = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT document_name, document_description, document_content FROM documents WHERE document_id = $document_id")); + $doc = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT document_name, document_description, document_content, " . documentMarkdownSql() . " FROM documents WHERE document_id = $document_id")); if (!$doc) { return 0; } @@ -553,12 +608,15 @@ function kbArticleFromDocument($document_id) { ]); $from = dirname(__DIR__) . "/uploads/documents/$document_id"; $content = (string) $doc['document_content']; + $markdown = $doc['document_markdown'] ?? null; if (is_dir($from)) { copyDirectory($from, kbArticleDir($kb_article_id)); $content = str_replace("/uploads/documents/$document_id/", "/uploads/kb/$kb_article_id/", $content); + $markdown = $markdown === null ? null : str_replace("/uploads/documents/$document_id/", "/uploads/kb/$kb_article_id/", $markdown); } mysqli_query($mysqli, "UPDATE kb_articles SET kb_article_content = '" . mysqli_real_escape_string($mysqli, $content) . "', kb_article_content_raw = '" . escapeSql(kbArticleContentRaw($doc['document_name'], (string) $doc['document_description'], $content)) . "' + " . kbMarkdownSet($markdown) . " WHERE kb_article_id = $kb_article_id"); return $kb_article_id; } diff --git a/functions/markdown.php b/functions/markdown.php index 5c38082cb..4e3be559e 100644 --- a/functions/markdown.php +++ b/functions/markdown.php @@ -201,17 +201,19 @@ function htmlToMarkdown($html, &$notes = null) { /** * Pictures pasted into a Markdown document arrive as data - each is saved under * uploads/documents//, as a picture pasted into the rich text editor is, and the - * Markdown points at the file instead. + * Markdown points at the file instead. A Knowledge Base article's go under uploads/kb// + * ($folder 'kb'). */ -function markdownSaveImages($markdown, $document_id) { +function markdownSaveImages($markdown, $document_id, $folder = 'documents') { $document_id = intval($document_id); - return preg_replace_callback('#data:image/(png|jpe?g|gif|webp);base64,([A-Za-z0-9+/=\r\n]+)#i', function ($m) use ($document_id) { + $folder = $folder === 'kb' ? 'kb' : 'documents'; + return preg_replace_callback('#data:image/(png|jpe?g|gif|webp);base64,([A-Za-z0-9+/=\r\n]+)#i', function ($m) use ($document_id, $folder) { $binary = base64_decode(preg_replace('/\s+/', '', $m[2]), true); if ($binary === false || $binary === '' || @getimagesizefromstring($binary) === false) { return $m[0]; } $ext = strtolower($m[1]) === 'jpeg' ? 'jpg' : strtolower($m[1]); - $dir = dirname(__DIR__) . "/uploads/documents/$document_id"; + $dir = dirname(__DIR__) . "/uploads/$folder/$document_id"; if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) { return $m[0]; } @@ -219,7 +221,7 @@ function markdownSaveImages($markdown, $document_id) { if (file_put_contents("$dir/$filename", $binary) === false) { return $m[0]; } - return "/uploads/documents/$document_id/$filename"; + return "/uploads/$folder/$document_id/$filename"; }, (string) $markdown); } diff --git a/includes/document_editors.php b/includes/document_editors.php index d4028223e..9368593a1 100644 --- a/includes/document_editors.php +++ b/includes/document_editors.php @@ -7,14 +7,19 @@ * switched either way as it is written (js/document_markdown.js). The form posts format, with * content or markdown (documentPostedContent()). * - * Used by New and Edit Document (agent/modals/document/document_form.php) and New Document in the - * client portal (client/document_add.php). Expects the escaped $document_content, and + * Used by New and Edit Document (agent/modals/document/document_form.php), New Document in the + * client portal (client/document_add.php) and New and Edit Article in the Knowledge Base + * (agent/modals/kb/kb_article_form.php). Expects the escaped $document_content, and * $document_markdown - what a Markdown document says, raw, or unset or null for rich text. With * $document_format_remember it starts in the way of writing used last in this browser; with * $document_editor_required something has to be written in it (js/portal.js checks). + * $document_editor_rich_class is the rich text editor's (tinymce-document unless set - an article + * keeps its own, tinymce), and $document_editor_markdown_ready whether Markdown can be saved + * where this posts (documentMarkdownReady() unless set - kbMarkdownReady() for an article). */ -$document_markdown_ready = documentMarkdownReady(); +$document_markdown_ready = isset($document_editor_markdown_ready) ? (bool) $document_editor_markdown_ready : documentMarkdownReady(); +$document_rich_class = in_array($document_editor_rich_class ?? '', ['tinymce', 'tinymce-document'], true) ? $document_editor_rich_class : 'tinymce-document'; $document_is_markdown = $document_markdown_ready && isset($document_markdown) && $document_markdown !== null; $document_format_uid = bin2hex(random_bytes(4)); $document_editor_required = !empty($document_editor_required); @@ -34,7 +39,7 @@ $document_editor_required = !empty($document_editor_required);
> - +
From 2de909ed81ce4caa0a4377819531fe333abeec98 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Thu, 3 Dec 2026 00:35:55 -0500 Subject: [PATCH 7/8] Knowledge Base API: api/v1/kb_articles read (by words, category, who can read them, published, a client's portal, archived; one article with its versions), create, update, archive, unarchive and delete over functions/kb.php with Markdown, audiences, review and tags, Support levels, no target client for agents limited to some clients, categories/read.php kind=kb; Markdown tables bordered when an article goes into a ticket reply; 26.12.5 changelog --- CHANGELOG.md | 4 +- api/v1/categories/read.php | 4 +- api/v1/enforce_api_rbac.php | 7 +- api/v1/kb_articles/archive.php | 37 +++++ api/v1/kb_articles/create.php | 52 ++++++ api/v1/kb_articles/delete.php | 35 ++++ api/v1/kb_articles/kb_article_model.php | 210 ++++++++++++++++++++++++ api/v1/kb_articles/read.php | 90 ++++++++++ api/v1/kb_articles/unarchive.php | 36 ++++ api/v1/kb_articles/update.php | 51 ++++++ functions/kb.php | 18 +- 11 files changed, 537 insertions(+), 7 deletions(-) create mode 100644 api/v1/kb_articles/archive.php create mode 100644 api/v1/kb_articles/create.php create mode 100644 api/v1/kb_articles/delete.php create mode 100644 api/v1/kb_articles/kb_article_model.php create mode 100644 api/v1/kb_articles/read.php create mode 100644 api/v1/kb_articles/unarchive.php create mode 100644 api/v1/kb_articles/update.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 291611932..a6136a1ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,8 @@ Update from Maintenance > Update as usual. This release has two database changes - Cron leaves alone the jobs that have nothing to do on your ITFlow - what they work with is switched off or isn't set up: AI Triage, Text Messages, RMM Sync and RMM Alerts, the Ticket Email Parser with email to ticket off or no mailbox, the Mail Queue with no mail server, Payment Provider Fees without Stripe, the Update Check on an install that isn't a git checkout, and Manager Check-in and Managed Instances when there's nothing connected. Before, each one started every minute only to stop itself. Maintenance > Cron shows them as **Not in use**, with why under each; they start by themselves once that changes, and **Run Now** still runs them. Cron Watch doesn't email about them falling behind. - An API / service account no longer takes a seat on the agent user limit - the one your hosting provider sets, or one set for your installation. Nobody signs in as it: it's the login an integration's API keys act as. You can add one, enable one or restore one when every seat is taken, and Admin > Users shows the seats without them. Turning one back into an agent who signs in takes a seat, so there has to be one free. A hosted instance's manager sees it the same way: its seats taken leave API accounts out, and its list of agents marks them. - Unlock your credentials with a passkey. When a passkey sign-in leaves them locked although your passkey opens them - signing in by scanning a QR code with your phone, or some password managers' autofill - the Unlock window offers **Unlock with a Passkey** before your password, with any passkey of yours that opens them. It's there while passkeys are on in Admin > Settings > Security. -- Knowledge Base articles can be written in Markdown, as documents can. New and Edit Article have the same **Rich text** / **Markdown** switch and Markdown toolbar with Write and Preview, and switching either way converts what's written. A new article starts the way you wrote last. Saved versions keep their Markdown, so putting one back brings back what was written then. **Import Markdown Files**, in the New Article menu, makes each .md file an article - a draft for agents only, in the category you pick - and **Export** on an article now has **Markdown (.md)** beside PDF. A document written in Markdown copied into the Knowledge Base arrives in Markdown, and with Write up for the Knowledge Base in Markdown the AI's draft comes in as Markdown. The client portal, the public help center, search, ticket replies and PDFs show a Markdown article like any other. +- Knowledge Base articles can be written in Markdown, as documents can. New and Edit Article have the same **Rich text** / **Markdown** switch and Markdown toolbar with Write and Preview, and switching either way converts what's written. A new article starts the way you wrote last. Saved versions keep their Markdown, so putting one back brings back what was written then. **Import Markdown Files**, in the New Article menu, makes each .md file an article - a draft for agents only, in the category you pick - and **Export** on an article now has **Markdown (.md)** beside PDF. A document written in Markdown copied into the Knowledge Base arrives in Markdown, and with Write up for the Knowledge Base in Markdown the AI's draft comes in as Markdown. The client portal, the public help center, search, ticket replies and PDFs show a Markdown article like any other - its tables keep their lines in an emailed reply too. +- The Knowledge Base is in the API. An integration can find articles - by words, category, who can read them, drafts, or what a client's portal shows - and write, change, archive and delete them, in rich text or Markdown, with who can read them, their category, review and tags. A change keeps the version before, as in ITFlow. It takes Support in the key's role, and Full to delete. See the API reference under Tickets. - Password managers fill your password in the Unlock window. Bitwarden and the like offer the ITFlow password they keep for signing in, as they do on the sign-in page - handy where your passkey can't open your credentials itself, as with passkeys kept in Bitwarden. ### Bug Fixes @@ -33,6 +34,7 @@ Update from Maintenance > Update as usual. This release has two database changes - Cron and runs outside it (database 4.4.2, `cron_jobs.cron_job_outside_at`): `cron/includes/cron_lock.php` gains `cronLockFile()`, `cronLockHolder()`, `cronLockFileProblem()`, `cronLockDispatchBeat()`, `cronLockOutsideFile()`, `cronLockAttended()` and `cronLockRunAsOwner()`, run first: started as root on an install whose `cron/cron.php` is another user's, it calls `posix_initgroups()`, `posix_setgid()` and `posix_setuid()` to become that user, or exits saying how to run it. `cronLockAcquire($path, $stamp)` returns null for a lock file it can't open (it used to `die()`, ending the dispatch at that job), and writes `direct` or `terminal` into the file while a run on its own holds it. The dispatcher touches the heartbeat file each cycle; a run on its own without a terminal on STDIN (`stream_isatty()`) while it is under 180 seconds old exits 0, quietly, and touches its `.outside` file. The dispatcher records that file's time, or a lock found held by a `direct` run, as `cron_job_outside_at` (`cronJobNoteOutside()`, at most every ten minutes), and fails a job whose lock can't be opened with `cronLockFileProblem()` as its error (`cronJobLockFailed()`, logged to App Logs once). `functions/cron_health.php`: `cronStrayLines()` reads `/etc/crontab` and the `/etc/cron.d` files cron would read for lines that run this install's job scripts on their own (anything in `cron/` but `cron.php`, and the old `scripts/cron*.php` and `cron_*.php`), `cronStrayText()`, `cronStrayWhat()`, `cronOutsideJobs()` (the last `CRON_HEALTH_OUTSIDE_HOURS`, 26), `cronOutsideReady()` and `cronFilesOwner()`; `cronHealthProblems()` adds a `stray` problem and an `outside` one per job the lines don't cover, and doesn't call a job overdue while it is run outside. `health.php` leaves both kinds out, so an uptime monitor doesn't go red for them. Maintenance > Cron has a card for the lines (`data-cron-stray`, `data-cron-stray-line`) and a note on each job run outside (`data-cron-outside`); Debug's Background jobs adds Old cron lines. CONTRIBUTING.md has the rule. - Passkeys sealed to the vault after they were added (`functions/passkey.php`, no database change): `login_passkey.php` keeps a passkey's PRF result for the session when it has no `passkey_vault` that opens with it - `passkeySealKeep()`, AES-256-GCM in `$_SESSION['passkey_seal']` with its key in the httponly `passkey_seal_key` cookie, set as `user_encryption_session_key` is - and once the vault opens, `vaultUnlock()` or the new `vaultUnlockPasskey()` seals the vault key to it (`passkeySealKept()`, checked to open before `passkey_vault` is written; the kept secret is dropped either way, and logout clears the cookie). `vaultUnlockPasskey()` checks an assertion for the new `unlock` challenge purpose against the signed-in agent's own passkeys - `passkeyVerify($post, $purpose, $user_id)`, which `passkeyVerifySignIn()` now wraps - and opens the vault with its PRF result; a passkey whose copy doesn't open with it keeps that result for the password to seal. `passkeyUnlockOptions()`, `passkeyVaultCount()` and `passkeySealPending()` feed the Unlock window (`includes/footer.php`, `[data-vault-unlock-passkey]`), and `agent/ajax.php` adds `vault_unlock_passkey_options` and `vault_unlock_passkey` (POST, CSRF). `js/passkey.js` handles the button, runs once per page (`window.itflowPasskeys`) and fires `itflow:vault-unlocked` on `#vaultUnlockModal`, which `js/credentials.js` now listens for. A passkey that doesn't unlock is logged as Login / Unlock Failed. `vaultLockedReason()` for a passkey sign-in now reads "your passkey sign-in didn't open them". The Unlock window's form drops `autocomplete="off"` and carries the agent's email in a hidden `autocomplete="username"` field (as `join.php` does), so password managers match it to the sign-in they keep. - Knowledge Base articles in Markdown (database 4.4.3): `kb_articles.kb_article_markdown` and `kb_article_versions.kb_article_version_markdown` (NULL for rich text), with `kbMarkdownReady()`, `kbMarkdownSql()` and `kbMarkdownSet()` in `functions/kb.php`. `kbArticleFields()` reads `format` and `markdown`; `kbArticleSave()` takes `markdown` and stores `kb_article_content` as `markdownToHtml()` of it, so every reader of `kb_article_content` is unchanged; `kbKeepVersion()`, the version restore, `copy_kb_article` and `kbArticleFromDocument()` carry it (with picture paths moved to the new article's folder). `markdownSaveImages()` takes a third `$folder` ('kb' for `uploads/kb//`). `includes/document_editors.php` takes `$document_editor_rich_class` and `$document_editor_markdown_ready`, which `agent/modals/kb/kb_article_form.php` sets to keep `.tinymce` and `kbMarkdownReady()`. New: `export_kb_article_markdown` and `import_markdown_kb_articles` in `agent/post/kb.php` and `agent/modals/kb/kb_import_markdown.php`. The write-up from a ticket uses `itflowDocumentFormat.putHtml()` when its form is in Markdown. +- Knowledge Base API (`api/v1/kb_articles/`): `read.php` (`kb_article_id` with its versions, or a list by `q`, `category_id`, `visibility`, `published`, `client_id` - what that client's portal shows - and `archived`), `create.php`, `update.php`, `archive.php`, `unarchive.php` and `delete.php` over `functions/kb.php`, and `categories/read.php` takes `kind=kb` - `kbApiFields()` in `kb_article_model.php` maps the API's `kb_article_*` fields onto `kbArticleFields()` over the article as it stands, `kbArticleSave()` saves (versions and Markdown as on the pages), and `kbApiRow()` gives typed rows with the audience, review state, public address and, for one article, `kbApiVersions()`. The endpoints answer 403 while the Knowledge Base module is off, and 400 or 404 with what was wrong. `enforce_api_rbac.php` maps `kb_articles` to `module_support` and leaves it out of the write target-client check (`$resource_without_client`); a limited agent's update keeps the clients it can't reach, which its reads don't show. `kbArticleRow()`'s query is `kbArticleSelectSql()`, shared with the list. `kbArticleReplyHtml()` gives a `table-bordered` table `border="1"`, `cellpadding` and `border-collapse` for email. ## [26.12.4] diff --git a/api/v1/categories/read.php b/api/v1/categories/read.php index 6088c7423..734376f32 100644 --- a/api/v1/categories/read.php +++ b/api/v1/categories/read.php @@ -11,7 +11,7 @@ * api_key required - Your API key * kind optional - Expense, Income, Referral, Ticket, network_interface, * asset_status, software_type, rack_type, - * contact_note_type or asset_note_type (or what + * contact_note_type, kb or asset_note_type (or what * Admin > Categories calls it - "Asset Status"), * in any case * category_id optional - One category, archived or not @@ -31,7 +31,7 @@ * * Only the kinds whose records the key's user can read - expense categories * need Financial, income categories Sales or Financial, referrals and contact - * note types Clients, the rest Support. + * note types Clients, the rest - Knowledge Base categories (kb) among them - Support. */ require_once '../validate_api_key.php'; diff --git a/api/v1/enforce_api_rbac.php b/api/v1/enforce_api_rbac.php index 46b6ab438..36e5abab6 100644 --- a/api/v1/enforce_api_rbac.php +++ b/api/v1/enforce_api_rbac.php @@ -163,6 +163,8 @@ $resource_module = [ 'tasks' => 'module_support', 'task_approvals' => 'module_support', 'recurring_tickets' => 'module_support', + // Knowledge Base articles - api/v1/kb_articles/ also wants the Knowledge Base switched on (kbOn()) + 'kb_articles' => 'module_support', 'clients' => 'module_client', 'contacts' => 'module_client', 'contact_notes' => 'module_client', @@ -272,7 +274,10 @@ $client_id_supplied = isset($_POST['client_id']) || isset($_GET['client_id']); // client's record just as update does, so they name a client the user can reach too. // Listing the reads, not the writes, keeps a new kind of write from slipping past. $is_write = !in_array($operation_file, ['read.php', 'time.php', 'download.php'], true); -if ($is_write && !apiUserCanAccessClient($client_id)) { +// Records that are no client's - Knowledge Base articles - take no target client, as on their pages: +// an agent limited to some clients writes them there too +$resource_without_client = ['kb_articles']; +if ($is_write && !in_array($resource, $resource_without_client, true) && !apiUserCanAccessClient($client_id)) { // Writes act on a single client the caller names (client_id 0 = a global record). // The user must be able to access it - this also blocks a restricted user from // writing global (client_id 0) records, which their access does not include. diff --git a/api/v1/kb_articles/archive.php b/api/v1/kb_articles/archive.php new file mode 100644 index 000000000..dd9bf428b --- /dev/null +++ b/api/v1/kb_articles/archive.php @@ -0,0 +1,37 @@ + Settings > Modules. + */ + +isset($mysqli) || die("Direct file access is not allowed"); + +require_once __DIR__ . '/../../../includes/load_global_settings.php'; + +// The Knowledge Base switched off +if (!kbOn()) { + http_response_code(403); + echo json_encode(['success' => 'False', 'message' => moduleOffText('kb')]); + exit(); +} + +/* A call that can't be done - its status and why, and stop. */ +function kbApiFail($message, $status = 400) { + http_response_code($status); + echo json_encode(['success' => 'False', 'message' => $message]); + exit(); +} + +/* A list sent as an array or comma-separated - its trimmed, non-empty values. */ +function kbApiList($value) { + $values = is_array($value) ? $value : explode(',', (string) $value); + return array_values(array_filter(array_map(function ($v) { + return trim((string) $v); + }, $values), 'strlen')); +} + +/* 1, true, "yes" - on; anything else off. */ +function kbApiOn($value) { + return in_array(strtolower(trim(var_export($value, true), "'")), ['1', 'true', 'yes', 'on'], true); +} + +/* + * One article as the API gives it - $row from kbArticleRow() or kbArticleSelectSql(), $audience + * from kbAudiencesFor(). Clients it is shared with by name are the ones the key's user can reach. + * $versions, for one article asked for: its earlier versions, newest first. + */ +function kbApiRow(array $row, array $audience, $versions = null) { + $review = kbReviewState($row); + $published = !empty($row['kb_article_published_at']); + $public = $published && empty($row['kb_article_archived_at']) && $row['kb_article_visibility'] === 'public' && kbPublicOn(); + $out = [ + 'kb_article_id' => intval($row['kb_article_id']), + 'kb_article_title' => $row['kb_article_title'], + 'kb_article_summary' => (string) $row['kb_article_summary'] !== '' ? $row['kb_article_summary'] : null, + 'kb_article_content' => (string) $row['kb_article_content'], + 'kb_article_markdown' => $row['kb_article_markdown'] ?? null, + 'kb_article_format' => ($row['kb_article_markdown'] ?? null) !== null ? 'markdown' : 'html', + 'kb_article_category_id' => intval($row['kb_article_category_id']), + 'kb_article_category_name' => intval($row['kb_article_category_id']) > 0 ? ($row['category_name'] ?? null) : null, + 'kb_article_published_at' => $row['kb_article_published_at'] ?? null, + 'kb_article_visibility' => $row['kb_article_visibility'], + 'kb_article_all_clients' => intval($row['kb_article_all_clients']) === 1, + 'kb_article_client_tag_ids' => array_map('intval', array_column($audience['tags'] ?? [], 'tag_id')), + 'kb_article_client_ids' => array_values(array_filter(array_map('intval', array_keys($audience['clients'] ?? [])), 'hasClientAccess')), + 'kb_article_review_months' => intval($row['kb_article_review_months']), + 'kb_article_reviewed_at' => $row['kb_article_reviewed_at'] ?? null, + 'kb_article_next_review' => $review ? $review['next'] : null, + 'kb_article_review_due' => $review ? (bool) $review['due'] : false, + 'kb_article_views' => intval($row['kb_article_views'] ?? 0), + 'kb_article_created_at' => $row['kb_article_created_at'], + 'kb_article_created_by' => intval($row['kb_article_created_by']), + 'kb_article_created_by_name' => $row['created_by_name'] ?? null, + 'kb_article_updated_at' => $row['kb_article_updated_at'] ?? null, + 'kb_article_updated_by' => intval($row['kb_article_updated_by']), + 'kb_article_updated_by_name' => $row['updated_by_name'] ?? null, + 'kb_article_archived_at' => $row['kb_article_archived_at'] ?? null, + 'kb_article_public_url' => $public ? kbPublicUrl($row['kb_article_id'], $row['kb_article_title']) : null, + ]; + if ($versions !== null) { + $out['kb_article_versions'] = $versions; + } + return $out; +} + +/* An article's earlier versions, newest first - when each was saved, by whom, its title and whether it was in Markdown. */ +function kbApiVersions($kb_article_id) { + global $mysqli; + $versions = []; + $sql = mysqli_query($mysqli, "SELECT kb_article_version_id, kb_article_version_title, kb_article_version_created_at, kb_article_version_created_by, + " . kbMarkdownSql('kb_article_version_markdown') . ", user_name + FROM kb_article_versions LEFT JOIN users ON user_id = kb_article_version_created_by AND kb_article_version_created_by > 0 + WHERE kb_article_version_kb_article_id = " . intval($kb_article_id) . " + ORDER BY kb_article_version_created_at DESC, kb_article_version_id DESC"); + while ($sql && $row = mysqli_fetch_assoc($sql)) { + $versions[] = [ + 'kb_article_version_id' => intval($row['kb_article_version_id']), + 'kb_article_version_title' => $row['kb_article_version_title'], + 'kb_article_version_created_at' => $row['kb_article_version_created_at'], + 'kb_article_version_created_by' => intval($row['kb_article_version_created_by']), + 'kb_article_version_created_by_name' => $row['user_name'] ?? null, + 'kb_article_version_format' => $row['kb_article_version_markdown'] !== null ? 'markdown' : 'html', + ]; + } + return $versions; +} + +/* + * What kbArticleFields() reads, from what the API was sent, over the article as it stands ($row, + * kbArticleRow()) - or a new article's starting values: a draft for agents only, reviewed every + * year. Anything left out stays as it is. [fields, error]. + */ +function kbApiFields(array $post, $row = null) { + if ($row) { + $in = [ + 'title' => $row['kb_article_title'], + 'summary' => (string) $row['kb_article_summary'], + 'category_id' => intval($row['kb_article_category_id']), + 'review_months' => intval($row['kb_article_review_months']), + 'published' => !empty($row['kb_article_published_at']), + ] + kbAudienceFields($row); + // Clients already on it stay, even ones the key's user can't reach - as on the pages + $in['keep_client_ids'] = $in['client_ids']; + } else { + $in = ['title' => '', 'summary' => '', 'category_id' => 0, 'review_months' => 12, 'published' => false, + 'visibility' => 'agents', 'all_clients' => false, 'client_tag_ids' => [], 'client_ids' => [], 'keep_client_ids' => []]; + } + + if (array_key_exists('kb_article_title', $post)) { + $in['title'] = (string) $post['kb_article_title']; + } + if (array_key_exists('kb_article_summary', $post)) { + $in['summary'] = (string) $post['kb_article_summary']; + } + if (array_key_exists('kb_article_category_id', $post)) { + $category_id = intval($post['kb_article_category_id']); + if ($category_id > 0 && kbCategoryId($category_id) === 0) { + return [[], "kb_article_category_id $category_id isn't a Knowledge Base category - categories/read.php?kind=kb lists them, and 0 is none."]; + } + $in['category_id'] = max(0, $category_id); + } + if (array_key_exists('kb_article_review_months', $post)) { + $in['review_months'] = intval($post['kb_article_review_months']); + if (!isset(KB_REVIEW_MONTHS[$in['review_months']])) { + return [[], 'kb_article_review_months is how often it is reviewed: 0 (never), 3, 6, 12 or 24.']; + } + } + if (array_key_exists('kb_article_published', $post)) { + $in['published'] = kbApiOn($post['kb_article_published']); + } + + // Who can read it + if (array_key_exists('kb_article_visibility', $post)) { + $in['visibility'] = strtolower(trim((string) $post['kb_article_visibility'])); + if (!isset(KB_VISIBILITY[$in['visibility']])) { + return [[], 'kb_article_visibility is agents, clients or public.']; + } + } + if (array_key_exists('kb_article_all_clients', $post)) { + $in['all_clients'] = kbApiOn($post['kb_article_all_clients']); + } + if (array_key_exists('kb_article_client_tag_ids', $post)) { + $asked = array_map('intval', kbApiList($post['kb_article_client_tag_ids'])); + $missing = array_diff($asked, kbClientTagIds($asked)); + if ($missing) { + return [[], 'kb_article_client_tag_ids: ' . implode(', ', $missing) . " isn't a client tag - tags/read.php?kind=client lists them."]; + } + $in['client_tag_ids'] = $asked; + } + if (array_key_exists('kb_article_client_ids', $post)) { + $asked = array_map('intval', kbApiList($post['kb_article_client_ids'])); + $missing = array_diff($asked, kbClientIds($asked, $in['keep_client_ids'])); + if ($missing) { + return [[], 'kb_article_client_ids: ' . implode(', ', $missing) . " isn't a client the user linked to this API key can reach."]; + } + // The clients it is shared with that the key's user can't reach aren't in what they read (kbApiRow()), so they stay + $unseen = array_values(array_filter($in['keep_client_ids'], function ($id) { + return !hasClientAccess($id); + })); + $in['client_ids'] = array_values(array_unique(array_merge($asked, $unseen))); + } + + // What it says - in Markdown, as HTML, or as it is + if (array_key_exists('kb_article_markdown', $post)) { + if (!kbMarkdownReady()) { + return [[], 'Articles in Markdown come with database 4.4.3 - run the database update from Maintenance > Update first.']; + } + $in['format'] = 'markdown'; + $in['markdown'] = (string) $post['kb_article_markdown']; + } elseif (array_key_exists('kb_article_content', $post)) { + $in['content'] = (string) $post['kb_article_content']; + } elseif ($row && ($row['kb_article_markdown'] ?? null) !== null) { + $in['format'] = 'markdown'; + $in['markdown'] = $row['kb_article_markdown']; + } elseif ($row) { + $in['content'] = (string) $row['kb_article_content']; + } + + return kbArticleFields($in); +} + +/* The article named by kb_article_id - or a 404. */ +function kbApiArticle($kb_article_id) { + $row = kbArticleRow($kb_article_id); + if (!$row) { + kbApiFail('No Knowledge Base article has that kb_article_id.', 404); + } + return $row; +} diff --git a/api/v1/kb_articles/read.php b/api/v1/kb_articles/read.php new file mode 100644 index 000000000..56473c8dd --- /dev/null +++ b/api/v1/kb_articles/read.php @@ -0,0 +1,90 @@ + 0) { + $found = []; + while ($row = mysqli_fetch_assoc($sql)) { + $found[intval($row['kb_article_id'])] = $row; + } + $audiences = kbAudiencesFor(array_keys($found)); + $one = isset($_GET['kb_article_id']); + $rows = []; + foreach ($found as $kb_article_id => $row) { + $rows[] = kbApiRow($row, $audiences[$kb_article_id] ?? [], $one ? kbApiVersions($kb_article_id) : null); + } + $rows = tagApiAttach($rows, 'kb_article'); + echo json_encode(['success' => 'True', 'count' => count($rows), 'data' => $rows]); + exit(); +} + +// Output - nothing found +require_once '../read_output.php'; diff --git a/api/v1/kb_articles/unarchive.php b/api/v1/kb_articles/unarchive.php new file mode 100644 index 000000000..5b89fb9a9 --- /dev/null +++ b/api/v1/kb_articles/unarchive.php @@ -0,0 +1,36 @@ +]*\bclass="[^"]*\btable-bordered\b[^"]*"[^>]*)>#i', function ($m) { + if (preg_match('/\sborder\s*=/i', $m[1])) { + return $m[0]; + } + return ''; + }, $html); return preg_replace('#\b(src|href)="/?(uploads/kb/\d+/[^"]+)"#', '$1="https://' . $config_base_url . '/$2"', $html); } @@ -301,7 +309,12 @@ function kbClosedText($level = 1) { function kbArticleRow($kb_article_id) { global $mysqli; $kb_article_id = intval($kb_article_id); - return mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT kb_article_id, kb_article_title, kb_article_summary, kb_article_content, " . kbMarkdownSql() . ", kb_article_category_id, + return mysqli_fetch_assoc(mysqli_query($mysqli, kbArticleSelectSql() . " WHERE kb_article_id = $kb_article_id")) ?: null; +} + +/** How kbArticleRow() reads an article - for a WHERE of its own (the API's list, api/v1/kb_articles/read.php). */ +function kbArticleSelectSql() { + return "SELECT kb_article_id, kb_article_title, kb_article_summary, kb_article_content, " . kbMarkdownSql() . ", kb_article_category_id, kb_article_published_at, kb_article_visibility, kb_article_all_clients, kb_article_review_months, kb_article_reviewed_at, kb_article_reviewed_by, " . (kbFeedbackReady() ? 'kb_article_views' : '0 AS kb_article_views') . ", kb_article_created_at, kb_article_created_by, kb_article_updated_at, kb_article_updated_by, kb_article_archived_at, @@ -311,8 +324,7 @@ function kbArticleRow($kb_article_id) { LEFT JOIN categories ON category_id = kb_article_category_id AND kb_article_category_id > 0 LEFT JOIN users creator ON creator.user_id = kb_article_created_by AND kb_article_created_by > 0 LEFT JOIN users updater ON updater.user_id = kb_article_updated_by AND kb_article_updated_by > 0 - LEFT JOIN users reviewer ON reviewer.user_id = kb_article_reviewed_by AND kb_article_reviewed_by > 0 - WHERE kb_article_id = $kb_article_id")) ?: null; + LEFT JOIN users reviewer ON reviewer.user_id = kb_article_reviewed_by AND kb_article_reviewed_by > 0"; } /* From 015b8a821794aeb53927b018c763849e50a9d63c Mon Sep 17 00:00:00 2001 From: johnnyq Date: Thu, 3 Dec 2026 00:36:33 -0500 Subject: [PATCH 8/8] Release 26.12.5: set the app version to 26.12.5 and add to the changelog's Upgrading section what changes when you update - cron jobs not in use, API accounts off the agent seats, passkeys opening credentials after one password unlock --- CHANGELOG.md | 3 +++ includes/app_version.php | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6136a1ba..536b5bf9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ Update from Maintenance > Update as usual. This release has two database changes - If ITFlow was installed with the install script before 26.08, `/etc/cron.d/itflow` may still have a line for each job besides the `cron.php` one - the 26.08 upgrade asked for them to come out. Maintenance > Cron now lists any it finds, with the file and line. Take them out: `cron.php` runs every job. Until then they step aside while `cron.php` is running, so nothing runs twice. - Cron started as root - a crontab line for root, or `php cron/cron.php` typed in a root shell - now runs as the user that owns ITFlow's files, so what it makes is that user's. +- Jobs with nothing to do on your ITFlow - AI Triage with no AI model, Text Messages with no provider, an RMM job with no RMM, and the others under New Features - show **Not in use** on Maintenance > Cron instead of **Completed** every minute, and start by themselves once they have something to do. +- API / service accounts stop counting against your agent seats, so a hosted instance with one shows a seat more free. +- A passkey that doesn't open your credentials yet: the first sign-in with it after the update says, when you unlock, that it will open them once you type your password. Type it, and from your next sign-in that passkey opens them by itself. Passkeys kept in Bitwarden and some other password managers never do - your password manager fills the Unlock window instead. ### New Features & Updates diff --git a/includes/app_version.php b/includes/app_version.php index 87b19ac89..b04dea9d1 100644 --- a/includes/app_version.php +++ b/includes/app_version.php @@ -5,4 +5,4 @@ * Update this file each time we merge develop into master. Format is YY.MM (add a .v if there is more than one release a month. */ -DEFINE("APP_VERSION", "26.12.4"); +DEFINE("APP_VERSION", "26.12.5");