diff --git a/CHANGELOG.md b/CHANGELOG.md index 49e2ff39c..47922318f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Update from Maintenance > Update as usual. There is no database change. - If you have switched a module off in Admin > Settings > Modules - IT documentation, ticketing, invoicing and accounting or any of the others - check that you meant it before updating. Its pages, bookmarks to them and links in old emails stop opening, and the nightly run stops doing its work: with ticketing off, no recurring tickets are raised and resolved tickets aren't closed; with invoicing and accounting off, no recurring invoices or expenses are made, no autopay is charged and no payment reminders go out; with IT documentation off, no domain, certificate, warranty or service review notifications, and shared links - logins, files, documents and IT documentation exports sent to clients - don't open. Switch it back on and the next run picks up what is due, and shared links that haven't run out open again. - API keys get a 403 saying which module is off for anything of a module that is switched off - tickets with ticketing off, assets and credentials with IT documentation off, invoices with invoicing off. +- Contacts imported before with a ? in place of an accented letter keep it. Import the same file again with **A contact already here** set to **Update it** and their names are put right - contacts are matched by email. Anything else imported that way, such as a location or vendor, is matched by its name, so correct those by hand. ### New Features & Updates @@ -19,12 +20,17 @@ Update from Maintenance > Update as usual. There is no database change. - Maintenance > Cron shows the jobs of a module that is off as **Not in use**, saying which module: the Ticket Email Parser, Ticket SLA Monitor, Ticket Pictures and AI Triage with ticketing off, the Domain and Certificate Refreshers with IT documentation off, and Payment Provider Fees with invoicing off. - Audit logs and notifications still name a ticket, invoice or asset of a module that is off, without linking it. The quick looks - a contact, location, vendor or ticket at a glance - leave out what is off too, and a quote's files from the client can still be downloaded with IT documentation off. +### Bug Fixes + +- Importing a CSV file with accented letters - ü, é, ñ, ø and the like - keeps them. A file saved from Excel as plain **CSV (Comma delimited)**, exported from Outlook, or saved from Excel for Mac as **Comma Separated Values** imported with a ? in place of each accented letter, and one with an accented letter in a heading didn't import at all. Every import - clients, contacts, locations, assets and the rest - now reads the file in whatever it was saved as, and a file whose columns are separated by tabs imports too. Bank statements imported on Expenses and Income read the same way, so one saved on a Mac or in Unicode now imports too. + ### Developer Updates - `functions/settings.php`: `modulePaths()` lists each module's pages, windows (`agent/modals/`, `admin/modals/`, a trailing `/` for a whole folder), portal pages and guest pages; `moduleForPath()` gives the modules a path belongs to, a report's from its `'feature'`s in `reportCatalog()`; `modulePathOff()`; `moduleRequestGuard()` turns a request away with `moduleRefuse()` - a window's JSON `content` "Switched off", a portal page's flash and `/client/index.php`, a guest page's plain 404, and an agent page's flash with the `HTTP_REFERER` when that is on this host and not off too, else `/agent/dashboard.php` or `/admin/settings_module.php`. It runs from `includes/check_login.php`, `client/includes/check_login.php`, `guest/includes/inc_all_guest.php` and `guest/guest_ticket_attachment.php`; `guest/share_ajax.php` answers `state: gone` with IT documentation off. `agent/file.php` isn't mapped - a quote's files from the client download through it. `moduleOffText()` now names `itdoc`, `ticketing`, `accounting` and `portal`. `moduleLink($module, $href, $inner_html, $attrs)` gives an `` or, with the module off, a ``; `ticketLink()` and `reportAssetCell()` use it. `settingsStartPages()` leaves out pages that are off, and `includes/load_global_settings.php` and `login.php` open the dashboard instead of a start page that is off (`moduleSwitchesLoad()` reads the switches where the settings aren't loaded). CONTRIBUTING.md has the rule. - `api/v1/enforce_api_rbac.php` maps each resource to its module in `$resource_feature` and `apiDeny(moduleOffText())`s one that is off, reading the switches from `settings` itself. `categoryKindModule()`, `categoryKindsOn()` (`functions/categories.php`), `tagKindModule()` and `tagKindsOn()` (`functions/tags.php`) give the kinds of the modules on - Admin > Categories and Tags, their windows, global search and the API use them, and the API refuses a kind that is off. `calendarSources()` takes a `'part'` per source. `dashboardAccess()` adds `itdoc`. `globalSearchGroups()` gives the documentation groups `'enabled' => $itdoc`. `auditLogRecords()` leaves `url` empty for a record whose page is off and `auditLogRecordLink()` gives a ``; `notificationActionUrl()` returns null for one. - Cron: `cronJobModuleOff()` (`includes/cron_jobs.php`) and `not_in_use` checks on `ticket_email_parser`, `ticket_sla`, `ai_triage`, `ticket_pictures`, `domain_refresher`, `certificate_refresher` and `payment_provider_fees`; `cronJobSettings()` reads the whole settings row. `cron/nightly_tasks.php` skips contracts, recurring invoices, expenses and payments, reminders, quote and draft notices and card checks with accounting off, recurring tickets, auto-close and the pending-tickets notice with ticketing off, and the domain, certificate, warranty, asset date and service review notices with IT documentation off. - Pages: `agent/contact.php`, `location.php`, `asset.php`, `vendor.php`, `service.php`, `ticket.php`, `license.php`, `services.php`, `assets.php`, `calls.php`, `texts.php`, `invoice.php`, `invoices.php`, `quote.php`, `contract.php`, `trips.php`, `unbilled_time.php`, `client_overview.php`, `includes/client_actions_menu.php`, `reports/client_review.php`, `admin/includes/side_nav.php`, `rmm_clients.php`, `payment_methods.php`, `agent_banners.php`, `settings.php`, `settings_mail.php`, `settings_notification.php`, `settings_invoice.php`, `settings_default.php`, `tax_rates.php`, the contract and contract template windows (SLAs kept as hidden fields), the contact, location, vendor and ticket quick looks (`agent/modals/*/`), the offboarding window's open tickets note, `client/index.php`, `search.php`, `functions.php` (`portalNav()`) and `includes/header.php`. A switch or field hidden for a module that is off is kept as saved: `admin/post/settings_notification.php` only writes `config_enable_alert_domain_expire` with IT documentation on, and `tax_rates.php` posts `tax_time` and `tax_trips` hidden. +- Imports: `csvTextToUtf8($text)` (`functions/import.php`) gives a CSV's text as UTF-8 - UTF-8 as it is with its BOM dropped, UTF-16 LE or BE by its BOM, and otherwise Windows-1252 or Mac Roman, whichever `csvTextMisreads()` finds fewer signs of a wrong reading in (C1 control characters, a capital or symbols in the middle of a word, an opening quote or `š`/`ˆ`/`fl` after a letter), Windows-1252 on a tie. `importFile()` reads the whole upload through it into `php://temp`, turns lone `\r` line ends into `\n`, and takes comma, semicolon or tab, whichever the heading line has most of; `expenseImportRead()` uses it in place of its own BOM strip and Windows-1252 fallback, which also let a UTF-16 statement fail its NUL check, and so do the network IP and interface imports in `agent/post/network_ip.php` and `agent/post/asset_interface.php`. Before, `importFile()` passed the bytes through: `importSqlText()`'s `mb_substr()` turned each invalid byte into `?` before `escapeSql()`'s Windows-1252 fallback could see it, and an invalid byte in a heading made `json_encode()` return false, so `import_check` answered with an empty body. `agent/post/import.php` now encodes its answer with `JSON_INVALID_UTF8_SUBSTITUTE`. CONTRIBUTING.md has the rule. ## [26.12.5] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8293fb3d1..89a21c8d3 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -270,6 +270,8 @@ The prefix is the entity name, which is usually but not always the singular of t Two standing exceptions: junction tables (`client_tags`, `service_assets`, …) carry the two parent FK names unprefixed, and `settings` / `user_settings` use `config_*` / `user_config_*`. +**Read an uploaded CSV through `csvTextToUtf8()`.** Excel's plain CSV is Windows-1252 on Windows and Mac Roman on a Mac, and its Unicode Text is UTF-16. Read raw, an accented letter turns into `?` at the first `mb_substr()`, or breaks `json_encode()` outright. `importFile()` does it for the Import window. Anything reading `$_FILES` itself puts the text through `csvTextToUtf8()` and `fgetcsv()`s it from `php://temp`, as `expenseImportRead()`, `agent/post/network_ip.php` and `agent/post/asset_interface.php` do. `escapeSql()`'s Windows-1252 fallback works on one value at a time, so it can't tell a Mac file from a Windows one. + **Schema changes require two edits in one PR:** 1. `db.sql` — so fresh installs get the new schema. diff --git a/agent/post/asset_interface.php b/agent/post/asset_interface.php index 1d4480db4..514ff6a16 100644 --- a/agent/post/asset_interface.php +++ b/agent/post/asset_interface.php @@ -351,7 +351,10 @@ if (isset($_POST['import_client_asset_interfaces_csv'])) { redirect(); } - $file = fopen($_FILES['file']['tmp_name'], 'r'); + // As UTF-8 whatever the spreadsheet saved it as + $file = fopen('php://temp', 'r+'); + fwrite($file, csvTextToUtf8((string) @file_get_contents($_FILES['file']['tmp_name']))); + rewind($file); $header = fgetcsv($file, 1000, ','); if (!is_array($header) || !in_array(count($header), [8, 9], true)) { fclose($file); diff --git a/agent/post/import.php b/agent/post/import.php index 22327decb..e928c15b9 100644 --- a/agent/post/import.php +++ b/agent/post/import.php @@ -17,7 +17,7 @@ if (isset($_POST['import_check']) || isset($_POST['import_run'])) { $answer = function (array $answer) { header('Content-Type: application/json; charset=utf-8'); - echo json_encode($answer); + echo json_encode($answer, JSON_INVALID_UTF8_SUBSTITUTE); exit; }; diff --git a/agent/post/network_ip.php b/agent/post/network_ip.php index b1960ff5e..a98a3dc7a 100644 --- a/agent/post/network_ip.php +++ b/agent/post/network_ip.php @@ -266,7 +266,10 @@ if (isset($_POST['import_network_ips_csv'])) { redirect(); } - $file = fopen($_FILES['file']['tmp_name'], 'r'); + // As UTF-8 whatever the spreadsheet saved it as + $file = fopen('php://temp', 'r+'); + fwrite($file, csvTextToUtf8((string) @file_get_contents($_FILES['file']['tmp_name']))); + rewind($file); $header = fgetcsv($file, 1000, ','); if (!is_array($header) || !in_array(count($header), [3, 5], true)) { fclose($file); diff --git a/functions/expense_import.php b/functions/expense_import.php index 0fb95ab9d..be87b5586 100644 --- a/functions/expense_import.php +++ b/functions/expense_import.php @@ -38,9 +38,9 @@ function expenseImportDateFormats() { /** * Read a statement CSV - [header (a name for each column), rows (lists of - * cells)], or null with $error. Handles a byte order mark, Windows text, - * commas, semicolons, tabs or pipes, lines before the header, and a file - * with no header at all. + * cells)], or null with $error. Handles any text the bank or spreadsheet + * saved it as (csvTextToUtf8), commas, semicolons, tabs or pipes, lines + * before the header, and a file with no header at all. */ function expenseImportRead($path, &$error = '') { $error = ''; @@ -53,10 +53,7 @@ function expenseImportRead($path, &$error = '') { $error = 'That file is too big - export a month or two at a time'; return null; } - $text = preg_replace('/^\xEF\xBB\xBF/', '', $text); - if (!mb_check_encoding($text, 'UTF-8')) { - $text = mb_convert_encoding($text, 'UTF-8', 'Windows-1252'); - } + $text = csvTextToUtf8($text); $text = str_replace(["\r\n", "\r"], "\n", $text); if (strpos($text, "\0") !== false) { $error = "That doesn't look like a CSV file - export the statement as CSV"; diff --git a/functions/import.php b/functions/import.php index 6b9fdb0e8..24d8bbd40 100644 --- a/functions/import.php +++ b/functions/import.php @@ -69,9 +69,9 @@ function importHeadingKey($heading) { /** * The uploaded file ($_FILES[$field]) - [$headings, $rows, $error]; $rows - * are [line in the file, cells]. Comma or semicolon separated, whichever its - * heading line has more of; a byte-order mark is skipped, and so is a row with - * nothing in it. + * are [line in the file, cells]. Read as UTF-8 whatever the spreadsheet saved + * it as (csvTextToUtf8). Comma, semicolon or tab separated, whichever its + * heading line has most of; a row with nothing in it is skipped. */ function importFile($field = 'file') { $upload = $_FILES[$field] ?? null; @@ -84,17 +84,23 @@ function importFile($field = 'file') { if (intval($upload['size']) > IMPORT_MAX_BYTES) { return [[], [], 'The file is over ' . (IMPORT_MAX_BYTES / 1048576) . ' MB - split it and import each part.']; } - $handle = fopen($upload['tmp_name'], 'r'); - $first = $handle ? fgets($handle) : false; - if ($first === false || trim($first) === '') { + $text = str_replace(["\r\n", "\r"], "\n", csvTextToUtf8((string) @file_get_contents($upload['tmp_name']))); + $first = strstr($text . "\n", "\n", true); + if (trim($first) === '') { return [[], [], 'The file is empty.']; } - $delimiter = substr_count($first, ';') > substr_count($first, ',') ? ';' : ','; + $delimiter = ','; + foreach ([';', "\t"] as $candidate) { + if (substr_count($first, $candidate) > substr_count($first, $delimiter)) { + $delimiter = $candidate; + } + } + $handle = fopen('php://temp', 'r+'); + fwrite($handle, $text); rewind($handle); $headings = array_map(function ($heading) { return trim((string) $heading); }, (array) fgetcsv($handle, 0, $delimiter, '"', '')); - $headings[0] = trim(preg_replace('/^\xEF\xBB\xBF/', '', $headings[0] ?? '')); $rows = []; $line = 1; while (($cells = fgetcsv($handle, 0, $delimiter, '"', '')) !== false) { @@ -118,6 +124,63 @@ function importFile($field = 'file') { return [$headings, $rows, '']; } +/** + * A CSV file's text as UTF-8, whatever the spreadsheet or bank saved it as: + * UTF-8 as it is (its byte order mark dropped), UTF-16 by its byte order mark + * (Excel's "Unicode Text"), and otherwise Windows-1252 (Excel's plain "CSV" on + * Windows, Outlook) or Mac Roman (Excel's plain "CSV" on a Mac), whichever + * shows fewer signs of a wrong reading (csvTextMisreads) - Windows-1252 when + * it's a tie. + */ +function csvTextToUtf8($text) { + $text = (string) $text; + if (strncmp($text, "\xEF\xBB\xBF", 3) === 0) { + $text = substr($text, 3); + } elseif (strncmp($text, "\xFF\xFE", 2) === 0 || strncmp($text, "\xFE\xFF", 2) === 0) { + return (string) mb_convert_encoding(substr($text, 2), 'UTF-8', $text[0] === "\xFF" ? 'UTF-16LE' : 'UTF-16BE'); + } + if (mb_check_encoding($text, 'UTF-8')) { + return $text; + } + static $mac_roman = null; + if ($mac_roman === null) { + $mac_roman = []; + foreach ([ + 0x00C4, 0x00C5, 0x00C7, 0x00C9, 0x00D1, 0x00D6, 0x00DC, 0x00E1, 0x00E0, 0x00E2, 0x00E4, 0x00E3, 0x00E5, 0x00E7, 0x00E9, 0x00E8, + 0x00EA, 0x00EB, 0x00ED, 0x00EC, 0x00EE, 0x00EF, 0x00F1, 0x00F3, 0x00F2, 0x00F4, 0x00F6, 0x00F5, 0x00FA, 0x00F9, 0x00FB, 0x00FC, + 0x2020, 0x00B0, 0x00A2, 0x00A3, 0x00A7, 0x2022, 0x00B6, 0x00DF, 0x00AE, 0x00A9, 0x2122, 0x00B4, 0x00A8, 0x2260, 0x00C6, 0x00D8, + 0x221E, 0x00B1, 0x2264, 0x2265, 0x00A5, 0x00B5, 0x2202, 0x2211, 0x220F, 0x03C0, 0x222B, 0x00AA, 0x00BA, 0x03A9, 0x00E6, 0x00F8, + 0x00BF, 0x00A1, 0x00AC, 0x221A, 0x0192, 0x2248, 0x2206, 0x00AB, 0x00BB, 0x2026, 0x00A0, 0x00C0, 0x00C3, 0x00D5, 0x0152, 0x0153, + 0x2013, 0x2014, 0x201C, 0x201D, 0x2018, 0x2019, 0x00F7, 0x25CA, 0x00FF, 0x0178, 0x2044, 0x20AC, 0x2039, 0x203A, 0xFB01, 0xFB02, + 0x2021, 0x00B7, 0x201A, 0x201E, 0x2030, 0x00C2, 0x00CA, 0x00C1, 0x00CB, 0x00C8, 0x00CD, 0x00CE, 0x00CF, 0x00CC, 0x00D3, 0x00D4, + 0xF8FF, 0x00D2, 0x00DA, 0x00DB, 0x00D9, 0x0131, 0x02C6, 0x02DC, 0x00AF, 0x02D8, 0x02D9, 0x02DA, 0x00B8, 0x02DD, 0x02DB, 0x02C7, + ] as $i => $codepoint) { + $mac_roman[chr(0x80 + $i)] = mb_chr($codepoint, 'UTF-8'); + } + } + $windows = (string) mb_convert_encoding($text, 'UTF-8', 'Windows-1252'); + $mac = strtr($text, $mac_roman); + return csvTextMisreads($mac) < csvTextMisreads($windows) ? $mac : $windows; +} + +/** + * How many signs $text shows of having been read in the wrong encoding: a + * control character (a byte Windows-1252 doesn't have), a capital in the + * middle of a word ("MŸller", "FranÁois"), symbols in the middle of a word + * ("J¸rgen", "S¿ren", "Pe–a" - but not an apostrophe, em dash, ellipsis or + * trademark, which real text has there), an opening quote or a letter Western + * words don't have right after a letter ("Zo‘", "Malmš", "Strafle"), and an + * "œ" ending a word. + */ +function csvTextMisreads($text) { + $odd_symbol = '[^\x00-\x7F\p{L}\x{A0}\x{A9}\x{AE}\x{2014}\x{2019}\x{2026}\x{2122}]'; + return intval(preg_match_all('/[\x{80}-\x{9F}]' + . '|(?<=\p{Ll})[^\x00-\x7F\P{Lu}]|(?<=\p{L})[^\x00-\x7F\P{Lu}](?=\p{Ll})' + . '|(?<=\p{L})(?!\x{2013}\p{L})' . $odd_symbol . '+(?=\p{L})|(?<=\p{Ll})\x{2013}(?=\p{Ll})' + . '|(?<=\p{L})[\x{2018}\x{201C}\x{0161}\x{017E}\x{0192}\x{02C6}\x{0131}\x{FB01}\x{FB02}]' + . '|(?<=\p{L})\x{0153}(?!\p{L})/u', (string) $text)); +} + /** Which field each of the file's columns is, by its heading - column => field key. The first column for a field takes it. */ function importAutoMap(array $def, array $headings) { $lookup = [];