WebOrbiton

Code

PriviMetrics 2

Modern, fast analytics for your websites.

Version history

Version 1.1.4 2026-11-20

Browse files
Files changed15
Lines added+1246
Lines removed-8
.htaccess Modified +1 -1
⋮ 14 unchanged lines ⋮
      </IfModule>
  </FilesMatch>
  
- <FilesMatch "^(functions|storage|sources|version|updater-functions|cron-update)\.php$">
+ <FilesMatch "^(functions|storage|sources|stats|version|updater-functions|cron-update)\.php$">
      Require all denied
      <IfModule !mod_authz_core.c>
          Order deny,allow
⋮ 24 unchanged lines ⋮
api.php Added +97 -0
+ <?php
+ 
+ declare(strict_types=1);
+ require_once __DIR__ . '/functions.php';
+ 
+ header('Content-Type: application/json; charset=utf-8');
+ header('X-Content-Type-Options: nosniff');
+ header('Access-Control-Allow-Origin: *');
+ header('Access-Control-Allow-Methods: GET, OPTIONS');
+ header('Access-Control-Allow-Headers: Authorization, X-API-Key');
+ 
+ function pmApiRespond(int $status, array $body, int $cacheSeconds = 0): void
+ {
+     http_response_code($status);
+     header($cacheSeconds > 0 ? 'Cache-Control: public, max-age=' . $cacheSeconds : 'Cache-Control: no-store');
+     $flags = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE;
+     if (pmQueryString('pretty') === '1') $flags |= JSON_PRETTY_PRINT;
+     echo json_encode($body, $flags);
+     exit;
+ }
+ 
+ if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'OPTIONS') {
+     http_response_code(204);
+     exit;
+ }
+ 
+ if (!envIsInstalled()) {
+     pmApiRespond(503, ['error' => 'PriviMetrics is not installed yet.']);
+ }
+ 
+ require_once __DIR__ . '/storage.php';
+ require_once __DIR__ . '/stats.php';
+ 
+ $key = trim((string) ($_SERVER['HTTP_X_API_KEY'] ?? ''));
+ if ($key === '' && preg_match('/^Bearer\s+(\S+)$/i', (string) ($_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? ''), $m)) {
+     $key = $m[1];
+ }
+ if ($key === '') {
+     $key = trim(pmQueryString('key'));
+ }
+ $code = trim(pmQueryString('site'));
+ 
+ $storage = new StorageManager();
+ $site = null;
+ $fields = [];
+ $private = false;
+ 
+ if ($key !== '') {
+     foreach ($storage->listSites() as $candidate) {
+         $candidateKey = (string) ($candidate['api_key'] ?? '');
+         if ($candidateKey !== '' && !empty($candidate['api_key_enabled']) && hash_equals($candidateKey, $key)) {
+             $site = $candidate;
+             break;
+         }
+     }
+     if (!$site) {
+         pmApiRespond(401, ['error' => 'This API key is not valid or API key access is turned off.']);
+     }
+     $private = true;
+     $fields = PM_API_ALL_FIELDS;
+ } elseif ($code !== '') {
+     $site = $storage->findSiteByTrackingCode($code);
+     if (!$site || empty($site['api_public'])) {
+         pmApiRespond(404, ['error' => 'Public stats are not available for this site.']);
+     }
+     $fields = array_filter(explode(',', pmValidApiFields($site['api_public_fields'] ?? PM_API_DEFAULT_PUBLIC_FIELDS)));
+     if (!$fields) {
+         pmApiRespond(404, ['error' => 'This site does not share any public stats.']);
+     }
+ } else {
+     pmApiRespond(400, [
+         'error' => 'Pass ?site=TRACKING_CODE for public stats, or send your API key in the X-API-Key header.',
+         'params' => ['range' => implode('|', array_keys(PM_RANGE_OPTIONS)), 'from' => 'YYYY-MM-DD (range=custom)', 'to' => 'YYYY-MM-DD (range=custom)', 'limit' => '1-1000, default 10', 'pretty' => '1'],
+     ]);
+ }
+ 
+ $clientId = $private ? 'key' : getClientIP();
+ if (!checkRateLimit('api_' . $site['id'] . '_' . $clientId, $private ? 120 : 60, 60)) {
+     header('Retry-After: 60');
+     pmApiRespond(429, ['error' => 'Too many requests. Try again in a minute.']);
+ }
+ 
+ $limit = max(1, min(1000, (int) pmQueryString('limit', '10')));
+ $data = pmComputeSiteStats(
+     $storage,
+     $site,
+     pmQueryString('range', '30d'),
+     pmQueryString('from'),
+     pmQueryString('to'),
+     array_values($fields),
+     $limit
+ );
+ $data['access'] = $private ? 'api_key' : 'public';
+ $data['generated_at'] = date('c');
+ 
+ pmApiRespond(200, $data, $private ? 0 : 60);
+ 
assets/dashboard-ui.js Added +293 -0
+ (function () {
+   var CHEVRON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"></polyline></svg>'
+   var CHECK = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"></polyline></svg>'
+   var PREV = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"></polyline></svg>'
+   var NEXT = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="9 18 15 12 9 6"></polyline></svg>'
+ 
+   var openPopover = null
+ 
+   function closeOpen(except) {
+     if (openPopover && openPopover !== except) {
+       openPopover.close()
+       openPopover = null
+     }
+   }
+ 
+   document.addEventListener("mousedown", function (evt) {
+     if (openPopover && !openPopover.root.contains(evt.target)) closeOpen()
+   })
+ 
+   document.addEventListener("keydown", function (evt) {
+     if (evt.key === "Escape" && openPopover) {
+       var current = openPopover
+       closeOpen()
+       if (current.focusTrigger) current.focusTrigger()
+     }
+   })
+ 
+   function enhanceSelect(select) {
+     var wrap = document.createElement("div")
+     wrap.className = "pm-select"
+     select.parentNode.insertBefore(wrap, select)
+     wrap.appendChild(select)
+     select.classList.add("pm-select-native")
+     select.tabIndex = -1
+     select.setAttribute("aria-hidden", "true")
+ 
+     var button = document.createElement("button")
+     button.type = "button"
+     button.className = "pm-select-btn"
+     button.setAttribute("aria-haspopup", "listbox")
+     button.setAttribute("aria-expanded", "false")
+     if (select.getAttribute("aria-label")) button.setAttribute("aria-label", select.getAttribute("aria-label"))
+     var label = document.createElement("span")
+     label.className = "pm-select-label"
+     button.appendChild(label)
+     button.insertAdjacentHTML("beforeend", '<span class="pm-select-chevron">' + CHEVRON + "</span>")
+     wrap.appendChild(button)
+ 
+     var menu = document.createElement("div")
+     menu.className = "pm-select-menu"
+     menu.setAttribute("role", "listbox")
+     menu.hidden = true
+     wrap.appendChild(menu)
+ 
+     var items = []
+     Array.prototype.forEach.call(select.options, function (opt, index) {
+       var item = document.createElement("div")
+       item.className = "pm-select-option"
+       item.setAttribute("role", "option")
+       item.tabIndex = -1
+       item.dataset.index = String(index)
+       item.innerHTML = '<span class="pm-select-check">' + CHECK + "</span>"
+       var text = document.createElement("span")
+       text.textContent = opt.textContent
+       item.appendChild(text)
+       item.addEventListener("click", function () { choose(index) })
+       item.addEventListener("mousemove", function () { if (document.activeElement !== item) item.focus({ preventScroll: true }) })
+       menu.appendChild(item)
+       items.push(item)
+     })
+ 
+     function sync() {
+       var opt = select.options[select.selectedIndex]
+       label.textContent = opt ? opt.textContent : ""
+       items.forEach(function (item, i) {
+         var selected = i === select.selectedIndex
+         item.classList.toggle("selected", selected)
+         item.setAttribute("aria-selected", selected ? "true" : "false")
+       })
+     }
+ 
+     function choose(index) {
+       var changed = select.selectedIndex !== index
+       select.selectedIndex = index
+       sync()
+       api.close()
+       openPopover = null
+       button.focus()
+       if (changed || select.options[index].value === "custom") select.dispatchEvent(new Event("change", { bubbles: true }))
+     }
+ 
+     var api = {
+       root: wrap,
+       open: function () {
+         closeOpen(api)
+         menu.hidden = false
+         wrap.classList.add("open")
+         button.setAttribute("aria-expanded", "true")
+         openPopover = api
+         var current = items[select.selectedIndex] || items[0]
+         if (current) current.focus({ preventScroll: true })
+       },
+       close: function () {
+         menu.hidden = true
+         wrap.classList.remove("open")
+         button.setAttribute("aria-expanded", "false")
+       },
+       focusTrigger: function () { button.focus() }
+     }
+ 
+     button.addEventListener("click", function () {
+       if (menu.hidden) api.open()
+       else { api.close(); openPopover = null }
+     })
+     button.addEventListener("keydown", function (evt) {
+       if (evt.key === "ArrowDown" || evt.key === "ArrowUp") {
+         evt.preventDefault()
+         api.open()
+       }
+     })
+     menu.addEventListener("keydown", function (evt) {
+       var index = items.indexOf(document.activeElement)
+       if (evt.key === "ArrowDown") { evt.preventDefault(); items[Math.min(items.length - 1, index + 1)].focus() }
+       else if (evt.key === "ArrowUp") { evt.preventDefault(); items[Math.max(0, index - 1)].focus() }
+       else if (evt.key === "Home") { evt.preventDefault(); items[0].focus() }
+       else if (evt.key === "End") { evt.preventDefault(); items[items.length - 1].focus() }
+       else if (evt.key === "Enter" || evt.key === " ") { evt.preventDefault(); if (index >= 0) choose(index) }
+       else if (evt.key === "Tab") { api.close(); openPopover = null }
+     })
+ 
+     sync()
+   }
+ 
+   function parseDay(value) {
+     var m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value || "")
+     return m ? new Date(+m[1], +m[2] - 1, +m[3]) : null
+   }
+ 
+   function formatDay(date) {
+     var m = String(date.getMonth() + 1).padStart(2, "0")
+     var d = String(date.getDate()).padStart(2, "0")
+     return date.getFullYear() + "-" + m + "-" + d
+   }
+ 
+   function sameDay(a, b) {
+     return a && b && a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
+   }
+ 
+   function enhanceDateRange(form) {
+     var fromInput = form.querySelector('input[name="from"]')
+     var toInput = form.querySelector('input[name="to"]')
+     var fields = { from: form.querySelector('[data-date-field="from"]'), to: form.querySelector('[data-date-field="to"]') }
+     var popover = form.querySelector(".date-popover")
+     var max = parseDay(form.getAttribute("data-max")) || new Date()
+     var locale = document.documentElement.lang || "en"
+     var displayFormat = new Intl.DateTimeFormat(locale, { day: "numeric", month: "short", year: "numeric" })
+     var monthFormat = new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" })
+     var weekdayFormat = new Intl.DateTimeFormat(locale, { weekday: "short" })
+     var active = "from"
+     var view = null
+     var hover = null
+ 
+     function value(name) { return parseDay((name === "from" ? fromInput : toInput).value) }
+ 
+     function syncFields() {
+       ;["from", "to"].forEach(function (name) {
+         var d = value(name)
+         fields[name].querySelector(".date-field-value").textContent = d ? displayFormat.format(d) : "Select date"
+         fields[name].classList.toggle("active", !popover.hidden && active === name)
+         fields[name].setAttribute("aria-expanded", !popover.hidden && active === name ? "true" : "false")
+       })
+     }
+ 
+     function render() {
+       var from = value("from")
+       var to = value("to")
+       var rangeEnd = to
+       if (active === "to" && from && hover) rangeEnd = hover
+       var lo = from, hi = rangeEnd
+       if (lo && hi && hi < lo) { var t = lo; lo = hi; hi = t }
+ 
+       var first = new Date(view.getFullYear(), view.getMonth(), 1)
+       var offset = (first.getDay() + 6) % 7
+       var start = new Date(first.getFullYear(), first.getMonth(), 1 - offset)
+       var nextMonth = new Date(view.getFullYear(), view.getMonth() + 1, 1)
+ 
+       var html = '<div class="dp-head">'
+         + '<button type="button" class="dp-nav" data-nav="-1" aria-label="Previous month">' + PREV + "</button>"
+         + '<div class="dp-title">' + monthFormat.format(first) + "</div>"
+         + '<button type="button" class="dp-nav" data-nav="1" aria-label="Next month"' + (nextMonth > max ? " disabled" : "") + ">" + NEXT + "</button>"
+         + '</div><div class="dp-grid" role="grid">'
+       for (var w = 0; w < 7; w++) {
+         html += '<div class="dp-weekday">' + weekdayFormat.format(new Date(2024, 0, 1 + w)).slice(0, 2) + "</div>"
+       }
+       var today = new Date()
+       for (var i = 0; i < 42; i++) {
+         var day = new Date(start.getFullYear(), start.getMonth(), start.getDate() + i)
+         var cls = ["dp-day"]
+         if (day.getMonth() !== first.getMonth()) cls.push("outside")
+         if (sameDay(day, today)) cls.push("today")
+         if (lo && hi && day > lo && day < hi) cls.push("in-range")
+         if (sameDay(day, lo)) cls.push("range-start")
+         if (sameDay(day, hi)) cls.push("range-end")
+         var disabled = day > max
+         html += '<button type="button" class="' + cls.join(" ") + '" data-day="' + formatDay(day) + '"' + (disabled ? " disabled" : "") + ">" + day.getDate() + "</button>"
+       }
+       html += '</div><div class="dp-foot"><span class="dp-hint">' + (active === "from" ? "Pick the start date" : "Pick the end date") + "</span>"
+         + '<button type="button" class="dp-today" data-day="' + formatDay(max) + '">Today</button></div>'
+       popover.innerHTML = html
+     }
+ 
+     function pick(dayStr) {
+       var day = parseDay(dayStr)
+       if (!day || day > max) return
+       if (active === "from") {
+         fromInput.value = dayStr
+         var to = value("to")
+         if (to && to < day) toInput.value = dayStr
+         active = "to"
+         hover = null
+         syncFields()
+         render()
+         return
+       }
+       var from = value("from")
+       if (from && day < from) {
+         toInput.value = fromInput.value
+         fromInput.value = dayStr
+       } else {
+         toInput.value = dayStr
+       }
+       api.close()
+       openPopover = null
+       syncFields()
+       form.querySelector('button[type="submit"]').focus()
+     }
+ 
+     var api = {
+       root: form,
+       open: function (name) {
+         closeOpen(api)
+         active = name
+         var base = value(name) || value("from") || max
+         view = new Date(base.getFullYear(), base.getMonth(), 1)
+         popover.hidden = false
+         openPopover = api
+         render()
+         syncFields()
+       },
+       close: function () {
+         popover.hidden = true
+         hover = null
+         syncFields()
+       },
+       focusTrigger: function () { fields[active].focus() }
+     }
+ 
+     ;["from", "to"].forEach(function (name) {
+       fields[name].addEventListener("click", function () {
+         if (!popover.hidden && active === name) { api.close(); openPopover = null }
+         else api.open(name)
+       })
+     })
+ 
+     popover.addEventListener("click", function (evt) {
+       var nav = evt.target.closest("[data-nav]")
+       if (nav) {
+         view = new Date(view.getFullYear(), view.getMonth() + Number(nav.getAttribute("data-nav")), 1)
+         render()
+         return
+       }
+       var dayBtn = evt.target.closest("[data-day]")
+       if (dayBtn && !dayBtn.disabled) pick(dayBtn.getAttribute("data-day"))
+     })
+ 
+     popover.addEventListener("mouseover", function (evt) {
+       var dayBtn = evt.target.closest(".dp-day")
+       if (active !== "to" || !dayBtn || dayBtn.disabled) return
+       var d = parseDay(dayBtn.getAttribute("data-day"))
+       if (!sameDay(d, hover)) {
+         hover = d
+         render()
+       }
+     })
+ 
+     form.addEventListener("pm:open-range", function () { api.open("from") })
+     syncFields()
+   }
+ 
+   document.querySelectorAll("select[data-enhance]").forEach(enhanceSelect)
+   document.querySelectorAll("[data-date-range]").forEach(enhanceDateRange)
+ })()
+ 
assets/export.js Added +535 -0
+ (function () {
+   var dataEl = document.getElementById("pmExportData")
+   var modal = document.getElementById("exportModal")
+   if (!dataEl || !modal) return
+ 
+   var DATA = JSON.parse(dataEl.textContent)
+   var STORE_KEY = "pmExportPrefs"
+   var W = 1240
+   var PAGE_H = 1754
+   var PAD = 72
+   var C = {
+     bg: "#ffffff", text: "#16171a", muted: "#6b6d73", faint: "#9799a0", border: "#e5e5e7",
+     soft: "#f5f5f6", accent: "#f1484e", accentDark: "#d53b40", accentSoft: "#fdeced", future: "#d4d4d8", empty: "#eab308"
+   }
+   var FONT = getComputedStyle(document.body).fontFamily || "system-ui, sans-serif"
+ 
+   var baseSections = [
+     { id: "summary", title: "Summary" },
+     { id: "timeline", title: "Visits over time" }
+   ]
+   if (DATA.map) baseSections.push({ id: "map", title: "Visitor map" })
+   var allSections = baseSections.concat(DATA.sections.map(function (s) { return { id: s.id, title: s.title, count: s.rows.length } }))
+ 
+   function loadPrefs() {
+     try { return JSON.parse(localStorage.getItem(STORE_KEY) || "null") || {} } catch (_) { return {} }
+   }
+ 
+   function savePrefs(prefs) {
+     try { localStorage.setItem(STORE_KEY, JSON.stringify(prefs)) } catch (_) { }
+   }
+ 
+   var listEl = modal.querySelector("[data-export-sections]")
+   var prefs = loadPrefs()
+   var disabled = prefs.disabled || []
+ 
+   allSections.forEach(function (s) {
+     var row = document.createElement("label")
+     row.className = "export-section"
+     var input = document.createElement("input")
+     input.type = "checkbox"
+     input.value = s.id
+     input.checked = disabled.indexOf(s.id) === -1
+     var name = document.createElement("span")
+     name.className = "export-section-name"
+     name.textContent = s.title
+     row.appendChild(input)
+     row.insertAdjacentHTML("beforeend", '<span class="export-check" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg></span>')
+     row.appendChild(name)
+     if (typeof s.count === "number") {
+       var count = document.createElement("span")
+       count.className = "export-section-count"
+       count.textContent = s.count === 0 ? "empty" : s.count + (s.count === 1 ? " row" : " rows")
+       row.appendChild(count)
+     }
+     listEl.appendChild(row)
+   })
+ 
+   if (prefs.format) {
+     var fmt = modal.querySelector('input[name="exportFormat"][value="' + prefs.format + '"]')
+     if (fmt) fmt.checked = true
+   }
+   if (prefs.rows) modal.querySelector("#exportRows").value = prefs.rows
+ 
+   modal.querySelector("[data-export-all]").addEventListener("click", function () {
+     listEl.querySelectorAll("input").forEach(function (i) { i.checked = true })
+   })
+   modal.querySelector("[data-export-none]").addEventListener("click", function () {
+     listEl.querySelectorAll("input").forEach(function (i) { i.checked = false })
+   })
+ 
+   function currentOptions() {
+     var selected = []
+     var off = []
+     listEl.querySelectorAll("input").forEach(function (i) { (i.checked ? selected : off).push(i.value) })
+     var format = modal.querySelector('input[name="exportFormat"]:checked').value
+     var rows = modal.querySelector("#exportRows").value
+     savePrefs({ format: format, rows: rows, disabled: off })
+     return { format: format, rows: rows === "all" ? Infinity : parseInt(rows, 10), sections: selected }
+   }
+ 
+   function fileBase() {
+     var slug = String(DATA.site.domain || DATA.site.name).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "site"
+     return "privimetrics-" + slug + "-" + DATA.range.from + "_" + DATA.range.to
+   }
+ 
+   function download(blob, name) {
+     var url = URL.createObjectURL(blob)
+     var a = document.createElement("a")
+     a.href = url
+     a.download = name
+     document.body.appendChild(a)
+     a.click()
+     a.remove()
+     setTimeout(function () { URL.revokeObjectURL(url) }, 4000)
+   }
+ 
+   function nf(n) { return Number(n).toLocaleString("en-US") }
+ 
+   function periodText() {
+     return DATA.range.from === DATA.range.to ? DATA.range.from : DATA.range.from + " to " + DATA.range.to
+   }
+ 
+   function sectionRows(id, limit) {
+     var s = DATA.sections.filter(function (x) { return x.id === id })[0]
+     return s ? s.rows.slice(0, limit) : []
+   }
+ 
+   function buildText(opts) {
+     var out = []
+     var line = new Array(64).join("=")
+     out.push(DATA.app + " report", line)
+     out.push("Site:      " + DATA.site.name + " (" + DATA.site.domain + ")")
+     out.push("Period:    " + DATA.range.label + ", " + periodText())
+     out.push("Generated: " + DATA.generated, "")
+     opts.sections.forEach(function (id) {
+       if (id === "summary") {
+         out.push("SUMMARY", new Array(64).join("-"))
+         out.push("Page views:       " + nf(DATA.summary.views))
+         out.push("Unique visitors:  " + nf(DATA.summary.unique), "")
+       } else if (id === "timeline") {
+         out.push("VISITS OVER TIME", new Array(64).join("-"))
+         DATA.timeline.forEach(function (t) { if (!t[2]) out.push(padRight(t[0], 16) + padLeft(nf(t[1]), 10)) })
+         out.push("")
+       } else if (id === "map") {
+         return
+       } else {
+         var s = DATA.sections.filter(function (x) { return x.id === id })[0]
+         if (!s) return
+         out.push(s.title.toUpperCase(), new Array(64).join("-"))
+         var rows = s.rows.slice(0, opts.rows)
+         if (!rows.length) out.push("(no data for this period)")
+         rows.forEach(function (r, i) {
+           var name = r.name + (r.code ? " [" + r.code + "]" : "") + (r.badge ? " (" + r.badge + ")" : "")
+           out.push(padLeft(String(i + 1), 3) + ". " + padRight(name, 48) + padLeft(nf(r.count), 10))
+         })
+         if (s.rows.length > rows.length) out.push("     ... and " + (s.rows.length - rows.length) + " more")
+         out.push("")
+       }
+     })
+     out.push(line, "Generated locally by PriviMetrics. No data left your server.")
+     return out.join("\r\n")
+   }
+ 
+   function padRight(s, n) { s = String(s); return s.length >= n ? s.slice(0, n - 1) + " " : s + new Array(n - s.length + 1).join(" ") }
+   function padLeft(s, n) { s = String(s); return s.length >= n ? s : new Array(n - s.length + 1).join(" ") + s }
+ 
+   function font(weight, size) { return weight + " " + size + "px " + FONT }
+ 
+   function fit(ctx, text, maxW) {
+     text = String(text)
+     if (ctx.measureText(text).width <= maxW) return text
+     while (text.length > 1 && ctx.measureText(text + "…").width > maxW) text = text.slice(0, -1)
+     return text + "…"
+   }
+ 
+   function roundRect(ctx, x, y, w, h, r) {
+     ctx.beginPath()
+     ctx.moveTo(x + r, y)
+     ctx.arcTo(x + w, y, x + w, y + h, r)
+     ctx.arcTo(x + w, y + h, x, y + h, r)
+     ctx.arcTo(x, y + h, x, y, r)
+     ctx.arcTo(x, y, x + w, y, r)
+     ctx.closePath()
+   }
+ 
+   function loadImage(src) {
+     return new Promise(function (resolve) {
+       var img = new Image()
+       img.onload = function () { resolve(img) }
+       img.onerror = function () { resolve(null) }
+       img.src = src
+     })
+   }
+ 
+   function buildBlocks(opts, images) {
+     var blocks = []
+     var inner = W - PAD * 2
+ 
+     blocks.push({
+       h: 150, keep: true, draw: function (ctx, y) {
+         roundRect(ctx, PAD, y + 8, 64, 64, 16)
+         var g = ctx.createLinearGradient(PAD, y + 8, PAD + 64, y + 72)
+         g.addColorStop(0, "#f67a7e"); g.addColorStop(1, C.accentDark)
+         ctx.fillStyle = g; ctx.fill()
+         if (images.logo) ctx.drawImage(images.logo, PAD + 14, y + 22, 36, 36)
+         ctx.fillStyle = C.text; ctx.font = font(700, 34)
+         ctx.fillText(fit(ctx, DATA.site.name, inner - 420), PAD + 88, y + 44)
+         ctx.fillStyle = C.muted; ctx.font = font(400, 20)
+         ctx.fillText(fit(ctx, DATA.site.domain, inner - 420), PAD + 88, y + 74)
+         ctx.textAlign = "right"
+         ctx.fillStyle = C.text; ctx.font = font(600, 20)
+         ctx.fillText(DATA.range.label, W - PAD, y + 40)
+         ctx.fillStyle = C.muted; ctx.font = font(400, 18)
+         ctx.fillText(periodText(), W - PAD, y + 66)
+         ctx.fillText("Generated " + DATA.generated, W - PAD, y + 90)
+         ctx.textAlign = "left"
+         ctx.fillStyle = C.border
+         ctx.fillRect(PAD, y + 122, inner, 2)
+       }
+     })
+ 
+     opts.sections.forEach(function (id) {
+       if (id === "summary") {
+         blocks.push({
+           h: 170, keep: true, draw: function (ctx, y) {
+             var days = Math.round((Date.parse(DATA.range.to) - Date.parse(DATA.range.from)) / 864e5) + 1
+             var cards = [["Page views", DATA.summary.views], ["Unique visitors", DATA.summary.unique], ["Days in period", days]]
+             var cw = (inner - 40) / 3
+             cards.forEach(function (c, i) {
+               var x = PAD + i * (cw + 20)
+               roundRect(ctx, x, y + 10, cw, 130, 18)
+               ctx.fillStyle = C.soft; ctx.fill()
+               ctx.strokeStyle = C.border; ctx.lineWidth = 2; ctx.stroke()
+               ctx.fillStyle = C.muted; ctx.font = font(500, 19)
+               ctx.fillText(c[0], x + 26, y + 52)
+               ctx.fillStyle = i === 0 ? C.accent : C.text; ctx.font = font(700, 44)
+               ctx.fillText(nf(c[1]), x + 26, y + 112)
+             })
+           }
+         })
+       } else if (id === "timeline") {
+         blocks.push(titleBlock("Visits over time"))
+         blocks.push({
+           h: 330, keep: true, draw: function (ctx, y) {
+             var t = DATA.timeline
+             var chartH = 250, top = y + 10
+             var max = Math.max.apply(null, t.map(function (x) { return x[1] }).concat([1]))
+             ctx.strokeStyle = C.border; ctx.lineWidth = 2
+             ctx.beginPath(); ctx.moveTo(PAD, top + chartH + 0.5); ctx.lineTo(W - PAD, top + chartH + 0.5); ctx.stroke()
+             ctx.fillStyle = C.faint; ctx.font = font(400, 15)
+             ctx.fillText(nf(max), PAD, top + 14)
+             var n = t.length || 1
+             var gap = n > 60 ? 1 : 4
+             var bw = Math.max(1, (inner - gap * (n - 1)) / n)
+             t.forEach(function (p, i) {
+               var x = PAD + i * (bw + gap)
+               var h = p[2] ? 3 : (p[1] > 0 ? Math.max(4, p[1] / max * (chartH - 30)) : 3)
+               ctx.fillStyle = p[2] ? C.future : (p[1] > 0 ? C.accent : C.empty)
+               roundRect(ctx, x, top + chartH - h, bw, h, Math.min(5, bw / 2, h / 2))
+               ctx.fill()
+             })
+             ctx.fillStyle = C.muted; ctx.font = font(400, 16)
+             if (t.length) {
+               ctx.fillText(t[0][0], PAD, top + chartH + 32)
+               ctx.textAlign = "right"
+               ctx.fillText(t[t.length - 1][0], W - PAD, top + chartH + 32)
+               ctx.textAlign = "left"
+             }
+           }
+         })
+       } else if (id === "map") {
+         if (!images.map) return
+         blocks.push(titleBlock("Visitor map"))
+         var mh = inner * images.map.height / images.map.width
+         blocks.push({
+           h: mh + 30, keep: true, draw: function (ctx, y) {
+             ctx.drawImage(images.map, PAD, y + 6, inner, mh)
+           }
+         })
+       } else {
+         var s = DATA.sections.filter(function (x) { return x.id === id })[0]
+         if (!s) return
+         var rows = s.rows.slice(0, opts.rows)
+         blocks.push(titleBlock(s.title, rows.length < s.rows.length ? "Top " + rows.length + " of " + nf(s.rows.length) : nf(s.rows.length) + (s.rows.length === 1 ? " row" : " rows")))
+         if (!rows.length) {
+           blocks.push({
+             h: 56, draw: function (ctx, y) {
+               ctx.fillStyle = C.faint; ctx.font = font(400, 18)
+               ctx.fillText("No data for this period.", PAD, y + 30)
+             }
+           })
+         }
+         var maxCount = Math.max.apply(null, rows.map(function (r) { return r.count }).concat([1]))
+         rows.forEach(function (r, i) {
+           blocks.push({
+             h: 46, draw: function (ctx, y) {
+               var x = PAD
+               ctx.fillStyle = C.faint; ctx.font = font(600, 16)
+               ctx.textAlign = "right"; ctx.fillText(String(i + 1), x + 28, y + 29); ctx.textAlign = "left"
+               x += 44
+               var barW = (inner - 44) * (r.count / maxCount)
+               roundRect(ctx, x - 8, y + 5, Math.max(barW, 16), 36, 9)
+               ctx.fillStyle = i === 0 ? C.accentSoft : C.soft; ctx.fill()
+               var icon = r.icon && images.icons[r.icon]
+               if (icon) {
+                 ctx.drawImage(icon, x, y + 11, 24, 24)
+                 x += 36
+               } else if (r.code) {
+                 roundRect(ctx, x, y + 12, 36, 22, 6)
+                 ctx.fillStyle = C.border; ctx.fill()
+                 ctx.fillStyle = C.muted; ctx.font = font(700, 13)
+                 ctx.textAlign = "center"; ctx.fillText(r.code, x + 18, y + 28); ctx.textAlign = "left"
+                 x += 48
+               }
+               ctx.font = font(700, 18)
+               var countText = nf(r.count)
+               var countW = ctx.measureText(countText).width
+               var badgeW = 0
+               if (r.badge) {
+                 ctx.font = font(600, 14)
+                 badgeW = ctx.measureText(r.badge).width + 22
+               }
+               ctx.fillStyle = C.text; ctx.font = font(500, 18)
+               ctx.fillText(fit(ctx, r.name, W - PAD - x - countW - badgeW - 40), x, y + 29)
+               if (r.badge) {
+                 var bx = W - PAD - countW - 24 - badgeW
+                 roundRect(ctx, bx, y + 11, badgeW, 24, 12)
+                 ctx.fillStyle = "#ffffff"; ctx.fill()
+                 ctx.strokeStyle = C.border; ctx.lineWidth = 1.5; ctx.stroke()
+                 ctx.fillStyle = C.muted; ctx.font = font(600, 14)
+                 ctx.fillText(r.badge, bx + 11, y + 28)
+               }
+               ctx.fillStyle = C.text; ctx.font = font(700, 18)
+               ctx.textAlign = "right"; ctx.fillText(countText, W - PAD, y + 29); ctx.textAlign = "left"
+             }
+           })
+         })
+         if (s.rows.length > rows.length) {
+           blocks.push({
+             h: 40, draw: function (ctx, y) {
+               ctx.fillStyle = C.faint; ctx.font = font(400, 16)
+               ctx.fillText("… and " + nf(s.rows.length - rows.length) + " more", PAD + 44, y + 26)
+             }
+           })
+         }
+       }
+     })
+     return blocks
+   }
+ 
+   function titleBlock(title, note) {
+     return {
+       h: 78, title: true, draw: function (ctx, y) {
+         ctx.fillStyle = C.accent
+         roundRect(ctx, PAD, y + 34, 6, 26, 3); ctx.fill()
+         ctx.fillStyle = C.text; ctx.font = font(700, 24)
+         ctx.fillText(title, PAD + 18, y + 56)
+         if (note) {
+           ctx.textAlign = "right"; ctx.fillStyle = C.faint; ctx.font = font(400, 16)
+           ctx.fillText(note, W - PAD, y + 56); ctx.textAlign = "left"
+         }
+       }
+     }
+   }
+ 
+   function footer(ctx, y, pageNo, pages) {
+     ctx.fillStyle = C.border; ctx.fillRect(PAD, y, W - PAD * 2, 2)
+     ctx.fillStyle = C.faint; ctx.font = font(400, 15)
+     ctx.fillText("PriviMetrics · generated locally, no data left your server", PAD, y + 30)
+     if (pages) {
+       ctx.textAlign = "right"
+       ctx.fillText("Page " + pageNo + " of " + pages, W - PAD, y + 30)
+       ctx.textAlign = "left"
+     }
+   }
+ 
+   function newCanvas(h) {
+     var canvas = document.createElement("canvas")
+     canvas.width = W
+     canvas.height = h
+     var ctx = canvas.getContext("2d")
+     ctx.fillStyle = C.bg
+     ctx.fillRect(0, 0, W, h)
+     ctx.textBaseline = "alphabetic"
+     return { canvas: canvas, ctx: ctx }
+   }
+ 
+   function renderLong(blocks) {
+     var total = PAD + blocks.reduce(function (s, b) { return s + b.h }, 0) + 70
+     var page = newCanvas(Math.min(total, 32000))
+     var y = PAD - 20
+     blocks.forEach(function (b) { b.draw(page.ctx, y); y += b.h })
+     footer(page.ctx, y + 14, 0, 0)
+     return page.canvas
+   }
+ 
+   function paginate(blocks) {
+     var pages = []
+     var current = []
+     var used = 0
+     var avail = PAGE_H - PAD - 20 - 80
+     blocks.forEach(function (b, i) {
+       var next = blocks[i + 1]
+       var need = b.h + (b.title && next ? next.h : 0)
+       if (used + need > avail && current.length) {
+         pages.push(current)
+         current = []
+         used = 0
+       }
+       current.push(b)
+       used += b.h
+     })
+     if (current.length) pages.push(current)
+     return pages.map(function (list, idx) {
+       var page = newCanvas(PAGE_H)
+       var y = PAD - 20
+       list.forEach(function (b) { b.draw(page.ctx, y); y += b.h })
+       footer(page.ctx, PAGE_H - 70, idx + 1, pages.length)
+       return page.canvas
+     })
+   }
+ 
+   function canvasToJpeg(canvas, quality) {
+     return new Promise(function (resolve) { canvas.toBlob(resolve, "image/jpeg", quality) })
+   }
+ 
+   function buildPdf(jpegs) {
+     var enc = new TextEncoder()
+     var parts = []
+     var offsets = []
+     var length = 0
+     function push(chunk) {
+       var bytes = typeof chunk === "string" ? enc.encode(chunk) : chunk
+       parts.push(bytes)
+       length += bytes.length
+     }
+     function obj(id, body, stream) {
+       offsets[id] = length
+       push(id + " 0 obj\n" + body)
+       if (stream) {
+         push("\nstream\n")
+         push(stream)
+         push("\nendstream")
+       }
+       push("\nendobj\n")
+     }
+     var pageW = 595.28, pageH = 841.89
+     var count = jpegs.length
+     var pageIds = []
+     for (var i = 0; i < count; i++) pageIds.push(4 + i * 3)
+     push("%PDF-1.4\n%\xE2\xE3\xCF\xD3\n")
+     obj(1, "<< /Type /Catalog /Pages 2 0 R >>")
+     obj(2, "<< /Type /Pages /Kids [" + pageIds.map(function (id) { return id + " 0 R" }).join(" ") + "] /Count " + count + " >>")
+     var title = (DATA.app + " report - " + DATA.site.name).replace(/[()\\]/g, "")
+     obj(3, "<< /Title (" + title.replace(/[^\x20-\x7E]/g, "") + ") /Producer (PriviMetrics) /Creator (PriviMetrics) >>")
+     jpegs.forEach(function (img, i) {
+       var pid = pageIds[i]
+       var content = "q " + pageW + " 0 0 " + pageH + " 0 0 cm /Im0 Do Q"
+       obj(pid, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 " + pageW + " " + pageH + "] /Resources << /XObject << /Im0 " + (pid + 2) + " 0 R >> >> /Contents " + (pid + 1) + " 0 R >>")
+       obj(pid + 1, "<< /Length " + content.length + " >>", enc.encode(content))
+       obj(pid + 2, "<< /Type /XObject /Subtype /Image /Width " + img.width + " /Height " + img.height + " /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length " + img.bytes.length + " >>", img.bytes)
+     })
+     var total = 4 + count * 3
+     var xref = length
+     var x = "xref\n0 " + total + "\n0000000000 65535 f \n"
+     for (var id = 1; id < total; id++) x += String(offsets[id]).padStart(10, "0") + " 00000 n \n"
+     push(x)
+     push("trailer\n<< /Size " + total + " /Root 1 0 R /Info 3 0 R >>\nstartxref\n" + xref + "\n%%EOF")
+     return new Blob(parts, { type: "application/pdf" })
+   }
+ 
+   async function prepareImages(opts) {
+     var images = { icons: {} }
+     images.logo = await loadImage("logo.webp")
+     var srcs = {}
+     opts.sections.forEach(function (id) {
+       sectionRows(id, opts.rows).forEach(function (r) { if (r.icon) srcs[r.icon] = true })
+     })
+     await Promise.all(Object.keys(srcs).map(function (src) {
+       return loadImage(src).then(function (img) { if (img) images.icons[src] = img })
+     }))
+     if (opts.sections.indexOf("map") > -1) {
+       var mapRoot = document.querySelector("[data-world-map]")
+       var map = mapRoot && mapRoot.pmWorldMap
+       if (map) {
+         images.map = map.snapshot(W - PAD * 2, Math.round((W - PAD * 2) * 0.5), {
+           background: "#ffffff", base: "#f2f2f3", land: "#e4e4e7", muted: "#a1a1aa", ocean: "#ffffff", text: "#16171a", accent: C.accent, border: C.border
+         })
+       }
+     }
+     return images
+   }
+ 
+   async function generate() {
+     var opts = currentOptions()
+     if (!opts.sections.length) {
+       setStatus("Pick at least one section.", true)
+       return
+     }
+     var button = modal.querySelector("[data-export-go]")
+     button.disabled = true
+     setStatus("Preparing your file…")
+     try {
+       if (document.fonts && document.fonts.ready) await document.fonts.ready
+       if (opts.format === "txt") {
+         download(new Blob(["" + buildText(opts)], { type: "text/plain;charset=utf-8" }), fileBase() + ".txt")
+       } else {
+         var images = await prepareImages(opts)
+         var blocks = buildBlocks(opts, images)
+         if (opts.format === "jpg") {
+           download(await canvasToJpeg(renderLong(blocks), 0.92), fileBase() + ".jpg")
+         } else {
+           var pages = paginate(blocks)
+           var jpegs = []
+           for (var i = 0; i < pages.length; i++) {
+             var blob = await canvasToJpeg(pages[i], 0.9)
+             jpegs.push({ width: pages[i].width, height: pages[i].height, bytes: new Uint8Array(await blob.arrayBuffer()) })
+           }
+           download(buildPdf(jpegs), fileBase() + ".pdf")
+         }
+       }
+       setStatus("Downloaded.")
+       setTimeout(close, 700)
+     } catch (err) {
+       setStatus("Could not create the file: " + (err && err.message ? err.message : err), true)
+     } finally {
+       button.disabled = false
+     }
+   }
+ 
+   function setStatus(text, isError) {
+     var el = modal.querySelector("[data-export-status]")
+     el.textContent = text
+     el.classList.toggle("error", !!isError)
+   }
+ 
+   function open() {
+     setStatus("")
+     modal.classList.add("show")
+     var first = modal.querySelector('input[name="exportFormat"]:checked')
+     if (first) first.focus()
+   }
+ 
+   function close() {
+     modal.classList.remove("show")
+   }
+ 
+   modal.querySelector("[data-export-go]").addEventListener("click", generate)
+   modal.querySelectorAll("[data-export-close]").forEach(function (b) { b.addEventListener("click", close) })
+   modal.addEventListener("mousedown", function (evt) { if (evt.target === modal) close() })
+   document.addEventListener("keydown", function (evt) { if (evt.key === "Escape" && modal.classList.contains("show")) close() })
+ 
+   window.PMExport = { open: open, close: close, buildText: buildText, options: currentOptions }
+ })()
+ 
assets/fonts/Rakkas.ttf Added +0 -0

            
assets/world-map.js Modified +36 -1
⋮ 604 unchanged lines ⋮
      }).observe(document.documentElement, { attributes: true, attributeFilter: ["data-theme"] })
    }
  
+   WorldMap.prototype.snapshot = function (width, height, palette) {
+     if (!this.features) return null
+     var canvas = document.createElement("canvas")
+     var scale = 2
+     canvas.width = Math.round(width * scale)
+     canvas.height = Math.round(height * scale)
+     var saved = {
+       ctx: this.ctx, w: this.w, h: this.h, dpr: this.dpr, colors: this.colors, mode: this.mode,
+       zoom: this.zoom, panX: this.panX, panY: this.panY, hover: this.hover, paths: this.paths
+     }
+     var colors = {}
+     for (var key in palette) colors[key] = parseColor(palette[key])
+     this.ctx = canvas.getContext("2d")
+     this.w = width
+     this.h = height
+     this.dpr = scale
+     this.colors = colors
+     this.mode = "2d"
+     this.zoom = 1
+     this.panX = 0
+     this.panY = 0
+     this.hover = null
+     try {
+       this.ctx.fillStyle = palette.background || "#ffffff"
+       this.ctx.fillRect(0, 0, canvas.width, canvas.height)
+       this.ctx.setTransform(scale, 0, 0, scale, 0, 0)
+       this.paths = []
+       this.draw2d()
+     } finally {
+       for (var k in saved) this[k] = saved[k]
+       this.dirty = true
+     }
+     return canvas
+   }
+ 
    window.PMWorldMap = WorldMap
  
-   document.querySelectorAll("[data-world-map]").forEach(function (el) { new WorldMap(el) })
+   document.querySelectorAll("[data-world-map]").forEach(function (el) { el.pmWorldMap = new WorldMap(el) })
  })()
  
dashboard.php Modified

Not shown (binary file or too large to diff).

font-options.php Modified +2 -1
⋮ 7 unchanged lines ⋮
          'space-grotesk' => ['label' => 'Space Grotesk', 'family' => "'Space Grotesk'", 'file' => 'SpaceGrotesk.ttf', 'fallback' => 'sans-serif'],
          'space-grotesk-qwantium' => ['label' => 'Space Grotesk Qwantium', 'family' => "'Space Grotesk Qwantium'", 'file' => 'SpaceGroteskQu.ttf', 'fallback' => 'sans-serif'],
          'museomoderno' => ['label' => 'MuseoModerno', 'family' => "'MuseoModerno'", 'file' => 'MuseoModerno.ttf', 'fallback' => 'sans-serif'],
+         'rakkas' => ['label' => 'Rakkas', 'family' => "'Rakkas'", 'file' => 'Rakkas.ttf', 'fallback' => 'serif'],
          'kumar-one-outline' => ['label' => 'Kumar One Outline', 'family' => "'Kumar One Outline'", 'file' => 'KumarOne.ttf', 'fallback' => 'sans-serif'],
          'inter' => ['label' => 'Inter', 'family' => "'Inter'", 'file' => 'Inter.ttf', 'fallback' => 'sans-serif'],
          'ibm-plex-sans' => ['label' => 'IBM Plex Sans', 'family' => "'IBM Plex Sans'", 'file' => 'IBMPlexSans.ttf', 'fallback' => 'sans-serif'],
⋮ 11 unchanged lines ⋮
      return match ($group) {
          'body'    => 'space-grotesk-qwantium',
          'heading' => 'orbit',
-         'value'   => 'kumar-one-outline',
+         'value'   => 'space-grotesk-qwantium',
          default   => 'system',
      };
  }
⋮ 36 unchanged lines ⋮
functions.php Modified +6 -0
⋮ 522 unchanged lines ⋮
      return $global;
  }
  
+ function pmQueryString(string $key, string $default = ''): string
+ {
+     $value = $_GET[$key] ?? $default;
+     return is_string($value) ? $value : $default;
+ }
+ 
  function pmValidFeatureMode(?string $mode): string
  {
      return in_array($mode, ['inherit', 'on', 'off'], true) ? $mode : 'inherit';
⋮ 271 unchanged lines ⋮
privimetrics.php Modified +1 -1
⋮ 122 unchanged lines ⋮
      'search_query' => $searchQuery,
      'referrer' => ($collectTrafficSources && pmIsExternalReferrer($referrer, $pageUrl)) ? pmReferrerDomain($referrer) : '',
      'utm_source' => $utmSource,
-     'browser' => $collectBrowser ? pmDetectBrowser(getUserAgent(), substr(sanitize((string) ($_GET['b'] ?? '')), 0, 40)) : '',
+     'browser' => $collectBrowser ? pmDetectBrowser(getUserAgent(), substr(sanitize(pmQueryString('b')), 0, 40)) : '',
  ];
  
  $storage->saveHit($site, $hit);
⋮ 4 unchanged lines ⋮
settings.php Modified

Not shown (binary file or too large to diff).

stats.php Added +209 -0
+ <?php
+ 
+ declare(strict_types=1);
+ 
+ const PM_API_PUBLIC_FIELDS = [
+     'summary' => 'Summary (views and visitors)',
+     'timeline' => 'Visits over time',
+     'pages' => 'Most visited pages',
+     'countries' => 'Countries',
+     'referrers' => 'Websites sending visitors',
+     'devices' => 'Devices',
+     'browsers' => 'Browsers',
+     'search_engines' => 'Search engines and AI search',
+ ];
+ 
+ const PM_API_ALL_FIELDS = ['summary', 'timeline', 'pages', 'searches', 'countries', 'devices', 'browsers', 'search_engines', 'crawlers', 'referrers', 'utm_sources'];
+ 
+ const PM_API_DEFAULT_PUBLIC_FIELDS = 'summary,timeline';
+ 
+ function pmValidApiFields($fields): string
+ {
+     $list = is_array($fields) ? $fields : explode(',', (string) $fields);
+     $valid = array_values(array_intersect(array_keys(PM_API_PUBLIC_FIELDS), array_map('trim', array_map('strval', $list))));
+     return implode(',', $valid);
+ }
+ 
+ function pmGenerateApiKey(): string
+ {
+     return 'pm_' . bin2hex(random_bytes(24));
+ }
+ 
+ function deviceTypeFromUserAgent(string $userAgent): string
+ {
+     $ua = strtolower($userAgent);
+     if ($ua === '' || $ua === 'unknown') {
+         return 'Unknown';
+     }
+ 
+     if (
+         str_contains($ua, 'ipad')
+         || (str_contains($ua, 'android') && !str_contains($ua, 'mobile'))
+         || str_contains($ua, 'tablet')
+         || str_contains($ua, 'kindle')
+         || str_contains($ua, 'playbook')
+     ) {
+         return 'Tablet';
+     }
+ 
+     if (
+         str_contains($ua, 'mobi')
+         || str_contains($ua, 'iphone')
+         || str_contains($ua, 'ipod')
+         || str_contains($ua, 'android')
+         || str_contains($ua, 'blackberry')
+         || str_contains($ua, 'windows phone')
+     ) {
+         return 'Mobile';
+     }
+ 
+     return 'Desktop';
+ }
+ 
+ function pmComputeSiteStats(StorageManager $storage, array $site, string $range, string $from, string $to, array $fields, int $limit): array
+ {
+     $range = isset(PM_RANGE_OPTIONS[$range]) ? $range : '30d';
+     if ($range === 'custom' && (pmParseDay($from) === null || pmParseDay($to) === null)) {
+         $range = '30d';
+     }
+     $dateRange = getDateRange($range, $from, $to);
+     $hits = $storage->getHits($site, (int) $dateRange['start'], (int) $dateRange['end']);
+     if ($dateRange['bucket'] === 'auto') {
+         $firstTs = $hits ? min(array_map(fn($h) => (int) $h['ts'], $hits)) : time();
+         $dateRange['start'] = strtotime(date('Y-m-d', $firstTs) . ' 00:00:00');
+         $dateRange['bucket'] = pmBucketForSpan((int) $dateRange['start'], (int) $dateRange['end']);
+     }
+ 
+     $want = array_flip($fields);
+     $traffic = pmFeatureEnabledForSite($site, 'traffic_sources');
+     $countriesOn = pmFeatureEnabledForSite($site, 'visitor_countries');
+     $searchesOn = pmFeatureEnabledForSite($site, 'search_queries');
+     $devicesOn = pmFeatureGlobalEnabled('device_type');
+     $browsersOn = pmFeatureEnabledForSite($site, 'browser_detection');
+     $enginesOn = pmFeatureGlobalEnabled('search_engines') && $traffic;
+     $crawlersOn = pmFeatureGlobalEnabled('crawlers');
+ 
+     $bucketFormat = ['hour' => 'H:00', 'day' => 'Y-m-d', 'month' => 'Y-m'][$dateRange['bucket']];
+     $unique = $pages = $referrers = $utm = $searches = $devices = $browsers = $crawlers = $timeline = [];
+     $countries = [];
+     $engines = ['search' => [], 'ai' => []];
+ 
+     foreach ($hits as $hit) {
+         $unique[$hit['user_hash']] = true;
+         $bucket = date($bucketFormat, (int) $hit['ts']);
+         $timeline[$bucket] = ($timeline[$bucket] ?? 0) + 1;
+ 
+         if (isset($want['pages'])) {
+             $page = $hit['page_url'] ?: '(unknown)';
+             $pages[$page] = ($pages[$page] ?? 0) + 1;
+         }
+         if ($traffic) {
+             if (isset($want['referrers']) && !empty($hit['referrer'])) $referrers[$hit['referrer']] = ($referrers[$hit['referrer']] ?? 0) + 1;
+             if (isset($want['utm_sources']) && !empty($hit['utm_source'])) $utm[$hit['utm_source']] = ($utm[$hit['utm_source']] ?? 0) + 1;
+         }
+         if ($countriesOn && isset($want['countries'])) {
+             $code = strtoupper((string) ($hit['country_code'] ?? ''));
+             $code = preg_match('/^[A-Z]{2}$/', $code) ? $code : 'XX';
+             if (!isset($countries[$code])) $countries[$code] = ['name' => $hit['country'] ?: 'Unknown', 'views' => 0];
+             $countries[$code]['views']++;
+         }
+         if ($searchesOn && isset($want['searches']) && !empty($hit['search_query'])) {
+             $searches[$hit['search_query']] = ($searches[$hit['search_query']] ?? 0) + 1;
+         }
+         if ($devicesOn && isset($want['devices'])) {
+             $device = deviceTypeFromUserAgent($hit['user_agent'] ?? '');
+             $devices[$device] = ($devices[$device] ?? 0) + 1;
+         }
+         if ($browsersOn && isset($want['browsers'])) {
+             $ua = (string) ($hit['user_agent'] ?? '');
+             $browser = (string) ($hit['browser'] ?? '');
+             if ($browser === '' || $browser === 'unknown' || !isset(pmBrowserCatalog()[$browser]) || pmCrawlerFromUserAgent($ua) !== null) {
+                 $browser = pmBrowserFromUserAgent($ua);
+             }
+             $browsers[$browser] = ($browsers[$browser] ?? 0) + 1;
+         }
+         if ($enginesOn && isset($want['search_engines'])) {
+             $engine = pmSearchEngineFromSource((string) ($hit['referrer'] ?? ''), (string) ($hit['utm_source'] ?? ''));
+             if ($engine !== null) {
+                 $type = pmSearchEngineCatalog()[$engine][1];
+                 $engines[$type][$engine] = ($engines[$type][$engine] ?? 0) + 1;
+             }
+         }
+         if ($crawlersOn && isset($want['crawlers'])) {
+             $crawler = pmCrawlerFromUserAgent((string) ($hit['user_agent'] ?? ''));
+             if ($crawler !== null) {
+                 if (!isset($crawlers[$crawler['key']])) $crawlers[$crawler['key']] = $crawler + ['views' => 0];
+                 $crawlers[$crawler['key']]['views']++;
+             }
+         }
+     }
+ 
+     $top = function (array $counts, callable $map) use ($limit): array {
+         arsort($counts);
+         $out = [];
+         foreach (array_slice($counts, 0, $limit, true) as $key => $count) {
+             $out[] = $map((string) $key, (int) $count);
+         }
+         return $out;
+     };
+ 
+     $result = [
+         'site' => ['name' => html_entity_decode((string) $site['name'], ENT_QUOTES, 'UTF-8'), 'domain' => $site['domain']],
+         'range' => [
+             'key' => $range,
+             'from' => date('Y-m-d', (int) $dateRange['start']),
+             'to' => date('Y-m-d', (int) min($dateRange['end'], time())),
+             'bucket' => $dateRange['bucket'],
+         ],
+     ];
+ 
+     if (isset($want['summary'])) {
+         $result['summary'] = ['views' => count($hits), 'unique_visitors' => count($unique)];
+     }
+     if (isset($want['timeline'])) {
+         $result['timeline'] = [];
+         foreach (pmTimelineSlots($dateRange['bucket'], (int) $dateRange['start'], (int) $dateRange['end']) as $key => $isFuture) {
+             if ($isFuture) continue;
+             $result['timeline'][] = ['period' => (string) $key, 'views' => $timeline[$key] ?? 0];
+         }
+     }
+     if (isset($want['pages'])) {
+         $result['pages'] = $top($pages, fn($k, $c) => ['url' => $k, 'views' => $c]);
+     }
+     if (isset($want['searches']) && $searchesOn) {
+         $result['searches'] = $top($searches, fn($k, $c) => ['query' => $k, 'views' => $c]);
+     }
+     if (isset($want['countries']) && $countriesOn) {
+         uasort($countries, fn($a, $b) => $b['views'] <=> $a['views']);
+         $result['countries'] = [];
+         foreach (array_slice($countries, 0, $limit, true) as $code => $c) {
+             $result['countries'][] = ['code' => (string) $code, 'name' => $c['name'], 'views' => $c['views']];
+         }
+     }
+     if (isset($want['devices']) && $devicesOn) {
+         $result['devices'] = $top($devices, fn($k, $c) => ['device' => $k, 'views' => $c]);
+     }
+     if (isset($want['browsers']) && $browsersOn) {
+         $result['browsers'] = $top($browsers, fn($k, $c) => ['id' => $k, 'name' => pmBrowserName($k), 'views' => $c]);
+     }
+     if (isset($want['search_engines']) && $enginesOn) {
+         $catalog = pmSearchEngineCatalog();
+         $engineMap = fn($k, $c) => ['id' => $k, 'name' => $catalog[$k][0] ?? $k, 'views' => $c];
+         $result['search_engines'] = $top($engines['search'], $engineMap);
+         $result['ai_search'] = $top($engines['ai'], $engineMap);
+     }
+     if (isset($want['crawlers']) && $crawlersOn) {
+         uasort($crawlers, fn($a, $b) => $b['views'] <=> $a['views']);
+         $labels = pmCrawlerTypeLabels();
+         $result['crawlers'] = array_map(fn($c) => ['id' => $c['key'], 'name' => $c['name'], 'type' => $labels[$c['type']] ?? 'Bot', 'views' => $c['views']], array_values(array_slice($crawlers, 0, $limit)));
+     }
+     if (isset($want['referrers']) && $traffic) {
+         $result['referrers'] = $top($referrers, fn($k, $c) => ['domain' => $k, 'views' => $c]);
+     }
+     if (isset($want['utm_sources']) && $traffic) {
+         $result['utm_sources'] = $top($utm, fn($k, $c) => ['source' => $k, 'views' => $c]);
+     }
+ 
+     return $result;
+ }
+ 
storage.php Modified +27 -3
⋮ 69 unchanged lines ⋮
                  visitor_countries_mode ENUM('inherit','on','off') NOT NULL DEFAULT 'inherit',
                  search_queries_mode ENUM('inherit','on','off') NOT NULL DEFAULT 'inherit',
                  browser_detection_mode ENUM('inherit','on','off') NOT NULL DEFAULT 'inherit',
+                 api_public TINYINT(1) NOT NULL DEFAULT 0,
+                 api_public_fields VARCHAR(255) NOT NULL DEFAULT 'summary,timeline',
+                 api_key VARCHAR(64) NOT NULL DEFAULT '',
+                 api_key_enabled TINYINT(1) NOT NULL DEFAULT 0,
                  active TINYINT(1) NOT NULL DEFAULT 1,
                  created_at INT NOT NULL,
                  INDEX idx_tracking_code (tracking_code)
⋮ 6 unchanged lines ⋮
                  'visitor_countries_mode' => "ALTER TABLE pm_sites ADD COLUMN visitor_countries_mode ENUM('inherit','on','off') NOT NULL DEFAULT 'inherit'",
                  'search_queries_mode'    => "ALTER TABLE pm_sites ADD COLUMN search_queries_mode ENUM('inherit','on','off') NOT NULL DEFAULT 'inherit'",
                  'browser_detection_mode' => "ALTER TABLE pm_sites ADD COLUMN browser_detection_mode ENUM('inherit','on','off') NOT NULL DEFAULT 'inherit'",
+                 'api_public'             => "ALTER TABLE pm_sites ADD COLUMN api_public TINYINT(1) NOT NULL DEFAULT 0",
+                 'api_public_fields'      => "ALTER TABLE pm_sites ADD COLUMN api_public_fields VARCHAR(255) NOT NULL DEFAULT 'summary,timeline'",
+                 'api_key'                => "ALTER TABLE pm_sites ADD COLUMN api_key VARCHAR(64) NOT NULL DEFAULT ''",
+                 'api_key_enabled'        => "ALTER TABLE pm_sites ADD COLUMN api_key_enabled TINYINT(1) NOT NULL DEFAULT 0",
              ] as $column => $alterSql
          ) {
              try {
⋮ 156 unchanged lines ⋮
              'visitor_countries_mode' => pmValidFeatureMode($visitorCountriesMode),
              'search_queries_mode' => pmValidFeatureMode($searchQueriesMode),
              'browser_detection_mode' => pmValidFeatureMode($browserDetectionMode),
+             'api_public' => 0,
+             'api_public_fields' => 'summary,timeline',
+             'api_key' => 'pm_' . bin2hex(random_bytes(24)),
+             'api_key_enabled' => 0,
              'active' => 1,
              'created_at' => time(),
          ];
  
          if ($this->sitesBackend() === 'mysql') {
              $stmt = $this->pdo->prepare("
-                 INSERT INTO pm_sites (id, name, domain, tracking_code, storage, restriction_mode, traffic_sources_mode, visitor_countries_mode, search_queries_mode, browser_detection_mode, active, created_at)
-                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+                 INSERT INTO pm_sites (id, name, domain, tracking_code, storage, restriction_mode, traffic_sources_mode, visitor_countries_mode, search_queries_mode, browser_detection_mode, api_public, api_public_fields, api_key, api_key_enabled, active, created_at)
+                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
              ");
              $stmt->execute([
                  $site['id'],
⋮ 6 unchanged lines ⋮
                  $site['visitor_countries_mode'],
                  $site['search_queries_mode'],
                  $site['browser_detection_mode'],
+                 $site['api_public'],
+                 $site['api_public_fields'],
+                 $site['api_key'],
+                 $site['api_key_enabled'],
                  $site['active'],
                  $site['created_at'],
              ]);
⋮ 9 unchanged lines ⋮
      public function updateSite(string $id, array $fields): bool
      {
          if ($this->sitesBackend() === 'mysql') {
-             $allowed = ['name', 'domain', 'storage', 'restriction_mode', 'active', 'traffic_sources_mode', 'visitor_countries_mode', 'search_queries_mode', 'browser_detection_mode'];
+             $allowed = ['name', 'domain', 'storage', 'restriction_mode', 'active', 'traffic_sources_mode', 'visitor_countries_mode', 'search_queries_mode', 'browser_detection_mode', 'api_public', 'api_public_fields', 'api_key', 'api_key_enabled'];
              $sets = [];
              $params = [];
              foreach ($fields as $k => $v) {
⋮ 76 unchanged lines ⋮
                  'visitor_countries_mode' => pmValidFeatureMode((string) ($s->visitor_countries_mode ?? '') ?: 'inherit'),
                  'search_queries_mode' => pmValidFeatureMode((string) ($s->search_queries_mode ?? '') ?: 'inherit'),
                  'browser_detection_mode' => pmValidFeatureMode((string) ($s->browser_detection_mode ?? '') ?: 'inherit'),
+                 'api_public' => (string) ($s->api_public ?? '') === '1' ? 1 : 0,
+                 'api_public_fields' => isset($s->api_public_fields) ? (string) $s->api_public_fields : 'summary,timeline',
+                 'api_key' => (string) ($s->api_key ?? ''),
+                 'api_key_enabled' => (string) ($s->api_key_enabled ?? '') === '1' ? 1 : 0,
                  'active' => (string) $s->active === '1' || (string) $s->active === 'true',
                  'created_at' => (int) $s->created_at,
              ];
⋮ 18 unchanged lines ⋮
              $node->addChild('visitor_countries_mode', htmlspecialchars(pmValidFeatureMode($s['visitor_countries_mode'] ?? 'inherit')));
              $node->addChild('search_queries_mode', htmlspecialchars(pmValidFeatureMode($s['search_queries_mode'] ?? 'inherit')));
              $node->addChild('browser_detection_mode', htmlspecialchars(pmValidFeatureMode($s['browser_detection_mode'] ?? 'inherit')));
+             $node->addChild('api_public', !empty($s['api_public']) ? '1' : '0');
+             $node->addChild('api_public_fields', htmlspecialchars((string) ($s['api_public_fields'] ?? 'summary,timeline')));
+             $node->addChild('api_key', htmlspecialchars((string) ($s['api_key'] ?? '')));
+             $node->addChild('api_key_enabled', !empty($s['api_key_enabled']) ? '1' : '0');
              $node->addChild('active', $s['active'] ? '1' : '0');
              $node->addChild('created_at', (string) $s['created_at']);
          }
⋮ 222 unchanged lines ⋮
updater.php Modified +38 -0
⋮ 764 unchanged lines ⋮
              }
          }
  
+         @media (prefers-reduced-motion: no-preference) {
+             @view-transition {
+                 navigation: auto;
+             }
+ 
+             .sidebar {
+                 view-transition-name: pm-sidebar;
+             }
+ 
+             ::view-transition-old(root),
+             ::view-transition-new(root) {
+                 animation-duration: 0.18s;
+             }
+ 
+             ::view-transition-group(pm-sidebar) {
+                 animation-duration: 0s;
+             }
+         }
+ 
      </style>
  </head>
  
⋮ 181 unchanged lines ⋮
              document.getElementById('sidebar').classList.remove('open');
              document.getElementById('backdrop').classList.remove('show');
          }
+     </script>
+     <script>
+         (function() {
+             var view = new URLSearchParams(location.search).get('view') || 'overview';
+             var key = 'pm_scroll:' + location.pathname + ':' + view;
+             try {
+                 if ('scrollRestoration' in history) history.scrollRestoration = 'manual';
+                 var saved = sessionStorage.getItem(key);
+                 if (saved !== null) {
+                     var y = parseInt(saved, 10) || 0;
+                     window.scrollTo(0, y);
+                     requestAnimationFrame(function() { window.scrollTo(0, y); });
+                     window.addEventListener('load', function() { window.scrollTo(0, y); }, { once: true });
+                 }
+             } catch (e) {}
+             window.addEventListener('pagehide', function() {
+                 try { sessionStorage.setItem(key, String(Math.round(window.scrollY))); } catch (e) {}
+             });
+         })();
      </script>
  </body>
  
⋮ 2 unchanged lines ⋮
version.txt Modified +1 -1
- 1.1.3
+ 1.1.4