diff --git a/CHANGELOG.md b/CHANGELOG.md index b6e4249ce..cfc8be6d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ This file documents all notable changes made to ITFlow. ### Upgrading -Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's thirty database changes (3.6.6 to 3.9.6) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, and a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, two settings and a column on tickets for keeping project tickets apart, a table for your other offices with a column each on agents and invites for which one they work from, three settings for the emails and notices your agents get about their tickets, three settings for sending and reading Microsoft 365 mail through Microsoft Graph, five tables, four settings and a role permission for purchase orders, five settings for switching Dispatch, Bookkeeping, Purchasing, Trips and the calendar on and off, and five tables, two columns and two settings for the Knowledge Base and who can read its articles, and change nothing that is there. Nothing else is required. Purchasing starts off - switch it on in Admin > Settings > Modules - and so does the Knowledge Base's public help center, in Admin > Settings > Knowledge Base. This release has twelve security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. +Update from Maintenance > Update — Queue Update hands the job to cron, which updates the files and applies this release's thirty-one database changes (3.6.6 to 3.9.7) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, and a table for the agents helping on a ticket, three columns on quote lines with three settings for what a quote line costs and how it is priced, a column each on quote lines and products with a setting for their pictures, two settings and a column on tickets for keeping project tickets apart, a table for your other offices with a column each on agents and invites for which one they work from, three settings for the emails and notices your agents get about their tickets, three settings for sending and reading Microsoft 365 mail through Microsoft Graph, five tables, four settings and a role permission for purchase orders, five settings for switching Dispatch, Bookkeeping, Purchasing, Trips and the calendar on and off, and seven tables, three columns and two settings for the Knowledge Base, who can read its articles and what its readers think of them, and change nothing that is there. Nothing else is required. Purchasing starts off - switch it on in Admin > Settings > Modules - and so does the Knowledge Base's public help center, in Admin > Settings > Knowledge Base. This release has twelve security fixes - see Security. On Apache, ITFlow's own .htaccess now sends security headers: if you show ITFlow inside a frame on another website, it will now refuse to load there. On nginx, add the same headers to your server block if you want them - see Developer Updates. ### Security @@ -135,6 +135,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Knowledge Base: one place for the how-tos, fixes and policies your team gives again and again, written once for every client - Knowledge Base, in the main menu. Each article has a title, a line saying what it's for, a category, tags and its content, written in the same editor as documents, pictures and all. An article is a draft until it's published. Every edit keeps what it said before, to look at or put back from its Versions. Say how often an article is reviewed - every year, to start with - and it shows Review due once it's that long since it was written, edited or marked reviewed. The list searches titles, summaries, the words in the articles and their tags, filters by category and tag, and has All, Published, Drafts, Review due and Archived views. Ticked articles can be put in a category, published, made drafts, archived, restored or deleted. Articles can be copied, and Copy to Knowledge Base on a client's document makes a draft article from it. Search everywhere finds articles too. Admins set up the categories, with an icon and color each, in Admin > Categories > Knowledge Base, and the tags in Admin > Tags. Reading the Knowledge Base takes Support; writing in it takes Support Edit, and deleting Support Full. Admin > Settings > Modules switches it off. - Knowledge Base articles for your clients: say who can read each article - your agents only (to start with), clients, or anyone. For clients, pick all of them, the ones with some client tags - every client tagged Managed, say - or some clients by name, or a mix. Once an article is published, those clients' contacts find it in their client portal under Help, a new item there once they have something to read: search, categories, a Print button, and Still stuck? Ask us, which opens a ticket about it. An article for anyone is in every client's portal too, and on a public help center - a page of its own with your logo, at /guest/kb.php, for anyone with the link and no sign-in, which you can put on your website. It starts off: switch it on in Admin > Settings > Knowledge Base, which has its link to copy. While it's on, the client portal's sign-in page links to it, and an article for anyone shows its public link to copy. Drafts and archived articles are never shown outside ITFlow. The Knowledge Base list has a Who can read it column and filter, and each article says who can read it and where they find it. - Knowledge Base on tickets: beside Canned response above a ticket's reply, Knowledge Base opens the published articles that look like they answer the ticket - counted on the button - with a search for the rest. Each says how the ticket's client could read it: Link puts a link to it in the reply - the public help center's, or their portal's - and Insert puts what it says in, pictures and all. Write up for the Knowledge Base, in a ticket's ⋮ menu, starts a draft article from the ticket, for agents only until it's read through: with AI set up for documentation, AI writes it as a how-to for any client, leaving out the client, its people and its systems; without, it starts from what the ticket asked. The ticket's history says it was written up. In the client portal, as a contact types a new ticket's subject, the Help articles that might answer it show under it, each opening in a new tab. +- Knowledge Base feedback and upkeep: under each article in the client portal and the public help center, Was this helpful? - and for a No, what were they looking for. A contact has one answer an article; on the help center it's one a visit. Each article counts how many times it was read there, once a visit. The Knowledge Base list has a Readers column - reads, and the share who said it helped - sortable by reads, and a Needs a look view for the articles readers said didn't help that nobody has dealt with yet. On an article, Feedback lists what they said, who said it and when, each with Dealt with. Not found, at the top of the list, shows what readers searched Help and the help center for in the last 90 days and found nothing - where, and how many times - with Write an article, which starts one with those words as its title. The Knowledge Base in the main menu counts the articles due for review or said not to help. Viewing the portal as a contact counts nothing. - Modules: Admin > Settings > Modules has five more switches, to take out of ITFlow what your business doesn't use - Dispatch, which comes with Ticketing; Bookkeeping, Purchasing and Trips, which come with invoicing; and the Calendar. Each part is off while the one it comes with is, and shows faded under it. Switched off, a part leaves the menus, the dashboard, search, the reports and the API, and its pages and windows say it is off. Nothing in it is deleted - switched back on, it is all there. Dispatch, Bookkeeping, Trips and the Calendar start on, as before. - Bookkeeping: switch it off when your books are kept somewhere else. Accounts, Transactions, Transfers, Reconcile and the statement imports go, and nobody picks an account: payments and income go into the default payment account, and expenses come out of the default expense account - both in Admin > Settings > Defaults, or the first account when there's no default. An expense is paid by The business or Paid personally. The dashboard leaves out the account balances, and the Tax Package its Accounts section. - Calendar: switched off, the calendar, its events and the calendar feeds go - a subscribed calendar stops getting them. Tickets are still booked from the ticket and on Dispatch, and booked work still shows on the dashboard. @@ -290,6 +291,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Knowledge Base: database 3.9.5 adds `kb_articles` (title, summary, content and its search text with a FULLTEXT index, `kb_article_category_id`, `kb_article_published_at` - none for a draft - `kb_article_review_months` and `kb_article_reviewed_at`/`_by`), `kb_article_versions`, `kb_article_tags` and `config_module_enable_kb` (on), which `load_global_settings.php` reads from 3.9.5. `functions/kb.php` has `kbOn()` (the switch, and the tables there), `kbCan($level)` on `module_support`, `kbClosedText()`, `kbArticleRow()`, `kbArticleFields()`, `kbArticleSave()` - which keeps the old words as a version and saves pasted images to `uploads/kb//` - `kbReviewState()` and `kbReviewDueSql()`, built like documents' review, `kbArticleFromDocument()` and `kbArticleDelete()`. Pages `agent/kb.php` and `agent/kb_article.php`, windows in `agent/modals/kb/`, handlers in `agent/post/kb.php`. Content is purified where it's shown, with `documentHtmlPurify()`. The `kb` category kind, the `kb_article` tag kind (type 13, with no client - `tagFilterOptionsHtml()`, `tagRecordsEditable()` and the tags API now allow a kind without one), the `Knowledge Base` audit log kind, a global search group with its shortcut, and the Modules switch, with `moduleOffText('kb')`. - Knowledge Base sharing: database 3.9.6 adds `kb_article_visibility` (`agents`, `clients` or `public`) and `kb_article_all_clients` to `kb_articles`, the tables `kb_article_client_tags` and `kb_article_clients` (both cascading), and `config_kb_public_enable` (off), which `load_global_settings.php` and `login.php` read once they are there - `kbOn()` now also wants 3.9.6. `kbClientSql($client_id)` and `kbPublicSql()` are the WHERE for what a client's contacts and the public may read (published, not archived), `kbPublicOn()`, `kbPublicUrl()`, and `kbAudiencesFor()`, `kbAudienceText()`, `kbAudienceBadge()`, `kbAudienceFields()` and `kbAudienceSave()` for who can read an article; `kbArticleFields()` checks the picked clients with `hasClientAccess()`, keeping the ones an article already had. Portal pages `client/kb.php` and `client/kb_article.php` with the Help nav item in `portalNav()`, the standalone public page `guest/kb.php` (its own CSP, `X-Robots-Tag: noindex`, 404 while off), the settings page `admin/settings_kb.php` with its handler, and `js/kb_article_form.js` for the window's audience fields. `tagMerge()` moves `kb_article_client_tags` too, and `tagKinds()` lists `kb_article` only once its table is there, so Admin > Tags works on a database before 3.9.5. - Knowledge Base on tickets (no database change): `kbFind($text, $where, $limit, $search)` - published articles by `MATCH` on `kb_article_content_raw`, dropping suggestions under a fifth of the best score, or a search box's with title and summary `LIKE` first - `kbClientHas()`, `kbClientReadableIds()`, `kbPortalArticleUrl()`, `kbReachFor()` (the link to send a ticket's client, if any), `kbPickerRowsHtml()` and `kbArticleReplyHtml()` (purified, with `uploads/kb` addresses made absolute for email). The picker is `agent/includes/inc_kb_picker.php` with `agent/js/kb_picker.js`, through `kb_picker` and `kb_article_reply` in `agent/ajax.php`. The write-up is `agent/modals/kb/kb_article_from_ticket.php`, with `aiTicketKbArticle()` in `functions/ai_ticket.php` (the Documentation model, secrets removed, AI feature `ticket_kb_article`) through `ai_ticket_kb_article` in `agent/ajax.php`; `add_kb_article` takes `from_ticket_id` for the ticket's history. The portal's suggestions are `kb_suggest` in `client/post.php` - answered when viewing the portal as a contact too - and a block in `js/portal.js`. `portalNav()` uses `kbClientHas()`. +- Knowledge Base feedback and upkeep: database 3.9.7 adds `kb_articles.kb_article_views`, `kb_article_feedback` (helpful, comment, source `portal` or `public`, contact and client, IP for public answers, dealt at/by; cascading with the article) and `kb_search_misses` (query, source and client unique, with a count and first and last searched). `kbFeedbackReady()` gates on 3.9.7 like `ticketWorkTimesReady()`. `kbCountView()` counts once a session and skips bots; `kbFeedbackSave()` replaces a contact's answer, and on the help center allows 20 an hour from one IP; `kbFeedbackComment()`, `kbFeedbackState()` and `kbFeedbackHtml()` for the panel, posted to `kb_feedback`/`kb_feedback_comment` in `client/post.php` or back to `guest/kb.php`, which now starts a session for its form token. `kbFeedbackCounts()`, `kbNeedsLookSql()`, `kbAttentionCount()` (the nav badge, from `get_side_nav_counts.php`), `kbReadersHtml()` and `kbFeedbackFor()` for the agent side; `kbSearchMissSave()` (at most 20 a session), `kbSearchMisses()` grouped by query and `kbSearchMissCount()`, both client-scoped. Handlers `deal_with_kb_feedback`, `deal_with_kb_article_feedback`, `dismiss_kb_search_miss` (by query) and `dismiss_kb_search_misses` in `agent/post/kb.php`; the list is `agent/modals/kb/kb_search_misses.php`, and `kb_article_add.php` takes `?title=`. ## [26.11.8] diff --git a/admin/database_updates/3.9.7.php b/admin/database_updates/3.9.7.php new file mode 100644 index 000000000..5c9d2df98 --- /dev/null +++ b/admin/database_updates/3.9.7.php @@ -0,0 +1,61 @@ + 0; + }; + + if (!$itflow_column('kb_articles', 'kb_article_views')) { + mysqli_query($mysqli, "ALTER TABLE `kb_articles` ADD `kb_article_views` int(11) NOT NULL DEFAULT 0 AFTER `kb_article_reviewed_by`"); + } + + mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `kb_article_feedback` ( + `kb_article_feedback_id` int(11) NOT NULL AUTO_INCREMENT, + `kb_article_feedback_helpful` tinyint(1) NOT NULL, + `kb_article_feedback_comment` varchar(500) DEFAULT NULL, + `kb_article_feedback_source` varchar(10) NOT NULL, + `kb_article_feedback_contact_id` int(11) NOT NULL DEFAULT 0, + `kb_article_feedback_client_id` int(11) NOT NULL DEFAULT 0, + `kb_article_feedback_ip` varchar(45) DEFAULT NULL, + `kb_article_feedback_created_at` datetime NOT NULL DEFAULT current_timestamp(), + `kb_article_feedback_dealt_at` datetime DEFAULT NULL, + `kb_article_feedback_dealt_by` int(11) NOT NULL DEFAULT 0, + `kb_article_feedback_kb_article_id` int(11) NOT NULL, + PRIMARY KEY (`kb_article_feedback_id`), + KEY `kb_article_feedback_kb_article_id` (`kb_article_feedback_kb_article_id`), + KEY `kb_article_feedback_ip` (`kb_article_feedback_ip`, `kb_article_feedback_created_at`), + CONSTRAINT `kb_article_feedback_ibfk_1` FOREIGN KEY (`kb_article_feedback_kb_article_id`) REFERENCES `kb_articles` (`kb_article_id`) ON DELETE CASCADE + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci"); + + mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS `kb_search_misses` ( + `kb_search_miss_id` int(11) NOT NULL AUTO_INCREMENT, + `kb_search_miss_query` varchar(100) NOT NULL, + `kb_search_miss_source` varchar(10) NOT NULL, + `kb_search_miss_client_id` int(11) NOT NULL DEFAULT 0, + `kb_search_miss_searches` int(11) NOT NULL DEFAULT 1, + `kb_search_miss_first_at` datetime NOT NULL DEFAULT current_timestamp(), + `kb_search_miss_last_at` datetime NOT NULL DEFAULT current_timestamp(), + PRIMARY KEY (`kb_search_miss_id`), + UNIQUE KEY `kb_search_miss_query` (`kb_search_miss_query`, `kb_search_miss_source`, `kb_search_miss_client_id`), + KEY `kb_search_miss_last_at` (`kb_search_miss_last_at`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci"); diff --git a/agent/includes/get_side_nav_counts.php b/agent/includes/get_side_nav_counts.php index c0d66a8d6..b2c3124f4 100644 --- a/agent/includes/get_side_nav_counts.php +++ b/agent/includes/get_side_nav_counts.php @@ -43,6 +43,8 @@ $num_purchasing = poNavCounts(); // Products whose stock is at or under the reorder level, or out $num_products_reorder = $config_module_enable_accounting == 1 && lookupUserPermission('module_sales') >= 1 ? productReorderCount() : 0; +// Knowledge Base articles due for review, or said not to help by readers +$num_kb_attention = kbCan(1) ? kbAttentionCount() : 0; // Open Quotes Count $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('quote_id') AS num FROM quotes WHERE (quote_status = 'Sent' OR quote_status = 'Viewed') AND quote_archived_at IS NULL " . clientScopeSql('quote_client_id') . "")); $num_open_quotes = $row['num']; diff --git a/agent/includes/side_nav.php b/agent/includes/side_nav.php index 3e825f765..464ad30dd 100644 --- a/agent/includes/side_nav.php +++ b/agent/includes/side_nav.php @@ -85,7 +85,12 @@ diff --git a/agent/kb.php b/agent/kb.php index e0c643a35..cfce12c8f 100644 --- a/agent/kb.php +++ b/agent/kb.php @@ -4,10 +4,12 @@ * The Knowledge Base - every article, for every client: how-tos, fixes and * policies written once. Each row has its category's icon, its title and what * it is for, its tags, its category, who can read it, when it last changed - * and when it is next reviewed. The pills are the views - every article, the published ones, the - * drafts, the ones due for review and the archived ones - counted over what - * the search, category and tags leave. Ticked rows can be put in a category, - * published, made drafts, archived, restored or deleted. + * and when it is next reviewed, and how its readers found it. The pills are the views - every + * article, the published ones, the drafts, the ones due for review, the ones + * readers said didn't help that nobody has dealt with, and the archived ones - + * counted over what the search, category and tags leave. Ticked rows can be + * put in a category, published, made drafts, archived, restored or deleted. + * Not found, in the header, lists what readers searched for and didn't find. * * The work is in functions/kb.php; the handlers are agent/post/kb.php. */ @@ -61,6 +63,13 @@ $shows = [ 'review' => ['label' => 'Review due', 'icon' => 'fa-calendar-check', 'where' => kbReviewDueSql(), 'title' => 'Published articles due for a read-through - an edit, or Mark reviewed, counts', 'alarm' => 'warning'], 'archived' => ['label' => 'Archived', 'icon' => 'fa-archive', 'where' => 'kb_article_archived_at IS NOT NULL', 'title' => 'Kept, out of the way'], ]; +// Readers' feedback, from database 3.9.7 - before Archived +$feedback_ready = kbFeedbackReady(); +if ($feedback_ready) { + $shows = array_slice($shows, 0, 4, true) + + ['attention' => ['label' => 'Needs a look', 'icon' => 'fa-thumbs-down', 'where' => kbNeedsLookSql(), 'title' => "Readers said these didn't help - and nobody has dealt with that yet", 'alarm' => 'warning']] + + array_slice($shows, 4, null, true); +} $show = isset($shows[$_GET['show'] ?? '']) ? ($_GET['show'] ?? '') : ''; // Only these sort - an unknown column would take the page down @@ -68,14 +77,14 @@ $sortable_columns = [ 'kb_article_title' => "kb_article_title $order", 'category_name' => "kb_article_category_id = 0 $order, category_order $order, category_name $order, kb_article_title ASC", 'kb_article_updated' => "COALESCE(kb_article_updated_at, kb_article_created_at) $order", -]; +] + ($feedback_ready ? ['kb_article_views' => "kb_article_views $order"] : []); if (!isset($sortable_columns[$sort])) { $sort = 'kb_article_updated'; } $sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS kb_article_id, kb_article_title, kb_article_summary, kb_article_content, 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_created_at, - kb_article_updated_at, kb_article_archived_at, + kb_article_updated_at, kb_article_archived_at, " . ($feedback_ready ? 'kb_article_views' : '0 AS kb_article_views') . ", category_name, category_description, category_color, category_icon, category_type, updater.user_name AS updated_by_name FROM kb_articles $joins WHERE $filters AND {$shows[$show]['where']} @@ -90,6 +99,8 @@ while ($row = mysqli_fetch_assoc($sql)) { } $article_tags = tagsForRecords('kb_article', array_keys($articles)); $audiences = kbAudiencesFor(array_keys($articles)); +$feedback_counts = kbFeedbackCounts(array_keys($articles)); +$search_misses = kbSearchMissCount(); // How many of each, for the pills - over what the filters leave $row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT " . implode(', ', array_map(function ($s) { @@ -116,7 +127,13 @@ $csrf = $_SESSION['csrf_token'];

Knowledge Base

-
+
+ + + +
+ + +
+
+

Feedback + +

+ 1) { ?> +
+ +
+ +
+
    + ' . escapeHtml($answer['contact_name']) . '' + . ($answer['client_name'] !== null ? ' · ' . escapeHtml($answer['client_name']) . '' : ''); + } else { + $who = $answer['client_name'] !== null ? escapeHtml($answer['client_name']) : 'A contact at a client'; + } ?> +
  • +
    +
    +
    + · + · dealt with +
    +
    + + Dealt with + +
  • + +
+
+ +
diff --git a/agent/modals/kb/kb_article_add.php b/agent/modals/kb/kb_article_add.php index dc5c8257a..0cf34ce72 100644 --- a/agent/modals/kb/kb_article_add.php +++ b/agent/modals/kb/kb_article_add.php @@ -2,7 +2,8 @@ /* * New Article in the Knowledge Base - the fields are kb_article_form.php. - * ?category starts it in a category. Starts reviewed every year, published. + * ?category starts it in a category, and ?title with a title - Write an + * article on the Not found list. Starts reviewed every year, published. */ require_once '../../../includes/modal_header.php'; @@ -14,6 +15,7 @@ if ($kb_closed !== '') { $kb_form_mode = 'add'; $kb_form = [ + 'kb_article_title' => mb_substr(trim((string) ($_GET['title'] ?? '')), 0, 200), 'kb_article_category_id' => intval($_GET['category'] ?? 0), 'kb_article_review_months' => 12, 'kb_article_published_at' => date('Y-m-d H:i:s'), diff --git a/agent/modals/kb/kb_search_misses.php b/agent/modals/kb/kb_search_misses.php new file mode 100644 index 000000000..d48827985 --- /dev/null +++ b/agent/modals/kb/kb_search_misses.php @@ -0,0 +1,92 @@ + $kb_closed])); +} + +$misses = kbSearchMisses(); +$can_edit = kbCan(2); +$csrf = $_SESSION['csrf_token']; + +ob_start(); + +?> + + + + Update.', 'error'); + redirect(); + } + if (isset($_GET['deal_with_kb_feedback'])) { + $feedback_id = intval($_GET['deal_with_kb_feedback']); + $kb_article_id = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT kb_article_feedback_kb_article_id FROM kb_article_feedback WHERE kb_article_feedback_id = $feedback_id"))[0] ?? 0); + $where = "kb_article_feedback_id = $feedback_id"; + } else { + $kb_article_id = intval($_GET['deal_with_kb_article_feedback']); + $where = "kb_article_feedback_kb_article_id = $kb_article_id"; + } + $row = kbArticleForHandler($kb_article_id, false); + + mysqli_query($mysqli, "UPDATE kb_article_feedback SET kb_article_feedback_dealt_at = NOW(), kb_article_feedback_dealt_by = $session_user_id + WHERE $where AND kb_article_feedback_helpful = 0 AND kb_article_feedback_dealt_at IS NULL"); + $dealt = mysqli_affected_rows($mysqli); + + if ($dealt > 0) { + logAudit("Knowledge Base", "Edit", "$session_name dealt with $dealt reader" . ($dealt === 1 ? "'s" : "s'") . " feedback on article " . escapeSql($row['kb_article_title']), 0, $kb_article_id); + } + flashAlert($dealt === 1 ? 'Feedback dealt with' : ($dealt ? "$dealt answers dealt with" : 'Nothing left to deal with')); + + redirect("kb_article.php?kb_article_id=$kb_article_id#kbArticleFeedback"); +} + +/* + * Searches that found nothing, taken off the Not found list - one search, + * wherever it was made (dismiss_kb_search_miss, its words) or all the agent + * can see (dismiss_kb_search_misses). Searched again, one comes back. + */ +if (isset($_GET['dismiss_kb_search_miss']) || isset($_GET['dismiss_kb_search_misses'])) { + + if (kbFeedbackReady()) { + $one = isset($_GET['dismiss_kb_search_miss']) ? mb_substr((string) $_GET['dismiss_kb_search_miss'], 0, 100) : null; + mysqli_query($mysqli, "DELETE FROM kb_search_misses WHERE " . ($one !== null ? "kb_search_miss_query = '" . escapeSql($one) . "'" : '1') . clientScopeSql('kb_search_miss_client_id')); + if (mysqli_affected_rows($mysqli) > 0) { + logAudit("Knowledge Base", "Delete", "$session_name took " . ($one !== null ? 'the search "' . escapeSql($one) . '"' : 'every search') . " off the Not found list", 0, 0); + } + } + flashAlert(isset($_GET['dismiss_kb_search_miss']) ? 'Search taken off the list' : 'Not found list cleared'); + + redirect('kb.php'); +} diff --git a/client/kb.php b/client/kb.php index 29ee3ee44..880a316c4 100644 --- a/client/kb.php +++ b/client/kb.php @@ -40,6 +40,11 @@ if ($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'))"; } $total = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM kb_articles WHERE $where"))[0]); + +// A search of all of Help that found nothing goes on the Knowledge Base's Not found list +if ($q !== '' && !$total && $category === null && !portalViewingAs()) { + kbSearchMissSave($q, 'portal', $session_client_id); +} $pages = max(1, (int) ceil($total / $per_page)); $page = min(max(1, intval($_GET['page'] ?? 1)), $pages); $offset = ($page - 1) * $per_page; diff --git a/client/kb_article.php b/client/kb_article.php index db2de07eb..be232cce0 100644 --- a/client/kb_article.php +++ b/client/kb_article.php @@ -7,6 +7,10 @@ * SCOPING: any contact who can sign in; the article must be one kbClientSql() * lets $session_client_id read - published, not archived, and shared with * them. + * + * Each visit counts as a read (kbCountView()), but not viewing the portal as a + * contact. Under it, "Was this helpful?" (kbFeedbackHtml(), kb_feedback in + * post.php). */ header("Content-Security-Policy: default-src 'self'"); @@ -38,6 +42,10 @@ if (!$article) { ?> exit; } +if (!portalViewingAs()) { + kbCountView($kb_article_id); +} + $content = documentHtmlPurify($article['kb_article_content']); $updated = $article['kb_article_updated_at'] ?: $article['kb_article_created_at']; $category_id = intval($article['kb_article_category_id']); @@ -80,6 +88,10 @@ if ($category_id) { + + + +

More in

diff --git a/client/post.php b/client/post.php index cd74d83dc..34f11b3b8 100644 --- a/client/post.php +++ b/client/post.php @@ -43,6 +43,28 @@ if (isset($_GET['kb_suggest'])) { exit; } +/* + * "Was this helpful?" under a Help article (kbFeedbackHtml()) - the answer + * (kb_feedback, with helpful), then for a no what was missing + * (kb_feedback_comment). Only for an article shared with their company. Back + * to the article. + */ +if (isset($_POST['kb_feedback']) || isset($_POST['kb_feedback_comment'])) { + + validateCSRFToken(); + + $kb_article_id = intval($_POST['kb_feedback'] ?? $_POST['kb_feedback_comment']); + if (!kbFeedbackReady() || !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM kb_articles WHERE kb_article_id = $kb_article_id AND " . kbClientSql($session_client_id)))) { + redirect('kb.php'); + } + if (isset($_POST['kb_feedback'])) { + kbFeedbackSave($kb_article_id, intval($_POST['helpful'] ?? 0) === 1, 'portal', $session_contact_id, $session_client_id); + } else { + kbFeedbackComment($kb_article_id, $_POST['comment'] ?? ''); + } + redirect("kb_article.php?id=$kb_article_id#kb-feedback"); +} + if (isset($_POST['add_ticket'])) { validateCSRFToken(); diff --git a/db.sql b/db.sql index ffbc59d01..6bec30b8c 100644 --- a/db.sql +++ b/db.sql @@ -1959,6 +1959,32 @@ CREATE TABLE `kb_article_clients` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `kb_article_feedback` +-- + +DROP TABLE IF EXISTS `kb_article_feedback`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `kb_article_feedback` ( + `kb_article_feedback_id` int(11) NOT NULL AUTO_INCREMENT, + `kb_article_feedback_helpful` tinyint(1) NOT NULL, + `kb_article_feedback_comment` varchar(500) DEFAULT NULL, + `kb_article_feedback_source` varchar(10) NOT NULL, + `kb_article_feedback_contact_id` int(11) NOT NULL DEFAULT 0, + `kb_article_feedback_client_id` int(11) NOT NULL DEFAULT 0, + `kb_article_feedback_ip` varchar(45) DEFAULT NULL, + `kb_article_feedback_created_at` datetime NOT NULL DEFAULT current_timestamp(), + `kb_article_feedback_dealt_at` datetime DEFAULT NULL, + `kb_article_feedback_dealt_by` int(11) NOT NULL DEFAULT 0, + `kb_article_feedback_kb_article_id` int(11) NOT NULL, + PRIMARY KEY (`kb_article_feedback_id`), + KEY `kb_article_feedback_kb_article_id` (`kb_article_feedback_kb_article_id`), + KEY `kb_article_feedback_ip` (`kb_article_feedback_ip`,`kb_article_feedback_created_at`), + CONSTRAINT `kb_article_feedback_ibfk_1` FOREIGN KEY (`kb_article_feedback_kb_article_id`) REFERENCES `kb_articles` (`kb_article_id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `kb_article_tags` -- @@ -2016,6 +2042,7 @@ CREATE TABLE `kb_articles` ( `kb_article_review_months` int(11) NOT NULL DEFAULT 0, `kb_article_reviewed_at` datetime DEFAULT NULL, `kb_article_reviewed_by` int(11) NOT NULL DEFAULT 0, + `kb_article_views` int(11) NOT NULL DEFAULT 0, `kb_article_created_at` datetime NOT NULL DEFAULT current_timestamp(), `kb_article_created_by` int(11) NOT NULL DEFAULT 0, `kb_article_updated_at` datetime DEFAULT NULL, @@ -2027,6 +2054,27 @@ CREATE TABLE `kb_articles` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `kb_search_misses` +-- + +DROP TABLE IF EXISTS `kb_search_misses`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `kb_search_misses` ( + `kb_search_miss_id` int(11) NOT NULL AUTO_INCREMENT, + `kb_search_miss_query` varchar(100) NOT NULL, + `kb_search_miss_source` varchar(10) NOT NULL, + `kb_search_miss_client_id` int(11) NOT NULL DEFAULT 0, + `kb_search_miss_searches` int(11) NOT NULL DEFAULT 1, + `kb_search_miss_first_at` datetime NOT NULL DEFAULT current_timestamp(), + `kb_search_miss_last_at` datetime NOT NULL DEFAULT current_timestamp(), + PRIMARY KEY (`kb_search_miss_id`), + UNIQUE KEY `kb_search_miss_query` (`kb_search_miss_query`,`kb_search_miss_source`,`kb_search_miss_client_id`), + KEY `kb_search_miss_last_at` (`kb_search_miss_last_at`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `location_documents` -- diff --git a/functions/kb.php b/functions/kb.php index 1de2480fd..6ee6a8ed1 100644 --- a/functions/kb.php +++ b/functions/kb.php @@ -29,11 +29,10 @@ * article (agent/modals/kb/kb_article_from_ticket.php); and a client typing a * new ticket's subject in the portal is shown the articles that might help. * - * On a ticket (kbFind(), kbReachFor()): the Knowledge Base picker above the - * reply suggests articles for it, to link to or put in the reply - * (agent/includes/inc_kb_picker.php); a ticket can be written up as a draft - * article (agent/modals/kb/kb_article_from_ticket.php); and a client typing a - * new ticket's subject in the portal is shown the articles that might help. + * Keeping it useful (database 3.9.7, kbFeedbackReady()): reads outside ITFlow + * are counted, readers say whether an article helped and what was missing, + * and searches that found nothing are listed - for the Needs a look view, an + * article's Feedback and the Not found list. * * Reading takes Support (view), writing Support edit, deleting Support full. */ @@ -266,7 +265,7 @@ function kbArticleRow($kb_article_id) { $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, kb_article_published_at, kb_article_visibility, kb_article_all_clients, kb_article_review_months, kb_article_reviewed_at, kb_article_reviewed_by, - kb_article_created_at, kb_article_created_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, category_id, category_name, category_description, category_color, category_icon, category_type, category_archived_at, creator.user_name AS created_by_name, updater.user_name AS updated_by_name, reviewer.user_name AS reviewed_by_name @@ -525,6 +524,9 @@ function kbArticleDelete($kb_article_id) { mysqli_query($mysqli, "DELETE FROM kb_article_tags WHERE kb_article_id = $kb_article_id"); mysqli_query($mysqli, "DELETE FROM kb_article_client_tags WHERE kb_article_id = $kb_article_id"); mysqli_query($mysqli, "DELETE FROM kb_article_clients WHERE kb_article_id = $kb_article_id"); + if (kbFeedbackReady()) { + mysqli_query($mysqli, "DELETE FROM kb_article_feedback WHERE kb_article_feedback_kb_article_id = $kb_article_id"); + } removeDirectory(kbArticleDir($kb_article_id)); return $row['kb_article_title']; } @@ -560,3 +562,271 @@ function kbArticleFromDocument($document_id) { WHERE kb_article_id = $kb_article_id"); return $kb_article_id; } + +/* + * Keeping it useful (database 3.9.7): how many times each article was read + * outside ITFlow, "Was this helpful?" from those readers, and what they + * searched for and didn't find. Readers are contacts in the client portal + * and anyone on the public help center; agents reading here aren't counted. + */ + +const KB_SEARCH_MISS_DAYS = 90; + +/** Has the database the read counts, feedback and searches that found nothing (3.9.7)? */ +function kbFeedbackReady() { + 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, '3.9.7', '>='); + } + return kbOn() && $ready; +} + +/** Count a read of an article outside ITFlow - once a visit, and not for a search engine, a link preview or a script. */ +function kbCountView($kb_article_id) { + global $mysqli; + $kb_article_id = intval($kb_article_id); + $agent = strtolower((string) ($_SERVER['HTTP_USER_AGENT'] ?? '')); + if (!kbFeedbackReady() || !empty($_SESSION['kb_viewed'][$kb_article_id]) || $agent === '' || preg_match('/bot|crawl|spider|slurp|preview|monitor|curl|wget|python|java\//', $agent)) { + return; + } + $_SESSION['kb_viewed'][$kb_article_id] = 1; + mysqli_query($mysqli, "UPDATE kb_articles SET kb_article_views = kb_article_views + 1 WHERE kb_article_id = $kb_article_id"); +} + +/* + * "Was this helpful?" from a reader - yes or no, from a contact in the portal + * ($contact_id at $client_id) or someone on the public help center. A + * contact has one answer an article, and a new one replaces it; on the help + * center it is one a visit, and at most 20 an hour from one IP address. The + * answer is kept in the visit's session, so what was missing can be added to + * it. Whether it was kept. + */ +function kbFeedbackSave($kb_article_id, $helpful, $source, $contact_id = 0, $client_id = 0) { + global $mysqli; + $kb_article_id = intval($kb_article_id); + $contact_id = intval($contact_id); + $client_id = intval($client_id); + $ip = ''; + if ($source === 'portal' && $contact_id) { + mysqli_query($mysqli, "DELETE FROM kb_article_feedback WHERE kb_article_feedback_kb_article_id = $kb_article_id + AND kb_article_feedback_source = 'portal' AND kb_article_feedback_contact_id = $contact_id"); + } else { + $source = 'public'; + $contact_id = $client_id = 0; + $ip = escapeSql(mb_substr(getIP(), 0, 45)); + $mine = intval($_SESSION['kb_feedback'][$kb_article_id] ?? 0); + if ($mine) { + // Changing their mind replaces the answer they gave + mysqli_query($mysqli, "DELETE FROM kb_article_feedback WHERE kb_article_feedback_id = $mine AND kb_article_feedback_kb_article_id = $kb_article_id AND kb_article_feedback_source = 'public'"); + } elseif (intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM kb_article_feedback WHERE kb_article_feedback_ip = '$ip' + AND kb_article_feedback_created_at > NOW() - INTERVAL 1 HOUR"))[0]) >= 20) { + return false; + } + } + mysqli_query($mysqli, "INSERT INTO kb_article_feedback SET kb_article_feedback_kb_article_id = $kb_article_id, kb_article_feedback_helpful = " . ($helpful ? 1 : 0) . ", + kb_article_feedback_source = '$source', kb_article_feedback_contact_id = $contact_id, kb_article_feedback_client_id = $client_id, + kb_article_feedback_ip = " . ($ip !== '' ? "'$ip'" : 'NULL')); + $_SESSION['kb_feedback'][$kb_article_id] = intval(mysqli_insert_id($mysqli)); + return true; +} + +/** What was missing, added to the "No" this visit gave an article. Whether it was kept. */ +function kbFeedbackComment($kb_article_id, $comment) { + global $mysqli; + $kb_article_id = intval($kb_article_id); + $feedback_id = intval($_SESSION['kb_feedback'][$kb_article_id] ?? 0); + $comment = trim(mb_substr(preg_replace('/\s+/u', ' ', strip_tags((string) $comment)), 0, 500)); + if (!$feedback_id || $comment === '') { + return false; + } + mysqli_query($mysqli, "UPDATE kb_article_feedback SET kb_article_feedback_comment = '" . escapeSql($comment) . "' + WHERE kb_article_feedback_id = $feedback_id AND kb_article_feedback_kb_article_id = $kb_article_id AND kb_article_feedback_helpful = 0"); + return mysqli_affected_rows($mysqli) > 0; +} + +/* + * Where a reader is with "Was this helpful?" on an article - '' (not + * answered), 'yes', 'no' (to say what was missing) or 'done'. A contact's + * answer from an earlier visit counts. + */ +function kbFeedbackState($kb_article_id, $contact_id = 0) { + global $mysqli; + $kb_article_id = intval($kb_article_id); + $feedback_id = intval($_SESSION['kb_feedback'][$kb_article_id] ?? 0); + $where = $feedback_id ? "kb_article_feedback_id = $feedback_id" + : (intval($contact_id) ? "kb_article_feedback_source = 'portal' AND kb_article_feedback_contact_id = " . intval($contact_id) : '0'); + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT kb_article_feedback_id, kb_article_feedback_helpful, kb_article_feedback_comment FROM kb_article_feedback + WHERE kb_article_feedback_kb_article_id = $kb_article_id AND $where ORDER BY kb_article_feedback_id DESC LIMIT 1")); + if (!$row) { + return ''; + } + $_SESSION['kb_feedback'][$kb_article_id] = intval($row['kb_article_feedback_id']); + return intval($row['kb_article_feedback_helpful']) ? 'yes' : ($row['kb_article_feedback_comment'] !== null ? 'done' : 'no'); +} + +/* + * "Was this helpful?" under an article in the portal or on the public help + * center, for where the reader is with it (kbFeedbackState()). Its forms + * post to $action with kb_feedback (the answer) or kb_feedback_comment (what + * was missing). $ask_url, when there is one, offers a ticket instead. HTML. + */ +function kbFeedbackHtml($kb_article_id, $state, $action, $csrf_token, $ask_url = '') { + $kb_article_id = intval($kb_article_id); + $hidden = ''; + $html = '
'; + if ($state === 'yes') { + $html .= 'Thanks - glad it helped.'; + } elseif ($state === 'done') { + $html .= 'Thanks - we\'ll use that to make it better.'; + } elseif ($state === 'no') { + $html .= '
' . $hidden + . '' + . '' + . '
' + . ($ask_url !== '' ? 'Or ask us in a ticket' : '') . '
'; + } else { + $html .= '
' . $hidden + . '' + . 'Was this helpful?' + . '' + . '
'; + } + return $html . '
'; +} + +/** The readers' answers on each article - [id => ['yes', 'no', 'open' => the noes nobody has dealt with]]. */ +function kbFeedbackCounts(array $kb_article_ids) { + global $mysqli; + $ids = array_values(array_filter(array_map('intval', $kb_article_ids))); + $out = array_fill_keys($ids, ['yes' => 0, 'no' => 0, 'open' => 0]); + if (!$ids || !kbFeedbackReady()) { + return $out; + } + $sql = mysqli_query($mysqli, "SELECT kb_article_feedback_kb_article_id AS id, SUM(kb_article_feedback_helpful = 1) AS yes, SUM(kb_article_feedback_helpful = 0) AS no, + SUM(kb_article_feedback_helpful = 0 AND kb_article_feedback_dealt_at IS NULL) AS open + FROM kb_article_feedback WHERE kb_article_feedback_kb_article_id IN (" . implode(',', $ids) . ") GROUP BY kb_article_feedback_kb_article_id"); + while ($row = mysqli_fetch_assoc($sql)) { + $out[intval($row['id'])] = ['yes' => intval($row['yes']), 'no' => intval($row['no']), 'open' => intval($row['open'])]; + } + return $out; +} + +/** The articles a reader said didn't help, that nobody has dealt with yet - a WHERE on kb_articles. */ +function kbNeedsLookSql() { + return "(kb_articles.kb_article_archived_at IS NULL AND EXISTS (SELECT 1 FROM kb_article_feedback f WHERE f.kb_article_feedback_kb_article_id = kb_articles.kb_article_id + AND f.kb_article_feedback_helpful = 0 AND f.kb_article_feedback_dealt_at IS NULL))"; +} + +/** How many articles want an agent - due for review, or said not to help - for the main menu. */ +function kbAttentionCount() { + global $mysqli; + if (!kbOn()) { + return 0; + } + return intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM kb_articles WHERE " . kbReviewDueSql() . (kbFeedbackReady() ? " OR " . kbNeedsLookSql() : '')))[0]); +} + +/** How an article does with its readers, for the list - its reads, the share who said it helped, and the noes to look at. HTML. */ +function kbReadersHtml(array $row, array $counts) { + $views = intval($row['kb_article_views'] ?? 0); + $answers = $counts['yes'] + $counts['no']; + $html = '' . number_format($views) . ' read' . ($views === 1 ? '' : 's') . ''; + if ($answers) { + $html .= '
' + . round(100 * $counts['yes'] / $answers) . '% of ' . $answers . '
'; + } + if ($counts['open']) { + $html .= '
' . $counts['open'] . ' to look at
'; + } + return $html; +} + +/* + * What readers said didn't help on an article, for its page - the ones nobody + * has dealt with first, then the newest - with the contact's and client's + * names. A client the agent can't reach isn't named. + */ +function kbFeedbackFor($kb_article_id, $limit = 20) { + global $mysqli; + if (!kbFeedbackReady()) { + return []; + } + $rows = []; + $sql = mysqli_query($mysqli, "SELECT kb_article_feedback_id, kb_article_feedback_helpful, kb_article_feedback_comment, kb_article_feedback_source, kb_article_feedback_contact_id, + kb_article_feedback_client_id, kb_article_feedback_created_at, kb_article_feedback_dealt_at, contact_name, client_name, user_name AS dealt_by_name + FROM kb_article_feedback + LEFT JOIN contacts ON contact_id = kb_article_feedback_contact_id AND kb_article_feedback_contact_id > 0 + LEFT JOIN clients ON client_id = kb_article_feedback_client_id AND kb_article_feedback_client_id > 0 + LEFT JOIN users ON user_id = kb_article_feedback_dealt_by AND kb_article_feedback_dealt_by > 0 + WHERE kb_article_feedback_kb_article_id = " . intval($kb_article_id) . " AND kb_article_feedback_helpful = 0 + ORDER BY kb_article_feedback_dealt_at IS NULL DESC, kb_article_feedback_id DESC + LIMIT " . intval($limit)); + while ($row = mysqli_fetch_assoc($sql)) { + if (intval($row['kb_article_feedback_client_id']) && !hasClientAccess(intval($row['kb_article_feedback_client_id']))) { + $row['contact_name'] = $row['client_name'] = null; + } + $rows[] = $row; + } + return $rows; +} + +/* + * A search of Help or the public help center that found nothing - counted by + * its words, where and for which client. A search repeated on a visit counts + * once, and a visit counts at most 20, so a script can't fill the list. + */ +function kbSearchMissSave($q, $source, $client_id = 0) { + global $mysqli; + $q = mb_strtolower(trim(preg_replace('/\s+/u', ' ', (string) $q))); + $source = $source === 'portal' ? 'portal' : 'public'; + $key = md5("$source|$q"); + if (!kbFeedbackReady() || mb_strlen($q) < 2 || mb_strlen($q) > 100 || isset($_SESSION['kb_misses'][$key]) || count($_SESSION['kb_misses'] ?? []) >= 20) { + return; + } + $_SESSION['kb_misses'][$key] = 1; + mysqli_query($mysqli, "INSERT INTO kb_search_misses SET kb_search_miss_query = '" . escapeSql($q) . "', kb_search_miss_source = '$source', kb_search_miss_client_id = " . intval($client_id) . " + ON DUPLICATE KEY UPDATE kb_search_miss_searches = kb_search_miss_searches + 1, kb_search_miss_last_at = NOW()"); +} + +/* + * The searches that found nothing in the last 90 days, of the clients the + * agent can reach - by their words, the most searched first: [query => + * ['searches', 'last_at', 'places' => [['source', 'client_id', 'client_name']]]]. + */ +function kbSearchMisses($limit = 100) { + global $mysqli; + if (!kbFeedbackReady()) { + return []; + } + $out = []; + $sql = mysqli_query($mysqli, "SELECT kb_search_miss_query, kb_search_miss_source, kb_search_miss_client_id, kb_search_miss_searches, kb_search_miss_last_at, client_name + FROM kb_search_misses + LEFT JOIN clients ON client_id = kb_search_miss_client_id AND kb_search_miss_client_id > 0 + WHERE kb_search_miss_last_at > NOW() - INTERVAL " . KB_SEARCH_MISS_DAYS . " DAY" . clientScopeSql('kb_search_miss_client_id') . " + ORDER BY kb_search_miss_source = 'public' DESC, client_name ASC"); + while ($row = mysqli_fetch_assoc($sql)) { + $query = (string) $row['kb_search_miss_query']; + $out[$query] = $out[$query] ?? ['searches' => 0, 'last_at' => '', 'places' => []]; + $out[$query]['searches'] += intval($row['kb_search_miss_searches']); + $out[$query]['last_at'] = max($out[$query]['last_at'], (string) $row['kb_search_miss_last_at']); + $out[$query]['places'][] = ['source' => $row['kb_search_miss_source'], 'client_id' => intval($row['kb_search_miss_client_id']), 'client_name' => $row['client_name']]; + } + uasort($out, function ($a, $b) { + return [$b['searches'], $b['last_at']] <=> [$a['searches'], $a['last_at']]; + }); + return array_slice($out, 0, intval($limit), true); +} + +/** How many different searches found nothing in the last 90 days, of the clients the agent can reach. */ +function kbSearchMissCount() { + global $mysqli; + return kbFeedbackReady() ? intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(DISTINCT kb_search_miss_query) FROM kb_search_misses + WHERE kb_search_miss_last_at > NOW() - INTERVAL " . KB_SEARCH_MISS_DAYS . " DAY" . clientScopeSql('kb_search_miss_client_id')))[0]) : 0; +} diff --git a/guest/kb.php b/guest/kb.php index 07c3cae9c..55cd3e67c 100644 --- a/guest/kb.php +++ b/guest/kb.php @@ -9,11 +9,17 @@ * Laid out like the client portal, with your logo, so it looks like yours. * An article's own tables and colours are inline styles, already through * HTMLPurifier (documentHtmlPurify()), so styles are let in; scripts are not. + * + * Each visit counts as a read (kbCountView()), "Was this helpful?" goes under + * an article (kbFeedbackHtml(), posted back here), and a search that finds + * nothing goes on the Knowledge Base's Not found list. A session keeps a + * visit's reads, answer and form token. */ require_once $_SERVER['DOCUMENT_ROOT'] . '/config.php'; require_once $_SERVER['DOCUMENT_ROOT'] . '/functions.php'; require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/load_global_settings.php'; +require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/session_init.php'; require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/inc_set_timezone.php'; header("Content-Security-Policy: default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-ancestors 'none'"); @@ -32,6 +38,25 @@ $per_page = 25; $q = trim((string) ($_GET['q'] ?? '')); $q_sql = escapeSql($q); +if (empty($_SESSION['csrf_token'])) { + $_SESSION['csrf_token'] = randomString(32); +} + +// "Was this helpful?" under an article - the answer, then for a no what was missing. Back to the article. +if ($open && $_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['kb_feedback']) || isset($_POST['kb_feedback_comment']))) { + $kb_article_id = intval($_POST['kb_feedback'] ?? $_POST['kb_feedback_comment']); + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT kb_article_id, kb_article_title FROM kb_articles WHERE kb_article_id = $kb_article_id AND $visible LIMIT 1")); + if ($row && kbFeedbackReady() && hash_equals($_SESSION['csrf_token'], (string) ($_POST['csrf_token'] ?? ''))) { + if (isset($_POST['kb_feedback'])) { + kbFeedbackSave($kb_article_id, intval($_POST['helpful'] ?? 0) === 1, 'public'); + } else { + kbFeedbackComment($kb_article_id, $_POST['comment'] ?? ''); + } + } + header('Location: ' . ($row ? kbPublicArticleUrl($row) . '#kb-feedback' : 'kb.php')); + exit; +} + $article = null; $categories = []; $category = null; @@ -49,7 +74,10 @@ if ($open && isset($_GET['article'])) { WHERE kb_article_id = $kb_article_id AND $visible LIMIT 1")); if (!$article) { http_response_code(404); - } elseif (intval($article['kb_article_category_id'])) { + } else { + kbCountView($kb_article_id); + } + if ($article && intval($article['kb_article_category_id'])) { $sql = mysqli_query($mysqli, "SELECT kb_article_id, kb_article_title FROM kb_articles WHERE $visible AND kb_article_category_id = " . intval($article['kb_article_category_id']) . " AND kb_article_id != $kb_article_id ORDER BY COALESCE(kb_article_updated_at, kb_article_created_at) DESC LIMIT 5"); @@ -76,6 +104,9 @@ if ($open && isset($_GET['article'])) { $where .= " AND (kb_article_title LIKE '%$q_sql%' OR kb_article_summary LIKE '%$q_sql%' OR MATCH(kb_article_content_raw) AGAINST ('$q_sql'))"; } $total = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COUNT(*) FROM kb_articles WHERE $where"))[0]); + if ($q !== '' && !$total && $category === null) { + kbSearchMissSave($q, 'public'); + } $pages = max(1, (int) ceil($total / $per_page)); $page = min(max(1, intval($_GET['page'] ?? 1)), $pages); $offset = ($page - 1) * $per_page; @@ -178,6 +209,10 @@ $title = $article ? $article['kb_article_title'] . ' | ' : ''; + + + +

More in