From 475f27fc7fbe37de312c331deefdff71d8a93ca4 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 17 Nov 2026 21:25:57 -0500 Subject: [PATCH] Quotes: a line can have a picture beside its name on the quote, guest link, portal and PDF, uploaded or pulled from a link to a picture or a product page's main picture, fetched only from public addresses and kept as ITFlow's own resized copy in uploads/quote_images; products keep a picture that a quote line added from them copies, Copy Quote copies them, and deleting a line, quote, client or product removes the files; Admin Settings Quotes can switch pictures off; database 3.8.8 adds quote_items.item_image, products.product_image and config_quote_show_images; 26.11.9 changelog entries --- .gitignore | 2 + CHANGELOG.md | 4 +- admin/database_updates/3.8.8.php | 32 ++ admin/post/demo_data_model.php | 1 + admin/post/settings_quote.php | 14 +- admin/settings_quote.php | 7 + agent/modals/billing/billing_item.php | 5 +- agent/modals/product/product_add.php | 2 +- agent/modals/product/product_edit.php | 2 +- agent/modals/product/product_form.php | 3 + agent/post/billing.php | 7 + agent/post/client.php | 3 +- agent/post/product.php | 14 + agent/post/quote.php | 7 +- api/v1/clients/delete.php | 1 + api/v1/quotes/delete.php | 1 + css/itflow_custom.css | 23 ++ db.sql | 3 + functions.php | 1 + functions/billing.php | 13 +- functions/billing_pdf.php | 4 +- functions/products.php | 5 +- functions/quote_images.php | 439 ++++++++++++++++++++++++++ functions/settings.php | 1 + includes/billing_paper.php | 9 +- js/app.js | 30 ++ uploads/quote_images/index.php | 1 + 27 files changed, 619 insertions(+), 15 deletions(-) create mode 100644 admin/database_updates/3.8.8.php create mode 100644 functions/quote_images.php create mode 100644 uploads/quote_images/index.php diff --git a/.gitignore b/.gitignore index 30ced6b46..5fd8b281e 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,8 @@ uploads/ticket_templates/* uploads/canned_responses/* !uploads/canned_responses/index.php !uploads/canned_responses/.htaccess +uploads/quote_images/* +!uploads/quote_images/index.php .idea/* plugins/htmlpurifier/standalone/HTMLPurifier/DefinitionCache/Serializer/HTML/* !plugins/htmlpurifier/standalone/HTMLPurifier/DefinitionCache/Serializer/HTML/.gitkeep diff --git a/CHANGELOG.md b/CHANGELOG.md index 3786d0071..aa2f3cc32 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 twenty-one database changes (3.6.6 to 3.8.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, and three columns on quote lines with three settings for what a quote line costs and how it is priced, and change nothing that is there. Nothing else is required. This release has eleven 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 twenty-two database changes (3.6.6 to 3.8.8) in the same pass. They add four tables for RMM providers and their alerts, a setting for device actions and one for API keys in the address, a column marking the emails the mail queue clears once sent, a column and a table for agent banners, two columns for ticket statuses with a setting for the "ticket assigned" message, a column on tickets with a setting for the "no response" message, a table for who a ticket's email replies go to, the settings for Quick tickets, columns on recurring tickets and recurring invoices for booking and making them ahead, two columns on ticket replies for when their time was worked, the settings for cron alerts, a table and a setting for labor costs, a column on users for API / service accounts, columns on tickets and recurring tickets for how long booked work takes, a column each on recurring tickets and calendar events for repeating on a weekday, three columns on agents' settings for their calendar color, what their calendar shows and their own time zone, 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, and a column each on quote lines and products with a setting for their pictures, and change nothing that is there. Nothing else is required. This release has eleven 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 @@ -110,6 +110,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Time zones: an agent who works away from the company can pick My time zone under Account > Preferences. The calendar, the ticket's booking, the Schedule window, New Event and Edit, and the event's quick look are then on their own clock, with a note saying so, and their booking emails give their time with the company's beside it. Bookings are still kept in the company's time, so the client's emails and calendar files, and everyone else's view, don't change. From Mountaineer IT's build of ITFlow. - Dispatch: a new page under Support puts each agent's booked work beside the tickets still to give out. The queue on the left has three tabs - No agent, Not booked (with an agent, nothing booked) and Left behind - most urgent first, with a search, a client and a priority filter. Day shows a column for each agent through the day; Week a row for each agent with a column for each day. Drag a ticket from the queue onto an agent and a time, or drag a booking to another agent or time, and the Schedule window opens with the agent, the time, how long and onsite or remote filled in - Schedule it gives the ticket to that agent and books it, emailing them the calendar file, the agent who had it the cancellation, and the contact and watchers unless you switch that off. Drag a booking back onto the queue to take it off the schedule. One-off events move the same way, to another time or agent. Workload shows each agent's open tickets (leading and helping), SLAs breached or close to it, tickets past due, not booked or gone quiet, and the hours booked today and this week against the working hours in Admin > SLA - flagged Falling behind, Watch, Overloaded or Has room against the team. Click an agent for their tickets, or drop a ticket from the queue on one to give it to them. Under it, This week shows tickets in and closed each day, against last week and the last four, the week's SLA results and each agent's share. Which agents show, the view and weekends are kept to your account, and an agent on their own time zone sees it on their clock. Seeing Dispatch takes Support in your role; booking from it takes Support at Modify. From Mountaineer IT's build of ITFlow. - Quotes: a quote line can carry what it costs you, and its price can come from that cost. In a line's Edit window, Your cost has Cost each, Price by - Markup (a % added to the cost), Margin (a % of the price) or Set price - and the %, with buttons for the ones you use most: the Price is worked out as you type, and says what the line makes each. Typing the Price yourself makes it a set price. A line added from a product takes the product's cost and keeps its price. On the quote, while it can be changed, each line with a cost shows it under its name with its markup or margin, and the quote's Margin counts each line's own cost. Only agents see any of it - never the PDF, the guest link, the client portal or the invoice made from the quote. Admin > Settings > Quotes has what a line is priced by to start with, its % and the quick picks. From Mountaineer IT's build of ITFlow. +- Quotes: a quote line can have a picture beside its name - on the quote, the guest link, the client portal and the PDF. In the line's Edit window, upload one or paste a link: a picture, or the product's web page, whose main picture is taken. A product keeps a picture too, in its Edit window, and a quote line added from it takes a copy; copying a quote copies them. ITFlow keeps its own copy of each, made smaller, and only fetches from public websites. Admin > Settings > Quotes can switch pictures off. From Mountaineer IT's build of ITFlow. ### Bug Fixes @@ -240,6 +241,7 @@ Update from Maintenance > Update — Queue Update hands the job to cron, which u - Database 3.8.6: `user_settings.user_config_timezone` (NULL is the company's) - `functions/user_timezone.php`: `timezoneUsersReady()`, `timezoneOwn()`, `timezoneOf()`, `timezoneView()`, `timezoneShifted()`, `timezoneConvert()`, `timezoneToView()` and `timezoneFromView()`; `timezoneField()` and `timezoneSave()` (`edit_your_user_preferences`, posting `timezone`). Times go out on the viewer's clock and come back in the company's: `calendar_items` and `calendar_day` turn the days asked for with `timezoneFromView()` and the items with `timezoneItems()`, `calendar_move` takes `timezoneMovePost()`, `add_event` and `edit_event` take `timezoneEventPost()`, `edit_ticket_schedule`, `add_ticket` and `save_ticket_helper` turn `scheduled_date_time` and `schedule` back, and the event form, Schedule window and helper window show `timezoneToView()` with `timezoneFormHint()`. `ticketScheduleShortText()` is on the viewer's clock with `timezoneAbbr()`; `timezoneEventWhenText()` is the quick look's; `agent/calendar.php` has `data-zone` and `timezoneNote()`, and `agent/js/calendar.js` sets `now` from it. `ticketMailSchedule($row, $cal_str, $cancelled, $when_text, $start, $end)` and the helper emails give the agent's time with `timezoneWhenFor()`. From Mountaineer IT's build of ITFlow. - Dispatch (`agent/dispatch.php`, `agent/js/dispatch.js`, `functions/dispatch.php`): `dispatchCan()` (Support at View), `dispatchCanEdit()` (`calendarCanScheduleTickets()`), `dispatchAgents()` (active agents who are admins or have Support at Modify, with `calendarAgentColor()`), `dispatchState()` / `dispatchStateSave()` (the `dispatch` key of `user_settings.user_config_calendar_state`, which `calendarUserStateSave()` now keeps: `view`, `hidden`, `weekends`), `dispatchBusinessHours()` and `dispatchWorkingDay()` from `getSlaSettings()`, `dispatchQueue($tab, $filters)` (`unassigned`, `unbooked`, `left_behind` via `calendarLeftBehindSql()`, with each tab's count), `dispatchItems($from, $to, $agent_ids)` (the tickets, helper bookings, events and holidays sources per agent, `extendedProps.agent` and `reference` added, only tickets and one-off events editable, through `timezoneItems()`), `dispatchBook()` (`ticketChangeAssignee()`, `ticketMailScheduleAgentCancelled()` for the agent who had it, then `ticketSetSchedule()`), `dispatchUnbook()` (`ticketCancelSchedule()`), `dispatchAssign()` (refused for a booked ticket), `dispatchEventMove()` (a one-off event in time and from one agent to another with `calendarEventSetAgents()`, `calendarSendInvites()` with `update` to those who have it), `dispatchWorkload()` with `dispatchWorkloadFlags()`, and `dispatchWeekStats()` (tickets given this week read from the `assigned the ticket to ` history lines). `agent/ajax.php`: GET `dispatch_queue`, `dispatch_items`, `dispatch_workload`, `dispatch_week`; POST (CSRF) `dispatch_state`, and with `dispatchCanEdit()`, after `timezoneMovePost()`, `dispatch_book`, `dispatch_unbook`, `dispatch_assign` and `dispatch_event_move` - JSON `{ok, message, conflicts}` or `{error}` with 400/403. `ticketSetSchedule()` and `ticketMailSchedule()` take `$tell_client` (default true) to leave the contact and watchers out. Day is a FullCalendar `timeGridDay` per agent in one scroller (`drop` for the queue's `FullCalendar.Interaction.Draggable`, `eventReceive` between columns, `eventDragStop` over the queue to unbook); Week and Workload use SortableJS. From Mountaineer IT's build of ITFlow. - Database 3.8.7: `quote_items.item_cost`, `item_price_method` (`markup`, `margin` or `price`) and `item_price_percent` - the names MountaineerIT's build uses - and `config_quote_price_method`, `config_quote_price_percent` and `config_quote_price_presets` - `quotePricingReady()`. `functions/quote_pricing.php`: `QUOTE_PRICE_METHODS`, `quotePricingSettings()` (read from `settings` directly, not `load_global_settings.php`), `quotePriceFromCost()`, `quotePricingFromInput()`, `quotePricingSetSql()` - `billingItemSave()` takes `pricing` with `cost`, `price_method` and `price_percent` on a quote, and gives a new line from a product its `product_cost` as a set price - `quotePricingCopySql()` (`add_quote_copy`, which now also keeps `item_product_id`, and `billingCopyLines()` to a quote), `quotePricingMethodNow()` (a markup or margin whose price was changed by hand reads as a set price), `quotePricingLineHtml()` (under the line in `includes/billing_paper.php` while `edit`) and `quotePricingFields()` with `itflowBillingPricingForm()` in `js/billing_items.js`. `billingItems()` returns the three columns for a quote; `billingMargin()` uses `item_cost` before the product's cost. The API's quote line read returns them as it returns every column. From Mountaineer IT's build of ITFlow. +- Database 3.8.8: `quote_items.item_image`, `products.product_image` (paths under `uploads/`, the names MountaineerIT's build uses; their `uploads/mit_images/` files are taken as they are) and `config_quote_show_images` - `quoteImagesReady()`, `quoteImagesShown()`. `functions/quote_images.php`: `quoteImageStore()` redraws a JPG, PNG, GIF or WebP with GD at up to 800 pixels a side into `uploads/quote_images/<32 hex>.jpg|png`; `quoteImageFromUpload()`, `quoteImageFromUrl()` (the image, or a page's `og:image` / `twitter:image` / `image_src`) through `quoteImageFetch()` - http(s) on ports 80, 443, 8080 and 8443, every resolved address checked by `quoteImageIpIsPublic()` and pinned with `CURLOPT_RESOLVE`, no proxy, three redirects each checked, 8 MB and 25 seconds in all; `quoteImageSave($table, $id, $in, $files)` for `item_image` / `product_image` with `_url` and `_remove`, `quoteImageField()`, `quoteImageThumbHtml()`, `quoteImageFromProduct()` (a new quote line in `billingItemSave()`), `quoteImageCopySql()` (`add_quote_copy`, `billingCopyLines()` to a quote) and `quoteImagesDeleteFor()` (`billingItemDelete()`, `delete_quote`, deleting a client from the page or the API, the API's quote delete, demo data); `productDelete()` throws the product's away. `includes/billing_paper.php` and `billingPdfRender()` show it; the Edit Line and product windows post `multipart/form-data`, and `js/app.js` previews the file picked. From Mountaineer IT's build of ITFlow. ## [26.11.8] diff --git a/admin/database_updates/3.8.8.php b/admin/database_updates/3.8.8.php new file mode 100644 index 000000000..42c878b62 --- /dev/null +++ b/admin/database_updates/3.8.8.php @@ -0,0 +1,32 @@ + 0; + }; + + if (!$itflow_column('quote_items', 'item_image')) { + mysqli_query($mysqli, "ALTER TABLE `quote_items` ADD `item_image` varchar(255) DEFAULT NULL AFTER `item_price_percent`"); + } + if (!$itflow_column('products', 'product_image')) { + mysqli_query($mysqli, "ALTER TABLE `products` ADD `product_image` varchar(255) DEFAULT NULL AFTER `product_cost`"); + } + if (!$itflow_column('settings', 'config_quote_show_images')) { + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_quote_show_images` tinyint(1) NOT NULL DEFAULT 1 AFTER `config_quote_price_presets`"); + } diff --git a/admin/post/demo_data_model.php b/admin/post/demo_data_model.php index 767c1ee7f..92d7337f4 100644 --- a/admin/post/demo_data_model.php +++ b/admin/post/demo_data_model.php @@ -793,6 +793,7 @@ function demoDataRemove($mysqli) { $sql = mysqli_query($mysqli, "SELECT quote_id FROM quotes WHERE quote_client_id = $client_id"); while ($row = mysqli_fetch_assoc($sql)) { $quote_id = intval($row['quote_id']); + quoteImagesDeleteFor("item_quote_id = $quote_id"); mysqli_query($mysqli, "DELETE FROM quote_items WHERE item_quote_id = $quote_id"); mysqli_query($mysqli, "DELETE FROM history WHERE history_quote_id = $quote_id"); } diff --git a/admin/post/settings_quote.php b/admin/post/settings_quote.php index 874ce10c6..9377d1b8d 100644 --- a/admin/post/settings_quote.php +++ b/admin/post/settings_quote.php @@ -3,7 +3,8 @@ /* * Admin > Settings > Quotes (admin/settings_quote.php): * edit_quote_settings saves the numbering, the footer, who is emailed a - * client's answer and the pricing a line starts with. A next number already + * client's answer, the pricing a line starts with and whether lines show + * their pictures. A next number already * in use, an email address that isn't one, or a % that can't be used, comes * back to the page saying so - nothing is saved. */ @@ -15,10 +16,14 @@ if (isset($_POST['edit_quote_settings'])) { validateCSRFToken(); $pricing_columns = quotePricingReady() ? ['config_quote_price_method', 'config_quote_price_percent', 'config_quote_price_presets'] : []; - $before = settingsCurrent(array_merge(['config_quote_prefix', 'config_quote_next_number', 'config_quote_footer', 'config_quote_notification_email'], $pricing_columns)); + $image_columns = quoteImagesReady() ? ['config_quote_show_images'] : []; + $before = settingsCurrent(array_merge(['config_quote_prefix', 'config_quote_next_number', 'config_quote_footer', 'config_quote_notification_email'], $pricing_columns, $image_columns)); - // What was sent, and what is saved for anything that wasn't + // What was sent, and what is saved for anything that wasn't - a switch sends nothing when off $in = $_POST + array_map(function ($value) { return (string) $value; }, $before); + if ($image_columns) { + $in['config_quote_show_images'] = empty($_POST['config_quote_show_images']) ? '0' : '1'; + } [$prefix, $number, $errors] = settingsNumberingCheck('quote', $in, $before); $after = [ @@ -30,6 +35,9 @@ if (isset($_POST['edit_quote_settings'])) { if ($problem = settingsEmailProblem($after['config_quote_notification_email'])) { $errors['config_quote_notification_email'] = $problem; } + if ($image_columns) { + $after['config_quote_show_images'] = $in['config_quote_show_images']; + } // How a line's price comes from its cost (functions/quote_pricing.php) if ($pricing_columns) { $method = quotePriceMethod($in['config_quote_price_method']); diff --git a/admin/settings_quote.php b/admin/settings_quote.php index b25733213..ed136af8a 100644 --- a/admin/settings_quote.php +++ b/admin/settings_quote.php @@ -44,6 +44,13 @@ echo settingsPageStart('quote'); + + + 'Show pictures on quotes', + 'help' => 'Beside each line on the quote, the guest link, the client portal and the PDF - and the Picture field in a line\'s Edit window. Off, they are kept but not shown.']) ?> + + + diff --git a/agent/modals/billing/billing_item.php b/agent/modals/billing/billing_item.php index 121e72719..b2f74c016 100644 --- a/agent/modals/billing/billing_item.php +++ b/agent/modals/billing/billing_item.php @@ -58,7 +58,7 @@ ob_start(); -
+ @@ -259,6 +259,9 @@ ob_start(); + + +
diff --git a/agent/modals/product/product_add.php b/agent/modals/product/product_add.php index 32144f94c..c910d6ab5 100644 --- a/agent/modals/product/product_add.php +++ b/agent/modals/product/product_add.php @@ -19,7 +19,7 @@ ob_start();
- + - + diff --git a/agent/modals/product/product_form.php b/agent/modals/product/product_form.php index 68304b4dc..1259784fc 100644 --- a/agent/modals/product/product_form.php +++ b/agent/modals/product/product_form.php @@ -252,6 +252,9 @@ if ($form_vendor_id && !isset($form_vendors[$form_vendor_id]) && $form_value('ve
+ + +
diff --git a/agent/post/billing.php b/agent/post/billing.php index 8cf0349f0..91389a45d 100644 --- a/agent/post/billing.php +++ b/agent/post/billing.php @@ -129,6 +129,13 @@ if (isset($_POST['billing_item_save'])) { $name = trim((string) $_POST['name']); logAudit(billingAuditType($type), 'Edit', escapeSql("$session_name " . ($item_id ? 'edited' : 'added') . " line $name " . ($item_id ? 'on' : 'to') . " $number"), $client_id, $doc_id); + // A quote line's picture - a new one, or taken off (functions/quote_images.php) + $image_error = $type === 'quote' ? quoteImageSave('quote_items', $saved, $_POST, $_FILES) : ''; + if ($image_error !== '') { + flashAlert('' . escapeHtml($name) . ' ' . ($item_id ? 'updated' : 'added') . ', but its picture couldn\'t be added: ' . escapeHtml($image_error), 'warning'); + billingPostBack($type, $doc_id, "line-$saved"); + } + flashAlert('' . escapeHtml($name) . ' ' . ($item_id ? 'updated' : 'added')); billingPostBack($type, $doc_id, $item_id ? "line-$saved" : 'add-line'); diff --git a/agent/post/client.php b/agent/post/client.php index 060cae8bd..24b50db72 100644 --- a/agent/post/client.php +++ b/agent/post/client.php @@ -304,8 +304,9 @@ if (isset($_GET['delete_client'])) { //Delete Quote and related items $sql = mysqli_query($mysqli, "SELECT quote_id FROM quotes WHERE quote_client_id = $client_id"); while($row = mysqli_fetch_assoc($sql)) { - $quote_id = $row['quote_id']; + $quote_id = intval($row['quote_id']); + quoteImagesDeleteFor("item_quote_id = $quote_id"); mysqli_query($mysqli, "DELETE FROM quote_items WHERE item_quote_id = $quote_id"); } mysqli_query($mysqli, "DELETE FROM quotes WHERE quote_client_id = $client_id"); diff --git a/agent/post/product.php b/agent/post/product.php index a522b41b7..2aed41365 100644 --- a/agent/post/product.php +++ b/agent/post/product.php @@ -42,6 +42,13 @@ if (isset($_POST['add_product'])) { logAudit("Product", "Create", "$session_name created " . strtolower($type_label) . " $name", 0, $product_id); + // Its picture (functions/quote_images.php) + $image_error = quoteImageSave('products', $product_id, $_POST, $_FILES); + if ($image_error !== '') { + flashAlert("$type_label " . escapeHtml($product['product_name']) . " added, but its picture couldn't be added: " . escapeHtml($image_error), 'warning'); + redirect(); + } + flashAlert("$type_label " . escapeHtml($product['product_name']) . " added"); redirect(); @@ -76,6 +83,13 @@ if (isset($_POST['edit_product'])) { } } + // Its picture (functions/quote_images.php) + $image_error = quoteImageSave('products', $product_id, $_POST, $_FILES); + if ($image_error !== '') { + flashAlert("" . escapeHtml($product['product_name']) . " saved$price_note - but its picture couldn't be added: " . escapeHtml($image_error), 'warning'); + redirect(); + } + flashAlert("" . escapeHtml($product['product_name']) . " saved$price_note"); redirect(); diff --git a/agent/post/quote.php b/agent/post/quote.php index 51abf1308..ff1f4a924 100644 --- a/agent/post/quote.php +++ b/agent/post/quote.php @@ -105,7 +105,7 @@ if (isset($_POST['add_quote_copy'])) { mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Draft', history_description = 'Quote copied!', history_quote_id = $new_quote_id"); $sql_items = mysqli_query($mysqli,"SELECT item_description, item_id, item_name, item_order, item_price, item_quantity, item_subtotal, - item_tax, item_tax_id, item_total, item_frequency, item_product_id" . (quotePricingReady() ? ', item_cost, item_price_method, item_price_percent' : '') . " FROM quote_items WHERE item_quote_id = $quote_id"); + item_tax, item_tax_id, item_total, item_frequency, item_product_id" . (quotePricingReady() ? ', item_cost, item_price_method, item_price_percent' : '') . (quoteImagesReady() ? ', item_image' : '') . " FROM quote_items WHERE item_quote_id = $quote_id"); while($row = mysqli_fetch_assoc($sql_items)) { $item_id = intval($row['item_id']); $item_name = escapeSql($row['item_name']); @@ -124,7 +124,7 @@ if (isset($_POST['add_quote_copy'])) { if ($item_product_id && !getFieldById('products', $item_product_id, 'product_id')) { $item_product_id = 0; } - $item_pricing = quotePricingCopySql($row); + $item_pricing = quotePricingCopySql($row) . quoteImageCopySql($row); mysqli_query($mysqli,"INSERT INTO quote_items SET item_name = '$item_name', item_description = '$item_description', item_quantity = $item_quantity, item_price = $item_price, item_subtotal = $item_subtotal, item_tax = $item_tax, item_total = $item_total, item_order = $item_order, item_tax_id = $tax_id, item_frequency = $item_frequency, item_product_id = $item_product_id$item_pricing, item_quote_id = $new_quote_id"); } @@ -247,7 +247,8 @@ if (isset($_GET['delete_quote'])) { mysqli_query($mysqli,"DELETE FROM quotes WHERE quote_id = $quote_id"); - //Delete Items Associated with the Quote + //Delete Items Associated with the Quote - and their pictures (functions/quote_images.php) + quoteImagesDeleteFor("item_quote_id = $quote_id"); $sql = mysqli_query($mysqli,"SELECT item_id FROM quote_items WHERE item_quote_id = $quote_id"); while($row = mysqli_fetch_assoc($sql)) {; $item_id = intval($row['item_id']); diff --git a/api/v1/clients/delete.php b/api/v1/clients/delete.php index 3073e2484..9caa448d6 100644 --- a/api/v1/clients/delete.php +++ b/api/v1/clients/delete.php @@ -48,6 +48,7 @@ if (!empty($client_id)) { $sql_quotes = mysqli_query($mysqli, "SELECT quote_id FROM quotes WHERE quote_client_id = $client_id"); while ($quote_row = mysqli_fetch_assoc($sql_quotes)) { $quote_id = intval($quote_row['quote_id']); + quoteImagesDeleteFor("item_quote_id = $quote_id"); mysqli_query($mysqli, "DELETE FROM quote_items WHERE item_quote_id = $quote_id"); } mysqli_query($mysqli, "DELETE FROM quotes WHERE quote_client_id = $client_id"); diff --git a/api/v1/quotes/delete.php b/api/v1/quotes/delete.php index 38a79c8aa..9bad35657 100644 --- a/api/v1/quotes/delete.php +++ b/api/v1/quotes/delete.php @@ -28,6 +28,7 @@ if (!empty($quote_id)) { $delete_count = mysqli_affected_rows($mysqli); if ($delete_count > 0) { + quoteImagesDeleteFor("item_quote_id = $quote_id"); mysqli_query($mysqli, "DELETE FROM quote_items WHERE item_quote_id = $quote_id"); // Its history - a recurring invoice's entry for the lines it added stays theirs diff --git a/css/itflow_custom.css b/css/itflow_custom.css index 95182dc93..6db8addae 100644 --- a/css/itflow_custom.css +++ b/css/itflow_custom.css @@ -6752,6 +6752,29 @@ a.itflow-report-stat:focus-visible { min-width: 12rem; width: 55%; } +/* A quote line's picture beside its name, and the box a picture field shows it in (functions/quote_images.php) - + on white in both themes, as a product photo is taken */ +.itflow-line-image { + flex-shrink: 0; + object-fit: contain; + background: #fff; + border: 1px solid var(--bs-border-color); + border-radius: var(--bs-border-radius-sm); +} +.itflow-line-image-box { + width: 6.5rem; + height: 6.5rem; +} +.itflow-line-image-box img { + max-width: 100%; + max-height: 100%; + object-fit: contain; +} +@media print { + .itflow-line-image { + border-color: #dee2e6; + } +} /* A line's rate under its tax wraps, so a long name ("Quebec GST + QST 14.975%") doesn't widen the column past the paper */ .itflow-paper-tax-label { diff --git a/db.sql b/db.sql index 64349d6f6..9b96a27b9 100644 --- a/db.sql +++ b/db.sql @@ -2416,6 +2416,7 @@ CREATE TABLE `products` ( `product_location` varchar(250) DEFAULT NULL, `product_price` decimal(15,2) NOT NULL, `product_cost` decimal(15,2) NOT NULL DEFAULT 0.00, + `product_image` varchar(255) DEFAULT NULL, `product_currency_code` varchar(200) NOT NULL, `product_frequency` varchar(10) DEFAULT NULL, `product_seat_source` varchar(20) DEFAULT NULL, @@ -2530,6 +2531,7 @@ CREATE TABLE `quote_items` ( `item_cost` decimal(15,2) DEFAULT NULL, `item_price_method` varchar(10) DEFAULT NULL, `item_price_percent` decimal(7,2) DEFAULT NULL, + `item_image` varchar(255) DEFAULT NULL, `item_subtotal` decimal(15,2) NOT NULL DEFAULT 0.00, `item_tax` decimal(15,2) NOT NULL DEFAULT 0.00, `item_total` decimal(15,2) NOT NULL DEFAULT 0.00, @@ -3360,6 +3362,7 @@ CREATE TABLE `settings` ( `config_quote_price_method` varchar(10) NOT NULL DEFAULT 'markup', `config_quote_price_percent` decimal(7,2) NOT NULL DEFAULT 20.00, `config_quote_price_presets` varchar(100) NOT NULL DEFAULT '15,20,25,35', + `config_quote_show_images` tinyint(1) NOT NULL DEFAULT 1, `config_ticket_prefix` varchar(200) DEFAULT NULL, `config_ticket_next_number` int(11) DEFAULT NULL, `config_ticket_from_name` varchar(200) DEFAULT NULL, diff --git a/functions.php b/functions.php index c86dfc0a6..abaffd84c 100644 --- a/functions.php +++ b/functions.php @@ -94,6 +94,7 @@ require_once __DIR__ . '/functions/contract_hours.php'; require_once __DIR__ . '/functions/contract_billing.php'; require_once __DIR__ . '/functions/products.php'; require_once __DIR__ . '/functions/quote_pricing.php'; +require_once __DIR__ . '/functions/quote_images.php'; require_once __DIR__ . '/functions/billing_email.php'; require_once __DIR__ . '/functions/billing_pay.php'; require_once __DIR__ . '/functions/payment_provider.php'; diff --git a/functions/billing.php b/functions/billing.php index 0e8f48042..b3540dd0b 100644 --- a/functions/billing.php +++ b/functions/billing.php @@ -118,6 +118,10 @@ function billingItems($type, $id) { if ($type === 'quote' && quotePricingReady()) { $seat_columns .= ', item_cost, item_price_method, item_price_percent'; } + // And its picture (functions/quote_images.php) + if ($type === 'quote' && quoteImagesReady()) { + $seat_columns .= ', item_image'; + } $sql = mysqli_query($mysqli, "SELECT item_id, item_name, item_description, item_quantity, item_price, item_subtotal, item_tax, item_total, item_order, item_tax_id, item_product_id, item_created_at, tax_name, tax_percent $seat_columns FROM {$t['items']} @@ -440,6 +444,10 @@ function billingItemSave($type, $doc_id, array $in, $item_id = 0, &$error = '') $order = intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT COALESCE(MAX(item_order), 0) + 1 FROM {$t['items']} WHERE {$t['item_fk']} = $doc_id"))[0]); mysqli_query($mysqli, "INSERT INTO {$t['items']} SET $set, item_order = $order, item_product_id = $product_id, {$t['item_fk']} = $doc_id"); $item_id = mysqli_insert_id($mysqli); + // A quote line from a product gets its own copy of the product's picture (functions/quote_images.php) + if ($type === 'quote' && $product_id) { + quoteImageFromProduct($item_id, $product_id); + } } if ($stock_change != 0) { productStockMove($product_id, -$stock_change, $stock_change > 0 ? 'sold' : 'returned', [ @@ -557,6 +565,9 @@ function billingItemDelete($type, $doc_id, $item_id) { if (!$item) { return null; } + if ($type === 'quote') { + quoteImagesDeleteFor("item_id = $item_id"); + } mysqli_query($mysqli, "DELETE FROM {$t['items']} WHERE item_id = $item_id"); $product_id = intval($item['item_product_id']); if ($type === 'invoice' && $product_id && intval(getFieldById('products', $product_id, 'product_track_stock')) === 1 && floatval($item['item_quantity']) > 0) { @@ -1584,7 +1595,7 @@ function billingCopyLines(array $items, $to_type, $to_id, $suffix = '') { $product_id = 0; } // A quote line's cost and pricing go with it to another quote - an invoice is made from the price alone - $pricing = $to_type === 'quote' ? quotePricingCopySql($item) : ''; + $pricing = $to_type === 'quote' ? quotePricingCopySql($item) . quoteImageCopySql($item) : ''; mysqli_query($mysqli, "INSERT INTO {$t['items']} SET item_name = '$name', item_description = '$description', item_quantity = " . floatval($item['item_quantity']) . ", item_price = " . floatval($item['item_price']) . ", item_subtotal = " . floatval($item['item_subtotal']) . ", item_tax = " . floatval($item['item_tax']) . ", item_total = " . floatval($item['item_total']) . ", item_order = $order, item_tax_id = " . intval($item['item_tax_id']) . ", item_product_id = $product_id$pricing, {$t['item_fk']} = $to_id"); diff --git a/functions/billing_pdf.php b/functions/billing_pdf.php index f2d899b69..9c193a886 100644 --- a/functions/billing_pdf.php +++ b/functions/billing_pdf.php @@ -253,7 +253,9 @@ function billingPdfRender($type, array $row, $variant = 'document') { $tax_label = floatval($item['item_tax']) != 0 || intval($item['item_tax_id']) ? '
' . $e(trim(($item['tax_name'] ?? '') . ' ' . ($item['tax_percent'] !== null ? taxPercentText($item['tax_percent']) . '%' : ''))) . '' : ''; - $html .= '' . $e($item['item_name']) . '' + // A quote line's picture above its name (functions/quote_images.php) + $image = $type === 'quote' && quoteImagesShown() && quoteImageUrl($item['item_image'] ?? '') !== '' ? '
' : ''; + $html .= '' . $image . '' . $e($item['item_name']) . '' . (trim((string) $item['item_description']) !== '' ? '
' . nl2br($e($item['item_description'])) . '' : '') . ' ' . $e(billingQuantity($item['item_quantity'])) . ' ' . $money($item['item_price']) . ' diff --git a/functions/products.php b/functions/products.php index 506bc0294..b133279f3 100644 --- a/functions/products.php +++ b/functions/products.php @@ -338,13 +338,16 @@ function productCopy($product_id) { ], 0, $error); } -/** Delete a product, its stock and its price history. Lines it is on keep their text and amounts; license templates sold as it no longer are. */ +/** Delete a product, its stock, its price history and its picture. Lines it is on keep their text and amounts; license templates sold as it no longer are. */ function productDelete($product_id) { global $mysqli; $product_id = intval($product_id); mysqli_query($mysqli, "UPDATE software_templates SET software_template_product_id = 0, software_template_updated_at = software_template_updated_at WHERE software_template_product_id = $product_id"); mysqli_query($mysqli, "DELETE FROM product_stock WHERE stock_product_id = $product_id"); mysqli_query($mysqli, "DELETE FROM product_prices WHERE price_product_id = $product_id"); + if (quoteImagesReady()) { + quoteImageDelete((string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT product_image FROM products WHERE product_id = $product_id"))[0] ?? '')); + } mysqli_query($mysqli, "DELETE FROM products WHERE product_id = $product_id"); } diff --git a/functions/quote_images.php b/functions/quote_images.php new file mode 100644 index 000000000..5c2af7fe3 --- /dev/null +++ b/functions/quote_images.php @@ -0,0 +1,439 @@ + Settings > Quotes). + */ + +const QUOTE_IMAGE_DIR = 'uploads/quote_images'; +const QUOTE_IMAGE_MAX_BYTES = 8 * 1024 * 1024; +const QUOTE_IMAGE_MAX_SIDE = 800; + +/** Whether the 3.8.8 update has run. */ +function quoteImagesReady() { + 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.8.8', '>='); + } + return $ready; +} + +/** Whether quotes show their lines' pictures (Admin > Settings > Quotes) - on unless switched off. */ +function quoteImagesShown() { + global $mysqli; + static $shown = null; + if ($shown === null) { + $shown = quoteImagesReady() + && intval(mysqli_fetch_row(mysqli_query($mysqli, "SELECT config_quote_show_images FROM settings WHERE company_id = 1"))[0] ?? 1) === 1; + } + return $shown; +} + +/** Whether a stored path is one of these pictures, and nothing else. */ +function quoteImageIsOurs($relative) { + return is_string($relative) && preg_match('#^uploads/(quote_images|mit_images)/[a-f0-9]{32}\.(jpg|png)$#', $relative) === 1; +} + +/** Where a picture is on disk. */ +function quoteImagePath($relative) { + return dirname(__DIR__) . '/' . $relative; +} + +/** Where a browser shows it from - '' for none. */ +function quoteImageUrl($relative) { + return quoteImageIsOurs($relative) && is_file(quoteImagePath($relative)) ? '/' . $relative : ''; +} + +/* + * Keep image bytes as a picture of our own - redrawn at up to 800 pixels a + * side, as a PNG when it can be see-through, else a JPG. Its path. Throws, + * with what to tell the agent, when it isn't a JPG, PNG, GIF or WebP. + */ +function quoteImageStore($bytes) { + if (strlen($bytes) === 0 || strlen($bytes) > QUOTE_IMAGE_MAX_BYTES) { + throw new RuntimeException('The picture is empty or bigger than ' . (QUOTE_IMAGE_MAX_BYTES / 1048576) . ' MB.'); + } + $info = @getimagesizefromstring($bytes); + if (!$info || !in_array($info[2], [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP], true)) { + throw new RuntimeException('That is not a JPG, PNG, GIF or WebP picture.'); + } + // The whole bitmap is held in memory - about 4 bytes a pixel + if ($info[0] * $info[1] > 25000000) { + throw new RuntimeException('That picture is too large to work with.'); + } + $source = @imagecreatefromstring($bytes); + if (!$source) { + throw new RuntimeException('That picture could not be read.'); + } + $width = imagesx($source); + $height = imagesy($source); + $scale = min(1, QUOTE_IMAGE_MAX_SIDE / max($width, $height)); + $new_width = max(1, (int) round($width * $scale)); + $new_height = max(1, (int) round($height * $scale)); + $alpha = in_array($info[2], [IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP], true); + $image = imagecreatetruecolor($new_width, $new_height); + if ($alpha) { + imagealphablending($image, false); + imagesavealpha($image, true); + imagefill($image, 0, 0, imagecolorallocatealpha($image, 255, 255, 255, 127)); + } else { + imagefill($image, 0, 0, imagecolorallocate($image, 255, 255, 255)); + } + imagecopyresampled($image, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height); + imagedestroy($source); + + $dir = quoteImagePath(QUOTE_IMAGE_DIR); + if (!is_dir($dir) && !@mkdir($dir, 0750, true)) { + throw new RuntimeException('The pictures folder could not be made in uploads.'); + } + $relative = QUOTE_IMAGE_DIR . '/' . bin2hex(random_bytes(16)) . ($alpha ? '.png' : '.jpg'); + $saved = $alpha ? imagepng($image, quoteImagePath($relative), 6) : imagejpeg($image, quoteImagePath($relative), 85); + imagedestroy($image); + if (!$saved) { + throw new RuntimeException('The picture could not be saved.'); + } + return $relative; +} + +/** An uploaded file ($_FILES entry) kept - '' when none was sent. Throws on a bad one. */ +function quoteImageFromUpload($file) { + if (!is_array($file) || ($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) { + return ''; + } + if ($file['error'] !== UPLOAD_ERR_OK || !is_uploaded_file($file['tmp_name'])) { + throw new RuntimeException('The picture didn\'t come through - try again, up to ' . (QUOTE_IMAGE_MAX_BYTES / 1048576) . ' MB.'); + } + return quoteImageStore((string) file_get_contents($file['tmp_name'])); +} + +/** A copy of one of these pictures, for a line or product of its own - '' when there is none. */ +function quoteImageCopy($relative) { + if (!quoteImageIsOurs($relative) || !is_file(quoteImagePath($relative))) { + return ''; + } + $dir = quoteImagePath(QUOTE_IMAGE_DIR); + if (!is_dir($dir) && !@mkdir($dir, 0750, true)) { + return ''; + } + $copy = QUOTE_IMAGE_DIR . '/' . bin2hex(random_bytes(16)) . '.' . pathinfo($relative, PATHINFO_EXTENSION); + return @copy(quoteImagePath($relative), quoteImagePath($copy)) ? $copy : ''; +} + +/** Throw one of these pictures away. */ +function quoteImageDelete($relative) { + if (quoteImageIsOurs($relative)) { + @unlink(quoteImagePath($relative)); + } +} + +/* + * Whether an address is on the public internet - not private, loopback, + * link-local, reserved, carrier-grade NAT, or IPv6 that reaches an IPv4 + * address through a gateway (NAT64, 6to4, Teredo) or by mapping. + */ +function quoteImageIpIsPublic($ip) { + $flags = FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE; + if (defined('FILTER_FLAG_GLOBAL_RANGE')) { + $flags |= FILTER_FLAG_GLOBAL_RANGE; + } + if (!filter_var($ip, FILTER_VALIDATE_IP, $flags)) { + return false; + } + if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) && (ip2long($ip) & 0xFFC00000) === (ip2long('100.64.0.0') & 0xFFC00000)) { + return false; + } + if (stripos($ip, '::ffff:') === 0) { + return quoteImageIpIsPublic(substr($ip, 7)); + } + $bytes = @inet_pton($ip); + if ($bytes !== false && strlen($bytes) === 16) { + $hex = bin2hex($bytes); + foreach (['0064ff9b0000000000000000', '0064ff9b0001', '2002', '20010000'] as $prefix) { + if (strpos($hex, $prefix) === 0) { + return false; + } + } + } + return true; +} + +/* + * Fetch a web address for a picture: http(s) on the usual ports only, every + * address the name has checked public and the connection held to the one + * checked, at most three redirects (each checked again), a size cap and one + * time limit for it all. [body, content type]. Throws with what to tell the agent. + */ +function quoteImageFetch($url, $deadline) { + for ($hop = 0; $hop < 4; $hop++) { + $time_left = (int) floor($deadline - microtime(true)); + if ($time_left < 2) { + throw new RuntimeException('The website took too long to answer.'); + } + $parts = parse_url((string) $url); + $scheme = strtolower($parts['scheme'] ?? ''); + $host = $parts['host'] ?? ''; + if (!in_array($scheme, ['http', 'https'], true) || $host === '' || isset($parts['user']) || isset($parts['pass'])) { + throw new RuntimeException('Use a web address that starts with http:// or https://.'); + } + $port = intval($parts['port'] ?? ($scheme === 'https' ? 443 : 80)); + if (!in_array($port, [80, 443, 8080, 8443], true)) { + throw new RuntimeException('That web address uses a port ITFlow won\'t fetch from.'); + } + $host_plain = trim($host, '[]'); + $ips = filter_var($host_plain, FILTER_VALIDATE_IP) ? [$host_plain] : array_merge( + (array) @gethostbynamel($host_plain), + array_column((array) @dns_get_record($host_plain, DNS_AAAA), 'ipv6') + ); + $ips = array_values(array_filter($ips)); + if (!$ips) { + throw new RuntimeException("$host couldn't be found."); + } + foreach ($ips as $ip) { + if (!quoteImageIpIsPublic($ip)) { + throw new RuntimeException('That address is on a private or local network - ITFlow only fetches from public websites.'); + } + } + $body = ''; + $ch = curl_init($url); + curl_setopt_array($ch, [ + CURLOPT_RETURNTRANSFER => false, + CURLOPT_FOLLOWLOCATION => false, + CURLOPT_TIMEOUT => min(15, $time_left), + CURLOPT_CONNECTTIMEOUT => min(8, $time_left), + CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, + // No proxy from the environment - it would look the name up again itself + CURLOPT_PROXY => '', + CURLOPT_NOPROXY => '*', + // To the address checked above - looked up again, the name could point somewhere else + CURLOPT_RESOLVE => ["$host_plain:$port:" . (strpos($ips[0], ':') !== false ? "[{$ips[0]}]" : $ips[0])], + CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; ITFlow picture fetch)', + CURLOPT_HTTPHEADER => ['Accept: image/*,text/html;q=0.9,*/*;q=0.5'], + CURLOPT_ENCODING => '', + CURLOPT_WRITEFUNCTION => function ($ch, $chunk) use (&$body) { + $body .= $chunk; + return strlen($body) > QUOTE_IMAGE_MAX_BYTES ? 0 : strlen($chunk); + }, + ]); + curl_exec($ch); + $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + $type = strtolower((string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE)); + $redirect = (string) curl_getinfo($ch, CURLINFO_REDIRECT_URL); + $error = curl_error($ch); + curl_close($ch); + if (strlen($body) > QUOTE_IMAGE_MAX_BYTES) { + throw new RuntimeException('That file is bigger than ' . (QUOTE_IMAGE_MAX_BYTES / 1048576) . ' MB.'); + } + if ($status >= 300 && $status < 400 && $redirect !== '') { + $url = $redirect; + continue; + } + if ($status !== 200) { + throw new RuntimeException('The website answered ' . ($status ?: ($error !== '' ? $error : 'nothing')) . '.'); + } + return [$body, $type]; + } + throw new RuntimeException('That web address redirects too many times.'); +} + +/* A link found on a page, made whole against the page's address - '' for anything but http(s). */ +function quoteImageResolveUrl($base, $relative) { + $relative = trim($relative); + if (preg_match('#^https?://#i', $relative)) { + return $relative; + } + $b = parse_url($base); + if (empty($b['scheme']) || empty($b['host']) || preg_match('#^[a-z][a-z0-9+.-]*:#i', $relative)) { + return ''; + } + if (strpos($relative, '//') === 0) { + return $b['scheme'] . ':' . $relative; + } + $origin = $b['scheme'] . '://' . $b['host'] . (isset($b['port']) ? ':' . $b['port'] : ''); + if (strpos($relative, '/') === 0) { + return $origin . $relative; + } + if (strpos($relative, '?') === 0) { + return $origin . ($b['path'] ?? '/') . $relative; + } + $segments = []; + foreach (explode('/', preg_replace('#/[^/]*$#', '/', $b['path'] ?? '/') . $relative) as $segment) { + if ($segment === '..') { + array_pop($segments); + } elseif ($segment !== '.') { + $segments[] = $segment; + } + } + return $origin . '/' . ltrim(implode('/', $segments), '/'); +} + +/* A picture from a link - the image itself, or a web page's main picture. Its path. Throws with what to tell the agent. */ +function quoteImageFromUrl($url) { + $url = trim((string) $url); + $deadline = microtime(true) + 25; + [$body, $type] = quoteImageFetch($url, $deadline); + if (strpos($type, 'text/html') !== false || preg_match('/^\s*<(!doctype|html)/i', substr($body, 0, 200))) { + $image_url = ''; + foreach (['og:image:secure_url', 'og:image', 'twitter:image', 'twitter:image:src'] as $name) { + $quoted = preg_quote($name, '/'); + if (preg_match('/]+(?:property|name)=["\']' . $quoted . '["\'][^>]*content=["\']([^"\']+)["\']/i', $body, $match) + || preg_match('/]+content=["\']([^"\']+)["\'][^>]*(?:property|name)=["\']' . $quoted . '["\']/i', $body, $match)) { + $image_url = html_entity_decode($match[1], ENT_QUOTES); + break; + } + } + if ($image_url === '' && preg_match('/]+rel=["\']image_src["\'][^>]*href=["\']([^"\']+)["\']/i', $body, $match)) { + $image_url = html_entity_decode($match[1], ENT_QUOTES); + } + if ($image_url === '') { + throw new RuntimeException('That page doesn\'t name a main picture - right-click the picture you want, copy its image address and use that.'); + } + $image_url = quoteImageResolveUrl($url, $image_url); + if ($image_url === '') { + throw new RuntimeException('That page\'s main picture isn\'t at a web address - copy the image address instead.'); + } + [$body] = quoteImageFetch($image_url, $deadline); + } + return quoteImageStore($body); +} + +/* + * The picture a form asks for - a new upload in $files[$field], else a link in + * _url. Its path, or '' for nothing new; $error says why one asked for + * couldn't be had. + */ +function quoteImageFromForm(array $in, array $files, $field, &$error = '') { + $error = ''; + try { + $upload = quoteImageFromUpload($files[$field] ?? null); + if ($upload !== '') { + return $upload; + } + $url = trim((string) ($in[$field . '_url'] ?? '')); + return $url !== '' ? quoteImageFromUrl($url) : ''; + } catch (Throwable $e) { + $error = $e->getMessage(); + return ''; + } +} + +/* + * Save what a form asked for to a row's picture column - a new one (the old + * one thrown away) or _remove. $table quote_items or products. '' or + * why the new one couldn't be had (the rest is saved either way). + */ +function quoteImageSave($table, $id, array $in, array $files) { + global $mysqli; + if (!quoteImagesReady() || !in_array($table, ['quote_items', 'products'], true)) { + return ''; + } + [$column, $key] = $table === 'quote_items' ? ['item_image', 'item_id'] : ['product_image', 'product_id']; + $id = intval($id); + $old = (string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT $column FROM $table WHERE $key = $id"))[0] ?? ''); + $new = quoteImageFromForm($in, $files, $column, $error); + if ($new !== '') { + mysqli_query($mysqli, "UPDATE $table SET $column = '" . escapeSql($new) . "' WHERE $key = $id"); + quoteImageDelete($old); + } elseif (!empty($in[$column . '_remove']) && $old !== '') { + mysqli_query($mysqli, "UPDATE $table SET $column = NULL WHERE $key = $id"); + quoteImageDelete($old); + } + return $error; +} + +/* A new quote line from a product gets its own copy of the product's picture. */ +function quoteImageFromProduct($item_id, $product_id) { + global $mysqli; + if (!quoteImagesReady() || !intval($product_id)) { + return; + } + $copy = quoteImageCopy((string) (mysqli_fetch_row(mysqli_query($mysqli, "SELECT product_image FROM products WHERE product_id = " . intval($product_id)))[0] ?? '')); + if ($copy !== '') { + mysqli_query($mysqli, "UPDATE quote_items SET item_image = '" . escapeSql($copy) . "' WHERE item_id = " . intval($item_id)); + } +} + +/* The SET that gives a copied quote line its own copy of the picture of the one it came from ($item a billingItems() row). */ +function quoteImageCopySql(array $item) { + if (!quoteImagesReady() || empty($item['item_image'])) { + return ''; + } + $copy = quoteImageCopy((string) $item['item_image']); + return $copy !== '' ? ", item_image = '" . escapeSql($copy) . "'" : ''; +} + +/* Throw away the pictures of these quote lines (WHERE on quote_items) - before they are deleted. */ +function quoteImagesDeleteFor($where) { + global $mysqli; + if (!quoteImagesReady()) { + return; + } + $sql = mysqli_query($mysqli, "SELECT item_image FROM quote_items WHERE item_image IS NOT NULL AND ($where)"); + while ($row = mysqli_fetch_row($sql)) { + quoteImageDelete((string) $row[0]); + } +} + +/* A picture as a small square - '' for none. */ +function quoteImageThumbHtml($relative, $size = 56) { + $url = quoteImageUrl($relative); + return $url !== '' ? '' : ''; +} + +/* + * The picture field in a form - what it is now, upload one, or paste a link to + * pull one from, and remove it. $name is the column (item_image, product_image). + */ +function quoteImageField($name, $current, $help = '') { + $url = quoteImageUrl((string) $current); + ob_start(); ?> +
+ +
+
+ > + > +
+
+
+ + +
+
+ + +
+
From a web page it takes the page's main picture. ITFlow keeps its own copy.
+ +
+ + +
+ +
+
+
+ ['page' => 'quote', 'section' => 'Answers', 'label' => 'Email quote answers to', 'words' => 'accepted declined notification email'], 'config_quote_price_method' => ['page' => 'quote', 'section' => 'Pricing', 'label' => 'Price lines by', 'kind' => 'select', 'words' => 'markup margin cost price profit'], 'config_quote_price_percent' => ['page' => 'quote', 'section' => 'Pricing', 'label' => 'Markup or margin %', 'words' => 'markup margin percent percentage cost'], + 'config_quote_show_images' => ['page' => 'quote', 'section' => 'Pictures', 'label' => 'Show pictures on quotes', 'kind' => 'switch', 'words' => 'image picture photo product quote line'], 'config_quote_price_presets' => ['page' => 'quote', 'section' => 'Pricing', 'label' => 'Quick picks', 'words' => 'markup margin presets buttons percent'], // Invoices and billing diff --git a/includes/billing_paper.php b/includes/billing_paper.php index 377fc78ca..991983f78 100644 --- a/includes/billing_paper.php +++ b/includes/billing_paper.php @@ -75,6 +75,9 @@ $paper_seat_sources = recurringSeatSources(); // A quote with lines billed each month, quarter or year shows them apart from // what is billed once - the lines under a heading each, and a total each $paper_groups = $paper_type === 'quote' && !empty($paper_totals['recurring']) ? $paper_totals['groups'] : null; + +// A quote's lines show their pictures, unless Admin > Settings > Quotes says not to (functions/quote_images.php) +$paper_images = $paper_type === 'quote' && quoteImagesShown(); $paper_line_groups = $paper_groups ?: ['' => ['frequency' => '', 'label' => '', 'items' => $paper_items]]; // Where the lines can be changed, what can be changed where it sits is wrapped @@ -207,12 +210,15 @@ $paper_bill_lines = array_filter([ $item_tax_html = $item_tax_label !== '' ? $paper_money($item['item_tax']) . '
' . escapeHtml($item_tax_label) . '
' : '-'; - $item_quantity = billingQuantity($item['item_quantity']); ?> + $item_quantity = billingQuantity($item['item_quantity']); + // A quote line's picture, beside its name (functions/quote_images.php) + $item_image = $paper_type === 'quote' && $paper_images ? quoteImageThumbHtml($item['item_image'] ?? '') : ''; ?> +
@@ -236,6 +242,7 @@ $paper_bill_lines = array_filter([ +
diff --git a/js/app.js b/js/app.js index 484d1036e..bc8c9faf4 100644 --- a/js/app.js +++ b/js/app.js @@ -1006,6 +1006,36 @@ itflowBindOnce('itflowModalStackHidden', 'hidden.bs.modal', '.modal', function ( } }); +/* + * A picture field (quoteImageField(), functions/quote_images.php) - the file + * picked shows in its box before it is saved, and picking one clears a link + * typed in and a Remove ticked. + */ +itflowBindOnce('itflowImageField', 'change', '[data-image-file]', function () { + const field = this.closest('[data-image-field]'); + const file = this.files && this.files[0]; + if (!field || !file || !/^image\//.test(file.type)) { + return; + } + const preview = field.querySelector('[data-image-preview]'); + const empty = field.querySelector('[data-image-empty]'); + const url = field.querySelector('[data-image-url]'); + const remove = field.querySelector('[data-image-remove]'); + if (preview) { + preview.src = URL.createObjectURL(file); + preview.hidden = false; + } + if (empty) { + empty.hidden = true; + } + if (url) { + url.value = ''; + } + if (remove) { + remove.checked = false; + } +}); + /** * A required field left empty on a tab that isn't showing - the Ticket tab of * a template while Sets up is open, a fill-in on Details while Tasks is - diff --git a/uploads/quote_images/index.php b/uploads/quote_images/index.php new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/uploads/quote_images/index.php @@ -0,0 +1 @@ +