Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f4d6b06203 | ||
|
|
1f09671fee | ||
|
|
6ae3ab55a9 | ||
|
|
0c913110cc | ||
|
|
3239b511bd | ||
|
|
c1c579dd14 | ||
|
|
7e7f3c1c14 | ||
|
|
daaddc7c24 | ||
|
|
65f3f36569 |
163
.github/workflows/publish-release.yml
vendored
163
.github/workflows/publish-release.yml
vendored
@@ -1,43 +1,168 @@
|
||||
name: Publish Release
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Release-notes strategy (in order of preference):
|
||||
#
|
||||
# 1. If CHANGELOG.md has a "## [X.Y.Z] - YYYY-MM-DD" section matching the
|
||||
# tag version, use that section verbatim. This is the normal path —
|
||||
# maintainers write release notes once in CHANGELOG and they flow to
|
||||
# GitHub automatically with no re-typing.
|
||||
#
|
||||
# 2. Otherwise, fall back to grouping the commits in the tag range by
|
||||
# conventional-commit prefix (feat / fix / refactor / docs / other).
|
||||
# Keeps releases useful even if the maintainer forgot the CHANGELOG.
|
||||
#
|
||||
# 3. Append a compare link (PREV_TAG...TAG) at the bottom so readers can
|
||||
# dive into the full diff in one click.
|
||||
#
|
||||
# Retag safety:
|
||||
# When a tag is force-pushed (e.g. to fix a last-minute doc error), the
|
||||
# workflow normally would overwrite any hand-edited release body. We guard
|
||||
# against that by checking the current release body BEFORE running the
|
||||
# generator — if a body is already present, we leave it alone. To
|
||||
# intentionally regenerate, clear the body first via:
|
||||
# gh release edit vX.Y.Z --notes ""
|
||||
#
|
||||
# Security note:
|
||||
# All ${{ ... }} interpolation in this file flows through `env:` blocks
|
||||
# rather than inline in `run:` commands. Shell scripts reference those
|
||||
# env vars with $VAR, which is immune to the command-injection pattern
|
||||
# that hits workflows interpolating untrusted event data directly.
|
||||
# -----------------------------------------------------------------------------
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
# Need full history for `git describe` to find the previous tag and
|
||||
# for `git log PREV..HEAD` to enumerate commits in the release range.
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Extract tag name
|
||||
id: tag
|
||||
run: echo "version=${GITHUB_REF#refs/tags/}" >> "$GITHUB_OUTPUT"
|
||||
- name: Derive versions
|
||||
id: version
|
||||
env:
|
||||
REF: ${{ github.ref }}
|
||||
run: |
|
||||
TAG="${REF#refs/tags/}"
|
||||
VERSION="${TAG#v}"
|
||||
# Previous tag for compare link + commit range. Empty on first release.
|
||||
PREV_TAG=$(git describe --tags --abbrev=0 "$TAG^" 2>/dev/null || echo "")
|
||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "prev_tag=$PREV_TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "Tag: $TAG Version: $VERSION Previous: ${PREV_TAG:-<none>}"
|
||||
|
||||
- name: Check for existing release body
|
||||
id: existing
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ steps.version.outputs.tag }}
|
||||
REPO: ${{ github.repository }}
|
||||
run: |
|
||||
# If the release already has a non-empty body, skip generation so
|
||||
# hand-edits survive tag re-pushes. Fresh releases (no body) proceed.
|
||||
BODY=$(gh release view "$TAG" --repo "$REPO" --json body -q .body 2>/dev/null || echo "")
|
||||
if [ -n "$(printf '%s' "$BODY" | tr -d '[:space:]')" ]; then
|
||||
echo "Existing release body detected — preserving manual edits."
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "No existing body (or empty) — will generate."
|
||||
echo "skip=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Generate release notes
|
||||
id: notes
|
||||
if: steps.existing.outputs.skip != 'true'
|
||||
env:
|
||||
VERSION: ${{ steps.version.outputs.version }}
|
||||
TAG: ${{ steps.version.outputs.tag }}
|
||||
PREV_TAG: ${{ steps.version.outputs.prev_tag }}
|
||||
REPO: ${{ github.repository }}
|
||||
run: |
|
||||
# Get previous tag
|
||||
PREV_TAG=$(git describe --tags --abbrev=0 HEAD^ 2>/dev/null || echo "")
|
||||
if [ -n "$PREV_TAG" ]; then
|
||||
NOTES=$(git log --pretty=format:"- %s" "$PREV_TAG"..HEAD)
|
||||
else
|
||||
NOTES=$(git log --pretty=format:"- %s")
|
||||
set -eo pipefail
|
||||
|
||||
# --- 1. Try extracting the section from CHANGELOG.md --------------
|
||||
# Matches "## [1.2.0] ..." exactly and prints every line up to the
|
||||
# next "## [" heading or EOF.
|
||||
CHANGELOG_SECTION=""
|
||||
if [ -f CHANGELOG.md ]; then
|
||||
CHANGELOG_SECTION=$(awk -v ver="$VERSION" '
|
||||
$0 ~ "^## \\[" ver "\\]" { found=1; next }
|
||||
found && /^## \[/ { exit }
|
||||
found { print }
|
||||
' CHANGELOG.md)
|
||||
fi
|
||||
# Write to file for the release body
|
||||
echo "$NOTES" > /tmp/release-notes.txt
|
||||
|
||||
# --- 2. Commit-based fallback ------------------------------------
|
||||
# Used only when CHANGELOG has no section for this version. Groups
|
||||
# conventional-commit prefixes into readable categories; skips
|
||||
# automated "chore(release): …" bump commits from display since
|
||||
# they're noise in a release the reader is already looking at.
|
||||
if [ -z "$(printf '%s' "$CHANGELOG_SECTION" | tr -d '[:space:]')" ]; then
|
||||
echo "::warning::CHANGELOG.md has no section for [$VERSION]; falling back to commit-log grouping."
|
||||
|
||||
if [ -n "$PREV_TAG" ]; then RANGE="$PREV_TAG..HEAD"; else RANGE=""; fi
|
||||
LOG=$(git log $RANGE --no-merges --pretty=format:'%s' \
|
||||
| grep -vE '^chore\(release\)' || true)
|
||||
|
||||
# extract <regex> — prints matching commits as "- <rest>" with the
|
||||
# conventional-commit "type(scope)?:" prefix stripped for readability.
|
||||
extract() {
|
||||
printf '%s\n' "$LOG" \
|
||||
| grep -E "^($1)(\([^)]+\))?:" \
|
||||
| sed -E "s/^($1)(\([^)]+\))?:[[:space:]]*/- /" \
|
||||
|| true
|
||||
}
|
||||
|
||||
FEATURES=$(extract 'feat')
|
||||
FIXES=$(extract 'fix')
|
||||
REFACTORS=$(extract 'refactor')
|
||||
DOCS=$(extract 'docs')
|
||||
OTHER=$(printf '%s\n' "$LOG" \
|
||||
| grep -vE '^(feat|fix|refactor|docs|chore)(\([^)]+\))?:' \
|
||||
| sed -E 's/^/- /' \
|
||||
|| true)
|
||||
|
||||
{
|
||||
[ -n "$FEATURES" ] && printf '### Features\n\n%s\n\n' "$FEATURES"
|
||||
[ -n "$FIXES" ] && printf '### Bug Fixes\n\n%s\n\n' "$FIXES"
|
||||
[ -n "$REFACTORS" ] && printf '### Changes\n\n%s\n\n' "$REFACTORS"
|
||||
[ -n "$DOCS" ] && printf '### Documentation\n\n%s\n\n' "$DOCS"
|
||||
[ -n "$OTHER" ] && printf '### Other\n\n%s\n\n' "$OTHER"
|
||||
} > /tmp/generated.md
|
||||
|
||||
CHANGELOG_SECTION=$(cat /tmp/generated.md)
|
||||
fi
|
||||
|
||||
# --- 3. Compose final body (content + compare footer) ------------
|
||||
{
|
||||
printf '%s\n' "$CHANGELOG_SECTION"
|
||||
if [ -n "$PREV_TAG" ]; then
|
||||
printf '\n---\n\n**Full Changelog:** [%s...%s](https://github.com/%s/compare/%s...%s)\n' \
|
||||
"$PREV_TAG" "$TAG" "$REPO" "$PREV_TAG" "$TAG"
|
||||
fi
|
||||
} > /tmp/release-notes.md
|
||||
|
||||
echo "--- release notes ($(wc -c < /tmp/release-notes.md) bytes) ---"
|
||||
head -20 /tmp/release-notes.md
|
||||
echo "---"
|
||||
|
||||
- name: Create release
|
||||
if: steps.existing.outputs.skip != 'true'
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.tag.outputs.version }}
|
||||
name: ${{ steps.tag.outputs.version }}
|
||||
body_path: /tmp/release-notes.txt
|
||||
tag_name: ${{ steps.version.outputs.tag }}
|
||||
name: ${{ steps.version.outputs.tag }}
|
||||
body_path: /tmp/release-notes.md
|
||||
draft: false
|
||||
prerelease: false
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
41
CHANGELOG.md
41
CHANGELOG.md
@@ -2,6 +2,47 @@
|
||||
|
||||
All notable changes to the VirtFusion Direct Provisioning Module for WHMCS.
|
||||
|
||||
## [1.4.0] - 2026-04-24
|
||||
|
||||
### Features
|
||||
- **Dynamic VPS stock control driven by live hypervisor capacity.** Opt-in per product via WHMCS's native `tblproducts.stockcontrol` toggle; when enabled, the module overwrites `tblproducts.qty` with the real number of VPSes the panel can still provision and WHMCS handles the "Out of Stock" badge, Add-to-Cart gating, and checkout refusal natively — no template work required. qty is derived by combining two authoritative sources:
|
||||
- `GET /packages/{packageId}` for the per-VPS resource footprint (`memory`, `cpuCores`, `primaryStorage`, `primaryStorageProfile`, `enabled`)
|
||||
- `GET /compute/hypervisors/groups/{id}/resources` for live per-hypervisor free/allocated data
|
||||
|
||||
Algorithm sums `min(memory, cpu, storage)` across eligible hypervisors (enabled AND commissioned AND !prohibit) for every group the product can be placed in (default `configoption1` plus every numeric value of a `Location` configurable option), capped by the group-level IPv4 pool taken as `max()` within a group to avoid double-counting. Storage matching is strict against `package.primaryStorageProfile`; hypervisors without the named pool contribute 0. Confirmed-missing conditions (HTTP 404 on `/packages/{id}`, `package.enabled=false`) force qty=0; transient failures leave `qty` UNTOUCHED to avoid false out-of-stock during API blips.
|
||||
|
||||
- **Event-driven stock recalculation hooks:**
|
||||
- `AfterModuleCreate` — refreshes qty after every VirtFusion provision (capacity just decreased). Bursts of parallel provisions coalesce via a 30 s shared rate-limit.
|
||||
- `AfterModuleTerminate` — refreshes qty after every VirtFusion termination (capacity just increased). Shares the 30 s rate-limit with create.
|
||||
- `AfterCronJob` — every-2-hour safety net that catches capacity changes made directly in the VirtFusion panel without going through WHMCS. Interval tunable via `STOCK_CRON_INTERVAL_SECONDS` in `hooks.php`.
|
||||
- `ClientAreaPageCart` — opportunistic per-product refresh during the order flow, rate-limited to once per product per 60 s.
|
||||
|
||||
- **Order auto-accept after successful provision.** `AfterModuleCreate` calls WHMCS `AcceptOrder` (with `autosetup=false` so there's no double-provision) when the parent order is still in Pending status. Closes the gap for installs that rely on pending-order workflows for non-VF products but want VirtFusion provisions to auto-advance. Idempotent — already-accepted orders are skipped.
|
||||
|
||||
- **Admin-triggered full recalculation.** New `admin.php?action=stockRecalculate` action (POST + same-origin required) runs `StockControl::recalculateAll()` on demand and returns a JSON `{productId: qty}` map; the module log gets a compact summary (`{total, updated, zeroed, skipped}`) so it stays readable on stores with hundreds of products.
|
||||
|
||||
- **Per-product safety buffer.** New `stockSafetyBufferPct` config option (configoption7, default 10) reserves X% of each resource's `max` during stock calculation. Applied only to capped resources (unlimited resources with `max=0` skip the buffer). Admins can override per product in the module settings; blank falls back to 10% so existing products get sensible headroom without any config change.
|
||||
|
||||
- **Test Connection now probes `/compute/hypervisors/groups`.** A VirtFusion API token scoped only to `/servers` would pass the existing `/connect` check but silently break nightly stock updates. The admin's Test Connection button now surfaces missing `/compute` read scope at config time with a specific error rather than as unexplained nightly silence.
|
||||
|
||||
### Caching
|
||||
- New cache keys: `pkg:{packageId}` (10 min TTL, package definitions rarely change) and `grpres:{groupId}` (120 s TTL, resources change minute-to-minute under load). Confirmed 404 responses are cached for 60 s so an admin re-creating a deleted package/group takes effect quickly.
|
||||
|
||||
### Safety Properties
|
||||
- `Module::fetchPackage()` and `Module::fetchGroupResources()` return a tri-state `array | false | null`: `false` means "VirtFusion confirmed this doesn't exist → OOS is correct", `null` means "we can't tell right now → don't touch existing qty". Without this distinction the module would either zero out inventory during transient API blips, or show inventory for deleted packages.
|
||||
- `\Throwable` catches on every stock-path entry point (not just `\Exception`) so a `TypeError` from a malformed API response can't escape the tri-state contract.
|
||||
- Stock-control is gated by `tblproducts.stockcontrol=1` — products that opt out are never touched, even by the safety-net cron.
|
||||
|
||||
## [1.3.0] - 2026-04-17
|
||||
|
||||
### Bug Fixes
|
||||
- **Critical: decrypt() corruption of plaintext addon API keys.** `Config::get()` was calling WHMCS's `decrypt()` on the raw `tbladdonmodules.value` for the PowerDNS API key and accepting whatever non-empty result came back. WHMCS addon password-type fields are actually stored **plaintext** (unlike `tblservers.password` which is encrypted), and `decrypt()` on plaintext input returns ~4 bytes of binary garbage instead of empty. That garbage was ending up in the `X-API-Key:` header, producing a baffling 401 from PowerDNS and an empty zone list — which then surfaced as **"no zone"** for every IP in the client-area rDNS panel. Fix: only use `decrypt()`'s output when it's printable ASCII; fall back to raw otherwise. Also `trim()` the chosen value so a stray paste-newline can't corrupt the header.
|
||||
|
||||
### Features
|
||||
- **IPv6 subnet visibility + custom-host PTR flow.** VirtFusion allocates v6 as whole subnets (e.g. a /64 routed to the VPS) rather than discrete host addresses. The module previously filtered these silently; now subnets appear as first-class rows in the client rDNS panel with a collapsible "Add host PTR" form. Ownership verification uses **subnet containment** (`IpUtil::ipv6InSubnet()` via `inet_pton` + bit masking) so any address inside one of the VPS's allocated subnets is writeable, while addresses outside them are rejected. FCrDNS / rate-limit / CSRF guards all still apply.
|
||||
- **Diagnose-an-IP tool** on the VirtFusion DNS addon admin page. Takes an IP input and runs the full PtrManager pipeline inline: config snapshot, fresh zone list (cache-bypassed), computed PTR name, matched zone, current PTR content. Every common failure mode (wrong key, wrong serverId, forgotten zone, mis-aligned RFC 2317 label, stale cache) produces a distinctive shape in that output, turning "support ticket" into "screenshot the diagnosis".
|
||||
- **Actionable auth-error messages.** `Client::ping()` now returns structured guidance on 401/403 (check API key, `api-allow-from`, whitespace) and 404 (check `serverId`, it should be the literal `localhost`), replacing the previous "authentication failed (check API key)" / "unexpected HTTP 404" which gave no clue which of several causes was actually biting.
|
||||
|
||||
## [1.2.0] - 2026-04-17
|
||||
|
||||
### Features
|
||||
|
||||
34
CLAUDE.md
34
CLAUDE.md
@@ -69,6 +69,7 @@ The `publish-release.yml` workflow creates a GitHub/Gitea release with auto-gene
|
||||
| `PowerDns\IpUtil` | Pure helpers: `ptrNameForIp` (v4/v6 nibble reversal), `expandIpv6`, `extractIps` (all interfaces), `findZoneAndPtrName` (standard + RFC 2317 classless), `parseClasslessZone`. |
|
||||
| `PowerDns\Resolver` | Forward-DNS verification via `dns_get_record()` with up-to-5-hop CNAME following. Cached per (hostname, ip) pair. |
|
||||
| `PowerDns\PtrManager` | Orchestrator: `syncServer`, `deleteForServer`, `listPtrs`, `setPtr`, `reconcile`, `reconcileAll`. Per-request zone cache. 10s per-IP write rate limit. Enforces FCrDNS before writes. |
|
||||
| `StockControl` | Orchestrator for dynamic inventory. `recalculateForProduct()` and `recalculateAll()` compute per-product qty from live `/packages/{id}` + `/compute/hypervisors/groups/{id}/resources` data and write to `tblproducts.qty`. Fail-safe: null return = qty untouched. |
|
||||
|
||||
### Class Hierarchy
|
||||
|
||||
@@ -134,6 +135,38 @@ Opt-in integration via the companion `VirtFusionDns` addon module. Loose-coupled
|
||||
|
||||
Custom option names can be mapped in `config/ConfigOptionMapping.php` (copy from `-example.php`). Default mapping keys: `packageId`, `hypervisorId`, `ipv4`, `storage`, `memory`, `traffic`, `cpuCores`, `networkSpeedInbound`, `networkSpeedOutbound`, `networkProfile`, `storageProfile`.
|
||||
|
||||
### Inventory / Stock Control
|
||||
|
||||
Opt-in per product via WHMCS's native stock-control toggle (`tblproducts.stockcontrol=1`). When enabled, the module overwrites `tblproducts.qty` with the real number of VPSes that can still be provisioned — WHMCS then handles the "Out of Stock" badge, Add-to-Cart gating, and checkout refusal natively. No templates or JS required.
|
||||
|
||||
**Data sources (authoritative):**
|
||||
- `GET /packages/{id}` — per-VPS resource footprint (`memory`, `cpuCores`, `primaryStorage`, `primaryStorageProfile`, `enabled`)
|
||||
- `GET /compute/hypervisors/groups/{id}/resources` — live free/allocated per hypervisor with per-metric quotas, storage pools (matched by package.primaryStorageProfile), and a group-level IPv4 pool
|
||||
|
||||
**Algorithm:** for every group the product can be placed in (default `configoption1` plus every numeric value of the `Location` configurable option), sum `min(memory, cpu, storage)` across eligible hypervisors (enabled AND commissioned AND !prohibit) and cap by the group-level IPv4 pool (`max` across hypervisors, not summed — IPv4 is a single group-wide pool). Sum across groups → qty.
|
||||
|
||||
**Triggers:**
|
||||
- `AfterModuleCreate` — post-provision refresh; bursts rate-limited to one recalc per 30 s via `stockrefresh:event` cache key.
|
||||
- `AfterModuleTerminate` — post-termination refresh; shares the same 30 s rate-limit key.
|
||||
- `AfterCronJob` — every-2-hour safety net (captures out-of-band VirtFusion panel changes). Tunable via `STOCK_CRON_INTERVAL_SECONDS` constant in `hooks.php`.
|
||||
- `ClientAreaPageCart` — opportunistic per-product refresh on cart/order pages with a 60 s rate-limit key (`stockrefresh:{pid}`). The `grpres:{id}` cache (120 s TTL) naturally coalesces bursts.
|
||||
- `admin.php?action=stockRecalculate` — admin-triggered full recalc (POST + same-origin required); returns JSON `{productId: qty}` map.
|
||||
|
||||
**Order auto-accept:** `AfterModuleCreate` additionally calls WHMCS `AcceptOrder` with `autosetup=false` when the service's parent order is still Pending. Closes the loop for installs that rely on pending-order workflows for non-VF products but want VF provisions to auto-advance.
|
||||
|
||||
**Caching:** `pkg:{id}` 600 s (package definitions rarely change), `grpres:{id}` 120 s (resources change under load). Confirmed 404s cached 60 s so re-creating a deleted package/group takes effect quickly.
|
||||
|
||||
**Safety properties:**
|
||||
- Transient API failures (null from `fetchPackage` / `fetchGroupResources`) leave `qty` UNTOUCHED — never silently takes the catalogue offline.
|
||||
- Confirmed-missing conditions (HTTP 404 on package, `package.enabled=false`) return qty=0 — the product genuinely cannot be provisioned.
|
||||
- IPv4 cap is max-within-group (not summed across hypervisors) to avoid double-counting the shared pool.
|
||||
- Storage match is strict: the package's `primaryStorageProfile` must exist and be enabled on the target hypervisor, otherwise that hypervisor contributes 0. Falls back to `localStorage` only when the package has no profile set.
|
||||
- Stock control is gated by `tblproducts.stockcontrol=1` per product — the module never touches qty on products that opt out.
|
||||
|
||||
**Per-product setting:** `stockSafetyBufferPct` (configoption7, default 10). Reserves X% of each resource's `max` before computing fits; ignored for unlimited resources (`max=0`) and for IPv4 (no per-hypervisor `max` in the response). Admins can override per product in the module settings; blank falls back to 10%.
|
||||
|
||||
**API scope required:** the VirtFusion API token must have read access to both `/packages` and `/compute/hypervisors/groups`. The Test Connection button probes the compute endpoint and shows a clear error if scope is missing.
|
||||
|
||||
## Security Patterns
|
||||
|
||||
- All PHP files start with `if (!defined("WHMCS")) die()` to prevent direct access (except entry points using `init.php`)
|
||||
@@ -173,6 +206,7 @@ Custom option names can be mapped in `config/ConfigOptionMapping.php` (copy from
|
||||
| configoption4 | Self-Service Mode | 0=Disabled, 1=Hourly, 2=Resource Packs, 3=Both | 0 |
|
||||
| configoption5 | Auto Top-Off Threshold | Credit balance below which auto top-off triggers | 0 |
|
||||
| configoption6 | Auto Top-Off Amount | Credit amount to add on auto top-off | 100 |
|
||||
| configoption7 | Stock Safety Buffer (%) | Headroom reserved per resource during stock calculation (0-100). Only effective with WHMCS stock control enabled. Blank falls back to the default. | 10 |
|
||||
|
||||
## WHMCS Compatibility
|
||||
|
||||
|
||||
128
CODE_OF_CONDUCT.md
Normal file
128
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,128 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
* Demonstrating empathy and kindness toward other people
|
||||
* Being respectful of differing opinions, viewpoints, and experiences
|
||||
* Giving and gracefully accepting constructive feedback
|
||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
* Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
* The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
support@ezscale.cloud.
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.0, available at
|
||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||
enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at
|
||||
https://www.contributor-covenant.org/translations.
|
||||
@@ -41,6 +41,13 @@ function virtfusiondns_load_server_libs(): bool
|
||||
}
|
||||
require_once $base . $f;
|
||||
}
|
||||
// PtrManager + IpUtil are only needed for the diagnostic tool below; load them
|
||||
// if present but don't require them for the basic status page to work.
|
||||
foreach (['PowerDns/Resolver.php', 'PowerDns/PtrManager.php'] as $optional) {
|
||||
if (is_file($base . $optional)) {
|
||||
require_once $base . $optional;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -230,5 +237,131 @@ function VirtFusionDns_output($vars)
|
||||
echo '<li><code>api-allow-from</code> must include the WHMCS host\'s IP.</li>';
|
||||
echo '</ul>';
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Diagnostic: "What does the module see for IP X?"
|
||||
//
|
||||
// Runs the full pipeline an admin would otherwise have to trace through
|
||||
// multiple log lines to reproduce:
|
||||
// 1. Current config (what values is Config::get() actually returning?)
|
||||
// 2. Zone list (what does Client::listZones() return right now, post-cache?)
|
||||
// 3. Zone match for an input IP (is findZoneAndPtrName selecting the right zone?)
|
||||
// 4. Current PTR content at the located (zone, ptrName) pair
|
||||
//
|
||||
// Catches every common failure mode: wrong API key (empty zones, auth error),
|
||||
// wrong server ID (404), forgotten zone (no match), stale cache (mismatched
|
||||
// zones), and typos in the RFC 2317 zone name (parseClasslessZone rejection).
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
echo '<h3 style="margin-top:24px">Diagnose an IP</h3>';
|
||||
echo '<p>Runs the exact same pipeline the client-area rDNS panel uses. Useful when a specific IP shows "no zone" in the UI and you need to see <em>why</em>.</p>';
|
||||
|
||||
$diagIp = isset($_GET['diag_ip']) ? trim((string) $_GET['diag_ip']) : '';
|
||||
echo '<form method="get" action="" style="display:flex;gap:8px;align-items:center;margin-bottom:12px">';
|
||||
// WHMCS passes the module slug via ?module=... — preserve any existing query params
|
||||
// by re-emitting the current GET state as hidden fields (except diag_ip itself).
|
||||
foreach ($_GET as $k => $v) {
|
||||
if ($k === 'diag_ip') {
|
||||
continue;
|
||||
}
|
||||
echo '<input type="hidden" name="' . htmlspecialchars((string) $k, ENT_QUOTES, 'UTF-8') . '" value="' . htmlspecialchars((string) $v, ENT_QUOTES, 'UTF-8') . '">';
|
||||
}
|
||||
echo '<input type="text" name="diag_ip" placeholder="IP address (e.g. 198.51.100.42 or 2001:db8::1)" value="' . htmlspecialchars($diagIp, ENT_QUOTES, 'UTF-8') . '" class="form-control form-control-sm" style="max-width:320px;font-family:monospace">';
|
||||
echo '<button type="submit" class="btn btn-primary btn-sm">Diagnose</button>';
|
||||
echo '</form>';
|
||||
|
||||
if ($diagIp !== '') {
|
||||
echo '<div style="background:#f8f9fa;border:1px solid #dee2e6;border-radius:4px;padding:12px;font-family:monospace;font-size:13px;white-space:pre-wrap;word-break:break-all">';
|
||||
|
||||
if (filter_var($diagIp, FILTER_VALIDATE_IP) === false) {
|
||||
echo '<span style="color:#dc3545">Invalid IP address.</span>';
|
||||
} elseif (! Config::isEnabled()) {
|
||||
echo '<span style="color:#dc3545">Addon disabled or missing endpoint/API key. Diagnosis skipped.</span>';
|
||||
} else {
|
||||
$client = new Client;
|
||||
|
||||
echo '<strong>Config snapshot:</strong>' . "\n";
|
||||
echo ' endpoint = ' . htmlspecialchars($config['endpoint'], ENT_QUOTES, 'UTF-8') . "\n";
|
||||
echo ' serverId = ' . htmlspecialchars($config['serverId'], ENT_QUOTES, 'UTF-8') . "\n";
|
||||
echo ' cacheTtl = ' . $cacheTtl . 's' . "\n";
|
||||
echo ' apiKey = ' . ($config['apiKey'] !== '' ? '(set, ' . strlen($config['apiKey']) . ' chars)' : '(MISSING)') . "\n\n";
|
||||
|
||||
// Always forget cache before diagnose so we see the LIVE state, not a
|
||||
// potentially-stale cached list from an earlier misconfigured call.
|
||||
$client->forgetZoneCache();
|
||||
$zones = $client->listZones();
|
||||
|
||||
echo '<strong>Live zone list (cache purged, ' . count($zones) . ' zones):</strong>' . "\n";
|
||||
if (empty($zones)) {
|
||||
echo ' <span style="color:#dc3545">NO ZONES RETURNED.</span>' . "\n";
|
||||
echo ' Likely causes: wrong API key (PowerDNS returned 401/403), wrong Server ID' . "\n";
|
||||
echo ' (PowerDNS returned 404), or api-allow-from blocking the WHMCS host IP.' . "\n";
|
||||
echo ' Run the Test Connection button above to see the exact HTTP error.' . "\n\n";
|
||||
} else {
|
||||
foreach (array_slice($zones, 0, 15) as $z) {
|
||||
echo ' ' . htmlspecialchars($z, ENT_QUOTES, 'UTF-8') . "\n";
|
||||
}
|
||||
if (count($zones) > 15) {
|
||||
echo ' ... and ' . (count($zones) - 15) . ' more' . "\n";
|
||||
}
|
||||
echo "\n";
|
||||
}
|
||||
|
||||
$ptrName = IpUtil::ptrNameForIp($diagIp);
|
||||
echo '<strong>Computed PTR name for ' . htmlspecialchars($diagIp, ENT_QUOTES, 'UTF-8') . ':</strong>' . "\n";
|
||||
echo ' ' . htmlspecialchars((string) $ptrName, ENT_QUOTES, 'UTF-8') . "\n\n";
|
||||
|
||||
$loc = IpUtil::findZoneAndPtrName($diagIp, $zones);
|
||||
echo '<strong>Zone match (IpUtil::findZoneAndPtrName):</strong>' . "\n";
|
||||
if ($loc === null) {
|
||||
echo ' <span style="color:#dc3545">NO MATCH.</span>' . "\n";
|
||||
echo ' The IP does not fall within any zone returned above.' . "\n";
|
||||
if (IpUtil::isIpv4($diagIp)) {
|
||||
$oct = (int) explode('.', $diagIp)[3];
|
||||
echo " For IPv4: confirm a standard reverse zone exists (one of the listed\n";
|
||||
echo " zones should end with the first-three-octets-reversed of $diagIp), OR\n";
|
||||
echo " that an RFC 2317 classless zone exists whose range covers octet $oct.\n";
|
||||
}
|
||||
if (IpUtil::isIpv6($diagIp)) {
|
||||
echo " For IPv6: confirm a reverse zone exists ending in .ip6.arpa. whose\n";
|
||||
echo " nibble prefix matches the high-order bits of $diagIp.\n";
|
||||
}
|
||||
echo "\n";
|
||||
} else {
|
||||
echo ' zone = ' . htmlspecialchars($loc['zone'], ENT_QUOTES, 'UTF-8') . "\n";
|
||||
echo ' ptrName = ' . htmlspecialchars($loc['ptrName'], ENT_QUOTES, 'UTF-8') . "\n\n";
|
||||
|
||||
// Actual current PTR content, if any.
|
||||
echo '<strong>Current PTR record in PowerDNS:</strong>' . "\n";
|
||||
$zoneData = $client->getZone($loc['zone']);
|
||||
if ($zoneData === null) {
|
||||
echo ' <span style="color:#dc3545">Unable to fetch zone contents (HTTP error or not found).</span>' . "\n";
|
||||
} else {
|
||||
$found = null;
|
||||
foreach ($zoneData['rrsets'] ?? [] as $rr) {
|
||||
if (($rr['type'] ?? '') === 'PTR' && rtrim($rr['name'], '.') === rtrim($loc['ptrName'], '.')) {
|
||||
foreach ($rr['records'] ?? [] as $rec) {
|
||||
if (empty($rec['disabled']) && ! empty($rec['content'])) {
|
||||
$found = [
|
||||
'content' => $rec['content'],
|
||||
'ttl' => (int) ($rr['ttl'] ?? 0),
|
||||
];
|
||||
break 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if ($found === null) {
|
||||
echo ' (no PTR record present at ' . htmlspecialchars($loc['ptrName'], ENT_QUOTES, 'UTF-8') . ')' . "\n";
|
||||
} else {
|
||||
echo ' content = ' . htmlspecialchars($found['content'], ENT_QUOTES, 'UTF-8') . "\n";
|
||||
echo ' ttl = ' . $found['ttl'] . 's' . "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
@@ -114,6 +114,13 @@ function VirtFusionDirect_ConfigOptions()
|
||||
'Description' => 'Credit amount to add when auto top-off triggers.',
|
||||
'Default' => '100',
|
||||
],
|
||||
'stockSafetyBufferPct' => [
|
||||
'FriendlyName' => 'Stock Safety Buffer (%)',
|
||||
'Type' => 'text',
|
||||
'Size' => '5',
|
||||
'Description' => 'Reserved headroom applied per resource when calculating stock. Only effective when the WHMCS Stock Control toggle is enabled on this product. 0-100; ignored for resources with no quota set in VirtFusion. Default is 10% if left blank.',
|
||||
'Default' => '10',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -135,6 +142,28 @@ function VirtFusionDirect_TestConnection(array $params)
|
||||
$httpCode = $request->getRequestInfo('http_code');
|
||||
|
||||
if ($httpCode == 200) {
|
||||
// Probe the compute scope: stock control depends on read access to
|
||||
// /compute/hypervisors/groups. A token scoped only to /servers will pass the
|
||||
// /connect check above but silently break nightly stock recalculation, so we
|
||||
// surface the missing scope at config time rather than a week later.
|
||||
$groupsProbe = $module->initCurl($password);
|
||||
$groupsProbe->get($url . '/compute/hypervisors/groups?results=1');
|
||||
$groupsHttp = (int) $groupsProbe->getRequestInfo('http_code');
|
||||
|
||||
if ($groupsHttp === 401 || $groupsHttp === 403) {
|
||||
return [
|
||||
'success' => false,
|
||||
'error' => 'VirtFusion OK but API token lacks read access to /compute/hypervisors/groups (HTTP ' . $groupsHttp . '). Stock Control will not work — re-issue the token with compute:read scope.',
|
||||
];
|
||||
}
|
||||
|
||||
if ($groupsHttp !== 200) {
|
||||
return [
|
||||
'success' => false,
|
||||
'error' => 'VirtFusion OK but /compute/hypervisors/groups returned HTTP ' . $groupsHttp . '. Stock Control may not work correctly.',
|
||||
];
|
||||
}
|
||||
|
||||
// Also verify PowerDNS health when the DNS addon is activated, so the
|
||||
// admin's Test Connection button reflects the full provisioning path.
|
||||
if (PowerDnsConfig::isEnabled()) {
|
||||
|
||||
@@ -39,6 +39,7 @@ use WHMCS\Module\Server\VirtFusionDirect\Module;
|
||||
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\Config as PowerDnsConfig;
|
||||
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\PtrManager;
|
||||
use WHMCS\Module\Server\VirtFusionDirect\ServerResource;
|
||||
use WHMCS\Module\Server\VirtFusionDirect\StockControl;
|
||||
|
||||
$vf = new Module;
|
||||
|
||||
@@ -169,6 +170,46 @@ try {
|
||||
$vf->output(['success' => true, 'data' => $summary], true, true, 200);
|
||||
break;
|
||||
|
||||
// =================================================================
|
||||
// Stock Control
|
||||
// =================================================================
|
||||
|
||||
/**
|
||||
* Force a full stock-quantity recalculation across every VirtFusionDirect
|
||||
* product that has WHMCS stock control enabled. Same logic as the 2-hour
|
||||
* AfterCronJob safety-net hook and the post-provision / post-termination
|
||||
* event hooks in hooks.php, but on-demand. Cache TTLs still govern freshness
|
||||
* of the underlying VirtFusion API reads — run a separate cache bust first
|
||||
* if the admin needs to bypass the 120 s grpres:{id} TTL.
|
||||
*
|
||||
* Usable by admins via POST; returns a JSON map of productId => qty (or null
|
||||
* where the product was skipped / left untouched by the orchestrator).
|
||||
*/
|
||||
case 'stockRecalculate':
|
||||
|
||||
$vf->requirePost();
|
||||
$vf->requireSameOrigin();
|
||||
|
||||
$results = (new StockControl)->recalculateAll();
|
||||
|
||||
// Log a compact summary instead of the full map — the admin client still
|
||||
// gets the detailed per-product map in the JSON response, but the module
|
||||
// log stays readable even on stores with hundreds of VirtFusion products.
|
||||
$summary = ['total' => count($results), 'updated' => 0, 'zeroed' => 0, 'skipped' => 0];
|
||||
foreach ($results as $qty) {
|
||||
if ($qty === null) {
|
||||
$summary['skipped']++;
|
||||
} elseif ((int) $qty === 0) {
|
||||
$summary['zeroed']++;
|
||||
} else {
|
||||
$summary['updated']++;
|
||||
}
|
||||
}
|
||||
Log::insert('stockRecalculate:ok', [], $summary);
|
||||
|
||||
$vf->output(['success' => true, 'data' => $results], true, true, 200);
|
||||
break;
|
||||
|
||||
default:
|
||||
$vf->output(['success' => false, 'errors' => 'invalid action'], true, true, 400);
|
||||
}
|
||||
|
||||
@@ -544,15 +544,35 @@ try {
|
||||
$vf->output(['success' => false, 'errors' => 'Unable to verify IP ownership'], true, true, 502);
|
||||
break;
|
||||
}
|
||||
$assigned = IpUtil::extractIps($serverData)['addresses'];
|
||||
$extracted = IpUtil::extractIps($serverData);
|
||||
$targetBin = @inet_pton($ip);
|
||||
$owns = false;
|
||||
foreach ($assigned as $a) {
|
||||
|
||||
// Stage 1: exact-IP match. Covers every v4 case and any v6 host address
|
||||
// VirtFusion exposes directly (per-host records or /128 subnet entries).
|
||||
foreach ($extracted['addresses'] as $a) {
|
||||
if (@inet_pton($a) === $targetBin) {
|
||||
$owns = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Stage 2: v6 subnet containment. If the exact match failed and this is
|
||||
// a v6 address, check whether it falls inside any of the server's
|
||||
// allocated v6 subnets. This is the path for "my VirtFusion VPS has a
|
||||
// /64 routed to it and I want a PTR for mail.example.com on one of the
|
||||
// host addresses inside that /64" — we don't know which host addresses
|
||||
// are actually in use, but we can prove this one lies within a range
|
||||
// the customer is authorised for.
|
||||
if (! $owns && IpUtil::isIpv6($ip)) {
|
||||
foreach ($extracted['subnets'] as $s) {
|
||||
if (IpUtil::ipv6InSubnet($ip, $s['subnet'], (int) $s['cidr'])) {
|
||||
$owns = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (! $owns) {
|
||||
Log::insert('rdnsUpdate:ownership', ['serviceID' => $serviceID, 'ip' => $ip], 'IP not assigned to this service');
|
||||
$vf->output(['success' => false, 'errors' => 'This IP is not assigned to your server'], true, true, 403);
|
||||
|
||||
@@ -19,7 +19,12 @@
|
||||
*
|
||||
* HOOKS REGISTERED HERE
|
||||
* ---------------------
|
||||
|
||||
* DailyCronJob — PowerDNS reconciliation across all services
|
||||
* AfterCronJob — Every-2-hour stock recalculation safety net
|
||||
* AfterModuleCreate — Stock refresh + order auto-accept after a VPS provisions
|
||||
* AfterModuleTerminate — Stock refresh after a VPS is destroyed
|
||||
* ClientAreaPageCart — Lazy per-product stock refresh during the order flow
|
||||
* ShoppingCartValidateCheckout — blocks checkout until OS is selected
|
||||
* ClientAreaFooterOutput — injects the OS/SSH-key gallery on order form
|
||||
*
|
||||
@@ -32,12 +37,14 @@
|
||||
*/
|
||||
|
||||
use WHMCS\Database\Capsule;
|
||||
use WHMCS\Module\Server\VirtFusionDirect\Cache;
|
||||
use WHMCS\Module\Server\VirtFusionDirect\ConfigureService;
|
||||
use WHMCS\Module\Server\VirtFusionDirect\Database;
|
||||
use WHMCS\Module\Server\VirtFusionDirect\Log;
|
||||
use WHMCS\Module\Server\VirtFusionDirect\Module;
|
||||
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\Config as PowerDnsConfig;
|
||||
use WHMCS\Module\Server\VirtFusionDirect\PowerDns\PtrManager;
|
||||
use WHMCS\Module\Server\VirtFusionDirect\StockControl;
|
||||
|
||||
if (! defined('WHMCS')) {
|
||||
exit('This file cannot be accessed directly');
|
||||
@@ -63,6 +70,190 @@ add_hook('DailyCronJob', 1, function ($vars) {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Every-~2-hour stock recalculation safety net.
|
||||
*
|
||||
* Events (AfterModuleCreate/Terminate) cover every capacity change driven
|
||||
* through WHMCS. But an operator can also create/destroy VMs directly in the
|
||||
* VirtFusion panel — no WHMCS hook fires for that, so stock qty would drift
|
||||
* until the next cart-page visit or the next event-driven refresh. This hook
|
||||
* closes that blind spot.
|
||||
*
|
||||
* AfterCronJob fires on every main WHMCS cron invocation (typically every
|
||||
* 5 minutes). Cache::get on the rate-limit key means the hook is effectively
|
||||
* free on the 99% of invocations where no recalc is due — one cache read,
|
||||
* return. The actual recalc only runs when the key has expired.
|
||||
*
|
||||
* Interval: 2 hours. Tunable via the STOCK_CRON_INTERVAL_SECONDS constant
|
||||
* below. Short enough that out-of-band VirtFusion panel changes surface the
|
||||
* same business day; long enough that the storefront isn't writing
|
||||
* tblproducts.qty every five minutes.
|
||||
*
|
||||
* FAIL-SAFE: StockControl::recalculateAll() returns a map of productId =>
|
||||
* qty|null, where null means the orchestrator left qty UNTOUCHED (transient
|
||||
* API failure, missing CP, etc.). Our catch here only fires on truly unexpected
|
||||
* errors that escape the orchestrator itself.
|
||||
*/
|
||||
const STOCK_CRON_INTERVAL_SECONDS = 2 * 3600; // 2 hours
|
||||
|
||||
add_hook('AfterCronJob', 5, function ($vars) {
|
||||
try {
|
||||
$rateKey = 'stockrefresh:cron';
|
||||
if (Cache::get($rateKey) !== null) {
|
||||
return;
|
||||
}
|
||||
Cache::set($rateKey, 1, STOCK_CRON_INTERVAL_SECONDS);
|
||||
|
||||
(new StockControl)->recalculateAll();
|
||||
} catch (Throwable $e) {
|
||||
Log::insert('StockControl:AfterCronJob', [], $e->getMessage());
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Post-provision: auto-accept the originating order and refresh stock.
|
||||
*
|
||||
* Fires after every successful VirtFusion CreateAccount. Two responsibilities,
|
||||
* independent try/catch blocks so a failure in one doesn't short-circuit the other:
|
||||
*
|
||||
* 1. AUTO-ACCEPT — if the service's parent order is still 'Pending' (admin
|
||||
* hasn't manually accepted yet), call WHMCS's AcceptOrder API with
|
||||
* autosetup=false (we already provisioned, don't re-trigger CreateAccount).
|
||||
* This closes the loop for installs that rely on pending-order workflows
|
||||
* for non-VF products but want VF provisions to auto-advance.
|
||||
*
|
||||
* 2. STOCK REFRESH — a new VM just consumed memory/cpu/disk/IPv4 on the
|
||||
* target hypervisor group. Bust the grpres:{id} cache and recalculate
|
||||
* every stock-controlled product. A shared 30 s rate-limit key prevents
|
||||
* a burst of 10 parallel provisions from triggering 10 full recalcs.
|
||||
*
|
||||
* Filtering by moduletype='VirtFusionDirect' keeps this hook harmless for
|
||||
* unrelated products that happen to share the WHMCS install.
|
||||
*/
|
||||
add_hook('AfterModuleCreate', 1, function ($vars) {
|
||||
if (($vars['params']['moduletype'] ?? '') !== 'VirtFusionDirect') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Part 1: auto-accept the originating order if still Pending.
|
||||
try {
|
||||
$serviceId = (int) ($vars['params']['serviceid'] ?? 0);
|
||||
if ($serviceId > 0) {
|
||||
$hosting = Capsule::table('tblhosting')->where('id', $serviceId)->first();
|
||||
$orderId = $hosting ? (int) ($hosting->orderid ?? 0) : 0;
|
||||
if ($orderId > 0) {
|
||||
$order = Capsule::table('tblorders')->where('id', $orderId)->first();
|
||||
if ($order && strcasecmp((string) $order->status, 'Pending') === 0) {
|
||||
$resp = localAPI('AcceptOrder', [
|
||||
'orderid' => $orderId,
|
||||
'autosetup' => false, // already provisioned; don't re-run CreateAccount
|
||||
'sendemail' => true,
|
||||
]);
|
||||
Log::insert(
|
||||
'AutoAcceptOrder',
|
||||
['orderid' => $orderId, 'serviceid' => $serviceId],
|
||||
$resp,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
Log::insert('AutoAcceptOrder:fail', ['serviceID' => $vars['params']['serviceid'] ?? null], $e->getMessage());
|
||||
}
|
||||
|
||||
// Part 2: refresh stock (capacity just decreased).
|
||||
try {
|
||||
if (Cache::get('stockrefresh:event') === null) {
|
||||
Cache::set('stockrefresh:event', 1, 30);
|
||||
|
||||
$groupId = (int) ($vars['params']['configoption1'] ?? 0);
|
||||
if ($groupId > 0) {
|
||||
Cache::forget('grpres:' . $groupId);
|
||||
}
|
||||
|
||||
(new StockControl)->recalculateAll();
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
Log::insert('StockControl:AfterModuleCreate', ['serviceID' => $vars['params']['serviceid'] ?? null], $e->getMessage());
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Post-termination stock refresh.
|
||||
*
|
||||
* A destroyed VM just freed memory/cpu/disk/IPv4 on the target hypervisor group.
|
||||
* Refresh so the storefront reflects the restored capacity immediately. Shares
|
||||
* the 30 s rate-limit key with AfterModuleCreate — a provision-then-terminate in
|
||||
* quick succession only triggers one full recalc.
|
||||
*/
|
||||
add_hook('AfterModuleTerminate', 1, function ($vars) {
|
||||
if (($vars['params']['moduletype'] ?? '') !== 'VirtFusionDirect') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (Cache::get('stockrefresh:event') !== null) {
|
||||
return;
|
||||
}
|
||||
Cache::set('stockrefresh:event', 1, 30);
|
||||
|
||||
$groupId = (int) ($vars['params']['configoption1'] ?? 0);
|
||||
if ($groupId > 0) {
|
||||
Cache::forget('grpres:' . $groupId);
|
||||
}
|
||||
|
||||
(new StockControl)->recalculateAll();
|
||||
} catch (Throwable $e) {
|
||||
Log::insert('StockControl:AfterModuleTerminate', ['serviceID' => $vars['params']['serviceid'] ?? null], $e->getMessage());
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Lazy stock refresh on order-flow cart pages.
|
||||
*
|
||||
* Keeps "hot" products fresh between daily cron runs without a polling loop: when a
|
||||
* customer lands on a cart page for a specific product, we opportunistically recalculate
|
||||
* that product's qty. If the upstream grpres:{id} cache is warm (populated in the last
|
||||
* 120 s by an earlier view or the daily cron), recalculateForProduct does no HTTP calls
|
||||
* and just re-writes the same qty — effectively free.
|
||||
*
|
||||
* WHY ClientAreaPageCart (not ClientAreaPageProductDetails)
|
||||
* ---------------------------------------------------------
|
||||
* ClientAreaPageProductDetails fires on the My Services → product-details view for an
|
||||
* EXISTING service, which is the wrong place — the stock number only matters during
|
||||
* pre-order. ClientAreaPageCart fires on every cart/order page (product browse, config,
|
||||
* checkout) and WHMCS consults tblproducts.qty on each of those, so this is where a
|
||||
* fresh number pays off.
|
||||
*
|
||||
* RATE LIMIT
|
||||
* ----------
|
||||
* 60 s per product (stockrefresh:{pid}). Short enough that a busy product refreshes
|
||||
* near-continuously across viewers; long enough that two customers arriving within the
|
||||
* same second don't trigger two identical DB UPDATEs. The pid check below filters this
|
||||
* hook to only fire when a specific product is known — generic cart pages (templatefile=
|
||||
* "cart.tpl") pass no pid and are no-ops.
|
||||
*/
|
||||
add_hook('ClientAreaPageCart', 1, function ($vars) {
|
||||
try {
|
||||
$productId = (int) ($vars['pid'] ?? $vars['productid'] ?? ($vars['productinfo']['pid'] ?? 0));
|
||||
if ($productId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$rateKey = 'stockrefresh:' . $productId;
|
||||
if (Cache::get($rateKey) !== null) {
|
||||
return null;
|
||||
}
|
||||
Cache::set($rateKey, 1, 60);
|
||||
|
||||
(new StockControl)->recalculateForProduct($productId);
|
||||
} catch (Throwable $e) {
|
||||
Log::insert('StockControl:ClientAreaPageCart', ['pid' => $vars['pid'] ?? null], $e->getMessage());
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
|
||||
/**
|
||||
* Shopping Cart Validation Hook
|
||||
*
|
||||
|
||||
@@ -56,6 +56,14 @@ use WHMCS\Database\Capsule;
|
||||
*/
|
||||
class Module
|
||||
{
|
||||
/**
|
||||
* @var array|false|null Memoised catalogue-level CP connection used by fetchPackage/fetchGroupResources.
|
||||
* Resolved via getCP(false, true) — "any available VirtFusion server" — on first use.
|
||||
* Kept on the instance so a cron loop recalculating 20 products doesn't hit
|
||||
* tblservers 20×N times when N stock helpers are called per product.
|
||||
*/
|
||||
private $catalogueCp = null;
|
||||
|
||||
/**
|
||||
* Initialises the module and ensures the database schema is up to date.
|
||||
*/
|
||||
@@ -1240,4 +1248,175 @@ class Module
|
||||
{
|
||||
return json_decode($response, true, 512, JSON_THROW_ON_ERROR);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Catalogue helpers — used by StockControl to size the WHMCS inventory from
|
||||
// live VirtFusion data. Pre-order code path: CP is resolved via "any
|
||||
// available server" since no service context exists yet.
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* Resolve the catalogue-level CP (any available VirtFusion server) and memoise.
|
||||
*
|
||||
* Stock calculations run from a cron loop or product-detail page view — there's
|
||||
* no WHMCS service yet, so we can't dereference a specific panel via
|
||||
* resolveServiceContext. "Any enabled server" is the correct fallback for read-only
|
||||
* catalogue operations (package + hypervisor-group endpoints return the same data
|
||||
* from every VirtFusion node on the same cluster).
|
||||
*
|
||||
* @return array{url: string, base_url: string, token: string}|false
|
||||
*/
|
||||
private function getCatalogueCp()
|
||||
{
|
||||
if ($this->catalogueCp === null) {
|
||||
$this->catalogueCp = $this->getCP(false, true);
|
||||
}
|
||||
|
||||
return $this->catalogueCp;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a VirtFusion package by ID — the authoritative source for "how much RAM,
|
||||
* CPU, and disk does one VPS of this product cost?".
|
||||
*
|
||||
* Return values distinguish confirmed-missing from transient failure:
|
||||
* array — package data (fields: memory, cpuCores, primaryStorage, primaryStorageProfile, enabled, …)
|
||||
* false — HTTP 404: package has been deleted in VirtFusion. Callers treat as OOS.
|
||||
* null — Transient failure (no CP, network error, 5xx, malformed body). Callers must
|
||||
* NOT overwrite WHMCS qty on a null — that would zero out inventory during a blip.
|
||||
*
|
||||
* Success responses are cached 10 min (key "pkg:{id}") since package definitions
|
||||
* rarely change; 404 responses get a short 60 s cache so an admin re-creating a
|
||||
* deleted package doesn't have to wait ten minutes for stock to pick it up again.
|
||||
*
|
||||
* @param int $packageId VirtFusion package ID (from tblproducts.configoption2).
|
||||
* @return array|false|null
|
||||
*/
|
||||
public function fetchPackage($packageId)
|
||||
{
|
||||
try {
|
||||
$packageId = (int) $packageId;
|
||||
if ($packageId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$cacheKey = 'pkg:' . $packageId;
|
||||
$cached = Cache::get($cacheKey);
|
||||
if ($cached !== null) {
|
||||
// Sentinel marker for a previously-confirmed 404.
|
||||
if (is_array($cached) && ! empty($cached['__notFound'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$cp = $this->getCatalogueCp();
|
||||
if (! $cp) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$request = $this->initCurl($cp['token']);
|
||||
$data = $request->get($cp['url'] . '/packages/' . $packageId);
|
||||
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
|
||||
|
||||
$httpCode = (int) $request->getRequestInfo('http_code');
|
||||
|
||||
if ($httpCode === 200) {
|
||||
$decoded = json_decode($data, true);
|
||||
if (is_array($decoded)) {
|
||||
$package = $decoded['data'] ?? $decoded;
|
||||
if (is_array($package)) {
|
||||
Cache::set($cacheKey, $package, 600);
|
||||
|
||||
return $package;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($httpCode === 404) {
|
||||
Cache::set($cacheKey, ['__notFound' => true], 60);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (\Throwable $e) {
|
||||
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch free/allocated resources for every hypervisor in a group — the live picture
|
||||
* of how much headroom remains to place more VPSes.
|
||||
*
|
||||
* Same tri-state return contract as fetchPackage():
|
||||
* array — decoded response with a 'data' array of per-hypervisor resource breakdowns.
|
||||
* false — HTTP 404: group has been deleted. Callers may treat as "zero capacity from this group".
|
||||
* null — Transient failure. Callers must NOT overwrite WHMCS qty on a null.
|
||||
*
|
||||
* Cache TTL is 120 s — short enough that customers don't see stale OOS labels for
|
||||
* long after capacity frees up, and long enough to amortise the upstream call across
|
||||
* bursty product-page traffic. Matches the traffic-stats TTL in getTrafficStats().
|
||||
*
|
||||
* @param int $groupId VirtFusion hypervisor group ID.
|
||||
* @return array|false|null
|
||||
*/
|
||||
public function fetchGroupResources($groupId)
|
||||
{
|
||||
try {
|
||||
$groupId = (int) $groupId;
|
||||
if ($groupId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$cacheKey = 'grpres:' . $groupId;
|
||||
$cached = Cache::get($cacheKey);
|
||||
if ($cached !== null) {
|
||||
if (is_array($cached) && ! empty($cached['__notFound'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$cp = $this->getCatalogueCp();
|
||||
if (! $cp) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$request = $this->initCurl($cp['token']);
|
||||
$data = $request->get($cp['url'] . '/compute/hypervisors/groups/' . $groupId . '/resources');
|
||||
Log::insert(__FUNCTION__, $request->getRequestInfo(), $data);
|
||||
|
||||
$httpCode = (int) $request->getRequestInfo('http_code');
|
||||
|
||||
if ($httpCode === 200) {
|
||||
$decoded = json_decode($data, true);
|
||||
if (is_array($decoded) && isset($decoded['data']) && is_array($decoded['data'])) {
|
||||
Cache::set($cacheKey, $decoded, 120);
|
||||
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($httpCode === 404) {
|
||||
Cache::set($cacheKey, ['__notFound' => true], 60);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (\Throwable $e) {
|
||||
Log::insert(__FUNCTION__, [], $e->getMessage());
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,7 +128,38 @@ class Client
|
||||
return ['ok' => false, 'http' => 0, 'error' => $err];
|
||||
}
|
||||
if ($http === 401 || $http === 403) {
|
||||
return ['ok' => false, 'http' => $http, 'error' => 'authentication failed (check API key)'];
|
||||
// Three distinct causes all produce 401/403 here:
|
||||
// (a) Actual wrong API key — the #1 obvious cause.
|
||||
// (b) `api-allow-from` in PowerDNS config excludes the WHMCS
|
||||
// host's IP. PowerDNS rejects pre-auth in some configs,
|
||||
// producing 401/403 even with a valid key.
|
||||
// (c) Invisible whitespace in the stored key (fixed in Config
|
||||
// via trim(), but a pre-upgrade install might still have
|
||||
// a cached request dating from before the fix).
|
||||
// Listing all three gives the operator a concrete checklist.
|
||||
return [
|
||||
'ok' => false,
|
||||
'http' => $http,
|
||||
'error' => 'HTTP ' . $http . ' — PowerDNS rejected authentication. Check: ' .
|
||||
'(1) the X-API-Key matches the `api-key=` in PowerDNS config, ' .
|
||||
'(2) `api-allow-from=` includes this WHMCS host\'s IP, and ' .
|
||||
'(3) the key has no trailing whitespace/newlines (re-paste it if unsure).',
|
||||
];
|
||||
}
|
||||
if ($http === 404) {
|
||||
// The endpoint reached PowerDNS (no 0/connection-refused) but the
|
||||
// server ID path segment isn't known. By far the most common cause
|
||||
// is an addon misconfiguration where someone entered the nameserver
|
||||
// FQDN instead of the literal string "localhost" into the Server ID
|
||||
// field. Surface that hypothesis directly — it's the single highest-
|
||||
// probability fix and turns a mystery into an actionable error.
|
||||
return [
|
||||
'ok' => false,
|
||||
'http' => 404,
|
||||
'error' => 'HTTP 404 — PowerDNS does not recognise server id "' . $this->serverId .
|
||||
'". This field should almost always be the literal string "localhost" ' .
|
||||
'(the PowerDNS API server identifier, NOT your nameserver hostname).',
|
||||
];
|
||||
}
|
||||
|
||||
return ['ok' => false, 'http' => $http, 'error' => 'unexpected HTTP ' . $http . ': ' . substr((string) $body, 0, 200)];
|
||||
|
||||
@@ -119,23 +119,50 @@ class Config
|
||||
$config['cacheTtl'] = max(10, (int) ($rows['cacheTtl'] ?? 60));
|
||||
|
||||
if (! empty($rows['apiKey'])) {
|
||||
$raw = (string) $rows['apiKey'];
|
||||
$decrypted = '';
|
||||
|
||||
try {
|
||||
// decrypt() is WHMCS's global helper — matches how the VirtFusion
|
||||
// bearer token is handled in Module::getCP().
|
||||
$decrypted = decrypt($rows['apiKey']);
|
||||
|
||||
// Fallback to raw value if decrypt returned empty or non-string —
|
||||
// defends against the rare case where decrypt silently fails
|
||||
// (wrong encryption key at rest) or the value was inserted
|
||||
// manually as plaintext during development.
|
||||
$config['apiKey'] = is_string($decrypted) && $decrypted !== '' ? $decrypted : (string) $rows['apiKey'];
|
||||
$decrypted = (string) decrypt($raw);
|
||||
} catch (\Throwable $e) {
|
||||
// Even when decrypt throws, we try the raw value so a diagnostic
|
||||
// path exists. Operator sees the decrypt error in the module log
|
||||
// but isn't locked out of using the addon while they investigate.
|
||||
$config['apiKey'] = (string) $rows['apiKey'];
|
||||
Log::insert('PowerDns:Config', 'decrypt skipped', $e->getMessage());
|
||||
Log::insert('PowerDns:Config', 'decrypt threw', $e->getMessage());
|
||||
}
|
||||
|
||||
// WHMCS addon module password-type fields are stored PLAINTEXT in
|
||||
// tbladdonmodules.value (unlike tblservers.password which IS encrypted).
|
||||
// When fed a plaintext input, WHMCS's decrypt() doesn't return empty
|
||||
// or unchanged — it returns a short binary garbage string. If we used
|
||||
// that as the API key we'd produce a baffling 401 from PowerDNS.
|
||||
//
|
||||
// Heuristic: an API key is printable ASCII by definition. If
|
||||
// decrypt() produced non-printable output, we know it mangled a
|
||||
// plaintext value and we should stick with raw. If decrypt()
|
||||
// produced a different-but-printable string, it's a genuine
|
||||
// decryption of an actually-encrypted value (unusual for addons,
|
||||
// but some third-party setups do encrypt at rest).
|
||||
//
|
||||
// trim() handles another common foot-gun: admin UIs silently
|
||||
// appending a newline on paste, which would land in the
|
||||
// X-API-Key: header verbatim and also produce a 401.
|
||||
$candidate = $raw;
|
||||
if ($decrypted !== '' && $decrypted !== $raw && ctype_print($decrypted)) {
|
||||
$candidate = $decrypted;
|
||||
} elseif ($decrypted !== '' && $decrypted !== $raw) {
|
||||
// Decrypt output wasn't printable — it's garbage from mangling
|
||||
// a plaintext input. Log once so the diagnostic trail is clear
|
||||
// but don't expose key material.
|
||||
Log::insert(
|
||||
'PowerDns:Config',
|
||||
'decrypt produced non-printable output; using raw',
|
||||
['raw_len' => strlen($raw), 'dec_len' => strlen($decrypted)],
|
||||
);
|
||||
}
|
||||
$config['apiKey'] = trim($candidate);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
// Any DB-level failure (table doesn't exist, connection dropped, etc.)
|
||||
|
||||
@@ -101,19 +101,30 @@ class IpUtil
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract every host IP address (v4 and v6) from a VirtFusion server object.
|
||||
* Extract every IP address and IPv6 subnet from a VirtFusion server object.
|
||||
*
|
||||
* Walks every interface, not just interfaces[0] (ServerResource only reads the primary).
|
||||
* Handles both explicit `address` fields and `subnet`+`cidr` pairs.
|
||||
* For IPv6 entries exposed only as `subnet`+`cidr`, the subnet base is used when
|
||||
* the cidr is /128 (single host); otherwise the entry is skipped and reported.
|
||||
* Returns three buckets:
|
||||
*
|
||||
* addresses — discrete host IPs (v4 always, v6 when the API exposes per-host records
|
||||
* or a /128 subnet entry). Each entry is a plain IP string.
|
||||
*
|
||||
* subnets — IPv6 subnet allocations (e.g. 2001:db8:0:5d::/64) where the module
|
||||
* cannot auto-discover individual host addresses. These are surfaced
|
||||
* so the client UI can show "here's your /64" and offer an "Add host PTR"
|
||||
* path where the customer types a specific address inside the subnet.
|
||||
* Each entry: ['subnet' => '2001:db8:0:5d::', 'cidr' => 64].
|
||||
*
|
||||
* skipped — malformed / unusable entries (non-IP, missing cidr, etc.) kept for
|
||||
* logging so we can diagnose schema drift in the VirtFusion API.
|
||||
*
|
||||
* @param object|array $serverObject Raw VirtFusion server payload (may be wrapped in `data`)
|
||||
* @return array{addresses: string[], skipped: array} Deduped IP strings + array of skipped entries with reasons
|
||||
* @return array{addresses: string[], subnets: array<int, array{subnet: string, cidr: int}>, skipped: array}
|
||||
*/
|
||||
public static function extractIps($serverObject): array
|
||||
{
|
||||
$addresses = [];
|
||||
$subnets = [];
|
||||
$skipped = [];
|
||||
|
||||
// Normalise object-or-array input. json_decode(json_encode($x), true) is the
|
||||
@@ -123,7 +134,7 @@ class IpUtil
|
||||
$serverObject = json_decode(json_encode($serverObject), true);
|
||||
}
|
||||
if (! is_array($serverObject)) {
|
||||
return ['addresses' => [], 'skipped' => []];
|
||||
return ['addresses' => [], 'subnets' => [], 'skipped' => []];
|
||||
}
|
||||
|
||||
// VirtFusion wraps the payload in a "data" key on GET responses but the stored
|
||||
@@ -131,7 +142,7 @@ class IpUtil
|
||||
$data = $serverObject['data'] ?? $serverObject;
|
||||
$interfaces = $data['network']['interfaces'] ?? [];
|
||||
if (! is_array($interfaces)) {
|
||||
return ['addresses' => [], 'skipped' => []];
|
||||
return ['addresses' => [], 'subnets' => [], 'skipped' => []];
|
||||
}
|
||||
|
||||
// Walk every interface (not just interfaces[0]). ServerResource only reads [0]
|
||||
@@ -159,29 +170,91 @@ class IpUtil
|
||||
continue;
|
||||
}
|
||||
|
||||
// Fallback shape: VirtFusion sometimes exposes v6 only as subnet+cidr
|
||||
// (common when a /64 is routed to the VPS and the OS auto-assigns
|
||||
// specific host addresses). We can't set a PTR for the whole subnet,
|
||||
// so we only accept /128 (single-host) entries and report the rest
|
||||
// via the "skipped" channel so callers can surface a UI note.
|
||||
// Subnet-with-cidr shape. VirtFusion's common v6 allocation model is
|
||||
// to route a whole /64 to the VPS and let the OS auto-assign specific
|
||||
// host addresses. The module can't know which host the customer
|
||||
// actually uses, so we surface the subnet as a first-class entry and
|
||||
// let the client UI offer an "Add host PTR" path with containment
|
||||
// ownership verification.
|
||||
$subnet = $v6['subnet'] ?? null;
|
||||
$cidr = isset($v6['cidr']) ? (int) $v6['cidr'] : null;
|
||||
if ($subnet && self::isIpv6($subnet)) {
|
||||
if ($subnet && self::isIpv6($subnet) && $cidr !== null) {
|
||||
if ($cidr === 128) {
|
||||
// Single-host "subnet" — treat as a discrete address.
|
||||
$addresses[$subnet] = true;
|
||||
} elseif ($cidr > 0 && $cidr < 128) {
|
||||
// Genuine subnet allocation. Dedupe by (subnet, cidr) pair.
|
||||
$key = $subnet . '/' . $cidr;
|
||||
if (! isset($subnets[$key])) {
|
||||
$subnets[$key] = ['subnet' => $subnet, 'cidr' => $cidr];
|
||||
}
|
||||
} else {
|
||||
$skipped[] = [
|
||||
'subnet' => $subnet,
|
||||
'cidr' => $cidr,
|
||||
'reason' => 'ipv6-subnet-without-explicit-host-address',
|
||||
];
|
||||
$skipped[] = ['subnet' => $subnet, 'cidr' => $cidr, 'reason' => 'invalid-cidr'];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// array_keys gives us the de-duplicated list in insertion order.
|
||||
return ['addresses' => array_keys($addresses), 'skipped' => $skipped];
|
||||
return [
|
||||
'addresses' => array_keys($addresses),
|
||||
'subnets' => array_values($subnets),
|
||||
'skipped' => $skipped,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* True if $ip falls inside the subnet $prefix/$cidrBits.
|
||||
*
|
||||
* Used for subnet-containment ownership checks when the customer wants to set
|
||||
* a PTR for a specific host address inside an IPv6 subnet allocated to their
|
||||
* VPS — we can't enumerate their assigned hosts, but we CAN prove the address
|
||||
* they're claiming lies within one of their subnets.
|
||||
*
|
||||
* Works on the binary (inet_pton) representation so v6 notation differences
|
||||
* (compression, case) don't affect the comparison.
|
||||
*
|
||||
* ALGORITHM
|
||||
* ---------
|
||||
* 1. Convert both IPs to 16 raw bytes via inet_pton (or 4 for v4).
|
||||
* 2. Compare the first floor(cidr/8) bytes byte-wise (full-byte prefix).
|
||||
* 3. If cidr isn't a multiple of 8, mask the next byte and compare bits.
|
||||
*
|
||||
* Example: 2001:db8::5 vs 2001:db8::/32
|
||||
* fullBytes = 32/8 = 4; first 4 bytes of both are 20:01:0d:b8 → match
|
||||
* remBits = 0 → no partial byte to compare
|
||||
* → true
|
||||
*/
|
||||
public static function ipv6InSubnet(string $ip, string $subnetPrefix, int $cidrBits): bool
|
||||
{
|
||||
if (! self::isIpv6($ip) || ! self::isIpv6($subnetPrefix)) {
|
||||
return false;
|
||||
}
|
||||
if ($cidrBits < 0 || $cidrBits > 128) {
|
||||
return false;
|
||||
}
|
||||
$ipBin = @inet_pton($ip);
|
||||
$subBin = @inet_pton($subnetPrefix);
|
||||
if ($ipBin === false || $subBin === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$fullBytes = intdiv($cidrBits, 8);
|
||||
$remBits = $cidrBits % 8;
|
||||
|
||||
// Compare whole-byte prefix with a single substr compare.
|
||||
if ($fullBytes > 0 && substr($ipBin, 0, $fullBytes) !== substr($subBin, 0, $fullBytes)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Compare the partial byte at the cidr boundary, if any.
|
||||
if ($remBits > 0) {
|
||||
$mask = (0xFF << (8 - $remBits)) & 0xFF;
|
||||
if ((ord($ipBin[$fullBytes]) & $mask) !== (ord($subBin[$fullBytes]) & $mask)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -246,6 +246,22 @@ class PtrManager
|
||||
return $out;
|
||||
}
|
||||
|
||||
// Subnet-only rows come first so the client UI can render "you have a /64,
|
||||
// here's how to add a host PTR inside it" above the discrete-IP list.
|
||||
// These carry no PTR content themselves — they're informational anchors
|
||||
// plus the "Add custom host" entry point.
|
||||
foreach ($extracted['subnets'] as $s) {
|
||||
$out[] = [
|
||||
'ip' => null,
|
||||
'subnet' => $s['subnet'],
|
||||
'cidr' => $s['cidr'],
|
||||
'ptr' => null,
|
||||
'ttl' => null,
|
||||
'zone' => null,
|
||||
'status' => 'subnet-only',
|
||||
];
|
||||
}
|
||||
|
||||
foreach ($extracted['addresses'] as $ip) {
|
||||
try {
|
||||
$loc = $this->locate($ip);
|
||||
|
||||
537
modules/servers/VirtFusionDirect/lib/StockControl.php
Normal file
537
modules/servers/VirtFusionDirect/lib/StockControl.php
Normal file
@@ -0,0 +1,537 @@
|
||||
<?php
|
||||
|
||||
namespace WHMCS\Module\Server\VirtFusionDirect;
|
||||
|
||||
use WHMCS\Database\Capsule as DB;
|
||||
|
||||
/**
|
||||
* Computes accurate stock quantities for VirtFusionDirect products and writes them
|
||||
* to tblproducts.qty, leveraging WHMCS's native stock-control feature (badges,
|
||||
* disabled Add-to-Cart, checkout block) instead of building parallel UI.
|
||||
*
|
||||
* HOW THE NUMBER IS DERIVED
|
||||
* -------------------------
|
||||
* For every product with tblproducts.stockcontrol=1:
|
||||
*
|
||||
* qty = Σ groupCapacity(g, package, ipv4Req, bufferPct) for every eligible group g
|
||||
*
|
||||
* where groupCapacity is computed from live /compute/hypervisors/groups/{id}/resources
|
||||
* data and package is the VirtFusion /packages/{id} response — the authoritative
|
||||
* per-VPS resource footprint. Each hypervisor's per-metric capacity is
|
||||
* min(memory, cpu, storage), summed across hypervisors in the group; IPv4 is a
|
||||
* group-level pool so its cap is taken as the per-hypervisor max within the group
|
||||
* (not summed) to avoid double-counting.
|
||||
*
|
||||
* ELIGIBLE GROUPS
|
||||
* ---------------
|
||||
* The default group (tblproducts.configoption1) plus every value of the Location
|
||||
* configurable option, if the product exposes one. Location is detected by matching
|
||||
* the configurable option name against the "hypervisorId" label from
|
||||
* config/ConfigOptionMapping.php (falls back to "Location") — same convention
|
||||
* ModuleFunctions::createAccount() uses to map configoptions to VirtFusion fields.
|
||||
* This lets a single product span multiple regions and still get a meaningful qty.
|
||||
*
|
||||
* ELIGIBLE HYPERVISORS
|
||||
* --------------------
|
||||
* enabled=true AND commissioned=true AND prohibit=false. Everything else is skipped
|
||||
* with zero contribution to the group total.
|
||||
*
|
||||
* FAIL-SAFE INVARIANT
|
||||
* -------------------
|
||||
* CRITICAL: if the computation cannot complete (missing CP, transient API failure,
|
||||
* malformed response, no groups resolved), recalculateForProduct() returns null and
|
||||
* the caller MUST NOT touch tblproducts.qty. The reason: a false zero during a
|
||||
* transient failure would pull every product out of the storefront, causing
|
||||
* lost-order incidents that take human intervention to recover. Better to keep a
|
||||
* slightly-stale qty than to silently take the catalogue offline.
|
||||
*
|
||||
* Confirmed-missing cases (package 404 or package.enabled=false) DO return 0 —
|
||||
* that's the right answer, the product genuinely cannot be provisioned.
|
||||
*
|
||||
* CACHING
|
||||
* -------
|
||||
* Packages cached 10 min (rarely change), group resources cached 120 s (change
|
||||
* meaningfully minute-to-minute under load). Both handled inside Module's
|
||||
* fetchPackage / fetchGroupResources helpers, keyed 'pkg:{id}' / 'grpres:{id}' so
|
||||
* multiple products in a cron sweep share cached data for the same upstream call.
|
||||
*/
|
||||
class StockControl
|
||||
{
|
||||
/** Default mapping from internal VF key → WHMCS configurable-option label.
|
||||
* Kept in sync with $configOptionDefaultNaming in ModuleFunctions::createAccount(). */
|
||||
private const DEFAULT_OPTION_LABELS = [
|
||||
'ipv4' => 'IPv4',
|
||||
'packageId' => 'Package',
|
||||
'hypervisorId' => 'Location',
|
||||
'storage' => 'Storage',
|
||||
'memory' => 'Memory',
|
||||
'traffic' => 'Bandwidth',
|
||||
'networkSpeedInbound' => 'Inbound Network Speed',
|
||||
'networkSpeedOutbound' => 'Outbound Network Speed',
|
||||
'cpuCores' => 'CPU Cores',
|
||||
'networkProfile' => 'Network Type',
|
||||
'storageProfile' => 'Storage Type',
|
||||
];
|
||||
|
||||
/** @var Module Shared for its CP memoisation + initCurl/fetchPackage/fetchGroupResources helpers. */
|
||||
private $module;
|
||||
|
||||
/** @var array<string,string>|null Resolved per-request once. */
|
||||
private $optionLabelMap = null;
|
||||
|
||||
public function __construct(?Module $module = null)
|
||||
{
|
||||
// Dependency-inject for testability; default wires up a real Module so production
|
||||
// callers (hooks.php, admin.php) don't have to know about the dependency.
|
||||
$this->module = $module ?? new Module;
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Public API
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Recalculate qty for every VirtFusionDirect product that has WHMCS stock control enabled.
|
||||
*
|
||||
* Called from the every-2-hour AfterCronJob safety-net hook, from the post-provision
|
||||
* and post-termination event hooks in hooks.php, and from the admin stockRecalculate
|
||||
* AJAX endpoint in admin.php. Returns a map of productId => resulting qty (or null
|
||||
* where the product was skipped / left untouched), useful for the admin endpoint's
|
||||
* JSON response and for per-event logging.
|
||||
*
|
||||
* @return array<int,int|null>
|
||||
*/
|
||||
public function recalculateAll(): array
|
||||
{
|
||||
$results = [];
|
||||
|
||||
try {
|
||||
$products = DB::table('tblproducts')
|
||||
->where('servertype', 'VirtFusionDirect')
|
||||
->where('stockcontrol', 1)
|
||||
->get();
|
||||
|
||||
foreach ($products as $product) {
|
||||
$results[(int) $product->id] = $this->recalculateForProduct((int) $product->id);
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::insert('StockControl:recalculateAll', [], $e->getMessage());
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recalculate qty for a single product.
|
||||
*
|
||||
* Returns the new qty on success, or null on any unrecoverable failure — in which case
|
||||
* tblproducts.qty is left unchanged (fail-safe invariant).
|
||||
*/
|
||||
public function recalculateForProduct(int $productId): ?int
|
||||
{
|
||||
try {
|
||||
$product = DB::table('tblproducts')->where('id', $productId)->first();
|
||||
if (! $product) {
|
||||
return null;
|
||||
}
|
||||
if ($product->servertype !== 'VirtFusionDirect') {
|
||||
return null;
|
||||
}
|
||||
if ((int) $product->stockcontrol !== 1) {
|
||||
// Stock control disabled on this product — don't manage qty.
|
||||
return null;
|
||||
}
|
||||
|
||||
$qty = $this->computeQtyForProduct($product);
|
||||
if ($qty === null) {
|
||||
// Transient / unrecoverable — preserve existing qty.
|
||||
return null;
|
||||
}
|
||||
|
||||
DB::table('tblproducts')
|
||||
->where('id', $productId)
|
||||
->update(['qty' => (int) $qty]);
|
||||
|
||||
Log::insert(
|
||||
'StockControl:recalculate',
|
||||
[
|
||||
'productId' => $productId,
|
||||
'packageId' => (int) $product->configoption2,
|
||||
'defaultGroupId' => (int) $product->configoption1,
|
||||
],
|
||||
['qty' => $qty],
|
||||
);
|
||||
|
||||
return $qty;
|
||||
} catch (\Throwable $e) {
|
||||
Log::insert('StockControl:recalculateForProduct', ['productId' => $productId], $e->getMessage());
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Computation
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Compute the qty integer without touching the DB.
|
||||
*
|
||||
* @param object $product tblproducts row.
|
||||
* @return int|null Non-negative qty, or null when the computation cannot complete.
|
||||
*/
|
||||
private function computeQtyForProduct($product): ?int
|
||||
{
|
||||
$productId = (int) $product->id;
|
||||
|
||||
$packageId = (int) $product->configoption2;
|
||||
if ($packageId <= 0) {
|
||||
Log::insert(
|
||||
'StockControl:compute',
|
||||
['productId' => $productId],
|
||||
'no packageId in configoption2 — skipped',
|
||||
);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$package = $this->module->fetchPackage($packageId);
|
||||
if ($package === null) {
|
||||
// Transient — preserve qty.
|
||||
return null;
|
||||
}
|
||||
if ($package === false) {
|
||||
// Confirmed 404: package deleted in VirtFusion. Product is unfulfillable.
|
||||
Log::insert(
|
||||
'StockControl:compute',
|
||||
['productId' => $productId, 'packageId' => $packageId],
|
||||
'package 404 — qty forced to 0',
|
||||
);
|
||||
|
||||
return 0;
|
||||
}
|
||||
if (empty($package['enabled'])) {
|
||||
Log::insert(
|
||||
'StockControl:compute',
|
||||
['productId' => $productId, 'packageId' => $packageId],
|
||||
'package disabled in VirtFusion — qty forced to 0',
|
||||
);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
$groupIds = $this->resolveHypervisorGroupIds($product);
|
||||
if (empty($groupIds)) {
|
||||
Log::insert(
|
||||
'StockControl:compute',
|
||||
['productId' => $productId],
|
||||
'no hypervisor groups resolved — qty untouched',
|
||||
);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$ipv4Required = max(1, (int) ($product->configoption3 ?? 1));
|
||||
$bufferPct = $this->bufferPctForProduct($product);
|
||||
|
||||
$total = 0;
|
||||
foreach ($groupIds as $groupId) {
|
||||
$resources = $this->module->fetchGroupResources($groupId);
|
||||
if ($resources === null) {
|
||||
// Transient failure on any group aborts the whole computation — we can't
|
||||
// safely reduce qty to a partial total and risk under-reporting stock.
|
||||
return null;
|
||||
}
|
||||
if ($resources === false) {
|
||||
// Group 404 — deleted; contributes 0. Keep going so other eligible groups still count.
|
||||
Log::insert(
|
||||
'StockControl:compute',
|
||||
['productId' => $productId, 'groupId' => $groupId],
|
||||
'group 404 — contributing 0 capacity',
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$total += $this->groupCapacity($resources, $package, $ipv4Required, $bufferPct);
|
||||
}
|
||||
|
||||
return max(0, $total);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sum of per-hypervisor minimums (mem/cpu/storage), capped by the group-level IPv4 pool.
|
||||
*
|
||||
* IPv4 CAP IS MAX-WITHIN-GROUP, NOT SUMMED
|
||||
* ----------------------------------------
|
||||
* network.total.ipv4.free in the API is a group-level pool visible from every hypervisor
|
||||
* in the group — the same number is reported on each. Summing per-hypervisor IPv4 caps
|
||||
* would overcount the pool by the hypervisor count. Taking max() within a group, then
|
||||
* summing across groups, reflects the real constraint.
|
||||
*/
|
||||
private function groupCapacity(array $resources, array $package, int $ipv4Required, float $bufferPct): int
|
||||
{
|
||||
$hypervisors = $resources['data'] ?? [];
|
||||
if (! is_array($hypervisors) || empty($hypervisors)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$hypMinSum = 0;
|
||||
$ipv4CapForGroup = 0;
|
||||
|
||||
foreach ($hypervisors as $h) {
|
||||
$hyp = $h['hypervisor'] ?? [];
|
||||
if (empty($hyp['enabled']) || empty($hyp['commissioned']) || ! empty($hyp['prohibit'])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$res = $h['resources'] ?? [];
|
||||
if (! is_array($res)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$memCap = self::capFor($res['memory'] ?? null, (int) ($package['memory'] ?? 0), $bufferPct);
|
||||
$cpuCap = self::capFor($res['cpuCores'] ?? null, (int) ($package['cpuCores'] ?? 0), $bufferPct);
|
||||
$storeCap = self::capForStorage(
|
||||
$res,
|
||||
(int) ($package['primaryStorageProfile'] ?? 0),
|
||||
(int) ($package['primaryStorage'] ?? 0),
|
||||
$bufferPct,
|
||||
);
|
||||
|
||||
$hypMinSum += min($memCap, $cpuCap, $storeCap);
|
||||
|
||||
$ipv4Free = (int) ($res['network']['total']['ipv4']['free'] ?? 0);
|
||||
if ($ipv4Free > 0) {
|
||||
$ipv4Cap = intdiv($ipv4Free, max(1, $ipv4Required));
|
||||
if ($ipv4Cap > $ipv4CapForGroup) {
|
||||
$ipv4CapForGroup = $ipv4Cap;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If no hypervisor reported any ipv4 data (unusual but defensible), don't let
|
||||
// the cap kill an otherwise-valid count — treat as "no IPv4 constraint known".
|
||||
if ($ipv4CapForGroup === 0) {
|
||||
foreach ($hypervisors as $h) {
|
||||
if (isset($h['resources']['network']['total']['ipv4']['free'])) {
|
||||
// There WAS an ipv4 value (possibly 0); the cap is genuinely 0.
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
// No ipv4 data anywhere in the response → don't apply the cap.
|
||||
return max(0, $hypMinSum);
|
||||
}
|
||||
|
||||
return min($hypMinSum, $ipv4CapForGroup);
|
||||
}
|
||||
|
||||
/**
|
||||
* How many VPSes fit into a single (free, max, buffer) cell for one resource.
|
||||
*
|
||||
* Handles three edge cases consistent with live API behaviour:
|
||||
* - need <= 0 → unlimited fit (nothing consumed for this dimension)
|
||||
* - resource.max = 0 → unlimited quota; free can be negative but we don't care
|
||||
* - negative/zero available after buffer → 0 (clamp; never negative qty)
|
||||
*/
|
||||
private static function capFor($resource, int $need, float $bufferPct): int
|
||||
{
|
||||
if ($need <= 0) {
|
||||
return PHP_INT_MAX;
|
||||
}
|
||||
if (! is_array($resource)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$max = (int) ($resource['max'] ?? 0);
|
||||
$free = (int) ($resource['free'] ?? 0);
|
||||
|
||||
if ($max === 0) {
|
||||
// Unlimited quota — buffer doesn't apply (X% of 0 is 0).
|
||||
return PHP_INT_MAX;
|
||||
}
|
||||
|
||||
$reserve = (int) ceil(((float) $max) * ($bufferPct / 100.0));
|
||||
$available = $free - $reserve;
|
||||
|
||||
if ($available <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return intdiv($available, $need);
|
||||
}
|
||||
|
||||
/**
|
||||
* Storage variant of capFor() that respects the package's primaryStorageProfile.
|
||||
*
|
||||
* Rules:
|
||||
* - profileId > 0 → must match an otherStorage[].id on the hypervisor; if the
|
||||
* matched pool is disabled or missing, this hypervisor has
|
||||
* zero storage capacity for this product (can't place there).
|
||||
* - profileId <= 0 → fall back to localStorage. If local is disabled, 0.
|
||||
*/
|
||||
private static function capForStorage(array $res, int $profileId, int $needGb, float $bufferPct): int
|
||||
{
|
||||
if ($needGb <= 0) {
|
||||
return PHP_INT_MAX;
|
||||
}
|
||||
|
||||
if ($profileId > 0) {
|
||||
foreach ($res['otherStorage'] ?? [] as $pool) {
|
||||
if ((int) ($pool['id'] ?? 0) !== $profileId) {
|
||||
continue;
|
||||
}
|
||||
if (empty($pool['enabled'])) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return self::capFor(
|
||||
['max' => (int) ($pool['max'] ?? 0), 'free' => (int) ($pool['free'] ?? 0)],
|
||||
$needGb,
|
||||
$bufferPct,
|
||||
);
|
||||
}
|
||||
|
||||
// Storage profile not present on this hypervisor — cannot place the VM.
|
||||
return 0;
|
||||
}
|
||||
|
||||
$local = $res['localStorage'] ?? null;
|
||||
if (is_array($local) && ! empty($local['enabled'])) {
|
||||
return self::capFor(
|
||||
['max' => (int) ($local['max'] ?? 0), 'free' => (int) ($local['free'] ?? 0)],
|
||||
$needGb,
|
||||
$bufferPct,
|
||||
);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin-tunable safety buffer (configoption7), clamped to [0, 100].
|
||||
*
|
||||
* Default is 10% when the field is blank or non-numeric — reserves 10% of each
|
||||
* resource's max so we stop selling a product before the hypervisor is literally
|
||||
* at 100%, which is where placement timing issues and fragmentation start biting.
|
||||
* Admins can override per product (including down to 0) in the module settings.
|
||||
*/
|
||||
private function bufferPctForProduct($product): float
|
||||
{
|
||||
$raw = $product->configoption7 ?? '';
|
||||
if ($raw === null || $raw === '') {
|
||||
return 10.0;
|
||||
}
|
||||
$val = is_numeric($raw) ? (float) $raw : 10.0;
|
||||
|
||||
return max(0.0, min(100.0, $val));
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Hypervisor-group resolution
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Collect every hypervisor group ID this product could be provisioned into:
|
||||
* the default (configoption1) plus every numeric value of the "Location"
|
||||
* configurable option (if one is attached).
|
||||
*
|
||||
* @return int[] Deduplicated list of group IDs, strictly positive.
|
||||
*/
|
||||
private function resolveHypervisorGroupIds($product): array
|
||||
{
|
||||
$groups = [];
|
||||
|
||||
$defaultGroup = (int) ($product->configoption1 ?? 0);
|
||||
if ($defaultGroup > 0) {
|
||||
$groups[] = $defaultGroup;
|
||||
}
|
||||
|
||||
$locationLabel = $this->optionLabelFor('hypervisorId');
|
||||
if ($locationLabel !== null && $locationLabel !== '') {
|
||||
foreach ($this->fetchConfigurableOptionValues((int) $product->id, $locationLabel) as $value) {
|
||||
$asInt = (int) $value;
|
||||
if ($asInt > 0) {
|
||||
$groups[] = $asInt;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return array_values(array_unique($groups));
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up every sub-option value for a given configurable option name on a product.
|
||||
*
|
||||
* WHMCS stores option names as either "Location" or "Location|Display Override" —
|
||||
* this method normalises both by comparing just the part before the pipe.
|
||||
*
|
||||
* @return array<int,string> Raw sub-option names (callers decide numeric parsing).
|
||||
*/
|
||||
private function fetchConfigurableOptionValues(int $productId, string $label): array
|
||||
{
|
||||
try {
|
||||
$options = DB::table('tblproductconfiglinks as l')
|
||||
->join('tblproductconfigoptions as o', 'o.gid', '=', 'l.gid')
|
||||
->where('l.pid', $productId)
|
||||
->select('o.id', 'o.optionname')
|
||||
->get();
|
||||
|
||||
$matchedIds = [];
|
||||
foreach ($options as $opt) {
|
||||
$name = (string) $opt->optionname;
|
||||
$pipe = strpos($name, '|');
|
||||
if ($pipe !== false) {
|
||||
$name = substr($name, 0, $pipe);
|
||||
}
|
||||
if ($name === $label) {
|
||||
$matchedIds[] = (int) $opt->id;
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($matchedIds)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return DB::table('tblproductconfigoptionssub')
|
||||
->whereIn('configid', $matchedIds)
|
||||
->pluck('optionname')
|
||||
->toArray();
|
||||
} catch (\Throwable $e) {
|
||||
Log::insert('StockControl:fetchConfigurableOptionValues', ['productId' => $productId, 'label' => $label], $e->getMessage());
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the WHMCS configurable-option label for an internal key, respecting
|
||||
* config/ConfigOptionMapping.php overrides — same contract as ModuleFunctions::createAccount().
|
||||
*/
|
||||
private function optionLabelFor(string $key): ?string
|
||||
{
|
||||
if ($this->optionLabelMap === null) {
|
||||
$this->optionLabelMap = self::DEFAULT_OPTION_LABELS;
|
||||
|
||||
try {
|
||||
// Resolve the mapping file directly relative to this class — avoids
|
||||
// depending on WHMCS's ROOTDIR, which isn't defined when the module
|
||||
// is loaded outside a full WHMCS request (cron tooling, tests).
|
||||
// __DIR__ is .../modules/servers/VirtFusionDirect/lib, so the config
|
||||
// directory is one level up.
|
||||
$overridePath = dirname(__DIR__) . '/config/ConfigOptionMapping.php';
|
||||
if (is_file($overridePath)) {
|
||||
$override = require $overridePath;
|
||||
if (is_array($override)) {
|
||||
$this->optionLabelMap = array_merge($this->optionLabelMap, $override);
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
// Swallow — mapping override is best-effort; defaults still work.
|
||||
}
|
||||
}
|
||||
|
||||
return $this->optionLabelMap[$key] ?? null;
|
||||
}
|
||||
}
|
||||
@@ -545,3 +545,32 @@
|
||||
.vf-rdns-edit { flex-direction: column; align-items: stretch; }
|
||||
.vf-rdns-msg { padding-left: 0; }
|
||||
}
|
||||
|
||||
/* Subnet-only rows (IPv6 /64 allocations). Distinct visual treatment so
|
||||
customers see "this is a subnet, not a host" without reading the badge. */
|
||||
.vf-rdns-subnet-row {
|
||||
background: rgba(23, 162, 184, 0.04);
|
||||
border-left: 3px solid #17a2b8;
|
||||
padding-left: 8px;
|
||||
}
|
||||
.vf-rdns-subnet-form {
|
||||
flex-basis: 100%;
|
||||
padding: 10px 0 0 180px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.vf-rdns-subnet-inputs {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.vf-rdns-subnet-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
@media (max-width: 768px) {
|
||||
.vf-rdns-subnet-form { padding-left: 0; }
|
||||
.vf-rdns-subnet-inputs { flex-direction: column; }
|
||||
}
|
||||
|
||||
@@ -1117,7 +1117,8 @@ var VF_RDNS_STATUS = {
|
||||
"missing": { label: "no PTR", bg: "#6c757d", fg: "#fff" },
|
||||
"no-zone": { label: "no zone", bg: "#dc3545", fg: "#fff" },
|
||||
"error": { label: "error", bg: "#dc3545", fg: "#fff" },
|
||||
"disabled": { label: "disabled", bg: "#6c757d", fg: "#fff" }
|
||||
"disabled": { label: "disabled", bg: "#6c757d", fg: "#fff" },
|
||||
"subnet-only": { label: "subnet", bg: "#17a2b8", fg: "#fff" }
|
||||
};
|
||||
|
||||
function vfRdnsBadge(status) {
|
||||
@@ -1157,6 +1158,19 @@ function vfRenderRdnsPanel(serviceId, systemUrl, ips) {
|
||||
return;
|
||||
}
|
||||
ips.forEach(function (row) {
|
||||
// Subnet-only rows (IPv6 /64 allocations) render as a distinct informational
|
||||
// anchor with an expandable "Add host PTR" form — the customer types a
|
||||
// specific address inside the subnet + hostname, backend verifies containment.
|
||||
if (row.status === "subnet-only") {
|
||||
list.append(vfRenderSubnetRow(serviceId, systemUrl, row));
|
||||
return;
|
||||
}
|
||||
list.append(vfRenderIpRow(serviceId, systemUrl, row));
|
||||
});
|
||||
}
|
||||
|
||||
/** Standard per-IP row with inline PTR editor. Used for v4 addresses + discrete v6 hosts. */
|
||||
function vfRenderIpRow(serviceId, systemUrl, row) {
|
||||
var wrap = $('<div class="vf-rdns-row"></div>');
|
||||
var ipLabel = $('<div class="vf-rdns-ip"></div>').text(row.ip);
|
||||
var badge = vfRdnsBadge(row.status);
|
||||
@@ -1175,12 +1189,65 @@ function vfRenderRdnsPanel(serviceId, systemUrl, ips) {
|
||||
});
|
||||
|
||||
var editor = $('<div class="vf-rdns-edit"></div>').append(input).append(saveBtn);
|
||||
wrap.append(ipLabel).append(editor).append(badge).append(msg);
|
||||
list.append(wrap);
|
||||
});
|
||||
return wrap.append(ipLabel).append(editor).append(badge).append(msg);
|
||||
}
|
||||
|
||||
function vfUpdateRdns(serviceId, systemUrl, ip, input, saveBtn, msg, badge) {
|
||||
/**
|
||||
* Subnet-only row: shows "2602:2f3:0:5d::/64" with a collapsible "Add host PTR" form.
|
||||
*
|
||||
* Why collapsed by default: most customers won't set custom v6 PTRs, so burying
|
||||
* the form until explicitly requested keeps the panel uncluttered for the common
|
||||
* case. Adding a host PTR is a power-user operation (needs a pre-existing AAAA
|
||||
* record) so surfacing it as a secondary action is UX-appropriate.
|
||||
*/
|
||||
function vfRenderSubnetRow(serviceId, systemUrl, row) {
|
||||
var wrap = $('<div class="vf-rdns-row vf-rdns-subnet-row"></div>');
|
||||
var label = $('<div class="vf-rdns-ip"></div>').text(row.subnet + "/" + row.cidr);
|
||||
var badge = vfRdnsBadge(row.status);
|
||||
|
||||
var toggleBtn = $('<button type="button" class="btn btn-sm btn-outline-secondary">+ Add host PTR</button>');
|
||||
var form = $('<div class="vf-rdns-subnet-form" style="display:none;"></div>');
|
||||
|
||||
var ipInput = $('<input type="text" class="form-control form-control-sm vf-rdns-input" placeholder="Host IPv6 address inside this subnet (e.g. 2602:2f3:0:5d::10)">');
|
||||
var ptrInput = $('<input type="text" class="form-control form-control-sm vf-rdns-input" maxlength="253" placeholder="Hostname for PTR (e.g. mail.example.com)">');
|
||||
var addBtn = $('<button type="button" class="btn btn-sm btn-primary">Add PTR</button>');
|
||||
var cancelBtn = $('<button type="button" class="btn btn-sm btn-link">Cancel</button>');
|
||||
var msg = $('<div class="vf-rdns-msg"></div>');
|
||||
|
||||
toggleBtn.on("click", function () {
|
||||
form.toggle();
|
||||
toggleBtn.text(form.is(":visible") ? "− Hide" : "+ Add host PTR");
|
||||
});
|
||||
cancelBtn.on("click", function () {
|
||||
form.hide();
|
||||
toggleBtn.text("+ Add host PTR");
|
||||
ipInput.val(""); ptrInput.val(""); msg.hide();
|
||||
});
|
||||
|
||||
addBtn.on("click", function () {
|
||||
var ip = (ipInput.val() || "").trim();
|
||||
var ptr = (ptrInput.val() || "").trim();
|
||||
if (!ip) { msg.text("Enter a host IPv6 address.").css("color", "#dc3545").show(); return; }
|
||||
if (!ptr) { msg.text("Enter a hostname for the PTR.").css("color", "#dc3545").show(); return; }
|
||||
// Same server-side validation guards apply; we reuse the normal update flow.
|
||||
vfUpdateRdns(serviceId, systemUrl, ip, ptrInput, addBtn, msg, null, function () {
|
||||
// On success, refresh the whole panel so the new host PTR shows up as its own row
|
||||
// alongside the subnet it came from.
|
||||
setTimeout(function () { vfLoadRdns(serviceId, systemUrl); }, 1500);
|
||||
});
|
||||
});
|
||||
ipInput.on("keydown", function (e) { if (e.key === "Enter") { e.preventDefault(); ptrInput.focus(); } });
|
||||
ptrInput.on("keydown", function (e) { if (e.key === "Enter") { e.preventDefault(); addBtn.click(); } });
|
||||
|
||||
var inputsRow = $('<div class="vf-rdns-subnet-inputs"></div>').append(ipInput).append(ptrInput);
|
||||
var actionsRow = $('<div class="vf-rdns-subnet-actions"></div>').append(addBtn).append(cancelBtn);
|
||||
form.append(inputsRow).append(actionsRow).append(msg);
|
||||
|
||||
var editorWrap = $('<div class="vf-rdns-edit"></div>').append(toggleBtn);
|
||||
return wrap.append(label).append(editorWrap).append(badge).append(form);
|
||||
}
|
||||
|
||||
function vfUpdateRdns(serviceId, systemUrl, ip, input, saveBtn, msg, badge, onSuccess) {
|
||||
var ptr = (input.val() || "").trim();
|
||||
// Light client-side regex mirrors the server-side one — strict enforcement is on the server.
|
||||
if (ptr !== "" && !/^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}\.?$/.test(ptr)) {
|
||||
@@ -1201,12 +1268,17 @@ function vfUpdateRdns(serviceId, systemUrl, ip, input, saveBtn, msg, badge) {
|
||||
var verb = (ptr === "") ? "deleted" : "saved";
|
||||
msg.text("rDNS " + verb + ".").css("color", "#28a745").show();
|
||||
setTimeout(function () { msg.fadeOut(); }, 2500);
|
||||
// Badge may be null (e.g. when called from the subnet row's Add-PTR form
|
||||
// which has no per-row badge to update). Guard rather than crash.
|
||||
if (badge) {
|
||||
// Optimistically update the badge; a background refresh will correct it.
|
||||
if (ptr === "") {
|
||||
badge.replaceWith(vfRdnsBadge("missing"));
|
||||
} else {
|
||||
badge.replaceWith(vfRdnsBadge("ok"));
|
||||
}
|
||||
}
|
||||
if (typeof onSuccess === "function") { onSuccess(); }
|
||||
} else {
|
||||
var err = (resp && resp.errors) ? resp.errors : "Save failed.";
|
||||
msg.text(err).css("color", "#dc3545").show();
|
||||
|
||||
Reference in New Issue
Block a user