mirror of
https://github.com/itflow-org/itflow
synced 2026-12-04 01:59:00 +00:00
Merge pull request #1320 from itflow-org/develop
Develop to master for 26.12.5 release
This commit is contained in:
37
CHANGELOG.md
37
CHANGELOG.md
@@ -2,6 +2,43 @@
|
||||
|
||||
This file documents all notable changes made to ITFlow.
|
||||
|
||||
## [26.12.5]
|
||||
|
||||
### Upgrading to 26.12.5
|
||||
|
||||
Update from Maintenance > Update as usual. This release has two database changes: 4.4.2 keeps when a cron job was last started by something other than cron.php, and 4.4.3 lets Knowledge Base articles be written in Markdown.
|
||||
|
||||
- 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
|
||||
|
||||
- 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 - 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
|
||||
|
||||
- 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". 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/<id>/`). `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]
|
||||
|
||||
### Upgrading to 26.12.4
|
||||
|
||||
@@ -108,6 +108,10 @@ 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,9 @@ 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),
|
||||
// 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;
|
||||
@@ -122,15 +126,27 @@ 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;
|
||||
}
|
||||
|
||||
// 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
|
||||
$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 +239,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 +263,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 +316,7 @@ $status_looks = [
|
||||
|
||||
<?php } else { ?>
|
||||
<p class="mb-0 text-body-secondary">
|
||||
It last ran <?= $ago($cron_last_dispatch_at) ?>. <?= count($jobs_on) ?> job<?= count($jobs_on) === 1 ? ' is' : 's are' ?> on<?= $jobs_off ? ", $jobs_off off" : '' ?>, and none failed on its last run.
|
||||
It last ran <?= $ago($cron_last_dispatch_at) ?>. <?= count($jobs_on) ?> job<?= count($jobs_on) === 1 ? ' is' : 's are' ?> on<?= $jobs_unused ? " ($jobs_unused with nothing to do here yet)" : '' ?><?= $jobs_off ? ", $jobs_off off" : '' ?>, and none failed on its last run.
|
||||
<?php if ($next_job) { ?>
|
||||
Next is <?= $job_names([$next_job]) ?>, <?= $next_job['next_run'] <= date('Y-m-d H:i:s') ? 'within a minute' : $ago($next_job['next_run']) ?>.
|
||||
<?php } ?>
|
||||
@@ -333,6 +350,33 @@ $status_looks = [
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if ($stray_lines) { ?>
|
||||
<!-- Old crontab lines that run jobs again, outside cron.php (functions/cron_health.php) -->
|
||||
<div class="card mb-3 border-warning" data-cron-stray>
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-start gap-3">
|
||||
<i class="fas fa-fw fa-exclamation-triangle text-warning mt-1" aria-hidden="true"></i>
|
||||
<div class="flex-grow-1 min-w-0">
|
||||
<div class="fw-semibold">Old cron lines run some jobs a second time</div>
|
||||
<p class="text-body-secondary small mb-2">
|
||||
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
|
||||
<code>cron.php</code>. While <code>cron.php</code> 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 - <code>cron.php</code> runs every job now:
|
||||
</p>
|
||||
<?php foreach ($stray_lines as $stray_line) { ?>
|
||||
<div class="small mb-2" data-cron-stray-line>
|
||||
<div><strong><?= escapeHtml($stray_line['file']) ?></strong>, line <?= intval($stray_line['line']) ?> - <?= escapeHtml(cronStrayWhat($stray_line)) ?></div>
|
||||
<pre class="itflow-command bg-body-tertiary border rounded p-2 mb-0 mt-1 small text-wrap text-break"><code><?= escapeHtml($stray_line['text']) ?></code></pre>
|
||||
</div>
|
||||
<?php } ?>
|
||||
<p class="text-body-secondary small mb-0">
|
||||
Put <code>#</code> in front of each, or delete the file if every line in it is one of these - with <code>sudo nano</code>, say. Then this goes by itself.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
<!-- Every job: what it does, its schedule, and how its last run went -->
|
||||
<div class="card mb-3">
|
||||
<div class="card-header py-3">
|
||||
@@ -352,7 +396,7 @@ $status_looks = [
|
||||
<?php foreach ($jobs as $job) {
|
||||
$look = $status_looks[$job['state']];
|
||||
$failing = in_array($job['state'], ['failed', 'lost'], true);
|
||||
$icon_tone = $failing ? 'bg-danger-subtle text-danger-emphasis' : ($job['enabled'] ? 'itflow-asset-tone-peripheral' : 'itflow-asset-tone-other opacity-50');
|
||||
$icon_tone = $failing ? 'bg-danger-subtle text-danger-emphasis' : ($job['enabled'] && $job['state'] !== 'unused' ? 'itflow-asset-tone-peripheral' : 'itflow-asset-tone-other opacity-50');
|
||||
// Why a skipped run was skipped - but not the switch, twelve times over, while the top of the page is saying it
|
||||
$reason = $job['reason'] === 'Cron is switched off' && !$cron_on ? '' : $job['reason'];
|
||||
?>
|
||||
@@ -384,7 +428,7 @@ $status_looks = [
|
||||
<?php } ?>
|
||||
</td>
|
||||
<td class="border-bottom-0 pt-3 pb-1">
|
||||
<span class="badge rounded-pill bg-<?= $look['tone'] ?>-subtle text-<?= $look['tone'] ?>-emphasis"><?php if ($job['state'] === 'running') { ?><i class="fas fa-circle-notch fa-spin me-1"></i><?php } ?><?= escapeHtml($look['label']) ?></span>
|
||||
<span class="badge rounded-pill bg-<?= $look['tone'] ?>-subtle text-<?= $look['tone'] ?>-emphasis"<?= isset($look['title']) ? ' title="' . escapeHtml($look['title']) . '"' : '' ?>><?php if ($job['state'] === 'running') { ?><i class="fas fa-circle-notch fa-spin me-1"></i><?php } ?><?= escapeHtml($look['label']) ?></span>
|
||||
</td>
|
||||
<td class="border-bottom-0 pt-3 pb-1 text-end pe-3">
|
||||
<?php if ($job['id']) { ?>
|
||||
@@ -438,6 +482,11 @@ $status_looks = [
|
||||
<div class="small text-body-secondary mt-1 text-break" data-cron-reason><i class="fas fa-fw fa-info-circle me-1"></i><?= escapeHtml($reason) ?></div>
|
||||
<?php } ?>
|
||||
|
||||
<?php if ($job['outside_at']) { ?>
|
||||
<div class="small text-warning-emphasis mt-1" data-cron-outside><i class="fas fa-fw fa-exclamation-triangle me-1"></i>Also started by something other than cron.php, last <?= $ago($job['outside_at']) ?> -
|
||||
<?= in_array($job['name'], $stray_jobs, true) ? 'an old cron line, above.' : 'a crontab line from before 26.08, most likely: look with <code>crontab -l</code>, as root and as ' . escapeHtml(cronFilesOwner()) . '.' ?> Take it out - while cron.php runs, it steps aside.</div>
|
||||
<?php } ?>
|
||||
|
||||
<?php if ($job['last_error'] !== '') { ?>
|
||||
<div class="d-flex align-items-start gap-2 small rounded bg-danger-subtle text-danger-emphasis p-2 mt-2" data-cron-error>
|
||||
<i class="fas fa-fw fa-exclamation-triangle mt-1" aria-hidden="true"></i>
|
||||
|
||||
21
admin/database_updates/4.4.2.php
Normal file
21
admin/database_updates/4.4.2.php
Normal file
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - Database update to version 4.4.2 (from 4.4.1)
|
||||
* Included by admin/database_updates.php - do not access directly
|
||||
*
|
||||
* cron_jobs.cron_job_outside_at - when the job was last found run by something other than cron.php: a crontab
|
||||
* line from before 26.08 that runs its script on its own. Such a run steps aside while cron.php is running, or
|
||||
* holds the job's lock when it isn't, and the dispatcher records it here (cron/cron.php, cron/includes/cron_lock.php);
|
||||
* Maintenance > 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`");
|
||||
}
|
||||
29
admin/database_updates/4.4.3.php
Normal file
29
admin/database_updates/4.4.3.php
Normal file
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* ITFlow - Database update to version 4.4.3 (from 4.4.2)
|
||||
* Included by admin/database_updates.php - do not access directly
|
||||
*
|
||||
* Knowledge Base articles written in Markdown (functions/kb.php, as documents are - database 4.2.3):
|
||||
* kb_articles.kb_article_markdown - what a Markdown article says, as it was written; NULL for an
|
||||
* article written in the rich text editor. kb_article_content stays the HTML every page shows -
|
||||
* the article, the client portal, the public help center, search, ticket replies, its PDF -
|
||||
* rendered from it each time it is saved
|
||||
* kb_article_versions.kb_article_version_markdown - the same, for each earlier version
|
||||
*
|
||||
* Re-runnable: each column is added only where it isn't there.
|
||||
*/
|
||||
|
||||
defined('FROM_DB_UPDATER') || die("Direct file access is not allowed");
|
||||
|
||||
$itflow_kb_markdown_columns = [
|
||||
['kb_articles', 'kb_article_markdown', "longtext DEFAULT NULL AFTER `kb_article_content_raw`"],
|
||||
['kb_article_versions', 'kb_article_version_markdown', "longtext DEFAULT NULL AFTER `kb_article_version_content`"],
|
||||
];
|
||||
foreach ($itflow_kb_markdown_columns as [$itflow_table, $itflow_column, $itflow_definition]) {
|
||||
$itflow_column_exists = mysqli_query($mysqli, "SELECT 1 FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '$itflow_table' AND COLUMN_NAME = '$itflow_column' LIMIT 1");
|
||||
if (!$itflow_column_exists || mysqli_num_rows($itflow_column_exists) === 0) {
|
||||
mysqli_query($mysqli, "ALTER TABLE `$itflow_table` ADD `$itflow_column` $itflow_definition");
|
||||
}
|
||||
}
|
||||
@@ -352,7 +352,7 @@ if ($error_count > 0) {
|
||||
<td class="ps-3">
|
||||
<div class="fw-semibold"><?= escapeHtml((string) ($agent['name'] ?? '')) ?>
|
||||
<?php if ($invited) { ?><span class="badge rounded-pill bg-info-subtle text-info-emphasis border border-info-subtle fw-normal ms-1">Invited</span><?php } ?>
|
||||
<?php if (!empty($agent['service'])) { ?><span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis border border-secondary-subtle fw-normal ms-1">API account</span><?php } ?>
|
||||
<?php if (!empty($agent['service'])) { ?><span class="badge rounded-pill bg-secondary-subtle text-secondary-emphasis border border-secondary-subtle fw-normal ms-1" title="A login only for API keys - it can't sign in, and takes no seat">API account</span><?php } ?>
|
||||
</div>
|
||||
<div class="text-body-secondary text-break"><?= escapeHtml((string) ($agent['email'] ?? '')) ?></div>
|
||||
</td>
|
||||
|
||||
@@ -27,7 +27,7 @@ ob_start();
|
||||
|
||||
<div class="modal-body">
|
||||
<?php if (agentUserLimitReached()) { ?>
|
||||
<div class="alert alert-danger small"><?= agentUserLimitMessage() ?></div>
|
||||
<div class="alert alert-danger small" data-user-limit><?= agentUserLimitMessage() ?><?= serviceAccountsReady() ? ' You can still add an API / service account - it takes no seat.' : '' ?></div>
|
||||
<?php } ?>
|
||||
<?php require 'user_form.php'; ?>
|
||||
</div>
|
||||
|
||||
@@ -189,7 +189,7 @@ $value = function ($key) use ($form) {
|
||||
<input class="form-check-input" type="checkbox" role="switch" name="service_account" value="1" id="<?= $form_id ?>ServiceAccount" <?= $form_service ? 'checked' : '' ?>>
|
||||
<label class="form-check-label fw-semibold" for="<?= $form_id ?>ServiceAccount"><i class="fas fa-fw fa-plug text-body-secondary me-1"></i>API / service account</label>
|
||||
<div class="form-text mt-0">
|
||||
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.
|
||||
<?= $is_new ? 'Set a password for it - it isn\'t invited.' : '' ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -34,7 +34,7 @@ ob_start();
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if (agentUserLimitReached()) { ?>
|
||||
<?php if (agentUserLimitReached() && !serviceAccountIs($user_id)) { ?>
|
||||
<div class="alert alert-danger small"><?= agentUserLimitMessage() ?></div>
|
||||
<?php } ?>
|
||||
<?php if ($email_taken) { ?>
|
||||
|
||||
@@ -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('<strong>' . escapeHtml($row['user_name']) . '</strong> 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;
|
||||
}
|
||||
|
||||
@@ -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'];
|
||||
<h3 class="card-title mt-2"><i class="fas fa-fw fa-users me-2"></i>Users
|
||||
<?php if ($agent_user_limit > 0) { ?>
|
||||
<span class="badge rounded-pill text-bg-<?= $agent_user_limit_reached ? 'danger' : 'secondary' ?> fw-normal ms-2"
|
||||
title="<?= $agent_user_count ?> active agent<?= $agent_user_count === 1 ? '' : 's' ?><?= $agent_invites_holding ? " and $agent_invites_holding invite" . ($agent_invites_holding === 1 ? '' : 's') . ' waiting' : '' ?>, of the agent user limit <?= $managed_limit_by !== '' ? 'set by ' . escapeHtml($managed_limit_by) : 'set for this installation' ?>">
|
||||
title="<?= $agent_user_count ?> active agent<?= $agent_user_count === 1 ? '' : 's' ?><?= $agent_invites_holding ? " and $agent_invites_holding invite" . ($agent_invites_holding === 1 ? '' : 's') . ' waiting' : '' ?>, of the agent user limit <?= $managed_limit_by !== '' ? 'set by ' . escapeHtml($managed_limit_by) : 'set for this installation' ?><?= serviceAccountsReady() ? ' - API / service accounts take none' : '' ?>">
|
||||
<?= $agent_user_count + $agent_invites_holding ?> of <?= $agent_user_limit ?> seats
|
||||
</span>
|
||||
<?php } ?>
|
||||
</h3>
|
||||
<div class="card-tools">
|
||||
<div class="btn-group">
|
||||
<?php if ($agent_user_limit_reached) { ?>
|
||||
<?php if ($agent_user_limit_reached && !serviceAccountsReady()) { ?>
|
||||
<button type="button" class="btn btn-primary" disabled title="Every seat is taken - disable or archive a user<?= $agent_invites_holding ? ', or cancel an invite,' : '' ?> first">
|
||||
<i class="fas fa-user-plus"></i><span class="d-none d-lg-inline ms-2">New User</span>
|
||||
</button>
|
||||
|
||||
@@ -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
|
||||
|
||||
25
agent/kb.php
25
agent/kb.php
@@ -136,15 +136,26 @@ $csrf = $_SESSION['csrf_token'];
|
||||
<i class="fas fa-plus"></i><span class="d-none d-lg-inline ms-2">New Article</span>
|
||||
</button>
|
||||
<?php } ?>
|
||||
<?php if ($session_is_admin) { ?>
|
||||
<?php $kb_import = $can_edit && kbMarkdownReady(); ?>
|
||||
<?php if ($session_is_admin || $kb_import) { ?>
|
||||
<button type="button" class="btn btn-primary dropdown-toggle <?= $can_edit ? 'dropdown-toggle-split' : '' ?>" data-bs-toggle="dropdown" aria-label="More actions"><?= $can_edit ? '' : '<i class="fas fa-ellipsis-v"></i>' ?></button>
|
||||
<div class="dropdown-menu dropdown-menu-end">
|
||||
<a class="dropdown-item" href="/admin/categories.php?category=kb">
|
||||
<i class="fas fa-fw fa-list-ul text-secondary me-2"></i>Categories
|
||||
</a>
|
||||
<a class="dropdown-item" href="/admin/tags.php?type=<?= tagEntity('kb_article')['type'] ?>">
|
||||
<i class="fas fa-fw fa-tags text-secondary me-2"></i>Tags
|
||||
</a>
|
||||
<?php if ($kb_import) { ?>
|
||||
<a class="dropdown-item ajax-modal" href="#" data-modal-url="<?= escapeHtml('modals/kb/kb_import_markdown.php' . (intval($category_filter) > 0 ? '?category=' . intval($category_filter) : '')) ?>">
|
||||
<i class="fab fa-fw fa-markdown me-2"></i>Import Markdown Files
|
||||
</a>
|
||||
<?php } ?>
|
||||
<?php if ($session_is_admin) { ?>
|
||||
<?php if ($kb_import) { ?>
|
||||
<div class="dropdown-divider"></div>
|
||||
<?php } ?>
|
||||
<a class="dropdown-item" href="/admin/categories.php?category=kb">
|
||||
<i class="fas fa-fw fa-list-ul text-secondary me-2"></i>Categories
|
||||
</a>
|
||||
<a class="dropdown-item" href="/admin/tags.php?type=<?= tagEntity('kb_article')['type'] ?>">
|
||||
<i class="fas fa-fw fa-tags text-secondary me-2"></i>Tags
|
||||
</a>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
|
||||
@@ -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'];
|
||||
<span title="<?= formatDateTime($updated_at) ?>">Updated <?= timeAgo($updated_at) ?></span><?= $updated_by !== '' ? " by $updated_by" : '' ?>
|
||||
· Written <?= date('M j, Y', strtotime($row['kb_article_created_at'])) ?><?= $row['created_by_name'] !== null ? ' by ' . escapeHtml($row['created_by_name']) : '' ?>
|
||||
<?php if ($versions) { ?>· <a class="text-reset d-print-none" href="#kbArticleVersions"><?= count($versions) ?> earlier version<?= count($versions) === 1 ? '' : 's' ?></a><?php } ?>
|
||||
<?php if (($row['kb_article_markdown'] ?? null) !== null) { ?>· <span title="Written in Markdown - Edit shows the Markdown"><i class="fab fa-fw fa-markdown me-1"></i>Markdown</span><?php } ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex flex-wrap gap-2 d-print-none">
|
||||
@@ -116,8 +117,17 @@ $page_title = $row['kb_article_title'];
|
||||
<i class="fas fa-clipboard-check"></i><span class="d-none d-md-inline ms-2">Review with AI</span>
|
||||
</button>
|
||||
<?php } ?>
|
||||
<button type="button" class="btn btn-outline-secondary" onclick="window.print();" title="Print"><i class="fas fa-print"></i></button>
|
||||
<a class="btn btn-outline-secondary" href="post.php?export_kb_article=<?= $kb_article_id ?>&csrf_token=<?= $csrf ?>" title="Export as PDF"><i class="fas fa-file-pdf"></i><span class="d-none d-md-inline ms-2">PDF</span></a>
|
||||
<div class="dropdown">
|
||||
<button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false" title="Download or print it">
|
||||
<i class="fas fa-download"></i><span class="d-none d-md-inline ms-2">Export</span>
|
||||
</button>
|
||||
<div class="dropdown-menu dropdown-menu-end">
|
||||
<a class="dropdown-item" href="post.php?export_kb_article=<?= $kb_article_id ?>&csrf_token=<?= $csrf ?>"><i class="fas fa-fw fa-file-pdf me-2"></i>PDF</a>
|
||||
<a class="dropdown-item" href="post.php?export_kb_article_markdown=<?= $kb_article_id ?>&csrf_token=<?= $csrf ?>"><i class="fab fa-fw fa-markdown me-2"></i>Markdown (.md)</a>
|
||||
<div class="dropdown-divider"></div>
|
||||
<button type="button" class="dropdown-item" onclick="window.print();"><i class="fas fa-fw fa-print me-2"></i>Print</button>
|
||||
</div>
|
||||
</div>
|
||||
<?php if ($can_edit) { ?>
|
||||
<div class="dropdown">
|
||||
<button type="button" class="btn btn-outline-secondary" data-bs-toggle="dropdown" title="More actions"><i class="fas fa-ellipsis-v"></i></button>
|
||||
|
||||
@@ -4,12 +4,15 @@
|
||||
* The body of New Article and Edit Article (kb_article_add.php,
|
||||
* kb_article_edit.php): title and summary across the top, its category, tags,
|
||||
* how often it's reviewed and whether it's published under them, the editor
|
||||
* below. Posts what kbArticleFields() reads (functions/kb.php).
|
||||
* below - in rich text or Markdown, switched either way as it is written
|
||||
* (includes/document_editors.php, as for documents). Posts what
|
||||
* kbArticleFields() reads (functions/kb.php).
|
||||
*
|
||||
* Expects $kb_form (kbArticleRow(), or the new article's starting values:
|
||||
* kb_article_title, kb_article_summary, kb_article_content,
|
||||
* kb_article_title, kb_article_summary, kb_article_content, kb_article_markdown,
|
||||
* kb_article_category_id, kb_article_review_months, kb_article_published_at)
|
||||
* and $kb_form_mode ('add' or 'edit').
|
||||
* and $kb_form_mode ('add' or 'edit'). A new article starts in the way the
|
||||
* agent wrote last.
|
||||
*
|
||||
* Who can read it - agents only, clients (all, by client tag, by name) or
|
||||
* anyone - shows its choices as it is set (js/kb_article_form.js).
|
||||
@@ -142,7 +145,14 @@ $kb_form_audience = $kb_form_mode === 'edit' ? kbAudienceFields($kb_form) : ['vi
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<textarea class="form-control tinymce" name="content" aria-label="Content"><?= escapeHtml($kb_form['kb_article_content'] ?? '') ?></textarea>
|
||||
<?php
|
||||
$document_content = escapeHtml($kb_form['kb_article_content'] ?? '');
|
||||
$document_markdown = $kb_form['kb_article_markdown'] ?? null;
|
||||
$document_format_remember = $kb_form_mode === 'add';
|
||||
$document_editor_rich_class = 'tinymce';
|
||||
$document_editor_markdown_ready = kbMarkdownReady();
|
||||
require dirname(__DIR__, 3) . '/includes/document_editors.php';
|
||||
?>
|
||||
|
||||
<?php if ($kb_form_mode === 'edit') { ?>
|
||||
<div class="form-text"><i class="fas fa-history me-1"></i>Saving keeps what it says now in the article's versions, so it can be put back.</div>
|
||||
|
||||
@@ -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) {
|
||||
|
||||
65
agent/modals/kb/kb_import_markdown.php
Normal file
65
agent/modals/kb/kb_import_markdown.php
Normal file
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* Import Markdown files into the Knowledge Base - each .md file picked becomes an article written
|
||||
* in Markdown, a draft for agents only, in the category picked (import_markdown_kb_articles,
|
||||
* agent/post/kb.php). ?category starts it in the list's category.
|
||||
*/
|
||||
|
||||
require_once '../../../includes/modal_header.php';
|
||||
|
||||
$kb_closed = kbClosedText(2);
|
||||
if ($kb_closed !== '') {
|
||||
exit(json_encode(['error' => $kb_closed]));
|
||||
}
|
||||
|
||||
$kb_import_category = kbCategoryId($_GET['category'] ?? 0);
|
||||
|
||||
ob_start();
|
||||
|
||||
?>
|
||||
|
||||
<div class="modal-header bg-dark">
|
||||
<h5 class="modal-title"><i class="fab fa-fw fa-markdown me-2"></i>Import Markdown Files</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<form action="post.php" method="post" enctype="multipart/form-data" autocomplete="off">
|
||||
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
|
||||
<div class="modal-body">
|
||||
<?php if (!kbMarkdownReady()) { ?>
|
||||
<div class="alert alert-warning mb-0">Articles in Markdown arrive with the next database update - run it from Maintenance > Update first.</div>
|
||||
<?php } else { ?>
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Markdown files <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-file-import"></i></span>
|
||||
<input type="file" class="form-control" name="files[]" multiple required accept=".md,.markdown,.mdown,.mkd,text/markdown">
|
||||
</div>
|
||||
<div class="form-text">Each becomes an article written in Markdown, named by the heading it starts with or its file name - up to 50 at a time. They come in as drafts for agents only, to read through before you publish them. Pictures a file points to on your computer aren't brought in.</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="form-label">Category</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-list-ul"></i></span>
|
||||
<select class="form-select select2" name="category_id">
|
||||
<option value="0">- No category -</option>
|
||||
<?php foreach (categoryPicker('kb', $kb_import_category ? [$kb_import_category] : []) as $category_id => $category_row) { ?>
|
||||
<?= categoryOptionHtml($category_row, intval($category_id) === $kb_import_category) ?>
|
||||
<?php } ?>
|
||||
</select>
|
||||
<?= categoryAddButtonHtml('kb') ?>
|
||||
</div>
|
||||
</div>
|
||||
<?php } ?>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<?php if (kbMarkdownReady()) { ?>
|
||||
<button type="submit" name="import_markdown_kb_articles" class="btn btn-primary fw-bold"><i class="fas fa-file-import me-2"></i>Import</button>
|
||||
<?php } ?>
|
||||
<button type="button" class="btn btn-light" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i>Cancel</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<?php
|
||||
require_once '../../../includes/modal_footer.php';
|
||||
@@ -3,16 +3,16 @@
|
||||
/*
|
||||
* ITFlow - GET/POST request handlers for the Knowledge Base (agent/kb.php,
|
||||
* agent/kb_article.php): writing, editing, publishing, reviewing, archiving,
|
||||
* copying and deleting articles, their versions, the bulk actions, and
|
||||
* copying a client's document in as a new article. The work is in
|
||||
* functions/kb.php.
|
||||
* copying and deleting articles, their versions, the bulk actions, copying a
|
||||
* client's document in as a new article, importing .md files as articles and
|
||||
* downloading one as PDF or Markdown. The work is in functions/kb.php.
|
||||
*/
|
||||
|
||||
defined('FROM_POST_HANDLER') || die("Direct file access is not allowed");
|
||||
|
||||
// Closed while the Knowledge Base is off, or to a role that can't write in it (or delete, for the deletes)
|
||||
$kb_requested = array_merge(
|
||||
array_intersect(['add_kb_article', 'edit_kb_article', 'restore_kb_article_version', 'bulk_category_kb_articles', 'bulk_publish_kb_articles', 'upload_kb_article_files', 'set_kb_article_summary',
|
||||
array_intersect(['add_kb_article', 'edit_kb_article', 'restore_kb_article_version', 'bulk_category_kb_articles', 'bulk_publish_kb_articles', 'upload_kb_article_files', 'set_kb_article_summary', 'import_markdown_kb_articles',
|
||||
'bulk_draft_kb_articles', 'bulk_archive_kb_articles', 'bulk_restore_kb_articles', 'bulk_delete_kb_articles'], array_keys($_POST)),
|
||||
array_intersect(['publish_kb_article', 'draft_kb_article', 'mark_kb_article_reviewed', 'archive_kb_article', 'restore_kb_article', 'delete_kb_article',
|
||||
'copy_kb_article', 'delete_kb_article_version', 'copy_document_to_kb', 'deal_with_kb_feedback', 'deal_with_kb_article_feedback', 'dismiss_kb_search_miss',
|
||||
@@ -192,15 +192,19 @@ if (isset($_GET['copy_kb_article'])) {
|
||||
'published' => 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 <strong>' . escapeHtml($imported[0][1]) . '</strong> 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');
|
||||
}
|
||||
|
||||
@@ -314,7 +314,7 @@ if (isset($_POST['add_your_passkey'])) {
|
||||
|
||||
flashAlert("Passkey <strong>" . escapeHtml($name) . "</strong> 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");
|
||||
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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.
|
||||
|
||||
37
api/v1/kb_articles/archive.php
Normal file
37
api/v1/kb_articles/archive.php
Normal file
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* API - Knowledge Base articles - Archive
|
||||
* POST /api/v1/kb_articles/archive.php
|
||||
*
|
||||
* Archive an article - it leaves the Knowledge Base's lists, the client portal and the public
|
||||
* help center, and comes back with unarchive.php.
|
||||
*
|
||||
* Parameters (POST, JSON body):
|
||||
* api_key required - Your API key
|
||||
* kb_article_id required - The article
|
||||
*/
|
||||
|
||||
require_once '../validate_api_key.php';
|
||||
|
||||
require_once '../require_post_method.php';
|
||||
|
||||
require_once 'kb_article_model.php';
|
||||
|
||||
$update_count = false;
|
||||
|
||||
$row = kbApiArticle($_POST['kb_article_id'] ?? 0);
|
||||
if ($row['kb_article_archived_at']) {
|
||||
kbApiFail('That article is archived already.');
|
||||
}
|
||||
|
||||
$kb_article_id = intval($row['kb_article_id']);
|
||||
mysqli_query($mysqli, "UPDATE kb_articles SET kb_article_archived_at = NOW() WHERE kb_article_id = $kb_article_id");
|
||||
$update_count = mysqli_affected_rows($mysqli);
|
||||
|
||||
$title = escapeSql($row['kb_article_title']);
|
||||
logAudit("Knowledge Base", "Archive", "$session_name archived article $title via API ($api_key_name)", 0, $kb_article_id);
|
||||
logAudit("API", "Success", "Archived Knowledge Base article $title via API ($api_key_name)", 0);
|
||||
|
||||
// Output
|
||||
require_once '../update_output.php';
|
||||
52
api/v1/kb_articles/create.php
Normal file
52
api/v1/kb_articles/create.php
Normal file
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* API - Knowledge Base articles - Create
|
||||
* POST /api/v1/kb_articles/create.php
|
||||
*
|
||||
* Write an article, as New Article does - a draft for agents only unless it says otherwise.
|
||||
*
|
||||
* Parameters (POST, JSON body):
|
||||
* api_key required - Your API key
|
||||
* kb_article_title required - Up to 200 characters
|
||||
* kb_article_content optional - What it says, as HTML. Pictures in it as data: URLs are saved as files
|
||||
* kb_article_markdown optional - What it says in Markdown, instead - it is written in Markdown,
|
||||
* and kb_article_content is made from it
|
||||
* kb_article_summary optional - One line on what it helps with, up to 255 characters
|
||||
* kb_article_category_id optional - A Knowledge Base category (categories/read.php?kind=kb)
|
||||
* kb_article_review_months optional - How often it is reviewed: 0 (never), 3, 6, 12 (the default) or 24
|
||||
* kb_article_published optional - 1 to publish it; a draft otherwise
|
||||
* kb_article_visibility optional - agents (the default), clients or public
|
||||
* kb_article_all_clients optional - 1: every client, for clients
|
||||
* kb_article_client_tag_ids optional - For clients: the clients with these client tags
|
||||
* kb_article_client_ids optional - For clients: these clients
|
||||
* tags optional - Its tags - ids or names, as an array or comma-separated
|
||||
*
|
||||
* Shared with clients, it needs kb_article_all_clients, kb_article_client_tag_ids or
|
||||
* kb_article_client_ids. Returns the new article's id.
|
||||
*/
|
||||
|
||||
require_once '../validate_api_key.php';
|
||||
|
||||
require_once '../require_post_method.php';
|
||||
|
||||
require_once 'kb_article_model.php';
|
||||
|
||||
$insert_id = false;
|
||||
|
||||
[$fields, $error] = kbApiFields($_POST);
|
||||
if ($error !== '') {
|
||||
kbApiFail($error);
|
||||
}
|
||||
|
||||
$insert_id = kbArticleSave($fields);
|
||||
if (isset($_POST['tags'])) {
|
||||
tagSetForRecord('kb_article', $insert_id, kbApiList($_POST['tags']));
|
||||
}
|
||||
|
||||
$title = escapeSql($fields['title']);
|
||||
logAudit("Knowledge Base", "Create", "$session_name wrote " . ($fields['published'] ? '' : 'a draft of ') . "article $title via API ($api_key_name)", 0, $insert_id);
|
||||
logAudit("API", "Success", "Created Knowledge Base article $title via API ($api_key_name)", 0);
|
||||
|
||||
// Output
|
||||
require_once '../create_output.php';
|
||||
35
api/v1/kb_articles/delete.php
Normal file
35
api/v1/kb_articles/delete.php
Normal file
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* API - Knowledge Base articles - Delete
|
||||
* POST /api/v1/kb_articles/delete.php
|
||||
*
|
||||
* Delete an article for good, as Delete on its page does - with its versions, tags, files,
|
||||
* pictures and readers' feedback. Needs Full on Support.
|
||||
*
|
||||
* Parameters (POST, JSON body):
|
||||
* api_key required - Your API key
|
||||
* kb_article_id required - The article
|
||||
*/
|
||||
|
||||
require_once '../validate_api_key.php';
|
||||
|
||||
require_once '../require_post_method.php';
|
||||
|
||||
require_once 'kb_article_model.php';
|
||||
|
||||
$delete_count = false;
|
||||
|
||||
$row = kbApiArticle($_POST['kb_article_id'] ?? 0);
|
||||
$kb_article_id = intval($row['kb_article_id']);
|
||||
|
||||
$title = kbArticleDelete($kb_article_id);
|
||||
if ($title !== null) {
|
||||
$delete_count = 1;
|
||||
$title = escapeSql($title);
|
||||
logAudit("Knowledge Base", "Delete", "$session_name deleted article $title and its versions via API ($api_key_name)", 0, $kb_article_id);
|
||||
logAudit("API", "Success", "Deleted Knowledge Base article $title via API ($api_key_name)", 0);
|
||||
}
|
||||
|
||||
// Output
|
||||
require_once '../delete_output.php';
|
||||
210
api/v1/kb_articles/kb_article_model.php
Normal file
210
api/v1/kb_articles/kb_article_model.php
Normal file
@@ -0,0 +1,210 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* API - Knowledge Base articles - what the endpoints share. The work is functions/kb.php's, as for
|
||||
* the Knowledge Base pages: kbArticleFields() checks what is sent, kbArticleSave() saves it -
|
||||
* keeping the version before - and articles written in Markdown are stored as the pages store them.
|
||||
*
|
||||
* Articles are no client's, so no client_id is needed to change one, as on the pages. Reading takes
|
||||
* Support at View, changing Modify and deleting Full, with the Knowledge Base switched on in
|
||||
* Admin > 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;
|
||||
}
|
||||
90
api/v1/kb_articles/read.php
Normal file
90
api/v1/kb_articles/read.php
Normal file
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* API - Knowledge Base articles - Read
|
||||
* GET /api/v1/kb_articles/read.php
|
||||
*
|
||||
* The Knowledge Base's articles, newest change first, or one of them.
|
||||
*
|
||||
* Parameters (GET):
|
||||
* api_key required - Your API key
|
||||
* kb_article_id optional - One article, archived or not, with its earlier versions
|
||||
* q optional - Articles with these words in the title, the summary or the text
|
||||
* category_id optional - Articles in this Knowledge Base category, 0 for none
|
||||
* visibility optional - agents, clients or public: who can read them
|
||||
* published optional - 1 for published articles only, 0 for drafts only
|
||||
* client_id optional - The articles this client's portal shows (published, shared with it)
|
||||
* archived optional - 1 to include archived articles
|
||||
* limit optional - Max rows to return (default 50)
|
||||
* offset optional - Offset for pagination (default 0)
|
||||
*
|
||||
* Each article: kb_article_id, kb_article_title, kb_article_summary, kb_article_content (as
|
||||
* HTML), kb_article_markdown (as written for an article in Markdown, null for rich text),
|
||||
* kb_article_format (markdown or html), kb_article_category_id and _name, kb_article_published_at
|
||||
* (null for a draft), kb_article_visibility, kb_article_all_clients, kb_article_client_tag_ids,
|
||||
* kb_article_client_ids (the clients it is shared with by name that the key's user can reach),
|
||||
* kb_article_review_months, kb_article_reviewed_at, kb_article_next_review, kb_article_review_due,
|
||||
* kb_article_views, kb_article_created_at, _by and _by_name, kb_article_updated_at, _by and
|
||||
* _by_name, kb_article_archived_at, kb_article_public_url (its address on the public help center,
|
||||
* when it is on it) and tags. One article asked for by its id also has kb_article_versions.
|
||||
*/
|
||||
|
||||
require_once '../validate_api_key.php';
|
||||
|
||||
require_once '../require_get_method.php';
|
||||
|
||||
require_once 'kb_article_model.php';
|
||||
|
||||
if (isset($_GET['kb_article_id'])) {
|
||||
$where = 'kb_article_id = ' . intval($_GET['kb_article_id']);
|
||||
} else {
|
||||
$where = intval($_GET['archived'] ?? 0) === 1 ? '1 = 1' : 'kb_article_archived_at IS NULL';
|
||||
if (isset($_GET['category_id'])) {
|
||||
$where .= ' AND kb_article_category_id = ' . max(0, intval($_GET['category_id']));
|
||||
}
|
||||
if (isset($_GET['visibility'])) {
|
||||
$visibility = strtolower(trim((string) $_GET['visibility']));
|
||||
if (!isset(KB_VISIBILITY[$visibility])) {
|
||||
kbApiFail('visibility is agents, clients or public.');
|
||||
}
|
||||
$where .= " AND kb_article_visibility = '$visibility'";
|
||||
}
|
||||
if (isset($_GET['published'])) {
|
||||
$where .= intval($_GET['published']) === 1 ? ' AND kb_article_published_at IS NOT NULL' : ' AND kb_article_published_at IS NULL';
|
||||
}
|
||||
if (!empty($client_id_supplied)) {
|
||||
$kb_client_id = intval($_GET['client_id']);
|
||||
if (!apiUserCanAccessClient($kb_client_id)) {
|
||||
apiDeny("The user linked to this API key does not have access to that client.");
|
||||
}
|
||||
$where .= ' AND ' . kbClientSql($kb_client_id);
|
||||
}
|
||||
$q = trim((string) ($_GET['q'] ?? ''));
|
||||
if ($q !== '') {
|
||||
$q_sql = escapeSql($q);
|
||||
$where .= " AND (kb_article_title LIKE '%$q_sql%' OR kb_article_summary LIKE '%$q_sql%' OR MATCH(kb_article_content_raw) AGAINST ('$q_sql'))";
|
||||
}
|
||||
}
|
||||
|
||||
$sql = mysqli_query($mysqli, kbArticleSelectSql() . " WHERE $where
|
||||
ORDER BY COALESCE(kb_article_updated_at, kb_article_created_at) DESC, kb_article_id DESC
|
||||
LIMIT $limit OFFSET $offset");
|
||||
|
||||
if ($sql && mysqli_num_rows($sql) > 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';
|
||||
36
api/v1/kb_articles/unarchive.php
Normal file
36
api/v1/kb_articles/unarchive.php
Normal file
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* API - Knowledge Base articles - Unarchive
|
||||
* POST /api/v1/kb_articles/unarchive.php
|
||||
*
|
||||
* Bring an archived article back, as Restore does - published or a draft, as it was.
|
||||
*
|
||||
* Parameters (POST, JSON body):
|
||||
* api_key required - Your API key
|
||||
* kb_article_id required - The archived article
|
||||
*/
|
||||
|
||||
require_once '../validate_api_key.php';
|
||||
|
||||
require_once '../require_post_method.php';
|
||||
|
||||
require_once 'kb_article_model.php';
|
||||
|
||||
$update_count = false;
|
||||
|
||||
$row = kbApiArticle($_POST['kb_article_id'] ?? 0);
|
||||
if (!$row['kb_article_archived_at']) {
|
||||
kbApiFail("That article isn't archived.");
|
||||
}
|
||||
|
||||
$kb_article_id = intval($row['kb_article_id']);
|
||||
mysqli_query($mysqli, "UPDATE kb_articles SET kb_article_archived_at = NULL WHERE kb_article_id = $kb_article_id");
|
||||
$update_count = mysqli_affected_rows($mysqli);
|
||||
|
||||
$title = escapeSql($row['kb_article_title']);
|
||||
logAudit("Knowledge Base", "Restore", "$session_name restored article $title via API ($api_key_name)", 0, $kb_article_id);
|
||||
logAudit("API", "Success", "Restored Knowledge Base article $title via API ($api_key_name)", 0);
|
||||
|
||||
// Output
|
||||
require_once '../update_output.php';
|
||||
51
api/v1/kb_articles/update.php
Normal file
51
api/v1/kb_articles/update.php
Normal file
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* API - Knowledge Base articles - Update
|
||||
* POST /api/v1/kb_articles/update.php
|
||||
*
|
||||
* Change an article, as Edit Article does - what it said before is kept in its versions when its
|
||||
* words change. Only what is sent changes.
|
||||
*
|
||||
* Parameters (POST, JSON body):
|
||||
* api_key required - Your API key
|
||||
* kb_article_id required - The article - not an archived one (unarchive.php first)
|
||||
* any of the fields create.php takes. kb_article_content makes it an article in rich text,
|
||||
* kb_article_markdown one in Markdown; sending neither leaves what it says as it is. Sending
|
||||
* tags sets its tags to those. Sending kb_article_client_ids sets the clients it is shared
|
||||
* with - apart from any the key's user can't reach, which stay.
|
||||
*/
|
||||
|
||||
require_once '../validate_api_key.php';
|
||||
|
||||
require_once '../require_post_method.php';
|
||||
|
||||
require_once 'kb_article_model.php';
|
||||
|
||||
$update_count = false;
|
||||
|
||||
$row = kbApiArticle($_POST['kb_article_id'] ?? 0);
|
||||
if ($row['kb_article_archived_at']) {
|
||||
kbApiFail('That article is archived - unarchive.php brings it back to be changed.');
|
||||
}
|
||||
|
||||
[$fields, $error] = kbApiFields($_POST, $row);
|
||||
if ($error !== '') {
|
||||
kbApiFail($error);
|
||||
}
|
||||
|
||||
$kb_article_id = intval($row['kb_article_id']);
|
||||
kbArticleSave($fields, $row);
|
||||
if (isset($_POST['tags'])) {
|
||||
tagSetForRecord('kb_article', $kb_article_id, kbApiList($_POST['tags']));
|
||||
}
|
||||
$update_count = 1;
|
||||
|
||||
$title = escapeSql($fields['title']);
|
||||
$was = !empty($row['kb_article_published_at']);
|
||||
$how = $fields['published'] === $was ? 'edited' : ($fields['published'] ? 'edited and published' : 'edited and made a draft of');
|
||||
logAudit("Knowledge Base", "Edit", "$session_name $how article $title via API ($api_key_name)", 0, $kb_article_id);
|
||||
logAudit("API", "Success", "Edited Knowledge Base article $title via API ($api_key_name)", 0);
|
||||
|
||||
// Output
|
||||
require_once '../update_output.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");
|
||||
|
||||
102
cron/cron.php
102
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"));
|
||||
|
||||
@@ -153,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
|
||||
@@ -203,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);
|
||||
@@ -221,6 +278,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, " . (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']] = ['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) {
|
||||
if ($cron_dispatch_running === null) {
|
||||
return;
|
||||
@@ -243,10 +311,34 @@ 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']]['run_now']) && 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);
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
3
db.sql
3
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;
|
||||
@@ -2256,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,
|
||||
@@ -2277,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',
|
||||
|
||||
@@ -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 [
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
|
||||
@@ -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 '<a href="#" class="text-body-secondary text-decoration-none" data-vault-unlock data-vault-locked title="Unlock with your password"><i class="fas fa-lock me-1"></i>Locked</a>';
|
||||
// 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 '<a href="#" class="text-body-secondary text-decoration-none" data-vault-unlock data-vault-locked title="Unlock your credentials"><i class="fas fa-lock me-1"></i>Locked</a>';
|
||||
}
|
||||
if ($username === '') {
|
||||
return '<span class="text-body-secondary">' . $empty . '</span>';
|
||||
|
||||
@@ -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;
|
||||
@@ -60,7 +62,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;
|
||||
@@ -69,13 +72,13 @@ 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;
|
||||
}
|
||||
$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']];
|
||||
@@ -145,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'];
|
||||
@@ -167,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']) . '.'];
|
||||
@@ -340,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';
|
||||
}
|
||||
|
||||
100
functions/kb.php
100
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);
|
||||
@@ -190,6 +228,14 @@ function kbPickerRowsHtml(array $rows, $client_id) {
|
||||
function kbArticleReplyHtml(array $row) {
|
||||
global $config_base_url;
|
||||
$html = documentHtmlPurify((string) $row['kb_article_content']);
|
||||
// A table written in Markdown is bordered by the app's styles (table-bordered, markdownToHtml()),
|
||||
// which an email doesn't have - it gets a plain border of its own, as a rich text table has
|
||||
$html = preg_replace_callback('#<table\b([^>]*\bclass="[^"]*\btable-bordered\b[^"]*"[^>]*)>#i', function ($m) {
|
||||
if (preg_match('/\sborder\s*=/i', $m[1])) {
|
||||
return $m[0];
|
||||
}
|
||||
return '<table' . $m[1] . ' border="1" cellpadding="6"' . (preg_match('/\sstyle\s*=/i', $m[1]) ? '' : ' style="border-collapse: collapse;"') . '>';
|
||||
}, $html);
|
||||
return preg_replace('#\b(src|href)="/?(uploads/kb/\d+/[^"]+)"#', '$1="https://' . $config_base_url . '/$2"', $html);
|
||||
}
|
||||
|
||||
@@ -263,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, 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,
|
||||
@@ -273,14 +324,15 @@ 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";
|
||||
}
|
||||
|
||||
/*
|
||||
* 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 +348,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 +368,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 +426,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 +434,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 +444,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 +459,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 +599,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 +620,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;
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -201,17 +201,19 @@ function htmlToMarkdown($html, &$notes = null) {
|
||||
/**
|
||||
* Pictures pasted into a Markdown document arrive as data - each is saved under
|
||||
* uploads/documents/<id>/, 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/<id>/
|
||||
* ($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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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). */
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
<div data-editor-rich<?= $document_is_markdown ? ' hidden' : '' ?>>
|
||||
<!-- Written as it will read on its page (.tinymce-document, js/app.js) -->
|
||||
<textarea class="form-control tinymce-document" name="content" aria-label="Content"<?= $document_editor_required ? ' data-required' : '' ?>><?= $document_content ?></textarea>
|
||||
<textarea class="form-control <?= $document_rich_class ?>" name="content" aria-label="Content"<?= $document_editor_required ? ' data-required' : '' ?>><?= $document_content ?></textarea>
|
||||
</div>
|
||||
|
||||
<?php if ($document_markdown_ready) { ?>
|
||||
|
||||
@@ -96,12 +96,21 @@ try {
|
||||
<script src="<?= staticFileUrl('/js/app.js') ?>"></script>
|
||||
<script src="<?= staticFileUrl('/js/picture_field.js') ?>"></script>
|
||||
<?php
|
||||
// Signed in without the password that opens the credential vault - a passkey that can't, an identity provider or a mail password; their password unlocks it (vaultUnlock(), js/credentials.js)
|
||||
// Signed in without the password that opens the credential vault - a passkey sign-in that didn't, an identity provider or a mail password; their password
|
||||
// unlocks it (vaultUnlock(), js/credentials.js), and so does a passkey of theirs that opens it (vaultUnlockPasskey(), js/passkey.js)
|
||||
try {
|
||||
$itflow_vault_locked = function_exists('vaultLocked') && vaultLocked();
|
||||
} catch (Throwable $e) {
|
||||
$itflow_vault_locked = false;
|
||||
}
|
||||
// And a passkey whose secret is kept from this sign-in, sealed to once the vault opens (passkeySealKept())
|
||||
try {
|
||||
$itflow_vault_passkeys = $itflow_vault_locked ? passkeyVaultCount($session_user_id) : 0;
|
||||
$itflow_vault_seal = $itflow_vault_locked ? passkeySealPending($session_user_id) : '';
|
||||
} catch (Throwable $e) {
|
||||
$itflow_vault_passkeys = 0;
|
||||
$itflow_vault_seal = '';
|
||||
}
|
||||
if ($itflow_vault_locked) { ?>
|
||||
<div class="modal" id="vaultUnlockModal" tabindex="-1" data-csrf="<?= $_SESSION['csrf_token'] ?>">
|
||||
<div class="modal-dialog">
|
||||
@@ -110,14 +119,25 @@ if ($itflow_vault_locked) { ?>
|
||||
<h5 class="modal-title"><i class="fas fa-fw fa-lock me-2"></i>Unlock Your Credentials</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<form data-vault-unlock-form autocomplete="off">
|
||||
<form data-vault-unlock-form>
|
||||
<div class="modal-body">
|
||||
<p><?= escapeHtml(ucfirst(vaultLockedReason())) ?>, so your usernames, passwords and 2FA codes are locked. Type your ITFlow password to unlock them until you sign out.</p>
|
||||
<p><?= escapeHtml(ucfirst(vaultLockedReason())) ?>, so your usernames, passwords and 2FA codes are locked. <?= $itflow_vault_passkeys ? 'Unlock them with a passkey or your ITFlow password' : 'Type your ITFlow password to unlock them' ?> until you sign out.</p>
|
||||
<?php if ($itflow_vault_seal !== '') { ?>
|
||||
<p class="small text-body-secondary"><i class="fas fa-fingerprint me-1"></i>Once you do, your passkey <strong><?= escapeHtml($itflow_vault_seal) ?></strong> opens them by itself from your next sign-in.</p>
|
||||
<?php } ?>
|
||||
<div data-vault-unlock-message></div>
|
||||
<label class="form-label">Your password <strong class="text-danger">*</strong></label>
|
||||
<?php if ($itflow_vault_passkeys) { ?>
|
||||
<div data-vault-unlock-passkey-box hidden>
|
||||
<button type="button" class="btn btn-outline-primary w-100" data-vault-unlock-passkey><i class="fas fa-fingerprint me-2"></i>Unlock with a Passkey</button>
|
||||
<div class="text-center small text-body-secondary my-3">or type your password</div>
|
||||
</div>
|
||||
<?php } ?>
|
||||
<!-- Whose password it is, so a password manager offers the one it keeps for signing in here (as join.php does) -->
|
||||
<input type="text" class="d-none" name="username" value="<?= escapeHtml($session_email ?? '') ?>" autocomplete="username" aria-hidden="true" tabindex="-1">
|
||||
<label class="form-label" for="vaultUnlockPassword">Your password <strong class="text-danger">*</strong></label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-fw fa-lock"></i></span>
|
||||
<input type="password" class="form-control" name="password" autocomplete="current-password" required>
|
||||
<input type="password" class="form-control" name="password" id="vaultUnlockPassword" autocomplete="current-password" required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
@@ -128,6 +148,9 @@ if ($itflow_vault_locked) { ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php if ($itflow_vault_passkeys) { ?>
|
||||
<script src="<?= staticFileUrl('/js/passkey.js') ?>"></script>
|
||||
<?php } ?>
|
||||
<?php } ?>
|
||||
<script src="<?= staticFileUrl('/js/credentials.js') ?>"></script>
|
||||
<script src="<?= staticFileUrl('/js/tag_picker.js') ?>"></script>
|
||||
|
||||
@@ -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;
|
||||
});
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user