From c20acc9ac1814a13dc769b4d37eb3d02c4ed0e76 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Thu, 19 Nov 2026 14:00:54 -0500 Subject: [PATCH] Remove RMM device actions: the Device actions switch in a provider's Edit, Actions on a device's card on its asset and beside it on a ticket, the Run a script window and their handlers are gone, along with the Tactical reboot, patch, maintenance mode and script calls behind them; database 3.6.9 is gone and 3.9.9 drops rmm_providers.rmm_provider_actions where a develop build added it; the 26.12 changelog, the demo locks and the development mode text no longer mention them --- CHANGELOG.md | 14 +- admin/backup.php | 2 +- admin/database_updates/3.6.9.php | 21 -- admin/database_updates/3.9.9.php | 22 ++ admin/modals/rmm/rmm_provider_edit.php | 28 +-- agent/asset.php | 13 +- agent/modals/rmm/rmm_script.php | 218 ------------------ agent/post/rmm.php | 151 ------------- agent/ticket.php | 16 +- db.sql | 1 - functions/demo.php | 4 - functions/dev_mode.php | 3 +- functions/rmm.php | 292 +------------------------ functions/rmm_tactical.php | 163 +------------- 14 files changed, 49 insertions(+), 899 deletions(-) delete mode 100644 admin/database_updates/3.6.9.php create mode 100644 admin/database_updates/3.9.9.php delete mode 100644 agent/modals/rmm/rmm_script.php delete mode 100644 agent/post/rmm.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 4a5166ef9..4adf49d38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading to 26.12 -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's thirty-two database changes (3.6.6 to 3.9.8) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, two settings and a column on tickets for keeping project tickets apart, a table for your other offices with a column each on agents and invites for which one they work from, three settings for the emails and notices your agents get about their tickets, three settings for sending and reading Microsoft 365 mail through Microsoft Graph, five tables, four settings and a role permission for purchase orders, five settings for switching Dispatch, Bookkeeping, Purchasing, Trips and the calendar on and off, and eight tables, three columns and two settings for the Knowledge Base, who can read its articles, what its readers think of them and their files, a column on documents for how often each is reviewed, and change nothing that is there. Nothing else is required, but it is a big release, so take a backup before you update. Purchasing starts off - switch it on in Admin > Settings > Modules - and so does the Knowledge Base's public help center, in Admin > Settings > Knowledge Base. This release has thirteen security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's thirty-two database changes (3.6.6 to 3.9.9) in the same pass. They add four tables for RMM providers and their alerts, a setting for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, two settings and a column on tickets for keeping project tickets apart, a table for your other offices with a column each on agents and invites for which one they work from, three settings for the emails and notices your agents get about their tickets, three settings for sending and reading Microsoft 365 mail through Microsoft Graph, five tables, four settings and a role permission for purchase orders, five settings for switching Dispatch, Bookkeeping, Purchasing, Trips and the calendar on and off, and eight tables, three columns and two settings for the Knowledge Base, who can read its articles, what its readers think of them and their files, a column on documents for how often each is reviewed, and change nothing that is there. Nothing else is required, but it is a big release, so take a backup before you update. Purchasing starts off - switch it on in Admin > Settings > Modules - and so does the Knowledge Base's public help center, in Admin > Settings > Knowledge Base. This release has thirteen security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. ### Security @@ -40,9 +40,6 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - RMM Providers: bill per managed device. A recurring invoice line's Quantity from has Managed devices - the client's devices your RMM has - beside Users and Devices. Like Devices it can count only some types, Desktop and Laptop for a managed workstation, Server and Virtual Machine for a managed server, or only those with a tag. With more than one RMM it can count one of them. A device the RMM no longer has stops counting at the next invoice, and lost, stolen or retired ones never count. - RMM Providers: a product can be counted Per managed device, so it bills that way on any recurring invoice it is added to - in the product window, and as Per managed device in a product import. - RMM Providers: if the RMM provider a line counted is deleted, the line stays at the quantity it last billed, marked RMM provider gone, until another is picked. Deleting a provider says how many lines bill its devices. -- RMM Providers: device actions. Turn on Device actions in a provider's Edit, and technicians who can edit assets can reboot a device, install its patches, turn its maintenance mode on and off, and run one of the RMM's scripts on it - from Actions on the device's card on its asset, or the lightning button beside the asset on a ticket. Rebooting and installing patches ask first, and say who is signed in. Installing patches is for Windows devices, and installs what the device's patch policy approves. While maintenance mode is on, Tactical raises no alerts for the device, so none opens a ticket. -- RMM Providers: Run a script lists your RMM's scripts that run on the device's system, favorites first, and starts with the script's own arguments and timeout. The output shows in the window, and the ticket you pick - the one you started from, on a ticket - gets what was run and its output as an internal note. For a long script, turn off Wait for its output: the RMM runs it and keeps the output in the device's history there. -- RMM Providers: every device action goes in the asset's history and the audit log, and on the ticket it was done from. Device actions are off for every provider until you turn them on. Tactical does each as the API key's user, so its role needs Shutdown / Reboot Agents, Manage Windows Updates, Edit Agents for maintenance mode, and List Scripts and Run Script - give it only the ones you want, and one it hasn't got says so when tried. - RMM Providers: the RMM Sync job is on Maintenance > Cron, and so is RMM Alerts, every minute. Turning a provider off stops its syncs, and Delete forgets its links - the assets stay as they are either way. API keys are kept like other providers' keys and never shown again. A Tactical RMM key can do whatever its Tactical user can, so make it for a user whose role can see clients and agents, and do the device actions you turn on, and no more. - API: invoices can be made with their lines, changed, emailed, marked sent, cancelled and deleted, and their lines changed or taken off. Emailing one sends it to the client's primary and billing contacts, or the contacts you name, with its link to view and pay - or a reminder of what is still owed. - API: quotes can be made with their lines - billed once, or each month, quarter or year - changed, emailed, marked sent, accepted or declined, and deleted. An accepted quote can be invoiced as Invoice does on its page: its one-time lines on a new invoice, the rest on recurring invoices. A quote's lines can be read, added, changed and taken off. @@ -93,7 +90,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Recurring invoices: Make it ahead makes each invoice so many days before its date, dated the day it's made, and Due, when made ahead sets it due on its date plus the client's terms, or on its date. With 0 days nothing changes. From Mountaineer IT's build of ITFlow. - Maintenance > Cron: the new Cron Watch job, every 5 minutes, emails your admins when a job fails, gets stuck or falls behind - once when it starts, again once a day while it lasts, and once more when it's fixed. The Alerts card turns the emails off, sends them to other addresses instead, and sends a test. From Mountaineer IT's build of ITFlow. - Maintenance > Cron: an email can't say cron has stopped, since cron sends it. The Alerts card has a private health address for an uptime monitor such as Uptime Kuma or UptimeRobot: it answers OK while all is well and an error when cron isn't running or a job is in trouble. Check it every 5 minutes. Make a new address if the old one gets out. From Mountaineer IT's build of ITFlow. -- Development mode, for a test copy of your ITFlow: turn it on in Admin > Backup before you restore production's backup onto a test server, and nothing reaches your clients, your team or the systems production talks to. Every email goes to a test inbox you give, with who it was for at the front of its subject. Texts wait in the queue, the ticket mailbox isn't read, AI Triage doesn't run, Stripe charges nothing (autopay included), nothing is done to RMM devices, log entries aren't sent to your syslog server, a managed ITFlow doesn't check in with its manager, and telemetry isn't sent. A red DEVELOPMENT badge shows in the top bar for everyone. It's kept in config.php rather than the database, so a restore can't turn it off. Never turn it on in production. From Mountaineer IT's build of ITFlow. +- Development mode, for a test copy of your ITFlow: turn it on in Admin > Backup before you restore production's backup onto a test server, and nothing reaches your clients, your team or the systems production talks to. Every email goes to a test inbox you give, with who it was for at the front of its subject. Texts wait in the queue, the ticket mailbox isn't read, AI Triage doesn't run, Stripe charges nothing (autopay included), log entries aren't sent to your syslog server, a managed ITFlow doesn't check in with its manager, and telemetry isn't sent. A red DEVELOPMENT badge shows in the top bar for everyone. It's kept in config.php rather than the database, so a restore can't turn it off. Never turn it on in production. From Mountaineer IT's build of ITFlow. - Maintenance > Backup: restore a backup from the page - Restore in a backup's menu, or upload one under Restoring, from another ITFlow say, with its key. An upload of up to 5 GB goes up in pieces, joins the list as Uploaded and opens its Restore window. That window says what's in the backup and refuses one from a newer version, and you confirm with your password and by typing RESTORE. Cron does it within a minute: ITFlow backs itself up first, kept as Before restore so the restore can be undone, then restores the backup and brings its database up to this version. The top of the page shows it waiting (with Cancel), running, and how it went. The command line restore is still under Restoring, for a backup of any size. From Mountaineer IT's build of ITFlow. - Admin > Labor Costs, under Lists: what an hour of each agent costs your company - wage, payroll taxes and benefits - with the date each rate counts from, so a raise doesn't change what last year cost, and a company default for agents with none. Only admins see it, and the audit log never records the amounts. From Mountaineer IT's build of ITFlow. - Reports: Client Profitability, with labor costs set, shows each client's labor cost (their hours at the cost of the agent who worked them), parts cost (the products on their invoices, at cost), profit and margin, and for flat monthly fees the hours a month their fee pays for against the hours they take, marked Over when they take more. The totals along the top add labor, parts, profit, and how many clients lose money or go over. Paid and Invoiced switch income between money received, as before, and sales before tax on invoices dated in the period. Hours by agents with no cost and no default are flagged. From Mountaineer IT's build of ITFlow. @@ -208,10 +205,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - `rmmAlertTicketOpen()` makes the ticket the way a text does (`smsTicketOpen()`): next ticket number, `ticket_source` `RMM`, `applyTicketSla()`, the new-ticket address (`ticketMailNewTicketAddress($ticket_id, 'rmm')`) and `triggerCustomAction('ticket_create')`, but no email to the client's contacts. Its notes are internal replies with `ticket_reply_by` 0, and `rmmTicketWorked()` counts any reply by someone (`ticket_reply_by` > 0). Resolving and reopening go through `ticketResolve()` and `ticketReopen()`, so the SLA clock and history follow. `ticketSourceIcon()` and the ticket page know the `RMM` source. - Seat lines have a fourth source, `managed` (`recurringSeatSources()`): the client's assets in use that have an `rmm_devices` row not marked removed (`recurringSeatManagedSql()`). Its filter takes `types` and `tag` as `assets` does, and `rmm`, a provider id - absent for any. `recurringSeatCount()` gives null for a provider that is gone, so the line keeps its quantity as it does for a license that is gone; `recurringSeatLines()` adds `seat_gone`, the words for that. `recurringSeatOptions()` adds the managed count, types and tags, and each provider's count, once an RMM is set up. `productSeatSources()` has `managed`, and the line script, product import, AI catalog text and tag merges know it. `recurringSeatManagedLineCount($provider_id)` counts the active recurring lines that bill a provider's devices. No database change - `item_seat_source` and `product_seat_source` take the new value. - `cron/rmm_alerts.php` is the `rmm_alerts` job, every minute. It stops when cron or ticketing is off, or no provider's alerts open tickets. -- Database 3.6.9: `rmm_providers.rmm_provider_actions`, 0 for every provider until an admin turns device actions on in its Edit. Re-runnable. -- Device actions are optional kind entries: `actions` (`reboot`, `patches`, `maintenance`, `script`, each with `label`, `icon`, `needs` - the permission its key's user needs there - `about`, and `platforms` when it is only for some), `act($provider, $remote_id, $action, $options)` answering `ok`, `output`, `timed_out` and `error`, and for scripts `scripts($provider, $platform)` and `script($provider, $id)`, each script in the shape described above `rmmProviderKinds()`. `actions_help` is the provider window's text. `rmmDeviceActions($row)` is what a device offers - its provider on with actions on, the device not removed, the action for its platform - and `rmmDeviceActionsMenu($row, $ticket_id)` draws them for Modify on Support. `rmmActionTarget()` checks the device and the ticket (the asset's client's, not closed), and `rmmActionRecord()` writes the asset history, the audit log (`Asset` / `RMM`) and the ticket's internal note by the person, through the new `rmmTicketNoteHtml()` that `rmmTicketNote()` now uses. -- `agent/post/rmm.php` handles `rmm_reboot`, `rmm_install_patches`, `rmm_maintenance_on` and `rmm_maintenance_off`, each with the `rmm_devices` id and an optional `ticket_id`, and `rmm_run_script` with `script_id`, `args` (one a line), `timeout` (5 to 600) and `wait`, which answers JSON when asked for it and a flash otherwise. A script run waits up to its timeout plus 30 seconds, with `set_time_limit()` to match and the session closed first, so the person's other tabs aren't held up. The window is `agent/modals/rmm/rmm_script.php`. The request keys are in `DEMO_MODE_LOCKS`. -- Tactical: `POST /agents//reboot/`, `POST /winupdate//install/`, `PUT /agents//` with `maintenance_mode`, `GET /scripts/` and `/scripts//`, and `POST /agents//runscript/` with every key its view reads - output `wait` or `forget`, and the script's own `env_vars` as Tactical's Run Script window sends them. `rmmHttp()` takes `$text_ok` for answers that are a JSON string, reads a JSON-string error body into its message, and sends `{}` for an empty body. `rmmTacticalActError()` turns a 403 into the permission the key's role needs. +- Database 3.9.9 drops `rmm_providers.rmm_provider_actions` where it is. Develop builds added it in a 3.6.9 that is no longer there; an install updating from 26.11.8 never had it. Re-runnable. - `agent/ajax.php`: the seventeen GET answers that printed JSON under PHP's default `text/html` now send `Content-Type: application/json` first - `get_credential_via_id`, `get_totp_token_via_id`, `get_readable_pass`, `get_active_clients`, `get_client_contacts`, `get_client_assets`, `get_client_locations`, `get_client_vendors`, `get_client_projects`, `get_internal_users`, `get_document_content`, `get_canned_response`, `ticket_query_views`, `client_duplicate_check`, `contact_email_check`, `network_ip_check` and `domain_check`. Their callers read the body as text (`itflowGet()`) or with `res.json()`, so nothing changes for them. A new JSON answer sets the header the same way: a value that is not escaped for HTML, as a login's username and password are not, must never go out as `text/html`. - `getFieldByIdInScope($table, $id, $field, $client_field)` (`functions/app.php`) is `getFieldById()` for a record that belongs to a client. It gives null unless `hasClientAccess()` passes for the record's client, as it does for a record that isn't there; a record with no client (0) is anyone's. Use it wherever a label is made from an id in the query string. The two labels read with their own query, on `agent/trips.php` and `agent/modals/trip/trip_export.php`, take `clientScopeSql()` instead. - `join.php` puts the login key in its sign-in link only while the invite is `pending` or `accepted` (`userInviteState()`). @@ -270,7 +264,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Database 3.7.7: `recurring_tickets.recurring_ticket_schedule_time` (NULL books nothing), `_schedule_onsite`, `_lead_days` and `_lead_mode` (days or month), and `recurring_invoices.recurring_invoice_lead_days` and `_due_mode` (terms or next) - `recurringAheadReady()`. The nightly job takes recurring tickets by `recurringTicketDueSql()` and recurring invoices up to `recurring_invoice_lead_days` ahead, made with `recurringInvoiceGenerate()`'s `$early` when the date is still to come. `recurringTicketRunNow()` calls `recurringTicketBook()`, which books through `ticketSetSchedule()` for the run day at the time (today for a missed run), as "Recurring ticket" from the cron; `recurringInvoiceGenerate()` dates an invoice made ahead with lead days due by `recurringInvoiceAheadDue()`. Days ahead are kept short of one step by `recurringTicketLeadDays()` and `recurringInvoiceLeadDays()` (a month is 28 days, 90 at most; 27 before the 1st of the month, month-based repeats only). The fields are `schedule_time`, `schedule_onsite`, `lead_days` and `lead_mode` on the recurring ticket windows (`agent/includes/inc_recurring_ticket_ahead.php`), and `lead_days` and `due_mode` on the recurring invoice form; a post without `lead_days` keeps what is saved. From Mountaineer IT's build of ITFlow. - Database 3.7.8: `ticket_replies.ticket_reply_work_start` and `ticket_reply_work_end`, in company time - `ticketWorkTimesReady()`. `add_ticket_reply` takes `work_date`, `work_start` and `work_end` (`ticketWorkRange()`; an end before the start is the next day, under 24 hours) for a note with time worked, and `ticketWorkTimeWorked()` makes the time worked their length unless it agrees to the minute; without them, or from the bulk reply, the API or email, they stay NULL - it ended when it was posted. `edit_ticket_reply` takes the same fields: changed times set the time worked, the same times with a new time worked move the start, times left as `ticketWorkTimesShown()` filled them on a note without any keep it without, and no time worked clears them. The reply box's time row is Time worked and When it was worked, above Status and Send; `agent/js/ticket_work_times.js` follows `#hours` / `#minutes` / `#seconds` from `ticket_time_tracking.js` (at least a minute), in company time from `#workTimes` `data-now`, and refuses the form in the capture phase, before the timer resets, when a note with time worked has no valid times. From Mountaineer IT's build of ITFlow. - Database 3.7.9: `config_cron_alert_email` (default 1), `config_cron_alert_to`, `config_cron_health_key` and `config_cron_alert_state` (JSON: `sent`, each problem's key and when it was last emailed; `waiting`, each job that is on and has never run and since when) - `cronHealthReady()`. `functions/cron_health.php`: `cronHealthProblems()` reads the heartbeat, `config_enable_cron` and each enabled registry job's row (not those a manager has paused) into problems with a key, kind (`not_running`, `off`, `failed`, `stuck` after `CRON_HEALTH_STUCK_MINUTES`, `overdue` - past two intervals and at least ten minutes over, or two hours past a daily time; a job never run is late once `waiting` is older than that), text and error. `cron/cron_watch.php` is the `cron_watch` job, every 5 minutes: `cronHealthWatch()` records `waiting`, then emails the problems that are new, a day old or gone with `cronHealthAlert()` through `cronHealthMail()` (`emailQueue()`, to `config_cron_alert_to`, else active admins - `cronHealthRecipients()`), leaving out `not_running` and its own; Admin > Mail previews it as `cron_alert`. `health.php` answers 200 `OK` or 503 with a line per problem, given `config_cron_health_key` as `?key=` or an `X-Health-Key` header, and 403 otherwise. `admin/post/cron.php` has `edit_cron_alerts`, `test_cron_alert` (to the addresses typed) and `renew_cron_health_key`, locked in the demo. From Mountaineer IT's build of ITFlow. -- Development mode (`functions/dev_mode.php`): `$config_dev_mode` and `$config_dev_mail_to` in config.php - `devModeOn()`, `devModeMailTo()`. `edit_dev_mode` (`admin/post/backup.php`, locked in the demo) writes both with `devModeConfigSet()`, which replaces each line or adds them at the end and invalidates opcache; when config.php can't be written, Admin > Backup shows the lines to add. `sendQueueEmail()` (`cron/mail_queue.php`) sends to `devModeMailTo()` with `[DEV to ]` in front of the subject, and with no test inbox the queue is cancelled as in the demo. `includes/stripe_init.php` calls `devModeBlockStripe()`, a `\Stripe\ApiRequestor::setHttpClient()` client that throws `ApiConnectionException`. `smsSendQueued()` leaves a text queued, `rmmDeviceAct()` refuses, `managedHttpJson()` answers not ok, and `logForwardQueue()` and `logForwardSend()` send nothing. `cron/ticket_email_parser.php`, `ai_triage.php`, `sms_queue.php`, `payment_provider_fees.php`, `manager_checkin.php` and `managed_instances.php` stop with `cronJobStop("Development mode - ...")`; `cron/nightly_tasks.php` skips autopay and telemetry. `includes/top_nav.php` shows `[data-dev-mode]`, a link to `admin/backup.php#dev-mode` for admins. From Mountaineer IT's build of ITFlow. +- Development mode (`functions/dev_mode.php`): `$config_dev_mode` and `$config_dev_mail_to` in config.php - `devModeOn()`, `devModeMailTo()`. `edit_dev_mode` (`admin/post/backup.php`, locked in the demo) writes both with `devModeConfigSet()`, which replaces each line or adds them at the end and invalidates opcache; when config.php can't be written, Admin > Backup shows the lines to add. `sendQueueEmail()` (`cron/mail_queue.php`) sends to `devModeMailTo()` with `[DEV to ]` in front of the subject, and with no test inbox the queue is cancelled as in the demo. `includes/stripe_init.php` calls `devModeBlockStripe()`, a `\Stripe\ApiRequestor::setHttpClient()` client that throws `ApiConnectionException`. `smsSendQueued()` leaves a text queued, `managedHttpJson()` answers not ok, and `logForwardQueue()` and `logForwardSend()` send nothing. `cron/ticket_email_parser.php`, `ai_triage.php`, `sms_queue.php`, `payment_provider_fees.php`, `manager_checkin.php` and `managed_instances.php` stop with `cronJobStop("Development mode - ...")`; `cron/nightly_tasks.php` skips autopay and telemetry. `includes/top_nav.php` shows `[data-dev-mode]`, a link to `admin/backup.php#dev-mode` for admins. From Mountaineer IT's build of ITFlow. - Restoring from Maintenance > Backup (`functions/backup_restore.php`): `restore_backup` (`admin/post/backup.php`) checks the password and RESTORE, then `backupRestoreQueue()` checks the archive with `backupRestoreCheck()` (`backupInspectArchive()`, refused when its database version is newer) and the disk (three times its size), writes `restore_queued.json` beside the backups - another install's key sealed with this one's (`backupRestoreSealKey()`, AES-256-GCM) - and `restore_status.json`, and sets the Backup job's `cron_job_run_now`. `cron/backup.php` calls `backupRestoreRunQueued()` after the queued backups: it deletes the request first, refuses one older than `BACKUP_RESTORE_WAIT_MINUTES`, makes a Full Backup with source `Before restore`, runs `backupRestoreArchive()`, puts that row and the restored one back in the restored `backups` (others found again by retention), marks `Running` and `Pending` rows `Failed`, runs `scripts/update_cli.php --update_db`, records the outcome and sets `$cron_dispatch_stop_cycle`. `cron/cron.php` exits before its heartbeat while `backupRestoreInProgress()`. `cancel_restore` removes a request. Uploads: `backup_upload` in one request, or `backup_upload_start`, `backup_upload_chunk` and `backup_upload_finish` from `js/backup_restore.js` (JSON, the upload in the session, pieces of `backupRestoreChunkBytes()` appended to `upload_.part`, retried smaller when a proxy refuses), then `backupRestoreAdopt()` lists it with source `Uploaded`. The Restore window is `admin/modals/backup/backup_restore.php`, opened from a row's menu or by `?restore=`; `backupMadeBy()` words a row's source. All locked in the demo. From Mountaineer IT's build of ITFlow. - Database 3.8.0: `user_cost_rates` (`user_cost_rate_user_id`, `_from`, `_hourly`, `_created_by`, `_created_at`, one a day per agent) and `config_labor_cost_default` (NULL leaves time uncosted) - `laborCostReady()`. `functions/labor_cost.php`: `laborCostRates()`, `laborCostRateOn()` (the newest rate on or before the day, the first also before it, else the default), `laborCostRateSave()`, `laborCostRateDelete()`, `laborCostParse()`. `admin/labor_costs.php`, `admin/modals/labor_cost/labor_cost_rates.php` and `labor_cost_default.php`, handlers `add_labor_cost_rate`, `delete_labor_cost_rate` and `edit_labor_cost_default` (`admin/post/labor_cost.php`). `agent/reports/client_profitability.php` calls `laborProfitAdd()` before net - `?basis=invoiced` replaces income with `item_subtotal` less `invoice_discount_amount` on Sent, Viewed, Partial and Paid invoices by `invoice_date`, plus revenue; labor by `ticket_reply_by` and day; parts as `product_cost * item_quantity` - and `laborProfitFinish()` after it for profit, margin, `hours_month` and `break_even`; the columns, totals, basis switch (`laborProfitBasis()`, paid by default) and second stats row are there only with 3.8.0. From Mountaineer IT's build of ITFlow. - Database 3.8.1: `users.user_service_account` - `serviceAccountsReady()`, `serviceAccountIs()`, `serviceAccountSave()` (`functions/service_account.php`). `serviceAccountsOutSql($column)` adds ` AND user_service_account = 0` to the agent lists and pickers (tickets, recurring tickets, projects, contracts, calendar and events, ticket templates, bulk assign, exports, reports, client onboarding, Quick ticket, mentions, trips, expenses, labor costs, Getting Started's team, user archive's hand-over, incident response) and to `appNotify()`, `signInAdmins()`, `cronHealthRecipients()` and the last-admin checks (`userActiveAdminCount()` in `functions/user.php`, `roles.php`). Not to `apiKeyAgents()`, the API's own checks (`api/v1/enforce_api_rbac.php`) or `getActiveAgentUserCount()`. `login.php` matches agents with `user_service_account = 0`, and `includes/load_user_session.php` ends a service account's session. The switch is `service_account` with `service_account_present` on `admin/modals/user/user_form.php`'s Sign in tab, saved by `add_user` (an invite with it is refused) and `edit_user`. `admin/users.php` adds the `service` view and excludes them from the others but `archived`. From Mountaineer IT's build of ITFlow. diff --git a/admin/backup.php b/admin/backup.php index b6ef9bb7b..b8c3248ca 100644 --- a/admin/backup.php +++ b/admin/backup.php @@ -603,7 +603,7 @@ $status_looks = [

For a test copy of your ITFlow. Turn it on before you restore production's backup onto it: - every email then goes to the test inbox, and texts, the ticket mailbox, AI Triage, Stripe, RMM device actions, log forwarding and check-ins with a manager are off. + every email then goes to the test inbox, and texts, the ticket mailbox, AI Triage, Stripe, log forwarding and check-ins with a manager are off. It's kept in config.php, so a restore can't turn it off. Never turn it on in production.

diff --git a/admin/database_updates/3.6.9.php b/admin/database_updates/3.6.9.php deleted file mode 100644 index 50901af38..000000000 --- a/admin/database_updates/3.6.9.php +++ /dev/null @@ -1,21 +0,0 @@ - 0) { + mysqli_query($mysqli, "ALTER TABLE `rmm_providers` DROP `rmm_provider_actions`"); + } diff --git a/admin/modals/rmm/rmm_provider_edit.php b/admin/modals/rmm/rmm_provider_edit.php index 692f782cb..16291bdab 100644 --- a/admin/modals/rmm/rmm_provider_edit.php +++ b/admin/modals/rmm/rmm_provider_edit.php @@ -5,8 +5,7 @@ * picked when it is added and stays; each kind brings its own fields (rmmProviderKinds() in * functions/rmm.php) - addresses, a key, a secret. A key or secret is never put back into the * page, so left empty it stays. A kind that has alerts can have them open tickets, from the - * level picked, in a category; one that has device actions can have them turned on, off until - * they are. Save asks first (check_rmm_provider, admin/post/rmm.php): what + * level picked, in a category. Save asks first (check_rmm_provider, admin/post/rmm.php): what * is wrong shows beside each field and the window stays open; once all is right it saves, and * tries the connection. */ @@ -28,15 +27,11 @@ $kinds = rmmProviderKinds(); $kind_key = $row ? (string) $row['rmm_provider_kind'] : (string) array_key_first($kinds); $kind = $kinds[$kind_key]; -// What the window's script needs of each kind - its name, to follow the kind picked, and whether it has alerts and device actions +// What the window's script needs of each kind - its name, to follow the kind picked, and whether it has alerts $kinds_js = array_map(function ($info) { - return ['name' => $info['name'], 'alerts' => isset($info['alerts'], $info['alert']), 'alertsHelp' => (string) ($info['alerts_help'] ?? ''), - 'actions' => !empty($info['actions']), 'actionsHelp' => (string) ($info['actions_help'] ?? '')]; + return ['name' => $info['name'], 'alerts' => isset($info['alerts'], $info['alert']), 'alertsHelp' => (string) ($info['alerts_help'] ?? '')]; }, $kinds); -// Device actions - once the 3.6.9 database update is in -$actions_offered = rmmActionsReady(); - // Alerts open tickets - once the 3.6.8 database update is in, with ticketing on $alerts_offered = rmmAlertsReady() && !empty($config_module_enable_ticketing); $alert_level = (string) ($row['rmm_provider_alert_level'] ?? ''); @@ -155,17 +150,6 @@ ob_start();
- -
-
- > - -
-
Technicians who can edit assets get them on a device's card on its asset and beside it on its tickets. Each goes in the asset's history and the audit log, and on the ticket it was done from - a script's output with it. -
-
- - -
- - - - - -
- - - ['reboot', [], 'rebooted %1$s %2$s', 'couldn\'t reboot'], - 'rmm_install_patches' => ['patches', [], 'started installing the patches on %1$s %2$s', 'couldn\'t install the patches on'], - 'rmm_maintenance_on' => ['maintenance', ['on' => true], 'turned maintenance mode on for %1$s %2$s', 'couldn\'t turn maintenance mode on for'], - 'rmm_maintenance_off' => ['maintenance', ['on' => false], 'turned maintenance mode off for %1$s %2$s', 'couldn\'t turn maintenance mode off for'], - ]; - $key = (string) array_key_first(array_intersect_key($asked, $_POST)); - [$action, $options, $did, $failed] = $asked[$key]; - - [$row, $ticket, $error] = rmmActionTarget(intval($_POST[$key]), intval($_POST['ticket_id'] ?? 0), $action); - if ($row) { - $client_id = intval($row['asset_client_id']); - enforceClientAccess(); - } - if ($error !== '') { - flashAlert(escapeHtml($error), 'error'); - redirect(); - } - - $name = rmmProviderName($row); - $host = rmmActionHost($row); - $answer = rmmDeviceAct($row, $action, $options); - if (!$answer['ok']) { - flashAlert(escapeHtml("$name $failed $host. {$answer['error']}"), 'error'); - redirect(); - } - - // Maintenance mode shows straight away - the next sync says the same - if ($action === 'maintenance') { - mysqli_query($mysqli, "UPDATE rmm_devices SET rmm_device_maintenance = " . (empty($options['on']) ? 0 : 1) . " WHERE rmm_device_id = " . intval($row['rmm_device_id'])); - } - rmmActionRecord($row, $ticket, $did); - - $done = [ - 'reboot' => "$host is rebooting.", - 'patches' => "$name is installing the patches $host's patch policy approves.", - 'maintenance' => empty($options['on']) ? "Maintenance mode is off for $host." : "Maintenance mode is on for $host - $name raises no alerts for it until it's off.", - ][$action]; - flashAlert(escapeHtml($done) . ($ticket ? ' Noted on ' . escapeHtml($ticket['ticket_prefix'] . $ticket['ticket_number']) . '.' : '')); - - redirect(); - -} - -if (isset($_POST['rmm_run_script'])) { - - validateCSRFToken(); - - // The window asks in JSON and shows what comes back; anything else gets it as a flash - $wants_json = str_contains((string) ($_SERVER['HTTP_ACCEPT'] ?? ''), 'application/json'); - $answer_with = function (array $answer) use ($wants_json) { - if ($wants_json) { - header('Content-Type: application/json; charset=utf-8'); - echo json_encode($answer); - exit; - } - flashAlert(escapeHtml($answer['ok'] ? $answer['text'] : $answer['error']), $answer['ok'] ? 'success' : 'error'); - redirect(); - }; - - $support = intval(lookupUserPermission('module_support')); - if ($support < 2) { - $answer_with(['ok' => false, 'error' => permissionRefusedText('module_support', 2, $support)]); - } - [$row, $ticket, $error] = rmmActionTarget(intval($_POST['rmm_run_script']), intval($_POST['ticket_id'] ?? 0), 'script'); - if ($row && !hasClientAccess($row['asset_client_id'])) { - $answer_with(['ok' => false, 'error' => 'You don\'t have access to this client.']); - } - if ($error !== '') { - $answer_with(['ok' => false, 'error' => $error]); - } - - $name = rmmProviderName($row); - $host = rmmActionHost($row); - $found = rmmDeviceScript($row, (string) intval($_POST['script_id'] ?? 0)); - if (!$found['ok']) { - $answer_with(['ok' => false, 'error' => $found['error']]); - } - $script = $found['script']; - - // Its arguments, one a line, as typed - and how long to wait for it - $args = array_values(array_filter(array_map('trim', preg_split('/\R/', (string) ($_POST['args'] ?? ''))), 'strlen')); - $args = array_map(function ($arg) { - return mb_substr($arg, 0, 500); - }, array_slice($args, 0, 50)); - $timeout = max(5, min(600, intval($_POST['timeout'] ?? 0) ?: $script['timeout'])); - $wait = !empty($_POST['wait']); - - // Waiting is up to the timeout, and a little more for the RMM to answer - without holding up the person's other tabs - set_time_limit($timeout + 60); - if ($wants_json) { - session_write_close(); - } - - $result = rmmDeviceAct($row, 'script', ['script' => $script, 'args' => $args, 'timeout' => $timeout, 'wait' => $wait]); - if (!$result['ok']) { - $answer_with(['ok' => false, 'error' => "$name couldn't run {$script['name']} on $host. {$result['error']}"]); - } - - // How it is kept - what was run, then its output - $ran = str_replace('%', '%%', $script['name']); - $with = $args ? ', with ' . str_replace('%', '%%', implode(' ', $args)) : ''; - $output = null; - if (!$wait) { - $what = "started the script $ran on %1\$s %2\$s$with"; - $more = '

' . escapeHtml("Its output is in the device's history in $name.") . '

'; - $text = "$name is running {$script['name']} on $host - its output will be in the device's history there."; - } elseif ($result['timed_out']) { - $what = "ran the script $ran on %1\$s %2\$s$with - it didn't finish within $timeout seconds"; - $more = '

' . escapeHtml("If it finishes, its output is in the device's history in $name.") . '

'; - $text = "{$script['name']} didn't finish on $host within $timeout seconds. If it finishes, its output is in the device's history in $name."; - } else { - $output = (string) $result['output']; - // A long one keeps its end, where the errors are - if (mb_strlen($output) > 60000) { - $output = '... (the first ' . number_format(mb_strlen($output) - 60000) . " characters left out)\n" . mb_substr($output, -60000); - } - $what = "ran the script $ran on %1\$s %2\$s$with"; - $more = '
' . escapeHtml(trim($output) !== '' ? $output : '(no output)') . '
'; - $text = "Ran {$script['name']} on $host."; - } - rmmActionRecord($row, $ticket, $what, $more); - - $answer_with([ - 'ok' => true, - 'text' => $text . ($ticket ? ' Noted on ' . $ticket['ticket_prefix'] . $ticket['ticket_number'] . '.' : ''), - 'output' => $output, - 'timed_out' => $wait && $result['timed_out'], - ]); - -} diff --git a/agent/ticket.php b/agent/ticket.php index c8756c8b7..02c5b3fc9 100644 --- a/agent/ticket.php +++ b/agent/ticket.php @@ -1782,21 +1782,14 @@ if (isset($_GET['ticket_id'])) {
Nothing linked yet. Use to add an asset, vendor, project, service or watcher.
- + -
- + - &id=" title=""> - diff --git a/db.sql b/db.sql index 24aaea071..055da93d1 100644 --- a/db.sql +++ b/db.sql @@ -3420,7 +3420,6 @@ CREATE TABLE `rmm_providers` ( `rmm_provider_alerts_since` datetime DEFAULT NULL, `rmm_provider_alerts_at` datetime DEFAULT NULL, `rmm_provider_alerts_note` varchar(500) DEFAULT NULL, - `rmm_provider_actions` tinyint(1) NOT NULL DEFAULT 0, `rmm_provider_created_at` datetime NOT NULL DEFAULT current_timestamp(), `rmm_provider_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), PRIMARY KEY (`rmm_provider_id`) diff --git a/functions/demo.php b/functions/demo.php index 1b1fc690d..440acfe2b 100644 --- a/functions/demo.php +++ b/functions/demo.php @@ -102,10 +102,6 @@ const DEMO_MODE_LOCKS = [ 'keys' => ['add_rmm_provider', 'check_rmm_provider', 'edit_rmm_provider', 'delete_rmm_provider', 'test_rmm_provider', 'sync_rmm', 'turn_rmm_provider_off', 'turn_rmm_provider_on', 'link_rmm_client', 'link_rmm_suggested', 'unlink_rmm_client', 'rmm_bring_back'], ], - [ - 'message' => "Devices can't be rebooted or have scripts run on them in the demo.", - 'keys' => ['rmm_reboot', 'rmm_install_patches', 'rmm_maintenance_on', 'rmm_maintenance_off', 'rmm_run_script'], - ], [ 'message' => "Managed instances are turned off in the demo.", 'keys' => ['managed_checkin_now', 'managed_connect', 'managed_disconnect', 'add_managed_instance', 'delete_managed_instance', 'edit_managed_instance', diff --git a/functions/dev_mode.php b/functions/dev_mode.php index 71fc23b18..78de70de5 100644 --- a/functions/dev_mode.php +++ b/functions/dev_mode.php @@ -19,7 +19,6 @@ * - AI Triage doesn't run (cron/ai_triage.php) * - Stripe refuses every call, so no card is charged and nothing is made there * (includes/stripe_init.php); autopay and Payment Provider Fees don't run - * - RMM devices still come in, but nothing is done to one (rmmDeviceAct()) * - log entries aren't sent to a syslog server (functions/log_forward.php) * - a managed instance doesn't talk to its manager, and a manager doesn't watch its * instances (managedHttpJson(), cron/manager_checkin.php, cron/managed_instances.php) @@ -49,7 +48,7 @@ function devModeSummary(): string { $to = devModeMailTo(); return 'Development mode: ' . ($to !== '' ? "every email goes to $to" : 'no email is sent') - . '; texts, the ticket mailbox, AI Triage, Stripe, RMM device actions, log forwarding and managed check-ins are off.'; + . '; texts, the ticket mailbox, AI Triage, Stripe, log forwarding and managed check-ins are off.'; } /** includes/stripe_init.php: in development mode every Stripe call is refused - nothing is charged or made. */ diff --git a/functions/rmm.php b/functions/rmm.php index 167b4a0fe..a3e04813d 100644 --- a/functions/rmm.php +++ b/functions/rmm.php @@ -27,10 +27,6 @@ * A device the RMM no longer has keeps its asset, marked as gone from it. An asset deleted in * ITFlow isn't brought back by the next sync - its row stays, with no asset, until Bring back * on the Clients page lets the sync make it again. - * - * A provider with device actions on (rmm_provider_actions) lets technicians reboot a device, - * install its patches, turn its maintenance mode on and off and run one of the RMM's scripts on - * it, from its asset or a ticket it is on - see Device actions below. */ /* @@ -56,19 +52,6 @@ * the open ones, 'error'], and fn(provider, alert's id there): ['ok', * 'alert' => it, or null when the RMM no longer has it, 'error'] - each * alert as described under Alerts below - * actions, act - optional, for device actions: action => [label, icon, needs (what its - * key's user needs there to do it), platforms (only on these, when set), - * about (what it does)] of reboot, patches, maintenance and script; and - * fn(provider, device's id there, action, options): ['ok', 'output' => a - * script's when it was waited for, else null, 'timed_out' => it wasn't - * done in time, 'error'] - options are on (maintenance), and script (as - * script gives it), args, timeout and wait for a script - * scripts, script - with the script action: fn(provider, platform): ['ok', 'scripts', 'error'], - * the ones that run there; and fn(provider, script's id): ['ok', 'script' - * => it, or null when the RMM no longer has it, 'error'] - each script - * [id, name, category, description, args, env_vars, platforms, timeout - * (seconds), favorite, hidden] - * actions_help - what its key's user needs for them, for the provider window */ /** The RMMs ITFlow can bring devices in from - kind => what it is. */ @@ -196,10 +179,9 @@ function rmmDeviceUrls(array $row): array /** * Ask an RMM's API - ['ok', 'code', 'json', 'error']: error is what to tell a person when it - * didn't work, with the kind's hints. The kind's file says where and how to sign in. An answer - * that is only text in JSON - "ok", a script's output - is one only when $text_ok. + * didn't work, with the kind's hints. The kind's file says where and how to sign in. */ -function rmmHttp(array $provider, string $method, string $url, array $headers = [], ?array $body = null, int $timeout = 30, bool $text_ok = false): array +function rmmHttp(array $provider, string $method, string $url, array $headers = [], ?array $body = null, int $timeout = 30): array { $name = rmmProviderName($provider); $hints = rmmKind($provider)['hints'] ?? []; @@ -219,7 +201,7 @@ function rmmHttp(array $provider, string $method, string $url, array $headers = CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, ]; if ($body !== null) { - $options[CURLOPT_POSTFIELDS] = $body === [] ? '{}' : json_encode($body); + $options[CURLOPT_POSTFIELDS] = json_encode($body); } curl_setopt_array($ch, $options); $raw = curl_exec($ch); @@ -244,10 +226,10 @@ function rmmHttp(array $provider, string $method, string $url, array $headers = return ['ok' => false, 'code' => $code, 'json' => $json, 'error' => "Nothing at $path on $host (HTTP 404)" . $hint('not_found')]; } if ($code < 200 || $code > 299) { - $detail = is_array($json) ? rmmText($json['detail'] ?? $json['error'] ?? $json['message'] ?? '', 300) : rmmText(is_string($json) ? $json : '', 300); + $detail = is_array($json) ? rmmText($json['detail'] ?? $json['error'] ?? $json['message'] ?? '', 300) : ''; return ['ok' => false, 'code' => $code, 'json' => $json, 'error' => "$name answered HTTP $code" . ($detail !== '' ? " - $detail" : '')]; } - if (!is_array($json) && !($text_ok && is_string($json))) { + if (!is_array($json)) { return ['ok' => false, 'code' => $code, 'json' => null, 'error' => "$host answered, but not as $name's API" . $hint('not_json')]; } return ['ok' => true, 'code' => $code, 'json' => $json, 'error' => '']; @@ -1014,17 +996,11 @@ function rmmAlertInsert(int $provider_id, array $device, array $alert, int $tick /** An internal note on a ticket, written by ITFlow - $text is plain. */ function rmmTicketNote(int $ticket_id, string $text): void -{ - rmmTicketNoteHtml($ticket_id, '

' . nl2br(escapeHtml($text)) . '

', 0); -} - -/** An internal note on a ticket from HTML made safe already - by a user, or by ITFlow (0). */ -function rmmTicketNoteHtml(int $ticket_id, string $html, int $by): void { global $mysqli; - // Escaped as itself - escapeSql() would take the tags out - $html = mysqli_real_escape_string($mysqli, $html); - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$html', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $by, ticket_reply_ticket_id = $ticket_id"); + // HTML, escaped as itself - escapeSql() would take the tags out + $html = mysqli_real_escape_string($mysqli, '

' . nl2br(escapeHtml($text)) . '

'); + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$html', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:00:00', ticket_reply_by = 0, ticket_reply_ticket_id = $ticket_id"); mysqli_query($mysqli, "UPDATE tickets SET ticket_updated_at = NOW() WHERE ticket_id = $ticket_id"); } @@ -1430,247 +1406,6 @@ function rmmListLabel(): string return count($providers) === 1 ? rmmProviderName($providers[0]) : 'an RMM'; } -/* - * ------------------------------------------------------------------ Device actions - * - * A provider with device actions on (rmm_provider_actions, from the 3.6.9 database update) lets - * a device that is still in its RMM be rebooted, have its patches installed, have maintenance - * mode turned on and off, and have one of the RMM's scripts run on it - by someone who can edit - * assets (Modify on Support) and see its client. They are on the device's card on its asset - * and beside it on a ticket it is on (rmmDeviceActionsMenu()), and done by agent/post/rmm.php. - * The RMM does each as its key's user, so that user's role there limits them too. Each goes in - * the asset's history and the audit log, and on the ticket it was done from as a note by whoever - * did it - a script's output with it. - */ - -/** Whether device actions can be turned on - the column arrives with the 3.6.9 database update. */ -function rmmActionsReady(): bool -{ - global $mysqli; - static $ready = null; - if ($ready === null) { - try { - mysqli_query($mysqli, "SELECT rmm_provider_actions FROM rmm_providers LIMIT 1"); - $ready = true; - } catch (Throwable $e) { - $ready = false; - } - } - return $ready; -} - -/** One device by its id, with its provider's columns, its RMM client and its asset's name and client - raw, or null when it or its asset is gone. */ -function rmmDeviceById(int $device_id): ?array -{ - global $mysqli; - if (!$device_id || !rmmTablesReady()) { - return null; - } - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT rmm_devices.*, rmm_providers.*, rmm_client_name, rmm_client_client_id, asset_name, asset_client_id FROM rmm_devices - JOIN rmm_providers ON rmm_provider_id = rmm_device_provider_id - JOIN assets ON asset_id = rmm_device_asset_id - LEFT JOIN rmm_clients ON rmm_clients.rmm_client_id = rmm_device_rmm_client_id - WHERE rmm_device_id = $device_id LIMIT 1")); - return $row ?: null; -} - -/** - * What can be done to a device from here - action => as its kind has it. None when its provider - * hasn't device actions on, is off, or no longer has it; only the ones for its platform. - */ -function rmmDeviceActions(array $row): array -{ - $kind = rmmKind($row); - if (!$kind || empty($kind['actions']) || !isset($kind['act']) || !intval($row['rmm_provider_actions'] ?? 0) || !rmmProviderUsable($row) - || $row['rmm_device_removed_at'] !== null || (string) $row['rmm_device_remote_id'] === '' || !intval($row['rmm_device_asset_id'])) { - return []; - } - $actions = []; - foreach ($kind['actions'] as $action => $about) { - if ($action === 'script' && !isset($kind['scripts'], $kind['script'])) { - continue; - } - if (!empty($about['platforms']) && !in_array((string) $row['rmm_device_platform'], $about['platforms'], true)) { - continue; - } - $actions[$action] = $about; - } - return $actions; -} - -/** A device's platform as people call it - Windows, Linux, macOS. */ -function rmmPlatformName(string $platform): string -{ - return ['windows' => 'Windows', 'linux' => 'Linux', 'darwin' => 'macOS'][$platform] ?? ($platform !== '' ? ucfirst($platform) : 'its system'); -} - -/** What a device is called when an action is spoken of - its name in the RMM, or its asset's. */ -function rmmActionHost(array $row): string -{ - $host = trim((string) ($row['rmm_device_hostname'] ?? '')); - return $host !== '' ? $host : (trim((string) ($row['asset_name'] ?? '')) ?: 'the device'); -} - -/** - * The device and ticket an action is asked for, checked - [$row, $ticket, $error]: $row as - * rmmDeviceById() gives it, $ticket the ticket's row or null, and $error what to say when it - * can't be done. Whether the person may do it is the handler's to check, with the asset's client. - */ -function rmmActionTarget(int $device_id, int $ticket_id, string $action): array -{ - global $mysqli; - $row = rmmDeviceById($device_id); - if (!$row) { - return [null, null, 'That device, or its asset, is no longer in ITFlow.']; - } - if (!isset(rmmDeviceActions($row)[$action])) { - $name = rmmProviderName($row); - return [$row, null, rmmActionHost($row) . " can't have that done from ITFlow now - $name may be off, have its device actions off, or no longer have it."]; - } - $ticket = null; - if ($ticket_id) { - $ticket = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number FROM tickets - WHERE ticket_id = $ticket_id AND ticket_client_id = " . intval($row['asset_client_id']) . " AND ticket_closed_at IS NULL LIMIT 1")) ?: null; - if (!$ticket) { - return [$row, null, 'That ticket is closed, or isn\'t this client\'s - nothing was done.']; - } - } - return [$row, $ticket, '']; -} - -/** Do an action to a device - ['ok', 'output', 'timed_out', 'error'] as its kind's act says. */ -function rmmDeviceAct(array $row, string $action, array $options = []): array -{ - if (!isset(rmmDeviceActions($row)[$action])) { - return ['ok' => false, 'output' => null, 'timed_out' => false, 'error' => rmmActionHost($row) . ' can\'t have that done from ITFlow now.']; - } - // Development mode: devices still come in, but nothing is done to one (functions/dev_mode.php) - if (devModeOn()) { - return ['ok' => false, 'output' => null, 'timed_out' => false, 'error' => 'Development mode - nothing is done to devices from this server.']; - } - return call_user_func(rmmKind($row)['act'], $row, (string) $row['rmm_device_remote_id'], $action, $options); -} - -/** The RMM's scripts that run on a device - ['ok', 'scripts', 'error'], each as its kind's scripts gives them. */ -function rmmDeviceScripts(array $row): array -{ - if (!isset(rmmDeviceActions($row)['script'])) { - return ['ok' => false, 'scripts' => [], 'error' => rmmActionHost($row) . ' can\'t have scripts run from ITFlow now.']; - } - return call_user_func(rmmKind($row)['scripts'], $row, (string) $row['rmm_device_platform']); -} - -/** - * One of the RMM's scripts, to run on a device - ['ok', 'script', 'error']: refused when the RMM - * no longer has it, has hidden it, or it doesn't run on the device's platform. - */ -function rmmDeviceScript(array $row, string $script_id): array -{ - if (!isset(rmmDeviceActions($row)['script'])) { - return ['ok' => false, 'script' => null, 'error' => rmmActionHost($row) . ' can\'t have scripts run from ITFlow now.']; - } - $answer = call_user_func(rmmKind($row)['script'], $row, $script_id); - if (!$answer['ok']) { - return $answer; - } - $script = $answer['script']; - $name = rmmProviderName($row); - if (!$script || $script['hidden']) { - return ['ok' => false, 'script' => null, 'error' => "$name no longer has that script - pick another."]; - } - if ($script['platforms'] && !in_array((string) $row['rmm_device_platform'], $script['platforms'], true)) { - return ['ok' => false, 'script' => null, 'error' => "{$script['name']} doesn't run on " . rmmPlatformName((string) $row['rmm_device_platform']) . ', so not on ' . rmmActionHost($row) . ' - pick another.']; - } - return ['ok' => true, 'script' => $script, 'error' => '']; -} - -/** - * The tickets an action on an asset can go on as a note - its tickets that aren't closed, newest - * first, and $also when that is one of its client's. [ticket_id => row with prefix, number, subject]. - */ -function rmmActionTickets(int $asset_id, int $client_id, int $also = 0): array -{ - global $mysqli; - $tickets = []; - $sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_prefix, ticket_number, ticket_subject FROM tickets - WHERE ticket_client_id = $client_id AND ticket_closed_at IS NULL AND ticket_archived_at IS NULL - AND (ticket_asset_id = $asset_id OR ticket_id IN (SELECT ticket_id FROM ticket_assets WHERE asset_id = $asset_id) OR ticket_id = $also) - ORDER BY ticket_id = $also DESC, ticket_created_at DESC, ticket_id DESC LIMIT 25"); - while ($ticket = mysqli_fetch_assoc($sql)) { - $tickets[intval($ticket['ticket_id'])] = $ticket; - } - return $tickets; -} - -/** - * An action done to a device, kept - in its asset's history, the audit log and, when it was done - * from one, on the ticket as an internal note by whoever did it, with $html_more after (made - * safe already - a script's output). $what is plain, with %1$s for the device and %2$s for - * "through" its RMM: "rebooted %1$s %2$s". - */ -function rmmActionRecord(array $row, ?array $ticket, string $what, string $html_more = ''): void -{ - global $session_name, $session_user_id; - $through = 'through ' . rmmProviderName($row); - $asset_id = intval($row['rmm_device_asset_id']); - rmmAssetHistory($asset_id, stripslashes((string) $session_name), sprintf($what, 'it', $through)); - logAudit('Asset', 'RMM', "$session_name " . escapeSql(sprintf($what, "asset {$row['asset_name']}", $through) - . ($ticket ? " - on ticket {$ticket['ticket_prefix']}{$ticket['ticket_number']}" : '')), intval($row['asset_client_id']), $asset_id); - if ($ticket) { - rmmTicketNoteHtml(intval($ticket['ticket_id']), '

' . escapeHtml(ucfirst(sprintf($what, rmmActionHost($row), $through)) . '.') . '

' . $html_more, intval($session_user_id)); - } -} - -/** - * A device's actions as a menu - '' when it has none, or the person can't do them (Modify on - * Support). From a ticket, $ticket_id has them go on it as notes. Reboot and patches ask first, - * maintenance mode goes at once, and Run a script opens its window (modals/rmm/rmm_script.php). - * $label '' makes the button just its icon. - */ -function rmmDeviceActionsMenu(array $row, int $ticket_id = 0, string $toggle = 'btn btn-sm btn-outline-secondary', string $label = 'Actions'): string -{ - $actions = lookupUserPermission('module_support') >= 2 ? rmmDeviceActions($row) : []; - if (!$actions) { - return ''; - } - $device_id = intval($row['rmm_device_id']); - $name = rmmProviderName($row); - $host = rmmActionHost($row); - $items = ''; - foreach ($actions as $action => $about) { - $icon = ''; - $title = ' title="' . escapeHtml((string) ($about['about'] ?? '')) . '"'; - if ($action === 'script') { - $items .= '
' - . $icon . escapeHtml($about['label']) . '...'; - } elseif ($action === 'maintenance') { - $on = !intval($row['rmm_device_maintenance']); - $items .= ''; - } else { - $text = (string) ($about['about'] ?? ''); - if ($action === 'reboot' && $row['rmm_device_status'] === 'online' && (string) $row['rmm_device_logged_user'] !== '') { - $text .= ' ' . $row['rmm_device_logged_user'] . ' is signed in, and loses anything not saved.'; - } - $confirm = $action === 'reboot' ? ["Reboot $host now?", 'Reboot'] : ["Install $host's patches now?", 'Install']; - $items .= ''; - } - } - $toggle_html = $label !== '' - ? '' . escapeHtml($label) - : 'Actions in ' . escapeHtml($name) . ''; - return ''; -} - /* * ------------------------------------------------------------------ Linking clients */ @@ -1796,11 +1531,6 @@ function rmmProviderCheck(array $in, ?array $before): array $after['rmm_provider_alerts_restart'] = $level !== '' && ($level !== (string) ($before['rmm_provider_alert_level'] ?? '') || ($before && !intval($before['rmm_provider_active']) && $after['rmm_provider_active'])); } - - // Device actions - only for a kind that has them, and off until turned on - if (rmmActionsReady()) { - $after['rmm_provider_actions'] = !empty($kind['actions']) && !empty($in['actions']) ? 1 : 0; - } return [$after, $errors]; } @@ -1826,9 +1556,6 @@ function rmmProviderWrite(array $after, int $provider_id = 0): int $set[] = 'rmm_provider_alerts_since = NULL, rmm_provider_alerts_note = NULL'; } } - if (array_key_exists('rmm_provider_actions', $after)) { - $set[] = 'rmm_provider_actions = ' . intval($after['rmm_provider_actions']); - } if ($provider_id) { mysqli_query($mysqli, "UPDATE rmm_providers SET " . implode(', ', $set) . " WHERE rmm_provider_id = $provider_id"); return $provider_id; @@ -1868,8 +1595,5 @@ function rmmProviderChangeLines(array $before, array $after): array $category = intval($after['rmm_provider_alert_category_id']) ? (string) getFieldById('categories', intval($after['rmm_provider_alert_category_id']), 'category_name') : ''; $lines[] = $category === '' ? 'alert tickets not categorized' : "alert tickets in $category"; } - if (array_key_exists('rmm_provider_actions', $after) && intval($before['rmm_provider_actions'] ?? 0) !== intval($after['rmm_provider_actions'])) { - $lines[] = intval($after['rmm_provider_actions']) ? 'device actions turned on' : 'device actions turned off'; - } return $lines; } diff --git a/functions/rmm_tactical.php b/functions/rmm_tactical.php index cc18270f9..617d8f468 100644 --- a/functions/rmm_tactical.php +++ b/functions/rmm_tactical.php @@ -12,14 +12,6 @@ * Its alerts: PATCH /alerts/ with resolvedFilter false lists the open ones its dashboard shows * (a check's or agent's dashboard alert setting decides which those are), and GET /alerts// * says whether one has cleared. The key's role needs to be able to list alerts. - * - * Its device actions, each needing its own permission in the key's role: POST - * /agents//reboot/ (Shutdown / Reboot Agents), POST /winupdate//install/ (Manage Windows - * Updates - it installs what the agent's patch policy approves, and reboots after if that policy - * says to), PUT /agents// with maintenance_mode (Edit Agents), and POST - * /agents//runscript/ (Run Script) with a script from GET /scripts/ (List Scripts). Most - * answer with text in JSON - "ok", or what went wrong with a 400; a script run with output - * "wait" answers with its output, or "timeout" when the agent didn't finish in time. */ /** What Tactical RMM is, as rmmProviderKinds() describes a kind. */ @@ -61,28 +53,11 @@ function rmmTacticalKind(): array 'alerts' => 'rmmTacticalAlerts', 'alert' => 'rmmTacticalAlert', 'alerts_help' => 'These are the alerts Tactical\'s dashboard shows - a check\'s or agent\'s Dashboard alert setting, or its alert template, decides which those are. The API key\'s user needs to be able to list alerts.', - 'actions' => [ - 'reboot' => ['label' => 'Reboot now', 'icon' => 'fa-redo-alt', 'needs' => 'Shutdown / Reboot Agents', - 'about' => 'It restarts straight away.'], - 'patches' => ['label' => 'Install patches now', 'icon' => 'fa-download', 'needs' => 'Manage Windows Updates', 'platforms' => ['windows'], - 'about' => 'Tactical installs the ones its patch policy approves, and restarts it afterwards if that policy says to.'], - 'maintenance' => ['label' => 'Maintenance mode', 'icon' => 'fa-tools', 'needs' => 'Edit Agents', - 'about' => 'While it is on, Tactical raises no alerts for it - so none opens a ticket.'], - 'script' => ['label' => 'Run a script', 'icon' => 'fa-scroll', 'needs' => 'List Scripts and Run Script', - 'about' => 'One of the scripts in Tactical\'s library, with its output back here.'], - ], - 'act' => 'rmmTacticalAct', - 'scripts' => 'rmmTacticalScripts', - 'script' => 'rmmTacticalScript', - 'actions_help' => 'Tactical does each as the API key\'s user, so its role needs Shutdown / Reboot Agents, Manage Windows Updates, Edit Agents (for maintenance mode), and List Scripts and Run Script - give it only the ones you want done from ITFlow.', ]; } -/** - * Ask Tactical's API. $path is Tactical's, with its trailing slash (/agents/) - it matters there. - * $text_ok for the answers that are only text. - */ -function rmmTacticalRequest(array $provider, string $method, string $path, array $query = [], ?array $body = null, int $timeout = 30, bool $text_ok = false): array +/** Ask Tactical's API. $path is Tactical's, with its trailing slash (/agents/) - it matters there. */ +function rmmTacticalRequest(array $provider, string $method, string $path, array $query = [], ?array $body = null, int $timeout = 30): array { $base = rmmUrlClean($provider['rmm_provider_api_url'] ?? ''); $key = trim((string) ($provider['rmm_provider_api_key'] ?? '')); @@ -90,7 +65,7 @@ function rmmTacticalRequest(array $provider, string $method, string $path, array return ['ok' => false, 'code' => 0, 'json' => null, 'error' => 'Its API address and key aren\'t set.']; } $url = $base . '/' . ltrim($path, '/') . ($query ? '?' . http_build_query($query, '', '&') : ''); - return rmmHttp($provider, $method, $url, ['X-API-KEY: ' . $key], $body, $timeout, $text_ok); + return rmmHttp($provider, $method, $url, ['X-API-KEY: ' . $key], $body, $timeout); } /** Tactical's clients - ['ok', 'clients' => [id, name, sites, devices], 'error']. */ @@ -253,138 +228,6 @@ function rmmTacticalDeviceUrls(array $provider, string $remote_id): array ]; } -/** - * Do an action to one of Tactical's agents - ['ok', 'output', 'timed_out', 'error'] (functions/rmm.php, - * Device actions). A script waited for has its output; timed_out when it didn't finish in time. - */ -function rmmTacticalAct(array $provider, string $remote_id, string $action, array $options = []): array -{ - $id = rawurlencode($remote_id); - $timeout = 30; - if ($action === 'reboot') { - $answer = rmmTacticalRequest($provider, 'POST', "/agents/$id/reboot/", [], [], 30, true); - } elseif ($action === 'patches') { - $answer = rmmTacticalRequest($provider, 'POST', "/winupdate/$id/install/", [], [], 30, true); - } elseif ($action === 'maintenance') { - $answer = rmmTacticalRequest($provider, 'PUT', "/agents/$id/", [], ['maintenance_mode' => !empty($options['on'])], 30, true); - } elseif ($action === 'script') { - $timeout = max(5, min(600, intval($options['timeout'] ?? 90))); - $wait = !empty($options['wait']); - // Every key its run_script view reads, with the script's own environment variables as Tactical's Run Script window sends them - $answer = rmmTacticalRequest($provider, 'POST', "/agents/$id/runscript/", [], [ - 'script' => intval($options['script']['id'] ?? 0), - 'output' => $wait ? 'wait' : 'forget', - 'args' => array_values(array_map('strval', (array) ($options['args'] ?? []))), - 'env_vars' => array_values(array_map('strval', (array) ($options['script']['env_vars'] ?? []))), - 'timeout' => $timeout, - 'run_as_user' => false, - 'emails' => [], - 'emailMode' => 'default', - 'custom_field' => null, - 'save_all_output' => false, - ], $timeout + 30, true); - if ($answer['ok'] && $wait) { - $output = is_string($answer['json']) ? $answer['json'] : json_encode($answer['json'], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); - if (trim($output) === 'timeout') { - return ['ok' => true, 'output' => null, 'timed_out' => true, 'error' => '']; - } - return ['ok' => true, 'output' => $output, 'timed_out' => false, 'error' => '']; - } - } else { - return ['ok' => false, 'output' => null, 'timed_out' => false, 'error' => rmmProviderName($provider) . ' can\'t do that.']; - } - if (!$answer['ok']) { - return ['ok' => false, 'output' => null, 'timed_out' => false, 'error' => rmmTacticalActError($provider, $answer, $action)]; - } - return ['ok' => true, 'output' => null, 'timed_out' => false, 'error' => '']; -} - -/** What went wrong with an action, in words - what the key's role needs for it, or Tactical's own reason. */ -function rmmTacticalActError(array $provider, array $answer, string $action): string -{ - $name = rmmProviderName($provider); - if ($answer['code'] === 401 || $answer['code'] === 403) { - $needs = rmmTacticalKind()['actions'][$action]['needs'] ?? ''; - return "$name didn't let the API key do that" . ($needs !== '' ? " - its user's role needs $needs" : '') . '.'; - } - if ($answer['code'] === 404) { - return "$name no longer has that " . ($action === 'script' ? 'device or script' : 'device') . '.'; - } - if ($answer['code'] === 400 && is_string($answer['json']) && trim($answer['json']) !== '') { - $reason = rmmText($answer['json'], 300); - return "$name said: $reason" . (stripos($reason, 'unable to contact') !== false ? ' - is it online?' : ''); - } - return $answer['error']; -} - -/** Tactical's scripts that run on $platform - its favorites first, then by category and name. */ -function rmmTacticalScripts(array $provider, string $platform): array -{ - $answer = rmmTacticalRequest($provider, 'GET', '/scripts/'); - if (!$answer['ok']) { - if ($answer['code'] === 401 || $answer['code'] === 403) { - $answer['error'] = rmmProviderName($provider) . ' didn\'t let the API key see its scripts - its user\'s role needs List Scripts.'; - } - return ['ok' => false, 'scripts' => [], 'error' => $answer['error']]; - } - $scripts = []; - foreach ($answer['json'] as $script) { - if (!is_array($script) || !isset($script['id'], $script['name']) || !empty($script['hidden'])) { - continue; - } - $platforms = array_map('strval', (array) ($script['supported_platforms'] ?? [])); - if ($platforms && !in_array($platform, $platforms, true)) { - continue; - } - $scripts[] = rmmTacticalScriptShape($script); - } - usort($scripts, function ($a, $b) { - if ($a['favorite'] !== $b['favorite']) { - return $a['favorite'] ? -1 : 1; - } - if (($a['category'] === '') !== ($b['category'] === '')) { - return $a['category'] === '' ? 1 : -1; - } - return strcasecmp($a['category'], $b['category']) ?: strcasecmp($a['name'], $b['name']); - }); - return ['ok' => true, 'scripts' => $scripts, 'error' => '']; -} - -/** One of Tactical's scripts by its id - null when Tactical no longer has it. */ -function rmmTacticalScript(array $provider, string $script_id): array -{ - $answer = rmmTacticalRequest($provider, 'GET', '/scripts/' . intval($script_id) . '/'); - if (!$answer['ok']) { - if ($answer['code'] === 404) { - return ['ok' => true, 'script' => null, 'error' => '']; - } - return ['ok' => false, 'script' => null, 'error' => rmmTacticalActError($provider, $answer, 'script')]; - } - return ['ok' => true, 'script' => rmmTacticalScriptShape($answer['json']), 'error' => '']; -} - -/** One of Tactical's scripts as a script (functions/rmm.php, Device actions). */ -function rmmTacticalScriptShape(array $script): array -{ - $list = function ($values) { - return array_values(array_filter(array_map(function ($value) { - return is_scalar($value) ? mb_substr((string) $value, 0, 500) : ''; - }, (array) $values), 'strlen')); - }; - return [ - 'id' => (string) intval($script['id'] ?? 0), - 'name' => rmmText($script['name'] ?? '', 255) ?: 'Script ' . intval($script['id'] ?? 0), - 'category' => rmmText($script['category'] ?? '', 100), - 'description' => rmmText($script['description'] ?? '', 500), - 'args' => $list($script['args'] ?? []), - 'env_vars' => $list($script['env_vars'] ?? []), - 'platforms' => array_map('strval', (array) ($script['supported_platforms'] ?? [])), - 'timeout' => max(5, min(600, intval($script['default_timeout'] ?? 90) ?: 90)), - 'favorite' => !empty($script['favorite']), - 'hidden' => !empty($script['hidden']), - ]; -} - /** Tactical's one "make model" string, as ITFlow's make and model. */ function rmmTacticalMakeModel($make_model): array {