From 75df17698b1ac45d6096286208e6977923f8eb21 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Thu, 15 Oct 2026 00:09:09 -0400 Subject: [PATCH] Domains makeover: rebuilt domains list with expiry pills (red expired, amber close, blue close but auto-renewing), registrar and hosts shown once per vendor with their roles, SPF/DMARC/DKIM email pills, filters for Starred, Expiring in 45 days, Expired, No auto-renew and Email gaps with counts, registrar-or-host and tag filters, search across notes, hosts and tag names, safe column sorting, open straight to a domain with ?open=ID; new domain quick look with expiry, auto-renew, registration date and status, who registers it and hosts DNS, website and email, A/NS/MX records to copy, plain-language email checks (SPF strictness and duplicates, DMARC policy, DKIM at common selectors), certificates, services, the registrar and host logins, notes, TXT records, raw WHOIS and history; tabbed add/edit form that tidies pasted addresses to the domain, checks the name as it is typed (saved as, subdomain, already on the client), auto-renew switch, star, tags, client and our own vendors as registrar and hosts, Registrar does it all; add several domains at once from a pasted list; bulk look up now, set registrar or host, tags, star and unstar; domain tags (tag type 7) with a starter pack; refresher looks up a batch of up to 50 a run, never-checked, stale and soon-to-expire first; expiry alerts skip archived domains and clients, mention auto-renew and open the domain; vendor Domains tab opens the quick look and adds a domain with that vendor as registrar, our vendors get a Client domains tab; service quick look, overview renewals and search open the domain; client portal shows days to expiry and auto-renew; more export columns and filters; demo data with auto-renew, varied DMARC and DKIM, WHOIS lines and campaign domains near expiry. Fixes lookups, edits, the refresher and API updates wiping expiry dates and records when a lookup came back empty, edits logged without a client and dropping a past expiry date, every edit running slow lookups, expiry alerts for archived domains, deleted domains left on services and certificates, bulk archive needing delete rights and list actions limited to admins, registrar and host pickers accepting another client's vendors and dropping our own on save, services linking other clients' domains, a new client's website domain not added when its expiry could not be found, the WHOIS summary cut at 254 characters, and API names, vendors and duplicates not checked. Adds functions/domain.php helpers, domain quick look and shared form, domain_check lookup; removes domain_model.php. DB 2.8.3 --- admin/database_updates/2.8.3.php | 32 ++ admin/modals/tag/tag_add.php | 2 + admin/modals/tag/tag_edit.php | 2 + admin/post/demo_data_model.php | 47 +- admin/post/starter_content_model.php | 10 +- admin/tags.php | 1 + agent/ajax.php | 55 ++- agent/domains.php | 642 ++++++++++++++----------- agent/modals/domain/domain.php | 230 +++++++++ agent/modals/domain/domain_add.php | 203 ++------ agent/modals/domain/domain_edit.php | 270 ++--------- agent/modals/domain/domain_export.php | 26 +- agent/modals/domain/domain_form.php | 298 ++++++++++++ agent/modals/service/service.php | 16 +- agent/post/client.php | 35 +- agent/post/domain.php | 647 ++++++++++++-------------- agent/post/domain_model.php | 11 - agent/post/service.php | 6 +- agent/vendor.php | 50 +- api/v1/domains/create.php | 23 +- api/v1/domains/domain_model.php | 22 +- api/v1/domains/update.php | 68 +-- client/domains.php | 12 +- cron/domain_refresher.php | 104 ++--- cron/nightly_tasks.php | 9 +- css/itflow_custom.css | 20 + db.sql | 21 + functions/client_overview.php | 4 +- functions/domain.php | 534 ++++++++++++++++++++- functions/export.php | 9 + functions/search.php | 9 +- functions/tags.php | 10 +- includes/cron_jobs.php | 2 +- 33 files changed, 2162 insertions(+), 1268 deletions(-) create mode 100644 admin/database_updates/2.8.3.php create mode 100644 agent/modals/domain/domain.php create mode 100644 agent/modals/domain/domain_form.php delete mode 100644 agent/post/domain_model.php diff --git a/admin/database_updates/2.8.3.php b/admin/database_updates/2.8.3.php new file mode 100644 index 000000000..6233d84f8 --- /dev/null +++ b/admin/database_updates/2.8.3.php @@ -0,0 +1,32 @@ + 0 AND `domain_id` IS NULL"); diff --git a/admin/modals/tag/tag_add.php b/admin/modals/tag/tag_add.php index 473f61791..9c17f5e6d 100644 --- a/admin/modals/tag/tag_add.php +++ b/admin/modals/tag/tag_add.php @@ -19,6 +19,8 @@ if (isset($_GET['type'])) { $type_display = "Asset"; } elseif ($type === 6) { $type_display = "Vendor"; + } elseif ($type === 7) { + $type_display = "Domain"; } } ob_start(); diff --git a/admin/modals/tag/tag_edit.php b/admin/modals/tag/tag_edit.php index f7cfc8a5d..48a266bb5 100644 --- a/admin/modals/tag/tag_edit.php +++ b/admin/modals/tag/tag_edit.php @@ -24,6 +24,8 @@ if ($tag_type == 1) { $tag_type_display = "Asset"; } elseif ($tag_type == 6) { $tag_type_display = "Vendor"; +} elseif ($tag_type == 7) { + $tag_type_display = "Domain"; } else { $tag_type_display = "Unknown"; } diff --git a/admin/post/demo_data_model.php b/admin/post/demo_data_model.php index c1b9ee85f..92ae28bb9 100644 --- a/admin/post/demo_data_model.php +++ b/admin/post/demo_data_model.php @@ -1283,28 +1283,63 @@ function demoBuildClient($mysqli, $profile, $index, $context, &$counts) { demoBuildNetworkIps($mysqli, $profile, $assets, $network_ids, $counts); demoBuildPatchPanel($mysqli, $profile, $assets, $network_ids, $months, $counts); - // Domain, DNS and the certificate on it + // Domain, DNS and the certificate on it. Half renew by themselves; the + // email records vary so the Email checks have something to say - DMARC + // enforced, monitoring only, or missing + $domain_auto_renew = $index % 2; + $domain_m365 = strpos($profile['mail_servers'], 'google') === false; $domain_id = starterInsert($mysqli, 'domains', [ 'domain_name' => $profile['domain'], 'domain_description' => 'Primary domain - website and email', 'domain_expire' => demoDate(-1 * (60 + ($index * 21))), + 'domain_auto_renew' => $domain_auto_renew, 'domain_ip' => '203.0.113.' . (10 + $index), - 'domain_name_servers' => 'ns1.' . $profile['dns_host'] . ', ns2.' . $profile['dns_host'], - 'domain_raw_whois' => 'Registrar: Harbour Registrar Services. Status: clientTransferProhibited. Registrant: ' . $profile['name'] . '.', - 'domain_mail_servers' => $profile['mail_servers'], + 'domain_name_servers' => 'ns1.' . $profile['dns_host'] . "\nns2." . $profile['dns_host'], + 'domain_raw_whois' => "Registrar: Harbour Registrar Services\nRegistered: " . demoDate(365 * (6 + $index % 9) + $index * 11) . "\nExpires: " . demoDate(-1 * (60 + ($index * 21))) . "\nStatus: client transfer prohibited\nNameservers: ns1." . $profile['dns_host'] . ', ns2.' . $profile['dns_host'], + 'domain_mail_servers' => '0 ' . $profile['mail_servers'], + 'domain_dmarc' => [0 => 'v=DMARC1; p=reject; rua=mailto:dmarc@' . $profile['domain'], 1 => 'v=DMARC1; p=none; rua=mailto:dmarc@' . $profile['domain'], 2 => ''][$index % 3], + 'domain_dkim' => $index % 4 === 3 ? '' : ($domain_m365 ? "selector1\nselector2" : 'google'), + 'domain_refreshed_at' => demoDateTime(1 + $index % 6, 4, 0), // These three are vendor IDs, not names - who hosts the site, who runs // DNS, and who the mail lands with 'domain_webhost' => intval($profile['build'] === 1 ? ($context['org_vendors']['Nextcloud Hosting Partner'] ?? 0) : $primary_vendor_id), 'domain_dnshost' => intval($primary_vendor_id), 'domain_mailhost' => intval($context['org_vendors']['Cascade Cloud Licensing'] ?? 0), - 'domain_txt' => 'v=spf1 include:' . $profile['dns_host'] . ' -all', - 'domain_notes' => 'Registrar login is held in the credential vault. Renewal is set to manual so it cannot lapse without a ticket.', + 'domain_txt' => 'v=spf1 include:' . $profile['dns_host'] . ' -all' . ($domain_m365 ? "\nMS=ms" . substr(demoSerial($profile['domain'], 8), 0, 8) : "\ngoogle-site-verification=" . strtolower(demoSerial($profile['domain'], 20))), + 'domain_notes' => 'Registrar login is held in the credential vault. ' . ($domain_auto_renew ? 'Auto-renew is on and charged to the card on file - check it before the card expires.' : 'Renewal is set to manual so it cannot lapse without a ticket.'), 'domain_registrar' => $primary_vendor_id, 'domain_client_id' => $client_id, 'domain_created_at' => demoMonthDateTime($months, 7, 9, 45), 'domain_accessed_at' => demoDateTime($index % 13, 15, 5), ]); + demoAttachTags($mysqli, 'domain_tags', 'domain_id', 'tag_id', $domain_id, 7, ['Primary', 'Managed DNS']); + + // Every third client also keeps a campaign domain nobody remembers - parked, + // no mail, and close to lapsing or already lapsed + if ($index % 3 === 0) { + $campaign_days = $index % 2 ? -12 : 20; + $campaign_domain_id = starterInsert($mysqli, 'domains', [ + 'domain_name' => 'get' . $profile['domain'], + 'domain_description' => 'Old campaign domain - forwards to the main site', + 'domain_expire' => demoDate(-1 * $campaign_days), + 'domain_auto_renew' => 0, + 'domain_ip' => '203.0.113.' . (10 + $index), + 'domain_name_servers' => 'ns1.' . $profile['dns_host'] . "\nns2." . $profile['dns_host'], + 'domain_txt' => 'v=spf1 -all', + 'domain_dmarc' => 'v=DMARC1; p=reject', + 'domain_raw_whois' => "Registrar: Harbour Registrar Services\nRegistered: " . demoDate(365 * 3 + $index) . "\nStatus: client transfer prohibited", + 'domain_notes' => 'Ask the client whether to keep it before it renews.', + 'domain_registrar' => $primary_vendor_id, + 'domain_dnshost' => intval($primary_vendor_id), + 'domain_client_id' => $client_id, + 'domain_created_at' => demoMonthDateTime($months, 7, 10, 5), + 'domain_refreshed_at' => demoDateTime(2 + $index % 5, 4, 0), + ]); + demoAttachTags($mysqli, 'domain_tags', 'domain_id', 'tag_id', $campaign_domain_id, 7, ['Parked', 'Marketing']); + $counts['documentation']++; + } + $certificate_id = starterInsert($mysqli, 'certificates', [ 'certificate_name' => 'www.' . $profile['domain'], 'certificate_description' => $profile['cert_issuer'] === "Let's Encrypt" ? 'Public website certificate, renewed automatically by the reverse proxy' : 'Public website certificate, renewed manually at expiry', diff --git a/admin/post/starter_content_model.php b/admin/post/starter_content_model.php index e578e67bb..849732924 100644 --- a/admin/post/starter_content_model.php +++ b/admin/post/starter_content_model.php @@ -30,7 +30,7 @@ function starterContentPacks() { 'tags' => [ 'label' => 'Tags', 'icon' => 'fa-tags', - 'description' => 'Client, location, contact, credential, asset and vendor tags.', + 'description' => 'Client, location, contact, credential, asset, vendor and domain tags.', ], 'ticket_templates' => [ 'label' => 'Ticket Templates', @@ -675,6 +675,14 @@ function starterContentTags() { [6, 'Hosting', '#17a2b8', 'globe'], [6, 'Professional Services', '#343a40', 'briefcase'], [6, 'Authorised Contacts Only', '#d81b60', 'user-lock'], + + // Domain + [7, 'Primary', '#007bff', 'star'], + [7, 'Client-owned', '#6f42c1', 'user-tie'], + [7, 'Managed DNS', '#20c997', 'sitemap'], + [7, 'Parked', '#adb5bd', 'parking'], + [7, 'Marketing', '#fd7e14', 'bullhorn'], + [7, 'Do Not Renew', '#dc3545', 'ban'], ]; return $tags; diff --git a/admin/tags.php b/admin/tags.php index 8d2320d86..7b5826a98 100644 --- a/admin/tags.php +++ b/admin/tags.php @@ -20,6 +20,7 @@ $tag_types = [ 4 => ['label' => 'Credential', 'icon' => 'fa-key'], 5 => ['label' => 'Asset', 'icon' => 'fa-desktop'], 6 => ['label' => 'Vendor', 'icon' => 'fa-building'], + 7 => ['label' => 'Domain', 'icon' => 'fa-globe'], ]; // Label for the selected type diff --git a/agent/ajax.php b/agent/ajax.php index fa9921bb2..bba15665c 100644 --- a/agent/ajax.php +++ b/agent/ajax.php @@ -1780,24 +1780,63 @@ if (isset($_GET['ai_ticket_summary'])) { } // Stops people trying to use sub-domains in the domains tracker -if (isset($_GET['apex_domain_check'])) { +/* + * The domain name in a New / Edit Domain form, checked as it is typed: what it + * is saved as, whether DNS answers for it, whether it looks like a subdomain + * of one that does, and whether the client has it already. + */ +if (isset($_GET['domain_check'])) { enforceUserPermission('module_support', 2); - $domain = escapeSql($_GET['domain']); + $input = (string) ($_GET['domain'] ?? ''); + $name = domainNormalizeName($input); + $check_client_id = intval($_GET['client_id'] ?? 0); + $check_domain_id = intval($_GET['domain_id'] ?? 0); + $response = ['state' => '', 'message' => '', 'name' => $name]; - $response['message'] = ""; // default + if (trim($input) === '') { + echo json_encode($response); + exit; + } + if ($name === '') { + echo json_encode(['state' => 'bad', 'message' => "That isn't a domain name - something like example.com.", 'name' => '']); + exit; + } - if (strlen($domain) >= 4) { + $saved_as = strcasecmp(trim($input), $name) !== 0 ? "Saved as $name. " : ''; - // SOA record check - // This isn't 100%, as sub-domains can have their own SOA but will capture 99% - if (!checkdnsrr($domain, 'SOA')) { - $response['message'] = " Domain name is invalid."; + // Already on this client? + if ($check_client_id) { + $client_id = $check_client_id; + enforceClientAccess(); + $name_sql = escapeSql($name); + if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM domains WHERE domain_name = '$name_sql' AND domain_client_id = $check_client_id AND domain_id <> $check_domain_id LIMIT 1"))) { + echo json_encode(['state' => 'bad', 'message' => $saved_as . "$name is already on this client.", 'name' => $name]); + exit; } + } + if (@checkdnsrr($name, 'SOA')) { + $response = ['state' => 'ok', 'message' => $saved_as . 'Found in DNS - its records and expiry are looked up when it is saved.', 'name' => $name]; + } else { + // Nothing for the name itself - is it a subdomain of one that does answer? + $parts = explode('.', $name); + $parent = ''; + while (count($parts) > 2) { + array_shift($parts); + $candidate = implode('.', $parts); + if (@checkdnsrr($candidate, 'SOA')) { + $parent = $candidate; + break; + } + } + $response = $parent + ? ['state' => 'warn', 'message' => $saved_as . "That looks like a subdomain of $parent - add $parent instead, unless it is registered on its own.", 'name' => $name] + : ['state' => 'warn', 'message' => $saved_as . "Nothing answers for it in DNS yet - check the spelling. It can still be saved.", 'name' => $name]; } echo json_encode($response); + exit; } // Get internal users/techs diff --git a/agent/domains.php b/agent/domains.php index 5af3510c0..962656db1 100644 --- a/agent/domains.php +++ b/agent/domains.php @@ -1,5 +1,13 @@ ['label' => 'All', 'where' => ''], + 'starred' => ['label' => 'Starred', 'icon' => 'fa-star', 'where' => 'domains.domain_favorite = 1'], + 'soon' => ['label' => "Expiring in $soon_days days", 'icon' => 'fa-hourglass-half', 'where' => "domains.domain_expire BETWEEN CURDATE() AND CURDATE() + INTERVAL $soon_days DAY"], + 'expired' => ['label' => 'Expired', 'icon' => 'fa-calendar-times', 'where' => 'domains.domain_expire < CURDATE()'], + 'noauto' => ['label' => 'No auto-renew', 'icon' => 'fa-hand-paper', 'where' => 'domains.domain_auto_renew = 0'], + 'mail' => ['label' => 'Email gaps', 'icon' => 'fa-envelope-open-text', 'where' => domainMailGapSql()], +]; +$show = isset($shows[$_GET['show'] ?? '']) ? ($_GET['show'] ?? '') : ''; +$show_query = $shows[$show]['where'] ? 'AND ' . $shows[$show]['where'] : ''; + +$expire_days = $_GET['expire_days'] ?? ''; +$expire_query = ''; +if ($expire_days === 'expired') { + $expire_query = 'AND domains.domain_expire < CURDATE()'; +} elseif (intval($expire_days) > 0) { + $expire_query = 'AND domains.domain_expire BETWEEN CURDATE() AND CURDATE() + INTERVAL ' . intval($expire_days) . ' DAY'; } -$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS domains.*, clients.*, - registrar.vendor_id AS registrar_id, - registrar.vendor_name AS registrar_name, - dnshost.vendor_id AS dnshost_id, - dnshost.vendor_name AS dnshost_name, - mailhost.vendor_id AS mailhost_id, - mailhost.vendor_name AS mailhost_name, - webhost.vendor_id AS webhost_id, - webhost.vendor_name AS webhost_name - FROM domains - LEFT JOIN clients ON client_id = domain_client_id - LEFT JOIN vendors AS registrar ON domains.domain_registrar = registrar.vendor_id - LEFT JOIN vendors AS dnshost ON domains.domain_dnshost = dnshost.vendor_id - LEFT JOIN vendors AS mailhost ON domains.domain_mailhost = mailhost.vendor_id - LEFT JOIN vendors AS webhost ON domains.domain_webhost = webhost.vendor_id - WHERE (domains.domain_name LIKE '%$q%' OR domains.domain_description LIKE '%$q%' OR registrar.vendor_name LIKE '%$q%' OR dnshost.vendor_name LIKE '%$q%' OR mailhost.vendor_name LIKE '%$q%' OR webhost.vendor_name LIKE '%$q%' OR client_name LIKE '%$q%') - AND $archive_query - " . clientScopeSql('domain_client_id') . " - $client_query - $expire_query - ORDER BY $sort $order LIMIT $record_from, $record_to"); +// Only these sort - filter_header.php will hand through any lowercase word, and +// an unknown column takes the page down with a mysqli exception +$sortable_columns = ['domain_name' => 'domains.domain_name', 'domain_expire' => 'domains.domain_expire', 'registrar_name' => 'registrar.vendor_name', + 'client_name' => 'client_name', 'domain_created_at' => 'domains.domain_created_at', 'domain_refreshed_at' => 'domains.domain_refreshed_at']; +if (!isset($sortable_columns[$sort])) { + $sort = 'domain_name'; +} +// Domains without an expiry go last whichever way the expiry is sorted +$sort_sql = ($sort === 'domain_expire' ? 'domains.domain_expire IS NULL, ' : '') . $sortable_columns[$sort] . " $order"; + +[$domain_columns, $domain_joins] = domainSelectSql(); +$search_query = "AND (domains.domain_name LIKE '%$q%' OR domains.domain_description LIKE '%$q%' OR domains.domain_notes LIKE '%$q%' + OR registrar.vendor_name LIKE '%$q%' OR dnshost.vendor_name LIKE '%$q%' OR mailhost.vendor_name LIKE '%$q%' OR webhost.vendor_name LIKE '%$q%' OR client_name LIKE '%$q%' + OR domains.domain_id IN (SELECT domain_id FROM domain_tags JOIN tags USING (tag_id) WHERE tag_name LIKE '%$q%'))"; +$scope_query = clientScopeSql('domain_client_id'); +$filters = "$archive_query $tag_query $vendor_query $search_query $expire_query $scope_query $client_query"; + +$sql = mysqli_query($mysqli, "SELECT SQL_CALC_FOUND_ROWS $domain_columns + FROM domains $domain_joins + WHERE $filters $show_query + ORDER BY domains.domain_favorite DESC, $sort_sql, domains.domain_name ASC LIMIT $record_from, $record_to"); $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); +$domains = []; +while ($row = mysqli_fetch_assoc($sql)) { + $domains[intval($row['domain_id'])] = $row; +} +$domains_tags = tagsForRecords('domain', array_keys($domains)); + +// How many of each, for the pills - everything in scope, before the pill itself +$count_sql = []; +foreach ($shows as $key => $s) { + $count_sql[] = $key === '' ? 'COUNT(*)' : "COALESCE(SUM({$s['where']}), 0)"; +} +$row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT " . implode(', ', $count_sql) . " FROM domains $domain_joins WHERE $filters")); +$counts = []; +foreach (array_keys($shows) as $i => $key) { + $counts[$key] = intval($row[$i]); +} + +$filter_url = function ($changes) { + $params = array_merge($_GET, $changes); + unset($params['page']); + return '?' . http_build_query(array_filter($params, function ($v) { return $v !== '' && $v !== null; })); +}; + +// Vendors for the filter - the ones registering or hosting a domain in this scope +$sql_vendors_filter = mysqli_query($mysqli, "SELECT DISTINCT vendor_id, vendor_name, vendor_description, vendor_client_id FROM vendors + JOIN domains ON vendor_id IN (domain_registrar, domain_dnshost, domain_webhost, domain_mailhost) + LEFT JOIN clients ON client_id = domain_client_id + WHERE $archive_query $scope_query $client_query + ORDER BY vendor_name ASC"); + +// Vendors the bulk "set registrar or host" offers - the client's and ours, or only ours across clients +$bulk_vendor_options = $can_edit ? domainVendorChoices($client_url ? $client_id : 0) : []; + ?>

Domains

+
- + + + 0) { ?> - - +
@@ -112,275 +165,262 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); +
-
+
- - + +
- +
+ +
+
+ +
-
-
- + + - - - - -
+ SELECT DISTINCT client_id, client_name, client_abbreviation + FROM clients + JOIN domains ON domain_client_id = client_id + WHERE $archive_query + " . clientScopeSql('clients.client_id') . " + ORDER BY client_name ASC + "); + while ($row = mysqli_fetch_assoc($sql_clients_filter)) { + $client_id_filter = intval($row['client_id']); ?> + + +
- -
-
- -
-
- - -
- - -
-
- "> - Archived +
+
+ + Archived - -
-
-
- -
- - - + +
+
+ + +
+ +
+
+
+ + + + + + + + + 'That domain no longer exists.']); + exit; +} +$client_id = intval($domain['domain_client_id']); +enforceClientAccess(); + +// When it was last looked at - kept off the updated date, which the refresher uses +mysqli_query($mysqli, "UPDATE domains SET domain_accessed_at = NOW(), domain_updated_at = domain_updated_at WHERE domain_id = $domain_id"); + +$domain_name = escapeHtml($domain['domain_name']); +$domain_archived = !empty($domain['domain_archived_at']); +$can_edit = domainCan(2) && !$domain_archived; +$expiry = domainExpiry($domain['domain_expire'], $domain['domain_auto_renew']); +$facts = domainRegistrationFacts($domain['domain_raw_whois']); +$mail_checks = domainMailChecks($domain); +$certificates = domainCertificates($domain); +$services = domainServices($domain_id); +$logins = domainLogins($domain); +$history = domainHistory($domain_id, 15); +$tags = tagsForRecord('domain', $domain_id); +$txt_records = array_values(array_filter(array_map('trim', preg_split('/\r?\n/', (string) $domain['domain_txt'])), 'strlen')); + +// One record line with its copy button +$record = function ($value) { + $value = trim((string) $value); + return '
' . escapeHtml($value) . '' + . '
'; +}; +$records = function ($text) use ($record) { + $lines = domainLines($text); + return $lines ? implode('', array_map($record, $lines)) : 'None'; +}; + +ob_start(); + +?> + + + + + + + +
+ + + -
- - 'That domain no longer exists.']); + exit; +} +$client_id = intval($domain['domain_client_id']); enforceClientAccess(); +$domain_form_mode = 'edit'; +$domain_name = escapeHtml($domain['domain_name']); +$domain_description = escapeHtml($domain['domain_description']); +$domain_expire = escapeHtml($domain['domain_expire']); +$domain_notes = escapeHtml($domain['domain_notes']); +$domain_favorite = intval($domain['domain_favorite']); +$domain_auto_renew = intval($domain['domain_auto_renew']); +$domain_tag_ids = array_map('intval', array_column(tagsForRecord('domain', $domain_id), 'tag_id')); +$domain_vendor_ids = []; +foreach (DOMAIN_ROLES as $role => $info) { + $domain_vendor_ids[$role] = intval($domain[$info['column']]); +} + ob_start(); ?> -
+ @@ -86,6 +90,26 @@ ob_start();
+
+ +
+ + +
+
+ + + +

Only domains registered or hosted with

+ +
diff --git a/agent/modals/domain/domain_form.php b/agent/modals/domain/domain_form.php new file mode 100644 index 000000000..e92feb432 --- /dev/null +++ b/agent/modals/domain/domain_form.php @@ -0,0 +1,298 @@ + vendor id) before + * including this. Posts what domainFormSet() (functions/domain.php) reads. + * + * Tabs: Domain (the name, checked as it is typed - or several pasted at once + * when adding - what it is for, the star, the expiry and auto-renew), Who + * (the registrar and who hosts DNS, the website and email), Details (tags) + * and Notes. The records themselves are looked up, never typed, and show in + * the domain's quick look. + * + * Should not be accessed directly. + */ + +isset($mysqli) || die("Direct file access is not allowed"); + +$client_options = $vendor_options = []; +if ($client_id) { + $vendor_options = domainVendorChoices($client_id, array_values($domain_vendor_ids)); + $client_name_for_vendors = getFieldById('clients', $client_id, 'client_name'); +} else { + $sql = mysqli_query($mysqli, "SELECT client_id, client_name, client_abbreviation FROM clients WHERE client_archived_at IS NULL " . clientScopeSql('clients.client_id') . " ORDER BY client_name ASC"); + while ($row = mysqli_fetch_assoc($sql)) { + $client_options[] = $row; + } +} + +$sql_tags_select = mysqli_query($mysqli, "SELECT tag_id, tag_name, tag_color, tag_icon FROM tags WHERE tag_type = 7 ORDER BY tag_name ASC"); + +$form_id = 'domainForm' . ($domain_form_mode === 'edit' ? $domain_id : 'New'); + +?> + + + +
+ + +
+
+ +
+ +
+ + +
+
Set the registrar and hosts from the domain once it's saved.
+
+ + +
+
+ + + + +
+
+ +
+ +
+ + > +
+
Paste a web address if that is easier - it is tidied to the domain.
+
+
+
+ > + +
+
+ +
+ + +
One per line - or separated by spaces or commas. Each is looked up as it is added; ones already on the client are skipped. The registrar, hosts, auto-renew and tags you set here go on all of them.
+
+ +
+ +
+ + +
+
+
+ +
+ + +
+
Leave it empty - it is looked up from the registry. Set it by hand for registries that don't publish it.
+
+
+
+ > + +
+
+
+
+ + +
+ +
+ $info) { + $picked = intval($domain_vendor_ids[$role] ?? 0); ?> +
+ +
+ + +
+
+ +
+ + Someone missing? Add them as a vendor - the client's own, or one of ours if we host it. +
+
+ +
Pick the client first - the registrar and hosts are their vendors, or ours.
+ +
+ + +
+ + +
+ + + + + +
+ +

Domain ID

+ +
+ + +
+ + +
+ +
+ + diff --git a/agent/modals/service/service.php b/agent/modals/service/service.php index 20ed88f3b..aa9538ee4 100644 --- a/agent/modals/service/service.php +++ b/agent/modals/service/service.php @@ -54,9 +54,10 @@ $service_credentials = lookupUserPermission('module_credential') >= 1 // Associated Domains $sql_domains = mysqli_query( $mysqli, - "SELECT domain_name FROM service_domains - LEFT JOIN domains ON service_domains.domain_id = domains.domain_id - WHERE service_id = $service_id" + "SELECT domains.domain_id, domain_name, domain_expire, domain_auto_renew, domain_archived_at FROM service_domains + JOIN domains ON service_domains.domain_id = domains.domain_id + WHERE service_id = $service_id + ORDER BY domain_name" ); // Associated Certificates @@ -179,13 +180,12 @@ ob_start(); 0) { - echo "
Domains
    "; + echo "
    Domains
      "; mysqli_data_seek($sql_domains, 0); while ($row = mysqli_fetch_assoc($sql_domains)) { - if (!empty($row['domain_name'])) { - $domain_name = escapeHtml($row['domain_name']); - echo "
    • $domain_name
    • "; - } + // Each opens its quick look, with when it expires + echo '
    • ' . domainLink($row['domain_id'], $row['domain_name'], ['archived' => !empty($row['domain_archived_at'])]) + . domainExpiryPill(domainExpiry($row['domain_expire'], $row['domain_auto_renew']), true) . '
    • '; } echo "
    "; } diff --git a/agent/post/client.php b/agent/post/client.php index bbb0b4650..221f5f39b 100644 --- a/agent/post/client.php +++ b/agent/post/client.php @@ -80,34 +80,17 @@ if (isset($_POST['add_client'])) { } } - // Create domain and SSL certificate - if (!empty($website) && filter_var($website, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) { - $expire = getDomainExpirationDate($website); - $records = getDnsRecords($website); - $a = escapeSql($records['a']); - $ns = escapeSql($records['ns']); - $mx = escapeSql($records['mx']); - $whois = escapeSql($records['whois']); - - try { - mysqli_query($mysqli, "INSERT INTO domains SET domain_name = '$website', domain_registrar = 0, domain_webhost = 0, domain_expire = '$expire', domain_ip = '$a', domain_name_servers = '$ns', domain_mail_servers = '$mx', domain_raw_whois = '$whois', domain_client_id = $client_id"); - $extended_log_description .= ", domain $website added"; - } catch (Exception $e) { - $extended_log_description .= ", domain not added"; - logApp("Client", "warning", "Failed to add domain $website during client creation"); - } - + // Create domain and SSL certificate - the website's domain, tidied, looked up + // like any other; one whose lookup finds nothing is still added, without records + $website_domain = domainNormalizeName($website); + if ($website_domain !== '') { + $website_domain_sql = escapeSql($website_domain); + mysqli_query($mysqli, "INSERT INTO domains SET domain_name = '$website_domain_sql', domain_description = 'Website', domain_client_id = $client_id"); $domain_id = mysqli_insert_id($mysqli); - $certificate = getSslCertificate($website); + $extended_log_description .= ", domain $website_domain_sql added"; - if ($certificate['success'] == "TRUE") { - $expire = escapeSql($certificate['expire']); - $issued_by = escapeSql($certificate['issued_by']); - $public_key = escapeSql($certificate['public_key']); - - mysqli_query($mysqli, "INSERT INTO certificates SET certificate_name = '$website', certificate_domain = '$website', certificate_issued_by = '$issued_by', certificate_expire = '$expire', certificate_public_key = '$public_key', certificate_domain_id = $domain_id, certificate_client_id = $client_id"); - - $extended_log_description .= ", SSL certificate $website added"; + if (domainApplyLookup($domain_id, domainLookup($website_domain)) && domainAddCertificate($domain_id, $website_domain, $client_id)) { + $extended_log_description .= ", SSL certificate $website_domain_sql added"; } } diff --git a/agent/post/domain.php b/agent/post/domain.php index 5b3e32c3c..3527a8042 100644 --- a/agent/post/domain.php +++ b/agent/post/domain.php @@ -2,63 +2,153 @@ /* * ITFlow - GET/POST request handler for client domains + * + * Every handler checks the support module and the domain's own client; the + * registrar and hosts a form names must be the client's vendors or ours. + * Lookups (DNS, registration data, expiry) go through domainLookup() in + * functions/domain.php, and a lookup that finds nothing changes nothing - + * a network blip must not wipe a domain's records or its expiry date. */ defined('FROM_POST_HANDLER') || die("Direct file access is not allowed"); +/** The domain a request names, after the module and client checks - or back with an error if it is gone. */ +function domainForRequest($domain_id, $level) { + global $client_id; + enforceUserPermission('module_support', $level); + $row = domainRow($domain_id); + if (!$row) { + flashAlert('That domain no longer exists.', 'error'); + redirect(); + } + $client_id = intval($row['domain_client_id']); + enforceClientAccess(); + return $row; +} + +/** The domains a bulk action names that this agent may act on - [id => row]. */ +function domainsForBulk($level) { + global $client_id; + enforceUserPermission('module_support', $level); + $rows = []; + foreach (array_unique(array_map('intval', (array) ($_POST['domain_ids'] ?? []))) as $domain_id) { + $row = domainRow($domain_id); + if (!$row) { + continue; + } + $client_id = intval($row['domain_client_id']); + enforceClientAccess(); + $rows[$domain_id] = $row; + } + return $rows; +} + +/** Look a domain up and save what came back, with its history. True when something answered. */ +function domainRefresh($row) { + $domain_id = intval($row['domain_id']); + $lookup = domainLookup($row['domain_name']); + if (!$lookup) { + return false; + } + $before = domainHistorySnapshot($domain_id); + domainApplyLookup($domain_id, $lookup); + domainWriteHistory($domain_id, $before, domainHistorySnapshot($domain_id)); + return true; +} + if (isset($_POST['add_domain'])) { validateCSRFToken(); enforceUserPermission('module_support', 2); - require_once 'domain_model.php'; - $extended_log_description = ''; - $client_id = intval($_POST['client_id']); + $client_id = intval($_POST['client_id'] ?? 0); enforceClientAccess(); - // Set/check/lookup expiry date - if (strtotime($expire)) { - $expire = "'" . $expire . "'"; + if (!$client_id || !getFieldById('clients', $client_id, 'client_name')) { + flashAlert('Pick the client this domain is for.', 'error'); + redirect(); } - else { - $expire = getDomainExpirationDate($name); - if (strtotime($expire)) { - $expire = "'" . $expire . "'"; - } else { - $expire = 'NULL'; + + // Several at once - a pasted list, one per line (or separated by spaces or commas) + $names_input = trim((string) ($_POST['names'] ?? '')); + if ($names_input !== '') { + + set_time_limit(0); + + $added = []; + $skipped_invalid = $skipped_existing = 0; + foreach (array_unique(array_filter(preg_split('/[\s,;]+/', $names_input), 'strlen')) as $input) { + $post = $_POST; + $post['name'] = $input; + $post['expire'] = ''; + $form = domainFormSet($post, $client_id, 0, $error); + if ($form === null) { + if (domainNormalizeName($input) === '') { + $skipped_invalid++; + } else { + $skipped_existing++; + } + continue; + } + if (isset($added[$form['name']])) { + continue; + } + mysqli_query($mysqli, "INSERT INTO domains SET {$form['set']}, domain_client_id = $client_id"); + $domain_id = mysqli_insert_id($mysqli); + domainSetTags($domain_id, $_POST['tags'] ?? []); + $added[$form['name']] = $domain_id; + logAudit("Domain", "Create", "$session_name created domain " . escapeSql($form['name']), $client_id, $domain_id); } + + // Look up what there is time for now; the refresher takes the rest first on its next run + $looked_up = 0; + $started = time(); + foreach ($added as $name => $domain_id) { + if (time() - $started > 20) { + break; + } + if (domainApplyLookup($domain_id, domainLookup($name))) { + $looked_up++; + } + } + + $count = count($added); + $message = "$count domain" . ($count === 1 ? '' : 's') . " added"; + if ($count) { + $message .= $looked_up === $count ? ' and looked up' : ", $looked_up looked up now - the rest are checked on the refresher's next run"; + } + if ($skipped_existing) { + $message .= ", $skipped_existing already on this client"; + } + if ($skipped_invalid) { + $message .= ", $skipped_invalid not domain names"; + } + logAudit("Domain", "Bulk Create", "$session_name added $count domain(s)", $client_id); + flashAlert($message, $count ? 'success' : 'error'); + redirect(); } - // NS, MX, A and WHOIS records/data - $records = getDnsRecords($name); - $a = escapeSql($records['a']); - $ns = escapeSql($records['ns']); - $mx = escapeSql($records['mx']); - $txt = escapeSql($records['txt']); - $whois = escapeSql($records['whois']); + $form = domainFormSet($_POST, $client_id, 0, $error); + if ($form === null) { + flashAlert($error, 'error'); + redirect(); + } - // Add domain record - mysqli_query($mysqli,"INSERT INTO domains SET domain_name = '$name', domain_description = '$description', domain_registrar = $registrar, domain_webhost = $webhost, domain_dnshost = $dnshost, domain_mailhost = $mailhost, domain_expire = $expire, domain_ip = '$a', domain_name_servers = '$ns', domain_mail_servers = '$mx', domain_txt = '$txt', domain_raw_whois = '$whois', domain_notes = '$notes', domain_client_id = $client_id"); - - // Get inserted ID (for linking certificate, if exists) + mysqli_query($mysqli, "INSERT INTO domains SET {$form['set']}, domain_client_id = $client_id"); $domain_id = mysqli_insert_id($mysqli); - // Get SSL cert for domain (if exists) - $certificate = getSslCertificate($name); - if ($certificate['success'] == "TRUE") { - $expire = escapeSql($certificate['expire']); - $issued_by = escapeSql($certificate['issued_by']); - $public_key = escapeSql($certificate['public_key']); + domainSetTags($domain_id, $_POST['tags'] ?? []); - mysqli_query($mysqli,"INSERT INTO certificates SET certificate_name = '$name', certificate_domain = '$name', certificate_issued_by = '$issued_by', certificate_expire = '$expire', certificate_public_key = '$public_key', certificate_domain_id = $domain_id, certificate_client_id = $client_id"); - $extended_log_description = ', with associated SSL cert'; - } + // Its records, registration and expiry - and the certificate on its website + $found = domainApplyLookup($domain_id, domainLookup($form['name'])); + $with_certificate = $found && domainAddCertificate($domain_id, $form['name'], $client_id); - logAudit("Domain", "Create", "$session_name created domain $name$extended_log_description", $client_id, $domain_id); + $name = $form['name']; + logAudit("Domain", "Create", "$session_name created domain " . escapeSql($name) . ($with_certificate ? ', with its SSL certificate' : ''), $client_id, $domain_id); - flashAlert("Domain $name created"); + flashAlert("Domain $name created" . ($found ? ($with_certificate ? ', with its SSL certificate' : '') : ' - nothing answered for it in DNS, so check the name'), $found ? 'success' : 'warning'); redirect(); @@ -68,89 +158,35 @@ if (isset($_POST['edit_domain'])) { validateCSRFToken(); - enforceUserPermission('module_support', 2); + $row = domainForRequest($_POST['domain_id'] ?? 0, 2); + $domain_id = intval($row['domain_id']); - require_once 'domain_model.php'; - - $domain_id = intval($_POST['domain_id']); - - $client_id = intval(getFieldById('domains', $domain_id, 'domain_client_id')); - - enforceClientAccess(); - - // Set/check/lookup expiry date - if (strtotime($expire) && (new DateTime($expire)) > (new DateTime())) { - $expire = "'" . $expire . "'"; - - } else { - $expire = getDomainExpirationDate($name); - if (strtotime($expire)) { - $expire = "'" . $expire . "'"; - } else { - $expire = 'NULL'; - } + $form = domainFormSet($_POST, $client_id, $domain_id, $error); + if ($form === null) { + flashAlert($error, 'error'); + redirect(); } - $client_id = intval($_POST['client_id']); + $before = domainHistorySnapshot($domain_id); - // Update NS, MX, A and WHOIS records/data - $records = getDnsRecords($name); - $a = escapeSql($records['a']); - $ns = escapeSql($records['ns']); - $mx = escapeSql($records['mx']); - $txt = escapeSql($records['txt']); - $whois = escapeSql($records['whois']); + mysqli_query($mysqli, "UPDATE domains SET {$form['set']} WHERE domain_id = $domain_id"); - // Current domain info - $original_domain_info = mysqli_fetch_assoc(mysqli_query($mysqli," - SELECT - domains.*, - registrar.vendor_name AS registrar_name, - dnshost.vendor_name AS dnshost_name, - mailhost.vendor_name AS mailhost_name, - webhost.vendor_name AS webhost_name - FROM domains - LEFT JOIN vendors AS registrar ON domains.domain_registrar = registrar.vendor_id - LEFT JOIN vendors AS dnshost ON domains.domain_dnshost = dnshost.vendor_id - LEFT JOIN vendors AS mailhost ON domains.domain_mailhost = mailhost.vendor_id - LEFT JOIN vendors AS webhost ON domains.domain_webhost = webhost.vendor_id - WHERE domain_id = $domain_id - ")); - - // Update domain - mysqli_query($mysqli,"UPDATE domains SET domain_name = '$name', domain_description = '$description', domain_registrar = $registrar, domain_webhost = $webhost, domain_dnshost = $dnshost, domain_mailhost = $mailhost, domain_expire = $expire, domain_ip = '$a', domain_name_servers = '$ns', domain_mail_servers = '$mx', domain_txt = '$txt', domain_raw_whois = '$whois', domain_notes = '$notes' WHERE domain_id = $domain_id"); - - // Fetch updated info - $new_domain_info = mysqli_fetch_assoc(mysqli_query($mysqli," - SELECT - domains.*, - registrar.vendor_name AS registrar_name, - dnshost.vendor_name AS dnshost_name, - mailhost.vendor_name AS mailhost_name, - webhost.vendor_name AS webhost_name - FROM domains - LEFT JOIN vendors AS registrar ON domains.domain_registrar = registrar.vendor_id - LEFT JOIN vendors AS dnshost ON domains.domain_dnshost = dnshost.vendor_id - LEFT JOIN vendors AS mailhost ON domains.domain_mailhost = mailhost.vendor_id - LEFT JOIN vendors AS webhost ON domains.domain_webhost = webhost.vendor_id - WHERE domain_id = $domain_id - ")); - - // Compare/log changes - $ignored_columns = ["domain_updated_at", "domain_accessed_at", "domain_registrar", "domain_webhost", "domain_dnshost", "domain_mailhost"]; - foreach ($original_domain_info as $column => $old_value) { - $new_value = $new_domain_info[$column]; - if ($old_value != $new_value && !in_array($column, $ignored_columns)) { - $column = escapeSql($column); - $old_value = escapeSql($old_value); - $new_value = escapeSql($new_value); - mysqli_query($mysqli,"INSERT INTO domain_history SET domain_history_column = '$column', domain_history_old_value = '$old_value', domain_history_new_value = '$new_value', domain_history_domain_id = $domain_id"); - } + // Only a form that showed the tags changes them + if (isset($_POST['tags_form'])) { + domainSetTags($domain_id, $_POST['tags'] ?? []); } - logAudit("Domain", "Edit", "$session_name edited domain $name", $client_id, $domain_id); + // A new name is a new domain to look up; otherwise saving stays quick + if ($form['name'] !== $row['domain_name']) { + domainApplyLookup($domain_id, domainLookup($form['name'])); + } - flashAlert("Domain $name edited"); + domainWriteHistory($domain_id, $before, domainHistorySnapshot($domain_id)); + + $name = $form['name']; + logAudit("Domain", "Edit", "$session_name edited domain " . escapeSql($name), $client_id, $domain_id); + + flashAlert("Domain $name updated"); redirect(); @@ -160,39 +196,34 @@ if (isset($_GET['refresh_domain'])) { validateCSRFToken(); - enforceUserPermission('module_support', 2); + $row = domainForRequest($_GET['refresh_domain'], 2); + $domain_id = intval($row['domain_id']); + $name = $row['domain_name']; - $domain_id = intval($_GET['refresh_domain']); - - // Get Name and Client ID for logging and alert message - $sql = mysqli_query($mysqli,"SELECT domain_name, domain_client_id FROM domains WHERE domain_id = $domain_id"); - $row = mysqli_fetch_assoc($sql); - $domain_name = escapeSql($row['domain_name']); - $client_id = intval($row['domain_client_id']); - - enforceClientAccess(); - - // Lookup expiry date - $expire = getDomainExpirationDate($domain_name); - if (strtotime($expire)) { - $expire = "'" . $expire . "'"; - } else { - $expire = 'NULL'; + if (!domainRefresh($row)) { + flashAlert("Nothing answered for $name in DNS - nothing was changed. Check the name, or whether it has lapsed.", 'error'); + redirect(); } - // NS, MX, A and WHOIS records/data - $records = getDnsRecords($domain_name); - $a = escapeSql($records['a']); - $ns = escapeSql($records['ns']); - $mx = escapeSql($records['mx']); - $txt = escapeSql($records['txt']); - $whois = escapeSql($records['whois']); + logAudit("Domain", "Refresh", "$session_name looked up domain " . escapeSql($name), $client_id, $domain_id); - mysqli_query($mysqli,"UPDATE domains SET domain_expire = $expire, domain_ip = '$a', domain_name_servers = '$ns', domain_mail_servers = '$mx', domain_txt = '$txt', domain_raw_whois = '$whois' WHERE domain_id = $domain_id"); + flashAlert("Looked up $name"); - logAudit("Domain", "Refresh", "$session_name refreshed records for domain $domain_name", $client_id, $domain_id); + redirect(); - flashAlert("Refreshed records for $domain_name"); +} + +if (isset($_GET['favorite_domain']) || isset($_GET['unfavorite_domain'])) { + + validateCSRFToken(); + + $favorite = isset($_GET['favorite_domain']) ? 1 : 0; + $row = domainForRequest($favorite ? $_GET['favorite_domain'] : $_GET['unfavorite_domain'], 2); + $domain_id = intval($row['domain_id']); + + mysqli_query($mysqli, "UPDATE domains SET domain_favorite = $favorite WHERE domain_id = $domain_id"); + + logAudit("Domain", "Edit", "$session_name " . ($favorite ? 'starred' : 'unstarred') . " domain " . escapeSql($row['domain_name']), $client_id, $domain_id); redirect(); @@ -202,49 +233,31 @@ if (isset($_GET['archive_domain'])) { validateCSRFToken(); - enforceUserPermission('module_support', 2); + $row = domainForRequest($_GET['archive_domain'], 2); + $domain_id = intval($row['domain_id']); - $domain_id = intval($_GET['archive_domain']); + mysqli_query($mysqli, "UPDATE domains SET domain_archived_at = NOW() WHERE domain_id = $domain_id"); - //Get domain Name - $sql = mysqli_query($mysqli,"SELECT domain_client_id, domain_name FROM domains WHERE domain_id = $domain_id"); - $row = mysqli_fetch_assoc($sql); - $domain_name = escapeSql($row['domain_name']); - $client_id = intval($row['domain_client_id']); + logAudit("Domain", "Archive", "$session_name archived domain " . escapeSql($row['domain_name']), $client_id, $domain_id); - enforceClientAccess(); - - mysqli_query($mysqli,"UPDATE domains SET domain_archived_at = NOW() WHERE domain_id = $domain_id"); - - logAudit("Domain", "Archive", "$session_name archived domain $domain_name", $client_id, $domain_id); - - flashAlert("Domain $domain_name archived", 'error'); + flashAlert("Domain {$row['domain_name']} archived", 'error'); redirect(); } -if(isset($_GET['restore_domain'])){ +if (isset($_GET['restore_domain'])) { validateCSRFToken(); - enforceUserPermission('module_support', 2); + $row = domainForRequest($_GET['restore_domain'], 2); + $domain_id = intval($row['domain_id']); - $domain_id = intval($_GET['restore_domain']); + mysqli_query($mysqli, "UPDATE domains SET domain_archived_at = NULL WHERE domain_id = $domain_id"); - // Get Name and Client ID for logging and alert message - $sql = mysqli_query($mysqli,"SELECT domain_name, domain_client_id FROM domains WHERE domain_id = $domain_id"); - $row = mysqli_fetch_assoc($sql); - $domain_name = escapeSql($row['domain_name']); - $client_id = intval($row['domain_client_id']); + logAudit("Domain", "Restore", "$session_name restored domain " . escapeSql($row['domain_name']), $client_id, $domain_id); - enforceClientAccess(); - - mysqli_query($mysqli,"UPDATE domains SET domain_archived_at = NULL WHERE domain_id = $domain_id"); - - logAudit("Domain", "Restore", "$session_name restored domain $domain_name", $client_id, $domain_id); - - flashAlert("Domain $domain_name restored"); + flashAlert("Domain {$row['domain_name']} restored"); redirect(); @@ -254,141 +267,65 @@ if (isset($_GET['delete_domain'])) { validateCSRFToken(); - enforceUserPermission('module_support', 3); + $row = domainForRequest($_GET['delete_domain'], 3); - $domain_id = intval($_GET['delete_domain']); + domainDeleteForGood($row['domain_id']); - // Get Domain Name and Client ID for logging and alert message - $sql = mysqli_query($mysqli,"SELECT domain_name, domain_client_id FROM domains WHERE domain_id = $domain_id"); - $row = mysqli_fetch_assoc($sql); - $domain_name = escapeSql($row['domain_name']); - $client_id = intval($row['domain_client_id']); + logAudit("Domain", "Delete", "$session_name deleted domain " . escapeSql($row['domain_name']), $client_id); - enforceClientAccess(); - - mysqli_query($mysqli,"DELETE FROM domains WHERE domain_id = $domain_id"); - - logAudit("Domain", "Delete", "$session_name deleted domain $domain_name", $client_id); - - flashAlert("Domain $domain_name deleted", 'error'); + flashAlert("Domain {$row['domain_name']} deleted", 'error'); redirect(); } -if (isset($_POST['bulk_archive_domains'])) { +if (isset($_POST['bulk_favorite_domains']) || isset($_POST['bulk_unfavorite_domains'])) { validateCSRFToken(); - enforceUserPermission('module_support', 3); - - if (isset($_POST['domain_ids'])) { - - // Get Selected Count - $count = count($_POST['domain_ids']); - - // Cycle through array and archive each record - foreach ($_POST['domain_ids'] as $domain_id) { - - $domain_id = intval($domain_id); - - // Get Name and Client ID for logging and alert message - $sql = mysqli_query($mysqli,"SELECT domain_name, domain_client_id FROM domains WHERE domain_id = $domain_id"); - $row = mysqli_fetch_assoc($sql); - $domain_name = escapeSql($row['domain_name']); - $client_id = intval($row['domain_client_id']); - - enforceClientAccess(); - - mysqli_query($mysqli,"UPDATE domains SET domain_archived_at = NOW() WHERE domain_id = $domain_id"); - - logAudit("Domain", "Archive", "$session_name archived domain $domain_name", $client_id, $domain_id); - } - - logAudit("Domain", "Bulk Archive", "$session_name archived $count domain(s)", $client_id); - - flashAlert("Archived $count domain(s)", 'error'); - + $favorite = isset($_POST['bulk_favorite_domains']) ? 1 : 0; + $count = 0; + foreach (domainsForBulk(2) as $domain_id => $row) { + mysqli_query($mysqli, "UPDATE domains SET domain_favorite = $favorite WHERE domain_id = $domain_id"); + logAudit("Domain", "Edit", "$session_name " . ($favorite ? 'starred' : 'unstarred') . " domain " . escapeSql($row['domain_name']), intval($row['domain_client_id']), $domain_id); + $count++; } + flashAlert(($favorite ? 'Starred' : 'Unstarred') . " $count domain" . ($count === 1 ? '' : 's')); + redirect(); } -if (isset($_POST['bulk_restore_domains'])) { +// Who registers or hosts them - one vendor into one role for several domains at once +if (isset($_POST['bulk_set_domain_vendor'])) { validateCSRFToken(); - enforceUserPermission('module_support', 2); - - if (isset($_POST['domain_ids'])) { - - // Get Selected Count - $count = count($_POST['domain_ids']); - - // Cycle through array and restore - foreach ($_POST['domain_ids'] as $domain_id) { - - $domain_id = intval($domain_id); - - // Get Name and Client ID for logging and alert message - $sql = mysqli_query($mysqli,"SELECT domain_name, domain_client_id FROM domains WHERE domain_id = $domain_id"); - $row = mysqli_fetch_assoc($sql); - $domain_name = escapeSql($row['domain_name']); - $client_id = intval($row['domain_client_id']); - - enforceClientAccess(); - - mysqli_query($mysqli,"UPDATE domains SET domain_archived_at = NULL WHERE domain_id = $domain_id"); - - logAudit("Domain", "Restore", "$session_name restored domain $domain_name", $client_id, $domain_id); + $role = $_POST['role'] ?? ''; + if (!isset(DOMAIN_ROLES[$role])) { + flashAlert('Pick what the vendor does for them.', 'error'); + redirect(); + } + $column = DOMAIN_ROLES[$role]['column']; + $vendor_input = intval($_POST['vendor_id'] ?? 0); + $count = $skipped = 0; + foreach (domainsForBulk(2) as $domain_id => $row) { + $vendor_id = domainVendorId($vendor_input, $row['domain_client_id']); + if ($vendor_input && !$vendor_id) { + // That vendor is another client's + $skipped++; + continue; } - - logAudit("Domain", "Bulk Restore", "$session_name restored $count domain(s)", $client_id); - - flashAlert("Restored $count domain(s)"); - + $before = domainHistorySnapshot($domain_id); + mysqli_query($mysqli, "UPDATE domains SET $column = $vendor_id WHERE domain_id = $domain_id"); + domainWriteHistory($domain_id, $before, domainHistorySnapshot($domain_id)); + logAudit("Domain", "Edit", "$session_name set the " . strtolower(DOMAIN_ROLES[$role]['label']) . " vendor on domain " . escapeSql($row['domain_name']), intval($row['domain_client_id']), $domain_id); + $count++; } - redirect(); - -} - -if (isset($_POST['bulk_delete_domains'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 3); - - if (isset($_POST['domain_ids'])) { - - // Get Selected Count - $count = count($_POST['domain_ids']); - - // Cycle through array and delete each domain - foreach ($_POST['domain_ids'] as $domain_id) { - - $domain_id = intval($domain_id); - - // Get Name and Client ID for logging and alert message - $sql = mysqli_query($mysqli,"SELECT domain_name, domain_client_id FROM domains WHERE domain_id = $domain_id"); - $row = mysqli_fetch_assoc($sql); - $domain_name = escapeSql($row['domain_name']); - $client_id = intval($row['domain_client_id']); - - enforceClientAccess(); - - mysqli_query($mysqli, "DELETE FROM domains WHERE domain_id = $domain_id AND domain_client_id = $client_id"); - - logAudit("Domain", "Delete", "$session_name deleted domain $domain_name", $client_id); - } - - logAudit("Domain", "Bulk Delete", "$session_name deleted $count domain(s)", $client_id); - - flashAlert("Deleted $count domain(s)", 'error'); - - } + flashAlert("Set the " . strtolower(DOMAIN_ROLES[$role]['label']) . ($role === 'registrar' ? '' : ' host') . " on $count domain" . ($count === 1 ? '' : 's') . ($skipped ? ", $skipped skipped - that vendor is another client's" : '')); redirect(); @@ -398,59 +335,74 @@ if (isset($_POST['bulk_refresh_domains'])) { validateCSRFToken(); - enforceUserPermission('module_support', 2); + // Lookups are slow - don't time out mid-batch + set_time_limit(0); - if (isset($_POST['domain_ids'])) { - - // WHOIS lookups are slow - don't time out mid-batch - set_time_limit(0); - - // Get Selected Count - $count = count($_POST['domain_ids']); - - // Cycle through array and refresh each record - foreach ($_POST['domain_ids'] as $domain_id) { - - $domain_id = intval($domain_id); - - // Get Name and Client ID for logging and alert message - $sql = mysqli_query($mysqli,"SELECT domain_name, domain_client_id FROM domains WHERE domain_id = $domain_id"); - $row = mysqli_fetch_assoc($sql); - $domain_name = escapeSql($row['domain_name']); - $client_id = intval($row['domain_client_id']); - - enforceClientAccess(); - - // Lookup expiry date - $expire = getDomainExpirationDate($domain_name); - if (strtotime($expire)) { - $expire = "'" . $expire . "'"; - } else { - $expire = 'NULL'; - } - - // NS, MX, A and WHOIS records/data - $records = getDnsRecords($domain_name); - $a = escapeSql($records['a']); - $ns = escapeSql($records['ns']); - $mx = escapeSql($records['mx']); - $txt = escapeSql($records['txt']); - $whois = escapeSql($records['whois']); - - mysqli_query($mysqli,"UPDATE domains SET domain_expire = $expire, domain_ip = '$a', domain_name_servers = '$ns', domain_mail_servers = '$mx', domain_txt = '$txt', domain_raw_whois = '$whois' WHERE domain_id = $domain_id"); - - logAudit("Domain", "Refresh", "$session_name refreshed records for domain $domain_name", $client_id, $domain_id); - - // Be gentle on WHOIS servers - sleep(1); + $count = $found = 0; + foreach (domainsForBulk(2) as $domain_id => $row) { + $count++; + if (domainRefresh($row)) { + $found++; + logAudit("Domain", "Refresh", "$session_name looked up domain " . escapeSql($row['domain_name']), intval($row['domain_client_id']), $domain_id); } - - logAudit("Domain", "Bulk Refresh", "$session_name refreshed records for $count domain(s)", $client_id); - - flashAlert("Refreshed records for $count domain(s)"); - + // Be gentle on the registries + usleep(500000); } + $missed = $count - $found; + flashAlert("Looked up $found domain" . ($found === 1 ? '' : 's') . ($missed ? ", nothing answered for $missed - left as they were" : ''), $missed ? 'warning' : 'success'); + + redirect(); + +} + +if (isset($_POST['bulk_archive_domains'])) { + + validateCSRFToken(); + + $count = 0; + foreach (domainsForBulk(2) as $domain_id => $row) { + mysqli_query($mysqli, "UPDATE domains SET domain_archived_at = NOW() WHERE domain_id = $domain_id"); + logAudit("Domain", "Archive", "$session_name archived domain " . escapeSql($row['domain_name']), intval($row['domain_client_id']), $domain_id); + $count++; + } + + flashAlert("Archived $count domain" . ($count === 1 ? '' : 's'), 'error'); + + redirect(); + +} + +if (isset($_POST['bulk_restore_domains'])) { + + validateCSRFToken(); + + $count = 0; + foreach (domainsForBulk(2) as $domain_id => $row) { + mysqli_query($mysqli, "UPDATE domains SET domain_archived_at = NULL WHERE domain_id = $domain_id"); + logAudit("Domain", "Restore", "$session_name restored domain " . escapeSql($row['domain_name']), intval($row['domain_client_id']), $domain_id); + $count++; + } + + flashAlert("Restored $count domain" . ($count === 1 ? '' : 's')); + + redirect(); + +} + +if (isset($_POST['bulk_delete_domains'])) { + + validateCSRFToken(); + + $count = 0; + foreach (domainsForBulk(3) as $domain_id => $row) { + domainDeleteForGood($domain_id); + logAudit("Domain", "Delete", "$session_name deleted domain " . escapeSql($row['domain_name']), intval($row['domain_client_id'])); + $count++; + } + + flashAlert("Deleted $count domain" . ($count === 1 ? '' : 's'), 'error'); + redirect(); } @@ -499,18 +451,31 @@ if (isExportRequest('export_domains')) { } // Expiring In Filter + $expire_query = ''; if (!empty($_POST['expire_days'])) { if ($_POST['expire_days'] == "expired") { - $expire_query = "AND (domain_expire IS NOT NULL AND domain_expire != '0000-00-00' AND domain_expire < CURDATE())"; + $expire_query = "AND (domain_expire IS NOT NULL AND domain_expire < CURDATE())"; $filter_summary['Expiry'] = 'Expired'; } else { $expire_days = intval($_POST['expire_days']); - $expire_query = "AND (domain_expire IS NOT NULL AND domain_expire != '0000-00-00' AND domain_expire BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL $expire_days DAY))"; + $expire_query = "AND (domain_expire IS NOT NULL AND domain_expire BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL $expire_days DAY))"; $filter_summary['Expiry'] = "Expiring within $expire_days days"; } - } else { - // Default - any - $expire_query = ''; + } + + // Tags Filter - a domain with any of them + $tag_query = ''; + if (isset($_POST['tags']) && is_array($_POST['tags']) && !empty($_POST['tags'])) { + $tag_filter = implode(",", array_map('intval', $_POST['tags'])); + $tag_query = "AND domains.domain_id IN (SELECT domain_id FROM domain_tags WHERE tag_id IN ($tag_filter))"; + } + + // Vendor Filter - registrar or any host + $vendor_query = ''; + if (!empty($_POST['vendor'])) { + $vendor_filter = intval($_POST['vendor']); + $vendor_query = "AND $vendor_filter IN (domain_registrar, domain_dnshost, domain_webhost, domain_mailhost)"; + $filter_summary['Vendor'] = getFieldById('vendors', $vendor_filter, 'vendor_name'); } // Search Filter @@ -519,21 +484,25 @@ if (isExportRequest('export_domains')) { $filter_summary['Search'] = $_POST['q']; } + [$domain_columns, $domain_joins] = domainSelectSql(); $sql = mysqli_query( $mysqli, - "SELECT domains.*, clients.*, - registrar.vendor_name AS domain_registrar_name, - webhost.vendor_name AS domain_webhost_name - FROM domains - LEFT JOIN clients ON client_id = domain_client_id - LEFT JOIN vendors AS registrar ON domains.domain_registrar = registrar.vendor_id - LEFT JOIN vendors AS webhost ON domains.domain_webhost = webhost.vendor_id - WHERE (domains.domain_name LIKE '%$q%' OR domains.domain_description LIKE '%$q%' OR registrar.vendor_name LIKE '%$q%' OR webhost.vendor_name LIKE '%$q%' OR client_name LIKE '%$q%') + "SELECT $domain_columns, + registrar.vendor_name AS domain_registrar_name, webhost.vendor_name AS domain_webhost_name, + dnshost.vendor_name AS domain_dnshost_name, mailhost.vendor_name AS domain_mailhost_name, + IF(domain_auto_renew = 1, 'Yes', 'No') AS domain_auto_renew_label, + (SELECT GROUP_CONCAT(tag_name ORDER BY tag_name SEPARATOR ', ') FROM domain_tags dt JOIN tags t ON t.tag_id = dt.tag_id WHERE dt.domain_id = domains.domain_id) AS domain_tags + FROM domains $domain_joins + WHERE (domains.domain_name LIKE '%$q%' OR domains.domain_description LIKE '%$q%' OR domains.domain_notes LIKE '%$q%' + OR registrar.vendor_name LIKE '%$q%' OR dnshost.vendor_name LIKE '%$q%' OR webhost.vendor_name LIKE '%$q%' OR mailhost.vendor_name LIKE '%$q%' OR client_name LIKE '%$q%' + OR domains.domain_id IN (SELECT domain_id FROM domain_tags JOIN tags USING (tag_id) WHERE tag_name LIKE '%$q%')) AND $archive_query " . clientScopeSql('domain_client_id') . " $client_query $expire_query - ORDER BY domains.domain_name ASC" + $tag_query + $vendor_query + ORDER BY client_name ASC, domains.domain_name ASC" ); $num_rows = mysqli_num_rows($sql); diff --git a/agent/post/domain_model.php b/agent/post/domain_model.php deleted file mode 100644 index e63acf8e3..000000000 --- a/agent/post/domain_model.php +++ /dev/null @@ -1,11 +0,0 @@ - ['label' => 'Expenses', 'icon' => 'fa-receipt', 'count' => $spend ? $spend['count'] : 0], 'recurring' => ['label' => 'Recurring', 'icon' => 'fa-redo-alt', 'count' => count($recurring)], 'cases' => ['label' => 'Cases', 'icon' => 'fa-life-ring', 'count' => $case_count, 'badge' => $case_open_count], + 'domains' => ['label' => 'Client domains', 'icon' => 'fa-globe', 'count' => count($domains)], 'history' => ['label' => 'History', 'icon' => 'fa-history', 'count' => count($history)], ]; + if (!$domains) { + unset($vendor_tabs['domains']); + } if (!$can_financial) { unset($vendor_tabs['expenses'], $vendor_tabs['recurring']); } @@ -557,12 +566,17 @@ if (!$vendor || (isset($_GET['client_id']) && $vendor_client_id !== intval($clie
    - Domains they register or host, and for what. + + + +
    - + Client' : '' ?> + $expiry = domainExpiry($domain['domain_expire'], $domain['domain_auto_renew']); ?> - + + + + diff --git a/api/v1/domains/create.php b/api/v1/domains/create.php index bc1585777..d3f9e8b4b 100644 --- a/api/v1/domains/create.php +++ b/api/v1/domains/create.php @@ -7,28 +7,17 @@ require_once 'domain_model.php'; $insert_id = false; -if (!empty($name) && !empty($client_id)) { - // Use the supplied expiry when valid, otherwise look it up from WHOIS. - if (strtotime($expire)) { - $expire = "'$expire'"; - } else { - $expire = getDomainExpirationDate($name); - $expire = strtotime($expire) ? "'$expire'" : 'NULL'; - } +if (!empty($name) && !empty($client_id) && !mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM domains WHERE domain_name = '$name' AND domain_client_id = $client_id LIMIT 1"))) { + $expire_sql = $expire !== '' ? "'$expire'" : 'NULL'; - // Populate DNS and WHOIS data from the domain rather than accepting it from the API. - $records = getDnsRecords($name); - $ip = escapeSql($records['a']); - $name_servers = escapeSql($records['ns']); - $mail_servers = escapeSql($records['mx']); - $txt = escapeSql($records['txt']); - $raw_whois = escapeSql($records['whois']); - - $insert_sql = mysqli_query($mysqli, "INSERT INTO domains SET domain_name = '$name', domain_description = '$description', domain_expire = $expire, domain_ip = '$ip', domain_name_servers = '$name_servers', domain_mail_servers = '$mail_servers', domain_txt = '$txt', domain_raw_whois = '$raw_whois', domain_notes = '$notes', domain_registrar = $registrar, domain_webhost = $webhost, domain_dnshost = $dnshost, domain_mailhost = $mailhost, domain_client_id = $client_id"); + $insert_sql = mysqli_query($mysqli, "INSERT INTO domains SET domain_name = '$name', domain_description = '$description', domain_expire = $expire_sql, domain_auto_renew = $auto_renew, domain_notes = '$notes', domain_registrar = $registrar, domain_webhost = $webhost, domain_dnshost = $dnshost, domain_mailhost = $mailhost, domain_client_id = $client_id"); if ($insert_sql) { $insert_id = mysqli_insert_id($mysqli); + // DNS, registration and the expiry come from the domain itself rather than the request + domainApplyLookup($insert_id, domainLookup($name)); + logAudit("Domain", "Create", "$name via API ($api_key_name)", $client_id, $insert_id); logAudit("API", "Success", "Created domain $name via API ($api_key_name)", $client_id); } diff --git a/api/v1/domains/domain_model.php b/api/v1/domains/domain_model.php index 3198cf0aa..87d77df6e 100644 --- a/api/v1/domains/domain_model.php +++ b/api/v1/domains/domain_model.php @@ -3,7 +3,8 @@ // Variable assignment from POST (or: blank/from DB is updating) if (isset($_POST['domain_name'])) { - $name = preg_replace("(^https?://)", "", escapeSql($_POST['domain_name'])); + // Tidied the way the app keeps it - lowercase, no scheme, path or leading www. + $name = escapeSql(domainNormalizeName($_POST['domain_name'])); } elseif (isset($domain_row) && isset($domain_row['domain_name'])) { $name = mysqli_real_escape_string($mysqli, $domain_row['domain_name']); } else { @@ -64,4 +65,23 @@ if (isset($_POST['domain_mailhost'])) { $mailhost = $domain_row['domain_mailhost']; } else { $mailhost = 0; +} + +if (isset($_POST['domain_auto_renew'])) { + $auto_renew = intval($_POST['domain_auto_renew']) ? 1 : 0; +} elseif (isset($domain_row) && isset($domain_row['domain_auto_renew'])) { + $auto_renew = intval($domain_row['domain_auto_renew']); +} else { + $auto_renew = 0; +} + +// The registrar and hosts must be the client's vendors or ours +$registrar = domainVendorId($registrar, $client_id); +$webhost = domainVendorId($webhost, $client_id); +$dnshost = domainVendorId($dnshost, $client_id); +$mailhost = domainVendorId($mailhost, $client_id); + +// An expiry that is not a date is no expiry +if ($expire !== '' && !DateTime::createFromFormat('!Y-m-d', $expire)) { + $expire = ''; } \ No newline at end of file diff --git a/api/v1/domains/update.php b/api/v1/domains/update.php index 557a2e50f..469d25113 100644 --- a/api/v1/domains/update.php +++ b/api/v1/domains/update.php @@ -23,69 +23,27 @@ if (!empty($domain_id)) { LIMIT 1 ")); - $original_domain_info = $domain_row; - require_once 'domain_model.php'; - // Use the supplied expiry when valid, otherwise look it up from WHOIS. - if (strtotime($expire)) { - $expire = "'$expire'"; - } else { - $expire = getDomainExpirationDate($name); - $expire = strtotime($expire) ? "'$expire'" : 'NULL'; - } + $expire_sql = $expire !== '' ? "'$expire'" : 'NULL'; + $duplicate = $domain_row && mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM domains WHERE domain_name = '$name' AND domain_client_id = $client_id AND domain_id <> $domain_id LIMIT 1")); - // Populate DNS and WHOIS data from the domain rather than accepting it from the API. - $records = getDnsRecords($name); - $ip = escapeSql($records['a']); - $name_servers = escapeSql($records['ns']); - $mail_servers = escapeSql($records['mx']); - $txt = escapeSql($records['txt']); - $raw_whois = escapeSql($records['whois']); + if ($domain_row && $name !== '' && !$duplicate) { + $before = domainHistorySnapshot($domain_id); - $update_sql = mysqli_query($mysqli, "UPDATE domains SET domain_name = '$name', domain_description = '$description', domain_expire = $expire, domain_ip = '$ip', domain_name_servers = '$name_servers', domain_mail_servers = '$mail_servers', domain_txt = '$txt', domain_raw_whois = '$raw_whois', domain_notes = '$notes', domain_registrar = $registrar, domain_webhost = $webhost, domain_dnshost = $dnshost, domain_mailhost = $mailhost WHERE domain_id = $domain_id AND domain_client_id = $client_id AND domain_archived_at IS NULL LIMIT 1"); + $update_sql = mysqli_query($mysqli, "UPDATE domains SET domain_name = '$name', domain_description = '$description', domain_expire = $expire_sql, domain_auto_renew = $auto_renew, domain_notes = '$notes', domain_registrar = $registrar, domain_webhost = $webhost, domain_dnshost = $dnshost, domain_mailhost = $mailhost WHERE domain_id = $domain_id AND domain_client_id = $client_id AND domain_archived_at IS NULL LIMIT 1"); - if ($update_sql && $domain_row) { - // Capture the update result before any history or audit queries run. - $update_count = mysqli_affected_rows($mysqli); + if ($update_sql) { + // Capture the update result before any history or audit queries run. + $update_count = mysqli_affected_rows($mysqli); - $new_domain_info = mysqli_fetch_assoc(mysqli_query($mysqli, " - SELECT - domains.*, - registrar.vendor_name AS registrar_name, - dnshost.vendor_name AS dnshost_name, - mailhost.vendor_name AS mailhost_name, - webhost.vendor_name AS webhost_name - FROM domains - LEFT JOIN vendors AS registrar ON domains.domain_registrar = registrar.vendor_id - LEFT JOIN vendors AS dnshost ON domains.domain_dnshost = dnshost.vendor_id - LEFT JOIN vendors AS mailhost ON domains.domain_mailhost = mailhost.vendor_id - LEFT JOIN vendors AS webhost ON domains.domain_webhost = webhost.vendor_id - WHERE domain_id = $domain_id AND domain_client_id = $client_id - LIMIT 1 - ")); + // DNS and registration come from the domain itself; a lookup that finds nothing keeps what was there + domainApplyLookup($domain_id, domainLookup($name)); + domainWriteHistory($domain_id, $before, domainHistorySnapshot($domain_id)); - $ignored_columns = [ - 'domain_updated_at', - 'domain_accessed_at', - 'domain_registrar', - 'domain_webhost', - 'domain_dnshost', - 'domain_mailhost' - ]; - - foreach ($original_domain_info as $column => $old_value) { - $new_value = $new_domain_info[$column]; - if ($old_value != $new_value && !in_array($column, $ignored_columns)) { - $column = escapeSql($column); - $old_value = escapeSql($old_value); - $new_value = escapeSql($new_value); - mysqli_query($mysqli, "INSERT INTO domain_history SET domain_history_column = '$column', domain_history_old_value = '$old_value', domain_history_new_value = '$new_value', domain_history_domain_id = $domain_id"); - } + logAudit("Domain", "Edit", "$name via API ($api_key_name)", $client_id, $domain_id); + logAudit("API", "Success", "Updated domain $name via API ($api_key_name)", $client_id); } - - logAudit("Domain", "Edit", "$name via API ($api_key_name)", $client_id, $domain_id); - logAudit("API", "Success", "Updated domain $name via API ($api_key_name)", $client_id); } } diff --git a/client/domains.php b/client/domains.php index 03c5d8b32..5222091ad 100644 --- a/client/domains.php +++ b/client/domains.php @@ -10,7 +10,7 @@ require_once "includes/inc_all.php"; enforceContactCan('itdoc'); -$domains_sql = mysqli_query($mysqli, "SELECT domain_id, domain_name, domain_expire FROM domains WHERE domain_client_id = $session_client_id AND domain_archived_at IS NULL ORDER BY domain_expire ASC"); +$domains_sql = mysqli_query($mysqli, "SELECT domain_id, domain_name, domain_expire, domain_auto_renew FROM domains WHERE domain_client_id = $session_client_id AND domain_archived_at IS NULL ORDER BY domain_expire IS NULL, domain_expire ASC"); ?>

    Domains

    @@ -26,6 +26,7 @@ $domains_sql = mysqli_query($mysqli, "SELECT domain_id, domain_name, domain_expi + @@ -34,12 +35,19 @@ $domains_sql = mysqli_query($mysqli, "SELECT domain_id, domain_name, domain_expi while ($row = mysqli_fetch_assoc($domains_sql)) { $domain_name = escapeHtml($row['domain_name']); $domain_expire = escapeHtml($row['domain_expire']); + $expiry = domainExpiry($row['domain_expire'], $row['domain_auto_renew']); ?> - + + diff --git a/cron/domain_refresher.php b/cron/domain_refresher.php index d1905a3fe..2f24aef14 100644 --- a/cron/domain_refresher.php +++ b/cron/domain_refresher.php @@ -37,86 +37,46 @@ if ($config_enable_cron == 0) { * ############################################################################################################### */ -// REFRESH DOMAIN WHOIS DATA (1 a day/run) -// Get the oldest updated domain (MariaDB shows NULLs first when ordering by default) -$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT domain_id, domain_name, domain_expire FROM `domains` WHERE domain_archived_at IS NULL ORDER BY domain_updated_at LIMIT 1")); +// A batch a run - as many as fit in a few minutes, up to 50. Due are the ones +// never looked up, not looked up in a week, or expiring within 60 days and not +// looked up today. Least recently tried first: a domain that answers nothing is +// touched anyway, so it goes to the back rather than taking a slot every run. +// A lookup that finds nothing changes nothing (domainApplyLookup()). +$started = time(); +$checked = $found = 0; +$sql = mysqli_query($mysqli, "SELECT domain_id, domain_name FROM domains + LEFT JOIN clients ON client_id = domain_client_id + WHERE domain_archived_at IS NULL AND client_archived_at IS NULL + AND (domain_refreshed_at IS NULL OR domain_refreshed_at < NOW() - INTERVAL 7 DAY + OR (domain_expire IS NOT NULL AND domain_expire <= CURDATE() + INTERVAL 60 DAY AND domain_refreshed_at < NOW() - INTERVAL 1 DAY)) + ORDER BY domain_updated_at ASC + LIMIT 50"); -if ($row) { +while ($row = mysqli_fetch_assoc($sql)) { + + if (time() - $started > 240) { + break; + } - // Get current data in database $domain_id = intval($row['domain_id']); - $domain_name = escapeSql($row['domain_name']); - $current_expire = escapeSql($row['domain_expire']); + $checked++; // Touch the record we're refreshing to ensure we don't loop mysqli_query($mysqli, "UPDATE domains SET domain_updated_at = NOW() WHERE domain_id = $domain_id"); - // Lookup fresh info - $expire = getDomainExpirationDate($domain_name); - $records = getDnsRecords($domain_name); - $a = escapeSql($records['a']); - $ns = escapeSql($records['ns']); - $mx = escapeSql($records['mx']); - $txt = escapeSql($records['txt']); - $whois = escapeSql($records['whois']); - - // Handle expiry date - if (strtotime($expire)) { - $expire = "'" . $expire . "'"; // Valid - } elseif (!strtotime($expire) && strtotime($current_expire)) { - // New expiry date is invalid, but old one is OK - reverting back - $expire = "'" . $current_expire . "'"; + $before = domainHistorySnapshot($domain_id); + if (domainApplyLookup($domain_id, domainLookup($row['domain_name']))) { + domainWriteHistory($domain_id, $before, domainHistorySnapshot($domain_id)); + $found++; + echo "Updated {$row['domain_name']}.\n"; } else { - // Neither are valid, setting expiry to NULL - $expire = 'NULL'; - } - - // Current domain info - $original_domain_info = mysqli_fetch_assoc(mysqli_query($mysqli," - SELECT - domains.*, - registrar.vendor_name AS registrar_name, - dnshost.vendor_name AS dnshost_name, - mailhost.vendor_name AS mailhost_name, - webhost.vendor_name AS webhost_name - FROM domains - LEFT JOIN vendors AS registrar ON domains.domain_registrar = registrar.vendor_id - LEFT JOIN vendors AS dnshost ON domains.domain_dnshost = dnshost.vendor_id - LEFT JOIN vendors AS mailhost ON domains.domain_mailhost = mailhost.vendor_id - LEFT JOIN vendors AS webhost ON domains.domain_webhost = webhost.vendor_id - WHERE domain_id = $domain_id - ")); - - // Update the domain - mysqli_query($mysqli, "UPDATE domains SET domain_name = '$domain_name', domain_expire = $expire, domain_ip = '$a', domain_name_servers = '$ns', domain_mail_servers = '$mx', domain_txt = '$txt', domain_raw_whois = '$whois' WHERE domain_id = $domain_id"); - echo "Updated $domain_name."; - - // Fetch updated info - $new_domain_info = mysqli_fetch_assoc(mysqli_query($mysqli," - SELECT - domains.*, - registrar.vendor_name AS registrar_name, - dnshost.vendor_name AS dnshost_name, - mailhost.vendor_name AS mailhost_name, - webhost.vendor_name AS webhost_name - FROM domains - LEFT JOIN vendors AS registrar ON domains.domain_registrar = registrar.vendor_id - LEFT JOIN vendors AS dnshost ON domains.domain_dnshost = dnshost.vendor_id - LEFT JOIN vendors AS mailhost ON domains.domain_mailhost = mailhost.vendor_id - LEFT JOIN vendors AS webhost ON domains.domain_webhost = webhost.vendor_id - WHERE domain_id = $domain_id - ")); - - // Compare/log changes - $ignored_columns = ["domain_updated_at", "domain_accessed_at", "domain_registrar", "domain_webhost", "domain_dnshost", "domain_mailhost"]; - foreach ($original_domain_info as $column => $old_value) { - $new_value = $new_domain_info[$column]; - if ($old_value != $new_value && !in_array($column, $ignored_columns)) { - $column = escapeSql($column); - $old_value = escapeSql($old_value); - $new_value = escapeSql($new_value); - mysqli_query($mysqli,"INSERT INTO domain_history SET domain_history_column = '$column', domain_history_old_value = '$old_value', domain_history_new_value = '$new_value', domain_history_domain_id = $domain_id"); - } + echo "Nothing answered for {$row['domain_name']} - left as it was.\n"; } + // Be gentle on the registries + sleep(1); +} + +if ($checked) { + logApp("Cron-Domain-Refresher", "info", "Looked up $checked domain(s), $found answered."); } diff --git a/cron/nightly_tasks.php b/cron/nightly_tasks.php index e165b5e1b..64cfc1af8 100644 --- a/cron/nightly_tasks.php +++ b/cron/nightly_tasks.php @@ -231,9 +231,10 @@ if ($config_enable_alert_domain_expire == 1) { //Get Domains Expiring $sql = mysqli_query( $mysqli, - "SELECT client_id, client_name, domain_expire, domain_id, domain_name FROM domains + "SELECT client_id, client_name, domain_expire, domain_auto_renew, domain_id, domain_name FROM domains LEFT JOIN clients ON domain_client_id = client_id - WHERE domain_expire IS NOT NULL AND domain_expire = CURDATE() + INTERVAL $day DAY" + WHERE domain_expire IS NOT NULL AND domain_expire = CURDATE() + INTERVAL $day DAY + AND domain_archived_at IS NULL AND client_archived_at IS NULL" ); while ($row = mysqli_fetch_assoc($sql)) { @@ -243,7 +244,9 @@ if ($config_enable_alert_domain_expire == 1) { $client_id = intval($row['client_id']); $client_name = escapeSql($row['client_name']); - appNotify("Domain Expiring", "Domain $domain_name for $client_name will expire in $day Days on $domain_expire", "/agent/domains.php?client_id=$client_id", $client_id); + // Auto-renew still fails on an expired card, so it is said rather than skipped + $domain_renewal = intval($row['domain_auto_renew']) ? ' - set to auto-renew, check it goes through' : ''; + appNotify("Domain Expiring", "Domain $domain_name for $client_name will expire in $day Days on $domain_expire$domain_renewal", "/agent/domains.php?client_id=$client_id&open=$domain_id", $client_id); } diff --git a/css/itflow_custom.css b/css/itflow_custom.css index dce0246b4..634c8a829 100644 --- a/css/itflow_custom.css +++ b/css/itflow_custom.css @@ -4686,3 +4686,23 @@ img.itflow-contact-avatar { min-width: 12rem; max-width: 22rem; } + +/* Domains - agent/domains.php and agent/modals/domain/ (functions/domain.php). + Records are monospace, one per line with a copy button; the registrar and + hosts column keeps to one width. */ +.itflow-domain-dl dt { + white-space: nowrap; +} +.itflow-domain-dl dd { + min-height: 1.5rem; + min-width: 0; +} +.itflow-domain-who { + max-width: 18rem; +} +.itflow-domain-checks li + li { + margin-top: .25rem; +} +.itflow-domain-mail > .d-inline-flex { + flex-wrap: nowrap !important; +} diff --git a/db.sql b/db.sql index eca08090f..6f0892e4f 100644 --- a/db.sql +++ b/db.sql @@ -1227,6 +1227,23 @@ CREATE TABLE `domain_history` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `domain_tags` +-- + +DROP TABLE IF EXISTS `domain_tags`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8mb4 */; +CREATE TABLE `domain_tags` ( + `domain_id` int(11) NOT NULL, + `tag_id` int(11) NOT NULL, + PRIMARY KEY (`domain_id`,`tag_id`), + KEY `tag_id` (`tag_id`), + CONSTRAINT `domain_tags_ibfk_1` FOREIGN KEY (`domain_id`) REFERENCES `domains` (`domain_id`) ON DELETE CASCADE, + CONSTRAINT `domain_tags_ibfk_2` FOREIGN KEY (`tag_id`) REFERENCES `tags` (`tag_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 `domains` -- @@ -1239,10 +1256,13 @@ CREATE TABLE `domains` ( `domain_name` varchar(200) NOT NULL, `domain_description` text DEFAULT NULL, `domain_expire` date DEFAULT NULL, + `domain_auto_renew` tinyint(1) NOT NULL DEFAULT 0, `domain_ip` varchar(255) DEFAULT NULL, `domain_name_servers` varchar(255) DEFAULT NULL, `domain_mail_servers` varchar(255) DEFAULT NULL, `domain_txt` text DEFAULT NULL, + `domain_dmarc` text DEFAULT NULL, + `domain_dkim` varchar(255) DEFAULT NULL, `domain_raw_whois` text DEFAULT NULL, `domain_notes` text DEFAULT NULL, `domain_favorite` tinyint(1) NOT NULL DEFAULT 0, @@ -1250,6 +1270,7 @@ CREATE TABLE `domains` ( `domain_updated_at` datetime DEFAULT NULL ON UPDATE current_timestamp(), `domain_archived_at` datetime DEFAULT NULL, `domain_accessed_at` datetime DEFAULT NULL, + `domain_refreshed_at` datetime DEFAULT NULL, `domain_registrar` int(11) NOT NULL DEFAULT 0, `domain_webhost` int(11) NOT NULL DEFAULT 0, `domain_dnshost` int(11) NOT NULL DEFAULT 0, diff --git a/functions/client_overview.php b/functions/client_overview.php index 09fa6ee3c..e5823501b 100644 --- a/functions/client_overview.php +++ b/functions/client_overview.php @@ -283,7 +283,7 @@ function clientOverviewRenewals($client_id, $days = 45) { $sources = [ ['domain', 'globe', "SELECT domain_id AS id, domain_name AS name, domain_expire AS d FROM domains WHERE domain_client_id = $client_id AND domain_archived_at IS NULL AND domain_expire IS NOT NULL AND domain_expire <= $window", - 'Domain', "/agent/domains.php?client_id=$client_id&q="], + 'Domain', "/agent/domains.php?client_id=$client_id&open="], ['certificate', 'lock', "SELECT certificate_id AS id, certificate_name AS name, certificate_expire AS d FROM certificates WHERE certificate_client_id = $client_id AND certificate_archived_at IS NULL AND certificate_expire IS NOT NULL AND certificate_expire <= $window", 'Certificate', "/agent/certificates.php?client_id=$client_id&q="], @@ -308,7 +308,7 @@ function clientOverviewRenewals($client_id, $days = 45) { 'kind' => $kind, 'icon' => $icon, 'label' => $label, 'name' => $row['name'], 'date' => $row['d'], 'days' => (int) $today->diff($date)->format('%r%a'), - 'url' => in_array($kind, ['warranty', 'retire', 'software'], true) ? $url . intval($row['id']) : $url . rawurlencode($row['name']), + 'url' => in_array($kind, ['domain', 'warranty', 'retire', 'software'], true) ? $url . intval($row['id']) : $url . rawurlencode($row['name']), ]; } } diff --git a/functions/domain.php b/functions/domain.php index d40e30e9e..69ee9b62d 100644 --- a/functions/domain.php +++ b/functions/domain.php @@ -296,6 +296,8 @@ function getDnsRecords($name) { 'ns' => '', 'mx' => '', 'txt' => '', + 'dmarc' => '', + 'dkim' => '', 'whois' => '', 'expire' => '' ); @@ -343,10 +345,33 @@ function getDnsRecords($name) { $records['txt'] = implode("\n", $txt_records); } + // DMARC - the policy record at _dmarc + $dmarc = @dns_get_record("_dmarc.$domain", DNS_TXT); + if (is_array($dmarc)) { + foreach ($dmarc as $record) { + if (isset($record['txt']) && stripos($record['txt'], 'v=DMARC1') === 0) { + $records['dmarc'] = $record['txt']; + break; + } + } + } + + // DKIM - there is no list of a domain's selectors, so look at the ones the + // big senders use (Microsoft 365, Google Workspace, Mailchimp and the usual defaults) + $selectors = array(); + foreach (DOMAIN_DKIM_SELECTORS as $selector) { + $dkim = @dns_get_record("$selector._domainkey.$domain", DNS_TXT); + $cname = $dkim ? array() : @dns_get_record("$selector._domainkey.$domain", DNS_CNAME); + if (!empty($dkim) || !empty($cname)) { + $selectors[] = $selector; + } + } + $records['dkim'] = implode("\n", $selectors); + // Registration data - RDAP first, legacy whois only if the TLD has no RDAP $rdap = getDomainRdap($domain); if ($rdap !== null) { - $records['whois'] = substr(getRdapSummary($rdap), 0, 254); + $records['whois'] = substr(getRdapSummary($rdap), 0, 4000); $expires = getRdapEventDate($rdap, 'expiration'); if (!empty($expires)) { @@ -363,7 +388,7 @@ function getDnsRecords($name) { $lines = array_map(function ($line) { return preg_replace('/ +/', ' ', rtrim($line)); }, $lines); - $records['whois'] = substr(trim(strip_tags(implode("\n", $lines))), 0, 254); + $records['whois'] = substr(trim(strip_tags(implode("\n", $lines))), 0, 4000); } } @@ -467,3 +492,508 @@ function getDomainExpirationDate($domain) { return null; } + +// ============================================================ +// Domains in the app - what the list, the quick look, the forms +// and the refresher share +// ============================================================ + +/** Expiring within this many days is "soon" - the same 45 days the first expiry alert goes out at. */ +const DOMAIN_SOON_DAYS = 45; + +/** DKIM selectors looked for - Microsoft 365 (selector1, selector2), Google Workspace, the usual defaults and Mailchimp. */ +const DOMAIN_DKIM_SELECTORS = ['selector1', 'selector2', 'google', 'default', 'k1', 's1']; + +/** Who does what for a domain: each role, its column and how it is shown. */ +const DOMAIN_ROLES = [ + 'registrar' => ['column' => 'domain_registrar', 'label' => 'Registrar', 'icon' => 'fa-id-card'], + 'dnshost' => ['column' => 'domain_dnshost', 'label' => 'DNS', 'icon' => 'fa-sitemap'], + 'webhost' => ['column' => 'domain_webhost', 'label' => 'Website', 'icon' => 'fa-server'], + 'mailhost' => ['column' => 'domain_mailhost', 'label' => 'Email', 'icon' => 'fa-envelope'], +]; + +/** What each tracked column is called in a domain's history. */ +const DOMAIN_HISTORY_LABELS = [ + 'domain_name' => 'Name', 'domain_description' => 'Description', 'domain_expire' => 'Expiry', 'domain_auto_renew' => 'Auto-renew', + 'registrar_name' => 'Registrar', 'dnshost_name' => 'DNS host', 'webhost_name' => 'Web host', 'mailhost_name' => 'Mail host', + 'domain_ip' => 'A records', 'domain_name_servers' => 'Name servers', 'domain_mail_servers' => 'MX records', 'domain_txt' => 'TXT records', + 'domain_dmarc' => 'DMARC', 'domain_dkim' => 'DKIM', 'domain_raw_whois' => 'WHOIS', 'domain_notes' => 'Notes', +]; + +/** May this agent do this with domains? 1 is to see them, 2 to change them, 3 to delete them. */ +function domainCan($level) { + return lookupUserPermission('module_support') >= $level; +} + +/** The columns and joins for a domain with its client and the vendor behind each role (registrar_name, dnshost_name...). */ +function domainSelectSql() { + $columns = 'domains.*, client_name'; + $joins = 'LEFT JOIN clients ON client_id = domain_client_id'; + foreach (DOMAIN_ROLES as $role => $info) { + $columns .= ", $role.vendor_name AS {$role}_name, $role.vendor_client_id AS {$role}_client_id, $role.vendor_archived_at AS {$role}_archived_at"; + $joins .= " LEFT JOIN vendors AS $role ON $role.vendor_id = domains.{$info['column']}"; + } + return [$columns, $joins]; +} + +/** One domain by id with its client and vendors - raw, or null. */ +function domainRow($domain_id) { + global $mysqli; + $domain_id = intval($domain_id); + if (!$domain_id) { + return null; + } + [$columns, $joins] = domainSelectSql(); + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT $columns FROM domains $joins WHERE domain_id = $domain_id LIMIT 1")); + return $row ?: null; +} + +/** + * A domain name as it is kept - lowercase, without a scheme, a path, a port, + * a leading www. or a trailing dot, and international names in their ASCII + * form - from whatever was pasted ("https://www.Example.com/contact"). '' when + * it is not a domain name. + */ +function domainNormalizeName($input) { + $name = strtolower(trim(html_entity_decode((string) $input, ENT_QUOTES, 'UTF-8'))); + $name = preg_replace('#^[a-z][a-z0-9+.\-]*://#', '', $name); + $name = preg_replace('#^[^@/]*@#', '', $name); + $name = preg_split('#[/?\#\s]#', $name)[0]; + $name = preg_replace('#:\d+$#', '', $name); + $name = trim($name, '.'); + $name = preg_replace('#^www\.#', '', $name); + if ($name !== '' && preg_match('/[^\x20-\x7e]/', $name) && function_exists('idn_to_ascii')) { + $ascii = idn_to_ascii($name, IDNA_DEFAULT, INTL_IDNA_VARIANT_UTS46); + $name = $ascii ?: $name; + } + if ($name === '' || strlen($name) > 200 || strpos($name, '.') === false + || !filter_var($name, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) + || !preg_match('/\.[a-z][a-z0-9\-]*[a-z0-9]$|\.xn--[a-z0-9\-]+$/', $name)) { + return ''; + } + return $name; +} + +/** A vendor id a domain may use - one of the client's own, or one of ours (the MSP hosting DNS or mail) - else 0. */ +function domainVendorId($vendor_id, $client_id) { + global $mysqli; + $vendor_id = intval($vendor_id); + $client_id = intval($client_id); + if (!$vendor_id) { + return 0; + } + $row = mysqli_fetch_row(mysqli_query($mysqli, "SELECT vendor_id FROM vendors WHERE vendor_id = $vendor_id AND vendor_client_id IN ($client_id, 0) LIMIT 1")); + return $row ? intval($row[0]) : 0; +} + +/** The vendors a domain's pickers offer - the client's, then ours - plus any already picked, archived or not. */ +function domainVendorChoices($client_id, array $keep_ids = []) { + global $mysqli; + $client_id = intval($client_id); + $keep = implode(',', array_filter(array_map('intval', $keep_ids))) ?: '0'; + $sql = mysqli_query($mysqli, "SELECT vendor_id, vendor_name, vendor_description, vendor_client_id FROM vendors + WHERE (vendor_client_id IN ($client_id, 0) AND vendor_archived_at IS NULL) OR vendor_id IN ($keep) + ORDER BY vendor_client_id = 0, vendor_favorite DESC, vendor_name ASC"); + $rows = []; + while ($row = mysqli_fetch_assoc($sql)) { + $rows[] = $row; + } + return $rows; +} + +/** + * The fields a New / Edit form posts, as a SQL SET list, with the tidied name. + * Null with $error set when it cannot be saved: not a domain name, already on + * this client, or an expiry that is not a date. The vendors must be the + * client's or ours. + */ +function domainFormSet($post, $client_id, $domain_id = 0, &$error = '') { + global $mysqli; + $error = ''; + $client_id = intval($client_id); + $domain_id = intval($domain_id); + $name = domainNormalizeName($post['name'] ?? ''); + if ($name === '') { + $error = "That isn't a domain name - something like example.com."; + return null; + } + $name_sql = escapeSql($name); + if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM domains WHERE domain_name = '$name_sql' AND domain_client_id = $client_id AND domain_id <> $domain_id LIMIT 1"))) { + $error = "$name is already on this client."; + return null; + } + $expire = trim((string) ($post['expire'] ?? '')); + if ($expire !== '') { + $date = DateTime::createFromFormat('!Y-m-d', $expire); + if (!$date || $date->format('Y-m-d') !== $expire) { + $error = 'The expiry date is not a date.'; + return null; + } + } + $fields = [ + 'domain_name' => "'$name_sql'", + 'domain_description' => "'" . escapeSql(mb_substr(trim((string) ($post['description'] ?? '')), 0, 500)) . "'", + 'domain_expire' => $expire === '' ? 'NULL' : "'$expire'", + 'domain_auto_renew' => intval($post['auto_renew'] ?? 0) ? 1 : 0, + 'domain_favorite' => intval($post['favorite'] ?? 0) ? 1 : 0, + 'domain_notes' => "'" . escapeSql(trim((string) ($post['notes'] ?? ''))) . "'", + ]; + foreach (DOMAIN_ROLES as $role => $info) { + $fields[$info['column']] = domainVendorId($post[$role] ?? 0, $client_id); + } + $set = []; + foreach ($fields as $column => $value) { + $set[] = "$column = $value"; + } + return ['set' => implode(', ', $set), 'name' => $name, 'expire' => $expire]; +} + +/** Replace a domain's tags with these - domain tags (type 7) only. */ +function domainSetTags($domain_id, $tag_ids) { + global $mysqli; + $domain_id = intval($domain_id); + mysqli_query($mysqli, "DELETE FROM domain_tags WHERE domain_id = $domain_id"); + $tag_ids = array_values(array_unique(array_filter(array_map('intval', (array) $tag_ids)))); + if (!$tag_ids) { + return; + } + mysqli_query($mysqli, "INSERT IGNORE INTO domain_tags (domain_id, tag_id) + SELECT $domain_id, tag_id FROM tags WHERE tag_type = 7 AND tag_id IN (" . implode(',', $tag_ids) . ")"); +} + +/** + * Look a domain up - DNS (A, NS, MX, TXT, DMARC, DKIM), registration data + * and the expiry date. Null when nothing answers for it (a typo, a lapsed + * domain, or no network), so callers keep what they had rather than wiping it. + */ +function domainLookup($name) { + $name = domainNormalizeName($name); + if ($name === '' || !@checkdnsrr($name, 'SOA')) { + return null; + } + $records = getDnsRecords($name); + $expire = getDomainExpirationDate($name); + $records['expire'] = $expire ?: (string) $records['expire']; + return $records; +} + +/** + * Save what a lookup found. The expiry is the registry's when it gave one, + * otherwise the date already there stays (some registries don't publish it); + * the WHOIS summary stays when this lookup got none. False when there was + * nothing to save. + */ +function domainApplyLookup($domain_id, $lookup) { + global $mysqli; + $domain_id = intval($domain_id); + if (!$lookup || !$domain_id) { + return false; + } + $set = [ + "domain_ip = '" . escapeSql($lookup['a']) . "'", + "domain_name_servers = '" . escapeSql(mb_substr($lookup['ns'], 0, 255)) . "'", + "domain_mail_servers = '" . escapeSql(mb_substr($lookup['mx'], 0, 255)) . "'", + "domain_txt = '" . escapeSql($lookup['txt']) . "'", + "domain_dmarc = '" . escapeSql($lookup['dmarc'] ?? '') . "'", + "domain_dkim = '" . escapeSql(mb_substr($lookup['dkim'] ?? '', 0, 255)) . "'", + 'domain_refreshed_at = NOW()', + ]; + if (trim((string) $lookup['whois']) !== '') { + $set[] = "domain_raw_whois = '" . escapeSql($lookup['whois']) . "'"; + } + if (!empty($lookup['expire']) && strtotime($lookup['expire'])) { + $set[] = "domain_expire = '" . escapeSql($lookup['expire']) . "'"; + } + mysqli_query($mysqli, "UPDATE domains SET " . implode(', ', $set) . " WHERE domain_id = $domain_id"); + return true; +} + +/** What a domain's history tracks, as it stands now - compared before and after a change by domainWriteHistory(). */ +function domainHistorySnapshot($domain_id) { + $row = domainRow($domain_id); + if (!$row) { + return []; + } + $snapshot = []; + foreach (array_keys(DOMAIN_HISTORY_LABELS) as $column) { + $snapshot[$column] = (string) ($row[$column] ?? ''); + } + return $snapshot; +} + +/** Record what changed between two snapshots in the domain's history. */ +function domainWriteHistory($domain_id, array $before, array $after) { + global $mysqli; + $domain_id = intval($domain_id); + foreach ($after as $column => $new_value) { + $old_value = $before[$column] ?? ''; + if ((string) $old_value === (string) $new_value) { + continue; + } + mysqli_query($mysqli, "INSERT INTO domain_history SET domain_history_column = '" . escapeSql($column) . "', + domain_history_old_value = '" . escapeSql($old_value) . "', domain_history_new_value = '" . escapeSql($new_value) . "', + domain_history_domain_id = $domain_id"); + } +} + +/** A domain's history, newest first - each change with its label. */ +function domainHistory($domain_id, $limit = 25) { + global $mysqli; + $domain_id = intval($domain_id); + $limit = max(1, intval($limit)); + $sql = mysqli_query($mysqli, "SELECT domain_history_column, domain_history_old_value, domain_history_new_value, domain_history_modified_at + FROM domain_history WHERE domain_history_domain_id = $domain_id + ORDER BY domain_history_modified_at DESC, domain_history_id DESC LIMIT $limit"); + $rows = []; + while ($row = mysqli_fetch_assoc($sql)) { + $row['label'] = DOMAIN_HISTORY_LABELS[$row['domain_history_column']] ?? ucfirst(str_replace('_', ' ', preg_replace('/^domain_/', '', $row['domain_history_column']))); + $rows[] = $row; + } + return $rows; +} + +/** + * When it expires: 'expired', 'soon' (within 45 days) or 'active', with a + * tone, a line to show and a short form for the list. A domain set to + * auto-renew is blue rather than amber when it is close. Null without a date. + */ +function domainExpiry($expire, $auto_renew = 0) { + $renewal = softwareRenewal($expire, DOMAIN_SOON_DAYS); + if (!$renewal) { + return null; + } + $days = $renewal['days']; + $auto = intval($auto_renew) === 1; + if ($renewal['state'] === 'expired') { + $renewal['short'] = 'Expired'; + } elseif ($renewal['state'] === 'soon') { + $when = $days === 0 ? 'today' : ($days === 1 ? 'tomorrow' : "in $days days"); + $renewal['text'] = ($auto ? 'Auto-renews ' : 'Expires ') . $when; + $renewal['short'] = $days === 0 ? 'Today' : ($days === 1 ? 'Tomorrow' : "$days days"); + $renewal['tone'] = $auto ? 'info' : ($days <= 7 ? 'danger' : 'warning'); + } else { + $renewal['text'] = ($auto ? 'Auto-renews ' : 'Expires ') . timeAgo($renewal['date']); + $renewal['short'] = timeAgo($renewal['date']); + } + $renewal['auto'] = $auto; + return $renewal; +} + +/** The expiry as a soft pill - red expired, amber soon, blue soon but auto-renewing, otherwise green. */ +function domainExpiryPill($expiry, $use_text = false) { + if (!$expiry) { + return '' + . 'Unknown'; + } + $tone = $expiry['tone']; + $icon = $expiry['state'] === 'expired' ? 'fa-calendar-times' : ($expiry['auto'] ? 'fa-sync-alt' : ($expiry['state'] === 'soon' ? 'fa-hourglass-half' : 'fa-calendar-check')); + return '' + . '' . escapeHtml($use_text ? $expiry['text'] : $expiry['short']) . ''; +} + +/** A domain's tile - a globe, in the same rounded square as the other tiles. $size 'xs' | 'sm' | '' | 'lg'. */ +function domainTile($size = '') { + $size_class = in_array($size, ['xs', 'sm', 'lg'], true) ? " itflow-asset-icon-$size" . ($size === 'xs' ? ' itflow-vendor-tile-xs' : '') : ''; + return ''; +} + +/** A domain wherever a page mentions one: its tile and its name, opening its quick look. 'archived' strikes it through. */ +function domainLink($domain_id, $name, $options = []) { + $domain_id = intval($domain_id); + $label = escapeHtml(html_entity_decode((string) $name, ENT_QUOTES, 'UTF-8')); + $archived = !empty($options['archived']); + $class = trim('text-truncate ' . ($options['class'] ?? '') . ($archived ? ' text-decoration-line-through text-body-secondary' : '')); + return '' . domainTile('xs') + . "$label"; +} + +/** Record lines kept one per line (or comma-separated in older data) as a list. */ +function domainLines($text) { + return array_values(array_filter(array_map('trim', preg_split('/[\r\n,]+/', (string) $text)), 'strlen')); +} + +/** + * Who does what - each vendor with the roles it holds for this domain, so a + * registrar that also runs DNS and the website shows once: [vendor_id => + * ['name', 'client_id', 'archived', 'roles' => [labels]]]. + */ +function domainVendors($row) { + $vendors = []; + foreach (DOMAIN_ROLES as $role => $info) { + $vendor_id = intval($row[$info['column']] ?? 0); + if (!$vendor_id || ($row["{$role}_name"] ?? null) === null) { + continue; + } + if (!isset($vendors[$vendor_id])) { + $vendors[$vendor_id] = ['name' => $row["{$role}_name"], 'client_id' => intval($row["{$role}_client_id"]), 'archived' => !empty($row["{$role}_archived_at"]), 'roles' => []]; + } + $vendors[$vendor_id]['roles'][] = $info['label']; + } + return $vendors; +} + +/** The vendors as small links, each with the roles it holds. */ +function domainVendorsHtml($row) { + $html = ''; + foreach (domainVendors($row) as $vendor_id => $vendor) { + $html .= '
    ' . vendorLink($vendor_id, $vendor['name'], ['archived' => $vendor['archived']]) + . '' . escapeHtml(implode(' · ', $vendor['roles'])) . '
    '; + } + return $html; +} + +/** + * The email checks MSPs get asked about - is there mail (MX), SPF and how + * strict it is, the DMARC policy, DKIM at the common selectors. Each is + * [label, state ok|warn|bad|off|unknown, text]. DMARC and DKIM are unknown + * until the domain has been looked up since those checks existed. + */ +function domainMailChecks($row) { + $looked_up = !empty($row['domain_refreshed_at']); + $has_mail = domainLines($row['domain_mail_servers'] ?? '') !== []; + $spf = array_values(array_filter(domainLines(str_replace(',', ' ', (string) ($row['domain_txt'] ?? ''))), function ($line) { + return stripos(trim($line, '"'), 'v=spf1') === 0; + })); + $checks = []; + + $checks['mx'] = $has_mail + ? ['label' => 'MX', 'state' => 'ok', 'text' => 'Takes mail at ' . implode(', ', array_map(function ($mx) { return preg_replace('/^\d+\s+/', '', $mx); }, array_slice(domainLines($row['domain_mail_servers']), 0, 2)))] + : ['label' => 'MX', 'state' => 'off', 'text' => 'No mail servers - it takes no email']; + + if (count($spf) > 1) { + $checks['spf'] = ['label' => 'SPF', 'state' => 'bad', 'text' => count($spf) . ' SPF records - receivers treat that as no SPF at all. Merge them into one.']; + } elseif (!$spf) { + $checks['spf'] = ['label' => 'SPF', 'state' => $has_mail ? 'bad' : 'warn', 'text' => $has_mail ? 'No SPF record - anyone can send as this domain' : 'No SPF record - add "v=spf1 -all" so nobody can send as it']; + } else { + $record = trim($spf[0], '"'); + if (preg_match('/[\-~]all\b/i', $record) || stripos($record, 'redirect=') !== false) { + $checks['spf'] = ['label' => 'SPF', 'state' => 'ok', 'text' => (stripos($record, '-all') !== false ? 'SPF, hard fail (-all)' : (stripos($record, '~all') !== false ? 'SPF, soft fail (~all)' : 'SPF, redirected')) . ': ' . $record]; + } else { + $checks['spf'] = ['label' => 'SPF', 'state' => 'warn', 'text' => 'SPF that lets anyone through (no -all or ~all): ' . $record]; + } + } + + $dmarc = trim((string) ($row['domain_dmarc'] ?? '')); + if (!$looked_up && $dmarc === '') { + $checks['dmarc'] = ['label' => 'DMARC', 'state' => 'unknown', 'text' => 'Not checked yet - look the domain up']; + } elseif ($dmarc === '') { + $checks['dmarc'] = ['label' => 'DMARC', 'state' => $has_mail ? 'bad' : 'warn', 'text' => 'No DMARC record']; + } else { + $policy = preg_match('/\bp\s*=\s*(none|quarantine|reject)/i', $dmarc, $match) ? strtolower($match[1]) : 'none'; + $checks['dmarc'] = $policy === 'none' + ? ['label' => 'DMARC', 'state' => 'warn', 'text' => 'DMARC p=none - reports only, spoofed mail still delivered: ' . $dmarc] + : ['label' => 'DMARC', 'state' => 'ok', 'text' => "DMARC p=$policy: $dmarc"]; + } + + $dkim = domainLines($row['domain_dkim'] ?? ''); + if (!$looked_up && !$dkim) { + $checks['dkim'] = ['label' => 'DKIM', 'state' => 'unknown', 'text' => 'Not checked yet - look the domain up']; + } elseif ($dkim) { + $checks['dkim'] = ['label' => 'DKIM', 'state' => 'ok', 'text' => 'DKIM at ' . implode(', ', $dkim)]; + } else { + $checks['dkim'] = ['label' => 'DKIM', 'state' => $has_mail ? 'warn' : 'off', 'text' => 'No DKIM at the usual selectors (' . implode(', ', DOMAIN_DKIM_SELECTORS) . ') - it may use another']; + } + return $checks; +} + +/** The email checks as small pills - green, amber, red, grey. */ +function domainMailPillsHtml(array $checks) { + $tones = ['ok' => 'success', 'warn' => 'warning', 'bad' => 'danger', 'off' => 'secondary', 'unknown' => 'secondary']; + $icons = ['ok' => 'fa-check', 'warn' => 'fa-exclamation', 'bad' => 'fa-times', 'off' => 'fa-minus', 'unknown' => 'fa-question']; + $html = ''; + foreach ($checks as $check) { + $tone = $tones[$check['state']]; + $html .= '' + . '' . escapeHtml($check['label']) . ''; + } + return '' . $html . ''; +} + +/** The SQL for "takes mail but SPF is missing or DMARC is missing or only p=none" - the Email gaps filter. */ +function domainMailGapSql($alias = 'domains') { + return "(COALESCE($alias.domain_mail_servers, '') <> '' AND (COALESCE($alias.domain_txt, '') NOT LIKE '%v=spf1%' + OR ($alias.domain_refreshed_at IS NOT NULL AND (COALESCE($alias.domain_dmarc, '') = '' OR $alias.domain_dmarc LIKE '%p=none%'))))"; +} + +/** The registration facts in the WHOIS summary - registrar, registered, status - when it has them one per line. */ +function domainRegistrationFacts($whois) { + $facts = []; + foreach (['registrar' => 'Registrar', 'registered' => 'Registered', 'status' => 'Status'] as $key => $label) { + if (preg_match('/^' . $label . ':\s*(.+)$/mi', (string) $whois, $match) && strpos((string) $whois, "\n") !== false) { + $facts[$key] = trim($match[1]); + } + } + return $facts; +} + +/** The certificates for a domain - linked to it, or for it or one of its subdomains on the same client. */ +function domainCertificates($row) { + global $mysqli; + $domain_id = intval($row['domain_id']); + $client_id = intval($row['domain_client_id']); + $name = escapeSql($row['domain_name']); + $name_like = escapeSql(str_replace(['\\', '%', '_'], ['\\\\', '\%', '\_'], $row['domain_name'])); + $sql = mysqli_query($mysqli, "SELECT certificate_id, certificate_name, certificate_domain, certificate_issued_by, certificate_expire FROM certificates + WHERE certificate_archived_at IS NULL AND certificate_client_id = $client_id + AND (certificate_domain_id = $domain_id OR certificate_domain = '$name' OR certificate_domain LIKE '%.$name_like') + ORDER BY certificate_expire IS NULL, certificate_expire ASC"); + $rows = []; + while ($cert = mysqli_fetch_assoc($sql)) { + $rows[] = $cert; + } + return $rows; +} + +/** The services that use a domain. */ +function domainServices($domain_id) { + global $mysqli; + $domain_id = intval($domain_id); + $sql = mysqli_query($mysqli, "SELECT services.service_id, service_name, service_importance FROM service_domains + JOIN services ON services.service_id = service_domains.service_id WHERE service_domains.domain_id = $domain_id ORDER BY service_name"); + $rows = []; + while ($service = mysqli_fetch_assoc($sql)) { + $rows[] = $service; + } + return $rows; +} + +/** The client's logins for the domain's registrar and hosts - linked to those vendors - for those who may see credentials. */ +function domainLogins($row) { + $vendor_ids = array_keys(domainVendors($row)); + if (!$vendor_ids || lookupUserPermission('module_credential') < 1) { + return []; + } + $client_id = intval($row['domain_client_id']); + return credentialRows("credential_client_id = $client_id AND credential_id IN (SELECT credential_id FROM vendor_credentials WHERE vendor_id IN (" . implode(',', array_map('intval', $vendor_ids)) . "))"); +} + +/** Deleting a domain for good - services stop listing it and certificates stop pointing at it. History and tags cascade. */ +function domainDeleteForGood($domain_id) { + global $mysqli; + $domain_id = intval($domain_id); + mysqli_query($mysqli, "DELETE FROM service_domains WHERE domain_id = $domain_id"); + mysqli_query($mysqli, "UPDATE certificates SET certificate_domain_id = 0 WHERE certificate_domain_id = $domain_id"); + mysqli_query($mysqli, "DELETE FROM domains WHERE domain_id = $domain_id"); +} + +/** + * Bring an SSL certificate for a new domain in, when its website has one and + * the client has none for that name yet. True when one was added. + */ +function domainAddCertificate($domain_id, $name, $client_id) { + global $mysqli; + $domain_id = intval($domain_id); + $client_id = intval($client_id); + $name_sql = escapeSql($name); + if (mysqli_num_rows(mysqli_query($mysqli, "SELECT 1 FROM certificates WHERE certificate_client_id = $client_id AND certificate_domain IN ('$name_sql', 'www.$name_sql') LIMIT 1"))) { + return false; + } + $certificate = getSslCertificate($name); + if (empty($certificate['success'])) { + return false; + } + mysqli_query($mysqli, "INSERT INTO certificates SET certificate_name = '$name_sql', certificate_domain = '$name_sql', + certificate_issued_by = '" . escapeSql($certificate['issued_by']) . "', certificate_expire = '" . escapeSql($certificate['expire']) . "', + certificate_public_key = '" . escapeSql($certificate['public_key']) . "', certificate_domain_id = $domain_id, certificate_client_id = $client_id"); + return true; +} diff --git a/functions/export.php b/functions/export.php index 575e8e9f3..777c0aff4 100644 --- a/functions/export.php +++ b/functions/export.php @@ -187,6 +187,15 @@ function getExportColumns($export_type) { 'domain_registrar' => ['label' => 'Registrar', 'field' => 'domain_registrar_name'], 'domain_webhost' => ['label' => 'Web Host', 'field' => 'domain_webhost_name'], 'domain_expire' => ['label' => 'Expiration Date'], + 'domain_dnshost' => ['label' => 'DNS Host', 'field' => 'domain_dnshost_name', 'default' => false], + 'domain_mailhost' => ['label' => 'Mail Host', 'field' => 'domain_mailhost_name', 'default' => false], + 'domain_auto_renew' => ['label' => 'Auto-renew', 'field' => 'domain_auto_renew_label', 'default' => false], + 'domain_name_servers' => ['label' => 'Name Servers', 'weight' => 2, 'default' => false], + 'domain_mail_servers' => ['label' => 'MX Records', 'weight' => 2, 'default' => false], + 'domain_dmarc' => ['label' => 'DMARC', 'weight' => 2, 'default' => false], + 'domain_tags' => ['label' => 'Tags', 'weight' => 2, 'default' => false], + 'domain_notes' => ['label' => 'Notes', 'weight' => 3, 'default' => false], + 'client_name' => ['label' => 'Client', 'weight' => 2, 'default' => false], ], // Defaults match what this export has always emitted, secrets included. diff --git a/functions/search.php b/functions/search.php index e171addf0..720c59b07 100644 --- a/functions/search.php +++ b/functions/search.php @@ -287,18 +287,19 @@ function globalSearchGroups($terms, $deep) { $groups[] = [ 'key' => 'domains', 'label' => 'Domains', 'icon' => 'globe', 'module' => 'module_support', - 'select' => 'domain_id, domain_name, domain_expire, domain_client_id, client_name', + 'select' => 'domain_id, domain_name, domain_description, domain_expire, domain_auto_renew, domain_client_id, client_name', 'from' => 'domains LEFT JOIN clients ON domain_client_id = client_id', - 'where' => "domain_archived_at IS NULL AND domain_name LIKE '%$like%'", + 'where' => "domain_archived_at IS NULL AND (domain_name LIKE '%$like%' OR domain_description LIKE '%$like%')", 'scope' => 'domain_client_id', 'order' => "(domain_name = '$eq') DESC, (domain_name LIKE '$like%') DESC, domain_name", 'list_url' => '/agent/domains.php?' . http_build_query(['q' => $q]), 'item' => function ($row) { return [ 'title' => $row['domain_name'], - 'subtitle' => $row['domain_expire'] ? 'Expires ' . $row['domain_expire'] : '', + 'subtitle' => implode(' · ', array_filter([($expiry = domainExpiry($row['domain_expire'], $row['domain_auto_renew'])) ? $expiry['text'] : '', $row['domain_description']])), 'context' => $row['client_name'], - 'url' => globalSearchClientUrl('domains.php', $row['domain_client_id'], ['q' => $row['domain_name']]), + // Straight to its quick look on the client's domains page + 'url' => globalSearchClientUrl('domains.php', $row['domain_client_id'], ['open' => intval($row['domain_id'])]), ]; }, ]; diff --git a/functions/tags.php b/functions/tags.php index 5465b2bb3..5b277e8f3 100644 --- a/functions/tags.php +++ b/functions/tags.php @@ -1,7 +1,7 @@ [ @@ -50,6 +50,12 @@ function tagEntity($entity) { 'table' => 'vendors', 'id' => 'vendor_id', 'client' => 'vendor_client_id', 'name' => 'vendor_name', 'log' => 'Vendor', 'list' => 'vendors.php' ], + 'domain' => [ + 'type' => 7, 'label' => 'domain', 'module' => 'module_support', + 'link_table' => 'domain_tags', 'link_record' => 'domain_id', 'link_tag' => 'tag_id', + 'table' => 'domains', 'id' => 'domain_id', 'client' => 'domain_client_id', 'name' => 'domain_name', + 'log' => 'Domain', 'list' => 'domains.php' + ], ]; return $entities[$entity] ?? null; diff --git a/includes/cron_jobs.php b/includes/cron_jobs.php index f3504c86e..0a0563775 100644 --- a/includes/cron_jobs.php +++ b/includes/cron_jobs.php @@ -71,7 +71,7 @@ function cronJobRegistry(): array 'name' => 'domain_refresher', 'label' => 'Domain Refresher', 'script' => 'domain_refresher.php', - 'description' => 'Refreshes WHOIS and DNS for the domain that was checked longest ago. One domain per run.', + 'description' => 'Looks up DNS, registration and expiry for domains that are due - never looked up, not in a week, or expiring within 60 days. Up to 50 a run.', 'schedule' => 'Daily', 'daily_at' => '04:00', ],
    DomainThey areExpires
    DomainThey areExpires
    - -
    +
    + +
    + +
    +
    +
    -' ?>
    Domain Name ExpiryRenews automatically
    + + + + +